返回 CodeWhale
toast.rs
1 //! Toasts: one line, a mark and a sentence, stacked at the bottom right.
2 //!
3 //! The rendering half of the engine's `StatusToast` (`crates/tui/src/tui/
4 //! app/status.rs`, `Hmbown/CodeWhale` `58b1dd3dd`), plus the clock the engine
5 //! keeps beside it: a [`Ttl`] and a `born` instant the caller supplies, so
6 //! nothing here reads the time. Painting is a pure function of what the host
7 //! passes in ([`Toasts::at`]); expiry is [`Toasts::retain_live`], called by
8 //! the host with its own `now`. Failures and anything that needs the person
9 //! stay until they have been seen ([`Ttl::UntilSeen`]); a stack caps at
10 //! [`Toasts::max_visible`] and says `+n more` with the real n.
11 //!
12 //! A toast arrives and leaves in steps of ink (`Dim`, `Hint`, `Muted`, then
13 //! `Foreground`), never by moving, and only under [`MotionMode::Full`]:
14 //! reduced and still motion show it at full ink at once.
15
16 use std::{
17 borrow::Cow,
18 time::{Duration, Instant},
19 };
20
21 use ratatui::{
22 buffer::Buffer,
23 layout::Rect,
24 style::Modifier,
25 text::{Line, Span},
26 widgets::Widget,
27 };
28
29 use crate::{KeyHint, MotionMode, Paint, Role, State, StatusMark, Theme, text};
30
31 /// How long a toast lives.
32 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33 pub enum Ttl {
34 /// This many seconds after it was born.
35 Seconds(u16),
36 /// Until the person has seen it ([`Toasts::mark_seen`]), then
37 /// [`TOAST_SEEN_LINGER`] more: a failure must not vanish unread.
38 UntilSeen,
39 }
40
41 impl Ttl {
42 /// What [`Toast::new`] gives a state: failures, blocked states, and things
43 /// that need the person stay until seen; everything else lasts five seconds.
44 #[must_use]
45 pub const fn for_state(state: State) -> Self {
46 match state {
47 State::Failed | State::NeedsYou | State::Blocked => Self::UntilSeen,
48 _ => Self::Seconds(5),
49 }
50 }
51 }
52
53 /// How long a seen [`Ttl::UntilSeen`] toast stays before it goes.
54 pub const TOAST_SEEN_LINGER: Duration = Duration::from_secs(2);
55 /// How long a timed error toast ([`Toast::timed_error`]) lasts before expiring,
56 /// matching Desktop Wave 9 (`8000 ms`).
57 pub const TOAST_ERROR_SECONDS: u16 = 8;
58 /// A toast arrives over this long, in three steps of ink.
59 pub const TOAST_FADE_IN: Duration = Duration::from_millis(180);
60 /// A toast leaves over this long, in three steps of ink.
61 pub const TOAST_FADE_OUT: Duration = Duration::from_millis(300);
62
63 /// One notice: `✓ Theme set to Shoreline`.
64 #[derive(Clone, Debug, PartialEq, Eq)]
65 pub struct Toast {
66 pub state: State,
67 pub text: Cow<'static, str>,
68 /// Draws `→`: there is more to open.
69 pub opens: bool,
70 /// Optional right-aligned keyboard action hint.
71 pub action: Option<KeyHint>,
72 pub ttl: Ttl,
73 /// When the host raised it. `None` never expires by time and never fades.
74 pub born: Option<Instant>,
75 /// When the person saw it, for [`Ttl::UntilSeen`].
76 pub seen: Option<Instant>,
77 }
78
79 impl Toast {
80 #[must_use]
81 pub fn new(state: State, text: impl Into<Cow<'static, str>>) -> Self {
82 Self {
83 state,
84 text: text.into(),
85 opens: false,
86 action: None,
87 ttl: Ttl::for_state(state),
88 born: None,
89 seen: None,
90 }
91 }
92
93 /// A completed-action toast (`State::Done`, 5-second TTL).
94 #[must_use]
95 pub fn success(text: impl Into<Cow<'static, str>>) -> Self {
96 Self::new(State::Done, text)
97 }
98
99 /// An attention-needed toast (`State::NeedsYou`, [`Ttl::UntilSeen`]).
100 #[must_use]
101 pub fn attention(text: impl Into<Cow<'static, str>>) -> Self {
102 Self::new(State::NeedsYou, text)
103 }
104
105 /// A failure toast (`State::Failed`, [`Ttl::UntilSeen`]).
106 #[must_use]
107 pub fn error(text: impl Into<Cow<'static, str>>) -> Self {
108 Self::new(State::Failed, text)
109 }
110
111 /// A timed failure toast (`State::Failed`, [`TOAST_ERROR_SECONDS`] seconds).
112 #[must_use]
113 pub fn timed_error(text: impl Into<Cow<'static, str>>) -> Self {
114 Self::new(State::Failed, text).ttl(Ttl::Seconds(TOAST_ERROR_SECONDS))
115 }
116
117 /// A quiet informational toast (`State::Ready`, 5-second TTL).
118 #[must_use]
119 pub fn info(text: impl Into<Cow<'static, str>>) -> Self {
120 Self::new(State::Ready, text)
121 }
122
123 #[must_use]
124 pub fn opens(mut self) -> Self {
125 self.opens = true;
126 self
127 }
128
129 /// Attach an optional right-aligned keyboard action hint to this toast.
130 #[must_use]
131 pub fn action(mut self, action: KeyHint) -> Self {
132 self.action = Some(action);
133 self
134 }
135
136 #[must_use]
137 pub fn ttl(mut self, ttl: Ttl) -> Self {
138 self.ttl = ttl;
139 self
140 }
141
142 /// When the host raised this toast. Painting never reads a clock; the
143 /// host passes the instant it measured.
144 #[must_use]
145 pub fn born(mut self, born: Instant) -> Self {
146 self.born = Some(born);
147 self
148 }
149
150 /// When this toast goes, if it is known yet: `born` plus the seconds, or
151 /// the moment it was seen plus [`TOAST_SEEN_LINGER`]. `None` means not yet
152 /// (unborn, or not seen).
153 #[must_use]
154 pub fn expires_at(&self) -> Option<Instant> {
155 match self.ttl {
156 Ttl::Seconds(s) => self.born.map(|b| b + Duration::from_secs(u64::from(s))),
157 Ttl::UntilSeen => self.seen.map(|s| s + TOAST_SEEN_LINGER),
158 }
159 }
160
161 /// Whether the toast still shows at `now`.
162 #[must_use]
163 pub fn is_live(&self, now: Instant) -> bool {
164 self.expires_at().is_none_or(|end| now < end)
165 }
166
167 /// The ink the sentence takes at `now`: `Foreground` once settled, and
168 /// `Dim`, `Hint` or `Muted` while it arrives or leaves. `Foreground`
169 /// always unless `motion` is [`MotionMode::Full`] and the toast has a
170 /// `born`.
171 #[must_use]
172 pub fn ink(&self, now: Instant, motion: MotionMode) -> Role {
173 const STEPS: [Role; 3] = [Role::Dim, Role::Hint, Role::Muted];
174 if !motion.animates() {
175 return Role::Foreground;
176 }
177 let mut step = 3usize;
178 if let Some(born) = self.born {
179 let age = now.saturating_duration_since(born);
180 if age < TOAST_FADE_IN {
181 step = step.min((age.as_millis() / 60) as usize);
182 }
183 }
184 if let Some(end) = self.expires_at()
185 && let Some(left) = end.checked_duration_since(now)
186 && left < TOAST_FADE_OUT
187 {
188 step = step.min((left.as_millis() / 100) as usize);
189 }
190 STEPS.get(step).copied().unwrap_or(Role::Foreground)
191 }
192
193 fn line(&self, max: usize, ink: Role, theme: &Theme) -> Line<'static> {
194 let mark = StatusMark::new(self.state);
195 let glyph = mark.glyph(theme);
196 let arrow = if self.opens {
197 if theme.ascii() { " >" } else { " →" }
198 } else {
199 ""
200 };
201 let fixed = 1 + text::width(glyph) + 1 + text::width(arrow) + 1;
202 let safe_body = text::display_safe(&self.text);
203 let min_body = text::width(&safe_body).min(4);
204 let mut action_spans: Option<(Vec<Span<'static>>, usize)> = None;
205 if let Some(hint) = &self.action {
206 let keys = text::display_safe(&hint.keys).into_owned();
207 let verb = text::display_safe(&hint.verb).into_owned();
208 let keys_w = text::width(&keys);
209 let verb_w = text::width(&verb);
210 let avail_for_action = max.saturating_sub(fixed + min_body + 2);
211 if keys_w > 0 && avail_for_action >= keys_w {
212 let (key_style, verb_style) = if hint.enabled {
213 (
214 theme.fg(Role::Foreground).add_modifier(Modifier::BOLD),
215 theme.fg(Role::Muted),
216 )
217 } else {
218 (
219 theme.fg(Role::Muted),
220 theme.fg(Role::Muted).add_modifier(Modifier::DIM),
221 )
222 };
223 if verb_w > 0 && avail_for_action >= keys_w + 1 + verb_w {
224 action_spans = Some((
225 vec![
226 Span::raw(" "),
227 Span::styled(keys, key_style),
228 Span::raw(" "),
229 Span::styled(verb, verb_style),
230 ],
231 2 + keys_w + 1 + verb_w,
232 ));
233 } else if verb_w > 0 && avail_for_action >= keys_w + 2 {
234 let cut = text::truncate(&verb, avail_for_action - keys_w - 1, theme.ascii())
235 .into_owned();
236 let cut_w = text::width(&cut);
237 if cut_w > 0 {
238 action_spans = Some((
239 vec![
240 Span::raw(" "),
241 Span::styled(keys, key_style),
242 Span::raw(" "),
243 Span::styled(cut, verb_style),
244 ],
245 2 + keys_w + 1 + cut_w,
246 ));
247 } else {
248 action_spans = Some((
249 vec![Span::raw(" "), Span::styled(keys, key_style)],
250 2 + keys_w,
251 ));
252 }
253 } else {
254 action_spans = Some((
255 vec![Span::raw(" "), Span::styled(keys, key_style)],
256 2 + keys_w,
257 ));
258 }
259 }
260 }
261 let action_w = action_spans.as_ref().map_or(0, |(_, w)| *w);
262 let body = text::truncate_words(
263 &safe_body,
264 max.saturating_sub(fixed + action_w),
265 theme.ascii(),
266 )
267 .into_owned();
268 let mut spans = vec![
269 Span::raw(" "),
270 Span::styled(glyph, theme.fg(self.state.role())),
271 Span::raw(" "),
272 Span::styled(body, theme.fg(ink)),
273 ];
274 if let Some((extra, _)) = action_spans {
275 spans.extend(extra);
276 }
277 if !arrow.is_empty() {
278 spans.push(Span::styled(arrow, theme.fg(Role::Muted)));
279 }
280 spans.push(Span::raw(" "));
281 Line::from(spans)
282 }
283 }
284
285 /// Words a toast stack prints. `Default` is English.
286 #[derive(Clone, Debug, PartialEq, Eq)]
287 pub struct ToastWords {
288 /// `+2 more`.
289 pub more: Cow<'static, str>,
290 }
291
292 impl Default for ToastWords {
293 fn default() -> Self {
294 Self {
295 more: Cow::Borrowed("more"),
296 }
297 }
298 }
299
300 /// How many toasts a stack shows before it says `+n more`.
301 pub const TOAST_MAX_VISIBLE: usize = 3;
302
303 /// A stack of toasts anchored to the bottom right of an area, newest last
304 /// (nearest the horizon). At most [`Toasts::max_visible`] show, and the rows
305 /// available cap that further; older ones fold into a `+n more` line above
306 /// the stack, with n the real number hidden.
307 #[derive(Clone, Debug, PartialEq, Eq)]
308 pub struct Toasts {
309 pub items: Vec<Toast>,
310 pub max_visible: usize,
311 /// The host's clock for this frame; with [`MotionMode::Full`] it lets
312 /// toasts fade. `None` paints every toast settled.
313 pub now: Option<Instant>,
314 pub motion: MotionMode,
315 pub words: ToastWords,
316 }
317
318 impl Default for Toasts {
319 fn default() -> Self {
320 Self::new(Vec::new())
321 }
322 }
323
324 impl Toasts {
325 #[must_use]
326 pub fn new(items: Vec<Toast>) -> Self {
327 Self {
328 items,
329 max_visible: TOAST_MAX_VISIBLE,
330 now: None,
331 motion: MotionMode::Full,
332 words: ToastWords::default(),
333 }
334 }
335
336 #[must_use]
337 pub fn max_visible(mut self, max_visible: usize) -> Self {
338 self.max_visible = max_visible;
339 self
340 }
341
342 /// Paint as of `now`, the host's clock for this frame.
343 #[must_use]
344 pub fn at(mut self, now: Instant) -> Self {
345 self.now = Some(now);
346 self
347 }
348
349 #[must_use]
350 pub fn motion(mut self, motion: MotionMode) -> Self {
351 self.motion = motion;
352 self
353 }
354
355 #[must_use]
356 pub fn words(mut self, words: ToastWords) -> Self {
357 self.words = words;
358 self
359 }
360
361 /// `(shown, hidden, more_row)` for a stack `rows` tall: the newest
362 /// `shown` toasts draw, `hidden` older ones are folded, and `more_row`
363 /// says whether the `+n more` line has a row. With one row the newest
364 /// toast gets it and the count goes unspoken.
365 #[must_use]
366 pub fn window(&self, rows: u16) -> (usize, usize, bool) {
367 let rows = usize::from(rows);
368 let len = self.items.len();
369 if len == 0 || rows == 0 {
370 return (0, 0, false);
371 }
372 if len <= self.max_visible.min(rows) {
373 return (len, 0, false);
374 }
375 if rows == 1 {
376 return (1, len - 1, false);
377 }
378 let shown = self.max_visible.min(rows - 1);
379 (shown, len - shown, true)
380 }
381
382 /// Drop the toasts that have expired at `now`, and say how many went.
383 /// Failures stay until [`Toasts::mark_seen`] has run for them.
384 pub fn retain_live(&mut self, now: Instant) -> usize {
385 let before = self.items.len();
386 self.items.retain(|t| t.is_live(now));
387 before - self.items.len()
388 }
389
390 /// Record that the person saw the toasts a stack `rows` tall shows, so
391 /// their [`Ttl::UntilSeen`] clocks start. Call it when the stack was
392 /// really on screen.
393 pub fn mark_seen(&mut self, now: Instant, rows: u16) {
394 let (shown, _, _) = self.window(rows);
395 let first = self.items.len() - shown;
396 for toast in &mut self.items[first..] {
397 toast.seen.get_or_insert(now);
398 }
399 }
400
401 /// How long until anything about the stack changes (a toast expires or
402 /// moves a step of ink), or `None` when nothing will: the host schedules
403 /// its next redraw from this instead of polling.
404 #[must_use]
405 pub fn next_change_in(&self, now: Instant) -> Option<Duration> {
406 let mut soonest: Option<Duration> = None;
407 let mut consider = |at: Instant| {
408 if let Some(after) = at.checked_duration_since(now)
409 && !after.is_zero()
410 {
411 soonest = Some(soonest.map_or(after, |s| s.min(after)));
412 }
413 };
414 for toast in &self.items {
415 let end = toast.expires_at();
416 if let Some(end) = end {
417 consider(end);
418 }
419 if self.motion.animates() {
420 if let Some(born) = toast.born {
421 for ms in [60, 120, 180] {
422 consider(born + Duration::from_millis(ms));
423 }
424 }
425 if let Some(end) = end {
426 for ms in [300, 200, 100] {
427 if let Some(at) = end.checked_sub(Duration::from_millis(ms)) {
428 consider(at);
429 }
430 }
431 }
432 }
433 }
434 soonest
435 }
436 }
437
438 impl Paint for Toasts {
439 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
440 let area = area.intersection(buf.area);
441 if area.is_empty() {
442 return;
443 }
444 let max = usize::from(area.width);
445 let (shown, hidden, more_row) = self.window(area.height);
446 let first = self.items.len() - shown;
447 let top = area.bottom() - shown as u16 - u16::from(more_row);
448 if more_row {
449 let more = format!(" +{hidden} {} ", text::display_safe(&self.words.more));
450 let more = text::truncate(&more, max, theme.ascii()).into_owned();
451 let w = u16::try_from(text::width(&more))
452 .unwrap_or(u16::MAX)
453 .min(area.width);
454 let rect = Rect {
455 x: area.right() - w,
456 y: top,
457 width: w,
458 height: 1,
459 };
460 buf.set_style(rect, theme.bg(Role::Surface));
461 Line::from(Span::styled(more, theme.fg(Role::Muted))).render(rect, buf);
462 }
463 for (row, toast) in self.items[first..].iter().enumerate() {
464 let ink = match self.now {
465 Some(now) => toast.ink(now, self.motion),
466 None => Role::Foreground,
467 };
468 let line = toast.line(max, ink, theme);
469 let w = u16::try_from(line.width())
470 .unwrap_or(u16::MAX)
471 .min(area.width);
472 let rect = Rect {
473 x: area.right() - w,
474 y: top + u16::from(more_row) + row as u16,
475 width: w,
476 height: 1,
477 };
478 buf.set_style(rect, theme.bg(Role::Surface));
479 line.render(rect, buf);
480 }
481 }
482
483 fn height(&self, _width: u16, _theme: &Theme) -> u16 {
484 let len = self.items.len();
485 let rows = if len <= self.max_visible {
486 len
487 } else {
488 self.max_visible + 1
489 };
490 u16::try_from(rows).unwrap_or(u16::MAX)
491 }
492 }
493
493 lines RUST