teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Snackbar — a transient, button-triggered floating notification surface.
//!
//! A `Snackbar` pairs a trigger (a `Button` by default, or any custom
//! widget via `.trigger(...)`) with a dormant content surface. Activating
//! the trigger presents the surface as an `OverlayPlacement::BottomCenter`
//! overlay and dismisses it automatically after a configurable timeout
//! (default: 4 s). The surface stays until dismissed when `.persistent()`
//! is set. Only one snackbar can be shown at a time — presenting a second
//! one dismisses the first.
//!
//! For richer, stackable, severity-aware notifications see the
//! [`Toast`](crate::toast::Toast) system, which also maintains a
//! persistent `NotificationArchiveModel`.
//!
//! ## Accessibility
//!
//! The content surface exposes `Role::Alert` with `Live::Polite` so
//! screen readers announce the notification without interrupting the user.
//! Supply `.announcement(...)` to give the alert a descriptive name
//! instead of the generic "notification" fallback.
//!
//! ```ignore
//! use teksilo_widgets::{Snackbar};
//! use teksilo_i18n::lit;
//! use teksilo_widgets::primitives::TextWidget;
//! use teksilo_tokens::TextRole;
//!
//! // In build():
//! ctx.add(
//!     Snackbar::new(lit!("Undo"))
//!         .content(TextWidget::new(lit!("File deleted.")).color(TextRole::TooltipText))
//!         .announcement(lit!("File deleted."))
//!         .auto_dismiss_after(std::time::Duration::from_secs(5)),
//! );
//! ```

use std::rc::Rc;
use std::time::Duration;

use teksilo_canvas::{Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::overlay::{DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest};
use teksilo_core::signal::Prop;
use teksilo_core::styles::{SharedSnackbarStyle, SnackbarStyleConfig};
use teksilo_core::widget::{LayoutContext, PendingChild, Widget, WidgetPlacement};
use teksilo_core::widget_id::WidgetId;

use crate::button::{Button, ButtonVariant};
use crate::overlay_trigger::OverlayTrigger;
use teksilo_i18n::LocalizedString;

const DEFAULT_AUTO_DISMISS: Duration = Duration::from_secs(4);

fn present_snackbar(
    ctx: &mut teksilo_core::widget::EventContext,
    anchor: WidgetId,
    content_id: WidgetId,
    shown: &teksilo_core::signal::Signal<bool>,
    dismiss: DismissBehavior,
    auto_dismiss_after: Option<Duration>,
    fade_duration: Option<Duration>,
) {
    ctx.dismiss_all_except_hosts();
    // Build the surface if this is the first time this snackbar is presented —
    // `activate` alone would wake a node whose subtree does not exist yet.
    shown.set(true);
    ctx.materialize_now(content_id);
    ctx.activate(content_id);
    let request = OverlayRequest {
        content_id,
        anchor,
        placement: OverlayPlacement::BottomCenter,
        dismiss,
        layer: OverlayLayer::InTree,
        parent_overlay: None,
        on_dismiss: None,
        fade_duration,
    };
    if let Some(duration) = auto_dismiss_after {
        ctx.show_overlay_for(request, duration);
    } else {
        ctx.show_overlay(request);
    }
}

struct SnackbarSurface {
    content_id: Option<WidgetId>,
    pending_content: Option<PendingChild>,
    /// Optional explicit SR announcement string. When set,
    /// `accessibility()` uses it as the Alert's accessible name
    /// so screen readers read out the caller-provided message
    /// the moment the snackbar appears. Falls back to the
    /// generic `a11y_snackbar_name` when unset.
    announcement: Option<LocalizedString>,
    /// Per-call override for the snackbar surface chrome.
    style_override: Option<SharedSnackbarStyle>,
    /// Build state — the `SnackbarStyle::make_body` root.
    root_child_id: Option<WidgetId>,
}

impl SnackbarSurface {
    fn new(content: PendingChild) -> Self {
        Self {
            content_id: None,
            pending_content: Some(content),
            announcement: None,
            style_override: None,
            root_child_id: None,
        }
    }

    fn with_announcement(mut self, text: Option<LocalizedString>) -> Self {
        self.announcement = text;
        self
    }

    fn with_style(mut self, style: Option<SharedSnackbarStyle>) -> Self {
        self.style_override = style;
        self
    }
}

impl std::fmt::Debug for SnackbarSurface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SnackbarSurface").finish()
    }
}

