Skip to main content

bhoo/systems/material/
snackbar.rs

1//! Caller-owned lifecycle for transient snackbar messages.
2//!
3//! Times are monotonic seconds. The host renders `current()` and calls `update`
4//! whenever input or the returned deadline changes. No timer or frame loop is
5//! allocated by the queue.
6use std::collections::{HashSet, VecDeque};
7
8/// Compose Material 3's standard durations; a caller can provide an
9/// accessibility-adjusted duration, or an indefinite notice.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub enum Duration {
12    Short,
13    Long,
14    Seconds(f64),
15    Indefinite,
16}
17
18impl Duration {
19    fn seconds(self) -> Option<f64> {
20        match self {
21            Self::Short => Some(4.0),
22            Self::Long => Some(10.0),
23            Self::Seconds(s) if s.is_finite() && s > 0.0 => Some(s),
24            Self::Seconds(_) | Self::Indefinite => None,
25        }
26    }
27}
28
29#[derive(Clone, Debug, PartialEq)]
30pub struct Notice {
31    /// Unique among current and queued notices. Returned with the result.
32    pub id: u64,
33    pub message: String,
34    pub action: Option<String>,
35    /// Optional localized accessible label for a separate close control.
36    pub dismiss_label: Option<String>,
37    pub duration: Duration,
38}
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Outcome {
42    Action,
43    Dismissed,
44    TimedOut,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct Result {
49    pub id: u64,
50    pub outcome: Outcome,
51}
52
53struct Active {
54    notice: Notice,
55    remaining: Option<f64>,
56    since: f64,
57    paused: bool,
58}
59
60/// FIFO host. Duplicate IDs are rejected to prevent stale action results from
61/// being attributed to a newer notice. `update` returns the next wake deadline.
62#[derive(Default)]
63pub struct Host {
64    current: Option<Active>,
65    pending: VecDeque<Notice>,
66    ids: HashSet<u64>,
67    results: VecDeque<Result>,
68}
69
70impl Host {
71    pub fn enqueue(&mut self, notice: Notice, now: f64) -> bool {
72        if !self.ids.insert(notice.id) {
73            return false;
74        }
75        self.pending.push_back(notice);
76        self.start_next(now);
77        true
78    }
79
80    pub fn current(&self) -> Option<&Notice> {
81        self.current.as_ref().map(|active| &active.notice)
82    }
83
84    fn start_next(&mut self, now: f64) {
85        if self.current.is_none()
86            && let Some(notice) = self.pending.pop_front()
87        {
88            self.current = Some(Active {
89                remaining: notice.duration.seconds(),
90                notice,
91                since: now,
92                paused: false,
93            });
94        }
95    }
96
97    fn finish(&mut self, outcome: Outcome, now: f64) {
98        if let Some(active) = self.current.take() {
99            self.ids.remove(&active.notice.id);
100            self.results.push_back(Result {
101                id: active.notice.id,
102                outcome,
103            });
104            self.start_next(now);
105        }
106    }
107
108    /// Pause while an actionable notice is hovered or focused. Call on every
109    /// input change and at the returned deadline, before accepting an action.
110    pub fn update(&mut self, now: f64, interacting: bool) -> Option<f64> {
111        let active = self.current.as_mut()?;
112        let elapsed = (now - active.since).max(0.0);
113        if !active.paused
114            && let Some(remaining) = &mut active.remaining
115        {
116            *remaining = (*remaining - elapsed).max(0.0);
117        }
118        active.since = now;
119        if active.remaining == Some(0.0) {
120            self.finish(Outcome::TimedOut, now);
121            return self.update(now, interacting);
122        }
123        active.paused = interacting;
124        if interacting {
125            None
126        } else {
127            active.remaining.map(|remaining| now + remaining)
128        }
129    }
130
131    /// Only the visible notice can receive an action; an absent action cannot fire.
132    pub fn action(&mut self, id: u64, now: f64) -> bool {
133        if !self
134            .current
135            .as_ref()
136            .is_some_and(|a| a.notice.id == id && a.notice.action.is_some())
137        {
138            return false;
139        }
140        self.finish(Outcome::Action, now);
141        true
142    }
143
144    /// Dismiss the current notice or remove a queued notice.
145    pub fn dismiss(&mut self, id: u64, now: f64) -> bool {
146        if self.current.as_ref().is_some_and(|a| a.notice.id == id) {
147            self.finish(Outcome::Dismissed, now);
148            return true;
149        }
150        if let Some(index) = self.pending.iter().position(|notice| notice.id == id) {
151            self.pending.remove(index);
152            self.ids.remove(&id);
153            self.results.push_back(Result {
154                id,
155                outcome: Outcome::Dismissed,
156            });
157            return true;
158        }
159        false
160    }
161
162    pub fn take_result(&mut self) -> Option<Result> {
163        self.results.pop_front()
164    }
165}
166
167/// Presentation state for a snackbar host. Keep it alongside the queue.
168#[derive(Default)]
169pub struct Presentation {
170    /// Place the action below the message, even when there is room beside it.
171    pub action_on_new_line: bool,
172    /// Mirror leading/trailing placement for right-to-left interfaces.
173    pub right_to_left: bool,
174    visible: Option<Notice>,
175    entered: f64,
176    exiting: Option<(Notice, f64)>,
177}
178
179fn action_id(host_id: u64, notice_id: u64) -> u64 {
180    (host_id ^ notice_id.wrapping_mul(0x9e3779b97f4a7c15)) & ((1_u64 << 52) - 1)
181}
182fn dismiss_id(host_id: u64, notice_id: u64) -> u64 {
183    action_id(host_id, notice_id) ^ (1_u64 << 50)
184}
185
186impl crate::Frame<'_> {
187    /// Render a queued snackbar at the bottom of `viewport`. Returns outcomes
188    /// through `Host::take_result`; `host_id` must be stable and unique.
189    /// A non-focusable status semantic exposes the message to host adapters.
190    pub fn snackbar_host(
191        &mut self,
192        host_id: u64,
193        viewport: crate::Rect,
194        host: &mut Host,
195        presentation: &mut Presentation,
196    ) {
197        let now = self.time();
198        let bounds = host
199            .current()
200            .map(|notice| notice_layout(self, viewport, notice, presentation.action_on_new_line).0)
201            .unwrap_or_default();
202        let interacting = host.current().is_some_and(|notice| {
203            self.pointer_in(bounds)
204                || (notice.action.is_some()
205                    && self.focused_id() == Some(action_id(host_id, notice.id)))
206                || (notice.dismiss_label.is_some()
207                    && self.focused_id() == Some(dismiss_id(host_id, notice.id)))
208        });
209        if let Some(deadline) = host.update(now, interacting) {
210            self.wake_at(deadline);
211        }
212        let next = host.current().cloned();
213        if presentation.visible != next {
214            if let Some(previous) = presentation.visible.take() {
215                presentation.exiting = Some((previous, now));
216            }
217            presentation.visible = next;
218            presentation.entered = now;
219        }
220        let reduced = self.reduced_motion();
221        if let Some((notice, started)) = presentation.exiting.as_ref() {
222            let bounds = notice_layout(self, viewport, notice, presentation.action_on_new_line).0;
223            let progress = if reduced {
224                1.0
225            } else {
226                ((now - started).max(0.0) / 0.075).min(1.0) as f32
227            };
228            if progress < 1.0 {
229                let alpha =
230                    1.0 - crate::timing::Easing::Cubic([0.4, 0.0, 1.0, 1.0]).sample(progress);
231                paint_notice(
232                    self,
233                    bounds,
234                    notice,
235                    host_id,
236                    (alpha, 1.0),
237                    false,
238                    (presentation.action_on_new_line, presentation.right_to_left),
239                );
240                self.continuous(bounds);
241            } else {
242                presentation.exiting = None;
243            }
244        }
245        if let Some(notice) = presentation.visible.as_ref() {
246            let bounds = notice_layout(self, viewport, notice, presentation.action_on_new_line).0;
247            let progress = if reduced {
248                1.0
249            } else {
250                ((now - presentation.entered).max(0.0) / 0.150).min(1.0) as f32
251            };
252            let alpha = crate::timing::Easing::StandardDecelerate.sample(progress);
253            let clicked = paint_notice(
254                self,
255                bounds,
256                notice,
257                host_id,
258                (alpha, 0.8 + 0.2 * alpha),
259                true,
260                (presentation.action_on_new_line, presentation.right_to_left),
261            );
262            if progress < 1.0 {
263                self.continuous(bounds);
264            }
265            let finished = match clicked {
266                Some(Outcome::Action) => host.action(notice.id, now),
267                Some(Outcome::Dismissed) => host.dismiss(notice.id, now),
268                _ => false,
269            };
270            if finished {
271                self.wake_at(now + 0.001);
272            } else {
273                self.semantic(
274                    crate::Response {
275                        id: action_id(host_id, notice.id) ^ (1_u64 << 51),
276                        bounds,
277                        enabled: true,
278                        ..crate::Response::default()
279                    },
280                    crate::Role::Status,
281                    &notice.message,
282                    false,
283                    None,
284                    None,
285                    None,
286                );
287            }
288        }
289    }
290}
291
292fn message_lines(frame: &crate::Frame<'_>, text: &str, width: f32) -> Vec<String> {
293    let style = crate::TextStyle {
294        size: 14.0,
295        ..crate::TextStyle::default()
296    };
297    let mut lines = Vec::new();
298    let space_width = frame.text_width(" ", style);
299    for paragraph in text.split('\n') {
300        let mut line = String::new();
301        let mut line_width = 0.0;
302        for word in paragraph.split_whitespace() {
303            let word_width = frame.text_width(word, style);
304            if !line.is_empty() && line_width + space_width + word_width > width {
305                lines.push(std::mem::take(&mut line));
306                line_width = 0.0;
307            }
308            if !line.is_empty() {
309                line.push(' ');
310                line_width += space_width;
311            }
312            for ch in word.chars() {
313                let mut buffer = [0; 4];
314                let char_width = frame.text_width(ch.encode_utf8(&mut buffer), style);
315                if !line.is_empty() && line_width + char_width > width {
316                    lines.push(std::mem::take(&mut line));
317                    line_width = 0.0;
318                }
319                line.push(ch);
320                line_width += char_width;
321            }
322        }
323        lines.push(line);
324    }
325    lines
326}
327
328fn action_width(frame: &crate::Frame<'_>, notice: &Notice, width: f32) -> f32 {
329    notice.action.as_ref().map_or(0.0, |label| {
330        let style = crate::TextStyle {
331            size: 14.0,
332            weight: 500,
333            letter_spacing: 0.096,
334            ..crate::TextStyle::default()
335        };
336        (frame.text_width(label, style) + 32.0).max(72.0).min(width)
337    })
338}
339
340fn notice_layout(
341    frame: &crate::Frame<'_>,
342    viewport: crate::Rect,
343    notice: &Notice,
344    force_stacked: bool,
345) -> (crate::Rect, f32, Vec<String>, bool) {
346    let width = (viewport.width - 16.0).clamp(0.0, 672.0);
347    let dismiss_width = if notice.dismiss_label.is_some() {
348        48.0_f32.min(width)
349    } else {
350        0.0
351    };
352    let action_width = action_width(frame, notice, (width - dismiss_width).max(0.0));
353    let control_width = action_width + dismiss_width;
354    let stacked = control_width > 0.0 && (force_stacked || width - control_width - 32.0 < 96.0);
355    let lines = message_lines(
356        frame,
357        &notice.message,
358        (width - if stacked { 0.0 } else { control_width } - 32.0).max(0.0),
359    );
360    let height = (28.0 + 20.0 * lines.len() as f32 + if stacked { 40.0 } else { 0.0 })
361        .min(viewport.height.max(0.0));
362    let bounds = crate::Rect {
363        x: viewport.x + (viewport.width - width) * 0.5,
364        y: viewport.y + (viewport.height - height - 8.0).max(0.0),
365        width,
366        height,
367    };
368    (bounds, action_width, lines, stacked)
369}
370
371fn paint_notice(
372    frame: &mut crate::Frame<'_>,
373    bounds: crate::Rect,
374    notice: &Notice,
375    host_id: u64,
376    motion: (f32, f32),
377    interactive: bool,
378    options: (bool, bool),
379) -> Option<Outcome> {
380    let (alpha, scale) = motion;
381    let (force_stacked, right_to_left) = options;
382    let theme = frame.theme();
383    let dismiss_width = if notice.dismiss_label.is_some() {
384        48.0_f32.min(bounds.width)
385    } else {
386        0.0
387    };
388    let action_width = action_width(frame, notice, (bounds.width - dismiss_width).max(0.0));
389    let control_width = action_width + dismiss_width;
390    let stacked =
391        control_width > 0.0 && (force_stacked || bounds.width - control_width - 32.0 < 96.0);
392    let lines = message_lines(
393        frame,
394        &notice.message,
395        (bounds.width - if stacked { 0.0 } else { control_width } - 32.0).max(0.0),
396    );
397    let action_bounds = crate::Rect {
398        x: if right_to_left {
399            bounds.x + dismiss_width + (8.0_f32.min(action_width))
400        } else {
401            bounds.x + bounds.width - control_width
402        },
403        y: bounds.y
404            + if stacked {
405                (bounds.height - 44.0).max(0.0)
406            } else {
407                (bounds.height - 40.0).max(0.0) * 0.5
408            },
409        width: (action_width - 8.0).max(0.0),
410        height: 40.0_f32.min(bounds.height),
411    };
412    let dismiss_bounds = crate::Rect {
413        x: if right_to_left {
414            bounds.x
415        } else {
416            bounds.x + bounds.width - dismiss_width
417        },
418        width: dismiss_width,
419        ..action_bounds
420    };
421    let mut clicked = None;
422    frame.with_opacity(alpha, |frame| {
423        frame.with_scale(
424            [
425                bounds.x + bounds.width * 0.5,
426                bounds.y + bounds.height * 0.5,
427            ],
428            scale,
429            |frame| {
430                frame.elevation(bounds, 4.0, 6);
431                frame.paint_rect(bounds, 4.0, theme.inverse_surface);
432                let message_bounds = crate::Rect {
433                    x: bounds.x
434                        + if right_to_left && !stacked {
435                            control_width
436                        } else {
437                            0.0
438                        },
439                    width: (bounds.width - if stacked { 0.0 } else { control_width }).max(0.0),
440                    height: (bounds.height - if stacked { 44.0 } else { 0.0 }).max(0.0),
441                    ..bounds
442                };
443                let style = crate::TextStyle {
444                    size: 14.0,
445                    padding: 16.0,
446                    align: if right_to_left { 2 } else { 0 },
447                    ..crate::TextStyle::default()
448                };
449                if lines.len() == 1 {
450                    frame.styled_text(
451                        message_bounds,
452                        &notice.message,
453                        theme.inverse_on_surface,
454                        style,
455                    );
456                } else {
457                    let count = lines.len();
458                    frame.within(message_bounds, |frame| {
459                        for (i, line) in lines.iter().enumerate() {
460                            frame.styled_text(
461                                crate::Rect {
462                                    y: bounds.y
463                                        + (message_bounds.height - count as f32 * 20.0).max(0.0)
464                                            * 0.5
465                                        + i as f32 * 20.0,
466                                    height: 20.0,
467                                    ..message_bounds
468                                },
469                                line,
470                                theme.inverse_on_surface,
471                                style,
472                            );
473                        }
474                    });
475                }
476                if let Some(label) = &notice.action {
477                    if interactive {
478                        let response = frame.target(
479                            action_id(host_id, notice.id),
480                            action_bounds,
481                            label,
482                            true,
483                            crate::Role::Button,
484                        );
485                        frame.state_layer(response, 20.0, theme.inverse_primary);
486                        frame.focus_ring(response);
487                        if response.clicked {
488                            clicked = Some(Outcome::Action);
489                        }
490                    }
491                    let style = crate::TextStyle {
492                        size: 14.0,
493                        weight: 500,
494                        letter_spacing: 0.096,
495                        align: 1,
496                        ..crate::TextStyle::default()
497                    };
498                    if frame.text_width(label, style) > action_bounds.width {
499                        frame.within(action_bounds, |frame| {
500                            frame.styled_text(action_bounds, label, theme.inverse_primary, style)
501                        });
502                    } else {
503                        frame.styled_text(action_bounds, label, theme.inverse_primary, style);
504                    }
505                }
506                if let Some(label) = &notice.dismiss_label {
507                    if interactive {
508                        let response = frame.target(
509                            dismiss_id(host_id, notice.id),
510                            dismiss_bounds,
511                            label,
512                            true,
513                            crate::Role::Button,
514                        );
515                        frame.state_layer(response, 24.0, theme.inverse_on_surface);
516                        frame.focus_ring(response);
517                        if response.clicked {
518                            clicked = Some(Outcome::Dismissed);
519                        }
520                    }
521                    let size = 24.0_f32
522                        .min(dismiss_bounds.width)
523                        .min(dismiss_bounds.height);
524                    frame.paint_material_icon(
525                        crate::Rect {
526                            x: dismiss_bounds.x + (dismiss_bounds.width - size) * 0.5,
527                            y: dismiss_bounds.y + (dismiss_bounds.height - size) * 0.5,
528                            width: size,
529                            height: size,
530                        },
531                        crate::MaterialIcon::Close,
532                        theme.inverse_on_surface,
533                    );
534                }
535            },
536        )
537    });
538    clicked
539}
540
541#[cfg(test)]
542#[path = "snackbar.spec.rs"]
543mod tests;