From f0386ee63a931146b3068e1e8bc3c920b65cd0ee Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Wed, 18 Nov 2026 10:04:55 -0800 Subject: [PATCH] Extras: notify, transient toasts and a persistent notice stack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both consumers hand-build a toast slot and a notice stack (#347). The notify feature gives them one widget on core's public API: - The queue is the application's: `notifications(key, &[Notice])` takes `Option::as_slice` for a slot a new notice replaces, or a `Vec` for a stack, newest nearest the anchor. Expiry, the ×, Esc and actions come back through `on_dismiss(app, id, Dismissed)` and `on_action`. - `Lifetime::Dwell(Duration)` per stack, on egui's clock: the library keeps only each visible id's dwell, ticked by a pure `Dwell` (the tooltip's pattern), and books a repaint for the next expiry. It holds while the pointer is over the stack, focus is inside it, or the window is in the background. A new id starts afresh; an expired notice fires once. - Esc dismisses a notice only while focus is inside it, remembered across the pass in which egui drops the focus for the Esc. - Toasts show a × only with `closable()`; `UntilDismissed` notices always do. Actions are buttons and leave the notice up. - The stack is a named `Status` node with a polite live region (`NodeHandle::live`), in a `Band::Popup` overlay that takes no focus, never dismisses itself and passes outside presses through, so it sits above dialogs and stays clickable. - `ScreenAnchor` plus a `Distance` inset is a thin constructor of core's `Placement::edge(..).align(..)` with an inset window boundary; the rect is the existing `placed.overlay(key).rect()`. The look is a private default derived from the core style (the menu's popover surface at sonner's sizes) until the render round picks the NotifyStyle; no shadcn values and no entrance motion yet. Part of #347. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PWiKKe8zfqGfVMCSC5L3up --- Cargo.toml | 2 +- crates/eggshell-ui-extras/Cargo.toml | 1 + crates/eggshell-ui-extras/src/lib.rs | 2 + crates/eggshell-ui-extras/src/notify/dwell.rs | 115 +++++ crates/eggshell-ui-extras/src/notify/look.rs | 68 +++ crates/eggshell-ui-extras/src/notify/mod.rs | 474 ++++++++++++++++++ tests/it/main.rs | 1 + tests/it/notify.rs | 407 +++++++++++++++ 8 files changed, 1069 insertions(+), 1 deletion(-) create mode 100644 crates/eggshell-ui-extras/src/notify/dwell.rs create mode 100644 crates/eggshell-ui-extras/src/notify/look.rs create mode 100644 crates/eggshell-ui-extras/src/notify/mod.rs create mode 100644 tests/it/notify.rs diff --git a/Cargo.toml b/Cargo.toml index 8d0857af..82961eb3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ eframe = "0.37" egui_kittest = "0.37" trybuild = "1" eggshell-ui-shadcn = { path = "crates/eggshell-ui-shadcn", features = ["extras"] } -eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["markdown"] } +eggshell-ui-extras = { path = "crates/eggshell-ui-extras", features = ["markdown", "notify"] } # proptest's rng wants a getrandom backend that the browser build does not # select, and the fuzzers only run natively. diff --git a/crates/eggshell-ui-extras/Cargo.toml b/crates/eggshell-ui-extras/Cargo.toml index 737183f2..e1d6b92c 100644 --- a/crates/eggshell-ui-extras/Cargo.toml +++ b/crates/eggshell-ui-extras/Cargo.toml @@ -10,6 +10,7 @@ repository = "https://github.com/samitbasu/eggshell" [features] # Each widget is opt-in. markdown = ["dep:pulldown-cmark"] +notify = [] [dependencies] eggshell-ui = { path = "../..", version = "0.1.0" } diff --git a/crates/eggshell-ui-extras/src/lib.rs b/crates/eggshell-ui-extras/src/lib.rs index 2e0b7acc..3c694407 100644 --- a/crates/eggshell-ui-extras/src/lib.rs +++ b/crates/eggshell-ui-extras/src/lib.rs @@ -22,3 +22,5 @@ #[cfg(feature = "markdown")] pub mod markdown; +#[cfg(feature = "notify")] +pub mod notify; diff --git a/crates/eggshell-ui-extras/src/notify/dwell.rs b/crates/eggshell-ui-extras/src/notify/dwell.rs new file mode 100644 index 00000000..4b7eeb2a --- /dev/null +++ b/crates/eggshell-ui-extras/src/notify/dwell.rs @@ -0,0 +1,115 @@ +//! How long a notice has been on screen, on a clock the caller passes in. + +use core::time::Duration; + +/// Whether the dwell counts the time since the last tick. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Hold { + Running, + Held, +} + +/// What a tick found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Countdown { + /// This much is left. + Left(Duration), + /// The dwell ran out at this tick. + Expires, + /// It ran out at an earlier tick. + Over, +} + +/// One notice's dwell. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Dwell { + Counting { elapsed: Duration, seen: Duration }, + Over, +} + +impl Dwell { + /// A dwell first seen at `now`. + pub(super) fn new(now: Duration) -> Self { + Self::Counting { + elapsed: Duration::ZERO, + seen: now, + } + } + + /// Moves the dwell to `now`: the time since the last tick counts unless + /// it is `hold`'s. Reports [`Countdown::Expires`] once. + pub(super) fn tick(&mut self, now: Duration, length: Duration, hold: Hold) -> Countdown { + let Self::Counting { elapsed, seen } = *self else { + return Countdown::Over; + }; + let elapsed = match hold { + Hold::Running => elapsed.saturating_add(now.saturating_sub(seen)), + Hold::Held => elapsed, + }; + let left = length.saturating_sub(elapsed); + if left.is_zero() { + *self = Self::Over; + Countdown::Expires + } else { + *self = Self::Counting { elapsed, seen: now }; + Countdown::Left(left) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ms(ms: u64) -> Duration { + Duration::from_millis(ms) + } + + #[test] + fn a_dwell_counts_down_and_expires_once() { + let mut dwell = Dwell::new(ms(1000)); + assert_eq!( + dwell.tick(ms(1000), ms(500), Hold::Running), + Countdown::Left(ms(500)) + ); + assert_eq!( + dwell.tick(ms(1300), ms(500), Hold::Running), + Countdown::Left(ms(200)) + ); + assert_eq!( + dwell.tick(ms(1500), ms(500), Hold::Running), + Countdown::Expires + ); + assert_eq!( + dwell.tick(ms(1600), ms(500), Hold::Running), + Countdown::Over + ); + } + + #[test] + fn held_time_is_not_counted_and_the_dwell_resumes_where_it_left_off() { + let mut dwell = Dwell::new(ms(0)); + dwell.tick(ms(300), ms(500), Hold::Running); + assert_eq!( + dwell.tick(ms(5000), ms(500), Hold::Held), + Countdown::Left(ms(200)) + ); + assert_eq!( + dwell.tick(ms(5100), ms(500), Hold::Running), + Countdown::Left(ms(100)) + ); + assert_eq!( + dwell.tick(ms(5200), ms(500), Hold::Running), + Countdown::Expires + ); + } + + #[test] + fn a_clock_that_goes_back_counts_nothing() { + let mut dwell = Dwell::new(ms(1000)); + assert_eq!( + dwell.tick(ms(400), ms(500), Hold::Running), + Countdown::Left(ms(500)) + ); + } +} diff --git a/crates/eggshell-ui-extras/src/notify/look.rs b/crates/eggshell-ui-extras/src/notify/look.rs new file mode 100644 index 00000000..ca562610 --- /dev/null +++ b/crates/eggshell-ui-extras/src/notify/look.rs @@ -0,0 +1,68 @@ +//! What a notice looks like until the render round settles its style: the +//! page's popover surface, at sonner's sizes. + +use eggshell_ui::{Style, TextSpec, Tw, tw}; +use egui::epaint::Shadow; + +pub(super) struct Look { + fill: egui::Color32, + border: egui::Color32, + text: egui::Color32, + border_width: f32, + radius: u8, + shadow: Option, + role: TextSpec, +} + +const WIDTH: f32 = 356.0; +/// Tailwind spacing units. +const PADDING: f32 = 4.0; +const INNER_GAP: f32 = 1.5; +const STACK_GAP: f32 = 3.5; + +impl Look { + pub(super) fn of(style: &Style) -> Self { + let popup = &style.menu.popup; + let colors = popup.paint.states.rest; + Self { + fill: colors.fill, + border: colors.border, + text: colors.text, + border_width: popup.border_width, + radius: style.menu.radius, + shadow: popup.paint.shadow, + role: style + .menu + .text + .clone() + .unwrap_or_else(|| style.text.clone()), + } + } + + pub(super) fn stack(&self) -> Tw { + tw().flex().flex_col().gap(STACK_GAP).sense_hover() + } + + pub(super) fn card(&self) -> Tw { + let card = tw() + .flex() + .items_center() + .gap(INNER_GAP) + .w_px(WIDTH) + .p(PADDING) + .border(self.border_width) + .border_color(self.border) + .bg(self.fill) + .text(self.text) + .rounded_px(f32::from(self.radius)) + .role(self.role.clone()); + match self.shadow { + Some(shadow) => card.shadow(shadow), + None => card, + } + } + + pub(super) fn sentence(&self) -> Tw { + tw().flex_1().min_w_0() + } +} diff --git a/crates/eggshell-ui-extras/src/notify/mod.rs b/crates/eggshell-ui-extras/src/notify/mod.rs new file mode 100644 index 00000000..851bf6b4 --- /dev/null +++ b/crates/eggshell-ui-extras/src/notify/mod.rs @@ -0,0 +1,474 @@ +//! TODO(prose) +//! +//! ``` +//! use core::time::Duration; +//! use eggshell_ui::{Builder, Distance}; +//! use eggshell_ui_extras::notify::{Lifetime, Notice, NoticeId, NotifyExt, ScreenAnchor}; +//! +//! #[derive(Clone, Copy)] +//! enum Act { +//! CopyDetails, +//! } +//! +//! struct App { +//! toast: Option, +//! notices: Vec>, +//! copied: Option, +//! } +//! +//! fn view<'f>(b: &mut Builder<'_, 'f, App>, app: &'f App) { +//! b.notifications("toast", app.toast.as_slice()) +//! .at(ScreenAnchor::BottomCenter, Distance::new(28.0)) +//! .lifetime(Lifetime::Dwell(Duration::from_millis(2400))) +//! .on_dismiss(|app: &mut App, _, _| app.toast = None) +//! .add(); +//! b.notifications("notices", &app.notices) +//! .at(ScreenAnchor::TopRight, Distance::new(16.0)) +//! .on_action(|app: &mut App, id, Act::CopyDetails| app.copied = Some(id)) +//! .on_dismiss(|app: &mut App, id, _| app.notices.retain(|n| n.id != id)) +//! .add(); +//! } +//! +//! let mut app = App { toast: None, notices: Vec::new(), copied: None }; +//! app.toast = Some(Notice::new(1, "Copied")); +//! app.notices.push(Notice::new(2, "Export failed.").action("Copy details", Act::CopyDetails)); +//! ``` + +mod dwell; +mod look; + +use core::time::Duration; +use std::collections::HashMap; +use std::rc::Rc; + +use eggshell_ui::overlay::{Align, Anchor, Band, DismissOn, Focus, Outside, Placement, Side}; +use eggshell_ui::{Boundary, Builder, Distance, Icon, Key, NodeUi as _, Scope, Sides, icons}; +use egui::accesskit::Live; +use egui::{Context, Id, Modifiers, Role}; + +use dwell::{Countdown, Dwell, Hold}; +use look::Look; + +/// TODO(prose): the application's name for a notice. A notice with a new id +/// is a new notice: its dwell starts afresh. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct NoticeId(u64); + +impl NoticeId { + /// TODO(prose) + pub const fn new(id: u64) -> Self { + Self(id) + } +} + +impl From for NoticeId { + fn from(id: u64) -> Self { + Self(id) + } +} + +impl From for u64 { + fn from(id: NoticeId) -> u64 { + id.0 + } +} + +/// TODO(prose): the action of a notice that has none. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum NoAction {} + +/// TODO(prose): one notification, held by the application: an `Option` of +/// them is a slot a new one replaces, a `Vec` a stack. +#[derive(Clone, Debug, PartialEq)] +pub struct Notice { + /// TODO(prose) + pub id: NoticeId, + /// TODO(prose) + pub text: String, + /// TODO(prose): shown as buttons, in this order. + pub actions: Vec>, +} + +/// TODO(prose) +#[derive(Clone, Debug, PartialEq)] +pub struct NoticeAction { + /// TODO(prose): the button's label. + pub label: String, + /// TODO(prose): what [`on_action`](Notifications::on_action) is given. + pub act: Act, +} + +impl Notice { + /// TODO(prose) + pub fn new(id: impl Into, text: impl Into) -> Self { + Self { + id: id.into(), + text: text.into(), + actions: Vec::new(), + } + } + + /// TODO(prose) + #[must_use] + pub fn action(mut self, label: impl Into, act: Act) -> Self { + self.actions.push(NoticeAction { + label: label.into(), + act, + }); + self + } +} + +/// TODO(prose): how long the notices of a stack stay up. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Lifetime { + /// TODO(prose): each for this long on screen, on egui's clock, not + /// counting the time the stack is hovered or focused or the window is + /// in the background. + Dwell(Duration), + /// TODO(prose): until the application removes them. + UntilDismissed, +} + +/// TODO(prose): why [`on_dismiss`](Notifications::on_dismiss) ran. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Dismissed { + /// TODO(prose): its dwell ran out. + Expired, + /// TODO(prose): its × was pressed. + Closed, + /// TODO(prose): Esc was pressed with focus inside it. + Escape, +} + +/// TODO(prose): the corner or edge of the window a stack sits at. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ScreenAnchor { + /// TODO(prose) + TopLeft, + /// TODO(prose) + TopCenter, + /// TODO(prose) + TopRight, + /// TODO(prose) + BottomLeft, + /// TODO(prose) + BottomCenter, + /// TODO(prose) + BottomRight, +} + +impl ScreenAnchor { + /// TODO(prose): core's placement of a stack at this anchor, `inset` from + /// every edge of the window. + pub fn placement(self, inset: Distance) -> Placement { + let align = match self { + Self::TopLeft | Self::BottomLeft => Align::Start, + Self::TopCenter | Self::BottomCenter => Align::Center, + Self::TopRight | Self::BottomRight => Align::End, + }; + Placement::edge(self.side()) + .align(align) + .boundary(Boundary::Window.inset(Sides::all(inset))) + } + + fn side(self) -> Side { + match self { + Self::TopLeft | Self::TopCenter | Self::TopRight => Side::Top, + Self::BottomLeft | Self::BottomCenter | Self::BottomRight => Side::Bottom, + } + } +} + +/// Whether a transient toast shows its ×. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CloseButton { + Hidden, + Shown, +} + +/// TODO(prose) +pub trait NotifyExt<'b, 'f, A> { + /// TODO(prose): the stack `key` showing `items`, newest (last) nearest + /// its anchor. Nothing is shown while `items` is empty. + fn notifications<'s, K: Key + Clone, Act: Clone + 'static>( + &'s mut self, + key: K, + items: &'s [Notice], + ) -> Notifications<'s, 'b, 'f, A, K, Act>; +} + +impl<'b, 'f, A: 'static> NotifyExt<'b, 'f, A> for Builder<'b, 'f, A> { + fn notifications<'s, K: Key + Clone, Act: Clone + 'static>( + &'s mut self, + key: K, + items: &'s [Notice], + ) -> Notifications<'s, 'b, 'f, A, K, Act> { + Notifications { + b: self, + key, + items, + anchor: ScreenAnchor::BottomRight, + inset: Distance::new(24.0), + lifetime: Lifetime::UntilDismissed, + close: CloseButton::Hidden, + name: "Notifications".to_owned(), + on_action: None, + on_dismiss: None, + } + } +} + +type OnAction = Rc; +type OnDismiss = Rc; + +/// TODO(prose): a stack of notices, drawn above the page and its dialogs, +/// and announced politely as it changes. +#[must_use = "the notifications are not added until you call `.add()`"] +pub struct Notifications<'s, 'b, 'f, A, K, Act> { + b: &'s mut Builder<'b, 'f, A>, + key: K, + items: &'s [Notice], + anchor: ScreenAnchor, + inset: Distance, + lifetime: Lifetime, + close: CloseButton, + name: String, + on_action: Option>, + on_dismiss: Option>, +} + +impl<'s, 'b, 'f, A: 'static, K: Key + Clone, Act: Clone + 'static> + Notifications<'s, 'b, 'f, A, K, Act> +{ + /// TODO(prose): where the stack sits, `inset` from the window's edges. + /// [`ScreenAnchor::BottomRight`], 24 points in, unless set. + pub fn at(self, anchor: ScreenAnchor, inset: Distance) -> Self { + Self { + anchor, + inset, + ..self + } + } + + /// TODO(prose): [`Lifetime::UntilDismissed`] unless set. + pub fn lifetime(self, lifetime: Lifetime) -> Self { + Self { lifetime, ..self } + } + + /// TODO(prose): gives each notice of a [`Lifetime::Dwell`] stack a ×, + /// which the notices of an [`UntilDismissed`](Lifetime::UntilDismissed) + /// stack always have. + pub fn closable(self) -> Self { + Self { + close: CloseButton::Shown, + ..self + } + } + + /// TODO(prose): the stack's accessible name; "Notifications" unless set. + pub fn named(self, name: impl Into) -> Self { + Self { + name: name.into(), + ..self + } + } + + /// TODO(prose): runs when an action's button is pressed. The notice + /// stays up unless the handler removes it. + pub fn on_action(self, on_action: impl Fn(&mut A, NoticeId, Act) + 'static) -> Self { + Self { + on_action: Some(Rc::new(on_action)), + ..self + } + } + + /// TODO(prose): runs when a notice expires, its × is pressed, or Esc is + /// pressed with focus inside it: remove it. A notice no handler removes + /// stays up, and expires only once. + pub fn on_dismiss(self, on_dismiss: impl Fn(&mut A, NoticeId, Dismissed) + 'static) -> Self { + Self { + on_dismiss: Some(Rc::new(on_dismiss)), + ..self + } + } + + /// TODO(prose) + #[track_caller] + pub fn add(self) { + let Self { + b, + key, + items, + anchor, + inset, + lifetime, + close, + name, + on_action, + on_dismiss, + } = self; + let dwells = b + .id_of(key.clone()) + .with("eggshell-ui-extras-notify-dwells"); + if items.is_empty() { + b.ctx().data_mut(|data| data.remove::(dwells)); + return; + } + let close = match lifetime { + Lifetime::UntilDismissed => CloseButton::Shown, + Lifetime::Dwell(_) => close, + }; + let handlers = Handlers { + on_action, + on_dismiss, + }; + let look = Look::of(b.style()); + let ids: Vec = items.iter().map(|notice| notice.id).collect(); + let nearest_first = anchor.side() == Side::Top; + b.overlay(key) + .anchor(Anchor::Screen) + .placement(anchor.placement(inset)) + .band(Band::Popup) + .focus(Focus::None) + .dismiss_on(DismissOn::Never) + .outside(Outside::PassThrough) + .children(|s| { + let stack = s + .div_id("stack", look.stack(), |s| { + let mut cards = + |notice: &Notice| card(s, notice, &look, close, &handlers); + if nearest_first { + items.iter().rev().for_each(&mut cards); + } else { + items.iter().for_each(&mut cards); + } + }) + .role(Role::Status) + .named(name) + .live(Live::Polite); + if let Lifetime::Dwell(length) = lifetime { + let on_dismiss = handlers.on_dismiss.clone(); + stack.draw(move |app, ui| { + let hold = if ui.node_response().contains_pointer() + || ui.has_focus_within() + || !ui.input(|input| input.focused) + { + Hold::Held + } else { + Hold::Running + }; + let expired = tick(ui.ctx(), dwells, &ids, length, hold); + if let Some(on_dismiss) = on_dismiss { + for id in expired { + on_dismiss(app, id, Dismissed::Expired); + } + } + }); + } + }); + } +} + +struct Handlers { + on_action: Option>, + on_dismiss: Option>, +} + +/// The dwells of one stack's visible notices. +#[derive(Clone, Default)] +struct Dwells(HashMap); + +/// Moves the dwells of `ids` to egui's clock and books a repaint for the +/// next expiry. Returns the notices that expire now. +fn tick( + ctx: &Context, + dwells: Id, + ids: &[NoticeId], + length: Duration, + hold: Hold, +) -> Vec { + let now = Duration::try_from_secs_f64(ctx.input(|input| input.time).max(0.0)) + .unwrap_or(Duration::MAX); + let mut expired = Vec::new(); + let mut next: Option = None; + ctx.data_mut(|data| { + let Dwells(dwells) = data.get_temp_mut_or_default::(dwells); + dwells.retain(|id, _| ids.contains(id)); + for &id in ids { + let dwell = dwells.entry(id).or_insert_with(|| Dwell::new(now)); + match dwell.tick(now, length, hold) { + Countdown::Left(left) => next = Some(next.map_or(left, |next| next.min(left))), + Countdown::Expires => expired.push(id), + Countdown::Over => {} + } + } + }); + if let (Hold::Running, Some(next)) = (hold, next) { + ctx.request_repaint_after(next); + } + expired +} + +fn card( + s: &mut Scope<'_, '_, A>, + notice: &Notice, + look: &Look, + close: CloseButton, + handlers: &Handlers, +) { + let id = notice.id; + let card = s.div_id(id, look.card(), |s| { + s.text(look.sentence(), notice.text.clone()); + for (at, action) in notice.actions.iter().enumerate() { + let (act, on_action) = (action.act.clone(), handlers.on_action.clone()); + s.button(("action", at), action.label.clone()) + .on_click(move |app| { + if let Some(on_action) = on_action { + on_action(app, id, act); + } + }); + } + if close == CloseButton::Shown { + let on_dismiss = handlers.on_dismiss.clone(); + let name = format!("Dismiss: {}", notice.text); + s.button("close", (Icon::new(icons::CLOSE), name)) + .on_click(move |app| { + if let Some(on_dismiss) = on_dismiss { + on_dismiss(app, id, Dismissed::Closed); + } + }); + } + }); + if let Some(on_dismiss) = handlers.on_dismiss.clone() { + card.draw(move |app, ui| { + if focus_was_inside(ui) + && ui.input_mut(|input| input.consume_key(Modifiers::NONE, egui::Key::Escape)) + { + on_dismiss(app, id, Dismissed::Escape); + } + }); + } +} + +/// Marks a notice that held focus at the end of its last draw. +#[derive(Clone, Copy, Default)] +struct FocusInside; + +/// Whether focus is inside the node now or was in its last draw: egui drops +/// the focus at the start of the pass an Esc is pressed in. +fn focus_was_inside(ui: &egui::Ui) -> bool { + let Some(node) = ui.node_id() else { + return false; + }; + let mark = node.with("eggshell-ui-extras-notify-focus"); + let now = ui.has_focus_within(); + let before = ui.data_mut(|data| { + let before = data.remove_temp::(mark).is_some(); + if now { + data.insert_temp(mark, FocusInside); + } + before + }); + now || before +} diff --git a/tests/it/main.rs b/tests/it/main.rs index d0217894..1f37fdf3 100644 --- a/tests/it/main.rs +++ b/tests/it/main.rs @@ -70,6 +70,7 @@ mod modal; mod mount; mod named_layouts; mod nested_layouts; +mod notify; mod numbers; mod overlay; mod overlay_input; diff --git a/tests/it/notify.rs b/tests/it/notify.rs new file mode 100644 index 00000000..41ae110f --- /dev/null +++ b/tests/it/notify.rs @@ -0,0 +1,407 @@ +//! Notifications (#347) through the real path: a toast slot and a notice +//! stack, built, laid out and drawn by the rig, on a clock the harness steps. + +use core::time::Duration; +use std::cell::Cell; +use std::rc::Rc; + +use eggshell_ui::overlay::Modal; +use eggshell_ui::{Builder, Distance, TextStyle, tw}; +use eggshell_ui_extras::notify::{Dismissed, Lifetime, Notice, NoticeId, NotifyExt, ScreenAnchor}; +use eggshell_ui_shadcn::Tokens; +use egui::accesskit::{Live, Role}; +use egui::{Key, Rect, Theme, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; + +use crate::support::{self, Rig, click_node, hover_over, rect_of}; + +const STEP: f32 = 0.05; +const DWELL: Duration = Duration::from_millis(1000); +const SIZE: egui::Vec2 = vec2(800.0, 600.0); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Act { + CopyDetails, +} + +struct App { + toast: Option, + notices: Vec>, + closable: bool, + inset: f32, + dialog: bool, + dismissed: Vec<(NoticeId, Dismissed)>, + acted: Vec<(NoticeId, Act)>, +} + +impl Default for App { + fn default() -> Self { + Self { + toast: None, + notices: Vec::new(), + closable: false, + inset: 28.0, + dialog: false, + dismissed: Vec::new(), + acted: Vec::new(), + } + } +} + +fn view<'f>(b: &mut Builder<'_, 'f, App>, app: &'f App) { + b.div(tw().p(4.0), |b| { + b.button("page", "Page").add(); + }); + if app.dialog { + b.overlay("dialog") + .modal(Modal::Center) + .on_dismiss(|app: &mut App| app.dialog = false) + .children(|s| { + s.div(tw().p(4.0).w_px(200.0), |s| { + s.button("inside", "Inside").add(); + }); + }); + } + let toast = b + .notifications("toast", app.toast.as_slice()) + .at(ScreenAnchor::BottomCenter, Distance::new(app.inset)) + .lifetime(Lifetime::Dwell(DWELL)) + .on_dismiss(|app: &mut App, id, why| { + app.dismissed.push((id, why)); + if app.toast.as_ref().is_some_and(|toast| toast.id == id) { + app.toast = None; + } + }); + if app.closable { + toast.closable().add(); + } else { + toast.add(); + } + b.notifications("notices", &app.notices) + .at(ScreenAnchor::TopRight, Distance::new(16.0)) + .named("Alerts") + .on_action(|app: &mut App, id, act| app.acted.push((id, act))) + .on_dismiss(|app: &mut App, id, why| { + app.dismissed.push((id, why)); + app.notices.retain(|notice| notice.id != id); + }) + .add(); +} + +/// A rig that settles with no notices, then posts `app`'s and draws one +/// frame, so that a dwell starts at a known time. +fn harness(mut app: App) -> Harness<'static, Rig> { + let tokens = Tokens::for_theme(Theme::Light); + let (toast, notices) = (app.toast.take(), std::mem::take(&mut app.notices)); + let mut harness = support::harness_stepped( + SIZE, + STEP, + TextStyle::new(tokens.text_role(), tokens.foreground), + app, + view, + ); + harness.run_steps(2); + let app = &mut harness.state_mut().app; + (app.toast, app.notices) = (toast, notices); + harness.step(); + harness +} + +fn wait(harness: &mut Harness<'_, Rig>, time: Duration) { + harness.run_steps((time.as_secs_f32() / STEP).ceil() as usize); +} + +const TOAST: &str = "/\"toast\"/\"stack\""; +const NOTICES: &str = "/\"notices\"/\"stack\""; + +fn card(stack: &str, id: u64) -> String { + format!("{stack}/NoticeId({id})") +} + +fn shown(harness: &Harness<'_, Rig>, stack: &str) -> Vec { + let prefix = format!("{stack}/NoticeId("); + harness + .state() + .nodes + .iter() + .filter(|(path, _)| path.starts_with(&prefix) && !path[prefix.len()..].contains('/')) + .map(|(path, _)| path.clone()) + .collect() +} + +fn toast(id: u64) -> Option { + Some(Notice::new(id, format!("Toast {id}"))) +} + +fn notice(id: u64) -> Notice { + Notice::new(id, format!("Notice {id}")).action("Copy details", Act::CopyDetails) +} + +#[test] +fn a_toast_expires_after_its_dwell_on_the_stepped_clock() { + let mut harness = harness(App { + toast: toast(1), + ..App::default() + }); + assert_eq!(shown(&harness, TOAST), [card(TOAST, 1)]); + wait(&mut harness, DWELL - Duration::from_millis(200)); + assert_eq!(shown(&harness, TOAST), [card(TOAST, 1)], "not yet"); + assert!(harness.state().app.dismissed.is_empty()); + wait(&mut harness, Duration::from_millis(400)); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(1), Dismissed::Expired)] + ); + assert!(shown(&harness, TOAST).is_empty()); +} + +#[test] +fn a_running_dwell_books_a_repaint_for_its_expiry() { + let delay = |harness: &Harness<'_, Rig>| { + harness.output().viewport_output[&egui::ViewportId::ROOT].repaint_delay + }; + let mut harness = harness(App::default()); + harness.run_steps(10); + assert_eq!( + delay(&harness), + Duration::MAX, + "precondition: the page is idle" + ); + harness.state_mut().app.toast = toast(1); + harness.run_steps(10); + let left = DWELL - Duration::from_secs_f32(9.0 * STEP); + assert!( + delay(&harness).abs_diff(left) <= Duration::from_secs_f32(STEP), + "a repaint is booked for the expiry, {left:?} away: {:?}", + delay(&harness) + ); +} + +#[test] +fn the_dwell_holds_while_the_pointer_is_over_the_stack() { + let mut harness = harness(App { + toast: toast(1), + ..App::default() + }); + let over = rect_of(&harness, &card(TOAST, 1)).center(); + hover_over(&mut harness, over); + wait(&mut harness, DWELL * 3); + assert_eq!(shown(&harness, TOAST), [card(TOAST, 1)], "held"); + assert!(harness.state().app.dismissed.is_empty()); + hover_over(&mut harness, egui::pos2(5.0, 300.0)); + wait(&mut harness, DWELL); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(1), Dismissed::Expired)], + "resumes once the pointer leaves" + ); +} + +#[test] +fn the_dwell_holds_while_focus_is_inside_and_while_the_window_is_in_the_background() { + let mut harness = harness(App { + toast: toast(1), + closable: true, + ..App::default() + }); + harness + .get_by_role_and_label(Role::Button, "Dismiss: Toast 1") + .focus(); + wait(&mut harness, DWELL * 2); + assert!(harness.state().app.dismissed.is_empty(), "held by focus"); + + harness.get_by_role_and_label(Role::Button, "Page").focus(); + harness.run_steps(2); + harness.input_mut().focused = false; + wait(&mut harness, DWELL * 2); + assert!( + harness.state().app.dismissed.is_empty(), + "held while the window is unfocused" + ); + harness.input_mut().focused = true; + wait(&mut harness, DWELL); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(1), Dismissed::Expired)] + ); +} + +#[test] +fn a_replacement_keeps_one_toast_and_starts_its_own_dwell() { + let mut harness = harness(App { + toast: toast(1), + ..App::default() + }); + wait(&mut harness, DWELL / 2); + harness.state_mut().app.toast = toast(2); + harness.run_steps(2); + assert_eq!(shown(&harness, TOAST), [card(TOAST, 2)]); + wait(&mut harness, DWELL * 3 / 4); + assert_eq!( + shown(&harness, TOAST), + [card(TOAST, 2)], + "past the first toast's expiry, the second is still up" + ); + wait(&mut harness, DWELL / 2); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(2), Dismissed::Expired)], + "only the toast on screen expires" + ); +} + +#[test] +fn a_persistent_notice_never_expires_and_newest_sits_nearest_the_top_anchor() { + let mut harness = harness(App { + notices: vec![notice(1), notice(2)], + ..App::default() + }); + wait(&mut harness, DWELL * 5); + assert!(harness.state().app.dismissed.is_empty()); + let (older, newer) = ( + rect_of(&harness, &card(NOTICES, 1)), + rect_of(&harness, &card(NOTICES, 2)), + ); + assert!(newer.max.y <= older.min.y, "{newer:?} above {older:?}"); +} + +#[test] +fn esc_dismisses_a_notice_only_while_focus_is_inside_it() { + let mut harness = harness(App { + notices: vec![notice(1), notice(2)], + ..App::default() + }); + harness.key_press(Key::Escape); + harness.run_steps(2); + assert!( + harness.state().app.dismissed.is_empty(), + "focus is elsewhere" + ); + + harness + .get_by_role_and_label(Role::Button, "Dismiss: Notice 1") + .focus(); + harness.run_steps(2); + harness.key_press(Key::Escape); + harness.run_steps(2); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(1), Dismissed::Escape)] + ); + assert_eq!(shown(&harness, NOTICES), [card(NOTICES, 2)]); +} + +#[test] +fn the_close_button_dismisses_its_notice() { + let mut harness = harness(App { + notices: vec![notice(1), notice(2)], + ..App::default() + }); + click_node(&mut harness, &format!("{}/\"close\"", card(NOTICES, 2))); + harness.run_steps(2); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(2), Dismissed::Closed)] + ); + assert_eq!(shown(&harness, NOTICES), [card(NOTICES, 1)]); +} + +#[test] +fn a_toast_has_no_close_button_unless_asked() { + let mut harness = harness(App { + toast: toast(1), + ..App::default() + }); + let close = |harness: &Harness<'_, Rig>| { + harness + .query_by_role_and_label(Role::Button, "Dismiss: Toast 1") + .is_some() + }; + assert!(!close(&harness)); + harness.state_mut().app.closable = true; + harness.run_steps(2); + assert!(close(&harness)); +} + +#[test] +fn an_action_button_runs_on_action_and_leaves_the_notice_up() { + let mut harness = harness(App { + notices: vec![notice(1)], + ..App::default() + }); + harness + .get_by_role_and_label(Role::Button, "Copy details") + .click(); + harness.run_steps(2); + assert_eq!( + harness.state().app.acted, + [(NoticeId::new(1), Act::CopyDetails)] + ); + assert_eq!(shown(&harness, NOTICES), [card(NOTICES, 1)]); +} + +#[test] +fn a_stack_is_a_polite_status_region_by_its_name() { + let harness = harness(App { + toast: toast(1), + notices: vec![notice(1)], + ..App::default() + }); + for name in ["Notifications", "Alerts"] { + let region = harness.get_by_role_and_label(Role::Status, name); + assert_eq!(region.accesskit_node().data().live(), Some(Live::Polite)); + } +} + +#[test] +fn the_stack_follows_its_inset_and_its_rect_is_queryable() { + let rect = Rc::new(Cell::new(Rect::NOTHING)); + let mut harness = harness(App { + toast: toast(1), + ..App::default() + }); + let seen = Rc::clone(&rect); + harness.state_mut().observe = Some(Box::new(move |placed| { + if let Some(overlay) = placed.overlay("toast") { + seen.set(overlay.rect()); + } + })); + let at = |harness: &mut Harness<'_, Rig>, inset: f32| { + harness.state_mut().app.inset = inset; + harness.run_steps(2); + rect.get() + }; + let flush = at(&mut harness, 0.0); + let (at_28, at_41) = (at(&mut harness, 28.0), at(&mut harness, 41.0)); + assert!(flush.is_positive(), "precondition: the stack is placed"); + assert_eq!(at_28.max.y, flush.max.y - 28.0); + assert_eq!(at_41.max.y, flush.max.y - 41.0); + assert_eq!(at_41.size(), flush.size()); + assert_eq!(at_41.center().x, flush.center().x, "centred"); + assert!( + (flush.center().x - SIZE.x / 2.0).abs() < 10.0, + "centred: {flush:?}" + ); +} + +#[test] +fn a_notice_floats_above_an_open_dialog_and_takes_the_pointer() { + let mut harness = harness(App { + dialog: true, + ..App::default() + }); + harness.state_mut().app.notices.push(notice(1)); + harness.run_steps(2); + assert!( + harness.state().app.dialog, + "precondition: the dialog is open" + ); + click_node(&mut harness, &format!("{}/\"close\"", card(NOTICES, 1))); + harness.run_steps(2); + assert_eq!( + harness.state().app.dismissed, + [(NoticeId::new(1), Dismissed::Closed)] + ); + assert!(harness.state().app.dialog, "the press was the notice's"); +}