impl Widget for SnackbarSurface {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        if let Some(pending) = self.pending_content.take() {
            self.content_id = Some(match pending {
                PendingChild::Id(id) => id,
                PendingChild::Deferred(w) => ctx.add_boxed(w),
            });
        }
        // The surface chrome (dark `tooltip_bg` panel + border + padding
        // inset) is owned by the active `SnackbarStyle`; this widget
        // keeps its `Role::Alert` / `Live::Polite` accessibility node.
        let content_id = self
            .content_id
            .expect("SnackbarSurface requires content — none was set");
        let style: SharedSnackbarStyle = self
            .style_override
            .clone()
            .or_else(|| ctx.theme().style_slots.snackbar.clone())
            .unwrap_or_else(|| Rc::new(crate::styles::RecipeSnackbarStyle::default()));
        let root_id = style.make_body(
            &SnackbarStyleConfig {
                content: content_id,
            },
            ctx,
        );
        self.root_child_id = Some(root_id);
        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        self.root_child_id
            .and_then(|id| ctx.child_size(id, proposal))
            .unwrap_or_else(|| proposal.resolve(220.0, 44.0))
            .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // Role::Alert + Live::Polite mirrors the ARIA pattern for
        // transient notifications: screen readers announce the
        // contents when the snackbar appears, without interrupting
        // the user's current action. The accessible name is the
        // caller-supplied announcement when present, otherwise
        // the generic fallback. Child widgets still contribute
        // their own nodes for full context.
        builder.set_role(teksilo_core::accesskit::Role::Alert);
        builder.set_live(teksilo_core::accesskit::Live::Polite);
        let name = self
            .announcement
            .as_ref()
            .map(|a| a.resolve_now())
            .unwrap_or_else(|| teksilo_i18n::tr_widget!(a11y_snackbar_name()).resolve_now());
        builder.set_name(name);
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}

/// A button-triggered transient notification surface.
///
/// Call `.content(...)` to supply the notification body, then add the
/// widget to the tree. The trigger label is shown as a `Button` (or a
/// custom widget via `.trigger(...)`); activating it presents the
/// content surface at the bottom center of the window.
pub struct Snackbar {
    label: LocalizedString,
    variant: ButtonVariant,
    /// Enabled state (static or reactive). Wired into the arena on the
    /// trigger node -- the default `Button` and, on the `.trigger(...)`
    /// path, the `OverlayTrigger` -- so a disabled trigger greys out,
    /// reports `disabled` to AT, and has its dispatch gated. The snapshot
    /// read in `build()` is a redundant early-out kept in the custom-trigger
    /// closures.
    enabled: Prop<bool>,
    dismiss: DismissBehavior,
    auto_dismiss_after: Option<Duration>,
    pending_content: Option<PendingChild>,
    pending_trigger: Option<PendingChild>,
    /// Optional explicit announcement string threaded through to
    /// the `SnackbarSurface`'s a11y node. When set, screen readers
    /// read this as the Alert's name when the snackbar appears.
    announcement: Option<LocalizedString>,
    /// Per-call override for the snackbar surface chrome.
    style_override: Option<SharedSnackbarStyle>,
    root_child_id: Option<WidgetId>,
}

impl Snackbar {
    /// Create a snackbar whose default trigger button shows `label`.
    pub fn new(label: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = label.into();
        Self {
            label: ls,
            variant: ButtonVariant::Plain,
            enabled: Prop::Static(true),
            dismiss: DismissBehavior::ClickOutside,
            auto_dismiss_after: Some(DEFAULT_AUTO_DISMISS),
            pending_content: None,
            pending_trigger: None,
            announcement: None,
            style_override: None,
            root_child_id: None,
        }
    }

