ailloli_ui_widgets/controls/
toast.rs

1//! Overlay toast values and a non-focusable stacking host.
2
3use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::Event;
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::style::{
10    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
11};
12use ailloli_ui_core::{Color, FontId, IconId, Offset, TextStyle, Theme};
13use ailloli_ui_runtime::component::{
14    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
15};
16use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
17use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutPass, LayoutResult};
18use ailloli_ui_runtime::scene::PaintCtx;
19use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect};
20
21use super::popup::{apply_opacity, paint_overlay_text_in_rect};
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
24/// Semantic accent color for a [`Toast`].
25///
26/// # Examples
27///
28/// ```
29/// use ailloli_ui_widgets::controls::ToastTone;
30/// assert_eq!(ToastTone::default(), ToastTone::Neutral);
31/// ```
32pub enum ToastTone {
33    /// De-emphasized neutral accent.
34    #[default]
35    Neutral,
36    /// Successful outcome.
37    Success,
38    /// Warning outcome.
39    Warning,
40    /// Failed or destructive outcome.
41    Danger,
42    /// Informational outcome.
43    Info,
44}
45
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47/// Corner from which a [`ToastHost`] stacks notifications.
48///
49/// # Examples
50///
51/// ```
52/// use ailloli_ui_widgets::controls::ToastPosition;
53/// assert_eq!(ToastPosition::default(), ToastPosition::TopRight);
54/// ```
55pub enum ToastPosition {
56    /// Stack downward from the top-left inset.
57    TopLeft,
58    /// Stack downward from the top-right inset.
59    #[default]
60    TopRight,
61    /// Stack upward from the bottom-left inset.
62    BottomLeft,
63    /// Stack upward from the bottom-right inset.
64    BottomRight,
65}
66
67#[derive(Clone, Debug, PartialEq)]
68/// Resolved toast colors, typography, and logical-pixel geometry.
69///
70/// Toast heights are fixed at 52 pixels without a description and 72 pixels
71/// with one. `padding_y` is retained for style compatibility but those fixed
72/// vertical offsets currently do not read it.
73///
74/// # Examples
75///
76/// ```
77/// use ailloli_ui_core::Theme;
78/// use ailloli_ui_widgets::controls::ToastStyle;
79/// let style = ToastStyle::from_theme(Theme::dark());
80/// assert_eq!(style.width, 330.0);
81/// assert_eq!(style.inset, 18.0);
82/// ```
83pub struct ToastStyle {
84    /// Card fill.
85    pub background: Color,
86    /// Card border.
87    pub border: Border,
88    /// Card shadows; inset entries are skipped.
89    pub shadows: Vec<BoxShadow>,
90    /// Title text style.
91    pub title_text: TextStyle,
92    /// Description text style.
93    pub description_text: TextStyle,
94    /// Close-icon tint before the fixed 0.82 opacity multiplier.
95    pub close_tint: Color,
96    /// Neutral tone-strip and icon color.
97    pub neutral: Color,
98    /// Success tone-strip and icon color.
99    pub success: Color,
100    /// Warning tone-strip and icon color.
101    pub warning: Color,
102    /// Danger tone-strip and icon color.
103    pub danger: Color,
104    /// Info tone-strip and icon color.
105    pub info: Color,
106    /// Card corner radii.
107    pub radius: Radius,
108    /// Toast width in logical pixels.
109    pub width: f32,
110    /// Horizontal text/icon inset in logical pixels.
111    pub padding_x: f32,
112    /// Reserved vertical padding; fixed toast offsets currently ignore it.
113    pub padding_y: f32,
114    /// Gap between leading icon/text and text/close regions.
115    pub gap: f32,
116    /// Leading icon width and height.
117    pub icon_size: f32,
118    /// Close hit/icon width and height.
119    pub close_size: f32,
120    /// Gap between stacked toast rectangles.
121    pub stack_gap: f32,
122    /// Distance from the selected host edges.
123    pub inset: f32,
124}
125
126impl Default for ToastStyle {
127    fn default() -> Self {
128        Self::from_theme(Theme::default())
129    }
130}
131
132impl ToastStyle {
133    /// Resolves toast colors, typography, and geometry from `theme`.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use ailloli_ui_core::Theme;
139    /// use ailloli_ui_widgets::controls::ToastStyle;
140    /// let style = ToastStyle::from_theme(Theme::dark());
141    /// assert_eq!(style.icon_size, 16.0);
142    /// assert_eq!(style.stack_gap, 10.0);
143    /// ```
144    pub fn from_theme(theme: Theme) -> Self {
145        let palette = theme.palette();
146        Self {
147            background: palette.surface_elevated,
148            border: Border::new(1.0, palette.border),
149            shadows: vec![theme.shadows().md],
150            title_text: TextStyle::new(FontId::Ui, 13, palette.text),
151            description_text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
152            close_tint: palette.text_muted,
153            neutral: palette.text_muted,
154            success: palette.success,
155            warning: palette.warning,
156            danger: palette.danger,
157            info: palette.info,
158            radius: Radius::uniform(theme.radius().lg),
159            width: 330.0,
160            padding_x: 12.0,
161            padding_y: 10.0,
162            gap: 8.0,
163            icon_size: 16.0,
164            close_size: 16.0,
165            stack_gap: 10.0,
166            inset: 18.0,
167        }
168    }
169
170    /// Returns the configured accent color for `tone`.
171    ///
172    /// # Examples
173    ///
174    /// ```
175    /// use ailloli_ui_widgets::controls::{ToastStyle, ToastTone};
176    /// let style = ToastStyle::default();
177    /// assert_eq!(style.tone_color(ToastTone::Success), style.success);
178    /// ```
179    pub fn tone_color(&self, tone: ToastTone) -> Color {
180        match tone {
181            ToastTone::Neutral => self.neutral,
182            ToastTone::Success => self.success,
183            ToastTone::Warning => self.warning,
184            ToastTone::Danger => self.danger,
185            ToastTone::Info => self.info,
186        }
187    }
188}
189
190#[derive(Clone, Debug, PartialEq)]
191/// Owned data for one overlay notification.
192///
193/// IDs route dismissal and should be unique. Duplicate IDs are accepted; a
194/// bound-host dismissal removes every matching value while invoking its callback
195/// once. `Some("")` description still selects the taller 72-pixel layout.
196///
197/// # Examples
198///
199/// ```
200/// use ailloli_ui_widgets::controls::{Toast, ToastTone};
201/// let toast = Toast::new("saved", "Saved").tone(ToastTone::Success);
202/// assert_eq!(toast.id(), "saved");
203/// ```
204pub struct Toast {
205    /// Dismissal identity.
206    id: String,
207    /// Primary text.
208    title: String,
209    /// Optional secondary line; presence controls height even when empty.
210    description: Option<String>,
211    /// Semantic accent tone.
212    tone: ToastTone,
213    /// Optional tone-tinted leading icon.
214    leading_icon: Option<IconId>,
215    /// Whether a pointer-accessible close affordance is painted.
216    closable: bool,
217}
218
219impl Toast {
220    /// Creates a neutral, closable toast with no description or icon.
221    ///
222    /// Empty and duplicate IDs are accepted but unique stable IDs are recommended.
223    ///
224    /// # Examples
225    ///
226    /// ```
227    /// use ailloli_ui_widgets::controls::Toast;
228    /// let toast = Toast::new("connected", "Connected");
229    /// assert_eq!(toast.title(), "Connected");
230    /// ```
231    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
232        Self {
233            id: id.into(),
234            title: title.into(),
235            description: None,
236            tone: ToastTone::Neutral,
237            leading_icon: None,
238            closable: true,
239        }
240    }
241
242    /// Borrows the exact dismissal identity.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use ailloli_ui_widgets::controls::Toast;
248    /// let toast = Toast::new("job-1", "Started");
249    /// assert_eq!(toast.id(), "job-1");
250    /// ```
251    pub fn id(&self) -> &str {
252        &self.id
253    }
254
255    /// Borrows the exact primary title.
256    ///
257    /// # Examples
258    ///
259    /// ```
260    /// use ailloli_ui_widgets::controls::Toast;
261    /// let toast = Toast::new("job-1", "Started");
262    /// assert_eq!(toast.title(), "Started");
263    /// ```
264    pub fn title(&self) -> &str {
265        &self.title
266    }
267
268    /// Sets the secondary line, replacing any previous description.
269    ///
270    /// An empty string remains `Some` and selects the taller toast layout.
271    ///
272    /// # Examples
273    ///
274    /// ```
275    /// use ailloli_ui_widgets::controls::Toast;
276    /// let toast = Toast::new("saved", "Saved").description("All changes are on disk");
277    /// let _ = toast;
278    /// ```
279    pub fn description(mut self, description: impl Into<String>) -> Self {
280        self.description = Some(description.into());
281        self
282    }
283
284    /// Sets the semantic accent tone.
285    ///
286    /// # Examples
287    ///
288    /// ```
289    /// use ailloli_ui_widgets::controls::{Toast, ToastTone};
290    /// let toast = Toast::new("failed", "Failed").tone(ToastTone::Danger);
291    /// let _ = toast;
292    /// ```
293    pub fn tone(mut self, tone: ToastTone) -> Self {
294        self.tone = tone;
295        self
296    }
297
298    /// Sets a tone-tinted leading icon, replacing any prior icon.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use ailloli_ui_core::IconId;
304    /// use ailloli_ui_widgets::controls::Toast;
305    /// let toast = Toast::new("done", "Done").leading_icon(IconId::Check);
306    /// let _ = toast;
307    /// ```
308    pub fn leading_icon(mut self, icon: IconId) -> Self {
309        self.leading_icon = Some(icon);
310        self
311    }
312
313    /// Controls whether the close icon, hit bound, and dismiss path are present.
314    ///
315    /// Non-closable toasts can still be removed by changing the host's source.
316    ///
317    /// # Examples
318    ///
319    /// ```
320    /// use ailloli_ui_widgets::controls::Toast;
321    /// let toast = Toast::new("sync", "Syncing").closable(false);
322    /// let _ = toast;
323    /// ```
324    pub fn closable(mut self, closable: bool) -> Self {
325        self.closable = closable;
326        self
327    }
328}
329
330/// Shared callback receiving the dismissed toast ID.
331type ToastDismissHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
332
333/// A full-slot host that overlays a stack of toasts over one optional child.
334///
335/// The host itself is never focusable. Close activation is pointer-only and
336/// checks visible values in reverse order. Bound mode removes all matching IDs;
337/// controlled/static mode reports dismissal but cannot mutate its source.
338/// Toasts are not clipped or virtualized and may extend outside a small host.
339///
340/// # Examples
341///
342/// ```
343/// use ailloli_ui_widgets::controls::{Toast, ToastHost};
344/// let host: ToastHost<()> = ToastHost::new().toast(Toast::new("saved", "Saved"));
345/// let _ = host;
346/// ```
347pub struct ToastHost<A = ()> {
348    /// Layout configuration for the full host slot.
349    pub(crate) layout: LayoutStyle,
350    /// Flex-item behavior used by the parent layout.
351    pub(crate) flex_item: FlexItemStyle,
352    /// Static, controlled, or bound toast values in stack order.
353    toasts: Binding<Vec<Toast>>,
354    /// Writable source in bound mode only.
355    bound_toasts: Option<Signal<Vec<Toast>>>,
356    /// Corner and stack direction.
357    position: ToastPosition,
358    /// Resolved paint and geometry.
359    style: ToastStyle,
360    /// Optional dismissal callback.
361    on_dismiss: Option<ToastDismissHandler<A>>,
362    /// Optional sole host child below the overlay.
363    child: Option<View<A>>,
364}
365
366crate::impl_layout_builders!(ToastHost);
367
368impl<A: 'static> Default for ToastHost<A> {
369    fn default() -> Self {
370        Self::new()
371    }
372}
373
374impl<A: 'static> ToastHost<A> {
375    /// Creates an empty top-right host with no child or dismissal callback.
376    ///
377    /// # Examples
378    ///
379    /// ```
380    /// use ailloli_ui_widgets::controls::ToastHost;
381    /// let host: ToastHost<()> = ToastHost::new();
382    /// let _ = host;
383    /// ```
384    pub fn new() -> Self {
385        Self {
386            layout: LayoutStyle::default(),
387            flex_item: FlexItemStyle::default(),
388            toasts: Binding::Static(Vec::new()),
389            bound_toasts: None,
390            position: ToastPosition::TopRight,
391            style: ToastStyle::default(),
392            on_dismiss: None,
393            child: None,
394        }
395    }
396
397    /// Appends one toast to a snapshot of the current binding.
398    ///
399    /// This converts the result to static mode and clears a writable binding.
400    /// Repeated calls preserve order and grow an unbounded vector.
401    ///
402    /// # Examples
403    ///
404    /// ```
405    /// use ailloli_ui_widgets::controls::{Toast, ToastHost};
406    /// let host: ToastHost<()> = ToastHost::new().toast(Toast::new("one", "First"));
407    /// let _ = host;
408    /// ```
409    pub fn toast(mut self, toast: Toast) -> Self {
410        let mut toasts = self.toasts.read();
411        toasts.push(toast);
412        self.toasts = Binding::Static(toasts);
413        self.bound_toasts = None;
414        self
415    }
416
417    /// Replaces the static or reactive controlled toast list.
418    ///
419    /// This clears bound mode, so close activation cannot mutate the source.
420    /// The callback can be used to ask the consumer to update it.
421    ///
422    /// # Examples
423    ///
424    /// ```
425    /// use ailloli_ui_widgets::controls::{Toast, ToastHost};
426    /// let host: ToastHost<()> = ToastHost::new().toasts(vec![Toast::new("one", "First")]);
427    /// let _ = host;
428    /// ```
429    pub fn toasts(mut self, toasts: impl Into<Binding<Vec<Toast>>>) -> Self {
430        self.toasts = toasts.into();
431        self.bound_toasts = None;
432        self
433    }
434
435    /// Installs a writable signal for two-way dismissal.
436    ///
437    /// Close activation removes every toast whose ID equals the activated ID,
438    /// then invokes the optional callback once.
439    ///
440    /// # Examples
441    ///
442    /// ```
443    /// use std::{cell::RefCell, rc::Rc};
444    /// use ailloli_ui_runtime::component::Signal;
445    /// use ailloli_ui_widgets::controls::{Toast, ToastHost};
446    /// let toasts = Signal::new(Rc::new(RefCell::new(vec![Toast::new("one", "First")])), Rc::new(|| {}));
447    /// let host: ToastHost<()> = ToastHost::new().bind_toasts(toasts);
448    /// let _ = host;
449    /// ```
450    pub fn bind_toasts(mut self, toasts: impl Into<Signal<Vec<Toast>>>) -> Self {
451        let signal = toasts.into();
452        self.toasts = Binding::Signal(signal.clone());
453        self.bound_toasts = Some(signal);
454        self
455    }
456
457    /// Selects the corner and vertical stacking direction.
458    ///
459    /// # Examples
460    ///
461    /// ```
462    /// use ailloli_ui_widgets::controls::{ToastHost, ToastPosition};
463    /// let host: ToastHost<()> = ToastHost::new().position(ToastPosition::BottomLeft);
464    /// let _ = host;
465    /// ```
466    pub fn position(mut self, position: ToastPosition) -> Self {
467        self.position = position;
468        self
469    }
470
471    /// Replaces complete toast-stack style and geometry.
472    ///
473    /// # Examples
474    ///
475    /// ```
476    /// use ailloli_ui_core::Theme;
477    /// use ailloli_ui_widgets::controls::{ToastHost, ToastStyle};
478    /// let style = ToastStyle::from_theme(Theme::dark());
479    /// let host: ToastHost<()> = ToastHost::new().toast_style(style);
480    /// let _ = host;
481    /// ```
482    pub fn toast_style(mut self, style: ToastStyle) -> Self {
483        self.style = style;
484        self
485    }
486
487    /// Maps each dismissed ID to an application action and dispatches it.
488    ///
489    /// The mapper runs after bound values are removed. A later handler replaces it.
490    ///
491    /// # Examples
492    ///
493    /// ```
494    /// use ailloli_ui_widgets::controls::ToastHost;
495    /// enum Action { Dismissed(String) }
496    /// let host = ToastHost::new().on_dismiss(Action::Dismissed);
497    /// let _ = host;
498    /// ```
499    pub fn on_dismiss(mut self, f: impl Fn(String) -> A + 'static) -> Self {
500        self.on_dismiss = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
501        self
502    }
503
504    /// Installs a context-aware dismissal callback.
505    ///
506    /// # Examples
507    ///
508    /// ```
509    /// use ailloli_ui_widgets::controls::ToastHost;
510    /// let host = ToastHost::<()>::new().on_dismiss_ctx(|ctx, _id| ctx.request_repaint());
511    /// let _ = host;
512    /// ```
513    pub fn on_dismiss_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
514        self.on_dismiss = Some(Rc::new(f));
515        self
516    }
517
518    /// Sets the sole underlying host child, replacing any previous child.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use ailloli_ui_widgets::controls::ToastHost;
524    /// use ailloli_ui_widgets::text::Text;
525    /// let host = ToastHost::<()>::new().child(Text::new("Workspace"));
526    /// let _ = host;
527    /// ```
528    pub fn child(mut self, child: impl IntoView<A>) -> Self {
529        self.child = Some(child.into_view());
530        self
531    }
532}
533
534/// Component properties used to build the overlay host node.
535struct ToastHostComponent<A> {
536    /// Outer logical sizing policy for the underlying host child.
537    layout: LayoutStyle,
538    /// Readable ordered toast collection.
539    toasts: Binding<Vec<Toast>>,
540    /// Optional writable collection used for built-in dismissal.
541    bound_toasts: Option<Signal<Vec<Toast>>>,
542    /// Viewport corner or edge used to stack toast overlays.
543    position: ToastPosition,
544    /// Toast colors, spacing, and logical-pixel geometry.
545    style: ToastStyle,
546    /// Optional callback receiving dismissed toast identities.
547    on_dismiss: Option<ToastDismissHandler<A>>,
548    /// Optional underlying host content painted below overlays.
549    child: Option<View<A>>,
550}
551
552impl<A: 'static> ComponentNode<A> for ToastHostComponent<A> {
553    fn build(&self, _context: &mut Context<A>) -> View<A> {
554        let mut children = Vec::new();
555        if let Some(child) = self.child.clone() {
556            children.push(child);
557        }
558        View::node(
559            ToastHostWidget {
560                layout: self.layout,
561                toasts: self.toasts.clone(),
562                bound_toasts: self.bound_toasts.clone(),
563                position: self.position,
564                style: self.style.clone(),
565                on_dismiss: self.on_dismiss.clone(),
566            },
567            children,
568        )
569    }
570}
571
572impl<A: 'static> IntoView<A> for ToastHost<A> {
573    fn into_view(self) -> View<A> {
574        finish_view_sized(
575            View::component(ToastHostComponent {
576                layout: self.layout,
577                toasts: self.toasts,
578                bound_toasts: self.bound_toasts,
579                position: self.position,
580                style: self.style,
581                on_dismiss: self.on_dismiss,
582                child: self.child,
583            }),
584            self.flex_item,
585            LayoutSizeHint::from_layout(self.layout),
586        )
587    }
588}
589
590/// Retained overlay widget resolving stack geometry and close activation.
591struct ToastHostWidget<A> {
592    /// Outer logical sizing policy for the underlying host child.
593    layout: LayoutStyle,
594    /// Readable ordered toast collection.
595    toasts: Binding<Vec<Toast>>,
596    /// Optional writable collection used for built-in dismissal.
597    bound_toasts: Option<Signal<Vec<Toast>>>,
598    /// Viewport corner or edge used to stack toast overlays.
599    position: ToastPosition,
600    /// Toast colors, spacing, and logical-pixel geometry.
601    style: ToastStyle,
602    /// Optional retained dismissal callback.
603    on_dismiss: Option<ToastDismissHandler<A>>,
604}
605
606impl<A: 'static> Widget<A> for ToastHostWidget<A> {
607    fn debug_name(&self) -> &'static str {
608        "ToastHost"
609    }
610
611    fn layout(
612        &self,
613        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
614        ctx: &mut LayoutCtx<'_>,
615        children: &mut [LayoutChild],
616        constraints: Constraints,
617    ) -> LayoutResult {
618        let size = host_slot_size(engine, ctx, children, constraints, self.layout);
619        let mut child_layouts = Vec::new();
620        if let Some(child) = children.first_mut() {
621            let r = ctx.with_layout_pass(LayoutPass::Commit, |ctx| {
622                child.layout(engine, ctx, Constraints::tight(size.w, size.h))
623            });
624            child_layouts.push(ChildLayout {
625                offset: Offset::default(),
626                size: r.size,
627                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
628                visual_bounds: r.visual_bounds,
629            });
630        }
631
632        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
633        let overlay_hit_bounds = self
634            .toast_rects(size)
635            .into_iter()
636            .filter_map(|(_, toast, rect)| toast.closable.then_some(self.close_rect(rect)))
637            .collect();
638
639        LayoutResult {
640            size,
641            children: child_layouts,
642            paint_bounds,
643            visual_bounds: paint_bounds,
644            overlay_hit_bounds,
645            clip: None,
646            is_window_root_clip: false,
647            artifact: None,
648        }
649    }
650
651    fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
652
653    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
654        for (_, toast, rect) in self.toast_rects(bounds.size()).into_iter() {
655            self.paint_toast(ctx, rect.translate(Offset::new(bounds.x, bounds.y)), &toast);
656        }
657    }
658
659    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
660        let Event::Pointer(PointerEvent::Button {
661            pos,
662            button: MouseButton::Left,
663            pressed: false,
664            ..
665        }) = event
666        else {
667            return;
668        };
669
670        for (_, toast, rect) in self.toast_rects(bounds.size()).into_iter().rev() {
671            let rect = rect.translate(Offset::new(bounds.x, bounds.y));
672            if toast.closable && self.close_rect(rect).contains(pos.x, pos.y) {
673                self.dismiss(ctx, toast.id.clone());
674                ctx.stop_propagation();
675                return;
676            }
677        }
678    }
679
680    fn focus_policy(&self) -> FocusPolicy {
681        FocusPolicy::NotFocusable
682    }
683}
684
685impl<A: 'static> ToastHostWidget<A> {
686    /// Resolves all toast rectangles in source order without clipping.
687    fn toast_rects(&self, host_size: Size) -> Vec<(usize, Toast, Rect)> {
688        let mut y = match self.position {
689            ToastPosition::TopLeft | ToastPosition::TopRight => self.style.inset,
690            ToastPosition::BottomLeft | ToastPosition::BottomRight => {
691                host_size.h - self.style.inset
692            }
693        };
694        let mut out = Vec::new();
695        for (idx, toast) in self.toasts.read().into_iter().enumerate() {
696            let h = self.toast_height(&toast);
697            if matches!(
698                self.position,
699                ToastPosition::BottomLeft | ToastPosition::BottomRight
700            ) {
701                y -= h;
702            }
703            let x = match self.position {
704                ToastPosition::TopLeft | ToastPosition::BottomLeft => self.style.inset,
705                ToastPosition::TopRight | ToastPosition::BottomRight => {
706                    host_size.w - self.style.inset - self.style.width
707                }
708            }
709            .max(self.style.inset);
710            out.push((idx, toast, Rect::new(x, y, self.style.width, h)));
711            if matches!(
712                self.position,
713                ToastPosition::TopLeft | ToastPosition::TopRight
714            ) {
715                y += h + self.style.stack_gap;
716            } else {
717                y -= self.style.stack_gap;
718            }
719        }
720        out
721    }
722
723    /// Returns 72 pixels when a description is present, otherwise 52.
724    fn toast_height(&self, toast: &Toast) -> f32 {
725        if toast.description.is_some() {
726            72.0
727        } else {
728            52.0
729        }
730    }
731
732    /// Returns the close hit/icon square aligned to the toast's right inset.
733    fn close_rect(&self, rect: Rect) -> Rect {
734        Rect::new(
735            rect.right() - self.style.padding_x - self.style.close_size,
736            rect.y + (rect.h - self.style.close_size) * 0.5,
737            self.style.close_size,
738            self.style.close_size,
739        )
740    }
741
742    /// Removes matching bound values, reports once, and requests repaint.
743    fn dismiss(&self, ctx: &mut EventCtx<A>, id: String) {
744        if let Some(bound) = &self.bound_toasts {
745            bound.update(|toasts| toasts.retain(|toast| toast.id != id));
746        }
747        if let Some(on_dismiss) = &self.on_dismiss {
748            on_dismiss(ctx, id);
749        }
750        ctx.request_repaint();
751    }
752
753    /// Paints one card, four-pixel tone strip, content, close icon, and border.
754    fn paint_toast(&self, ctx: &mut PaintCtx<'_>, rect: Rect, toast: &Toast) {
755        for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
756            ctx.push_overlay(DrawCmd::BoxShadow(DrawBoxShadow {
757                rect,
758                radius: self.style.radius,
759                shadow,
760            }));
761        }
762        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
763            rect,
764            radius: self.style.radius.tl,
765            color: self.style.background,
766        }));
767
768        let tone = self.style.tone_color(toast.tone);
769        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
770            rect: Rect::new(rect.x, rect.y, 4.0, rect.h),
771            radius: self.style.radius.tl.min(4.0),
772            color: tone,
773        }));
774
775        let mut x = rect.x + self.style.padding_x + 4.0;
776        if let Some(icon) = &toast.leading_icon {
777            ctx.push_overlay(DrawCmd::Image(DrawImage {
778                rect: Rect::new(
779                    x,
780                    rect.y + (rect.h - self.style.icon_size) * 0.5,
781                    self.style.icon_size,
782                    self.style.icon_size,
783                ),
784                icon: icon.clone(),
785                tint: tone,
786                rotation_rad: 0.0,
787            }));
788            x += self.style.icon_size + self.style.gap;
789        }
790
791        let right = if toast.closable {
792            self.close_rect(rect).x - self.style.gap
793        } else {
794            rect.right() - self.style.padding_x
795        };
796        let text_rect = Rect::new(x, rect.y + 7.0, (right - x).max(0.0), 24.0);
797        paint_overlay_text_in_rect(ctx, &toast.title, self.style.title_text, text_rect, 1.0);
798        if let Some(description) = &toast.description {
799            let desc = Rect::new(x, rect.y + 34.0, (right - x).max(0.0), 22.0);
800            paint_overlay_text_in_rect(ctx, description, self.style.description_text, desc, 1.0);
801        }
802
803        if toast.closable {
804            ctx.push_overlay(DrawCmd::Image(DrawImage {
805                rect: self.close_rect(rect),
806                icon: IconId::Close,
807                tint: apply_opacity(self.style.close_tint, 0.82),
808                rotation_rad: 0.0,
809            }));
810        }
811
812        if self.style.border.is_visible() {
813            ctx.push_overlay(DrawCmd::Border(DrawBorder {
814                rect,
815                radius: self.style.radius,
816                border: self.style.border,
817            }));
818        }
819    }
820}
821
822/// Resolves host size from its child or finite constraint maxima.
823fn host_slot_size<A: 'static>(
824    engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
825    ctx: &mut LayoutCtx<'_>,
826    children: &mut [LayoutChild],
827    constraints: Constraints,
828    layout: LayoutStyle,
829) -> Size {
830    let intrinsic = if let Some(child) = children.first_mut() {
831        ctx.with_layout_pass(LayoutPass::Measure, |ctx| {
832            child.layout(engine, ctx, constraints.loosen()).size
833        })
834    } else {
835        Size::new(
836            finite_or(constraints.max_w, 0.0),
837            finite_or(constraints.max_h, 0.0),
838        )
839    };
840    apply_layout_size(intrinsic, layout, constraints)
841}
842
843/// Returns `value` when finite and `fallback` for NaN or either infinity.
844fn finite_or(value: f32, fallback: f32) -> f32 {
845    if value.is_finite() {
846        value
847    } else {
848        fallback
849    }
850}
851
852/// Local geometry extension used to pass host dimensions to stack layout.
853trait RectExt {
854    /// Copies rectangle width and height into a [`Size`].
855    fn size(self) -> Size;
856}
857
858impl RectExt for Rect {
859    fn size(self) -> Size {
860        Size::new(self.w, self.h)
861    }
862}