Skip to main content

egui_pop_core/
note.rs

1//! Notes: a message in sentences shown inside a page, a form or a panel
2//! (an error, a warning, a success, a piece of information), where a
3//! badge ([`Indicator`](crate::indicator::Indicator)) is too small for it.
4//!
5//! A note has a severity, shown by a symbol from the icon registry whose
6//! tooltip and accessible name say the severity in words; a headline in
7//! plain words; an optional reason, hint and technical details (folded,
8//! closed at first); its actions; and a Copy button that copies all of
9//! it with the time the note was first shown. Every text wraps to the
10//! width it is given and can be selected.
11//!
12//! For screen readers, a note is a group with the `Alert` role (an error
13//! or a warning) or the `Status` role (otherwise), holding its text, and
14//! it is announced ([`a11y::announce`]) when it appears or its text
15//! changes: at once for an error, when the reader is idle otherwise.
16//!
17//! ```
18//! use egui_pop_core::note::{Note, Severity};
19//!
20//! let note = Note::error("cloudy was not added")
21//!     .reason("The network found no route to it.")
22//!     .hint("Check that cloudy is on and on the same network.")
23//!     .details("cannot enrol with cloudy: connect: No route to host (os error 113)")
24//!     .time("2026-12-01 10:42:03 UTC");
25//! assert_eq!(note.severity, Severity::Error);
26//! assert_eq!(
27//!     note.copy_text(),
28//!     "cloudy was not added\n\nThe network found no route to it.\n\n\
29//!      Check that cloudy is on and on the same network.\n\n---\n\
30//!      cannot enrol with cloudy: connect: No route to host (os error 113)\n\
31//!      time: 2026-12-01 10:42:03 UTC"
32//! );
33//! ```
34//!
35//! A compact note ([`Note::compact`]) is one line of text after its
36//! symbol, wrapped and selectable, with no frame, no Copy button and no
37//! announcement: a toned title in a list, a reason beside a button.
38//!
39//! <div class="warning">Experimental: may change in any release
40//! (docs/stability.md).</div>
41
42use 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/// How serious a note is: its symbol, its colour, its role for screen
54/// readers and how urgently it is announced.
55#[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    /// The severity a kit tone says, if it says one: `Danger` and
79    /// `Record` are errors; `Neutral`, `Accent` and `Muted` say none.
80    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    /// Its symbol in the icon registry.
91    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    /// The tone its symbol and frame are drawn in.
101    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    /// The word its symbol is named and tooltipped with.
111    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    /// Its role for assistive technologies: `Alert` for an error or a
121    /// warning, `Status` otherwise.
122    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    /// How urgently it is announced: at once for an error.
130    pub fn politeness(self) -> Politeness {
131        match self {
132            Severity::Error => Politeness::Assertive,
133            _ => Politeness::Polite,
134        }
135    }
136}
137
138/// An inline message in sentences: see the [module](self).
139///
140/// Need (help): an inline message (an error, a warning, a success) in sentences, selectable and copyable.
141#[derive(Clone, Debug, PartialEq)]
142#[non_exhaustive]
143#[must_use]
144pub struct Note {
145    pub severity: Severity,
146    /// What happened, in plain words.
147    pub headline: String,
148    /// Why, in plain words.
149    pub reason: Option<String>,
150    /// What the user can do about it.
151    pub hint: Option<String>,
152    /// The technical chain (an error's sources), folded at first.
153    pub details: Option<String>,
154    /// When it happened, as copied; when not given, the time the note
155    /// was first shown.
156    pub time: Option<String>,
157    /// The labels of its buttons, in order.
158    pub actions: Vec<String>,
159    /// The Copy button (on by default).
160    pub copy: bool,
161    /// Announced when it appears or changes (on by default).
162    pub announce: bool,
163    /// One line after its symbol, nothing else ([`Note::compact`]).
164    pub compact: bool,
165    id_salt: Option<IdSalt>,
166}
167
168/// What happened to a note this pass.
169#[derive(Debug)]
170pub struct NoteResponse {
171    /// The whole note's.
172    pub response: Response,
173    /// The index of the action clicked, in [`Note::actions`].
174    pub action: Option<usize>,
175    /// Its Copy button was clicked.
176    pub copied: bool,
177}
178
179/// How long the "Copied." note stays, in seconds.
180const 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    /// The note of a notice ([`egui_pop_model::notice::Notice`]): its
204    /// severity, headline, reason, hint, details, time (when it has one)
205    /// and its actions' labels, in order; its id keeps the note's state
206    /// (folded details, announcement) while its text changes.
207    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    /// Why, in plain words (left out when blank).
235    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    /// What the user can do about it (left out when blank).
241    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    /// The technical chain, folded under "Details" (left out when blank).
247    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    /// When it happened, as the Copy button writes it.
253    pub fn time(mut self, time: impl Into<String>) -> Self {
254        self.time = Some(time.into());
255        self
256    }
257
258    /// A button, after the others; [`NoteResponse::action`] says which
259    /// one was clicked.
260    pub fn action(mut self, label: impl Into<String>) -> Self {
261        self.actions.push(label.into());
262        self
263    }
264
265    /// With or without the Copy button.
266    pub fn copyable(mut self, copy: bool) -> Self {
267        self.copy = copy;
268        self
269    }
270
271    /// Announced to screen readers when it appears or changes, or not.
272    pub fn announced(mut self, announce: bool) -> Self {
273        self.announce = announce;
274        self
275    }
276
277    /// One line of text after its symbol: no frame, no Copy button, no
278    /// details, no announcement.
279    pub fn compact(mut self) -> Self {
280        self.compact = true;
281        self
282    }
283
284    /// Its id among its siblings (by default its severity and headline):
285    /// give one to keep its folded details and its announcement when its
286    /// text changes.
287    pub fn id_salt(mut self, salt: impl egui::AsIdSalt) -> Self {
288        self.id_salt = Some(IdSalt::new(salt));
289        self
290    }
291
292    /// What its Copy button puts on the clipboard: the headline, the
293    /// reason and the hint, each a paragraph, then under a `---` line
294    /// the details and the time (`time: …`).
295    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    /// Draws it, as wide as the room left.
316    pub fn show(self, ui: &mut Ui) -> NoteResponse {
317        self.show_with(ui, |_| {})
318    }
319
320    /// Draws it with widgets of the caller's after its actions (a
321    /// button running a command, for instance).
322    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            // The group node first, so what is drawn inside is its child.
375            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    /// The texts, the details, the buttons.
400    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
460/// The Copy button, with a short "Copied." after a click; whether it
461/// was clicked.
462fn 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/// A note's memory: the last pass it was drawn in, a digest of its text,
486/// the time it was first shown.
487#[derive(Clone, Debug)]
488struct Seen {
489    pass: u64,
490    digest: u64,
491    since: String,
492}
493
494/// Remembers the note drawn this pass, and announces it when it was not
495/// drawn in the pass before or its text changed; the time it was first
496/// shown (as it is now).
497fn 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            &note.headline,
506            &note.reason,
507            &note.hint,
508            &note.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 [&note.reason, &note.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
548/// The wall clock in UTC, `2026-12-01 10:42:03 UTC`.
549fn 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
560/// Seconds since 1970 in UTC, as [`utc_now`] writes them (the civil
561/// calendar from a count of days, after Howard Hinnant's public
562/// `civil_from_days`).
563fn 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}