1use egui::accesskit::Role;
43use egui::{Align, Id, IdSalt, Layout, Margin, Response, RichText, Stroke, Ui, UiBuilder};
44use serde::Serialize;
45
46use crate::a11y::{self, Politeness};
47use crate::icon::{Icon, Size, Tone as IconTone};
48use crate::kit::Tone;
49use crate::state::pass;
50use crate::strings::{self, StrKey};
51use crate::theme::Tokens;
52
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
56#[serde(rename_all = "lowercase")]
57pub enum Severity {
58 #[default]
59 Info,
60 Success,
61 Warning,
62 Error,
63}
64
65impl From<egui_pop_model::notice::Severity> for Severity {
66 fn from(s: egui_pop_model::notice::Severity) -> Self {
67 use egui_pop_model::notice::Severity as N;
68 match s {
69 N::Info => Severity::Info,
70 N::Success => Severity::Success,
71 N::Warning => Severity::Warning,
72 N::Error => Severity::Error,
73 }
74 }
75}
76
77impl Severity {
78 pub fn of_tone(tone: Tone) -> Option<Self> {
81 match tone {
82 Tone::Danger | Tone::Record => Some(Severity::Error),
83 Tone::Warning => Some(Severity::Warning),
84 Tone::Success => Some(Severity::Success),
85 Tone::Info => Some(Severity::Info),
86 Tone::Neutral | Tone::Accent | Tone::Muted => None,
87 }
88 }
89
90 pub fn icon(self) -> Icon {
92 match self {
93 Severity::Info => Icon::Info,
94 Severity::Success => Icon::Success,
95 Severity::Warning => Icon::Warning,
96 Severity::Error => Icon::Error,
97 }
98 }
99
100 pub fn icon_tone(self) -> IconTone {
102 match self {
103 Severity::Info => IconTone::Info,
104 Severity::Success => IconTone::Success,
105 Severity::Warning => IconTone::Warning,
106 Severity::Error => IconTone::Danger,
107 }
108 }
109
110 pub fn word(self) -> &'static StrKey {
112 match self {
113 Severity::Info => &strings::NOTE_INFO,
114 Severity::Success => &strings::NOTE_SUCCESS,
115 Severity::Warning => &strings::NOTE_WARNING,
116 Severity::Error => &strings::NOTE_ERROR,
117 }
118 }
119
120 pub fn role(self) -> Role {
123 match self {
124 Severity::Warning | Severity::Error => Role::Alert,
125 Severity::Info | Severity::Success => Role::Status,
126 }
127 }
128
129 pub fn politeness(self) -> Politeness {
131 match self {
132 Severity::Error => Politeness::Assertive,
133 _ => Politeness::Polite,
134 }
135 }
136}
137
138#[derive(Clone, Debug, PartialEq)]
142#[non_exhaustive]
143#[must_use]
144pub struct Note {
145 pub severity: Severity,
146 pub headline: String,
148 pub reason: Option<String>,
150 pub hint: Option<String>,
152 pub details: Option<String>,
154 pub time: Option<String>,
157 pub actions: Vec<String>,
159 pub copy: bool,
161 pub announce: bool,
163 pub compact: bool,
165 id_salt: Option<IdSalt>,
166}
167
168#[derive(Debug)]
170pub struct NoteResponse {
171 pub response: Response,
173 pub action: Option<usize>,
175 pub copied: bool,
177}
178
179const COPIED_FOR: f64 = 2.0;
181
182impl Note {
183 pub fn new(severity: Severity, headline: impl Into<String>) -> Self {
184 Self {
185 severity,
186 headline: headline.into(),
187 reason: None,
188 hint: None,
189 details: None,
190 time: None,
191 actions: Vec::new(),
192 copy: true,
193 announce: true,
194 compact: false,
195 id_salt: None,
196 }
197 }
198
199 pub fn info(headline: impl Into<String>) -> Self {
200 Self::new(Severity::Info, headline)
201 }
202
203 pub fn from_notice(notice: &egui_pop_model::notice::Notice) -> Self {
208 let mut note = Self::new(notice.severity.into(), notice.headline.clone());
209 note.reason = notice.reason.clone().filter(|t| !t.trim().is_empty());
210 note.hint = notice.hint.clone().filter(|t| !t.trim().is_empty());
211 note.details = notice.details.clone().filter(|t| !t.trim().is_empty());
212 if notice.at_ms > 0 {
213 note.time = Some(utc(notice.at_ms / 1_000));
214 }
215 note.actions = notice.actions.iter().map(|a| a.label.clone()).collect();
216 if !notice.id.is_empty() {
217 note = note.id_salt(("egui_pop.notice", notice.id.as_str()));
218 }
219 note
220 }
221
222 pub fn success(headline: impl Into<String>) -> Self {
223 Self::new(Severity::Success, headline)
224 }
225
226 pub fn warning(headline: impl Into<String>) -> Self {
227 Self::new(Severity::Warning, headline)
228 }
229
230 pub fn error(headline: impl Into<String>) -> Self {
231 Self::new(Severity::Error, headline)
232 }
233
234 pub fn reason(mut self, reason: impl Into<String>) -> Self {
236 self.reason = Some(reason.into()).filter(|r| !r.trim().is_empty());
237 self
238 }
239
240 pub fn hint(mut self, hint: impl Into<String>) -> Self {
242 self.hint = Some(hint.into()).filter(|h| !h.trim().is_empty());
243 self
244 }
245
246 pub fn details(mut self, details: impl Into<String>) -> Self {
248 self.details = Some(details.into()).filter(|d| !d.trim().is_empty());
249 self
250 }
251
252 pub fn time(mut self, time: impl Into<String>) -> Self {
254 self.time = Some(time.into());
255 self
256 }
257
258 pub fn action(mut self, label: impl Into<String>) -> Self {
261 self.actions.push(label.into());
262 self
263 }
264
265 pub fn copyable(mut self, copy: bool) -> Self {
267 self.copy = copy;
268 self
269 }
270
271 pub fn announced(mut self, announce: bool) -> Self {
273 self.announce = announce;
274 self
275 }
276
277 pub fn compact(mut self) -> Self {
280 self.compact = true;
281 self
282 }
283
284 pub fn id_salt(mut self, salt: impl egui::AsIdSalt) -> Self {
288 self.id_salt = Some(IdSalt::new(salt));
289 self
290 }
291
292 pub fn copy_text(&self) -> String {
296 let mut text = self.headline.clone();
297 for part in [&self.reason, &self.hint].into_iter().flatten() {
298 text.push_str("\n\n");
299 text.push_str(part);
300 }
301 if self.details.is_some() || self.time.is_some() {
302 text.push_str("\n\n---");
303 }
304 if let Some(d) = &self.details {
305 text.push('\n');
306 text.push_str(d.trim_end());
307 }
308 if let Some(t) = &self.time {
309 text.push_str("\ntime: ");
310 text.push_str(t);
311 }
312 text
313 }
314
315 pub fn show(self, ui: &mut Ui) -> NoteResponse {
317 self.show_with(ui, |_| {})
318 }
319
320 pub fn show_with(mut self, ui: &mut Ui, extra: impl FnOnce(&mut Ui)) -> NoteResponse {
323 let ctx = ui.ctx().clone();
324 let t = Tokens::of(&ctx);
325 let salt = self
326 .id_salt
327 .unwrap_or_else(|| IdSalt::new((self.severity, &self.headline)));
328 let id = ui.scope_id().with(("egui_pop.note", salt));
329 let first_shown = seen(ui, id, &self);
330 if self.time.is_none() {
331 self.time = Some(first_shown);
332 }
333 let word = strings::tr(&ctx, self.severity.word());
334 let icon = self
335 .severity
336 .icon()
337 .size(Size::Inline)
338 .tone(self.severity.icon_tone())
339 .label(&word);
340 if self.compact {
341 let inner = ui.scope_builder(UiBuilder::new().id_salt(salt), |ui| {
342 ui.horizontal_top(|ui| {
343 ui.add(icon);
344 let width = ui.available_width();
345 ui.allocate_ui_with_layout(
346 egui::vec2(width, 0.0),
347 Layout::top_down(Align::Min),
348 |ui| {
349 ui.set_max_width(width);
350 ui.add(egui::Label::new(&self.headline).wrap().selectable(true));
351 },
352 );
353 });
354 });
355 return NoteResponse {
356 response: inner.response,
357 action: None,
358 copied: false,
359 };
360 }
361 let color = self.severity.icon_tone().color(&t);
362 let stroke = 1.0;
363 let margin = t.space.s;
364 let frame = egui::Frame::new()
365 .fill(color.gamma_multiply(0.12))
366 .stroke(Stroke::new(stroke, color.gamma_multiply(0.6)))
367 .corner_radius(t.radius.widget)
368 .inner_margin(Margin::same(margin.round() as i8));
369 let width = ui.available_width();
370 let mut action = None;
371 let mut copied = false;
372 let role = self.severity.role();
373 let inner = ui.scope_builder(UiBuilder::new().id_salt(salt), |ui| {
374 ctx.accesskit_node_builder(ui.unique_id(), |n| n.set_role(role));
376 frame.show(ui, |ui| {
377 ui.set_width((width - 2.0 * (margin + stroke)).max(0.0));
378 ui.horizontal_top(|ui| {
379 ui.add(icon);
380 let width = ui.available_width();
381 ui.allocate_ui_with_layout(
382 egui::vec2(width, 0.0),
383 Layout::top_down(Align::Min),
384 |ui| {
385 ui.set_max_width(width);
386 self.body(ui, id, &mut action, &mut copied, extra);
387 },
388 );
389 });
390 });
391 });
392 NoteResponse {
393 response: inner.response,
394 action,
395 copied,
396 }
397 }
398
399 fn body(
401 &self,
402 ui: &mut Ui,
403 id: Id,
404 action: &mut Option<usize>,
405 copied: &mut bool,
406 extra: impl FnOnce(&mut Ui),
407 ) {
408 let ctx = ui.ctx().clone();
409 let t = Tokens::of(&ctx);
410 ui.add(
411 egui::Label::new(RichText::new(&self.headline).strong())
412 .wrap()
413 .selectable(true),
414 );
415 if let Some(reason) = &self.reason {
416 ui.add(egui::Label::new(reason).wrap().selectable(true));
417 }
418 if let Some(hint) = &self.hint {
419 ui.add(
420 egui::Label::new(RichText::new(hint).color(t.text.muted))
421 .wrap()
422 .selectable(true),
423 );
424 }
425 if let Some(details) = &self.details {
426 let title = strings::tr(&ctx, &strings::NOTE_DETAILS);
427 egui::CollapsingHeader::new(&title)
428 .id_salt(id.with("details"))
429 .default_open(false)
430 .show(ui, |ui| {
431 let mut shown = details.as_str();
432 let r = ui.add(
433 egui::TextEdit::multiline(&mut shown)
434 .font(egui::TextStyle::Monospace)
435 .desired_width(f32::INFINITY)
436 .desired_rows(details.lines().count().clamp(1, 8)),
437 );
438 ctx.accesskit_node_builder(r.id, |n| n.set_label(title.as_str()));
439 });
440 }
441 let copy = self.copy;
442 if self.actions.is_empty() && !copy {
443 extra(ui);
444 return;
445 }
446 ui.horizontal_wrapped(|ui| {
447 for (i, label) in self.actions.iter().enumerate() {
448 if ui.button(label).clicked() {
449 *action = Some(i);
450 }
451 }
452 extra(ui);
453 if copy {
454 *copied = copy_button(ui, id, &self.copy_text());
455 }
456 });
457 }
458}
459
460fn copy_button(ui: &mut Ui, id: Id, text: &str) -> bool {
463 let ctx = ui.ctx().clone();
464 let name = strings::tr(&ctx, &strings::NOTE_COPY);
465 let button = ui.add(Icon::Copy.size(Size::Inline).label(&name).sense_click());
466 let now = ctx.input(|i| i.time);
467 let at_id = id.with("copied_at");
468 let clicked = button.clicked();
469 if clicked {
470 ctx.copy_text(text.to_string());
471 ctx.data_mut(|d| d.insert_temp(at_id, now));
472 }
473 if let Some(when) = ctx.data(|d| d.get_temp::<f64>(at_id)) {
474 let left = COPIED_FOR - (now - when);
475 if left > 0.0 {
476 ui.weak(strings::tr(&ctx, &strings::NOTE_COPIED));
477 ctx.request_repaint_after_secs(left as f32);
478 } else {
479 ctx.data_mut(|d| d.remove::<f64>(at_id));
480 }
481 }
482 clicked
483}
484
485#[derive(Clone, Debug)]
488struct Seen {
489 pass: u64,
490 digest: u64,
491 since: String,
492}
493
494fn seen(ui: &Ui, id: Id, note: &Note) -> String {
498 let ctx = ui.ctx();
499 let now = pass(ctx);
500 let digest = {
501 use std::hash::{Hash as _, Hasher as _};
502 let mut h = std::collections::hash_map::DefaultHasher::new();
503 (
504 note.severity,
505 ¬e.headline,
506 ¬e.reason,
507 ¬e.hint,
508 ¬e.details,
509 )
510 .hash(&mut h);
511 h.finish()
512 };
513 let key = id.with("seen");
514 let before: Option<Seen> = ctx.data(|d| d.get_temp(key));
515 let fresh = match &before {
516 Some(s) => s.digest != digest || s.pass + 1 < now,
517 None => true,
518 };
519 let since = match before {
520 Some(s) if !fresh => s.since,
521 _ => utc_now(),
522 };
523 if fresh && note.announce && !note.compact && ui.is_visible() {
524 let mut said = format!(
525 "{}: {}",
526 strings::tr(ctx, note.severity.word()),
527 note.headline
528 );
529 for part in [¬e.reason, ¬e.hint].into_iter().flatten() {
530 said.push_str(". ");
531 said.push_str(part);
532 }
533 a11y::announce(ctx, said, note.severity.politeness());
534 }
535 ctx.data_mut(|d| {
536 d.insert_temp(
537 key,
538 Seen {
539 pass: now,
540 digest,
541 since: since.clone(),
542 },
543 );
544 });
545 since
546}
547
548fn utc_now() -> String {
550 #[cfg(not(target_arch = "wasm32"))]
551 use std::time::{SystemTime, UNIX_EPOCH};
552 #[cfg(target_arch = "wasm32")]
553 use web_time::{SystemTime, UNIX_EPOCH};
554 let secs = SystemTime::now()
555 .duration_since(UNIX_EPOCH)
556 .map_or(0, |d| d.as_secs());
557 utc(secs)
558}
559
560fn utc(secs: u64) -> String {
564 let days = (secs / 86_400) as i64;
565 let rest = secs % 86_400;
566 let z = days + 719_468;
567 let era = z.div_euclid(146_097);
568 let doe = z.rem_euclid(146_097);
569 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
570 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
571 let mp = (5 * doy + 2) / 153;
572 let day = doy - (153 * mp + 2) / 5 + 1;
573 let month = if mp < 10 { mp + 3 } else { mp - 9 };
574 let year = yoe + era * 400 + i64::from(month <= 2);
575 format!(
576 "{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02} UTC",
577 rest / 3_600,
578 rest % 3_600 / 60,
579 rest % 60
580 )
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586
587 #[test]
588 fn the_clock_writes_utc_dates() {
589 assert_eq!(utc(0), "1970-01-01 00:00:00 UTC");
590 assert_eq!(utc(951_782_400), "2000-02-29 00:00:00 UTC");
591 assert_eq!(utc(1_796_121_723), "2026-12-01 10:42:03 UTC");
592 }
593
594 #[test]
595 fn the_copied_text_leaves_out_what_is_missing() {
596 assert_eq!(Note::warning("Low disk").copy_text(), "Low disk");
597 assert_eq!(
598 Note::error("Not saved")
599 .reason(" ")
600 .details("io: full\n")
601 .copy_text(),
602 "Not saved\n\n---\nio: full"
603 );
604 }
605
606 #[test]
607 fn a_notice_gives_its_note() {
608 use egui_pop_model::notice::Notice;
609 let n = Notice::warning("Backup late")
610 .reason("The NAS was off.")
611 .details("ssh: timeout")
612 .at_ms(1_796_121_723_456)
613 .action("backup.run", "Back up now")
614 .id("n7");
615 let note = Note::from_notice(&n);
616 assert_eq!(note.severity, Severity::Warning);
617 assert_eq!(note.headline, "Backup late");
618 assert_eq!(note.hint, None);
619 assert_eq!(note.time.as_deref(), Some("2026-12-01 10:42:03 UTC"));
620 assert_eq!(note.actions, ["Back up now"]);
621 assert!(note.id_salt.is_some());
622 assert_eq!(Note::from_notice(&Notice::info("Hi")).time, None);
623 }
624
625 #[test]
626 fn tones_say_a_severity_or_none() {
627 assert_eq!(Severity::of_tone(Tone::Danger), Some(Severity::Error));
628 assert_eq!(Severity::of_tone(Tone::Accent), None);
629 assert_eq!(Severity::Error.role(), Role::Alert);
630 assert_eq!(Severity::Success.role(), Role::Status);
631 }
632}