ailloli_ui_widgets/controls/
dialog.rs

1//! Modal confirmation dialogs painted over an optional host child.
2
3use std::cell::{Cell, RefCell};
4use std::rc::Rc;
5
6use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
7use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
8use ailloli_ui_core::event::{Event, KeyState, NamedKey};
9use ailloli_ui_core::geometry::{Constraints, Rect, Size};
10use ailloli_ui_core::style::{
11    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
12};
13use ailloli_ui_core::{Color, FontId, Offset, TextStyle, Theme};
14use ailloli_ui_runtime::component::{
15    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
16};
17use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, IntoClickAction};
18use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutPass, LayoutResult};
19use ailloli_ui_runtime::popup::{
20    PopupContent, PopupDismissReason, PopupFocusPolicy, PopupRole, PopupSemantics,
21};
22use ailloli_ui_runtime::scene::PaintCtx;
23use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect, DrawRect, DrawText};
24
25use ailloli_ui_text::{TextLayoutHandle, TextLayoutParams, WrapMode};
26
27use crate::transactional_layout::TransactionalLayoutPending;
28
29use super::popup::PopupPortalBridge;
30
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32/// Semantic treatment for a dialog's confirm action.
33///
34/// # Examples
35///
36/// ```
37/// use ailloli_ui_widgets::controls::DialogTone;
38/// assert_eq!(DialogTone::default(), DialogTone::Neutral);
39/// ```
40pub enum DialogTone {
41    /// Accent-colored primary confirmation.
42    #[default]
43    Neutral,
44    /// Danger-colored confirmation for destructive operations.
45    Danger,
46}
47
48#[derive(Clone, Debug, PartialEq)]
49/// Resolved paint, typography, and logical-pixel geometry for a [`Dialog`].
50///
51/// `primary_background_pressed`, `cancel_background_pressed`, and
52/// `danger_background_pressed` are retained for style compatibility but the
53/// current overlay painter does not yet resolve per-button pressed state.
54///
55/// # Examples
56///
57/// ```
58/// use ailloli_ui_core::Theme;
59/// use ailloli_ui_widgets::controls::{DialogStyle, DialogTone};
60/// let style = DialogStyle::from_theme(Theme::dark(), DialogTone::Neutral);
61/// assert_eq!(style.panel_width, 360.0);
62/// assert_eq!(style.button_height, 34.0);
63/// ```
64pub struct DialogStyle {
65    /// Full-host overlay fill.
66    pub backdrop: Color,
67    /// Panel fill.
68    pub panel_background: Color,
69    /// Panel border.
70    pub border: Border,
71    /// Panel shadows; inset entries are skipped by the current painter.
72    pub shadows: Vec<BoxShadow>,
73    /// Title text style.
74    pub title_text: TextStyle,
75    /// Wrapping body text style.
76    pub body_text: TextStyle,
77    /// Shared cancel and confirm label style.
78    pub button_text: TextStyle,
79    /// Neutral confirm-button fill.
80    pub primary_background: Color,
81    /// Reserved neutral pressed fill; currently not painted.
82    pub primary_background_pressed: Color,
83    /// Cancel-button fill.
84    pub cancel_background: Color,
85    /// Reserved cancel pressed fill; currently not painted.
86    pub cancel_background_pressed: Color,
87    /// Danger confirm-button fill.
88    pub danger_background: Color,
89    /// Reserved danger pressed fill; currently not painted.
90    pub danger_background_pressed: Color,
91    /// Shared button border.
92    pub button_border: Border,
93    /// Panel corner radii.
94    pub radius: Radius,
95    /// Button corner radii.
96    pub button_radius: Radius,
97    /// Preferred panel width in logical pixels.
98    pub panel_width: f32,
99    /// Minimum panel height in logical pixels.
100    pub panel_min_height: f32,
101    /// Panel and button edge inset in logical pixels.
102    pub padding: f32,
103    /// Cancel and confirm button height in logical pixels.
104    pub button_height: f32,
105    /// Width of each button in logical pixels.
106    pub button_width: f32,
107    /// Horizontal gap between cancel and confirm buttons.
108    pub gap: f32,
109}
110
111impl Default for DialogStyle {
112    fn default() -> Self {
113        Self::from_theme(Theme::default(), DialogTone::Neutral)
114    }
115}
116
117impl DialogStyle {
118    /// Resolves `tone` through `theme` into complete dialog style values.
119    ///
120    /// Tone affects the primary and primary-pressed colors; danger-specific
121    /// fields are populated for either tone.
122    ///
123    /// # Examples
124    ///
125    /// ```
126    /// use ailloli_ui_core::Theme;
127    /// use ailloli_ui_widgets::controls::{DialogStyle, DialogTone};
128    /// let neutral = DialogStyle::from_theme(Theme::dark(), DialogTone::Neutral);
129    /// let danger = DialogStyle::from_theme(Theme::dark(), DialogTone::Danger);
130    /// assert_ne!(neutral.primary_background, danger.primary_background);
131    /// ```
132    pub fn from_theme(theme: Theme, tone: DialogTone) -> Self {
133        let palette = theme.palette();
134        let danger = palette.danger;
135        Self {
136            backdrop: Color::BLACK.with_alpha(0.56),
137            panel_background: palette.surface_elevated,
138            border: Border::new(1.0, palette.border),
139            shadows: vec![theme.shadows().lg],
140            title_text: TextStyle::new(FontId::Ui, 16, palette.text),
141            body_text: TextStyle::new(FontId::Ui, 13, palette.text_muted),
142            button_text: TextStyle::new(FontId::Ui, 13, palette.text),
143            primary_background: match tone {
144                DialogTone::Neutral => palette.accent,
145                DialogTone::Danger => danger,
146            },
147            primary_background_pressed: match tone {
148                DialogTone::Neutral => Color::hex_rgb(0xD94800),
149                DialogTone::Danger => Color::hex_rgb(0xB91C1C),
150            },
151            cancel_background: palette.surface,
152            cancel_background_pressed: Color::hex_rgb(0x20252A),
153            danger_background: danger,
154            danger_background_pressed: Color::hex_rgb(0xB91C1C),
155            button_border: Border::new(1.0, palette.border),
156            radius: Radius::uniform(theme.radius().lg),
157            button_radius: Radius::uniform(theme.radius().md),
158            panel_width: 360.0,
159            panel_min_height: 184.0,
160            padding: 18.0,
161            button_height: 34.0,
162            button_width: 96.0,
163            gap: 10.0,
164        }
165    }
166}
167
168/// A modal confirmation overlay with controlled, bound, or internal visibility.
169///
170/// Confirm activation runs the confirm action and requests close. Cancel-button,
171/// backdrop, and Escape activation run the cancel action and request close.
172/// In controlled mode, close cannot mutate the supplied binding; the consumer
173/// must update it. Bound mode writes `false`, and internal mode updates retained
174/// state. Disabled state hides the dialog without changing visibility state.
175/// The optional child remains the underlying host content.
176///
177/// # Examples
178///
179/// ```
180/// use ailloli_ui_widgets::controls::Dialog;
181/// let dialog: Dialog<()> = Dialog::new().title("Unsaved changes?").default_open(true);
182/// let _ = dialog;
183/// ```
184pub struct Dialog<A = ()> {
185    /// Layout configuration for the full host slot.
186    pub(crate) layout: LayoutStyle,
187    /// Flex-item behavior used by the parent layout.
188    pub(crate) flex_item: FlexItemStyle,
189    /// Optional controlled or bound visibility source.
190    open: Option<Binding<bool>>,
191    /// Writable visibility signal in bound mode only.
192    bound_open: Option<Signal<bool>>,
193    /// Initial internal visibility used only without an external binding.
194    default_open: bool,
195    /// Live disabled state; disabled open dialogs are hidden but remain open.
196    disabled: Binding<bool>,
197    /// Live title text.
198    title: Binding<String>,
199    /// Live wrapping body text.
200    body: Binding<String>,
201    /// Live confirm-button label.
202    confirm_label: Binding<String>,
203    /// Live cancel-button label.
204    cancel_label: Binding<String>,
205    /// Semantic confirm treatment.
206    tone: DialogTone,
207    /// Resolved paint and geometry.
208    style: DialogStyle,
209    /// Optional confirm action.
210    on_confirm: Option<Rc<ClickAction<A>>>,
211    /// Optional cancellation action.
212    on_cancel: Option<Rc<ClickAction<A>>>,
213    /// Optional submit action used by non-repeated Enter in composed modal content.
214    on_submit: Option<Rc<ClickAction<A>>>,
215    /// Optional retained modal content replacing the fixed confirmation surface.
216    modal_content: Option<View<A>>,
217    /// Optional sole host child painted under the overlay.
218    child: Option<View<A>>,
219}
220
221crate::impl_layout_builders!(Dialog);
222
223impl<A: 'static> Default for Dialog<A> {
224    fn default() -> Self {
225        Self::new()
226    }
227}
228
229impl<A: 'static> Dialog<A> {
230    /// Creates a closed, enabled, internally managed neutral dialog.
231    ///
232    /// Default labels are `"Dialog"`, `"Confirm"`, and `"Cancel"`; body text is
233    /// empty and no actions or host child are installed.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use ailloli_ui_widgets::controls::Dialog;
239    /// let dialog: Dialog<()> = Dialog::new();
240    /// let _ = dialog;
241    /// ```
242    pub fn new() -> Self {
243        Self {
244            layout: LayoutStyle::default(),
245            flex_item: FlexItemStyle::default(),
246            open: None,
247            bound_open: None,
248            default_open: false,
249            disabled: Binding::Static(false),
250            title: Binding::Static("Dialog".to_string()),
251            body: Binding::Static(String::new()),
252            confirm_label: Binding::Static("Confirm".to_string()),
253            cancel_label: Binding::Static("Cancel".to_string()),
254            tone: DialogTone::Neutral,
255            style: DialogStyle::default(),
256            on_confirm: None,
257            on_cancel: None,
258            on_submit: None,
259            modal_content: None,
260            child: None,
261        }
262    }
263
264    /// Sets controlled static or reactive visibility.
265    ///
266    /// This clears writable bound mode. Confirm/cancel still run and consume
267    /// their input, but the dialog remains open until the external source reads
268    /// `false`.
269    ///
270    /// # Examples
271    ///
272    /// ```
273    /// use ailloli_ui_widgets::controls::Dialog;
274    /// let dialog: Dialog<()> = Dialog::new().open(true);
275    /// let _ = dialog;
276    /// ```
277    pub fn open(mut self, open: impl Into<Binding<bool>>) -> Self {
278        self.open = Some(open.into());
279        self.bound_open = None;
280        self
281    }
282
283    /// Installs a writable visibility signal for two-way close behavior.
284    ///
285    /// Confirm, cancel, backdrop, and Escape paths set the signal to `false`.
286    /// A later [`Self::open`] call returns to controlled mode.
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// use std::{cell::RefCell, rc::Rc};
292    /// use ailloli_ui_runtime::component::Signal;
293    /// use ailloli_ui_widgets::controls::Dialog;
294    /// let open = Signal::new(Rc::new(RefCell::new(true)), Rc::new(|| {}));
295    /// let dialog: Dialog<()> = Dialog::new().bind_open(open);
296    /// let _ = dialog;
297    /// ```
298    pub fn bind_open(mut self, open: impl Into<Signal<bool>>) -> Self {
299        let signal = open.into();
300        self.open = Some(Binding::Signal(signal.clone()));
301        self.bound_open = Some(signal);
302        self
303    }
304
305    /// Sets initial retained visibility for internal mode.
306    ///
307    /// This value is ignored when [`Self::open`] or [`Self::bind_open`] supplies
308    /// external visibility. It initializes state during first component build;
309    /// it is not a recurring reopen command.
310    ///
311    /// # Examples
312    ///
313    /// ```
314    /// use ailloli_ui_widgets::controls::Dialog;
315    /// let dialog: Dialog<()> = Dialog::new().default_open(true);
316    /// let _ = dialog;
317    /// ```
318    pub fn default_open(mut self, open: bool) -> Self {
319        self.default_open = open;
320        self
321    }
322
323    /// Sets a static or reactive disabled binding.
324    ///
325    /// Disabled state hides overlay paint/hit bounds, ignores events, and
326    /// removes focusability without closing or resetting visibility state.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use ailloli_ui_widgets::controls::Dialog;
332    /// let dialog: Dialog<()> = Dialog::new().open(true).disabled(true);
333    /// let _ = dialog;
334    /// ```
335    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
336        self.disabled = disabled.into();
337        self
338    }
339
340    /// Replaces static or reactive title text.
341    ///
342    /// Empty text is valid and paints no glyphs while retaining title geometry.
343    ///
344    /// # Examples
345    ///
346    /// ```
347    /// use ailloli_ui_widgets::controls::Dialog;
348    /// let dialog: Dialog<()> = Dialog::new().title("Delete project?");
349    /// let _ = dialog;
350    /// ```
351    pub fn title(mut self, title: impl Into<Binding<String>>) -> Self {
352        self.title = title.into();
353        self
354    }
355
356    /// Replaces static or reactive wrapping body text.
357    ///
358    /// Empty body reserves one nominal line; any non-empty body reserves two
359    /// nominal lines before layout constraints, independently of actual wraps.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use ailloli_ui_widgets::controls::Dialog;
365    /// let dialog: Dialog<()> = Dialog::new().body("This operation cannot be undone.");
366    /// let _ = dialog;
367    /// ```
368    pub fn body(mut self, body: impl Into<Binding<String>>) -> Self {
369        self.body = body.into();
370        self
371    }
372
373    /// Replaces static or reactive confirm-button text.
374    ///
375    /// # Examples
376    ///
377    /// ```
378    /// use ailloli_ui_widgets::controls::Dialog;
379    /// let dialog: Dialog<()> = Dialog::new().confirm_label("Delete");
380    /// let _ = dialog;
381    /// ```
382    pub fn confirm_label(mut self, label: impl Into<Binding<String>>) -> Self {
383        self.confirm_label = label.into();
384        self
385    }
386
387    /// Replaces static or reactive cancel-button text.
388    ///
389    /// # Examples
390    ///
391    /// ```
392    /// use ailloli_ui_widgets::controls::Dialog;
393    /// let dialog: Dialog<()> = Dialog::new().cancel_label("Keep editing");
394    /// let _ = dialog;
395    /// ```
396    pub fn cancel_label(mut self, label: impl Into<Binding<String>>) -> Self {
397        self.cancel_label = label.into();
398        self
399    }
400
401    /// Sets semantic tone and replaces the complete style from the default theme.
402    ///
403    /// This discards custom style values installed earlier.
404    ///
405    /// # Examples
406    ///
407    /// ```
408    /// use ailloli_ui_widgets::controls::{Dialog, DialogTone};
409    /// let dialog: Dialog<()> = Dialog::new().tone(DialogTone::Danger);
410    /// let _ = dialog;
411    /// ```
412    pub fn tone(mut self, tone: DialogTone) -> Self {
413        self.tone = tone;
414        self.style = DialogStyle::from_theme(Theme::default(), tone);
415        self
416    }
417
418    /// Replaces the complete resolved style without changing semantic tone.
419    ///
420    /// A later [`Self::tone`] call replaces this custom style. Geometry values
421    /// are otherwise accepted as-is.
422    ///
423    /// # Examples
424    ///
425    /// ```
426    /// use ailloli_ui_core::Theme;
427    /// use ailloli_ui_widgets::controls::{Dialog, DialogStyle, DialogTone};
428    /// let style = DialogStyle::from_theme(Theme::dark(), DialogTone::Neutral);
429    /// let dialog: Dialog<()> = Dialog::new().dialog_style(style);
430    /// let _ = dialog;
431    /// ```
432    pub fn dialog_style(mut self, style: DialogStyle) -> Self {
433        self.style = style;
434        self
435    }
436
437    /// Installs an action run before a confirm close request.
438    ///
439    /// A later call replaces it. Clicking confirm closes even without an action.
440    /// Keyboard Enter does not currently synthesize confirmation.
441    ///
442    /// # Examples
443    ///
444    /// ```
445    /// use ailloli_ui_widgets::controls::Dialog;
446    /// #[derive(Clone)]
447    /// enum Action { Confirm }
448    /// let dialog = Dialog::new().on_confirm(Action::Confirm);
449    /// let _ = dialog;
450    /// ```
451    pub fn on_confirm(mut self, action: impl IntoClickAction<A>) -> Self {
452        self.on_confirm = Some(Rc::new(action.into_click_action()));
453        self
454    }
455
456    /// Installs an action run before cancellation closes are requested.
457    ///
458    /// The action covers cancel-button, backdrop, and Escape paths. A later call
459    /// replaces it; cancellation closes even without an action.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use ailloli_ui_widgets::controls::Dialog;
465    /// #[derive(Clone)]
466    /// enum Action { Cancel }
467    /// let dialog = Dialog::new().on_cancel(Action::Cancel);
468    /// let _ = dialog;
469    /// ```
470    pub fn on_cancel(mut self, action: impl IntoClickAction<A>) -> Self {
471        self.on_cancel = Some(Rc::new(action.into_click_action()));
472        self
473    }
474
475    /// Installs the action invoked by a non-repeated Enter key in composed modal content.
476    ///
477    /// Descendants receive the event first; a descendant which consumes Enter prevents
478    /// this fallback submission. The fixed confirmation surface keeps its historical
479    /// pointer-only confirmation behavior.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use ailloli_ui_widgets::controls::Dialog;
485    /// let dialog = Dialog::new().on_submit(());
486    /// let _ = dialog;
487    /// ```
488    pub fn on_submit(mut self, action: impl IntoClickAction<A>) -> Self {
489        self.on_submit = Some(Rc::new(action.into_click_action()));
490        self
491    }
492
493    /// Replaces the fixed confirmation panel with retained, declarative modal content.
494    ///
495    /// The content is mounted in a full-viewport retained overlay and may freely compose
496    /// `Text`, `TextInput`, `Button`, `ScrollView`, and layout widgets. The host child set
497    /// by [`Self::child`] remains mounted below the modal.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use ailloli_ui_widgets::{controls::Dialog, text::Text};
503    /// let dialog = Dialog::<()>::new().modal_content(Text::new("Settings"));
504    /// let _ = dialog;
505    /// ```
506    pub fn modal_content(mut self, content: impl IntoView<A>) -> Self {
507        self.modal_content = Some(content.into_view());
508        self
509    }
510
511    /// Sets the sole underlying host child, replacing any previous child.
512    ///
513    /// The child fills the resolved host slot and remains painted while the
514    /// dialog overlay is open.
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// use ailloli_ui_widgets::controls::Dialog;
520    /// use ailloli_ui_widgets::text::Text;
521    /// let dialog = Dialog::<()>::new().child(Text::new("Workspace"));
522    /// let _ = dialog;
523    /// ```
524    pub fn child(mut self, child: impl IntoView<A>) -> Self {
525        self.child = Some(child.into_view());
526        self
527    }
528}
529
530/// Component properties used to allocate internal visibility state.
531struct DialogComponent<A> {
532    /// Outer logical sizing policy for the underlying host child.
533    layout: LayoutStyle,
534    /// Optional readable external open state.
535    open: Option<Binding<bool>>,
536    /// Optional writable external open state.
537    bound_open: Option<Signal<bool>>,
538    /// Initial open state used by an uncontrolled dialog.
539    default_open: bool,
540    /// Reactive interaction-disable flag.
541    disabled: Binding<bool>,
542    /// Reactive user-visible dialog title.
543    title: Binding<String>,
544    /// Reactive user-visible dialog body.
545    body: Binding<String>,
546    /// Reactive confirm-button label.
547    confirm_label: Binding<String>,
548    /// Reactive cancel-button label.
549    cancel_label: Binding<String>,
550    /// Semantic color tone for the confirm action.
551    tone: DialogTone,
552    /// Surface, backdrop, and logical-pixel geometry.
553    style: DialogStyle,
554    /// Optional confirm action shared by pointer and keyboard activation.
555    on_confirm: Option<Rc<ClickAction<A>>>,
556    /// Optional cancel action shared by button, Escape, and outside dismissal.
557    on_cancel: Option<Rc<ClickAction<A>>>,
558    /// Optional Enter fallback for composed modal content.
559    on_submit: Option<Rc<ClickAction<A>>>,
560    /// Optional retained modal subtree.
561    modal_content: Option<View<A>>,
562    /// Optional underlying host content painted below the modal overlay.
563    child: Option<View<A>>,
564}
565
566impl<A: 'static> ComponentNode<A> for DialogComponent<A> {
567    fn build(&self, context: &mut Context<A>) -> View<A> {
568        let internal_open = context.signal(self.default_open);
569        let popup = self.modal_content.as_ref().map(|content| {
570            let content = content.clone();
571            let open = self.open.clone();
572            let bound_open = self.bound_open.clone();
573            let internal_open_for_surface = internal_open.clone();
574            let disabled = self.disabled.clone();
575            let on_cancel = self.on_cancel.clone();
576            let on_submit = self.on_submit.clone();
577            let style = self.style.clone();
578            PopupPortalBridge::new_retained_with_content(
579                context,
580                PopupSemantics::new()
581                    .with_role(PopupRole::Dialog)
582                    .with_focus_policy(PopupFocusPolicy::TrapWithinPopup)
583                    .dismiss_on_outside_press(false)
584                    .dismiss_on_escape(false),
585                false,
586                PopupContent::new(move || {
587                    View::node(
588                        ModalSurfaceWidget {
589                            open: open.clone(),
590                            bound_open: bound_open.clone(),
591                            internal_open: internal_open_for_surface.clone(),
592                            disabled: disabled.clone(),
593                            on_cancel: on_cancel.clone(),
594                            on_submit: on_submit.clone(),
595                            style: style.clone(),
596                        },
597                        vec![content.clone()],
598                    )
599                }),
600            )
601        });
602        let mut children = Vec::new();
603        if let Some(child) = self.child.clone() {
604            children.push(child);
605        }
606        View::node(
607            DialogWidget {
608                layout: self.layout,
609                open: self.open.clone(),
610                bound_open: self.bound_open.clone(),
611                internal_open,
612                disabled: self.disabled.clone(),
613                title: self.title.clone(),
614                body: self.body.clone(),
615                confirm_label: self.confirm_label.clone(),
616                cancel_label: self.cancel_label.clone(),
617                tone: self.tone,
618                style: self.style.clone(),
619                on_confirm: self.on_confirm.clone(),
620                on_cancel: self.on_cancel.clone(),
621                popup,
622                pending_portal: Cell::new(None),
623                pending_legacy_paint: RefCell::new(None),
624                committed_legacy_paint: RefCell::new(None),
625            },
626            children,
627        )
628    }
629}
630
631impl<A: 'static> IntoView<A> for Dialog<A> {
632    fn into_view(self) -> View<A> {
633        finish_view_sized(
634            View::component(DialogComponent {
635                layout: self.layout,
636                open: self.open,
637                bound_open: self.bound_open,
638                default_open: self.default_open,
639                disabled: self.disabled,
640                title: self.title,
641                body: self.body,
642                confirm_label: self.confirm_label,
643                cancel_label: self.cancel_label,
644                tone: self.tone,
645                style: self.style,
646                on_confirm: self.on_confirm,
647                on_cancel: self.on_cancel,
648                on_submit: self.on_submit,
649                modal_content: self.modal_content,
650                child: self.child,
651            }),
652            self.flex_item,
653            LayoutSizeHint::from_layout(self.layout),
654        )
655    }
656}
657
658/// Retained overlay widget resolving visibility and modal event paths.
659struct DialogWidget<A> {
660    /// Outer logical sizing policy for the underlying host child.
661    layout: LayoutStyle,
662    /// Optional readable external open state.
663    open: Option<Binding<bool>>,
664    /// Optional writable external open state.
665    bound_open: Option<Signal<bool>>,
666    /// Retained open state used by an uncontrolled dialog.
667    internal_open: Signal<bool>,
668    /// Reactive interaction-disable flag.
669    disabled: Binding<bool>,
670    /// Reactive user-visible dialog title.
671    title: Binding<String>,
672    /// Reactive user-visible dialog body.
673    body: Binding<String>,
674    /// Reactive confirm-button label.
675    confirm_label: Binding<String>,
676    /// Reactive cancel-button label.
677    cancel_label: Binding<String>,
678    /// Semantic color tone for the confirm action.
679    tone: DialogTone,
680    /// Surface, backdrop, and logical-pixel geometry.
681    style: DialogStyle,
682    /// Optional retained confirm action.
683    on_confirm: Option<Rc<ClickAction<A>>>,
684    /// Optional retained cancel action.
685    on_cancel: Option<Rc<ClickAction<A>>>,
686    /// Retained portal used only by composed modal content.
687    popup: Option<PopupPortalBridge<A>>,
688    /// Visibility and full-viewport geometry staged by authoritative layout.
689    pending_portal: Cell<Option<TransactionalLayoutPending<DialogPortalState>>>,
690    /// Text artifacts staged by the exact authoritative legacy layout.
691    pending_legacy_paint: RefCell<Option<TransactionalLayoutPending<LegacyDialogPaint>>>,
692    /// Text artifacts published only after successful layout commit.
693    committed_legacy_paint: RefCell<Option<LegacyDialogPaint>>,
694}
695
696#[derive(Clone, Copy)]
697struct DialogPortalState {
698    open: bool,
699    bounds: Rect,
700}
701
702#[derive(Clone)]
703struct LegacyDialogPaint {
704    size: Size,
705    title: TextLayoutHandle,
706    body: TextLayoutHandle,
707    cancel: TextLayoutHandle,
708    confirm: TextLayoutHandle,
709}
710
711/// Full-viewport retained modal shell mounted in the runtime popup tree.
712struct ModalSurfaceWidget<A> {
713    open: Option<Binding<bool>>,
714    bound_open: Option<Signal<bool>>,
715    internal_open: Signal<bool>,
716    disabled: Binding<bool>,
717    on_cancel: Option<Rc<ClickAction<A>>>,
718    on_submit: Option<Rc<ClickAction<A>>>,
719    style: DialogStyle,
720}
721
722impl<A: 'static> ModalSurfaceWidget<A> {
723    fn close(&self) {
724        if let Some(bound) = &self.bound_open {
725            bound.set(false);
726        } else if self.open.is_none() {
727            self.internal_open.set(false);
728        }
729    }
730
731    fn cancel(&self, ctx: &mut EventCtx<A>) {
732        if let Some(action) = &self.on_cancel {
733            action.run(ctx);
734        }
735        self.close();
736        ctx.request_layout();
737        ctx.stop_propagation();
738    }
739}
740
741impl<A: 'static> Widget<A> for ModalSurfaceWidget<A> {
742    fn debug_name(&self) -> &'static str {
743        "DialogModalSurface"
744    }
745
746    fn layout(
747        &self,
748        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
749        ctx: &mut LayoutCtx<'_>,
750        children: &mut [LayoutChild],
751        constraints: Constraints,
752    ) -> LayoutResult {
753        let size = constraints.constrain(Size::new(
754            finite_or(constraints.max_w, constraints.min_w),
755            finite_or(constraints.max_h, constraints.min_h),
756        ));
757        let mut child_layouts = Vec::new();
758        if let Some(child) = children.first_mut() {
759            let available_width = self.style.panel_width.min((size.w - 48.0).max(180.0));
760            let available_height = (size.h - 48.0).max(self.style.panel_min_height);
761            let result = child.layout(
762                engine,
763                ctx,
764                Constraints::loose(available_width, available_height),
765            );
766            let child_size = Size::new(
767                result.size.w.min(available_width),
768                result
769                    .size
770                    .h
771                    .max(self.style.panel_min_height)
772                    .min(available_height),
773            );
774            let offset = Offset::new((size.w - child_size.w) * 0.5, (size.h - child_size.h) * 0.5);
775            child_layouts.push(ChildLayout {
776                offset,
777                size: child_size,
778                paint_bounds: Rect::new(offset.x, offset.y, child_size.w, child_size.h),
779                visual_bounds: Rect::new(offset.x, offset.y, child_size.w, child_size.h),
780            });
781        }
782        let bounds = Rect::new(0.0, 0.0, size.w, size.h);
783        LayoutResult {
784            size,
785            children: child_layouts,
786            paint_bounds: bounds,
787            visual_bounds: bounds,
788            // The retained popup tree is already the topmost presentation. Keeping
789            // the full viewport in the overlay stratum would make this ancestor win
790            // before its TextInput/Button descendants are considered. Its base hit
791            // bounds still receive backdrop presses after descendant hit-testing.
792            overlay_hit_bounds: Vec::new(),
793            clip: None,
794            is_window_root_clip: false,
795            artifact: None,
796        }
797    }
798
799    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
800        ctx.push(DrawCmd::Rect(DrawRect {
801            rect: bounds,
802            color: self.style.backdrop,
803        }));
804        if let Some(child) = layout.children.first() {
805            let panel = Rect::new(
806                bounds.x + child.offset.x,
807                bounds.y + child.offset.y,
808                child.size.w,
809                child.size.h,
810            );
811            for shadow in self
812                .style
813                .shadows
814                .iter()
815                .copied()
816                .filter(|shadow| !shadow.inset)
817            {
818                ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
819                    rect: panel,
820                    radius: self.style.radius,
821                    shadow,
822                }));
823            }
824            ctx.push(DrawCmd::RRect(DrawRRect {
825                rect: panel,
826                radius: self.style.radius.tl,
827                color: self.style.panel_background,
828            }));
829            if self.style.border.is_visible() {
830                ctx.push(DrawCmd::Border(DrawBorder {
831                    rect: panel,
832                    radius: self.style.radius,
833                    border: self.style.border,
834                }));
835            }
836        }
837    }
838
839    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
840        if self.disabled.read() {
841            return;
842        }
843        match event {
844            Event::Keyboard(key)
845                if key.state == KeyState::Pressed
846                    && !key.repeat
847                    && matches!(
848                        key.key,
849                        ailloli_ui_core::event::Key::Named(NamedKey::Escape)
850                    ) =>
851            {
852                self.cancel(ctx);
853            }
854            Event::Keyboard(key)
855                if key.state == KeyState::Pressed
856                    && !key.repeat
857                    && matches!(key.key, ailloli_ui_core::event::Key::Named(NamedKey::Enter)) =>
858            {
859                if let Some(action) = &self.on_submit {
860                    action.run(ctx);
861                    self.close();
862                    ctx.request_layout();
863                    ctx.stop_propagation();
864                }
865            }
866            Event::Pointer(PointerEvent::Button {
867                pos,
868                button: MouseButton::Left,
869                pressed: false,
870                ..
871            }) => {
872                let inside_panel = layout.children.first().is_some_and(|child| {
873                    Rect::new(
874                        bounds.x + child.offset.x,
875                        bounds.y + child.offset.y,
876                        child.size.w,
877                        child.size.h,
878                    )
879                    .contains(pos.x, pos.y)
880                });
881                if !inside_panel {
882                    self.cancel(ctx);
883                }
884            }
885            _ => {}
886        }
887    }
888
889    fn focus_policy(&self) -> FocusPolicy {
890        FocusPolicy::Focusable
891    }
892}
893
894impl<A: 'static> Widget<A> for DialogWidget<A> {
895    fn debug_name(&self) -> &'static str {
896        "Dialog"
897    }
898
899    fn layout(
900        &self,
901        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
902        ctx: &mut LayoutCtx<'_>,
903        children: &mut [LayoutChild],
904        constraints: Constraints,
905    ) -> LayoutResult {
906        let size = host_slot_size(engine, ctx, children, constraints, self.layout);
907        let mut child_layouts = Vec::new();
908        if let Some(child) = children.first_mut() {
909            let r = ctx.with_layout_pass(LayoutPass::Commit, |ctx| {
910                child.layout(engine, ctx, Constraints::tight(size.w, size.h))
911            });
912            child_layouts.push(ChildLayout {
913                offset: Offset::default(),
914                size: r.size,
915                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
916                visual_bounds: r.visual_bounds,
917            });
918        }
919        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
920        let overlay_hit_bounds = if self.is_open() && !self.disabled.read() {
921            if self.popup.is_some() {
922                Vec::new()
923            } else {
924                vec![paint_bounds]
925            }
926        } else {
927            Vec::new()
928        };
929        if ctx.layout_pass().is_committed() {
930            let open = self.is_open() && !self.disabled.read();
931            self.pending_portal.set(TransactionalLayoutPending::new(
932                ctx,
933                DialogPortalState {
934                    open,
935                    bounds: paint_bounds,
936                },
937            ));
938            if self.popup.is_none() {
939                let title = self.title.read();
940                let body = self.body.read();
941                let cancel = self.cancel_label.read();
942                let confirm = self.confirm_label.read();
943                let prepared = ctx
944                    .text_system
945                    .as_deref_mut()
946                    .map(|text| LegacyDialogPaint {
947                        size,
948                        title: text.layout_cached(TextLayoutParams {
949                            text: &title,
950                            style: self.style.title_text,
951                            max_width: Some(
952                                (self.style.panel_width - self.style.padding * 2.0).max(0.0),
953                            ),
954                            wrap_mode: WrapMode::NoWrap,
955                        }),
956                        body: text.layout_cached(TextLayoutParams {
957                            text: &body,
958                            style: self.style.body_text,
959                            max_width: Some(
960                                (self.style.panel_width - self.style.padding * 2.0).max(0.0),
961                            ),
962                            wrap_mode: WrapMode::WordOrAnywhere,
963                        }),
964                        cancel: text.layout_cached(TextLayoutParams {
965                            text: &cancel,
966                            style: self.style.button_text,
967                            max_width: Some(self.style.button_width),
968                            wrap_mode: WrapMode::NoWrap,
969                        }),
970                        confirm: text.layout_cached(TextLayoutParams {
971                            text: &confirm,
972                            style: self.style.button_text,
973                            max_width: Some(self.style.button_width),
974                            wrap_mode: WrapMode::NoWrap,
975                        }),
976                    });
977                self.pending_legacy_paint.replace(
978                    prepared.and_then(|paint| TransactionalLayoutPending::new(ctx, paint)),
979                );
980            }
981        }
982
983        LayoutResult {
984            size,
985            children: child_layouts,
986            paint_bounds,
987            visual_bounds: paint_bounds,
988            overlay_hit_bounds,
989            clip: None,
990            is_window_root_clip: false,
991            artifact: None,
992        }
993    }
994
995    fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
996
997    fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
998        if let Some(state) = self
999            .pending_portal
1000            .take()
1001            .and_then(|pending| pending.into_committed(ctx))
1002        {
1003            if let Some(popup) = &self.popup {
1004                if state.open {
1005                    let popup_bounds =
1006                        Rect::new(bounds.x, bounds.y, state.bounds.w, state.bounds.h);
1007                    popup.open_without_event(popup_bounds, popup_bounds);
1008                } else {
1009                    popup.close(PopupDismissReason::Programmatic);
1010                }
1011            }
1012        }
1013        if let Some(paint) = self
1014            .pending_legacy_paint
1015            .borrow_mut()
1016            .take()
1017            .and_then(|pending| pending.into_committed(ctx))
1018        {
1019            self.committed_legacy_paint.replace(Some(paint));
1020        }
1021    }
1022
1023    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1024        if self.popup.is_some() || !self.is_open() || self.disabled.read() {
1025            return;
1026        }
1027        let paint = self.committed_legacy_paint.borrow();
1028        let Some(paint) = paint
1029            .as_ref()
1030            .filter(|paint| paint.size == Size::new(bounds.w, bounds.h))
1031        else {
1032            return;
1033        };
1034        self.paint_dialog(ctx, bounds, paint);
1035    }
1036
1037    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1038        if !self.is_open() || self.disabled.read() {
1039            return;
1040        }
1041
1042        match event {
1043            Event::Pointer(PointerEvent::Button {
1044                pos,
1045                button: MouseButton::Left,
1046                pressed: false,
1047                ..
1048            }) => {
1049                let panel = self.panel_rect(bounds);
1050                if self.confirm_rect(panel).contains(pos.x, pos.y) {
1051                    if let Some(action) = &self.on_confirm {
1052                        action.run(ctx);
1053                    }
1054                    self.close();
1055                    ctx.request_repaint();
1056                    ctx.stop_propagation();
1057                } else if self.cancel_rect(panel).contains(pos.x, pos.y)
1058                    || !panel.contains(pos.x, pos.y)
1059                {
1060                    self.cancel(ctx);
1061                }
1062            }
1063            Event::Keyboard(key)
1064                if key.state == KeyState::Pressed
1065                    && matches!(
1066                        key.key,
1067                        ailloli_ui_core::event::Key::Named(NamedKey::Escape)
1068                    ) =>
1069            {
1070                self.cancel(ctx);
1071            }
1072            _ => {}
1073        }
1074    }
1075
1076    fn focus_policy(&self) -> FocusPolicy {
1077        if self.is_open() && !self.disabled.read() {
1078            FocusPolicy::Focusable
1079        } else {
1080            FocusPolicy::NotFocusable
1081        }
1082    }
1083}
1084
1085impl<A: 'static> DialogWidget<A> {
1086    /// Reads controlled/bound visibility, falling back to retained internal state.
1087    fn is_open(&self) -> bool {
1088        self.open
1089            .as_ref()
1090            .map(Binding::read)
1091            .unwrap_or_else(|| self.internal_open.read())
1092    }
1093
1094    /// Writes `false` only in bound or internal mode.
1095    fn close(&self) {
1096        if let Some(bound) = &self.bound_open {
1097            bound.set(false);
1098        } else if self.open.is_none() {
1099            self.internal_open.set(false);
1100        }
1101    }
1102
1103    /// Runs the optional cancel action, requests close/repaint, and consumes input.
1104    fn cancel(&self, ctx: &mut EventCtx<A>) {
1105        if let Some(action) = &self.on_cancel {
1106            action.run(ctx);
1107        }
1108        self.close();
1109        ctx.request_repaint();
1110        ctx.stop_propagation();
1111    }
1112
1113    /// Centers the preferred panel, reserving 24 pixels per horizontal host edge.
1114    fn panel_rect(&self, bounds: Rect) -> Rect {
1115        let width = self.style.panel_width.min((bounds.w - 48.0).max(180.0));
1116        let body_lines = if self.body.read().is_empty() {
1117            1.0
1118        } else {
1119            2.0
1120        };
1121        let height = self
1122            .style
1123            .panel_min_height
1124            .max(self.style.padding * 2.0 + 28.0 + 18.0 * body_lines + 46.0);
1125        Rect::new(
1126            bounds.x + (bounds.w - width) * 0.5,
1127            bounds.y + (bounds.h - height) * 0.5,
1128            width,
1129            height,
1130        )
1131    }
1132
1133    /// Places the confirm button at the panel's bottom-right padding inset.
1134    fn confirm_rect(&self, panel: Rect) -> Rect {
1135        Rect::new(
1136            panel.right() - self.style.padding - self.style.button_width,
1137            panel.bottom() - self.style.padding - self.style.button_height,
1138            self.style.button_width,
1139            self.style.button_height,
1140        )
1141    }
1142
1143    /// Places the cancel button immediately left of confirm with the style gap.
1144    fn cancel_rect(&self, panel: Rect) -> Rect {
1145        let confirm = self.confirm_rect(panel);
1146        Rect::new(
1147            confirm.x - self.style.gap - self.style.button_width,
1148            confirm.y,
1149            self.style.button_width,
1150            self.style.button_height,
1151        )
1152    }
1153
1154    /// Paints backdrop, non-inset shadows, panel, text, buttons, then border.
1155    fn paint_dialog(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, paint: &LegacyDialogPaint) {
1156        ctx.push_overlay(DrawCmd::Rect(DrawRect {
1157            rect: bounds,
1158            color: self.style.backdrop,
1159        }));
1160
1161        let panel = self.panel_rect(bounds);
1162        for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
1163            ctx.push_overlay(DrawCmd::BoxShadow(DrawBoxShadow {
1164                rect: panel,
1165                radius: self.style.radius,
1166                shadow,
1167            }));
1168        }
1169        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1170            rect: panel,
1171            radius: self.style.radius.tl,
1172            color: self.style.panel_background,
1173        }));
1174
1175        let title = Rect::new(
1176            panel.x + self.style.padding,
1177            panel.y + self.style.padding - 2.0,
1178            panel.w - self.style.padding * 2.0,
1179            28.0,
1180        );
1181        push_prepared_text(ctx, title, self.style.title_text, &paint.title, false);
1182
1183        let body_y = title.bottom() + 10.0;
1184        let button_top = self.cancel_rect(panel).y;
1185        let body = Rect::new(
1186            panel.x + self.style.padding,
1187            body_y,
1188            panel.w - self.style.padding * 2.0,
1189            (button_top - body_y - 10.0).max(0.0),
1190        );
1191        push_prepared_text(ctx, body, self.style.body_text, &paint.body, false);
1192
1193        self.paint_button(
1194            ctx,
1195            self.cancel_rect(panel),
1196            &paint.cancel,
1197            self.style.cancel_background,
1198            self.style.cancel_background_pressed,
1199        );
1200        let confirm_bg = match self.tone {
1201            DialogTone::Neutral => self.style.primary_background,
1202            DialogTone::Danger => self.style.danger_background,
1203        };
1204        let confirm_pressed = match self.tone {
1205            DialogTone::Neutral => self.style.primary_background_pressed,
1206            DialogTone::Danger => self.style.danger_background_pressed,
1207        };
1208        self.paint_button(
1209            ctx,
1210            self.confirm_rect(panel),
1211            &paint.confirm,
1212            confirm_bg,
1213            confirm_pressed,
1214        );
1215
1216        if self.style.border.is_visible() {
1217            ctx.push_overlay(DrawCmd::Border(DrawBorder {
1218                rect: panel,
1219                radius: self.style.radius,
1220                border: self.style.border,
1221            }));
1222        }
1223    }
1224
1225    /// Paints one overlay button; the reserved pressed color is currently unused.
1226    fn paint_button(
1227        &self,
1228        ctx: &mut PaintCtx<'_>,
1229        rect: Rect,
1230        label: &TextLayoutHandle,
1231        color: Color,
1232        _pressed: Color,
1233    ) {
1234        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1235            rect,
1236            radius: self.style.button_radius.tl,
1237            color,
1238        }));
1239        if self.style.button_border.is_visible() {
1240            ctx.push_overlay(DrawCmd::Border(DrawBorder {
1241                rect,
1242                radius: self.style.button_radius,
1243                border: self.style.button_border,
1244            }));
1245        }
1246        push_prepared_text(ctx, rect, self.style.button_text, label, true);
1247    }
1248}
1249
1250fn push_prepared_text(
1251    ctx: &mut PaintCtx<'_>,
1252    rect: Rect,
1253    style: TextStyle,
1254    layout: &TextLayoutHandle,
1255    centered: bool,
1256) {
1257    let x = if centered {
1258        rect.x + ((rect.w - layout.metrics.width).max(0.0) * 0.5)
1259    } else {
1260        rect.x
1261    };
1262    let y = if centered {
1263        rect.y + rect.h * 0.5 + style.px_size as f32 * 0.35
1264    } else {
1265        rect.y + style.px_size as f32
1266    };
1267    ctx.push_overlay(DrawCmd::Text(DrawText {
1268        pos: [x, y],
1269        color: style.color,
1270        decoration: style.decoration,
1271        layout: layout.clone(),
1272    }));
1273}
1274
1275/// Resolves host size from its child or finite constraint maxima.
1276fn host_slot_size<A: 'static>(
1277    engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1278    ctx: &mut LayoutCtx<'_>,
1279    children: &mut [LayoutChild],
1280    constraints: Constraints,
1281    layout: LayoutStyle,
1282) -> Size {
1283    let intrinsic = if let Some(child) = children.first_mut() {
1284        ctx.with_layout_pass(LayoutPass::Measure, |ctx| {
1285            child.layout(engine, ctx, constraints.loosen()).size
1286        })
1287    } else {
1288        Size::new(
1289            finite_or(constraints.max_w, 0.0),
1290            finite_or(constraints.max_h, 0.0),
1291        )
1292    };
1293    apply_layout_size(intrinsic, layout, constraints)
1294}
1295
1296/// Returns `value` when finite and `fallback` for NaN or either infinity.
1297fn finite_or(value: f32, fallback: f32) -> f32 {
1298    if value.is_finite() {
1299        value
1300    } else {
1301        fallback
1302    }
1303}