Skip to main content

sui_widgets/
composites.rs

1use std::{cell::RefCell, rc::Rc, sync::Arc};
2
3use sui_core::{
4    Color, Event, InvalidationKind, InvalidationRequest, InvalidationTarget, KeyState, Path,
5    PathBuilder, Point, PointerButton, PointerEventKind, Rect, SemanticsAction, SemanticsNode,
6    SemanticsPopupKind, SemanticsRole, SemanticsState, SemanticsValue, Size, TimerToken, Transform,
7    Vector, WakeEvent, WidgetId,
8};
9use sui_layout::{
10    Alignment, Axis, Constraints, FlexAlignContent, FlexItem, FlexJustify, FlexLayout, FlexStyle,
11    FlexWrap, Padding as Insets, arrange_flex, flex_layout,
12};
13use sui_reactive::{Observable, Signal};
14use sui_runtime::{
15    ArrangeCtx, Command, EventCtx, EventPhase, LayerOptions, MeasureCtx, OVERLAY_DISMISS_REQUEST,
16    OverlayDismissPolicy, OverlayFocusBehavior, OverlayKind, OverlayOptions, PaintBoundaryMode,
17    PaintCtx, REACTIVE_CHANGED, SemanticsCtx, SingleChild, StackSurfaceOptions, Widget,
18    WidgetChildren, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
19};
20use sui_scene::{LayerCompositionMode, LayerProperties, StrokeStyle};
21use sui_text::{
22    FontFeature, FontWeight, TextAlign, TextDocument, TextLayoutRequest, TextMeasurement,
23    TextStyle, TextWrap,
24};
25
26use crate::{
27    Button, ButtonAppearance, ControlMetrics, DefaultTheme, HdrThemeMode, IconGlyph, Interpolate,
28    MotionScalar, ResolvedEffectStyle, ResolvedHdrStyle, SemanticTone, ThemeTextToken,
29    WidgetColorRole, WidgetEffectRole, WidgetLuminanceRole, WidgetMaterialRole,
30    controls::{apply_hdr_policy_cap, cap_resolved_hdr_style, draw_icon_glyph},
31    overlay::{
32        OverlayAlignment, OverlayPlacement, OverlayPlacementRequest, OverlaySide, place_overlay,
33    },
34    paint_theme_shadow, resolve_widget_hdr_style,
35    text_align::{paint_aligned_text, paint_single_line_aligned_text},
36};
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum TooltipPlacement {
40    Above,
41    Below,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum TooltipAlignment {
46    Start,
47    Center,
48    End,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum SurfaceRole {
53    Window,
54    Sidebar,
55    Panel,
56    Titlebar,
57    Field,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum SurfaceBorder {
62    None,
63    All,
64    Top,
65    Right,
66    Bottom,
67    Left,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum SurfaceElevation {
72    None,
73    Small,
74    Medium,
75    Large,
76}
77
78#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
79pub enum SurfaceAppearance {
80    /// The surface token associated with [`SurfaceRole`].
81    #[default]
82    Standard,
83    /// The shared raised-surface token, useful for elevated chips and cards.
84    Raised,
85    /// A low-emphasis semantic wash.
86    Soft,
87    /// A solid semantic fill.
88    Filled,
89}
90
91pub struct Surface {
92    theme: Box<DefaultTheme>,
93    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
94    name: Option<String>,
95    role: SurfaceRole,
96    appearance: SurfaceAppearance,
97    tone: SemanticTone,
98    border: SurfaceBorder,
99    elevation: SurfaceElevation,
100    radius: f32,
101    padding: Insets,
102    fill_width: bool,
103    fill_height: bool,
104    child: SingleChild,
105}
106
107impl Surface {
108    pub fn new<W>(role: SurfaceRole, child: W) -> Self
109    where
110        W: Widget + 'static,
111    {
112        Self {
113            theme: Box::new(DefaultTheme::default()),
114            theme_reader: None,
115            name: None,
116            role,
117            appearance: SurfaceAppearance::Standard,
118            tone: SemanticTone::Neutral,
119            border: SurfaceBorder::None,
120            elevation: SurfaceElevation::None,
121            radius: 0.0,
122            padding: Insets::ZERO,
123            fill_width: false,
124            fill_height: false,
125            child: SingleChild::new(child),
126        }
127    }
128
129    pub fn window<W>(child: W) -> Self
130    where
131        W: Widget + 'static,
132    {
133        Self::new(SurfaceRole::Window, child)
134    }
135
136    pub fn sidebar<W>(child: W) -> Self
137    where
138        W: Widget + 'static,
139    {
140        Self::new(SurfaceRole::Sidebar, child).border(SurfaceBorder::Right)
141    }
142
143    pub fn panel<W>(child: W) -> Self
144    where
145        W: Widget + 'static,
146    {
147        Self::new(SurfaceRole::Panel, child)
148            .border(SurfaceBorder::All)
149            .radius(8.0)
150    }
151
152    pub fn titlebar<W>(child: W) -> Self
153    where
154        W: Widget + 'static,
155    {
156        Self::new(SurfaceRole::Titlebar, child).border(SurfaceBorder::Bottom)
157    }
158
159    pub fn field<W>(child: W) -> Self
160    where
161        W: Widget + 'static,
162    {
163        Self::new(SurfaceRole::Field, child)
164            .border(SurfaceBorder::All)
165            .radius(6.0)
166    }
167
168    pub fn theme(mut self, theme: DefaultTheme) -> Self {
169        self.theme = Box::new(theme);
170        self.theme_reader = None;
171        self
172    }
173
174    pub fn theme_when<F>(mut self, theme: F) -> Self
175    where
176        F: Fn() -> DefaultTheme + 'static,
177    {
178        self.theme_reader = Some(Box::new(theme));
179        self
180    }
181
182    pub fn name(mut self, name: impl Into<String>) -> Self {
183        self.name = Some(name.into());
184        self
185    }
186
187    pub fn border(mut self, border: SurfaceBorder) -> Self {
188        self.border = border;
189        self
190    }
191
192    pub fn appearance(mut self, appearance: SurfaceAppearance) -> Self {
193        self.appearance = appearance;
194        self
195    }
196
197    pub fn tone(mut self, tone: SemanticTone) -> Self {
198        self.tone = tone;
199        self
200    }
201
202    pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
203        self.elevation = elevation;
204        self
205    }
206
207    pub fn radius(mut self, radius: f32) -> Self {
208        self.radius = radius.max(0.0);
209        self
210    }
211
212    pub fn padding(mut self, padding: Insets) -> Self {
213        self.padding = padding;
214        self
215    }
216
217    pub fn fill(mut self) -> Self {
218        self.fill_width = true;
219        self.fill_height = true;
220        self
221    }
222
223    pub fn fill_width(mut self) -> Self {
224        self.fill_width = true;
225        self
226    }
227
228    pub fn fill_height(mut self) -> Self {
229        self.fill_height = true;
230        self
231    }
232
233    fn resolved_theme(&self) -> DefaultTheme {
234        self.theme_reader
235            .as_ref()
236            .map(|theme| theme())
237            .unwrap_or(*self.theme)
238    }
239
240    fn background_for_role(theme: &DefaultTheme, role: SurfaceRole) -> Color {
241        match role {
242            SurfaceRole::Window => theme.surfaces.window,
243            SurfaceRole::Sidebar => theme.surfaces.sidebar,
244            SurfaceRole::Panel => theme.surfaces.panel,
245            SurfaceRole::Titlebar => theme.surfaces.titlebar,
246            SurfaceRole::Field => theme.surfaces.field,
247        }
248    }
249
250    fn resolved_colors(&self, theme: &DefaultTheme) -> (Color, Color) {
251        match self.appearance {
252            SurfaceAppearance::Standard => (
253                Self::background_for_role(theme, self.role),
254                theme.surfaces.border,
255            ),
256            SurfaceAppearance::Raised => (theme.palette.surface_raised, theme.surfaces.border),
257            SurfaceAppearance::Soft => {
258                let (fill, _) = theme.semantic_tone_soft_colors(self.tone);
259                let border = if self.tone == SemanticTone::Neutral {
260                    theme.surfaces.border
261                } else {
262                    theme.semantic_tone_color(self.tone).with_alpha(0.36)
263                };
264                (fill, border)
265            }
266            SurfaceAppearance::Filled => {
267                let (fill, _) = theme.semantic_tone_colors(self.tone);
268                (fill, fill)
269            }
270        }
271    }
272
273    fn content_rect(&self, bounds: Rect) -> Rect {
274        inset_rect(bounds, self.padding)
275    }
276}
277
278impl Widget for Surface {
279    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
280        let max_child = Size::new(
281            if constraints.max.width.is_finite() {
282                (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
283            } else {
284                f32::INFINITY
285            },
286            if constraints.max.height.is_finite() {
287                (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
288            } else {
289                f32::INFINITY
290            },
291        );
292        // `arrange` always gives the child the complete content rect. Keep the
293        // measurement constraints consistent with that contract so
294        // width-dependent children (notably wrapping text in a flex item) are
295        // not measured narrowly and then stretched without being remeasured.
296        // A filling surface makes the corresponding content axis tight even
297        // when its own parent supplied loose constraints.
298        let min_child = Size::new(
299            if self.fill_width && max_child.width.is_finite() {
300                max_child.width
301            } else {
302                (constraints.min.width - self.padding.left - self.padding.right)
303                    .max(0.0)
304                    .min(max_child.width)
305            },
306            if self.fill_height && max_child.height.is_finite() {
307                max_child.height
308            } else {
309                (constraints.min.height - self.padding.top - self.padding.bottom)
310                    .max(0.0)
311                    .min(max_child.height)
312            },
313        );
314        let child_size = self
315            .child
316            .measure(ctx, Constraints::new(min_child, max_child));
317        let mut size = Size::new(
318            child_size.width + self.padding.left + self.padding.right,
319            child_size.height + self.padding.top + self.padding.bottom,
320        );
321        if self.fill_width && constraints.max.width.is_finite() {
322            size.width = constraints.max.width;
323        }
324        if self.fill_height && constraints.max.height.is_finite() {
325            size.height = constraints.max.height;
326        }
327        constraints.clamp(size)
328    }
329
330    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
331        self.child.arrange(ctx, self.content_rect(bounds));
332    }
333
334    fn paint(&self, ctx: &mut PaintCtx) {
335        let theme = self.resolved_theme();
336        let bounds = ctx.bounds();
337        let radius = self.radius.min(bounds.width().min(bounds.height()) * 0.5);
338
339        let shadow = match self.elevation {
340            SurfaceElevation::None => None,
341            SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
342            SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
343            SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
344        };
345        if let Some(shadow) = shadow {
346            paint_theme_shadow(ctx, bounds, [radius; 4], shadow);
347        }
348
349        let (background, border) = self.resolved_colors(&theme);
350        if radius > 0.0 {
351            ctx.fill(rounded_rect_path(bounds, radius), background);
352        } else {
353            ctx.fill_rect(bounds, background);
354        }
355
356        let stroke_width = physical_pixels(ctx, theme.metrics.border_width.max(1.0));
357        match self.border {
358            SurfaceBorder::None => {}
359            SurfaceBorder::All => {
360                ctx.stroke(
361                    rounded_rect_path(bounds, radius),
362                    border,
363                    StrokeStyle::new(stroke_width),
364                );
365            }
366            SurfaceBorder::Top => ctx.fill_rect(
367                Rect::new(bounds.x(), bounds.y(), bounds.width(), stroke_width),
368                border,
369            ),
370            SurfaceBorder::Right => ctx.fill_rect(
371                Rect::new(
372                    bounds.max_x() - stroke_width,
373                    bounds.y(),
374                    stroke_width,
375                    bounds.height(),
376                ),
377                border,
378            ),
379            SurfaceBorder::Bottom => ctx.fill_rect(
380                Rect::new(
381                    bounds.x(),
382                    bounds.max_y() - stroke_width,
383                    bounds.width(),
384                    stroke_width,
385                ),
386                border,
387            ),
388            SurfaceBorder::Left => ctx.fill_rect(
389                Rect::new(bounds.x(), bounds.y(), stroke_width, bounds.height()),
390                border,
391            ),
392        }
393
394        self.child.paint(ctx);
395    }
396
397    fn semantics(&self, ctx: &mut SemanticsCtx) {
398        if let Some(name) = &self.name {
399            let mut node = SemanticsNode::new(
400                ctx.widget_id(),
401                SemanticsRole::GenericContainer,
402                ctx.bounds(),
403            );
404            node.name = Some(name.clone());
405            ctx.push(node);
406        }
407        self.child.semantics(ctx);
408    }
409
410    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
411        self.child.visit_children(visitor);
412    }
413
414    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
415        self.child.visit_children_mut(visitor);
416    }
417}
418
419/// A reusable field frame for compound editors such as search/composer rows.
420///
421/// The child owns editing, focus, and semantics. The frame owns only the
422/// standard field surface and border, which avoids applications repainting
423/// control chrome around otherwise stock SUI editors. Use [`Self::focused_when`]
424/// when the wrapped editor publishes its focus state.
425pub struct FramedField {
426    theme: Box<DefaultTheme>,
427    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
428    name: Option<String>,
429    description: Option<String>,
430    padding: Insets,
431    min_height: Option<f32>,
432    fill_width: bool,
433    focused: Option<bool>,
434    focused_reader: Option<Box<dyn Fn() -> bool>>,
435    invalid: bool,
436    invalid_reader: Option<Box<dyn Fn() -> bool>>,
437    hovered: bool,
438    hover_animation: AnimatedScalar,
439    child: SingleChild,
440}
441
442impl FramedField {
443    pub fn new<W>(child: W) -> Self
444    where
445        W: Widget + 'static,
446    {
447        Self {
448            theme: Box::new(DefaultTheme::default()),
449            theme_reader: None,
450            name: None,
451            description: None,
452            padding: Insets::ZERO,
453            min_height: None,
454            fill_width: false,
455            focused: None,
456            focused_reader: None,
457            invalid: false,
458            invalid_reader: None,
459            hovered: false,
460            hover_animation: AnimatedScalar::new(0.0),
461            child: SingleChild::new(child),
462        }
463    }
464
465    pub fn theme(mut self, theme: DefaultTheme) -> Self {
466        self.theme = Box::new(theme);
467        self.theme_reader = None;
468        self
469    }
470
471    pub fn theme_when<F>(mut self, theme: F) -> Self
472    where
473        F: Fn() -> DefaultTheme + 'static,
474    {
475        self.theme_reader = Some(Box::new(theme));
476        self
477    }
478
479    pub fn name(mut self, name: impl Into<String>) -> Self {
480        self.name = Some(name.into());
481        self
482    }
483
484    pub fn description(mut self, description: impl Into<String>) -> Self {
485        self.description = Some(description.into());
486        self
487    }
488
489    pub fn padding(mut self, padding: Insets) -> Self {
490        self.padding = padding;
491        self
492    }
493
494    pub fn min_height(mut self, min_height: f32) -> Self {
495        self.min_height = Some(min_height.max(0.0));
496        self
497    }
498
499    pub fn fill_width(mut self) -> Self {
500        self.fill_width = true;
501        self
502    }
503
504    pub fn focused(mut self, focused: bool) -> Self {
505        self.focused = Some(focused);
506        self.focused_reader = None;
507        self
508    }
509
510    pub fn focused_when<F>(mut self, focused: F) -> Self
511    where
512        F: Fn() -> bool + 'static,
513    {
514        self.focused_reader = Some(Box::new(focused));
515        self
516    }
517
518    pub fn invalid(mut self, invalid: bool) -> Self {
519        self.invalid = invalid;
520        self.invalid_reader = None;
521        self
522    }
523
524    pub fn invalid_when<F>(mut self, invalid: F) -> Self
525    where
526        F: Fn() -> bool + 'static,
527    {
528        self.invalid_reader = Some(Box::new(invalid));
529        self
530    }
531
532    fn resolved_theme(&self) -> DefaultTheme {
533        self.theme_reader
534            .as_ref()
535            .map(|theme| theme())
536            .unwrap_or(*self.theme)
537    }
538
539    fn child_contains(&self, target: WidgetId) -> bool {
540        if self.child.child().id() == target {
541            return true;
542        }
543        struct Finder {
544            target: WidgetId,
545            found: bool,
546        }
547        impl WidgetPodVisitor for Finder {
548            fn visit(&mut self, child: &WidgetPod) {
549                if self.found {
550                    return;
551                }
552                if child.id() == self.target {
553                    self.found = true;
554                } else {
555                    child.visit_children(self);
556                }
557            }
558        }
559        let mut finder = Finder {
560            target,
561            found: false,
562        };
563        self.child.child().visit_children(&mut finder);
564        finder.found
565    }
566
567    fn is_focused(&self, focused_widget_id: Option<WidgetId>) -> bool {
568        if let Some(focused) = &self.focused_reader {
569            return focused();
570        }
571        if let Some(focused) = self.focused {
572            return focused;
573        }
574        focused_widget_id
575            .map(|focused| self.child_contains(focused))
576            .unwrap_or(false)
577    }
578
579    fn is_invalid(&self) -> bool {
580        self.invalid_reader
581            .as_ref()
582            .map(|invalid| invalid())
583            .unwrap_or(self.invalid)
584    }
585
586    fn content_rect(&self, bounds: Rect) -> Rect {
587        inset_rect(bounds, self.padding)
588    }
589
590    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
591        if self.hovered == hovered {
592            return;
593        }
594        self.hovered = hovered;
595        let theme = self.resolved_theme();
596        set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
597        ctx.request_paint();
598    }
599}
600
601impl Widget for FramedField {
602    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
603        match event {
604            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
605                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
606            }
607            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
608                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
609            }
610            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
611                self.set_hovered(false, ctx);
612            }
613            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
614                let previous = self.hover_animation.value;
615                if self.hover_animation.advance(*time) {
616                    ctx.request_animation_frame();
617                }
618                if self.hover_animation.changed_since(previous) {
619                    ctx.request_paint();
620                }
621            }
622            _ => {}
623        }
624    }
625
626    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
627        let max_child = Size::new(
628            if constraints.max.width.is_finite() {
629                (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
630            } else {
631                f32::INFINITY
632            },
633            if constraints.max.height.is_finite() {
634                (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
635            } else {
636                f32::INFINITY
637            },
638        );
639        let child = self
640            .child
641            .measure(ctx, Constraints::new(Size::ZERO, max_child));
642        let theme = self.resolved_theme();
643        let mut size = Size::new(
644            child.width + self.padding.left + self.padding.right,
645            (child.height + self.padding.top + self.padding.bottom)
646                .max(self.min_height.unwrap_or(theme.metrics.min_height)),
647        );
648        if self.fill_width && constraints.max.width.is_finite() {
649            size.width = constraints.max.width;
650        }
651        constraints.clamp(size)
652    }
653
654    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
655        self.child.arrange(ctx, self.content_rect(bounds));
656    }
657
658    fn paint(&self, ctx: &mut PaintCtx) {
659        let theme = self.resolved_theme();
660        let bounds = ctx.bounds();
661        let radius = theme
662            .metrics
663            .corner_radius
664            .min(bounds.width().min(bounds.height()) * 0.5);
665        let invalid = self.is_invalid();
666        let focused = self.is_focused(ctx.focused_widget_id());
667        let interaction_border = mix_color(
668            theme.palette.border,
669            theme.palette.border_hover,
670            self.hover_animation.value,
671        );
672        let border = if invalid {
673            theme.semantic_tone_color(SemanticTone::Danger)
674        } else if focused {
675            theme.palette.border_focus
676        } else {
677            interaction_border
678        };
679        let background = mix_color(
680            theme.surfaces.field,
681            theme.palette.surface_focus,
682            focused as u8 as f32,
683        );
684        ctx.fill(rounded_rect_path(bounds, radius), background);
685        ctx.stroke(
686            rounded_rect_path(bounds, radius),
687            border,
688            StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
689        );
690        if focused {
691            let outset = physical_pixels(ctx, theme.metrics.focus_ring_outset);
692            ctx.stroke(
693                rounded_rect_path(bounds.inflate(outset, outset), radius + outset),
694                if invalid {
695                    theme.semantic_tone_color(SemanticTone::Danger)
696                } else {
697                    theme.palette.focus_ring
698                },
699                StrokeStyle::new(physical_pixels(ctx, theme.metrics.focus_ring_width)),
700            );
701        }
702        self.child.paint(ctx);
703    }
704
705    fn semantics(&self, ctx: &mut SemanticsCtx) {
706        if self.name.is_some() || self.description.is_some() {
707            let mut node = SemanticsNode::new(
708                ctx.widget_id(),
709                SemanticsRole::GenericContainer,
710                ctx.bounds(),
711            );
712            node.name = self.name.clone();
713            node.description = self.description.clone();
714            node.state.focused = self.is_focused(ctx.focused_widget_id());
715            node.state.hovered = self.hovered;
716            ctx.push(node);
717        }
718        self.child.semantics(ctx);
719    }
720
721    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
722        self.child.visit_children(visitor);
723    }
724
725    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
726        self.child.visit_children_mut(visitor);
727    }
728}
729
730#[derive(Debug, Clone, PartialEq, Eq)]
731pub struct MenuItem {
732    label: String,
733    shortcut: Option<String>,
734    enabled: bool,
735    destructive: bool,
736    separator_before: bool,
737}
738
739impl MenuItem {
740    pub fn new(label: impl Into<String>) -> Self {
741        Self {
742            label: label.into(),
743            shortcut: None,
744            enabled: true,
745            destructive: false,
746            separator_before: false,
747        }
748    }
749
750    pub fn label(&self) -> &str {
751        &self.label
752    }
753
754    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
755        self.shortcut = Some(shortcut.into());
756        self
757    }
758
759    pub fn disabled(mut self) -> Self {
760        self.enabled = false;
761        self
762    }
763
764    pub fn destructive(mut self) -> Self {
765        self.destructive = true;
766        self
767    }
768
769    pub fn separator_before(mut self) -> Self {
770        self.separator_before = true;
771        self
772    }
773
774    fn text_color(&self, theme: &DefaultTheme) -> Color {
775        if !self.enabled {
776            theme.palette.placeholder
777        } else if self.destructive {
778            theme.semantic_tone_color(SemanticTone::Danger)
779        } else {
780            theme.palette.text
781        }
782    }
783}
784
785fn virtual_menu_item_id(parent: WidgetId, index: usize) -> WidgetId {
786    WidgetId::new(
787        (1_u64 << 63)
788            | parent
789                .get()
790                .wrapping_mul(257)
791                .wrapping_add(index as u64 + 1),
792    )
793}
794
795fn menu_row_height(theme: &DefaultTheme) -> f32 {
796    theme.metrics.menu_row_height
797}
798
799fn themed_menu_height_for_rows(theme: &DefaultTheme, row_height: f32, rows: usize) -> f32 {
800    theme.metrics.menu_padding.top + theme.metrics.menu_padding.bottom + (row_height * rows as f32)
801}
802
803fn menu_item_semantics_node(
804    parent: WidgetId,
805    index: usize,
806    item: &MenuItem,
807    bounds: Rect,
808    highlighted: bool,
809) -> SemanticsNode {
810    let mut node = SemanticsNode::new(
811        virtual_menu_item_id(parent, index),
812        SemanticsRole::MenuItem,
813        bounds,
814    );
815    node.parent = Some(parent);
816    node.name = Some(item.label.clone());
817    node.state.disabled = !item.enabled;
818    node.state.selected = highlighted;
819    if item.enabled {
820        node.actions = vec![SemanticsAction::Activate];
821    }
822    node
823}
824
825pub struct Toolbar {
826    theme: Box<DefaultTheme>,
827    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
828    axis: Axis,
829    name: Option<String>,
830    extent: Option<f32>,
831    padding: Option<Insets>,
832    spacing: Option<f32>,
833    line_spacing: Option<f32>,
834    wrap: FlexWrap,
835    background: Option<Color>,
836    divider: bool,
837    children: WidgetChildren,
838    layout: Option<FlexLayout>,
839}
840
841impl Toolbar {
842    pub fn horizontal() -> Self {
843        Self::new(Axis::Horizontal)
844    }
845
846    pub fn vertical() -> Self {
847        Self::new(Axis::Vertical)
848    }
849
850    pub fn new(axis: Axis) -> Self {
851        Self {
852            theme: Box::new(DefaultTheme::default()),
853            theme_reader: None,
854            axis,
855            name: None,
856            extent: None,
857            padding: None,
858            spacing: None,
859            line_spacing: None,
860            wrap: FlexWrap::NoWrap,
861            background: None,
862            divider: true,
863            children: WidgetChildren::new(),
864            layout: None,
865        }
866    }
867
868    pub fn theme(mut self, theme: DefaultTheme) -> Self {
869        self.theme = Box::new(theme);
870        self.theme_reader = None;
871        self
872    }
873
874    pub fn theme_when<F>(mut self, theme: F) -> Self
875    where
876        F: Fn() -> DefaultTheme + 'static,
877    {
878        self.theme_reader = Some(Box::new(theme));
879        self
880    }
881
882    pub fn name(mut self, name: impl Into<String>) -> Self {
883        self.name = Some(name.into());
884        self
885    }
886
887    pub fn extent(mut self, extent: f32) -> Self {
888        self.extent = Some(extent.max(0.0));
889        self
890    }
891
892    pub fn padding(mut self, padding: Insets) -> Self {
893        self.padding = Some(padding);
894        self
895    }
896
897    pub fn spacing(mut self, spacing: f32) -> Self {
898        self.spacing = Some(spacing.max(0.0));
899        self
900    }
901
902    /// Allow toolbar items to flow into additional rows or columns while
903    /// retaining their original widget identities and navigation order.
904    pub fn wrap(mut self, wrap: FlexWrap) -> Self {
905        self.wrap = wrap;
906        self
907    }
908
909    pub fn wrapping(self) -> Self {
910        self.wrap(FlexWrap::Wrap)
911    }
912
913    pub fn line_spacing(mut self, spacing: f32) -> Self {
914        self.line_spacing = Some(spacing.max(0.0));
915        self
916    }
917
918    pub fn background(mut self, color: Color) -> Self {
919        self.background = Some(color);
920        self
921    }
922
923    pub fn divider(mut self, divider: bool) -> Self {
924        self.divider = divider;
925        self
926    }
927
928    pub fn with_child<W>(mut self, child: W) -> Self
929    where
930        W: Widget + 'static,
931    {
932        self.children.push(child);
933        self
934    }
935
936    pub fn push<W>(&mut self, child: W)
937    where
938        W: Widget + 'static,
939    {
940        self.children.push(child);
941    }
942
943    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
944        self.children.as_slice()
945    }
946
947    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
948        self.children.as_mut_slice()
949    }
950
951    fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
952        self.extent.unwrap_or(metrics.toolbar_extent)
953    }
954
955    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
956        self.padding.unwrap_or(metrics.toolbar_padding)
957    }
958
959    fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
960        self.spacing.unwrap_or(metrics.toolbar_spacing)
961    }
962
963    fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
964        let padding = self.resolved_padding(metrics);
965        Rect::new(
966            bounds.x() + padding.left,
967            bounds.y() + padding.top,
968            (bounds.width() - padding.left - padding.right).max(0.0),
969            (bounds.height() - padding.top - padding.bottom).max(0.0),
970        )
971    }
972
973    fn resolved_theme(&self) -> DefaultTheme {
974        self.theme_reader
975            .as_ref()
976            .map(|theme| theme())
977            .unwrap_or(*self.theme)
978    }
979}
980
981impl Default for Toolbar {
982    fn default() -> Self {
983        Self::horizontal()
984    }
985}
986
987impl Widget for Toolbar {
988    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
989        let theme = self.resolved_theme();
990        let metrics = theme.metrics;
991        let extent = self.resolved_extent(metrics);
992        let padding = self.resolved_padding(metrics);
993        let spacing = self.resolved_spacing(metrics);
994        if self.wrap == FlexWrap::Wrap {
995            let line_spacing = self.line_spacing.unwrap_or(spacing);
996            let max_content = Size::new(
997                if constraints.max.width.is_finite() {
998                    (constraints.max.width - padding.left - padding.right).max(0.0)
999                } else {
1000                    f32::INFINITY
1001                },
1002                if constraints.max.height.is_finite() {
1003                    (constraints.max.height - padding.top - padding.bottom).max(0.0)
1004                } else {
1005                    f32::INFINITY
1006                },
1007            );
1008            let min_cross = match self.axis {
1009                Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
1010                Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
1011            };
1012            let min_content = match self.axis {
1013                Axis::Horizontal => Size::new(
1014                    if max_content.width.is_finite() {
1015                        max_content.width
1016                    } else {
1017                        0.0
1018                    },
1019                    min_cross,
1020                ),
1021                Axis::Vertical => Size::new(
1022                    min_cross,
1023                    if max_content.height.is_finite() {
1024                        max_content.height
1025                    } else {
1026                        0.0
1027                    },
1028                ),
1029            };
1030            let style = FlexStyle::new(self.axis)
1031                .wrap(FlexWrap::Wrap)
1032                .main_gap(spacing)
1033                .cross_gap(line_spacing)
1034                .justify(FlexJustify::Start)
1035                .align_items(Alignment::Center)
1036                .align_content(FlexAlignContent::Start);
1037            let items = vec![FlexItem::new(); self.children.len()];
1038            let layout = flex_layout(
1039                style,
1040                &items,
1041                Constraints::new(min_content, max_content),
1042                |index, child_constraints| {
1043                    self.children.measure_child(index, ctx, child_constraints)
1044                },
1045            );
1046            let natural = Size::new(
1047                layout.size.width + padding.left + padding.right,
1048                layout.size.height + padding.top + padding.bottom,
1049            );
1050            self.layout = Some(layout);
1051            return constraints.clamp(natural);
1052        }
1053        self.layout = None;
1054        let content_cross = match self.axis {
1055            Axis::Horizontal => (extent - padding.top - padding.bottom).max(0.0),
1056            Axis::Vertical => (extent - padding.left - padding.right).max(0.0),
1057        };
1058        let child_constraints = match self.axis {
1059            Axis::Horizontal => {
1060                Constraints::new(Size::ZERO, Size::new(f32::INFINITY, content_cross))
1061            }
1062            Axis::Vertical => Constraints::new(Size::ZERO, Size::new(content_cross, f32::INFINITY)),
1063        };
1064
1065        let mut main: f32 = 0.0;
1066        let mut cross: f32 = 0.0;
1067        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1068            let child_size = child.measure(ctx, child_constraints);
1069            if index > 0 {
1070                main += spacing;
1071            }
1072            main += toolbar_main(self.axis, child_size);
1073            cross = cross.max(toolbar_cross(self.axis, child_size));
1074        }
1075
1076        let natural = match self.axis {
1077            Axis::Horizontal => Size::new(
1078                main + padding.left + padding.right,
1079                extent.max(cross + padding.top + padding.bottom),
1080            ),
1081            Axis::Vertical => Size::new(
1082                extent.max(cross + padding.left + padding.right),
1083                main + padding.top + padding.bottom,
1084            ),
1085        };
1086        let filled = match self.axis {
1087            Axis::Horizontal => Size::new(
1088                if constraints.max.width.is_finite() {
1089                    constraints.max.width
1090                } else {
1091                    natural.width
1092                },
1093                extent,
1094            ),
1095            Axis::Vertical => Size::new(
1096                extent,
1097                if constraints.max.height.is_finite() {
1098                    constraints.max.height
1099                } else {
1100                    natural.height
1101                },
1102            ),
1103        };
1104
1105        constraints.clamp(filled)
1106    }
1107
1108    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1109        let theme = self.resolved_theme();
1110        let metrics = theme.metrics;
1111        let spacing = self.resolved_spacing(metrics);
1112        let content = self.content_bounds(bounds, metrics);
1113        if self.wrap == FlexWrap::Wrap {
1114            let style = FlexStyle::new(self.axis)
1115                .wrap(FlexWrap::Wrap)
1116                .main_gap(spacing)
1117                .cross_gap(self.line_spacing.unwrap_or(spacing))
1118                .justify(FlexJustify::Start)
1119                .align_items(Alignment::Center)
1120                .align_content(FlexAlignContent::Start);
1121            let items = vec![FlexItem::new(); self.children.len()];
1122            let measured = self
1123                .children
1124                .as_slice()
1125                .iter()
1126                .map(WidgetPod::measured_size)
1127                .collect::<Vec<_>>();
1128            let layout = arrange_flex(style, &items, content.size, &measured);
1129            for (index, item) in layout.items.iter().enumerate() {
1130                self.children.arrange_child(
1131                    index,
1132                    ctx,
1133                    item.rect.translate(content.origin.to_vector()),
1134                );
1135            }
1136            self.layout = Some(layout);
1137            return;
1138        }
1139        let content_main = toolbar_main(self.axis, content.size);
1140        let content_cross = toolbar_cross(self.axis, content.size);
1141        let mut main_offset = 0.0;
1142
1143        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1144            if index > 0 {
1145                main_offset += spacing;
1146            }
1147
1148            let measured = child.measured_size();
1149            let remaining = (content_main - main_offset).max(0.0);
1150            let child_main = toolbar_main(self.axis, measured).min(remaining);
1151            let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
1152            let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
1153            let origin = match self.axis {
1154                Axis::Horizontal => {
1155                    Point::new(content.x() + main_offset, content.y() + cross_offset)
1156                }
1157                Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1158            };
1159            child.arrange(
1160                ctx,
1161                Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
1162            );
1163            main_offset += child_main;
1164        }
1165    }
1166
1167    fn paint(&self, ctx: &mut PaintCtx) {
1168        let theme = self.resolved_theme();
1169        let palette = theme.palette;
1170        let bounds = ctx.bounds();
1171        ctx.fill_bounds(self.background.unwrap_or(palette.surface));
1172        if self.divider {
1173            let divider = match self.axis {
1174                Axis::Horizontal => {
1175                    Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
1176                }
1177                Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
1178            };
1179            ctx.stroke_rect(
1180                divider,
1181                palette.border.with_alpha(0.85),
1182                StrokeStyle::new(1.0),
1183            );
1184        }
1185        self.children.paint(ctx);
1186    }
1187
1188    fn semantics(&self, ctx: &mut SemanticsCtx) {
1189        if let Some(name) = &self.name {
1190            let mut node = SemanticsNode::new(
1191                ctx.widget_id(),
1192                SemanticsRole::GenericContainer,
1193                ctx.bounds(),
1194            );
1195            node.name = Some(name.clone());
1196            ctx.push(node);
1197        }
1198        self.children.semantics(ctx);
1199    }
1200
1201    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1202        self.children.visit_children(visitor);
1203    }
1204
1205    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1206        self.children.visit_children_mut(visitor);
1207    }
1208}
1209
1210pub struct CommandGroup {
1211    theme: Box<DefaultTheme>,
1212    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1213    axis: Axis,
1214    name: Option<String>,
1215    padding: Option<Insets>,
1216    spacing: Option<f32>,
1217    corner_radius: Option<f32>,
1218    background: Option<Color>,
1219    border: Option<Color>,
1220    children: WidgetChildren,
1221}
1222
1223impl CommandGroup {
1224    pub fn horizontal(name: impl Into<String>) -> Self {
1225        Self::new(Axis::Horizontal, name)
1226    }
1227
1228    pub fn vertical(name: impl Into<String>) -> Self {
1229        Self::new(Axis::Vertical, name)
1230    }
1231
1232    pub fn new(axis: Axis, name: impl Into<String>) -> Self {
1233        Self {
1234            theme: Box::new(DefaultTheme::default()),
1235            theme_reader: None,
1236            axis,
1237            name: Some(name.into()),
1238            padding: None,
1239            spacing: None,
1240            corner_radius: None,
1241            background: None,
1242            border: None,
1243            children: WidgetChildren::new(),
1244        }
1245    }
1246
1247    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1248        self.theme = Box::new(theme);
1249        self.theme_reader = None;
1250        self
1251    }
1252
1253    pub fn theme_when<F>(mut self, theme: F) -> Self
1254    where
1255        F: Fn() -> DefaultTheme + 'static,
1256    {
1257        self.theme_reader = Some(Box::new(theme));
1258        self
1259    }
1260
1261    pub fn unnamed(mut self) -> Self {
1262        self.name = None;
1263        self
1264    }
1265
1266    pub fn padding(mut self, padding: Insets) -> Self {
1267        self.padding = Some(padding);
1268        self
1269    }
1270
1271    pub fn spacing(mut self, spacing: f32) -> Self {
1272        self.spacing = Some(spacing.max(0.0));
1273        self
1274    }
1275
1276    pub fn corner_radius(mut self, corner_radius: f32) -> Self {
1277        self.corner_radius = Some(corner_radius.max(0.0));
1278        self
1279    }
1280
1281    pub fn background(mut self, color: Color) -> Self {
1282        self.background = Some(color);
1283        self
1284    }
1285
1286    pub fn border(mut self, color: Color) -> Self {
1287        self.border = Some(color);
1288        self
1289    }
1290
1291    pub fn with_child<W>(mut self, child: W) -> Self
1292    where
1293        W: Widget + 'static,
1294    {
1295        self.children.push(child);
1296        self
1297    }
1298
1299    pub fn push<W>(&mut self, child: W)
1300    where
1301        W: Widget + 'static,
1302    {
1303        self.children.push(child);
1304    }
1305
1306    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
1307        self.children.as_slice()
1308    }
1309
1310    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
1311        self.children.as_mut_slice()
1312    }
1313
1314    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1315        self.padding.unwrap_or(metrics.command_group_padding)
1316    }
1317
1318    fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1319        self.spacing.unwrap_or(metrics.command_group_spacing)
1320    }
1321
1322    fn resolved_corner_radius(&self, metrics: ControlMetrics) -> f32 {
1323        self.corner_radius.unwrap_or(metrics.command_group_radius)
1324    }
1325
1326    fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1327        inset_rect(bounds, self.resolved_padding(metrics))
1328    }
1329
1330    fn resolved_theme(&self) -> DefaultTheme {
1331        self.theme_reader
1332            .as_ref()
1333            .map(|theme| theme())
1334            .unwrap_or(*self.theme)
1335    }
1336}
1337
1338impl Widget for CommandGroup {
1339    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1340        let theme = self.resolved_theme();
1341        let metrics = theme.metrics;
1342        let padding = self.resolved_padding(metrics);
1343        let spacing = self.resolved_spacing(metrics);
1344        let max_width = if constraints.max.width.is_finite() {
1345            (constraints.max.width - padding.left - padding.right).max(0.0)
1346        } else {
1347            f32::INFINITY
1348        };
1349        let max_height = if constraints.max.height.is_finite() {
1350            (constraints.max.height - padding.top - padding.bottom).max(0.0)
1351        } else {
1352            f32::INFINITY
1353        };
1354        let child_constraints = Constraints::new(Size::ZERO, Size::new(max_width, max_height));
1355
1356        let mut main: f32 = 0.0;
1357        let mut cross: f32 = 0.0;
1358        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1359            let child_size = child.measure(ctx, child_constraints);
1360            if index > 0 {
1361                main += spacing;
1362            }
1363            main += toolbar_main(self.axis, child_size);
1364            cross = cross.max(toolbar_cross(self.axis, child_size));
1365        }
1366
1367        let natural = match self.axis {
1368            Axis::Horizontal => Size::new(
1369                main + padding.left + padding.right,
1370                cross + padding.top + padding.bottom,
1371            ),
1372            Axis::Vertical => Size::new(
1373                cross + padding.left + padding.right,
1374                main + padding.top + padding.bottom,
1375            ),
1376        };
1377        constraints.clamp(natural)
1378    }
1379
1380    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1381        let theme = self.resolved_theme();
1382        let metrics = theme.metrics;
1383        let spacing = self.resolved_spacing(metrics);
1384        let content = self.content_bounds(bounds, metrics);
1385        let content_main = toolbar_main(self.axis, content.size);
1386        let content_cross = toolbar_cross(self.axis, content.size);
1387        let mut main_offset = 0.0;
1388
1389        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1390            if index > 0 {
1391                main_offset += spacing;
1392            }
1393
1394            let measured = child.measured_size();
1395            let remaining = (content_main - main_offset).max(0.0);
1396            let child_main = toolbar_main(self.axis, measured).min(remaining);
1397            let child_cross = toolbar_cross(self.axis, measured).min(content_cross);
1398            let cross_offset = ((content_cross - child_cross) * 0.5).max(0.0);
1399            let origin = match self.axis {
1400                Axis::Horizontal => {
1401                    Point::new(content.x() + main_offset, content.y() + cross_offset)
1402                }
1403                Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1404            };
1405            child.arrange(
1406                ctx,
1407                Rect::from_origin_size(origin, toolbar_size(self.axis, child_main, child_cross)),
1408            );
1409            main_offset += child_main;
1410        }
1411    }
1412
1413    fn paint(&self, ctx: &mut PaintCtx) {
1414        let theme = self.resolved_theme();
1415        let radius = self
1416            .resolved_corner_radius(theme.metrics)
1417            .min(ctx.bounds().width().min(ctx.bounds().height()) * 0.5);
1418        let background = self.background.unwrap_or(theme.palette.surface_raised);
1419        let border = self.border.unwrap_or(theme.palette.border);
1420        let shape = rounded_rect_path(ctx.bounds(), radius);
1421        ctx.fill(shape.clone(), background);
1422        ctx.stroke(shape, border, StrokeStyle::new(physical_pixels(ctx, 1.0)));
1423        self.children.paint(ctx);
1424    }
1425
1426    fn semantics(&self, ctx: &mut SemanticsCtx) {
1427        if let Some(name) = &self.name {
1428            let mut node = SemanticsNode::new(
1429                ctx.widget_id(),
1430                SemanticsRole::GenericContainer,
1431                ctx.bounds(),
1432            );
1433            node.name = Some(name.clone());
1434            ctx.push(node);
1435        }
1436        self.children.semantics(ctx);
1437    }
1438
1439    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1440        self.children.visit_children(visitor);
1441    }
1442
1443    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1444        self.children.visit_children_mut(visitor);
1445    }
1446}
1447
1448fn toolbar_main(axis: Axis, size: Size) -> f32 {
1449    match axis {
1450        Axis::Horizontal => size.width,
1451        Axis::Vertical => size.height,
1452    }
1453}
1454
1455fn toolbar_cross(axis: Axis, size: Size) -> f32 {
1456    match axis {
1457        Axis::Horizontal => size.height,
1458        Axis::Vertical => size.width,
1459    }
1460}
1461
1462fn toolbar_size(axis: Axis, main: f32, cross: f32) -> Size {
1463    match axis {
1464        Axis::Horizontal => Size::new(main, cross),
1465        Axis::Vertical => Size::new(cross, main),
1466    }
1467}
1468
1469#[derive(Debug, Clone, PartialEq, Eq)]
1470pub struct ToolPaletteItem {
1471    icon: IconGlyph,
1472    label: String,
1473    enabled: bool,
1474}
1475
1476impl ToolPaletteItem {
1477    pub fn new(icon: IconGlyph, label: impl Into<String>) -> Self {
1478        Self {
1479            icon,
1480            label: label.into(),
1481            enabled: true,
1482        }
1483    }
1484
1485    pub fn disabled(mut self) -> Self {
1486        self.enabled = false;
1487        self
1488    }
1489
1490    pub fn label(&self) -> &str {
1491        &self.label
1492    }
1493}
1494
1495pub struct ToolPalette {
1496    theme: Box<DefaultTheme>,
1497    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1498    axis: Axis,
1499    name: String,
1500    items: Vec<ToolPaletteItem>,
1501    selected: Option<usize>,
1502    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
1503    hovered: Option<usize>,
1504    hover_visual: Option<usize>,
1505    pressed: Option<usize>,
1506    press_visual: Option<usize>,
1507    hover_animation: AnimatedScalar,
1508    press_animation: AnimatedScalar,
1509    focus_animation: AnimatedScalar,
1510    extent: Option<f32>,
1511    padding: Option<Insets>,
1512    spacing: Option<f32>,
1513    item_size: Option<f32>,
1514    icon_size: Option<f32>,
1515    background: Option<Color>,
1516    divider: bool,
1517    on_change: Option<Box<dyn FnMut(usize, String)>>,
1518    on_change_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, String)>>,
1519}
1520
1521impl ToolPalette {
1522    pub fn vertical(name: impl Into<String>) -> Self {
1523        Self::new(Axis::Vertical, name)
1524    }
1525
1526    pub fn horizontal(name: impl Into<String>) -> Self {
1527        Self::new(Axis::Horizontal, name)
1528    }
1529
1530    pub fn new(axis: Axis, name: impl Into<String>) -> Self {
1531        Self {
1532            theme: Box::new(DefaultTheme::default()),
1533            theme_reader: None,
1534            axis,
1535            name: name.into(),
1536            items: Vec::new(),
1537            selected: None,
1538            selected_reader: None,
1539            hovered: None,
1540            hover_visual: None,
1541            pressed: None,
1542            press_visual: None,
1543            hover_animation: AnimatedScalar::new(0.0),
1544            press_animation: AnimatedScalar::new(0.0),
1545            focus_animation: AnimatedScalar::new(0.0),
1546            extent: None,
1547            padding: None,
1548            spacing: None,
1549            item_size: None,
1550            icon_size: None,
1551            background: None,
1552            divider: true,
1553            on_change: None,
1554            on_change_with_ctx: None,
1555        }
1556    }
1557
1558    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1559        self.theme = Box::new(theme);
1560        self.theme_reader = None;
1561        self
1562    }
1563
1564    pub fn theme_when<F>(mut self, theme: F) -> Self
1565    where
1566        F: Fn() -> DefaultTheme + 'static,
1567    {
1568        self.theme_reader = Some(Box::new(theme));
1569        self
1570    }
1571
1572    pub fn item(mut self, item: ToolPaletteItem) -> Self {
1573        self.items.push(item);
1574        self
1575    }
1576
1577    pub fn items<I>(mut self, items: I) -> Self
1578    where
1579        I: IntoIterator<Item = ToolPaletteItem>,
1580    {
1581        self.items.extend(items);
1582        self
1583    }
1584
1585    pub fn selected(mut self, selected: usize) -> Self {
1586        self.selected = Some(selected);
1587        self.selected_reader = None;
1588        self
1589    }
1590
1591    pub fn selected_when<F>(mut self, selected: F) -> Self
1592    where
1593        F: Fn() -> Option<usize> + 'static,
1594    {
1595        self.selected_reader = Some(Box::new(selected));
1596        self
1597    }
1598
1599    pub fn extent(mut self, extent: f32) -> Self {
1600        self.extent = Some(extent.max(0.0));
1601        self
1602    }
1603
1604    pub fn padding(mut self, padding: Insets) -> Self {
1605        self.padding = Some(padding);
1606        self
1607    }
1608
1609    pub fn spacing(mut self, spacing: f32) -> Self {
1610        self.spacing = Some(spacing.max(0.0));
1611        self
1612    }
1613
1614    pub fn item_size(mut self, item_size: f32) -> Self {
1615        self.item_size = Some(item_size.max(0.0));
1616        self
1617    }
1618
1619    pub fn icon_size(mut self, icon_size: f32) -> Self {
1620        self.icon_size = Some(icon_size.max(0.0));
1621        self
1622    }
1623
1624    pub fn background(mut self, color: Color) -> Self {
1625        self.background = Some(color);
1626        self
1627    }
1628
1629    pub fn divider(mut self, divider: bool) -> Self {
1630        self.divider = divider;
1631        self
1632    }
1633
1634    pub fn on_change<F>(mut self, on_change: F) -> Self
1635    where
1636        F: FnMut(usize, String) + 'static,
1637    {
1638        self.on_change = Some(Box::new(on_change));
1639        self
1640    }
1641
1642    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
1643    where
1644        F: FnMut(&mut EventCtx, usize, String) + 'static,
1645    {
1646        self.on_change_with_ctx = Some(Box::new(on_change));
1647        self
1648    }
1649
1650    pub fn selected_index(&self) -> Option<usize> {
1651        self.current_selected()
1652    }
1653
1654    fn current_selected(&self) -> Option<usize> {
1655        self.selected_reader
1656            .as_ref()
1657            .map(|selected| selected())
1658            .unwrap_or(self.selected)
1659            .filter(|index| *index < self.items.len())
1660    }
1661
1662    fn resolved_theme(&self) -> DefaultTheme {
1663        self.theme_reader
1664            .as_ref()
1665            .map(|theme| theme())
1666            .unwrap_or(*self.theme)
1667    }
1668
1669    fn resolved_extent(&self, metrics: ControlMetrics) -> f32 {
1670        self.extent.unwrap_or(metrics.toolbar_extent)
1671    }
1672
1673    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
1674        self.padding.unwrap_or(metrics.toolbar_padding)
1675    }
1676
1677    fn resolved_spacing(&self, metrics: ControlMetrics) -> f32 {
1678        self.spacing.unwrap_or(metrics.toolbar_spacing)
1679    }
1680
1681    fn resolved_item_size(&self, metrics: ControlMetrics) -> f32 {
1682        self.item_size.unwrap_or(metrics.tool_palette_item_size)
1683    }
1684
1685    fn resolved_icon_size(&self, metrics: ControlMetrics) -> f32 {
1686        self.icon_size.unwrap_or(metrics.tool_palette_icon_size)
1687    }
1688
1689    fn content_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
1690        let padding = self.resolved_padding(metrics);
1691        Rect::new(
1692            bounds.x() + padding.left,
1693            bounds.y() + padding.top,
1694            (bounds.width() - padding.left - padding.right).max(0.0),
1695            (bounds.height() - padding.top - padding.bottom).max(0.0),
1696        )
1697    }
1698
1699    fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
1700        if index >= self.items.len() {
1701            return None;
1702        }
1703
1704        let metrics = self.resolved_theme().metrics;
1705        let item_size = self.resolved_item_size(metrics);
1706        let spacing = self.resolved_spacing(metrics);
1707        let content = self.content_bounds(bounds, metrics);
1708        let content_main = toolbar_main(self.axis, content.size);
1709        let content_cross = toolbar_cross(self.axis, content.size);
1710        let item_main = item_size.min(content_main);
1711        let item_cross = item_size.min(content_cross);
1712        let main_offset = index as f32 * (item_size + spacing);
1713        if main_offset >= content_main {
1714            return None;
1715        }
1716        let cross_offset = ((content_cross - item_cross) * 0.5).max(0.0);
1717        let origin = match self.axis {
1718            Axis::Horizontal => Point::new(content.x() + main_offset, content.y() + cross_offset),
1719            Axis::Vertical => Point::new(content.x() + cross_offset, content.y() + main_offset),
1720        };
1721        Some(Rect::from_origin_size(
1722            origin,
1723            toolbar_size(self.axis, item_main, item_cross),
1724        ))
1725    }
1726
1727    fn hit_at(&self, bounds: Rect, position: Point) -> Option<usize> {
1728        (0..self.items.len()).find(|index| {
1729            self.items[*index].enabled
1730                && self
1731                    .item_rect(bounds, *index)
1732                    .is_some_and(|rect| rect.contains(position))
1733        })
1734    }
1735
1736    fn select(&mut self, ctx: &mut EventCtx, index: usize) {
1737        let Some(item) = self.items.get(index) else {
1738            return;
1739        };
1740        if !item.enabled {
1741            return;
1742        }
1743
1744        self.selected = Some(index);
1745        if let Some(on_change) = &mut self.on_change {
1746            on_change(index, item.label.clone());
1747        }
1748        if let Some(on_change_with_ctx) = &mut self.on_change_with_ctx {
1749            on_change_with_ctx(ctx, index, item.label.clone());
1750        }
1751    }
1752
1753    fn move_selection(&mut self, ctx: &mut EventCtx, delta: isize) {
1754        if self.items.is_empty() {
1755            return;
1756        }
1757
1758        let start = self.current_selected().unwrap_or(0);
1759        let mut index = start as isize;
1760        let last = self.items.len() as isize - 1;
1761        for _ in 0..self.items.len() {
1762            index = (index + delta).clamp(0, last);
1763            if self
1764                .items
1765                .get(index as usize)
1766                .is_some_and(|item| item.enabled)
1767            {
1768                self.select(ctx, index as usize);
1769                return;
1770            }
1771            if index == 0 || index == last {
1772                return;
1773            }
1774        }
1775    }
1776
1777    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
1778        if self.hovered == hovered {
1779            return;
1780        }
1781        let theme = self.resolved_theme();
1782        self.hovered = hovered;
1783        if let Some(index) = hovered {
1784            self.hover_visual = Some(index);
1785            self.hover_animation = AnimatedScalar::new(0.0);
1786            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
1787        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
1788            self.hover_visual = None;
1789        }
1790        ctx.request_paint();
1791        ctx.request_semantics();
1792    }
1793
1794    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
1795        if self.pressed == pressed {
1796            return;
1797        }
1798        let theme = self.resolved_theme();
1799        self.pressed = pressed;
1800        if let Some(index) = pressed {
1801            self.press_visual = Some(index);
1802            self.press_animation = AnimatedScalar::new(0.0);
1803            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
1804        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
1805            self.press_visual = None;
1806        }
1807        ctx.request_paint();
1808        ctx.request_semantics();
1809    }
1810
1811    fn hover_amount_for(&self, index: usize) -> f32 {
1812        if self.hover_visual == Some(index) {
1813            self.hover_animation.value
1814        } else {
1815            0.0
1816        }
1817    }
1818
1819    fn press_amount_for(&self, index: usize) -> f32 {
1820        if self.press_visual == Some(index) {
1821            self.press_animation.value
1822        } else {
1823            0.0
1824        }
1825    }
1826
1827    fn advance_animations(&mut self, time: f64) -> bool {
1828        let hover_animating = self.hover_animation.advance(time);
1829        if !hover_animating
1830            && self.hovered.is_none()
1831            && self.hover_animation.value <= AnimatedScalar::EPSILON
1832        {
1833            self.hover_visual = None;
1834        }
1835
1836        let press_animating = self.press_animation.advance(time);
1837        if !press_animating
1838            && self.pressed.is_none()
1839            && self.press_animation.value <= AnimatedScalar::EPSILON
1840        {
1841            self.press_visual = None;
1842        }
1843
1844        hover_animating | press_animating | self.focus_animation.advance(time)
1845    }
1846}
1847
1848impl Widget for ToolPalette {
1849    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1850        match event {
1851            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1852                self.set_hovered(self.hit_at(ctx.bounds(), pointer.position), ctx);
1853            }
1854            Event::Pointer(pointer)
1855                if pointer.kind == PointerEventKind::Down
1856                    && pointer.button == Some(PointerButton::Primary) =>
1857            {
1858                let hovered = self.hit_at(ctx.bounds(), pointer.position);
1859                self.set_hovered(hovered, ctx);
1860                self.set_pressed(hovered, ctx);
1861                if self.pressed.is_some() {
1862                    ctx.request_focus();
1863                    ctx.request_pointer_capture(pointer.pointer_id);
1864                    ctx.set_handled();
1865                }
1866            }
1867            Event::Pointer(pointer)
1868                if pointer.kind == PointerEventKind::Up
1869                    && pointer.button == Some(PointerButton::Primary) =>
1870            {
1871                let hovered = self.hit_at(ctx.bounds(), pointer.position);
1872                if let Some(index) = self
1873                    .pressed
1874                    .zip(hovered)
1875                    .filter(|(left, right)| left == right)
1876                    .map(|(index, _)| index)
1877                {
1878                    self.select(ctx, index);
1879                }
1880                self.set_hovered(hovered, ctx);
1881                self.set_pressed(None, ctx);
1882                ctx.release_pointer_capture(pointer.pointer_id);
1883                ctx.set_handled();
1884            }
1885            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
1886                self.set_hovered(None, ctx);
1887            }
1888            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1889                if self.pressed.is_some() {
1890                    self.set_pressed(None, ctx);
1891                    self.set_hovered(None, ctx);
1892                    ctx.release_pointer_capture(pointer.pointer_id);
1893                    ctx.set_handled();
1894                }
1895            }
1896            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1897                match key.key.as_str() {
1898                    "ArrowUp" if self.axis == Axis::Vertical => self.move_selection(ctx, -1),
1899                    "ArrowDown" if self.axis == Axis::Vertical => self.move_selection(ctx, 1),
1900                    "ArrowLeft" if self.axis == Axis::Horizontal => self.move_selection(ctx, -1),
1901                    "ArrowRight" if self.axis == Axis::Horizontal => self.move_selection(ctx, 1),
1902                    "Home" => {
1903                        if let Some(index) = self.items.iter().position(|item| item.enabled) {
1904                            self.select(ctx, index);
1905                        }
1906                    }
1907                    "End" => {
1908                        if let Some(index) = self.items.iter().rposition(|item| item.enabled) {
1909                            self.select(ctx, index);
1910                        }
1911                    }
1912                    "Enter" | " " => {
1913                        if let Some(index) = self.current_selected() {
1914                            self.select(ctx, index);
1915                        }
1916                    }
1917                    _ => return,
1918                }
1919                ctx.request_paint();
1920                ctx.request_semantics();
1921                ctx.set_handled();
1922            }
1923            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1924                if self.advance_animations(*time) {
1925                    ctx.request_animation_frame();
1926                }
1927                ctx.request_paint();
1928            }
1929            _ => {}
1930        }
1931    }
1932
1933    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1934        let theme = self.resolved_theme();
1935        let metrics = theme.metrics;
1936        let item_size = self.resolved_item_size(metrics);
1937        let spacing = self.resolved_spacing(metrics);
1938        let padding = self.resolved_padding(metrics);
1939        let extent = self.resolved_extent(metrics);
1940        let item_count = self.items.len();
1941        let main = if item_count == 0 {
1942            0.0
1943        } else {
1944            (item_size * item_count as f32) + (spacing * (item_count - 1) as f32)
1945        };
1946        let natural = match self.axis {
1947            Axis::Horizontal => Size::new(main + padding.left + padding.right, extent),
1948            Axis::Vertical => Size::new(extent, main + padding.top + padding.bottom),
1949        };
1950        let filled = match self.axis {
1951            Axis::Horizontal => Size::new(
1952                if constraints.max.width.is_finite() {
1953                    constraints.max.width
1954                } else {
1955                    natural.width
1956                },
1957                natural.height,
1958            ),
1959            Axis::Vertical => Size::new(
1960                natural.width,
1961                if constraints.max.height.is_finite() {
1962                    constraints.max.height
1963                } else {
1964                    natural.height
1965                },
1966            ),
1967        };
1968
1969        constraints.clamp(filled)
1970    }
1971
1972    fn paint(&self, ctx: &mut PaintCtx) {
1973        let theme = self.resolved_theme();
1974        let palette = theme.palette;
1975        let metrics = theme.metrics;
1976        let interaction = theme.interaction;
1977        let icon_size = self.resolved_icon_size(metrics);
1978        let bounds = ctx.bounds();
1979        ctx.fill_bounds(self.background.unwrap_or(palette.surface));
1980        if self.divider {
1981            let divider = match self.axis {
1982                Axis::Horizontal => {
1983                    Rect::new(bounds.x(), bounds.max_y() - 1.0, bounds.width(), 1.0)
1984                }
1985                Axis::Vertical => Rect::new(bounds.max_x() - 1.0, bounds.y(), 1.0, bounds.height()),
1986            };
1987            ctx.stroke_rect(
1988                divider,
1989                palette.border.with_alpha(0.85),
1990                StrokeStyle::new(1.0),
1991            );
1992        }
1993
1994        let selected = self.current_selected();
1995        for (index, item) in self.items.iter().enumerate() {
1996            let Some(rect) = self.item_rect(bounds, index) else {
1997                continue;
1998            };
1999            let selected_item = selected == Some(index);
2000            let hovered = self.hovered == Some(index);
2001            let hover_amount = self.hover_amount_for(index);
2002            let press_amount = self.press_amount_for(index);
2003            let enabled = item.enabled;
2004            let base_background = if selected_item {
2005                mix_color(palette.surface, palette.accent, interaction.selected_blend)
2006            } else {
2007                palette.surface
2008            };
2009            let background = if !enabled {
2010                mix_color(
2011                    base_background,
2012                    palette.surface,
2013                    interaction.disabled_opacity,
2014                )
2015            } else if press_amount > 0.0 {
2016                mix_color(
2017                    if hover_amount > 0.0 {
2018                        mix_color(
2019                            base_background,
2020                            palette.control_hover,
2021                            interaction.hover_blend
2022                                * if selected_item { 0.35 } else { 1.0 }
2023                                * hover_amount,
2024                        )
2025                    } else {
2026                        base_background
2027                    },
2028                    palette.control_active,
2029                    interaction.pressed_blend
2030                        * if selected_item { 0.45 } else { 1.0 }
2031                        * press_amount,
2032                )
2033            } else if hover_amount > 0.0 {
2034                mix_color(
2035                    base_background,
2036                    palette.control_hover,
2037                    interaction.hover_blend * if selected_item { 0.35 } else { 1.0 } * hover_amount,
2038                )
2039            } else {
2040                base_background
2041            };
2042            let border = if !enabled {
2043                palette.border.with_alpha(0.55)
2044            } else if ctx.is_focused() && selected_item {
2045                palette.border_focus
2046            } else if selected_item {
2047                palette.accent_border
2048            } else if hovered || hover_amount > 0.0 || press_amount > 0.0 {
2049                palette.border_hover
2050            } else {
2051                palette.border
2052            };
2053            draw_control_frame(
2054                ctx,
2055                rect,
2056                metrics.corner_radius,
2057                metrics,
2058                background,
2059                border,
2060                (self.focus_animation.value > AnimatedScalar::EPSILON && selected_item).then_some(
2061                    palette
2062                        .focus_ring
2063                        .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
2064                ),
2065            );
2066            let center = rect_center(rect);
2067            let side = icon_size.min(rect.width().min(rect.height())).max(0.0);
2068            let pressed_offset = press_amount * interaction.pressed_offset;
2069            let icon_rect = Rect::new(
2070                center.x - side * 0.5,
2071                center.y - side * 0.5 + pressed_offset,
2072                side,
2073                side,
2074            );
2075            draw_icon_glyph(
2076                ctx,
2077                item.icon,
2078                icon_rect,
2079                if !enabled {
2080                    palette.text.with_alpha(0.38)
2081                } else if selected_item {
2082                    palette.accent
2083                } else {
2084                    palette.text
2085                },
2086            );
2087        }
2088    }
2089
2090    fn semantics(&self, ctx: &mut SemanticsCtx) {
2091        let selected = self.current_selected();
2092        let mut node = SemanticsNode::new(
2093            ctx.widget_id(),
2094            SemanticsRole::GenericContainer,
2095            ctx.bounds(),
2096        );
2097        node.name = Some(self.name.clone());
2098        node.value = selected
2099            .and_then(|index| self.items.get(index))
2100            .map(|item| SemanticsValue::Text(item.label.clone()));
2101        node.state.focused = ctx.is_focused();
2102        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
2103        ctx.push(node);
2104
2105        for (index, item) in self.items.iter().enumerate() {
2106            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
2107                continue;
2108            };
2109            let mut item_node = SemanticsNode::new(
2110                tool_palette_item_id(ctx.widget_id(), index),
2111                SemanticsRole::Button,
2112                rect,
2113            );
2114            item_node.parent = Some(ctx.widget_id());
2115            item_node.name = Some(item.label.clone());
2116            item_node.value = Some(SemanticsValue::Text(item.label.clone()));
2117            item_node.state.disabled = !item.enabled;
2118            item_node.state.hovered = self.hovered == Some(index);
2119            item_node.state.selected = selected == Some(index);
2120            if item.enabled {
2121                item_node.actions = vec![SemanticsAction::Activate];
2122            }
2123            ctx.push(item_node);
2124        }
2125    }
2126
2127    fn accepts_focus(&self) -> bool {
2128        self.items.iter().any(|item| item.enabled)
2129    }
2130
2131    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2132        let theme = self.resolved_theme();
2133        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2134        ctx.request_paint();
2135        ctx.request_semantics();
2136    }
2137}
2138
2139fn tool_palette_item_id(parent: WidgetId, index: usize) -> WidgetId {
2140    const TAG: u64 = 4_u64 << 50;
2141    const LOW_MASK: u64 = (1_u64 << 50) - 1;
2142
2143    WidgetId::new(
2144        TAG | (parent
2145            .get()
2146            .wrapping_mul(397)
2147            .wrapping_add(index as u64 + 1)
2148            & LOW_MASK),
2149    )
2150}
2151
2152pub struct ActionCard {
2153    theme: Box<DefaultTheme>,
2154    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2155    title: String,
2156    description: String,
2157    icon: Option<IconGlyph>,
2158    tone: SemanticTone,
2159    accent: Option<Color>,
2160    padding: Option<Insets>,
2161    min_width: Option<f32>,
2162    min_height: Option<f32>,
2163    hovered: bool,
2164    pressed: bool,
2165    hover_animation: AnimatedScalar,
2166    press_animation: AnimatedScalar,
2167    focus_animation: AnimatedScalar,
2168    title_measurement: Option<TextMeasurement>,
2169    description_measurement: Option<TextMeasurement>,
2170    enabled: bool,
2171    enabled_reader: Option<Box<dyn Fn() -> bool>>,
2172    on_press: Option<Box<dyn FnMut()>>,
2173    on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
2174}
2175
2176impl ActionCard {
2177    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
2178        Self {
2179            theme: Box::new(DefaultTheme::default()),
2180            theme_reader: None,
2181            title: title.into(),
2182            description: description.into(),
2183            icon: None,
2184            tone: SemanticTone::Accent,
2185            accent: None,
2186            padding: None,
2187            min_width: None,
2188            min_height: None,
2189            hovered: false,
2190            pressed: false,
2191            hover_animation: AnimatedScalar::new(0.0),
2192            press_animation: AnimatedScalar::new(0.0),
2193            focus_animation: AnimatedScalar::new(0.0),
2194            title_measurement: None,
2195            description_measurement: None,
2196            enabled: true,
2197            enabled_reader: None,
2198            on_press: None,
2199            on_press_with_ctx: None,
2200        }
2201    }
2202
2203    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2204        self.theme = Box::new(theme);
2205        self.theme_reader = None;
2206        self
2207    }
2208
2209    pub fn theme_when<F>(mut self, theme: F) -> Self
2210    where
2211        F: Fn() -> DefaultTheme + 'static,
2212    {
2213        self.theme_reader = Some(Box::new(theme));
2214        self
2215    }
2216
2217    pub fn icon(mut self, icon: IconGlyph) -> Self {
2218        self.icon = Some(icon);
2219        self
2220    }
2221
2222    pub fn without_icon(mut self) -> Self {
2223        self.icon = None;
2224        self
2225    }
2226
2227    pub fn accent(mut self, accent: Color) -> Self {
2228        self.accent = Some(accent);
2229        self
2230    }
2231
2232    pub fn tone(mut self, tone: SemanticTone) -> Self {
2233        self.tone = tone;
2234        self
2235    }
2236
2237    pub fn padding(mut self, padding: Insets) -> Self {
2238        self.padding = Some(padding);
2239        self
2240    }
2241
2242    pub fn min_width(mut self, width: f32) -> Self {
2243        self.min_width = Some(width.max(0.0));
2244        self
2245    }
2246
2247    pub fn min_height(mut self, height: f32) -> Self {
2248        self.min_height = Some(height.max(0.0));
2249        self
2250    }
2251
2252    pub fn enabled(mut self, enabled: bool) -> Self {
2253        self.enabled = enabled;
2254        self.enabled_reader = None;
2255        self
2256    }
2257
2258    pub fn enabled_when<F>(mut self, enabled: F) -> Self
2259    where
2260        F: Fn() -> bool + 'static,
2261    {
2262        self.enabled_reader = Some(Box::new(enabled));
2263        self
2264    }
2265
2266    pub fn on_press<F>(mut self, on_press: F) -> Self
2267    where
2268        F: FnMut() + 'static,
2269    {
2270        self.on_press = Some(Box::new(on_press));
2271        self
2272    }
2273
2274    pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
2275    where
2276        F: FnMut(&mut EventCtx) + 'static,
2277    {
2278        self.on_press_with_ctx = Some(Box::new(on_press));
2279        self
2280    }
2281
2282    fn is_enabled(&self) -> bool {
2283        self.enabled_reader
2284            .as_ref()
2285            .map(|enabled| enabled())
2286            .unwrap_or(self.enabled)
2287    }
2288
2289    fn resolved_theme(&self) -> DefaultTheme {
2290        self.theme_reader
2291            .as_ref()
2292            .map(|theme| theme())
2293            .unwrap_or(*self.theme)
2294    }
2295
2296    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
2297        self.padding.unwrap_or(metrics.action_card_padding)
2298    }
2299
2300    fn resolved_min_width(&self, metrics: ControlMetrics) -> f32 {
2301        self.min_width.unwrap_or(metrics.action_card_min_width)
2302    }
2303
2304    fn resolved_min_height(&self, metrics: ControlMetrics) -> f32 {
2305        self.min_height.unwrap_or(metrics.action_card_min_height)
2306    }
2307
2308    fn activate(&mut self, ctx: &mut EventCtx) {
2309        if !self.is_enabled() {
2310            return;
2311        }
2312        if let Some(on_press) = &mut self.on_press {
2313            on_press();
2314        }
2315        if let Some(on_press) = &mut self.on_press_with_ctx {
2316            on_press(ctx);
2317        }
2318    }
2319
2320    fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
2321        if self.hovered == hovered {
2322            return;
2323        }
2324        let theme = self.resolved_theme();
2325        self.hovered = hovered;
2326        set_action_card_hover_animation_target(
2327            &mut self.hover_animation,
2328            hovered as u8 as f32,
2329            &theme,
2330            ctx,
2331        );
2332        ctx.request_paint();
2333        ctx.request_semantics();
2334    }
2335
2336    fn advance_animations(&mut self, time: f64) -> bool {
2337        self.hover_animation.advance(time)
2338            | self.press_animation.advance(time)
2339            | self.focus_animation.advance(time)
2340    }
2341
2342    fn clear_transient_state_for_hidden_bounds(&mut self, ctx: &mut ArrangeCtx) {
2343        if !self.hovered && !self.pressed && !self.focus_animation.is_presented() {
2344            return;
2345        }
2346
2347        self.hovered = false;
2348        self.pressed = false;
2349        self.hover_animation = AnimatedScalar::new(0.0);
2350        self.press_animation = AnimatedScalar::new(0.0);
2351        self.focus_animation = AnimatedScalar::new(0.0);
2352        ctx.request_paint();
2353        ctx.request_semantics();
2354    }
2355
2356    fn resolved_title_style(&self) -> TextStyle {
2357        let theme = self.resolved_theme();
2358        TextStyle {
2359            weight: FontWeight::SEMIBOLD,
2360            ..text_token_style(&theme, theme.text.base, theme.palette.text)
2361        }
2362    }
2363
2364    fn resolved_description_style(&self) -> TextStyle {
2365        let theme = self.resolved_theme();
2366        text_token_style(&theme, theme.text.sm, theme.palette.text_muted)
2367    }
2368
2369    fn content_rect(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
2370        inset_rect(bounds, self.resolved_padding(metrics))
2371    }
2372
2373    fn text_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
2374        let content = self.content_rect(bounds, metrics);
2375        let icon_extent = self
2376            .icon
2377            .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
2378            .unwrap_or(0.0);
2379        let trailing = metrics.action_card_trailing_gap;
2380        Rect::new(
2381            content.x() + icon_extent,
2382            content.y(),
2383            (content.width() - icon_extent - trailing).max(0.0),
2384            content.height(),
2385        )
2386    }
2387}
2388
2389impl Widget for ActionCard {
2390    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2391        if !self.is_enabled() {
2392            if self.hovered || self.pressed {
2393                let theme = self.resolved_theme();
2394                self.hovered = false;
2395                self.pressed = false;
2396                set_action_card_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
2397                set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2398                ctx.request_paint();
2399                ctx.request_semantics();
2400            }
2401            return;
2402        }
2403
2404        match event {
2405            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2406                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2407            }
2408            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
2409                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
2410            }
2411            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
2412                self.set_hovered(false, ctx);
2413            }
2414            Event::Pointer(pointer)
2415                if pointer.kind == PointerEventKind::Down
2416                    && pointer.button == Some(PointerButton::Primary) =>
2417            {
2418                let theme = self.resolved_theme();
2419                self.pressed = true;
2420                self.hovered = true;
2421                set_action_card_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
2422                set_action_card_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
2423                ctx.request_pointer_capture(pointer.pointer_id);
2424                ctx.request_focus();
2425                ctx.request_paint();
2426                ctx.request_semantics();
2427                ctx.set_handled();
2428            }
2429            Event::Pointer(pointer)
2430                if pointer.kind == PointerEventKind::Up
2431                    && pointer.button == Some(PointerButton::Primary) =>
2432            {
2433                let theme = self.resolved_theme();
2434                let hovered = ctx.bounds().contains(pointer.position);
2435                let activate = self.pressed && hovered;
2436                self.pressed = false;
2437                self.hovered = hovered;
2438                set_action_card_hover_animation_target(
2439                    &mut self.hover_animation,
2440                    hovered as u8 as f32,
2441                    &theme,
2442                    ctx,
2443                );
2444                set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
2445                ctx.release_pointer_capture(pointer.pointer_id);
2446                if activate {
2447                    self.activate(ctx);
2448                }
2449                ctx.request_paint();
2450                ctx.request_semantics();
2451                ctx.set_handled();
2452            }
2453            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2454                if self.pressed {
2455                    let theme = self.resolved_theme();
2456                    self.pressed = false;
2457                    self.hovered = false;
2458                    set_action_card_hover_animation_target(
2459                        &mut self.hover_animation,
2460                        0.0,
2461                        &theme,
2462                        ctx,
2463                    );
2464                    set_action_card_press_animation_target(
2465                        &mut self.press_animation,
2466                        0.0,
2467                        &theme,
2468                        ctx,
2469                    );
2470                    ctx.release_pointer_capture(pointer.pointer_id);
2471                    ctx.request_paint();
2472                    ctx.request_semantics();
2473                    ctx.set_handled();
2474                }
2475            }
2476            Event::Keyboard(key)
2477                if key.state == KeyState::Pressed
2478                    && ctx.is_focused()
2479                    && matches!(key.key.as_str(), "Enter" | " ") =>
2480            {
2481                self.activate(ctx);
2482                ctx.request_paint();
2483                ctx.request_semantics();
2484                ctx.set_handled();
2485            }
2486            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
2487                if self.advance_animations(*time) {
2488                    ctx.request_animation_frame();
2489                }
2490                ctx.request_paint();
2491            }
2492            _ => {}
2493        }
2494    }
2495
2496    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2497        let theme = self.resolved_theme();
2498        let metrics = theme.metrics;
2499        let padding = self.resolved_padding(metrics);
2500        let title_style = self.resolved_title_style();
2501        let description_style = self.resolved_description_style();
2502        let title = measure_text(ctx, &self.title, &title_style);
2503        let description = measure_text(ctx, &self.description, &description_style);
2504        self.title_measurement = Some(title);
2505        self.description_measurement = Some(description);
2506
2507        let icon_extent = self
2508            .icon
2509            .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
2510            .unwrap_or(0.0);
2511        let text_width = title.width.max(description.width).min(320.0);
2512        let natural = Size::new(
2513            self.resolved_min_width(metrics).max(
2514                padding.left
2515                    + icon_extent
2516                    + text_width
2517                    + metrics.action_card_trailing_gap
2518                    + padding.right,
2519            ),
2520            self.resolved_min_height(metrics).max(
2521                padding.top
2522                    + title.height.max(title_style.line_height)
2523                    + metrics.action_card_text_gap
2524                    + description.height.max(description_style.line_height)
2525                    + padding.bottom,
2526            ),
2527        );
2528        constraints.clamp(natural)
2529    }
2530
2531    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2532        if bounds.width() <= 0.0 || bounds.height() <= 0.0 {
2533            self.clear_transient_state_for_hidden_bounds(ctx);
2534        }
2535    }
2536
2537    fn paint(&self, ctx: &mut PaintCtx) {
2538        let theme = self.resolved_theme();
2539        let palette = theme.palette;
2540        let metrics = theme.metrics;
2541        let enabled = self.is_enabled();
2542        let hover = if enabled {
2543            self.hover_animation.value
2544        } else {
2545            0.0
2546        };
2547        let press = if enabled {
2548            self.press_animation.value
2549        } else {
2550            0.0
2551        };
2552        let accent = self
2553            .accent
2554            .unwrap_or_else(|| theme.semantic_tone_color(self.tone));
2555        let mut background = mix_color(palette.control, palette.control_hover, hover);
2556        background = mix_color(background, palette.control_active, press * 0.55);
2557        if !enabled {
2558            background = mix_color(background, palette.surface, 0.68).with_alpha(0.82);
2559        }
2560        let border = if !enabled {
2561            palette.border.with_alpha(0.55)
2562        } else if ctx.is_focused() {
2563            palette.border_focus
2564        } else {
2565            mix_color(palette.border, palette.border_hover, hover)
2566        };
2567
2568        // Elevation shadow behind the raised card surface, drawn before the
2569        // fill so the soft shadow is not clipped.
2570        if enabled {
2571            paint_theme_shadow(
2572                ctx,
2573                ctx.bounds(),
2574                [metrics.corner_radius; 4],
2575                &theme.shadows.box_shadow.md,
2576            );
2577        }
2578
2579        draw_control_frame(
2580            ctx,
2581            ctx.bounds(),
2582            metrics.corner_radius,
2583            metrics,
2584            background,
2585            border,
2586            (self.focus_animation.value > AnimatedScalar::EPSILON && enabled).then_some(
2587                palette
2588                    .focus_ring
2589                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
2590            ),
2591        );
2592
2593        let bounds = ctx.bounds();
2594        let content = self.content_rect(bounds, metrics);
2595        let accent_inset = metrics.action_card_accent_inset.min(bounds.height() * 0.5);
2596        let accent_height = (bounds.height() - accent_inset * 2.0).max(0.0);
2597        let accent_rail = Rect::new(
2598            bounds.x(),
2599            bounds.y() + accent_inset,
2600            metrics.action_card_accent_width,
2601            accent_height,
2602        );
2603        ctx.fill(
2604            rounded_rect_path(accent_rail, metrics.action_card_accent_width * 0.5),
2605            accent.with_alpha(0.78),
2606        );
2607
2608        if let Some(icon) = self.icon {
2609            let icon_box_size = metrics
2610                .action_card_icon_box_size
2611                .min(content.width())
2612                .min(content.height())
2613                .max(0.0);
2614            let icon_box = Rect::new(
2615                content.x(),
2616                content.y() + ((content.height() - icon_box_size) * 0.5),
2617                icon_box_size,
2618                icon_box_size,
2619            );
2620            ctx.fill(
2621                rounded_rect_path(icon_box, metrics.corner_radius),
2622                mix_color(background, accent, 0.14),
2623            );
2624            ctx.stroke(
2625                rounded_rect_path(icon_box, metrics.corner_radius),
2626                accent.with_alpha(if enabled { 0.42 } else { 0.22 }),
2627                StrokeStyle::new(physical_pixels(ctx, 1.0)),
2628            );
2629            let icon_size = metrics
2630                .action_card_icon_size
2631                .min(icon_box.width())
2632                .min(icon_box.height())
2633                .max(0.0);
2634            let icon_rect = Rect::new(
2635                icon_box.x() + ((icon_box.width() - icon_size) * 0.5),
2636                icon_box.y() + ((icon_box.height() - icon_size) * 0.5),
2637                icon_size,
2638                icon_size,
2639            );
2640            draw_icon_glyph(
2641                ctx,
2642                icon,
2643                icon_rect,
2644                if enabled {
2645                    accent
2646                } else {
2647                    palette.text.with_alpha(0.34)
2648                },
2649            );
2650        }
2651
2652        let text_bounds = self.text_bounds(bounds, metrics);
2653        let title_style = self.resolved_title_style();
2654        let description_style = self.resolved_description_style();
2655        let title_height = title_style.line_height.max(
2656            self.title_measurement
2657                .map(|measurement| measurement.height)
2658                .unwrap_or(title_style.line_height),
2659        );
2660        let description_min_height = description_style.line_height.max(
2661            self.description_measurement
2662                .map(|measurement| measurement.height)
2663                .unwrap_or(description_style.line_height),
2664        );
2665        let description_height =
2666            (text_bounds.height() - title_height - metrics.action_card_text_gap)
2667                .max(description_min_height)
2668                .min((description_style.line_height * 2.0).max(description_min_height));
2669        let text_block_height = title_height + metrics.action_card_text_gap + description_height;
2670        let text_y = text_bounds.y() + ((text_bounds.height() - text_block_height) * 0.5).max(0.0);
2671        let title_slot = Rect::new(text_bounds.x(), text_y, text_bounds.width(), title_height);
2672        let description_slot = Rect::new(
2673            text_bounds.x(),
2674            title_slot.max_y() + metrics.action_card_text_gap,
2675            text_bounds.width(),
2676            description_height,
2677        );
2678        let title_paint_style = TextStyle {
2679            color: if enabled {
2680                palette.text
2681            } else {
2682                palette.text.with_alpha(0.45)
2683            },
2684            ..title_style
2685        };
2686        let description_paint_style = TextStyle {
2687            color: if enabled {
2688                palette.placeholder
2689            } else {
2690                palette.placeholder.with_alpha(0.45)
2691            },
2692            ..description_style
2693        };
2694        let description_layout = {
2695            let mut layout_style = description_paint_style.clone();
2696            layout_style.color = Color::WHITE;
2697            ctx.shape_text(
2698                self.description.clone(),
2699                Size::new(
2700                    description_slot.width().max(1.0),
2701                    description_slot.height().max(1.0),
2702                ),
2703                layout_style,
2704            )
2705            .ok()
2706        };
2707        ctx.push_clip_rect(title_slot);
2708        paint_aligned_text(
2709            ctx,
2710            title_slot,
2711            &self.title,
2712            &title_paint_style,
2713            title_paint_style.line_height,
2714            0.0,
2715        );
2716        ctx.pop_clip();
2717        ctx.push_clip_rect(description_slot);
2718        if let Some(layout) = description_layout.filter(|layout| layout.lines().len() > 1) {
2719            let measurement = layout.measurement();
2720            let width = measurement.width.min(description_slot.width()).max(0.0);
2721            let height = description_paint_style
2722                .line_height
2723                .max(measurement.height)
2724                .min(description_slot.height());
2725            let description_rect = Rect::new(
2726                description_slot.x(),
2727                description_slot.y() + ((description_slot.height() - height).max(0.0) * 0.5),
2728                width,
2729                height,
2730            );
2731            ctx.draw_text_layout_with_color(
2732                description_rect.origin,
2733                &layout,
2734                description_paint_style.color,
2735            );
2736        } else {
2737            paint_aligned_text(
2738                ctx,
2739                description_slot,
2740                &self.description,
2741                &description_paint_style,
2742                description_paint_style.line_height,
2743                0.0,
2744            );
2745        }
2746        ctx.pop_clip();
2747
2748        let chevron_size = metrics
2749            .action_card_chevron_size
2750            .min(content.width())
2751            .min(content.height())
2752            .max(0.0);
2753        let chevron = Rect::new(
2754            content.max_x() - chevron_size,
2755            content.y() + ((content.height() - chevron_size) * 0.5),
2756            chevron_size,
2757            chevron_size,
2758        );
2759        draw_icon_glyph(
2760            ctx,
2761            IconGlyph::ChevronRight,
2762            chevron,
2763            if enabled {
2764                mix_color(palette.placeholder, accent, hover * 0.45).with_alpha(0.74)
2765            } else {
2766                palette.placeholder.with_alpha(0.32)
2767            },
2768        );
2769    }
2770
2771    fn semantics(&self, ctx: &mut SemanticsCtx) {
2772        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
2773        node.name = Some(self.title.clone());
2774        node.description = Some(self.description.clone());
2775        node.value = Some(SemanticsValue::Text(self.description.clone()));
2776        node.state.focused = ctx.is_focused();
2777        node.state.hovered = self.hovered && self.is_enabled();
2778        node.state.disabled = !self.is_enabled();
2779        node.actions = if self.is_enabled() {
2780            vec![SemanticsAction::Focus, SemanticsAction::Activate]
2781        } else {
2782            Vec::new()
2783        };
2784        ctx.push(node);
2785    }
2786
2787    fn accepts_focus(&self) -> bool {
2788        self.is_enabled()
2789    }
2790
2791    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2792        let theme = self.resolved_theme();
2793        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2794        ctx.request_paint();
2795        ctx.request_semantics();
2796    }
2797}
2798
2799fn set_animation_target(
2800    animation: &mut AnimatedScalar,
2801    target: f32,
2802    duration: f64,
2803    easing: crate::Easing,
2804    ctx: &mut EventCtx,
2805) -> bool {
2806    animation.set_target_event(target, duration, easing, ctx)
2807}
2808
2809fn set_hover_animation_target(
2810    animation: &mut AnimatedScalar,
2811    target: f32,
2812    theme: &DefaultTheme,
2813    ctx: &mut EventCtx,
2814) -> bool {
2815    set_animation_target(
2816        animation,
2817        target,
2818        theme.motion.hover_duration(),
2819        theme.motion.hover_easing(),
2820        ctx,
2821    )
2822}
2823
2824fn set_press_animation_target(
2825    animation: &mut AnimatedScalar,
2826    target: f32,
2827    theme: &DefaultTheme,
2828    ctx: &mut EventCtx,
2829) -> bool {
2830    set_animation_target(
2831        animation,
2832        target,
2833        theme.motion.press_duration(),
2834        theme.motion.press_easing(),
2835        ctx,
2836    )
2837}
2838
2839fn set_focus_animation_target(
2840    animation: &mut AnimatedScalar,
2841    target: f32,
2842    theme: &DefaultTheme,
2843    ctx: &mut EventCtx,
2844) -> bool {
2845    set_animation_target(
2846        animation,
2847        target,
2848        theme.motion.focus_duration(),
2849        theme.motion.focus_easing(),
2850        ctx,
2851    )
2852}
2853
2854fn set_action_card_animation_target(
2855    animation: &mut AnimatedScalar,
2856    target: f32,
2857    duration: f64,
2858    easing: crate::Easing,
2859    ctx: &mut EventCtx,
2860) {
2861    set_animation_target(animation, target, duration, easing, ctx);
2862}
2863
2864fn set_action_card_hover_animation_target(
2865    animation: &mut AnimatedScalar,
2866    target: f32,
2867    theme: &DefaultTheme,
2868    ctx: &mut EventCtx,
2869) {
2870    set_action_card_animation_target(
2871        animation,
2872        target,
2873        theme.motion.hover_duration(),
2874        theme.motion.hover_easing(),
2875        ctx,
2876    );
2877}
2878
2879fn set_action_card_press_animation_target(
2880    animation: &mut AnimatedScalar,
2881    target: f32,
2882    theme: &DefaultTheme,
2883    ctx: &mut EventCtx,
2884) {
2885    set_action_card_animation_target(
2886        animation,
2887        target,
2888        theme.motion.press_duration(),
2889        theme.motion.press_easing(),
2890        ctx,
2891    );
2892}
2893
2894#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2895pub enum PropertyRowLayout {
2896    Stacked,
2897    Inline,
2898}
2899
2900#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2901enum PropertyRowDefaults {
2902    Property,
2903    Form,
2904}
2905
2906pub struct PropertyRow {
2907    theme: Box<DefaultTheme>,
2908    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2909    label: String,
2910    defaults: PropertyRowDefaults,
2911    layout: PropertyRowLayout,
2912    label_width: Option<f32>,
2913    control_width: Option<f32>,
2914    auto_control_width: bool,
2915    gap: Option<f32>,
2916    label_style: Option<TextStyle>,
2917    child: SingleChild,
2918    label_measurement: Option<TextMeasurement>,
2919}
2920
2921impl PropertyRow {
2922    pub fn new<W>(label: impl Into<String>, control: W) -> Self
2923    where
2924        W: Widget + 'static,
2925    {
2926        Self {
2927            theme: Box::new(DefaultTheme::default()),
2928            theme_reader: None,
2929            label: label.into(),
2930            defaults: PropertyRowDefaults::Property,
2931            layout: PropertyRowLayout::Stacked,
2932            label_width: None,
2933            control_width: None,
2934            auto_control_width: true,
2935            gap: None,
2936            label_style: None,
2937            child: SingleChild::new(control),
2938            label_measurement: None,
2939        }
2940    }
2941
2942    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2943        self.theme = Box::new(theme);
2944        self.theme_reader = None;
2945        self
2946    }
2947
2948    pub fn theme_when<F>(mut self, theme: F) -> Self
2949    where
2950        F: Fn() -> DefaultTheme + 'static,
2951    {
2952        self.theme_reader = Some(Box::new(theme));
2953        self
2954    }
2955
2956    pub fn layout(mut self, layout: PropertyRowLayout) -> Self {
2957        self.layout = layout;
2958        self
2959    }
2960
2961    pub fn stacked(self) -> Self {
2962        self.layout(PropertyRowLayout::Stacked)
2963    }
2964
2965    pub fn inline(self) -> Self {
2966        self.layout(PropertyRowLayout::Inline)
2967    }
2968
2969    pub fn label_width(mut self, width: f32) -> Self {
2970        self.label_width = Some(width.max(0.0));
2971        self
2972    }
2973
2974    pub fn control_width(mut self, width: f32) -> Self {
2975        self.control_width = Some(width.max(0.0));
2976        self.auto_control_width = false;
2977        self
2978    }
2979
2980    pub fn auto_control_width(mut self) -> Self {
2981        self.control_width = None;
2982        self.auto_control_width = true;
2983        self
2984    }
2985
2986    pub fn gap(mut self, gap: f32) -> Self {
2987        self.gap = Some(gap.max(0.0));
2988        self
2989    }
2990
2991    pub fn label_style(mut self, style: TextStyle) -> Self {
2992        self.label_style = Some(style);
2993        self
2994    }
2995
2996    pub fn child(&self) -> &sui_runtime::WidgetPod {
2997        self.child.child()
2998    }
2999
3000    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
3001        self.child.child_mut()
3002    }
3003
3004    fn resolved_label_style(&self) -> TextStyle {
3005        let theme = self.resolved_theme();
3006        self.label_style
3007            .clone()
3008            .unwrap_or_else(|| text_token_style(&theme, theme.text.sm, theme.palette.text_muted))
3009    }
3010
3011    fn resolved_theme(&self) -> DefaultTheme {
3012        self.theme_reader
3013            .as_ref()
3014            .map(|theme| theme())
3015            .unwrap_or(*self.theme)
3016    }
3017
3018    fn with_form_defaults(mut self) -> Self {
3019        self.defaults = PropertyRowDefaults::Form;
3020        self.auto_control_width = true;
3021        self
3022    }
3023
3024    fn resolved_label_width(&self, metrics: ControlMetrics) -> f32 {
3025        self.label_width.unwrap_or(match self.defaults {
3026            PropertyRowDefaults::Property => metrics.property_row_label_width,
3027            PropertyRowDefaults::Form => metrics.form_row_label_width,
3028        })
3029    }
3030
3031    fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
3032        self.gap.unwrap_or(match self.defaults {
3033            PropertyRowDefaults::Form => metrics.form_row_gap,
3034            PropertyRowDefaults::Property => match self.layout {
3035                PropertyRowLayout::Stacked => metrics.property_row_stacked_gap,
3036                PropertyRowLayout::Inline => metrics.property_row_inline_gap,
3037            },
3038        })
3039    }
3040
3041    fn resolved_control_width(&self, metrics: ControlMetrics) -> Option<f32> {
3042        if self.auto_control_width {
3043            None
3044        } else {
3045            self.control_width.or_else(|| {
3046                matches!(self.defaults, PropertyRowDefaults::Form)
3047                    .then_some(metrics.form_row_control_width)
3048            })
3049        }
3050    }
3051
3052    fn label_height(&self, style: &TextStyle) -> f32 {
3053        self.label_measurement
3054            .map(|measurement| measurement.height)
3055            .unwrap_or(style.line_height)
3056            .max(style.line_height)
3057    }
3058
3059    fn child_constraints(
3060        &self,
3061        constraints: Constraints,
3062        label_extent: f32,
3063        metrics: ControlMetrics,
3064    ) -> Constraints {
3065        let max_width = constraints.max.width;
3066        let gap = self.resolved_gap(metrics);
3067        let available = match self.layout {
3068            PropertyRowLayout::Stacked => max_width,
3069            PropertyRowLayout::Inline => {
3070                if max_width.is_finite() {
3071                    (max_width - label_extent - gap).max(0.0)
3072                } else {
3073                    f32::INFINITY
3074                }
3075            }
3076        };
3077        let width = self
3078            .resolved_control_width(metrics)
3079            .map(|width| width.min(available).max(0.0));
3080
3081        match width {
3082            Some(width) => Constraints::new(
3083                Size::new(width, 0.0),
3084                Size::new(width, constraints.max.height),
3085            ),
3086            None => Constraints::new(Size::ZERO, Size::new(available, constraints.max.height)),
3087        }
3088    }
3089
3090    fn child_width_for_bounds(
3091        &self,
3092        bounds: Rect,
3093        label_extent: f32,
3094        metrics: ControlMetrics,
3095    ) -> f32 {
3096        let gap = self.resolved_gap(metrics);
3097        let available = match self.layout {
3098            PropertyRowLayout::Stacked => bounds.width(),
3099            PropertyRowLayout::Inline => (bounds.width() - label_extent - gap).max(0.0),
3100        };
3101        self.resolved_control_width(metrics)
3102            .unwrap_or(available)
3103            .min(available)
3104            .max(0.0)
3105    }
3106}
3107
3108impl Widget for PropertyRow {
3109    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3110        let theme = self.resolved_theme();
3111        let metrics = theme.metrics;
3112        let gap = self.resolved_gap(metrics);
3113        let label_style = self.resolved_label_style();
3114        let label_measurement = measure_text(ctx, &self.label, &label_style);
3115        self.label_measurement = Some(label_measurement);
3116        let label_height = self.label_height(&label_style);
3117        let label_extent = match self.layout {
3118            PropertyRowLayout::Stacked => label_measurement.width,
3119            PropertyRowLayout::Inline => self
3120                .resolved_label_width(metrics)
3121                .max(label_measurement.width),
3122        };
3123        let child_size = self.child.measure(
3124            ctx,
3125            self.child_constraints(constraints, label_extent, metrics),
3126        );
3127        let natural = match self.layout {
3128            PropertyRowLayout::Stacked => Size::new(
3129                label_measurement.width.max(child_size.width),
3130                label_height + gap + child_size.height,
3131            ),
3132            PropertyRowLayout::Inline => Size::new(
3133                label_extent + gap + child_size.width,
3134                label_height.max(child_size.height),
3135            ),
3136        };
3137
3138        constraints.clamp(natural)
3139    }
3140
3141    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3142        let theme = self.resolved_theme();
3143        let metrics = theme.metrics;
3144        let gap = self.resolved_gap(metrics);
3145        let label_style = self.resolved_label_style();
3146        let label_height = self.label_height(&label_style);
3147        let label_width = match self.layout {
3148            PropertyRowLayout::Stacked => bounds.width(),
3149            PropertyRowLayout::Inline => self
3150                .resolved_label_width(metrics)
3151                .min(bounds.width())
3152                .max(0.0),
3153        };
3154        let child_measured = self.child.child().measured_size();
3155        let child_width = self.child_width_for_bounds(bounds, label_width, metrics);
3156        let child_height = child_measured.height.min(bounds.height()).max(0.0);
3157
3158        let child_bounds = match self.layout {
3159            PropertyRowLayout::Stacked => Rect::new(
3160                bounds.x(),
3161                bounds.y() + label_height + gap,
3162                child_width,
3163                child_height.min((bounds.height() - label_height - gap).max(0.0)),
3164            ),
3165            PropertyRowLayout::Inline => Rect::new(
3166                bounds.x() + label_width + gap,
3167                bounds.y() + ((bounds.height() - child_height) * 0.5).max(0.0),
3168                child_width,
3169                child_height,
3170            ),
3171        };
3172        self.child.arrange(ctx, child_bounds);
3173    }
3174
3175    fn paint(&self, ctx: &mut PaintCtx) {
3176        let theme = self.resolved_theme();
3177        let metrics = theme.metrics;
3178        let label_style = self.resolved_label_style();
3179        let label_height = self.label_height(&label_style);
3180        let bounds = ctx.bounds();
3181        let label_rect = match self.layout {
3182            PropertyRowLayout::Stacked => {
3183                Rect::new(bounds.x(), bounds.y(), bounds.width(), label_height)
3184            }
3185            PropertyRowLayout::Inline => Rect::new(
3186                bounds.x(),
3187                bounds.y() + ((bounds.height() - label_height) * 0.5).max(0.0),
3188                self.resolved_label_width(metrics)
3189                    .min(bounds.width())
3190                    .max(0.0),
3191                label_height,
3192            ),
3193        };
3194        ctx.push_clip_rect(label_rect);
3195        paint_single_line_aligned_text(
3196            ctx,
3197            label_rect,
3198            &self.label,
3199            &label_style,
3200            label_height,
3201            0.0,
3202        );
3203        ctx.pop_clip();
3204        self.child.paint(ctx);
3205    }
3206
3207    fn semantics(&self, ctx: &mut SemanticsCtx) {
3208        let theme = self.resolved_theme();
3209        let metrics = theme.metrics;
3210        let mut row = SemanticsNode::new(
3211            ctx.widget_id(),
3212            SemanticsRole::GenericContainer,
3213            ctx.bounds(),
3214        );
3215        row.name = Some(self.label.clone());
3216        ctx.push(row);
3217
3218        let label_style = self.resolved_label_style();
3219        let label_height = self.label_height(&label_style);
3220        let label_bounds = match self.layout {
3221            PropertyRowLayout::Stacked => Rect::new(
3222                ctx.bounds().x(),
3223                ctx.bounds().y(),
3224                ctx.bounds().width(),
3225                label_height,
3226            ),
3227            PropertyRowLayout::Inline => Rect::new(
3228                ctx.bounds().x(),
3229                ctx.bounds().y() + ((ctx.bounds().height() - label_height) * 0.5).max(0.0),
3230                self.resolved_label_width(metrics)
3231                    .min(ctx.bounds().width())
3232                    .max(0.0),
3233                label_height,
3234            ),
3235        };
3236        let mut label = SemanticsNode::new(
3237            property_row_label_id(ctx.widget_id()),
3238            SemanticsRole::Text,
3239            label_bounds,
3240        );
3241        label.parent = Some(ctx.widget_id());
3242        label.name = Some(self.label.clone());
3243        label.value = Some(SemanticsValue::Text(self.label.clone()));
3244        ctx.push(label);
3245
3246        self.child.semantics(ctx);
3247    }
3248
3249    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3250        self.child.visit_children(visitor);
3251    }
3252
3253    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3254        self.child.visit_children_mut(visitor);
3255    }
3256}
3257
3258fn property_row_label_id(parent: WidgetId) -> WidgetId {
3259    const TAG: u64 = 1_u64 << 51;
3260    const LOW_MASK: u64 = (1_u64 << 51) - 1;
3261
3262    WidgetId::new(TAG | (parent.get().wrapping_mul(271).wrapping_add(1) & LOW_MASK))
3263}
3264
3265pub struct SectionLabel {
3266    theme: Box<DefaultTheme>,
3267    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3268    label: String,
3269    semantic_name: Option<String>,
3270    color: Option<Color>,
3271}
3272
3273impl SectionLabel {
3274    pub fn new(label: impl Into<String>) -> Self {
3275        Self {
3276            theme: Box::new(DefaultTheme::default()),
3277            theme_reader: None,
3278            label: label.into(),
3279            semantic_name: None,
3280            color: None,
3281        }
3282    }
3283
3284    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3285        self.theme = Box::new(theme);
3286        self.theme_reader = None;
3287        self
3288    }
3289
3290    pub fn theme_when<F>(mut self, theme: F) -> Self
3291    where
3292        F: Fn() -> DefaultTheme + 'static,
3293    {
3294        self.theme_reader = Some(Box::new(theme));
3295        self
3296    }
3297
3298    pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
3299        self.semantic_name = Some(name.into());
3300        self
3301    }
3302
3303    pub fn color(mut self, color: Color) -> Self {
3304        self.color = Some(color);
3305        self
3306    }
3307
3308    fn resolved_theme(&self) -> DefaultTheme {
3309        self.theme_reader
3310            .as_ref()
3311            .map(|theme| theme())
3312            .unwrap_or(*self.theme)
3313    }
3314
3315    fn display_text(&self) -> String {
3316        self.label.to_uppercase()
3317    }
3318
3319    fn text_style(&self, theme: &DefaultTheme) -> TextStyle {
3320        section_label_text_style(theme, self.color)
3321    }
3322}
3323
3324impl Widget for SectionLabel {
3325    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3326        let theme = self.resolved_theme();
3327        let style = self.text_style(&theme);
3328        let text = self.display_text();
3329        let measured = measure_text(ctx, &text, &style);
3330        constraints.clamp(Size::new(measured.width, style.line_height))
3331    }
3332
3333    fn paint(&self, ctx: &mut PaintCtx) {
3334        let theme = self.resolved_theme();
3335        let style = self.text_style(&theme);
3336        let text = self.display_text();
3337        ctx.push_clip_rect(ctx.bounds());
3338        paint_single_line_aligned_text(ctx, ctx.bounds(), &text, &style, style.line_height, 0.0);
3339        ctx.pop_clip();
3340    }
3341
3342    fn semantics(&self, ctx: &mut SemanticsCtx) {
3343        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
3344        let name = self
3345            .semantic_name
3346            .clone()
3347            .unwrap_or_else(|| self.label.clone());
3348        node.name = Some(name.clone());
3349        node.value = Some(SemanticsValue::Text(name));
3350        ctx.push(node);
3351    }
3352}
3353
3354#[derive(Debug, Clone, Copy, Default)]
3355pub struct SectionLabelPaint {
3356    color: Option<Color>,
3357}
3358
3359impl SectionLabelPaint {
3360    pub const fn new() -> Self {
3361        Self { color: None }
3362    }
3363
3364    pub const fn color(mut self, color: Color) -> Self {
3365        self.color = Some(color);
3366        self
3367    }
3368}
3369
3370pub fn paint_section_label(
3371    ctx: &mut PaintCtx,
3372    theme: &DefaultTheme,
3373    rect: Rect,
3374    label: &str,
3375    paint: SectionLabelPaint,
3376) {
3377    let style = section_label_text_style(theme, paint.color);
3378    let text = label.to_uppercase();
3379    ctx.push_clip_rect(rect);
3380    paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
3381    ctx.pop_clip();
3382}
3383
3384pub fn paint_section_label_detail(
3385    ctx: &mut PaintCtx,
3386    theme: &DefaultTheme,
3387    rect: Rect,
3388    label: &str,
3389    detail: &str,
3390    paint: SectionLabelPaint,
3391) {
3392    let style = section_label_text_style(theme, paint.color);
3393    let text = if detail.trim().is_empty() {
3394        label.to_uppercase()
3395    } else {
3396        format!("{} · {detail}", label.to_uppercase())
3397    };
3398    ctx.push_clip_rect(rect);
3399    paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
3400    ctx.pop_clip();
3401}
3402
3403fn section_label_text_style(theme: &DefaultTheme, color: Option<Color>) -> TextStyle {
3404    let mut style = text_token_style(
3405        theme,
3406        theme.text.xs,
3407        color.unwrap_or(theme.surfaces.text_faint),
3408    );
3409    style.weight = FontWeight::SEMIBOLD;
3410    style.line_height = style.line_height.max(14.0);
3411    style
3412}
3413
3414pub struct DetailRow {
3415    theme: Box<DefaultTheme>,
3416    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3417    label: String,
3418    label_reader: Option<Box<dyn Fn() -> String>>,
3419    value: String,
3420    value_reader: Option<Box<dyn Fn() -> String>>,
3421    max_value_lines: Option<usize>,
3422}
3423
3424impl DetailRow {
3425    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
3426        Self {
3427            theme: Box::new(DefaultTheme::default()),
3428            theme_reader: None,
3429            label: label.into(),
3430            label_reader: None,
3431            value: value.into(),
3432            value_reader: None,
3433            max_value_lines: None,
3434        }
3435    }
3436
3437    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3438        self.theme = Box::new(theme);
3439        self.theme_reader = None;
3440        self
3441    }
3442
3443    pub fn theme_when<F>(mut self, theme: F) -> Self
3444    where
3445        F: Fn() -> DefaultTheme + 'static,
3446    {
3447        self.theme_reader = Some(Box::new(theme));
3448        self
3449    }
3450
3451    pub fn label_when<F>(mut self, label: F) -> Self
3452    where
3453        F: Fn() -> String + 'static,
3454    {
3455        self.label_reader = Some(Box::new(label));
3456        self
3457    }
3458
3459    pub fn value_when<F>(mut self, value: F) -> Self
3460    where
3461        F: Fn() -> String + 'static,
3462    {
3463        self.value_reader = Some(Box::new(value));
3464        self
3465    }
3466
3467    pub fn max_value_lines(mut self, max_lines: usize) -> Self {
3468        self.max_value_lines = Some(max_lines.max(1));
3469        self
3470    }
3471
3472    fn label(&self) -> String {
3473        self.label_reader
3474            .as_ref()
3475            .map(|reader| reader())
3476            .unwrap_or_else(|| self.label.clone())
3477    }
3478
3479    fn value(&self) -> String {
3480        self.value_reader
3481            .as_ref()
3482            .map(|reader| reader())
3483            .unwrap_or_else(|| self.value.clone())
3484    }
3485
3486    fn resolved_theme(&self) -> DefaultTheme {
3487        self.theme_reader
3488            .as_ref()
3489            .map(|theme| theme())
3490            .unwrap_or(*self.theme)
3491    }
3492}
3493
3494impl Widget for DetailRow {
3495    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3496        let theme = self.resolved_theme();
3497        let label_style = detail_row_label_style(&theme);
3498        let value_style = detail_row_value_style(&theme);
3499        let width = if constraints.max.width.is_finite() {
3500            constraints.max.width.max(0.0)
3501        } else {
3502            let label = measure_text(ctx, &self.label().to_uppercase(), &label_style);
3503            let value = measure_text(ctx, &self.value(), &value_style);
3504            label.width.max(value.width)
3505        };
3506        let value = self.value();
3507        let lines = wrap_detail_row_value(&value, width, self.max_value_lines, |text| {
3508            measure_text(ctx, text, &value_style).width
3509        });
3510        constraints.clamp(Size::new(width, detail_row_height(&theme, lines.len())))
3511    }
3512
3513    fn paint(&self, ctx: &mut PaintCtx) {
3514        let theme = self.resolved_theme();
3515        paint_detail_row_at(
3516            ctx,
3517            &theme,
3518            Point::new(ctx.bounds().x(), ctx.bounds().y()),
3519            ctx.bounds().width(),
3520            &self.label(),
3521            &self.value(),
3522            self.max_value_lines,
3523        );
3524    }
3525
3526    fn semantics(&self, ctx: &mut SemanticsCtx) {
3527        let mut node = SemanticsNode::new(
3528            ctx.widget_id(),
3529            SemanticsRole::GenericContainer,
3530            ctx.bounds(),
3531        );
3532        node.name = Some(self.label());
3533        node.value = Some(SemanticsValue::Text(self.value()));
3534        ctx.push(node);
3535    }
3536}
3537
3538pub fn paint_detail_row_at(
3539    ctx: &mut PaintCtx,
3540    theme: &DefaultTheme,
3541    origin: Point,
3542    width: f32,
3543    label: &str,
3544    value: &str,
3545    max_value_lines: Option<usize>,
3546) -> f32 {
3547    let width = width.max(0.0);
3548    let label_style = detail_row_label_style(theme);
3549    let value_style = detail_row_value_style(theme);
3550    let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
3551        ctx.measure_text(text.to_string(), value_style.clone())
3552            .map(|measurement| measurement.width)
3553            .unwrap_or(0.0)
3554    });
3555    let height = detail_row_height(theme, lines.len());
3556    let clip = Rect::new(origin.x, origin.y, width, height);
3557
3558    ctx.push_clip_rect(clip);
3559    paint_aligned_text(
3560        ctx,
3561        Rect::new(origin.x, origin.y, width, label_style.line_height),
3562        &label.to_uppercase(),
3563        &label_style,
3564        label_style.line_height,
3565        0.0,
3566    );
3567
3568    let mut y = origin.y + label_style.line_height + detail_row_label_value_gap(theme);
3569    for line in lines {
3570        paint_aligned_text(
3571            ctx,
3572            Rect::new(origin.x, y, width, value_style.line_height),
3573            &line,
3574            &value_style,
3575            value_style.line_height,
3576            0.0,
3577        );
3578        y += value_style.line_height;
3579    }
3580    ctx.pop_clip();
3581    height
3582}
3583
3584pub fn detail_row_height_for_value(
3585    ctx: &PaintCtx,
3586    theme: &DefaultTheme,
3587    width: f32,
3588    value: &str,
3589    max_value_lines: Option<usize>,
3590) -> f32 {
3591    let width = width.max(0.0);
3592    let value_style = detail_row_value_style(theme);
3593    let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
3594        ctx.measure_text(text.to_string(), value_style.clone())
3595            .map(|measurement| measurement.width)
3596            .unwrap_or(0.0)
3597    });
3598    detail_row_height(theme, lines.len())
3599}
3600
3601fn detail_row_label_style(theme: &DefaultTheme) -> TextStyle {
3602    let mut style = text_token_style(theme, theme.text.xs, theme.palette.text_muted);
3603    style.weight = FontWeight::SEMIBOLD;
3604    style.line_height = style.line_height.max(14.0);
3605    style
3606}
3607
3608fn detail_row_value_style(theme: &DefaultTheme) -> TextStyle {
3609    let mut style = text_token_style(theme, theme.text.sm, theme.palette.text);
3610    style.line_height = style.line_height.max(17.0);
3611    style
3612}
3613
3614fn detail_row_label_value_gap(theme: &DefaultTheme) -> f32 {
3615    (theme.metrics.icon_label_gap * 0.35).max(2.0)
3616}
3617
3618fn detail_row_bottom_gap(theme: &DefaultTheme) -> f32 {
3619    theme.metrics.property_row_stacked_gap.max(6.0)
3620}
3621
3622fn detail_row_height(theme: &DefaultTheme, value_lines: usize) -> f32 {
3623    let label_style = detail_row_label_style(theme);
3624    let value_style = detail_row_value_style(theme);
3625    label_style.line_height
3626        + detail_row_label_value_gap(theme)
3627        + value_style.line_height * value_lines.max(1) as f32
3628        + detail_row_bottom_gap(theme)
3629}
3630
3631fn wrap_detail_row_value<F>(
3632    value: &str,
3633    width: f32,
3634    max_lines: Option<usize>,
3635    mut measure: F,
3636) -> Vec<String>
3637where
3638    F: FnMut(&str) -> f32,
3639{
3640    let max_lines = max_lines.unwrap_or(usize::MAX).max(1);
3641    let width = width.max(1.0);
3642    let mut lines = Vec::new();
3643
3644    for paragraph in value.split('\n') {
3645        if lines.len() >= max_lines {
3646            break;
3647        }
3648        let mut current = String::new();
3649        for word in paragraph.split_whitespace() {
3650            let candidate = if current.is_empty() {
3651                word.to_string()
3652            } else {
3653                format!("{current} {word}")
3654            };
3655            if current.is_empty() || measure(&candidate) <= width {
3656                current = candidate;
3657            } else {
3658                lines.push(std::mem::take(&mut current));
3659                if lines.len() >= max_lines {
3660                    break;
3661                }
3662                current = word.to_string();
3663            }
3664        }
3665        if lines.len() < max_lines {
3666            lines.push(current);
3667        }
3668    }
3669
3670    if lines.is_empty() {
3671        lines.push(String::new());
3672    }
3673    lines
3674}
3675
3676pub struct FormRow {
3677    row: PropertyRow,
3678}
3679
3680impl FormRow {
3681    pub fn new<W>(label: impl Into<String>, control: W) -> Self
3682    where
3683        W: Widget + 'static,
3684    {
3685        Self {
3686            row: PropertyRow::new(label, control)
3687                .inline()
3688                .with_form_defaults(),
3689        }
3690    }
3691
3692    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3693        self.row = self.row.theme(theme);
3694        self
3695    }
3696
3697    pub fn theme_when<F>(mut self, theme: F) -> Self
3698    where
3699        F: Fn() -> DefaultTheme + 'static,
3700    {
3701        self.row = self.row.theme_when(theme);
3702        self
3703    }
3704
3705    pub fn stacked(mut self) -> Self {
3706        self.row = self.row.stacked();
3707        self
3708    }
3709
3710    pub fn inline(mut self) -> Self {
3711        self.row = self.row.inline();
3712        self
3713    }
3714
3715    pub fn label_width(mut self, width: f32) -> Self {
3716        self.row = self.row.label_width(width);
3717        self
3718    }
3719
3720    pub fn control_width(mut self, width: f32) -> Self {
3721        self.row = self.row.control_width(width);
3722        self
3723    }
3724
3725    pub fn auto_control_width(mut self) -> Self {
3726        self.row = self.row.auto_control_width();
3727        self
3728    }
3729
3730    pub fn gap(mut self, gap: f32) -> Self {
3731        self.row = self.row.gap(gap);
3732        self
3733    }
3734
3735    pub fn label_style(mut self, style: TextStyle) -> Self {
3736        self.row = self.row.label_style(style);
3737        self
3738    }
3739
3740    pub fn child(&self) -> &sui_runtime::WidgetPod {
3741        self.row.child()
3742    }
3743
3744    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
3745        self.row.child_mut()
3746    }
3747}
3748
3749impl Widget for FormRow {
3750    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3751        self.row.measure(ctx, constraints)
3752    }
3753
3754    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3755        self.row.arrange(ctx, bounds);
3756    }
3757
3758    fn paint(&self, ctx: &mut PaintCtx) {
3759        self.row.paint(ctx);
3760    }
3761
3762    fn semantics(&self, ctx: &mut SemanticsCtx) {
3763        self.row.semantics(ctx);
3764    }
3765
3766    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3767        self.row.visit_children(visitor);
3768    }
3769
3770    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3771        self.row.visit_children_mut(visitor);
3772    }
3773}
3774
3775pub struct FieldGroup {
3776    theme: Box<DefaultTheme>,
3777    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3778    children: WidgetChildren,
3779    spacing: Option<f32>,
3780    padding: Insets,
3781    max_width: Option<f32>,
3782    fill_width: bool,
3783}
3784
3785impl FieldGroup {
3786    pub fn new() -> Self {
3787        Self {
3788            theme: Box::new(DefaultTheme::default()),
3789            theme_reader: None,
3790            children: WidgetChildren::new(),
3791            spacing: None,
3792            padding: Insets::ZERO,
3793            max_width: None,
3794            fill_width: false,
3795        }
3796    }
3797
3798    pub fn theme(mut self, theme: DefaultTheme) -> Self {
3799        self.theme = Box::new(theme);
3800        self.theme_reader = None;
3801        self
3802    }
3803
3804    pub fn theme_when<F>(mut self, theme: F) -> Self
3805    where
3806        F: Fn() -> DefaultTheme + 'static,
3807    {
3808        self.theme_reader = Some(Box::new(theme));
3809        self
3810    }
3811
3812    pub fn with_child<W>(mut self, child: W) -> Self
3813    where
3814        W: Widget + 'static,
3815    {
3816        self.children.push(child);
3817        self
3818    }
3819
3820    pub fn push<W>(&mut self, child: W)
3821    where
3822        W: Widget + 'static,
3823    {
3824        self.children.push(child);
3825    }
3826
3827    pub fn spacing(mut self, spacing: f32) -> Self {
3828        self.spacing = Some(spacing.max(0.0));
3829        self
3830    }
3831
3832    pub fn padding(mut self, padding: Insets) -> Self {
3833        self.padding = padding;
3834        self
3835    }
3836
3837    pub fn max_width(mut self, width: f32) -> Self {
3838        self.max_width = Some(width.max(0.0));
3839        self
3840    }
3841
3842    pub fn auto_width(mut self) -> Self {
3843        self.max_width = None;
3844        self
3845    }
3846
3847    pub fn fill_width(mut self) -> Self {
3848        self.fill_width = true;
3849        self
3850    }
3851
3852    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
3853        self.children.as_slice()
3854    }
3855
3856    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
3857        self.children.as_mut_slice()
3858    }
3859
3860    fn content_max_width(&self, constraints: Constraints) -> f32 {
3861        let available = if constraints.max.width.is_finite() {
3862            (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
3863        } else {
3864            f32::INFINITY
3865        };
3866        self.max_width
3867            .map(|width| width.min(available))
3868            .unwrap_or(available)
3869    }
3870
3871    fn content_rect(&self, bounds: Rect) -> Rect {
3872        let inset = inset_rect(bounds, self.padding);
3873        let width = self
3874            .max_width
3875            .map(|max_width| max_width.min(inset.width()))
3876            .unwrap_or(inset.width())
3877            .max(0.0);
3878        Rect::new(inset.x(), inset.y(), width, inset.height())
3879    }
3880
3881    fn resolved_theme(&self) -> DefaultTheme {
3882        self.theme_reader
3883            .as_ref()
3884            .map(|theme| theme())
3885            .unwrap_or(*self.theme)
3886    }
3887
3888    fn resolved_spacing(&self) -> f32 {
3889        self.spacing
3890            .unwrap_or_else(|| self.resolved_theme().metrics.field_group_spacing)
3891    }
3892}
3893
3894impl Default for FieldGroup {
3895    fn default() -> Self {
3896        Self::new()
3897    }
3898}
3899
3900impl Widget for FieldGroup {
3901    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3902        let spacing = self.resolved_spacing();
3903        let content_max_width = self.content_max_width(constraints);
3904        let mut y: f32 = 0.0;
3905        let mut width: f32 = 0.0;
3906        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
3907            if index > 0 {
3908                y += spacing;
3909            }
3910            let child_size = child.measure(
3911                ctx,
3912                Constraints::new(
3913                    Size::ZERO,
3914                    Size::new(content_max_width, constraints.max.height),
3915                ),
3916            );
3917            y += child_size.height;
3918            width = width.max(child_size.width);
3919        }
3920
3921        if self.fill_width && content_max_width.is_finite() {
3922            width = content_max_width;
3923        }
3924
3925        constraints.clamp(Size::new(
3926            width + self.padding.left + self.padding.right,
3927            y + self.padding.top + self.padding.bottom,
3928        ))
3929    }
3930
3931    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3932        let spacing = self.resolved_spacing();
3933        let content = self.content_rect(bounds);
3934        let mut y = content.y();
3935        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
3936            if index > 0 {
3937                y += spacing;
3938            }
3939            let measured = child.measured_size();
3940            let width = if self.fill_width {
3941                content.width()
3942            } else {
3943                measured.width.min(content.width())
3944            };
3945            child.arrange(ctx, Rect::new(content.x(), y, width, measured.height));
3946            y += measured.height;
3947        }
3948    }
3949
3950    fn paint(&self, ctx: &mut PaintCtx) {
3951        self.children.paint(ctx);
3952    }
3953
3954    fn semantics(&self, ctx: &mut SemanticsCtx) {
3955        self.children.semantics(ctx);
3956    }
3957
3958    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3959        self.children.visit_children(visitor);
3960    }
3961
3962    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3963        self.children.visit_children_mut(visitor);
3964    }
3965}
3966
3967pub struct FormSection {
3968    theme: Box<DefaultTheme>,
3969    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
3970    title: String,
3971    description: Option<String>,
3972    title_style: Option<TextStyle>,
3973    description_style: Option<TextStyle>,
3974    header_action: Option<SingleChild>,
3975    child: SingleChild,
3976    padding: Option<Insets>,
3977    body_gap: Option<f32>,
3978    header_gap: Option<f32>,
3979    description_gap: Option<f32>,
3980    max_width: Option<f32>,
3981    auto_width: bool,
3982    radius: Option<f32>,
3983    elevation: SurfaceElevation,
3984    fill_width: bool,
3985    title_measurement: Option<TextMeasurement>,
3986    description_measurement: Option<TextMeasurement>,
3987}
3988
3989impl FormSection {
3990    pub fn new<W>(title: impl Into<String>, child: W) -> Self
3991    where
3992        W: Widget + 'static,
3993    {
3994        Self {
3995            theme: Box::new(DefaultTheme::default()),
3996            theme_reader: None,
3997            title: title.into(),
3998            description: None,
3999            title_style: None,
4000            description_style: None,
4001            header_action: None,
4002            child: SingleChild::new(child),
4003            padding: None,
4004            body_gap: None,
4005            header_gap: None,
4006            description_gap: None,
4007            max_width: None,
4008            auto_width: false,
4009            radius: None,
4010            elevation: SurfaceElevation::Small,
4011            fill_width: false,
4012            title_measurement: None,
4013            description_measurement: None,
4014        }
4015    }
4016
4017    pub fn theme(mut self, theme: DefaultTheme) -> Self {
4018        self.theme = Box::new(theme);
4019        self.theme_reader = None;
4020        self
4021    }
4022
4023    pub fn theme_when<F>(mut self, theme: F) -> Self
4024    where
4025        F: Fn() -> DefaultTheme + 'static,
4026    {
4027        self.theme_reader = Some(Box::new(theme));
4028        self
4029    }
4030
4031    pub fn description(mut self, description: impl Into<String>) -> Self {
4032        self.description = Some(description.into());
4033        self
4034    }
4035
4036    pub fn title_style(mut self, style: TextStyle) -> Self {
4037        self.title_style = Some(style);
4038        self
4039    }
4040
4041    pub fn description_style(mut self, style: TextStyle) -> Self {
4042        self.description_style = Some(style);
4043        self
4044    }
4045
4046    pub fn header_action<W>(mut self, action: W) -> Self
4047    where
4048        W: Widget + 'static,
4049    {
4050        self.header_action = Some(SingleChild::new(action));
4051        self
4052    }
4053
4054    pub fn padding(mut self, padding: Insets) -> Self {
4055        self.padding = Some(padding);
4056        self
4057    }
4058
4059    pub fn body_gap(mut self, gap: f32) -> Self {
4060        self.body_gap = Some(gap.max(0.0));
4061        self
4062    }
4063
4064    pub fn header_gap(mut self, gap: f32) -> Self {
4065        self.header_gap = Some(gap.max(0.0));
4066        self
4067    }
4068
4069    pub fn max_width(mut self, width: f32) -> Self {
4070        self.max_width = Some(width.max(0.0));
4071        self.auto_width = false;
4072        self
4073    }
4074
4075    pub fn auto_width(mut self) -> Self {
4076        self.max_width = None;
4077        self.auto_width = true;
4078        self
4079    }
4080
4081    pub fn fill_width(mut self) -> Self {
4082        self.fill_width = true;
4083        self
4084    }
4085
4086    pub fn radius(mut self, radius: f32) -> Self {
4087        self.radius = Some(radius.max(0.0));
4088        self
4089    }
4090
4091    pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
4092        self.elevation = elevation;
4093        self
4094    }
4095
4096    pub fn child(&self) -> &sui_runtime::WidgetPod {
4097        self.child.child()
4098    }
4099
4100    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
4101        self.child.child_mut()
4102    }
4103
4104    fn resolved_theme(&self) -> DefaultTheme {
4105        self.theme_reader
4106            .as_ref()
4107            .map(|theme| theme())
4108            .unwrap_or(*self.theme)
4109    }
4110
4111    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
4112        self.padding.unwrap_or(metrics.form_section_padding)
4113    }
4114
4115    fn resolved_body_gap(&self, metrics: ControlMetrics) -> f32 {
4116        self.body_gap.unwrap_or(metrics.form_section_body_gap)
4117    }
4118
4119    fn resolved_header_gap(&self, metrics: ControlMetrics) -> f32 {
4120        self.header_gap.unwrap_or(metrics.form_section_header_gap)
4121    }
4122
4123    fn resolved_description_gap(&self, metrics: ControlMetrics) -> f32 {
4124        self.description_gap
4125            .unwrap_or(metrics.form_section_description_gap)
4126    }
4127
4128    fn resolved_max_width(&self, metrics: ControlMetrics) -> Option<f32> {
4129        if self.auto_width {
4130            None
4131        } else {
4132            Some(self.max_width.unwrap_or(metrics.form_section_max_width))
4133        }
4134    }
4135
4136    fn resolved_radius(&self, metrics: ControlMetrics) -> f32 {
4137        self.radius.unwrap_or(metrics.form_section_radius).max(0.0)
4138    }
4139
4140    fn resolved_title_style(&self) -> TextStyle {
4141        let theme = self.resolved_theme();
4142        self.title_style.clone().unwrap_or_else(|| TextStyle {
4143            weight: FontWeight::SEMIBOLD,
4144            ..text_token_style(&theme, theme.text.sm, theme.surfaces.text)
4145        })
4146    }
4147
4148    fn resolved_description_style(&self) -> TextStyle {
4149        let theme = self.resolved_theme();
4150        self.description_style
4151            .clone()
4152            .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.surfaces.text_muted))
4153    }
4154
4155    fn title_height(&self, style: &TextStyle) -> f32 {
4156        self.title_measurement
4157            .map(|measurement| measurement.height)
4158            .unwrap_or(style.line_height)
4159            .max(style.line_height)
4160    }
4161
4162    fn description_height(&self, style: &TextStyle) -> f32 {
4163        if self.description.is_some() {
4164            self.description_measurement
4165                .map(|measurement| measurement.height)
4166                .unwrap_or(style.line_height)
4167                .max(style.line_height)
4168        } else {
4169            0.0
4170        }
4171    }
4172
4173    fn text_block_height(&self, title_style: &TextStyle, description_style: &TextStyle) -> f32 {
4174        let title = self.title_height(title_style);
4175        let description = self.description_height(description_style);
4176        if description > 0.0 {
4177            let metrics = self.resolved_theme().metrics;
4178            title + self.resolved_description_gap(metrics) + description
4179        } else {
4180            title
4181        }
4182    }
4183
4184    fn content_max_width(&self, available_width: f32) -> f32 {
4185        let theme = self.resolved_theme();
4186        let metrics = theme.metrics;
4187        let padding = self.resolved_padding(metrics);
4188        let available = if available_width.is_finite() {
4189            (available_width - padding.left - padding.right).max(0.0)
4190        } else {
4191            f32::INFINITY
4192        };
4193        self.resolved_max_width(metrics)
4194            .map(|width| width.min(available))
4195            .unwrap_or(available)
4196    }
4197
4198    fn card_rect(&self, bounds: Rect) -> Rect {
4199        let theme = self.resolved_theme();
4200        let metrics = theme.metrics;
4201        let padding = self.resolved_padding(metrics);
4202        let width = if self.fill_width {
4203            bounds.width()
4204        } else {
4205            self.resolved_max_width(metrics)
4206                .map(|max_width| (max_width + padding.left + padding.right).min(bounds.width()))
4207                .unwrap_or(bounds.width())
4208        }
4209        .max(0.0);
4210        let x = if self.fill_width || width >= bounds.width() {
4211            bounds.x()
4212        } else {
4213            bounds.x() + ((bounds.width() - width) * 0.5)
4214        };
4215        Rect::new(x, bounds.y(), width, bounds.height())
4216    }
4217
4218    fn content_rect(&self, bounds: Rect) -> Rect {
4219        let theme = self.resolved_theme();
4220        inset_rect(self.card_rect(bounds), self.resolved_padding(theme.metrics))
4221    }
4222
4223    fn header_height(&self, title_style: &TextStyle, description_style: &TextStyle) -> f32 {
4224        let text_height = self.text_block_height(title_style, description_style);
4225        let action_height = self
4226            .header_action
4227            .as_ref()
4228            .map(|action| action.child().measured_size().height)
4229            .unwrap_or(0.0);
4230        text_height.max(action_height)
4231    }
4232}
4233
4234impl Widget for FormSection {
4235    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4236        let theme = self.resolved_theme();
4237        let metrics = theme.metrics;
4238        let padding = self.resolved_padding(metrics);
4239        let body_gap = self.resolved_body_gap(metrics);
4240        let header_gap = self.resolved_header_gap(metrics);
4241        let title_style = self.resolved_title_style();
4242        let description_style = self.resolved_description_style();
4243        let title = measure_text(ctx, &self.title, &title_style);
4244        self.title_measurement = Some(title);
4245        let description = self
4246            .description
4247            .as_ref()
4248            .map(|description| measure_text(ctx, description, &description_style));
4249        self.description_measurement = description;
4250
4251        let content_max_width = self.content_max_width(constraints.max.width);
4252        let action_size = self
4253            .header_action
4254            .as_mut()
4255            .map(|action| {
4256                action.measure(
4257                    ctx,
4258                    Constraints::new(
4259                        Size::ZERO,
4260                        Size::new(content_max_width, constraints.max.height),
4261                    ),
4262                )
4263            })
4264            .unwrap_or(Size::ZERO);
4265        let action_extent = if self.header_action.is_some() {
4266            action_size.width + header_gap
4267        } else {
4268            0.0
4269        };
4270        let text_width = title.width.max(
4271            description
4272                .map(|measurement| measurement.width)
4273                .unwrap_or(0.0),
4274        );
4275        let header_width = (text_width + action_extent).min(content_max_width);
4276        let child_size = self.child.measure(
4277            ctx,
4278            Constraints::new(
4279                Size::ZERO,
4280                Size::new(content_max_width, constraints.max.height),
4281            ),
4282        );
4283        let content_width = header_width.max(child_size.width).min(content_max_width);
4284        let header_height = self.header_height(&title_style, &description_style);
4285
4286        let mut width = content_width + padding.left + padding.right;
4287        if self.fill_width && constraints.max.width.is_finite() {
4288            width = constraints.max.width;
4289        }
4290        let height = padding.top + header_height + body_gap + child_size.height + padding.bottom;
4291        constraints.clamp(Size::new(width, height))
4292    }
4293
4294    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4295        let theme = self.resolved_theme();
4296        let metrics = theme.metrics;
4297        let body_gap = self.resolved_body_gap(metrics);
4298        let content = self.content_rect(bounds);
4299        let title_style = self.resolved_title_style();
4300        let description_style = self.resolved_description_style();
4301        let header_height = self.header_height(&title_style, &description_style);
4302
4303        if let Some(action) = &mut self.header_action {
4304            let action_size = action.child().measured_size();
4305            action.arrange(
4306                ctx,
4307                Rect::new(
4308                    content.max_x() - action_size.width,
4309                    content.y() + ((header_height - action_size.height) * 0.5).max(0.0),
4310                    action_size.width,
4311                    action_size.height,
4312                ),
4313            );
4314        }
4315
4316        let child_size = self.child.child().measured_size();
4317        self.child.arrange(
4318            ctx,
4319            Rect::new(
4320                content.x(),
4321                content.y() + header_height + body_gap,
4322                child_size.width.min(content.width()),
4323                child_size.height,
4324            ),
4325        );
4326    }
4327
4328    fn paint(&self, ctx: &mut PaintCtx) {
4329        let theme = self.resolved_theme();
4330        let metrics = theme.metrics;
4331        let card = self.card_rect(ctx.bounds());
4332        let radius = self
4333            .resolved_radius(metrics)
4334            .min(card.width().min(card.height()) * 0.5);
4335        let shadow = match self.elevation {
4336            SurfaceElevation::None => None,
4337            SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
4338            SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
4339            SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
4340        };
4341        if let Some(shadow) = shadow {
4342            paint_theme_shadow(ctx, card, [radius; 4], shadow);
4343        }
4344
4345        let background = theme.surfaces.panel;
4346        let border = theme.surfaces.border;
4347        let shape = rounded_rect_path(card, radius);
4348        ctx.fill(shape.clone(), background);
4349        ctx.stroke(
4350            shape,
4351            border,
4352            StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
4353        );
4354
4355        let content = inset_rect(card, self.resolved_padding(metrics));
4356        let title_style = self.resolved_title_style();
4357        let description_style = self.resolved_description_style();
4358        let title_height = self.title_height(&title_style);
4359        let description_height = self.description_height(&description_style);
4360        let header_gap = self.resolved_header_gap(metrics);
4361        let description_gap = self.resolved_description_gap(metrics);
4362        let action_width = self
4363            .header_action
4364            .as_ref()
4365            .map(|action| action.child().measured_size().width + header_gap)
4366            .unwrap_or(0.0)
4367            .min(content.width());
4368        let text_width = (content.width() - action_width).max(0.0);
4369        let text_block_height = self.text_block_height(&title_style, &description_style);
4370        let header_height = self.header_height(&title_style, &description_style);
4371        let text_y = content.y() + ((header_height - text_block_height) * 0.5).max(0.0);
4372        let title_slot = Rect::new(content.x(), text_y, text_width, title_height);
4373        ctx.push_clip_rect(title_slot);
4374        paint_aligned_text(
4375            ctx,
4376            title_slot,
4377            &self.title,
4378            &title_style,
4379            title_style.line_height,
4380            0.0,
4381        );
4382        ctx.pop_clip();
4383        if let Some(description) = &self.description {
4384            let description_slot = Rect::new(
4385                content.x(),
4386                title_slot.max_y() + description_gap,
4387                text_width,
4388                description_height,
4389            );
4390            ctx.push_clip_rect(description_slot);
4391            paint_aligned_text(
4392                ctx,
4393                description_slot,
4394                description,
4395                &description_style,
4396                description_style.line_height,
4397                0.0,
4398            );
4399            ctx.pop_clip();
4400        }
4401
4402        if let Some(action) = &self.header_action {
4403            action.paint(ctx);
4404        }
4405        self.child.paint(ctx);
4406    }
4407
4408    fn semantics(&self, ctx: &mut SemanticsCtx) {
4409        let card = self.card_rect(ctx.bounds());
4410        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::GenericContainer, card);
4411        node.name = Some(self.title.clone());
4412        node.description = self.description.clone();
4413        ctx.push(node);
4414        if let Some(action) = &self.header_action {
4415            action.semantics(ctx);
4416        }
4417        self.child.semantics(ctx);
4418    }
4419
4420    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4421        if let Some(action) = &self.header_action {
4422            action.visit_children(visitor);
4423        }
4424        self.child.visit_children(visitor);
4425    }
4426
4427    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4428        if let Some(action) = &mut self.header_action {
4429            action.visit_children_mut(visitor);
4430        }
4431        self.child.visit_children_mut(visitor);
4432    }
4433}
4434
4435pub struct PanelSection {
4436    theme: Box<DefaultTheme>,
4437    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
4438    title: String,
4439    gap: Option<f32>,
4440    action_gap: Option<f32>,
4441    title_style: Option<TextStyle>,
4442    header_action: Option<SingleChild>,
4443    child: SingleChild,
4444    title_measurement: Option<TextMeasurement>,
4445    collapsible: bool,
4446    expanded: bool,
4447    hovered_header: bool,
4448    pressed_header: bool,
4449    hover_animation: AnimatedScalar,
4450    press_animation: AnimatedScalar,
4451    focus_animation: AnimatedScalar,
4452}
4453
4454impl PanelSection {
4455    pub fn new<W>(title: impl Into<String>, child: W) -> Self
4456    where
4457        W: Widget + 'static,
4458    {
4459        Self {
4460            theme: Box::new(DefaultTheme::default()),
4461            theme_reader: None,
4462            title: title.into(),
4463            gap: None,
4464            action_gap: None,
4465            title_style: None,
4466            header_action: None,
4467            child: SingleChild::new(child),
4468            title_measurement: None,
4469            collapsible: false,
4470            expanded: true,
4471            hovered_header: false,
4472            pressed_header: false,
4473            hover_animation: AnimatedScalar::new(0.0),
4474            press_animation: AnimatedScalar::new(0.0),
4475            focus_animation: AnimatedScalar::new(0.0),
4476        }
4477    }
4478
4479    pub fn theme(mut self, theme: DefaultTheme) -> Self {
4480        self.theme = Box::new(theme);
4481        self.theme_reader = None;
4482        self
4483    }
4484
4485    pub fn theme_when<F>(mut self, theme: F) -> Self
4486    where
4487        F: Fn() -> DefaultTheme + 'static,
4488    {
4489        self.theme_reader = Some(Box::new(theme));
4490        self
4491    }
4492
4493    pub fn gap(mut self, gap: f32) -> Self {
4494        self.gap = Some(gap.max(0.0));
4495        self
4496    }
4497
4498    pub fn title_style(mut self, style: TextStyle) -> Self {
4499        self.title_style = Some(style);
4500        self
4501    }
4502
4503    pub fn header_action<W>(mut self, action: W) -> Self
4504    where
4505        W: Widget + 'static,
4506    {
4507        self.header_action = Some(SingleChild::new(action));
4508        self
4509    }
4510
4511    pub fn action_gap(mut self, gap: f32) -> Self {
4512        self.action_gap = Some(gap.max(0.0));
4513        self
4514    }
4515
4516    pub fn collapsible(mut self, collapsible: bool) -> Self {
4517        self.collapsible = collapsible;
4518        self
4519    }
4520
4521    pub fn expanded(mut self, expanded: bool) -> Self {
4522        self.expanded = expanded;
4523        self
4524    }
4525
4526    pub fn collapsed(mut self) -> Self {
4527        self.expanded = false;
4528        self
4529    }
4530
4531    pub fn child(&self) -> &sui_runtime::WidgetPod {
4532        self.child.child()
4533    }
4534
4535    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
4536        self.child.child_mut()
4537    }
4538
4539    fn resolved_title_style(&self) -> TextStyle {
4540        let theme = self.resolved_theme();
4541        self.title_style
4542            .clone()
4543            .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.palette.text_muted))
4544    }
4545
4546    fn resolved_theme(&self) -> DefaultTheme {
4547        self.theme_reader
4548            .as_ref()
4549            .map(|theme| theme())
4550            .unwrap_or(*self.theme)
4551    }
4552
4553    fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
4554        self.gap.unwrap_or(metrics.panel_section_gap)
4555    }
4556
4557    fn resolved_action_gap(&self, metrics: ControlMetrics) -> f32 {
4558        self.action_gap.unwrap_or(metrics.panel_section_action_gap)
4559    }
4560
4561    fn title_height(&self, style: &TextStyle) -> f32 {
4562        self.title_measurement
4563            .map(|measurement| measurement.height)
4564            .unwrap_or(style.line_height)
4565            .max(style.line_height)
4566    }
4567
4568    fn header_height(&self, title_style: &TextStyle) -> f32 {
4569        let action_height = self
4570            .header_action
4571            .as_ref()
4572            .map(|action| action.child().measured_size().height)
4573            .unwrap_or(0.0);
4574        self.title_height(title_style).max(action_height)
4575    }
4576
4577    fn is_expanded(&self) -> bool {
4578        !self.collapsible || self.expanded
4579    }
4580
4581    fn disclosure_width(&self, metrics: ControlMetrics) -> f32 {
4582        if self.collapsible {
4583            metrics.panel_section_disclosure_size
4584        } else {
4585            0.0
4586        }
4587    }
4588
4589    fn title_rect(&self, bounds: Rect, header_height: f32, title_height: f32) -> Rect {
4590        let metrics = self.resolved_theme().metrics;
4591        let action_width = self
4592            .header_action
4593            .as_ref()
4594            .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
4595            .unwrap_or(0.0)
4596            .min(bounds.width());
4597        let disclosure_width = self.disclosure_width(metrics);
4598        Rect::new(
4599            bounds.x() + disclosure_width,
4600            bounds.y() + ((header_height - title_height) * 0.5).max(0.0),
4601            (bounds.width() - action_width - disclosure_width).max(0.0),
4602            title_height,
4603        )
4604    }
4605
4606    fn header_rect(&self, bounds: Rect) -> Rect {
4607        let title_style = self.resolved_title_style();
4608        let header_height = self.header_height(&title_style);
4609        Rect::new(bounds.x(), bounds.y(), bounds.width(), header_height)
4610    }
4611
4612    fn header_hit_rect(&self, bounds: Rect) -> Rect {
4613        let metrics = self.resolved_theme().metrics;
4614        let header = self.header_rect(bounds);
4615        let action_width = self
4616            .header_action
4617            .as_ref()
4618            .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
4619            .unwrap_or(0.0)
4620            .min(header.width());
4621        Rect::new(
4622            header.x(),
4623            header.y(),
4624            (header.width() - action_width).max(0.0),
4625            header.height(),
4626        )
4627    }
4628
4629    fn toggle(&mut self, ctx: &mut EventCtx) {
4630        if !self.collapsible {
4631            return;
4632        }
4633
4634        self.expanded = !self.expanded;
4635        self.set_pressed_header(false, ctx);
4636        ctx.request_measure();
4637        ctx.request_paint();
4638        ctx.request_semantics();
4639    }
4640
4641    fn set_hovered_header(&mut self, hovered: bool, ctx: &mut EventCtx) {
4642        if self.hovered_header == hovered {
4643            return;
4644        }
4645        let theme = self.resolved_theme();
4646        self.hovered_header = hovered;
4647        set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
4648        ctx.request_paint();
4649        ctx.request_semantics();
4650    }
4651
4652    fn set_pressed_header(&mut self, pressed: bool, ctx: &mut EventCtx) {
4653        if self.pressed_header == pressed {
4654            return;
4655        }
4656        let theme = self.resolved_theme();
4657        self.pressed_header = pressed;
4658        set_press_animation_target(&mut self.press_animation, pressed as u8 as f32, &theme, ctx);
4659        ctx.request_paint();
4660        ctx.request_semantics();
4661    }
4662
4663    fn advance_animations(&mut self, time: f64) -> bool {
4664        self.hover_animation.advance(time)
4665            | self.press_animation.advance(time)
4666            | self.focus_animation.advance(time)
4667    }
4668}
4669
4670impl Widget for PanelSection {
4671    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
4672        if !self.collapsible {
4673            return;
4674        }
4675
4676        match event {
4677            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
4678                let hovered = self
4679                    .header_hit_rect(ctx.bounds())
4680                    .contains(pointer.position);
4681                self.set_hovered_header(hovered, ctx);
4682            }
4683            Event::Pointer(pointer)
4684                if pointer.kind == PointerEventKind::Down
4685                    && pointer.button == Some(PointerButton::Primary)
4686                    && self
4687                        .header_hit_rect(ctx.bounds())
4688                        .contains(pointer.position) =>
4689            {
4690                self.set_hovered_header(true, ctx);
4691                self.set_pressed_header(true, ctx);
4692                ctx.request_focus();
4693                ctx.request_pointer_capture(pointer.pointer_id);
4694                ctx.set_handled();
4695            }
4696            Event::Pointer(pointer)
4697                if pointer.kind == PointerEventKind::Up
4698                    && pointer.button == Some(PointerButton::Primary)
4699                    && self.pressed_header =>
4700            {
4701                let hovered = self
4702                    .header_hit_rect(ctx.bounds())
4703                    .contains(pointer.position);
4704                if hovered {
4705                    self.toggle(ctx);
4706                }
4707                self.set_hovered_header(hovered, ctx);
4708                self.set_pressed_header(false, ctx);
4709                ctx.release_pointer_capture(pointer.pointer_id);
4710                ctx.set_handled();
4711            }
4712            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
4713                self.set_hovered_header(false, ctx);
4714            }
4715            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
4716                if self.pressed_header || self.hovered_header {
4717                    self.set_hovered_header(false, ctx);
4718                    self.set_pressed_header(false, ctx);
4719                    ctx.release_pointer_capture(pointer.pointer_id);
4720                    ctx.set_handled();
4721                }
4722            }
4723            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
4724                match key.key.as_str() {
4725                    "Enter" | " " => {
4726                        self.toggle(ctx);
4727                        ctx.set_handled();
4728                    }
4729                    _ => {}
4730                }
4731            }
4732            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
4733                if self.advance_animations(*time) {
4734                    ctx.request_animation_frame();
4735                }
4736                ctx.request_paint();
4737            }
4738            _ => {}
4739        }
4740    }
4741
4742    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
4743        let theme = self.resolved_theme();
4744        let metrics = theme.metrics;
4745        let gap = self.resolved_gap(metrics);
4746        let action_gap = self.resolved_action_gap(metrics);
4747        let title_style = self.resolved_title_style();
4748        let title_measurement = measure_text(ctx, &self.title, &title_style);
4749        self.title_measurement = Some(title_measurement);
4750        let action_size = self
4751            .header_action
4752            .as_mut()
4753            .map(|action| {
4754                action.measure(
4755                    ctx,
4756                    Constraints::new(Size::ZERO, Size::new(constraints.max.width, f32::INFINITY)),
4757                )
4758            })
4759            .unwrap_or(Size::ZERO);
4760        let header_height = self.title_height(&title_style).max(action_size.height);
4761        let child_size = if self.is_expanded() {
4762            self.child.measure(ctx, constraints)
4763        } else {
4764            Size::ZERO
4765        };
4766        let header_width = if self.header_action.is_some() {
4767            self.disclosure_width(metrics)
4768                + title_measurement.width
4769                + action_gap
4770                + action_size.width
4771        } else {
4772            self.disclosure_width(metrics) + title_measurement.width
4773        };
4774        let natural = Size::new(
4775            header_width.max(child_size.width),
4776            header_height
4777                + if self.is_expanded() && child_size.height > 0.0 {
4778                    gap + child_size.height
4779                } else {
4780                    0.0
4781                },
4782        );
4783
4784        constraints.clamp(natural)
4785    }
4786
4787    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
4788        let theme = self.resolved_theme();
4789        let metrics = theme.metrics;
4790        let gap = self.resolved_gap(metrics);
4791        let title_style = self.resolved_title_style();
4792        let header_height = self.header_height(&title_style);
4793        if let Some(action) = &mut self.header_action {
4794            let action_size = action.child().measured_size();
4795            action.arrange(
4796                ctx,
4797                Rect::new(
4798                    bounds.max_x() - action_size.width.min(bounds.width()),
4799                    bounds.y() + ((header_height - action_size.height) * 0.5).max(0.0),
4800                    action_size.width.min(bounds.width()).max(0.0),
4801                    action_size.height,
4802                ),
4803            );
4804        }
4805        let child_size = if self.is_expanded() {
4806            self.child.child().measured_size()
4807        } else {
4808            Size::ZERO
4809        };
4810        let child_height = if self.is_expanded() {
4811            child_size
4812                .height
4813                .min((bounds.height() - header_height - gap).max(0.0))
4814        } else {
4815            0.0
4816        };
4817        self.child.arrange(
4818            ctx,
4819            Rect::new(
4820                bounds.x(),
4821                bounds.y() + header_height + gap,
4822                bounds.width().min(child_size.width).max(0.0),
4823                child_height,
4824            ),
4825        );
4826    }
4827
4828    fn paint(&self, ctx: &mut PaintCtx) {
4829        let theme = self.resolved_theme();
4830        let metrics = theme.metrics;
4831        let title_style = self.resolved_title_style();
4832        let title_height = self.title_height(&title_style);
4833        let header_height = self.header_height(&title_style);
4834        let title_slot = self.title_rect(ctx.bounds(), header_height, title_height);
4835        if self.collapsible {
4836            let header_hit = self.header_hit_rect(ctx.bounds());
4837            let hover_amount = self.hover_animation.value;
4838            let press_amount = self.press_animation.value;
4839            let focus_amount = self.focus_animation.value;
4840            if focus_amount > AnimatedScalar::EPSILON {
4841                let outset = physical_pixels(ctx, metrics.focus_ring_outset);
4842                ctx.stroke(
4843                    rounded_rect_path(
4844                        header_hit.inflate(outset, outset),
4845                        metrics.indicator_corner_radius + outset,
4846                    ),
4847                    theme
4848                        .palette
4849                        .focus_ring
4850                        .with_alpha(theme.palette.focus_ring.alpha * focus_amount),
4851                    StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
4852                );
4853            }
4854            let hover_alpha = (theme.interaction.hover_blend * 0.07 * hover_amount).min(0.08);
4855            let press_alpha = (theme.interaction.selected_blend * 0.48 * press_amount).min(0.14);
4856            let header_fill = if press_alpha > 0.0 {
4857                theme.palette.accent.with_alpha(press_alpha)
4858            } else if hover_alpha > 0.0 {
4859                theme.palette.accent.with_alpha(hover_alpha)
4860            } else {
4861                theme.palette.surface.with_alpha(0.001)
4862            };
4863            ctx.fill(
4864                rounded_rect_path(header_hit, metrics.indicator_corner_radius),
4865                header_fill,
4866            );
4867            paint_panel_section_disclosure(
4868                ctx,
4869                self.header_rect(ctx.bounds()),
4870                self.expanded,
4871                hover_amount,
4872                press_amount,
4873                &theme,
4874                metrics.panel_section_disclosure_size,
4875            );
4876        }
4877        ctx.push_clip_rect(title_slot);
4878        paint_aligned_text(
4879            ctx,
4880            title_slot,
4881            &self.title,
4882            &title_style,
4883            title_style.line_height,
4884            0.0,
4885        );
4886        ctx.pop_clip();
4887        if let Some(action) = &self.header_action {
4888            action.paint(ctx);
4889        }
4890        if self.is_expanded() {
4891            self.child.paint(ctx);
4892        }
4893    }
4894
4895    fn semantics(&self, ctx: &mut SemanticsCtx) {
4896        let mut section = SemanticsNode::new(
4897            ctx.widget_id(),
4898            SemanticsRole::GenericContainer,
4899            ctx.bounds(),
4900        );
4901        section.name = Some(self.title.clone());
4902        section.state.focused = ctx.is_focused();
4903        section.state.hovered = self.hovered_header;
4904        if self.collapsible {
4905            section.state.expanded = Some(self.expanded);
4906            section.actions = vec![
4907                SemanticsAction::Focus,
4908                SemanticsAction::Expand,
4909                SemanticsAction::Collapse,
4910            ];
4911        }
4912        ctx.push(section);
4913
4914        let title_style = self.resolved_title_style();
4915        let title_height = self.title_height(&title_style);
4916        let header_height = self.header_height(&title_style);
4917        let mut title = SemanticsNode::new(
4918            panel_section_title_id(ctx.widget_id()),
4919            SemanticsRole::Text,
4920            self.title_rect(ctx.bounds(), header_height, title_height),
4921        );
4922        title.parent = Some(ctx.widget_id());
4923        title.name = Some(self.title.clone());
4924        title.value = Some(SemanticsValue::Text(self.title.clone()));
4925        ctx.push(title);
4926
4927        if let Some(action) = &self.header_action {
4928            action.semantics(ctx);
4929        }
4930        if self.is_expanded() {
4931            self.child.semantics(ctx);
4932        }
4933    }
4934
4935    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
4936        if let Some(action) = &self.header_action {
4937            action.visit_children(visitor);
4938        }
4939        if self.is_expanded() {
4940            self.child.visit_children(visitor);
4941        }
4942    }
4943
4944    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
4945        if let Some(action) = &mut self.header_action {
4946            action.visit_children_mut(visitor);
4947        }
4948        if self.is_expanded() {
4949            self.child.visit_children_mut(visitor);
4950        }
4951    }
4952
4953    fn accepts_focus(&self) -> bool {
4954        self.collapsible
4955    }
4956
4957    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
4958        if self.collapsible {
4959            let theme = self.resolved_theme();
4960            set_focus_animation_target(
4961                &mut self.focus_animation,
4962                focused as u8 as f32,
4963                &theme,
4964                ctx,
4965            );
4966            ctx.request_paint();
4967            ctx.request_semantics();
4968        }
4969    }
4970}
4971
4972fn panel_section_title_id(parent: WidgetId) -> WidgetId {
4973    const TAG: u64 = 3_u64 << 50;
4974    const LOW_MASK: u64 = (1_u64 << 50) - 1;
4975
4976    WidgetId::new(TAG | (parent.get().wrapping_mul(431).wrapping_add(7) & LOW_MASK))
4977}
4978
4979fn paint_panel_section_disclosure(
4980    ctx: &mut PaintCtx,
4981    header: Rect,
4982    expanded: bool,
4983    hover_amount: f32,
4984    press_amount: f32,
4985    theme: &DefaultTheme,
4986    disclosure_size: f32,
4987) {
4988    let palette = theme.palette;
4989    let center = Point::new(
4990        header.x() + disclosure_size * 0.5,
4991        header.y() + header.height() * 0.5,
4992    );
4993    let half = disclosure_size * 0.25;
4994    let tip = disclosure_size * 0.22;
4995    let base_color = palette.text.with_alpha(0.68);
4996    let hover_color = mix_color(base_color, palette.text, hover_amount);
4997    let color = mix_color(hover_color, palette.accent, press_amount);
4998    let mut builder = PathBuilder::new();
4999    if expanded {
5000        builder
5001            .move_to(Point::new(center.x - half, center.y - tip * 0.55))
5002            .line_to(Point::new(center.x + half, center.y - tip * 0.55))
5003            .line_to(Point::new(center.x, center.y + tip));
5004    } else {
5005        builder
5006            .move_to(Point::new(center.x - tip * 0.55, center.y - half))
5007            .line_to(Point::new(center.x + tip, center.y))
5008            .line_to(Point::new(center.x - tip * 0.55, center.y + half));
5009    }
5010    ctx.fill(builder.build(), color);
5011}
5012
5013pub struct DockPanel {
5014    theme: Box<DefaultTheme>,
5015    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5016    name: Option<String>,
5017    title: String,
5018    header_height: Option<f32>,
5019    padding: Option<Insets>,
5020    background: Option<Color>,
5021    header_background: Option<Color>,
5022    child: SingleChild,
5023    title_measurement: Option<TextMeasurement>,
5024}
5025
5026impl DockPanel {
5027    pub fn new<W>(title: impl Into<String>, child: W) -> Self
5028    where
5029        W: Widget + 'static,
5030    {
5031        Self {
5032            theme: Box::new(DefaultTheme::default()),
5033            theme_reader: None,
5034            name: None,
5035            title: title.into(),
5036            header_height: None,
5037            padding: None,
5038            background: None,
5039            header_background: None,
5040            child: SingleChild::new(child),
5041            title_measurement: None,
5042        }
5043    }
5044
5045    pub fn theme(mut self, theme: DefaultTheme) -> Self {
5046        self.theme = Box::new(theme);
5047        self.theme_reader = None;
5048        self
5049    }
5050
5051    pub fn theme_when<F>(mut self, theme: F) -> Self
5052    where
5053        F: Fn() -> DefaultTheme + 'static,
5054    {
5055        self.theme_reader = Some(Box::new(theme));
5056        self
5057    }
5058
5059    pub fn name(mut self, name: impl Into<String>) -> Self {
5060        self.name = Some(name.into());
5061        self
5062    }
5063
5064    pub fn header_height(mut self, height: f32) -> Self {
5065        self.header_height = Some(height.max(0.0));
5066        self
5067    }
5068
5069    pub fn padding(mut self, padding: Insets) -> Self {
5070        self.padding = Some(padding);
5071        self
5072    }
5073
5074    pub fn background(mut self, color: Color) -> Self {
5075        self.background = Some(color);
5076        self
5077    }
5078
5079    pub fn header_background(mut self, color: Color) -> Self {
5080        self.header_background = Some(color);
5081        self
5082    }
5083
5084    pub fn child(&self) -> &sui_runtime::WidgetPod {
5085        self.child.child()
5086    }
5087
5088    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
5089        self.child.child_mut()
5090    }
5091
5092    fn resolved_title_style(&self) -> TextStyle {
5093        let theme = self.resolved_theme();
5094        text_token_style(&theme, theme.text.sm, theme.palette.text)
5095    }
5096
5097    fn resolved_theme(&self) -> DefaultTheme {
5098        self.theme_reader
5099            .as_ref()
5100            .map(|theme| theme())
5101            .unwrap_or(*self.theme)
5102    }
5103
5104    fn resolved_header_height(&self, metrics: ControlMetrics) -> f32 {
5105        self.header_height
5106            .unwrap_or(metrics.dock_panel_header_height)
5107    }
5108
5109    fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
5110        self.padding.unwrap_or(metrics.dock_panel_padding)
5111    }
5112
5113    fn title_height(&self, style: &TextStyle) -> f32 {
5114        self.title_measurement
5115            .map(|measurement| measurement.height)
5116            .unwrap_or(style.line_height)
5117            .max(style.line_height)
5118    }
5119
5120    fn header_rect(&self, bounds: Rect) -> Rect {
5121        let theme = self.resolved_theme();
5122        Rect::new(
5123            bounds.x(),
5124            bounds.y(),
5125            bounds.width(),
5126            self.resolved_header_height(theme.metrics),
5127        )
5128    }
5129
5130    fn content_rect(&self, bounds: Rect) -> Rect {
5131        let theme = self.resolved_theme();
5132        let metrics = theme.metrics;
5133        let header_height = self.resolved_header_height(metrics);
5134        inset_rect(
5135            Rect::new(
5136                bounds.x(),
5137                bounds.y() + header_height,
5138                bounds.width(),
5139                (bounds.height() - header_height).max(0.0),
5140            ),
5141            self.resolved_padding(metrics),
5142        )
5143    }
5144
5145    fn child_constraints(&self, constraints: Constraints) -> Constraints {
5146        let theme = self.resolved_theme();
5147        let metrics = theme.metrics;
5148        let padding = self.resolved_padding(metrics);
5149        let header_height = self.resolved_header_height(metrics);
5150        let width = if constraints.max.width.is_finite() {
5151            (constraints.max.width - padding.left - padding.right).max(0.0)
5152        } else {
5153            f32::INFINITY
5154        };
5155        let height = if constraints.max.height.is_finite() {
5156            (constraints.max.height - header_height - padding.top - padding.bottom).max(0.0)
5157        } else {
5158            f32::INFINITY
5159        };
5160        Constraints::new(Size::ZERO, Size::new(width, height))
5161    }
5162}
5163
5164impl Widget for DockPanel {
5165    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5166        let theme = self.resolved_theme();
5167        let metrics = theme.metrics;
5168        let padding = self.resolved_padding(metrics);
5169        let header_height = self.resolved_header_height(metrics);
5170        let title_style = self.resolved_title_style();
5171        let title_measurement = measure_text(ctx, &self.title, &title_style);
5172        self.title_measurement = Some(title_measurement);
5173        let child_size = self.child.measure(ctx, self.child_constraints(constraints));
5174        let natural = Size::new(
5175            (title_measurement.width + padding.left + padding.right)
5176                .max(child_size.width + padding.left + padding.right),
5177            header_height + padding.top + child_size.height + padding.bottom,
5178        );
5179
5180        constraints.clamp(natural)
5181    }
5182
5183    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5184        self.child.arrange(ctx, self.content_rect(bounds));
5185    }
5186
5187    fn paint(&self, ctx: &mut PaintCtx) {
5188        let theme = self.resolved_theme();
5189        let palette = theme.palette;
5190        let metrics = theme.metrics;
5191        let padding = self.resolved_padding(metrics);
5192        let bounds = ctx.bounds();
5193        let header = self.header_rect(bounds);
5194        let title_style = self.resolved_title_style();
5195        let title_height = self.title_height(&title_style);
5196        let title_slot = Rect::new(
5197            header.x() + padding.left,
5198            header.y() + ((header.height() - title_height) * 0.5).max(0.0),
5199            (header.width() - padding.left - padding.right).max(0.0),
5200            title_height,
5201        );
5202        let divider_height = physical_pixels(ctx, 1.0);
5203
5204        ctx.fill_rect(bounds, self.background.unwrap_or(palette.surface));
5205        ctx.fill_rect(
5206            header,
5207            self.header_background
5208                .unwrap_or_else(|| palette.surface_raised.with_alpha(0.72)),
5209        );
5210        ctx.fill_rect(
5211            Rect::new(
5212                header.x(),
5213                header.max_y() - divider_height,
5214                header.width(),
5215                divider_height,
5216            ),
5217            palette.border,
5218        );
5219        ctx.push_clip_rect(title_slot);
5220        paint_aligned_text(
5221            ctx,
5222            title_slot,
5223            &self.title,
5224            &title_style,
5225            title_style.line_height,
5226            0.0,
5227        );
5228        ctx.pop_clip();
5229
5230        self.child.paint(ctx);
5231    }
5232
5233    fn semantics(&self, ctx: &mut SemanticsCtx) {
5234        let theme = self.resolved_theme();
5235        let padding = self.resolved_padding(theme.metrics);
5236        let mut panel = SemanticsNode::new(
5237            ctx.widget_id(),
5238            SemanticsRole::GenericContainer,
5239            ctx.bounds(),
5240        );
5241        panel.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
5242        ctx.push(panel);
5243
5244        let title_style = self.resolved_title_style();
5245        let title_height = self.title_height(&title_style);
5246        let header = self.header_rect(ctx.bounds());
5247        let mut title = SemanticsNode::new(
5248            dock_panel_title_id(ctx.widget_id()),
5249            SemanticsRole::Text,
5250            Rect::new(
5251                header.x() + padding.left,
5252                header.y() + ((header.height() - title_height) * 0.5).max(0.0),
5253                (header.width() - padding.left - padding.right).max(0.0),
5254                title_height,
5255            ),
5256        );
5257        title.parent = Some(ctx.widget_id());
5258        title.name = Some(self.title.clone());
5259        title.value = Some(SemanticsValue::Text(self.title.clone()));
5260        ctx.push(title);
5261
5262        self.child.semantics(ctx);
5263    }
5264
5265    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5266        self.child.visit_children(visitor);
5267    }
5268
5269    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5270        self.child.visit_children_mut(visitor);
5271    }
5272}
5273
5274fn dock_panel_title_id(parent: WidgetId) -> WidgetId {
5275    const TAG: u64 = 5_u64 << 50;
5276    const LOW_MASK: u64 = (1_u64 << 50) - 1;
5277
5278    WidgetId::new(TAG | (parent.get().wrapping_mul(467).wrapping_add(11) & LOW_MASK))
5279}
5280
5281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5282pub enum HairlineEdge {
5283    Top,
5284    Right,
5285    Bottom,
5286    Left,
5287}
5288
5289pub fn paint_rounded_rect(ctx: &mut PaintCtx, rect: Rect, color: Color, radius: f32) {
5290    if rect.width() <= 0.0 || rect.height() <= 0.0 {
5291        return;
5292    }
5293    let radius = radius
5294        .min(rect.width() * 0.5)
5295        .min(rect.height() * 0.5)
5296        .max(0.0);
5297    if radius <= 0.5 {
5298        ctx.fill_rect(rect, color);
5299    } else {
5300        ctx.fill(Path::rounded_rect(rect, radius), color);
5301    }
5302}
5303
5304pub fn paint_rounded_panel(
5305    ctx: &mut PaintCtx,
5306    rect: Rect,
5307    fill: Color,
5308    border: Color,
5309    radius: f32,
5310) {
5311    paint_rounded_rect(ctx, rect, border, radius);
5312    paint_rounded_rect(ctx, rect.inflate(-1.0, -1.0), fill, (radius - 1.0).max(0.0));
5313}
5314
5315pub fn paint_hairline(ctx: &mut PaintCtx, rect: Rect, edge: HairlineEdge, color: Color) {
5316    let line = match edge {
5317        HairlineEdge::Top => Rect::new(rect.x(), rect.y(), rect.width(), 1.0),
5318        HairlineEdge::Right => Rect::new(rect.max_x() - 1.0, rect.y(), 1.0, rect.height()),
5319        HairlineEdge::Bottom => Rect::new(rect.x(), rect.max_y() - 1.0, rect.width(), 1.0),
5320        HairlineEdge::Left => Rect::new(rect.x(), rect.y(), 1.0, rect.height()),
5321    };
5322    ctx.fill_rect(line, color);
5323}
5324
5325pub fn paint_border(ctx: &mut PaintCtx, rect: Rect, color: Color) {
5326    paint_hairline(ctx, rect, HairlineEdge::Top, color);
5327    paint_hairline(ctx, rect, HairlineEdge::Right, color);
5328    paint_hairline(ctx, rect, HairlineEdge::Bottom, color);
5329    paint_hairline(ctx, rect, HairlineEdge::Left, color);
5330}
5331
5332fn centered_text_slot(bounds: Rect, center_y: f32, line_height: f32) -> Rect {
5333    let height = line_height.max(1.0) * 2.0;
5334    Rect::new(bounds.x(), center_y - height * 0.5, bounds.width(), height)
5335}
5336
5337#[derive(Clone, Copy)]
5338pub struct EmptyStatePaint<'a> {
5339    icon: Option<IconGlyph>,
5340    title: &'a str,
5341    description: &'a str,
5342    detail: Option<&'a str>,
5343    background: Option<Color>,
5344    center_offset_y: f32,
5345    reserve_action_space: bool,
5346}
5347
5348impl<'a> EmptyStatePaint<'a> {
5349    pub const fn new(title: &'a str, description: &'a str) -> Self {
5350        Self {
5351            icon: None,
5352            title,
5353            description,
5354            detail: None,
5355            background: None,
5356            center_offset_y: 0.0,
5357            reserve_action_space: false,
5358        }
5359    }
5360
5361    pub const fn icon(mut self, icon: IconGlyph) -> Self {
5362        self.icon = Some(icon);
5363        self
5364    }
5365
5366    pub const fn detail(mut self, detail: &'a str) -> Self {
5367        self.detail = Some(detail);
5368        self
5369    }
5370
5371    pub const fn background(mut self, color: Color) -> Self {
5372        self.background = Some(color);
5373        self
5374    }
5375
5376    pub const fn center_offset_y(mut self, offset: f32) -> Self {
5377        self.center_offset_y = offset;
5378        self
5379    }
5380
5381    pub const fn reserve_action_space(mut self, reserve: bool) -> Self {
5382        self.reserve_action_space = reserve;
5383        self
5384    }
5385}
5386
5387pub fn paint_empty_state(
5388    ctx: &mut PaintCtx,
5389    theme: &DefaultTheme,
5390    bounds: Rect,
5391    paint: EmptyStatePaint<'_>,
5392) {
5393    if let Some(background) = paint.background {
5394        ctx.fill_rect(bounds, background);
5395    }
5396
5397    let cy = bounds.y() + bounds.height() * 0.5
5398        - if paint.reserve_action_space {
5399            18.0
5400        } else {
5401            0.0
5402        }
5403        + paint.center_offset_y;
5404    let icon_color = theme.surfaces.text_faint;
5405    if let Some(icon) = paint.icon {
5406        let side = 40.0;
5407        let cx = bounds.x() + bounds.width() * 0.5;
5408        draw_icon_glyph(
5409            ctx,
5410            icon,
5411            Rect::new(cx - side * 0.5, cy - 46.0 - side * 0.5, side, side),
5412            icon_color,
5413        );
5414    }
5415
5416    let mut title_style = text_token_style(theme, theme.text.lg, theme.surfaces.text_muted);
5417    title_style.weight = FontWeight::SEMIBOLD;
5418    paint_single_line_aligned_text(
5419        ctx,
5420        centered_text_slot(bounds, cy + 4.0, title_style.line_height),
5421        paint.title,
5422        &title_style,
5423        title_style.line_height,
5424        0.5,
5425    );
5426
5427    let description_style = text_token_style(theme, theme.text.sm, theme.surfaces.text_faint);
5428    paint_single_line_aligned_text(
5429        ctx,
5430        centered_text_slot(bounds, cy + 30.0, description_style.line_height),
5431        paint.description,
5432        &description_style,
5433        description_style.line_height,
5434        0.5,
5435    );
5436
5437    if let Some(detail) = paint.detail {
5438        let mut detail_style = text_token_style(theme, theme.text.xs, theme.surfaces.text_muted);
5439        detail_style.weight = FontWeight::MEDIUM;
5440        paint_single_line_aligned_text(
5441            ctx,
5442            centered_text_slot(bounds, cy + 48.0, detail_style.line_height),
5443            detail,
5444            &detail_style,
5445            detail_style.line_height,
5446            0.5,
5447        );
5448    }
5449}
5450
5451pub struct EmptyState {
5452    theme: Box<DefaultTheme>,
5453    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5454    name: Option<String>,
5455    icon: Option<IconGlyph>,
5456    title: String,
5457    description: String,
5458    detail: Option<String>,
5459    action: Option<SingleChild>,
5460    action_height: f32,
5461    action_max_width: f32,
5462    background: Option<Color>,
5463}
5464
5465impl EmptyState {
5466    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
5467        Self {
5468            theme: Box::new(DefaultTheme::default()),
5469            theme_reader: None,
5470            name: None,
5471            icon: None,
5472            title: title.into(),
5473            description: description.into(),
5474            detail: None,
5475            action: None,
5476            action_height: 32.0,
5477            action_max_width: 360.0,
5478            background: None,
5479        }
5480    }
5481
5482    pub fn theme(mut self, theme: DefaultTheme) -> Self {
5483        self.theme = Box::new(theme);
5484        self.theme_reader = None;
5485        self
5486    }
5487
5488    pub fn theme_when<F>(mut self, theme: F) -> Self
5489    where
5490        F: Fn() -> DefaultTheme + 'static,
5491    {
5492        self.theme_reader = Some(Box::new(theme));
5493        self
5494    }
5495
5496    pub fn name(mut self, name: impl Into<String>) -> Self {
5497        self.name = Some(name.into());
5498        self
5499    }
5500
5501    pub fn icon(mut self, icon: IconGlyph) -> Self {
5502        self.icon = Some(icon);
5503        self
5504    }
5505
5506    pub fn detail(mut self, detail: impl Into<String>) -> Self {
5507        self.detail = Some(detail.into());
5508        self
5509    }
5510
5511    pub fn action<W>(mut self, action: W) -> Self
5512    where
5513        W: Widget + 'static,
5514    {
5515        self.action = Some(SingleChild::new(action));
5516        self
5517    }
5518
5519    pub fn action_height(mut self, height: f32) -> Self {
5520        self.action_height = height.max(32.0);
5521        self
5522    }
5523
5524    pub fn action_max_width(mut self, width: f32) -> Self {
5525        self.action_max_width = width.max(0.0);
5526        self
5527    }
5528
5529    pub fn background(mut self, color: Color) -> Self {
5530        self.background = Some(color);
5531        self
5532    }
5533
5534    pub fn transparent(mut self) -> Self {
5535        self.background = Some(Color::TRANSPARENT);
5536        self
5537    }
5538
5539    pub fn action_child(&self) -> Option<&WidgetPod> {
5540        self.action.as_ref().map(SingleChild::child)
5541    }
5542
5543    pub fn action_child_mut(&mut self) -> Option<&mut WidgetPod> {
5544        self.action.as_mut().map(SingleChild::child_mut)
5545    }
5546
5547    fn resolved_theme(&self) -> DefaultTheme {
5548        self.theme_reader
5549            .as_ref()
5550            .map(|reader| reader())
5551            .unwrap_or(*self.theme)
5552    }
5553
5554    fn action_rect(&self, bounds: Rect) -> Rect {
5555        let width = self.action_max_width.min((bounds.width() - 32.0).max(0.0));
5556        let cx = bounds.x() + bounds.width() * 0.5;
5557        let cy = bounds.y() + bounds.height() * 0.5 - 18.0;
5558        Rect::new(cx - width * 0.5, cy + 54.0, width, self.action_height)
5559    }
5560}
5561
5562impl Widget for EmptyState {
5563    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5564        let width = if constraints.max.width.is_finite() {
5565            constraints.max.width
5566        } else {
5567            constraints.min.width.max(self.action_max_width + 32.0)
5568        };
5569        let action_height = if let Some(action) = &mut self.action {
5570            let action_width = self.action_max_width.min((width - 32.0).max(0.0));
5571            action.measure(
5572                ctx,
5573                Constraints::tight(Size::new(action_width, self.action_height)),
5574            );
5575            self.action_height
5576        } else {
5577            0.0
5578        };
5579        let height = if constraints.max.height.is_finite() {
5580            constraints.max.height
5581        } else {
5582            constraints
5583                .min
5584                .height
5585                .max(142.0 + action_height + if action_height > 0.0 { 12.0 } else { 0.0 })
5586        };
5587        constraints.clamp(Size::new(width, height))
5588    }
5589
5590    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
5591        let action_rect = self.action_rect(bounds);
5592        if let Some(action) = &mut self.action {
5593            action.arrange(ctx, action_rect);
5594        }
5595    }
5596
5597    fn paint(&self, ctx: &mut PaintCtx) {
5598        let theme = self.resolved_theme();
5599        let bounds = ctx.bounds();
5600        let mut paint = EmptyStatePaint::new(&self.title, &self.description)
5601            .background(self.background.unwrap_or(theme.surfaces.window))
5602            .reserve_action_space(self.action.is_some());
5603        if let Some(icon) = self.icon {
5604            paint = paint.icon(icon);
5605        }
5606        if let Some(detail) = self.detail.as_deref() {
5607            paint = paint.detail(detail);
5608        }
5609        paint_empty_state(ctx, &theme, bounds, paint);
5610
5611        if let Some(action) = &self.action {
5612            action.paint(ctx);
5613        }
5614    }
5615
5616    fn semantics(&self, ctx: &mut SemanticsCtx) {
5617        let mut node = SemanticsNode::new(
5618            ctx.widget_id(),
5619            SemanticsRole::GenericContainer,
5620            ctx.bounds(),
5621        );
5622        node.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
5623        node.description = Some(match &self.detail {
5624            Some(detail)
5625                if matches!(
5626                    self.description.chars().last(),
5627                    Some('.') | Some('!') | Some('?')
5628                ) =>
5629            {
5630                format!("{} {}", self.description, detail)
5631            }
5632            Some(detail) => format!("{}. {}", self.description, detail),
5633            None => self.description.clone(),
5634        });
5635        ctx.push(node);
5636        if let Some(action) = &self.action {
5637            action.semantics(ctx);
5638        }
5639    }
5640
5641    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
5642        if let Some(action) = &self.action {
5643            action.visit_children(visitor);
5644        }
5645    }
5646
5647    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
5648        if let Some(action) = &mut self.action {
5649            action.visit_children_mut(visitor);
5650        }
5651    }
5652}
5653
5654pub struct PresetStrip {
5655    theme: Box<DefaultTheme>,
5656    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
5657    name: String,
5658    presets: Vec<String>,
5659    selected: Option<usize>,
5660    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
5661    hovered: Option<usize>,
5662    hover_visual: Option<usize>,
5663    pressed: Option<usize>,
5664    press_visual: Option<usize>,
5665    hover_animation: AnimatedScalar,
5666    press_animation: AnimatedScalar,
5667    focus_animation: AnimatedScalar,
5668    item_width: Option<f32>,
5669    item_height: Option<f32>,
5670    gap: Option<f32>,
5671    label_measurements: Vec<TextMeasurement>,
5672    item_widths: Vec<f32>,
5673    on_change: Option<Box<dyn FnMut(usize, String)>>,
5674}
5675
5676impl PresetStrip {
5677    pub fn new(name: impl Into<String>) -> Self {
5678        Self {
5679            theme: Box::new(DefaultTheme::default()),
5680            theme_reader: None,
5681            name: name.into(),
5682            presets: Vec::new(),
5683            selected: None,
5684            selected_reader: None,
5685            hovered: None,
5686            hover_visual: None,
5687            pressed: None,
5688            press_visual: None,
5689            hover_animation: AnimatedScalar::new(0.0),
5690            press_animation: AnimatedScalar::new(0.0),
5691            focus_animation: AnimatedScalar::new(0.0),
5692            item_width: None,
5693            item_height: None,
5694            gap: None,
5695            label_measurements: Vec::new(),
5696            item_widths: Vec::new(),
5697            on_change: None,
5698        }
5699    }
5700
5701    pub fn theme(mut self, theme: DefaultTheme) -> Self {
5702        self.theme = Box::new(theme);
5703        self.theme_reader = None;
5704        self
5705    }
5706
5707    pub fn theme_when<F>(mut self, theme: F) -> Self
5708    where
5709        F: Fn() -> DefaultTheme + 'static,
5710    {
5711        self.theme_reader = Some(Box::new(theme));
5712        self
5713    }
5714
5715    pub fn preset(mut self, preset: impl Into<String>) -> Self {
5716        self.presets.push(preset.into());
5717        self
5718    }
5719
5720    pub fn presets<I, S>(mut self, presets: I) -> Self
5721    where
5722        I: IntoIterator<Item = S>,
5723        S: Into<String>,
5724    {
5725        self.presets.extend(presets.into_iter().map(Into::into));
5726        self
5727    }
5728
5729    pub fn selected(mut self, selected: usize) -> Self {
5730        self.selected = Some(selected);
5731        self.selected_reader = None;
5732        self
5733    }
5734
5735    pub fn selected_when<F>(mut self, selected: F) -> Self
5736    where
5737        F: Fn() -> Option<usize> + 'static,
5738    {
5739        self.selected_reader = Some(Box::new(selected));
5740        self
5741    }
5742
5743    pub fn item_width(mut self, width: f32) -> Self {
5744        self.item_width = Some(width.max(0.0));
5745        self
5746    }
5747
5748    pub fn item_height(mut self, height: f32) -> Self {
5749        self.item_height = Some(height.max(20.0));
5750        self
5751    }
5752
5753    pub fn gap(mut self, gap: f32) -> Self {
5754        self.gap = Some(gap.max(0.0));
5755        self
5756    }
5757
5758    pub fn on_change<F>(mut self, on_change: F) -> Self
5759    where
5760        F: FnMut(usize, String) + 'static,
5761    {
5762        self.on_change = Some(Box::new(on_change));
5763        self
5764    }
5765
5766    pub fn selected_index(&self) -> Option<usize> {
5767        self.current_selected()
5768    }
5769
5770    fn current_selected(&self) -> Option<usize> {
5771        self.selected_reader
5772            .as_ref()
5773            .map(|selected| selected())
5774            .unwrap_or(self.selected)
5775            .filter(|index| *index < self.presets.len())
5776    }
5777
5778    fn resolved_theme(&self) -> DefaultTheme {
5779        self.theme_reader
5780            .as_ref()
5781            .map(|theme| theme())
5782            .unwrap_or(*self.theme)
5783    }
5784
5785    fn resolved_item_height(&self, metrics: ControlMetrics) -> f32 {
5786        self.item_height.unwrap_or(metrics.preset_strip_item_height)
5787    }
5788
5789    fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
5790        self.gap.unwrap_or(metrics.preset_strip_gap)
5791    }
5792
5793    fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
5794        if index >= self.presets.len() || self.item_widths.len() != self.presets.len() {
5795            return None;
5796        }
5797
5798        let metrics = self.resolved_theme().metrics;
5799        let item_height = self.resolved_item_height(metrics);
5800        let gap = self.resolved_gap(metrics);
5801        let mut x = bounds.x();
5802        for (current, width) in self.item_widths.iter().enumerate() {
5803            let available = (bounds.max_x() - x).max(0.0);
5804            let rect = Rect::new(x, bounds.y(), width.min(available), item_height);
5805            if current == index {
5806                return (!rect.is_empty()).then_some(rect);
5807            }
5808            x += *width + gap;
5809        }
5810
5811        None
5812    }
5813
5814    fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
5815        self.presets.iter().enumerate().find_map(|(index, _)| {
5816            self.item_rect(bounds, index)
5817                .filter(|rect| rect.contains(position))
5818                .map(|_| index)
5819        })
5820    }
5821
5822    fn activate(&mut self, index: usize) {
5823        if self.presets.is_empty() {
5824            return;
5825        }
5826
5827        let index = index.min(self.presets.len() - 1);
5828        self.selected = Some(index);
5829        if let Some(on_change) = &mut self.on_change {
5830            on_change(index, self.presets[index].clone());
5831        }
5832    }
5833
5834    fn move_selection(&mut self, delta: isize) {
5835        if self.presets.is_empty() {
5836            return;
5837        }
5838
5839        let current = self.current_selected().unwrap_or(0) as isize;
5840        let last = self.presets.len() as isize - 1;
5841        let next = (current + delta).clamp(0, last) as usize;
5842        self.hovered = Some(next);
5843        self.activate(next);
5844    }
5845
5846    fn selected_text(&self) -> Option<String> {
5847        self.current_selected()
5848            .and_then(|index| self.presets.get(index).cloned())
5849    }
5850
5851    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
5852        if self.hovered == hovered {
5853            return;
5854        }
5855        let theme = self.resolved_theme();
5856        self.hovered = hovered;
5857        if let Some(index) = hovered {
5858            self.hover_visual = Some(index);
5859            self.hover_animation = AnimatedScalar::new(0.0);
5860            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
5861        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
5862            self.hover_visual = None;
5863        }
5864        ctx.request_paint();
5865        ctx.request_semantics();
5866    }
5867
5868    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
5869        if self.pressed == pressed {
5870            return;
5871        }
5872        let theme = self.resolved_theme();
5873        self.pressed = pressed;
5874        if let Some(index) = pressed {
5875            self.press_visual = Some(index);
5876            self.press_animation = AnimatedScalar::new(0.0);
5877            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
5878        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
5879            self.press_visual = None;
5880        }
5881        ctx.request_paint();
5882        ctx.request_semantics();
5883    }
5884
5885    fn hover_amount_for(&self, index: usize) -> f32 {
5886        if self.hover_visual == Some(index) {
5887            self.hover_animation.value
5888        } else {
5889            0.0
5890        }
5891    }
5892
5893    fn press_amount_for(&self, index: usize) -> f32 {
5894        if self.press_visual == Some(index) {
5895            self.press_animation.value
5896        } else {
5897            0.0
5898        }
5899    }
5900
5901    fn advance_animations(&mut self, time: f64) -> bool {
5902        let hover_animating = self.hover_animation.advance(time);
5903        if !hover_animating
5904            && self.hovered.is_none()
5905            && self.hover_animation.value <= AnimatedScalar::EPSILON
5906        {
5907            self.hover_visual = None;
5908        }
5909
5910        let press_animating = self.press_animation.advance(time);
5911        if !press_animating
5912            && self.pressed.is_none()
5913            && self.press_animation.value <= AnimatedScalar::EPSILON
5914        {
5915            self.press_visual = None;
5916        }
5917
5918        hover_animating | press_animating | self.focus_animation.advance(time)
5919    }
5920}
5921
5922impl Widget for PresetStrip {
5923    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
5924        match event {
5925            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
5926                self.set_hovered(self.item_at(ctx.bounds(), pointer.position), ctx);
5927            }
5928            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
5929                self.set_hovered(None, ctx);
5930            }
5931            Event::Pointer(pointer)
5932                if pointer.kind == PointerEventKind::Down
5933                    && pointer.button == Some(PointerButton::Primary) =>
5934            {
5935                let hovered = self.item_at(ctx.bounds(), pointer.position);
5936                self.set_hovered(hovered, ctx);
5937                self.set_pressed(hovered, ctx);
5938                if self.hovered.is_some() {
5939                    ctx.request_focus();
5940                    ctx.request_pointer_capture(pointer.pointer_id);
5941                    ctx.set_handled();
5942                }
5943            }
5944            Event::Pointer(pointer)
5945                if pointer.kind == PointerEventKind::Up
5946                    && pointer.button == Some(PointerButton::Primary) =>
5947            {
5948                let hovered = self.item_at(ctx.bounds(), pointer.position);
5949                if let Some(index) = self
5950                    .pressed
5951                    .zip(hovered)
5952                    .filter(|(left, right)| left == right)
5953                    .map(|(index, _)| index)
5954                {
5955                    self.activate(index);
5956                }
5957                self.set_hovered(hovered, ctx);
5958                self.set_pressed(None, ctx);
5959                ctx.release_pointer_capture(pointer.pointer_id);
5960                ctx.set_handled();
5961            }
5962            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
5963                if self.pressed.is_some() {
5964                    self.set_pressed(None, ctx);
5965                    self.set_hovered(None, ctx);
5966                    ctx.release_pointer_capture(pointer.pointer_id);
5967                    ctx.set_handled();
5968                }
5969            }
5970            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
5971                match key.key.as_str() {
5972                    "ArrowLeft" | "ArrowUp" => self.move_selection(-1),
5973                    "ArrowRight" | "ArrowDown" => self.move_selection(1),
5974                    "Home" => self.activate(0),
5975                    "End" if !self.presets.is_empty() => self.activate(self.presets.len() - 1),
5976                    "Enter" | " " => {
5977                        if let Some(selected) = self.current_selected().or(Some(0)) {
5978                            self.activate(selected);
5979                        }
5980                    }
5981                    _ => return,
5982                }
5983                ctx.request_paint();
5984                ctx.request_semantics();
5985                ctx.set_handled();
5986            }
5987            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
5988                if self.advance_animations(*time) {
5989                    ctx.request_animation_frame();
5990                }
5991                ctx.request_paint();
5992            }
5993            _ => {}
5994        }
5995    }
5996
5997    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
5998        let theme = self.resolved_theme();
5999        let metrics = theme.metrics;
6000        let item_height = self.resolved_item_height(metrics);
6001        let gap = self.resolved_gap(metrics);
6002        let style = text_token_style(&theme, theme.text.xs, theme.palette.text);
6003        self.label_measurements = self
6004            .presets
6005            .iter()
6006            .map(|preset| measure_text(ctx, preset, &style))
6007            .collect();
6008        self.item_widths = self
6009            .label_measurements
6010            .iter()
6011            .map(|measurement| {
6012                self.item_width.unwrap_or(
6013                    (measurement.width
6014                        + metrics.preset_strip_item_padding.left
6015                        + metrics.preset_strip_item_padding.right)
6016                        .max(metrics.preset_strip_item_min_width),
6017                )
6018            })
6019            .collect();
6020
6021        let width = self.item_widths.iter().sum::<f32>()
6022            + (gap * self.presets.len().saturating_sub(1) as f32);
6023        constraints.clamp(Size::new(width, item_height))
6024    }
6025
6026    fn paint(&self, ctx: &mut PaintCtx) {
6027        let theme = self.resolved_theme();
6028        let palette = theme.palette;
6029        let metrics = theme.metrics;
6030        let interaction = theme.interaction;
6031        let selected = self.current_selected();
6032        let style = text_token_style(&theme, theme.text.xs, palette.text);
6033
6034        if self.focus_animation.value > AnimatedScalar::EPSILON {
6035            ctx.stroke(
6036                rounded_rect_path(ctx.bounds().inflate(2.0, 2.0), metrics.corner_radius + 2.0),
6037                palette
6038                    .focus_ring
6039                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
6040                StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
6041            );
6042        }
6043
6044        for (index, preset) in self.presets.iter().enumerate() {
6045            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
6046                continue;
6047            };
6048            let is_selected = selected == Some(index);
6049            let is_hovered = self.hovered == Some(index);
6050            let hover_amount = self.hover_amount_for(index);
6051            let press_amount = self.press_amount_for(index);
6052            let base_background = if is_selected {
6053                palette.accent
6054            } else {
6055                palette.surface
6056            };
6057            let hover_background = if hover_amount > 0.0 {
6058                mix_color(
6059                    base_background,
6060                    palette.control_hover,
6061                    interaction.hover_blend * if is_selected { 0.35 } else { 1.0 } * hover_amount,
6062                )
6063            } else {
6064                base_background
6065            };
6066            let background = if press_amount > 0.0 {
6067                mix_color(
6068                    hover_background,
6069                    palette.control_active,
6070                    interaction.pressed_blend * if is_selected { 0.45 } else { 1.0 } * press_amount,
6071                )
6072            } else {
6073                hover_background
6074            };
6075            let border = if is_selected {
6076                palette.accent_border
6077            } else if is_hovered || hover_amount > 0.0 || press_amount > 0.0 {
6078                palette.border_hover
6079            } else {
6080                palette.border
6081            };
6082            let text_color = if is_selected {
6083                palette.accent_text
6084            } else {
6085                palette.text
6086            };
6087
6088            draw_control_shape(
6089                ctx,
6090                rect,
6091                metrics.corner_radius,
6092                physical_pixels(ctx, metrics.border_width),
6093                background,
6094                border,
6095            );
6096
6097            let text_slot = inset_rect(rect, metrics.preset_strip_label_padding);
6098            let pressed_offset = press_amount * interaction.pressed_offset;
6099            let text_style = TextStyle {
6100                color: text_color,
6101                ..style.clone()
6102            };
6103            ctx.push_clip_rect(text_slot);
6104            paint_aligned_text(
6105                ctx,
6106                text_slot.translate(Vector::new(0.0, pressed_offset)),
6107                preset,
6108                &text_style,
6109                text_style.line_height,
6110                0.5,
6111            );
6112            ctx.pop_clip();
6113        }
6114    }
6115
6116    fn semantics(&self, ctx: &mut SemanticsCtx) {
6117        let mut node = SemanticsNode::new(
6118            ctx.widget_id(),
6119            SemanticsRole::GenericContainer,
6120            ctx.bounds(),
6121        );
6122        node.name = Some(self.name.clone());
6123        node.value = self.selected_text().map(SemanticsValue::Text);
6124        node.state.focused = ctx.is_focused();
6125        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
6126        ctx.push(node);
6127
6128        let selected = self.current_selected();
6129        for (index, preset) in self.presets.iter().enumerate() {
6130            let Some(rect) = self.item_rect(ctx.bounds(), index) else {
6131                continue;
6132            };
6133            let mut item = SemanticsNode::new(
6134                preset_strip_item_id(ctx.widget_id(), index),
6135                SemanticsRole::Button,
6136                rect,
6137            );
6138            item.parent = Some(ctx.widget_id());
6139            item.name = Some(preset.clone());
6140            item.value = Some(SemanticsValue::Text(preset.clone()));
6141            item.state.hovered = self.hovered == Some(index);
6142            item.state.selected = selected == Some(index);
6143            item.actions = vec![SemanticsAction::Activate];
6144            ctx.push(item);
6145        }
6146    }
6147
6148    fn accepts_focus(&self) -> bool {
6149        !self.presets.is_empty()
6150    }
6151
6152    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
6153        let theme = self.resolved_theme();
6154        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
6155        ctx.request_paint();
6156        ctx.request_semantics();
6157    }
6158}
6159
6160fn preset_strip_item_id(parent: WidgetId, index: usize) -> WidgetId {
6161    const TAG: u64 = 6_u64 << 50;
6162    const LOW_MASK: u64 = (1_u64 << 50) - 1;
6163
6164    WidgetId::new(
6165        TAG | (parent
6166            .get()
6167            .wrapping_mul(487)
6168            .wrapping_add(index as u64 + 1)
6169            & LOW_MASK),
6170    )
6171}
6172
6173pub struct StatusBarSegment {
6174    text: String,
6175    reader: Option<Box<dyn Fn() -> String>>,
6176    min_width: Option<f32>,
6177    tone: SemanticTone,
6178    expand: bool,
6179}
6180
6181impl StatusBarSegment {
6182    pub fn new(text: impl Into<String>) -> Self {
6183        Self {
6184            text: text.into(),
6185            reader: None,
6186            min_width: None,
6187            tone: SemanticTone::Neutral,
6188            expand: false,
6189        }
6190    }
6191
6192    pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
6193    where
6194        F: Fn() -> String + 'static,
6195    {
6196        Self {
6197            text: fallback.into(),
6198            reader: Some(Box::new(reader)),
6199            min_width: None,
6200            tone: SemanticTone::Neutral,
6201            expand: false,
6202        }
6203    }
6204
6205    pub fn min_width(mut self, min_width: f32) -> Self {
6206        self.min_width = Some(min_width.max(0.0));
6207        self
6208    }
6209
6210    pub fn tone(mut self, tone: SemanticTone) -> Self {
6211        self.tone = tone;
6212        self
6213    }
6214
6215    pub fn expand(mut self, expand: bool) -> Self {
6216        self.expand = expand;
6217        self
6218    }
6219
6220    fn text(&self) -> String {
6221        self.reader
6222            .as_ref()
6223            .map(|reader| reader())
6224            .unwrap_or_else(|| self.text.clone())
6225    }
6226}
6227
6228pub struct StatusBar {
6229    theme: Box<DefaultTheme>,
6230    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
6231    name: Option<String>,
6232    description: Option<String>,
6233    description_reader: Option<Box<dyn Fn() -> String>>,
6234    height: Option<f32>,
6235    segments: Vec<StatusBarSegment>,
6236    measured_widths: Vec<f32>,
6237}
6238
6239impl StatusBar {
6240    pub fn new() -> Self {
6241        Self {
6242            theme: Box::new(DefaultTheme::default()),
6243            theme_reader: None,
6244            name: None,
6245            description: None,
6246            description_reader: None,
6247            height: None,
6248            segments: Vec::new(),
6249            measured_widths: Vec::new(),
6250        }
6251    }
6252
6253    pub fn theme(mut self, theme: DefaultTheme) -> Self {
6254        self.theme = Box::new(theme);
6255        self.theme_reader = None;
6256        self
6257    }
6258
6259    pub fn theme_when<F>(mut self, theme: F) -> Self
6260    where
6261        F: Fn() -> DefaultTheme + 'static,
6262    {
6263        self.theme_reader = Some(Box::new(theme));
6264        self
6265    }
6266
6267    pub fn name(mut self, name: impl Into<String>) -> Self {
6268        self.name = Some(name.into());
6269        self
6270    }
6271
6272    pub fn description(mut self, description: impl Into<String>) -> Self {
6273        self.description = Some(description.into());
6274        self.description_reader = None;
6275        self
6276    }
6277
6278    pub fn description_when<F>(mut self, description: F) -> Self
6279    where
6280        F: Fn() -> String + 'static,
6281    {
6282        self.description_reader = Some(Box::new(description));
6283        self
6284    }
6285
6286    pub fn height(mut self, height: f32) -> Self {
6287        self.height = Some(height.max(18.0));
6288        self
6289    }
6290
6291    pub fn segment(mut self, segment: StatusBarSegment) -> Self {
6292        self.segments.push(segment);
6293        self
6294    }
6295
6296    pub fn text_segment(self, text: impl Into<String>) -> Self {
6297        self.segment(StatusBarSegment::new(text))
6298    }
6299
6300    pub fn dynamic_segment<F>(self, fallback: impl Into<String>, reader: F) -> Self
6301    where
6302        F: Fn() -> String + 'static,
6303    {
6304        self.segment(StatusBarSegment::dynamic(fallback, reader))
6305    }
6306
6307    fn text_style(&self) -> TextStyle {
6308        let theme = self.resolved_theme();
6309        text_token_style(&theme, theme.text.xs, theme.palette.placeholder)
6310    }
6311
6312    fn resolved_theme(&self) -> DefaultTheme {
6313        self.theme_reader
6314            .as_ref()
6315            .map(|theme| theme())
6316            .unwrap_or(*self.theme)
6317    }
6318
6319    fn resolved_height(&self, metrics: ControlMetrics) -> f32 {
6320        self.height.unwrap_or(metrics.status_bar_height)
6321    }
6322
6323    fn description_text(&self) -> Option<String> {
6324        self.description_reader
6325            .as_ref()
6326            .map(|reader| reader())
6327            .or_else(|| self.description.clone())
6328    }
6329
6330    fn resolved_segment_min_width(segment: &StatusBarSegment, metrics: ControlMetrics) -> f32 {
6331        segment
6332            .min_width
6333            .unwrap_or(metrics.status_bar_segment_min_width)
6334    }
6335
6336    fn segment_widths(&self, metrics: ControlMetrics) -> Vec<f32> {
6337        if self.measured_widths.len() == self.segments.len() {
6338            self.measured_widths.clone()
6339        } else {
6340            self.segments
6341                .iter()
6342                .map(|segment| Self::resolved_segment_min_width(segment, metrics))
6343                .collect()
6344        }
6345    }
6346
6347    fn segment_rects(&self, bounds: Rect, metrics: ControlMetrics) -> Vec<Rect> {
6348        let mut widths = self.segment_widths(metrics);
6349        let expandable = self
6350            .segments
6351            .iter()
6352            .filter(|segment| segment.expand)
6353            .count();
6354        if expandable > 0 {
6355            let fixed: f32 = widths.iter().sum();
6356            let extra = (bounds.width() - fixed).max(0.0) / expandable as f32;
6357            for (index, segment) in self.segments.iter().enumerate() {
6358                if segment.expand {
6359                    widths[index] += extra;
6360                }
6361            }
6362        }
6363
6364        let mut x = bounds.x();
6365        widths
6366            .into_iter()
6367            .map(|width| {
6368                let available = (bounds.max_x() - x).max(0.0);
6369                let rect = Rect::new(x, bounds.y(), width.min(available), bounds.height());
6370                x = rect.max_x();
6371                rect
6372            })
6373            .collect()
6374    }
6375}
6376
6377impl Default for StatusBar {
6378    fn default() -> Self {
6379        Self::new()
6380    }
6381}
6382
6383pub struct StatusBarHost {
6384    content: SingleChild,
6385    status_bar: SingleChild,
6386}
6387
6388impl StatusBarHost {
6389    pub fn new<C, S>(content: C, status_bar: S) -> Self
6390    where
6391        C: Widget + 'static,
6392        S: Widget + 'static,
6393    {
6394        Self {
6395            content: SingleChild::new(content),
6396            status_bar: SingleChild::new(status_bar),
6397        }
6398    }
6399
6400    pub fn content(&self) -> &sui_runtime::WidgetPod {
6401        self.content.child()
6402    }
6403
6404    pub fn content_mut(&mut self) -> &mut sui_runtime::WidgetPod {
6405        self.content.child_mut()
6406    }
6407
6408    pub fn status_bar(&self) -> &sui_runtime::WidgetPod {
6409        self.status_bar.child()
6410    }
6411
6412    pub fn status_bar_mut(&mut self) -> &mut sui_runtime::WidgetPod {
6413        self.status_bar.child_mut()
6414    }
6415}
6416
6417impl Widget for StatusBarHost {
6418    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6419        let max = constraints.max;
6420        let status_size = self.status_bar.measure(
6421            ctx,
6422            Constraints::new(Size::ZERO, Size::new(max.width, max.height)),
6423        );
6424        let content_max_height = if max.height.is_finite() {
6425            (max.height - status_size.height).max(0.0)
6426        } else {
6427            f32::INFINITY
6428        };
6429        let content_size = self.content.measure(
6430            ctx,
6431            Constraints::new(Size::ZERO, Size::new(max.width, content_max_height)),
6432        );
6433
6434        constraints.clamp(Size::new(
6435            content_size.width.max(status_size.width),
6436            content_size.height + status_size.height,
6437        ))
6438    }
6439
6440    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
6441        let status_height = self
6442            .status_bar
6443            .child()
6444            .measured_size()
6445            .height
6446            .min(bounds.height())
6447            .max(0.0);
6448        let content_height = (bounds.height() - status_height).max(0.0);
6449
6450        self.content.arrange(
6451            ctx,
6452            Rect::new(bounds.x(), bounds.y(), bounds.width(), content_height),
6453        );
6454        self.status_bar.arrange(
6455            ctx,
6456            Rect::new(
6457                bounds.x(),
6458                bounds.y() + content_height,
6459                bounds.width(),
6460                status_height,
6461            ),
6462        );
6463    }
6464
6465    fn paint(&self, ctx: &mut PaintCtx) {
6466        self.content.paint(ctx);
6467        self.status_bar.paint(ctx);
6468    }
6469
6470    fn semantics(&self, ctx: &mut SemanticsCtx) {
6471        self.content.semantics(ctx);
6472        self.status_bar.semantics(ctx);
6473    }
6474
6475    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
6476        self.content.visit_children(visitor);
6477        self.status_bar.visit_children(visitor);
6478    }
6479
6480    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
6481        self.content.visit_children_mut(visitor);
6482        self.status_bar.visit_children_mut(visitor);
6483    }
6484}
6485
6486impl Widget for StatusBar {
6487    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
6488        let theme = self.resolved_theme();
6489        let metrics = theme.metrics;
6490        let text_style = self.text_style();
6491        self.measured_widths = self
6492            .segments
6493            .iter()
6494            .map(|segment| {
6495                let text = segment.text();
6496                let segment_style = numeric_text_style_if_numeric(&text, text_style.clone());
6497                let measured = measure_text(ctx, &text, &segment_style).width
6498                    + metrics.status_bar_segment_padding * 2.0;
6499                Self::resolved_segment_min_width(segment, metrics).max(measured.ceil())
6500            })
6501            .collect();
6502        let natural_width: f32 = self.measured_widths.iter().sum();
6503        constraints.clamp(Size::new(
6504            if constraints.max.width.is_finite() {
6505                constraints.max.width
6506            } else {
6507                natural_width
6508            },
6509            self.resolved_height(metrics),
6510        ))
6511    }
6512
6513    fn paint(&self, ctx: &mut PaintCtx) {
6514        let theme = self.resolved_theme();
6515        let palette = theme.palette;
6516        let metrics = theme.metrics;
6517        let bounds = ctx.bounds();
6518        ctx.fill_bounds(palette.surface);
6519        ctx.stroke_rect(
6520            Rect::new(bounds.x(), bounds.y(), bounds.width(), 1.0),
6521            palette.border,
6522            StrokeStyle::new(theme.metrics.border_width.max(1.0)),
6523        );
6524
6525        let text_style = self.text_style();
6526        for (index, (segment, rect)) in self
6527            .segments
6528            .iter()
6529            .zip(self.segment_rects(bounds, metrics))
6530            .enumerate()
6531        {
6532            if rect.is_empty() {
6533                continue;
6534            }
6535            if index > 0 {
6536                let inset = metrics.status_bar_separator_inset.min(rect.height() * 0.5);
6537                ctx.stroke_rect(
6538                    Rect::new(
6539                        rect.x(),
6540                        rect.y() + inset,
6541                        1.0,
6542                        (rect.height() - inset * 2.0).max(0.0),
6543                    ),
6544                    palette.border.with_alpha(0.7),
6545                    StrokeStyle::new(1.0),
6546                );
6547            }
6548            let segment_text = segment.text();
6549            let segment_style = if segment.tone == SemanticTone::Neutral {
6550                text_style.clone()
6551            } else {
6552                let tone = theme.semantic_tone_color(segment.tone);
6553                let pill = Rect::new(
6554                    rect.x() + metrics.status_bar_separator_inset.min(rect.width() * 0.5),
6555                    rect.y() + metrics.status_bar_separator_inset.min(rect.height() * 0.5),
6556                    (rect.width() - metrics.status_bar_separator_inset * 2.0).max(0.0),
6557                    (rect.height() - metrics.status_bar_separator_inset * 2.0).max(0.0),
6558                );
6559                if !pill.is_empty() {
6560                    ctx.fill(
6561                        rounded_rect_path(pill, metrics.indicator_corner_radius),
6562                        tone.with_alpha(0.12),
6563                    );
6564                }
6565                TextStyle {
6566                    color: tone,
6567                    ..text_style.clone()
6568                }
6569            };
6570            let segment_style = numeric_text_style_if_numeric(&segment_text, segment_style);
6571            let content_rect = Rect::new(
6572                rect.x() + metrics.status_bar_segment_padding,
6573                rect.y(),
6574                (rect.width() - metrics.status_bar_segment_padding * 2.0).max(0.0),
6575                rect.height(),
6576            );
6577            ctx.push_clip_rect(content_rect);
6578            paint_aligned_text(
6579                ctx,
6580                content_rect,
6581                &segment_text,
6582                &segment_style,
6583                segment_style.line_height,
6584                0.0,
6585            );
6586            ctx.pop_clip();
6587        }
6588    }
6589
6590    fn semantics(&self, ctx: &mut SemanticsCtx) {
6591        let theme = self.resolved_theme();
6592        let metrics = theme.metrics;
6593        let mut node = SemanticsNode::new(
6594            ctx.widget_id(),
6595            SemanticsRole::GenericContainer,
6596            ctx.bounds(),
6597        );
6598        node.name = self.name.clone();
6599        if let Some(description) = self.description_text() {
6600            node.value = Some(SemanticsValue::Text(description.clone()));
6601            node.description = Some(description);
6602        }
6603        ctx.push(node);
6604
6605        for (index, (segment, rect)) in self
6606            .segments
6607            .iter()
6608            .zip(self.segment_rects(ctx.bounds(), metrics))
6609            .enumerate()
6610        {
6611            let text = segment.text();
6612            let mut child = SemanticsNode::new(
6613                status_bar_segment_id(ctx.widget_id(), index),
6614                SemanticsRole::Text,
6615                rect,
6616            );
6617            child.parent = Some(ctx.widget_id());
6618            child.name = Some(text.clone());
6619            child.value = Some(SemanticsValue::Text(text));
6620            ctx.push(child);
6621        }
6622    }
6623}
6624
6625fn status_bar_segment_id(parent: WidgetId, index: usize) -> WidgetId {
6626    const TAG: u64 = 2_u64 << 51;
6627    const LOW_MASK: u64 = (1_u64 << 51) - 1;
6628
6629    WidgetId::new(
6630        TAG | (parent
6631            .get()
6632            .wrapping_mul(263)
6633            .wrapping_add(index as u64 + 1)
6634            & LOW_MASK),
6635    )
6636}
6637
6638type SegmentedControlChange = Box<dyn FnMut(usize, String)>;
6639type SegmentedControlContextChange = Box<dyn FnMut(usize, String, &mut EventCtx)>;
6640
6641fn segmented_control_item_id(parent: WidgetId, index: usize) -> WidgetId {
6642    const TAG: u64 = 3_u64 << 51;
6643    const LOW_MASK: u64 = (1_u64 << 51) - 1;
6644
6645    WidgetId::new(
6646        TAG | (parent
6647            .get()
6648            .wrapping_mul(269)
6649            .wrapping_add(index as u64 + 1)
6650            & LOW_MASK),
6651    )
6652}
6653
6654pub struct StatusBadge {
6655    theme: Box<DefaultTheme>,
6656    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
6657    label: String,
6658    label_reader: Option<Box<dyn Fn() -> String>>,
6659    icon: Option<IconGlyph>,
6660    tone: SemanticTone,
6661    tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
6662    min_width: Option<f32>,
6663}
6664
6665impl StatusBadge {
6666    pub fn new(label: impl Into<String>) -> Self {
6667        Self {
6668            theme: Box::new(DefaultTheme::default()),
6669            theme_reader: None,
6670            label: label.into(),
6671            label_reader: None,
6672            icon: None,
6673            tone: SemanticTone::Neutral,
6674            tone_reader: None,
6675            min_width: None,
6676        }
6677    }
6678
6679    pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
6680    where
6681        F: Fn() -> String + 'static,
6682    {
6683        Self {
6684            label: fallback.into(),
6685            label_reader: Some(Box::new(reader)),
6686            ..Self::new("")
6687        }
6688    }
6689
6690    pub fn theme(mut self, theme: DefaultTheme) -> Self {
6691        self.theme = Box::new(theme);
6692        self.theme_reader = None;
6693        self
6694    }
6695
6696    pub fn theme_when<F>(mut self, theme: F) -> Self
6697    where
6698        F: Fn() -> DefaultTheme + 'static,
6699    {
6700        self.theme_reader = Some(Box::new(theme));
6701        self
6702    }
6703
6704    pub fn icon(mut self, icon: IconGlyph) -> Self {
6705        self.icon = Some(icon);
6706        self
6707    }
6708
6709    pub fn tone(mut self, tone: SemanticTone) -> Self {
6710        self.tone = tone;
6711        self.tone_reader = None;
6712        self
6713    }
6714
6715    pub fn tone_when<F>(mut self, tone: F) -> Self
6716    where
6717        F: Fn() -> SemanticTone + 'static,
6718    {
6719        self.tone_reader = Some(Box::new(tone));
6720        self
6721    }
6722
6723    pub fn min_width(mut self, min_width: f32) -> Self {
6724        self.min_width = Some(min_width.max(0.0));
6725        self
6726    }
6727
6728    fn resolved_theme(&self) -> DefaultTheme {
6729        self.theme_reader
6730            .as_ref()
6731            .map(|theme| theme())
6732            .unwrap_or(*self.theme)
6733    }
6734
6735    fn label(&self) -> String {
6736        self.label_reader
6737            .as_ref()
6738            .map(|reader| reader())
6739            .unwrap_or_else(|| self.label.clone())
6740    }
6741
6742    fn resolved_tone(&self) -> SemanticTone {
6743        self.tone_reader
6744            .as_ref()
6745            .map(|reader| reader())
6746            .unwrap_or(self.tone)
6747    }
6748
6749    fn text_style(&self, theme: &DefaultTheme, label: &str, tone: SemanticTone) -> TextStyle {
6750        // Mesh badge label: xs/600 in the status ink that reads on the soft wash.
6751        let (_, tone_ink) = theme.semantic_tone_soft_colors(tone);
6752        let mut style = text_token_style(theme, theme.text.xs, tone_ink);
6753        style.weight = FontWeight::SEMIBOLD;
6754        numeric_text_style_if_numeric(label, style)
6755    }
6756
6757    fn metrics(&self, theme: &DefaultTheme) -> (f32, f32, f32, f32) {
6758        let height = (theme.metrics.min_height - 2.0).max(22.0);
6759        let icon_size = (height - 13.0).clamp(11.0, 15.0);
6760        let gap = theme.metrics.icon_label_gap.max(4.0);
6761        let padding = theme.metrics.button_padding.left.max(8.0);
6762        (height, icon_size, gap, padding)
6763    }
6764}
6765
6766pub fn paint_status_badge(
6767    ctx: &mut PaintCtx,
6768    rect: Rect,
6769    theme: &DefaultTheme,
6770    label: &str,
6771    icon: Option<IconGlyph>,
6772    tone: SemanticTone,
6773) {
6774    if rect.width() <= 0.0 || rect.height() <= 0.0 {
6775        return;
6776    }
6777
6778    // Mesh badge: soft status wash, no border, status-hued ink (`--sm-*-soft`
6779    // fill + `--sm-*-text` content) at the xs/600 label size, r-1 corners.
6780    let (tone_soft, tone_ink) = theme.semantic_tone_soft_colors(tone);
6781    let icon_size = (rect.height() - 13.0).clamp(11.0, 15.0);
6782    let gap = theme.metrics.icon_label_gap.max(4.0);
6783    let padding = theme.metrics.button_padding.left.max(6.0);
6784    let radius = theme.radius.sm.min(rect.height() * 0.5);
6785
6786    ctx.fill(rounded_rect_path(rect, radius), tone_soft);
6787
6788    let mut x = rect.x() + padding.min(rect.width() * 0.5);
6789    if let Some(icon) = icon {
6790        let icon_rect = Rect::new(
6791            x,
6792            rect.y() + (rect.height() - icon_size) * 0.5,
6793            icon_size,
6794            icon_size,
6795        );
6796        draw_icon_glyph(ctx, icon, icon_rect, tone_ink);
6797        x = icon_rect.max_x() + gap;
6798    }
6799    let content_rect = Rect::new(
6800        x,
6801        rect.y(),
6802        (rect.max_x() - x - padding * 0.5).max(0.0),
6803        rect.height(),
6804    );
6805    if content_rect.width() <= 0.0 {
6806        return;
6807    }
6808
6809    let mut style = text_token_style(theme, theme.text.xs, tone_ink);
6810    style.weight = FontWeight::SEMIBOLD;
6811    let style = numeric_text_style_if_numeric(label, style);
6812    ctx.push_clip_rect(content_rect);
6813    paint_aligned_text(ctx, content_rect, label, &style, style.line_height, 0.0);
6814    ctx.pop_clip();
6815}
6816
6817#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6818pub enum CommandButtonFill {
6819    Surface,
6820    Filled,
6821}
6822
6823#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6824pub struct CommandButtonPaint {
6825    pub tone: SemanticTone,
6826    pub icon_tone: Option<SemanticTone>,
6827    pub fill: CommandButtonFill,
6828    pub hovered: bool,
6829    pub pressed: bool,
6830}
6831
6832impl CommandButtonPaint {
6833    pub const fn neutral() -> Self {
6834        Self {
6835            tone: SemanticTone::Neutral,
6836            icon_tone: None,
6837            fill: CommandButtonFill::Surface,
6838            hovered: false,
6839            pressed: false,
6840        }
6841    }
6842
6843    pub const fn tonal(tone: SemanticTone) -> Self {
6844        Self {
6845            tone,
6846            icon_tone: None,
6847            fill: CommandButtonFill::Surface,
6848            hovered: false,
6849            pressed: false,
6850        }
6851    }
6852
6853    pub const fn filled(tone: SemanticTone) -> Self {
6854        Self {
6855            tone,
6856            icon_tone: None,
6857            fill: CommandButtonFill::Filled,
6858            hovered: false,
6859            pressed: false,
6860        }
6861    }
6862
6863    pub const fn icon_tone(mut self, tone: SemanticTone) -> Self {
6864        self.icon_tone = Some(tone);
6865        self
6866    }
6867
6868    pub const fn hovered(mut self, hovered: bool) -> Self {
6869        self.hovered = hovered;
6870        self
6871    }
6872
6873    pub const fn pressed(mut self, pressed: bool) -> Self {
6874        self.pressed = pressed;
6875        self
6876    }
6877}
6878
6879impl Default for CommandButtonPaint {
6880    fn default() -> Self {
6881        Self::neutral()
6882    }
6883}
6884
6885#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6886pub struct DisclosureButtonPaint {
6887    pub command: CommandButtonPaint,
6888}
6889
6890impl DisclosureButtonPaint {
6891    pub const fn new() -> Self {
6892        Self {
6893            command: CommandButtonPaint::tonal(SemanticTone::Accent)
6894                .icon_tone(SemanticTone::Accent),
6895        }
6896    }
6897
6898    pub const fn command(mut self, command: CommandButtonPaint) -> Self {
6899        self.command = command;
6900        self
6901    }
6902
6903    pub const fn tone(mut self, tone: SemanticTone) -> Self {
6904        self.command = CommandButtonPaint::tonal(tone).icon_tone(tone);
6905        self
6906    }
6907
6908    pub const fn hovered(mut self, hovered: bool) -> Self {
6909        self.command = self.command.hovered(hovered);
6910        self
6911    }
6912
6913    pub const fn pressed(mut self, pressed: bool) -> Self {
6914        self.command = self.command.pressed(pressed);
6915        self
6916    }
6917}
6918
6919impl Default for DisclosureButtonPaint {
6920    fn default() -> Self {
6921        Self::new()
6922    }
6923}
6924
6925pub fn paint_command_button(
6926    ctx: &mut PaintCtx,
6927    theme: &DefaultTheme,
6928    rect: Rect,
6929    label: &str,
6930    icon: Option<IconGlyph>,
6931    style: CommandButtonPaint,
6932) {
6933    if rect.width() <= 0.0 || rect.height() <= 0.0 {
6934        return;
6935    }
6936
6937    let (tone_color, tone_text) = theme.semantic_tone_colors(style.tone);
6938    let (base_fill, border, label_color) = match style.fill {
6939        CommandButtonFill::Surface => {
6940            let label_color = if style.tone == SemanticTone::Neutral {
6941                theme.palette.text
6942            } else {
6943                tone_color
6944            };
6945            let border = if style.tone == SemanticTone::Neutral {
6946                theme.palette.border
6947            } else {
6948                tone_color.with_alpha(0.72)
6949            };
6950            (theme.surfaces.field, border, label_color)
6951        }
6952        CommandButtonFill::Filled => (tone_color, tone_color, tone_text),
6953    };
6954    let fill = match style.fill {
6955        CommandButtonFill::Surface if style.pressed => theme.palette.control_active,
6956        CommandButtonFill::Surface if style.hovered => theme.palette.control_hover,
6957        CommandButtonFill::Filled
6958            if style.pressed && matches!(style.tone, SemanticTone::Accent) =>
6959        {
6960            theme.palette.accent_pressed
6961        }
6962        CommandButtonFill::Filled
6963            if style.hovered && matches!(style.tone, SemanticTone::Accent) =>
6964        {
6965            theme.palette.accent_hover
6966        }
6967        _ => base_fill,
6968    };
6969    let icon_color = style
6970        .icon_tone
6971        .map(|tone| {
6972            if style.fill == CommandButtonFill::Filled && tone == style.tone {
6973                theme.semantic_tone_text_color(tone)
6974            } else if tone == SemanticTone::Neutral {
6975                theme.palette.text_muted
6976            } else {
6977                theme.semantic_tone_color(tone)
6978            }
6979        })
6980        .unwrap_or_else(|| match style.fill {
6981            CommandButtonFill::Surface => {
6982                if style.tone == SemanticTone::Neutral {
6983                    theme.palette.text_muted
6984                } else {
6985                    tone_color
6986                }
6987            }
6988            CommandButtonFill::Filled => tone_text,
6989        });
6990
6991    let radius = theme
6992        .metrics
6993        .corner_radius
6994        .min(rect.height() * 0.35)
6995        .max(0.0);
6996    ctx.fill(rounded_rect_path(rect, radius), fill);
6997    ctx.stroke(
6998        rounded_rect_path(rect, radius),
6999        border,
7000        StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7001    );
7002
7003    let icon_size = (rect.height() - 14.0).clamp(12.0, 16.0);
7004    let padding = theme
7005        .metrics
7006        .button_padding
7007        .left
7008        .max(8.0)
7009        .min(rect.width() * 0.4);
7010    let gap = theme.metrics.icon_label_gap.max(5.0);
7011    let mut text_x = rect.x() + padding;
7012    if let Some(icon) = icon {
7013        let icon_rect = Rect::new(
7014            rect.x() + padding,
7015            rect.y() + (rect.height() - icon_size) * 0.5,
7016            icon_size,
7017            icon_size,
7018        );
7019        draw_icon_glyph(ctx, icon, icon_rect, icon_color);
7020        text_x = icon_rect.max_x() + gap;
7021    }
7022
7023    let label_rect = Rect::new(
7024        text_x,
7025        rect.y(),
7026        (rect.max_x() - text_x - padding * 0.75).max(0.0),
7027        rect.height(),
7028    );
7029    if label_rect.width() <= 0.0 {
7030        return;
7031    }
7032
7033    let mut text_style = text_token_style(theme, theme.text.sm, label_color);
7034    text_style.weight = FontWeight::SEMIBOLD;
7035    let text_style = fit_command_button_label_style(ctx, label, text_style, label_rect.width());
7036    let text_style = numeric_text_style_if_numeric(label, text_style);
7037    ctx.push_clip_rect(label_rect);
7038    paint_aligned_text(
7039        ctx,
7040        label_rect,
7041        label,
7042        &text_style,
7043        text_style.line_height,
7044        0.0,
7045    );
7046    ctx.pop_clip();
7047}
7048
7049pub fn paint_disclosure_button(
7050    ctx: &mut PaintCtx,
7051    theme: &DefaultTheme,
7052    rect: Rect,
7053    label: &str,
7054    expanded: bool,
7055    paint: DisclosureButtonPaint,
7056) {
7057    paint_command_button(
7058        ctx,
7059        theme,
7060        rect,
7061        label,
7062        Some(if expanded {
7063            IconGlyph::ChevronUp
7064        } else {
7065            IconGlyph::ChevronDown
7066        }),
7067        paint.command,
7068    );
7069}
7070
7071fn fit_command_button_label_style(
7072    ctx: &PaintCtx,
7073    label: &str,
7074    mut style: TextStyle,
7075    max_width: f32,
7076) -> TextStyle {
7077    if label.is_empty() || max_width <= 0.0 || style.font_size <= 0.0 {
7078        return style;
7079    }
7080
7081    let measured_width = ctx
7082        .measure_text(label.to_string(), style.clone())
7083        .ok()
7084        .map(|measurement| measurement.width)
7085        .unwrap_or_else(|| label.chars().count() as f32 * style.font_size * 0.56);
7086    if measured_width <= max_width || measured_width <= 0.0 {
7087        return style;
7088    }
7089
7090    let min_font_size = 10.0_f32.min(style.font_size);
7091    let scale = ((max_width * 0.98) / measured_width).clamp(min_font_size / style.font_size, 1.0);
7092    style.font_size = (style.font_size * scale).max(min_font_size);
7093    style.line_height = (style.line_height * scale).max(min_font_size + 2.0);
7094    style
7095}
7096
7097#[derive(Clone, Copy, Debug, PartialEq)]
7098pub struct ActionTilePaint {
7099    pub tone: SemanticTone,
7100    pub highlighted: bool,
7101    pub hovered: bool,
7102    pub pressed: bool,
7103    pub enabled: bool,
7104    pub background: Option<Color>,
7105    pub border: Option<Color>,
7106    pub title_color: Option<Color>,
7107    pub subtitle_color: Option<Color>,
7108    pub icon_color: Option<Color>,
7109    pub leading_tone_dot: Option<SemanticTone>,
7110    pub radius: Option<f32>,
7111    pub padding_x: Option<f32>,
7112    pub leading_width: f32,
7113    pub trailing_width: f32,
7114}
7115
7116impl ActionTilePaint {
7117    pub const fn neutral() -> Self {
7118        Self {
7119            tone: SemanticTone::Neutral,
7120            highlighted: false,
7121            hovered: false,
7122            pressed: false,
7123            enabled: true,
7124            background: None,
7125            border: None,
7126            title_color: None,
7127            subtitle_color: None,
7128            icon_color: None,
7129            leading_tone_dot: None,
7130            radius: None,
7131            padding_x: None,
7132            leading_width: 0.0,
7133            trailing_width: 0.0,
7134        }
7135    }
7136
7137    pub const fn tonal(tone: SemanticTone) -> Self {
7138        Self {
7139            tone,
7140            highlighted: true,
7141            hovered: false,
7142            pressed: false,
7143            enabled: true,
7144            background: None,
7145            border: None,
7146            title_color: None,
7147            subtitle_color: None,
7148            icon_color: None,
7149            leading_tone_dot: None,
7150            radius: None,
7151            padding_x: None,
7152            leading_width: 0.0,
7153            trailing_width: 0.0,
7154        }
7155    }
7156
7157    pub const fn highlighted(mut self, highlighted: bool) -> Self {
7158        self.highlighted = highlighted;
7159        self
7160    }
7161
7162    pub const fn hovered(mut self, hovered: bool) -> Self {
7163        self.hovered = hovered;
7164        self
7165    }
7166
7167    pub const fn pressed(mut self, pressed: bool) -> Self {
7168        self.pressed = pressed;
7169        self
7170    }
7171
7172    pub const fn enabled(mut self, enabled: bool) -> Self {
7173        self.enabled = enabled;
7174        self
7175    }
7176
7177    pub const fn background(mut self, background: Color) -> Self {
7178        self.background = Some(background);
7179        self
7180    }
7181
7182    pub const fn border(mut self, border: Color) -> Self {
7183        self.border = Some(border);
7184        self
7185    }
7186
7187    pub const fn title_color(mut self, title_color: Color) -> Self {
7188        self.title_color = Some(title_color);
7189        self
7190    }
7191
7192    pub const fn subtitle_color(mut self, subtitle_color: Color) -> Self {
7193        self.subtitle_color = Some(subtitle_color);
7194        self
7195    }
7196
7197    pub const fn icon_color(mut self, icon_color: Color) -> Self {
7198        self.icon_color = Some(icon_color);
7199        self
7200    }
7201
7202    pub const fn leading_tone_dot(mut self, tone: SemanticTone) -> Self {
7203        self.leading_tone_dot = Some(tone);
7204        self
7205    }
7206
7207    pub const fn radius(mut self, radius: f32) -> Self {
7208        self.radius = Some(radius);
7209        self
7210    }
7211
7212    pub const fn padding_x(mut self, padding_x: f32) -> Self {
7213        self.padding_x = Some(padding_x);
7214        self
7215    }
7216
7217    pub const fn leading_width(mut self, leading_width: f32) -> Self {
7218        self.leading_width = leading_width;
7219        self
7220    }
7221
7222    pub const fn trailing_width(mut self, trailing_width: f32) -> Self {
7223        self.trailing_width = trailing_width;
7224        self
7225    }
7226}
7227
7228impl Default for ActionTilePaint {
7229    fn default() -> Self {
7230        Self::neutral()
7231    }
7232}
7233
7234#[derive(Clone, Copy, Debug, PartialEq)]
7235pub struct CalloutPaint {
7236    pub tone: SemanticTone,
7237    pub fill: Option<Color>,
7238    pub border: Option<Color>,
7239    pub rail_color: Option<Color>,
7240    pub icon_color: Option<Color>,
7241    pub title_color: Option<Color>,
7242    pub body_color: Option<Color>,
7243    pub radius: Option<f32>,
7244    pub padding: Insets,
7245    pub icon_size: f32,
7246    pub icon_gap: f32,
7247    pub rail_width: f32,
7248    pub reserved_bottom: f32,
7249}
7250
7251impl CalloutPaint {
7252    pub const fn new(tone: SemanticTone) -> Self {
7253        Self {
7254            tone,
7255            fill: None,
7256            border: None,
7257            rail_color: None,
7258            icon_color: None,
7259            title_color: None,
7260            body_color: None,
7261            radius: None,
7262            padding: Insets {
7263                left: 12.0,
7264                top: 10.0,
7265                right: 12.0,
7266                bottom: 10.0,
7267            },
7268            icon_size: 15.0,
7269            icon_gap: 9.0,
7270            rail_width: 2.0,
7271            reserved_bottom: 0.0,
7272        }
7273    }
7274
7275    pub const fn fill(mut self, fill: Color) -> Self {
7276        self.fill = Some(fill);
7277        self
7278    }
7279
7280    pub const fn border(mut self, border: Color) -> Self {
7281        self.border = Some(border);
7282        self
7283    }
7284
7285    pub const fn rail_color(mut self, rail_color: Color) -> Self {
7286        self.rail_color = Some(rail_color);
7287        self
7288    }
7289
7290    pub const fn icon_color(mut self, icon_color: Color) -> Self {
7291        self.icon_color = Some(icon_color);
7292        self
7293    }
7294
7295    pub const fn title_color(mut self, title_color: Color) -> Self {
7296        self.title_color = Some(title_color);
7297        self
7298    }
7299
7300    pub const fn body_color(mut self, body_color: Color) -> Self {
7301        self.body_color = Some(body_color);
7302        self
7303    }
7304
7305    pub const fn radius(mut self, radius: f32) -> Self {
7306        self.radius = Some(radius);
7307        self
7308    }
7309
7310    pub const fn padding(mut self, padding: Insets) -> Self {
7311        self.padding = padding;
7312        self
7313    }
7314
7315    pub const fn icon_size(mut self, icon_size: f32) -> Self {
7316        self.icon_size = icon_size;
7317        self
7318    }
7319
7320    pub const fn icon_gap(mut self, icon_gap: f32) -> Self {
7321        self.icon_gap = icon_gap;
7322        self
7323    }
7324
7325    pub const fn rail_width(mut self, rail_width: f32) -> Self {
7326        self.rail_width = rail_width;
7327        self
7328    }
7329
7330    pub const fn reserved_bottom(mut self, reserved_bottom: f32) -> Self {
7331        self.reserved_bottom = reserved_bottom;
7332        self
7333    }
7334}
7335
7336impl Default for CalloutPaint {
7337    fn default() -> Self {
7338        Self::new(SemanticTone::Info)
7339    }
7340}
7341
7342pub fn paint_callout(
7343    ctx: &mut PaintCtx,
7344    theme: &DefaultTheme,
7345    rect: Rect,
7346    icon: Option<IconGlyph>,
7347    title: Option<&str>,
7348    body: &str,
7349    style: CalloutPaint,
7350) {
7351    if rect.width() <= 0.0 || rect.height() <= 0.0 {
7352        return;
7353    }
7354
7355    let palette = theme.palette;
7356    let (tone_color, _) = theme.semantic_tone_colors(style.tone);
7357    // Mesh callout: quiet soft wash, hairline border, a 2px status rail, and
7358    // the status-hued ink (not the on-solid content color) for the icon.
7359    let (tone_soft, tone_ink) = theme.semantic_tone_soft_colors(style.tone);
7360    let fill = style.fill.unwrap_or(tone_soft);
7361    let border = style.border.unwrap_or(palette.border);
7362    let rail = style.rail_color.unwrap_or(tone_color);
7363    let radius = style.radius.unwrap_or(theme.radius.md).max(0.0);
7364
7365    ctx.fill(rounded_rect_path(rect, radius), fill);
7366    ctx.stroke(
7367        rounded_rect_path(rect, radius),
7368        border,
7369        StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7370    );
7371
7372    let rail_width = style.rail_width.max(0.0).min(rect.width());
7373    if rail_width > 0.0 {
7374        let rail_rect = Rect::new(rect.x(), rect.y(), rail_width, rect.height());
7375        ctx.fill(rounded_rect_path(rail_rect, rail_width * 0.5), rail);
7376    }
7377
7378    let padding = style.padding;
7379    let content_bottom = (rect.max_y() - padding.bottom.max(0.0) - style.reserved_bottom.max(0.0))
7380        .max(rect.y() + padding.top.max(0.0));
7381    let content = Rect::new(
7382        rect.x() + padding.left.max(0.0),
7383        rect.y() + padding.top.max(0.0),
7384        (rect.width() - padding.left.max(0.0) - padding.right.max(0.0)).max(0.0),
7385        (content_bottom - rect.y() - padding.top.max(0.0)).max(0.0),
7386    );
7387    if content.width() <= 0.0 || content.height() <= 0.0 {
7388        return;
7389    }
7390
7391    let icon_size = style
7392        .icon_size
7393        .max(0.0)
7394        .min(content.height())
7395        .min(content.width());
7396    let mut text_x = content.x();
7397    if let Some(icon) = icon.filter(|_| icon_size > 0.0) {
7398        let icon_rect = Rect::new(
7399            content.x(),
7400            content.y() + 2.0_f32.min((content.height() - icon_size).max(0.0)),
7401            icon_size,
7402            icon_size,
7403        );
7404        draw_icon_glyph(ctx, icon, icon_rect, style.icon_color.unwrap_or(tone_ink));
7405        text_x = icon_rect.max_x() + style.icon_gap.max(0.0);
7406    }
7407
7408    let text_rect = Rect::new(
7409        text_x,
7410        content.y(),
7411        (content.max_x() - text_x).max(0.0),
7412        content.height(),
7413    );
7414    if text_rect.width() <= 0.0 || text_rect.height() <= 0.0 {
7415        return;
7416    }
7417
7418    let title_line = if title.is_some() {
7419        theme.text.sm.line_height
7420    } else {
7421        0.0
7422    };
7423    if let Some(title) = title {
7424        let mut title_style = text_token_style(
7425            theme,
7426            theme.text.sm,
7427            style.title_color.unwrap_or(palette.text),
7428        );
7429        title_style.weight = FontWeight::SEMIBOLD;
7430        let title_rect = Rect::new(text_rect.x(), text_rect.y(), text_rect.width(), title_line);
7431        ctx.push_clip_rect(title_rect);
7432        paint_single_line_aligned_text(
7433            ctx,
7434            title_rect,
7435            title,
7436            &title_style,
7437            title_style.line_height,
7438            0.0,
7439        );
7440        ctx.pop_clip();
7441    }
7442
7443    if body.trim().is_empty() {
7444        return;
7445    }
7446    let body_y = text_rect.y() + title_line + if title.is_some() { 4.0 } else { 0.0 };
7447    let body_rect = Rect::new(
7448        text_rect.x(),
7449        body_y,
7450        text_rect.width(),
7451        (text_rect.max_y() - body_y).max(0.0),
7452    );
7453    if body_rect.width() <= 0.0 || body_rect.height() <= 0.0 {
7454        return;
7455    }
7456
7457    let color = style.body_color.unwrap_or(palette.text_muted);
7458    let mut layout_style = text_token_style(theme, theme.text.sm, color);
7459    layout_style.color = Color::WHITE;
7460    let mut document = TextDocument::from_plain_text(body.to_string(), layout_style);
7461    for paragraph in &mut document.paragraphs {
7462        paragraph.style.align = TextAlign::Start;
7463        paragraph.style.wrap = TextWrap::Word;
7464    }
7465
7466    ctx.push_clip_rect(body_rect);
7467    if let Ok(layout) = ctx.layout_text_document(TextLayoutRequest::new(document).with_box_size(
7468        Size::new(body_rect.width().max(1.0), body_rect.height().max(1.0)),
7469    )) {
7470        ctx.draw_text_layout_with_color(body_rect.origin, &layout, color);
7471    } else {
7472        let fallback_style = text_token_style(theme, theme.text.sm, color);
7473        ctx.draw_text(body_rect, body.to_string(), fallback_style);
7474    }
7475    ctx.pop_clip();
7476}
7477
7478pub fn paint_action_tile(
7479    ctx: &mut PaintCtx,
7480    theme: &DefaultTheme,
7481    rect: Rect,
7482    title: &str,
7483    subtitle: Option<&str>,
7484    icon: Option<IconGlyph>,
7485    style: ActionTilePaint,
7486) {
7487    if rect.width() <= 0.0 || rect.height() <= 0.0 {
7488        return;
7489    }
7490
7491    let palette = theme.palette;
7492    let tone_color = theme.semantic_tone_color(style.tone);
7493    let effective_tone = if style.tone == SemanticTone::Neutral {
7494        palette.text_muted
7495    } else {
7496        tone_color
7497    };
7498    let base_background = if !style.enabled {
7499        mix_color(palette.control, palette.surface, 0.68).with_alpha(0.82)
7500    } else if style.pressed {
7501        palette.control_active
7502    } else if style.hovered {
7503        palette.control_hover
7504    } else {
7505        palette.control
7506    };
7507    let background = style.background.unwrap_or(base_background);
7508    let base_border = if !style.enabled {
7509        palette.border.with_alpha(0.55)
7510    } else if style.highlighted {
7511        effective_tone.with_alpha(0.84)
7512    } else if style.hovered {
7513        palette.border_hover
7514    } else {
7515        palette.border
7516    };
7517    let border = style.border.unwrap_or(base_border);
7518    let radius = theme
7519        .metrics
7520        .corner_radius
7521        .min(rect.height() * 0.28)
7522        .max(0.0);
7523    let radius = style.radius.unwrap_or(radius).max(0.0);
7524    ctx.fill(rounded_rect_path(rect, radius), background);
7525    ctx.stroke(
7526        rounded_rect_path(rect, radius),
7527        border,
7528        StrokeStyle::new(theme.metrics.border_width.max(1.0)),
7529    );
7530
7531    let padding_x = style
7532        .padding_x
7533        .unwrap_or_else(|| theme.metrics.button_padding.left.max(10.0))
7534        .max(0.0)
7535        .min(rect.width() * 0.45);
7536    let compact = rect.height() <= 46.0 || subtitle.is_none();
7537    let base_icon_side: f32 = if compact { 14.0 } else { 17.0 };
7538    let icon_side = base_icon_side
7539        .min((rect.height() - 14.0).max(10.0))
7540        .max(0.0);
7541    let icon_y = if compact {
7542        rect.y() + (rect.height() - icon_side) * 0.5
7543    } else {
7544        rect.y() + 12.0
7545    };
7546    let mut text_x = rect.x() + padding_x;
7547    if let Some(icon) = icon {
7548        let icon_rect = Rect::new(rect.x() + padding_x, icon_y, icon_side, icon_side);
7549        let icon_color = style.icon_color.unwrap_or_else(|| {
7550            if style.enabled {
7551                if style.highlighted || style.hovered {
7552                    effective_tone
7553                } else {
7554                    palette.text_muted
7555                }
7556            } else {
7557                palette.text.with_alpha(0.34)
7558            }
7559        });
7560        draw_icon_glyph(ctx, icon, icon_rect, icon_color);
7561        text_x = icon_rect.max_x() + theme.metrics.icon_label_gap.max(7.0);
7562    } else if let Some(dot_tone) = style.leading_tone_dot {
7563        let dot_side = 8.0_f32.min((rect.height() - 12.0).max(4.0)).max(4.0);
7564        let leading_width = style
7565            .leading_width
7566            .max(dot_side + theme.metrics.icon_label_gap.max(7.0));
7567        let dot_rect = Rect::new(
7568            rect.x() + padding_x,
7569            if compact {
7570                rect.y() + (rect.height() - dot_side) * 0.5
7571            } else {
7572                rect.y() + 15.0_f32.min((rect.height() - dot_side).max(0.0))
7573            },
7574            dot_side,
7575            dot_side,
7576        );
7577        ctx.fill(
7578            rounded_rect_path(dot_rect, dot_side * 0.5),
7579            theme.semantic_tone_color(dot_tone),
7580        );
7581        text_x += leading_width;
7582    } else if style.leading_width > 0.0 {
7583        text_x += style.leading_width;
7584    }
7585
7586    let text_width = (rect.max_x() - text_x - padding_x - style.trailing_width.max(0.0)).max(0.0);
7587    if text_width <= 0.0 {
7588        return;
7589    }
7590
7591    let title_color = style.title_color.unwrap_or_else(|| {
7592        if !style.enabled {
7593            palette.text.with_alpha(0.42)
7594        } else if style.highlighted {
7595            palette.text
7596        } else {
7597            palette.text_muted
7598        }
7599    });
7600    let subtitle_color = style.subtitle_color.unwrap_or_else(|| {
7601        if !style.enabled {
7602            palette.text.with_alpha(0.32)
7603        } else {
7604            palette.placeholder
7605        }
7606    });
7607    let mut title_style = text_token_style(theme, theme.text.sm, title_color);
7608    title_style.weight = FontWeight::SEMIBOLD;
7609    let title_style = numeric_text_style_if_numeric(title, title_style);
7610    let subtitle_style = text_token_style(theme, theme.text.xs, subtitle_color);
7611
7612    if compact {
7613        let title_rect = Rect::new(text_x, rect.y(), text_width, rect.height());
7614        ctx.push_clip_rect(title_rect);
7615        paint_aligned_text(
7616            ctx,
7617            title_rect,
7618            title,
7619            &title_style,
7620            title_style.line_height,
7621            0.0,
7622        );
7623        ctx.pop_clip();
7624        return;
7625    }
7626
7627    let title_rect = Rect::new(text_x, rect.y() + 8.0, text_width, title_style.line_height);
7628    ctx.push_clip_rect(title_rect);
7629    paint_single_line_aligned_text(
7630        ctx,
7631        title_rect,
7632        title,
7633        &title_style,
7634        title_style.line_height,
7635        0.0,
7636    );
7637    ctx.pop_clip();
7638
7639    if let Some(subtitle) = subtitle {
7640        let subtitle_rect = Rect::new(
7641            text_x,
7642            title_rect.max_y() + theme.metrics.action_card_text_gap.min(3.0),
7643            text_width,
7644            subtitle_style.line_height,
7645        );
7646        ctx.push_clip_rect(subtitle_rect);
7647        paint_single_line_aligned_text(
7648            ctx,
7649            subtitle_rect,
7650            subtitle,
7651            &subtitle_style,
7652            subtitle_style.line_height,
7653            0.0,
7654        );
7655        ctx.pop_clip();
7656    }
7657}
7658
7659#[derive(Clone, Copy, Debug, PartialEq)]
7660pub struct CodePanelPaint {
7661    pub fill: Option<Color>,
7662    pub border: Option<Color>,
7663    pub header_fill: Option<Color>,
7664    pub label_color: Option<Color>,
7665    pub radius: Option<f32>,
7666    pub header_height: f32,
7667    pub content_padding: Insets,
7668    pub label_inset_x: f32,
7669}
7670
7671impl CodePanelPaint {
7672    pub const fn new() -> Self {
7673        Self {
7674            fill: None,
7675            border: None,
7676            header_fill: None,
7677            label_color: None,
7678            radius: None,
7679            header_height: 24.0,
7680            content_padding: Insets {
7681                left: 8.0,
7682                top: 6.0,
7683                right: 8.0,
7684                bottom: 4.0,
7685            },
7686            label_inset_x: 10.0,
7687        }
7688    }
7689
7690    pub const fn fill(mut self, fill: Color) -> Self {
7691        self.fill = Some(fill);
7692        self
7693    }
7694
7695    pub const fn border(mut self, border: Color) -> Self {
7696        self.border = Some(border);
7697        self
7698    }
7699
7700    pub const fn header_fill(mut self, header_fill: Color) -> Self {
7701        self.header_fill = Some(header_fill);
7702        self
7703    }
7704
7705    pub const fn label_color(mut self, label_color: Color) -> Self {
7706        self.label_color = Some(label_color);
7707        self
7708    }
7709
7710    pub const fn radius(mut self, radius: f32) -> Self {
7711        self.radius = Some(radius);
7712        self
7713    }
7714
7715    pub const fn header_height(mut self, header_height: f32) -> Self {
7716        self.header_height = header_height;
7717        self
7718    }
7719
7720    pub const fn content_padding(mut self, content_padding: Insets) -> Self {
7721        self.content_padding = content_padding;
7722        self
7723    }
7724
7725    pub const fn label_inset_x(mut self, label_inset_x: f32) -> Self {
7726        self.label_inset_x = label_inset_x;
7727        self
7728    }
7729}
7730
7731impl Default for CodePanelPaint {
7732    fn default() -> Self {
7733        Self::new()
7734    }
7735}
7736
7737#[derive(Clone, Copy, Debug, PartialEq)]
7738pub struct CodeTextSpan<'a> {
7739    pub text: &'a str,
7740    pub color: Option<Color>,
7741}
7742
7743impl<'a> CodeTextSpan<'a> {
7744    pub const fn new(text: &'a str) -> Self {
7745        Self { text, color: None }
7746    }
7747
7748    pub const fn color(mut self, color: Color) -> Self {
7749        self.color = Some(color);
7750        self
7751    }
7752}
7753
7754#[derive(Clone, Copy, Debug, PartialEq)]
7755pub struct CodeTextLine<'a> {
7756    pub spans: &'a [CodeTextSpan<'a>],
7757    pub background: Option<Color>,
7758    pub fallback_color: Option<Color>,
7759}
7760
7761impl<'a> CodeTextLine<'a> {
7762    pub const fn new(spans: &'a [CodeTextSpan<'a>]) -> Self {
7763        Self {
7764            spans,
7765            background: None,
7766            fallback_color: None,
7767        }
7768    }
7769
7770    pub const fn background(mut self, background: Color) -> Self {
7771        self.background = Some(background);
7772        self
7773    }
7774
7775    pub const fn fallback_color(mut self, color: Color) -> Self {
7776        self.fallback_color = Some(color);
7777        self
7778    }
7779}
7780
7781#[derive(Clone, Copy, Debug, PartialEq)]
7782pub struct CodeTextPaint {
7783    pub color: Option<Color>,
7784    pub font_size: f32,
7785    pub line_height: f32,
7786    pub x_padding: f32,
7787    pub weight: FontWeight,
7788}
7789
7790impl CodeTextPaint {
7791    pub const fn new() -> Self {
7792        Self {
7793            color: None,
7794            font_size: 12.0,
7795            line_height: 17.0,
7796            x_padding: 2.0,
7797            weight: FontWeight::NORMAL,
7798        }
7799    }
7800
7801    pub const fn color(mut self, color: Color) -> Self {
7802        self.color = Some(color);
7803        self
7804    }
7805
7806    pub const fn font_size(mut self, font_size: f32) -> Self {
7807        self.font_size = font_size;
7808        self
7809    }
7810
7811    pub const fn line_height(mut self, line_height: f32) -> Self {
7812        self.line_height = line_height;
7813        self
7814    }
7815
7816    pub const fn x_padding(mut self, x_padding: f32) -> Self {
7817        self.x_padding = x_padding;
7818        self
7819    }
7820
7821    pub const fn weight(mut self, weight: FontWeight) -> Self {
7822        self.weight = weight;
7823        self
7824    }
7825}
7826
7827impl Default for CodeTextPaint {
7828    fn default() -> Self {
7829        Self::new()
7830    }
7831}
7832
7833pub fn paint_code_lines(
7834    ctx: &mut PaintCtx,
7835    theme: &DefaultTheme,
7836    rect: Rect,
7837    lines: &[CodeTextLine<'_>],
7838    style: CodeTextPaint,
7839) {
7840    if rect.width() <= 0.0 || rect.height() <= 0.0 || lines.is_empty() {
7841        return;
7842    }
7843
7844    let mut base_style = TextStyle {
7845        font_size: style.font_size.max(1.0),
7846        line_height: style.line_height.max(1.0),
7847        color: style.color.unwrap_or(theme.palette.text),
7848        ..theme.mono_text_style(theme.palette.text)
7849    };
7850    base_style.weight = style.weight;
7851
7852    let line_height = base_style.line_height;
7853    let mut y = rect.y();
7854    ctx.push_clip_rect(rect);
7855    for line in lines {
7856        if y + line_height > rect.max_y() {
7857            break;
7858        }
7859        if let Some(background) = line.background {
7860            ctx.fill_rect(
7861                Rect::new(rect.x(), y, rect.width(), line_height),
7862                background,
7863            );
7864        }
7865
7866        let mut x = rect.x() + style.x_padding.max(0.0);
7867        for span in line.spans {
7868            if span.text.is_empty() || x > rect.max_x() {
7869                continue;
7870            }
7871            let mut span_style = base_style.clone();
7872            span_style.color = span
7873                .color
7874                .or(line.fallback_color)
7875                .unwrap_or(base_style.color);
7876            let width = ctx
7877                .measure_text(span.text.to_string(), span_style.clone())
7878                .ok()
7879                .map(|measurement| measurement.width)
7880                .unwrap_or(0.0);
7881            ctx.draw_text(
7882                Rect::new(x, y, (rect.max_x() - x).max(0.0), line_height),
7883                span.text,
7884                span_style,
7885            );
7886            x += width;
7887        }
7888        y += line_height;
7889    }
7890    ctx.pop_clip();
7891}
7892
7893pub fn paint_code_panel(
7894    ctx: &mut PaintCtx,
7895    theme: &DefaultTheme,
7896    rect: Rect,
7897    label: &str,
7898    style: CodePanelPaint,
7899) -> Rect {
7900    if rect.width() <= 0.0 || rect.height() <= 0.0 {
7901        return Rect::ZERO;
7902    }
7903
7904    let fill = style.fill.unwrap_or(theme.surfaces.field);
7905    let border = style.border.unwrap_or(theme.surfaces.border);
7906    let header_fill = style.header_fill.unwrap_or(theme.surfaces.titlebar);
7907    let label_color = style.label_color.unwrap_or(theme.surfaces.text_faint);
7908    let radius = style
7909        .radius
7910        .unwrap_or(theme.radius.xl)
7911        .min(rect.width().min(rect.height()) * 0.5)
7912        .max(0.0);
7913    let border_width = physical_pixels(ctx, theme.metrics.border_width.max(1.0));
7914
7915    let panel_shape = rounded_rect_path(rect, radius);
7916    ctx.fill(panel_shape.clone(), fill);
7917
7918    let header_height = style.header_height.clamp(0.0, rect.height());
7919    if header_height > 0.0 {
7920        let header_rect = Rect::new(rect.x(), rect.y(), rect.width(), header_height);
7921        let header_radius = radius.min(header_height * 0.5);
7922        ctx.fill(rounded_rect_path(header_rect, header_radius), header_fill);
7923        if header_height > header_radius {
7924            ctx.fill_rect(
7925                Rect::new(
7926                    header_rect.x(),
7927                    (header_rect.max_y() - header_radius).max(header_rect.y()),
7928                    header_rect.width(),
7929                    header_radius,
7930                ),
7931                header_fill,
7932            );
7933        }
7934
7935        let mut label_style = text_token_style(theme, theme.text.xs, label_color);
7936        label_style.weight = FontWeight::SEMIBOLD;
7937        let label_x = rect.x() + style.label_inset_x.max(0.0);
7938        let label_rect = Rect::new(
7939            label_x,
7940            rect.y() + ((header_height - label_style.line_height) * 0.5).max(0.0),
7941            (rect.max_x() - label_x - style.label_inset_x.max(0.0)).max(0.0),
7942            label_style.line_height,
7943        );
7944        if label_rect.width() > 0.0 {
7945            ctx.push_clip_rect(label_rect);
7946            paint_single_line_aligned_text(
7947                ctx,
7948                label_rect,
7949                label,
7950                &label_style,
7951                label_style.line_height,
7952                0.0,
7953            );
7954            ctx.pop_clip();
7955        }
7956    }
7957
7958    ctx.stroke(panel_shape, border, StrokeStyle::new(border_width));
7959
7960    Rect::new(
7961        rect.x() + style.content_padding.left,
7962        rect.y() + header_height + style.content_padding.top,
7963        (rect.width() - style.content_padding.left - style.content_padding.right).max(0.0),
7964        (rect.height() - header_height - style.content_padding.top - style.content_padding.bottom)
7965            .max(0.0),
7966    )
7967}
7968
7969#[derive(Clone, Copy, Debug, PartialEq)]
7970pub struct SectionPanelPaint {
7971    pub fill: Option<Color>,
7972    pub border: Option<Color>,
7973    pub title_color: Option<Color>,
7974    pub radius: Option<f32>,
7975    pub header_height: f32,
7976    pub content_padding: Insets,
7977    pub title_inset_x: f32,
7978    pub trailing_width: f32,
7979    pub title_token: Option<ThemeTextToken>,
7980    pub title_weight: FontWeight,
7981}
7982
7983#[derive(Clone, Copy, Debug, PartialEq)]
7984pub struct SectionPanelGeometry {
7985    pub panel_rect: Rect,
7986    pub header_rect: Rect,
7987    pub title_rect: Rect,
7988    pub content_rect: Rect,
7989}
7990
7991impl SectionPanelPaint {
7992    pub const fn new() -> Self {
7993        Self {
7994            fill: None,
7995            border: None,
7996            title_color: None,
7997            radius: None,
7998            header_height: 34.0,
7999            content_padding: Insets {
8000                left: 12.0,
8001                top: 0.0,
8002                right: 12.0,
8003                bottom: 8.0,
8004            },
8005            title_inset_x: 12.0,
8006            trailing_width: 0.0,
8007            title_token: None,
8008            title_weight: FontWeight::SEMIBOLD,
8009        }
8010    }
8011
8012    pub const fn fill(mut self, fill: Color) -> Self {
8013        self.fill = Some(fill);
8014        self
8015    }
8016
8017    pub const fn border(mut self, border: Color) -> Self {
8018        self.border = Some(border);
8019        self
8020    }
8021
8022    pub const fn title_color(mut self, title_color: Color) -> Self {
8023        self.title_color = Some(title_color);
8024        self
8025    }
8026
8027    pub const fn radius(mut self, radius: f32) -> Self {
8028        self.radius = Some(radius);
8029        self
8030    }
8031
8032    pub const fn header_height(mut self, header_height: f32) -> Self {
8033        self.header_height = header_height;
8034        self
8035    }
8036
8037    pub const fn content_padding(mut self, content_padding: Insets) -> Self {
8038        self.content_padding = content_padding;
8039        self
8040    }
8041
8042    pub const fn title_inset_x(mut self, title_inset_x: f32) -> Self {
8043        self.title_inset_x = title_inset_x;
8044        self
8045    }
8046
8047    pub const fn trailing_width(mut self, trailing_width: f32) -> Self {
8048        self.trailing_width = trailing_width;
8049        self
8050    }
8051
8052    pub const fn title_token(mut self, title_token: ThemeTextToken) -> Self {
8053        self.title_token = Some(title_token);
8054        self
8055    }
8056
8057    pub const fn title_weight(mut self, title_weight: FontWeight) -> Self {
8058        self.title_weight = title_weight;
8059        self
8060    }
8061}
8062
8063impl Default for SectionPanelPaint {
8064    fn default() -> Self {
8065        Self::new()
8066    }
8067}
8068
8069pub fn paint_section_panel(
8070    ctx: &mut PaintCtx,
8071    theme: &DefaultTheme,
8072    rect: Rect,
8073    title: &str,
8074    style: SectionPanelPaint,
8075) -> SectionPanelGeometry {
8076    if rect.width() <= 0.0 || rect.height() <= 0.0 {
8077        return SectionPanelGeometry {
8078            panel_rect: Rect::ZERO,
8079            header_rect: Rect::ZERO,
8080            title_rect: Rect::ZERO,
8081            content_rect: Rect::ZERO,
8082        };
8083    }
8084
8085    let fill = style.fill.unwrap_or(theme.surfaces.panel);
8086    let border = style.border.unwrap_or(theme.surfaces.border);
8087    let title_color = style.title_color.unwrap_or(theme.surfaces.text);
8088    let radius = style
8089        .radius
8090        .unwrap_or(theme.radius.lg)
8091        .min(rect.width().min(rect.height()) * 0.5)
8092        .max(0.0);
8093    let header_height = style.header_height.clamp(0.0, rect.height());
8094    let shape = rounded_rect_path(rect, radius);
8095    ctx.fill(shape.clone(), fill);
8096    ctx.stroke(
8097        shape,
8098        border,
8099        StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
8100    );
8101
8102    let header_rect = Rect::new(rect.x(), rect.y(), rect.width(), header_height);
8103    let mut title_style = text_token_style(
8104        theme,
8105        style.title_token.unwrap_or(theme.text.sm),
8106        title_color,
8107    );
8108    title_style.weight = style.title_weight;
8109    let title_x = rect.x() + style.title_inset_x.max(0.0);
8110    let title_rect = Rect::new(
8111        title_x,
8112        rect.y() + ((header_height - title_style.line_height) * 0.5).max(0.0),
8113        (rect.max_x() - title_x - style.title_inset_x.max(0.0) - style.trailing_width.max(0.0))
8114            .max(0.0),
8115        title_style.line_height,
8116    );
8117    if title_rect.width() > 0.0 && !title.is_empty() {
8118        ctx.push_clip_rect(title_rect);
8119        paint_single_line_aligned_text(
8120            ctx,
8121            title_rect,
8122            title,
8123            &title_style,
8124            title_style.line_height,
8125            0.0,
8126        );
8127        ctx.pop_clip();
8128    }
8129
8130    let content_rect = Rect::new(
8131        rect.x() + style.content_padding.left,
8132        rect.y() + header_height + style.content_padding.top,
8133        (rect.width() - style.content_padding.left - style.content_padding.right).max(0.0),
8134        (rect.height() - header_height - style.content_padding.top - style.content_padding.bottom)
8135            .max(0.0),
8136    );
8137
8138    SectionPanelGeometry {
8139        panel_rect: rect,
8140        header_rect,
8141        title_rect,
8142        content_rect,
8143    }
8144}
8145
8146impl Widget for StatusBadge {
8147    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8148        let theme = self.resolved_theme();
8149        let (height, icon_size, gap, padding) = self.metrics(&theme);
8150        let label = self.label();
8151        let tone = self.resolved_tone();
8152        let text = measure_text(ctx, &label, &self.text_style(&theme, &label, tone));
8153        let icon_w = self.icon.map(|_| icon_size + gap).unwrap_or(0.0);
8154        let natural_w = text.width.ceil() + icon_w + padding * 2.0;
8155        constraints.clamp(Size::new(
8156            self.min_width.unwrap_or(0.0).max(natural_w),
8157            height,
8158        ))
8159    }
8160
8161    fn paint(&self, ctx: &mut PaintCtx) {
8162        let theme = self.resolved_theme();
8163        let label = self.label();
8164        let tone = self.resolved_tone();
8165        paint_status_badge(ctx, ctx.bounds(), &theme, &label, self.icon, tone);
8166    }
8167
8168    fn semantics(&self, ctx: &mut SemanticsCtx) {
8169        let label = self.label();
8170        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8171        node.name = Some(label.clone());
8172        node.value = Some(SemanticsValue::Text(label));
8173        ctx.push(node);
8174    }
8175}
8176
8177#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8178pub struct CoverageDotsConfig {
8179    pub current: usize,
8180    pub target: usize,
8181    pub tone: SemanticTone,
8182    pub max_dots: usize,
8183    pub show_label: bool,
8184}
8185
8186impl CoverageDotsConfig {
8187    pub fn new(current: usize, target: usize) -> Self {
8188        Self {
8189            current,
8190            target,
8191            tone: SemanticTone::Neutral,
8192            max_dots: 4,
8193            show_label: true,
8194        }
8195    }
8196
8197    fn normalized_target(self) -> usize {
8198        self.target.max(self.current)
8199    }
8200
8201    fn normalized_max_dots(self) -> usize {
8202        self.max_dots.max(1)
8203    }
8204
8205    fn label(self) -> String {
8206        format!("{}/{}", self.current, self.normalized_target())
8207    }
8208}
8209
8210pub fn paint_coverage_dots(
8211    ctx: &mut PaintCtx,
8212    theme: &DefaultTheme,
8213    rect: Rect,
8214    current: usize,
8215    target: usize,
8216    tone: SemanticTone,
8217) {
8218    let mut config = CoverageDotsConfig::new(current, target);
8219    config.tone = tone;
8220    paint_coverage_dots_with_config(ctx, theme, rect, config);
8221}
8222
8223pub fn paint_coverage_dots_with_config(
8224    ctx: &mut PaintCtx,
8225    theme: &DefaultTheme,
8226    rect: Rect,
8227    config: CoverageDotsConfig,
8228) {
8229    let target = config.normalized_target();
8230    if target == 0 || rect.width() <= 0.0 || rect.height() <= 0.0 {
8231        return;
8232    }
8233
8234    let (dot, gap, label_gap) = coverage_dot_metrics(theme);
8235    let shown = target.min(config.normalized_max_dots());
8236    let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
8237    let label = config.label();
8238    let label_width = if config.show_label {
8239        (label.len() as f32 * theme.text.xs.size * 0.56).min(34.0)
8240    } else {
8241        0.0
8242    };
8243    let total_width = dots_width
8244        + if config.show_label {
8245            label_gap + label_width
8246        } else {
8247            0.0
8248        };
8249    let mut x = rect.x() + ((rect.width() - total_width) * 0.5).max(0.0);
8250    let y = rect.y() + (rect.height() - dot) * 0.5;
8251    let (tone_color, _) = theme.semantic_tone_colors(config.tone);
8252    for index in 0..shown {
8253        let dot_rect = Rect::new(x, y, dot, dot);
8254        if index < config.current.min(shown) {
8255            ctx.fill(rounded_rect_path(dot_rect, dot * 0.5), tone_color);
8256        } else {
8257            ctx.stroke(
8258                rounded_rect_path(dot_rect, dot * 0.5),
8259                theme.palette.border,
8260                StrokeStyle::new(theme.metrics.border_width.max(1.0)),
8261            );
8262        }
8263        x += dot + gap;
8264    }
8265
8266    if config.show_label {
8267        let label_rect = Rect::new(
8268            x + (label_gap - gap).max(0.0),
8269            rect.y(),
8270            (rect.max_x() - x).max(0.0),
8271            rect.height(),
8272        );
8273        let text_style = numeric_text_style(text_token_style(
8274            theme,
8275            theme.text.xs,
8276            theme.palette.text_muted,
8277        ));
8278        ctx.push_clip_rect(label_rect);
8279        paint_aligned_text(
8280            ctx,
8281            label_rect,
8282            &label,
8283            &text_style,
8284            text_style.line_height,
8285            0.0,
8286        );
8287        ctx.pop_clip();
8288    }
8289}
8290
8291fn coverage_dot_metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
8292    let dot = (theme.text.xs.size * 0.42).clamp(4.0, 6.0);
8293    let gap = (dot * 0.65).clamp(2.0, 4.0);
8294    let label_gap = (theme.metrics.icon_label_gap * 0.7).max(4.0);
8295    (dot, gap, label_gap)
8296}
8297
8298pub struct CoverageDots {
8299    theme: Box<DefaultTheme>,
8300    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8301    name: String,
8302    config: CoverageDotsConfig,
8303    min_width: Option<f32>,
8304}
8305
8306impl CoverageDots {
8307    pub fn new(name: impl Into<String>, current: usize, target: usize) -> Self {
8308        Self {
8309            theme: Box::new(DefaultTheme::default()),
8310            theme_reader: None,
8311            name: name.into(),
8312            config: CoverageDotsConfig::new(current, target),
8313            min_width: None,
8314        }
8315    }
8316
8317    pub fn theme(mut self, theme: DefaultTheme) -> Self {
8318        self.theme = Box::new(theme);
8319        self.theme_reader = None;
8320        self
8321    }
8322
8323    pub fn theme_when<F>(mut self, theme: F) -> Self
8324    where
8325        F: Fn() -> DefaultTheme + 'static,
8326    {
8327        self.theme_reader = Some(Box::new(theme));
8328        self
8329    }
8330
8331    pub fn tone(mut self, tone: SemanticTone) -> Self {
8332        self.config.tone = tone;
8333        self
8334    }
8335
8336    pub fn max_dots(mut self, max_dots: usize) -> Self {
8337        self.config.max_dots = max_dots;
8338        self
8339    }
8340
8341    pub fn show_label(mut self, show_label: bool) -> Self {
8342        self.config.show_label = show_label;
8343        self
8344    }
8345
8346    pub fn min_width(mut self, min_width: f32) -> Self {
8347        self.min_width = Some(min_width.max(0.0));
8348        self
8349    }
8350
8351    fn resolved_theme(&self) -> DefaultTheme {
8352        self.theme_reader
8353            .as_ref()
8354            .map(|theme| theme())
8355            .unwrap_or(*self.theme)
8356    }
8357}
8358
8359impl Widget for CoverageDots {
8360    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8361        let theme = self.resolved_theme();
8362        let target = self.config.normalized_target();
8363        if target == 0 {
8364            return constraints.clamp(Size::ZERO);
8365        }
8366        let (dot, gap, label_gap) = coverage_dot_metrics(&theme);
8367        let shown = target.min(self.config.normalized_max_dots());
8368        let dots_width = shown as f32 * dot + shown.saturating_sub(1) as f32 * gap;
8369        let label_width = if self.config.show_label {
8370            measure_text(
8371                ctx,
8372                &self.config.label(),
8373                &numeric_text_style(text_token_style(
8374                    &theme,
8375                    theme.text.xs,
8376                    theme.palette.text_muted,
8377                )),
8378            )
8379            .width
8380                + label_gap
8381        } else {
8382            0.0
8383        };
8384        constraints.clamp(Size::new(
8385            self.min_width.unwrap_or(0.0).max(dots_width + label_width),
8386            theme
8387                .text
8388                .xs
8389                .line_height
8390                .max(dot + 2.0)
8391                .max(theme.metrics.min_height * 0.55),
8392        ))
8393    }
8394
8395    fn paint(&self, ctx: &mut PaintCtx) {
8396        paint_coverage_dots_with_config(ctx, &self.resolved_theme(), ctx.bounds(), self.config);
8397    }
8398
8399    fn semantics(&self, ctx: &mut SemanticsCtx) {
8400        let target = self.config.normalized_target();
8401        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8402        node.name = Some(self.name.clone());
8403        node.value = Some(SemanticsValue::Text(self.config.label()));
8404        node.description = Some(format!(
8405            "{} of {} covered",
8406            self.config.current.min(target),
8407            target
8408        ));
8409        ctx.push(node);
8410    }
8411}
8412
8413pub struct PlacementBadge {
8414    theme: Box<DefaultTheme>,
8415    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8416    label: String,
8417    label_reader: Option<Box<dyn Fn() -> String>>,
8418    icon: Option<IconGlyph>,
8419    tone: SemanticTone,
8420    tone_reader: Option<Box<dyn Fn() -> SemanticTone>>,
8421    coverage: Option<(usize, usize)>,
8422    coverage_reader: Option<Box<dyn Fn() -> Option<(usize, usize)>>>,
8423    min_width: Option<f32>,
8424}
8425
8426impl PlacementBadge {
8427    pub fn new(label: impl Into<String>) -> Self {
8428        Self {
8429            theme: Box::new(DefaultTheme::default()),
8430            theme_reader: None,
8431            label: label.into(),
8432            label_reader: None,
8433            icon: None,
8434            tone: SemanticTone::Neutral,
8435            tone_reader: None,
8436            coverage: None,
8437            coverage_reader: None,
8438            min_width: None,
8439        }
8440    }
8441
8442    pub fn dynamic<F>(fallback: impl Into<String>, reader: F) -> Self
8443    where
8444        F: Fn() -> String + 'static,
8445    {
8446        let mut badge = Self::new(fallback);
8447        badge.label_reader = Some(Box::new(reader));
8448        badge
8449    }
8450
8451    pub fn theme(mut self, theme: DefaultTheme) -> Self {
8452        self.theme = Box::new(theme);
8453        self.theme_reader = None;
8454        self
8455    }
8456
8457    pub fn theme_when<F>(mut self, theme: F) -> Self
8458    where
8459        F: Fn() -> DefaultTheme + 'static,
8460    {
8461        self.theme_reader = Some(Box::new(theme));
8462        self
8463    }
8464
8465    pub fn icon(mut self, icon: IconGlyph) -> Self {
8466        self.icon = Some(icon);
8467        self
8468    }
8469
8470    pub fn tone(mut self, tone: SemanticTone) -> Self {
8471        self.tone = tone;
8472        self.tone_reader = None;
8473        self
8474    }
8475
8476    pub fn tone_when<F>(mut self, tone: F) -> Self
8477    where
8478        F: Fn() -> SemanticTone + 'static,
8479    {
8480        self.tone_reader = Some(Box::new(tone));
8481        self
8482    }
8483
8484    pub fn coverage(mut self, current: usize, target: usize) -> Self {
8485        self.coverage = Some((current, target));
8486        self.coverage_reader = None;
8487        self
8488    }
8489
8490    pub fn coverage_when<F>(mut self, coverage: F) -> Self
8491    where
8492        F: Fn() -> Option<(usize, usize)> + 'static,
8493    {
8494        self.coverage_reader = Some(Box::new(coverage));
8495        self
8496    }
8497
8498    pub fn min_width(mut self, min_width: f32) -> Self {
8499        self.min_width = Some(min_width.max(0.0));
8500        self
8501    }
8502
8503    fn resolved_theme(&self) -> DefaultTheme {
8504        self.theme_reader
8505            .as_ref()
8506            .map(|theme| theme())
8507            .unwrap_or(*self.theme)
8508    }
8509
8510    fn label(&self) -> String {
8511        self.label_reader
8512            .as_ref()
8513            .map(|reader| reader())
8514            .unwrap_or_else(|| self.label.clone())
8515    }
8516
8517    fn resolved_tone(&self) -> SemanticTone {
8518        self.tone_reader
8519            .as_ref()
8520            .map(|reader| reader())
8521            .unwrap_or(self.tone)
8522    }
8523
8524    fn resolved_coverage(&self) -> Option<(usize, usize)> {
8525        self.coverage_reader
8526            .as_ref()
8527            .map(|reader| reader())
8528            .unwrap_or(self.coverage)
8529            .filter(|(_, target)| *target > 0)
8530    }
8531
8532    fn metrics(theme: &DefaultTheme) -> (f32, f32, f32) {
8533        let height = (theme.metrics.min_height - 2.0).max(22.0);
8534        let coverage_width = 50.0;
8535        let gap = theme.metrics.icon_label_gap.max(6.0);
8536        (height, coverage_width, gap)
8537    }
8538}
8539
8540#[derive(Clone, Copy, Debug, PartialEq)]
8541pub struct PlacementBadgePaint {
8542    pub padding: Insets,
8543}
8544
8545impl PlacementBadgePaint {
8546    pub const fn new() -> Self {
8547        Self {
8548            padding: Insets::ZERO,
8549        }
8550    }
8551
8552    pub const fn padding(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self {
8553        self.padding = Insets {
8554            left,
8555            top,
8556            right,
8557            bottom,
8558        };
8559        self
8560    }
8561
8562    fn content_rect(self, rect: Rect) -> Rect {
8563        Rect::new(
8564            rect.x() + self.padding.left,
8565            rect.y() + self.padding.top,
8566            (rect.width() - self.padding.left - self.padding.right).max(0.0),
8567            (rect.height() - self.padding.top - self.padding.bottom).max(0.0),
8568        )
8569    }
8570}
8571
8572impl Default for PlacementBadgePaint {
8573    fn default() -> Self {
8574        Self::new()
8575    }
8576}
8577
8578pub fn paint_placement_badge(
8579    ctx: &mut PaintCtx,
8580    theme: &DefaultTheme,
8581    rect: Rect,
8582    label: &str,
8583    icon: Option<IconGlyph>,
8584    tone: SemanticTone,
8585    coverage: Option<(usize, usize)>,
8586) {
8587    paint_placement_badge_with(
8588        ctx,
8589        theme,
8590        rect,
8591        label,
8592        icon,
8593        tone,
8594        coverage,
8595        PlacementBadgePaint::new(),
8596    );
8597}
8598
8599pub fn paint_placement_badge_with(
8600    ctx: &mut PaintCtx,
8601    theme: &DefaultTheme,
8602    rect: Rect,
8603    label: &str,
8604    icon: Option<IconGlyph>,
8605    tone: SemanticTone,
8606    coverage: Option<(usize, usize)>,
8607    paint: PlacementBadgePaint,
8608) {
8609    let rect = paint.content_rect(rect);
8610    if rect.width() <= 0.0 || rect.height() <= 0.0 {
8611        return;
8612    }
8613
8614    let (_, coverage_width, gap) = PlacementBadge::metrics(theme);
8615    let show_coverage = coverage.is_some() && rect.width() >= 118.0;
8616    let coverage_slot = if show_coverage { coverage_width } else { 0.0 };
8617    let slot_gap = if show_coverage { gap } else { 0.0 };
8618    let badge_rect = Rect::new(
8619        rect.x(),
8620        rect.y(),
8621        (rect.width() - coverage_slot - slot_gap).clamp(48.0, 86.0),
8622        rect.height(),
8623    );
8624    paint_status_badge(ctx, badge_rect, theme, label, icon, tone);
8625
8626    if show_coverage && let Some((current, target)) = coverage {
8627        let dots_rect = Rect::new(
8628            badge_rect.max_x() + slot_gap,
8629            rect.y(),
8630            (rect.max_x() - badge_rect.max_x() - slot_gap).max(0.0),
8631            rect.height(),
8632        );
8633        paint_coverage_dots(ctx, theme, dots_rect, current, target, tone);
8634    }
8635}
8636
8637impl Widget for PlacementBadge {
8638    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
8639        let theme = self.resolved_theme();
8640        let (height, coverage_width, gap) = Self::metrics(&theme);
8641        let label = self.label();
8642        let tone = self.resolved_tone();
8643        let icon_w = self
8644            .icon
8645            .map(|_| (height - 13.0).clamp(11.0, 15.0) + theme.metrics.icon_label_gap.max(4.0))
8646            .unwrap_or(0.0);
8647        let text = measure_text(
8648            ctx,
8649            &label,
8650            &StatusBadge::new(&label).text_style(&theme, &label, tone),
8651        );
8652        let badge_width =
8653            (text.width.ceil() + icon_w + theme.metrics.button_padding.left.max(8.0) * 2.0)
8654                .clamp(48.0, 86.0);
8655        let coverage_width = if self.resolved_coverage().is_some() {
8656            coverage_width + gap
8657        } else {
8658            0.0
8659        };
8660        constraints.clamp(Size::new(
8661            self.min_width
8662                .unwrap_or(0.0)
8663                .max(badge_width + coverage_width),
8664            height,
8665        ))
8666    }
8667
8668    fn paint(&self, ctx: &mut PaintCtx) {
8669        let theme = self.resolved_theme();
8670        paint_placement_badge(
8671            ctx,
8672            &theme,
8673            ctx.bounds(),
8674            &self.label(),
8675            self.icon,
8676            self.resolved_tone(),
8677            self.resolved_coverage(),
8678        );
8679    }
8680
8681    fn semantics(&self, ctx: &mut SemanticsCtx) {
8682        let label = self.label();
8683        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
8684        node.name = Some(label.clone());
8685        node.value = Some(SemanticsValue::Text(label.clone()));
8686        if let Some((current, target)) = self.resolved_coverage() {
8687            let target = target.max(current);
8688            node.description = Some(format!("{current} of {target} replicas available"));
8689        }
8690        ctx.push(node);
8691    }
8692}
8693
8694pub struct TabBar {
8695    theme: Box<DefaultTheme>,
8696    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
8697    name: String,
8698    tabs: Vec<String>,
8699    selected: usize,
8700    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
8701    selected_source: Option<Arc<dyn Observable<Option<usize>>>>,
8702    selection_from: usize,
8703    selection_animation: AnimatedScalar,
8704    hovered: Option<usize>,
8705    hover_visual: Option<usize>,
8706    pressed: Option<usize>,
8707    press_visual: Option<usize>,
8708    hover_animation: AnimatedScalar,
8709    press_animation: AnimatedScalar,
8710    focus_animation: AnimatedScalar,
8711    gap: Option<f32>,
8712    label_measurements: Vec<TextMeasurement>,
8713    widths: Vec<f32>,
8714    on_change: Option<Box<dyn FnMut(usize, String)>>,
8715}
8716
8717impl TabBar {
8718    pub fn new(name: impl Into<String>) -> Self {
8719        Self {
8720            theme: Box::new(DefaultTheme::default()),
8721            theme_reader: None,
8722            name: name.into(),
8723            tabs: Vec::new(),
8724            selected: 0,
8725            selected_reader: None,
8726            selected_source: None,
8727            selection_from: 0,
8728            selection_animation: AnimatedScalar::new(1.0),
8729            hovered: None,
8730            hover_visual: None,
8731            pressed: None,
8732            press_visual: None,
8733            hover_animation: AnimatedScalar::new(0.0),
8734            press_animation: AnimatedScalar::new(0.0),
8735            focus_animation: AnimatedScalar::new(0.0),
8736            gap: None,
8737            label_measurements: Vec::new(),
8738            widths: Vec::new(),
8739            on_change: None,
8740        }
8741    }
8742
8743    pub fn theme(mut self, theme: DefaultTheme) -> Self {
8744        self.theme = Box::new(theme);
8745        self.theme_reader = None;
8746        self
8747    }
8748
8749    pub fn theme_when<F>(mut self, theme: F) -> Self
8750    where
8751        F: Fn() -> DefaultTheme + 'static,
8752    {
8753        self.theme_reader = Some(Box::new(theme));
8754        self
8755    }
8756
8757    pub fn tab(mut self, label: impl Into<String>) -> Self {
8758        self.tabs.push(label.into());
8759        self
8760    }
8761
8762    pub fn tabs<I, S>(mut self, labels: I) -> Self
8763    where
8764        I: IntoIterator<Item = S>,
8765        S: Into<String>,
8766    {
8767        self.tabs.extend(labels.into_iter().map(Into::into));
8768        self
8769    }
8770
8771    pub fn selected(mut self, index: usize) -> Self {
8772        self.selected = index;
8773        self.selected_reader = None;
8774        self.selected_source = None;
8775        self.selection_from = index;
8776        self.selection_animation = AnimatedScalar::new(1.0);
8777        self
8778    }
8779
8780    pub fn selected_when<F>(mut self, selected: F) -> Self
8781    where
8782        F: Fn() -> Option<usize> + 'static,
8783    {
8784        if let Some(index) = selected() {
8785            self.selected = index;
8786            self.selection_from = index;
8787        }
8788        self.selected_reader = Some(Box::new(selected));
8789        self.selected_source = None;
8790        self
8791    }
8792
8793    /// Bind the selected tab to an observable value without rebuilding the
8794    /// retained tab bar.
8795    pub fn selected_from<O>(mut self, selected: O) -> Self
8796    where
8797        O: Observable<Option<usize>> + 'static,
8798    {
8799        if let Some(index) = selected.get() {
8800            self.selected = index;
8801            self.selection_from = index;
8802        }
8803        self.selected_reader = None;
8804        self.selected_source = Some(Arc::new(selected));
8805        self
8806    }
8807
8808    pub fn gap(mut self, gap: f32) -> Self {
8809        self.gap = Some(gap.max(0.0));
8810        self
8811    }
8812
8813    pub fn on_change<F>(mut self, on_change: F) -> Self
8814    where
8815        F: FnMut(usize, String) + 'static,
8816    {
8817        self.on_change = Some(Box::new(on_change));
8818        self
8819    }
8820
8821    pub fn selected_index(&self) -> usize {
8822        self.normalized_selected()
8823    }
8824
8825    pub fn current_tab(&self) -> Option<&str> {
8826        self.tabs
8827            .get(self.normalized_selected())
8828            .map(String::as_str)
8829    }
8830
8831    fn normalized_selected(&self) -> usize {
8832        let selected = self
8833            .selected_source
8834            .as_ref()
8835            .and_then(|source| source.get())
8836            .or_else(|| self.selected_reader.as_ref().and_then(|reader| reader()))
8837            .unwrap_or(self.selected);
8838        if self.tabs.is_empty() {
8839            0
8840        } else {
8841            selected.min(self.tabs.len() - 1)
8842        }
8843    }
8844
8845    fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
8846        if self.tabs.is_empty() {
8847            return;
8848        }
8849
8850        let index = index.min(self.tabs.len() - 1);
8851        let selected = self.normalized_selected();
8852        if selected != index {
8853            self.selected = index;
8854            if let Some(on_change) = &mut self.on_change {
8855                on_change(index, self.tabs[index].clone());
8856            }
8857            let target = self.normalized_selected();
8858            self.selected = target;
8859            self.start_selection_animation(selected, target, ctx);
8860        }
8861    }
8862
8863    fn start_selection_animation(&mut self, from: usize, to: usize, ctx: &mut EventCtx) {
8864        if self.tabs.is_empty() || from == to {
8865            self.selection_from = to;
8866            self.selection_animation = AnimatedScalar::new(1.0);
8867            return;
8868        }
8869
8870        let theme = self.resolved_theme();
8871        self.selection_from = from.min(self.tabs.len() - 1);
8872        self.selection_animation = AnimatedScalar::new(0.0);
8873        self.selection_animation.set_target_event(
8874            1.0,
8875            theme.motion.tab_switch_duration(),
8876            theme.motion.tab_switch_easing(),
8877            ctx,
8878        );
8879        ctx.request_paint();
8880        ctx.request_semantics();
8881    }
8882
8883    fn sync_external_selected(&mut self, ctx: &mut EventCtx) {
8884        if (self.selected_reader.is_none() && self.selected_source.is_none())
8885            || self.tabs.is_empty()
8886        {
8887            return;
8888        }
8889
8890        if let Some(source) = &self.selected_source {
8891            let _ = ctx.observe(source.as_ref(), InvalidationKind::Paint);
8892            let _ = ctx.observe(source.as_ref(), InvalidationKind::Semantics);
8893        }
8894
8895        let previous = self.selected.min(self.tabs.len() - 1);
8896        let selected = self.normalized_selected();
8897        if previous != selected {
8898            self.selected = selected;
8899            self.start_selection_animation(previous, selected, ctx);
8900        }
8901    }
8902
8903    fn tab_height(&self) -> f32 {
8904        self.resolved_theme().metrics.tab_height
8905    }
8906
8907    fn resolved_gap(&self) -> f32 {
8908        self.gap
8909            .unwrap_or(self.resolved_theme().metrics.tab_gap)
8910            .max(0.0)
8911    }
8912
8913    fn measured_widths(&self) -> &[f32] {
8914        &self.widths
8915    }
8916
8917    fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
8918        if index >= self.tabs.len() || self.measured_widths().len() != self.tabs.len() {
8919            return None;
8920        }
8921
8922        let gap = self.resolved_gap();
8923        let base_total =
8924            self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
8925        let extra_per_tab = if bounds.width() > base_total && !self.tabs.is_empty() {
8926            (bounds.width() - base_total) / self.tabs.len() as f32
8927        } else {
8928            0.0
8929        };
8930
8931        let tab_height = self.tab_height().min(bounds.height()).max(0.0);
8932        let tab_y = bounds.y() + ((bounds.height() - tab_height) * 0.5).max(0.0);
8933        let mut x = bounds.x();
8934        for (current, width) in self.widths.iter().enumerate() {
8935            let width = *width + extra_per_tab;
8936            let rect = Rect::new(x, tab_y, width, tab_height);
8937            if current == index {
8938                return Some(rect);
8939            }
8940            x += width + gap;
8941        }
8942
8943        None
8944    }
8945
8946    fn tab_at(&self, bounds: Rect, position: Point) -> Option<usize> {
8947        self.tabs.iter().enumerate().find_map(|(index, _)| {
8948            self.tab_rect(bounds, index)
8949                .filter(|rect| rect.contains(position))
8950                .map(|_| index)
8951        })
8952    }
8953
8954    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
8955        if self.tabs.is_empty() {
8956            return;
8957        }
8958
8959        let selected = self.normalized_selected() as isize;
8960        let last = self.tabs.len() as isize - 1;
8961        let next = (selected + delta).clamp(0, last) as usize;
8962        self.activate(next, ctx);
8963        self.set_hovered(Some(next), ctx);
8964    }
8965
8966    fn advance_animations(&mut self, time: f64) -> bool {
8967        let selection_animating = self.selection_animation.advance(time);
8968        let hover_animating = self.hover_animation.advance(time);
8969        if !hover_animating
8970            && self.hovered.is_none()
8971            && self.hover_animation.value <= AnimatedScalar::EPSILON
8972        {
8973            self.hover_visual = None;
8974        }
8975        let press_animating = self.press_animation.advance(time);
8976        if !press_animating
8977            && self.pressed.is_none()
8978            && self.press_animation.value <= AnimatedScalar::EPSILON
8979        {
8980            self.press_visual = None;
8981        }
8982        let focus_animating = self.focus_animation.advance(time);
8983        selection_animating | hover_animating | press_animating | focus_animating
8984    }
8985
8986    fn resolved_theme(&self) -> DefaultTheme {
8987        self.theme_reader
8988            .as_ref()
8989            .map(|theme| theme())
8990            .unwrap_or(*self.theme)
8991    }
8992
8993    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
8994        if self.hovered == hovered {
8995            return;
8996        }
8997        let theme = self.resolved_theme();
8998        self.hovered = hovered;
8999        if let Some(index) = hovered {
9000            self.hover_visual = Some(index);
9001            self.hover_animation = AnimatedScalar::new(0.0);
9002            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
9003        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
9004            self.hover_visual = None;
9005        }
9006        ctx.request_paint();
9007        ctx.request_semantics();
9008    }
9009
9010    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
9011        if self.pressed == pressed {
9012            return;
9013        }
9014        let theme = self.resolved_theme();
9015        self.pressed = pressed;
9016        if let Some(index) = pressed {
9017            self.press_visual = Some(index);
9018            self.press_animation = AnimatedScalar::new(0.0);
9019            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
9020        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
9021            self.press_visual = None;
9022        }
9023        ctx.request_paint();
9024        ctx.request_semantics();
9025    }
9026
9027    fn hover_amount_for(&self, index: usize) -> f32 {
9028        if self.hover_visual == Some(index) {
9029            self.hover_animation.value
9030        } else {
9031            0.0
9032        }
9033    }
9034
9035    fn press_amount_for(&self, index: usize) -> f32 {
9036        if self.press_visual == Some(index) {
9037            self.press_animation.value
9038        } else {
9039            0.0
9040        }
9041    }
9042}
9043
9044impl Widget for TabBar {
9045    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
9046        self.sync_external_selected(ctx);
9047        match event {
9048            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
9049                self.set_hovered(self.tab_at(ctx.bounds(), pointer.position), ctx);
9050            }
9051            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
9052                self.set_hovered(None, ctx);
9053            }
9054            Event::Pointer(pointer)
9055                if pointer.kind == PointerEventKind::Down
9056                    && pointer.button == Some(PointerButton::Primary) =>
9057            {
9058                let hovered = self.tab_at(ctx.bounds(), pointer.position);
9059                self.set_hovered(hovered, ctx);
9060                self.set_pressed(hovered, ctx);
9061                ctx.request_focus();
9062                ctx.request_pointer_capture(pointer.pointer_id);
9063                ctx.set_handled();
9064            }
9065            Event::Pointer(pointer)
9066                if pointer.kind == PointerEventKind::Up
9067                    && pointer.button == Some(PointerButton::Primary) =>
9068            {
9069                let hovered = self.tab_at(ctx.bounds(), pointer.position);
9070                if let Some(index) = self
9071                    .pressed
9072                    .zip(hovered)
9073                    .filter(|(left, right)| left == right)
9074                    .map(|(index, _)| index)
9075                {
9076                    self.activate(index, ctx);
9077                }
9078                self.set_hovered(hovered, ctx);
9079                self.set_pressed(None, ctx);
9080                ctx.release_pointer_capture(pointer.pointer_id);
9081                ctx.set_handled();
9082            }
9083            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
9084                if self.pressed.is_some() {
9085                    self.set_pressed(None, ctx);
9086                    self.set_hovered(None, ctx);
9087                    ctx.release_pointer_capture(pointer.pointer_id);
9088                    ctx.set_handled();
9089                }
9090            }
9091            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
9092                match key.key.as_str() {
9093                    "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
9094                    "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
9095                    "Home" => self.activate(0, ctx),
9096                    "End" if !self.tabs.is_empty() => self.activate(self.tabs.len() - 1, ctx),
9097                    _ => return,
9098                }
9099                ctx.request_paint();
9100                ctx.request_semantics();
9101                ctx.set_handled();
9102            }
9103            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
9104                if self.advance_animations(*time) {
9105                    ctx.request_animation_frame();
9106                }
9107                ctx.request_paint();
9108            }
9109            _ => {}
9110        }
9111    }
9112
9113    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
9114        if command.is(REACTIVE_CHANGED) && self.selected_source.is_some() {
9115            self.sync_external_selected(ctx);
9116            ctx.set_handled();
9117        }
9118    }
9119
9120    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
9121        if let Some(source) = &self.selected_source {
9122            let selected = ctx.observe_with(source.as_ref(), InvalidationKind::Paint);
9123            let _ = ctx.observe_with(source.as_ref(), InvalidationKind::Semantics);
9124            if let Some(selected) = selected {
9125                self.selected = selected;
9126            }
9127        }
9128        let theme = self.resolved_theme();
9129        let style = text_token_style(&theme, theme.text.sm, theme.palette.text);
9130        let padding = theme.metrics.tab_padding;
9131        self.label_measurements = self
9132            .tabs
9133            .iter()
9134            .map(|tab| measure_text(ctx, tab, &style))
9135            .collect();
9136        self.widths = self
9137            .label_measurements
9138            .iter()
9139            .map(|measurement| {
9140                (measurement.width + padding.left + padding.right).max(theme.metrics.tab_min_width)
9141            })
9142            .collect();
9143
9144        let gap = self.resolved_gap();
9145        let width =
9146            self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
9147        constraints.clamp(Size::new(width.max(160.0), self.tab_height()))
9148    }
9149
9150    fn paint(&self, ctx: &mut PaintCtx) {
9151        let theme = self.resolved_theme();
9152        let palette = theme.palette;
9153        let metrics = theme.metrics;
9154        let interaction = theme.interaction;
9155        let tab_padding = metrics.tab_padding;
9156        let label_style = text_token_style(&theme, theme.text.sm, palette.text_muted);
9157        let selected_label_style = text_token_style(&theme, theme.text.sm, palette.text);
9158
9159        // Navigation tabs share one flat strip. Selection is communicated by the
9160        // animated underline below rather than by a second, raised tile.
9161        ctx.fill_rect(ctx.bounds(), palette.control);
9162        let divider_height = physical_pixels(ctx, metrics.border_width);
9163        ctx.fill_rect(
9164            Rect::new(
9165                ctx.bounds().x(),
9166                ctx.bounds().max_y() - divider_height,
9167                ctx.bounds().width(),
9168                divider_height,
9169            ),
9170            palette.border.with_alpha(0.72),
9171        );
9172
9173        let focus_progress = self.focus_animation.value;
9174        for (index, tab) in self.tabs.iter().enumerate() {
9175            let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9176                continue;
9177            };
9178            let selected = self.normalized_selected() == index;
9179            let hovered = self.hovered == Some(index);
9180            let pressed = self.pressed == Some(index);
9181            let hover_amount = self.hover_amount_for(index);
9182            let press_amount = self.press_amount_for(index);
9183
9184            // Hover and press remain local to each tab, but the steady selected
9185            // state stays flat so it does not compete with the underline.
9186            if (hovered
9187                || pressed
9188                || hover_amount > AnimatedScalar::EPSILON
9189                || press_amount > AnimatedScalar::EPSILON)
9190                && let Some((background, border)) =
9191                    tab_state_visuals(&theme, false, hovered, pressed, hover_amount, press_amount)
9192            {
9193                draw_control_shape(
9194                    ctx,
9195                    rect,
9196                    metrics.corner_radius,
9197                    physical_pixels(ctx, metrics.border_width),
9198                    background,
9199                    border,
9200                );
9201            }
9202
9203            if selected && focus_progress > AnimatedScalar::EPSILON {
9204                draw_focus_ring_frame(
9205                    ctx,
9206                    rect,
9207                    metrics.corner_radius,
9208                    metrics,
9209                    palette
9210                        .focus_ring
9211                        .with_alpha(palette.focus_ring.alpha * focus_progress),
9212                );
9213            }
9214
9215            let text_style = if selected {
9216                selected_label_style.clone()
9217            } else {
9218                label_style.clone()
9219            };
9220            let text_slot = inset_rect(rect, tab_padding);
9221            let pressed_offset = press_amount * interaction.pressed_offset;
9222            ctx.push_clip_rect(text_slot);
9223            paint_aligned_text(
9224                ctx,
9225                text_slot.translate(Vector::new(0.0, pressed_offset)),
9226                tab,
9227                &text_style,
9228                text_style.line_height,
9229                0.5,
9230            );
9231            ctx.pop_clip();
9232        }
9233
9234        if let Some(accent) = tab_indicator_rect(
9235            |index| self.tab_rect(ctx.bounds(), index),
9236            self.selection_from,
9237            self.normalized_selected(),
9238            self.selection_animation.value,
9239            tab_padding,
9240            interaction.active_indicator_thickness,
9241        ) {
9242            ctx.fill(
9243                rounded_rect_path(accent, accent.height() * 0.5),
9244                palette.accent,
9245            );
9246        }
9247    }
9248
9249    fn semantics(&self, ctx: &mut SemanticsCtx) {
9250        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TabBar, ctx.bounds());
9251        node.name = Some(self.name.clone());
9252        node.value = self
9253            .current_tab()
9254            .map(|value| SemanticsValue::Text(value.to_string()));
9255        node.state.focused = ctx.is_focused();
9256        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
9257        ctx.push(node);
9258    }
9259
9260    fn accepts_focus(&self) -> bool {
9261        true
9262    }
9263
9264    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
9265        let theme = self.resolved_theme();
9266        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
9267        ctx.request_paint();
9268        ctx.request_semantics();
9269    }
9270}
9271
9272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9273enum BrowserTabHit {
9274    Tab(usize),
9275    Close(usize),
9276}
9277
9278impl BrowserTabHit {
9279    fn index(self) -> usize {
9280        match self {
9281            Self::Tab(index) | Self::Close(index) => index,
9282        }
9283    }
9284}
9285
9286type BrowserTabBarChange = Box<dyn FnMut(usize, String)>;
9287type BrowserTabBarContextChange = Box<dyn FnMut(usize, String, &mut EventCtx)>;
9288
9289pub struct BrowserTabBar {
9290    theme: Box<DefaultTheme>,
9291    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
9292    name: String,
9293    tabs: Vec<String>,
9294    tabs_reader: Option<Box<dyn Fn() -> Vec<String>>>,
9295    selected: Option<usize>,
9296    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
9297    selection_from: Option<usize>,
9298    selection_to: Option<usize>,
9299    selection_animation: AnimatedScalar,
9300    hovered: Option<BrowserTabHit>,
9301    hover_visual: Option<BrowserTabHit>,
9302    pressed: Option<BrowserTabHit>,
9303    press_visual: Option<BrowserTabHit>,
9304    hover_animation: AnimatedScalar,
9305    press_animation: AnimatedScalar,
9306    focus_animation: AnimatedScalar,
9307    label_measurements: Vec<TextMeasurement>,
9308    widths: Vec<f32>,
9309    on_change: Option<BrowserTabBarChange>,
9310    on_change_with_ctx: Option<BrowserTabBarContextChange>,
9311    on_close: Option<BrowserTabBarChange>,
9312    on_close_with_ctx: Option<BrowserTabBarContextChange>,
9313}
9314
9315impl BrowserTabBar {
9316    pub fn new(name: impl Into<String>) -> Self {
9317        Self {
9318            theme: Box::new(DefaultTheme::default()),
9319            theme_reader: None,
9320            name: name.into(),
9321            tabs: Vec::new(),
9322            tabs_reader: None,
9323            selected: None,
9324            selected_reader: None,
9325            selection_from: None,
9326            selection_to: None,
9327            selection_animation: AnimatedScalar::new(1.0),
9328            hovered: None,
9329            hover_visual: None,
9330            pressed: None,
9331            press_visual: None,
9332            hover_animation: AnimatedScalar::new(0.0),
9333            press_animation: AnimatedScalar::new(0.0),
9334            focus_animation: AnimatedScalar::new(0.0),
9335            label_measurements: Vec::new(),
9336            widths: Vec::new(),
9337            on_change: None,
9338            on_change_with_ctx: None,
9339            on_close: None,
9340            on_close_with_ctx: None,
9341        }
9342    }
9343
9344    pub fn theme(mut self, theme: DefaultTheme) -> Self {
9345        self.theme = Box::new(theme);
9346        self.theme_reader = None;
9347        self
9348    }
9349
9350    pub fn theme_when<F>(mut self, theme: F) -> Self
9351    where
9352        F: Fn() -> DefaultTheme + 'static,
9353    {
9354        self.theme_reader = Some(Box::new(theme));
9355        self
9356    }
9357
9358    pub fn tabs<I, S>(mut self, labels: I) -> Self
9359    where
9360        I: IntoIterator<Item = S>,
9361        S: Into<String>,
9362    {
9363        self.tabs.extend(labels.into_iter().map(Into::into));
9364        self
9365    }
9366
9367    pub fn tabs_when<F>(mut self, tabs: F) -> Self
9368    where
9369        F: Fn() -> Vec<String> + 'static,
9370    {
9371        self.tabs_reader = Some(Box::new(tabs));
9372        self
9373    }
9374
9375    pub fn selected(mut self, index: Option<usize>) -> Self {
9376        self.selected = index;
9377        self.selection_from = index;
9378        self.selection_to = index;
9379        self.selection_animation = AnimatedScalar::new(1.0);
9380        self
9381    }
9382
9383    pub fn selected_when<F>(mut self, selected: F) -> Self
9384    where
9385        F: Fn() -> Option<usize> + 'static,
9386    {
9387        self.selected_reader = Some(Box::new(selected));
9388        self
9389    }
9390
9391    pub fn on_change<F>(mut self, on_change: F) -> Self
9392    where
9393        F: FnMut(usize, String) + 'static,
9394    {
9395        self.on_change = Some(Box::new(on_change));
9396        self
9397    }
9398
9399    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
9400    where
9401        F: FnMut(usize, String, &mut EventCtx) + 'static,
9402    {
9403        self.on_change_with_ctx = Some(Box::new(on_change));
9404        self
9405    }
9406
9407    pub fn on_close<F>(mut self, on_close: F) -> Self
9408    where
9409        F: FnMut(usize, String) + 'static,
9410    {
9411        self.on_close = Some(Box::new(on_close));
9412        self
9413    }
9414
9415    pub fn on_close_with_ctx<F>(mut self, on_close: F) -> Self
9416    where
9417        F: FnMut(usize, String, &mut EventCtx) + 'static,
9418    {
9419        self.on_close_with_ctx = Some(Box::new(on_close));
9420        self
9421    }
9422
9423    pub fn selected_index(&self) -> Option<usize> {
9424        self.normalized_selected()
9425    }
9426
9427    fn refresh_tabs(&mut self) {
9428        if let Some(reader) = &self.tabs_reader {
9429            self.tabs = reader();
9430        }
9431        self.selected = self.resolved_selected_raw();
9432        let selected = self.normalized_selected();
9433        if self.selection_animation.value >= 1.0 - AnimatedScalar::EPSILON
9434            && self.selection_to != selected
9435        {
9436            self.selection_from = selected;
9437            self.selection_to = selected;
9438            self.selection_animation = AnimatedScalar::new(1.0);
9439        }
9440    }
9441
9442    fn resolved_selected_raw(&self) -> Option<usize> {
9443        self.selected_reader
9444            .as_ref()
9445            .map(|reader| reader())
9446            .unwrap_or(self.selected)
9447    }
9448
9449    fn normalized_selected(&self) -> Option<usize> {
9450        let selected = self.resolved_selected_raw()?;
9451        (selected < self.tabs.len()).then_some(selected)
9452    }
9453
9454    fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
9455        self.refresh_tabs();
9456        if index >= self.tabs.len() {
9457            return;
9458        }
9459        let from = self.normalized_selected();
9460        if from == Some(index) {
9461            return;
9462        }
9463        let label = self.tabs[index].clone();
9464        self.selected = Some(index);
9465        if let Some(on_change) = &mut self.on_change {
9466            on_change(index, label.clone());
9467        }
9468        if let Some(on_change) = &mut self.on_change_with_ctx {
9469            on_change(index, label, ctx);
9470        }
9471        self.refresh_tabs();
9472        self.start_selection_animation(from, self.normalized_selected(), ctx);
9473    }
9474
9475    fn close(&mut self, index: usize, ctx: &mut EventCtx) {
9476        self.refresh_tabs();
9477        if index >= self.tabs.len() {
9478            return;
9479        }
9480        let from = self.normalized_selected();
9481        let label = self.tabs[index].clone();
9482        if let Some(on_close) = &mut self.on_close {
9483            on_close(index, label.clone());
9484        }
9485        if let Some(on_close) = &mut self.on_close_with_ctx {
9486            on_close(index, label, ctx);
9487        }
9488        self.refresh_tabs();
9489        self.start_selection_animation(from, self.normalized_selected(), ctx);
9490    }
9491
9492    fn start_selection_animation(
9493        &mut self,
9494        from: Option<usize>,
9495        to: Option<usize>,
9496        ctx: &mut EventCtx,
9497    ) {
9498        self.selection_from = from.or(to);
9499        self.selection_to = to;
9500        if from.zip(to).is_some_and(|(from, to)| from != to) {
9501            let theme = self.resolved_theme();
9502            self.selection_animation = AnimatedScalar::new(0.0);
9503            self.selection_animation.set_target_event(
9504                1.0,
9505                theme.motion.tab_switch_duration(),
9506                theme.motion.tab_switch_easing(),
9507                ctx,
9508            );
9509        } else {
9510            self.selection_animation = AnimatedScalar::new(1.0);
9511        }
9512        ctx.request_paint();
9513        ctx.request_semantics();
9514    }
9515
9516    fn resolved_theme(&self) -> DefaultTheme {
9517        self.theme_reader
9518            .as_ref()
9519            .map(|theme| theme())
9520            .unwrap_or(*self.theme)
9521    }
9522
9523    fn close_size(theme: &DefaultTheme) -> f32 {
9524        (theme.metrics.tab_height * 0.56).clamp(16.0, 20.0)
9525    }
9526
9527    fn close_gap(theme: &DefaultTheme) -> f32 {
9528        theme.metrics.icon_label_gap.max(7.0)
9529    }
9530
9531    fn tab_height(&self) -> f32 {
9532        self.resolved_theme().metrics.tab_height
9533    }
9534
9535    fn measured_widths(&self) -> &[f32] {
9536        &self.widths
9537    }
9538
9539    fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
9540        if index >= self.tabs.len() || self.measured_widths().len() != self.tabs.len() {
9541            return None;
9542        }
9543
9544        let theme = self.resolved_theme();
9545        let gap = theme.metrics.tab_gap;
9546        let tab_height = self.tab_height().min(bounds.height()).max(0.0);
9547        let tab_y = bounds.y() + ((bounds.height() - tab_height) * 0.5).max(0.0);
9548        let mut x = bounds.x();
9549        for (current, measured_width) in self.widths.iter().enumerate() {
9550            let visible_width = (*measured_width).min((bounds.max_x() - x).max(0.0));
9551            let rect = Rect::new(x, tab_y, visible_width, tab_height);
9552            if current == index {
9553                return (visible_width > 0.0).then_some(rect);
9554            }
9555            x += *measured_width + gap;
9556            if x >= bounds.max_x() {
9557                break;
9558            }
9559        }
9560
9561        None
9562    }
9563
9564    fn close_rect_for(&self, tab_rect: Rect) -> Rect {
9565        let theme = self.resolved_theme();
9566        let close = Self::close_size(&theme)
9567            .min(tab_rect.width())
9568            .min(tab_rect.height());
9569        Rect::new(
9570            tab_rect.max_x() - close - Self::close_gap(&theme),
9571            tab_rect.y() + ((tab_rect.height() - close) * 0.5),
9572            close,
9573            close,
9574        )
9575    }
9576
9577    fn label_rect_for(&self, tab_rect: Rect) -> Rect {
9578        let theme = self.resolved_theme();
9579        let padding = theme.metrics.tab_padding;
9580        let close = self.close_rect_for(tab_rect);
9581        Rect::new(
9582            tab_rect.x() + padding.left,
9583            tab_rect.y() + padding.top,
9584            (close.x() - tab_rect.x() - padding.left - Self::close_gap(&theme)).max(0.0),
9585            (tab_rect.height() - padding.top - padding.bottom).max(0.0),
9586        )
9587    }
9588
9589    fn hit_at(&self, bounds: Rect, position: Point) -> Option<BrowserTabHit> {
9590        for index in 0..self.tabs.len() {
9591            let Some(rect) = self.tab_rect(bounds, index) else {
9592                continue;
9593            };
9594            if self.close_rect_for(rect).contains(position) {
9595                return Some(BrowserTabHit::Close(index));
9596            }
9597            if rect.contains(position) {
9598                return Some(BrowserTabHit::Tab(index));
9599            }
9600        }
9601        None
9602    }
9603
9604    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
9605        self.refresh_tabs();
9606        if self.tabs.is_empty() {
9607            return;
9608        }
9609        let selected = self.normalized_selected().unwrap_or(0) as isize;
9610        let last = self.tabs.len() as isize - 1;
9611        let next = (selected + delta).clamp(0, last) as usize;
9612        self.activate(next, ctx);
9613        self.set_hovered(Some(BrowserTabHit::Tab(next)), ctx);
9614    }
9615
9616    fn advance_animations(&mut self, time: f64) -> bool {
9617        let selection_animating = self.selection_animation.advance(time);
9618        let hover_animating = self.hover_animation.advance(time);
9619        if !hover_animating
9620            && self.hovered.is_none()
9621            && self.hover_animation.value <= AnimatedScalar::EPSILON
9622        {
9623            self.hover_visual = None;
9624        }
9625        let press_animating = self.press_animation.advance(time);
9626        if !press_animating
9627            && self.pressed.is_none()
9628            && self.press_animation.value <= AnimatedScalar::EPSILON
9629        {
9630            self.press_visual = None;
9631        }
9632        let focus_animating = self.focus_animation.advance(time);
9633        selection_animating | hover_animating | press_animating | focus_animating
9634    }
9635
9636    fn set_hovered(&mut self, hovered: Option<BrowserTabHit>, ctx: &mut EventCtx) {
9637        if self.hovered == hovered {
9638            return;
9639        }
9640        let theme = self.resolved_theme();
9641        self.hovered = hovered;
9642        if let Some(hit) = hovered {
9643            self.hover_visual = Some(hit);
9644            self.hover_animation = AnimatedScalar::new(0.0);
9645            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
9646        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
9647            self.hover_visual = None;
9648        }
9649        ctx.request_paint();
9650        ctx.request_semantics();
9651    }
9652
9653    fn set_pressed(&mut self, pressed: Option<BrowserTabHit>, ctx: &mut EventCtx) {
9654        if self.pressed == pressed {
9655            return;
9656        }
9657        let theme = self.resolved_theme();
9658        self.pressed = pressed;
9659        if let Some(hit) = pressed {
9660            self.press_visual = Some(hit);
9661            self.press_animation = AnimatedScalar::new(0.0);
9662            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
9663        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
9664            self.press_visual = None;
9665        }
9666        ctx.request_paint();
9667        ctx.request_semantics();
9668    }
9669
9670    fn hover_amount_for(&self, index: usize) -> f32 {
9671        if self.hover_visual.is_some_and(|hit| hit.index() == index) {
9672            self.hover_animation.value
9673        } else {
9674            0.0
9675        }
9676    }
9677
9678    fn press_amount_for(&self, index: usize) -> f32 {
9679        if self.press_visual.is_some_and(|hit| hit.index() == index) {
9680            self.press_animation.value
9681        } else {
9682            0.0
9683        }
9684    }
9685}
9686
9687impl Widget for BrowserTabBar {
9688    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
9689        self.refresh_tabs();
9690        match event {
9691            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
9692                self.set_hovered(self.hit_at(ctx.bounds(), pointer.position), ctx);
9693            }
9694            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
9695                self.set_hovered(None, ctx);
9696            }
9697            Event::Pointer(pointer)
9698                if pointer.kind == PointerEventKind::Down
9699                    && pointer.button == Some(PointerButton::Primary) =>
9700            {
9701                let hovered = self.hit_at(ctx.bounds(), pointer.position);
9702                self.set_hovered(hovered, ctx);
9703                self.set_pressed(hovered, ctx);
9704                ctx.request_focus();
9705                ctx.request_pointer_capture(pointer.pointer_id);
9706                ctx.set_handled();
9707            }
9708            Event::Pointer(pointer)
9709                if pointer.kind == PointerEventKind::Up
9710                    && pointer.button == Some(PointerButton::Primary) =>
9711            {
9712                let hovered = self.hit_at(ctx.bounds(), pointer.position);
9713                if let Some(hit) = self
9714                    .pressed
9715                    .zip(hovered)
9716                    .filter(|(left, right)| left == right)
9717                    .map(|(hit, _)| hit)
9718                {
9719                    match hit {
9720                        BrowserTabHit::Tab(index) => self.activate(index, ctx),
9721                        BrowserTabHit::Close(index) => self.close(index, ctx),
9722                    }
9723                }
9724                self.set_hovered(hovered, ctx);
9725                self.set_pressed(None, ctx);
9726                ctx.release_pointer_capture(pointer.pointer_id);
9727                ctx.set_handled();
9728            }
9729            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
9730                if self.pressed.is_some() {
9731                    self.set_pressed(None, ctx);
9732                    self.set_hovered(None, ctx);
9733                    ctx.release_pointer_capture(pointer.pointer_id);
9734                    ctx.set_handled();
9735                }
9736            }
9737            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
9738                match key.key.as_str() {
9739                    "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
9740                    "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
9741                    "Home" => self.activate(0, ctx),
9742                    "End" if !self.tabs.is_empty() => self.activate(self.tabs.len() - 1, ctx),
9743                    _ => return,
9744                }
9745                ctx.request_paint();
9746                ctx.request_semantics();
9747                ctx.set_handled();
9748            }
9749            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
9750                if self.advance_animations(*time) {
9751                    ctx.request_animation_frame();
9752                }
9753                ctx.request_paint();
9754            }
9755            _ => {}
9756        }
9757    }
9758
9759    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
9760        self.refresh_tabs();
9761        let theme = self.resolved_theme();
9762        let style = text_token_style(&theme, theme.text.sm, theme.palette.text);
9763        let padding = theme.metrics.tab_padding;
9764        let close_extent = Self::close_size(&theme) + (Self::close_gap(&theme) * 2.0);
9765        self.label_measurements = self
9766            .tabs
9767            .iter()
9768            .map(|tab| measure_text(ctx, tab, &style))
9769            .collect();
9770        self.widths = self
9771            .label_measurements
9772            .iter()
9773            .map(|measurement| {
9774                (measurement.width + padding.left + padding.right + close_extent)
9775                    .max(theme.metrics.tab_min_width)
9776            })
9777            .collect();
9778
9779        let gap = theme.metrics.tab_gap;
9780        let width =
9781            self.widths.iter().sum::<f32>() + (gap * self.tabs.len().saturating_sub(1) as f32);
9782        constraints.clamp(Size::new(width, self.tab_height()))
9783    }
9784
9785    fn paint(&self, ctx: &mut PaintCtx) {
9786        let theme = self.resolved_theme();
9787        let palette = theme.palette;
9788        let interaction = theme.interaction;
9789        let selected_index = self.normalized_selected();
9790        let focus_progress = self.focus_animation.value;
9791
9792        let clip_outset = physical_pixels(
9793            ctx,
9794            theme.metrics.focus_ring_outset + (theme.metrics.focus_ring_width * 0.5),
9795        );
9796        ctx.push_clip_rect(ctx.bounds().inflate(clip_outset, clip_outset));
9797        for (index, tab) in self.tabs.iter().enumerate() {
9798            let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9799                continue;
9800            };
9801            let selected = selected_index == Some(index);
9802            let hovered = self.hovered.is_some_and(|hit| hit.index() == index);
9803            let pressed = self.pressed.is_some_and(|hit| hit.index() == index);
9804            let hover_amount = self.hover_amount_for(index);
9805            let press_amount = self.press_amount_for(index);
9806
9807            if let Some((background, border)) = tab_state_visuals(
9808                &theme,
9809                selected,
9810                hovered,
9811                pressed,
9812                hover_amount,
9813                press_amount,
9814            ) {
9815                draw_control_shape(
9816                    ctx,
9817                    rect,
9818                    theme.metrics.corner_radius,
9819                    physical_pixels(ctx, theme.metrics.border_width),
9820                    background,
9821                    border,
9822                );
9823            }
9824
9825            if selected && focus_progress > AnimatedScalar::EPSILON {
9826                draw_focus_ring_frame(
9827                    ctx,
9828                    rect,
9829                    theme.metrics.corner_radius,
9830                    theme.metrics,
9831                    palette
9832                        .focus_ring
9833                        .with_alpha(palette.focus_ring.alpha * focus_progress),
9834                );
9835            }
9836
9837            let text_style = text_token_style(
9838                &theme,
9839                theme.text.sm,
9840                if selected {
9841                    palette.text
9842                } else {
9843                    palette.text_muted
9844                },
9845            );
9846            let text_slot = self.label_rect_for(rect);
9847            let pressed_offset = press_amount * interaction.pressed_offset;
9848            ctx.push_clip_rect(text_slot);
9849            paint_aligned_text(
9850                ctx,
9851                text_slot.translate(Vector::new(0.0, pressed_offset)),
9852                tab,
9853                &text_style,
9854                text_style.line_height,
9855                0.0,
9856            );
9857            ctx.pop_clip();
9858
9859            let close = self.close_rect_for(rect);
9860            let close_hovered = self.hovered == Some(BrowserTabHit::Close(index));
9861            let close_pressed = self.pressed == Some(BrowserTabHit::Close(index));
9862            if close_hovered || close_pressed {
9863                ctx.fill(
9864                    rounded_rect_path(close, theme.metrics.corner_radius.min(5.0)),
9865                    if close_pressed {
9866                        palette.control_active
9867                    } else {
9868                        palette.control_hover
9869                    },
9870                );
9871            }
9872            draw_icon_glyph(
9873                ctx,
9874                IconGlyph::Close,
9875                close.inflate(-3.0, -3.0),
9876                if close_hovered || selected {
9877                    palette.text
9878                } else {
9879                    palette.placeholder
9880                }
9881                .with_alpha(if close_pressed { 0.95 } else { 0.78 }),
9882            );
9883        }
9884
9885        if let Some(selected) = selected_index {
9886            let progress = if self.selection_to == Some(selected) {
9887                self.selection_animation.value
9888            } else {
9889                1.0
9890            };
9891            if let Some(accent) = tab_indicator_rect(
9892                |index| self.tab_rect(ctx.bounds(), index),
9893                self.selection_from.unwrap_or(selected),
9894                selected,
9895                progress,
9896                theme.metrics.tab_padding,
9897                interaction.active_indicator_thickness,
9898            ) {
9899                ctx.fill(
9900                    rounded_rect_path(accent, accent.height() * 0.5),
9901                    palette.accent,
9902                );
9903            }
9904        }
9905        ctx.pop_clip();
9906    }
9907
9908    fn semantics(&self, ctx: &mut SemanticsCtx) {
9909        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TabBar, ctx.bounds());
9910        node.name = Some(self.name.clone());
9911        node.value = self
9912            .normalized_selected()
9913            .and_then(|index| self.tabs.get(index))
9914            .map(|value| SemanticsValue::Text(value.to_string()));
9915        node.state.focused = ctx.is_focused();
9916        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
9917        ctx.push(node);
9918
9919        for (index, tab) in self.tabs.iter().enumerate() {
9920            let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
9921                continue;
9922            };
9923            let tab_id = browser_tab_semantics_id(ctx.widget_id(), index);
9924            let mut tab_node = SemanticsNode::new(tab_id, SemanticsRole::Button, rect);
9925            tab_node.parent = Some(ctx.widget_id());
9926            tab_node.name = Some(tab.clone());
9927            tab_node.state.selected = self.normalized_selected() == Some(index);
9928            tab_node.state.hovered = self.hovered.is_some_and(|hit| hit.index() == index);
9929            tab_node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
9930            ctx.push(tab_node);
9931
9932            let mut close_node = SemanticsNode::new(
9933                browser_tab_close_semantics_id(ctx.widget_id(), index),
9934                SemanticsRole::Button,
9935                self.close_rect_for(rect),
9936            );
9937            close_node.parent = Some(tab_id);
9938            close_node.name = Some(format!("Close {tab} tab"));
9939            close_node.state.hovered = self.hovered == Some(BrowserTabHit::Close(index));
9940            close_node.actions = vec![SemanticsAction::Activate, SemanticsAction::Focus];
9941            ctx.push(close_node);
9942        }
9943    }
9944
9945    fn accepts_focus(&self) -> bool {
9946        true
9947    }
9948
9949    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
9950        let theme = self.resolved_theme();
9951        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
9952        ctx.request_paint();
9953        ctx.request_semantics();
9954    }
9955}
9956
9957fn browser_tab_semantics_id(parent: WidgetId, index: usize) -> WidgetId {
9958    const TAG: u64 = 3_u64 << 51;
9959    const LOW_MASK: u64 = (1_u64 << 51) - 1;
9960    WidgetId::new(
9961        TAG | (parent
9962            .get()
9963            .wrapping_mul(397)
9964            .wrapping_add(index as u64 + 1)
9965            & LOW_MASK),
9966    )
9967}
9968
9969fn browser_tab_close_semantics_id(parent: WidgetId, index: usize) -> WidgetId {
9970    const TAG: u64 = 3_u64 << 51;
9971    const LOW_MASK: u64 = (1_u64 << 51) - 1;
9972    WidgetId::new(
9973        TAG | (parent
9974            .get()
9975            .wrapping_mul(397)
9976            .wrapping_add(10_000 + index as u64)
9977            & LOW_MASK),
9978    )
9979}
9980
9981pub struct SegmentedControl {
9982    theme: Box<DefaultTheme>,
9983    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
9984    name: String,
9985    segments: Vec<SegmentedControlItem>,
9986    selected: usize,
9987    selected_reader: Option<Box<dyn Fn() -> Option<usize>>>,
9988    selection_from: usize,
9989    selection_animation: AnimatedScalar,
9990    hovered: Option<usize>,
9991    hover_visual: Option<usize>,
9992    pressed: Option<usize>,
9993    press_visual: Option<usize>,
9994    hover_animation: AnimatedScalar,
9995    press_animation: AnimatedScalar,
9996    focus_animation: AnimatedScalar,
9997    label_measurements: Vec<TextMeasurement>,
9998    on_change: Option<SegmentedControlChange>,
9999    on_change_with_ctx: Option<SegmentedControlContextChange>,
10000}
10001
10002pub struct SegmentedControlItem {
10003    label: String,
10004    semantic_name: Option<String>,
10005    description: Option<String>,
10006    disabled: bool,
10007}
10008
10009impl SegmentedControlItem {
10010    pub fn new(label: impl Into<String>) -> Self {
10011        Self {
10012            label: label.into(),
10013            semantic_name: None,
10014            description: None,
10015            disabled: false,
10016        }
10017    }
10018
10019    pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
10020        self.semantic_name = Some(name.into());
10021        self
10022    }
10023
10024    pub fn description(mut self, description: impl Into<String>) -> Self {
10025        self.description = Some(description.into());
10026        self
10027    }
10028
10029    pub fn disabled(mut self) -> Self {
10030        self.disabled = true;
10031        self
10032    }
10033
10034    pub fn label(&self) -> &str {
10035        &self.label
10036    }
10037}
10038
10039impl SegmentedControl {
10040    pub fn new(name: impl Into<String>) -> Self {
10041        Self {
10042            theme: Box::new(DefaultTheme::default()),
10043            theme_reader: None,
10044            name: name.into(),
10045            segments: Vec::new(),
10046            selected: 0,
10047            selected_reader: None,
10048            selection_from: 0,
10049            selection_animation: AnimatedScalar::new(1.0),
10050            hovered: None,
10051            hover_visual: None,
10052            pressed: None,
10053            press_visual: None,
10054            hover_animation: AnimatedScalar::new(0.0),
10055            press_animation: AnimatedScalar::new(0.0),
10056            focus_animation: AnimatedScalar::new(0.0),
10057            label_measurements: Vec::new(),
10058            on_change: None,
10059            on_change_with_ctx: None,
10060        }
10061    }
10062
10063    pub fn theme(mut self, theme: DefaultTheme) -> Self {
10064        self.theme = Box::new(theme);
10065        self.theme_reader = None;
10066        self
10067    }
10068
10069    pub fn theme_when<F>(mut self, theme: F) -> Self
10070    where
10071        F: Fn() -> DefaultTheme + 'static,
10072    {
10073        self.theme_reader = Some(Box::new(theme));
10074        self
10075    }
10076
10077    pub fn item(mut self, item: SegmentedControlItem) -> Self {
10078        self.segments.push(item);
10079        self
10080    }
10081
10082    pub fn items<I>(mut self, items: I) -> Self
10083    where
10084        I: IntoIterator<Item = SegmentedControlItem>,
10085    {
10086        self.segments.extend(items);
10087        self
10088    }
10089
10090    pub fn segments<I, S>(mut self, labels: I) -> Self
10091    where
10092        I: IntoIterator<Item = S>,
10093        S: Into<String>,
10094    {
10095        self.segments
10096            .extend(labels.into_iter().map(SegmentedControlItem::new));
10097        self
10098    }
10099
10100    pub fn selected(mut self, index: usize) -> Self {
10101        self.selected = index;
10102        self.selected_reader = None;
10103        self.selection_from = index;
10104        self.selection_animation = AnimatedScalar::new(1.0);
10105        self
10106    }
10107
10108    pub fn selected_when<F>(mut self, selected: F) -> Self
10109    where
10110        F: Fn() -> Option<usize> + 'static,
10111    {
10112        self.selected_reader = Some(Box::new(selected));
10113        self
10114    }
10115
10116    pub fn on_change<F>(mut self, on_change: F) -> Self
10117    where
10118        F: FnMut(usize, String) + 'static,
10119    {
10120        self.on_change = Some(Box::new(on_change));
10121        self
10122    }
10123
10124    pub fn on_change_with_ctx<F>(mut self, on_change: F) -> Self
10125    where
10126        F: FnMut(usize, String, &mut EventCtx) + 'static,
10127    {
10128        self.on_change_with_ctx = Some(Box::new(on_change));
10129        self
10130    }
10131
10132    pub fn selected_index(&self) -> usize {
10133        self.normalized_selected()
10134    }
10135
10136    fn normalized_selected(&self) -> usize {
10137        let selected = self
10138            .selected_reader
10139            .as_ref()
10140            .and_then(|reader| reader())
10141            .unwrap_or(self.selected);
10142        if self.segments.is_empty() {
10143            0
10144        } else {
10145            selected.min(self.segments.len() - 1)
10146        }
10147    }
10148
10149    fn segment_height(&self) -> f32 {
10150        self.resolved_theme().metrics.tab_height
10151    }
10152
10153    fn segment_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
10154        if index >= self.segments.len() {
10155            return None;
10156        }
10157        let count = self.segments.len().max(1);
10158        let width = bounds.width() / count as f32;
10159        let x = bounds.x() + width * index as f32;
10160        let width = if index + 1 == count {
10161            bounds.max_x() - x
10162        } else {
10163            width
10164        };
10165        Some(Rect::new(
10166            x,
10167            bounds.y(),
10168            width.max(0.0),
10169            bounds.height().max(0.0),
10170        ))
10171    }
10172
10173    fn segment_at(&self, bounds: Rect, position: Point) -> Option<usize> {
10174        if !bounds.contains(position) || self.segments.is_empty() {
10175            return None;
10176        }
10177        let slot_width = (bounds.width() / self.segments.len() as f32).max(1.0);
10178        let index = ((position.x - bounds.x()) / slot_width).floor() as usize;
10179        Some(index.min(self.segments.len() - 1))
10180    }
10181
10182    fn resolved_theme(&self) -> DefaultTheme {
10183        self.theme_reader
10184            .as_ref()
10185            .map(|theme| theme())
10186            .unwrap_or(*self.theme)
10187    }
10188
10189    fn activate(&mut self, index: usize, ctx: &mut EventCtx) {
10190        let Some(segment) = self.segments.get(index) else {
10191            return;
10192        };
10193        if segment.disabled {
10194            return;
10195        }
10196
10197        let index = index.min(self.segments.len() - 1);
10198        let selected = self.normalized_selected();
10199        if selected != index {
10200            let theme = self.resolved_theme();
10201            self.selection_from = selected;
10202            self.selected = index;
10203            self.selection_animation = AnimatedScalar::new(0.0);
10204            self.selection_animation.set_target_event(
10205                1.0,
10206                theme.motion.tab_switch_duration(),
10207                theme.motion.tab_switch_easing(),
10208                ctx,
10209            );
10210            let label = self.segments[index].label.clone();
10211            if let Some(on_change) = &mut self.on_change {
10212                on_change(index, label.clone());
10213            }
10214            if let Some(on_change) = &mut self.on_change_with_ctx {
10215                on_change(index, label, ctx);
10216            }
10217        }
10218    }
10219
10220    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
10221        if self.segments.is_empty() {
10222            return;
10223        }
10224        let selected = self.normalized_selected() as isize;
10225        let last = self.segments.len() as isize - 1;
10226        let next = (selected + delta).clamp(0, last) as usize;
10227        self.activate(next, ctx);
10228        self.set_hovered(Some(next), ctx);
10229    }
10230
10231    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
10232        if self.hovered == hovered {
10233            return;
10234        }
10235        let theme = self.resolved_theme();
10236        self.hovered = hovered;
10237        if let Some(index) = hovered {
10238            self.hover_visual = Some(index);
10239            self.hover_animation = AnimatedScalar::new(0.0);
10240            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
10241        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
10242            self.hover_visual = None;
10243        }
10244        ctx.request_paint();
10245        ctx.request_semantics();
10246    }
10247
10248    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
10249        if self.pressed == pressed {
10250            return;
10251        }
10252        let theme = self.resolved_theme();
10253        self.pressed = pressed;
10254        if let Some(index) = pressed {
10255            self.press_visual = Some(index);
10256            self.press_animation = AnimatedScalar::new(0.0);
10257            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
10258        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
10259            self.press_visual = None;
10260        }
10261        ctx.request_paint();
10262        ctx.request_semantics();
10263    }
10264
10265    fn hover_amount_for(&self, index: usize) -> f32 {
10266        if self.hover_visual == Some(index) {
10267            self.hover_animation.value
10268        } else {
10269            0.0
10270        }
10271    }
10272
10273    fn press_amount_for(&self, index: usize) -> f32 {
10274        if self.press_visual == Some(index) {
10275            self.press_animation.value
10276        } else {
10277            0.0
10278        }
10279    }
10280
10281    fn advance_animations(&mut self, time: f64) -> bool {
10282        let selection_animating = self.selection_animation.advance(time);
10283        let hover_animating = self.hover_animation.advance(time);
10284        if !hover_animating
10285            && self.hovered.is_none()
10286            && self.hover_animation.value <= AnimatedScalar::EPSILON
10287        {
10288            self.hover_visual = None;
10289        }
10290        let press_animating = self.press_animation.advance(time);
10291        if !press_animating
10292            && self.pressed.is_none()
10293            && self.press_animation.value <= AnimatedScalar::EPSILON
10294        {
10295            self.press_visual = None;
10296        }
10297        let focus_animating = self.focus_animation.advance(time);
10298        selection_animating | hover_animating | press_animating | focus_animating
10299    }
10300}
10301
10302impl Widget for SegmentedControl {
10303    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
10304        match event {
10305            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
10306                self.set_hovered(self.segment_at(ctx.bounds(), pointer.position), ctx);
10307            }
10308            Event::Pointer(pointer)
10309                if pointer.kind == PointerEventKind::Leave
10310                    || pointer.kind == PointerEventKind::Cancel =>
10311            {
10312                if pointer.kind == PointerEventKind::Cancel && self.pressed.is_some() {
10313                    ctx.release_pointer_capture(pointer.pointer_id);
10314                    ctx.set_handled();
10315                }
10316                self.set_pressed(None, ctx);
10317                self.set_hovered(None, ctx);
10318            }
10319            Event::Pointer(pointer)
10320                if pointer.kind == PointerEventKind::Down
10321                    && pointer.button == Some(PointerButton::Primary) =>
10322            {
10323                let hovered = self.segment_at(ctx.bounds(), pointer.position);
10324                self.set_hovered(hovered, ctx);
10325                self.set_pressed(hovered, ctx);
10326                ctx.request_focus();
10327                ctx.request_pointer_capture(pointer.pointer_id);
10328                ctx.set_handled();
10329            }
10330            Event::Pointer(pointer)
10331                if pointer.kind == PointerEventKind::Up
10332                    && pointer.button == Some(PointerButton::Primary) =>
10333            {
10334                let hovered = self.segment_at(ctx.bounds(), pointer.position);
10335                if let Some(index) = self
10336                    .pressed
10337                    .zip(hovered)
10338                    .filter(|(left, right)| left == right)
10339                    .map(|(index, _)| index)
10340                {
10341                    self.activate(index, ctx);
10342                }
10343                self.set_hovered(hovered, ctx);
10344                self.set_pressed(None, ctx);
10345                ctx.release_pointer_capture(pointer.pointer_id);
10346                ctx.set_handled();
10347            }
10348            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
10349                match key.key.as_str() {
10350                    "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
10351                    "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
10352                    "Home" => self.activate(0, ctx),
10353                    "End" if !self.segments.is_empty() => {
10354                        self.activate(self.segments.len() - 1, ctx)
10355                    }
10356                    _ => return,
10357                }
10358                ctx.request_paint();
10359                ctx.request_semantics();
10360                ctx.set_handled();
10361            }
10362            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
10363                if self.advance_animations(*time) {
10364                    ctx.request_animation_frame();
10365                }
10366                ctx.request_paint();
10367            }
10368            _ => {}
10369        }
10370    }
10371
10372    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
10373        let theme = self.resolved_theme();
10374        let style = theme.body_text_style();
10375        let padding = theme.metrics.tab_padding;
10376        self.label_measurements = self
10377            .segments
10378            .iter()
10379            .map(|segment| measure_text(ctx, &segment.label, &style))
10380            .collect();
10381        let widest = self
10382            .label_measurements
10383            .iter()
10384            .map(|measurement| measurement.width + padding.left + padding.right)
10385            .fold(theme.metrics.tab_min_width, f32::max);
10386        let width = widest * self.segments.len().max(1) as f32;
10387        constraints.clamp(Size::new(width.max(160.0), self.segment_height()))
10388    }
10389
10390    fn paint(&self, ctx: &mut PaintCtx) {
10391        let theme = self.resolved_theme();
10392        let palette = theme.palette;
10393        let metrics = theme.metrics;
10394        let interaction = theme.interaction;
10395        let padding = metrics.tab_padding;
10396        let label_style = TextStyle {
10397            font_size: theme.text.xs.size,
10398            line_height: theme.text.xs.line_height,
10399            weight: sui_text::FontWeight(theme.font_weights.semibold),
10400            color: palette.text_muted,
10401            ..theme.body_text_style()
10402        };
10403        let selected_label_style = TextStyle {
10404            color: palette.accent,
10405            ..label_style.clone()
10406        };
10407        let radius = metrics.corner_radius;
10408
10409        ctx.fill(rounded_rect_path(ctx.bounds(), radius), palette.control);
10410
10411        let selected_thumb = if !self.segments.is_empty() {
10412            let from = self.selection_from.min(self.segments.len() - 1);
10413            let selected = self.normalized_selected();
10414            let thumb = sliding_inset_rect(
10415                |index| self.segment_rect(ctx.bounds(), index),
10416                from,
10417                selected,
10418                self.selection_animation.value,
10419                Insets::all(2.0),
10420            );
10421            if let Some(thumb) = thumb {
10422                draw_control_shape(
10423                    ctx,
10424                    thumb,
10425                    (thumb.height() * 0.5).min(radius),
10426                    physical_pixels(ctx, metrics.border_width),
10427                    palette.selection,
10428                    palette.accent.with_alpha(0.36),
10429                );
10430            }
10431            thumb
10432        } else {
10433            None
10434        };
10435
10436        let focus_progress = self.focus_animation.value;
10437        for (index, segment) in self.segments.iter().enumerate() {
10438            let Some(rect) = self.segment_rect(ctx.bounds(), index) else {
10439                continue;
10440            };
10441            let selected = self.normalized_selected() == index;
10442            let hovered = self.hovered == Some(index);
10443            let pressed = self.pressed == Some(index);
10444            let hover_amount = self.hover_amount_for(index);
10445            let press_amount = self.press_amount_for(index);
10446
10447            if !selected
10448                && let Some((background, border)) =
10449                    tab_state_visuals(&theme, false, hovered, pressed, hover_amount, press_amount)
10450            {
10451                draw_control_shape(
10452                    ctx,
10453                    rect.inflate(-1.0, -1.0),
10454                    radius,
10455                    physical_pixels(ctx, metrics.border_width),
10456                    background,
10457                    border,
10458                );
10459            }
10460
10461            if selected && focus_progress > AnimatedScalar::EPSILON {
10462                let focus_bounds = selected_thumb.unwrap_or_else(|| rect.inflate(-2.0, -2.0));
10463                draw_focus_ring_frame(
10464                    ctx,
10465                    focus_bounds,
10466                    (focus_bounds.height() * 0.5).min(radius),
10467                    metrics,
10468                    palette
10469                        .focus_ring
10470                        .with_alpha(palette.focus_ring.alpha * focus_progress),
10471                );
10472            }
10473
10474            let text_style = if selected {
10475                selected_label_style.clone()
10476            } else {
10477                label_style.clone()
10478            };
10479            let text_slot = inset_rect(rect, padding);
10480            let pressed_offset = press_amount * interaction.pressed_offset;
10481            ctx.push_clip_rect(text_slot);
10482            paint_aligned_text(
10483                ctx,
10484                text_slot.translate(Vector::new(0.0, pressed_offset)),
10485                &segment.label,
10486                &text_style,
10487                text_style.line_height,
10488                0.5,
10489            );
10490            ctx.pop_clip();
10491        }
10492    }
10493
10494    fn semantics(&self, ctx: &mut SemanticsCtx) {
10495        let selected = self.normalized_selected();
10496        let value = self
10497            .segments
10498            .get(selected)
10499            .map(|segment| segment.label.clone());
10500        let mut group =
10501            SemanticsNode::new(ctx.widget_id(), SemanticsRole::RadioGroup, ctx.bounds());
10502        group.name = Some(self.name.clone());
10503        group.value = value.map(SemanticsValue::Text);
10504        group.state.focused = ctx.is_focused();
10505        group.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
10506        ctx.push(group);
10507
10508        for (index, segment) in self.segments.iter().enumerate() {
10509            let Some(bounds) = self.segment_rect(ctx.bounds(), index) else {
10510                continue;
10511            };
10512            let mut node = SemanticsNode::new(
10513                segmented_control_item_id(ctx.widget_id(), index),
10514                SemanticsRole::RadioButton,
10515                bounds,
10516            );
10517            node.parent = Some(ctx.widget_id());
10518            node.name = Some(
10519                segment
10520                    .semantic_name
10521                    .clone()
10522                    .unwrap_or_else(|| segment.label.clone()),
10523            );
10524            node.description = segment.description.clone();
10525            node.value = Some(SemanticsValue::Text(segment.label.clone()));
10526            node.actions = if segment.disabled {
10527                Vec::new()
10528            } else {
10529                vec![SemanticsAction::Activate]
10530            };
10531            node.state.disabled = segment.disabled;
10532            node.state.hovered = self.hovered == Some(index);
10533            node.state.selected = selected == index;
10534            node.state.checked = Some(if selected == index {
10535                sui_core::ToggleState::Checked
10536            } else {
10537                sui_core::ToggleState::Unchecked
10538            });
10539            ctx.push(node);
10540        }
10541    }
10542
10543    fn accepts_focus(&self) -> bool {
10544        true
10545    }
10546
10547    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
10548        let theme = self.resolved_theme();
10549        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
10550        ctx.request_paint();
10551        ctx.request_semantics();
10552    }
10553}
10554
10555pub struct Tabs {
10556    theme: Box<DefaultTheme>,
10557    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
10558    name: String,
10559    labels: Vec<String>,
10560    panels: WidgetChildren,
10561    selected: usize,
10562    selection_from: usize,
10563    selection_animation: AnimatedScalar,
10564    hovered: Option<usize>,
10565    hover_visual: Option<usize>,
10566    pressed: Option<usize>,
10567    press_visual: Option<usize>,
10568    hover_animation: AnimatedScalar,
10569    press_animation: AnimatedScalar,
10570    focus_animation: AnimatedScalar,
10571    label_measurements: Vec<TextMeasurement>,
10572    widths: Vec<f32>,
10573    gap: Option<f32>,
10574    panel_frame: Rect,
10575    on_change: Option<Box<dyn FnMut(usize, String)>>,
10576}
10577
10578impl Tabs {
10579    pub fn new(name: impl Into<String>) -> Self {
10580        Self {
10581            theme: Box::new(DefaultTheme::default()),
10582            theme_reader: None,
10583            name: name.into(),
10584            labels: Vec::new(),
10585            panels: WidgetChildren::new(),
10586            selected: 0,
10587            selection_from: 0,
10588            selection_animation: AnimatedScalar::new(1.0),
10589            hovered: None,
10590            hover_visual: None,
10591            pressed: None,
10592            press_visual: None,
10593            hover_animation: AnimatedScalar::new(0.0),
10594            press_animation: AnimatedScalar::new(0.0),
10595            focus_animation: AnimatedScalar::new(0.0),
10596            label_measurements: Vec::new(),
10597            widths: Vec::new(),
10598            gap: None,
10599            panel_frame: Rect::ZERO,
10600            on_change: None,
10601        }
10602    }
10603
10604    pub fn theme(mut self, theme: DefaultTheme) -> Self {
10605        self.theme = Box::new(theme);
10606        self.theme_reader = None;
10607        self
10608    }
10609
10610    pub fn theme_when<F>(mut self, theme: F) -> Self
10611    where
10612        F: Fn() -> DefaultTheme + 'static,
10613    {
10614        self.theme_reader = Some(Box::new(theme));
10615        self
10616    }
10617
10618    pub fn selected(mut self, index: usize) -> Self {
10619        self.selected = index;
10620        self.selection_from = index;
10621        self.selection_animation = AnimatedScalar::new(1.0);
10622        self
10623    }
10624
10625    pub fn on_change<F>(mut self, on_change: F) -> Self
10626    where
10627        F: FnMut(usize, String) + 'static,
10628    {
10629        self.on_change = Some(Box::new(on_change));
10630        self
10631    }
10632
10633    pub fn tab<W>(mut self, label: impl Into<String>, panel: W) -> Self
10634    where
10635        W: Widget + 'static,
10636    {
10637        self.labels.push(label.into());
10638        self.panels.push(panel);
10639        self
10640    }
10641
10642    pub fn selected_index(&self) -> usize {
10643        self.normalized_selected()
10644    }
10645
10646    pub fn current_tab(&self) -> Option<&str> {
10647        self.labels
10648            .get(self.normalized_selected())
10649            .map(String::as_str)
10650    }
10651
10652    fn normalized_selected(&self) -> usize {
10653        if self.labels.is_empty() {
10654            0
10655        } else {
10656            self.selected.min(self.labels.len() - 1)
10657        }
10658    }
10659
10660    fn header_height(&self) -> f32 {
10661        self.resolved_theme().metrics.tab_height
10662    }
10663
10664    fn resolved_gap(&self) -> f32 {
10665        self.gap
10666            .unwrap_or(self.resolved_theme().metrics.tab_gap)
10667            .max(0.0)
10668    }
10669
10670    fn header_rect(&self, bounds: Rect) -> Rect {
10671        Rect::new(bounds.x(), bounds.y(), bounds.width(), self.header_height())
10672    }
10673
10674    fn tab_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
10675        if index >= self.labels.len() || self.widths.len() != self.labels.len() {
10676            return None;
10677        }
10678
10679        let header = self.header_rect(bounds);
10680        let gap = self.resolved_gap();
10681        let base_total =
10682            self.widths.iter().sum::<f32>() + (gap * self.labels.len().saturating_sub(1) as f32);
10683        let extra_per_tab = if header.width() > base_total && !self.labels.is_empty() {
10684            (header.width() - base_total) / self.labels.len() as f32
10685        } else {
10686            0.0
10687        };
10688
10689        let mut x = header.x();
10690        for (current, width) in self.widths.iter().enumerate() {
10691            let rect = Rect::new(x, header.y(), *width + extra_per_tab, header.height());
10692            if current == index {
10693                return Some(rect);
10694            }
10695            x += rect.width() + gap;
10696        }
10697
10698        None
10699    }
10700
10701    fn tab_at(&self, bounds: Rect, position: Point) -> Option<usize> {
10702        self.labels.iter().enumerate().find_map(|(index, _)| {
10703            self.tab_rect(bounds, index)
10704                .filter(|rect| rect.contains(position))
10705                .map(|_| index)
10706        })
10707    }
10708
10709    fn select(&mut self, index: usize, ctx: &mut EventCtx) {
10710        if self.labels.is_empty() {
10711            return;
10712        }
10713
10714        let index = index.min(self.labels.len() - 1);
10715        if self.selected != index {
10716            let theme = self.resolved_theme();
10717            self.selection_from = self.normalized_selected();
10718            self.selected = index;
10719            self.selection_animation = AnimatedScalar::new(0.0);
10720            self.selection_animation.set_target_event(
10721                1.0,
10722                theme.motion.tab_switch_duration(),
10723                theme.motion.tab_switch_easing(),
10724                ctx,
10725            );
10726            if let Some(on_change) = &mut self.on_change {
10727                on_change(index, self.labels[index].clone());
10728            }
10729        }
10730    }
10731
10732    fn move_selection(&mut self, delta: isize, ctx: &mut EventCtx) {
10733        if self.labels.is_empty() {
10734            return;
10735        }
10736
10737        let next = (self.normalized_selected() as isize + delta)
10738            .clamp(0, self.labels.len() as isize - 1) as usize;
10739        self.set_hovered(Some(next), ctx);
10740        self.select(next, ctx);
10741    }
10742
10743    fn advance_animations(&mut self, time: f64) -> bool {
10744        let selection_animating = self.selection_animation.advance(time);
10745        let hover_animating = self.hover_animation.advance(time);
10746        if !hover_animating
10747            && self.hovered.is_none()
10748            && self.hover_animation.value <= AnimatedScalar::EPSILON
10749        {
10750            self.hover_visual = None;
10751        }
10752        let press_animating = self.press_animation.advance(time);
10753        if !press_animating
10754            && self.pressed.is_none()
10755            && self.press_animation.value <= AnimatedScalar::EPSILON
10756        {
10757            self.press_visual = None;
10758        }
10759        let focus_animating = self.focus_animation.advance(time);
10760        selection_animating | hover_animating | press_animating | focus_animating
10761    }
10762
10763    fn selected_panel(&self) -> Option<&sui_runtime::WidgetPod> {
10764        self.panels.as_slice().get(self.normalized_selected())
10765    }
10766
10767    fn selected_panel_mut(&mut self) -> Option<&mut sui_runtime::WidgetPod> {
10768        let index = self.normalized_selected();
10769        self.panels.as_mut_slice().get_mut(index)
10770    }
10771
10772    fn resolved_theme(&self) -> DefaultTheme {
10773        self.theme_reader
10774            .as_ref()
10775            .map(|theme| theme())
10776            .unwrap_or(*self.theme)
10777    }
10778
10779    fn set_hovered(&mut self, hovered: Option<usize>, ctx: &mut EventCtx) {
10780        if self.hovered == hovered {
10781            return;
10782        }
10783        let theme = self.resolved_theme();
10784        self.hovered = hovered;
10785        if let Some(index) = hovered {
10786            self.hover_visual = Some(index);
10787            self.hover_animation = AnimatedScalar::new(0.0);
10788            set_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
10789        } else if !set_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx) {
10790            self.hover_visual = None;
10791        }
10792        ctx.request_paint();
10793        ctx.request_semantics();
10794    }
10795
10796    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
10797        if self.pressed == pressed {
10798            return;
10799        }
10800        let theme = self.resolved_theme();
10801        self.pressed = pressed;
10802        if let Some(index) = pressed {
10803            self.press_visual = Some(index);
10804            self.press_animation = AnimatedScalar::new(0.0);
10805            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
10806        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
10807            self.press_visual = None;
10808        }
10809        ctx.request_paint();
10810        ctx.request_semantics();
10811    }
10812
10813    fn hover_amount_for(&self, index: usize) -> f32 {
10814        if self.hover_visual == Some(index) {
10815            self.hover_animation.value
10816        } else {
10817            0.0
10818        }
10819    }
10820
10821    fn press_amount_for(&self, index: usize) -> f32 {
10822        if self.press_visual == Some(index) {
10823            self.press_animation.value
10824        } else {
10825            0.0
10826        }
10827    }
10828}
10829
10830impl Widget for Tabs {
10831    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
10832        match event {
10833            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
10834                self.set_hovered(self.tab_at(ctx.bounds(), pointer.position), ctx);
10835            }
10836            Event::Pointer(_pointer) if matches!(_pointer.kind, PointerEventKind::Leave) => {
10837                self.set_hovered(None, ctx);
10838            }
10839            Event::Pointer(pointer)
10840                if pointer.kind == PointerEventKind::Down
10841                    && pointer.button == Some(PointerButton::Primary)
10842                    && self.header_rect(ctx.bounds()).contains(pointer.position) =>
10843            {
10844                let hovered = self.tab_at(ctx.bounds(), pointer.position);
10845                self.set_hovered(hovered, ctx);
10846                self.set_pressed(hovered, ctx);
10847                ctx.request_focus();
10848                ctx.request_pointer_capture(pointer.pointer_id);
10849                ctx.set_handled();
10850            }
10851            Event::Pointer(pointer)
10852                if pointer.kind == PointerEventKind::Up
10853                    && pointer.button == Some(PointerButton::Primary) =>
10854            {
10855                if self.pressed.is_some() {
10856                    let hovered = self.tab_at(ctx.bounds(), pointer.position);
10857                    if let Some(index) = self
10858                        .pressed
10859                        .zip(hovered)
10860                        .filter(|(left, right)| left == right)
10861                        .map(|(index, _)| index)
10862                    {
10863                        self.select(index, ctx);
10864                        ctx.request_measure();
10865                    }
10866                    self.set_hovered(hovered, ctx);
10867                    self.set_pressed(None, ctx);
10868                    ctx.release_pointer_capture(pointer.pointer_id);
10869                    ctx.set_handled();
10870                }
10871            }
10872            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
10873                if self.pressed.is_some() {
10874                    self.set_pressed(None, ctx);
10875                    self.set_hovered(None, ctx);
10876                    ctx.release_pointer_capture(pointer.pointer_id);
10877                    ctx.set_handled();
10878                }
10879            }
10880            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
10881                match key.key.as_str() {
10882                    "ArrowLeft" | "ArrowUp" => self.move_selection(-1, ctx),
10883                    "ArrowRight" | "ArrowDown" => self.move_selection(1, ctx),
10884                    "Home" => self.select(0, ctx),
10885                    "End" if !self.labels.is_empty() => self.select(self.labels.len() - 1, ctx),
10886                    _ => return,
10887                }
10888                ctx.request_measure();
10889                ctx.request_paint();
10890                ctx.request_semantics();
10891                ctx.set_handled();
10892            }
10893            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
10894                if self.advance_animations(*time) {
10895                    ctx.request_animation_frame();
10896                }
10897                ctx.request_paint();
10898            }
10899            _ => {}
10900        }
10901    }
10902
10903    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
10904        let theme = self.resolved_theme();
10905        let text_style = text_token_style(&theme, theme.text.sm, theme.palette.text);
10906        let tab_padding = theme.metrics.tab_padding;
10907        self.label_measurements = self
10908            .labels
10909            .iter()
10910            .map(|label| measure_text(ctx, label, &text_style))
10911            .collect();
10912        self.widths = self
10913            .label_measurements
10914            .iter()
10915            .map(|measurement| {
10916                (measurement.width + tab_padding.left + tab_padding.right)
10917                    .max(theme.metrics.tab_min_width)
10918            })
10919            .collect();
10920
10921        let gap = self.resolved_gap();
10922        let header_width =
10923            self.widths.iter().sum::<f32>() + (gap * self.labels.len().saturating_sub(1) as f32);
10924        let available_width = if constraints.max.width.is_finite() {
10925            constraints.max.width.max(header_width)
10926        } else {
10927            header_width.max(320.0)
10928        };
10929        let header_height = self.header_height();
10930        let padding = theme.metrics.tab_panel_padding;
10931        let panel_gap = theme.metrics.tab_panel_gap;
10932
10933        let panel_constraints = Constraints::new(
10934            Size::ZERO,
10935            Size::new(
10936                (available_width - padding.left - padding.right).max(0.0),
10937                if constraints.max.height.is_finite() {
10938                    (constraints.max.height
10939                        - header_height
10940                        - panel_gap
10941                        - padding.top
10942                        - padding.bottom)
10943                        .max(0.0)
10944                } else {
10945                    f32::INFINITY
10946                },
10947            ),
10948        );
10949
10950        let panel_size = if let Some(panel) = self.selected_panel_mut() {
10951            panel.measure(ctx, panel_constraints)
10952        } else {
10953            Size::new(0.0, theme.metrics.min_height)
10954        };
10955
10956        let content_width = (panel_size.width + padding.left + padding.right).max(available_width);
10957        let content_height = panel_size.height + padding.top + padding.bottom;
10958        self.panel_frame = Rect::new(
10959            0.0,
10960            header_height + panel_gap,
10961            content_width,
10962            content_height,
10963        );
10964
10965        constraints.clamp(Size::new(
10966            content_width,
10967            header_height + panel_gap + content_height,
10968        ))
10969    }
10970
10971    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
10972        let theme = self.resolved_theme();
10973        let header_height = self.header_height();
10974        let padding = theme.metrics.tab_panel_padding;
10975        let panel_gap = theme.metrics.tab_panel_gap;
10976        if let Some(panel) = self.selected_panel_mut() {
10977            let panel_size = panel.measured_size();
10978            panel.arrange(
10979                ctx,
10980                Rect::new(
10981                    bounds.x() + padding.left,
10982                    bounds.y() + header_height + panel_gap + padding.top,
10983                    panel_size.width,
10984                    panel_size.height,
10985                ),
10986            );
10987        }
10988    }
10989
10990    fn paint(&self, ctx: &mut PaintCtx) {
10991        let theme = self.resolved_theme();
10992        let palette = theme.palette;
10993        let metrics = theme.metrics;
10994        let interaction = theme.interaction;
10995        let tab_padding = metrics.tab_padding;
10996        let header = self.header_rect(ctx.bounds());
10997        let label_style = text_token_style(&theme, theme.text.sm, palette.text_muted);
10998        let selected_label_style = text_token_style(&theme, theme.text.sm, palette.text);
10999
11000        ctx.fill(
11001            rounded_rect_path(header, metrics.corner_radius),
11002            palette.control,
11003        );
11004
11005        let focus_progress = self.focus_animation.value;
11006        for (index, label) in self.labels.iter().enumerate() {
11007            let Some(rect) = self.tab_rect(ctx.bounds(), index) else {
11008                continue;
11009            };
11010            let selected = self.normalized_selected() == index;
11011            let hovered = self.hovered == Some(index);
11012            let pressed = self.pressed == Some(index);
11013            let hover_amount = self.hover_amount_for(index);
11014            let press_amount = self.press_amount_for(index);
11015
11016            if let Some((background, border)) = tab_state_visuals(
11017                &theme,
11018                selected,
11019                hovered,
11020                pressed,
11021                hover_amount,
11022                press_amount,
11023            ) {
11024                draw_control_shape(
11025                    ctx,
11026                    rect,
11027                    metrics.corner_radius,
11028                    physical_pixels(ctx, metrics.border_width),
11029                    background,
11030                    border,
11031                );
11032            }
11033
11034            if selected && focus_progress > AnimatedScalar::EPSILON {
11035                draw_focus_ring_frame(
11036                    ctx,
11037                    rect,
11038                    metrics.corner_radius,
11039                    metrics,
11040                    palette
11041                        .focus_ring
11042                        .with_alpha(palette.focus_ring.alpha * focus_progress),
11043                );
11044            }
11045
11046            let text_style = if selected {
11047                selected_label_style.clone()
11048            } else {
11049                label_style.clone()
11050            };
11051            let text_slot = inset_rect(rect, tab_padding);
11052            let pressed_offset = press_amount * interaction.pressed_offset;
11053            ctx.push_clip_rect(text_slot);
11054            paint_aligned_text(
11055                ctx,
11056                text_slot.translate(Vector::new(0.0, pressed_offset)),
11057                label,
11058                &text_style,
11059                text_style.line_height,
11060                0.5,
11061            );
11062            ctx.pop_clip();
11063        }
11064
11065        if let Some(accent) = tab_indicator_rect(
11066            |index| self.tab_rect(ctx.bounds(), index),
11067            self.selection_from,
11068            self.normalized_selected(),
11069            self.selection_animation.value,
11070            tab_padding,
11071            interaction.active_indicator_thickness,
11072        ) {
11073            ctx.fill(
11074                rounded_rect_path(accent, accent.height() * 0.5),
11075                palette.accent,
11076            );
11077        }
11078
11079        let content = self.panel_frame.translate(ctx.bounds().origin.to_vector());
11080        draw_control_frame(
11081            ctx,
11082            content,
11083            metrics.corner_radius + 2.0,
11084            metrics,
11085            palette.surface_raised,
11086            palette.border,
11087            None,
11088        );
11089        if let Some(panel) = self.selected_panel() {
11090            let panel_translation = tab_panel_transition_translation(
11091                self.selection_from,
11092                self.normalized_selected(),
11093                self.selection_animation.value,
11094                metrics,
11095            );
11096            if panel_translation == Vector::ZERO {
11097                panel.paint(ctx);
11098            } else {
11099                ctx.push_clip_rect(content);
11100                ctx.translate(panel_translation);
11101                panel.paint(ctx);
11102                ctx.pop_transform();
11103                ctx.pop_clip();
11104            }
11105        }
11106    }
11107
11108    fn semantics(&self, ctx: &mut SemanticsCtx) {
11109        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Tabs, ctx.bounds());
11110        node.name = Some(self.name.clone());
11111        node.value = self
11112            .current_tab()
11113            .map(|value| SemanticsValue::Text(value.to_string()));
11114        node.state.focused = ctx.is_focused();
11115        node.actions = vec![SemanticsAction::Focus, SemanticsAction::SetValue];
11116        ctx.push(node);
11117        if let Some(panel) = self.selected_panel() {
11118            panel.semantics(ctx);
11119        }
11120    }
11121
11122    fn accepts_focus(&self) -> bool {
11123        true
11124    }
11125
11126    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
11127        let theme = self.resolved_theme();
11128        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
11129        ctx.request_paint();
11130        ctx.request_semantics();
11131    }
11132
11133    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
11134        if let Some(panel) = self.selected_panel() {
11135            visitor.visit(panel);
11136        }
11137    }
11138
11139    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
11140        if let Some(panel) = self.selected_panel_mut() {
11141            visitor.visit(panel);
11142        }
11143    }
11144}
11145
11146pub struct Menu {
11147    theme: Box<DefaultTheme>,
11148    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
11149    name: String,
11150    items: Vec<MenuItem>,
11151    highlighted: Option<usize>,
11152    highlight_visual: Option<usize>,
11153    pressed: Option<usize>,
11154    press_visual: Option<usize>,
11155    highlight_animation: AnimatedScalar,
11156    press_animation: AnimatedScalar,
11157    focus_animation: AnimatedScalar,
11158    measured_width: f32,
11159    focus_on_pointer_down: bool,
11160    on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
11161    on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
11162}
11163
11164impl Menu {
11165    pub fn new(name: impl Into<String>) -> Self {
11166        Self {
11167            theme: Box::new(DefaultTheme::default()),
11168            theme_reader: None,
11169            name: name.into(),
11170            items: Vec::new(),
11171            highlighted: None,
11172            highlight_visual: None,
11173            pressed: None,
11174            press_visual: None,
11175            highlight_animation: AnimatedScalar::new(0.0),
11176            press_animation: AnimatedScalar::new(0.0),
11177            focus_animation: AnimatedScalar::new(0.0),
11178            measured_width: 220.0,
11179            focus_on_pointer_down: true,
11180            on_activate: None,
11181            on_activate_with_ctx: None,
11182        }
11183    }
11184
11185    pub fn theme(mut self, theme: DefaultTheme) -> Self {
11186        self.theme = Box::new(theme);
11187        self.theme_reader = None;
11188        self
11189    }
11190
11191    pub fn theme_when<F>(mut self, theme: F) -> Self
11192    where
11193        F: Fn() -> DefaultTheme + 'static,
11194    {
11195        self.theme_reader = Some(Box::new(theme));
11196        self
11197    }
11198
11199    pub fn item(mut self, item: MenuItem) -> Self {
11200        self.items.push(item);
11201        self
11202    }
11203
11204    pub fn items<I>(mut self, items: I) -> Self
11205    where
11206        I: IntoIterator<Item = MenuItem>,
11207    {
11208        self.items.extend(items);
11209        self
11210    }
11211
11212    pub fn highlighted(mut self, index: usize) -> Self {
11213        self.highlighted = Some(index);
11214        self.highlight_visual = Some(index);
11215        self.highlight_animation = AnimatedScalar::new(1.0);
11216        self
11217    }
11218
11219    pub fn on_activate<F>(mut self, on_activate: F) -> Self
11220    where
11221        F: FnMut(usize, MenuItem) + 'static,
11222    {
11223        self.on_activate = Some(Box::new(on_activate));
11224        self
11225    }
11226
11227    pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
11228    where
11229        F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
11230    {
11231        self.on_activate_with_ctx = Some(Box::new(on_activate));
11232        self
11233    }
11234
11235    pub fn focus_on_pointer_down(mut self, focus_on_pointer_down: bool) -> Self {
11236        self.focus_on_pointer_down = focus_on_pointer_down;
11237        self
11238    }
11239
11240    fn row_height(&self) -> f32 {
11241        let theme = self.resolved_theme();
11242        menu_row_height(&theme)
11243    }
11244
11245    fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
11246        let Some(item) = self.items.get(index).cloned() else {
11247            return;
11248        };
11249        if !item.enabled {
11250            return;
11251        }
11252        match (&mut self.on_activate, &mut self.on_activate_with_ctx) {
11253            (Some(on_activate), _) => on_activate(index, item),
11254            (None, Some(on_activate)) => on_activate(ctx, index, item),
11255            (None, None) => {}
11256        }
11257    }
11258
11259    fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
11260        if index >= self.items.len() {
11261            return None;
11262        }
11263        let theme = self.resolved_theme();
11264        let padding = theme.metrics.menu_padding;
11265        let x = bounds.x() + padding.left;
11266        let y = bounds.y() + padding.top + (index as f32 * self.row_height());
11267        Some(Rect::new(
11268            x,
11269            y,
11270            (bounds.width() - padding.left - padding.right).max(0.0),
11271            self.row_height(),
11272        ))
11273    }
11274
11275    fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
11276        self.items.iter().enumerate().find_map(|(index, _)| {
11277            self.item_rect(bounds, index)
11278                .filter(|rect| rect.contains(position))
11279                .map(|_| index)
11280        })
11281    }
11282
11283    fn move_highlight(&mut self, delta: isize, ctx: &mut EventCtx) {
11284        if self.items.is_empty() {
11285            return;
11286        }
11287
11288        let len = self.items.len() as isize;
11289        let start = self.highlighted.unwrap_or(0) as isize;
11290        let mut index = (start + delta).clamp(0, len - 1);
11291        while !self.items[index as usize].enabled {
11292            let next = (index + delta).clamp(0, len - 1);
11293            if next == index {
11294                break;
11295            }
11296            index = next;
11297        }
11298        self.set_highlighted(Some(index as usize), ctx);
11299    }
11300
11301    fn resolved_theme(&self) -> DefaultTheme {
11302        self.theme_reader
11303            .as_ref()
11304            .map(|theme| theme())
11305            .unwrap_or(*self.theme)
11306    }
11307
11308    fn set_highlighted(&mut self, highlighted: Option<usize>, ctx: &mut EventCtx) {
11309        if self.highlighted == highlighted {
11310            return;
11311        }
11312        let theme = self.resolved_theme();
11313        self.highlighted = highlighted;
11314        if let Some(index) = highlighted {
11315            self.highlight_visual = Some(index);
11316            self.highlight_animation = AnimatedScalar::new(0.0);
11317            set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
11318        } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
11319            self.highlight_visual = None;
11320        }
11321        ctx.request_paint();
11322        ctx.request_semantics();
11323    }
11324
11325    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
11326        if self.pressed == pressed {
11327            return;
11328        }
11329        let theme = self.resolved_theme();
11330        self.pressed = pressed;
11331        if let Some(index) = pressed {
11332            self.press_visual = Some(index);
11333            self.press_animation = AnimatedScalar::new(0.0);
11334            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
11335        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
11336            self.press_visual = None;
11337        }
11338        ctx.request_paint();
11339        ctx.request_semantics();
11340    }
11341
11342    fn highlight_amount_for(&self, index: usize) -> f32 {
11343        if self.highlight_visual == Some(index) {
11344            self.highlight_animation.value
11345        } else {
11346            0.0
11347        }
11348    }
11349
11350    fn press_amount_for(&self, index: usize) -> f32 {
11351        if self.press_visual == Some(index) {
11352            self.press_animation.value
11353        } else {
11354            0.0
11355        }
11356    }
11357
11358    fn advance_animations(&mut self, time: f64) -> bool {
11359        let highlight_animating = self.highlight_animation.advance(time);
11360        if !highlight_animating
11361            && self.highlighted.is_none()
11362            && self.highlight_animation.value <= AnimatedScalar::EPSILON
11363        {
11364            self.highlight_visual = None;
11365        }
11366
11367        let press_animating = self.press_animation.advance(time);
11368        if !press_animating
11369            && self.pressed.is_none()
11370            && self.press_animation.value <= AnimatedScalar::EPSILON
11371        {
11372            self.press_visual = None;
11373        }
11374
11375        highlight_animating | press_animating | self.focus_animation.advance(time)
11376    }
11377}
11378
11379impl Widget for Menu {
11380    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
11381        match event {
11382            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
11383                self.set_highlighted(self.item_at(ctx.bounds(), pointer.position), ctx);
11384            }
11385            Event::Pointer(pointer)
11386                if pointer.kind == PointerEventKind::Down
11387                    && pointer.button == Some(PointerButton::Primary) =>
11388            {
11389                let highlighted = self.item_at(ctx.bounds(), pointer.position);
11390                self.set_highlighted(highlighted, ctx);
11391                self.set_pressed(
11392                    highlighted
11393                        .filter(|index| self.items.get(*index).is_some_and(|item| item.enabled)),
11394                    ctx,
11395                );
11396                if self.focus_on_pointer_down {
11397                    ctx.request_focus();
11398                }
11399                ctx.request_pointer_capture(pointer.pointer_id);
11400                ctx.set_handled();
11401            }
11402            Event::Pointer(pointer)
11403                if pointer.kind == PointerEventKind::Up
11404                    && pointer.button == Some(PointerButton::Primary) =>
11405            {
11406                let highlighted = self.item_at(ctx.bounds(), pointer.position);
11407                if let Some(index) = self
11408                    .pressed
11409                    .zip(highlighted)
11410                    .filter(|(left, right)| left == right)
11411                    .map(|(index, _)| index)
11412                {
11413                    self.activate(ctx, index);
11414                }
11415                self.set_highlighted(highlighted, ctx);
11416                self.set_pressed(None, ctx);
11417                ctx.release_pointer_capture(pointer.pointer_id);
11418                ctx.set_handled();
11419            }
11420            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
11421                if self.pressed.is_some() {
11422                    self.set_pressed(None, ctx);
11423                    ctx.release_pointer_capture(pointer.pointer_id);
11424                    ctx.set_handled();
11425                }
11426            }
11427            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
11428                match key.key.as_str() {
11429                    "ArrowDown" => self.move_highlight(1, ctx),
11430                    "ArrowUp" => self.move_highlight(-1, ctx),
11431                    "Home" => {
11432                        self.set_highlighted(self.items.iter().position(|item| item.enabled), ctx);
11433                    }
11434                    "End" => {
11435                        self.set_highlighted(self.items.iter().rposition(|item| item.enabled), ctx);
11436                    }
11437                    "Enter" | " " => {
11438                        if let Some(index) = self.highlighted {
11439                            self.activate(ctx, index);
11440                        }
11441                    }
11442                    _ => return,
11443                }
11444                ctx.request_paint();
11445                ctx.request_semantics();
11446                ctx.set_handled();
11447            }
11448            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
11449                if self.advance_animations(*time) {
11450                    ctx.request_animation_frame();
11451                }
11452                ctx.request_paint();
11453            }
11454            _ => {}
11455        }
11456    }
11457
11458    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
11459        let theme = self.resolved_theme();
11460        let label_style = theme.body_text_style();
11461        let shortcut_style = theme.placeholder_text_style();
11462        let mut width: f32 = 0.0;
11463        for item in &self.items {
11464            let label = measure_text(ctx, item.label(), &label_style).width;
11465            let shortcut = item
11466                .shortcut
11467                .as_ref()
11468                .map(|text| measure_text(ctx, text, &shortcut_style).width)
11469                .unwrap_or(0.0);
11470            width = width.max(
11471                label
11472                    + shortcut
11473                    + theme.metrics.menu_item_padding.left
11474                    + theme.metrics.menu_item_padding.right
11475                    + theme.metrics.menu_shortcut_width,
11476            );
11477        }
11478        self.measured_width = width.max(220.0);
11479        let height = themed_menu_height_for_rows(&theme, self.row_height(), self.items.len());
11480        constraints.clamp(Size::new(
11481            self.measured_width,
11482            height.max(themed_menu_height_for_rows(&theme, self.row_height(), 1)),
11483        ))
11484    }
11485
11486    fn paint(&self, ctx: &mut PaintCtx) {
11487        let theme = self.resolved_theme();
11488        let palette = theme.palette;
11489        let metrics = theme.metrics;
11490        let interaction = theme.interaction;
11491        let item_padding = metrics.menu_item_padding;
11492
11493        // Cast an elevation shadow behind the raised menu surface before any
11494        // fill so the soft drop shadow is not clipped by the frame.
11495        let surface_radius = metrics.corner_radius + 2.0;
11496        paint_theme_shadow(
11497            ctx,
11498            ctx.bounds(),
11499            [surface_radius; 4],
11500            &theme.shadows.box_shadow.lg,
11501        );
11502
11503        draw_control_frame(
11504            ctx,
11505            ctx.bounds(),
11506            surface_radius,
11507            metrics,
11508            palette.surface_raised,
11509            palette.border,
11510            (self.focus_animation.value > AnimatedScalar::EPSILON).then_some(
11511                palette
11512                    .focus_ring
11513                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
11514            ),
11515        );
11516
11517        for (index, item) in self.items.iter().enumerate() {
11518            let Some(row) = self.item_rect(ctx.bounds(), index) else {
11519                continue;
11520            };
11521
11522            if item.separator_before {
11523                let line = Rect::new(
11524                    row.x(),
11525                    row.y() - (metrics.menu_padding.top * 0.5),
11526                    row.width(),
11527                    1.0,
11528                );
11529                ctx.fill(rounded_rect_path(line, 0.5), palette.border);
11530            }
11531
11532            let highlighted = self.highlighted == Some(index);
11533            let highlight_amount = self.highlight_amount_for(index);
11534            let press_amount = self.press_amount_for(index);
11535            let label_style = theme.text_style(item.text_color(&theme));
11536            let label_slot = Rect::new(
11537                row.x() + item_padding.left,
11538                row.y(),
11539                (row.width()
11540                    - item_padding.left
11541                    - item_padding.right
11542                    - item
11543                        .shortcut
11544                        .as_ref()
11545                        .map(|_| metrics.menu_shortcut_width)
11546                        .unwrap_or(0.0))
11547                .max(0.0),
11548                row.height(),
11549            );
11550            if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
11551                let highlight_background = mix_color(
11552                    palette.control,
11553                    palette.accent,
11554                    interaction.selected_blend * highlight_amount,
11555                );
11556                let background = if press_amount > 0.0 {
11557                    mix_color(
11558                        highlight_background,
11559                        palette.control_active,
11560                        interaction.pressed_blend * press_amount,
11561                    )
11562                } else {
11563                    highlight_background
11564                };
11565                ctx.fill(
11566                    rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
11567                    background,
11568                );
11569            }
11570
11571            ctx.push_clip_rect(label_slot);
11572            paint_aligned_text(
11573                ctx,
11574                label_slot,
11575                &item.label,
11576                &label_style,
11577                label_style.line_height,
11578                0.0,
11579            );
11580            ctx.pop_clip();
11581
11582            if let Some(shortcut) = &item.shortcut {
11583                let shortcut_style = theme.placeholder_text_style();
11584                let shortcut_slot = Rect::new(
11585                    row.max_x() - item_padding.right - metrics.menu_shortcut_width,
11586                    row.y(),
11587                    metrics.menu_shortcut_width,
11588                    row.height(),
11589                );
11590                ctx.push_clip_rect(shortcut_slot);
11591                paint_aligned_text(
11592                    ctx,
11593                    shortcut_slot,
11594                    shortcut,
11595                    &shortcut_style,
11596                    shortcut_style.line_height,
11597                    1.0,
11598                );
11599                ctx.pop_clip();
11600            }
11601        }
11602    }
11603
11604    fn semantics(&self, ctx: &mut SemanticsCtx) {
11605        let state = SemanticsState {
11606            focused: ctx.is_focused(),
11607            ..SemanticsState::default()
11608        };
11609        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Menu, ctx.bounds());
11610        node.name = Some(self.name.clone());
11611        node.state = state;
11612        node.value = self
11613            .highlighted
11614            .and_then(|index| self.items.get(index))
11615            .map(|item| SemanticsValue::Text(item.label.clone()));
11616        node.actions = vec![
11617            SemanticsAction::Focus,
11618            SemanticsAction::SetValue,
11619            SemanticsAction::Activate,
11620        ];
11621        ctx.push(node);
11622        for (index, item) in self.items.iter().enumerate() {
11623            let Some(row) = self.item_rect(ctx.bounds(), index) else {
11624                continue;
11625            };
11626            ctx.push(menu_item_semantics_node(
11627                ctx.widget_id(),
11628                index,
11629                item,
11630                row,
11631                self.highlighted == Some(index),
11632            ));
11633        }
11634    }
11635
11636    fn accepts_focus(&self) -> bool {
11637        true
11638    }
11639
11640    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
11641        let theme = self.resolved_theme();
11642        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
11643        ctx.request_paint();
11644        ctx.request_semantics();
11645    }
11646}
11647
11648type AnimatedScalar = MotionScalar;
11649
11650fn request_child_invalidation(ctx: &mut EventCtx, widget_id: WidgetId, kind: InvalidationKind) {
11651    ctx.request(InvalidationRequest::new(
11652        InvalidationTarget::Widget(widget_id),
11653        kind,
11654    ));
11655}
11656
11657fn tooltip_fallback_measurement(theme: &DefaultTheme) -> TextMeasurement {
11658    TextMeasurement {
11659        width: 120.0,
11660        height: theme.typography.body_line_height,
11661        bounds: Rect::new(0.0, 0.0, 120.0, theme.typography.body_line_height),
11662        ascent: theme.typography.body_font_size,
11663        descent: 0.0,
11664        cap_height: Some(theme.typography.body_font_size),
11665    }
11666}
11667
11668fn tooltip_bubble_rect(
11669    trigger_bounds: Rect,
11670    measurement: Option<TextMeasurement>,
11671    theme: &DefaultTheme,
11672    placement: TooltipPlacement,
11673    alignment: TooltipAlignment,
11674    viewport: Rect,
11675) -> (Rect, TooltipPlacement) {
11676    let measurement = measurement.unwrap_or_else(|| tooltip_fallback_measurement(theme));
11677    let padding = theme.metrics.tooltip_padding;
11678    let width =
11679        (measurement.width + padding.left + padding.right).max(theme.metrics.tooltip_min_width);
11680    let height =
11681        measurement.height.max(theme.typography.body_line_height) + padding.top + padding.bottom;
11682    let side = match placement {
11683        TooltipPlacement::Above => OverlaySide::Top,
11684        TooltipPlacement::Below => OverlaySide::Bottom,
11685    };
11686    let alignment = match alignment {
11687        TooltipAlignment::Start => OverlayAlignment::Start,
11688        TooltipAlignment::Center => OverlayAlignment::Center,
11689        TooltipAlignment::End => OverlayAlignment::End,
11690    };
11691    let result = place_overlay(
11692        &OverlayPlacementRequest::new(
11693            trigger_bounds,
11694            Size::new(width, height),
11695            viewport,
11696            OverlayPlacement::new(side, alignment),
11697        )
11698        .gap(theme.metrics.tooltip_gap)
11699        .margin(theme.metrics.tooltip_gap.max(4.0)),
11700    );
11701    let resolved = if result.placement.side == OverlaySide::Top {
11702        TooltipPlacement::Above
11703    } else {
11704        TooltipPlacement::Below
11705    };
11706    (result.bounds, resolved)
11707}
11708
11709#[derive(Debug, Clone)]
11710struct TooltipPresentationState {
11711    theme: DefaultTheme,
11712    text: String,
11713    placement: TooltipPlacement,
11714    resolved_placement: TooltipPlacement,
11715    alignment: TooltipAlignment,
11716    measurement: Option<TextMeasurement>,
11717    hovered: bool,
11718    trigger_bounds: Rect,
11719    bubble_bounds: Rect,
11720    reveal: AnimatedScalar,
11721}
11722
11723impl TooltipPresentationState {
11724    fn new(text: String) -> Self {
11725        Self {
11726            theme: DefaultTheme::default(),
11727            text,
11728            placement: TooltipPlacement::Above,
11729            resolved_placement: TooltipPlacement::Above,
11730            alignment: TooltipAlignment::Center,
11731            measurement: None,
11732            hovered: false,
11733            trigger_bounds: Rect::ZERO,
11734            bubble_bounds: Rect::ZERO,
11735            reveal: AnimatedScalar::new(0.0),
11736        }
11737    }
11738
11739    fn is_presented(&self) -> bool {
11740        self.reveal.is_presented()
11741    }
11742
11743    fn layer_properties(&self) -> LayerProperties {
11744        let direction = match self.resolved_placement {
11745            TooltipPlacement::Above => -1.0,
11746            TooltipPlacement::Below => 1.0,
11747        };
11748        LayerProperties {
11749            opacity: self.reveal.value,
11750            translation: Vector::new(
11751                0.0,
11752                self.theme.metrics.tooltip_reveal_offset * (1.0 - self.reveal.value) * direction,
11753            ),
11754        }
11755    }
11756}
11757
11758struct TooltipOverlay {
11759    state: Rc<RefCell<TooltipPresentationState>>,
11760}
11761
11762impl TooltipOverlay {
11763    fn new(state: Rc<RefCell<TooltipPresentationState>>) -> Self {
11764        Self { state }
11765    }
11766}
11767
11768impl Widget for TooltipOverlay {
11769    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
11770        let state = self.state.borrow();
11771        if !state.is_presented() {
11772            return Size::ZERO;
11773        }
11774        state.bubble_bounds.size
11775    }
11776
11777    fn arrange(&mut self, _ctx: &mut ArrangeCtx, bounds: Rect) {
11778        self.state.borrow_mut().bubble_bounds = bounds;
11779    }
11780
11781    fn paint(&self, ctx: &mut PaintCtx) {
11782        let state = self.state.borrow();
11783        if !state.is_presented() {
11784            return;
11785        }
11786
11787        let bubble = ctx.bounds();
11788        let metrics = state.theme.metrics;
11789        // Soft elevation behind the tooltip bubble, drawn before the fill.
11790        paint_theme_shadow(
11791            ctx,
11792            bubble,
11793            [metrics.corner_radius; 4],
11794            &state.theme.shadows.box_shadow.sm,
11795        );
11796        draw_control_frame(
11797            ctx,
11798            bubble,
11799            metrics.corner_radius,
11800            metrics,
11801            state.theme.surfaces.tooltip,
11802            state.theme.surfaces.tooltip_border,
11803            None,
11804        );
11805        let tail = tooltip_tail(state.trigger_bounds, bubble, state.resolved_placement);
11806        ctx.fill(tail, state.theme.surfaces.tooltip);
11807        let text_style = text_token_style(
11808            &state.theme,
11809            state.theme.text.sm,
11810            state.theme.surfaces.tooltip_text,
11811        );
11812        let text_slot = inset_rect(bubble, metrics.tooltip_padding);
11813        ctx.push_clip_rect(text_slot);
11814        paint_aligned_text(
11815            ctx,
11816            text_slot,
11817            &state.text,
11818            &text_style,
11819            text_style.line_height,
11820            0.0,
11821        );
11822        ctx.pop_clip();
11823    }
11824
11825    fn layer_options(&self) -> LayerOptions {
11826        let presented = self.state.borrow().is_presented();
11827        LayerOptions {
11828            paint_boundary: PaintBoundaryMode::Explicit,
11829            composition_mode: if presented {
11830                LayerCompositionMode::Overlay
11831            } else {
11832                LayerCompositionMode::Normal
11833            },
11834        }
11835    }
11836
11837    fn layer_properties(&self) -> LayerProperties {
11838        self.state.borrow().layer_properties()
11839    }
11840
11841    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
11842        self.state
11843            .borrow()
11844            .is_presented()
11845            .then_some(StackSurfaceOptions {
11846                transient: true,
11847                hit_test: false,
11848                ..StackSurfaceOptions::default()
11849            })
11850    }
11851}
11852
11853pub struct Tooltip {
11854    child: SingleChild,
11855    overlay: SingleChild,
11856    state: Rc<RefCell<TooltipPresentationState>>,
11857}
11858
11859impl Tooltip {
11860    pub fn new<W>(text: impl Into<String>, child: W) -> Self
11861    where
11862        W: Widget + 'static,
11863    {
11864        let state = Rc::new(RefCell::new(TooltipPresentationState::new(text.into())));
11865        Self {
11866            child: SingleChild::new(child),
11867            overlay: SingleChild::new(TooltipOverlay::new(Rc::clone(&state))),
11868            state,
11869        }
11870    }
11871
11872    pub fn theme(self, theme: DefaultTheme) -> Self {
11873        self.state.borrow_mut().theme = theme;
11874        self
11875    }
11876
11877    pub fn placement(self, placement: TooltipPlacement) -> Self {
11878        self.state.borrow_mut().placement = placement;
11879        self
11880    }
11881
11882    pub fn alignment(self, alignment: TooltipAlignment) -> Self {
11883        self.state.borrow_mut().alignment = alignment;
11884        self
11885    }
11886
11887    fn set_hovered(&mut self, ctx: &mut EventCtx, hovered: bool) {
11888        let overlay_id = self.overlay.child().id();
11889        let mut state = self.state.borrow_mut();
11890        if state.hovered == hovered {
11891            return;
11892        }
11893        let was_presented = state.is_presented();
11894        let motion = state.theme.motion;
11895        state.hovered = hovered;
11896        let should_animate = state.reveal.set_target(
11897            hovered as u8 as f32,
11898            ctx.current_time(),
11899            motion.entrance_duration(),
11900            motion.entrance_easing(),
11901        );
11902        let is_presented = state.is_presented();
11903        drop(state);
11904
11905        if was_presented != is_presented {
11906            ctx.request_measure();
11907            request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
11908        }
11909        if should_animate {
11910            ctx.request_animation_frame();
11911        }
11912        ctx.request_semantics();
11913    }
11914}
11915
11916impl Widget for Tooltip {
11917    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
11918        match event {
11919            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
11920                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11921            }
11922            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
11923                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11924            }
11925            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
11926                self.set_hovered(ctx, ctx.bounds().contains(pointer.position));
11927            }
11928            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
11929                let overlay_id = self.overlay.child().id();
11930                let mut state = self.state.borrow_mut();
11931                let was_presented = state.is_presented();
11932                let previous = state.reveal.value;
11933                let animating = state.reveal.advance(*time);
11934                let changed = state.reveal.changed_since(previous);
11935                let is_presented = state.is_presented();
11936                drop(state);
11937
11938                if changed {
11939                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Transform);
11940                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Effect);
11941                }
11942                if was_presented != is_presented {
11943                    ctx.request_measure();
11944                    request_child_invalidation(ctx, overlay_id, InvalidationKind::Visibility);
11945                }
11946                if animating {
11947                    ctx.request_animation_frame();
11948                }
11949                ctx.set_handled();
11950            }
11951            _ => {}
11952        }
11953    }
11954
11955    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
11956        let mut state = self.state.borrow_mut();
11957        let text_style = text_token_style(
11958            &state.theme,
11959            state.theme.text.sm,
11960            state.theme.surfaces.tooltip_text,
11961        );
11962        state.measurement = Some(measure_text(ctx, &state.text, &text_style));
11963        drop(state);
11964        self.child.measure(ctx, constraints)
11965    }
11966
11967    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
11968        let trigger_bounds =
11969            Rect::from_origin_size(bounds.origin, self.child.child().measured_size());
11970        self.child.arrange(ctx, trigger_bounds);
11971
11972        let mut state = self.state.borrow_mut();
11973        state.trigger_bounds = trigger_bounds;
11974        let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
11975        let (bubble_bounds, resolved_placement) = tooltip_bubble_rect(
11976            trigger_bounds,
11977            state.measurement,
11978            &state.theme,
11979            state.placement,
11980            state.alignment,
11981            viewport,
11982        );
11983        state.bubble_bounds = bubble_bounds;
11984        state.resolved_placement = resolved_placement;
11985        let overlay_bounds = if state.is_presented() {
11986            state.bubble_bounds
11987        } else {
11988            Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
11989        };
11990        drop(state);
11991        self.overlay.arrange(ctx, overlay_bounds);
11992    }
11993
11994    fn paint(&self, ctx: &mut PaintCtx) {
11995        self.child.paint(ctx);
11996        self.overlay.paint(ctx);
11997    }
11998
11999    fn overlay_options(&self) -> Option<OverlayOptions> {
12000        self.state.borrow().is_presented().then_some(
12001            OverlayOptions::new(OverlayKind::Tooltip)
12002                .dismiss(OverlayDismissPolicy::NONE)
12003                .focus(OverlayFocusBehavior::NONE),
12004        )
12005    }
12006
12007    fn semantics(&self, ctx: &mut SemanticsCtx) {
12008        self.child.semantics(ctx);
12009        let state = self.state.borrow();
12010        if state.hovered {
12011            let mut node =
12012                SemanticsNode::new(ctx.widget_id(), SemanticsRole::Tooltip, state.bubble_bounds);
12013            node.name = Some(state.text.clone());
12014            ctx.push(node);
12015        }
12016    }
12017
12018    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12019        self.child.visit_children(visitor);
12020        if self.state.borrow().is_presented() {
12021            self.overlay.visit_children(visitor);
12022        }
12023    }
12024
12025    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12026        self.child.visit_children_mut(visitor);
12027        if self.state.borrow().is_presented() {
12028            self.overlay.visit_children_mut(visitor);
12029        }
12030    }
12031}
12032
12033#[derive(Debug, Clone, Copy, PartialEq)]
12034struct PopoverVisuals {
12035    background: Color,
12036    border: Color,
12037    focus_ring: Option<Color>,
12038    surface_style: Option<ResolvedHdrStyle>,
12039    arrival_effect: Option<ResolvedEffectStyle>,
12040}
12041
12042#[derive(Debug, Clone)]
12043struct PopoverSurfaceState {
12044    theme: DefaultTheme,
12045    frame_rect: Rect,
12046    arrival_active: bool,
12047    reveal: AnimatedScalar,
12048    focus_animation: AnimatedScalar,
12049}
12050
12051impl PopoverSurfaceState {
12052    fn new() -> Self {
12053        Self {
12054            theme: DefaultTheme::default(),
12055            frame_rect: Rect::ZERO,
12056            arrival_active: false,
12057            reveal: AnimatedScalar::new(0.0),
12058            focus_animation: AnimatedScalar::new(0.0),
12059        }
12060    }
12061
12062    fn is_presented(&self) -> bool {
12063        self.reveal.is_presented()
12064    }
12065
12066    fn arrival_duration(&self) -> f64 {
12067        (0.18 / self.theme.hdr.effects.pulse.speed.max(0.25) as f64).clamp(0.10, 0.28)
12068    }
12069
12070    fn layer_properties(&self) -> LayerProperties {
12071        LayerProperties {
12072            opacity: self.reveal.value,
12073            translation: Vector::new(
12074                0.0,
12075                -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
12076            ),
12077        }
12078    }
12079
12080    fn resolved_visuals(&self) -> PopoverVisuals {
12081        let palette = self.theme.palette;
12082
12083        if !self.is_presented() || matches!(self.theme.hdr.mode, HdrThemeMode::Disabled) {
12084            return PopoverVisuals {
12085                background: palette.surface_raised,
12086                border: palette.border,
12087                focus_ring: Some(palette.focus_ring),
12088                surface_style: None,
12089                arrival_effect: None,
12090            };
12091        }
12092
12093        let surface_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
12094            &self.theme.hdr,
12095            WidgetColorRole::SurfaceElevated,
12096            WidgetLuminanceRole::Standard,
12097            WidgetMaterialRole::Raised,
12098            self.arrival_active.then_some(WidgetEffectRole::Pulse),
12099        ));
12100        let border_style = cap_resolved_hdr_style(resolve_widget_hdr_style(
12101            &self.theme.hdr,
12102            WidgetColorRole::SurfaceOutline,
12103            WidgetLuminanceRole::Standard,
12104            WidgetMaterialRole::Flat,
12105            None,
12106        ));
12107
12108        PopoverVisuals {
12109            background: surface_style.color,
12110            border: border_style.color,
12111            focus_ring: Some(border_style.color.with_alpha(palette.focus_ring.alpha)),
12112            surface_style: Some(surface_style),
12113            arrival_effect: surface_style.effect,
12114        }
12115    }
12116}
12117
12118struct PopoverSurface {
12119    content: SingleChild,
12120    state: Rc<RefCell<PopoverSurfaceState>>,
12121}
12122
12123impl PopoverSurface {
12124    fn new<C>(state: Rc<RefCell<PopoverSurfaceState>>, content: C) -> Self
12125    where
12126        C: Widget + 'static,
12127    {
12128        Self {
12129            content: SingleChild::new(content),
12130            state,
12131        }
12132    }
12133}
12134
12135impl Widget for PopoverSurface {
12136    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
12137        let state = self.state.borrow();
12138        if !state.is_presented() {
12139            return Size::ZERO;
12140        }
12141        let padding = state.theme.metrics.popover_padding;
12142        drop(state);
12143
12144        let content_constraints = Constraints::new(
12145            Size::ZERO,
12146            Size::new(
12147                if constraints.max.width.is_finite() {
12148                    (constraints.max.width - padding.left - padding.right).max(0.0)
12149                } else {
12150                    f32::INFINITY
12151                },
12152                if constraints.max.height.is_finite() {
12153                    (constraints.max.height - padding.top - padding.bottom).max(0.0)
12154                } else {
12155                    f32::INFINITY
12156                },
12157            ),
12158        );
12159        let content_size = self.content.measure(ctx, content_constraints);
12160        Size::new(
12161            content_size.width + padding.left + padding.right,
12162            content_size.height + padding.top + padding.bottom,
12163        )
12164    }
12165
12166    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
12167        let state = self.state.borrow();
12168        if !state.is_presented() {
12169            drop(state);
12170            self.content
12171                .arrange(ctx, Rect::from_origin_size(bounds.origin, Size::ZERO));
12172            return;
12173        }
12174        let padding = state.theme.metrics.popover_padding;
12175        drop(state);
12176        let content_size = self.content.child().measured_size();
12177        self.content.arrange(
12178            ctx,
12179            Rect::new(
12180                bounds.x() + padding.left,
12181                bounds.y() + padding.top,
12182                content_size.width,
12183                content_size.height,
12184            ),
12185        );
12186    }
12187
12188    fn paint(&self, ctx: &mut PaintCtx) {
12189        let state = self.state.borrow();
12190        if !state.is_presented() {
12191            return;
12192        }
12193
12194        let rect = ctx.bounds();
12195        let metrics = state.theme.metrics;
12196        let visuals = state.resolved_visuals();
12197        // Elevation shadow behind the popover surface, drawn before the fill.
12198        let surface_radius = metrics.corner_radius + 2.0;
12199        paint_theme_shadow(
12200            ctx,
12201            rect,
12202            [surface_radius; 4],
12203            &state.theme.shadows.box_shadow.md,
12204        );
12205        draw_control_frame(
12206            ctx,
12207            rect,
12208            surface_radius,
12209            metrics,
12210            visuals.background,
12211            visuals.border,
12212            None,
12213        );
12214        if let Some(arrival_effect) = visuals.arrival_effect {
12215            draw_popover_arrival_overlay(
12216                ctx,
12217                rect,
12218                metrics,
12219                visuals.background,
12220                visuals.border,
12221                arrival_effect,
12222            );
12223        }
12224        drop(state);
12225        self.content.paint(ctx);
12226    }
12227
12228    fn layer_options(&self) -> LayerOptions {
12229        let presented = self.state.borrow().is_presented();
12230        LayerOptions {
12231            paint_boundary: PaintBoundaryMode::Explicit,
12232            composition_mode: if presented {
12233                LayerCompositionMode::Overlay
12234            } else {
12235                LayerCompositionMode::Normal
12236            },
12237        }
12238    }
12239
12240    fn layer_properties(&self) -> LayerProperties {
12241        self.state.borrow().layer_properties()
12242    }
12243
12244    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
12245        self.state
12246            .borrow()
12247            .is_presented()
12248            .then_some(StackSurfaceOptions {
12249                transient: true,
12250                ..StackSurfaceOptions::default()
12251            })
12252    }
12253
12254    fn semantics(&self, ctx: &mut SemanticsCtx) {
12255        self.content.semantics(ctx);
12256    }
12257
12258    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12259        self.content.visit_children(visitor);
12260    }
12261
12262    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12263        self.content.visit_children_mut(visitor);
12264    }
12265}
12266
12267struct PopoverFocusSurface {
12268    state: Rc<RefCell<PopoverSurfaceState>>,
12269}
12270
12271impl PopoverFocusSurface {
12272    fn new(state: Rc<RefCell<PopoverSurfaceState>>) -> Self {
12273        Self { state }
12274    }
12275}
12276
12277impl Widget for PopoverFocusSurface {
12278    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
12279        let state = self.state.borrow();
12280        if state.is_presented() {
12281            state.frame_rect.size
12282        } else {
12283            Size::ZERO
12284        }
12285    }
12286
12287    fn paint(&self, ctx: &mut PaintCtx) {
12288        let state = self.state.borrow();
12289        if !state.is_presented() || !state.focus_animation.is_presented() {
12290            return;
12291        }
12292
12293        let Some(focus_ring) = state.resolved_visuals().focus_ring else {
12294            return;
12295        };
12296        let progress = state.focus_animation.value;
12297        if progress <= AnimatedScalar::EPSILON {
12298            return;
12299        }
12300
12301        let metrics = state.theme.metrics;
12302        draw_focus_ring_frame(
12303            ctx,
12304            ctx.bounds(),
12305            metrics.corner_radius + 2.0,
12306            metrics,
12307            focus_ring.with_alpha(focus_ring.alpha * progress),
12308        );
12309    }
12310
12311    fn layer_options(&self) -> LayerOptions {
12312        LayerOptions {
12313            paint_boundary: PaintBoundaryMode::Explicit,
12314            composition_mode: LayerCompositionMode::Normal,
12315        }
12316    }
12317
12318    fn layer_properties(&self) -> LayerProperties {
12319        self.state.borrow().layer_properties()
12320    }
12321
12322    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
12323        let state = self.state.borrow();
12324        (state.is_presented() && state.focus_animation.is_presented()).then_some(
12325            StackSurfaceOptions {
12326                transient: true,
12327                hit_test: false,
12328                ..StackSurfaceOptions::default()
12329            },
12330        )
12331    }
12332}
12333
12334#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12335pub enum PopoverAlignment {
12336    #[default]
12337    Start,
12338    End,
12339}
12340
12341pub struct Popover {
12342    name: String,
12343    trigger: SingleChild,
12344    surface: SingleChild,
12345    focus_surface: SingleChild,
12346    open: bool,
12347    open_reader: Option<Box<dyn Fn() -> bool>>,
12348    on_open_change: Option<Box<dyn FnMut(bool)>>,
12349    alignment: PopoverAlignment,
12350    gap: f32,
12351    arrival_timer: Option<TimerToken>,
12352    state: Rc<RefCell<PopoverSurfaceState>>,
12353}
12354
12355impl Popover {
12356    pub fn new<T, C>(name: impl Into<String>, trigger: T, content: C) -> Self
12357    where
12358        T: Widget + 'static,
12359        C: Widget + 'static,
12360    {
12361        let state = Rc::new(RefCell::new(PopoverSurfaceState::new()));
12362        Self {
12363            name: name.into(),
12364            trigger: SingleChild::new(trigger),
12365            surface: SingleChild::new(PopoverSurface::new(Rc::clone(&state), content)),
12366            focus_surface: SingleChild::new(PopoverFocusSurface::new(Rc::clone(&state))),
12367            open: false,
12368            open_reader: None,
12369            on_open_change: None,
12370            alignment: PopoverAlignment::Start,
12371            gap: DefaultTheme::default().metrics.popover_gap,
12372            arrival_timer: None,
12373            state,
12374        }
12375    }
12376
12377    pub fn theme(mut self, theme: DefaultTheme) -> Self {
12378        self.gap = theme.metrics.popover_gap;
12379        self.state.borrow_mut().theme = theme;
12380        self
12381    }
12382
12383    pub fn open(mut self, open: bool) -> Self {
12384        self.open = open;
12385        self.open_reader = None;
12386        {
12387            let mut state = self.state.borrow_mut();
12388            state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
12389        }
12390        self
12391    }
12392
12393    pub fn open_when<F>(mut self, open: F) -> Self
12394    where
12395        F: Fn() -> bool + 'static,
12396    {
12397        self.open_reader = Some(Box::new(open));
12398        self
12399    }
12400
12401    pub fn on_open_change<F>(mut self, on_open_change: F) -> Self
12402    where
12403        F: FnMut(bool) + 'static,
12404    {
12405        self.on_open_change = Some(Box::new(on_open_change));
12406        self
12407    }
12408
12409    /// Aligns a narrower trigger and surface within the popover's measured
12410    /// width. End alignment keeps title-bar and trailing toolbar triggers
12411    /// anchored while a wider surface opens beneath them.
12412    pub fn alignment(mut self, alignment: PopoverAlignment) -> Self {
12413        self.alignment = alignment;
12414        self
12415    }
12416
12417    fn sync_external_open(&mut self) {
12418        let Some(open) = self.open_reader.as_ref().map(|open| open()) else {
12419            return;
12420        };
12421        if self.open == open {
12422            return;
12423        }
12424        self.open = open;
12425        let mut state = self.state.borrow_mut();
12426        state.reveal = AnimatedScalar::new(if open { 1.0 } else { 0.0 });
12427        state.arrival_active = false;
12428    }
12429
12430    fn start_arrival(&mut self, ctx: &mut EventCtx) {
12431        if let Some(token) = self.arrival_timer.take() {
12432            ctx.cancel_timer(token);
12433        }
12434
12435        let mut state = self.state.borrow_mut();
12436        state.arrival_active = !matches!(state.theme.hdr.mode, HdrThemeMode::Disabled)
12437            && state.theme.hdr.effects.pulse.intensity > 0.0;
12438        if state.arrival_active {
12439            self.arrival_timer = Some(ctx.schedule_timer_after(state.arrival_duration()));
12440        }
12441    }
12442
12443    fn stop_arrival(&mut self, ctx: &mut EventCtx) {
12444        self.state.borrow_mut().arrival_active = false;
12445        if let Some(token) = self.arrival_timer.take() {
12446            ctx.cancel_timer(token);
12447        }
12448    }
12449
12450    fn trigger_rect(&self) -> Rect {
12451        self.trigger.child().bounds()
12452    }
12453
12454    fn content_rect(&self) -> Rect {
12455        self.state.borrow().frame_rect
12456    }
12457
12458    fn is_inside_open_regions(&self, position: Point) -> bool {
12459        self.trigger_rect().contains(position)
12460            || (self.open && self.content_rect().contains(position))
12461    }
12462
12463    fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
12464        if self.open == open {
12465            return;
12466        }
12467
12468        if open {
12469            self.start_arrival(ctx);
12470        } else {
12471            self.stop_arrival(ctx);
12472        }
12473
12474        self.open = open;
12475        if let Some(on_open_change) = &mut self.on_open_change {
12476            on_open_change(open);
12477        }
12478        let surface_id = self.surface.child().id();
12479        let focus_surface_id = self.focus_surface.child().id();
12480        let mut state = self.state.borrow_mut();
12481        let was_presented = state.is_presented();
12482        let motion = state.theme.motion;
12483        let should_animate = state.reveal.set_target(
12484            open as u8 as f32,
12485            ctx.current_time(),
12486            motion.entrance_duration(),
12487            motion.entrance_easing(),
12488        );
12489        let is_presented = state.is_presented();
12490        drop(state);
12491
12492        if open || was_presented != is_presented {
12493            ctx.request_measure();
12494            request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
12495            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12496        }
12497        if should_animate {
12498            ctx.request_animation_frame();
12499        }
12500        ctx.request_semantics();
12501    }
12502}
12503
12504impl Widget for Popover {
12505    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
12506        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
12507            self.set_open(ctx, false);
12508            ctx.set_handled();
12509        }
12510    }
12511
12512    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
12513        match event {
12514            Event::Pointer(pointer)
12515                if pointer.kind == PointerEventKind::Down
12516                    && pointer.button == Some(PointerButton::Primary)
12517                    && self.trigger_rect().contains(pointer.position) =>
12518            {
12519                let next = !self.open;
12520                self.set_open(ctx, next);
12521                ctx.request_focus();
12522                ctx.set_handled();
12523            }
12524            Event::Pointer(pointer)
12525                if pointer.kind == PointerEventKind::Down
12526                    && pointer.button == Some(PointerButton::Primary)
12527                    && self.open
12528                    && !self.is_inside_open_regions(pointer.position) =>
12529            {
12530                self.set_open(ctx, false);
12531            }
12532            Event::Keyboard(key)
12533                if ctx.is_focused()
12534                    && key.state == KeyState::Pressed
12535                    && key.key == "Escape"
12536                    && self.open =>
12537            {
12538                self.set_open(ctx, false);
12539                ctx.set_handled();
12540            }
12541            Event::Keyboard(key)
12542                if ctx.is_focused()
12543                    && key.state == KeyState::Pressed
12544                    && matches!(key.key.as_str(), "Enter" | " ") =>
12545            {
12546                self.set_open(ctx, !self.open);
12547                ctx.set_handled();
12548            }
12549            Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
12550                let open = match semantics.action {
12551                    sui_core::SemanticsActionRequest::Expand => Some(true),
12552                    sui_core::SemanticsActionRequest::Collapse => Some(false),
12553                    _ => None,
12554                };
12555                if let Some(open) = open {
12556                    self.set_open(ctx, open);
12557                    ctx.set_handled();
12558                }
12559            }
12560            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
12561                let surface_id = self.surface.child().id();
12562                let focus_surface_id = self.focus_surface.child().id();
12563                let mut state = self.state.borrow_mut();
12564                let was_presented = state.is_presented();
12565                let was_focus_presented = state.focus_animation.is_presented();
12566                let previous_reveal = state.reveal.value;
12567                let previous_focus = state.focus_animation.value;
12568                let reveal_animating = state.reveal.advance(*time);
12569                let focus_animating = state.focus_animation.advance(*time);
12570                let reveal_changed = state.reveal.changed_since(previous_reveal);
12571                let focus_changed = state.focus_animation.changed_since(previous_focus);
12572                let is_presented = state.is_presented();
12573                let is_focus_presented = state.focus_animation.is_presented();
12574                drop(state);
12575
12576                if reveal_changed {
12577                    request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
12578                    request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
12579                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
12580                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
12581                }
12582                if focus_changed {
12583                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
12584                }
12585                if was_presented != is_presented {
12586                    ctx.request_measure();
12587                    request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
12588                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12589                }
12590                if was_focus_presented != is_focus_presented {
12591                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12592                }
12593                if reveal_animating || focus_animating {
12594                    ctx.request_animation_frame();
12595                }
12596                ctx.set_handled();
12597            }
12598            Event::Wake(WakeEvent::Timer { token, .. }) if self.arrival_timer == Some(*token) => {
12599                self.arrival_timer = None;
12600                let surface_id = self.surface.child().id();
12601                let mut state = self.state.borrow_mut();
12602                if state.arrival_active {
12603                    state.arrival_active = false;
12604                    drop(state);
12605                    request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
12606                } else {
12607                    drop(state);
12608                }
12609                ctx.set_handled();
12610            }
12611            _ => {}
12612        }
12613    }
12614
12615    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
12616        self.sync_external_open();
12617        let trigger_size = self.trigger.measure(ctx, constraints.loosen());
12618        // A popover's trigger belongs to its parent's layout, but its surface belongs to the
12619        // window overlay stack. In particular, toolbar and title-bar slots are commonly tight to
12620        // the trigger; reusing those constraints for the surface collapses a wide panel into that
12621        // narrow slot. Measure the overlay against the viewport instead and keep it out of the
12622        // parent's reported size.
12623        let viewport = ctx.dpi().viewport;
12624        let viewport_margin = self.gap.max(4.0);
12625        let surface_max = Size::new(
12626            if viewport.width > 0.0 {
12627                (viewport.width - viewport_margin * 2.0).max(0.0)
12628            } else {
12629                f32::INFINITY
12630            },
12631            if viewport.height > 0.0 {
12632                (viewport.height - viewport_margin * 2.0).max(0.0)
12633            } else {
12634                f32::INFINITY
12635            },
12636        );
12637        let surface_size = self
12638            .surface
12639            .measure(ctx, Constraints::new(Size::ZERO, surface_max));
12640        let presented = self.state.borrow().is_presented();
12641        let focus_size = if presented { surface_size } else { Size::ZERO };
12642        self.focus_surface
12643            .measure(ctx, Constraints::tight(focus_size));
12644        constraints.clamp(trigger_size)
12645    }
12646
12647    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
12648        let trigger_size = self.trigger.child().measured_size();
12649        let aligned_x = |width: f32| match self.alignment {
12650            PopoverAlignment::Start => bounds.x(),
12651            PopoverAlignment::End => bounds.max_x() - width,
12652        };
12653        let trigger_bounds = Rect::new(
12654            aligned_x(trigger_size.width),
12655            bounds.y(),
12656            trigger_size.width,
12657            trigger_size.height,
12658        );
12659        self.trigger.arrange(ctx, trigger_bounds);
12660
12661        let presented = self.state.borrow().is_presented();
12662        let surface_bounds = if presented {
12663            let surface_size = self.surface.child().measured_size();
12664            let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
12665            let margin = self.gap.max(4.0);
12666            let width = surface_size.width.max(trigger_size.width);
12667            let alignment = match self.alignment {
12668                PopoverAlignment::Start => OverlayAlignment::Start,
12669                PopoverAlignment::End => OverlayAlignment::End,
12670            };
12671            place_overlay(
12672                &OverlayPlacementRequest::new(
12673                    trigger_bounds,
12674                    Size::new(width, surface_size.height),
12675                    viewport,
12676                    OverlayPlacement::new(OverlaySide::Bottom, alignment),
12677                )
12678                .fallbacks([OverlayPlacement::new(OverlaySide::Top, alignment)])
12679                .gap(self.gap)
12680                .margin(margin),
12681            )
12682            .bounds
12683        } else {
12684            Rect::from_origin_size(trigger_bounds.origin, Size::ZERO)
12685        };
12686        self.state.borrow_mut().frame_rect = surface_bounds;
12687        self.surface.arrange(ctx, surface_bounds);
12688        self.focus_surface.arrange(ctx, surface_bounds);
12689    }
12690
12691    fn paint(&self, ctx: &mut PaintCtx) {
12692        self.trigger.paint(ctx);
12693        if self.state.borrow().is_presented() {
12694            self.surface.paint(ctx);
12695            self.focus_surface.paint(ctx);
12696        }
12697    }
12698
12699    fn semantics(&self, ctx: &mut SemanticsCtx) {
12700        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Popover, ctx.bounds());
12701        node.name = Some(self.name.clone());
12702        node.state.focused = ctx.is_focused();
12703        node.state.expanded = Some(self.open);
12704        node.popup = Some(SemanticsPopupKind::Dialog);
12705        node.actions = vec![
12706            SemanticsAction::Focus,
12707            SemanticsAction::Expand,
12708            SemanticsAction::Collapse,
12709        ];
12710        ctx.push(node);
12711        self.trigger.semantics(ctx);
12712        if self.open {
12713            self.surface.semantics(ctx);
12714        }
12715    }
12716
12717    fn accepts_focus(&self) -> bool {
12718        true
12719    }
12720
12721    fn overlay_options(&self) -> Option<OverlayOptions> {
12722        (self.open || self.state.borrow().is_presented()).then_some(
12723            OverlayOptions::new(OverlayKind::Popover)
12724                .dismiss(if self.open {
12725                    OverlayDismissPolicy::TRANSIENT
12726                } else {
12727                    OverlayDismissPolicy::NONE
12728                })
12729                .focus(OverlayFocusBehavior::NONE),
12730        )
12731    }
12732
12733    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
12734        let focus_surface_id = self.focus_surface.child().id();
12735        let mut state = self.state.borrow_mut();
12736        let was_focus_presented = state.focus_animation.is_presented();
12737        let theme = state.theme;
12738        set_focus_animation_target(
12739            &mut state.focus_animation,
12740            focused as u8 as f32,
12741            &theme,
12742            ctx,
12743        );
12744        let is_focus_presented = state.focus_animation.is_presented();
12745        drop(state);
12746
12747        if was_focus_presented != is_focus_presented {
12748            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
12749        }
12750        request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
12751        if !focused && self.open {
12752            self.set_open(ctx, false);
12753        }
12754        ctx.request_semantics();
12755    }
12756
12757    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
12758        self.trigger.visit_children(visitor);
12759        if self.open || self.state.borrow().is_presented() {
12760            self.surface.visit_children(visitor);
12761            self.focus_surface.visit_children(visitor);
12762        }
12763    }
12764
12765    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
12766        self.trigger.visit_children_mut(visitor);
12767        if self.open || self.state.borrow().is_presented() {
12768            self.surface.visit_children_mut(visitor);
12769            self.focus_surface.visit_children_mut(visitor);
12770        }
12771    }
12772}
12773
12774#[derive(Debug, Clone)]
12775struct ContextMenuPresentationState {
12776    theme: DefaultTheme,
12777    items: Vec<MenuItem>,
12778    highlighted: Option<usize>,
12779    highlight_visual: Option<usize>,
12780    pressed: Option<usize>,
12781    press_visual: Option<usize>,
12782    frame_rect: Rect,
12783    row_height: f32,
12784    reveal: AnimatedScalar,
12785    focus_animation: AnimatedScalar,
12786    highlight_animation: AnimatedScalar,
12787    press_animation: AnimatedScalar,
12788}
12789
12790impl ContextMenuPresentationState {
12791    fn new() -> Self {
12792        let theme = DefaultTheme::default();
12793        Self {
12794            theme,
12795            items: Vec::new(),
12796            highlighted: None,
12797            highlight_visual: None,
12798            pressed: None,
12799            press_visual: None,
12800            frame_rect: Rect::ZERO,
12801            row_height: menu_row_height(&theme),
12802            reveal: AnimatedScalar::new(0.0),
12803            focus_animation: AnimatedScalar::new(0.0),
12804            highlight_animation: AnimatedScalar::new(0.0),
12805            press_animation: AnimatedScalar::new(0.0),
12806        }
12807    }
12808
12809    fn is_presented(&self) -> bool {
12810        self.reveal.is_presented()
12811    }
12812
12813    fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
12814        if index >= self.items.len() {
12815            return None;
12816        }
12817        let padding = self.theme.metrics.menu_padding;
12818        let x = bounds.x() + padding.left;
12819        let y = bounds.y() + padding.top + (index as f32 * self.row_height);
12820        Some(Rect::new(
12821            x,
12822            y,
12823            (bounds.width() - padding.left - padding.right).max(0.0),
12824            self.row_height,
12825        ))
12826    }
12827
12828    fn layer_properties(&self) -> LayerProperties {
12829        LayerProperties {
12830            opacity: self.reveal.value,
12831            translation: Vector::new(
12832                0.0,
12833                -self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
12834            ),
12835        }
12836    }
12837
12838    fn highlight_amount_for(&self, index: usize) -> f32 {
12839        if self.highlight_visual == Some(index) {
12840            self.highlight_animation.value
12841        } else {
12842            0.0
12843        }
12844    }
12845
12846    fn press_amount_for(&self, index: usize) -> f32 {
12847        if self.press_visual == Some(index) {
12848            self.press_animation.value
12849        } else {
12850            0.0
12851        }
12852    }
12853}
12854
12855struct ContextMenuSurface {
12856    state: Rc<RefCell<ContextMenuPresentationState>>,
12857}
12858
12859impl ContextMenuSurface {
12860    fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
12861        Self { state }
12862    }
12863}
12864
12865impl Widget for ContextMenuSurface {
12866    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
12867        let state = self.state.borrow();
12868        if state.is_presented() {
12869            state.frame_rect.size
12870        } else {
12871            Size::ZERO
12872        }
12873    }
12874
12875    fn paint(&self, ctx: &mut PaintCtx) {
12876        let state = self.state.borrow();
12877        if !state.is_presented() {
12878            return;
12879        }
12880
12881        let menu = ctx.bounds();
12882        let theme = state.theme;
12883        let metrics = theme.metrics;
12884        let palette = theme.palette;
12885        let interaction = theme.interaction;
12886        let item_padding = metrics.menu_item_padding;
12887        let surface_radius = metrics.corner_radius + 2.0;
12888        paint_theme_shadow(ctx, menu, [surface_radius; 4], &theme.shadows.box_shadow.lg);
12889        draw_control_frame(
12890            ctx,
12891            menu,
12892            surface_radius,
12893            metrics,
12894            palette.surface_raised,
12895            palette.border,
12896            None,
12897        );
12898
12899        for (index, item) in state.items.iter().enumerate() {
12900            let Some(row) = state.item_rect(menu, index) else {
12901                continue;
12902            };
12903
12904            if item.separator_before {
12905                let line = Rect::new(
12906                    row.x(),
12907                    row.y() - (metrics.menu_padding.top * 0.5),
12908                    row.width(),
12909                    1.0,
12910                );
12911                ctx.fill(rounded_rect_path(line, 0.5), palette.border);
12912            }
12913
12914            let highlighted = state.highlighted == Some(index);
12915            let highlight_amount = state.highlight_amount_for(index);
12916            let press_amount = state.press_amount_for(index);
12917            let label_style = theme.text_style(item.text_color(&theme));
12918            let label_slot = Rect::new(
12919                row.x() + item_padding.left,
12920                row.y(),
12921                (row.width()
12922                    - item_padding.left
12923                    - item_padding.right
12924                    - item
12925                        .shortcut
12926                        .as_ref()
12927                        .map(|_| metrics.menu_shortcut_width)
12928                        .unwrap_or(0.0))
12929                .max(0.0),
12930                row.height(),
12931            );
12932            if highlighted || highlight_amount > 0.0 || press_amount > 0.0 {
12933                let highlight_background = mix_color(
12934                    palette.control,
12935                    palette.accent,
12936                    interaction.selected_blend * highlight_amount,
12937                );
12938                let background = if press_amount > 0.0 {
12939                    mix_color(
12940                        highlight_background,
12941                        palette.control_active,
12942                        interaction.pressed_blend * press_amount,
12943                    )
12944                } else {
12945                    highlight_background
12946                };
12947                ctx.fill(
12948                    rounded_rect_path(row.inflate(-2.0, -2.0), metrics.corner_radius - 2.0),
12949                    background,
12950                );
12951            }
12952
12953            ctx.push_clip_rect(label_slot);
12954            paint_aligned_text(
12955                ctx,
12956                label_slot,
12957                &item.label,
12958                &label_style,
12959                label_style.line_height,
12960                0.0,
12961            );
12962            ctx.pop_clip();
12963
12964            if let Some(shortcut) = &item.shortcut {
12965                let shortcut_style = theme.placeholder_text_style();
12966                let shortcut_slot = Rect::new(
12967                    row.max_x() - item_padding.right - metrics.menu_shortcut_width,
12968                    row.y(),
12969                    metrics.menu_shortcut_width,
12970                    row.height(),
12971                );
12972                ctx.push_clip_rect(shortcut_slot);
12973                paint_aligned_text(
12974                    ctx,
12975                    shortcut_slot,
12976                    shortcut,
12977                    &shortcut_style,
12978                    shortcut_style.line_height,
12979                    1.0,
12980                );
12981                ctx.pop_clip();
12982            }
12983        }
12984    }
12985
12986    fn layer_options(&self) -> LayerOptions {
12987        let presented = self.state.borrow().is_presented();
12988        LayerOptions {
12989            paint_boundary: PaintBoundaryMode::Explicit,
12990            composition_mode: if presented {
12991                LayerCompositionMode::Overlay
12992            } else {
12993                LayerCompositionMode::Normal
12994            },
12995        }
12996    }
12997
12998    fn layer_properties(&self) -> LayerProperties {
12999        self.state.borrow().layer_properties()
13000    }
13001
13002    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
13003        self.state
13004            .borrow()
13005            .is_presented()
13006            .then_some(StackSurfaceOptions {
13007                transient: true,
13008                ..StackSurfaceOptions::default()
13009            })
13010    }
13011}
13012
13013struct ContextMenuFocusSurface {
13014    state: Rc<RefCell<ContextMenuPresentationState>>,
13015}
13016
13017impl ContextMenuFocusSurface {
13018    fn new(state: Rc<RefCell<ContextMenuPresentationState>>) -> Self {
13019        Self { state }
13020    }
13021}
13022
13023impl Widget for ContextMenuFocusSurface {
13024    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
13025        let state = self.state.borrow();
13026        if state.is_presented() {
13027            state.frame_rect.size
13028        } else {
13029            Size::ZERO
13030        }
13031    }
13032
13033    fn paint(&self, ctx: &mut PaintCtx) {
13034        let state = self.state.borrow();
13035        if !state.is_presented() || !state.focus_animation.is_presented() {
13036            return;
13037        }
13038
13039        let progress = state.focus_animation.value;
13040        if progress <= AnimatedScalar::EPSILON {
13041            return;
13042        }
13043
13044        let metrics = state.theme.metrics;
13045        let palette = state.theme.palette;
13046        draw_focus_ring_frame(
13047            ctx,
13048            ctx.bounds(),
13049            metrics.corner_radius + 2.0,
13050            metrics,
13051            palette
13052                .focus_ring
13053                .with_alpha(palette.focus_ring.alpha * progress),
13054        );
13055    }
13056
13057    fn layer_options(&self) -> LayerOptions {
13058        LayerOptions {
13059            paint_boundary: PaintBoundaryMode::Explicit,
13060            composition_mode: LayerCompositionMode::Normal,
13061        }
13062    }
13063
13064    fn layer_properties(&self) -> LayerProperties {
13065        self.state.borrow().layer_properties()
13066    }
13067
13068    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
13069        let state = self.state.borrow();
13070        (state.is_presented() && state.focus_animation.is_presented()).then_some(
13071            StackSurfaceOptions {
13072                transient: true,
13073                hit_test: false,
13074                ..StackSurfaceOptions::default()
13075            },
13076        )
13077    }
13078}
13079
13080pub struct ContextMenu {
13081    theme: Box<DefaultTheme>,
13082    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
13083    name: String,
13084    trigger: SingleChild,
13085    items: Vec<MenuItem>,
13086    items_provider: Option<Box<dyn Fn() -> Vec<MenuItem>>>,
13087    open: bool,
13088    highlighted: Option<usize>,
13089    highlight_visual: Option<usize>,
13090    pressed: Option<usize>,
13091    press_visual: Option<usize>,
13092    highlight_animation: AnimatedScalar,
13093    press_animation: AnimatedScalar,
13094    frame_rect: Rect,
13095    surface: SingleChild,
13096    focus_surface: SingleChild,
13097    surface_state: Rc<RefCell<ContextMenuPresentationState>>,
13098    activation_button: PointerButton,
13099    anchor_to_pointer: Option<bool>,
13100    open_position: Option<Point>,
13101    on_activate: Option<Box<dyn FnMut(usize, MenuItem)>>,
13102    on_activate_with_ctx: Option<Box<dyn FnMut(&mut EventCtx, usize, MenuItem)>>,
13103}
13104
13105impl ContextMenu {
13106    pub fn new<W>(name: impl Into<String>, trigger: W) -> Self
13107    where
13108        W: Widget + 'static,
13109    {
13110        let surface_state = Rc::new(RefCell::new(ContextMenuPresentationState::new()));
13111        Self {
13112            theme: Box::new(DefaultTheme::default()),
13113            theme_reader: None,
13114            name: name.into(),
13115            trigger: SingleChild::new(trigger),
13116            items: Vec::new(),
13117            items_provider: None,
13118            open: false,
13119            highlighted: None,
13120            highlight_visual: None,
13121            pressed: None,
13122            press_visual: None,
13123            highlight_animation: AnimatedScalar::new(0.0),
13124            press_animation: AnimatedScalar::new(0.0),
13125            frame_rect: Rect::ZERO,
13126            surface: SingleChild::new(ContextMenuSurface::new(Rc::clone(&surface_state))),
13127            focus_surface: SingleChild::new(ContextMenuFocusSurface::new(Rc::clone(
13128                &surface_state,
13129            ))),
13130            surface_state,
13131            activation_button: PointerButton::Secondary,
13132            anchor_to_pointer: None,
13133            open_position: None,
13134            on_activate: None,
13135            on_activate_with_ctx: None,
13136        }
13137    }
13138
13139    pub fn theme(mut self, theme: DefaultTheme) -> Self {
13140        self.theme = Box::new(theme);
13141        self.theme_reader = None;
13142        self
13143    }
13144
13145    pub fn theme_when<F>(mut self, theme: F) -> Self
13146    where
13147        F: Fn() -> DefaultTheme + 'static,
13148    {
13149        self.theme_reader = Some(Box::new(theme));
13150        self
13151    }
13152
13153    pub fn item(mut self, item: MenuItem) -> Self {
13154        self.items.push(item);
13155        self
13156    }
13157
13158    pub fn items<I>(mut self, items: I) -> Self
13159    where
13160        I: IntoIterator<Item = MenuItem>,
13161    {
13162        self.items.extend(items);
13163        self
13164    }
13165
13166    /// Rebuild the item list every time the menu opens, so per-item enabled
13167    /// state can reflect current application state (selection, clipboard, …).
13168    pub fn items_when<F>(mut self, provider: F) -> Self
13169    where
13170        F: Fn() -> Vec<MenuItem> + 'static,
13171    {
13172        self.items_provider = Some(Box::new(provider));
13173        self
13174    }
13175
13176    /// Widget id of the wrapped trigger. Menu activations can route commands
13177    /// back to it via `EventCtx::post_event` — for example the standard text
13178    /// editing commands (`TextCommand`) understood by the text widgets.
13179    pub fn trigger_id(&self) -> WidgetId {
13180        self.trigger.child().id()
13181    }
13182
13183    pub fn on_activate<F>(mut self, on_activate: F) -> Self
13184    where
13185        F: FnMut(usize, MenuItem) + 'static,
13186    {
13187        self.on_activate = Some(Box::new(on_activate));
13188        self
13189    }
13190
13191    pub fn on_activate_with_ctx<F>(mut self, on_activate: F) -> Self
13192    where
13193        F: FnMut(&mut EventCtx, usize, MenuItem) + 'static,
13194    {
13195        self.on_activate_with_ctx = Some(Box::new(on_activate));
13196        self
13197    }
13198
13199    pub fn activation_button(mut self, activation_button: PointerButton) -> Self {
13200        self.activation_button = activation_button;
13201        self
13202    }
13203
13204    /// Whether the menu opens at the press position instead of dropping below
13205    /// the trigger. Defaults by activation button: right-click menus anchor to
13206    /// the pointer (standard context-menu behavior, and the only sensible
13207    /// placement for large triggers), other buttons keep the dropdown layout.
13208    pub fn anchor_to_pointer(mut self, anchor_to_pointer: bool) -> Self {
13209        self.anchor_to_pointer = Some(anchor_to_pointer);
13210        self
13211    }
13212
13213    fn anchors_to_pointer(&self) -> bool {
13214        self.anchor_to_pointer
13215            .unwrap_or(self.activation_button == PointerButton::Secondary)
13216    }
13217
13218    fn row_height(&self) -> f32 {
13219        menu_row_height(&self.resolved_theme())
13220    }
13221
13222    fn measured_menu_width(&self, ctx: &mut MeasureCtx) -> f32 {
13223        let theme = self.resolved_theme();
13224        let label_style = theme.body_text_style();
13225        let shortcut_style = theme.placeholder_text_style();
13226        let mut width: f32 = 220.0;
13227        for item in &self.items {
13228            let label = measure_text(ctx, item.label(), &label_style).width;
13229            let shortcut = item
13230                .shortcut
13231                .as_ref()
13232                .map(|text| measure_text(ctx, text, &shortcut_style).width)
13233                .unwrap_or(0.0);
13234            width = width.max(
13235                label
13236                    + shortcut
13237                    + theme.metrics.menu_item_padding.left
13238                    + theme.metrics.menu_item_padding.right
13239                    + theme.metrics.menu_shortcut_width,
13240            );
13241        }
13242        width
13243    }
13244
13245    fn resolved_theme(&self) -> DefaultTheme {
13246        self.theme_reader
13247            .as_ref()
13248            .map(|theme| theme())
13249            .unwrap_or(*self.theme)
13250    }
13251
13252    fn trigger_rect(&self) -> Rect {
13253        self.trigger.child().bounds()
13254    }
13255
13256    fn item_rect(&self, bounds: Rect, index: usize) -> Option<Rect> {
13257        if index >= self.items.len() || !self.open {
13258            return None;
13259        }
13260        let theme = self.resolved_theme();
13261        let padding = theme.metrics.menu_padding;
13262        let menu = self.frame_rect.translate(bounds.origin.to_vector());
13263        let x = menu.x() + padding.left;
13264        let y = menu.y() + padding.top + (index as f32 * self.row_height());
13265        Some(Rect::new(
13266            x,
13267            y,
13268            (menu.width() - padding.left - padding.right).max(0.0),
13269            self.row_height(),
13270        ))
13271    }
13272
13273    fn item_at(&self, bounds: Rect, position: Point) -> Option<usize> {
13274        self.items.iter().enumerate().find_map(|(index, _)| {
13275            self.item_rect(bounds, index)
13276                .filter(|rect| rect.contains(position))
13277                .map(|_| index)
13278        })
13279    }
13280
13281    fn sync_surface_state(&self, bounds: Rect) {
13282        let theme = self.resolved_theme();
13283        let mut state = self.surface_state.borrow_mut();
13284        state.theme = theme;
13285        state.items = self.items.clone();
13286        state.highlighted = self.highlighted;
13287        state.highlight_visual = self.highlight_visual;
13288        state.pressed = self.pressed;
13289        state.press_visual = self.press_visual;
13290        state.highlight_animation = self.highlight_animation;
13291        state.press_animation = self.press_animation;
13292        state.frame_rect = self.frame_rect.translate(bounds.origin.to_vector());
13293        state.row_height = self.row_height();
13294    }
13295
13296    fn refresh_surface_interaction_state(&self, ctx: &mut EventCtx) {
13297        let surface_id = self.surface.child().id();
13298        let mut state = self.surface_state.borrow_mut();
13299        let changed = state.highlighted != self.highlighted
13300            || state.highlight_visual != self.highlight_visual
13301            || state.pressed != self.pressed
13302            || state.press_visual != self.press_visual
13303            || state.highlight_animation != self.highlight_animation
13304            || state.press_animation != self.press_animation;
13305        state.highlighted = self.highlighted;
13306        state.highlight_visual = self.highlight_visual;
13307        state.pressed = self.pressed;
13308        state.press_visual = self.press_visual;
13309        state.highlight_animation = self.highlight_animation;
13310        state.press_animation = self.press_animation;
13311        let presented = state.is_presented();
13312        drop(state);
13313
13314        if changed && presented {
13315            request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
13316        }
13317    }
13318
13319    fn set_highlighted(&mut self, highlighted: Option<usize>, ctx: &mut EventCtx) {
13320        if self.highlighted == highlighted {
13321            return;
13322        }
13323        let theme = self.resolved_theme();
13324        self.highlighted = highlighted;
13325        if let Some(index) = highlighted {
13326            self.highlight_visual = Some(index);
13327            self.highlight_animation = AnimatedScalar::new(0.0);
13328            set_hover_animation_target(&mut self.highlight_animation, 1.0, &theme, ctx);
13329        } else if !set_hover_animation_target(&mut self.highlight_animation, 0.0, &theme, ctx) {
13330            self.highlight_visual = None;
13331        }
13332        self.refresh_surface_interaction_state(ctx);
13333        ctx.request_paint();
13334        ctx.request_semantics();
13335    }
13336
13337    fn set_pressed(&mut self, pressed: Option<usize>, ctx: &mut EventCtx) {
13338        if self.pressed == pressed {
13339            return;
13340        }
13341        let theme = self.resolved_theme();
13342        self.pressed = pressed;
13343        if let Some(index) = pressed {
13344            self.press_visual = Some(index);
13345            self.press_animation = AnimatedScalar::new(0.0);
13346            set_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
13347        } else if !set_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx) {
13348            self.press_visual = None;
13349        }
13350        self.refresh_surface_interaction_state(ctx);
13351        ctx.request_paint();
13352        ctx.request_semantics();
13353    }
13354
13355    fn advance_row_animations(&mut self, time: f64) -> bool {
13356        let highlight_animating = self.highlight_animation.advance(time);
13357        if !highlight_animating
13358            && self.highlighted.is_none()
13359            && self.highlight_animation.value <= AnimatedScalar::EPSILON
13360        {
13361            self.highlight_visual = None;
13362        }
13363
13364        let press_animating = self.press_animation.advance(time);
13365        if !press_animating
13366            && self.pressed.is_none()
13367            && self.press_animation.value <= AnimatedScalar::EPSILON
13368        {
13369            self.press_visual = None;
13370        }
13371
13372        highlight_animating | press_animating
13373    }
13374
13375    fn set_open(&mut self, ctx: &mut EventCtx, open: bool) {
13376        if self.open == open {
13377            return;
13378        }
13379
13380        if open && let Some(provider) = &self.items_provider {
13381            self.items = provider();
13382        }
13383        if !open {
13384            self.open_position = None;
13385        }
13386
13387        self.open = open;
13388        self.highlighted = if open {
13389            self.items.iter().position(|item| item.enabled)
13390        } else {
13391            None
13392        };
13393        self.highlight_visual = self.highlighted;
13394        self.highlight_animation = AnimatedScalar::new(self.highlighted.is_some() as u8 as f32);
13395        self.pressed = None;
13396        self.press_visual = None;
13397        self.press_animation = AnimatedScalar::new(0.0);
13398
13399        let surface_id = self.surface.child().id();
13400        let focus_surface_id = self.focus_surface.child().id();
13401        let theme = self.resolved_theme();
13402        let mut state = self.surface_state.borrow_mut();
13403        state.theme = theme;
13404        state.items = self.items.clone();
13405        state.highlighted = self.highlighted;
13406        state.highlight_visual = self.highlight_visual;
13407        state.pressed = self.pressed;
13408        state.press_visual = self.press_visual;
13409        state.highlight_animation = self.highlight_animation;
13410        state.press_animation = self.press_animation;
13411        let was_presented = state.is_presented();
13412        let should_animate = if open {
13413            let motion = theme.motion;
13414            state.reveal.set_target(
13415                1.0,
13416                ctx.current_time(),
13417                motion.entrance_duration(),
13418                motion.entrance_easing(),
13419            )
13420        } else {
13421            state.reveal = AnimatedScalar::new(0.0);
13422            false
13423        };
13424        let is_presented = state.is_presented();
13425        drop(state);
13426
13427        if open || was_presented != is_presented {
13428            ctx.request_measure();
13429            request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
13430            request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
13431        }
13432        if should_animate {
13433            ctx.request_animation_frame();
13434        }
13435        ctx.request_paint();
13436        ctx.request_semantics();
13437    }
13438
13439    fn activate(&mut self, ctx: &mut EventCtx, index: usize) {
13440        let Some(item) = self.items.get(index).cloned() else {
13441            return;
13442        };
13443        if !item.enabled {
13444            return;
13445        }
13446        if let Some(on_activate) = &mut self.on_activate {
13447            on_activate(index, item.clone());
13448        }
13449        if let Some(on_activate) = &mut self.on_activate_with_ctx {
13450            on_activate(ctx, index, item);
13451        }
13452    }
13453}
13454
13455impl Widget for ContextMenu {
13456    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
13457        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.open {
13458            self.set_open(ctx, false);
13459            ctx.set_handled();
13460        }
13461    }
13462
13463    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
13464        match event {
13465            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move && self.open => {
13466                self.set_highlighted(self.item_at(ctx.bounds(), pointer.position), ctx);
13467            }
13468            Event::Pointer(pointer)
13469                if pointer.kind == PointerEventKind::Down
13470                    && pointer.button == Some(self.activation_button)
13471                    && ctx.phase() != EventPhase::Capture
13472                    && self.trigger_rect().contains(pointer.position) =>
13473            {
13474                // Target/Bubble only: the trigger widget sees the press first
13475                // (to focus itself or record the press position) before the
13476                // menu opens and takes keyboard focus.
13477                let open = !self.open;
13478                self.open_position = (open && self.anchors_to_pointer()).then(|| {
13479                    let origin = ctx.bounds().origin;
13480                    Point::new(pointer.position.x - origin.x, pointer.position.y - origin.y)
13481                });
13482                self.set_open(ctx, open);
13483                ctx.request_focus();
13484                ctx.set_handled();
13485            }
13486            Event::Pointer(pointer)
13487                if pointer.kind == PointerEventKind::Down
13488                    && pointer.button == Some(PointerButton::Primary)
13489                    && self.open =>
13490            {
13491                if let Some(index) = self.item_at(ctx.bounds(), pointer.position) {
13492                    self.set_highlighted(Some(index), ctx);
13493                    self.set_pressed(
13494                        self.items
13495                            .get(index)
13496                            .filter(|item| item.enabled)
13497                            .map(|_| index),
13498                        ctx,
13499                    );
13500                    ctx.request_pointer_capture(pointer.pointer_id);
13501                    ctx.set_handled();
13502                } else if !self.trigger_rect().contains(pointer.position) {
13503                    self.set_open(ctx, false);
13504                }
13505            }
13506            Event::Pointer(pointer)
13507                if pointer.kind == PointerEventKind::Up
13508                    && pointer.button == Some(PointerButton::Primary)
13509                    && self.open =>
13510            {
13511                let highlighted = self.item_at(ctx.bounds(), pointer.position);
13512                if let Some(index) = self
13513                    .pressed
13514                    .zip(highlighted)
13515                    .filter(|(left, right)| left == right)
13516                    .map(|(index, _)| index)
13517                {
13518                    self.activate(ctx, index);
13519                    self.set_open(ctx, false);
13520                }
13521                self.set_pressed(None, ctx);
13522                ctx.release_pointer_capture(pointer.pointer_id);
13523                ctx.set_handled();
13524            }
13525            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
13526                if self.pressed.is_some() {
13527                    self.set_pressed(None, ctx);
13528                    ctx.release_pointer_capture(pointer.pointer_id);
13529                    ctx.set_handled();
13530                }
13531            }
13532            Event::Keyboard(key)
13533                if ctx.is_focused() && key.state == KeyState::Pressed && self.open =>
13534            {
13535                match key.key.as_str() {
13536                    "ArrowDown" => {
13537                        let mut menu = Menu::new("temp").items(self.items.clone());
13538                        menu.highlighted = self.highlighted;
13539                        menu.move_highlight(1, ctx);
13540                        self.set_highlighted(menu.highlighted, ctx);
13541                    }
13542                    "ArrowUp" => {
13543                        let mut menu = Menu::new("temp").items(self.items.clone());
13544                        menu.highlighted = self.highlighted;
13545                        menu.move_highlight(-1, ctx);
13546                        self.set_highlighted(menu.highlighted, ctx);
13547                    }
13548                    "Enter" | " " => {
13549                        if let Some(index) = self.highlighted {
13550                            self.activate(ctx, index);
13551                            self.set_open(ctx, false);
13552                        }
13553                    }
13554                    "Escape" => {
13555                        self.set_open(ctx, false);
13556                    }
13557                    _ => return,
13558                }
13559                self.refresh_surface_interaction_state(ctx);
13560                ctx.request_paint();
13561                ctx.request_semantics();
13562                ctx.set_handled();
13563            }
13564            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
13565                let surface_id = self.surface.child().id();
13566                let focus_surface_id = self.focus_surface.child().id();
13567                let mut state = self.surface_state.borrow_mut();
13568                let was_presented = state.is_presented();
13569                let was_focus_presented = state.focus_animation.is_presented();
13570                let previous = state.reveal.value;
13571                let previous_focus = state.focus_animation.value;
13572                let reveal_animating = state.reveal.advance(*time);
13573                let focus_animating = state.focus_animation.advance(*time);
13574                let reveal_changed = state.reveal.changed_since(previous);
13575                let focus_changed = state.focus_animation.changed_since(previous_focus);
13576                let is_presented = state.is_presented();
13577                let is_focus_presented = state.focus_animation.is_presented();
13578                drop(state);
13579
13580                let previous_highlight = self.highlight_animation.value;
13581                let previous_press = self.press_animation.value;
13582                let row_animating = self.advance_row_animations(*time);
13583                let row_changed = self.highlight_animation.changed_since(previous_highlight)
13584                    || self.press_animation.changed_since(previous_press);
13585                if row_changed {
13586                    self.refresh_surface_interaction_state(ctx);
13587                    request_child_invalidation(ctx, surface_id, InvalidationKind::Paint);
13588                }
13589
13590                if reveal_changed {
13591                    request_child_invalidation(ctx, surface_id, InvalidationKind::Transform);
13592                    request_child_invalidation(ctx, surface_id, InvalidationKind::Effect);
13593                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Transform);
13594                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Effect);
13595                }
13596                if focus_changed {
13597                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
13598                }
13599                if was_presented != is_presented {
13600                    ctx.request_measure();
13601                    request_child_invalidation(ctx, surface_id, InvalidationKind::Visibility);
13602                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
13603                }
13604                if was_focus_presented != is_focus_presented {
13605                    request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
13606                }
13607                if reveal_animating || row_animating || focus_animating {
13608                    ctx.request_animation_frame();
13609                }
13610                ctx.set_handled();
13611            }
13612            _ => {}
13613        }
13614    }
13615
13616    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
13617        let trigger_size = self.trigger.measure(ctx, constraints.loosen());
13618        if self.open {
13619            let theme = self.resolved_theme();
13620            let pointer_anchored = self.open_position.is_some();
13621            let width = if pointer_anchored {
13622                self.measured_menu_width(ctx)
13623            } else {
13624                self.measured_menu_width(ctx).max(trigger_size.width)
13625            };
13626            let height = themed_menu_height_for_rows(&theme, self.row_height(), self.items.len());
13627            self.frame_rect = Rect::from_origin_size(Point::ZERO, Size::new(width, height));
13628            {
13629                let mut state = self.surface_state.borrow_mut();
13630                state.theme = theme;
13631                state.items = self.items.clone();
13632                state.highlighted = self.highlighted;
13633                state.highlight_visual = self.highlight_visual;
13634                state.pressed = self.pressed;
13635                state.press_visual = self.press_visual;
13636                state.highlight_animation = self.highlight_animation;
13637                state.press_animation = self.press_animation;
13638                state.frame_rect = Rect::from_origin_size(Point::ZERO, self.frame_rect.size);
13639                state.row_height = self.row_height();
13640            }
13641            self.surface
13642                .measure(ctx, Constraints::tight(self.frame_rect.size));
13643            self.focus_surface
13644                .measure(ctx, Constraints::tight(self.frame_rect.size));
13645        } else {
13646            self.frame_rect = Rect::ZERO;
13647        }
13648        constraints.clamp(trigger_size)
13649    }
13650
13651    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
13652        self.trigger.arrange(
13653            ctx,
13654            Rect::from_origin_size(bounds.origin, self.trigger.child().measured_size()),
13655        );
13656        if self.open {
13657            let theme = self.resolved_theme();
13658            let anchor = self.open_position.map_or_else(
13659                || self.trigger.child().bounds(),
13660                |position| {
13661                    Rect::from_origin_size(
13662                        Point::new(bounds.x() + position.x, bounds.y() + position.y),
13663                        Size::ZERO,
13664                    )
13665                },
13666            );
13667            let viewport = Rect::from_origin_size(Point::ZERO, ctx.dpi().viewport);
13668            let result = place_overlay(
13669                &OverlayPlacementRequest::new(
13670                    anchor,
13671                    self.frame_rect.size,
13672                    viewport,
13673                    OverlayPlacement::BOTTOM_START,
13674                )
13675                .fallbacks([
13676                    OverlayPlacement::TOP_START,
13677                    OverlayPlacement::RIGHT_START,
13678                    OverlayPlacement::LEFT_START,
13679                ])
13680                .gap(if self.open_position.is_some() {
13681                    0.0
13682                } else {
13683                    theme.metrics.popover_gap
13684                })
13685                .margin(theme.metrics.popover_gap.max(4.0)),
13686            );
13687            self.frame_rect = result
13688                .bounds
13689                .translate(Vector::new(-bounds.x(), -bounds.y()));
13690        }
13691        self.sync_surface_state(bounds);
13692        let state = self.surface_state.borrow();
13693        let surface_bounds = if state.is_presented() {
13694            state.frame_rect
13695        } else {
13696            Rect::from_origin_size(bounds.origin, Size::ZERO)
13697        };
13698        drop(state);
13699        self.surface.arrange(ctx, surface_bounds);
13700        self.focus_surface.arrange(ctx, surface_bounds);
13701    }
13702
13703    fn paint(&self, ctx: &mut PaintCtx) {
13704        self.trigger.paint(ctx);
13705        if self.surface_state.borrow().is_presented() {
13706            self.surface.paint(ctx);
13707            self.focus_surface.paint(ctx);
13708        }
13709    }
13710
13711    fn semantics(&self, ctx: &mut SemanticsCtx) {
13712        let mut node =
13713            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ContextMenu, ctx.bounds());
13714        node.name = Some(self.name.clone());
13715        node.state.focused = ctx.is_focused();
13716        node.state.expanded = Some(self.open);
13717        node.popup = Some(SemanticsPopupKind::Menu);
13718        node.value = self
13719            .highlighted
13720            .and_then(|index| self.items.get(index))
13721            .map(|item| SemanticsValue::Text(item.label.clone()));
13722        node.actions = vec![
13723            SemanticsAction::Focus,
13724            SemanticsAction::Expand,
13725            SemanticsAction::Collapse,
13726            SemanticsAction::Activate,
13727        ];
13728        ctx.push(node);
13729        if self.open {
13730            for (index, item) in self.items.iter().enumerate() {
13731                let Some(row) = self.item_rect(ctx.bounds(), index) else {
13732                    continue;
13733                };
13734                ctx.push(menu_item_semantics_node(
13735                    ctx.widget_id(),
13736                    index,
13737                    item,
13738                    row,
13739                    self.highlighted == Some(index),
13740                ));
13741            }
13742        }
13743        self.trigger.semantics(ctx);
13744    }
13745
13746    fn accepts_focus(&self) -> bool {
13747        true
13748    }
13749
13750    fn overlay_options(&self) -> Option<OverlayOptions> {
13751        (self.open || self.surface_state.borrow().is_presented()).then_some(
13752            OverlayOptions::new(OverlayKind::Menu)
13753                .dismiss(if self.open {
13754                    OverlayDismissPolicy::TRANSIENT
13755                } else {
13756                    OverlayDismissPolicy::NONE
13757                })
13758                .focus(OverlayFocusBehavior::NONE),
13759        )
13760    }
13761
13762    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
13763        if !focused && self.open {
13764            self.set_open(ctx, false);
13765        }
13766        let focus_surface_id = self.focus_surface.child().id();
13767        {
13768            let mut state = self.surface_state.borrow_mut();
13769            let was_focus_presented = state.focus_animation.is_presented();
13770            let theme = state.theme;
13771            set_focus_animation_target(
13772                &mut state.focus_animation,
13773                focused as u8 as f32,
13774                &theme,
13775                ctx,
13776            );
13777            if was_focus_presented != state.focus_animation.is_presented() {
13778                request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Visibility);
13779            }
13780        }
13781        request_child_invalidation(ctx, focus_surface_id, InvalidationKind::Paint);
13782        ctx.request_semantics();
13783    }
13784
13785    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
13786        self.trigger.visit_children(visitor);
13787        if self.surface_state.borrow().is_presented() {
13788            self.surface.visit_children(visitor);
13789            self.focus_surface.visit_children(visitor);
13790        }
13791    }
13792
13793    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
13794        self.trigger.visit_children_mut(visitor);
13795        if self.surface_state.borrow().is_presented() {
13796            self.surface.visit_children_mut(visitor);
13797            self.focus_surface.visit_children_mut(visitor);
13798        }
13799    }
13800}
13801
13802#[derive(Debug, Clone)]
13803struct DialogFocusState {
13804    theme: DefaultTheme,
13805    frame: Rect,
13806    shown: bool,
13807    animation: AnimatedScalar,
13808}
13809
13810impl DialogFocusState {
13811    fn new() -> Self {
13812        Self {
13813            theme: DefaultTheme::default(),
13814            frame: Rect::ZERO,
13815            shown: false,
13816            animation: AnimatedScalar::new(0.0),
13817        }
13818    }
13819}
13820
13821struct DialogFocusSurface {
13822    state: Rc<RefCell<DialogFocusState>>,
13823}
13824
13825impl DialogFocusSurface {
13826    fn new(state: Rc<RefCell<DialogFocusState>>) -> Self {
13827        Self { state }
13828    }
13829}
13830
13831impl Widget for DialogFocusSurface {
13832    fn measure(&mut self, _ctx: &mut MeasureCtx, _constraints: Constraints) -> Size {
13833        let state = self.state.borrow();
13834        if state.shown {
13835            state.frame.size
13836        } else {
13837            Size::ZERO
13838        }
13839    }
13840
13841    fn paint(&self, ctx: &mut PaintCtx) {
13842        let state = self.state.borrow();
13843        if !state.shown || !state.animation.is_presented() {
13844            return;
13845        }
13846        let progress = state.animation.value;
13847        if progress <= AnimatedScalar::EPSILON {
13848            return;
13849        }
13850        let metrics = state.theme.metrics;
13851        draw_focus_ring_frame(
13852            ctx,
13853            ctx.bounds(),
13854            metrics.corner_radius + 3.0,
13855            metrics,
13856            state
13857                .theme
13858                .palette
13859                .focus_ring
13860                .with_alpha(state.theme.palette.focus_ring.alpha * progress),
13861        );
13862    }
13863
13864    fn layer_options(&self) -> LayerOptions {
13865        LayerOptions {
13866            paint_boundary: PaintBoundaryMode::Explicit,
13867            composition_mode: LayerCompositionMode::Normal,
13868        }
13869    }
13870
13871    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
13872        let state = self.state.borrow();
13873        (state.shown && state.animation.is_presented()).then_some(StackSurfaceOptions {
13874            transient: true,
13875            hit_test: false,
13876            ..StackSurfaceOptions::default()
13877        })
13878    }
13879}
13880
13881pub struct Dialog {
13882    theme: Box<DefaultTheme>,
13883    title: String,
13884    description: Option<String>,
13885    shown: bool,
13886    modal: bool,
13887    dismiss_on_scrim: bool,
13888    max_width: Option<f32>,
13889    body: SingleChild,
13890    actions: WidgetChildren,
13891    body_frame: Rect,
13892    dialog_frame: Rect,
13893    title_measurement: Option<TextMeasurement>,
13894    description_measurement: Option<TextMeasurement>,
13895    reveal: AnimatedScalar,
13896    focus_animation: AnimatedScalar,
13897    focus_state: Rc<RefCell<DialogFocusState>>,
13898    focus_surface: SingleChild,
13899    entrance_started: bool,
13900    on_dismiss: Option<Box<dyn FnMut()>>,
13901    overlay_kind: OverlayKind,
13902}
13903
13904impl Dialog {
13905    pub fn new<W>(title: impl Into<String>, body: W) -> Self
13906    where
13907        W: Widget + 'static,
13908    {
13909        let focus_state = Rc::new(RefCell::new(DialogFocusState::new()));
13910        Self {
13911            theme: Box::new(DefaultTheme::default()),
13912            title: title.into(),
13913            description: None,
13914            shown: true,
13915            modal: true,
13916            dismiss_on_scrim: false,
13917            max_width: None,
13918            body: SingleChild::new(body),
13919            actions: WidgetChildren::new(),
13920            body_frame: Rect::ZERO,
13921            dialog_frame: Rect::ZERO,
13922            title_measurement: None,
13923            description_measurement: None,
13924            reveal: AnimatedScalar::new(0.0),
13925            focus_animation: AnimatedScalar::new(0.0),
13926            focus_surface: SingleChild::new(DialogFocusSurface::new(Rc::clone(&focus_state))),
13927            focus_state,
13928            entrance_started: false,
13929            on_dismiss: None,
13930            overlay_kind: OverlayKind::Dialog,
13931        }
13932    }
13933
13934    pub fn theme(mut self, theme: DefaultTheme) -> Self {
13935        self.theme = Box::new(theme);
13936        self
13937    }
13938
13939    pub fn description(mut self, description: impl Into<String>) -> Self {
13940        self.description = Some(description.into());
13941        self
13942    }
13943
13944    pub fn shown(mut self, shown: bool) -> Self {
13945        self.shown = shown;
13946        if !shown {
13947            self.reveal = AnimatedScalar::new(0.0);
13948            self.focus_animation = AnimatedScalar::new(0.0);
13949            self.entrance_started = false;
13950            let mut focus = self.focus_state.borrow_mut();
13951            focus.shown = false;
13952            focus.animation = AnimatedScalar::new(0.0);
13953        }
13954        self
13955    }
13956
13957    pub fn modal(mut self, modal: bool) -> Self {
13958        self.modal = modal;
13959        self
13960    }
13961
13962    pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
13963        self.dismiss_on_scrim = dismiss_on_scrim;
13964        self
13965    }
13966
13967    pub fn max_width(mut self, max_width: f32) -> Self {
13968        self.max_width = Some(max_width.max(self.theme.metrics.dialog_min_width));
13969        self
13970    }
13971
13972    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
13973    where
13974        F: FnMut() + 'static,
13975    {
13976        self.on_dismiss = Some(Box::new(on_dismiss));
13977        self
13978    }
13979
13980    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
13981    where
13982        F: FnMut() + 'static,
13983    {
13984        self.actions.push(
13985            Button::new(label.into())
13986                .min_width(self.theme.metrics.dialog_action_min_width)
13987                .on_press(on_press),
13988        );
13989        self
13990    }
13991
13992    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
13993    where
13994        F: FnMut() + 'static,
13995    {
13996        self.actions.push(
13997            Button::new(label.into())
13998                .min_width(self.theme.metrics.dialog_action_min_width)
13999                .on_press(on_press),
14000        );
14001        self
14002    }
14003
14004    fn resolved_max_width(&self) -> f32 {
14005        self.max_width
14006            .unwrap_or(self.theme.metrics.dialog_max_width)
14007    }
14008
14009    fn title_style(&self) -> TextStyle {
14010        TextStyle {
14011            font_size: self.theme.metrics.dialog_title_font_size,
14012            line_height: self.theme.metrics.dialog_title_line_height,
14013            color: self.theme.palette.text,
14014            ..self.theme.body_text_style()
14015        }
14016    }
14017
14018    fn dismiss(&mut self) {
14019        if let Some(on_dismiss) = &mut self.on_dismiss {
14020            on_dismiss();
14021        }
14022    }
14023
14024    fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
14025        if self.entrance_started {
14026            return;
14027        }
14028        self.entrance_started = true;
14029        let motion = self.theme.motion;
14030        if self.reveal.set_target(
14031            1.0,
14032            ctx.current_time(),
14033            motion.entrance_duration(),
14034            motion.entrance_easing(),
14035        ) {
14036            ctx.request_animation_frame();
14037        }
14038    }
14039}
14040
14041impl Widget for Dialog {
14042    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
14043        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.shown {
14044            self.dismiss();
14045            ctx.request_semantics();
14046            ctx.set_handled();
14047        }
14048    }
14049
14050    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
14051        if !self.shown {
14052            return;
14053        }
14054
14055        match event {
14056            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
14057                let previous = self.reveal.value;
14058                let animating = self.reveal.advance(*time);
14059                if self.reveal.changed_since(previous) {
14060                    ctx.request_effect();
14061                    if !self.modal {
14062                        ctx.request_transform();
14063                    }
14064                }
14065                let previous_focus = self.focus_animation.value;
14066                let was_focus_presented = self.focus_animation.is_presented();
14067                let focus_animating = self.focus_animation.advance(*time);
14068                if self.focus_animation.changed_since(previous_focus) {
14069                    self.focus_state.borrow_mut().animation = self.focus_animation;
14070                    request_child_invalidation(
14071                        ctx,
14072                        self.focus_surface.child().id(),
14073                        InvalidationKind::Paint,
14074                    );
14075                }
14076                if was_focus_presented != self.focus_animation.is_presented() {
14077                    request_child_invalidation(
14078                        ctx,
14079                        self.focus_surface.child().id(),
14080                        InvalidationKind::Visibility,
14081                    );
14082                }
14083                if animating || focus_animating {
14084                    ctx.request_animation_frame();
14085                }
14086                ctx.set_handled();
14087            }
14088            Event::Pointer(pointer)
14089                if pointer.kind == PointerEventKind::Down
14090                    && pointer.button == Some(PointerButton::Primary)
14091                    && self
14092                        .dialog_frame
14093                        .translate(ctx.bounds().origin.to_vector())
14094                        .contains(pointer.position) =>
14095            {
14096                ctx.request_focus();
14097                ctx.request_semantics();
14098            }
14099            Event::Pointer(pointer)
14100                if pointer.kind == PointerEventKind::Down
14101                    && pointer.button == Some(PointerButton::Primary)
14102                    && !self
14103                        .dialog_frame
14104                        .translate(ctx.bounds().origin.to_vector())
14105                        .contains(pointer.position) =>
14106            {
14107                if self.dismiss_on_scrim {
14108                    self.dismiss();
14109                }
14110                if self.modal || self.dismiss_on_scrim {
14111                    ctx.set_handled();
14112                }
14113                ctx.request_paint();
14114                ctx.request_semantics();
14115            }
14116            Event::Keyboard(key)
14117                if ctx.is_focused() && key.state == KeyState::Pressed && key.key == "Escape" =>
14118            {
14119                self.dismiss();
14120                ctx.request_paint();
14121                ctx.request_semantics();
14122                ctx.set_handled();
14123            }
14124            _ => {}
14125        }
14126    }
14127
14128    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
14129        if !self.shown {
14130            self.dialog_frame = Rect::ZERO;
14131            self.body_frame = Rect::ZERO;
14132            self.reveal = AnimatedScalar::new(0.0);
14133            self.focus_animation = AnimatedScalar::new(0.0);
14134            self.entrance_started = false;
14135            let mut focus = self.focus_state.borrow_mut();
14136            focus.shown = false;
14137            focus.frame = Rect::ZERO;
14138            focus.animation = AnimatedScalar::new(0.0);
14139            return Size::ZERO;
14140        }
14141        self.ensure_entrance_started(ctx);
14142
14143        let viewport = constraints.clamp(Size::new(
14144            if constraints.max.width.is_finite() {
14145                constraints.max.width
14146            } else {
14147                640.0
14148            },
14149            if constraints.max.height.is_finite() {
14150                constraints.max.height
14151            } else {
14152                420.0
14153            },
14154        ));
14155        let metrics = self.theme.metrics;
14156        let outer_margin = metrics.dialog_outer_margin;
14157        let padding = metrics.dialog_padding;
14158        let title_style = self.title_style();
14159        let description_style = self.theme.placeholder_text_style();
14160        self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
14161        self.description_measurement = self
14162            .description
14163            .as_ref()
14164            .map(|text| measure_text(ctx, text, &description_style));
14165
14166        let dialog_width = (viewport.width - (outer_margin * 2.0))
14167            .min(self.resolved_max_width())
14168            .max(metrics.dialog_min_width);
14169        let mut footer_height: f32 = 0.0;
14170        for button in self.actions.as_mut_slice().iter_mut() {
14171            let button_size = button.measure(
14172                ctx,
14173                Constraints::new(
14174                    Size::ZERO,
14175                    Size::new(dialog_width, metrics.min_height + metrics.dialog_action_gap),
14176                ),
14177            );
14178            footer_height = footer_height.max(button_size.height);
14179        }
14180
14181        let title_height = self
14182            .title_measurement
14183            .map(|measurement| measurement.height.max(title_style.line_height))
14184            .unwrap_or(title_style.line_height);
14185        let description_height = self
14186            .description_measurement
14187            .map(|measurement| measurement.height.max(description_style.line_height))
14188            .unwrap_or(0.0);
14189        let header_gap = if self.description.is_some() {
14190            metrics.dialog_description_gap
14191        } else {
14192            0.0
14193        };
14194        let body_top =
14195            padding.top + title_height + header_gap + description_height + metrics.dialog_body_gap;
14196        let footer_gap = if self.actions.is_empty() {
14197            0.0
14198        } else {
14199            metrics.dialog_footer_gap
14200        };
14201        let body_constraints = Constraints::new(
14202            Size::ZERO,
14203            Size::new(
14204                (dialog_width - padding.left - padding.right).max(0.0),
14205                (viewport.height
14206                    - outer_margin * 2.0
14207                    - body_top
14208                    - footer_gap
14209                    - footer_height
14210                    - padding.bottom)
14211                    .max(0.0),
14212            ),
14213        );
14214        let body_size = self.body.measure(ctx, body_constraints);
14215
14216        let dialog_height =
14217            body_top + body_size.height + footer_gap + footer_height + padding.bottom;
14218        let dialog_x = ((viewport.width - dialog_width) * 0.5).max(outer_margin);
14219        let dialog_y = ((viewport.height - dialog_height) * 0.5).max(outer_margin);
14220        self.dialog_frame = Rect::new(dialog_x, dialog_y, dialog_width, dialog_height);
14221        self.body_frame = Rect::new(padding.left, body_top, body_size.width, body_size.height);
14222        {
14223            let mut focus = self.focus_state.borrow_mut();
14224            focus.theme = *self.theme;
14225            focus.shown = true;
14226            focus.frame = self.dialog_frame;
14227            focus.animation = self.focus_animation;
14228        }
14229        self.focus_surface
14230            .measure(ctx, Constraints::tight(self.dialog_frame.size));
14231
14232        viewport
14233    }
14234
14235    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
14236        if !self.shown {
14237            return;
14238        }
14239
14240        let dialog = self.dialog_frame.translate(bounds.origin.to_vector());
14241        self.focus_state.borrow_mut().frame = dialog;
14242        self.focus_surface.arrange(ctx, dialog);
14243        self.body.arrange(
14244            ctx,
14245            Rect::new(
14246                dialog.x() + self.body_frame.x(),
14247                dialog.y() + self.body_frame.y(),
14248                self.body_frame.width(),
14249                self.body_frame.height(),
14250            ),
14251        );
14252
14253        if !self.actions.is_empty() {
14254            let metrics = self.theme.metrics;
14255            let padding = metrics.dialog_padding;
14256            let action_gap = metrics.dialog_action_gap;
14257            let footer_width = self
14258                .actions
14259                .as_slice()
14260                .iter()
14261                .map(|button| button.measured_size().width)
14262                .sum::<f32>()
14263                + (action_gap * self.actions.len().saturating_sub(1) as f32);
14264            let footer_height = self
14265                .actions
14266                .as_slice()
14267                .iter()
14268                .map(|button| button.measured_size().height)
14269                .fold(0.0, f32::max);
14270            let mut x = dialog.x() + dialog.width() - padding.right - footer_width;
14271            let y = dialog.y() + dialog.height() - padding.bottom - footer_height;
14272            for button in self.actions.as_mut_slice().iter_mut() {
14273                let size = button.measured_size();
14274                button.arrange(ctx, Rect::new(x, y, size.width, size.height));
14275                x += size.width + action_gap;
14276            }
14277        }
14278    }
14279
14280    fn paint(&self, ctx: &mut PaintCtx) {
14281        if !self.shown {
14282            return;
14283        }
14284
14285        let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
14286
14287        if self.modal {
14288            ctx.fill_bounds(self.theme.surfaces.overlay_scrim);
14289        }
14290
14291        let metrics = self.theme.metrics;
14292        let palette = self.theme.palette;
14293        // Prominent elevation shadow behind the dialog surface, drawn over the
14294        // (optional) modal backdrop and before the surface fill.
14295        let surface_radius = metrics.corner_radius + 3.0;
14296        paint_theme_shadow(
14297            ctx,
14298            dialog,
14299            [surface_radius; 4],
14300            &self.theme.shadows.box_shadow.xl,
14301        );
14302        draw_control_frame(
14303            ctx,
14304            dialog,
14305            surface_radius,
14306            metrics,
14307            palette.surface_raised,
14308            palette.border,
14309            None,
14310        );
14311
14312        let title_style = self.title_style();
14313        let description_style = self.theme.placeholder_text_style();
14314        let padding = metrics.dialog_padding;
14315        let text_x = dialog.x() + padding.left;
14316        let text_y = dialog.y() + padding.top;
14317        let text_width = (dialog.width() - padding.left - padding.right).max(0.0);
14318        let title_height = self
14319            .title_measurement
14320            .map(|measurement| measurement.height.max(title_style.line_height))
14321            .unwrap_or(title_style.line_height);
14322        let title_slot = Rect::new(text_x, text_y, text_width, title_height);
14323        ctx.push_clip_rect(title_slot);
14324        paint_aligned_text(
14325            ctx,
14326            title_slot,
14327            &self.title,
14328            &title_style,
14329            title_style.line_height,
14330            0.0,
14331        );
14332        ctx.pop_clip();
14333        if let Some(description) = &self.description {
14334            let description_height = self
14335                .description_measurement
14336                .map(|measurement| measurement.height.max(description_style.line_height))
14337                .unwrap_or(description_style.line_height);
14338            let description_slot = Rect::new(
14339                text_x,
14340                title_slot.max_y() + metrics.dialog_description_gap,
14341                text_width,
14342                description_height,
14343            );
14344            ctx.push_clip_rect(description_slot);
14345            paint_aligned_text(
14346                ctx,
14347                description_slot,
14348                description,
14349                &description_style,
14350                description_style.line_height,
14351                0.0,
14352            );
14353            ctx.pop_clip();
14354        }
14355
14356        self.body.paint(ctx);
14357        for button in self.actions.as_slice() {
14358            button.paint(ctx);
14359        }
14360        self.focus_surface.paint(ctx);
14361    }
14362
14363    fn layer_options(&self) -> LayerOptions {
14364        LayerOptions {
14365            paint_boundary: PaintBoundaryMode::Explicit,
14366            composition_mode: if self.shown {
14367                if self.modal {
14368                    LayerCompositionMode::Effect
14369                } else {
14370                    LayerCompositionMode::Overlay
14371                }
14372            } else {
14373                LayerCompositionMode::Normal
14374            },
14375        }
14376    }
14377
14378    fn layer_properties(&self) -> LayerProperties {
14379        let translation = if self.modal {
14380            Vector::ZERO
14381        } else {
14382            Vector::new(
14383                0.0,
14384                self.theme.metrics.popover_reveal_offset * (1.0 - self.reveal.value),
14385            )
14386        };
14387        LayerProperties::new(self.reveal.value, translation)
14388    }
14389
14390    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
14391        self.shown.then_some(StackSurfaceOptions {
14392            transient: true,
14393            ..StackSurfaceOptions::default()
14394        })
14395    }
14396
14397    fn overlay_options(&self) -> Option<OverlayOptions> {
14398        self.shown.then_some(
14399            OverlayOptions::new(self.overlay_kind)
14400                .modal(self.modal)
14401                .dismiss(OverlayDismissPolicy {
14402                    escape: true,
14403                    outside_pointer: self.dismiss_on_scrim,
14404                })
14405                .focus(OverlayFocusBehavior::CONTAINED),
14406        )
14407    }
14408
14409    fn semantics(&self, ctx: &mut SemanticsCtx) {
14410        if !self.shown {
14411            return;
14412        }
14413
14414        let dialog = self.dialog_frame.translate(ctx.bounds().origin.to_vector());
14415        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Dialog, dialog);
14416        node.name = Some(self.title.clone());
14417        node.description = self.description.clone();
14418        node.state.focused = ctx.is_focused();
14419        node.state.expanded = Some(self.shown);
14420        node.state.modal = self.modal;
14421        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
14422        ctx.push(node);
14423        self.body.semantics(ctx);
14424        for button in self.actions.as_slice() {
14425            button.semantics(ctx);
14426        }
14427    }
14428
14429    fn accepts_focus(&self) -> bool {
14430        true
14431    }
14432
14433    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
14434        let was_presented = self.focus_animation.is_presented();
14435        set_focus_animation_target(
14436            &mut self.focus_animation,
14437            focused as u8 as f32,
14438            &self.theme,
14439            ctx,
14440        );
14441        self.focus_state.borrow_mut().animation = self.focus_animation;
14442        request_child_invalidation(
14443            ctx,
14444            self.focus_surface.child().id(),
14445            InvalidationKind::Paint,
14446        );
14447        if was_presented != self.focus_animation.is_presented() {
14448            request_child_invalidation(
14449                ctx,
14450                self.focus_surface.child().id(),
14451                InvalidationKind::Visibility,
14452            );
14453        }
14454        ctx.request_semantics();
14455    }
14456
14457    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
14458        if self.shown {
14459            self.body.visit_children(visitor);
14460            self.actions.visit_children(visitor);
14461            self.focus_surface.visit_children(visitor);
14462        }
14463    }
14464
14465    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
14466        if self.shown {
14467            self.body.visit_children_mut(visitor);
14468            self.actions.visit_children_mut(visitor);
14469            self.focus_surface.visit_children_mut(visitor);
14470        }
14471    }
14472}
14473
14474/// Modal presentation shell for application command search and execution.
14475///
14476/// Query state, ranking, and command execution remain application policies;
14477/// this shell supplies the shared overlay lifecycle and desktop interaction
14478/// behavior.
14479pub struct CommandPalette {
14480    inner: Dialog,
14481}
14482
14483impl CommandPalette {
14484    pub fn new<W>(name: impl Into<String>, content: W) -> Self
14485    where
14486        W: Widget + 'static,
14487    {
14488        let mut inner = Dialog::new(name, content).dismiss_on_scrim(true);
14489        inner.overlay_kind = OverlayKind::CommandPalette;
14490        Self { inner }
14491    }
14492
14493    pub fn theme(mut self, theme: DefaultTheme) -> Self {
14494        self.inner = self.inner.theme(theme);
14495        self
14496    }
14497
14498    pub fn shown(mut self, shown: bool) -> Self {
14499        self.inner = self.inner.shown(shown);
14500        self
14501    }
14502
14503    pub fn description(mut self, description: impl Into<String>) -> Self {
14504        self.inner = self.inner.description(description);
14505        self
14506    }
14507
14508    pub fn max_width(mut self, max_width: f32) -> Self {
14509        self.inner = self.inner.max_width(max_width);
14510        self
14511    }
14512
14513    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
14514    where
14515        F: FnMut() + 'static,
14516    {
14517        self.inner = self.inner.on_dismiss(on_dismiss);
14518        self
14519    }
14520}
14521
14522impl Widget for CommandPalette {
14523    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
14524        self.inner.command(ctx, command);
14525    }
14526
14527    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
14528        self.inner.event(ctx, event);
14529    }
14530
14531    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
14532        self.inner.measure(ctx, constraints)
14533    }
14534
14535    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
14536        self.inner.arrange(ctx, bounds);
14537    }
14538
14539    fn paint(&self, ctx: &mut PaintCtx) {
14540        self.inner.paint(ctx);
14541    }
14542
14543    fn layer_options(&self) -> LayerOptions {
14544        self.inner.layer_options()
14545    }
14546
14547    fn layer_properties(&self) -> LayerProperties {
14548        self.inner.layer_properties()
14549    }
14550
14551    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
14552        self.inner.stack_surface_options()
14553    }
14554
14555    fn overlay_options(&self) -> Option<OverlayOptions> {
14556        self.inner.overlay_options()
14557    }
14558
14559    fn semantics(&self, ctx: &mut SemanticsCtx) {
14560        self.inner.semantics(ctx);
14561    }
14562
14563    fn accepts_focus(&self) -> bool {
14564        self.inner.accepts_focus()
14565    }
14566
14567    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
14568        self.inner.focus_changed(ctx, focused);
14569    }
14570
14571    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
14572        self.inner.visit_children(visitor);
14573    }
14574
14575    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
14576        self.inner.visit_children_mut(visitor);
14577    }
14578}
14579
14580pub type Modal = Dialog;
14581
14582#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
14583pub enum SideSheetPlacement {
14584    Left,
14585    #[default]
14586    Right,
14587    Bottom,
14588}
14589
14590/// Cloneable presentation state shared by a sheet and application controls.
14591#[derive(Clone, Debug)]
14592pub struct SheetState {
14593    shown: Signal<bool>,
14594}
14595
14596impl SheetState {
14597    pub fn new(shown: bool) -> Self {
14598        Self {
14599            shown: Signal::named("SheetState", shown),
14600        }
14601    }
14602
14603    pub fn is_shown(&self) -> bool {
14604        self.shown.get()
14605    }
14606
14607    pub fn show(&self) -> bool {
14608        self.shown.set(true)
14609    }
14610
14611    pub fn hide(&self) -> bool {
14612        self.shown.set(false)
14613    }
14614
14615    pub fn toggle(&self) -> bool {
14616        self.shown.update(|shown| *shown = !*shown)
14617    }
14618}
14619
14620impl Default for SheetState {
14621    fn default() -> Self {
14622        Self::new(false)
14623    }
14624}
14625
14626/// An overlay panel anchored to a viewport edge.
14627///
14628/// `SideSheet` is suitable for responsive inspectors, conversation drawers,
14629/// and focused configuration flows. It shares SUI's dialog surface, spacing,
14630/// elevation, motion, focus, and semantic contracts while using a horizontal
14631/// reveal appropriate to a drawer.
14632pub struct SideSheet {
14633    theme: Box<DefaultTheme>,
14634    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
14635    title: String,
14636    description: Option<String>,
14637    shown: bool,
14638    state: Option<SheetState>,
14639    modal: bool,
14640    dismiss_on_scrim: bool,
14641    placement: SideSheetPlacement,
14642    width: Option<f32>,
14643    height: Option<f32>,
14644    body: SingleChild,
14645    header_action: Option<SingleChild>,
14646    actions: WidgetChildren,
14647    sheet_frame: Rect,
14648    body_frame: Rect,
14649    header_action_frame: Rect,
14650    title_measurement: Option<TextMeasurement>,
14651    description_measurement: Option<TextMeasurement>,
14652    reveal: AnimatedScalar,
14653    focus_animation: AnimatedScalar,
14654    entrance_started: bool,
14655    focus_requested: bool,
14656    previous_focus: Option<WidgetId>,
14657    on_dismiss: Option<Box<dyn FnMut()>>,
14658}
14659
14660impl SideSheet {
14661    pub fn new<W>(title: impl Into<String>, body: W) -> Self
14662    where
14663        W: Widget + 'static,
14664    {
14665        Self {
14666            theme: Box::new(DefaultTheme::default()),
14667            theme_reader: None,
14668            title: title.into(),
14669            description: None,
14670            shown: true,
14671            state: None,
14672            modal: true,
14673            dismiss_on_scrim: true,
14674            placement: SideSheetPlacement::Right,
14675            width: None,
14676            height: None,
14677            body: SingleChild::new(body),
14678            header_action: None,
14679            actions: WidgetChildren::new(),
14680            sheet_frame: Rect::ZERO,
14681            body_frame: Rect::ZERO,
14682            header_action_frame: Rect::ZERO,
14683            title_measurement: None,
14684            description_measurement: None,
14685            reveal: AnimatedScalar::new(0.0),
14686            focus_animation: AnimatedScalar::new(0.0),
14687            entrance_started: false,
14688            focus_requested: false,
14689            previous_focus: None,
14690            on_dismiss: None,
14691        }
14692    }
14693
14694    pub fn theme(mut self, theme: DefaultTheme) -> Self {
14695        self.theme = Box::new(theme);
14696        self.theme_reader = None;
14697        self
14698    }
14699
14700    pub fn theme_when<F>(mut self, theme: F) -> Self
14701    where
14702        F: Fn() -> DefaultTheme + 'static,
14703    {
14704        self.theme_reader = Some(Box::new(theme));
14705        self
14706    }
14707
14708    pub fn description(mut self, description: impl Into<String>) -> Self {
14709        self.description = Some(description.into());
14710        self
14711    }
14712
14713    pub fn shown(mut self, shown: bool) -> Self {
14714        self.set_shown(shown);
14715        self
14716    }
14717
14718    pub fn is_shown(&self) -> bool {
14719        self.shown
14720    }
14721
14722    pub fn set_shown(&mut self, shown: bool) -> bool {
14723        self.state = None;
14724        if self.shown == shown {
14725            return false;
14726        }
14727        self.shown = shown;
14728        if !self.shown {
14729            self.reveal = AnimatedScalar::new(0.0);
14730            self.focus_animation = AnimatedScalar::new(0.0);
14731            self.entrance_started = false;
14732            self.focus_requested = false;
14733            self.previous_focus = None;
14734        }
14735        true
14736    }
14737
14738    pub fn state(mut self, state: SheetState) -> Self {
14739        self.shown = state.is_shown();
14740        self.state = Some(state);
14741        self
14742    }
14743
14744    pub fn modal(mut self, modal: bool) -> Self {
14745        self.modal = modal;
14746        self
14747    }
14748
14749    pub fn dismiss_on_scrim(mut self, dismiss_on_scrim: bool) -> Self {
14750        self.dismiss_on_scrim = dismiss_on_scrim;
14751        self
14752    }
14753
14754    pub fn placement(mut self, placement: SideSheetPlacement) -> Self {
14755        self.placement = placement;
14756        self
14757    }
14758
14759    pub fn width(mut self, width: f32) -> Self {
14760        self.width = Some(width.max(0.0));
14761        self
14762    }
14763
14764    /// Set the panel height when placed at [`SideSheetPlacement::Bottom`].
14765    pub fn height(mut self, height: f32) -> Self {
14766        self.height = Some(height.max(0.0));
14767        self
14768    }
14769
14770    pub fn header_action<W>(mut self, action: W) -> Self
14771    where
14772        W: Widget + 'static,
14773    {
14774        self.header_action = Some(SingleChild::new(action));
14775        self
14776    }
14777
14778    pub fn action<W>(mut self, action: W) -> Self
14779    where
14780        W: Widget + 'static,
14781    {
14782        self.actions.push(action);
14783        self
14784    }
14785
14786    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
14787    where
14788        F: FnMut() + 'static,
14789    {
14790        let theme = self.resolved_theme();
14791        self.actions.push(
14792            Button::new(label)
14793                .theme(theme)
14794                .min_width(theme.metrics.dialog_action_min_width)
14795                .on_press(on_press),
14796        );
14797        self
14798    }
14799
14800    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
14801    where
14802        F: FnMut() + 'static,
14803    {
14804        let theme = self.resolved_theme();
14805        self.actions.push(
14806            Button::new(label)
14807                .theme(theme)
14808                .appearance(ButtonAppearance::Outline)
14809                .tone(SemanticTone::Neutral)
14810                .min_width(theme.metrics.dialog_action_min_width)
14811                .on_press(on_press),
14812        );
14813        self
14814    }
14815
14816    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
14817    where
14818        F: FnMut() + 'static,
14819    {
14820        self.on_dismiss = Some(Box::new(on_dismiss));
14821        self
14822    }
14823
14824    fn resolved_theme(&self) -> DefaultTheme {
14825        self.theme_reader
14826            .as_ref()
14827            .map(|theme| theme())
14828            .unwrap_or(*self.theme)
14829    }
14830
14831    fn resolved_width(&self, viewport_width: f32, theme: &DefaultTheme) -> f32 {
14832        self.width
14833            .unwrap_or(theme.metrics.dialog_max_width.min(420.0))
14834            .max(theme.metrics.dialog_min_width.min(viewport_width))
14835            .min(viewport_width)
14836            .max(0.0)
14837    }
14838
14839    fn resolved_height(&self, viewport_height: f32, theme: &DefaultTheme) -> f32 {
14840        self.height
14841            .unwrap_or((viewport_height * 0.62).min(560.0))
14842            .max(theme.metrics.touch_target_size * 3.0)
14843            .min(viewport_height)
14844            .max(0.0)
14845    }
14846
14847    fn title_style(theme: &DefaultTheme) -> TextStyle {
14848        TextStyle {
14849            font_size: theme.metrics.dialog_title_font_size,
14850            line_height: theme.metrics.dialog_title_line_height,
14851            color: theme.palette.text,
14852            ..theme.body_text_style()
14853        }
14854    }
14855
14856    fn dismiss(&mut self, ctx: &mut EventCtx) {
14857        if let Some(state) = &self.state {
14858            state.hide();
14859            self.shown = false;
14860            ctx.request_measure();
14861            ctx.request_paint();
14862        }
14863        if let Some(on_dismiss) = &mut self.on_dismiss {
14864            on_dismiss();
14865        }
14866        if let Some(previous_focus) = self.previous_focus.take() {
14867            ctx.request_focus_for(previous_focus);
14868        }
14869    }
14870
14871    fn contains_widget(&self, target: WidgetId) -> bool {
14872        struct Finder {
14873            target: WidgetId,
14874            found: bool,
14875        }
14876
14877        impl WidgetPodVisitor for Finder {
14878            fn visit(&mut self, child: &WidgetPod) {
14879                if self.found {
14880                    return;
14881                }
14882                if child.id() == self.target {
14883                    self.found = true;
14884                } else {
14885                    child.visit_children(self);
14886                }
14887            }
14888        }
14889
14890        fn inspect(pod: &WidgetPod, finder: &mut Finder) {
14891            if finder.found {
14892                return;
14893            }
14894            if pod.id() == finder.target {
14895                finder.found = true;
14896            } else {
14897                pod.visit_children(finder);
14898            }
14899        }
14900
14901        let mut finder = Finder {
14902            target,
14903            found: false,
14904        };
14905        inspect(self.body.child(), &mut finder);
14906        if let Some(action) = &self.header_action {
14907            inspect(action.child(), &mut finder);
14908        }
14909        for action in self.actions.as_slice() {
14910            inspect(action, &mut finder);
14911        }
14912        finder.found
14913    }
14914
14915    fn ensure_entrance_started(&mut self, ctx: &mut MeasureCtx) {
14916        if self.entrance_started {
14917            return;
14918        }
14919        self.entrance_started = true;
14920        let motion = self.resolved_theme().motion;
14921        let reveal_animating = self.reveal.set_target(
14922            1.0,
14923            ctx.current_time(),
14924            f64::from(motion.duration_slower),
14925            motion.easing_decelerate,
14926        );
14927        if reveal_animating || !self.focus_requested {
14928            ctx.request_animation_frame();
14929        }
14930    }
14931
14932    fn reveal_offset(&self) -> Vector {
14933        let horizontal_distance = self.sheet_frame.width() * (1.0 - self.reveal.value);
14934        let vertical_distance = self.sheet_frame.height() * (1.0 - self.reveal.value);
14935        match self.placement {
14936            SideSheetPlacement::Left => Vector::new(-horizontal_distance, 0.0),
14937            SideSheetPlacement::Right => Vector::new(horizontal_distance, 0.0),
14938            SideSheetPlacement::Bottom => Vector::new(0.0, vertical_distance),
14939        }
14940    }
14941
14942    fn presented_sheet(&self, origin: Point) -> Rect {
14943        self.sheet_frame
14944            .translate(origin.to_vector() + self.reveal_offset())
14945    }
14946}
14947
14948impl Widget for SideSheet {
14949    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
14950        if command.get(OVERLAY_DISMISS_REQUEST).is_some() && self.is_shown() {
14951            self.dismiss(ctx);
14952            ctx.set_handled();
14953        }
14954    }
14955
14956    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
14957        if let Some(state) = &self.state {
14958            self.shown = state.is_shown();
14959        }
14960        if !self.shown {
14961            return;
14962        }
14963        match event {
14964            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
14965                if !self.focus_requested {
14966                    self.focus_requested = true;
14967                    let current_focus = ctx.focused_widget_id();
14968                    let focus_is_inside = current_focus.is_some_and(|focused| {
14969                        focused == ctx.widget_id() || self.contains_widget(focused)
14970                    });
14971                    if !focus_is_inside {
14972                        self.previous_focus = current_focus;
14973                        ctx.request_focus();
14974                    }
14975                }
14976                let previous = self.reveal.value;
14977                let previous_focus = self.focus_animation.value;
14978                if self.reveal.advance(*time) | self.focus_animation.advance(*time) {
14979                    ctx.request_animation_frame();
14980                }
14981                if self.reveal.changed_since(previous)
14982                    || self.focus_animation.changed_since(previous_focus)
14983                {
14984                    ctx.request_paint();
14985                }
14986                ctx.set_handled();
14987            }
14988            Event::Semantics(semantics)
14989                if semantics.target == ctx.widget_id()
14990                    && matches!(semantics.action, sui_core::SemanticsActionRequest::Collapse) =>
14991            {
14992                self.dismiss(ctx);
14993                ctx.request_semantics();
14994                ctx.set_handled();
14995            }
14996            Event::Pointer(pointer)
14997                if pointer.kind == PointerEventKind::Down
14998                    && pointer.button == Some(PointerButton::Primary) =>
14999            {
15000                if self
15001                    .presented_sheet(ctx.bounds().origin)
15002                    .contains(pointer.position)
15003                {
15004                    ctx.request_focus();
15005                    ctx.request_semantics();
15006                } else {
15007                    if self.dismiss_on_scrim {
15008                        self.dismiss(ctx);
15009                    }
15010                    if self.modal || self.dismiss_on_scrim {
15011                        ctx.set_handled();
15012                    }
15013                    ctx.request_semantics();
15014                }
15015            }
15016            Event::Keyboard(key) if key.state == KeyState::Pressed && key.key == "Escape" => {
15017                self.dismiss(ctx);
15018                ctx.request_semantics();
15019                ctx.set_handled();
15020            }
15021            _ => {}
15022        }
15023    }
15024
15025    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15026        if let Some(state) = &self.state {
15027            self.shown = ctx.observe(&state.shown);
15028        }
15029        if !self.shown {
15030            self.sheet_frame = Rect::ZERO;
15031            self.body_frame = Rect::ZERO;
15032            self.header_action_frame = Rect::ZERO;
15033            self.reveal = AnimatedScalar::new(0.0);
15034            self.focus_animation = AnimatedScalar::new(0.0);
15035            self.entrance_started = false;
15036            self.focus_requested = false;
15037            self.previous_focus = None;
15038            return Size::ZERO;
15039        }
15040        self.ensure_entrance_started(ctx);
15041
15042        let viewport = constraints.clamp(Size::new(
15043            if constraints.max.width.is_finite() {
15044                constraints.max.width
15045            } else {
15046                960.0
15047            },
15048            if constraints.max.height.is_finite() {
15049                constraints.max.height
15050            } else {
15051                640.0
15052            },
15053        ));
15054        let theme = self.resolved_theme();
15055        let metrics = theme.metrics;
15056        let padding = metrics.dialog_padding;
15057        let (sheet_x, sheet_y, sheet_width, sheet_height) = match self.placement {
15058            SideSheetPlacement::Left => (
15059                0.0,
15060                0.0,
15061                self.resolved_width(viewport.width, &theme),
15062                viewport.height,
15063            ),
15064            SideSheetPlacement::Right => {
15065                let width = self.resolved_width(viewport.width, &theme);
15066                (viewport.width - width, 0.0, width, viewport.height)
15067            }
15068            SideSheetPlacement::Bottom => {
15069                let height = self.resolved_height(viewport.height, &theme);
15070                (0.0, viewport.height - height, viewport.width, height)
15071            }
15072        };
15073        self.sheet_frame = Rect::new(sheet_x, sheet_y, sheet_width, sheet_height);
15074
15075        let title_style = Self::title_style(&theme);
15076        let description_style = theme.placeholder_text_style();
15077        self.title_measurement = Some(measure_text(ctx, &self.title, &title_style));
15078        self.description_measurement = self
15079            .description
15080            .as_ref()
15081            .map(|description| measure_text(ctx, description, &description_style));
15082
15083        let header_action_size = if let Some(action) = &mut self.header_action {
15084            action.measure(
15085                ctx,
15086                Constraints::new(
15087                    Size::ZERO,
15088                    Size::new(
15089                        (sheet_width - padding.left - padding.right).max(0.0),
15090                        metrics.touch_target_size,
15091                    ),
15092                ),
15093            )
15094        } else {
15095            Size::ZERO
15096        };
15097        let title_height = self
15098            .title_measurement
15099            .map(|measurement| measurement.height.max(title_style.line_height))
15100            .unwrap_or(title_style.line_height)
15101            .max(header_action_size.height);
15102        let description_height = self
15103            .description_measurement
15104            .map(|measurement| measurement.height.max(description_style.line_height))
15105            .unwrap_or(0.0);
15106        let description_gap = if self.description.is_some() {
15107            metrics.dialog_description_gap
15108        } else {
15109            0.0
15110        };
15111        let body_top = padding.top
15112            + title_height
15113            + description_gap
15114            + description_height
15115            + metrics.dialog_body_gap;
15116
15117        let mut footer_height: f32 = 0.0;
15118        for action in self.actions.as_mut_slice() {
15119            footer_height = footer_height.max(
15120                action
15121                    .measure(
15122                        ctx,
15123                        Constraints::new(
15124                            Size::ZERO,
15125                            Size::new(sheet_width, metrics.touch_target_size),
15126                        ),
15127                    )
15128                    .height,
15129            );
15130        }
15131        let footer_gap = if self.actions.is_empty() {
15132            0.0
15133        } else {
15134            metrics.dialog_footer_gap
15135        };
15136        let body_height =
15137            (sheet_height - body_top - footer_gap - footer_height - padding.bottom).max(0.0);
15138        let body_width = (sheet_width - padding.left - padding.right).max(0.0);
15139        let _ = self.body.measure(
15140            ctx,
15141            Constraints::new(Size::ZERO, Size::new(body_width, body_height)),
15142        );
15143        self.body_frame = Rect::new(padding.left, body_top, body_width, body_height);
15144        self.header_action_frame = Rect::new(
15145            sheet_width - padding.right - header_action_size.width,
15146            padding.top,
15147            header_action_size.width,
15148            header_action_size.height,
15149        );
15150        viewport
15151    }
15152
15153    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
15154        if !self.shown {
15155            return;
15156        }
15157        let sheet = self.sheet_frame.translate(bounds.origin.to_vector());
15158        self.body
15159            .arrange(ctx, self.body_frame.translate(sheet.origin.to_vector()));
15160        if let Some(action) = &mut self.header_action {
15161            action.arrange(
15162                ctx,
15163                self.header_action_frame.translate(sheet.origin.to_vector()),
15164            );
15165        }
15166        if !self.actions.is_empty() {
15167            let theme = self.resolved_theme();
15168            let metrics = theme.metrics;
15169            let padding = metrics.dialog_padding;
15170            let gap = metrics.dialog_action_gap;
15171            let total_width = self
15172                .actions
15173                .as_slice()
15174                .iter()
15175                .map(|action| action.measured_size().width)
15176                .sum::<f32>()
15177                + gap * self.actions.len().saturating_sub(1) as f32;
15178            let footer_height = self
15179                .actions
15180                .as_slice()
15181                .iter()
15182                .map(|action| action.measured_size().height)
15183                .fold(0.0, f32::max);
15184            let mut x = sheet.max_x() - padding.right - total_width;
15185            let y = sheet.max_y() - padding.bottom - footer_height;
15186            for action in self.actions.as_mut_slice() {
15187                let size = action.measured_size();
15188                action.arrange(ctx, Rect::new(x, y, size.width, size.height));
15189                x += size.width + gap;
15190            }
15191        }
15192    }
15193
15194    fn paint(&self, ctx: &mut PaintCtx) {
15195        if !self.shown {
15196            return;
15197        }
15198        let theme = self.resolved_theme();
15199        if self.modal {
15200            let scrim = theme
15201                .surfaces
15202                .overlay_scrim
15203                .with_alpha(theme.surfaces.overlay_scrim.alpha * self.reveal.value);
15204            ctx.fill_bounds(scrim);
15205        }
15206
15207        let reveal_offset = self.reveal_offset();
15208        ctx.push_transform(Transform::translation(reveal_offset.x, reveal_offset.y));
15209        let sheet = self.sheet_frame.translate(ctx.bounds().origin.to_vector());
15210        let metrics = theme.metrics;
15211        paint_theme_shadow(ctx, sheet, [0.0; 4], &theme.shadows.box_shadow.xl);
15212        ctx.fill_rect(sheet, theme.palette.surface_raised);
15213        let border_width = physical_pixels(ctx, metrics.border_width.max(1.0));
15214        let border = match self.placement {
15215            SideSheetPlacement::Left => Rect::new(
15216                sheet.max_x() - border_width,
15217                sheet.y(),
15218                border_width,
15219                sheet.height(),
15220            ),
15221            SideSheetPlacement::Right => {
15222                Rect::new(sheet.x(), sheet.y(), border_width, sheet.height())
15223            }
15224            SideSheetPlacement::Bottom => {
15225                Rect::new(sheet.x(), sheet.y(), sheet.width(), border_width)
15226            }
15227        };
15228        ctx.fill_rect(border, theme.palette.border);
15229        if self.focus_animation.value > AnimatedScalar::EPSILON {
15230            let inset = physical_pixels(ctx, theme.metrics.focus_ring_width) * 0.5;
15231            ctx.stroke(
15232                rounded_rect_path(sheet.inflate(-inset, -inset), 0.0),
15233                theme
15234                    .palette
15235                    .focus_ring
15236                    .with_alpha(theme.palette.focus_ring.alpha * self.focus_animation.value),
15237                StrokeStyle::new(physical_pixels(ctx, theme.metrics.focus_ring_width)),
15238            );
15239        }
15240
15241        let padding = metrics.dialog_padding;
15242        let title_style = Self::title_style(&theme);
15243        let action_width = if self.header_action.is_some() {
15244            self.header_action_frame.width() + metrics.dialog_action_gap
15245        } else {
15246            0.0
15247        };
15248        let title_height = self
15249            .title_measurement
15250            .map(|measurement| measurement.height.max(title_style.line_height))
15251            .unwrap_or(title_style.line_height)
15252            .max(self.header_action_frame.height());
15253        let title_slot = Rect::new(
15254            sheet.x() + padding.left,
15255            sheet.y() + padding.top,
15256            (sheet.width() - padding.left - padding.right - action_width).max(0.0),
15257            title_height,
15258        );
15259        paint_aligned_text(
15260            ctx,
15261            title_slot,
15262            &self.title,
15263            &title_style,
15264            title_style.line_height,
15265            0.0,
15266        );
15267        if let Some(description) = &self.description {
15268            let style = theme.placeholder_text_style();
15269            let height = self
15270                .description_measurement
15271                .map(|measurement| measurement.height.max(style.line_height))
15272                .unwrap_or(style.line_height);
15273            let slot = Rect::new(
15274                sheet.x() + padding.left,
15275                title_slot.max_y() + metrics.dialog_description_gap,
15276                (sheet.width() - padding.left - padding.right).max(0.0),
15277                height,
15278            );
15279            paint_aligned_text(ctx, slot, description, &style, style.line_height, 0.0);
15280        }
15281        self.body.paint(ctx);
15282        if let Some(action) = &self.header_action {
15283            action.paint(ctx);
15284        }
15285        self.actions.paint(ctx);
15286        ctx.pop_transform();
15287    }
15288
15289    fn layer_options(&self) -> LayerOptions {
15290        LayerOptions {
15291            paint_boundary: PaintBoundaryMode::Explicit,
15292            composition_mode: if self.shown {
15293                LayerCompositionMode::Overlay
15294            } else {
15295                LayerCompositionMode::Normal
15296            },
15297        }
15298    }
15299
15300    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
15301        self.shown.then_some(StackSurfaceOptions {
15302            transient: true,
15303            ..StackSurfaceOptions::default()
15304        })
15305    }
15306
15307    fn overlay_options(&self) -> Option<OverlayOptions> {
15308        self.is_shown().then_some(
15309            OverlayOptions::new(OverlayKind::Sheet)
15310                .modal(self.modal)
15311                .dismiss(OverlayDismissPolicy {
15312                    escape: true,
15313                    outside_pointer: self.dismiss_on_scrim,
15314                })
15315                .focus(OverlayFocusBehavior::CONTAINED),
15316        )
15317    }
15318
15319    fn semantics(&self, ctx: &mut SemanticsCtx) {
15320        if !self.shown {
15321            return;
15322        }
15323        let mut node = SemanticsNode::new(
15324            ctx.widget_id(),
15325            SemanticsRole::Dialog,
15326            self.sheet_frame.translate(ctx.bounds().origin.to_vector()),
15327        );
15328        node.name = Some(self.title.clone());
15329        node.description = self.description.clone();
15330        node.state.focused = ctx.is_focused();
15331        node.state.expanded = Some(true);
15332        node.state.modal = self.modal;
15333        node.actions = vec![SemanticsAction::Focus, SemanticsAction::Collapse];
15334        ctx.push(node);
15335        self.body.semantics(ctx);
15336        if let Some(action) = &self.header_action {
15337            action.semantics(ctx);
15338        }
15339        self.actions.semantics(ctx);
15340    }
15341
15342    fn accepts_focus(&self) -> bool {
15343        self.shown
15344    }
15345
15346    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
15347        let theme = self.resolved_theme();
15348        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
15349        ctx.request_paint();
15350        ctx.request_semantics();
15351    }
15352
15353    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
15354        if self.shown {
15355            self.body.visit_children(visitor);
15356            if let Some(action) = &self.header_action {
15357                action.visit_children(visitor);
15358            }
15359            self.actions.visit_children(visitor);
15360        }
15361    }
15362
15363    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
15364        if self.shown {
15365            self.body.visit_children_mut(visitor);
15366            if let Some(action) = &mut self.header_action {
15367                action.visit_children_mut(visitor);
15368            }
15369            self.actions.visit_children_mut(visitor);
15370        }
15371    }
15372}
15373
15374/// A familiar alias for navigation-oriented side sheets.
15375pub type Drawer = SideSheet;
15376
15377/// A modal surface anchored to the bottom edge of its allocated viewport.
15378///
15379/// `BottomSheet` follows the same focus, dismissal, semantics, and action
15380/// contracts as [`SideSheet`], while exposing height-oriented configuration.
15381pub struct BottomSheet {
15382    inner: SideSheet,
15383}
15384
15385impl BottomSheet {
15386    pub fn new<W>(title: impl Into<String>, body: W) -> Self
15387    where
15388        W: Widget + 'static,
15389    {
15390        Self {
15391            inner: SideSheet::new(title, body).placement(SideSheetPlacement::Bottom),
15392        }
15393    }
15394
15395    pub fn theme(mut self, theme: DefaultTheme) -> Self {
15396        self.inner = self.inner.theme(theme);
15397        self
15398    }
15399
15400    pub fn theme_when<F>(mut self, theme: F) -> Self
15401    where
15402        F: Fn() -> DefaultTheme + 'static,
15403    {
15404        self.inner = self.inner.theme_when(theme);
15405        self
15406    }
15407
15408    pub fn description(mut self, description: impl Into<String>) -> Self {
15409        self.inner = self.inner.description(description);
15410        self
15411    }
15412
15413    pub fn shown(mut self, shown: bool) -> Self {
15414        self.inner = self.inner.shown(shown);
15415        self
15416    }
15417
15418    pub fn state(mut self, state: SheetState) -> Self {
15419        self.inner = self.inner.state(state);
15420        self
15421    }
15422
15423    pub fn modal(mut self, modal: bool) -> Self {
15424        self.inner = self.inner.modal(modal);
15425        self
15426    }
15427
15428    pub fn dismiss_on_scrim(mut self, dismiss: bool) -> Self {
15429        self.inner = self.inner.dismiss_on_scrim(dismiss);
15430        self
15431    }
15432
15433    pub fn height(mut self, height: f32) -> Self {
15434        self.inner = self.inner.height(height);
15435        self
15436    }
15437
15438    pub fn header_action<W>(mut self, action: W) -> Self
15439    where
15440        W: Widget + 'static,
15441    {
15442        self.inner = self.inner.header_action(action);
15443        self
15444    }
15445
15446    pub fn action<W>(mut self, action: W) -> Self
15447    where
15448        W: Widget + 'static,
15449    {
15450        self.inner = self.inner.action(action);
15451        self
15452    }
15453
15454    pub fn primary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15455    where
15456        F: FnMut() + 'static,
15457    {
15458        self.inner = self.inner.primary_action(label, on_press);
15459        self
15460    }
15461
15462    pub fn secondary_action<F>(mut self, label: impl Into<String>, on_press: F) -> Self
15463    where
15464        F: FnMut() + 'static,
15465    {
15466        self.inner = self.inner.secondary_action(label, on_press);
15467        self
15468    }
15469
15470    pub fn on_dismiss<F>(mut self, on_dismiss: F) -> Self
15471    where
15472        F: FnMut() + 'static,
15473    {
15474        self.inner = self.inner.on_dismiss(on_dismiss);
15475        self
15476    }
15477}
15478
15479impl Widget for BottomSheet {
15480    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
15481        self.inner.command(ctx, command);
15482    }
15483
15484    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
15485        self.inner.event(ctx, event);
15486    }
15487
15488    fn debug_name(&self) -> &'static str {
15489        "sui_widgets::BottomSheet"
15490    }
15491
15492    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15493        self.inner.measure(ctx, constraints)
15494    }
15495
15496    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
15497        self.inner.arrange(ctx, bounds);
15498    }
15499
15500    fn paint(&self, ctx: &mut PaintCtx) {
15501        self.inner.paint(ctx);
15502    }
15503
15504    fn layer_options(&self) -> LayerOptions {
15505        self.inner.layer_options()
15506    }
15507
15508    fn layer_properties(&self) -> LayerProperties {
15509        self.inner.layer_properties()
15510    }
15511
15512    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
15513        self.inner.stack_surface_options()
15514    }
15515
15516    fn overlay_options(&self) -> Option<OverlayOptions> {
15517        self.inner.overlay_options()
15518    }
15519
15520    fn semantics(&self, ctx: &mut SemanticsCtx) {
15521        self.inner.semantics(ctx);
15522    }
15523
15524    fn accepts_focus(&self) -> bool {
15525        self.inner.accepts_focus()
15526    }
15527
15528    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
15529        self.inner.focus_changed(ctx, focused);
15530    }
15531
15532    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
15533        self.inner.visit_children(visitor);
15534    }
15535
15536    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
15537        self.inner.visit_children_mut(visitor);
15538    }
15539}
15540
15541pub struct ProgressBar {
15542    theme: Box<DefaultTheme>,
15543    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
15544    name: String,
15545    min: f64,
15546    max: f64,
15547    value: f64,
15548    tone: SemanticTone,
15549    min_width: Option<f32>,
15550    height: Option<f32>,
15551    show_value: bool,
15552}
15553
15554impl ProgressBar {
15555    pub fn new(name: impl Into<String>) -> Self {
15556        Self {
15557            theme: Box::new(DefaultTheme::default()),
15558            theme_reader: None,
15559            name: name.into(),
15560            min: 0.0,
15561            max: 1.0,
15562            value: 0.0,
15563            tone: SemanticTone::Accent,
15564            min_width: None,
15565            height: None,
15566            show_value: false,
15567        }
15568    }
15569
15570    pub fn theme(mut self, theme: DefaultTheme) -> Self {
15571        self.theme = Box::new(theme);
15572        self.theme_reader = None;
15573        self
15574    }
15575
15576    pub fn theme_when<F>(mut self, theme: F) -> Self
15577    where
15578        F: Fn() -> DefaultTheme + 'static,
15579    {
15580        self.theme_reader = Some(Box::new(theme));
15581        self
15582    }
15583
15584    pub fn range(mut self, min: f64, max: f64) -> Self {
15585        self.min = min.min(max);
15586        self.max = max.max(min);
15587        self.value = self.value.clamp(self.min, self.max);
15588        self
15589    }
15590
15591    pub fn value(mut self, value: f64) -> Self {
15592        self.value = value.clamp(self.min, self.max);
15593        self
15594    }
15595
15596    pub fn tone(mut self, tone: SemanticTone) -> Self {
15597        self.tone = tone;
15598        self
15599    }
15600
15601    pub fn min_width(mut self, min_width: f32) -> Self {
15602        self.min_width = Some(min_width.max(0.0));
15603        self
15604    }
15605
15606    pub fn height(mut self, height: f32) -> Self {
15607        self.height = Some(height.max(1.0));
15608        self
15609    }
15610
15611    pub fn show_value(mut self, show_value: bool) -> Self {
15612        self.show_value = show_value;
15613        self
15614    }
15615
15616    fn fraction(&self) -> f32 {
15617        if (self.max - self.min).abs() <= f64::EPSILON {
15618            0.0
15619        } else {
15620            ((self.value - self.min) / (self.max - self.min)).clamp(0.0, 1.0) as f32
15621        }
15622    }
15623
15624    fn resolved_theme(&self) -> DefaultTheme {
15625        self.theme_reader
15626            .as_ref()
15627            .map(|theme| theme())
15628            .unwrap_or(*self.theme)
15629    }
15630}
15631
15632pub fn paint_progress_bar(
15633    ctx: &mut PaintCtx,
15634    rect: Rect,
15635    theme: &DefaultTheme,
15636    fraction: f32,
15637    tone: SemanticTone,
15638) {
15639    if rect.width() <= 0.0 || rect.height() <= 0.0 {
15640        return;
15641    }
15642
15643    let metrics = theme.metrics;
15644    let palette = theme.palette;
15645    let (tone, _) = theme.semantic_tone_colors(tone);
15646    draw_control_shape(
15647        ctx,
15648        rect,
15649        metrics.corner_radius,
15650        physical_pixels(ctx, metrics.border_width).min(rect.height() * 0.5),
15651        palette.control,
15652        palette.border,
15653    );
15654
15655    let fill = Rect::new(
15656        rect.x(),
15657        rect.y(),
15658        rect.width() * fraction.clamp(0.0, 1.0),
15659        rect.height(),
15660    );
15661    if fill.width() > 0.0 {
15662        ctx.fill(rounded_rect_path(fill, metrics.corner_radius), tone);
15663    }
15664}
15665
15666impl Widget for ProgressBar {
15667    fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15668        let theme = self.resolved_theme();
15669        let metrics = theme.metrics;
15670        let min_height = if let Some(height) = self.height {
15671            height
15672        } else if self.show_value {
15673            metrics
15674                .progress_bar_value_height
15675                .max(text_token_style(&theme, theme.text.sm, theme.palette.text).line_height)
15676        } else {
15677            metrics.progress_bar_height
15678        };
15679        constraints.clamp(Size::new(
15680            self.min_width.unwrap_or(metrics.progress_bar_min_width),
15681            min_height,
15682        ))
15683    }
15684
15685    fn paint(&self, ctx: &mut PaintCtx) {
15686        let theme = self.resolved_theme();
15687        let metrics = theme.metrics;
15688        let (_, tone_text) = theme.semantic_tone_colors(self.tone);
15689        paint_progress_bar(ctx, ctx.bounds(), &theme, self.fraction(), self.tone);
15690        if self.show_value {
15691            let label = format!("{:.0}%", self.fraction() * 100.0);
15692            let text_style = numeric_text_style(text_token_style(&theme, theme.text.sm, tone_text));
15693            let label_padding = Insets {
15694                top: 0.0,
15695                bottom: 0.0,
15696                ..metrics.progress_bar_label_padding
15697            };
15698            let label_slot = inset_rect(ctx.bounds(), label_padding);
15699            ctx.push_clip_rect(label_slot);
15700            paint_aligned_text(
15701                ctx,
15702                label_slot,
15703                &label,
15704                &text_style,
15705                text_style.line_height,
15706                0.5,
15707            );
15708            ctx.pop_clip();
15709        }
15710    }
15711
15712    fn semantics(&self, ctx: &mut SemanticsCtx) {
15713        let mut node =
15714            SemanticsNode::new(ctx.widget_id(), SemanticsRole::ProgressBar, ctx.bounds());
15715        node.name = Some(self.name.clone());
15716        node.value = Some(SemanticsValue::Range {
15717            value: self.value,
15718            min: self.min,
15719            max: self.max,
15720        });
15721        ctx.push(node);
15722    }
15723}
15724
15725pub struct Spinner {
15726    theme: Box<DefaultTheme>,
15727    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
15728    name: String,
15729    size: f32,
15730    label: Option<String>,
15731}
15732
15733impl Spinner {
15734    pub fn new(name: impl Into<String>) -> Self {
15735        Self {
15736            theme: Box::new(DefaultTheme::default()),
15737            theme_reader: None,
15738            name: name.into(),
15739            size: 20.0,
15740            label: None,
15741        }
15742    }
15743
15744    pub fn theme(mut self, theme: DefaultTheme) -> Self {
15745        self.theme = Box::new(theme);
15746        self.theme_reader = None;
15747        self
15748    }
15749
15750    pub fn theme_when<F>(mut self, theme: F) -> Self
15751    where
15752        F: Fn() -> DefaultTheme + 'static,
15753    {
15754        self.theme_reader = Some(Box::new(theme));
15755        self
15756    }
15757
15758    pub fn size(mut self, size: f32) -> Self {
15759        self.size = size.max(8.0);
15760        self
15761    }
15762
15763    pub fn label(mut self, label: impl Into<String>) -> Self {
15764        self.label = Some(label.into());
15765        self
15766    }
15767
15768    fn indicator_rect(&self, bounds: Rect) -> Rect {
15769        Rect::new(
15770            bounds.x(),
15771            bounds.y() + ((bounds.height() - self.size) * 0.5),
15772            self.size,
15773            self.size,
15774        )
15775    }
15776
15777    fn resolved_theme(&self) -> DefaultTheme {
15778        self.theme_reader
15779            .as_ref()
15780            .map(|theme| theme())
15781            .unwrap_or(*self.theme)
15782    }
15783}
15784
15785impl Widget for Spinner {
15786    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
15787        let theme = self.resolved_theme();
15788        let text_style = text_token_style(&theme, theme.text.sm, theme.palette.text);
15789        let label_measurement = self
15790            .label
15791            .as_ref()
15792            .map(|label| measure_text(ctx, label, &text_style));
15793        let label_width = label_measurement
15794            .map(|measurement| measurement.width + 12.0)
15795            .unwrap_or(0.0);
15796        let label_height = label_measurement
15797            .map(|measurement| measurement.height.max(text_style.line_height))
15798            .unwrap_or(0.0);
15799        constraints.clamp(Size::new(
15800            self.size + label_width,
15801            self.size.max(20.0).max(label_height),
15802        ))
15803    }
15804
15805    fn paint(&self, ctx: &mut PaintCtx) {
15806        let theme = self.resolved_theme();
15807        let palette = theme.palette;
15808        let indicator = self.indicator_rect(ctx.bounds());
15809        let center = rect_center(indicator);
15810        let radius = indicator.width().min(indicator.height()) * 0.4;
15811        let dot_radius = (indicator.width() * 0.09).max(1.5);
15812        for index in 0..10 {
15813            let angle = (index as f32 / 10.0) * std::f32::consts::TAU;
15814            let alpha = 0.22 + ((index as f32) / 10.0) * 0.72;
15815            let color = Color::rgba(
15816                palette.accent.red,
15817                palette.accent.green,
15818                palette.accent.blue,
15819                alpha,
15820            );
15821            let dot = Point::new(
15822                center.x + angle.cos() * radius,
15823                center.y + angle.sin() * radius,
15824            );
15825            ctx.fill(Path::circle(dot, dot_radius), color);
15826        }
15827
15828        if let Some(label) = &self.label {
15829            let text_style = text_token_style(&theme, theme.text.sm, palette.text);
15830            let text_slot = Rect::new(
15831                indicator.max_x() + 12.0,
15832                ctx.bounds().y(),
15833                ctx.bounds().width() - indicator.width() - 12.0,
15834                ctx.bounds().height(),
15835            );
15836            ctx.push_clip_rect(text_slot);
15837            paint_aligned_text(
15838                ctx,
15839                text_slot,
15840                label,
15841                &text_style,
15842                text_style.line_height,
15843                0.0,
15844            );
15845            ctx.pop_clip();
15846        }
15847    }
15848
15849    fn semantics(&self, ctx: &mut SemanticsCtx) {
15850        let mut node =
15851            SemanticsNode::new(ctx.widget_id(), SemanticsRole::BusyIndicator, ctx.bounds());
15852        node.name = Some(self.name.clone());
15853        node.description = self.label.clone();
15854        node.state.busy = true;
15855        ctx.push(node);
15856    }
15857}
15858
15859pub type BusyIndicator = Spinner;
15860
15861fn measure_text(ctx: &mut MeasureCtx, text: &str, style: &TextStyle) -> TextMeasurement {
15862    ctx.layout()
15863        .measure_text(text.to_string(), style.clone())
15864        .unwrap_or(TextMeasurement {
15865            width: 0.0,
15866            height: style.line_height,
15867            bounds: Rect::new(0.0, 0.0, 0.0, style.line_height),
15868            ascent: style.font_size,
15869            descent: 0.0,
15870            cap_height: Some(style.font_size),
15871        })
15872}
15873
15874fn text_token_style(theme: &DefaultTheme, token: ThemeTextToken, color: Color) -> TextStyle {
15875    TextStyle {
15876        font_size: token.size.max(1.0),
15877        line_height: token.line_height.max(1.0),
15878        color,
15879        ..theme.body_text_style()
15880    }
15881}
15882
15883fn numeric_text_style(mut style: TextStyle) -> TextStyle {
15884    style.features.enable(FontFeature::TABULAR_FIGURES);
15885    style
15886}
15887
15888fn numeric_text_style_if_numeric(text: &str, style: TextStyle) -> TextStyle {
15889    if text_contains_ascii_digit(text) {
15890        numeric_text_style(style)
15891    } else {
15892        style
15893    }
15894}
15895
15896fn text_contains_ascii_digit(text: &str) -> bool {
15897    text.chars().any(|c| c.is_ascii_digit())
15898}
15899
15900fn rect_center(rect: Rect) -> Point {
15901    Point::new(
15902        rect.x() + (rect.width() * 0.5),
15903        rect.y() + (rect.height() * 0.5),
15904    )
15905}
15906
15907fn inset_rect(rect: Rect, padding: Insets) -> Rect {
15908    Rect::new(
15909        rect.x() + padding.left,
15910        rect.y() + padding.top,
15911        (rect.width() - padding.left - padding.right).max(0.0),
15912        (rect.height() - padding.top - padding.bottom).max(0.0),
15913    )
15914}
15915
15916fn rounded_rect_path(rect: Rect, radius: f32) -> Path {
15917    Path::rounded_rect(rect, radius.min(rect.width().min(rect.height()) * 0.5))
15918}
15919
15920fn tab_indicator_rect<F>(
15921    mut tab_rect: F,
15922    from_index: usize,
15923    selected_index: usize,
15924    progress: f32,
15925    padding: Insets,
15926    thickness: f32,
15927) -> Option<Rect>
15928where
15929    F: FnMut(usize) -> Option<Rect>,
15930{
15931    let to = tab_indicator_from_tab_rect(tab_rect(selected_index)?, padding, thickness);
15932    let from = tab_rect(from_index)
15933        .map(|rect| tab_indicator_from_tab_rect(rect, padding, thickness))
15934        .unwrap_or(to);
15935    Some(lerp_rect(from, to, progress))
15936}
15937
15938fn tab_indicator_from_tab_rect(rect: Rect, padding: Insets, thickness: f32) -> Rect {
15939    Rect::new(
15940        rect.x() + padding.left,
15941        rect.max_y() - thickness,
15942        (rect.width() - padding.left - padding.right).max(0.0),
15943        thickness,
15944    )
15945}
15946
15947fn sliding_inset_rect<F>(
15948    mut item_rect: F,
15949    from_index: usize,
15950    selected_index: usize,
15951    progress: f32,
15952    insets: Insets,
15953) -> Option<Rect>
15954where
15955    F: FnMut(usize) -> Option<Rect>,
15956{
15957    let to = inset_rect(item_rect(selected_index)?, insets);
15958    let from = item_rect(from_index)
15959        .map(|rect| inset_rect(rect, insets))
15960        .unwrap_or(to);
15961    Some(lerp_rect(from, to, progress))
15962}
15963
15964fn tab_panel_transition_translation(
15965    from_index: usize,
15966    selected_index: usize,
15967    progress: f32,
15968    metrics: ControlMetrics,
15969) -> Vector {
15970    if from_index == selected_index {
15971        return Vector::ZERO;
15972    }
15973
15974    let remaining = 1.0 - progress.clamp(0.0, 1.0);
15975    if remaining <= AnimatedScalar::EPSILON {
15976        return Vector::ZERO;
15977    }
15978
15979    let direction = if selected_index > from_index {
15980        1.0
15981    } else {
15982        -1.0
15983    };
15984    Vector::new(direction * metrics.tab_panel_gap * remaining, 0.0)
15985}
15986
15987fn lerp_rect(from: Rect, to: Rect, progress: f32) -> Rect {
15988    let progress = progress.clamp(0.0, 1.0);
15989    Rect::new(
15990        f32::interpolate(from.x(), to.x(), progress),
15991        f32::interpolate(from.y(), to.y(), progress),
15992        f32::interpolate(from.width(), to.width(), progress),
15993        f32::interpolate(from.height(), to.height(), progress),
15994    )
15995}
15996
15997fn tab_state_visuals(
15998    theme: &DefaultTheme,
15999    selected: bool,
16000    hovered: bool,
16001    pressed: bool,
16002    hover_amount: f32,
16003    press_amount: f32,
16004) -> Option<(Color, Color)> {
16005    let palette = theme.palette;
16006    let interaction = theme.interaction;
16007    if selected {
16008        Some((
16009            mix_color(
16010                palette.surface_raised,
16011                palette.accent,
16012                interaction.tab_selected_blend,
16013            ),
16014            palette.border.with_alpha(0.72),
16015        ))
16016    } else if pressed || press_amount > 0.0 {
16017        Some((
16018            mix_color(
16019                if hover_amount > 0.0 {
16020                    mix_color(
16021                        palette.control,
16022                        palette.control_hover,
16023                        interaction.hover_blend * hover_amount,
16024                    )
16025                } else {
16026                    palette.control
16027                },
16028                palette.control_active,
16029                interaction.pressed_blend * press_amount,
16030            ),
16031            palette.border_hover,
16032        ))
16033    } else if hovered || hover_amount > 0.0 {
16034        Some((
16035            mix_color(
16036                palette.control,
16037                palette.control_hover,
16038                interaction.hover_blend * hover_amount,
16039            ),
16040            palette.border_hover,
16041        ))
16042    } else {
16043        None
16044    }
16045}
16046
16047fn draw_control_frame(
16048    ctx: &mut PaintCtx,
16049    bounds: Rect,
16050    radius: f32,
16051    metrics: ControlMetrics,
16052    background: Color,
16053    border: Color,
16054    focus_ring: Option<Color>,
16055) {
16056    draw_control_shape(
16057        ctx,
16058        bounds,
16059        radius,
16060        physical_pixels(ctx, metrics.border_width),
16061        background,
16062        border,
16063    );
16064
16065    if let Some(focus_ring) = focus_ring {
16066        draw_focus_ring_frame(ctx, bounds, radius, metrics, focus_ring);
16067    }
16068}
16069
16070fn draw_focus_ring_frame(
16071    ctx: &mut PaintCtx,
16072    bounds: Rect,
16073    radius: f32,
16074    metrics: ControlMetrics,
16075    focus_ring: Color,
16076) {
16077    let focus_ring_outset = physical_pixels(ctx, metrics.focus_ring_outset);
16078    ctx.stroke(
16079        rounded_rect_path(
16080            bounds.inflate(focus_ring_outset, focus_ring_outset),
16081            radius + focus_ring_outset,
16082        ),
16083        focus_ring,
16084        StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
16085    );
16086}
16087
16088fn draw_control_shape(
16089    ctx: &mut PaintCtx,
16090    bounds: Rect,
16091    radius: f32,
16092    border_width: f32,
16093    background: Color,
16094    border: Color,
16095) {
16096    let shape = rounded_rect_path(bounds, radius);
16097    ctx.fill(shape.clone(), background);
16098    ctx.stroke(shape, border, StrokeStyle::new(border_width));
16099}
16100
16101fn mix_color(left: Color, right: Color, amount: f32) -> Color {
16102    crate::animation::Interpolate::interpolate(left, right, amount)
16103}
16104
16105fn draw_popover_arrival_overlay(
16106    ctx: &mut PaintCtx,
16107    rect: Rect,
16108    metrics: ControlMetrics,
16109    background: Color,
16110    border: Color,
16111    arrival_effect: ResolvedEffectStyle,
16112) {
16113    let overlay_inset = physical_pixels(ctx, 1.0);
16114    let overlay_rect = rect.inflate(-overlay_inset, -overlay_inset);
16115    let overlay_radius = (metrics.corner_radius + 2.0 - overlay_inset).max(0.0);
16116    let overlay_fill = mix_color(background, arrival_effect.color, 0.35)
16117        .with_alpha((0.10 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.22));
16118    let stroke_color = apply_hdr_policy_cap(
16119        mix_color(border, arrival_effect.color, 0.55),
16120        arrival_effect
16121            .color
16122            .red
16123            .max(arrival_effect.color.green.max(arrival_effect.color.blue)),
16124    )
16125    .with_alpha((0.16 + (arrival_effect.intensity * 0.12)).clamp(0.0, 0.30));
16126
16127    ctx.fill(
16128        rounded_rect_path(overlay_rect, overlay_radius),
16129        overlay_fill,
16130    );
16131    ctx.stroke(
16132        rounded_rect_path(
16133            overlay_rect.inflate(-overlay_inset * 0.5, -overlay_inset * 0.5),
16134            (overlay_radius - (overlay_inset * 0.5)).max(0.0),
16135        ),
16136        stroke_color,
16137        StrokeStyle::new(physical_pixels(ctx, 1.0)),
16138    );
16139}
16140
16141fn tooltip_tail(trigger: Rect, bubble: Rect, placement: TooltipPlacement) -> Path {
16142    let center_x = rect_center(trigger)
16143        .x
16144        .clamp(bubble.x() + 12.0, bubble.max_x() - 12.0);
16145    let mut builder = PathBuilder::new();
16146    match placement {
16147        TooltipPlacement::Above => {
16148            builder
16149                .move_to(Point::new(center_x - 6.0, bubble.max_y() - 1.0))
16150                .line_to(Point::new(center_x + 6.0, bubble.max_y() - 1.0))
16151                .line_to(Point::new(center_x, bubble.max_y() + 8.0));
16152        }
16153        TooltipPlacement::Below => {
16154            builder
16155                .move_to(Point::new(center_x - 6.0, bubble.y() + 1.0))
16156                .line_to(Point::new(center_x + 6.0, bubble.y() + 1.0))
16157                .line_to(Point::new(center_x, bubble.y() - 8.0));
16158        }
16159    }
16160    builder.build()
16161}
16162
16163fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
16164    if value <= 0.0 {
16165        return 0.0;
16166    }
16167    ctx.dpi().physical_pixels_to_logical(value)
16168}
16169
16170#[cfg(test)]
16171mod tests {
16172    use std::{
16173        cell::{Cell, RefCell},
16174        collections::BTreeSet,
16175        rc::Rc,
16176    };
16177
16178    use super::Tabs;
16179    use super::{
16180        ActionCard, ActionTilePaint, BottomSheet, BrowserTabBar, CalloutPaint, CodePanelPaint,
16181        CodeTextLine, CodeTextPaint, CodeTextSpan, CommandButtonPaint, CommandGroup, ContextMenu,
16182        CoverageDots, DetailRow, Dialog, DisclosureButtonPaint, DockPanel, EmptyState, FieldGroup,
16183        FormRow, FormSection, FramedField, HairlineEdge, Menu, MenuItem, PanelSection,
16184        PlacementBadge, PlacementBadgePaint, Popover, PopoverAlignment, PresetStrip, ProgressBar,
16185        PropertyRow, PropertyRowLayout, SectionLabel, SectionLabelPaint, SectionPanelPaint,
16186        SegmentedControl, SegmentedControlItem, SheetState, SideSheet, SideSheetPlacement, Spinner,
16187        StatusBadge, StatusBar, StatusBarHost, StatusBarSegment, Surface, SurfaceAppearance,
16188        TabBar, ToolPalette, ToolPaletteItem, Toolbar, paint_action_tile, paint_border,
16189        paint_callout, paint_code_lines, paint_code_panel, paint_command_button,
16190        paint_disclosure_button, paint_hairline, paint_placement_badge_with, paint_rounded_panel,
16191        paint_section_label, paint_section_label_detail, paint_section_panel, text_token_style,
16192    };
16193    use crate::FloatingStack;
16194    use crate::{
16195        DefaultTheme, HdrThemeMode, Padding, ScrollView, SelectionScope, SemanticColorToken,
16196        SemanticTone, SizedBox, Stack, TEXT_COMMAND, TextArea, TextCommand, ThemeTextToken,
16197    };
16198    use sui_core::{
16199        Color, Event, KeyState, KeyboardEvent, Point, PointerButton, PointerButtons, PointerEvent,
16200        PointerEventKind, Rect, SemanticsAction, SemanticsActionRequest, SemanticsNode,
16201        SemanticsRole, SemanticsValue, Size, Vector, WidgetId, WindowEvent,
16202    };
16203    use sui_layout::{Alignment, Constraints};
16204    use sui_reactive::Signal;
16205    use sui_runtime::{
16206        Application, ArrangeCtx, MeasureCtx, PaintCtx, RenderOutput, Runtime, SemanticsCtx, Widget,
16207        WindowBuilder,
16208    };
16209    use sui_scene::{
16210        Brush, LayerCompositionMode, SceneCommand, SceneLayerDescriptor, SceneLayerUpdateKind,
16211    };
16212    use sui_text::{FontFeature, FontRegistry, FontWeight, TextSystem};
16213
16214    fn build_runtime<W>(root: W) -> (Runtime, sui_core::WindowId)
16215    where
16216        W: Widget + 'static,
16217    {
16218        let runtime = Application::new()
16219            .window(WindowBuilder::new().title("Composites").root(root))
16220            .build()
16221            .unwrap();
16222        let window_id = runtime.window_ids()[0];
16223        (runtime, window_id)
16224    }
16225
16226    fn render<W>(root: W) -> RenderOutput
16227    where
16228        W: Widget + 'static,
16229    {
16230        let (mut runtime, window_id) = build_runtime(root);
16231        runtime.render(window_id).unwrap()
16232    }
16233
16234    fn render_isolated<W>(root: W) -> RenderOutput
16235    where
16236        W: Widget + 'static,
16237    {
16238        let mut runtime = Application::new()
16239            .window(
16240                WindowBuilder::new()
16241                    .title("Unused")
16242                    .root(crate::Label::new("Unused")),
16243            )
16244            .window(WindowBuilder::new().title("Composites").root(root))
16245            .build()
16246            .unwrap();
16247        let window_id = runtime.window_ids()[1];
16248        runtime.render(window_id).unwrap()
16249    }
16250
16251    #[test]
16252    fn filling_surface_measures_flex_text_at_its_arranged_width() {
16253        const TEXT: &str = "Evolution dashboard source ready";
16254        let output = render(
16255            crate::SizedBox::new().width(640.0).height(78.0).with_child(
16256                Surface::window(
16257                    crate::Flex::horizontal()
16258                        .with_item(crate::Label::new(TEXT), sui_layout::FlexItem::flex(1.0))
16259                        .with_child(crate::Label::new("1 promoted")),
16260                )
16261                .padding(sui_layout::Padding::all(20.0))
16262                .fill(),
16263            ),
16264        );
16265
16266        let label = output
16267            .semantics
16268            .iter()
16269            .find(|node| node.role == SemanticsRole::Text && node.name.as_deref() == Some(TEXT))
16270            .expect("flex label semantics present");
16271        assert!(
16272            label.bounds.width() > 200.0,
16273            "filling surface should allocate a useful text width, got {:?}",
16274            label.bounds
16275        );
16276
16277        let mut line_count = None;
16278        output.frame.scene.visit_commands(&mut |command| {
16279            if let SceneCommand::DrawShapedText(run) = command
16280                && let Some(layout) = run.resolve(output.frame.text_layout_registry.as_ref())
16281                && layout.text() == TEXT
16282            {
16283                line_count = Some(layout.lines().len());
16284            }
16285        });
16286        assert_eq!(line_count, Some(1));
16287    }
16288
16289    #[test]
16290    fn wrapping_toolbar_retains_items_across_multiple_rows() {
16291        let toolbar = Toolbar::horizontal()
16292            .wrapping()
16293            .padding(sui_layout::Padding::ZERO)
16294            .spacing(4.0)
16295            .line_spacing(6.0)
16296            .divider(false)
16297            .with_child(SizedBox::new().size(Size::new(60.0, 20.0)))
16298            .with_child(SizedBox::new().size(Size::new(60.0, 20.0)))
16299            .with_child(SizedBox::new().size(Size::new(60.0, 20.0)));
16300        let (mut runtime, window) = build_runtime(
16301            SizedBox::new()
16302                .size(Size::new(128.0, 80.0))
16303                .with_child(toolbar),
16304        );
16305        runtime.render(window).unwrap();
16306
16307        let graph = runtime.widget_graph(window).unwrap();
16308        let item_bounds = graph
16309            .nodes
16310            .iter()
16311            .filter(|node| node.bounds.size == Size::new(60.0, 20.0))
16312            .map(|node| node.bounds)
16313            .collect::<Vec<_>>();
16314        assert_eq!(item_bounds.len(), 3);
16315        assert_eq!(item_bounds[0].y(), item_bounds[1].y());
16316        assert!(item_bounds[2].y() >= item_bounds[0].max_y() + 6.0);
16317    }
16318
16319    #[test]
16320    fn density_modes_resize_menu_and_tabs() {
16321        let compact = DefaultTheme::compact();
16322        let touch = DefaultTheme::touch();
16323
16324        assert!(
16325            render(
16326                Menu::new("Actions")
16327                    .theme(compact)
16328                    .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")])
16329            )
16330            .frame
16331            .viewport
16332            .height
16333                < render(
16334                    Menu::new("Actions")
16335                        .theme(touch)
16336                        .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")])
16337                )
16338                .frame
16339                .viewport
16340                .height
16341        );
16342        assert!(
16343            render(
16344                TabBar::new("Tabs")
16345                    .theme(compact)
16346                    .tabs(["Canvas", "Inspector"])
16347            )
16348            .frame
16349            .viewport
16350            .height
16351                < render(
16352                    TabBar::new("Tabs")
16353                        .theme(touch)
16354                        .tabs(["Canvas", "Inspector"])
16355                )
16356                .frame
16357                .viewport
16358                .height
16359        );
16360        assert!(
16361            render(
16362                Tabs::new("Tabs")
16363                    .theme(compact)
16364                    .tab("Canvas", crate::Label::new("Canvas"))
16365                    .tab("Inspector", crate::Label::new("Inspector"))
16366            )
16367            .frame
16368            .viewport
16369            .height
16370                < render(
16371                    Tabs::new("Tabs")
16372                        .theme(touch)
16373                        .tab("Canvas", crate::Label::new("Canvas"))
16374                        .tab("Inspector", crate::Label::new("Inspector"))
16375                )
16376                .frame
16377                .viewport
16378                .height
16379        );
16380        assert!(
16381            render(
16382                SegmentedControl::new("View")
16383                    .theme(compact)
16384                    .segments(["All", "Chats", "Channels"])
16385            )
16386            .frame
16387            .viewport
16388            .height
16389                < render(
16390                    SegmentedControl::new("View")
16391                        .theme(touch)
16392                        .segments(["All", "Chats", "Channels"])
16393                )
16394                .frame
16395                .viewport
16396                .height
16397        );
16398    }
16399
16400    #[test]
16401    fn segmented_control_selection_thumb_is_evenly_inset() {
16402        let theme = DefaultTheme::default();
16403        let output = render(
16404            crate::SizedBox::new()
16405                .width(360.0)
16406                .height(theme.metrics.tab_height)
16407                .with_child(
16408                    SegmentedControl::new("Conversation view")
16409                        .theme(theme)
16410                        .segments(["All", "Chats", "Channels"]),
16411                ),
16412        );
16413        let group = output
16414            .semantics
16415            .iter()
16416            .find(|node| node.role == SemanticsRole::RadioGroup)
16417            .expect("segmented control semantics present");
16418        let mut selection_thumb = None;
16419        output.frame.scene.visit_commands(&mut |command| {
16420            if let SceneCommand::FillPath { path, brush } = command
16421                && *brush == Brush::Solid(theme.palette.selection)
16422            {
16423                selection_thumb = Some(path.bounds());
16424            }
16425        });
16426        let thumb = selection_thumb.expect("selected segment thumb painted");
16427
16428        assert!(
16429            (thumb.y() - group.bounds.y() - 2.0).abs() < 0.001,
16430            "selection thumb should have a 2 px top inset: group={:?}, thumb={thumb:?}",
16431            group.bounds
16432        );
16433        assert!(
16434            (group.bounds.max_y() - thumb.max_y() - 2.0).abs() < 0.001,
16435            "selection thumb should have a 2 px bottom inset: group={:?}, thumb={thumb:?}",
16436            group.bounds
16437        );
16438        assert!(
16439            !solid_fill_colors(&output).contains(&theme.palette.accent),
16440            "segmented controls should use a filled selection thumb without a tab underline"
16441        );
16442    }
16443
16444    #[test]
16445    fn segmented_control_click_updates_radio_semantics() -> Result<(), String> {
16446        let changes = Rc::new(RefCell::new(Vec::new()));
16447        let on_change = Rc::clone(&changes);
16448        let (mut runtime, window_id) = build_runtime(
16449            crate::SizedBox::new().width(260.0).height(28.0).with_child(
16450                SegmentedControl::new("Conversation view")
16451                    .items([
16452                        SegmentedControlItem::new("All 2").semantic_name("Show all conversations"),
16453                        SegmentedControlItem::new("Chats 1").semantic_name("Show chats only"),
16454                        SegmentedControlItem::new("Channels 1")
16455                            .semantic_name("Show channels only")
16456                            .description("1 visible conversation(s)"),
16457                    ])
16458                    .on_change(move |index, label| on_change.borrow_mut().push((index, label))),
16459            ),
16460        );
16461
16462        let _ = runtime
16463            .render(window_id)
16464            .map_err(|error| error.to_string())?;
16465        runtime
16466            .handle_event(
16467                window_id,
16468                primary_pointer(PointerEventKind::Down, Point::new(220.0, 14.0), true),
16469            )
16470            .map_err(|error| error.to_string())?;
16471        runtime
16472            .handle_event(
16473                window_id,
16474                primary_pointer(PointerEventKind::Up, Point::new(220.0, 14.0), false),
16475            )
16476            .map_err(|error| error.to_string())?;
16477
16478        assert_eq!(
16479            changes.borrow().as_slice(),
16480            &[(2, "Channels 1".to_string())]
16481        );
16482        let output = runtime
16483            .render(window_id)
16484            .map_err(|error| error.to_string())?;
16485        let group = output
16486            .semantics
16487            .iter()
16488            .find(|node| node.role == SemanticsRole::RadioGroup)
16489            .expect("radio group semantics present");
16490        assert_eq!(group.name.as_deref(), Some("Conversation view"));
16491        assert_eq!(
16492            group.value,
16493            Some(SemanticsValue::Text("Channels 1".to_string()))
16494        );
16495        let channel = output
16496            .semantics
16497            .iter()
16498            .find(|node| {
16499                node.role == SemanticsRole::RadioButton
16500                    && node.name.as_deref() == Some("Show channels only")
16501            })
16502            .expect("selected segment semantics present");
16503        assert_eq!(channel.parent, Some(group.id));
16504        assert_eq!(
16505            channel.description.as_deref(),
16506            Some("1 visible conversation(s)")
16507        );
16508        assert!(channel.state.selected);
16509        assert_eq!(channel.state.checked, Some(sui_core::ToggleState::Checked));
16510        assert!(channel.actions.contains(&SemanticsAction::Activate));
16511        Ok(())
16512    }
16513
16514    #[test]
16515    fn segmented_control_keyboard_changes_selection() -> Result<(), String> {
16516        let changes = Rc::new(RefCell::new(Vec::new()));
16517        let on_change = Rc::clone(&changes);
16518        let (mut runtime, window_id) = build_runtime(
16519            SegmentedControl::new("Conversation view")
16520                .segments(["All", "Chats", "Channels"])
16521                .on_change_with_ctx(move |index, label, ctx| {
16522                    on_change.borrow_mut().push((index, label));
16523                    ctx.request_measure();
16524                    ctx.request_arrange();
16525                    ctx.request_paint();
16526                    ctx.request_semantics();
16527                }),
16528        );
16529
16530        let _ = runtime
16531            .render(window_id)
16532            .map_err(|error| error.to_string())?;
16533        runtime
16534            .handle_event(
16535                window_id,
16536                Event::Keyboard(KeyboardEvent::new("Tab", KeyState::Pressed)),
16537            )
16538            .map_err(|error| error.to_string())?;
16539        runtime
16540            .handle_event(
16541                window_id,
16542                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
16543            )
16544            .map_err(|error| error.to_string())?;
16545
16546        assert_eq!(changes.borrow().as_slice(), &[(1, "Chats".to_string())]);
16547        Ok(())
16548    }
16549
16550    #[test]
16551    fn density_modes_resize_tool_command_widgets() {
16552        let compact = DefaultTheme::compact();
16553        let touch = DefaultTheme::touch();
16554
16555        assert!(
16556            render(
16557                Toolbar::horizontal()
16558                    .theme(compact)
16559                    .with_child(crate::Button::new("Undo"))
16560                    .with_child(crate::Button::new("Redo"))
16561            )
16562            .frame
16563            .viewport
16564            .height
16565                < render(
16566                    Toolbar::horizontal()
16567                        .theme(touch)
16568                        .with_child(crate::Button::new("Undo"))
16569                        .with_child(crate::Button::new("Redo"))
16570                )
16571                .frame
16572                .viewport
16573                .height
16574        );
16575        assert!(
16576            render(
16577                CommandGroup::horizontal("History")
16578                    .theme(compact)
16579                    .with_child(crate::Button::new("Undo"))
16580                    .with_child(crate::Button::new("Redo"))
16581            )
16582            .frame
16583            .viewport
16584            .height
16585                < render(
16586                    CommandGroup::horizontal("History")
16587                        .theme(touch)
16588                        .with_child(crate::Button::new("Undo"))
16589                        .with_child(crate::Button::new("Redo"))
16590                )
16591                .frame
16592                .viewport
16593                .height
16594        );
16595        assert!(
16596            render(
16597                ToolPalette::vertical("Tools")
16598                    .theme(compact)
16599                    .item(ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush"))
16600                    .item(ToolPaletteItem::new(crate::IconGlyph::Eraser, "Erase"))
16601            )
16602            .frame
16603            .viewport
16604            .width
16605                < render(
16606                    ToolPalette::vertical("Tools")
16607                        .theme(touch)
16608                        .item(ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush"))
16609                        .item(ToolPaletteItem::new(crate::IconGlyph::Eraser, "Erase"))
16610                )
16611                .frame
16612                .viewport
16613                .width
16614        );
16615        assert!(
16616            render(
16617                PresetStrip::new("Brush presets")
16618                    .theme(compact)
16619                    .presets(["8 px", "18 px", "36 px"])
16620            )
16621            .frame
16622            .viewport
16623            .height
16624                < render(
16625                    PresetStrip::new("Brush presets")
16626                        .theme(touch)
16627                        .presets(["8 px", "18 px", "36 px"])
16628                )
16629                .frame
16630                .viewport
16631                .height
16632        );
16633    }
16634
16635    #[test]
16636    fn density_modes_resize_overlay_widgets() {
16637        let compact = DefaultTheme::compact();
16638        let touch = DefaultTheme::touch();
16639
16640        let compact_dialog = render(
16641            Dialog::new("Export", crate::Label::new("Export settings"))
16642                .theme(compact)
16643                .description("Choose file settings"),
16644        );
16645        let touch_dialog = render(
16646            Dialog::new("Export", crate::Label::new("Export settings"))
16647                .theme(touch)
16648                .description("Choose file settings"),
16649        );
16650        let compact_bounds = compact_dialog
16651            .semantics
16652            .iter()
16653            .find(|node| node.role == SemanticsRole::Dialog)
16654            .expect("compact dialog semantics present")
16655            .bounds;
16656        let touch_bounds = touch_dialog
16657            .semantics
16658            .iter()
16659            .find(|node| node.role == SemanticsRole::Dialog)
16660            .expect("touch dialog semantics present")
16661            .bounds;
16662        assert!(compact_bounds.width() < touch_bounds.width());
16663        assert!(compact_bounds.height() < touch_bounds.height());
16664
16665        let (mut compact_popover, compact_window) = build_runtime(
16666            Popover::new(
16667                "Options",
16668                crate::Button::new("Open"),
16669                crate::Label::new("Popover body"),
16670            )
16671            .theme(compact),
16672        );
16673        let _ = compact_popover.render(compact_window).unwrap();
16674        compact_popover
16675            .handle_event(
16676                compact_window,
16677                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
16678            )
16679            .unwrap();
16680        let compact_output = compact_popover.render(compact_window).unwrap();
16681        let compact_offset = overlay_layer_descriptor(&compact_output)
16682            .expect("compact popover overlay present")
16683            .properties
16684            .translation
16685            .y
16686            .abs();
16687
16688        let (mut touch_popover, touch_window) = build_runtime(
16689            Popover::new(
16690                "Options",
16691                crate::Button::new("Open"),
16692                crate::Label::new("Popover body"),
16693            )
16694            .theme(touch),
16695        );
16696        let _ = touch_popover.render(touch_window).unwrap();
16697        touch_popover
16698            .handle_event(
16699                touch_window,
16700                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
16701            )
16702            .unwrap();
16703        let touch_output = touch_popover.render(touch_window).unwrap();
16704        let touch_offset = overlay_layer_descriptor(&touch_output)
16705            .expect("touch popover overlay present")
16706            .properties
16707            .translation
16708            .y
16709            .abs();
16710        assert!(compact_offset < touch_offset);
16711    }
16712
16713    #[test]
16714    fn popover_keyboard_and_semantic_actions_share_open_contract() {
16715        let changes = Rc::new(RefCell::new(Vec::new()));
16716        let on_open_change = Rc::clone(&changes);
16717        let (mut runtime, window_id) = build_runtime(
16718            Popover::new(
16719                "Health center",
16720                crate::Button::new("Open"),
16721                crate::Label::new("All systems operational"),
16722            )
16723            .on_open_change(move |open| on_open_change.borrow_mut().push(open)),
16724        );
16725        let output = runtime.render(window_id).unwrap();
16726        let popover_id = output
16727            .semantics
16728            .iter()
16729            .find(|node| node.role == SemanticsRole::Popover)
16730            .expect("popover semantics present")
16731            .id;
16732
16733        assert!(
16734            runtime
16735                .handle_semantics_action(window_id, popover_id, SemanticsActionRequest::Focus,)
16736                .unwrap()
16737        );
16738        runtime
16739            .handle_event(
16740                window_id,
16741                Event::Keyboard(KeyboardEvent::new("Enter", KeyState::Pressed)),
16742            )
16743            .unwrap();
16744        assert_eq!(changes.borrow().as_slice(), &[true]);
16745        assert_eq!(
16746            runtime
16747                .render(window_id)
16748                .unwrap()
16749                .semantics
16750                .iter()
16751                .find(|node| node.id == popover_id)
16752                .and_then(|node| node.state.expanded),
16753            Some(true)
16754        );
16755
16756        runtime
16757            .handle_event(
16758                window_id,
16759                Event::Keyboard(KeyboardEvent::new(" ", KeyState::Pressed)),
16760            )
16761            .unwrap();
16762        assert_eq!(changes.borrow().as_slice(), &[true, false]);
16763        let _ = runtime.render(window_id).unwrap();
16764        assert!(
16765            runtime
16766                .handle_semantics_action(window_id, popover_id, SemanticsActionRequest::Expand,)
16767                .unwrap()
16768        );
16769        let _ = runtime.render(window_id).unwrap();
16770        assert!(
16771            runtime
16772                .handle_semantics_action(window_id, popover_id, SemanticsActionRequest::Collapse,)
16773                .unwrap()
16774        );
16775        assert_eq!(changes.borrow().as_slice(), &[true, false, true, false]);
16776    }
16777
16778    #[test]
16779    fn popover_end_alignment_keeps_a_narrow_trigger_on_the_trailing_edge() {
16780        let output = render(
16781            crate::SizedBox::new().width(360.0).with_child(
16782                Popover::new(
16783                    "Trailing inspector",
16784                    crate::Button::new("Open").min_width(92.0),
16785                    crate::SizedBox::new()
16786                        .width(240.0)
16787                        .with_child(crate::Label::new("Inspector body")),
16788                )
16789                .alignment(PopoverAlignment::End)
16790                .open(true),
16791            ),
16792        );
16793        let popover = output
16794            .semantics
16795            .iter()
16796            .find(|node| {
16797                node.role == SemanticsRole::Popover
16798                    && node.name.as_deref() == Some("Trailing inspector")
16799            })
16800            .expect("popover semantics present");
16801        let trigger = output
16802            .semantics
16803            .iter()
16804            .find(|node| node.role == SemanticsRole::Button && node.name.as_deref() == Some("Open"))
16805            .expect("popover trigger semantics present");
16806
16807        assert!(trigger.bounds.x() > popover.bounds.x());
16808        assert!((trigger.bounds.max_x() - popover.bounds.max_x()).abs() < 0.01);
16809    }
16810
16811    #[test]
16812    fn popover_surface_escapes_a_tight_toolbar_slot() {
16813        let output = render(
16814            crate::SizedBox::new()
16815                .width(800.0)
16816                .height(600.0)
16817                .with_child(crate::Align::new(
16818                    Alignment::End,
16819                    Alignment::Start,
16820                    crate::SizedBox::new().width(150.0).height(24.0).with_child(
16821                        Popover::new(
16822                            "Toolbar recovery",
16823                            crate::Button::new("2 issues").min_width(150.0),
16824                            crate::SizedBox::new()
16825                                .width(400.0)
16826                                .height(300.0)
16827                                .with_child(crate::Label::new("Recovery panel")),
16828                        )
16829                        .alignment(PopoverAlignment::End)
16830                        .open(true),
16831                    ),
16832                )),
16833        );
16834        let popover = output
16835            .semantics
16836            .iter()
16837            .find(|node| {
16838                node.role == SemanticsRole::Popover
16839                    && node.name.as_deref() == Some("Toolbar recovery")
16840            })
16841            .expect("popover semantics present");
16842        let content = output
16843            .semantics
16844            .iter()
16845            .find(|node| {
16846                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Recovery panel")
16847            })
16848            .expect("popover content present");
16849        let surface = overlay_layer_descriptor(&output).expect("popover overlay present");
16850
16851        assert!((popover.bounds.width() - 150.0).abs() < 0.01);
16852        assert!((popover.bounds.height() - 24.0).abs() < 0.01);
16853        assert!(
16854            surface.bounds.width() >= 400.0,
16855            "surface={:?}, popover={:?}, content={:?}",
16856            surface.bounds,
16857            popover.bounds,
16858            content.bounds
16859        );
16860        assert!(content.bounds.y() >= popover.bounds.max_y());
16861    }
16862
16863    #[test]
16864    fn framed_field_owns_standard_and_validation_chrome() {
16865        let theme = DefaultTheme::default();
16866        let output = render(
16867            FramedField::new(crate::Label::new("Query"))
16868                .theme(theme)
16869                .name("Search query")
16870                .invalid(true),
16871        );
16872
16873        assert!(solid_fill_colors(&output).contains(&theme.surfaces.field));
16874        assert!(
16875            solid_stroke_colors(&output).contains(&theme.semantic_tone_color(SemanticTone::Danger))
16876        );
16877        assert!(output.semantics.iter().any(|node| {
16878            node.role == SemanticsRole::GenericContainer
16879                && node.name.as_deref() == Some("Search query")
16880        }));
16881        assert!(output.semantics.iter().any(|node| {
16882            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Query")
16883        }));
16884    }
16885
16886    #[test]
16887    fn framed_field_tracks_focus_anywhere_in_its_child_subtree() {
16888        let theme = DefaultTheme::default();
16889        let (mut runtime, window_id) = build_runtime(
16890            FramedField::new(crate::TextInput::new("Query").bare())
16891                .theme(theme)
16892                .name("Search field"),
16893        );
16894        let _ = runtime.render(window_id).unwrap();
16895        runtime
16896            .handle_event(
16897                window_id,
16898                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
16899            )
16900            .unwrap();
16901        let output = runtime.render(window_id).unwrap();
16902        let frame = output
16903            .semantics
16904            .iter()
16905            .find(|node| node.name.as_deref() == Some("Search field"))
16906            .expect("framed field semantics present");
16907        assert!(frame.state.focused);
16908        assert!(solid_stroke_colors(&output).contains(&theme.palette.focus_ring));
16909    }
16910
16911    #[test]
16912    fn framed_field_uses_stock_hover_and_focus_surface_tokens() {
16913        let theme = DefaultTheme::default();
16914        let (mut runtime, window_id) = build_runtime(
16915            FramedField::new(crate::TextInput::new("Query").bare())
16916                .theme(theme)
16917                .name("Search field"),
16918        );
16919        let _ = runtime.render(window_id).unwrap();
16920
16921        runtime
16922            .handle_event(
16923                window_id,
16924                primary_pointer(PointerEventKind::Move, Point::new(12.0, 12.0), false),
16925            )
16926            .unwrap();
16927        runtime.tick(1.0);
16928        handle_ready_events(&mut runtime).unwrap();
16929        let hovered = runtime.render(window_id).unwrap();
16930        assert!(solid_stroke_colors(&hovered).contains(&theme.palette.border_hover));
16931        assert!(
16932            hovered
16933                .semantics
16934                .iter()
16935                .any(|node| { node.name.as_deref() == Some("Search field") && node.state.hovered })
16936        );
16937
16938        runtime
16939            .handle_event(
16940                window_id,
16941                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
16942            )
16943            .unwrap();
16944        let focused = runtime.render(window_id).unwrap();
16945        assert!(solid_fill_colors(&focused).contains(&theme.palette.surface_focus));
16946        assert!(solid_stroke_colors(&focused).contains(&theme.palette.focus_ring));
16947    }
16948
16949    #[test]
16950    fn surface_appearance_uses_shared_raised_and_semantic_tokens() {
16951        let theme = DefaultTheme::default();
16952        let raised = render(
16953            Surface::field(crate::Label::new("Ready"))
16954                .theme(theme)
16955                .appearance(SurfaceAppearance::Raised),
16956        );
16957        assert!(solid_fill_colors(&raised).contains(&theme.palette.surface_raised));
16958
16959        let soft = render(
16960            Surface::field(crate::Label::new("Queued"))
16961                .theme(theme)
16962                .appearance(SurfaceAppearance::Soft)
16963                .tone(SemanticTone::Accent),
16964        );
16965        assert!(
16966            solid_fill_colors(&soft)
16967                .contains(&theme.semantic_tone_soft_colors(SemanticTone::Accent).0)
16968        );
16969    }
16970
16971    #[test]
16972    fn side_sheet_anchors_to_edge_and_exposes_dialog_semantics() {
16973        let output = render(
16974            SideSheet::new("Inspector", crate::Label::new("Selection details"))
16975                .description("Properties for the selected item")
16976                .placement(SideSheetPlacement::Right)
16977                .width(360.0),
16978        );
16979        let sheet = output
16980            .semantics
16981            .iter()
16982            .find(|node| {
16983                node.role == SemanticsRole::Dialog && node.name.as_deref() == Some("Inspector")
16984            })
16985            .expect("side sheet dialog semantics present");
16986        assert!((sheet.bounds.width() - 360.0).abs() < 0.01);
16987        assert!((sheet.bounds.max_x() - output.frame.viewport.width).abs() < 0.01);
16988        assert_eq!(sheet.state.expanded, Some(true));
16989        assert!(output.semantics.iter().any(|node| {
16990            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Selection details")
16991        }));
16992    }
16993
16994    #[test]
16995    fn side_sheet_scrim_dismisses_without_swallowing_sheet_presses() {
16996        let dismissals = Rc::new(Cell::new(0_u32));
16997        let on_dismiss = Rc::clone(&dismissals);
16998        let (mut runtime, window_id) = build_runtime(
16999            SideSheet::new("Inspector", crate::Label::new("Body"))
17000                .width(320.0)
17001                .on_dismiss(move || on_dismiss.set(on_dismiss.get() + 1)),
17002        );
17003        let _ = runtime.render(window_id).unwrap();
17004        runtime.tick(1.0);
17005        handle_ready_events(&mut runtime).unwrap();
17006        let settled = runtime.render(window_id).unwrap();
17007        let sheet = settled
17008            .semantics
17009            .iter()
17010            .find(|node| node.role == SemanticsRole::Dialog)
17011            .expect("side sheet semantics present");
17012        let sheet_id = sheet.id;
17013        let sheet_point = Point::new(sheet.bounds.x() + 12.0, sheet.bounds.y() + 12.0);
17014        runtime
17015            .handle_event(
17016                window_id,
17017                primary_pointer(PointerEventKind::Down, sheet_point, true),
17018            )
17019            .unwrap();
17020        assert_eq!(dismissals.get(), 0);
17021
17022        runtime
17023            .handle_event(
17024                window_id,
17025                primary_pointer(PointerEventKind::Down, Point::new(8.0, 8.0), true),
17026            )
17027            .unwrap();
17028        assert_eq!(dismissals.get(), 1);
17029        assert!(
17030            runtime
17031                .handle_semantics_action(window_id, sheet_id, SemanticsActionRequest::Collapse,)
17032                .unwrap()
17033        );
17034        assert_eq!(dismissals.get(), 2);
17035    }
17036
17037    #[test]
17038    fn side_sheet_takes_initial_focus_and_escape_dismisses_from_a_child() {
17039        let dismissals = Rc::new(Cell::new(0_u32));
17040        let on_dismiss = Rc::clone(&dismissals);
17041        let (mut runtime, window_id) = build_runtime(
17042            SideSheet::new("Inspector", crate::Button::new("Child action"))
17043                .width(320.0)
17044                .on_dismiss(move || on_dismiss.set(on_dismiss.get() + 1)),
17045        );
17046        let initial = runtime.render(window_id).unwrap();
17047        let _sheet_id = initial
17048            .semantics
17049            .iter()
17050            .find(|node| node.role == SemanticsRole::Dialog)
17051            .expect("side sheet semantics present")
17052            .id;
17053        let child_id = initial
17054            .semantics
17055            .iter()
17056            .find(|node| {
17057                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Child action")
17058            })
17059            .expect("side sheet child semantics present")
17060            .id;
17061
17062        runtime.tick(1.0);
17063        handle_ready_events(&mut runtime).unwrap();
17064        assert_eq!(runtime.focused_widget(window_id).unwrap(), Some(child_id));
17065
17066        assert!(
17067            runtime
17068                .handle_semantics_action(window_id, child_id, SemanticsActionRequest::Focus)
17069                .unwrap()
17070        );
17071        assert_eq!(runtime.focused_widget(window_id).unwrap(), Some(child_id));
17072        runtime
17073            .handle_event(
17074                window_id,
17075                Event::Keyboard(KeyboardEvent::new("Escape", KeyState::Pressed)),
17076            )
17077            .unwrap();
17078        assert_eq!(dismissals.get(), 1);
17079    }
17080
17081    #[test]
17082    fn dialog_title_and_description_visual_centers_match_header_slots() {
17083        let theme = DefaultTheme::default();
17084        let output = render(
17085            Dialog::new("Export", crate::Label::new("Export settings"))
17086                .theme(theme)
17087                .description("Choose file settings"),
17088        );
17089        let dialog = output
17090            .semantics
17091            .iter()
17092            .find(|node| node.role == SemanticsRole::Dialog)
17093            .expect("dialog semantics present")
17094            .bounds;
17095
17096        let title = text_run_for(&output, "Export");
17097        let title_layout = text_run_layout(&title);
17098        let title_line = title_layout
17099            .lines()
17100            .first()
17101            .expect("dialog title should contain one line");
17102        let title_visual_center = title.rect.y()
17103            + title_line.baseline
17104            + optical_visual_center(title_layout.measurement());
17105
17106        let description = text_run_for(&output, "Choose file settings");
17107        let description_layout = text_run_layout(&description);
17108        let description_line = description_layout
17109            .lines()
17110            .first()
17111            .expect("dialog description should contain one line");
17112        let description_visual_center = description.rect.y()
17113            + description_line.baseline
17114            + optical_visual_center(description_layout.measurement());
17115
17116        let metrics = theme.metrics;
17117        let padding = metrics.dialog_padding;
17118        let text_width = (dialog.width() - padding.left - padding.right).max(0.0);
17119        let title_height = title
17120            .style
17121            .line_height
17122            .max(title_layout.measurement().height);
17123        let description_height = description
17124            .style
17125            .line_height
17126            .max(description_layout.measurement().height);
17127        let title_slot = Rect::new(
17128            dialog.x() + padding.left,
17129            dialog.y() + padding.top,
17130            text_width,
17131            title_height,
17132        );
17133        let description_slot = Rect::new(
17134            dialog.x() + padding.left,
17135            title_slot.max_y() + metrics.dialog_description_gap,
17136            text_width,
17137            description_height,
17138        );
17139
17140        assert!((title_visual_center - super::rect_center(title_slot).y).abs() < 0.75);
17141        assert!((description_visual_center - super::rect_center(description_slot).y).abs() < 0.75);
17142    }
17143
17144    #[test]
17145    fn dialog_header_text_preserves_tall_measurements_in_compact_line_boxes() {
17146        let mut theme = DefaultTheme::default();
17147        theme.metrics.dialog_title_font_size = 32.0;
17148        theme.metrics.dialog_title_line_height = 12.0;
17149        theme.typography.body_font_size = 28.0;
17150        theme.typography.body_line_height = 10.0;
17151
17152        let output = render(
17153            Dialog::new("Export", crate::Label::new("Export settings"))
17154                .theme(theme)
17155                .description("Choose file settings"),
17156        );
17157        let dialog = output
17158            .semantics
17159            .iter()
17160            .find(|node| node.role == SemanticsRole::Dialog)
17161            .expect("dialog semantics present")
17162            .bounds;
17163        let title = text_run_for(&output, "Export");
17164        let title_layout = TextSystem::new()
17165            .shape_text_run(&title, &FontRegistry::new())
17166            .expect("dialog title should shape");
17167        let description = text_run_for(&output, "Choose file settings");
17168        let description_layout = TextSystem::new()
17169            .shape_text_run(&description, &FontRegistry::new())
17170            .expect("dialog description should shape");
17171        let metrics = theme.metrics;
17172        let padding = metrics.dialog_padding;
17173        let text_width = (dialog.width() - padding.left - padding.right).max(0.0);
17174        let title_height = title
17175            .style
17176            .line_height
17177            .max(title_layout.measurement().height);
17178        let description_height = description
17179            .style
17180            .line_height
17181            .max(description_layout.measurement().height);
17182        let title_slot = Rect::new(
17183            dialog.x() + padding.left,
17184            dialog.y() + padding.top,
17185            text_width,
17186            title_height,
17187        );
17188        let description_slot = Rect::new(
17189            dialog.x() + padding.left,
17190            title_slot.max_y() + metrics.dialog_description_gap,
17191            text_width,
17192            description_height,
17193        );
17194
17195        assert!(title.rect.height() >= title_layout.measurement().height - 0.01);
17196        assert!(title.rect.height() > title.style.line_height);
17197        assert!(description.rect.height() >= description_layout.measurement().height - 0.01);
17198        assert!(description.rect.height() > description.style.line_height);
17199        assert_eq!(description.style.color, theme.palette.placeholder);
17200        assert!((text_run_visual_center(&title) - super::rect_center(title_slot).y).abs() < 0.75);
17201        assert!(
17202            (text_run_visual_center(&description) - super::rect_center(description_slot).y).abs()
17203                < 0.75
17204        );
17205    }
17206
17207    #[test]
17208    fn density_modes_resize_composite_status_widgets() {
17209        let compact = DefaultTheme::compact();
17210        let touch = DefaultTheme::touch();
17211
17212        assert!(
17213            render(
17214                ActionCard::new("Paint", "Pixel canvas workspace")
17215                    .theme(compact)
17216                    .icon(crate::IconGlyph::Brush)
17217            )
17218            .frame
17219            .viewport
17220            .height
17221                < render(
17222                    ActionCard::new("Paint", "Pixel canvas workspace")
17223                        .theme(touch)
17224                        .icon(crate::IconGlyph::Brush)
17225                )
17226                .frame
17227                .viewport
17228                .height
17229        );
17230        assert!(
17231            render(
17232                StatusBar::new()
17233                    .theme(compact)
17234                    .text_segment("Ready")
17235                    .text_segment("100%")
17236            )
17237            .frame
17238            .viewport
17239            .height
17240                < render(
17241                    StatusBar::new()
17242                        .theme(touch)
17243                        .text_segment("Ready")
17244                        .text_segment("100%")
17245                )
17246                .frame
17247                .viewport
17248                .height
17249        );
17250        assert!(
17251            render(
17252                StatusBadge::new("Synced")
17253                    .theme(compact)
17254                    .tone(SemanticTone::Success)
17255                    .icon(crate::IconGlyph::Storage)
17256            )
17257            .frame
17258            .viewport
17259            .height
17260                < render(
17261                    StatusBadge::new("Synced")
17262                        .theme(touch)
17263                        .tone(SemanticTone::Success)
17264                        .icon(crate::IconGlyph::Storage)
17265                )
17266                .frame
17267                .viewport
17268                .height
17269        );
17270        assert!(
17271            render(
17272                CoverageDots::new("Replicas", 2, 3)
17273                    .theme(compact)
17274                    .tone(SemanticTone::Success)
17275            )
17276            .frame
17277            .viewport
17278            .height
17279                < render(
17280                    CoverageDots::new("Replicas", 2, 3)
17281                        .theme(touch)
17282                        .tone(SemanticTone::Success)
17283                )
17284                .frame
17285                .viewport
17286                .height
17287        );
17288        assert!(
17289            render(
17290                ProgressBar::new("Export progress")
17291                    .theme(compact)
17292                    .value(0.42)
17293            )
17294            .frame
17295            .viewport
17296            .height
17297                < render(ProgressBar::new("Export progress").theme(touch).value(0.42))
17298                    .frame
17299                    .viewport
17300                    .height
17301        );
17302    }
17303
17304    #[test]
17305    fn composite_focus_rings_use_theme_motion() -> Result<(), String> {
17306        assert_focus_ring_uses_theme_motion(
17307            crate::SizedBox::new()
17308                .size(Size::new(112.0, 44.0))
17309                .with_child(
17310                    ToolPalette::horizontal("Tools")
17311                        .items([
17312                            ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush"),
17313                            ToolPaletteItem::new(crate::IconGlyph::Eraser, "Erase"),
17314                        ])
17315                        .selected(0),
17316                ),
17317            Point::new(18.0, 18.0),
17318        )?;
17319
17320        assert_focus_ring_uses_theme_motion(
17321            crate::SizedBox::new()
17322                .size(Size::new(260.0, 92.0))
17323                .with_child(ActionCard::new("Paint", "Pixel canvas workspace")),
17324            Point::new(18.0, 18.0),
17325        )?;
17326
17327        assert_focus_ring_uses_theme_motion(
17328            crate::SizedBox::new()
17329                .size(Size::new(240.0, 40.0))
17330                .with_child(PresetStrip::new("Brush presets").presets(["8 px", "18 px"])),
17331            Point::new(24.0, 18.0),
17332        )?;
17333
17334        assert_focus_ring_uses_theme_motion(
17335            crate::SizedBox::new()
17336                .size(Size::new(260.0, 92.0))
17337                .with_child(
17338                    PanelSection::new("Advanced color", crate::Label::new("RGB sliders"))
17339                        .collapsible(true)
17340                        .collapsed(),
17341                ),
17342            Point::new(24.0, 18.0),
17343        )?;
17344
17345        assert_focus_ring_uses_theme_motion(
17346            Menu::new("App menu").items([MenuItem::new("New File"), MenuItem::new("Open...")]),
17347            Point::new(24.0, 24.0),
17348        )?;
17349
17350        assert_focus_ring_uses_theme_motion(
17351            ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
17352                .activation_button(PointerButton::Primary)
17353                .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")]),
17354            Point::new(24.0, 24.0),
17355        )?;
17356
17357        assert_focus_ring_uses_theme_motion(
17358            crate::SizedBox::new()
17359                .size(Size::new(640.0, 420.0))
17360                .with_child(Dialog::new(
17361                    "Confirm",
17362                    crate::Label::new("Apply the change?"),
17363                )),
17364            Point::new(320.0, 210.0),
17365        )
17366    }
17367
17368    #[test]
17369    fn density_modes_resize_form_and_panel_widgets() {
17370        let compact = DefaultTheme::compact();
17371        let touch = DefaultTheme::touch();
17372
17373        assert!(
17374            render(PropertyRow::new("Opacity", crate::Slider::new("Opacity")).theme(compact))
17375                .frame
17376                .viewport
17377                .height
17378                < render(PropertyRow::new("Opacity", crate::Slider::new("Opacity")).theme(touch))
17379                    .frame
17380                    .viewport
17381                    .height
17382        );
17383        assert!(
17384            render(
17385                FieldGroup::new()
17386                    .theme(compact)
17387                    .with_child(crate::Label::new("First"))
17388                    .with_child(crate::Label::new("Second"))
17389            )
17390            .frame
17391            .viewport
17392            .height
17393                < render(
17394                    FieldGroup::new()
17395                        .theme(touch)
17396                        .with_child(crate::Label::new("First"))
17397                        .with_child(crate::Label::new("Second"))
17398                )
17399                .frame
17400                .viewport
17401                .height
17402        );
17403        assert!(
17404            render(FormSection::new("Providers", crate::Label::new("Configured")).theme(compact))
17405                .frame
17406                .viewport
17407                .height
17408                < render(
17409                    FormSection::new("Providers", crate::Label::new("Configured")).theme(touch)
17410                )
17411                .frame
17412                .viewport
17413                .height
17414        );
17415        assert!(
17416            render(PanelSection::new("Brush", crate::Label::new("Opacity")).theme(compact))
17417                .frame
17418                .viewport
17419                .height
17420                < render(PanelSection::new("Brush", crate::Label::new("Opacity")).theme(touch))
17421                    .frame
17422                    .viewport
17423                    .height
17424        );
17425        assert!(
17426            render(
17427                DockPanel::new("Tool properties", crate::Label::new("Brush size")).theme(compact)
17428            )
17429            .frame
17430            .viewport
17431            .height
17432                < render(
17433                    DockPanel::new("Tool properties", crate::Label::new("Brush size")).theme(touch)
17434                )
17435                .frame
17436                .viewport
17437                .height
17438        );
17439    }
17440
17441    #[test]
17442    fn detail_row_wraps_metadata_and_exposes_value_semantics() {
17443        let theme = DefaultTheme::default();
17444        let value = "replicated across atlas, keep, and wren with one pending repair";
17445        let narrow = render(
17446            crate::SizedBox::new()
17447                .width(140.0)
17448                .with_child(DetailRow::new("Placement", value).theme(theme)),
17449        );
17450        let wide = render(
17451            crate::SizedBox::new()
17452                .width(360.0)
17453                .with_child(DetailRow::new("Placement", value).theme(theme)),
17454        );
17455
17456        assert!(
17457            narrow.frame.viewport.height > wide.frame.viewport.height,
17458            "narrow detail rows should wrap their metadata value"
17459        );
17460        let label = text_run_for(&wide, "PLACEMENT");
17461        assert_eq!(label.style.color, theme.palette.text_muted);
17462        let node = wide
17463            .semantics
17464            .iter()
17465            .find(|node| node.name.as_deref() == Some("Placement"))
17466            .expect("detail row semantics should exist");
17467        assert_eq!(node.value, Some(SemanticsValue::Text(value.to_string())));
17468    }
17469
17470    struct DetailRowHeightProbe {
17471        theme: DefaultTheme,
17472        measured: Rc<Cell<f32>>,
17473        painted: Rc<Cell<f32>>,
17474    }
17475
17476    impl Widget for DetailRowHeightProbe {
17477        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17478            constraints.clamp(Size::new(140.0, 96.0))
17479        }
17480
17481        fn paint(&self, ctx: &mut PaintCtx) {
17482            let value = "replicated across atlas, keep, and wren with one pending repair";
17483            self.measured.set(super::detail_row_height_for_value(
17484                ctx,
17485                &self.theme,
17486                ctx.bounds().width(),
17487                value,
17488                Some(2),
17489            ));
17490            self.painted.set(super::paint_detail_row_at(
17491                ctx,
17492                &self.theme,
17493                Point::new(ctx.bounds().x(), ctx.bounds().y()),
17494                ctx.bounds().width(),
17495                "Placement",
17496                value,
17497                Some(2),
17498            ));
17499        }
17500    }
17501
17502    #[test]
17503    fn detail_row_height_helper_matches_painter() {
17504        let measured = Rc::new(Cell::new(0.0));
17505        let painted = Rc::new(Cell::new(0.0));
17506        let _ = render(DetailRowHeightProbe {
17507            theme: DefaultTheme::default(),
17508            measured: Rc::clone(&measured),
17509            painted: Rc::clone(&painted),
17510        });
17511
17512        assert!(measured.get() > 0.0);
17513        assert!((measured.get() - painted.get()).abs() < 0.01);
17514    }
17515
17516    #[test]
17517    fn section_label_uses_micro_label_token_and_text_semantics() {
17518        let theme = DefaultTheme::default();
17519        let output = render(
17520            crate::SizedBox::new().width(120.0).height(18.0).with_child(
17521                SectionLabel::new("file tasks")
17522                    .semantic_name("File tasks")
17523                    .theme(theme),
17524            ),
17525        );
17526
17527        let label = text_run_for(&output, "FILE TASKS");
17528        assert_text_run_uses_token(&label, theme.text.xs);
17529        assert_eq!(label.style.color, theme.surfaces.text_faint);
17530        assert_eq!(label.style.weight, FontWeight::SEMIBOLD);
17531
17532        let node = output
17533            .semantics
17534            .iter()
17535            .find(|node| node.name.as_deref() == Some("File tasks"))
17536            .expect("section label semantics should exist");
17537        assert_eq!(node.role, SemanticsRole::Text);
17538        assert_eq!(
17539            node.value,
17540            Some(SemanticsValue::Text("File tasks".to_string()))
17541        );
17542    }
17543
17544    struct SectionLabelPaintFixture {
17545        theme: DefaultTheme,
17546        color: Color,
17547    }
17548
17549    impl Widget for SectionLabelPaintFixture {
17550        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17551            constraints.clamp(Size::new(120.0, 18.0))
17552        }
17553
17554        fn paint(&self, ctx: &mut PaintCtx) {
17555            paint_section_label(
17556                ctx,
17557                &self.theme,
17558                ctx.bounds(),
17559                "placement",
17560                SectionLabelPaint::new().color(self.color),
17561            );
17562        }
17563    }
17564
17565    #[test]
17566    fn section_label_paint_matches_widget_style_with_color_override() {
17567        let theme = DefaultTheme::default();
17568        let color = theme.palette.warning;
17569        let output = render(SectionLabelPaintFixture { theme, color });
17570
17571        let label = text_run_for(&output, "PLACEMENT");
17572        assert_text_run_uses_token(&label, theme.text.xs);
17573        assert_eq!(label.style.color, color);
17574        assert_eq!(label.style.weight, FontWeight::SEMIBOLD);
17575    }
17576
17577    struct SectionLabelDetailPaintFixture {
17578        theme: DefaultTheme,
17579        color: Color,
17580    }
17581
17582    impl Widget for SectionLabelDetailPaintFixture {
17583        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17584            constraints.clamp(Size::new(180.0, 18.0))
17585        }
17586
17587        fn paint(&self, ctx: &mut PaintCtx) {
17588            paint_section_label_detail(
17589                ctx,
17590                &self.theme,
17591                ctx.bounds(),
17592                "input",
17593                "command payload",
17594                SectionLabelPaint::new().color(self.color),
17595            );
17596        }
17597    }
17598
17599    #[test]
17600    fn section_label_detail_paint_preserves_detail_text() {
17601        let theme = DefaultTheme::default();
17602        let color = theme.palette.warning;
17603        let output = render(SectionLabelDetailPaintFixture { theme, color });
17604
17605        let label = text_run_for(&output, "INPUT · command payload");
17606        assert_text_run_uses_token(&label, theme.text.xs);
17607        assert_eq!(label.style.color, color);
17608        assert_eq!(label.style.weight, FontWeight::SEMIBOLD);
17609    }
17610
17611    struct GenericPaintPrimitiveFixture {
17612        fill: Color,
17613        panel_border: Color,
17614        right_hairline: Color,
17615        full_border: Color,
17616    }
17617
17618    impl Widget for GenericPaintPrimitiveFixture {
17619        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17620            constraints.clamp(Size::new(96.0, 64.0))
17621        }
17622
17623        fn paint(&self, ctx: &mut PaintCtx) {
17624            paint_rounded_panel(
17625                ctx,
17626                Rect::new(4.0, 4.0, 36.0, 20.0),
17627                self.fill,
17628                self.panel_border,
17629                0.0,
17630            );
17631            paint_hairline(
17632                ctx,
17633                Rect::new(50.0, 6.0, 24.0, 18.0),
17634                HairlineEdge::Right,
17635                self.right_hairline,
17636            );
17637            paint_border(ctx, Rect::new(10.0, 34.0, 18.0, 12.0), self.full_border);
17638        }
17639    }
17640
17641    #[test]
17642    fn generic_paint_primitives_emit_expected_rects() {
17643        let fill = Color::rgba(0.1, 0.2, 0.3, 1.0);
17644        let panel_border = Color::rgba(0.4, 0.5, 0.6, 1.0);
17645        let right_hairline = Color::rgba(0.7, 0.2, 0.1, 1.0);
17646        let full_border = Color::rgba(0.2, 0.8, 0.4, 1.0);
17647        let output = render(GenericPaintPrimitiveFixture {
17648            fill,
17649            panel_border,
17650            right_hairline,
17651            full_border,
17652        });
17653
17654        assert_eq!(
17655            solid_fill_rects_for_color(&output, fill),
17656            vec![Rect::new(5.0, 5.0, 34.0, 18.0)]
17657        );
17658        assert_eq!(
17659            solid_fill_rects_for_color(&output, panel_border),
17660            vec![Rect::new(4.0, 4.0, 36.0, 20.0)]
17661        );
17662        assert_eq!(
17663            solid_fill_rects_for_color(&output, right_hairline),
17664            vec![Rect::new(73.0, 6.0, 1.0, 18.0)]
17665        );
17666        assert_eq!(
17667            solid_fill_rects_for_color(&output, full_border),
17668            vec![
17669                Rect::new(10.0, 34.0, 18.0, 1.0),
17670                Rect::new(27.0, 34.0, 1.0, 12.0),
17671                Rect::new(10.0, 45.0, 18.0, 1.0),
17672                Rect::new(10.0, 34.0, 1.0, 12.0),
17673            ]
17674        );
17675    }
17676
17677    #[test]
17678    fn semantic_tones_drive_composite_status_colors() {
17679        let theme = DefaultTheme::default();
17680
17681        let action_card = render(
17682            ActionCard::new("Deploy", "Publish release artifacts")
17683                .theme(theme)
17684                .tone(SemanticTone::Success),
17685        );
17686        assert!(solid_fill_colors(&action_card).contains(&theme.palette.success.with_alpha(0.78)));
17687
17688        let status_bar = render(
17689            StatusBar::new()
17690                .theme(theme)
17691                .segment(StatusBarSegment::new("Offline").tone(SemanticTone::Warning)),
17692        );
17693        assert!(solid_fill_colors(&status_bar).contains(&theme.palette.warning.with_alpha(0.12)));
17694
17695        let badge = render(
17696            StatusBadge::new("Replicated")
17697                .theme(theme)
17698                .tone(SemanticTone::Success)
17699                .icon(crate::IconGlyph::Storage),
17700        );
17701        // Mesh badges fill with the soft status wash and draw no border.
17702        assert!(solid_fill_colors(&badge).contains(&theme.palette.success_soft));
17703        assert!(!solid_stroke_colors(&badge).contains(&theme.palette.success.with_alpha(0.52)));
17704
17705        let progress_bar = render(
17706            ProgressBar::new("Delete progress")
17707                .theme(theme)
17708                .tone(SemanticTone::Danger)
17709                .value(0.5),
17710        );
17711        assert!(solid_fill_colors(&progress_bar).contains(&theme.palette.danger));
17712    }
17713
17714    struct CommandButtonPaintFixture {
17715        theme: DefaultTheme,
17716        style: CommandButtonPaint,
17717    }
17718
17719    impl Widget for CommandButtonPaintFixture {
17720        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17721            constraints.clamp(Size::new(150.0, 28.0))
17722        }
17723
17724        fn paint(&self, ctx: &mut PaintCtx) {
17725            paint_command_button(
17726                ctx,
17727                &self.theme,
17728                ctx.bounds(),
17729                "Repair",
17730                Some(crate::IconGlyph::Storage),
17731                self.style,
17732            );
17733        }
17734    }
17735
17736    #[test]
17737    fn command_button_paint_uses_theme_surfaces_and_tones() {
17738        let theme = DefaultTheme::default();
17739
17740        let neutral = render(CommandButtonPaintFixture {
17741            theme,
17742            style: CommandButtonPaint::neutral().icon_tone(SemanticTone::Accent),
17743        });
17744        assert!(solid_fill_colors(&neutral).contains(&theme.surfaces.field));
17745        assert!(solid_stroke_colors(&neutral).contains(&theme.palette.border));
17746
17747        let hovered = render(CommandButtonPaintFixture {
17748            theme,
17749            style: CommandButtonPaint::neutral()
17750                .icon_tone(SemanticTone::Accent)
17751                .hovered(true),
17752        });
17753        assert!(solid_fill_colors(&hovered).contains(&theme.palette.control_hover));
17754
17755        let accent = render(CommandButtonPaintFixture {
17756            theme,
17757            style: CommandButtonPaint::filled(SemanticTone::Accent),
17758        });
17759        assert!(solid_fill_colors(&accent).contains(&theme.palette.accent));
17760        assert!(solid_stroke_colors(&accent).contains(&theme.palette.accent));
17761
17762        let pressed = render(CommandButtonPaintFixture {
17763            theme,
17764            style: CommandButtonPaint::filled(SemanticTone::Accent).pressed(true),
17765        });
17766        assert!(solid_fill_colors(&pressed).contains(&theme.palette.accent_pressed));
17767
17768        let danger = render(CommandButtonPaintFixture {
17769            theme,
17770            style: CommandButtonPaint::tonal(SemanticTone::Danger),
17771        });
17772        assert!(solid_fill_colors(&danger).contains(&theme.surfaces.field));
17773        assert!(solid_stroke_colors(&danger).contains(&theme.palette.danger.with_alpha(0.72)));
17774    }
17775
17776    struct DisclosureButtonPaintFixture {
17777        theme: DefaultTheme,
17778        expanded: bool,
17779    }
17780
17781    impl Widget for DisclosureButtonPaintFixture {
17782        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17783            constraints.clamp(Size::new(126.0, 24.0))
17784        }
17785
17786        fn paint(&self, ctx: &mut PaintCtx) {
17787            paint_disclosure_button(
17788                ctx,
17789                &self.theme,
17790                ctx.bounds(),
17791                if self.expanded {
17792                    "Show less"
17793                } else {
17794                    "Show more"
17795                },
17796                self.expanded,
17797                DisclosureButtonPaint::new(),
17798            );
17799        }
17800    }
17801
17802    #[test]
17803    fn disclosure_button_paint_uses_accent_command_button_style() {
17804        let theme = DefaultTheme::default();
17805        let collapsed = render(DisclosureButtonPaintFixture {
17806            theme,
17807            expanded: false,
17808        });
17809        let expanded = render(DisclosureButtonPaintFixture {
17810            theme,
17811            expanded: true,
17812        });
17813
17814        assert!(solid_fill_colors(&collapsed).contains(&theme.surfaces.field));
17815        assert!(solid_stroke_colors(&collapsed).contains(&theme.palette.accent.with_alpha(0.72)));
17816        assert_eq!(
17817            text_run_for(&collapsed, "Show more").style.color,
17818            theme.palette.accent
17819        );
17820        assert_eq!(
17821            text_run_for(&expanded, "Show less").style.color,
17822            theme.palette.accent
17823        );
17824    }
17825
17826    struct CompactCommandButtonPaintFixture {
17827        theme: DefaultTheme,
17828    }
17829
17830    impl Widget for CompactCommandButtonPaintFixture {
17831        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17832            constraints.clamp(Size::new(200.0, 24.0))
17833        }
17834
17835        fn paint(&self, ctx: &mut PaintCtx) {
17836            let mut natural_style =
17837                text_token_style(&self.theme, self.theme.text.sm, self.theme.palette.accent);
17838            natural_style.weight = FontWeight::SEMIBOLD;
17839            let natural_width = ctx
17840                .measure_text("Hide details", natural_style)
17841                .expect("command button label should be measurable")
17842                .width;
17843            let target_label_width = natural_width * 0.95;
17844            // Compact command buttons reserve 8px leading padding, a 12px icon,
17845            // a 6px gap, and 6px trailing padding around the label slot.
17846            let button_rect = Rect::new(
17847                ctx.bounds().x(),
17848                ctx.bounds().y(),
17849                target_label_width + 32.0,
17850                ctx.bounds().height(),
17851            );
17852            paint_command_button(
17853                ctx,
17854                &self.theme,
17855                button_rect,
17856                "Hide details",
17857                Some(crate::IconGlyph::ChevronUp),
17858                CommandButtonPaint::tonal(SemanticTone::Accent).icon_tone(SemanticTone::Accent),
17859            );
17860        }
17861    }
17862
17863    #[test]
17864    fn command_button_paint_scales_label_in_compact_slots() {
17865        let theme = DefaultTheme::default();
17866        let output = render(CompactCommandButtonPaintFixture { theme });
17867        let label = text_run_for(&output, "Hide details");
17868        let layout = text_layout_for(&output, "Hide details");
17869
17870        assert!(
17871            label.style.font_size < theme.text.sm.size,
17872            "compact command button should reduce label font size"
17873        );
17874        assert!(label.style.font_size >= 10.0);
17875        assert_eq!(layout.lines().len(), 1, "label should not wrap");
17876        assert!(
17877            layout.measurement().width <= layout.box_size().width + 0.01,
17878            "compact command button label should fit its slot: measurement={:?} box={:?}",
17879            layout.measurement(),
17880            layout.box_size()
17881        );
17882    }
17883
17884    struct ActionTilePaintFixture {
17885        theme: DefaultTheme,
17886        style: ActionTilePaint,
17887    }
17888
17889    impl Widget for ActionTilePaintFixture {
17890        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17891            constraints.clamp(Size::new(178.0, 58.0))
17892        }
17893
17894        fn paint(&self, ctx: &mut PaintCtx) {
17895            paint_action_tile(
17896                ctx,
17897                &self.theme,
17898                ctx.bounds(),
17899                "Check cluster",
17900                Some("background-agent"),
17901                Some(crate::IconGlyph::Storage),
17902                self.style,
17903            );
17904        }
17905    }
17906
17907    struct ActionTileReservedSlotFixture {
17908        theme: DefaultTheme,
17909        style: ActionTilePaint,
17910    }
17911
17912    impl Widget for ActionTileReservedSlotFixture {
17913        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
17914            constraints.clamp(Size::new(178.0, 58.0))
17915        }
17916
17917        fn paint(&self, ctx: &mut PaintCtx) {
17918            paint_action_tile(
17919                ctx,
17920                &self.theme,
17921                ctx.bounds(),
17922                "Check cluster",
17923                Some("background-agent"),
17924                None,
17925                self.style,
17926            );
17927        }
17928    }
17929
17930    #[test]
17931    fn action_tile_paint_supports_highlight_hover_and_press_states() {
17932        let theme = DefaultTheme::default();
17933
17934        let neutral = render(ActionTilePaintFixture {
17935            theme,
17936            style: ActionTilePaint::neutral(),
17937        });
17938        assert!(solid_fill_colors(&neutral).contains(&theme.palette.control));
17939        assert!(solid_stroke_colors(&neutral).contains(&theme.palette.border));
17940
17941        let highlighted = render(ActionTilePaintFixture {
17942            theme,
17943            style: ActionTilePaint::tonal(SemanticTone::Accent),
17944        });
17945        assert!(solid_stroke_colors(&highlighted).contains(&theme.palette.accent.with_alpha(0.84)));
17946
17947        let hovered = render(ActionTilePaintFixture {
17948            theme,
17949            style: ActionTilePaint::neutral().hovered(true),
17950        });
17951        assert!(solid_fill_colors(&hovered).contains(&theme.palette.control_hover));
17952
17953        let pressed = render(ActionTilePaintFixture {
17954            theme,
17955            style: ActionTilePaint::neutral().pressed(true),
17956        });
17957        assert!(solid_fill_colors(&pressed).contains(&theme.palette.control_active));
17958    }
17959
17960    #[test]
17961    fn action_tile_paint_supports_surface_overrides_and_reserved_slots() {
17962        let theme = DefaultTheme::default();
17963        let output = render(ActionTileReservedSlotFixture {
17964            theme,
17965            style: ActionTilePaint::neutral()
17966                .background(theme.surfaces.panel)
17967                .border(theme.palette.warning)
17968                .title_color(theme.palette.text)
17969                .subtitle_color(theme.surfaces.text_faint)
17970                .icon_color(theme.palette.accent)
17971                .radius(theme.radius.xl)
17972                .padding_x(12.0)
17973                .leading_width(18.0)
17974                .trailing_width(48.0),
17975        });
17976
17977        assert!(solid_fill_colors(&output).contains(&theme.surfaces.panel));
17978        assert!(solid_stroke_colors(&output).contains(&theme.palette.warning));
17979
17980        let title = text_run_for(&output, "Check cluster");
17981        let subtitle = text_run_for(&output, "background-agent");
17982        assert_eq!(title.style.color, theme.palette.text);
17983        assert_eq!(subtitle.style.color, theme.surfaces.text_faint);
17984        assert!(
17985            title.rect.x() >= 30.0,
17986            "reserved leading slot should move title after the status slot: {:?}",
17987            title.rect
17988        );
17989        let title_clip = clip_rect_for_text(&output, "Check cluster");
17990        assert!(
17991            title_clip.max_x() <= 118.0,
17992            "reserved trailing slot should keep title clip clear of action area: {:?}",
17993            title_clip
17994        );
17995    }
17996
17997    #[test]
17998    fn action_tile_paint_supports_leading_semantic_status_dot() {
17999        let theme = DefaultTheme::default();
18000        let output = render(ActionTileReservedSlotFixture {
18001            theme,
18002            style: ActionTilePaint::neutral()
18003                .padding_x(12.0)
18004                .leading_tone_dot(SemanticTone::Success)
18005                .leading_width(18.0),
18006        });
18007
18008        assert!(
18009            solid_fill_colors(&output).contains(&theme.semantic_tone_color(SemanticTone::Success)),
18010            "leading status dot should use semantic tone color"
18011        );
18012        let title = text_run_for(&output, "Check cluster");
18013        assert!(
18014            title.rect.x() >= 30.0,
18015            "leading status dot should reserve the standard leading slot: {:?}",
18016            title.rect
18017        );
18018    }
18019
18020    struct CalloutPaintFixture {
18021        theme: DefaultTheme,
18022    }
18023
18024    impl Widget for CalloutPaintFixture {
18025        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
18026            constraints.clamp(Size::new(260.0, 104.0))
18027        }
18028
18029        fn paint(&self, ctx: &mut PaintCtx) {
18030            paint_callout(
18031                ctx,
18032                &self.theme,
18033                ctx.bounds(),
18034                Some(crate::IconGlyph::Alert),
18035                Some("Conflict"),
18036                "notes.md changed on two devices while offline. Resolve before syncing.",
18037                CalloutPaint::new(SemanticTone::Warning).reserved_bottom(24.0),
18038            );
18039        }
18040    }
18041
18042    #[test]
18043    fn callout_paint_uses_tone_rail_wrapped_text_and_reserved_bottom() {
18044        let theme = DefaultTheme::default();
18045        let (tone, _) = theme.semantic_tone_colors(SemanticTone::Warning);
18046        let (tone_soft, _) = theme.semantic_tone_soft_colors(SemanticTone::Warning);
18047        let output = render(CalloutPaintFixture { theme });
18048
18049        assert!(solid_fill_colors(&output).contains(&tone_soft));
18050        assert!(solid_fill_colors(&output).contains(&tone));
18051        assert!(solid_stroke_colors(&output).contains(&theme.palette.border));
18052
18053        let title = text_run_for(&output, "Conflict");
18054        assert_text_run_uses_token(&title, theme.text.sm);
18055        assert_eq!(title.style.color, theme.palette.text);
18056        assert_eq!(title.style.weight, FontWeight::SEMIBOLD);
18057
18058        let body_text = "notes.md changed on two devices while offline. Resolve before syncing.";
18059        let body = text_run_for(&output, body_text);
18060        assert_text_run_uses_token(&body, theme.text.sm);
18061        assert_eq!(body.style.color, theme.palette.text_muted);
18062        let body_clip = clip_rect_for_text(&output, body_text);
18063        assert!(body_clip.height() <= 104.0 - 20.0 - 24.0 + 0.01);
18064    }
18065
18066    struct CodePanelPaintFixture {
18067        theme: DefaultTheme,
18068        style: CodePanelPaint,
18069        content: Rc<Cell<Rect>>,
18070    }
18071
18072    impl Widget for CodePanelPaintFixture {
18073        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
18074            constraints.clamp(Size::new(180.0, 84.0))
18075        }
18076
18077        fn paint(&self, ctx: &mut PaintCtx) {
18078            let content = paint_code_panel(ctx, &self.theme, ctx.bounds(), "rust", self.style);
18079            self.content.set(content);
18080            ctx.fill_rect(content, self.theme.palette.accent.with_alpha(0.08));
18081        }
18082    }
18083
18084    #[test]
18085    fn code_panel_paint_uses_compact_header_and_returns_content_rect() {
18086        let theme = DefaultTheme::default();
18087        let content = Rc::new(Cell::new(Rect::ZERO));
18088        let output = render(CodePanelPaintFixture {
18089            theme,
18090            style: CodePanelPaint::new(),
18091            content: Rc::clone(&content),
18092        });
18093
18094        assert!(solid_fill_colors(&output).contains(&theme.surfaces.field));
18095        assert!(solid_fill_colors(&output).contains(&theme.surfaces.titlebar));
18096        assert!(solid_stroke_colors(&output).contains(&theme.surfaces.border));
18097
18098        let label = text_run_for(&output, "rust");
18099        assert_text_run_uses_token(&label, theme.text.xs);
18100        assert_eq!(label.style.color, theme.surfaces.text_faint);
18101        assert_eq!(label.style.weight, FontWeight::SEMIBOLD);
18102
18103        let content = content.get();
18104        assert!((content.x() - 8.0).abs() < 0.01);
18105        assert!((content.y() - 30.0).abs() < 0.01);
18106        assert!((content.width() - 164.0).abs() < 0.01);
18107        assert!(content.height() > 0.0);
18108    }
18109
18110    struct CodeLinesPaintFixture {
18111        theme: DefaultTheme,
18112    }
18113
18114    impl Widget for CodeLinesPaintFixture {
18115        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
18116            constraints.clamp(Size::new(180.0, 46.0))
18117        }
18118
18119        fn paint(&self, ctx: &mut PaintCtx) {
18120            let first_spans = [
18121                CodeTextSpan::new("let").color(self.theme.palette.accent),
18122                CodeTextSpan::new(" value"),
18123            ];
18124            let second_spans = [CodeTextSpan::new("+ added").color(self.theme.palette.success)];
18125            let lines = [
18126                CodeTextLine::new(&first_spans),
18127                CodeTextLine::new(&second_spans)
18128                    .background(self.theme.palette.success.with_alpha(0.12)),
18129            ];
18130            paint_code_lines(
18131                ctx,
18132                &self.theme,
18133                ctx.bounds(),
18134                &lines,
18135                CodeTextPaint::new()
18136                    .color(self.theme.palette.text)
18137                    .line_height(18.0),
18138            );
18139        }
18140    }
18141
18142    #[test]
18143    fn code_lines_paint_supports_span_colors_and_line_backgrounds() {
18144        let theme = DefaultTheme::default();
18145        let output = render(CodeLinesPaintFixture { theme });
18146
18147        assert!(
18148            solid_fill_colors(&output).contains(&theme.palette.success.with_alpha(0.12)),
18149            "line background should be drawn before text"
18150        );
18151        let keyword = text_run_for(&output, "let");
18152        assert_eq!(keyword.style.color, theme.palette.accent);
18153        assert_eq!(keyword.style.font_families, Some(theme.fonts.mono.into()));
18154        let fallback = text_run_for(&output, " value");
18155        assert_eq!(fallback.style.color, theme.palette.text);
18156        let added = text_run_for(&output, "+ added");
18157        assert_eq!(added.style.color, theme.palette.success);
18158    }
18159
18160    struct SectionPanelPaintFixture {
18161        theme: DefaultTheme,
18162        content: Rc<Cell<Rect>>,
18163        title: Rc<Cell<Rect>>,
18164    }
18165
18166    impl Widget for SectionPanelPaintFixture {
18167        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
18168            constraints.clamp(Size::new(220.0, 90.0))
18169        }
18170
18171        fn paint(&self, ctx: &mut PaintCtx) {
18172            let geometry = paint_section_panel(
18173                ctx,
18174                &self.theme,
18175                ctx.bounds(),
18176                "Metadata",
18177                SectionPanelPaint::new()
18178                    .header_height(38.0)
18179                    .title_token(self.theme.text.base)
18180                    .trailing_width(42.0),
18181            );
18182            self.content.set(geometry.content_rect);
18183            self.title.set(geometry.title_rect);
18184            ctx.fill_rect(
18185                geometry.content_rect,
18186                self.theme.palette.accent.with_alpha(0.08),
18187            );
18188        }
18189    }
18190
18191    #[test]
18192    fn section_panel_paint_reserves_header_action_space_and_returns_content_rect() {
18193        let theme = DefaultTheme::default();
18194        let content = Rc::new(Cell::new(Rect::ZERO));
18195        let title_rect = Rc::new(Cell::new(Rect::ZERO));
18196        let output = render(SectionPanelPaintFixture {
18197            theme,
18198            content: Rc::clone(&content),
18199            title: Rc::clone(&title_rect),
18200        });
18201
18202        assert!(solid_fill_colors(&output).contains(&theme.surfaces.panel));
18203        assert!(solid_stroke_colors(&output).contains(&theme.surfaces.border));
18204
18205        let title = text_run_for(&output, "Metadata");
18206        assert_text_run_uses_token(&title, theme.text.base);
18207        assert_eq!(title.style.color, theme.surfaces.text);
18208        assert_eq!(title.style.weight, FontWeight::SEMIBOLD);
18209
18210        let title_rect = title_rect.get();
18211        assert!((title_rect.x() - 12.0).abs() < 0.01);
18212        assert!((title_rect.width() - 154.0).abs() < 0.01);
18213
18214        let content = content.get();
18215        assert!((content.x() - 12.0).abs() < 0.01);
18216        assert!((content.y() - 38.0).abs() < 0.01);
18217        assert!((content.width() - 196.0).abs() < 0.01);
18218        assert!(content.height() > 0.0);
18219    }
18220
18221    #[test]
18222    fn placement_badge_combines_status_and_replica_coverage() {
18223        let theme = DefaultTheme::default();
18224        let output = render(
18225            PlacementBadge::new("synced")
18226                .theme(theme)
18227                .icon(crate::IconGlyph::Storage)
18228                .tone(SemanticTone::Success)
18229                .coverage(2, 3)
18230                .min_width(136.0),
18231        );
18232
18233        assert!(solid_fill_colors(&output).contains(&theme.palette.success_soft));
18234        assert!(
18235            solid_fill_colors(&output)
18236                .iter()
18237                .filter(|color| **color == theme.palette.success)
18238                .count()
18239                >= 2,
18240            "coverage dots should paint filled replica dots"
18241        );
18242        let node = output
18243            .semantics
18244            .iter()
18245            .find(|node| node.name.as_deref() == Some("synced"))
18246            .expect("placement badge semantics should exist");
18247        assert_eq!(
18248            node.description.as_deref(),
18249            Some("2 of 3 replicas available")
18250        );
18251    }
18252
18253    struct PlacementBadgePaintFixture {
18254        theme: DefaultTheme,
18255    }
18256
18257    impl Widget for PlacementBadgePaintFixture {
18258        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
18259            constraints.clamp(Size::new(156.0, 34.0))
18260        }
18261
18262        fn paint(&self, ctx: &mut PaintCtx) {
18263            paint_placement_badge_with(
18264                ctx,
18265                &self.theme,
18266                ctx.bounds(),
18267                "synced",
18268                Some(crate::IconGlyph::Storage),
18269                SemanticTone::Success,
18270                Some((2, 3)),
18271                PlacementBadgePaint::new().padding(8.0, 5.0, 8.0, 5.0),
18272            );
18273        }
18274    }
18275
18276    #[test]
18277    fn placement_badge_paint_applies_cell_padding() {
18278        let theme = DefaultTheme::default();
18279        let output = render(PlacementBadgePaintFixture { theme });
18280
18281        let status = text_run_for(&output, "synced");
18282        assert!(
18283            status.rect.x() >= 8.0,
18284            "status label should stay inside left padding: {:?}",
18285            status.rect
18286        );
18287        assert!(
18288            status.rect.y() >= 5.0,
18289            "status label should stay inside top padding: {:?}",
18290            status.rect
18291        );
18292        assert!(
18293            status.rect.max_x() <= 148.0,
18294            "status label should stay inside right padding: {:?}",
18295            status.rect
18296        );
18297
18298        let coverage = text_run_for(&output, "2/3");
18299        assert!(
18300            coverage.rect.max_x() <= 148.0,
18301            "coverage label should stay inside right padding: {:?}",
18302            coverage.rect
18303        );
18304        assert!(
18305            solid_fill_colors(&output).contains(&theme.palette.success_soft),
18306            "padded placement badge should still paint the status fill"
18307        );
18308    }
18309
18310    #[test]
18311    fn action_card_exposes_accessible_description() {
18312        let output = render(
18313            crate::SizedBox::new()
18314                .size(Size::new(320.0, 104.0))
18315                .with_child(
18316                    ActionCard::new(
18317                        "Paint",
18318                        "Pixel canvas painting workspace with editor-style panels.",
18319                    )
18320                    .icon(crate::IconGlyph::Brush)
18321                    .accent(Color::rgba(0.80, 0.22, 0.44, 1.0)),
18322                ),
18323        );
18324
18325        let card = output
18326            .semantics
18327            .iter()
18328            .find(|node| node.role == SemanticsRole::Button)
18329            .expect("action card should expose button semantics");
18330        assert_eq!(card.name.as_deref(), Some("Paint"));
18331        assert_eq!(
18332            card.description.as_deref(),
18333            Some("Pixel canvas painting workspace with editor-style panels.")
18334        );
18335        assert_eq!(
18336            card.value,
18337            Some(SemanticsValue::Text(
18338                "Pixel canvas painting workspace with editor-style panels.".to_string()
18339            ))
18340        );
18341        assert!(card.actions.contains(&SemanticsAction::Focus));
18342        assert!(card.actions.contains(&SemanticsAction::Activate));
18343    }
18344
18345    #[test]
18346    fn action_card_text_visual_centers_match_title_and_description_slots() {
18347        let theme = DefaultTheme::default();
18348        let output = render(
18349            crate::SizedBox::new()
18350                .size(Size::new(320.0, 104.0))
18351                .with_child(
18352                    ActionCard::new("Paint", "Pixel canvas workspace")
18353                        .theme(theme)
18354                        .icon(crate::IconGlyph::Brush),
18355                ),
18356        );
18357        let card = output
18358            .semantics
18359            .iter()
18360            .find(|node| {
18361                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Paint")
18362            })
18363            .expect("action card should expose button semantics");
18364
18365        let title = text_run_for(&output, "Paint");
18366        let title_layout = text_run_layout(&title);
18367        let title_line = title_layout
18368            .lines()
18369            .first()
18370            .expect("action card title should contain one line");
18371        let title_visual_center = title.rect.y()
18372            + title_line.baseline
18373            + optical_visual_center(title_layout.measurement());
18374
18375        let description = text_run_for(&output, "Pixel canvas workspace");
18376        let description_layout = text_run_layout(&description);
18377        let description_line = description_layout
18378            .lines()
18379            .first()
18380            .expect("action card description should contain one line");
18381        let description_visual_center = description.rect.y()
18382            + description_line.baseline
18383            + optical_visual_center(description_layout.measurement());
18384
18385        let metrics = theme.metrics;
18386        let content = super::inset_rect(card.bounds, metrics.action_card_padding);
18387        let icon_extent = metrics.action_card_icon_box_size + metrics.action_card_icon_gap;
18388        let text_bounds = Rect::new(
18389            content.x() + icon_extent,
18390            content.y(),
18391            (content.width() - icon_extent - metrics.action_card_trailing_gap).max(0.0),
18392            content.height(),
18393        );
18394        let title_height = title
18395            .style
18396            .line_height
18397            .max(title_layout.measurement().height);
18398        let description_height =
18399            (text_bounds.height() - title_height - metrics.action_card_text_gap)
18400                .max(description.style.line_height)
18401                .min(description.style.line_height * 2.0);
18402        let text_block_height = title_height + metrics.action_card_text_gap + description_height;
18403        let text_y = text_bounds.y() + ((text_bounds.height() - text_block_height) * 0.5).max(0.0);
18404        let title_slot = Rect::new(text_bounds.x(), text_y, text_bounds.width(), title_height);
18405        let description_slot = Rect::new(
18406            text_bounds.x(),
18407            title_slot.max_y() + metrics.action_card_text_gap,
18408            text_bounds.width(),
18409            description_height,
18410        );
18411
18412        assert!((title_visual_center - super::rect_center(title_slot).y).abs() < 0.75);
18413        assert!((description_visual_center - super::rect_center(description_slot).y).abs() < 0.75);
18414    }
18415
18416    #[test]
18417    fn action_card_multiline_description_stays_inside_clip_slot() {
18418        let description = "Catalog of controls, containers, media, and text surfaces.";
18419        let output = render(
18420            crate::SizedBox::new()
18421                .size(Size::new(360.0, 104.0))
18422                .with_child(
18423                    ActionCard::new("Widget book", description)
18424                        .icon(crate::IconGlyph::MoreHorizontal),
18425                ),
18426        );
18427        let run = text_run_for(&output, description);
18428        let clip = clip_rect_for_text(&output, description);
18429        let layout = TextSystem::new()
18430            .shape_text_run(&run, &FontRegistry::new())
18431            .expect("action card description should shape");
18432
18433        assert!(
18434            layout.lines().len() > 1,
18435            "test description should wrap in the dev picker-sized card"
18436        );
18437        assert!(
18438            run.rect.y() >= clip.y() - 0.01,
18439            "description should start inside its clip: rect={:?}, clip={:?}",
18440            run.rect,
18441            clip
18442        );
18443        assert!(
18444            run.rect.max_y() <= clip.max_y() + 0.01,
18445            "description should end inside its clip: rect={:?}, clip={:?}",
18446            run.rect,
18447            clip
18448        );
18449    }
18450
18451    #[test]
18452    fn action_card_text_preserves_tall_measurements_in_compact_line_boxes() {
18453        let mut theme = DefaultTheme::default();
18454        theme.text.base = ThemeTextToken {
18455            size: 32.0,
18456            line_height: 12.0,
18457        };
18458        theme.text.sm = ThemeTextToken {
18459            size: 32.0,
18460            line_height: 12.0,
18461        };
18462        let output = render(
18463            crate::SizedBox::new()
18464                .size(Size::new(360.0, 148.0))
18465                .with_child(
18466                    ActionCard::new("Paint", "Glyph box")
18467                        .theme(theme)
18468                        .icon(crate::IconGlyph::Brush),
18469                ),
18470        );
18471        let card = output
18472            .semantics
18473            .iter()
18474            .find(|node| {
18475                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Paint")
18476            })
18477            .expect("action card should expose button semantics");
18478        let description = text_run_for(&output, "Glyph box");
18479        let description_layout = TextSystem::new()
18480            .shape_text_run(&description, &FontRegistry::new())
18481            .expect("action card description should shape");
18482        let title = text_run_for(&output, "Paint");
18483        let title_layout = TextSystem::new()
18484            .shape_text_run(&title, &FontRegistry::new())
18485            .expect("action card title should shape");
18486        let metrics = theme.metrics;
18487        let content = super::inset_rect(card.bounds, metrics.action_card_padding);
18488        let icon_extent = metrics.action_card_icon_box_size + metrics.action_card_icon_gap;
18489        let text_bounds = Rect::new(
18490            content.x() + icon_extent,
18491            content.y(),
18492            (content.width() - icon_extent - metrics.action_card_trailing_gap).max(0.0),
18493            content.height(),
18494        );
18495        let title_height = title
18496            .style
18497            .line_height
18498            .max(title_layout.measurement().height);
18499        let description_min_height = description
18500            .style
18501            .line_height
18502            .max(description_layout.measurement().height);
18503        let description_height =
18504            (text_bounds.height() - title_height - metrics.action_card_text_gap)
18505                .max(description_min_height)
18506                .min((description.style.line_height * 2.0).max(description_min_height));
18507        let text_block_height = title_height + metrics.action_card_text_gap + description_height;
18508        let text_y = text_bounds.y() + ((text_bounds.height() - text_block_height) * 0.5).max(0.0);
18509        let title_slot = Rect::new(text_bounds.x(), text_y, text_bounds.width(), title_height);
18510        let description_slot = Rect::new(
18511            text_bounds.x(),
18512            text_y + title_height + metrics.action_card_text_gap,
18513            text_bounds.width(),
18514            description_height,
18515        );
18516
18517        assert_text_run_uses_token(&title, theme.text.base);
18518        assert!(
18519            title.rect.height() >= title_layout.measurement().height - 0.01,
18520            "action card title rect should preserve measured glyph height: rect={:?}, measurement={:?}",
18521            title.rect,
18522            title_layout.measurement()
18523        );
18524        assert!(
18525            title.rect.height() > title.style.line_height,
18526            "test theme should exercise a title measurement taller than line-height"
18527        );
18528        assert!(
18529            (text_run_visual_center(&title) - super::rect_center(title_slot).y).abs() < 0.75,
18530            "title text should remain optically centered in its slot"
18531        );
18532        assert_text_run_uses_token(&description, theme.text.sm);
18533        assert!(
18534            description.rect.height() >= description_layout.measurement().height - 0.01,
18535            "action card description rect should preserve measured glyph height: rect={:?}, measurement={:?}",
18536            description.rect,
18537            description_layout.measurement()
18538        );
18539        assert!(
18540            description.rect.height() > description.style.line_height * 2.0,
18541            "test theme should exercise measured-height preservation beyond the old two-line cap"
18542        );
18543        assert!(
18544            (text_run_visual_center(&description) - super::rect_center(description_slot).y).abs()
18545                < 0.75,
18546            "description text should remain optically centered in its slot"
18547        );
18548        assert!(
18549            description.rect.y() >= text_bounds.y(),
18550            "description should stay inside action card text bounds"
18551        );
18552        assert!(
18553            description.rect.max_y() <= text_bounds.max_y() + 0.75,
18554            "description should stay inside action card text bounds"
18555        );
18556    }
18557
18558    #[test]
18559    fn composite_default_text_styles_follow_theme_text_tokens() {
18560        let mut theme = DefaultTheme::default();
18561        theme.text.xs = ThemeTextToken {
18562            size: 11.0,
18563            line_height: 15.0,
18564        };
18565        theme.text.sm = ThemeTextToken {
18566            size: 15.0,
18567            line_height: 23.0,
18568        };
18569        theme.text.base = ThemeTextToken {
18570            size: 17.0,
18571            line_height: 25.0,
18572        };
18573        theme.sync_derived_fields();
18574
18575        let action_card = render(
18576            crate::SizedBox::new()
18577                .size(Size::new(320.0, 112.0))
18578                .with_child(ActionCard::new("Token action", "Token action detail").theme(theme)),
18579        );
18580        assert_text_run_uses_token(&text_run_for(&action_card, "Token action"), theme.text.base);
18581        assert_text_run_uses_token(
18582            &text_run_for(&action_card, "Token action detail"),
18583            theme.text.sm,
18584        );
18585
18586        let property_row = render(
18587            crate::SizedBox::new()
18588                .size(Size::new(320.0, 64.0))
18589                .with_child(
18590                    PropertyRow::new("Token property", crate::Button::new("Edit"))
18591                        .theme(theme)
18592                        .inline(),
18593                ),
18594        );
18595        assert_text_run_uses_token(
18596            &text_run_for(&property_row, "Token property"),
18597            theme.text.sm,
18598        );
18599
18600        let form_section = render(
18601            crate::SizedBox::new()
18602                .size(Size::new(360.0, 140.0))
18603                .with_child(
18604                    FormSection::new("Token section", crate::Button::new("Apply"))
18605                        .theme(theme)
18606                        .description("Token section detail"),
18607                ),
18608        );
18609        assert_text_run_uses_token(&text_run_for(&form_section, "Token section"), theme.text.sm);
18610        assert_text_run_uses_token(
18611            &text_run_for(&form_section, "Token section detail"),
18612            theme.text.xs,
18613        );
18614
18615        let preset_strip = render(
18616            crate::SizedBox::new()
18617                .size(Size::new(240.0, 44.0))
18618                .with_child(
18619                    PresetStrip::new("Brush")
18620                        .theme(theme)
18621                        .preset("Token preset"),
18622                ),
18623        );
18624        assert_text_run_uses_token(&text_run_for(&preset_strip, "Token preset"), theme.text.xs);
18625
18626        let status_bar = render(
18627            crate::SizedBox::new()
18628                .size(Size::new(240.0, 32.0))
18629                .with_child(StatusBar::new().theme(theme).text_segment("Token status")),
18630        );
18631        assert_text_run_uses_token(&text_run_for(&status_bar, "Token status"), theme.text.xs);
18632    }
18633
18634    #[test]
18635    fn preset_strip_exposes_selected_preset_semantics() {
18636        let output = render(
18637            crate::SizedBox::new()
18638                .size(Size::new(220.0, 32.0))
18639                .with_child(
18640                    PresetStrip::new("Brush presets")
18641                        .presets(["8 px", "18 px", "36 px"])
18642                        .selected(1),
18643                ),
18644        );
18645
18646        let strip = output
18647            .semantics
18648            .iter()
18649            .find(|node| {
18650                node.role == SemanticsRole::GenericContainer
18651                    && node.name.as_deref() == Some("Brush presets")
18652            })
18653            .expect("preset strip container semantics should exist");
18654        assert_eq!(strip.value, Some(SemanticsValue::Text("18 px".to_string())));
18655        assert!(strip.actions.contains(&SemanticsAction::SetValue));
18656
18657        let selected = output
18658            .semantics
18659            .iter()
18660            .find(|node| {
18661                node.role == SemanticsRole::Button && node.name.as_deref() == Some("18 px")
18662            })
18663            .expect("selected preset button semantics should exist");
18664        assert!(selected.state.selected);
18665        assert_eq!(
18666            selected.value,
18667            Some(SemanticsValue::Text("18 px".to_string()))
18668        );
18669    }
18670
18671    #[test]
18672    fn preset_strip_label_clips_to_padded_item_slot() {
18673        let theme = DefaultTheme::default();
18674        let output = render(
18675            crate::SizedBox::new()
18676                .size(Size::new(220.0, 40.0))
18677                .with_child(
18678                    PresetStrip::new("Brush presets")
18679                        .item_width(180.0)
18680                        .preset("Soft"),
18681                ),
18682        );
18683        let preset = output
18684            .semantics
18685            .iter()
18686            .find(|node| node.role == SemanticsRole::Button && node.name.as_deref() == Some("Soft"))
18687            .expect("preset button semantics should exist");
18688        let text = text_run_for(&output, "Soft");
18689        let clip = clip_rect_for_text(&output, "Soft");
18690        let expected_clip =
18691            super::inset_rect(preset.bounds, theme.metrics.preset_strip_label_padding);
18692
18693        assert!(
18694            clip.width() > text.rect.width(),
18695            "clip should cover the padded item slot rather than the measured text rect"
18696        );
18697        assert!((clip.x() - expected_clip.x()).abs() < 0.75);
18698        assert!((clip.y() - expected_clip.y()).abs() < 0.75);
18699        assert!((clip.width() - expected_clip.width()).abs() < 0.75);
18700        assert!((clip.height() - expected_clip.height()).abs() < 0.75);
18701    }
18702
18703    #[test]
18704    fn preset_strip_label_preserves_tall_measurements_and_item_centering() {
18705        let mut theme = DefaultTheme::default();
18706        theme.text.xs = ThemeTextToken {
18707            size: 28.0,
18708            line_height: 12.0,
18709        };
18710        theme.sync_derived_fields();
18711
18712        let output = render_isolated(
18713            crate::SizedBox::new()
18714                .size(Size::new(240.0, 56.0))
18715                .with_child(
18716                    PresetStrip::new("Brush presets")
18717                        .theme(theme)
18718                        .item_height(56.0)
18719                        .item_width(180.0)
18720                        .preset("Soft"),
18721                ),
18722        );
18723        let preset = output
18724            .semantics
18725            .iter()
18726            .find(|node| node.role == SemanticsRole::Button && node.name.as_deref() == Some("Soft"))
18727            .expect("preset button semantics should exist");
18728        let text = text_run_for(&output, "Soft");
18729        let layout = TextSystem::new()
18730            .shape_text_run(&text, &FontRegistry::new())
18731            .expect("preset label should shape");
18732
18733        assert_text_run_uses_token(&text, theme.text.xs);
18734        assert!(text.rect.height() >= layout.measurement().height - 0.01);
18735        assert!(text.rect.height() > text.style.line_height);
18736        assert!(
18737            (text_visual_center_for(&output, "Soft") - super::rect_center(preset.bounds).y).abs()
18738                < 0.75
18739        );
18740    }
18741
18742    #[test]
18743    fn preset_strip_pointer_activation_updates_selection() -> sui_core::Result<()> {
18744        let chosen = Rc::new(RefCell::new(None));
18745        let chosen_writer = Rc::clone(&chosen);
18746        let (mut runtime, window_id) = build_runtime(
18747            crate::SizedBox::new()
18748                .size(Size::new(220.0, 32.0))
18749                .with_child(
18750                    PresetStrip::new("Brush presets")
18751                        .presets(["8 px", "18 px", "36 px"])
18752                        .selected(0)
18753                        .on_change(move |index, label| {
18754                            *chosen_writer.borrow_mut() = Some((index, label));
18755                        }),
18756                ),
18757        );
18758        let output = runtime.render(window_id)?;
18759        let preset = output
18760            .semantics
18761            .iter()
18762            .find(|node| {
18763                node.role == SemanticsRole::Button && node.name.as_deref() == Some("36 px")
18764            })
18765            .expect("target preset button should exist");
18766        let position = super::rect_center(preset.bounds);
18767
18768        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
18769        move_event.pointer_id = 1;
18770        runtime.handle_event(window_id, Event::Pointer(move_event))?;
18771
18772        let mut down = PointerEvent::new(PointerEventKind::Down, position);
18773        down.pointer_id = 1;
18774        down.button = Some(PointerButton::Primary);
18775        down.buttons = PointerButtons::new(1);
18776        runtime.handle_event(window_id, Event::Pointer(down))?;
18777
18778        let mut up = PointerEvent::new(PointerEventKind::Up, position);
18779        up.pointer_id = 1;
18780        up.button = Some(PointerButton::Primary);
18781        runtime.handle_event(window_id, Event::Pointer(up))?;
18782
18783        assert_eq!(*chosen.borrow(), Some((2, "36 px".to_string())));
18784        let output = runtime.render(window_id)?;
18785        assert!(output.semantics.iter().any(|node| {
18786            node.role == SemanticsRole::Button
18787                && node.name.as_deref() == Some("36 px")
18788                && node.state.selected
18789        }));
18790        Ok(())
18791    }
18792
18793    #[test]
18794    fn preset_strip_hover_and_press_use_theme_motion() -> Result<(), String> {
18795        let theme = DefaultTheme::default();
18796        let hover_duration = theme.motion.hover_duration();
18797        let press_duration = theme.motion.press_duration();
18798        let expected_hover = super::mix_color(
18799            theme.palette.surface,
18800            theme.palette.control_hover,
18801            theme.interaction.hover_blend,
18802        );
18803        let expected_press = super::mix_color(
18804            expected_hover,
18805            theme.palette.control_active,
18806            theme.interaction.pressed_blend,
18807        );
18808        let (mut runtime, window_id) = build_runtime(
18809            crate::SizedBox::new()
18810                .size(Size::new(220.0, 32.0))
18811                .with_child(
18812                    PresetStrip::new("Brush presets")
18813                        .theme(theme)
18814                        .presets(["8 px", "18 px", "36 px"]),
18815                ),
18816        );
18817        let output = runtime
18818            .render(window_id)
18819            .map_err(|error| error.to_string())?;
18820        let preset = output
18821            .semantics
18822            .iter()
18823            .find(|node| {
18824                node.role == SemanticsRole::Button && node.name.as_deref() == Some("18 px")
18825            })
18826            .expect("target preset button should exist");
18827        let position = super::rect_center(preset.bounds);
18828
18829        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
18830        move_event.pointer_id = 1;
18831        runtime
18832            .handle_event(window_id, Event::Pointer(move_event))
18833            .map_err(|error| error.to_string())?;
18834
18835        runtime.tick(hover_duration * 0.5);
18836        assert_eq!(handle_ready_events(&mut runtime)?, 1);
18837        let mid_hover = runtime
18838            .render(window_id)
18839            .map_err(|error| error.to_string())?;
18840        assert!(
18841            !solid_fill_colors(&mid_hover).contains(&expected_hover),
18842            "hover fill should not snap to the settled hover color"
18843        );
18844
18845        runtime.tick(hover_duration);
18846        assert_eq!(handle_ready_events(&mut runtime)?, 1);
18847        let settled_hover = runtime
18848            .render(window_id)
18849            .map_err(|error| error.to_string())?;
18850        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
18851
18852        runtime
18853            .handle_event(
18854                window_id,
18855                primary_pointer(PointerEventKind::Down, position, true),
18856            )
18857            .map_err(|error| error.to_string())?;
18858
18859        runtime.tick(hover_duration + press_duration * 0.5);
18860        assert_eq!(handle_ready_events(&mut runtime)?, 1);
18861        let mid_press = runtime
18862            .render(window_id)
18863            .map_err(|error| error.to_string())?;
18864        assert!(
18865            !solid_fill_colors(&mid_press).contains(&expected_press),
18866            "press fill should not snap to the settled pressed color"
18867        );
18868
18869        runtime.tick(hover_duration + press_duration);
18870        assert_eq!(handle_ready_events(&mut runtime)?, 1);
18871        let settled_press = runtime
18872            .render(window_id)
18873            .map_err(|error| error.to_string())?;
18874        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
18875
18876        Ok(())
18877    }
18878
18879    #[test]
18880    fn status_bar_exposes_dynamic_segment_semantics() {
18881        let theme = DefaultTheme::default();
18882        let zoom = Rc::new(RefCell::new("Zoom 35%".to_string()));
18883        let zoom_reader = Rc::clone(&zoom);
18884        let output = render(
18885            StatusBar::new()
18886                .name("Editor status")
18887                .segment(StatusBarSegment::new("Ready").min_width(80.0))
18888                .segment(
18889                    StatusBarSegment::dynamic("Zoom --", move || zoom_reader.borrow().clone())
18890                        .min_width(120.0),
18891                ),
18892        );
18893
18894        let status = output
18895            .semantics
18896            .iter()
18897            .find(|node| {
18898                node.role == SemanticsRole::GenericContainer
18899                    && node.name.as_deref() == Some("Editor status")
18900            })
18901            .expect("status bar container semantics should exist");
18902        assert_eq!(status.bounds.height(), theme.metrics.status_bar_height);
18903        assert!(output.semantics.iter().any(|node| {
18904            node.role == SemanticsRole::Text && node.name.as_deref() == Some("Zoom 35%")
18905        }));
18906    }
18907
18908    #[test]
18909    fn status_bar_description_is_exposed_to_semantics() {
18910        let summary = Rc::new(RefCell::new(
18911            "SIFS online | Path /services | idle".to_string(),
18912        ));
18913        let summary_reader = Rc::clone(&summary);
18914        let output = render(
18915            StatusBar::new()
18916                .name("Files status")
18917                .description_when(move || summary_reader.borrow().clone())
18918                .segment(StatusBarSegment::new("Path /services").expand(true)),
18919        );
18920
18921        let status = output
18922            .semantics
18923            .iter()
18924            .find(|node| {
18925                node.role == SemanticsRole::GenericContainer
18926                    && node.name.as_deref() == Some("Files status")
18927            })
18928            .expect("status bar container semantics should exist");
18929        assert_eq!(
18930            status.value,
18931            Some(SemanticsValue::Text(
18932                "SIFS online | Path /services | idle".to_string(),
18933            ))
18934        );
18935        assert_eq!(
18936            status.description.as_deref(),
18937            Some("SIFS online | Path /services | idle")
18938        );
18939    }
18940
18941    #[test]
18942    fn status_badge_publishes_text_semantics_and_theme_token_text() {
18943        let theme = DefaultTheme::default();
18944        let output = render(
18945            StatusBadge::new("Primary on atlas")
18946                .theme(theme)
18947                .tone(SemanticTone::Accent)
18948                .icon(crate::IconGlyph::Storage),
18949        );
18950        let node = output
18951            .semantics
18952            .iter()
18953            .find(|node| {
18954                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Primary on atlas")
18955            })
18956            .expect("status badge should publish text semantics");
18957        assert_eq!(
18958            node.value,
18959            Some(SemanticsValue::Text("Primary on atlas".to_string()))
18960        );
18961        assert_text_run_uses_token(&text_run_for(&output, "Primary on atlas"), theme.text.xs);
18962    }
18963
18964    #[test]
18965    fn coverage_dots_publish_replica_like_coverage_semantics_and_token_text() {
18966        let theme = DefaultTheme::default();
18967        let output = render(
18968            CoverageDots::new("Replicas", 2, 3)
18969                .theme(theme)
18970                .tone(SemanticTone::Warning),
18971        );
18972        let node = output
18973            .semantics
18974            .iter()
18975            .find(|node| {
18976                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Replicas")
18977            })
18978            .expect("coverage dots should publish text semantics");
18979        assert_eq!(node.value, Some(SemanticsValue::Text("2/3".to_string())));
18980        assert_eq!(node.description.as_deref(), Some("2 of 3 covered"));
18981        assert_text_run_uses_token(&text_run_for(&output, "2/3"), theme.text.xs);
18982        assert!(contains_approx_color(
18983            &solid_fill_colors(&output),
18984            theme.semantic_tone_colors(SemanticTone::Warning).0,
18985        ));
18986    }
18987
18988    #[test]
18989    fn status_bar_sizes_segments_from_measured_text() {
18990        let theme = DefaultTheme::default();
18991        let text = "Layer Paint / Normal / 100% / Unlocked";
18992        let output = render(
18993            StatusBar::new()
18994                .name("Editor status")
18995                .segment(StatusBarSegment::new(text))
18996                .segment(StatusBarSegment::new("Cursor --").expand(true)),
18997        );
18998
18999        let layer = output
19000            .semantics
19001            .iter()
19002            .find(|node| {
19003                node.role == SemanticsRole::Text
19004                    && node.name.as_deref() == Some("Layer Paint / Normal / 100% / Unlocked")
19005            })
19006            .expect("long status segment should expose text semantics");
19007        let measured_width = text_layout_for(&output, text).measurement().width;
19008        let expected_width = (measured_width + theme.metrics.status_bar_segment_padding * 2.0)
19009            .ceil()
19010            .max(theme.metrics.status_bar_segment_min_width);
19011        assert!(
19012            (layer.bounds.width() - expected_width).abs() < 0.01,
19013            "expected status segment width {expected_width} from text measurement, got {:?}",
19014            layer.bounds
19015        );
19016    }
19017
19018    #[test]
19019    fn status_bar_numeric_segments_use_tabular_figures_without_forcing_plain_labels() {
19020        let output = render(
19021            StatusBar::new()
19022                .name("Editor status")
19023                .segment(StatusBarSegment::new("Ready").min_width(80.0))
19024                .segment(StatusBarSegment::new("Zoom 35%").min_width(120.0)),
19025        );
19026
19027        let ready = text_run_for(&output, "Ready");
19028        let zoom = text_run_for(&output, "Zoom 35%");
19029
19030        assert!(
19031            !ready
19032                .style
19033                .features
19034                .iter()
19035                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
19036        );
19037        assert!(
19038            zoom.style
19039                .features
19040                .iter()
19041                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
19042        );
19043    }
19044
19045    #[test]
19046    fn status_bar_segment_text_visual_center_matches_segment_center() {
19047        let output = render(
19048            crate::SizedBox::new()
19049                .size(Size::new(220.0, 40.0))
19050                .with_child(
19051                    StatusBar::new()
19052                        .height(40.0)
19053                        .segment(StatusBarSegment::new("Ready").min_width(96.0)),
19054                ),
19055        );
19056        let text = text_run_for(&output, "Ready");
19057        let layout = TextSystem::new()
19058            .shape_text_run(&text, &FontRegistry::new())
19059            .expect("status segment text should shape");
19060        let line = layout
19061            .lines()
19062            .first()
19063            .expect("status segment text should contain one line");
19064        let actual_visual_center =
19065            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
19066        let segment = output
19067            .semantics
19068            .iter()
19069            .find(|node| node.role == SemanticsRole::Text && node.name.as_deref() == Some("Ready"))
19070            .expect("status segment semantics should exist");
19071        let segment_center = segment.bounds.y() + (segment.bounds.height() * 0.5);
19072
19073        assert!((actual_visual_center - segment_center).abs() < 0.75);
19074    }
19075
19076    #[test]
19077    fn status_bar_segments_preserve_tall_measurements_and_numeric_features() {
19078        let mut theme = DefaultTheme::default();
19079        theme.text.xs = ThemeTextToken {
19080            size: 28.0,
19081            line_height: 10.0,
19082        };
19083        theme.metrics.status_bar_height = 52.0;
19084        let output = render(
19085            crate::SizedBox::new()
19086                .size(Size::new(360.0, 52.0))
19087                .with_child(
19088                    StatusBar::new()
19089                        .theme(theme)
19090                        .height(52.0)
19091                        .segment(StatusBarSegment::new("Ready").min_width(120.0))
19092                        .segment(StatusBarSegment::new("Zoom 35%").min_width(140.0)),
19093                ),
19094        );
19095        for label in ["Ready", "Zoom 35%"] {
19096            let text = text_run_for(&output, label);
19097            let layout = TextSystem::new()
19098                .shape_text_run(&text, &FontRegistry::new())
19099                .expect("status segment text should shape");
19100            let segment = output
19101                .semantics
19102                .iter()
19103                .find(|node| {
19104                    node.role == SemanticsRole::Text && node.name.as_deref() == Some(label)
19105                })
19106                .expect("status segment semantics should exist");
19107            let segment_center = segment.bounds.y() + (segment.bounds.height() * 0.5);
19108
19109            assert_text_run_uses_token(&text, theme.text.xs);
19110            assert!(text.rect.height() >= layout.measurement().height - 0.01);
19111            assert!(text.rect.height() > text.style.line_height);
19112            assert!((text_run_visual_center(&text) - segment_center).abs() < 0.75);
19113        }
19114
19115        let ready = text_run_for(&output, "Ready");
19116        let zoom = text_run_for(&output, "Zoom 35%");
19117        assert!(
19118            !ready
19119                .style
19120                .features
19121                .iter()
19122                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
19123        );
19124        assert!(
19125            zoom.style
19126                .features
19127                .iter()
19128                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
19129        );
19130    }
19131
19132    #[test]
19133    fn horizontal_toolbar_centers_children_and_exposes_group_semantics() {
19134        let output = render(
19135            crate::SizedBox::new()
19136                .size(Size::new(320.0, 52.0))
19137                .with_child(
19138                    Toolbar::horizontal()
19139                        .name("Editor toolbar")
19140                        .with_child(crate::Button::new("Fit").min_width(48.0).min_height(32.0))
19141                        .with_child(
19142                            crate::Button::new("Export")
19143                                .min_width(72.0)
19144                                .min_height(32.0),
19145                        ),
19146                ),
19147        );
19148
19149        let toolbar = output
19150            .semantics
19151            .iter()
19152            .find(|node| {
19153                node.role == SemanticsRole::GenericContainer
19154                    && node.name.as_deref() == Some("Editor toolbar")
19155            })
19156            .expect("toolbar semantics should exist");
19157        assert_eq!(toolbar.bounds, Rect::new(0.0, 0.0, 320.0, 52.0));
19158
19159        let fit = output
19160            .semantics
19161            .iter()
19162            .find(|node| node.role == SemanticsRole::Button && node.name.as_deref() == Some("Fit"))
19163            .expect("toolbar child button should exist");
19164        assert!(fit.bounds.y() > 0.0);
19165        assert!(fit.bounds.max_y() < toolbar.bounds.max_y());
19166    }
19167
19168    #[test]
19169    fn command_group_keeps_natural_size_and_exposes_group_semantics() {
19170        let theme = DefaultTheme::default();
19171        let output = render(
19172            crate::SizedBox::new()
19173                .size(Size::new(320.0, 48.0))
19174                .with_child(
19175                    Toolbar::horizontal()
19176                        .name("Editor toolbar")
19177                        .padding(sui_layout::Padding::all(4.0))
19178                        .with_child(
19179                            CommandGroup::horizontal("History commands")
19180                                .with_child(
19181                                    crate::IconButton::new(crate::IconGlyph::Undo, "Undo")
19182                                        .size(28.0),
19183                                )
19184                                .with_child(
19185                                    crate::IconButton::new(crate::IconGlyph::Redo, "Redo")
19186                                        .size(28.0),
19187                                ),
19188                        ),
19189                ),
19190        );
19191
19192        let group = output
19193            .semantics
19194            .iter()
19195            .find(|node| {
19196                node.role == SemanticsRole::GenericContainer
19197                    && node.name.as_deref() == Some("History commands")
19198            })
19199            .expect("command group semantics should exist");
19200        let button_size = 28.0_f32.max(theme.metrics.icon_button_size);
19201        let expected_width = button_size * 2.0
19202            + theme.metrics.command_group_spacing
19203            + theme.metrics.command_group_padding.left
19204            + theme.metrics.command_group_padding.right;
19205        let expected_height = button_size
19206            + theme.metrics.command_group_padding.top
19207            + theme.metrics.command_group_padding.bottom;
19208        assert!(
19209            (group.bounds.width() - expected_width).abs() < 0.01,
19210            "expected command group width {expected_width}, got {}",
19211            group.bounds.width()
19212        );
19213        assert!(
19214            (group.bounds.height() - expected_height).abs() < 0.01,
19215            "expected command group height {expected_height}, got {}",
19216            group.bounds.height()
19217        );
19218
19219        for name in ["Undo", "Redo"] {
19220            let button = output
19221                .semantics
19222                .iter()
19223                .find(|node| {
19224                    node.role == SemanticsRole::Button && node.name.as_deref() == Some(name)
19225                })
19226                .expect("command button should exist");
19227            assert!(button.bounds.x() >= group.bounds.x());
19228            assert!(button.bounds.max_x() <= group.bounds.max_x());
19229        }
19230    }
19231
19232    #[test]
19233    fn vertical_toolbar_uses_fixed_extent_and_centers_children() {
19234        let output = render(
19235            crate::SizedBox::new()
19236                .size(Size::new(80.0, 180.0))
19237                .with_child(
19238                    Toolbar::vertical()
19239                        .name("Paint tools")
19240                        .extent(60.0)
19241                        .with_child(
19242                            crate::IconButton::new(crate::IconGlyph::Brush, "Brush tool")
19243                                .size(44.0),
19244                        )
19245                        .with_child(
19246                            crate::IconButton::new(crate::IconGlyph::Eraser, "Eraser tool")
19247                                .size(44.0),
19248                        ),
19249                ),
19250        );
19251
19252        let toolbar = output
19253            .semantics
19254            .iter()
19255            .find(|node| {
19256                node.role == SemanticsRole::GenericContainer
19257                    && node.name.as_deref() == Some("Paint tools")
19258            })
19259            .expect("vertical toolbar semantics should exist");
19260        assert_eq!(toolbar.bounds, Rect::new(0.0, 0.0, 80.0, 180.0));
19261
19262        let brush = output
19263            .semantics
19264            .iter()
19265            .find(|node| {
19266                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Brush tool")
19267            })
19268            .expect("toolbar child button should exist");
19269        assert_eq!(brush.bounds.width(), 44.0);
19270        assert!((brush.bounds.x() - 18.0).abs() < 0.001);
19271    }
19272
19273    #[test]
19274    fn tool_palette_exposes_selected_tool_semantics() {
19275        let output = render(
19276            crate::SizedBox::new()
19277                .size(Size::new(64.0, 180.0))
19278                .with_child(
19279                    ToolPalette::vertical("Paint tools")
19280                        .items([
19281                            ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush tool"),
19282                            ToolPaletteItem::new(crate::IconGlyph::Eraser, "Eraser tool"),
19283                            ToolPaletteItem::new(crate::IconGlyph::PaintBucket, "Fill tool"),
19284                        ])
19285                        .selected(1),
19286                ),
19287        );
19288
19289        let palette = output
19290            .semantics
19291            .iter()
19292            .find(|node| {
19293                node.role == SemanticsRole::GenericContainer
19294                    && node.name.as_deref() == Some("Paint tools")
19295            })
19296            .expect("tool palette container semantics should exist");
19297        assert_eq!(
19298            palette.value,
19299            Some(SemanticsValue::Text("Eraser tool".to_string()))
19300        );
19301        assert!(palette.actions.contains(&SemanticsAction::Focus));
19302        assert!(palette.actions.contains(&SemanticsAction::SetValue));
19303
19304        let selected = output
19305            .semantics
19306            .iter()
19307            .find(|node| {
19308                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Eraser tool")
19309            })
19310            .expect("selected tool button semantics should exist");
19311        assert!(selected.state.selected);
19312        assert!(selected.actions.contains(&SemanticsAction::Activate));
19313    }
19314
19315    #[test]
19316    fn tool_palette_pointer_activation_updates_selection() -> sui_core::Result<()> {
19317        let chosen = Rc::new(RefCell::new(None));
19318        let chosen_writer = Rc::clone(&chosen);
19319        let (mut runtime, window_id) = build_runtime(
19320            crate::SizedBox::new()
19321                .size(Size::new(64.0, 180.0))
19322                .with_child(
19323                    ToolPalette::vertical("Paint tools")
19324                        .items([
19325                            ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush tool"),
19326                            ToolPaletteItem::new(crate::IconGlyph::Eraser, "Eraser tool"),
19327                            ToolPaletteItem::new(crate::IconGlyph::PaintBucket, "Fill tool"),
19328                        ])
19329                        .selected(0)
19330                        .on_change(move |index, label| {
19331                            *chosen_writer.borrow_mut() = Some((index, label));
19332                        }),
19333                ),
19334        );
19335        let output = runtime.render(window_id)?;
19336        let fill = output
19337            .semantics
19338            .iter()
19339            .find(|node| {
19340                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Fill tool")
19341            })
19342            .expect("fill tool button semantics should exist");
19343        let position = super::rect_center(fill.bounds);
19344
19345        runtime.handle_event(
19346            window_id,
19347            primary_pointer(PointerEventKind::Down, position, true),
19348        )?;
19349        runtime.handle_event(
19350            window_id,
19351            primary_pointer(PointerEventKind::Up, position, false),
19352        )?;
19353
19354        assert_eq!(*chosen.borrow(), Some((2, "Fill tool".to_string())));
19355        let output = runtime.render(window_id)?;
19356        assert!(output.semantics.iter().any(|node| {
19357            node.role == SemanticsRole::Button
19358                && node.name.as_deref() == Some("Fill tool")
19359                && node.state.selected
19360        }));
19361        Ok(())
19362    }
19363
19364    #[test]
19365    fn tool_palette_hover_and_press_use_theme_motion() -> Result<(), String> {
19366        let theme = DefaultTheme::default();
19367        let hover_duration = theme.motion.hover_duration();
19368        let press_duration = theme.motion.press_duration();
19369        let expected_hover = super::mix_color(
19370            theme.palette.surface,
19371            theme.palette.control_hover,
19372            theme.interaction.hover_blend,
19373        );
19374        let expected_press = super::mix_color(
19375            expected_hover,
19376            theme.palette.control_active,
19377            theme.interaction.pressed_blend,
19378        );
19379        let (mut runtime, window_id) = build_runtime(
19380            crate::SizedBox::new()
19381                .size(Size::new(64.0, 180.0))
19382                .with_child(ToolPalette::vertical("Paint tools").theme(theme).items([
19383                    ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush tool"),
19384                    ToolPaletteItem::new(crate::IconGlyph::Eraser, "Eraser tool"),
19385                    ToolPaletteItem::new(crate::IconGlyph::PaintBucket, "Fill tool"),
19386                ])),
19387        );
19388        let output = runtime
19389            .render(window_id)
19390            .map_err(|error| error.to_string())?;
19391        let eraser = output
19392            .semantics
19393            .iter()
19394            .find(|node| {
19395                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Eraser tool")
19396            })
19397            .expect("eraser tool button semantics should exist");
19398        let position = super::rect_center(eraser.bounds);
19399
19400        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
19401        move_event.pointer_id = 1;
19402        runtime
19403            .handle_event(window_id, Event::Pointer(move_event))
19404            .map_err(|error| error.to_string())?;
19405
19406        runtime.tick(hover_duration * 0.5);
19407        assert_eq!(handle_ready_events(&mut runtime)?, 1);
19408        let mid_hover = runtime
19409            .render(window_id)
19410            .map_err(|error| error.to_string())?;
19411        assert!(
19412            !solid_fill_colors(&mid_hover).contains(&expected_hover),
19413            "tool hover fill should not snap to the settled hover color"
19414        );
19415
19416        runtime.tick(hover_duration);
19417        assert_eq!(handle_ready_events(&mut runtime)?, 1);
19418        let settled_hover = runtime
19419            .render(window_id)
19420            .map_err(|error| error.to_string())?;
19421        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
19422
19423        runtime
19424            .handle_event(
19425                window_id,
19426                primary_pointer(PointerEventKind::Down, position, true),
19427            )
19428            .map_err(|error| error.to_string())?;
19429
19430        runtime.tick(hover_duration + press_duration * 0.5);
19431        assert_eq!(handle_ready_events(&mut runtime)?, 1);
19432        let mid_press = runtime
19433            .render(window_id)
19434            .map_err(|error| error.to_string())?;
19435        assert!(
19436            !solid_fill_colors(&mid_press).contains(&expected_press),
19437            "tool press fill should not snap to the settled pressed color"
19438        );
19439
19440        runtime.tick(hover_duration + press_duration);
19441        assert_eq!(handle_ready_events(&mut runtime)?, 1);
19442        let settled_press = runtime
19443            .render(window_id)
19444            .map_err(|error| error.to_string())?;
19445        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
19446
19447        Ok(())
19448    }
19449
19450    #[test]
19451    fn tool_palette_keyboard_moves_between_tools() -> sui_core::Result<()> {
19452        let chosen = Rc::new(RefCell::new(Vec::new()));
19453        let chosen_writer = Rc::clone(&chosen);
19454        let (mut runtime, window_id) = build_runtime(
19455            crate::SizedBox::new()
19456                .size(Size::new(64.0, 180.0))
19457                .with_child(
19458                    ToolPalette::vertical("Paint tools")
19459                        .items([
19460                            ToolPaletteItem::new(crate::IconGlyph::Brush, "Brush tool"),
19461                            ToolPaletteItem::new(crate::IconGlyph::Eraser, "Eraser tool"),
19462                            ToolPaletteItem::new(crate::IconGlyph::PaintBucket, "Fill tool"),
19463                        ])
19464                        .selected(0)
19465                        .on_change(move |index, label| {
19466                            chosen_writer.borrow_mut().push((index, label));
19467                        }),
19468                ),
19469        );
19470        let output = runtime.render(window_id)?;
19471        let brush = output
19472            .semantics
19473            .iter()
19474            .find(|node| {
19475                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Brush tool")
19476            })
19477            .expect("brush tool button semantics should exist");
19478        let position = super::rect_center(brush.bounds);
19479
19480        runtime.handle_event(
19481            window_id,
19482            primary_pointer(PointerEventKind::Down, position, true),
19483        )?;
19484        runtime.handle_event(
19485            window_id,
19486            primary_pointer(PointerEventKind::Up, position, false),
19487        )?;
19488        runtime.handle_event(
19489            window_id,
19490            Event::Keyboard(KeyboardEvent::new("ArrowDown", KeyState::Pressed)),
19491        )?;
19492
19493        assert_eq!(
19494            chosen.borrow().last(),
19495            Some(&(1, "Eraser tool".to_string()))
19496        );
19497        let output = runtime.render(window_id)?;
19498        assert!(output.semantics.iter().any(|node| {
19499            node.role == SemanticsRole::Button
19500                && node.name.as_deref() == Some("Eraser tool")
19501                && node.state.selected
19502        }));
19503        Ok(())
19504    }
19505
19506    #[test]
19507    fn property_row_stacked_exposes_label_and_control_semantics() {
19508        let output = render(
19509            crate::SizedBox::new()
19510                .size(Size::new(320.0, 72.0))
19511                .with_child(
19512                    PropertyRow::new("Brush size", crate::NumberInput::new("Brush size"))
19513                        .control_width(120.0),
19514                ),
19515        );
19516
19517        let row = output
19518            .semantics
19519            .iter()
19520            .find(|node| {
19521                node.role == SemanticsRole::GenericContainer
19522                    && node.name.as_deref() == Some("Brush size")
19523            })
19524            .expect("property row semantics should exist");
19525        assert_eq!(row.bounds, Rect::new(0.0, 0.0, 320.0, 72.0));
19526
19527        let label = output
19528            .semantics
19529            .iter()
19530            .find(|node| {
19531                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Brush size")
19532            })
19533            .expect("property label semantics should exist");
19534        let control = output
19535            .semantics
19536            .iter()
19537            .find(|node| {
19538                node.role == SemanticsRole::SpinBox && node.name.as_deref() == Some("Brush size")
19539            })
19540            .expect("property control semantics should exist");
19541        assert_eq!(control.bounds.width(), 120.0);
19542        assert!(control.bounds.y() > label.bounds.y());
19543    }
19544
19545    #[test]
19546    fn property_row_inline_arranges_control_after_label() {
19547        let theme = DefaultTheme::default();
19548        let output = render(
19549            crate::SizedBox::new()
19550                .size(Size::new(320.0, 36.0))
19551                .with_child(
19552                    PropertyRow::new("Opacity", crate::Slider::new("Opacity"))
19553                        .layout(PropertyRowLayout::Inline)
19554                        .label_width(96.0),
19555                ),
19556        );
19557
19558        let label = output
19559            .semantics
19560            .iter()
19561            .find(|node| {
19562                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Opacity")
19563            })
19564            .expect("inline property label semantics should exist");
19565        let control = output
19566            .semantics
19567            .iter()
19568            .find(|node| {
19569                node.role == SemanticsRole::Slider && node.name.as_deref() == Some("Opacity")
19570            })
19571            .expect("inline property control semantics should exist");
19572        assert!(control.bounds.x() > label.bounds.max_x());
19573        let expected_width = 320.0 - 96.0 - theme.metrics.property_row_inline_gap;
19574        assert!((control.bounds.width() - expected_width).abs() < 0.01);
19575    }
19576
19577    #[test]
19578    fn property_row_inline_label_visual_center_matches_row_center() {
19579        let output = render(
19580            crate::SizedBox::new()
19581                .size(Size::new(320.0, 36.0))
19582                .with_child(
19583                    PropertyRow::new("Opacity", crate::Slider::new("Opacity"))
19584                        .layout(PropertyRowLayout::Inline)
19585                        .label_width(96.0),
19586                ),
19587        );
19588        let text = text_run_for(&output, "Opacity");
19589        let layout = TextSystem::new()
19590            .shape_text_run(&text, &FontRegistry::new())
19591            .expect("property row label should shape");
19592        let line = layout
19593            .lines()
19594            .first()
19595            .expect("property row label should contain one line");
19596        let actual_visual_center =
19597            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
19598        let row_center = output.frame.viewport.height * 0.5;
19599
19600        assert!((actual_visual_center - row_center).abs() < 0.75);
19601    }
19602
19603    #[test]
19604    fn property_row_numeric_control_aligns_value_to_control_edge() {
19605        let theme = DefaultTheme::default();
19606        let output = render(
19607            crate::SizedBox::new()
19608                .size(Size::new(320.0, 36.0))
19609                .with_child(
19610                    PropertyRow::new(
19611                        "Brush size",
19612                        crate::NumberInput::new("Brush size")
19613                            .precision(0)
19614                            .value(128.0),
19615                    )
19616                    .layout(PropertyRowLayout::Inline)
19617                    .label_width(96.0)
19618                    .control_width(120.0),
19619                ),
19620        );
19621        let value = text_run_for(&output, "128");
19622        let label = text_run_for(&output, "Brush size");
19623        let control = output
19624            .semantics
19625            .iter()
19626            .find(|node| {
19627                node.role == SemanticsRole::SpinBox && node.name.as_deref() == Some("Brush size")
19628            })
19629            .expect("number input semantics should exist");
19630        let expected_right = control.bounds.max_x()
19631            - theme.metrics.number_input_stepper_width
19632            - theme.metrics.text_input_padding.right;
19633
19634        assert!(
19635            value
19636                .style
19637                .features
19638                .iter()
19639                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
19640        );
19641        assert!((value.rect.max_x() - expected_right).abs() < 1.0);
19642        assert!(
19643            (text_run_visual_center(&value) - (control.bounds.y() + control.bounds.height() * 0.5))
19644                .abs()
19645                < 0.75,
19646            "property row numeric value should remain optically centered in the control"
19647        );
19648        assert!(
19649            (text_run_visual_center(&value) - text_run_visual_center(&label)).abs() < 0.75,
19650            "property row label and numeric value should share a visual baseline"
19651        );
19652    }
19653
19654    #[test]
19655    fn property_row_inline_label_preserves_tall_metrics_with_numeric_control() {
19656        let mut theme = DefaultTheme::default();
19657        theme.text.sm = ThemeTextToken {
19658            size: 28.0,
19659            line_height: 10.0,
19660        };
19661        theme.sync_derived_fields();
19662        theme.metrics.min_height = 56.0;
19663        let output = render(
19664            crate::SizedBox::new()
19665                .size(Size::new(380.0, 64.0))
19666                .with_child(
19667                    PropertyRow::new(
19668                        "Brush size",
19669                        crate::NumberInput::new("Brush size")
19670                            .theme(theme)
19671                            .precision(0)
19672                            .value(128.0),
19673                    )
19674                    .theme(theme)
19675                    .layout(PropertyRowLayout::Inline)
19676                    .label_width(132.0)
19677                    .control_width(150.0),
19678                ),
19679        );
19680        let label = text_run_for(&output, "Brush size");
19681        let label_layout = TextSystem::new()
19682            .shape_text_run(&label, &FontRegistry::new())
19683            .expect("property row label should shape");
19684        let value = text_run_for(&output, "128");
19685        let row_center = output.frame.viewport.height * 0.5;
19686        let control = output
19687            .semantics
19688            .iter()
19689            .find(|node| {
19690                node.role == SemanticsRole::SpinBox && node.name.as_deref() == Some("Brush size")
19691            })
19692            .expect("number input semantics should exist");
19693        let expected_right = control.bounds.max_x()
19694            - theme.metrics.number_input_stepper_width
19695            - theme.metrics.text_input_padding.right;
19696
19697        assert_text_run_uses_token(&label, theme.text.sm);
19698        assert!(label.rect.height() >= label_layout.measurement().height - 0.01);
19699        assert!(label.rect.height() > label.style.line_height);
19700        assert!((text_run_visual_center(&label) - row_center).abs() < 0.75);
19701        assert!((value.rect.max_x() - expected_right).abs() < 1.0);
19702        assert!(
19703            (text_run_visual_center(&value) - text_run_visual_center(&label)).abs() < 0.75,
19704            "property row label and numeric value should share a visual baseline for tall metrics"
19705        );
19706    }
19707
19708    #[test]
19709    fn property_row_label_id_is_javascript_safe() {
19710        let id = super::property_row_label_id(WidgetId::new(402)).get();
19711
19712        assert!(id < (1_u64 << 53));
19713    }
19714
19715    #[test]
19716    fn form_row_control_uses_full_available_width_by_default() {
19717        let theme = DefaultTheme::default();
19718        let width = 760.0;
19719        let output = render(
19720            crate::SizedBox::new()
19721                .size(Size::new(width, 36.0))
19722                .with_child(FormRow::new(
19723                    "Model",
19724                    crate::TextInput::new("provider-model"),
19725                )),
19726        );
19727
19728        let control = output
19729            .semantics
19730            .iter()
19731            .find(|node| {
19732                node.role == SemanticsRole::TextInput
19733                    && node.name.as_deref() == Some("provider-model")
19734            })
19735            .expect("form row control semantics should exist");
19736        let expected_width =
19737            width - theme.metrics.form_row_label_width - theme.metrics.form_row_gap;
19738        assert!(
19739            (control.bounds.width() - expected_width).abs() < 0.01,
19740            "form controls should use the card's available row width"
19741        );
19742        assert!((control.bounds.max_x() - width).abs() < 0.01);
19743    }
19744
19745    #[test]
19746    fn form_section_bounds_grouped_rows_and_exposes_semantics() {
19747        let output = render(
19748            crate::SizedBox::new()
19749                .size(Size::new(900.0, 180.0))
19750                .with_child(
19751                    FormSection::new(
19752                        "Providers",
19753                        FieldGroup::new()
19754                            .with_child(FormRow::new("API key", crate::Label::new("Configured")))
19755                            .with_child(FormRow::new(
19756                                "Default model",
19757                                crate::Label::new("Provider default"),
19758                            )),
19759                    )
19760                    .description("Credentials and model defaults"),
19761                ),
19762        );
19763
19764        let theme = DefaultTheme::default();
19765        assert!(
19766            solid_fill_colors(&output).contains(&theme.surfaces.panel),
19767            "form section card fill should use the surface panel token"
19768        );
19769
19770        let section = output
19771            .semantics
19772            .iter()
19773            .find(|node| {
19774                node.role == SemanticsRole::GenericContainer
19775                    && node.name.as_deref() == Some("Providers")
19776            })
19777            .expect("form section semantics should exist");
19778        let padding = theme.metrics.form_section_padding;
19779        assert!(
19780            section.bounds.width()
19781                <= theme.metrics.form_section_max_width + padding.left + padding.right
19782        );
19783        assert!(
19784            section.bounds.x() > 100.0,
19785            "wide parent should center a max-width form section"
19786        );
19787        assert_eq!(
19788            section.description.as_deref(),
19789            Some("Credentials and model defaults")
19790        );
19791        assert!(
19792            output
19793                .semantics
19794                .iter()
19795                .any(|node| node.role == SemanticsRole::Text
19796                    && node.name.as_deref() == Some("Default model"))
19797        );
19798    }
19799
19800    #[test]
19801    fn form_section_header_text_block_centers_against_tall_header_action() {
19802        let theme = DefaultTheme::default();
19803        let output = render(
19804            crate::SizedBox::new()
19805                .size(Size::new(420.0, 140.0))
19806                .with_child(
19807                    FormSection::new("Providers", crate::Label::new("Configured"))
19808                        .theme(theme)
19809                        .description("Credentials and defaults")
19810                        .header_action(
19811                            crate::SizedBox::new()
19812                                .size(Size::new(76.0, 52.0))
19813                                .with_child(crate::Label::new("Sync")),
19814                        ),
19815                ),
19816        );
19817        let section = output
19818            .semantics
19819            .iter()
19820            .find(|node| {
19821                node.role == SemanticsRole::GenericContainer
19822                    && node.name.as_deref() == Some("Providers")
19823            })
19824            .expect("form section semantics should exist");
19825
19826        let title = text_run_for(&output, "Providers");
19827        let title_layout = text_run_layout(&title);
19828        let title_line = title_layout
19829            .lines()
19830            .first()
19831            .expect("form section title should contain one line");
19832        let title_visual_center = title.rect.y()
19833            + title_line.baseline
19834            + optical_visual_center(title_layout.measurement());
19835
19836        let description = text_run_for(&output, "Credentials and defaults");
19837        let description_layout = text_run_layout(&description);
19838        let description_line = description_layout
19839            .lines()
19840            .first()
19841            .expect("form section description should contain one line");
19842        let description_visual_center = description.rect.y()
19843            + description_line.baseline
19844            + optical_visual_center(description_layout.measurement());
19845
19846        let metrics = theme.metrics;
19847        let content = super::inset_rect(section.bounds, metrics.form_section_padding);
19848        let header_gap = metrics.form_section_header_gap;
19849        let action_width = (76.0 + header_gap).min(content.width());
19850        let text_width = (content.width() - action_width).max(0.0);
19851        let title_height = title
19852            .style
19853            .line_height
19854            .max(title_layout.measurement().height);
19855        let description_height = description
19856            .style
19857            .line_height
19858            .max(description_layout.measurement().height);
19859        let text_block_height =
19860            title_height + metrics.form_section_description_gap + description_height;
19861        let header_height = text_block_height.max(52.0);
19862        let text_y = content.y() + ((header_height - text_block_height) * 0.5).max(0.0);
19863        let title_slot = Rect::new(content.x(), text_y, text_width, title_height);
19864        let description_slot = Rect::new(
19865            content.x(),
19866            title_slot.max_y() + metrics.form_section_description_gap,
19867            text_width,
19868            description_height,
19869        );
19870
19871        assert!((title_visual_center - super::rect_center(title_slot).y).abs() < 0.75);
19872        assert!((description_visual_center - super::rect_center(description_slot).y).abs() < 0.75);
19873    }
19874
19875    #[test]
19876    fn form_section_header_text_preserves_tall_measurements_in_compact_line_boxes() {
19877        let mut theme = DefaultTheme::default();
19878        theme.text.sm = ThemeTextToken {
19879            size: 30.0,
19880            line_height: 10.0,
19881        };
19882        theme.text.xs = ThemeTextToken {
19883            size: 28.0,
19884            line_height: 10.0,
19885        };
19886        theme.sync_derived_fields();
19887
19888        let output = render(
19889            crate::SizedBox::new()
19890                .size(Size::new(460.0, 190.0))
19891                .with_child(
19892                    FormSection::new("Providers", crate::Label::new("Configured"))
19893                        .theme(theme)
19894                        .description("Credentials and defaults")
19895                        .header_action(
19896                            crate::SizedBox::new()
19897                                .size(Size::new(76.0, 52.0))
19898                                .with_child(crate::Label::new("Sync")),
19899                        ),
19900                ),
19901        );
19902        let section = output
19903            .semantics
19904            .iter()
19905            .find(|node| {
19906                node.role == SemanticsRole::GenericContainer
19907                    && node.name.as_deref() == Some("Providers")
19908            })
19909            .expect("form section semantics should exist");
19910        let title = text_run_for(&output, "Providers");
19911        let title_layout = TextSystem::new()
19912            .shape_text_run(&title, &FontRegistry::new())
19913            .expect("form section title should shape");
19914        let description = text_run_for(&output, "Credentials and defaults");
19915        let description_layout = TextSystem::new()
19916            .shape_text_run(&description, &FontRegistry::new())
19917            .expect("form section description should shape");
19918        let metrics = theme.metrics;
19919        let content = super::inset_rect(section.bounds, metrics.form_section_padding);
19920        let action_width = (76.0 + metrics.form_section_header_gap).min(content.width());
19921        let text_width = (content.width() - action_width).max(0.0);
19922        let title_height = title
19923            .style
19924            .line_height
19925            .max(title_layout.measurement().height);
19926        let description_height = description
19927            .style
19928            .line_height
19929            .max(description_layout.measurement().height);
19930        let text_block_height =
19931            title_height + metrics.form_section_description_gap + description_height;
19932        let header_height = text_block_height.max(52.0);
19933        let text_y = content.y() + ((header_height - text_block_height) * 0.5).max(0.0);
19934        let title_slot = Rect::new(content.x(), text_y, text_width, title_height);
19935        let description_slot = Rect::new(
19936            content.x(),
19937            title_slot.max_y() + metrics.form_section_description_gap,
19938            text_width,
19939            description_height,
19940        );
19941
19942        assert_text_run_uses_token(&title, theme.text.sm);
19943        assert_text_run_uses_token(&description, theme.text.xs);
19944        assert!(title.rect.height() >= title_layout.measurement().height - 0.01);
19945        assert!(title.rect.height() > title.style.line_height);
19946        assert!(description.rect.height() >= description_layout.measurement().height - 0.01);
19947        assert!(description.rect.height() > description.style.line_height);
19948        assert!((text_run_visual_center(&title) - super::rect_center(title_slot).y).abs() < 0.75);
19949        assert!(
19950            (text_run_visual_center(&description) - super::rect_center(description_slot).y).abs()
19951                < 0.75
19952        );
19953    }
19954
19955    #[test]
19956    fn panel_section_exposes_group_title_and_child_semantics() {
19957        let output = render(
19958            crate::SizedBox::new()
19959                .size(Size::new(240.0, 92.0))
19960                .with_child(PanelSection::new("Brush", crate::Label::new("Opacity"))),
19961        );
19962
19963        let section = output
19964            .semantics
19965            .iter()
19966            .find(|node| {
19967                node.role == SemanticsRole::GenericContainer
19968                    && node.name.as_deref() == Some("Brush")
19969            })
19970            .expect("panel section group semantics should exist");
19971        let title = output
19972            .semantics
19973            .iter()
19974            .find(|node| {
19975                node.parent == Some(section.id)
19976                    && node.role == SemanticsRole::Text
19977                    && node.name.as_deref() == Some("Brush")
19978            })
19979            .expect("panel section title semantics should exist");
19980        let child = output
19981            .semantics
19982            .iter()
19983            .find(|node| {
19984                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Opacity")
19985            })
19986            .expect("panel section child semantics should exist");
19987
19988        assert!(child.bounds.y() > title.bounds.max_y());
19989    }
19990
19991    #[test]
19992    fn panel_section_header_action_is_arranged_after_title() {
19993        let output = render(
19994            crate::SizedBox::new()
19995                .size(Size::new(240.0, 92.0))
19996                .with_child(
19997                    PanelSection::new("Layers", crate::Label::new("Paint"))
19998                        .header_action(crate::IconButton::new(crate::IconGlyph::Add, "Add layer")),
19999                ),
20000        );
20001
20002        let section = output
20003            .semantics
20004            .iter()
20005            .find(|node| {
20006                node.role == SemanticsRole::GenericContainer
20007                    && node.name.as_deref() == Some("Layers")
20008            })
20009            .expect("panel section group semantics should exist");
20010        let title = output
20011            .semantics
20012            .iter()
20013            .find(|node| {
20014                node.parent == Some(section.id)
20015                    && node.role == SemanticsRole::Text
20016                    && node.name.as_deref() == Some("Layers")
20017            })
20018            .expect("panel section title semantics should exist");
20019        let action = output
20020            .semantics
20021            .iter()
20022            .find(|node| {
20023                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Add layer")
20024            })
20025            .expect("panel section header action semantics should exist");
20026        let child = output
20027            .semantics
20028            .iter()
20029            .find(|node| node.role == SemanticsRole::Text && node.name.as_deref() == Some("Paint"))
20030            .expect("panel section child semantics should exist");
20031
20032        assert!(action.bounds.x() > title.bounds.x());
20033        assert!(child.bounds.y() > action.bounds.max_y());
20034    }
20035
20036    #[test]
20037    fn panel_section_title_visual_center_matches_title_slot_center() {
20038        let output = render(
20039            crate::SizedBox::new()
20040                .size(Size::new(240.0, 92.0))
20041                .with_child(
20042                    PanelSection::new("Layers", crate::Label::new("Paint"))
20043                        .header_action(crate::IconButton::new(crate::IconGlyph::Add, "Add layer")),
20044                ),
20045        );
20046        let section = output
20047            .semantics
20048            .iter()
20049            .find(|node| {
20050                node.role == SemanticsRole::GenericContainer
20051                    && node.name.as_deref() == Some("Layers")
20052            })
20053            .expect("panel section group semantics should exist");
20054        let title_slot = output
20055            .semantics
20056            .iter()
20057            .find(|node| {
20058                node.parent == Some(section.id)
20059                    && node.role == SemanticsRole::Text
20060                    && node.name.as_deref() == Some("Layers")
20061            })
20062            .expect("panel section title semantics should exist")
20063            .bounds;
20064        let text = text_run_for(&output, "Layers");
20065        let layout = TextSystem::new()
20066            .shape_text_run(&text, &FontRegistry::new())
20067            .expect("panel section title should shape");
20068        let line = layout
20069            .lines()
20070            .first()
20071            .expect("panel section title should contain one line");
20072        let actual_visual_center =
20073            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
20074
20075        assert!((actual_visual_center - super::rect_center(title_slot).y).abs() < 0.75);
20076    }
20077
20078    #[test]
20079    fn panel_section_title_preserves_tall_measurement_and_header_centering() {
20080        let mut theme = DefaultTheme::default();
20081        theme.text.xs = ThemeTextToken {
20082            size: 30.0,
20083            line_height: 10.0,
20084        };
20085        theme.sync_derived_fields();
20086
20087        let output = render(
20088            crate::SizedBox::new()
20089                .size(Size::new(280.0, 120.0))
20090                .with_child(
20091                    PanelSection::new("Layers", crate::Label::new("Paint"))
20092                        .theme(theme)
20093                        .header_action(crate::IconButton::new(crate::IconGlyph::Add, "Add layer")),
20094                ),
20095        );
20096        let section = output
20097            .semantics
20098            .iter()
20099            .find(|node| {
20100                node.role == SemanticsRole::GenericContainer
20101                    && node.name.as_deref() == Some("Layers")
20102            })
20103            .expect("panel section group semantics should exist");
20104        let title_slot = output
20105            .semantics
20106            .iter()
20107            .find(|node| {
20108                node.parent == Some(section.id)
20109                    && node.role == SemanticsRole::Text
20110                    && node.name.as_deref() == Some("Layers")
20111            })
20112            .expect("panel section title semantics should exist")
20113            .bounds;
20114        let title = text_run_for(&output, "Layers");
20115        let layout = TextSystem::new()
20116            .shape_text_run(&title, &FontRegistry::new())
20117            .expect("panel section title should shape");
20118
20119        assert_text_run_uses_token(&title, theme.text.xs);
20120        assert!(title.rect.height() >= layout.measurement().height - 0.01);
20121        assert!(title.rect.height() > title.style.line_height);
20122        assert!((text_run_visual_center(&title) - super::rect_center(title_slot).y).abs() < 0.75);
20123    }
20124
20125    #[test]
20126    fn collapsible_panel_section_hides_collapsed_child_semantics() {
20127        let output = render(
20128            crate::SizedBox::new()
20129                .size(Size::new(240.0, 92.0))
20130                .with_child(
20131                    PanelSection::new("Advanced color", crate::Label::new("RGB sliders"))
20132                        .collapsible(true)
20133                        .collapsed(),
20134                ),
20135        );
20136
20137        let section = output
20138            .semantics
20139            .iter()
20140            .find(|node| {
20141                node.role == SemanticsRole::GenericContainer
20142                    && node.name.as_deref() == Some("Advanced color")
20143            })
20144            .expect("collapsible panel section semantics should exist");
20145        assert_eq!(section.state.expanded, Some(false));
20146        assert!(section.actions.contains(&SemanticsAction::Expand));
20147        assert!(
20148            !output
20149                .semantics
20150                .iter()
20151                .any(|node| node.role == SemanticsRole::Text
20152                    && node.name.as_deref() == Some("RGB sliders")),
20153            "collapsed section should not expose hidden child semantics"
20154        );
20155    }
20156
20157    #[test]
20158    fn collapsible_panel_section_pointer_toggle_exposes_child() -> sui_core::Result<()> {
20159        let (mut runtime, window_id) = build_runtime(
20160            crate::SizedBox::new()
20161                .size(Size::new(240.0, 120.0))
20162                .with_child(
20163                    PanelSection::new("Advanced color", crate::Label::new("RGB sliders"))
20164                        .collapsible(true)
20165                        .collapsed(),
20166                ),
20167        );
20168        let output = runtime.render(window_id)?;
20169        let section = output
20170            .semantics
20171            .iter()
20172            .find(|node| {
20173                node.role == SemanticsRole::GenericContainer
20174                    && node.name.as_deref() == Some("Advanced color")
20175            })
20176            .expect("collapsible panel section semantics should exist");
20177        let position = Point::new(section.bounds.x() + 20.0, section.bounds.y() + 8.0);
20178
20179        runtime.handle_event(
20180            window_id,
20181            primary_pointer(PointerEventKind::Move, position, false),
20182        )?;
20183        runtime.handle_event(
20184            window_id,
20185            primary_pointer(PointerEventKind::Down, position, true),
20186        )?;
20187        runtime.handle_event(
20188            window_id,
20189            primary_pointer(PointerEventKind::Up, position, false),
20190        )?;
20191
20192        let output = runtime.render(window_id)?;
20193        let section = output
20194            .semantics
20195            .iter()
20196            .find(|node| {
20197                node.role == SemanticsRole::GenericContainer
20198                    && node.name.as_deref() == Some("Advanced color")
20199            })
20200            .expect("collapsible panel section semantics should still exist");
20201        assert_eq!(section.state.expanded, Some(true));
20202        assert!(
20203            output
20204                .semantics
20205                .iter()
20206                .any(|node| node.role == SemanticsRole::Text
20207                    && node.name.as_deref() == Some("RGB sliders")),
20208            "expanded section should expose child semantics"
20209        );
20210
20211        Ok(())
20212    }
20213
20214    #[test]
20215    fn collapsible_panel_section_header_motion_uses_theme_motion() -> Result<(), String> {
20216        let theme = DefaultTheme::default();
20217        let hover_duration = theme.motion.hover_duration();
20218        let press_duration = theme.motion.press_duration();
20219        let expected_hover = theme
20220            .palette
20221            .accent
20222            .with_alpha((theme.interaction.hover_blend * 0.07).min(0.08));
20223        let expected_press = theme
20224            .palette
20225            .accent
20226            .with_alpha((theme.interaction.selected_blend * 0.48).min(0.14));
20227        let (mut runtime, window_id) = build_runtime(
20228            crate::SizedBox::new()
20229                .size(Size::new(240.0, 120.0))
20230                .with_child(
20231                    PanelSection::new("Advanced color", crate::Label::new("RGB sliders"))
20232                        .theme(theme)
20233                        .collapsible(true)
20234                        .collapsed(),
20235                ),
20236        );
20237        let output = runtime
20238            .render(window_id)
20239            .map_err(|error| error.to_string())?;
20240        let title = text_run_for(&output, "Advanced color");
20241        let position = super::rect_center(title.rect);
20242
20243        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
20244        move_event.pointer_id = 1;
20245        runtime
20246            .handle_event(window_id, Event::Pointer(move_event))
20247            .map_err(|error| error.to_string())?;
20248
20249        runtime.tick(hover_duration * 0.5);
20250        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20251        let mid_hover = runtime
20252            .render(window_id)
20253            .map_err(|error| error.to_string())?;
20254        assert!(
20255            !solid_fill_colors(&mid_hover).contains(&expected_hover),
20256            "panel header hover fill should not snap to the settled hover color"
20257        );
20258
20259        runtime.tick(hover_duration);
20260        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20261        let settled_hover = runtime
20262            .render(window_id)
20263            .map_err(|error| error.to_string())?;
20264        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
20265
20266        runtime
20267            .handle_event(
20268                window_id,
20269                primary_pointer(PointerEventKind::Down, position, true),
20270            )
20271            .map_err(|error| error.to_string())?;
20272
20273        runtime.tick(hover_duration + press_duration * 0.5);
20274        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20275        let mid_press = runtime
20276            .render(window_id)
20277            .map_err(|error| error.to_string())?;
20278        assert!(
20279            !solid_fill_colors(&mid_press).contains(&expected_press),
20280            "panel header press fill should not snap to the settled pressed color"
20281        );
20282
20283        runtime.tick(hover_duration + press_duration);
20284        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20285        let settled_press = runtime
20286            .render(window_id)
20287            .map_err(|error| error.to_string())?;
20288        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
20289
20290        Ok(())
20291    }
20292
20293    #[test]
20294    fn panel_section_title_id_is_javascript_safe() {
20295        let id = super::panel_section_title_id(WidgetId::new(402)).get();
20296
20297        assert!(id < (1_u64 << 53));
20298    }
20299
20300    #[test]
20301    fn dock_panel_exposes_title_and_arranges_child_below_header() {
20302        let output = render(
20303            crate::SizedBox::new()
20304                .size(Size::new(280.0, 160.0))
20305                .with_child(
20306                    DockPanel::new("Tool properties", crate::Label::new("Brush size"))
20307                        .name("Inspector")
20308                        .padding(sui_layout::Padding::all(8.0)),
20309                ),
20310        );
20311
20312        let panel = output
20313            .semantics
20314            .iter()
20315            .find(|node| {
20316                node.role == SemanticsRole::GenericContainer
20317                    && node.name.as_deref() == Some("Inspector")
20318            })
20319            .expect("dock panel semantics should exist");
20320        assert_eq!(panel.bounds, Rect::new(0.0, 0.0, 280.0, 160.0));
20321
20322        let title = output
20323            .semantics
20324            .iter()
20325            .find(|node| {
20326                node.parent == Some(panel.id)
20327                    && node.role == SemanticsRole::Text
20328                    && node.name.as_deref() == Some("Tool properties")
20329            })
20330            .expect("dock panel title semantics should exist");
20331        let child = output
20332            .semantics
20333            .iter()
20334            .find(|node| {
20335                node.role == SemanticsRole::Text && node.name.as_deref() == Some("Brush size")
20336            })
20337            .expect("dock panel child semantics should exist");
20338
20339        let theme = DefaultTheme::default();
20340        assert!(title.bounds.max_y() <= theme.metrics.dock_panel_header_height);
20341        assert!(
20342            child.bounds.y()
20343                >= theme.metrics.dock_panel_header_height + theme.metrics.dock_panel_padding.top
20344        );
20345    }
20346
20347    #[test]
20348    fn empty_state_exposes_content_and_action_semantics() {
20349        let theme = DefaultTheme::default();
20350        let output = render(
20351            crate::SizedBox::new()
20352                .size(Size::new(320.0, 220.0))
20353                .with_child(
20354                    EmptyState::new("Empty directory", "Nothing here yet.")
20355                        .theme(theme)
20356                        .icon(crate::IconGlyph::Folder)
20357                        .detail("No files matched the active filter.")
20358                        .action(crate::Button::new("Create file").theme(theme)),
20359                ),
20360        );
20361
20362        let state = output
20363            .semantics
20364            .iter()
20365            .find(|node| {
20366                node.role == SemanticsRole::GenericContainer
20367                    && node.name.as_deref() == Some("Empty directory")
20368            })
20369            .expect("empty-state semantics should exist");
20370        assert_eq!(
20371            state.description.as_deref(),
20372            Some("Nothing here yet. No files matched the active filter.")
20373        );
20374        assert!(output.semantics.iter().any(|node| {
20375            node.role == SemanticsRole::Button && node.name.as_deref() == Some("Create file")
20376        }));
20377        assert_eq!(
20378            text_run_for(&output, "Empty directory").style.color,
20379            theme.surfaces.text_muted
20380        );
20381        assert_eq!(
20382            text_run_for(&output, "Nothing here yet.").style.color,
20383            theme.surfaces.text_faint
20384        );
20385        assert_eq!(
20386            text_run_for(&output, "No files matched the active filter.")
20387                .style
20388                .color,
20389            theme.surfaces.text_muted
20390        );
20391        // The action reserves 18px above the geometric center. Each line is
20392        // then centered on its authored slot through the same optical-baseline
20393        // path used by buttons, inputs, tables, and other SUI controls.
20394        assert!((text_visual_center_for(&output, "Empty directory") - 96.0).abs() < 0.75);
20395        assert!((text_visual_center_for(&output, "Nothing here yet.") - 122.0).abs() < 0.75);
20396        assert!(
20397            (text_visual_center_for(&output, "No files matched the active filter.") - 140.0).abs()
20398                < 0.75
20399        );
20400    }
20401
20402    #[test]
20403    fn dock_panel_title_visual_center_matches_header_title_slot_center() {
20404        let output = render(
20405            crate::SizedBox::new()
20406                .size(Size::new(280.0, 160.0))
20407                .with_child(
20408                    DockPanel::new("Tool properties", crate::Label::new("Brush size"))
20409                        .name("Inspector")
20410                        .padding(sui_layout::Padding::all(8.0)),
20411                ),
20412        );
20413        let panel = output
20414            .semantics
20415            .iter()
20416            .find(|node| {
20417                node.role == SemanticsRole::GenericContainer
20418                    && node.name.as_deref() == Some("Inspector")
20419            })
20420            .expect("dock panel semantics should exist");
20421        let title_slot = output
20422            .semantics
20423            .iter()
20424            .find(|node| {
20425                node.parent == Some(panel.id)
20426                    && node.role == SemanticsRole::Text
20427                    && node.name.as_deref() == Some("Tool properties")
20428            })
20429            .expect("dock panel title semantics should exist")
20430            .bounds;
20431        let text = text_run_for(&output, "Tool properties");
20432        let layout = TextSystem::new()
20433            .shape_text_run(&text, &FontRegistry::new())
20434            .expect("dock panel title should shape");
20435        let line = layout
20436            .lines()
20437            .first()
20438            .expect("dock panel title should contain one line");
20439        let actual_visual_center =
20440            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
20441
20442        assert!((actual_visual_center - super::rect_center(title_slot).y).abs() < 0.75);
20443    }
20444
20445    #[test]
20446    fn dock_panel_title_preserves_tall_measurement_and_header_centering() {
20447        let mut theme = DefaultTheme::default();
20448        theme.text.sm = ThemeTextToken {
20449            size: 30.0,
20450            line_height: 10.0,
20451        };
20452        theme.sync_derived_fields();
20453        theme.metrics.dock_panel_header_height = 52.0;
20454
20455        let output = render(
20456            crate::SizedBox::new()
20457                .size(Size::new(300.0, 180.0))
20458                .with_child(
20459                    DockPanel::new("Tool properties", crate::Label::new("Brush size"))
20460                        .theme(theme)
20461                        .name("Inspector")
20462                        .padding(sui_layout::Padding::all(8.0)),
20463                ),
20464        );
20465        let panel = output
20466            .semantics
20467            .iter()
20468            .find(|node| {
20469                node.role == SemanticsRole::GenericContainer
20470                    && node.name.as_deref() == Some("Inspector")
20471            })
20472            .expect("dock panel semantics should exist");
20473        let title_slot = output
20474            .semantics
20475            .iter()
20476            .find(|node| {
20477                node.parent == Some(panel.id)
20478                    && node.role == SemanticsRole::Text
20479                    && node.name.as_deref() == Some("Tool properties")
20480            })
20481            .expect("dock panel title semantics should exist")
20482            .bounds;
20483        let title = text_run_for(&output, "Tool properties");
20484        let layout = TextSystem::new()
20485            .shape_text_run(&title, &FontRegistry::new())
20486            .expect("dock panel title should shape");
20487
20488        assert_text_run_uses_token(&title, theme.text.sm);
20489        assert!(title.rect.height() >= layout.measurement().height - 0.01);
20490        assert!(title.rect.height() > title.style.line_height);
20491        assert!((text_run_visual_center(&title) - super::rect_center(title_slot).y).abs() < 0.75);
20492    }
20493
20494    #[test]
20495    fn dock_panel_title_id_is_javascript_safe() {
20496        let id = super::dock_panel_title_id(WidgetId::new(402)).get();
20497
20498        assert!(id < (1_u64 << 53));
20499    }
20500
20501    #[test]
20502    fn status_bar_host_reserves_footer_height() {
20503        let output = render(
20504            crate::SizedBox::new()
20505                .size(Size::new(320.0, 160.0))
20506                .with_child(StatusBarHost::new(
20507                    crate::Label::new("Canvas content"),
20508                    StatusBar::new()
20509                        .name("Editor status")
20510                        .segment(StatusBarSegment::new("Ready").min_width(80.0)),
20511                )),
20512        );
20513
20514        let status = output
20515            .semantics
20516            .iter()
20517            .find(|node| {
20518                node.role == SemanticsRole::GenericContainer
20519                    && node.name.as_deref() == Some("Editor status")
20520            })
20521            .expect("status bar container semantics should exist");
20522
20523        let theme = DefaultTheme::default();
20524        assert_eq!(
20525            status.bounds,
20526            Rect::new(
20527                0.0,
20528                160.0 - theme.metrics.status_bar_height,
20529                320.0,
20530                theme.metrics.status_bar_height,
20531            )
20532        );
20533    }
20534
20535    #[test]
20536    fn status_bar_segment_ids_are_javascript_safe_and_distinct() {
20537        let parent = WidgetId::new(402);
20538        let ids = (0..6)
20539            .map(|index| super::status_bar_segment_id(parent, index).get())
20540            .collect::<Vec<_>>();
20541
20542        for id in &ids {
20543            assert!(*id < (1_u64 << 53));
20544        }
20545        for (left_index, left) in ids.iter().enumerate() {
20546            for right in ids.iter().skip(left_index + 1) {
20547                assert_ne!(left, right);
20548            }
20549        }
20550    }
20551
20552    fn text_run_from_shaped(
20553        output: &RenderOutput,
20554        run: &sui_text::ShapedText,
20555    ) -> Option<sui_text::TextRun> {
20556        run.resolve(output.frame.text_layout_registry.as_ref())
20557            .map(|layout| {
20558                let mut style = layout.style().clone();
20559                if let Some(color) = run.color_override {
20560                    style.color = color;
20561                }
20562                sui_text::TextRun {
20563                    rect: shaped_text_run_rect(run.origin, layout),
20564                    text: layout.text().to_string(),
20565                    style,
20566                }
20567            })
20568    }
20569
20570    fn shaped_text_run_rect(origin: Point, layout: &sui_text::TextLayout) -> Rect {
20571        let measurement = layout.measurement();
20572        let bounds = measurement.bounds;
20573        let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
20574            bounds.width()
20575        } else {
20576            measurement.width
20577        };
20578        Rect::new(
20579            origin.x + bounds.x(),
20580            origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
20581            width,
20582            layout.style().line_height.max(measurement.height),
20583        )
20584    }
20585
20586    fn first_text_run(output: &RenderOutput) -> sui_text::TextRun {
20587        output
20588            .frame
20589            .scene
20590            .commands()
20591            .iter()
20592            .find_map(|command| match command {
20593                sui_scene::SceneCommand::DrawText(text) => Some(text.clone()),
20594                sui_scene::SceneCommand::DrawShapedText(text) => text_run_from_shaped(output, text),
20595                _ => None,
20596            })
20597            .expect("text draw command present")
20598    }
20599
20600    fn text_run_for(output: &RenderOutput, text: &str) -> sui_text::TextRun {
20601        let mut found = None;
20602        output.frame.scene.visit_commands(&mut |command| {
20603            if found.is_some() {
20604                return;
20605            }
20606            found = match command {
20607                sui_scene::SceneCommand::DrawText(run) if run.text == text => Some(run.clone()),
20608                sui_scene::SceneCommand::DrawShapedText(run) => {
20609                    text_run_from_shaped(output, run).filter(|resolved| resolved.text == text)
20610                }
20611                _ => None,
20612            };
20613        });
20614        found.expect("text draw command present")
20615    }
20616
20617    fn text_layout_for(output: &RenderOutput, text: &str) -> sui_text::TextLayout {
20618        let mut found = None;
20619        output.frame.scene.visit_commands(&mut |command| {
20620            if found.is_some() {
20621                return;
20622            }
20623            if let sui_scene::SceneCommand::DrawShapedText(run) = command
20624                && let Some(layout) = run.resolve(output.frame.text_layout_registry.as_ref())
20625                && layout.text() == text
20626            {
20627                found = Some(layout.clone());
20628            }
20629        });
20630        found.expect("shaped text layout present")
20631    }
20632
20633    fn slow_normal_motion_theme() -> DefaultTheme {
20634        let mut theme = DefaultTheme::default();
20635        theme.motion.duration_fast = 0.0;
20636        theme.motion.duration_normal = 0.6;
20637        theme
20638    }
20639
20640    fn text_transform_dx_for(output: &RenderOutput, text: &str) -> Option<f32> {
20641        fn find_in_commands(
20642            output: &RenderOutput,
20643            text: &str,
20644            commands: &[SceneCommand],
20645            inherited_dx: f32,
20646            stack: &mut Vec<f32>,
20647        ) -> Option<f32> {
20648            let mut current_dx = inherited_dx;
20649            for command in commands {
20650                match command {
20651                    SceneCommand::PushTransform { transform } => {
20652                        stack.push(current_dx);
20653                        current_dx += transform.dx;
20654                    }
20655                    SceneCommand::PopTransform => {
20656                        current_dx = stack.pop().unwrap_or(inherited_dx);
20657                    }
20658                    SceneCommand::DrawText(run) if run.text == text => {
20659                        return Some(current_dx);
20660                    }
20661                    SceneCommand::DrawShapedText(run) => {
20662                        if run
20663                            .resolve(output.frame.text_layout_registry.as_ref())
20664                            .is_some_and(|layout| layout.text() == text)
20665                        {
20666                            return Some(current_dx);
20667                        }
20668                    }
20669                    SceneCommand::Layer(layer) => {
20670                        if let Some(dx) = find_in_commands(
20671                            output,
20672                            text,
20673                            layer.scene.commands(),
20674                            current_dx + layer.descriptor.properties.translation.x,
20675                            stack,
20676                        ) {
20677                            return Some(dx);
20678                        }
20679                    }
20680                    _ => {}
20681                }
20682            }
20683
20684            None
20685        }
20686
20687        find_in_commands(
20688            output,
20689            text,
20690            output.frame.scene.commands(),
20691            0.0,
20692            &mut Vec::new(),
20693        )
20694    }
20695
20696    fn clip_rect_for_text(output: &RenderOutput, text: &str) -> Rect {
20697        let mut stack = Vec::new();
20698        let mut found = None;
20699        output.frame.scene.visit_commands(&mut |command| {
20700            if found.is_some() {
20701                return;
20702            }
20703            match command {
20704                sui_scene::SceneCommand::PushClip { rect } => stack.push(*rect),
20705                sui_scene::SceneCommand::PopClip => {
20706                    stack.pop();
20707                }
20708                sui_scene::SceneCommand::DrawText(run) if run.text == text => {
20709                    found = stack.last().copied();
20710                }
20711                sui_scene::SceneCommand::DrawShapedText(run)
20712                    if run
20713                        .resolve(output.frame.text_layout_registry.as_ref())
20714                        .is_some_and(|layout| layout.text() == text) =>
20715                {
20716                    found = stack.last().copied();
20717                }
20718                _ => {}
20719            }
20720        });
20721        found.expect("text draw command should have an active clip")
20722    }
20723
20724    fn optical_visual_center(measurement: sui_text::TextMeasurement) -> f32 {
20725        let top = -measurement.cap_height.unwrap_or(measurement.ascent);
20726        let bottom = measurement.descent * 0.5;
20727        (top + bottom) * 0.5
20728    }
20729
20730    fn text_run_layout(run: &sui_text::TextRun) -> sui_text::TextLayout {
20731        TextSystem::new()
20732            .shape_text(
20733                run.text.clone(),
20734                Size::new(f32::INFINITY, run.rect.height().max(1.0)),
20735                run.style.clone(),
20736                &FontRegistry::new(),
20737            )
20738            .expect("text run should shape")
20739    }
20740
20741    fn text_run_visual_center(run: &sui_text::TextRun) -> f32 {
20742        let layout = text_run_layout(run);
20743        let line = layout.lines().first().expect("text run should have a line");
20744        run.rect.y() + line.baseline + optical_visual_center(layout.measurement())
20745    }
20746
20747    fn text_visual_center_for(output: &RenderOutput, text: &str) -> f32 {
20748        output
20749            .frame
20750            .scene
20751            .commands()
20752            .iter()
20753            .find_map(|command| match command {
20754                sui_scene::SceneCommand::DrawText(run) if run.text == text => {
20755                    Some(text_run_visual_center(run))
20756                }
20757                sui_scene::SceneCommand::DrawShapedText(run) => {
20758                    let layout = run.resolve(output.frame.text_layout_registry.as_ref())?;
20759                    if layout.text() != text {
20760                        return None;
20761                    }
20762                    let line = layout.lines().first().expect("text run should have a line");
20763                    Some(run.origin.y + line.baseline + optical_visual_center(layout.measurement()))
20764                }
20765                _ => None,
20766            })
20767            .expect("text draw command present")
20768    }
20769
20770    fn assert_text_run_uses_token(run: &sui_text::TextRun, token: ThemeTextToken) {
20771        assert!(
20772            (run.style.font_size - token.size).abs() < 0.001,
20773            "text '{}' used font size {}, expected token size {}",
20774            run.text,
20775            run.style.font_size,
20776            token.size
20777        );
20778        assert!(
20779            (run.style.line_height - token.line_height).abs() < 0.001,
20780            "text '{}' used line height {}, expected token line height {}",
20781            run.text,
20782            run.style.line_height,
20783            token.line_height
20784        );
20785    }
20786
20787    fn assert_focus_ring_uses_theme_motion<W>(root: W, position: Point) -> Result<(), String>
20788    where
20789        W: Widget + 'static,
20790    {
20791        let theme = DefaultTheme::default();
20792        let focus_duration = theme.motion.focus_duration();
20793        let (mut runtime, window_id) = build_runtime(root);
20794        let _ = runtime
20795            .render(window_id)
20796            .map_err(|error| error.to_string())?;
20797
20798        runtime
20799            .handle_event(
20800                window_id,
20801                primary_pointer(PointerEventKind::Down, position, true),
20802            )
20803            .map_err(|error| error.to_string())?;
20804        let _ = runtime
20805            .render(window_id)
20806            .map_err(|error| error.to_string())?;
20807
20808        runtime.tick(focus_duration * 0.5);
20809        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20810        let mid = runtime
20811            .render(window_id)
20812            .map_err(|error| error.to_string())?;
20813        assert!(
20814            !contains_approx_color(&solid_stroke_colors(&mid), theme.palette.focus_ring),
20815            "focus ring should not snap to the settled focus color"
20816        );
20817
20818        runtime.tick(focus_duration);
20819        assert_eq!(handle_ready_events(&mut runtime)?, 1);
20820        let settled = runtime
20821            .render(window_id)
20822            .map_err(|error| error.to_string())?;
20823        assert!(
20824            contains_approx_color(&solid_stroke_colors(&settled), theme.palette.focus_ring),
20825            "focus ring should settle to the theme focus color"
20826        );
20827
20828        Ok(())
20829    }
20830
20831    fn layer_descriptor_for(
20832        output: &RenderOutput,
20833        owner: WidgetId,
20834    ) -> Option<SceneLayerDescriptor> {
20835        let mut descriptor = None;
20836        output.frame.scene.visit_layers(&mut |layer| {
20837            if layer.widget_id() == owner {
20838                descriptor = Some(layer.descriptor.clone());
20839            }
20840        });
20841        descriptor
20842    }
20843
20844    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
20845        let mut event = PointerEvent::new(kind, position);
20846        event.pointer_id = 1;
20847        event.button = Some(PointerButton::Primary);
20848        event.buttons = if pressed {
20849            PointerButtons::new(1)
20850        } else {
20851            PointerButtons::NONE
20852        };
20853        Event::Pointer(event)
20854    }
20855
20856    fn handle_ready_events(runtime: &mut Runtime) -> Result<usize, String> {
20857        let ready = runtime.drain_ready_events();
20858        let count = ready.len();
20859        for (ready_window, event) in ready {
20860            runtime
20861                .handle_event(ready_window, event)
20862                .map_err(|error| error.to_string())?;
20863        }
20864        Ok(count)
20865    }
20866
20867    fn overlay_layer_descriptor(output: &RenderOutput) -> Option<SceneLayerDescriptor> {
20868        let mut descriptor = None;
20869        output.frame.scene.visit_layers(&mut |layer| {
20870            if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
20871                descriptor = Some(layer.descriptor.clone());
20872            }
20873        });
20874        descriptor
20875    }
20876
20877    fn overlay_layer_owner(output: &RenderOutput) -> Option<WidgetId> {
20878        let mut owner = None;
20879        output.frame.scene.visit_layers(&mut |layer| {
20880            if layer.descriptor.composition_mode == LayerCompositionMode::Overlay {
20881                owner = Some(layer.widget_id());
20882            }
20883        });
20884        owner
20885    }
20886
20887    fn solid_fill_colors(output: &RenderOutput) -> Vec<Color> {
20888        let mut colors = Vec::new();
20889        output
20890            .frame
20891            .scene
20892            .visit_commands(&mut |command| match command {
20893                SceneCommand::FillRect {
20894                    brush: Brush::Solid(color),
20895                    ..
20896                }
20897                | SceneCommand::FillPath {
20898                    brush: Brush::Solid(color),
20899                    ..
20900                } => colors.push(*color),
20901                _ => {}
20902            });
20903        colors
20904    }
20905
20906    fn solid_fill_rects_for_color(output: &RenderOutput, expected: Color) -> Vec<Rect> {
20907        let mut rects = Vec::new();
20908        output
20909            .frame
20910            .scene
20911            .visit_commands(&mut |command| match command {
20912                SceneCommand::FillRect {
20913                    rect,
20914                    brush: Brush::Solid(color),
20915                } if *color == expected => rects.push(*rect),
20916                _ => {}
20917            });
20918        rects
20919    }
20920
20921    fn solid_stroke_colors(output: &RenderOutput) -> Vec<Color> {
20922        let mut colors = Vec::new();
20923        output
20924            .frame
20925            .scene
20926            .visit_commands(&mut |command| match command {
20927                SceneCommand::StrokeRect {
20928                    brush: Brush::Solid(color),
20929                    ..
20930                }
20931                | SceneCommand::StrokePath {
20932                    brush: Brush::Solid(color),
20933                    ..
20934                } => colors.push(*color),
20935                _ => {}
20936            });
20937        colors
20938    }
20939
20940    fn contains_approx_color(colors: &[Color], expected: Color) -> bool {
20941        const CHANNEL_TOLERANCE: f32 = 1.0 / 255.0;
20942
20943        colors.iter().any(|color| {
20944            color.space == expected.space
20945                && (color.red - expected.red).abs() <= CHANNEL_TOLERANCE
20946                && (color.green - expected.green).abs() <= CHANNEL_TOLERANCE
20947                && (color.blue - expected.blue).abs() <= CHANNEL_TOLERANCE
20948                && (color.alpha - expected.alpha).abs() <= CHANNEL_TOLERANCE
20949        })
20950    }
20951
20952    fn non_hit_test_layer_descriptors(output: &RenderOutput) -> Vec<SceneLayerDescriptor> {
20953        let mut descriptors = Vec::new();
20954        output.frame.scene.visit_layers(&mut |layer| {
20955            if !layer.descriptor.hit_test {
20956                descriptors.push(layer.descriptor.clone());
20957            }
20958        });
20959        descriptors
20960    }
20961
20962    fn non_hit_test_layer_owners(output: &RenderOutput) -> Vec<WidgetId> {
20963        let mut owners = Vec::new();
20964        output.frame.scene.visit_layers(&mut |layer| {
20965            if !layer.descriptor.hit_test {
20966                owners.push(layer.widget_id());
20967            }
20968        });
20969        owners
20970    }
20971
20972    #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
20973    struct PanelCounters {
20974        measure: usize,
20975        arrange: usize,
20976        paint: usize,
20977        semantics: usize,
20978    }
20979
20980    struct SpyPanel {
20981        name: &'static str,
20982        counters: Rc<RefCell<PanelCounters>>,
20983    }
20984
20985    impl SpyPanel {
20986        fn new(name: &'static str, counters: Rc<RefCell<PanelCounters>>) -> Self {
20987            Self { name, counters }
20988        }
20989    }
20990
20991    impl Widget for SpyPanel {
20992        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
20993            self.counters.borrow_mut().measure += 1;
20994            constraints.clamp(Size::new(180.0, 72.0))
20995        }
20996
20997        fn arrange(&mut self, _ctx: &mut ArrangeCtx, _bounds: sui_core::Rect) {
20998            self.counters.borrow_mut().arrange += 1;
20999        }
21000
21001        fn paint(&self, ctx: &mut PaintCtx) {
21002            self.counters.borrow_mut().paint += 1;
21003            ctx.fill_bounds(Color::rgba(0.20, 0.28, 0.38, 1.0));
21004        }
21005
21006        fn semantics(&self, ctx: &mut SemanticsCtx) {
21007            self.counters.borrow_mut().semantics += 1;
21008            let mut node = SemanticsNode::new(
21009                ctx.widget_id(),
21010                SemanticsRole::GenericContainer,
21011                ctx.bounds(),
21012            );
21013            node.name = Some(self.name.to_string());
21014            ctx.push(node);
21015        }
21016    }
21017
21018    #[test]
21019    fn tab_bar_exposes_selected_value() {
21020        let output = render(
21021            TabBar::new("Main tabs")
21022                .tabs(["Design", "Inspect", "Export"])
21023                .selected(1),
21024        );
21025
21026        let tabs = output
21027            .semantics
21028            .into_iter()
21029            .find(|node| node.role == SemanticsRole::TabBar)
21030            .expect("tab bar semantics node present");
21031        assert_eq!(
21032            tabs.value,
21033            Some(SemanticsValue::Text("Inspect".to_string()))
21034        );
21035    }
21036
21037    #[test]
21038    fn navigation_tab_bar_uses_flat_strip_and_accent_underline() {
21039        let mut theme = DefaultTheme::default();
21040        theme.interaction.tab_selected_blend = 0.31;
21041        let selected_fill = super::mix_color(
21042            theme.palette.surface_raised,
21043            theme.palette.accent,
21044            theme.interaction.tab_selected_blend,
21045        );
21046
21047        let tab_bar = render_isolated(
21048            TabBar::new("Main tabs")
21049                .theme(theme)
21050                .tabs(["Design", "Inspect"])
21051                .selected(1),
21052        );
21053        let tab_bar_fills = solid_fill_colors(&tab_bar);
21054        assert!(tab_bar_fills.contains(&theme.palette.control));
21055        assert!(tab_bar_fills.contains(&theme.palette.accent));
21056        assert!(
21057            !tab_bar_fills.contains(&selected_fill),
21058            "selected navigation tabs should not paint a raised selection tile"
21059        );
21060        let mut accent_bounds = Vec::new();
21061        tab_bar
21062            .frame
21063            .scene
21064            .visit_commands(&mut |command| match command {
21065                SceneCommand::FillRect {
21066                    rect,
21067                    brush: Brush::Solid(color),
21068                } if *color == theme.palette.accent => accent_bounds.push(*rect),
21069                SceneCommand::FillPath {
21070                    path,
21071                    brush: Brush::Solid(color),
21072                } if *color == theme.palette.accent => accent_bounds.push(path.bounds()),
21073                _ => {}
21074            });
21075        assert_eq!(
21076            accent_bounds.len(),
21077            1,
21078            "navigation tab bars should paint exactly one accent underline"
21079        );
21080        let underline = accent_bounds[0];
21081        assert!((underline.height() - theme.interaction.active_indicator_thickness).abs() < 0.01);
21082        assert!((underline.max_y() - tab_bar.frame.viewport.height).abs() < 0.01);
21083        assert!(
21084            !solid_stroke_colors(&tab_bar).contains(&theme.palette.border_focus),
21085            "selected tab bar chrome should not use the focus border color"
21086        );
21087        assert!(
21088            !solid_stroke_colors(&tab_bar).contains(&theme.palette.focus_ring),
21089            "unfocused selected tab bar chrome should not paint a focus ring"
21090        );
21091
21092        // Content-bearing `Tabs` keeps its existing selected-panel treatment;
21093        // this test scopes the flat navigation grammar specifically to TabBar.
21094        let tabs = render_isolated(
21095            Tabs::new("Main tabs")
21096                .theme(theme)
21097                .selected(1)
21098                .tab("Design", crate::Label::new("Design"))
21099                .tab("Inspect", crate::Label::new("Inspect")),
21100        );
21101        assert!(solid_fill_colors(&tabs).contains(&selected_fill));
21102        assert!(
21103            !solid_stroke_colors(&tabs).contains(&theme.palette.border_focus),
21104            "selected tabs chrome should not use the focus border color"
21105        );
21106        assert!(
21107            !solid_stroke_colors(&tabs).contains(&theme.palette.focus_ring),
21108            "unfocused selected tabs chrome should not paint a focus ring"
21109        );
21110    }
21111
21112    #[test]
21113    fn tab_widgets_focus_highlights_selected_tab_button() -> Result<(), String> {
21114        let theme = DefaultTheme::default();
21115        let focus_duration = theme.motion.focus_duration();
21116        let tab_bar_point = Point::new(
21117            theme.metrics.tab_min_width + theme.metrics.tab_gap + 8.0,
21118            18.0,
21119        );
21120        let (mut tab_bar_runtime, tab_bar_window) = build_runtime(
21121            TabBar::new("Main tabs")
21122                .theme(theme)
21123                .tabs(["Design", "Inspect"])
21124                .selected(1),
21125        );
21126        let _ = tab_bar_runtime
21127            .render(tab_bar_window)
21128            .map_err(|error| error.to_string())?;
21129        tab_bar_runtime
21130            .handle_event(
21131                tab_bar_window,
21132                primary_pointer(PointerEventKind::Down, tab_bar_point, true),
21133            )
21134            .map_err(|error| error.to_string())?;
21135        tab_bar_runtime.tick(focus_duration + 0.01);
21136        assert!(handle_ready_events(&mut tab_bar_runtime)? >= 1);
21137        let tab_bar_focused = tab_bar_runtime
21138            .render(tab_bar_window)
21139            .map_err(|error| error.to_string())?;
21140        let tab_bar_strokes = solid_stroke_colors(&tab_bar_focused);
21141        assert!(
21142            contains_approx_color(&tab_bar_strokes, theme.palette.focus_ring),
21143            "focused selected tab button should paint a focus ring; strokes={tab_bar_strokes:?}"
21144        );
21145        assert!(
21146            !contains_approx_color(&tab_bar_strokes, theme.palette.border_focus),
21147            "focused tab bar should keep neutral selected strokes; strokes={tab_bar_strokes:?}"
21148        );
21149
21150        let tabs_point = Point::new(
21151            theme.metrics.tab_min_width + theme.metrics.tab_gap + 8.0,
21152            18.0,
21153        );
21154        let (mut tabs_runtime, tabs_window) = build_runtime(
21155            crate::SizedBox::new()
21156                .size(Size::new(260.0, 120.0))
21157                .with_child(
21158                    Tabs::new("Main tabs")
21159                        .theme(theme)
21160                        .selected(1)
21161                        .tab("Design", crate::Label::new("Design"))
21162                        .tab("Inspect", crate::Label::new("Inspect")),
21163                ),
21164        );
21165        let _ = tabs_runtime
21166            .render(tabs_window)
21167            .map_err(|error| error.to_string())?;
21168        tabs_runtime
21169            .handle_event(
21170                tabs_window,
21171                primary_pointer(PointerEventKind::Down, tabs_point, true),
21172            )
21173            .map_err(|error| error.to_string())?;
21174        tabs_runtime.tick(focus_duration + 0.01);
21175        assert!(handle_ready_events(&mut tabs_runtime)? >= 1);
21176        let tabs_focused = tabs_runtime
21177            .render(tabs_window)
21178            .map_err(|error| error.to_string())?;
21179        let tabs_strokes = solid_stroke_colors(&tabs_focused);
21180        assert!(
21181            contains_approx_color(&tabs_strokes, theme.palette.focus_ring),
21182            "focused selected tab button should paint a focus ring; strokes={tabs_strokes:?}"
21183        );
21184        assert!(
21185            !contains_approx_color(&tabs_strokes, theme.palette.border_focus),
21186            "focused tabs should keep neutral selected strokes; strokes={tabs_strokes:?}"
21187        );
21188
21189        Ok(())
21190    }
21191
21192    #[test]
21193    fn selected_tab_labels_preserve_body_text_metrics() {
21194        let mut theme = DefaultTheme::default();
21195        theme.text.sm = ThemeTextToken {
21196            size: 15.5,
21197            line_height: 22.0,
21198        };
21199        theme.sync_derived_fields();
21200
21201        let tab_bar = render_isolated(
21202            TabBar::new("Main tabs")
21203                .theme(theme)
21204                .tabs(["Design", "Inspect"])
21205                .selected(1),
21206        );
21207        let tab_bar_label = text_run_for(&tab_bar, "Inspect");
21208        assert_text_run_uses_token(&tab_bar_label, theme.text.sm);
21209        assert_eq!(tab_bar_label.style.color, theme.palette.text);
21210        assert!(
21211            (text_run_visual_center(&tab_bar_label) - (tab_bar.frame.viewport.height * 0.5)).abs()
21212                < 0.75
21213        );
21214
21215        let tabs = render(
21216            Tabs::new("Main tabs")
21217                .theme(theme)
21218                .selected(1)
21219                .tab("Design", crate::Label::new("Design"))
21220                .tab("Inspect", crate::Label::new("Inspect")),
21221        );
21222        let tabs_label = text_run_for(&tabs, "Inspect");
21223        assert_text_run_uses_token(&tabs_label, theme.text.sm);
21224        assert_eq!(tabs_label.style.color, theme.palette.text);
21225        assert!(
21226            (text_run_visual_center(&tabs_label) - (theme.metrics.tab_height * 0.5)).abs() < 0.75
21227        );
21228    }
21229
21230    #[test]
21231    fn selected_tab_labels_preserve_tall_measurements_and_exact_centering() {
21232        let mut theme = DefaultTheme::default();
21233        theme.text.sm = ThemeTextToken {
21234            size: 28.0,
21235            line_height: 12.0,
21236        };
21237        theme.sync_derived_fields();
21238        theme.metrics.tab_height = 48.0;
21239
21240        let tab_bar = render_isolated(
21241            TabBar::new("Main tabs")
21242                .theme(theme)
21243                .tabs(["Design", "Inspect"])
21244                .selected(1),
21245        );
21246        let tab_bar_label = text_run_for(&tab_bar, "Inspect");
21247        let tab_bar_layout = TextSystem::new()
21248            .shape_text_run(&tab_bar_label, &FontRegistry::new())
21249            .expect("selected tab bar label should shape");
21250
21251        assert_text_run_uses_token(&tab_bar_label, theme.text.sm);
21252        assert!(tab_bar_label.rect.height() >= tab_bar_layout.measurement().height - 0.01);
21253        assert!(tab_bar_label.rect.height() > tab_bar_label.style.line_height);
21254        assert!(
21255            (text_visual_center_for(&tab_bar, "Inspect") - (tab_bar.frame.viewport.height * 0.5))
21256                .abs()
21257                < 0.75
21258        );
21259
21260        let tabs = render_isolated(
21261            Tabs::new("Main tabs")
21262                .theme(theme)
21263                .selected(1)
21264                .tab("Design", crate::Label::new("Design panel"))
21265                .tab("Inspect", crate::Label::new("Selected panel")),
21266        );
21267        let tabs_label = text_run_for(&tabs, "Inspect");
21268        let tabs_layout = TextSystem::new()
21269            .shape_text_run(&tabs_label, &FontRegistry::new())
21270            .expect("selected tabs label should shape");
21271
21272        assert_text_run_uses_token(&tabs_label, theme.text.sm);
21273        assert!(tabs_label.rect.height() >= tabs_layout.measurement().height - 0.01);
21274        assert!(tabs_label.rect.height() > tabs_label.style.line_height);
21275        assert!(
21276            (text_visual_center_for(&tabs, "Inspect") - (theme.metrics.tab_height * 0.5)).abs()
21277                < 0.75
21278        );
21279    }
21280
21281    #[test]
21282    fn tab_widgets_share_pressed_tab_border() -> Result<(), String> {
21283        let theme = DefaultTheme::default();
21284
21285        let (mut runtime, window_id) = build_runtime(
21286            TabBar::new("Main tabs")
21287                .theme(theme)
21288                .tabs(["Design", "Inspect"]),
21289        );
21290        let initial_tab_bar = runtime
21291            .render(window_id)
21292            .map_err(|error| error.to_string())?;
21293        let press_point = super::rect_center(text_run_for(&initial_tab_bar, "Inspect").rect);
21294        runtime
21295            .handle_event(
21296                window_id,
21297                primary_pointer(PointerEventKind::Down, press_point, true),
21298            )
21299            .map_err(|error| error.to_string())?;
21300        let tab_bar = runtime
21301            .render(window_id)
21302            .map_err(|error| error.to_string())?;
21303        assert!(contains_approx_color(
21304            &solid_stroke_colors(&tab_bar),
21305            theme.palette.border_hover,
21306        ));
21307
21308        let (mut runtime, window_id) = build_runtime(
21309            Tabs::new("Main tabs")
21310                .theme(theme)
21311                .tab("Design", crate::Label::new("Design"))
21312                .tab("Inspect", crate::Label::new("Inspect")),
21313        );
21314        let initial_tabs = runtime
21315            .render(window_id)
21316            .map_err(|error| error.to_string())?;
21317        let press_point = super::rect_center(text_run_for(&initial_tabs, "Inspect").rect);
21318        runtime
21319            .handle_event(
21320                window_id,
21321                primary_pointer(PointerEventKind::Down, press_point, true),
21322            )
21323            .map_err(|error| error.to_string())?;
21324        let tabs = runtime
21325            .render(window_id)
21326            .map_err(|error| error.to_string())?;
21327        assert!(contains_approx_color(
21328            &solid_stroke_colors(&tabs),
21329            theme.palette.border_hover,
21330        ));
21331
21332        Ok(())
21333    }
21334
21335    #[test]
21336    fn tab_hover_and_press_chrome_use_theme_motion() -> Result<(), String> {
21337        let theme = DefaultTheme::default();
21338        let hover_duration = theme.motion.hover_duration();
21339        let press_duration = theme.motion.press_duration();
21340        let expected_hover = super::mix_color(
21341            theme.palette.control,
21342            theme.palette.control_hover,
21343            theme.interaction.hover_blend,
21344        );
21345        let expected_press = super::mix_color(
21346            expected_hover,
21347            theme.palette.control_active,
21348            theme.interaction.pressed_blend,
21349        );
21350
21351        fn assert_tab_header_motion<W>(
21352            root: W,
21353            hover_duration: f64,
21354            press_duration: f64,
21355            expected_hover: Color,
21356            expected_press: Color,
21357        ) -> Result<(), String>
21358        where
21359            W: Widget + 'static,
21360        {
21361            let (mut runtime, window_id) = build_runtime(root);
21362            let initial = runtime
21363                .render(window_id)
21364                .map_err(|error| error.to_string())?;
21365            let second_tab_point = super::rect_center(text_run_for(&initial, "Inspect").rect);
21366
21367            let mut move_event = PointerEvent::new(PointerEventKind::Move, second_tab_point);
21368            move_event.pointer_id = 1;
21369            runtime
21370                .handle_event(window_id, Event::Pointer(move_event))
21371                .map_err(|error| error.to_string())?;
21372
21373            runtime.tick(hover_duration * 0.5);
21374            assert_eq!(handle_ready_events(&mut runtime)?, 1);
21375            let mid_hover = runtime
21376                .render(window_id)
21377                .map_err(|error| error.to_string())?;
21378            assert!(
21379                !solid_fill_colors(&mid_hover).contains(&expected_hover),
21380                "tab hover fill should not snap to the settled hover color"
21381            );
21382
21383            runtime.tick(hover_duration);
21384            assert_eq!(handle_ready_events(&mut runtime)?, 1);
21385            let settled_hover = runtime
21386                .render(window_id)
21387                .map_err(|error| error.to_string())?;
21388            assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
21389
21390            runtime
21391                .handle_event(
21392                    window_id,
21393                    primary_pointer(PointerEventKind::Down, second_tab_point, true),
21394                )
21395                .map_err(|error| error.to_string())?;
21396
21397            runtime.tick(hover_duration + press_duration * 0.5);
21398            assert_eq!(handle_ready_events(&mut runtime)?, 1);
21399            let mid_press = runtime
21400                .render(window_id)
21401                .map_err(|error| error.to_string())?;
21402            assert!(
21403                !solid_fill_colors(&mid_press).contains(&expected_press),
21404                "tab press fill should not snap to the settled pressed color"
21405            );
21406
21407            runtime.tick(hover_duration + press_duration);
21408            assert_eq!(handle_ready_events(&mut runtime)?, 1);
21409            let settled_press = runtime
21410                .render(window_id)
21411                .map_err(|error| error.to_string())?;
21412            assert!(solid_fill_colors(&settled_press).contains(&expected_press));
21413
21414            Ok(())
21415        }
21416
21417        assert_tab_header_motion(
21418            TabBar::new("Main tabs")
21419                .theme(theme)
21420                .tabs(["Design", "Inspect"]),
21421            hover_duration,
21422            press_duration,
21423            expected_hover,
21424            expected_press,
21425        )?;
21426        assert_tab_header_motion(
21427            Tabs::new("Main tabs")
21428                .theme(theme)
21429                .tab("Design", crate::Label::new("Design"))
21430                .tab("Inspect", crate::Label::new("Inspect")),
21431            hover_duration,
21432            press_duration,
21433            expected_hover,
21434            expected_press,
21435        )?;
21436
21437        Ok(())
21438    }
21439
21440    #[test]
21441    fn tab_switch_animation_uses_theme_motion() -> Result<(), String> {
21442        let mut theme = DefaultTheme::default();
21443        theme.motion.duration_fast = 0.6;
21444        theme.motion.duration_normal = 0.0;
21445        let switch_duration = theme.motion.tab_switch_duration();
21446
21447        assert_keyboard_tab_switch_uses_duration(
21448            TabBar::new("Main tabs")
21449                .theme(theme)
21450                .tabs(["Design", "Inspect"]),
21451            SemanticsRole::TabBar,
21452            switch_duration,
21453        )?;
21454        let selected = Rc::new(RefCell::new(0_usize));
21455        let selected_reader = Rc::clone(&selected);
21456        let selected_writer = Rc::clone(&selected);
21457        assert_keyboard_tab_switch_uses_duration(
21458            TabBar::new("Main tabs")
21459                .theme(theme)
21460                .tabs(["Design", "Inspect"])
21461                .selected_when(move || Some(*selected_reader.borrow()))
21462                .on_change(move |index, _| *selected_writer.borrow_mut() = index),
21463            SemanticsRole::TabBar,
21464            switch_duration,
21465        )?;
21466        assert_keyboard_tab_switch_uses_duration(
21467            BrowserTabBar::new("Open tabs")
21468                .theme(theme)
21469                .tabs(["Design", "Inspect"]),
21470            SemanticsRole::TabBar,
21471            switch_duration,
21472        )?;
21473        assert_keyboard_tab_switch_uses_duration(
21474            Tabs::new("Main tabs")
21475                .theme(theme)
21476                .tab("Design", crate::Label::new("Design panel"))
21477                .tab("Inspect", crate::Label::new("Inspect panel")),
21478            SemanticsRole::Tabs,
21479            switch_duration,
21480        )?;
21481
21482        Ok(())
21483    }
21484
21485    #[test]
21486    fn tab_bar_external_selected_state_animates_without_rebuild() -> Result<(), String> {
21487        let mut theme = DefaultTheme::default();
21488        theme.motion.duration_fast = 0.6;
21489        theme.motion.duration_normal = 0.0;
21490        let switch_duration = theme.motion.tab_switch_duration();
21491        let selected = Rc::new(RefCell::new(0_usize));
21492        let selected_reader = Rc::clone(&selected);
21493        let (mut runtime, window_id) = build_runtime(
21494            TabBar::new("Main tabs")
21495                .theme(theme)
21496                .tabs(["Design", "Inspect"])
21497                .selected_when(move || Some(*selected_reader.borrow())),
21498        );
21499
21500        runtime
21501            .render(window_id)
21502            .map_err(|error| error.to_string())?;
21503        *selected.borrow_mut() = 1;
21504        runtime
21505            .handle_event(window_id, Event::Window(WindowEvent::RedrawRequested))
21506            .map_err(|error| error.to_string())?;
21507
21508        runtime.tick(switch_duration * 0.5);
21509        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21510        assert!(
21511            runtime
21512                .next_wakeup_time(window_id)
21513                .map_err(|error| error.to_string())?
21514                .is_some(),
21515            "externally selected tab switch should still be animating at half duration"
21516        );
21517
21518        runtime.tick(switch_duration);
21519        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21520        let output = runtime
21521            .render(window_id)
21522            .map_err(|error| error.to_string())?;
21523        let tabs = output
21524            .semantics
21525            .iter()
21526            .find(|node| node.role == SemanticsRole::TabBar)
21527            .expect("tab semantics present");
21528        assert_eq!(
21529            tabs.value,
21530            Some(SemanticsValue::Text("Inspect".to_string()))
21531        );
21532
21533        Ok(())
21534    }
21535
21536    #[test]
21537    fn tab_bar_observable_selection_animates_without_redraw_polling() -> Result<(), String> {
21538        let mut theme = DefaultTheme::default();
21539        theme.motion.duration_fast = 0.6;
21540        theme.motion.duration_normal = 0.0;
21541        let switch_duration = theme.motion.tab_switch_duration();
21542        let selected = Signal::named("active_tab", Some(0_usize));
21543        let (mut runtime, window_id) = build_runtime(
21544            TabBar::new("Main tabs")
21545                .theme(theme)
21546                .tabs(["Design", "Inspect"])
21547                .selected_from(selected.clone()),
21548        );
21549
21550        runtime
21551            .render(window_id)
21552            .map_err(|error| error.to_string())?;
21553        assert!(selected.set(Some(1)));
21554        let changed = runtime
21555            .render(window_id)
21556            .map_err(|error| error.to_string())?;
21557        assert!(
21558            changed
21559                .diagnostics
21560                .reactive_invalidations
21561                .iter()
21562                .any(|sample| sample.source_name == "active_tab")
21563        );
21564
21565        runtime.tick(switch_duration * 0.5);
21566        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21567        assert!(
21568            runtime
21569                .next_wakeup_time(window_id)
21570                .map_err(|error| error.to_string())?
21571                .is_some(),
21572            "observable tab selection should retain its in-flight animation"
21573        );
21574
21575        runtime.tick(switch_duration);
21576        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21577        let output = runtime
21578            .render(window_id)
21579            .map_err(|error| error.to_string())?;
21580        let tabs = output
21581            .semantics
21582            .iter()
21583            .find(|node| node.role == SemanticsRole::TabBar)
21584            .expect("tab semantics present");
21585        assert_eq!(
21586            tabs.value,
21587            Some(SemanticsValue::Text("Inspect".to_string()))
21588        );
21589        Ok(())
21590    }
21591
21592    #[test]
21593    fn browser_tab_bar_semantics_ids_are_javascript_safe_and_distinct() {
21594        let parent = WidgetId::new(17);
21595        let mut ids = BTreeSet::new();
21596        for tab_index in 0..13 {
21597            for id in [
21598                super::browser_tab_semantics_id(parent, tab_index).get(),
21599                super::browser_tab_close_semantics_id(parent, tab_index).get(),
21600            ] {
21601                assert!(id < (1_u64 << 53), "{id} should be JS-safe");
21602                assert!(ids.insert(id), "{id} should be unique");
21603            }
21604        }
21605    }
21606
21607    fn assert_keyboard_tab_switch_uses_duration<W>(
21608        widget: W,
21609        role: SemanticsRole,
21610        switch_duration: f64,
21611    ) -> Result<(), String>
21612    where
21613        W: Widget + 'static,
21614    {
21615        let (mut runtime, window_id) = build_runtime(widget);
21616
21617        runtime
21618            .render(window_id)
21619            .map_err(|error| error.to_string())?;
21620        runtime
21621            .handle_event(
21622                window_id,
21623                Event::Keyboard(KeyboardEvent::new("Tab", KeyState::Pressed)),
21624            )
21625            .map_err(|error| error.to_string())?;
21626        runtime.tick(0.0);
21627        let _ = handle_ready_events(&mut runtime)?;
21628        assert!(
21629            runtime
21630                .focused_widget(window_id)
21631                .map_err(|error| error.to_string())?
21632                .is_some(),
21633            "tab widget should receive keyboard focus before arrow-key switching"
21634        );
21635
21636        runtime
21637            .handle_event(
21638                window_id,
21639                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
21640            )
21641            .map_err(|error| error.to_string())?;
21642
21643        runtime.tick(switch_duration * 0.5);
21644        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21645        assert!(
21646            runtime
21647                .next_wakeup_time(window_id)
21648                .map_err(|error| error.to_string())?
21649                .is_some(),
21650            "tab switch should still be animating at half of the custom theme duration"
21651        );
21652
21653        runtime.tick(switch_duration);
21654        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21655        let output = runtime
21656            .render(window_id)
21657            .map_err(|error| error.to_string())?;
21658        let tabs = output
21659            .semantics
21660            .iter()
21661            .find(|node| node.role == role)
21662            .expect("tab semantics present");
21663        assert_eq!(
21664            tabs.value,
21665            Some(SemanticsValue::Text("Inspect".to_string()))
21666        );
21667        assert_eq!(
21668            runtime
21669                .next_wakeup_time(window_id)
21670                .map_err(|error| error.to_string())?,
21671            None
21672        );
21673
21674        Ok(())
21675    }
21676
21677    #[test]
21678    fn tabs_panel_body_slides_during_theme_switch_motion() -> Result<(), String> {
21679        let mut theme = DefaultTheme::default();
21680        theme.motion.duration_fast = 0.6;
21681        theme.motion.duration_normal = 0.0;
21682        let switch_duration = theme.motion.tab_switch_duration();
21683        let (mut runtime, window_id) = build_runtime(
21684            Tabs::new("Main tabs")
21685                .theme(theme)
21686                .tab("Design", crate::Label::new("Design panel"))
21687                .tab("Inspect", crate::Label::new("Inspect panel")),
21688        );
21689
21690        runtime
21691            .render(window_id)
21692            .map_err(|error| error.to_string())?;
21693        runtime
21694            .handle_event(
21695                window_id,
21696                Event::Keyboard(KeyboardEvent::new("Tab", KeyState::Pressed)),
21697            )
21698            .map_err(|error| error.to_string())?;
21699        runtime.tick(0.0);
21700        let _ = handle_ready_events(&mut runtime)?;
21701        runtime
21702            .handle_event(
21703                window_id,
21704                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
21705            )
21706            .map_err(|error| error.to_string())?;
21707
21708        runtime.tick(switch_duration * 0.5);
21709        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21710        let mid = runtime
21711            .render(window_id)
21712            .map_err(|error| error.to_string())?;
21713        let mid_dx = text_transform_dx_for(&mid, "Inspect panel")
21714            .expect("incoming panel text should be painted");
21715        assert!(
21716            mid_dx > 0.0,
21717            "forward tab switch should slide the incoming panel in from the right; dx={mid_dx}"
21718        );
21719
21720        runtime.tick(switch_duration);
21721        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21722        let settled = runtime
21723            .render(window_id)
21724            .map_err(|error| error.to_string())?;
21725        let settled_dx = text_transform_dx_for(&settled, "Inspect panel")
21726            .expect("settled panel text should be painted");
21727        assert_eq!(settled_dx, 0.0);
21728
21729        Ok(())
21730    }
21731
21732    #[test]
21733    fn tabs_render_only_the_active_panel_after_switching() {
21734        let first = Rc::new(RefCell::new(PanelCounters::default()));
21735        let second = Rc::new(RefCell::new(PanelCounters::default()));
21736        let (mut runtime, window_id) = build_runtime(
21737            Tabs::new("Main tabs")
21738                .tab("First", SpyPanel::new("first-panel", Rc::clone(&first)))
21739                .tab("Second", SpyPanel::new("second-panel", Rc::clone(&second))),
21740        );
21741
21742        let initial = runtime.render(window_id).unwrap();
21743        assert_eq!(
21744            *first.borrow(),
21745            PanelCounters {
21746                measure: 1,
21747                arrange: 1,
21748                paint: 1,
21749                semantics: 1
21750            }
21751        );
21752        assert_eq!(*second.borrow(), PanelCounters::default());
21753        assert!(
21754            initial
21755                .semantics
21756                .iter()
21757                .any(|node| node.name.as_deref() == Some("first-panel"))
21758        );
21759        assert!(
21760            !initial
21761                .semantics
21762                .iter()
21763                .any(|node| node.name.as_deref() == Some("second-panel"))
21764        );
21765
21766        let mut down = PointerEvent::new(PointerEventKind::Down, Point::new(48.0, 20.0));
21767        down.pointer_id = 1;
21768        down.button = Some(PointerButton::Primary);
21769        down.buttons = PointerButtons::new(1);
21770        runtime
21771            .handle_event(window_id, Event::Pointer(down))
21772            .unwrap();
21773
21774        let mut up = PointerEvent::new(PointerEventKind::Up, Point::new(48.0, 20.0));
21775        up.pointer_id = 1;
21776        up.button = Some(PointerButton::Primary);
21777        runtime.handle_event(window_id, Event::Pointer(up)).unwrap();
21778
21779        let first_before_switch = *first.borrow();
21780        let second_before_switch = *second.borrow();
21781
21782        runtime
21783            .handle_event(
21784                window_id,
21785                Event::Keyboard(KeyboardEvent::new("ArrowRight", KeyState::Pressed)),
21786            )
21787            .unwrap();
21788
21789        let after_switch = runtime.render(window_id).unwrap();
21790        assert_eq!(first.borrow().paint, first_before_switch.paint);
21791        assert_eq!(first.borrow().semantics, first_before_switch.semantics);
21792        assert_eq!(second.borrow().paint, second_before_switch.paint + 1);
21793        assert_eq!(
21794            second.borrow().semantics,
21795            second_before_switch.semantics + 1
21796        );
21797        assert!(
21798            !after_switch
21799                .semantics
21800                .iter()
21801                .any(|node| node.name.as_deref() == Some("first-panel"))
21802        );
21803        assert!(
21804            after_switch
21805                .semantics
21806                .iter()
21807                .any(|node| node.name.as_deref() == Some("second-panel"))
21808        );
21809    }
21810
21811    #[test]
21812    fn tab_bar_header_label_visual_center_matches_control_center() {
21813        let output = render(TabBar::new("Main tabs").tabs(["A", "B"]));
21814        assert_eq!(
21815            output.frame.viewport.height,
21816            DefaultTheme::default().metrics.tab_height
21817        );
21818
21819        let text = first_text_run(&output);
21820        let layout = TextSystem::new()
21821            .shape_text_run(&text, &FontRegistry::new())
21822            .expect("tab header label should shape");
21823        let line = layout
21824            .lines()
21825            .first()
21826            .expect("tab header label should contain one line");
21827        let actual_visual_center =
21828            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
21829        let control_center = output.frame.viewport.height * 0.5;
21830
21831        assert!((actual_visual_center - control_center).abs() < 0.75);
21832    }
21833
21834    #[test]
21835    fn menu_row_label_visual_center_matches_row_center() {
21836        let output = render(
21837            Menu::new("App menu").items([MenuItem::new("New File"), MenuItem::new("Open...")]),
21838        );
21839        assert!(output.semantics.iter().any(|node| {
21840            node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("New File")
21841        }));
21842        let text = text_run_for(&output, "New File");
21843        let layout = TextSystem::new()
21844            .shape_text_run(&text, &FontRegistry::new())
21845            .expect("menu item text should shape");
21846        let line = layout
21847            .lines()
21848            .first()
21849            .expect("menu item text should contain one line");
21850        let actual_visual_center =
21851            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
21852        let theme = DefaultTheme::default();
21853        let padding = theme.metrics.menu_padding;
21854        let row_height = (output.frame.viewport.height - padding.top - padding.bottom) / 2.0;
21855        let row_center = padding.top + (row_height * 0.5);
21856
21857        assert!((actual_visual_center - row_center).abs() < 0.75);
21858    }
21859
21860    #[test]
21861    fn menu_row_hover_and_press_use_theme_motion() -> Result<(), String> {
21862        let theme = DefaultTheme::default();
21863        let hover_duration = theme.motion.hover_duration();
21864        let press_duration = theme.motion.press_duration();
21865        let expected_hover = super::mix_color(
21866            theme.palette.control,
21867            theme.palette.accent,
21868            theme.interaction.selected_blend,
21869        );
21870        let expected_press = super::mix_color(
21871            expected_hover,
21872            theme.palette.control_active,
21873            theme.interaction.pressed_blend,
21874        );
21875        let (mut runtime, window_id) = build_runtime(
21876            Menu::new("App menu")
21877                .theme(theme)
21878                .items([MenuItem::new("New File"), MenuItem::new("Open...")]),
21879        );
21880        let output = runtime
21881            .render(window_id)
21882            .map_err(|error| error.to_string())?;
21883        let item = output
21884            .semantics
21885            .iter()
21886            .find(|node| {
21887                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("New File")
21888            })
21889            .expect("menu item semantics should exist");
21890        let position = super::rect_center(item.bounds);
21891
21892        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
21893        move_event.pointer_id = 1;
21894        runtime
21895            .handle_event(window_id, Event::Pointer(move_event))
21896            .map_err(|error| error.to_string())?;
21897
21898        runtime.tick(hover_duration * 0.5);
21899        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21900        let mid_hover = runtime
21901            .render(window_id)
21902            .map_err(|error| error.to_string())?;
21903        assert!(
21904            !solid_fill_colors(&mid_hover).contains(&expected_hover),
21905            "menu hover fill should not snap to the settled highlighted color"
21906        );
21907
21908        runtime.tick(hover_duration);
21909        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21910        let settled_hover = runtime
21911            .render(window_id)
21912            .map_err(|error| error.to_string())?;
21913        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
21914
21915        runtime
21916            .handle_event(
21917                window_id,
21918                primary_pointer(PointerEventKind::Down, position, true),
21919            )
21920            .map_err(|error| error.to_string())?;
21921
21922        runtime.tick(hover_duration + press_duration * 0.5);
21923        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21924        let mid_press = runtime
21925            .render(window_id)
21926            .map_err(|error| error.to_string())?;
21927        assert!(
21928            !solid_fill_colors(&mid_press).contains(&expected_press),
21929            "menu press fill should not snap to the settled pressed color"
21930        );
21931
21932        runtime.tick(hover_duration + press_duration);
21933        assert_eq!(handle_ready_events(&mut runtime)?, 1);
21934        let settled_press = runtime
21935            .render(window_id)
21936            .map_err(|error| error.to_string())?;
21937        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
21938
21939        Ok(())
21940    }
21941
21942    #[test]
21943    fn menu_shortcuts_align_to_trailing_edge_and_row_center() {
21944        let theme = DefaultTheme::default();
21945        let output = render(Menu::new("App menu").items([
21946            MenuItem::new("New File").shortcut("Ctrl+N"),
21947            MenuItem::new("Open...").shortcut("Ctrl+Shift+O"),
21948        ]));
21949        let first_row = output
21950            .semantics
21951            .iter()
21952            .find(|node| {
21953                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("New File")
21954            })
21955            .expect("first menu item semantics present")
21956            .bounds;
21957        let second_row = output
21958            .semantics
21959            .iter()
21960            .find(|node| {
21961                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Open...")
21962            })
21963            .expect("second menu item semantics present")
21964            .bounds;
21965        let first_shortcut = text_run_for(&output, "Ctrl+N");
21966        let second_shortcut = text_run_for(&output, "Ctrl+Shift+O");
21967        let first_label_clip = clip_rect_for_text(&output, "New File");
21968        let second_label_clip = clip_rect_for_text(&output, "Open...");
21969        let first_edge = first_row.max_x() - theme.metrics.menu_item_padding.right;
21970        let second_edge = second_row.max_x() - theme.metrics.menu_item_padding.right;
21971        let first_label_edge = first_row.max_x()
21972            - theme.metrics.menu_item_padding.right
21973            - theme.metrics.menu_shortcut_width;
21974        let second_label_edge = second_row.max_x()
21975            - theme.metrics.menu_item_padding.right
21976            - theme.metrics.menu_shortcut_width;
21977
21978        assert_eq!(
21979            first_shortcut.style.color,
21980            theme.placeholder_text_style().color
21981        );
21982        assert!((first_label_clip.max_x() - first_label_edge).abs() < 0.75);
21983        assert!((second_label_clip.max_x() - second_label_edge).abs() < 0.75);
21984        assert!((first_shortcut.rect.max_x() - first_edge).abs() < 0.75);
21985        assert!((second_shortcut.rect.max_x() - second_edge).abs() < 0.75);
21986        assert!((first_shortcut.rect.max_x() - second_shortcut.rect.max_x()).abs() < 0.75);
21987        assert!(
21988            (text_run_visual_center(&first_shortcut) - (first_row.y() + first_row.height() * 0.5))
21989                .abs()
21990                < 0.75
21991        );
21992    }
21993
21994    #[test]
21995    fn menu_shortcuts_preserve_tall_measurements_and_row_center() {
21996        let mut theme = DefaultTheme::default();
21997        theme.typography.body_font_size = 28.0;
21998        theme.typography.body_line_height = 12.0;
21999        theme.metrics.menu_row_height = 64.0;
22000        let metrics = theme.metrics;
22001        let output = render_isolated(
22002            Menu::new("App menu")
22003                .theme(theme)
22004                .items([MenuItem::new("New File").shortcut("Ctrl+N")]),
22005        );
22006        let row = output
22007            .semantics
22008            .iter()
22009            .find(|node| {
22010                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("New File")
22011            })
22012            .expect("menu item semantics present")
22013            .bounds;
22014        let label = text_run_for(&output, "New File");
22015        let shortcut = text_run_for(&output, "Ctrl+N");
22016        let label_layout = TextSystem::new()
22017            .shape_text_run(&label, &FontRegistry::new())
22018            .expect("menu item text should shape");
22019        let shortcut_layout = TextSystem::new()
22020            .shape_text_run(&shortcut, &FontRegistry::new())
22021            .expect("menu shortcut text should shape");
22022        let shortcut_edge = row.max_x() - metrics.menu_item_padding.right;
22023        let row_center = row.y() + (row.height() * 0.5);
22024
22025        assert_eq!(label.style.font_size, 28.0);
22026        assert_eq!(label.style.line_height, 12.0);
22027        assert_eq!(shortcut.style.font_size, 28.0);
22028        assert_eq!(shortcut.style.line_height, 12.0);
22029        assert!(label.rect.height() >= label_layout.measurement().height - 0.01);
22030        assert!(shortcut.rect.height() >= shortcut_layout.measurement().height - 0.01);
22031        assert!(label.rect.height() > label.style.line_height);
22032        assert!(shortcut.rect.height() > shortcut.style.line_height);
22033        assert!((shortcut.rect.max_x() - shortcut_edge).abs() < 0.75);
22034        assert!((text_run_visual_center(&label) - row_center).abs() < 0.75);
22035        assert!((text_run_visual_center(&shortcut) - row_center).abs() < 0.75);
22036    }
22037
22038    #[test]
22039    fn context_menu_row_label_visual_center_matches_row_center() -> Result<(), String> {
22040        // Dropdown anchoring keeps the row geometry derivable from the
22041        // trigger bounds; pointer anchoring is covered separately.
22042        let (mut runtime, window_id) = build_runtime(
22043            crate::SizedBox::new()
22044                .width(320.0)
22045                .height(180.0)
22046                .with_child(
22047                    ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22048                        .anchor_to_pointer(false)
22049                        .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")]),
22050                ),
22051        );
22052
22053        let closed = runtime
22054            .render(window_id)
22055            .map_err(|error| error.to_string())?;
22056        let trigger = closed
22057            .semantics
22058            .iter()
22059            .find(|node| node.role == SemanticsRole::Button)
22060            .expect("context menu trigger present")
22061            .bounds;
22062        let trigger_center = Point::new(
22063            trigger.x() + (trigger.width() * 0.5),
22064            trigger.y() + (trigger.height() * 0.5),
22065        );
22066
22067        let mut down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22068        down.pointer_id = 1;
22069        down.button = Some(PointerButton::Secondary);
22070        runtime
22071            .handle_event(window_id, Event::Pointer(down))
22072            .map_err(|error| error.to_string())?;
22073
22074        let output = runtime
22075            .render(window_id)
22076            .map_err(|error| error.to_string())?;
22077        let _context = output
22078            .semantics
22079            .iter()
22080            .find(|node| node.role == SemanticsRole::ContextMenu)
22081            .expect("context menu semantics present");
22082        let row = output
22083            .semantics
22084            .iter()
22085            .find(|node| {
22086                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Rename")
22087            })
22088            .expect("rename menu item semantics present")
22089            .bounds;
22090        let text = text_run_for(&output, "Rename");
22091        let layout = TextSystem::new()
22092            .shape_text_run(&text, &FontRegistry::new())
22093            .expect("context menu item text should shape");
22094        let line = layout
22095            .lines()
22096            .first()
22097            .expect("context menu item text should contain one line");
22098        let actual_visual_center =
22099            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
22100        let row_center = row.y() + row.height() * 0.5;
22101
22102        assert!((actual_visual_center - row_center).abs() < 0.75);
22103        Ok(())
22104    }
22105
22106    #[test]
22107    fn context_menu_opens_at_the_right_click_position() -> Result<(), String> {
22108        let (mut runtime, window_id) = build_runtime(
22109            ContextMenu::new(
22110                "Surface menu",
22111                crate::containers::SizedBox::new()
22112                    .width(600.0)
22113                    .height(400.0),
22114            )
22115            .items([MenuItem::new("Copy"), MenuItem::new("Select All")]),
22116        );
22117
22118        runtime
22119            .render(window_id)
22120            .map_err(|error| error.to_string())?;
22121        let press = Point::new(220.0, 140.0);
22122        let mut down = PointerEvent::new(PointerEventKind::Down, press);
22123        down.pointer_id = 1;
22124        down.button = Some(PointerButton::Secondary);
22125        runtime
22126            .handle_event(window_id, Event::Pointer(down))
22127            .map_err(|error| error.to_string())?;
22128
22129        let output = runtime
22130            .render(window_id)
22131            .map_err(|error| error.to_string())?;
22132        let first_item = output
22133            .semantics
22134            .iter()
22135            .find(|node| {
22136                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Copy")
22137            })
22138            .expect("menu item semantics present");
22139        let theme = DefaultTheme::default();
22140        let padding = theme.metrics.menu_padding;
22141        assert!(
22142            (first_item.bounds.x() - (press.x + padding.left)).abs() < 1.0,
22143            "menu should open at the press x, got item at {:?}",
22144            first_item.bounds
22145        );
22146        assert!(
22147            (first_item.bounds.y() - (press.y + padding.top)).abs() < 1.0,
22148            "menu should open at the press y, got item at {:?}",
22149            first_item.bounds
22150        );
22151
22152        // The menu must also actually paint at the anchored position.
22153        let label = text_run_for(&output, "Copy");
22154        assert!(
22155            (label.rect.y() - press.y).abs() < theme.metrics.menu_padding.top + 16.0,
22156            "menu label should paint near the press position, got {:?}",
22157            label.rect
22158        );
22159        Ok(())
22160    }
22161
22162    #[test]
22163    fn context_menu_routes_copy_to_read_only_text_area() -> Result<(), String> {
22164        let value = "node = local\naddress = 127.0.0.1:21353";
22165        let selection = SelectionScope::new();
22166        let menu = ContextMenu::new(
22167            "Connection details menu",
22168            TextArea::new("Connection details")
22169                .value(value)
22170                .read_only()
22171                .selectable(selection.clone()),
22172        );
22173        let text_area_id = menu.trigger_id();
22174        let menu = menu
22175            .items([MenuItem::new("Copy")])
22176            .on_activate_with_ctx(move |ctx, _, _| {
22177                ctx.post_command(text_area_id, TEXT_COMMAND, TextCommand::Copy);
22178            });
22179        let (mut runtime, window_id) = build_runtime(menu);
22180
22181        runtime
22182            .render(window_id)
22183            .map_err(|error| error.to_string())?;
22184        assert!(
22185            runtime
22186                .handle_semantics_action(
22187                    window_id,
22188                    text_area_id,
22189                    SemanticsActionRequest::SetSelection(sui_core::SemanticsTextRange::new(
22190                        0,
22191                        value.len(),
22192                    )),
22193                )
22194                .map_err(|error| error.to_string())?
22195        );
22196        assert_eq!(selection.selected_text().as_deref(), Some(value));
22197
22198        let press = Point::new(20.0, 20.0);
22199        let mut right_click = PointerEvent::new(PointerEventKind::Down, press);
22200        right_click.pointer_id = 1;
22201        right_click.button = Some(PointerButton::Secondary);
22202        runtime
22203            .handle_event(window_id, Event::Pointer(right_click))
22204            .map_err(|error| error.to_string())?;
22205
22206        let open = runtime
22207            .render(window_id)
22208            .map_err(|error| error.to_string())?;
22209        let copy = open
22210            .semantics
22211            .iter()
22212            .find(|node| {
22213                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Copy")
22214            })
22215            .expect("copy context-menu item should be presented")
22216            .bounds;
22217        let copy_center = Point::new(
22218            copy.x() + copy.width() * 0.5,
22219            copy.y() + copy.height() * 0.5,
22220        );
22221        runtime
22222            .handle_event(
22223                window_id,
22224                primary_pointer(PointerEventKind::Down, copy_center, true),
22225            )
22226            .map_err(|error| error.to_string())?;
22227        runtime
22228            .handle_event(
22229                window_id,
22230                primary_pointer(PointerEventKind::Up, copy_center, false),
22231            )
22232            .map_err(|error| error.to_string())?;
22233
22234        assert_eq!(runtime.clipboard().text().as_deref(), Some(value));
22235        assert_eq!(selection.selected_text().as_deref(), Some(value));
22236        Ok(())
22237    }
22238
22239    #[test]
22240    fn context_menu_pointer_activation_escapes_tight_trigger_inside_scroll_view()
22241    -> Result<(), String> {
22242        let activations = Rc::new(Cell::new(0));
22243        let recorded_activations = Rc::clone(&activations);
22244        let menu = ContextMenu::new(
22245            "Connection details menu",
22246            TextArea::new("Connection details")
22247                .value("node = local\naddress = 127.0.0.1:21353")
22248                .read_only(),
22249        )
22250        .items([MenuItem::new("Select all"), MenuItem::new("Copy")])
22251        .on_activate(move |index, _| {
22252            if index == 1 {
22253                activations.set(activations.get() + 1);
22254            }
22255        });
22256        let root = SizedBox::new()
22257            .size(Size::new(600.0, 360.0))
22258            .with_child(ScrollView::vertical(Padding::all(
22259                24.0,
22260                Stack::vertical()
22261                    .spacing(16.0)
22262                    .with_child(SizedBox::new().height(96.0))
22263                    .with_child(SizedBox::new().height(68.0).width(480.0).with_child(menu))
22264                    .with_child(SizedBox::new().height(420.0)),
22265            )));
22266        let (mut runtime, window_id) = build_runtime(root);
22267
22268        let closed = runtime
22269            .render(window_id)
22270            .map_err(|error| error.to_string())?;
22271        let trigger = closed
22272            .semantics
22273            .iter()
22274            .find(|node| {
22275                node.role == SemanticsRole::TextInput
22276                    && node.name.as_deref() == Some("Connection details")
22277            })
22278            .expect("nested context-menu trigger should be present")
22279            .bounds;
22280        assert!(
22281            trigger.height() <= 68.0,
22282            "trigger should remain constrained by the tight settings row"
22283        );
22284        let trigger_center = Point::new(
22285            trigger.x() + trigger.width() * 0.5,
22286            trigger.y() + trigger.height() * 0.5,
22287        );
22288        let mut right_click = PointerEvent::new(PointerEventKind::Down, trigger_center);
22289        right_click.pointer_id = 1;
22290        right_click.button = Some(PointerButton::Secondary);
22291        runtime
22292            .handle_event(window_id, Event::Pointer(right_click))
22293            .map_err(|error| error.to_string())?;
22294
22295        let open = runtime
22296            .render(window_id)
22297            .map_err(|error| error.to_string())?;
22298        let copy = open
22299            .semantics
22300            .iter()
22301            .find(|node| {
22302                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Copy")
22303            })
22304            .expect("copy item should be presented outside the tight trigger")
22305            .bounds;
22306        assert!(
22307            copy.max_y() > trigger.max_y(),
22308            "dropdown row should exercise out-of-trigger hit testing: trigger={trigger:?}, copy={copy:?}"
22309        );
22310        let copy_center = Point::new(
22311            copy.x() + copy.width() * 0.5,
22312            copy.y() + copy.height() * 0.5,
22313        );
22314        runtime
22315            .handle_event(
22316                window_id,
22317                primary_pointer(PointerEventKind::Down, copy_center, true),
22318            )
22319            .map_err(|error| error.to_string())?;
22320        let pressed = runtime
22321            .render(window_id)
22322            .map_err(|error| error.to_string())?;
22323        let context_menu = pressed
22324            .semantics
22325            .iter()
22326            .find(|node| {
22327                node.role == SemanticsRole::ContextMenu
22328                    && node.name.as_deref() == Some("Connection details menu")
22329            })
22330            .expect("context menu should remain present while its row is pressed");
22331        assert!(
22332            context_menu.state.focused,
22333            "ancestor scrollers must not steal focus during pointer capture"
22334        );
22335        assert_eq!(context_menu.state.expanded, Some(true));
22336        runtime
22337            .handle_event(
22338                window_id,
22339                primary_pointer(PointerEventKind::Up, copy_center, false),
22340            )
22341            .map_err(|error| error.to_string())?;
22342
22343        assert_eq!(recorded_activations.get(), 1);
22344        Ok(())
22345    }
22346
22347    #[test]
22348    fn context_menu_shortcut_aligns_to_trailing_edge() -> Result<(), String> {
22349        let theme = DefaultTheme::default();
22350        let (mut runtime, window_id) = build_runtime(
22351            crate::SizedBox::new()
22352                .width(320.0)
22353                .height(180.0)
22354                .with_child(
22355                    ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22356                        .anchor_to_pointer(false)
22357                        .items([MenuItem::new("Rename").shortcut("F2")]),
22358                ),
22359        );
22360
22361        let closed = runtime
22362            .render(window_id)
22363            .map_err(|error| error.to_string())?;
22364        let trigger = closed
22365            .semantics
22366            .iter()
22367            .find(|node| node.role == SemanticsRole::Button)
22368            .expect("context menu trigger present")
22369            .bounds;
22370        let trigger_center = Point::new(
22371            trigger.x() + (trigger.width() * 0.5),
22372            trigger.y() + (trigger.height() * 0.5),
22373        );
22374
22375        let mut down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22376        down.pointer_id = 1;
22377        down.button = Some(PointerButton::Secondary);
22378        runtime
22379            .handle_event(window_id, Event::Pointer(down))
22380            .map_err(|error| error.to_string())?;
22381
22382        let output = runtime
22383            .render(window_id)
22384            .map_err(|error| error.to_string())?;
22385        let row = output
22386            .semantics
22387            .iter()
22388            .find(|node| {
22389                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Rename")
22390            })
22391            .expect("context menu item semantics present")
22392            .bounds;
22393        let label_clip = clip_rect_for_text(&output, "Rename");
22394        let shortcut = text_run_for(&output, "F2");
22395        let label_edge =
22396            row.max_x() - theme.metrics.menu_item_padding.right - theme.metrics.menu_shortcut_width;
22397        let shortcut_edge = row.max_x() - theme.metrics.menu_item_padding.right;
22398
22399        assert_eq!(shortcut.style.color, theme.placeholder_text_style().color);
22400        assert!(
22401            (label_clip.max_x() - label_edge).abs() < 0.75,
22402            "label clip {:?} should end at {label_edge}; row={row:?}",
22403            label_clip
22404        );
22405        assert!((shortcut.rect.max_x() - shortcut_edge).abs() < 0.75);
22406        assert!((text_run_visual_center(&shortcut) - (row.y() + row.height() * 0.5)).abs() < 0.75);
22407        Ok(())
22408    }
22409
22410    #[test]
22411    fn context_menu_shortcuts_preserve_tall_measurements_and_row_center() -> Result<(), String> {
22412        let mut theme = DefaultTheme::default();
22413        theme.typography.body_font_size = 28.0;
22414        theme.typography.body_line_height = 12.0;
22415        theme.metrics.menu_row_height = 64.0;
22416        let metrics = theme.metrics;
22417        let (mut runtime, window_id) = build_runtime(
22418            crate::SizedBox::new()
22419                .width(320.0)
22420                .height(180.0)
22421                .with_child(
22422                    ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22423                        .theme(theme)
22424                        .items([MenuItem::new("Rename").shortcut("F2")]),
22425                ),
22426        );
22427
22428        let closed = runtime
22429            .render(window_id)
22430            .map_err(|error| error.to_string())?;
22431        let trigger = closed
22432            .semantics
22433            .iter()
22434            .find(|node| node.role == SemanticsRole::Button)
22435            .expect("context menu trigger present")
22436            .bounds;
22437        let trigger_center = Point::new(
22438            trigger.x() + (trigger.width() * 0.5),
22439            trigger.y() + (trigger.height() * 0.5),
22440        );
22441
22442        let mut down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22443        down.pointer_id = 1;
22444        down.button = Some(PointerButton::Secondary);
22445        runtime
22446            .handle_event(window_id, Event::Pointer(down))
22447            .map_err(|error| error.to_string())?;
22448
22449        let output = runtime
22450            .render(window_id)
22451            .map_err(|error| error.to_string())?;
22452        let row = output
22453            .semantics
22454            .iter()
22455            .find(|node| {
22456                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Rename")
22457            })
22458            .expect("context menu item semantics present")
22459            .bounds;
22460        let label = text_run_for(&output, "Rename");
22461        let shortcut = text_run_for(&output, "F2");
22462        let label_layout = TextSystem::new()
22463            .shape_text_run(&label, &FontRegistry::new())
22464            .expect("context menu item text should shape");
22465        let shortcut_layout = TextSystem::new()
22466            .shape_text_run(&shortcut, &FontRegistry::new())
22467            .expect("context menu shortcut text should shape");
22468        let shortcut_edge = row.max_x() - metrics.menu_item_padding.right;
22469        let row_center = row.y() + (row.height() * 0.5);
22470
22471        assert_eq!(label.style.font_size, 28.0);
22472        assert_eq!(label.style.line_height, 12.0);
22473        assert_eq!(shortcut.style.font_size, 28.0);
22474        assert_eq!(shortcut.style.line_height, 12.0);
22475        assert!(label.rect.height() >= label_layout.measurement().height - 0.01);
22476        assert!(shortcut.rect.height() >= shortcut_layout.measurement().height - 0.01);
22477        assert!(label.rect.height() > label.style.line_height);
22478        assert!(shortcut.rect.height() > shortcut.style.line_height);
22479        assert!((shortcut.rect.max_x() - shortcut_edge).abs() < 0.75);
22480        assert!((text_run_visual_center(&label) - row_center).abs() < 0.75);
22481        assert!((text_run_visual_center(&shortcut) - row_center).abs() < 0.75);
22482        Ok(())
22483    }
22484
22485    #[test]
22486    fn context_menu_entrance_uses_theme_motion_layer_properties() -> Result<(), String> {
22487        let theme = slow_normal_motion_theme();
22488        let duration = theme.motion.entrance_duration();
22489        let (mut runtime, window_id) = build_runtime(
22490            ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22491                .theme(theme)
22492                .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")]),
22493        );
22494
22495        let closed = runtime
22496            .render(window_id)
22497            .map_err(|error| error.to_string())?;
22498        assert!(overlay_layer_descriptor(&closed).is_none());
22499        let trigger = closed
22500            .semantics
22501            .iter()
22502            .find(|node| node.role == SemanticsRole::Button)
22503            .expect("context menu trigger present")
22504            .bounds;
22505        let trigger_center = Point::new(
22506            trigger.x() + (trigger.width() * 0.5),
22507            trigger.y() + (trigger.height() * 0.5),
22508        );
22509
22510        let mut down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22511        down.pointer_id = 1;
22512        down.button = Some(PointerButton::Secondary);
22513        runtime
22514            .handle_event(window_id, Event::Pointer(down))
22515            .map_err(|error| error.to_string())?;
22516
22517        let start = runtime
22518            .render(window_id)
22519            .map_err(|error| error.to_string())?;
22520        let context = start
22521            .semantics
22522            .iter()
22523            .find(|node| node.role == SemanticsRole::ContextMenu)
22524            .expect("context menu semantics present");
22525        let start_descriptor =
22526            overlay_layer_descriptor(&start).expect("context menu overlay layer should appear");
22527        let menu_owner = overlay_layer_owner(&start).expect("context menu overlay owner present");
22528        assert_eq!(start_descriptor.properties.opacity, 0.0);
22529        assert!(start_descriptor.properties.translation.y < 0.0);
22530        assert!(
22531            layer_descriptor_for(&start, context.id).is_none(),
22532            "the context menu owner should not fade or translate the trigger"
22533        );
22534
22535        runtime.tick(duration * 0.5);
22536        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22537        let mid = runtime
22538            .render(window_id)
22539            .map_err(|error| error.to_string())?;
22540        let mid_descriptor =
22541            overlay_layer_descriptor(&mid).expect("context menu overlay layer should stay active");
22542        assert!(mid_descriptor.properties.opacity > 0.0);
22543        assert!(mid_descriptor.properties.opacity < 1.0);
22544        assert!(mid_descriptor.properties.translation.y < 0.0);
22545        assert!(
22546            mid_descriptor.properties.translation.y.abs()
22547                < start_descriptor.properties.translation.y.abs()
22548        );
22549        assert!(
22550            mid.frame.layer_updates.iter().any(|update| {
22551                update.owner == menu_owner
22552                    && matches!(
22553                        update.kind,
22554                        SceneLayerUpdateKind::Transform | SceneLayerUpdateKind::Effect
22555                    )
22556            }),
22557            "context menu entrance should update retained layer properties"
22558        );
22559        assert!(
22560            !mid.frame.layer_updates.iter().any(|update| {
22561                update.owner == menu_owner && update.kind == SceneLayerUpdateKind::Content
22562            }),
22563            "context menu entrance should not repaint menu content"
22564        );
22565        assert!(
22566            runtime
22567                .next_wakeup_time(window_id)
22568                .map_err(|error| error.to_string())?
22569                .is_some()
22570        );
22571
22572        runtime.tick(duration);
22573        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22574        let settled = runtime
22575            .render(window_id)
22576            .map_err(|error| error.to_string())?;
22577        let settled_descriptor =
22578            overlay_layer_descriptor(&settled).expect("context menu overlay layer should remain");
22579        assert_eq!(settled_descriptor.properties.opacity, 1.0);
22580        assert_eq!(settled_descriptor.properties.translation.y, 0.0);
22581        assert_eq!(
22582            runtime
22583                .next_wakeup_time(window_id)
22584                .map_err(|error| error.to_string())?,
22585            None
22586        );
22587        Ok(())
22588    }
22589
22590    #[test]
22591    fn context_menu_focus_ring_uses_non_hit_test_retained_layer() -> Result<(), String> {
22592        let theme = DefaultTheme::default();
22593        let focus_duration = theme.motion.focus_duration();
22594        let (mut runtime, window_id) = build_runtime(
22595            ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22596                .theme(theme)
22597                .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")]),
22598        );
22599
22600        let closed = runtime
22601            .render(window_id)
22602            .map_err(|error| error.to_string())?;
22603        let trigger = closed
22604            .semantics
22605            .iter()
22606            .find(|node| node.role == SemanticsRole::Button)
22607            .expect("context menu trigger present")
22608            .bounds;
22609        let trigger_center = Point::new(
22610            trigger.x() + (trigger.width() * 0.5),
22611            trigger.y() + (trigger.height() * 0.5),
22612        );
22613
22614        let mut down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22615        down.pointer_id = 1;
22616        down.button = Some(PointerButton::Secondary);
22617        runtime
22618            .handle_event(window_id, Event::Pointer(down))
22619            .map_err(|error| error.to_string())?;
22620
22621        let opened = runtime
22622            .render(window_id)
22623            .map_err(|error| error.to_string())?;
22624        let menu_owner = overlay_layer_owner(&opened).expect("context menu overlay owner present");
22625        let overlay =
22626            overlay_layer_descriptor(&opened).expect("context menu overlay layer should appear");
22627        assert!(overlay.hit_test);
22628        let focus_layers = non_hit_test_layer_descriptors(&opened);
22629        assert_eq!(
22630            focus_layers.len(),
22631            1,
22632            "context menu focus chrome should be the only non-hit-test layer"
22633        );
22634        assert_eq!(
22635            focus_layers[0].composition_mode,
22636            LayerCompositionMode::Normal
22637        );
22638        let focus_owner = non_hit_test_layer_owners(&opened)
22639            .into_iter()
22640            .next()
22641            .expect("context menu focus layer owner present");
22642
22643        runtime.tick(focus_duration * 0.5);
22644        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22645        let mid_focus = runtime
22646            .render(window_id)
22647            .map_err(|error| error.to_string())?;
22648        assert!(
22649            !contains_approx_color(&solid_stroke_colors(&mid_focus), theme.palette.focus_ring),
22650            "context menu focus ring should not snap to the settled focus color"
22651        );
22652        assert!(
22653            !mid_focus.frame.layer_updates.iter().any(|update| {
22654                update.owner == menu_owner && update.kind == SceneLayerUpdateKind::Content
22655            }),
22656            "context menu rows should stay retained during focus chrome animation"
22657        );
22658        assert!(
22659            mid_focus
22660                .frame
22661                .layer_updates
22662                .iter()
22663                .any(|update| update.owner == focus_owner),
22664            "context menu focus layer should receive the animation update"
22665        );
22666
22667        runtime.tick(focus_duration + 0.01);
22668        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22669        let settled_focus = runtime
22670            .render(window_id)
22671            .map_err(|error| error.to_string())?;
22672        let settled_strokes = solid_stroke_colors(&settled_focus);
22673        assert!(
22674            contains_approx_color(&settled_strokes, theme.palette.focus_ring),
22675            "context menu focus ring should settle to the theme focus color; strokes={settled_strokes:?}"
22676        );
22677
22678        Ok(())
22679    }
22680
22681    #[test]
22682    fn context_menu_row_hover_and_press_use_theme_motion() -> Result<(), String> {
22683        let theme = DefaultTheme::default();
22684        let hover_duration = theme.motion.hover_duration();
22685        let press_duration = theme.motion.press_duration();
22686        let expected_hover = super::mix_color(
22687            theme.palette.control,
22688            theme.palette.accent,
22689            theme.interaction.selected_blend,
22690        );
22691        let expected_press = super::mix_color(
22692            expected_hover,
22693            theme.palette.control_active,
22694            theme.interaction.pressed_blend,
22695        );
22696        let (mut runtime, window_id) = build_runtime(
22697            ContextMenu::new("Canvas menu", crate::Button::new("Open menu"))
22698                .theme(theme)
22699                .items([MenuItem::new("Rename"), MenuItem::new("Duplicate")]),
22700        );
22701
22702        let closed = runtime
22703            .render(window_id)
22704            .map_err(|error| error.to_string())?;
22705        let trigger = closed
22706            .semantics
22707            .iter()
22708            .find(|node| node.role == SemanticsRole::Button)
22709            .expect("context menu trigger present")
22710            .bounds;
22711        let trigger_center = super::rect_center(trigger);
22712        let mut secondary_down = PointerEvent::new(PointerEventKind::Down, trigger_center);
22713        secondary_down.pointer_id = 1;
22714        secondary_down.button = Some(PointerButton::Secondary);
22715        secondary_down.buttons = PointerButtons::new(2);
22716        runtime
22717            .handle_event(window_id, Event::Pointer(secondary_down))
22718            .map_err(|error| error.to_string())?;
22719
22720        let opened = runtime
22721            .render(window_id)
22722            .map_err(|error| error.to_string())?;
22723        let duplicate = opened
22724            .semantics
22725            .iter()
22726            .find(|node| {
22727                node.role == SemanticsRole::MenuItem && node.name.as_deref() == Some("Duplicate")
22728            })
22729            .expect("duplicate menu item semantics should exist");
22730        let position = super::rect_center(duplicate.bounds);
22731
22732        let mut move_event = PointerEvent::new(PointerEventKind::Move, position);
22733        move_event.pointer_id = 1;
22734        runtime
22735            .handle_event(window_id, Event::Pointer(move_event))
22736            .map_err(|error| error.to_string())?;
22737
22738        runtime.tick(hover_duration * 0.5);
22739        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22740        let mid_hover = runtime
22741            .render(window_id)
22742            .map_err(|error| error.to_string())?;
22743        assert!(
22744            !solid_fill_colors(&mid_hover).contains(&expected_hover),
22745            "context menu hover fill should not snap to the settled highlighted color"
22746        );
22747
22748        runtime.tick(hover_duration);
22749        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22750        let settled_hover = runtime
22751            .render(window_id)
22752            .map_err(|error| error.to_string())?;
22753        assert!(solid_fill_colors(&settled_hover).contains(&expected_hover));
22754
22755        runtime
22756            .handle_event(
22757                window_id,
22758                primary_pointer(PointerEventKind::Down, position, true),
22759            )
22760            .map_err(|error| error.to_string())?;
22761
22762        runtime.tick(hover_duration + press_duration * 0.5);
22763        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22764        let mid_press = runtime
22765            .render(window_id)
22766            .map_err(|error| error.to_string())?;
22767        assert!(
22768            !solid_fill_colors(&mid_press).contains(&expected_press),
22769            "context menu press fill should not snap to the settled pressed color"
22770        );
22771
22772        runtime.tick(hover_duration + press_duration);
22773        assert_eq!(handle_ready_events(&mut runtime)?, 1);
22774        let settled_press = runtime
22775            .render(window_id)
22776            .map_err(|error| error.to_string())?;
22777        assert!(solid_fill_colors(&settled_press).contains(&expected_press));
22778
22779        Ok(())
22780    }
22781
22782    #[test]
22783    fn progress_bar_value_text_visual_center_matches_control_center() {
22784        let output = render_isolated(
22785            ProgressBar::new("Export progress")
22786                .range(0.0, 100.0)
22787                .value(42.0)
22788                .show_value(true),
22789        );
22790        let text = text_run_for(&output, "42%");
22791        let layout = TextSystem::new()
22792            .shape_text_run(&text, &FontRegistry::new())
22793            .expect("progress bar label should shape");
22794        let line = layout
22795            .lines()
22796            .first()
22797            .expect("progress bar label should contain one line");
22798        let actual_visual_center =
22799            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
22800        let control_center = output.frame.viewport.height * 0.5;
22801
22802        assert!(
22803            text.style
22804                .features
22805                .iter()
22806                .any(|feature| feature.tag == FontFeature::TABULAR_FIGURES && feature.value == 1)
22807        );
22808        assert!((actual_visual_center - control_center).abs() < 0.75);
22809    }
22810
22811    #[test]
22812    fn progress_bar_value_text_preserves_tall_measurements_and_exact_centering() {
22813        let mut theme = DefaultTheme::default();
22814        theme.text.sm = ThemeTextToken {
22815            size: 28.0,
22816            line_height: 12.0,
22817        };
22818        theme.sync_derived_fields();
22819
22820        let output = render_isolated(
22821            ProgressBar::new("Export progress")
22822                .theme(theme)
22823                .range(0.0, 100.0)
22824                .value(42.0)
22825                .height(48.0)
22826                .show_value(true),
22827        );
22828        let text = text_run_for(&output, "42%");
22829        let layout = TextSystem::new()
22830            .shape_text_run(&text, &FontRegistry::new())
22831            .expect("progress bar label should shape");
22832
22833        assert_text_run_uses_token(&text, theme.text.sm);
22834        assert!(text.rect.height() >= layout.measurement().height - 0.01);
22835        assert!(text.rect.height() > text.style.line_height);
22836        assert!(
22837            (text_visual_center_for(&output, "42%") - (output.frame.viewport.height * 0.5)).abs()
22838                < 0.75
22839        );
22840    }
22841
22842    #[test]
22843    fn spinner_label_visual_center_matches_indicator_center() {
22844        let output = render(Spinner::new("Background work").label("Uploading textures"));
22845        let text = text_run_for(&output, "Uploading textures");
22846        let layout = TextSystem::new()
22847            .shape_text_run(&text, &FontRegistry::new())
22848            .expect("spinner label should shape");
22849        let line = layout
22850            .lines()
22851            .first()
22852            .expect("spinner label should contain one line");
22853        let actual_visual_center =
22854            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
22855        let indicator_center = output.frame.viewport.height * 0.5;
22856
22857        assert!((actual_visual_center - indicator_center).abs() < 0.75);
22858    }
22859
22860    #[test]
22861    fn spinner_label_preserves_tall_measurement_and_indicator_centering() {
22862        let mut theme = DefaultTheme::default();
22863        theme.text.sm = ThemeTextToken {
22864            size: 28.0,
22865            line_height: 10.0,
22866        };
22867        theme.sync_derived_fields();
22868        let output = render(
22869            Spinner::new("Background work")
22870                .theme(theme)
22871                .label("Uploading"),
22872        );
22873        let text = text_run_for(&output, "Uploading");
22874        let layout = TextSystem::new()
22875            .shape_text_run(&text, &FontRegistry::new())
22876            .expect("spinner label should shape");
22877        let busy = output
22878            .semantics
22879            .iter()
22880            .find(|node| node.role == SemanticsRole::BusyIndicator)
22881            .expect("spinner semantics should exist");
22882        let center_y = busy.bounds.y() + busy.bounds.height() * 0.5;
22883
22884        assert_text_run_uses_token(&text, theme.text.sm);
22885        assert!(busy.bounds.height() > 20.0);
22886        assert!(text.rect.height() >= layout.measurement().height - 0.01);
22887        assert!(text.rect.height() > text.style.line_height);
22888        assert!((text_run_visual_center(&text) - center_y).abs() < 0.75);
22889    }
22890
22891    #[test]
22892    fn progress_bar_and_spinner_publish_semantics() {
22893        let output = render(sui_widgets_fixture(
22894            ProgressBar::new("Export progress")
22895                .range(0.0, 100.0)
22896                .value(42.0),
22897            Spinner::new("Background work").label("Uploading textures"),
22898        ));
22899
22900        let progress = output
22901            .semantics
22902            .iter()
22903            .find(|node| node.role == SemanticsRole::ProgressBar)
22904            .expect("progress bar node present");
22905        assert_eq!(
22906            progress.value,
22907            Some(SemanticsValue::Range {
22908                value: 42.0,
22909                min: 0.0,
22910                max: 100.0,
22911            })
22912        );
22913        let spinner = output
22914            .semantics
22915            .iter()
22916            .find(|node| node.role == SemanticsRole::BusyIndicator)
22917            .expect("spinner node present");
22918        assert!(spinner.state.busy);
22919    }
22920
22921    #[test]
22922    fn open_popover_uses_direct_overlay_layer_metadata() {
22923        let output = render(crate::Padding::all(
22924            16.0,
22925            Popover::new(
22926                "Inline inspector",
22927                crate::Button::new("Open inspector"),
22928                crate::Label::new("popover body"),
22929            )
22930            .open(true),
22931        ));
22932
22933        let descriptor =
22934            overlay_layer_descriptor(&output).expect("popover layer descriptor present");
22935
22936        assert!(descriptor.is_stack_surface);
22937        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Overlay);
22938    }
22939
22940    #[test]
22941    fn tooltip_paints_with_surface_tokens() -> Result<(), String> {
22942        let theme = DefaultTheme::default();
22943        let (mut runtime, window_id) = build_runtime(crate::Padding::all(
22944            16.0,
22945            crate::Tooltip::new(
22946                "Quick access to common commands",
22947                crate::Button::new("Hover for shortcuts").min_width(180.0),
22948            )
22949            .theme(theme),
22950        ));
22951
22952        let initial = runtime
22953            .render(window_id)
22954            .map_err(|error| error.to_string())?;
22955        let trigger = initial
22956            .semantics
22957            .iter()
22958            .find(|node| {
22959                node.role == SemanticsRole::Button
22960                    && node.name.as_deref() == Some("Hover for shortcuts")
22961            })
22962            .expect("tooltip trigger semantics present")
22963            .bounds;
22964        let hover_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
22965        runtime
22966            .handle_event(
22967                window_id,
22968                primary_pointer(PointerEventKind::Move, hover_point, false),
22969            )
22970            .map_err(|error| error.to_string())?;
22971
22972        let output = runtime
22973            .render(window_id)
22974            .map_err(|error| error.to_string())?;
22975        assert!(solid_fill_colors(&output).contains(&theme.surfaces.tooltip));
22976        let mut painted_tooltip_border = false;
22977        output
22978            .frame
22979            .scene
22980            .visit_commands(&mut |command| match command {
22981                SceneCommand::StrokeRect {
22982                    brush: Brush::Solid(color),
22983                    ..
22984                }
22985                | SceneCommand::StrokePath {
22986                    brush: Brush::Solid(color),
22987                    ..
22988                } if *color == theme.surfaces.tooltip_border => {
22989                    painted_tooltip_border = true;
22990                }
22991                _ => {}
22992            });
22993        assert!(painted_tooltip_border);
22994        Ok(())
22995    }
22996
22997    #[test]
22998    fn tooltip_end_alignment_keeps_bubble_inside_trailing_trigger_edge() -> Result<(), String> {
22999        let tooltip_text = "Enter sends · Shift+Enter newline";
23000        let (mut runtime, window_id) = build_runtime(
23001            crate::SizedBox::new()
23002                .size(Size::new(360.0, 160.0))
23003                .with_child(crate::Padding::all(
23004                    16.0,
23005                    crate::Tooltip::new(
23006                        tooltip_text,
23007                        crate::Button::new("Send message").min_width(32.0),
23008                    )
23009                    .alignment(super::TooltipAlignment::End),
23010                )),
23011        );
23012
23013        let initial = runtime
23014            .render(window_id)
23015            .map_err(|error| error.to_string())?;
23016        let trigger = initial
23017            .semantics
23018            .iter()
23019            .find(|node| {
23020                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Send message")
23021            })
23022            .expect("tooltip trigger semantics present")
23023            .bounds;
23024        runtime
23025            .handle_event(
23026                window_id,
23027                primary_pointer(
23028                    PointerEventKind::Move,
23029                    Point::new(trigger.x() + 8.0, trigger.y() + 8.0),
23030                    false,
23031                ),
23032            )
23033            .map_err(|error| error.to_string())?;
23034
23035        let output = runtime
23036            .render(window_id)
23037            .map_err(|error| error.to_string())?;
23038        let tooltip = output
23039            .semantics
23040            .iter()
23041            .find(|node| {
23042                node.role == SemanticsRole::Tooltip && node.name.as_deref() == Some(tooltip_text)
23043            })
23044            .expect("tooltip semantics present");
23045        assert!(
23046            (tooltip.bounds.max_x() - trigger.max_x()).abs() < 0.01,
23047            "end-aligned tooltip should share the trigger's trailing edge: trigger={trigger:?}, tooltip={:?}",
23048            tooltip.bounds
23049        );
23050        Ok(())
23051    }
23052
23053    #[test]
23054    fn tooltip_text_visual_center_matches_padded_bubble_center() -> Result<(), String> {
23055        let theme = DefaultTheme::default();
23056        let tooltip_text = "Quick access to common commands";
23057        let (mut runtime, window_id) = build_runtime(
23058            crate::SizedBox::new()
23059                .size(Size::new(360.0, 160.0))
23060                .with_child(crate::Padding::all(
23061                    16.0,
23062                    crate::Tooltip::new(
23063                        tooltip_text,
23064                        crate::Button::new("Hover for shortcuts").min_width(180.0),
23065                    )
23066                    .theme(theme),
23067                )),
23068        );
23069
23070        let initial = runtime
23071            .render(window_id)
23072            .map_err(|error| error.to_string())?;
23073        let trigger = initial
23074            .semantics
23075            .iter()
23076            .find(|node| {
23077                node.role == SemanticsRole::Button
23078                    && node.name.as_deref() == Some("Hover for shortcuts")
23079            })
23080            .expect("tooltip trigger semantics present")
23081            .bounds;
23082        let hover_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
23083        runtime
23084            .handle_event(
23085                window_id,
23086                primary_pointer(PointerEventKind::Move, hover_point, false),
23087            )
23088            .map_err(|error| error.to_string())?;
23089
23090        let output = runtime
23091            .render(window_id)
23092            .map_err(|error| error.to_string())?;
23093        let tooltip = output
23094            .semantics
23095            .iter()
23096            .find(|node| {
23097                node.role == SemanticsRole::Tooltip && node.name.as_deref() == Some(tooltip_text)
23098            })
23099            .expect("tooltip semantics present");
23100        let text = text_run_for(&output, tooltip_text);
23101        let layout = TextSystem::new()
23102            .shape_text_run(&text, &FontRegistry::new())
23103            .expect("tooltip text should shape");
23104        let line = layout
23105            .lines()
23106            .first()
23107            .expect("tooltip text should contain one line");
23108        let actual_visual_center =
23109            text.rect.y() + line.baseline + optical_visual_center(layout.measurement());
23110        let text_slot = super::inset_rect(tooltip.bounds, theme.metrics.tooltip_padding);
23111
23112        assert!((actual_visual_center - super::rect_center(text_slot).y).abs() < 0.75);
23113        Ok(())
23114    }
23115
23116    #[test]
23117    fn tooltip_text_preserves_tall_measurement_in_padded_bubble() -> Result<(), String> {
23118        let mut theme = DefaultTheme::default();
23119        theme.text.sm = ThemeTextToken {
23120            size: 28.0,
23121            line_height: 10.0,
23122        };
23123        theme.sync_derived_fields();
23124        let tooltip_text = "Quick commands";
23125        let (mut runtime, window_id) = build_runtime(
23126            crate::SizedBox::new()
23127                .size(Size::new(360.0, 160.0))
23128                .with_child(crate::Padding::all(
23129                    16.0,
23130                    crate::Tooltip::new(
23131                        tooltip_text,
23132                        crate::Button::new("Hover for shortcuts").min_width(180.0),
23133                    )
23134                    .theme(theme),
23135                )),
23136        );
23137
23138        let initial = runtime
23139            .render(window_id)
23140            .map_err(|error| error.to_string())?;
23141        let trigger = initial
23142            .semantics
23143            .iter()
23144            .find(|node| {
23145                node.role == SemanticsRole::Button
23146                    && node.name.as_deref() == Some("Hover for shortcuts")
23147            })
23148            .expect("tooltip trigger semantics present")
23149            .bounds;
23150        let hover_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
23151        runtime
23152            .handle_event(
23153                window_id,
23154                primary_pointer(PointerEventKind::Move, hover_point, false),
23155            )
23156            .map_err(|error| error.to_string())?;
23157
23158        let output = runtime
23159            .render(window_id)
23160            .map_err(|error| error.to_string())?;
23161        let tooltip = output
23162            .semantics
23163            .iter()
23164            .find(|node| {
23165                node.role == SemanticsRole::Tooltip && node.name.as_deref() == Some(tooltip_text)
23166            })
23167            .expect("tooltip semantics present");
23168        let text = text_run_for(&output, tooltip_text);
23169        let layout = TextSystem::new()
23170            .shape_text_run(&text, &FontRegistry::new())
23171            .expect("tooltip text should shape");
23172        let text_slot = super::inset_rect(tooltip.bounds, theme.metrics.tooltip_padding);
23173
23174        assert_text_run_uses_token(&text, theme.text.sm);
23175        assert!(text.rect.height() >= layout.measurement().height - 0.01);
23176        assert!(text.rect.height() > text.style.line_height);
23177        assert!(
23178            (text_run_visual_center(&text) - super::rect_center(text_slot).y).abs() < 0.75,
23179            "tooltip text should remain visually centered in the padded bubble; rect={:?}, slot={:?}, measurement={:?}",
23180            text.rect,
23181            text_slot,
23182            layout.measurement()
23183        );
23184        Ok(())
23185    }
23186
23187    #[test]
23188    fn tooltip_reveal_animation_updates_layer_properties_until_complete() -> Result<(), String> {
23189        let theme = DefaultTheme::default();
23190        let entrance_duration = theme.motion.entrance_duration();
23191
23192        let (mut runtime, window_id) = build_runtime(crate::Padding::all(
23193            16.0,
23194            crate::Tooltip::new(
23195                "Quick access to common commands",
23196                crate::Button::new("Hover for shortcuts").min_width(180.0),
23197            )
23198            .theme(theme),
23199        ));
23200
23201        let initial = runtime
23202            .render(window_id)
23203            .map_err(|error| error.to_string())?;
23204        assert!(overlay_layer_descriptor(&initial).is_none());
23205
23206        let trigger = initial
23207            .semantics
23208            .iter()
23209            .find(|node| {
23210                node.role == SemanticsRole::Button
23211                    && node.name.as_deref() == Some("Hover for shortcuts")
23212            })
23213            .expect("tooltip trigger semantics present")
23214            .bounds;
23215        let hover_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
23216        runtime
23217            .handle_event(
23218                window_id,
23219                primary_pointer(PointerEventKind::Move, hover_point, false),
23220            )
23221            .map_err(|error| error.to_string())?;
23222
23223        let start = runtime
23224            .render(window_id)
23225            .map_err(|error| error.to_string())?;
23226        let start_descriptor =
23227            overlay_layer_descriptor(&start).expect("tooltip overlay layer should appear");
23228        assert!(
23229            !start_descriptor.hit_test,
23230            "tooltip overlay should not intercept pointer hit testing"
23231        );
23232        assert_eq!(
23233            start_descriptor.properties.translation.y.signum(),
23234            -1.0,
23235            "tooltip reveal should start offset upward"
23236        );
23237        assert_eq!(
23238            start_descriptor.properties.translation.y.abs(),
23239            theme.metrics.tooltip_reveal_offset
23240        );
23241        assert_eq!(start_descriptor.properties.opacity, 0.0);
23242
23243        runtime.tick(entrance_duration * 0.5);
23244        assert!(handle_ready_events(&mut runtime)? >= 1);
23245        let mid = runtime
23246            .render(window_id)
23247            .map_err(|error| error.to_string())?;
23248        let mid_descriptor =
23249            overlay_layer_descriptor(&mid).expect("tooltip overlay layer should stay active");
23250        assert!(mid_descriptor.properties.opacity > 0.0);
23251        assert!(mid_descriptor.properties.opacity < 1.0);
23252        assert!(mid_descriptor.properties.translation.y < 0.0);
23253        assert!(
23254            mid_descriptor.properties.translation.y.abs()
23255                < start_descriptor.properties.translation.y.abs()
23256        );
23257        assert!(
23258            runtime
23259                .next_wakeup_time(window_id)
23260                .map_err(|error| error.to_string())?
23261                .is_some()
23262        );
23263
23264        runtime.tick(entrance_duration);
23265        assert!(handle_ready_events(&mut runtime)? >= 1);
23266        let settled = runtime
23267            .render(window_id)
23268            .map_err(|error| error.to_string())?;
23269        let settled_descriptor =
23270            overlay_layer_descriptor(&settled).expect("tooltip overlay layer should still exist");
23271        assert_eq!(settled_descriptor.properties.opacity, 1.0);
23272        assert_eq!(settled_descriptor.properties.translation.y, 0.0);
23273        assert_eq!(
23274            runtime
23275                .next_wakeup_time(window_id)
23276                .map_err(|error| error.to_string())?,
23277            None
23278        );
23279
23280        Ok(())
23281    }
23282
23283    #[test]
23284    fn popover_open_animation_stops_requesting_frames_after_completion() -> Result<(), String> {
23285        let theme = slow_normal_motion_theme();
23286        let entrance_duration = theme.motion.entrance_duration();
23287
23288        let content = Rc::new(RefCell::new(PanelCounters::default()));
23289        let (mut runtime, window_id) = build_runtime(crate::Padding::all(
23290            16.0,
23291            Popover::new(
23292                "Inline inspector",
23293                crate::Button::new("Open inspector").min_width(180.0),
23294                SpyPanel::new("popover-content", Rc::clone(&content)),
23295            )
23296            .theme(theme),
23297        ));
23298
23299        let closed = runtime
23300            .render(window_id)
23301            .map_err(|error| error.to_string())?;
23302        let trigger = closed
23303            .semantics
23304            .iter()
23305            .find(|node| {
23306                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Open inspector")
23307            })
23308            .expect("popover trigger semantics present")
23309            .bounds;
23310        assert_eq!(content.borrow().paint, 0);
23311
23312        let press_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
23313        runtime
23314            .handle_event(
23315                window_id,
23316                primary_pointer(PointerEventKind::Down, press_point, true),
23317            )
23318            .map_err(|error| error.to_string())?;
23319
23320        let opened = runtime
23321            .render(window_id)
23322            .map_err(|error| error.to_string())?;
23323        let open_descriptor =
23324            overlay_layer_descriptor(&opened).expect("popover overlay layer should appear");
23325        assert_eq!(content.borrow().paint, 1);
23326        assert_eq!(open_descriptor.properties.opacity, 0.0);
23327        assert!(open_descriptor.properties.translation.y < 0.0);
23328
23329        runtime.tick(entrance_duration * 0.5);
23330        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23331        let mid = runtime
23332            .render(window_id)
23333            .map_err(|error| error.to_string())?;
23334        let mid_descriptor =
23335            overlay_layer_descriptor(&mid).expect("popover overlay layer should stay active");
23336        assert!(mid_descriptor.properties.opacity > 0.0);
23337        assert!(mid_descriptor.properties.opacity < 1.0);
23338        assert!(mid_descriptor.properties.translation.y < 0.0);
23339        assert_eq!(
23340            content.borrow().paint,
23341            1,
23342            "popover content should stay retained while only layer properties change"
23343        );
23344        assert!(
23345            runtime
23346                .next_wakeup_time(window_id)
23347                .map_err(|error| error.to_string())?
23348                .is_some()
23349        );
23350
23351        runtime.tick(entrance_duration);
23352        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23353        let settled = runtime
23354            .render(window_id)
23355            .map_err(|error| error.to_string())?;
23356        let settled_descriptor =
23357            overlay_layer_descriptor(&settled).expect("popover overlay layer should remain open");
23358        assert_eq!(settled_descriptor.properties.opacity, 1.0);
23359        assert_eq!(settled_descriptor.properties.translation.y, 0.0);
23360        assert_eq!(
23361            content.borrow().paint,
23362            1,
23363            "popover content should not repaint on retained-only animation frames"
23364        );
23365        assert_eq!(
23366            runtime
23367                .next_wakeup_time(window_id)
23368                .map_err(|error| error.to_string())?,
23369            None
23370        );
23371
23372        Ok(())
23373    }
23374
23375    #[test]
23376    fn popover_focus_ring_animates_without_repainting_retained_content() -> Result<(), String> {
23377        let theme = DefaultTheme::default();
23378        let entrance_duration = theme.motion.entrance_duration();
23379        let focus_duration = theme.motion.focus_duration();
23380
23381        let content = Rc::new(RefCell::new(PanelCounters::default()));
23382        let (mut runtime, window_id) = build_runtime(crate::Padding::all(
23383            16.0,
23384            Popover::new(
23385                "Inline inspector",
23386                crate::Button::new("Open inspector").min_width(180.0),
23387                SpyPanel::new("popover-content", Rc::clone(&content)),
23388            )
23389            .theme(theme),
23390        ));
23391
23392        let closed = runtime
23393            .render(window_id)
23394            .map_err(|error| error.to_string())?;
23395        let trigger = closed
23396            .semantics
23397            .iter()
23398            .find(|node| {
23399                node.role == SemanticsRole::Button && node.name.as_deref() == Some("Open inspector")
23400            })
23401            .expect("popover trigger semantics present")
23402            .bounds;
23403        assert_eq!(content.borrow().paint, 0);
23404
23405        let press_point = Point::new(trigger.x() + 12.0, trigger.y() + (trigger.height() * 0.5));
23406        runtime
23407            .handle_event(
23408                window_id,
23409                primary_pointer(PointerEventKind::Down, press_point, true),
23410            )
23411            .map_err(|error| error.to_string())?;
23412
23413        let opened = runtime
23414            .render(window_id)
23415            .map_err(|error| error.to_string())?;
23416        let open_descriptor =
23417            overlay_layer_descriptor(&opened).expect("popover overlay layer should appear");
23418        assert!(open_descriptor.hit_test);
23419        let open_focus_layers = non_hit_test_layer_descriptors(&opened);
23420        assert_eq!(
23421            open_focus_layers.len(),
23422            1,
23423            "popover focus chrome should be the only non-hit-test layer"
23424        );
23425        assert_eq!(
23426            open_focus_layers[0].composition_mode,
23427            LayerCompositionMode::Normal
23428        );
23429        assert_eq!(content.borrow().paint, 1);
23430
23431        runtime.tick(focus_duration * 0.5);
23432        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23433        let mid_focus = runtime
23434            .render(window_id)
23435            .map_err(|error| error.to_string())?;
23436        assert!(
23437            !contains_approx_color(&solid_stroke_colors(&mid_focus), theme.palette.focus_ring),
23438            "popover focus ring should not snap to the settled focus color"
23439        );
23440        assert_eq!(
23441            content.borrow().paint,
23442            1,
23443            "popover content should stay retained while focus chrome repaints"
23444        );
23445
23446        runtime.tick(entrance_duration.max(focus_duration) + 0.01);
23447        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23448        let settled_focus = runtime
23449            .render(window_id)
23450            .map_err(|error| error.to_string())?;
23451        let settled_strokes = solid_stroke_colors(&settled_focus);
23452        assert!(
23453            contains_approx_color(&settled_strokes, theme.palette.focus_ring),
23454            "popover focus ring should settle to the theme focus color; strokes={settled_strokes:?}"
23455        );
23456        assert_eq!(
23457            content.borrow().paint,
23458            1,
23459            "popover content should not repaint on focus-only animation frames"
23460        );
23461        assert_eq!(
23462            runtime
23463                .next_wakeup_time(window_id)
23464                .map_err(|error| error.to_string())?,
23465            None
23466        );
23467
23468        Ok(())
23469    }
23470
23471    #[test]
23472    fn popover_arrival_effect_obeys_hdr_theme_mode() {
23473        let mut disabled_theme = DefaultTheme::default();
23474        disabled_theme.hdr.mode = HdrThemeMode::Disabled;
23475        disabled_theme.hdr.policy.max_large_area_lift = 1.12;
23476        disabled_theme.hdr.color_roles.surface_elevated =
23477            SemanticColorToken::from_sdr(disabled_theme.palette.surface_raised)
23478                .with_hdr(Color::linear_display_p3(1.30, 1.08, 1.05, 1.0));
23479
23480        let mut disabled = Popover::new(
23481            "Options",
23482            crate::Button::new("Open"),
23483            crate::Label::new("Popover body"),
23484        )
23485        .theme(disabled_theme);
23486        disabled.open = true;
23487        {
23488            let mut state = disabled.state.borrow_mut();
23489            state.reveal = super::AnimatedScalar::new(1.0);
23490            state.arrival_active = true;
23491        }
23492        let disabled_visuals = disabled.state.borrow().resolved_visuals();
23493
23494        assert_eq!(
23495            disabled_visuals.background,
23496            disabled_theme.palette.surface_raised
23497        );
23498        assert!(disabled_visuals.surface_style.is_none());
23499        assert!(disabled_visuals.arrival_effect.is_none());
23500
23501        let (mut disabled_runtime, disabled_window) = build_runtime(
23502            Popover::new(
23503                "Options",
23504                crate::Button::new("Open"),
23505                crate::Label::new("Popover body"),
23506            )
23507            .theme(disabled_theme),
23508        );
23509        let _ = disabled_runtime.render(disabled_window).unwrap();
23510        disabled_runtime
23511            .handle_event(
23512                disabled_window,
23513                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
23514            )
23515            .unwrap();
23516        let disabled_output = disabled_runtime.render(disabled_window).unwrap();
23517        assert!(
23518            !solid_fill_colors(&disabled_output)
23519                .iter()
23520                .any(|color| color.alpha < 1.0)
23521        );
23522
23523        let mut hdr_theme = disabled_theme;
23524        hdr_theme.hdr.mode = HdrThemeMode::ConstrainedHdr;
23525        hdr_theme.hdr.color_roles.surface_elevated =
23526            SemanticColorToken::from_sdr(hdr_theme.palette.surface_raised)
23527                .with_hdr(Color::linear_display_p3(1.30, 1.08, 1.05, 1.0));
23528
23529        let mut hdr = Popover::new(
23530            "Options",
23531            crate::Button::new("Open"),
23532            crate::Label::new("Popover body"),
23533        )
23534        .theme(hdr_theme);
23535        hdr.open = true;
23536        {
23537            let mut state = hdr.state.borrow_mut();
23538            state.reveal = super::AnimatedScalar::new(1.0);
23539            state.arrival_active = true;
23540        }
23541        let hdr_visuals = hdr.state.borrow().resolved_visuals();
23542        let surface_style = hdr_visuals
23543            .surface_style
23544            .expect("hdr surface style present");
23545        let arrival_effect = hdr_visuals
23546            .arrival_effect
23547            .expect("pulse arrival effect present");
23548
23549        assert_eq!(hdr_visuals.background, surface_style.color);
23550        assert!(surface_style.color.red <= hdr_theme.hdr.policy.max_large_area_lift);
23551        assert_ne!(hdr_visuals.background, hdr_theme.palette.surface_raised);
23552        assert!(arrival_effect.intensity > 0.0);
23553        assert!(arrival_effect.speed > 0.0);
23554
23555        let (mut runtime, window_id) = build_runtime(
23556            Popover::new(
23557                "Options",
23558                crate::Button::new("Open"),
23559                crate::Label::new("Popover body"),
23560            )
23561            .theme(hdr_theme),
23562        );
23563        let _ = runtime.render(window_id).unwrap();
23564        runtime
23565            .handle_event(
23566                window_id,
23567                primary_pointer(PointerEventKind::Down, Point::new(12.0, 12.0), true),
23568            )
23569            .unwrap();
23570        let arrival_output = runtime.render(window_id).unwrap();
23571        assert!(
23572            solid_fill_colors(&arrival_output)
23573                .iter()
23574                .any(|color| color.alpha < 1.0)
23575        );
23576
23577        runtime.tick(1.0);
23578        for (ready_window, event) in runtime.drain_ready_events() {
23579            runtime.handle_event(ready_window, event).unwrap();
23580        }
23581        let settled_output = runtime.render(window_id).unwrap();
23582        assert!(
23583            !solid_fill_colors(&settled_output)
23584                .iter()
23585                .any(|color| color.alpha < 1.0)
23586        );
23587    }
23588
23589    #[test]
23590    fn open_popover_resolves_to_nearest_stack_host_and_tracks_owner_surface() {
23591        let (mut runtime, window_id) = build_runtime(
23592            FloatingStack::new().with_window(
23593                sui_core::Rect::new(24.0, 24.0, 240.0, 160.0),
23594                crate::Padding::all(
23595                    16.0,
23596                    Popover::new(
23597                        "Options",
23598                        crate::Button::new("Open"),
23599                        crate::Label::new("Popover body"),
23600                    )
23601                    .open(true),
23602                ),
23603            ),
23604        );
23605
23606        let output = runtime.render(window_id).unwrap();
23607        let graph = runtime.widget_graph(window_id).unwrap();
23608        let owner = overlay_layer_owner(&output).expect("popover layer owner present");
23609        let descriptor =
23610            overlay_layer_descriptor(&output).expect("popover layer descriptor present");
23611        let node = graph
23612            .nodes
23613            .iter()
23614            .find(|node| node.id == owner)
23615            .expect("popover graph node present");
23616        let host = graph
23617            .stack_hosts
23618            .iter()
23619            .find(|host| host.host == graph.root)
23620            .expect("root stack host present");
23621
23622        assert_eq!(node.stack_host, graph.root);
23623        assert_eq!(node.stack_surface, owner);
23624        assert_eq!(node.transient_owner_surface, Some(host.surfaces[0]));
23625        assert_eq!(host.surfaces.last().copied(), Some(owner));
23626        assert_eq!(descriptor.stack_host, graph.root);
23627        assert_eq!(descriptor.transient_owner_surface, Some(host.surfaces[0]));
23628        assert!(descriptor.is_stack_surface);
23629    }
23630
23631    #[test]
23632    fn modal_dialog_uses_direct_effect_layer_metadata() {
23633        let output = render(
23634            crate::SizedBox::new()
23635                .size(Size::new(640.0, 420.0))
23636                .with_child(Dialog::new(
23637                    "Confirm",
23638                    crate::Label::new("Apply the change?"),
23639                )),
23640        );
23641
23642        let dialog = output
23643            .semantics
23644            .iter()
23645            .find(|node| node.role == SemanticsRole::Dialog)
23646            .expect("dialog semantics present");
23647        let descriptor =
23648            layer_descriptor_for(&output, dialog.id).expect("dialog layer descriptor present");
23649
23650        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Effect);
23651        assert!(
23652            solid_fill_colors(&output).contains(&DefaultTheme::default().surfaces.overlay_scrim)
23653        );
23654    }
23655
23656    #[test]
23657    fn modal_dialog_entrance_uses_theme_motion_effect_layer_properties() -> Result<(), String> {
23658        let theme = slow_normal_motion_theme();
23659        let duration = theme.motion.entrance_duration();
23660        let (mut runtime, window_id) = build_runtime(
23661            crate::SizedBox::new()
23662                .size(Size::new(640.0, 420.0))
23663                .with_child(
23664                    Dialog::new("Confirm", crate::Label::new("Apply the change?")).theme(theme),
23665                ),
23666        );
23667
23668        let start = runtime
23669            .render(window_id)
23670            .map_err(|error| error.to_string())?;
23671        let dialog = start
23672            .semantics
23673            .iter()
23674            .find(|node| node.role == SemanticsRole::Dialog)
23675            .expect("dialog semantics present");
23676        let start_descriptor =
23677            layer_descriptor_for(&start, dialog.id).expect("dialog layer descriptor present");
23678        assert_eq!(
23679            start_descriptor.composition_mode,
23680            LayerCompositionMode::Effect
23681        );
23682        assert_eq!(start_descriptor.properties.opacity, 0.0);
23683        assert_eq!(start_descriptor.properties.translation, Vector::ZERO);
23684        assert!(
23685            runtime
23686                .next_wakeup_time(window_id)
23687                .map_err(|error| error.to_string())?
23688                .is_some()
23689        );
23690
23691        runtime.tick(duration * 0.5);
23692        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23693        let mid = runtime
23694            .render(window_id)
23695            .map_err(|error| error.to_string())?;
23696        let mid_descriptor =
23697            layer_descriptor_for(&mid, dialog.id).expect("dialog layer descriptor still present");
23698        assert!(mid_descriptor.properties.opacity > 0.0);
23699        assert!(mid_descriptor.properties.opacity < 1.0);
23700        assert_eq!(mid_descriptor.properties.translation, Vector::ZERO);
23701
23702        runtime.tick(duration);
23703        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23704        let settled = runtime
23705            .render(window_id)
23706            .map_err(|error| error.to_string())?;
23707        let settled_descriptor = layer_descriptor_for(&settled, dialog.id)
23708            .expect("dialog layer descriptor still present after settling");
23709        assert_eq!(settled_descriptor.properties.opacity, 1.0);
23710        assert_eq!(settled_descriptor.properties.translation, Vector::ZERO);
23711        assert_eq!(
23712            runtime
23713                .next_wakeup_time(window_id)
23714                .map_err(|error| error.to_string())?,
23715            None
23716        );
23717        Ok(())
23718    }
23719
23720    #[test]
23721    fn dialog_entrance_animates_without_repainting_retained_body() -> Result<(), String> {
23722        let theme = slow_normal_motion_theme();
23723        let entrance_duration = theme.motion.entrance_duration();
23724        let body = Rc::new(RefCell::new(PanelCounters::default()));
23725        let (mut runtime, window_id) = build_runtime(
23726            crate::SizedBox::new()
23727                .size(Size::new(640.0, 420.0))
23728                .with_child(
23729                    Dialog::new("Confirm", SpyPanel::new("dialog-body", Rc::clone(&body)))
23730                        .theme(theme),
23731                ),
23732        );
23733
23734        let start = runtime
23735            .render(window_id)
23736            .map_err(|error| error.to_string())?;
23737        let dialog = start
23738            .semantics
23739            .iter()
23740            .find(|node| node.role == SemanticsRole::Dialog)
23741            .expect("dialog semantics present");
23742        let start_descriptor =
23743            layer_descriptor_for(&start, dialog.id).expect("dialog layer descriptor present");
23744        assert_eq!(start_descriptor.properties.opacity, 0.0);
23745        assert_eq!(body.borrow().paint, 1);
23746
23747        runtime.tick(entrance_duration * 0.5);
23748        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23749        let mid = runtime
23750            .render(window_id)
23751            .map_err(|error| error.to_string())?;
23752        let mid_descriptor =
23753            layer_descriptor_for(&mid, dialog.id).expect("dialog layer descriptor still present");
23754        assert!(mid_descriptor.properties.opacity > 0.0);
23755        assert!(mid_descriptor.properties.opacity < 1.0);
23756        assert_eq!(
23757            body.borrow().paint,
23758            1,
23759            "dialog body should stay retained while entrance only changes layer properties"
23760        );
23761
23762        runtime.tick(entrance_duration + 0.01);
23763        assert_eq!(handle_ready_events(&mut runtime)?, 1);
23764        let settled = runtime
23765            .render(window_id)
23766            .map_err(|error| error.to_string())?;
23767        let settled_descriptor = layer_descriptor_for(&settled, dialog.id)
23768            .expect("dialog layer descriptor still present after settling");
23769        assert_eq!(
23770            settled_descriptor.properties.opacity, 1.0,
23771            "dialog entrance should settle to full layer opacity"
23772        );
23773        assert_eq!(
23774            body.borrow().paint,
23775            1,
23776            "dialog body should not repaint on retained-only entrance frames"
23777        );
23778        assert_eq!(
23779            runtime
23780                .next_wakeup_time(window_id)
23781                .map_err(|error| error.to_string())?,
23782            None
23783        );
23784
23785        Ok(())
23786    }
23787
23788    #[test]
23789    fn non_modal_dialog_entrance_uses_overlay_translation() {
23790        let output = render(
23791            crate::SizedBox::new()
23792                .size(Size::new(640.0, 420.0))
23793                .with_child(
23794                    Dialog::new("Inspector", crate::Label::new("Layer settings")).modal(false),
23795                ),
23796        );
23797
23798        let dialog = output
23799            .semantics
23800            .iter()
23801            .find(|node| node.role == SemanticsRole::Dialog)
23802            .expect("dialog semantics present");
23803        let descriptor =
23804            layer_descriptor_for(&output, dialog.id).expect("dialog layer descriptor present");
23805
23806        assert_eq!(descriptor.composition_mode, LayerCompositionMode::Overlay);
23807        assert_eq!(descriptor.properties.opacity, 0.0);
23808        assert!(descriptor.properties.translation.y > 0.0);
23809    }
23810
23811    #[test]
23812    fn bottom_sheet_uses_requested_height_and_bottom_edge() {
23813        let output = render(
23814            crate::SizedBox::new()
23815                .size(Size::new(640.0, 480.0))
23816                .with_child(
23817                    BottomSheet::new("Filters", crate::Label::new("Filter options")).height(240.0),
23818                ),
23819        );
23820
23821        let sheet = output
23822            .semantics
23823            .iter()
23824            .find(|node| node.role == SemanticsRole::Dialog)
23825            .expect("bottom sheet semantics present");
23826        assert_eq!(sheet.name.as_deref(), Some("Filters"));
23827        assert_eq!(sheet.bounds, Rect::new(0.0, 240.0, 640.0, 240.0));
23828    }
23829
23830    #[test]
23831    fn sheet_state_presents_a_retained_bottom_sheet() {
23832        let state = SheetState::default();
23833        let (mut runtime, window_id) = build_runtime(
23834            crate::SizedBox::new()
23835                .size(Size::new(640.0, 480.0))
23836                .with_child(
23837                    BottomSheet::new("Filters", crate::Label::new("Filter options"))
23838                        .state(state.clone()),
23839                ),
23840        );
23841
23842        assert!(
23843            !runtime
23844                .render(window_id)
23845                .unwrap()
23846                .semantics
23847                .iter()
23848                .any(|node| node.role == SemanticsRole::Dialog)
23849        );
23850        state.show();
23851        assert!(
23852            runtime
23853                .render(window_id)
23854                .unwrap()
23855                .semantics
23856                .iter()
23857                .any(|node| node.name.as_deref() == Some("Filters"))
23858        );
23859    }
23860
23861    fn sui_widgets_fixture<A, B>(top: A, bottom: B) -> impl Widget
23862    where
23863        A: Widget + 'static,
23864        B: Widget + 'static,
23865    {
23866        crate::Stack::vertical()
23867            .spacing(12.0)
23868            .with_child(top)
23869            .with_child(bottom)
23870    }
23871}