    /// Per-call style override for the snackbar surface chrome.
    /// Replaces the theme-wide default `SnackbarStyle` for just this
    /// instance.
    pub fn style(mut self, style: impl teksilo_core::styles::SnackbarStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    /// The snackbar body — the message (and optional inline action)
    /// shown on the floating surface.
    ///
    /// The default surface is the high-contrast (dark) `tooltip_bg`,
    /// the same one tooltips use, and it stays dark in light theme.
    /// So any `TextWidget` you pass here must set
    /// `.color(TextRole::TooltipText)` (and actions can use
    /// `TooltipText` / `TooltipShortcut`) — the default `TextRole::Primary`
    /// is dark and renders nearly invisible on the dark surface in light
    /// theme. If you install a light-surface `SnackbarStyle`, color the
    /// content to match that instead.
    pub fn content(mut self, content: impl Widget + 'static) -> Self {
        self.pending_content = Some(PendingChild::Deferred(Box::new(content)));
        self
    }

    /// Supply the notification body by `WidgetId` (already added to the
    /// tree). Mutually exclusive with `.content(...)`.
    pub fn content_id(mut self, id: WidgetId) -> Self {
        self.pending_content = Some(PendingChild::Id(id));
        self
    }

    /// Override the default trigger [`ButtonVariant`] (default: `Plain`).
    pub fn variant(mut self, variant: ButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Set the enabled state of the trigger, statically or reactively.
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Override the overlay dismiss behavior (default: `ClickOutside`).
    pub fn dismiss_behavior(mut self, dismiss: DismissBehavior) -> Self {
        self.dismiss = dismiss;
        self
    }

    /// Set the auto-dismiss timeout. The overlay is removed after this
    /// duration without user interaction (default: 4 s).
    pub fn auto_dismiss_after(mut self, duration: Duration) -> Self {
        self.auto_dismiss_after = Some(duration);
        self
    }

    /// Keep the snackbar visible until explicitly dismissed; disables
    /// the auto-dismiss timeout.
    pub fn persistent(mut self) -> Self {
        self.auto_dismiss_after = None;
        self
    }

    /// Replace the default `Button` trigger with a custom widget. The
    /// widget is wired for tap, keyboard (Enter/Space), and AT Click
    /// activation automatically.
    pub fn trigger(mut self, trigger: impl Widget + 'static) -> Self {
        self.pending_trigger = Some(PendingChild::Deferred(Box::new(trigger)));
        self
    }

    /// Supply the custom trigger by `WidgetId` (already added to the tree).
    pub fn trigger_id(mut self, id: WidgetId) -> Self {
        self.pending_trigger = Some(PendingChild::Id(id));
        self
    }

    /// Screen-reader announcement string — used as the Alert's
    /// accessible name when the snackbar appears. Without this
    /// the surface falls back to the generic `a11y_snackbar_name`
    /// i18n string, which says "notification" but can't describe
    /// the specific message. Set this whenever the snackbar
    /// conveys information the user needs to hear (errors,
    /// confirmations, status changes).
    pub fn announcement(mut self, text: impl Into<LocalizedString>) -> Self {
        let ls: LocalizedString = text.into();
        self.announcement = Some(ls);
        self
    }
}

impl std::fmt::Debug for Snackbar {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Snackbar")
            .field("label", &self.label)
            .field("style", &self.variant)
            .field("enabled", &self.enabled.get())
            .finish()
    }
}

impl Widget for Snackbar {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let self_id = ctx.self_id();
        let label = self.label.clone();
        // Redundant early-out for the custom-trigger closures below; the
        // arena.s `enabled_when` (wired on the OverlayTrigger) already gates
        // dispatch, so this snapshot is belt-and-suspenders.
        let enabled = self.enabled.get();
        let dismiss = self.dismiss.clone();
        let auto_dismiss_after = self.auto_dismiss_after;
        let style = self.variant;
        // Captured at build time so the present-snackbar handlers
        // don't need a theme lookup at fire-time. `duration_normal`
        // matches the snackbar's typical "notification slide"
        // recommendation in MotionTokens.
        let fade_duration = if ctx.prefers_reduced_motion() {
            None
        } else {
            Some(ctx.theme().motion.duration_normal)
        };
        // The surface is built the first time the snackbar is presented, not on
        // every rebuild of the trigger that presents it. See
        // `teksilo_core::deferred_subtree::DeferredSubtree`.
        let shown = ctx.signal(false);
        let content_id = ctx.add_detached_deferred(
            shown.clone(),
            SnackbarSurface::new(
                self.pending_content
                    .take()
                    .expect("Snackbar requires .content(...) — no content was set"),
            )
            .with_announcement(self.announcement.clone())
            .with_style(self.style_override.clone()),
        );
        ctx.set_dormant(content_id);
        // The surface is shown through an overlay, so it stays out of the
        // child walk — but `add_detached` above still records who owns it, so
        // it is reaped with this Snackbar rather than stranded.

