From 49bd2dc286c73da607bba9ce3dde9a3f411ea063 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 4 Nov 2026 18:37:48 +0100 Subject: [PATCH] feat(cli-rs): add toasts and the theme error toast Toasts ports ToastProvider and the toast view: queue, timer, pause on hover, actions, and +N more. theme_error shows ThemeState::take_error() values. P-COMP U.3/toast and U.3/toast-theme match; a replacing toast does not keep stale fields (deviation T21). --- packages/cli-rs/crates/ui/src/toast.rs | 367 +++++++++++++++++- packages/cli-rs/crates/ui/tests/dialogs.rs | 70 +++- .../cli-rs/parity/component/U.3-toast.tsx | 40 ++ .../deviations/T21-toast-replace-merge.md | 18 + .../parity/fixtures/U.3/toast-theme.json | 40 ++ .../cli-rs/parity/fixtures/U.3/toast.json | 35 ++ 6 files changed, 567 insertions(+), 3 deletions(-) create mode 100644 packages/cli-rs/parity/component/U.3-toast.tsx create mode 100644 packages/cli-rs/parity/deviations/T21-toast-replace-merge.md create mode 100644 packages/cli-rs/parity/fixtures/U.3/toast-theme.json create mode 100644 packages/cli-rs/parity/fixtures/U.3/toast.json diff --git a/packages/cli-rs/crates/ui/src/toast.rs b/packages/cli-rs/crates/ui/src/toast.rs index 1ebc777d21a..771a0082a37 100644 --- a/packages/cli-rs/crates/ui/src/toast.rs +++ b/packages/cli-rs/crates/ui/src/toast.rs @@ -1 +1,366 @@ -//! Toasts (U.3). +//! Toasts (U.3): `packages/tui/src/ui/toast.tsx`, plus the theme error toast of +//! `component/theme-error-toast.tsx`. +//! +//! [`Toasts`] is the `ToastProvider` and the `` view together: one toast at a time in the top right +//! corner, a queue behind it, a timer that dismisses it, pause while hovered, and an optional action. + +use crate::theme::{Theme, ThemeError}; +use opentui::prelude::*; +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::rc::{Rc, Weak}; +use std::time::{Duration, Instant}; + +pub const DEFAULT_DURATION: Duration = Duration::from_millis(5000); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Variant { + #[default] + Info, + Success, + Warning, + Error, +} + +/// A toast's action: `› label`, run when the toast is clicked. +#[derive(Clone)] +pub struct ToastAction { + pub label: String, + pub run: Rc, +} + +/// `ToastOptions`; `duration` is [`DEFAULT_DURATION`] unless set. +#[derive(Clone, Default)] +pub struct ToastOptions { + pub title: Option, + pub message: String, + pub variant: Variant, + pub duration: Option, + pub action: Option, +} + +impl ToastOptions { + pub fn new(variant: Variant, message: impl Into) -> Self { + Self { + variant, + message: message.into(), + ..Self::default() + } + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + pub fn duration(mut self, duration: Duration) -> Self { + self.duration = Some(duration); + self + } + + pub fn action(mut self, label: impl Into, run: impl Fn() + 'static) -> Self { + self.action = Some(ToastAction { + label: label.into(), + run: Rc::new(run), + }); + self + } + + fn length(&self) -> Duration { + self.duration.unwrap_or(DEFAULT_DURATION) + } +} + +struct Inner { + app: App, + theme: RefCell, + parent: View, + surface: RefCell>, + current: RefCell>, + queue: RefCell>, + timer: Cell>, + started: Cell, + remaining: Cell, + paused: Cell, + hovered: Cell, +} + +/// The toast queue and its view. Cloning is cheap. +#[derive(Clone)] +pub struct Toasts(Rc); + +impl Toasts { + /// Creates the toasts. A toast floats over the top right of `parent`; the TUI uses the app's main box, which + /// sits beneath the dialog host. + pub fn new(app: &App, theme: Theme, parent: &View) -> Self { + Self(Rc::new(Inner { + app: app.clone(), + theme: RefCell::new(theme), + parent: parent.clone(), + surface: RefCell::new(None), + current: RefCell::new(None), + queue: RefCell::new(VecDeque::new()), + timer: Cell::new(None), + started: Cell::new(app.now()), + remaining: Cell::new(Duration::ZERO), + paused: Cell::new(false), + hovered: Cell::new(false), + })) + } + + pub fn set_theme(&self, theme: Theme) { + *self.0.theme.borrow_mut() = theme; + self.paint(); + } + + /// Shows a toast now, or queues it while one is paused or others wait. + pub fn show(&self, options: ToastOptions) { + let busy = self.0.current.borrow().is_some() + && (self.0.paused.get() || !self.0.queue.borrow().is_empty()); + if busy { + self.0.queue.borrow_mut().push_back(options); + self.paint(); + return; + } + let duration = options.length(); + *self.0.current.borrow_mut() = Some(options); + self.start(duration); + self.paint(); + } + + /// `toast.error`: an error toast with the message. + pub fn error(&self, message: impl Into) { + self.show(ToastOptions::new(Variant::Error, message)); + } + + /// The theme error toast: `Failed to load theme: {name}`. + pub fn theme_error(&self, error: ThemeError) { + self.show( + ToastOptions::new(Variant::Error, error.message) + .title(format!("Failed to load theme: {}", error.name)), + ); + } + + /// Hides the current toast and shows the next queued one. + pub fn dismiss(&self) { + self.clear_timer(); + let next = self.0.queue.borrow_mut().pop_front(); + let duration = next.as_ref().map(ToastOptions::length); + *self.0.current.borrow_mut() = next; + match duration { + None => self.0.paused.set(false), + Some(duration) => { + self.0.remaining.set(duration); + if !self.0.paused.get() { + self.start(duration); + } + } + } + self.paint(); + } + + /// Stops the timer, keeping the time left. + pub fn pause(&self) { + if self.0.current.borrow().is_none() || self.0.paused.get() { + return; + } + self.0.paused.set(true); + let elapsed = self + .0 + .app + .now() + .saturating_duration_since(self.0.started.get()); + self.0 + .remaining + .set(self.0.remaining.get().saturating_sub(elapsed)); + self.clear_timer(); + } + + pub fn resume(&self) { + if self.0.current.borrow().is_none() || !self.0.paused.get() { + return; + } + self.0.paused.set(false); + self.start(self.0.remaining.get()); + } + + /// Dismisses the toast and runs its action, as a click does. + pub fn activate(&self) { + let action = self + .0 + .current + .borrow() + .as_ref() + .and_then(|toast| toast.action.clone()); + self.dismiss(); + if let Some(action) = action { + (action.run)(); + } + } + + pub fn current(&self) -> Option { + self.0.current.borrow().clone() + } + + /// How many toasts wait behind the current one. + pub fn pending(&self) -> usize { + self.0.queue.borrow().len() + } + + fn start(&self, duration: Duration) { + self.clear_timer(); + self.0.remaining.set(duration); + self.0.started.set(self.0.app.now()); + let weak = Rc::downgrade(&self.0); + let timer = self.0.app.set_timeout(duration, move |_cx| { + if let Some(inner) = weak.upgrade() { + inner.timer.set(None); + Toasts(inner).dismiss(); + } + }); + self.0.timer.set(Some(timer)); + } + + fn clear_timer(&self) { + if let Some(timer) = self.0.timer.take() { + self.0.app.cancel_timer(timer); + } + } + + fn paint(&self) { + if let Some(old) = self.0.surface.borrow_mut().take() { + old.detach(); + } + let current = self.0.current.borrow().clone(); + let Some(toast) = current else { return }; + let surface = surface(self, &toast, self.pending()); + self.0.parent.add(&surface); + *self.0.surface.borrow_mut() = Some(surface); + } +} + +// `ToastSurface`. +fn surface(toasts: &Toasts, toast: &ToastOptions, pending: usize) -> View { + let app = &toasts.0.app; + let theme = toasts.0.theme.borrow().clone(); + let hovered = toasts.0.hovered.get(); + let width = app.size().0; + let feedback = &theme.text.feedback; + let border = match toast.variant { + Variant::Info => feedback.info.base, + Variant::Success => feedback.success.base, + Variant::Warning => feedback.warning.base, + Variant::Error => feedback.error.base, + }; + let affordance = Text::new( + app, + match &toast.action { + Some(action) => format!("› {}", action.label), + None => "x".to_owned(), + }, + ) + .shrink(0.0) + .margin_edge(Edge::Left, 2) + .wrap(WrapMode::None) + .fg(if hovered { + theme.text.action.primary.base + } else { + theme.text.muted + }); + if hovered && toast.action.is_some() { + affordance.bold(); + } + let body = View::new(app) + .width(Length::percent(100.0)) + .padding_x(2) + .padding_y(1) + .bg(theme.background.raised.high); + match &toast.title { + None => { + body.add( + &View::new(app) + .row() + .width(Length::percent(100.0)) + .child( + &Text::new(app, toast.message.as_str()) + .fg(theme.text.base) + .wrap(WrapMode::Word) + .grow(1.0) + .basis(Length::Auto), + ) + .child(&affordance), + ); + } + Some(title) => { + body.add( + &View::new(app) + .row() + .width(Length::percent(100.0)) + .margin_edge(Edge::Bottom, 1) + .child(&Text::new(app, title.as_str()).bold().fg(theme.text.base)) + .child(&View::new(app).grow(1.0).basis(Length::Auto)) + .child(&affordance), + ); + body.add( + &Text::new(app, toast.message.as_str()) + .fg(theme.text.base) + .wrap(WrapMode::Word) + .width(Length::percent(100.0)), + ); + } + } + if pending > 0 { + body.add( + &Text::new(app, format!("+{pending} more")) + .fg(theme.text.muted) + .margin_edge(Edge::Top, 1), + ); + } + let surface = View::new(app) + .absolute() + .position(Edge::Top, 1) + .position(Edge::Right, 2) + .max_width(60.min(i32::from(width) - 6)) + .justify(Justify::Center) + .align_items(Align::Start) + .border(BorderStyle::Heavy) + .border_sides(Sides::LEFT | Sides::RIGHT) + .border_color(border) + .child(&body); + let weak: Weak = Rc::downgrade(&toasts.0); + surface.on_hover(move |_cx, over| { + let Some(inner) = weak.upgrade() else { return }; + inner.hovered.set(over); + let toasts = Toasts(inner); + if over { + toasts.pause(); + } else { + toasts.resume(); + } + // Repaint after the event, since this handler belongs to the surface being replaced. + let weak = Rc::downgrade(&toasts.0); + toasts.0.app.defer(move |_cx| { + if let Some(inner) = weak.upgrade() { + Toasts(inner).paint(); + } + }); + }); + let weak: Weak = Rc::downgrade(&toasts.0); + surface.on_mouse(move |_cx, event| { + if !matches!(event.kind, MouseEventKind::Up(_)) { + return; + } + let Some(inner) = weak.upgrade() else { return }; + if inner + .app + .selected_text() + .is_some_and(|text| !text.is_empty()) + { + return; + } + let app = inner.app.clone(); + let toasts = Toasts(inner); + app.defer(move |_cx| toasts.activate()); + }); + surface +} diff --git a/packages/cli-rs/crates/ui/tests/dialogs.rs b/packages/cli-rs/crates/ui/tests/dialogs.rs index 83009060819..7327eebf3ae 100644 --- a/packages/cli-rs/crates/ui/tests/dialogs.rs +++ b/packages/cli-rs/crates/ui/tests/dialogs.rs @@ -5,12 +5,13 @@ use opencode_parity::assert_fixture; use opencode_ui::dialog::{DialogKeymap, Dialogs, route_keys}; use opencode_ui::keymap::{Keybinds, Options}; -use opencode_ui::theme::{Catalog, Theme, ThemeMode}; -use opencode_ui::{alert, confirm}; +use opencode_ui::theme::{Catalog, Theme, ThemeError, ThemeMode}; +use opencode_ui::{alert, confirm, toast}; use opentui::prelude::*; use opentui::testing::TestApp; use std::cell::RefCell; use std::rc::Rc; +use std::time::Duration; struct Kit { app: TestApp, @@ -175,3 +176,68 @@ fn replace_closes_the_previous_dialog_and_restores_focus_after_the_last() { assert_eq!(*log.borrow(), ["first", "second"]); assert!(input.is_focused()); } + +fn toasts(kit: &Kit) -> toast::Toasts { + toast::Toasts::new(&kit.app, theme(), &kit.app.root()) +} + +#[test] +fn theme_error_toast_matches_typescript() { + let kit = kit(70, 12); + let toasts = toasts(&kit); + toasts.theme_error(ThemeError { + name: "mine".into(), + message: "Color reference \"missing\" not found in defs or theme".into(), + }); + assert_fixture(&kit.app.render(), "U.3/toast-theme"); +} + +#[test] +fn toast_without_title_wraps_as_typescript_does() { + let kit = kit(50, 10); + let toasts = toasts(&kit); + toasts.show(toast::ToastOptions::new( + toast::Variant::Success, + "Copied the session link to the clipboard so you can share it", + )); + assert_fixture(&kit.app.render(), "U.3/toast"); +} + +#[test] +fn toasts_time_out_queue_while_paused_and_run_their_action() { + let kit = kit(70, 12); + let toasts = toasts(&kit); + toasts.show(toast::ToastOptions::new(toast::Variant::Info, "one")); + // Showing while nothing waits replaces the current toast, as in TypeScript. + toasts.show(toast::ToastOptions::new(toast::Variant::Info, "two").title("Two")); + assert_eq!(toasts.current().unwrap().message, "two"); + assert_eq!(toasts.pending(), 0); + kit.app.advance(Duration::from_millis(4999)); + assert!(toasts.current().is_some()); + kit.app.advance(Duration::from_millis(1)); + assert!(toasts.current().is_none()); + + let ran = Rc::new(RefCell::new(0)); + let count = ran.clone(); + toasts.show( + toast::ToastOptions::new(toast::Variant::Warning, "first") + .duration(Duration::from_millis(1000)) + .action("Open", move || *count.borrow_mut() += 1), + ); + kit.app.advance(Duration::from_millis(400)); + toasts.pause(); + toasts.show(toast::ToastOptions::new(toast::Variant::Info, "second")); + assert_eq!(toasts.pending(), 1); + assert!(kit.app.render().text().contains("+1 more")); + kit.app.advance(Duration::from_secs(10)); + assert_eq!(toasts.current().unwrap().message, "first"); + toasts.resume(); + kit.app.advance(Duration::from_millis(599)); + assert_eq!(toasts.current().unwrap().message, "first"); + toasts.activate(); + assert_eq!(*ran.borrow(), 1); + assert_eq!(toasts.current().unwrap().message, "second"); + kit.app.advance(Duration::from_millis(5000)); + assert!(toasts.current().is_none()); + assert!(kit.app.render().text().trim().is_empty()); +} diff --git a/packages/cli-rs/parity/component/U.3-toast.tsx b/packages/cli-rs/parity/component/U.3-toast.tsx new file mode 100644 index 00000000000..cb675b7c32a --- /dev/null +++ b/packages/cli-rs/parity/component/U.3-toast.tsx @@ -0,0 +1,40 @@ +/** @jsxImportSource @opentui/solid */ +// P-COMP fixtures for the toast (packages/tui/src/ui/toast.tsx): crates/ui/tests/dialogs.rs. "U.3/toast-theme" is +// the theme error toast (component/theme-error-toast.tsx); "U.3/toast" has no title and a message that wraps. +import { onMount } from "solid-js" +import { Toast, useToast, type ToastOptions } from "../../../tui/src/ui/toast" +import { renderComponent } from "../lib/component" + +function Show(props: { toasts: Omit[] }) { + const toast = useToast() + onMount(() => props.toasts.forEach((item) => toast.show(item))) + return +} + +await renderComponent({ + fixture: "U.3/toast-theme", + width: 70, + height: 12, + element: () => ( + + ), + ready: (frame) => frame.includes("defs"), +}) + +await renderComponent({ + fixture: "U.3/toast", + width: 50, + height: 10, + element: () => ( + + ), + ready: (frame) => frame.includes("Copied"), +}) diff --git a/packages/cli-rs/parity/deviations/T21-toast-replace-merge.md b/packages/cli-rs/parity/deviations/T21-toast-replace-merge.md new file mode 100644 index 00000000000..07418ed0f58 --- /dev/null +++ b/packages/cli-rs/parity/deviations/T21-toast-replace-merge.md @@ -0,0 +1,18 @@ +# T21: a replacing toast does not keep the old toast's fields + +## TypeScript + +`toast.show` replaces the current toast when it is not paused and nothing is queued +(`packages/tui/src/ui/toast.tsx:167-175`). It does so with `setStore("currentToast", toastOptions)`. A Solid +store merges an object into the object already there, so fields the new toast does not set stay from the old +one. Showing `{ title: "Failed to load theme: mine", message: "…" }` and then `{ message: "queued" }` shows the +title of the first toast over the message of the second. A wrong `action` can stay the same way. + +## Rust + +`Toasts::show` replaces the whole toast. The second toast shows only its own message. + +## Reason + +The TypeScript behavior is a store-merge defect, not a design choice: the toast's type has no field meant to +carry over. P-COMP fixture `U.3/toast-theme` shows one toast only, so both sides render the same cells. diff --git a/packages/cli-rs/parity/fixtures/U.3/toast-theme.json b/packages/cli-rs/parity/fixtures/U.3/toast-theme.json new file mode 100644 index 00000000000..188d04d9984 --- /dev/null +++ b/packages/cli-rs/parity/fixtures/U.3/toast-theme.json @@ -0,0 +1,40 @@ +{ + "width": 70, + "height": 12, + "rows": [ + " ", + " ┃ ┃ ", + " ┃ Failed to load theme: mine x ┃ ", + " ┃ ┃ ", + " ┃ Color reference \"missing\" not found in defs or theme ┃ ", + " ┃ ┃ ", + " ", + " ", + " ", + " ", + " ", + " " + ], + "styles": [ + "#ffffffff #0a0a0aff 0", + "#e06c75ff #0a0a0aff 0", + "#ffffffff #1e1e1eff 0", + "#eeeeeeff #1e1e1eff 1", + "#808080ff #1e1e1eff 0", + "#eeeeeeff #1e1e1eff 0" + ], + "runs": [ + [[0,70]], + [[0,10],[1,1],[2,56],[1,1],[0,2]], + [[0,10],[1,1],[2,2],[3,26],[2,25],[4,1],[2,2],[1,1],[0,2]], + [[0,10],[1,1],[2,56],[1,1],[0,2]], + [[0,10],[1,1],[2,2],[5,52],[2,2],[1,1],[0,2]], + [[0,10],[1,1],[2,56],[1,1],[0,2]], + [[0,70]], + [[0,70]], + [[0,70]], + [[0,70]], + [[0,70]], + [[0,70]] + ] +} diff --git a/packages/cli-rs/parity/fixtures/U.3/toast.json b/packages/cli-rs/parity/fixtures/U.3/toast.json new file mode 100644 index 00000000000..d6a7c100a67 --- /dev/null +++ b/packages/cli-rs/parity/fixtures/U.3/toast.json @@ -0,0 +1,35 @@ +{ + "width": 50, + "height": 10, + "rows": [ + " ", + " ┃ ┃ ", + " ┃ Copied the session link to the x ┃ ", + " ┃ clipboard so you can share it ┃ ", + " ┃ ┃ ", + " ", + " ", + " ", + " ", + " " + ], + "styles": [ + "#ffffffff #0a0a0aff 0", + "#7fd88fff #0a0a0aff 0", + "#ffffffff #1e1e1eff 0", + "#eeeeeeff #1e1e1eff 0", + "#808080ff #1e1e1eff 0" + ], + "runs": [ + [[0,50]], + [[0,8],[1,1],[2,38],[1,1],[0,2]], + [[0,8],[1,1],[2,2],[3,31],[2,2],[4,1],[2,2],[1,1],[0,2]], + [[0,8],[1,1],[2,2],[3,29],[2,7],[1,1],[0,2]], + [[0,8],[1,1],[2,38],[1,1],[0,2]], + [[0,50]], + [[0,50]], + [[0,50]], + [[0,50]], + [[0,50]] + ] +}