Skip to main content

repose_ui/
overlay.rs

1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::collections::VecDeque;
4use std::rc::{Rc, Weak};
5
6use repose_core::{Modifier, View, ViewKind, request_frame};
7use web_time::{Duration, Instant};
8
9// Registry of live snackbar controllers, held weakly so a dropped
10// controller stops ticking without explicit teardown. Dead entries are
11// pruned on every read (`tick_all` / `next_deadline`).
12thread_local! {
13    static SNACKBAR_REGISTRY: RefCell<Vec<Weak<SnackbarControllerInner>>> =
14        const { RefCell::new(Vec::new()) };
15    static AMBIENT_OVERLAY: RefCell<Option<OverlayHandle>> = const { RefCell::new(None) };
16}
17
18/// Run `f` with `handle` installed as the ambient overlay for this frame.
19///
20/// The platform runtime wraps composition in this, so floating surfaces
21/// (dropdowns, tooltips, dialogs, snackbars) resolve their layer without
22/// the caller threading an `OverlayHandle` through every view. An
23/// explicitly passed handle still works as an escape hatch.
24pub fn with_ambient_overlay<R>(handle: OverlayHandle, f: impl FnOnce() -> R) -> R {
25    struct Guard;
26    impl Drop for Guard {
27        fn drop(&mut self) {
28            AMBIENT_OVERLAY.with(|slot| *slot.borrow_mut() = None);
29        }
30    }
31    AMBIENT_OVERLAY.with(|slot| *slot.borrow_mut() = Some(handle));
32    let _guard = Guard;
33    f()
34}
35
36/// The ambient [`OverlayHandle`] installed by the runtime, if any.
37pub fn ambient_overlay() -> Option<OverlayHandle> {
38    AMBIENT_OVERLAY.with(|slot| slot.borrow().clone())
39}
40
41/// Duration of the snackbar exit animation before the overlay entry is removed.
42const SNACKBAR_EXIT_ANIM_MS: u64 = 200;
43
44#[derive(Clone)]
45pub struct OverlayHandle {
46    inner: Rc<RefCell<OverlayState>>,
47}
48
49pub type BackHandler = Rc<dyn Fn() -> bool>;
50
51struct OverlayState {
52    next_id: u64,
53    entries: Vec<OverlayEntry>,
54    back_handlers: HashMap<u64, BackHandler>,
55}
56
57#[derive(Clone)]
58pub struct OverlayEntry {
59    pub id: u64,
60    pub builder: Rc<dyn Fn() -> View>,
61    pub z_index: f32,
62    pub pass_through: bool,
63}
64
65impl Default for OverlayHandle {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl OverlayHandle {
72    pub fn new() -> Self {
73        Self {
74            inner: Rc::new(RefCell::new(OverlayState {
75                next_id: 1,
76                entries: Vec::new(),
77                back_handlers: HashMap::new(),
78            })),
79        }
80    }
81
82    pub fn show(&self, view: View) -> u64 {
83        self.show_with(view, 0.0, false)
84    }
85
86    pub fn show_with(&self, view: View, z_index: f32, pass_through: bool) -> u64 {
87        let builder = Rc::new(move || view.clone());
88        self.show_entry(builder, z_index, pass_through)
89    }
90
91    pub fn show_with_back(
92        &self,
93        view: View,
94        z_index: f32,
95        pass_through: bool,
96        back_handler: BackHandler,
97    ) -> u64 {
98        let builder = Rc::new(move || view.clone());
99        self.show_entry_with_back(builder, z_index, pass_through, Some(back_handler))
100    }
101
102    pub fn show_entry(
103        &self,
104        builder: Rc<dyn Fn() -> View>,
105        z_index: f32,
106        pass_through: bool,
107    ) -> u64 {
108        self.show_entry_with_back(builder, z_index, pass_through, None)
109    }
110
111    pub fn show_entry_with_back(
112        &self,
113        builder: Rc<dyn Fn() -> View>,
114        z_index: f32,
115        pass_through: bool,
116        back_handler: Option<BackHandler>,
117    ) -> u64 {
118        let mut inner = self.inner.borrow_mut();
119        let id = inner.next_id;
120        inner.next_id += 1;
121        inner.entries.push(OverlayEntry {
122            id,
123            builder,
124            z_index,
125            pass_through,
126        });
127        if let Some(back_handler) = back_handler {
128            inner.back_handlers.insert(id, back_handler);
129        }
130        request_frame();
131        id
132    }
133
134    /// Show `builder` and return a guard owning the entry. Dropping the
135    /// guard dismisses the entry; see [`OverlayGuard`].
136    pub fn show_guard(
137        &self,
138        builder: Rc<dyn Fn() -> View>,
139        z_index: f32,
140        pass_through: bool,
141    ) -> OverlayGuard {
142        OverlayGuard::show(self, builder, z_index, pass_through)
143    }
144
145    pub fn show_guard_with_back(
146        &self,
147        builder: Rc<dyn Fn() -> View>,
148        z_index: f32,
149        pass_through: bool,
150        back_handler: BackHandler,
151    ) -> OverlayGuard {
152        OverlayGuard::show_with_back(self, builder, z_index, pass_through, back_handler)
153    }
154
155    pub fn handle_back(&self) -> bool {
156        let handlers = {
157            let inner = self.inner.borrow();
158            let mut handlers = inner
159                .entries
160                .iter()
161                .enumerate()
162                .filter_map(|(order, entry)| {
163                    inner
164                        .back_handlers
165                        .get(&entry.id)
166                        .map(|handler| (order, entry.z_index, (*handler).clone()))
167                })
168                .collect::<Vec<_>>();
169            handlers.sort_by(|left, right| {
170                right
171                    .1
172                    .partial_cmp(&left.1)
173                    .unwrap_or(std::cmp::Ordering::Equal)
174                    .then_with(|| right.0.cmp(&left.0))
175            });
176            handlers
177                .into_iter()
178                .map(|(_, _, handler)| handler)
179                .collect::<Vec<_>>()
180        };
181        handlers.into_iter().any(|handler| handler())
182    }
183
184    /// Whether any overlay registered a back handler.
185    ///
186    /// Used by platform runners to decide whether back should reach the system
187    /// at all; the handler itself is only run on an actual press.
188    pub fn has_back_handler(&self) -> bool {
189        !self.inner.borrow().back_handlers.is_empty()
190    }
191
192    /// Number of live entries. Reads state directly rather than going through
193    /// [`Self::host`], which rebuilds every entry and so cannot be used to
194    /// observe what is registered.
195    pub fn entry_count(&self) -> usize {
196        self.inner.borrow().entries.len()
197    }
198
199    pub fn dismiss(&self, id: u64) -> bool {
200        let mut inner = self.inner.borrow_mut();
201        let before = inner.entries.len();
202        inner.entries.retain(|entry| entry.id != id);
203        let removed = inner.entries.len() != before;
204        inner.back_handlers.remove(&id);
205        if removed {
206            request_frame();
207        }
208        removed
209    }
210
211    pub fn clear(&self) {
212        let mut inner = self.inner.borrow_mut();
213        let had_entries = !inner.entries.is_empty();
214        inner.entries.clear();
215        inner.back_handlers.clear();
216        if had_entries {
217            request_frame();
218        }
219    }
220
221    /// Hoist `content` plus this handle's entries under one root.
222    ///
223    /// The runtime calls this implicitly around the app root each frame
224    /// (see [`with_ambient_overlay`]); explicit `host()` calls remain for
225    /// tests and advanced layering.
226    pub fn host(&self, modifier: Modifier, content: View) -> View {
227        let mut root = View::new(0, ViewKind::OverlayHost).modifier(modifier);
228        root.children.push(content);
229        let mut overlays = self.inner.borrow().entries.clone();
230        // Sort ascending by z_index so higher z_index overlays are painted last (on top)
231        overlays.sort_by(|a, b| {
232            a.z_index
233                .partial_cmp(&b.z_index)
234                .unwrap_or(std::cmp::Ordering::Equal)
235        });
236
237        for entry in overlays {
238            let view = (entry.builder)();
239            let mut modifier = view
240                .modifier
241                .clone()
242                .z_index(entry.z_index)
243                .render_z_index(entry.z_index + 1000.0);
244            if entry.pass_through {
245                modifier = modifier.hit_passthrough();
246            }
247            root.children.push(view.modifier(modifier));
248        }
249        root
250    }
251}
252
253/// RAII owner of a shown overlay entry.
254///
255/// Dropping the guard dismisses the entry, so callers can't leak entries by
256/// forgetting `dismiss` or mismatching a `0`-sentinel id. The typical shape
257/// is a `remember`-ed `RefCell<Option<OverlayGuard>>`: set it to `Some` when
258/// the overlay should show, back to `None` to hide.
259///
260/// The guard holds only the handle + id (no entry content), so it never
261/// participates in reference cycles with the overlay state.
262#[must_use = "dropping the guard dismisses the overlay entry"]
263pub struct OverlayGuard {
264    handle: OverlayHandle,
265    id: Option<u64>,
266}
267
268impl OverlayGuard {
269    /// Show `builder` on `handle` and own the resulting entry.
270    pub fn show(
271        handle: &OverlayHandle,
272        builder: Rc<dyn Fn() -> View>,
273        z_index: f32,
274        pass_through: bool,
275    ) -> Self {
276        let id = handle.show_entry(builder, z_index, pass_through);
277        Self {
278            handle: handle.clone(),
279            id: Some(id),
280        }
281    }
282
283    pub fn show_with_back(
284        handle: &OverlayHandle,
285        builder: Rc<dyn Fn() -> View>,
286        z_index: f32,
287        pass_through: bool,
288        back_handler: BackHandler,
289    ) -> Self {
290        let id = handle.show_entry_with_back(builder, z_index, pass_through, Some(back_handler));
291        Self {
292            handle: handle.clone(),
293            id: Some(id),
294        }
295    }
296
297    /// Entry id, or `None` after [`dismiss`](Self::dismiss).
298    pub fn id(&self) -> Option<u64> {
299        self.id
300    }
301
302    /// Dismiss now instead of at drop. Consuming the guard makes a
303    /// double-dismiss impossible.
304    pub fn dismiss(mut self) {
305        self.dismiss_now();
306    }
307
308    fn dismiss_now(&mut self) {
309        if let Some(id) = self.id.take() {
310            self.handle.dismiss(id);
311        }
312    }
313}
314
315impl Drop for OverlayGuard {
316    fn drop(&mut self) {
317        self.dismiss_now();
318    }
319}
320
321#[derive(Clone)]
322pub struct SnackbarController {
323    inner: Rc<SnackbarControllerInner>,
324}
325
326struct SnackbarControllerInner {
327    state: RefCell<SnackbarState>,
328    overlay: OverlayHandle,
329}
330
331#[derive(Clone)]
332pub struct SnackbarAction {
333    pub label: String,
334    pub on_click: Rc<dyn Fn()>,
335}
336
337#[derive(Clone)]
338pub struct SnackbarRequest {
339    pub message: String,
340    pub action: Option<SnackbarAction>,
341    pub duration_ms: u32,
342    pub on_finished: Option<Rc<dyn Fn()>>,
343    /// Called on every frame with whether the snackbar is in its
344    /// exit-animation phase, so the view can animate out.
345    pub builder: Rc<dyn Fn(bool) -> View>,
346}
347
348struct SnackbarState {
349    queue: VecDeque<SnackbarRequest>,
350    active: Option<ActiveSnackbar>,
351}
352
353/// Lifecycle phase of the visible snackbar. Both phases carry the `Instant`
354/// at which the snackbar leaves the phase (dismiss start, then removal).
355enum SnackbarPhase {
356    Showing { deadline: Instant },
357    Dismissing { deadline: Instant },
358}
359
360struct ActiveSnackbar {
361    /// Owns the overlay entry; clearing `active` dismisses the entry via drop.
362    /// Never read by name: its `Drop` impl is the whole point.
363    #[allow(dead_code)]
364    guard: OverlayGuard,
365    message: String,
366    action: Option<SnackbarAction>,
367    phase: SnackbarPhase,
368    on_finished: Option<Rc<dyn Fn()>>,
369}
370
371impl ActiveSnackbar {
372    fn deadline(&self) -> Instant {
373        match self.phase {
374            SnackbarPhase::Showing { deadline } | SnackbarPhase::Dismissing { deadline } => {
375                deadline
376            }
377        }
378    }
379
380    fn is_dismissing(&self) -> bool {
381        matches!(self.phase, SnackbarPhase::Dismissing { .. })
382    }
383
384    /// Idempotent transition into the exit animation.
385    fn start_dismiss(&mut self, now: Instant) {
386        if !self.is_dismissing() {
387            self.phase = SnackbarPhase::Dismissing {
388                deadline: now + Duration::from_millis(SNACKBAR_EXIT_ANIM_MS),
389            };
390            request_frame();
391        }
392    }
393}
394
395impl SnackbarController {
396    pub fn new(overlay: OverlayHandle) -> Self {
397        Self::with_handle(overlay)
398    }
399
400    /// Resolve the ambient handle installed by the runtime
401    /// ([`with_ambient_overlay`]), falling back to a fresh handle when
402    /// composition runs outside a runtime frame (tests, previews).
403    pub fn ambient() -> Self {
404        let overlay = ambient_overlay().unwrap_or_default();
405        Self::with_handle(overlay)
406    }
407
408    fn with_handle(overlay: OverlayHandle) -> Self {
409        let controller = Self {
410            inner: Rc::new(SnackbarControllerInner {
411                state: RefCell::new(SnackbarState {
412                    queue: VecDeque::new(),
413                    active: None,
414                }),
415                overlay,
416            }),
417        };
418
419        SNACKBAR_REGISTRY.with(|reg| reg.borrow_mut().push(Rc::downgrade(&controller.inner)));
420        controller
421    }
422
423    /// The handle this controller posts entries to.
424    pub fn handle(&self) -> OverlayHandle {
425        self.inner.overlay.clone()
426    }
427
428    fn live_controllers() -> Vec<Rc<SnackbarControllerInner>> {
429        SNACKBAR_REGISTRY.with(|reg| {
430            let mut reg = reg.borrow_mut();
431            reg.retain(|w| w.upgrade().is_some());
432            reg.iter().filter_map(Weak::upgrade).collect()
433        })
434    }
435
436    /// Tick all live controllers once. Call once per redraw.
437    pub fn tick_all() {
438        for inner in Self::live_controllers() {
439            Self { inner }.tick();
440        }
441    }
442
443    /// Earliest `Instant` when any snackbar needs to wake (dismiss start or
444    /// finish). `None` if no snackbar is active.
445    pub fn next_deadline() -> Option<Instant> {
446        Self::live_controllers()
447            .iter()
448            .filter_map(|inner| {
449                inner
450                    .state
451                    .borrow()
452                    .active
453                    .as_ref()
454                    .map(ActiveSnackbar::deadline)
455            })
456            .min()
457    }
458
459    pub fn show(&self, request: SnackbarRequest) {
460        if self.inner.state.borrow().active.is_some() {
461            self.inner.state.borrow_mut().queue.push_back(request);
462        } else {
463            self.activate_next(request);
464        }
465    }
466
467    pub fn tick(&self) {
468        let now = Instant::now();
469        let mut finished: Option<ActiveSnackbar> = None;
470        {
471            let mut state = self.inner.state.borrow_mut();
472            if let Some(active) = state.active.as_mut() {
473                match active.phase {
474                    SnackbarPhase::Showing { deadline } if now >= deadline => {
475                        active.start_dismiss(now);
476                    }
477                    SnackbarPhase::Dismissing { deadline } if now >= deadline => {
478                        finished = state.active.take();
479                    }
480                    _ => {}
481                }
482            }
483        }
484        if let Some(done) = finished
485            && let Some(cb) = done.on_finished
486        {
487            cb();
488        }
489        self.activate_next_if_needed();
490    }
491
492    pub fn dismiss(&self) {
493        let now = Instant::now();
494        if let Some(active) = self.inner.state.borrow_mut().active.as_mut() {
495            active.start_dismiss(now);
496        }
497    }
498
499    pub fn current(&self) -> Option<(String, Option<SnackbarAction>)> {
500        let inner = self.inner.state.borrow();
501        inner
502            .active
503            .as_ref()
504            .map(|active| (active.message.clone(), active.action.clone()))
505    }
506
507    fn activate_next_if_needed(&self) {
508        if self.inner.state.borrow().active.is_some() {
509            return;
510        }
511        let req = self.inner.state.borrow_mut().queue.pop_front();
512        if let Some(req) = req {
513            self.activate_next(req);
514        }
515    }
516
517    fn activate_next(&self, req: SnackbarRequest) {
518        if self.inner.state.borrow().active.is_some() {
519            return;
520        }
521        let weak = Rc::downgrade(&self.inner);
522        let original_builder = req.builder.clone();
523        let wrapped_builder: Rc<dyn Fn() -> View> = Rc::new(move || {
524            let dismissing = weak
525                .upgrade()
526                .and_then(|inner| {
527                    inner
528                        .state
529                        .borrow()
530                        .active
531                        .as_ref()
532                        .map(ActiveSnackbar::is_dismissing)
533                })
534                .unwrap_or(false);
535            (original_builder)(dismissing)
536        });
537        let action = req.action.map(|a| SnackbarAction {
538            on_click: {
539                let original = a.on_click;
540                let controller = self.clone();
541                Rc::new(move || {
542                    (original)();
543                    controller.dismiss();
544                })
545            },
546            label: a.label,
547        });
548        let guard = OverlayGuard::show(&self.inner.overlay, wrapped_builder, 900.0, true);
549        let deadline = Instant::now() + Duration::from_millis(u64::from(req.duration_ms.max(1)));
550        let on_finished = req.on_finished.clone();
551        self.inner.state.borrow_mut().active = Some(ActiveSnackbar {
552            guard,
553            message: req.message,
554            action,
555            on_finished,
556            phase: SnackbarPhase::Showing { deadline },
557        });
558    }
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use std::cell::Cell;
565
566    fn test_request() -> SnackbarRequest {
567        SnackbarRequest {
568            message: "hi".into(),
569            action: None,
570            duration_ms: 60_000,
571            on_finished: None,
572            builder: Rc::new(|_| View::new(0, ViewKind::OverlayHost)),
573        }
574    }
575
576    #[test]
577    fn dropped_controller_is_pruned_from_registry() {
578        {
579            let overlay = OverlayHandle::new();
580            let controller = SnackbarController::new(overlay);
581            controller.show(test_request());
582            SnackbarController::tick_all();
583            assert!(SnackbarController::next_deadline().is_some());
584        }
585        SnackbarController::tick_all();
586        assert!(SnackbarController::next_deadline().is_none());
587    }
588
589    #[test]
590    fn dismiss_schedules_exit_deadline() {
591        let overlay = OverlayHandle::new();
592        let controller = SnackbarController::new(overlay);
593        controller.show(test_request());
594        let before = Instant::now();
595        controller.dismiss();
596        let deadline = SnackbarController::next_deadline().expect("deadline while dismissing");
597        assert!(deadline >= before);
598        assert!(deadline.saturating_duration_since(before) <= Duration::from_millis(500));
599        controller.dismiss();
600        let again = SnackbarController::next_deadline().expect("deadline while dismissing");
601        assert_eq!(deadline, again);
602        drop(controller);
603        SnackbarController::tick_all();
604    }
605
606    #[test]
607    fn back_uses_topmost_handler_and_falls_back_after_dismiss() {
608        let overlay = OverlayHandle::new();
609        let lower = Rc::new(Cell::new(0u32));
610        let upper = Rc::new(Cell::new(0u32));
611        let lower_handler = lower.clone();
612        let upper_handler = upper.clone();
613        let builder: Rc<dyn Fn() -> View> = Rc::new(|| View::new(0, ViewKind::OverlayHost));
614        let lower_id = overlay.show_entry_with_back(
615            builder.clone(),
616            1.0,
617            false,
618            Some(Rc::new(move || {
619                lower_handler.set(lower_handler.get() + 1);
620                true
621            })),
622        );
623        overlay.show_entry_with_back(
624            builder,
625            2.0,
626            false,
627            Some(Rc::new(move || {
628                upper_handler.set(upper_handler.get() + 1);
629                true
630            })),
631        );
632        assert!(overlay.handle_back());
633        assert_eq!(upper.get(), 1);
634        assert_eq!(lower.get(), 0);
635        overlay.dismiss(lower_id);
636        assert!(overlay.handle_back());
637        assert_eq!(upper.get(), 2);
638    }
639
640    #[test]
641    fn guard_drop_dismisses_entry() {
642        let overlay = OverlayHandle::new();
643        let builder: Rc<dyn Fn() -> View> = Rc::new(|| View::new(0, ViewKind::OverlayHost));
644        {
645            let guard = overlay.show_guard(builder.clone(), 5.0, false);
646            assert!(guard.id().is_some());
647            assert_eq!(overlay.inner.borrow().entries.len(), 1);
648            guard.dismiss();
649            assert!(overlay.inner.borrow().entries.is_empty());
650        }
651        let guard = overlay.show_guard(builder, 5.0, false);
652        assert_eq!(overlay.inner.borrow().entries.len(), 1);
653        drop(guard);
654        assert!(overlay.inner.borrow().entries.is_empty());
655    }
656}