        let root_id = if let Some(trigger) = self.pending_trigger.take() {
            // A custom trigger is an arbitrary widget with no built-in
            // activation, so we wire pointer / keyboard / AT activation
            // by hand. (The default-Button branch below delegates all
            // three to `Button::on_activate_fn`.)
            let open_on_tap = {
                let dismiss = dismiss.clone();
                let shown = shown.clone();
                move |_event: &teksilo_core::TapEvent,
                      ctx: &mut teksilo_core::widget::EventContext| {
                    if !enabled {
                        return;
                    }
                    present_snackbar(
                        ctx,
                        self_id,
                        content_id,
                        &shown,
                        dismiss.clone(),
                        auto_dismiss_after,
                        fade_duration,
                    );
                }
            };
            let handlers = teksilo_core::widget_builder::HandlerSet::new()
                .focusable(true)
                .cursor(teksilo_core::widget::CursorIcon::Pointer)
                .on_tap(open_on_tap)
                .on_key({
                    let dismiss = dismiss.clone();
                    let shown = shown.clone();
                    move |event, ctx| match event {
                        WidgetEvent::KeyUp {
                            key: Key::Enter | Key::Space,
                            ..
                        } if enabled => {
                            present_snackbar(
                                ctx,
                                self_id,
                                content_id,
                                &shown,
                                dismiss.clone(),
                                auto_dismiss_after,
                                fade_duration,
                            );
                            EventResponse::Handled
                        }
                        _ => EventResponse::Ignored,
                    }
                })
                .on_access_action({
                    let shown = shown.clone();
                    move |action, ctx| {
                        if action == teksilo_core::accesskit::Action::Click && enabled {
                            present_snackbar(
                                ctx,
                                self_id,
                                content_id,
                                &shown,
                                dismiss.clone(),
                                auto_dismiss_after,
                                fade_duration,
                            );
                            EventResponse::Handled
                        } else {
                            EventResponse::Ignored
                        }
                    }
                });
            let overlay_trigger = match trigger {
                PendingChild::Id(id) => OverlayTrigger::from_id(id, handlers),
                PendingChild::Deferred(widget) => OverlayTrigger::new(widget, handlers),
            }
            .enabled(self.enabled.clone())
            .name(label);
            ctx.add(overlay_trigger)
        } else {
            // `Button::on_activate_fn` already fires on pointer tap,
            // Space/Enter (with the matched-KeyDown guard), and AccessKit
            // Click — so one handler covers all three activation paths.
            ctx.add(
                Button::new(label)
                    .variant(style)
                    .enabled(self.enabled.clone())
                    .on_activate_fn(move |ctx| {
                        present_snackbar(
                            ctx,
                            self_id,
                            content_id,
                            &shown,
                            dismiss.clone(),
                            auto_dismiss_after,
                            fade_duration,
                        );
                    }),
            )
        };

        self.root_child_id = Some(root_id);
        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        self.root_child_id
            .and_then(|id| ctx.child_size(id, proposal))
            .unwrap_or_else(|| proposal.resolve(140.0, 40.0))
            .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // The outer Snackbar widget is just a layout shell around the
        // focusable trigger (Button or OverlayTrigger). Hiding it from
        // the platform a11y tree prevents a dead GenericContainer node
        // from sitting between the trigger and its ancestors.
        builder.set_role(teksilo_core::accesskit::Role::GenericContainer);
        builder.set_hidden();
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use teksilo_canvas::Size;
    use teksilo_core::widget_tree::WidgetTree;
    use teksilo_i18n::lit;

    #[derive(Debug)]
    struct FixedLeaf(f32, f32);

    impl Widget for FixedLeaf {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> teksilo_core::widget::LayoutResponse {
            Size::new(self.0, self.1).into()
        }
    }

    #[test]
    fn access_click_opens_bottom_center_snackbar() {
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.add(Snackbar::new(lit!("Show snackbar")).content(FixedLeaf(220.0, 40.0)));
        tree.layout(SizeProposal::exact(800.0, 600.0));

        let trigger = tree.find_by_label("Show snackbar").unwrap();
        tree.dispatch_event(WidgetEvent::AccessAction {
            action: teksilo_core::accesskit::Action::Click,
            target: Some(trigger),
            target_node: teksilo_core::accessibility::root_node_id(),
            data: None,
        });
        tree.layout(SizeProposal::exact(800.0, 600.0));

        assert_eq!(tree.active_overlays().len(), 1);
        let content_id = tree.overlay_manager().active_content_ids()[0];
        let bounds = tree.bounds(content_id);
        let expected_x = (800.0 - bounds.width) / 2.0;
        assert!((bounds.x - expected_x).abs() < 1.0);
        assert!((bounds.y + bounds.height - (600.0 - 24.0)).abs() < 1.0);
    }

    #[test]
    fn default_button_keyboard_activation_opens_snackbar() {
        // The default-Button branch delegates all activation to
        // `Button::on_activate_fn`, so a matched KeyDown + KeyUp pair on
        // the focused trigger must present the snackbar — and inherits
        // Button's lone-KeyUp guard for free.
        use teksilo_core::event::Modifiers;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.add(Snackbar::new(lit!("Show snackbar")).content(FixedLeaf(220.0, 40.0)));
        tree.layout(SizeProposal::exact(800.0, 600.0));

        let trigger = tree.find_by_label("Show snackbar").unwrap();
        tree.focus(trigger);

        // A lone KeyUp (no matching KeyDown) must not activate.
        tree.dispatch_event(WidgetEvent::KeyUp {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
        });
        tree.layout(SizeProposal::exact(800.0, 600.0));
        assert!(tree.active_overlays().is_empty());

        // A matched KeyDown + KeyUp pair presents the snackbar.
        tree.dispatch_event(WidgetEvent::KeyDown {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
            text: None,
        });
        tree.dispatch_event(WidgetEvent::KeyUp {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
        });
        tree.layout(SizeProposal::exact(800.0, 600.0));
        assert_eq!(tree.active_overlays().len(), 1);
    }

    #[test]
    fn custom_trigger_opens_snackbar() {
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.add(
            Snackbar::new(lit!("Show snackbar"))
                .content(FixedLeaf(180.0, 36.0))
                .trigger(FixedLeaf(132.0, 36.0)),
        );
        tree.layout(SizeProposal::exact(640.0, 480.0));

        // OverlayTrigger now routes handlers onto the trigger child;
        // a pointer click on the wrapper hit-tests into the child where
        // the handler lives.
        let trigger = tree.find_by_label("Show snackbar").unwrap();
        tree.click(trigger);

        assert_eq!(tree.active_overlays().len(), 1);
    }

    #[test]
    fn snackbar_auto_dismisses_after_duration() {
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.add(
            Snackbar::new(lit!("Show snackbar"))
                .content(FixedLeaf(220.0, 40.0))
                .auto_dismiss_after(Duration::from_millis(300)),
        );
        tree.layout(SizeProposal::exact(800.0, 600.0));

        let trigger = tree.find_by_label("Show snackbar").unwrap();
        tree.dispatch_event(WidgetEvent::AccessAction {
            action: teksilo_core::accesskit::Action::Click,
            target: Some(trigger),
            target_node: teksilo_core::accessibility::root_node_id(),
            data: None,
        });
        assert_eq!(tree.active_overlays().len(), 1);

        tree.advance_time(Duration::from_millis(200));
        assert_eq!(tree.active_overlays().len(), 1);

        tree.advance_time(Duration::from_millis(150));
        assert!(tree.active_overlays().is_empty());
    }

    #[test]
    #[should_panic(expected = "Snackbar requires .content(...)")]
    fn snackbar_without_content_panics_on_build() {
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        tree.add(Snackbar::new(lit!("Show snackbar")));
        tree.layout(SizeProposal::exact(800.0, 600.0));
    }
}