Skip to main content

sui_widgets/composites/
forms.rs

1use crate::ControlMetrics;
2use crate::DefaultTheme;
3use crate::IconGlyph;
4use crate::SemanticTone;
5use crate::composites::indicators::{
6    draw_control_frame, inset_rect, measure_text, mix_color, physical_pixels, rounded_rect_path,
7    text_token_style,
8};
9use crate::composites::popups::AnimatedScalar;
10use crate::composites::surfaces::SurfaceElevation;
11use crate::controls::draw_icon_glyph;
12use crate::paint_theme_shadow;
13use crate::text_align::paint_aligned_text;
14use crate::text_align::paint_single_line_aligned_text;
15use sui_core::Color;
16use sui_core::Event;
17use sui_core::KeyState;
18use sui_core::PathBuilder;
19use sui_core::Point;
20use sui_core::PointerButton;
21use sui_core::PointerEventKind;
22use sui_core::Rect;
23use sui_core::SemanticsAction;
24use sui_core::SemanticsNode;
25use sui_core::SemanticsRole;
26use sui_core::SemanticsValue;
27use sui_core::Size;
28use sui_core::WakeEvent;
29use sui_core::WidgetId;
30use sui_layout::Constraints;
31use sui_layout::Padding as Insets;
32use sui_runtime::ArrangeCtx;
33use sui_runtime::EventCtx;
34use sui_runtime::LayerOptions;
35use sui_runtime::MeasureCtx;
36use sui_runtime::PaintBoundaryMode;
37use sui_runtime::PaintCtx;
38use sui_runtime::SemanticsCtx;
39use sui_runtime::SingleChild;
40use sui_runtime::Widget;
41use sui_runtime::WidgetChildren;
42use sui_runtime::WidgetPodMutVisitor;
43use sui_runtime::WidgetPodVisitor;
44use sui_scene::StrokeStyle;
45use sui_text::FontWeight;
46use sui_text::TextMeasurement;
47use sui_text::TextStyle;
48
49pub struct ActionCard {
50    pub(super) theme: Box<DefaultTheme>,
51    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
52    pub(super) title: String,
53    pub(super) description: String,
54    pub(super) icon: Option<IconGlyph>,
55    pub(super) tone: SemanticTone,
56    pub(super) accent: Option<Color>,
57    pub(super) padding: Option<Insets>,
58    pub(super) min_width: Option<f32>,
59    pub(super) min_height: Option<f32>,
60    pub(super) hovered: bool,
61    pub(super) pressed: bool,
62    pub(super) hover_animation: AnimatedScalar,
63    pub(super) press_animation: AnimatedScalar,
64    pub(super) focus_animation: AnimatedScalar,
65    pub(super) title_measurement: Option<TextMeasurement>,
66    pub(super) description_measurement: Option<TextMeasurement>,
67    pub(super) enabled: bool,
68    pub(super) enabled_reader: Option<Box<dyn Fn() -> bool>>,
69    pub(super) on_press: Option<Box<dyn FnMut()>>,
70    pub(super) on_press_with_ctx: Option<Box<dyn FnMut(&mut EventCtx)>>,
71}
72
73impl ActionCard {
74    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
75        Self {
76            theme: Box::new(DefaultTheme::default()),
77            theme_reader: None,
78            title: title.into(),
79            description: description.into(),
80            icon: None,
81            tone: SemanticTone::Accent,
82            accent: None,
83            padding: None,
84            min_width: None,
85            min_height: None,
86            hovered: false,
87            pressed: false,
88            hover_animation: AnimatedScalar::new(0.0),
89            press_animation: AnimatedScalar::new(0.0),
90            focus_animation: AnimatedScalar::new(0.0),
91            title_measurement: None,
92            description_measurement: None,
93            enabled: true,
94            enabled_reader: None,
95            on_press: None,
96            on_press_with_ctx: None,
97        }
98    }
99
100    pub fn theme(mut self, theme: DefaultTheme) -> Self {
101        self.theme = Box::new(theme);
102        self.theme_reader = None;
103        self
104    }
105
106    pub fn theme_when<F>(mut self, theme: F) -> Self
107    where
108        F: Fn() -> DefaultTheme + 'static,
109    {
110        self.theme_reader = Some(Box::new(theme));
111        self
112    }
113
114    pub fn icon(mut self, icon: IconGlyph) -> Self {
115        self.icon = Some(icon);
116        self
117    }
118
119    pub fn without_icon(mut self) -> Self {
120        self.icon = None;
121        self
122    }
123
124    pub fn accent(mut self, accent: Color) -> Self {
125        self.accent = Some(accent);
126        self
127    }
128
129    pub fn tone(mut self, tone: SemanticTone) -> Self {
130        self.tone = tone;
131        self
132    }
133
134    pub fn padding(mut self, padding: Insets) -> Self {
135        self.padding = Some(padding);
136        self
137    }
138
139    pub fn min_width(mut self, width: f32) -> Self {
140        self.min_width = Some(width.max(0.0));
141        self
142    }
143
144    pub fn min_height(mut self, height: f32) -> Self {
145        self.min_height = Some(height.max(0.0));
146        self
147    }
148
149    pub fn enabled(mut self, enabled: bool) -> Self {
150        self.enabled = enabled;
151        self.enabled_reader = None;
152        self
153    }
154
155    pub fn enabled_when<F>(mut self, enabled: F) -> Self
156    where
157        F: Fn() -> bool + 'static,
158    {
159        self.enabled_reader = Some(Box::new(enabled));
160        self
161    }
162
163    pub fn on_press<F>(mut self, on_press: F) -> Self
164    where
165        F: FnMut() + 'static,
166    {
167        self.on_press = Some(Box::new(on_press));
168        self
169    }
170
171    pub fn on_press_with_ctx<F>(mut self, on_press: F) -> Self
172    where
173        F: FnMut(&mut EventCtx) + 'static,
174    {
175        self.on_press_with_ctx = Some(Box::new(on_press));
176        self
177    }
178
179    pub(super) fn is_enabled(&self) -> bool {
180        self.enabled_reader
181            .as_ref()
182            .map(|enabled| enabled())
183            .unwrap_or(self.enabled)
184    }
185
186    pub(super) fn resolved_theme(&self) -> DefaultTheme {
187        self.theme_reader
188            .as_ref()
189            .map(|theme| theme())
190            .unwrap_or(*self.theme)
191    }
192
193    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
194        self.padding.unwrap_or(metrics.action_card_padding)
195    }
196
197    pub(super) fn resolved_min_width(&self, metrics: ControlMetrics) -> f32 {
198        self.min_width.unwrap_or(metrics.action_card_min_width)
199    }
200
201    pub(super) fn resolved_min_height(&self, metrics: ControlMetrics) -> f32 {
202        self.min_height.unwrap_or(metrics.action_card_min_height)
203    }
204
205    pub(super) fn activate(&mut self, ctx: &mut EventCtx) {
206        if !self.is_enabled() {
207            return;
208        }
209        if let Some(on_press) = &mut self.on_press {
210            on_press();
211        }
212        if let Some(on_press) = &mut self.on_press_with_ctx {
213            on_press(ctx);
214        }
215    }
216
217    pub(super) fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
218        if self.hovered == hovered {
219            return;
220        }
221        let theme = self.resolved_theme();
222        self.hovered = hovered;
223        set_action_card_hover_animation_target(
224            &mut self.hover_animation,
225            hovered as u8 as f32,
226            &theme,
227            ctx,
228        );
229        ctx.request_paint();
230        ctx.request_semantics();
231    }
232
233    pub(super) fn advance_animations(&mut self, time: f64) -> bool {
234        self.hover_animation.advance(time)
235            | self.press_animation.advance(time)
236            | self.focus_animation.advance(time)
237    }
238
239    pub(super) fn clear_transient_state_for_hidden_bounds(&mut self, ctx: &mut ArrangeCtx) {
240        if !self.hovered && !self.pressed && !self.focus_animation.is_presented() {
241            return;
242        }
243
244        self.hovered = false;
245        self.pressed = false;
246        self.hover_animation = AnimatedScalar::new(0.0);
247        self.press_animation = AnimatedScalar::new(0.0);
248        self.focus_animation = AnimatedScalar::new(0.0);
249        ctx.request_paint();
250        ctx.request_semantics();
251    }
252
253    pub(super) fn resolved_title_style(&self) -> TextStyle {
254        let theme = self.resolved_theme();
255        TextStyle {
256            weight: FontWeight::SEMIBOLD,
257            ..text_token_style(&theme, theme.text.base, theme.palette.text)
258        }
259    }
260
261    pub(super) fn resolved_description_style(&self) -> TextStyle {
262        let theme = self.resolved_theme();
263        text_token_style(&theme, theme.text.sm, theme.palette.text_muted)
264    }
265
266    pub(super) fn content_rect(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
267        inset_rect(bounds, self.resolved_padding(metrics))
268    }
269
270    pub(super) fn text_bounds(&self, bounds: Rect, metrics: ControlMetrics) -> Rect {
271        let content = self.content_rect(bounds, metrics);
272        let icon_extent = self
273            .icon
274            .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
275            .unwrap_or(0.0);
276        let trailing = metrics.action_card_trailing_gap;
277        Rect::new(
278            content.x() + icon_extent,
279            content.y(),
280            (content.width() - icon_extent - trailing).max(0.0),
281            content.height(),
282        )
283    }
284}
285
286impl Widget for ActionCard {
287    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
288        if !self.is_enabled() {
289            if self.hovered || self.pressed {
290                let theme = self.resolved_theme();
291                self.hovered = false;
292                self.pressed = false;
293                set_action_card_hover_animation_target(&mut self.hover_animation, 0.0, &theme, ctx);
294                set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
295                ctx.request_paint();
296                ctx.request_semantics();
297            }
298            return;
299        }
300
301        match event {
302            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
303                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
304            }
305            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
306                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
307            }
308            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
309                self.set_hovered(false, ctx);
310            }
311            Event::Pointer(pointer)
312                if pointer.kind == PointerEventKind::Down
313                    && pointer.button == Some(PointerButton::Primary) =>
314            {
315                let theme = self.resolved_theme();
316                self.pressed = true;
317                self.hovered = true;
318                set_action_card_hover_animation_target(&mut self.hover_animation, 1.0, &theme, ctx);
319                set_action_card_press_animation_target(&mut self.press_animation, 1.0, &theme, ctx);
320                ctx.request_pointer_capture(pointer.pointer_id);
321                ctx.request_focus();
322                ctx.request_paint();
323                ctx.request_semantics();
324                ctx.set_handled();
325            }
326            Event::Pointer(pointer)
327                if pointer.kind == PointerEventKind::Up
328                    && pointer.button == Some(PointerButton::Primary) =>
329            {
330                let theme = self.resolved_theme();
331                let hovered = ctx.bounds().contains(pointer.position);
332                let activate = self.pressed && hovered;
333                self.pressed = false;
334                self.hovered = hovered;
335                set_action_card_hover_animation_target(
336                    &mut self.hover_animation,
337                    hovered as u8 as f32,
338                    &theme,
339                    ctx,
340                );
341                set_action_card_press_animation_target(&mut self.press_animation, 0.0, &theme, ctx);
342                ctx.release_pointer_capture(pointer.pointer_id);
343                if activate {
344                    self.activate(ctx);
345                }
346                ctx.request_paint();
347                ctx.request_semantics();
348                ctx.set_handled();
349            }
350            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
351                if self.pressed {
352                    let theme = self.resolved_theme();
353                    self.pressed = false;
354                    self.hovered = false;
355                    set_action_card_hover_animation_target(
356                        &mut self.hover_animation,
357                        0.0,
358                        &theme,
359                        ctx,
360                    );
361                    set_action_card_press_animation_target(
362                        &mut self.press_animation,
363                        0.0,
364                        &theme,
365                        ctx,
366                    );
367                    ctx.release_pointer_capture(pointer.pointer_id);
368                    ctx.request_paint();
369                    ctx.request_semantics();
370                    ctx.set_handled();
371                }
372            }
373            Event::Keyboard(key)
374                if key.state == KeyState::Pressed
375                    && ctx.is_focused()
376                    && matches!(key.key.as_str(), "Enter" | " ") =>
377            {
378                self.activate(ctx);
379                ctx.request_paint();
380                ctx.request_semantics();
381                ctx.set_handled();
382            }
383            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
384                if self.advance_animations(*time) {
385                    ctx.request_animation_frame();
386                }
387                ctx.request_paint();
388            }
389            _ => {}
390        }
391    }
392
393    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
394        let theme = self.resolved_theme();
395        let metrics = theme.metrics;
396        let padding = self.resolved_padding(metrics);
397        let title_style = self.resolved_title_style();
398        let description_style = self.resolved_description_style();
399        let title = measure_text(ctx, &self.title, &title_style);
400        let description = measure_text(ctx, &self.description, &description_style);
401        self.title_measurement = Some(title);
402        self.description_measurement = Some(description);
403
404        let icon_extent = self
405            .icon
406            .map(|_| metrics.action_card_icon_box_size + metrics.action_card_icon_gap)
407            .unwrap_or(0.0);
408        let text_width = title.width.max(description.width).min(320.0);
409        let natural = Size::new(
410            self.resolved_min_width(metrics).max(
411                padding.left
412                    + icon_extent
413                    + text_width
414                    + metrics.action_card_trailing_gap
415                    + padding.right,
416            ),
417            self.resolved_min_height(metrics).max(
418                padding.top
419                    + title.height.max(title_style.line_height)
420                    + metrics.action_card_text_gap
421                    + description.height.max(description_style.line_height)
422                    + padding.bottom,
423            ),
424        );
425        constraints.clamp(natural)
426    }
427
428    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
429        if bounds.width() <= 0.0 || bounds.height() <= 0.0 {
430            self.clear_transient_state_for_hidden_bounds(ctx);
431        }
432    }
433
434    fn paint(&self, ctx: &mut PaintCtx) {
435        let theme = self.resolved_theme();
436        let palette = theme.palette;
437        let metrics = theme.metrics;
438        let enabled = self.is_enabled();
439        let hover = if enabled {
440            self.hover_animation.value
441        } else {
442            0.0
443        };
444        let press = if enabled {
445            self.press_animation.value
446        } else {
447            0.0
448        };
449        let accent = self
450            .accent
451            .unwrap_or_else(|| theme.semantic_tone_color(self.tone));
452        let mut background = mix_color(palette.control, palette.control_hover, hover);
453        background = mix_color(background, palette.control_active, press * 0.55);
454        if !enabled {
455            background = mix_color(background, palette.surface, 0.68).with_alpha(0.82);
456        }
457        let border = if !enabled {
458            palette.border.with_alpha(0.55)
459        } else if ctx.is_focused() {
460            palette.border_focus
461        } else {
462            mix_color(palette.border, palette.border_hover, hover)
463        };
464
465        // Elevation shadow behind the raised card surface, drawn before the
466        // fill so the soft shadow is not clipped.
467        if enabled {
468            paint_theme_shadow(
469                ctx,
470                ctx.bounds(),
471                [metrics.corner_radius; 4],
472                &theme.shadows.box_shadow.md,
473            );
474        }
475
476        draw_control_frame(
477            ctx,
478            ctx.bounds(),
479            metrics.corner_radius,
480            metrics,
481            background,
482            border,
483            (self.focus_animation.value > AnimatedScalar::EPSILON && enabled).then_some(
484                palette
485                    .focus_ring
486                    .with_alpha(palette.focus_ring.alpha * self.focus_animation.value),
487            ),
488        );
489
490        let bounds = ctx.bounds();
491        let content = self.content_rect(bounds, metrics);
492        let accent_inset = metrics.action_card_accent_inset.min(bounds.height() * 0.5);
493        let accent_height = (bounds.height() - accent_inset * 2.0).max(0.0);
494        let accent_rail = Rect::new(
495            bounds.x(),
496            bounds.y() + accent_inset,
497            metrics.action_card_accent_width,
498            accent_height,
499        );
500        ctx.fill(
501            rounded_rect_path(accent_rail, metrics.action_card_accent_width * 0.5),
502            accent.with_alpha(0.78),
503        );
504
505        if let Some(icon) = self.icon {
506            let icon_box_size = metrics
507                .action_card_icon_box_size
508                .min(content.width())
509                .min(content.height())
510                .max(0.0);
511            let icon_box = Rect::new(
512                content.x(),
513                content.y() + ((content.height() - icon_box_size) * 0.5),
514                icon_box_size,
515                icon_box_size,
516            );
517            ctx.fill(
518                rounded_rect_path(icon_box, metrics.corner_radius),
519                mix_color(background, accent, 0.14),
520            );
521            ctx.stroke(
522                rounded_rect_path(icon_box, metrics.corner_radius),
523                accent.with_alpha(if enabled { 0.42 } else { 0.22 }),
524                StrokeStyle::new(physical_pixels(ctx, 1.0)),
525            );
526            let icon_size = metrics
527                .action_card_icon_size
528                .min(icon_box.width())
529                .min(icon_box.height())
530                .max(0.0);
531            let icon_rect = Rect::new(
532                icon_box.x() + ((icon_box.width() - icon_size) * 0.5),
533                icon_box.y() + ((icon_box.height() - icon_size) * 0.5),
534                icon_size,
535                icon_size,
536            );
537            draw_icon_glyph(
538                ctx,
539                icon,
540                icon_rect,
541                if enabled {
542                    accent
543                } else {
544                    palette.text.with_alpha(0.34)
545                },
546            );
547        }
548
549        let text_bounds = self.text_bounds(bounds, metrics);
550        let title_style = self.resolved_title_style();
551        let description_style = self.resolved_description_style();
552        let title_height = title_style.line_height.max(
553            self.title_measurement
554                .map(|measurement| measurement.height)
555                .unwrap_or(title_style.line_height),
556        );
557        let description_min_height = description_style.line_height.max(
558            self.description_measurement
559                .map(|measurement| measurement.height)
560                .unwrap_or(description_style.line_height),
561        );
562        let description_height =
563            (text_bounds.height() - title_height - metrics.action_card_text_gap)
564                .max(description_min_height)
565                .min((description_style.line_height * 2.0).max(description_min_height));
566        let text_block_height = title_height + metrics.action_card_text_gap + description_height;
567        let text_y = text_bounds.y() + ((text_bounds.height() - text_block_height) * 0.5).max(0.0);
568        let title_slot = Rect::new(text_bounds.x(), text_y, text_bounds.width(), title_height);
569        let description_slot = Rect::new(
570            text_bounds.x(),
571            title_slot.max_y() + metrics.action_card_text_gap,
572            text_bounds.width(),
573            description_height,
574        );
575        let title_paint_style = TextStyle {
576            color: if enabled {
577                palette.text
578            } else {
579                palette.text.with_alpha(0.45)
580            },
581            ..title_style
582        };
583        let description_paint_style = TextStyle {
584            color: if enabled {
585                palette.placeholder
586            } else {
587                palette.placeholder.with_alpha(0.45)
588            },
589            ..description_style
590        };
591        let description_layout = {
592            let mut layout_style = description_paint_style.clone();
593            layout_style.color = Color::WHITE;
594            ctx.shape_text(
595                self.description.clone(),
596                Size::new(
597                    description_slot.width().max(1.0),
598                    description_slot.height().max(1.0),
599                ),
600                layout_style,
601            )
602            .ok()
603        };
604        ctx.push_clip_rect(title_slot);
605        paint_aligned_text(
606            ctx,
607            title_slot,
608            &self.title,
609            &title_paint_style,
610            title_paint_style.line_height,
611            0.0,
612        );
613        ctx.pop_clip();
614        ctx.push_clip_rect(description_slot);
615        if let Some(layout) = description_layout.filter(|layout| layout.lines().len() > 1) {
616            let measurement = layout.measurement();
617            let width = measurement.width.min(description_slot.width()).max(0.0);
618            let height = description_paint_style
619                .line_height
620                .max(measurement.height)
621                .min(description_slot.height());
622            let description_rect = Rect::new(
623                description_slot.x(),
624                description_slot.y() + ((description_slot.height() - height).max(0.0) * 0.5),
625                width,
626                height,
627            );
628            ctx.draw_text_layout_with_color(
629                description_rect.origin,
630                &layout,
631                description_paint_style.color,
632            );
633        } else {
634            paint_aligned_text(
635                ctx,
636                description_slot,
637                &self.description,
638                &description_paint_style,
639                description_paint_style.line_height,
640                0.0,
641            );
642        }
643        ctx.pop_clip();
644
645        let chevron_size = metrics
646            .action_card_chevron_size
647            .min(content.width())
648            .min(content.height())
649            .max(0.0);
650        let chevron = Rect::new(
651            content.max_x() - chevron_size,
652            content.y() + ((content.height() - chevron_size) * 0.5),
653            chevron_size,
654            chevron_size,
655        );
656        draw_icon_glyph(
657            ctx,
658            IconGlyph::ChevronRight,
659            chevron,
660            if enabled {
661                mix_color(palette.placeholder, accent, hover * 0.45).with_alpha(0.74)
662            } else {
663                palette.placeholder.with_alpha(0.32)
664            },
665        );
666    }
667
668    fn layer_options(&self) -> LayerOptions {
669        // Card motion changes only this card. Retain it separately so hover,
670        // press, and focus animation do not repaint a containing grid or rebuild
671        // its other cards' text and geometry in the renderer.
672        LayerOptions {
673            paint_boundary: PaintBoundaryMode::Explicit,
674            ..LayerOptions::default()
675        }
676    }
677
678    fn semantics(&self, ctx: &mut SemanticsCtx) {
679        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Button, ctx.bounds());
680        node.name = Some(self.title.clone());
681        node.description = Some(self.description.clone());
682        node.value = Some(SemanticsValue::Text(self.description.clone()));
683        node.state.focused = ctx.is_focused();
684        node.state.hovered = self.hovered && self.is_enabled();
685        node.state.disabled = !self.is_enabled();
686        node.actions = if self.is_enabled() {
687            vec![SemanticsAction::Focus, SemanticsAction::Activate]
688        } else {
689            Vec::new()
690        };
691        ctx.push(node);
692    }
693
694    fn accepts_focus(&self) -> bool {
695        self.is_enabled()
696    }
697
698    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
699        let theme = self.resolved_theme();
700        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
701        ctx.request_paint();
702        ctx.request_semantics();
703    }
704}
705
706pub(super) fn set_animation_target(
707    animation: &mut AnimatedScalar,
708    target: f32,
709    duration: f64,
710    easing: crate::Easing,
711    ctx: &mut EventCtx,
712) -> bool {
713    animation.set_target_event(target, duration, easing, ctx)
714}
715
716pub(super) fn set_hover_animation_target(
717    animation: &mut AnimatedScalar,
718    target: f32,
719    theme: &DefaultTheme,
720    ctx: &mut EventCtx,
721) -> bool {
722    set_animation_target(
723        animation,
724        target,
725        theme.motion.hover_duration(),
726        theme.motion.hover_easing(),
727        ctx,
728    )
729}
730
731pub(super) fn set_press_animation_target(
732    animation: &mut AnimatedScalar,
733    target: f32,
734    theme: &DefaultTheme,
735    ctx: &mut EventCtx,
736) -> bool {
737    set_animation_target(
738        animation,
739        target,
740        theme.motion.press_duration(),
741        theme.motion.press_easing(),
742        ctx,
743    )
744}
745
746pub(super) fn set_focus_animation_target(
747    animation: &mut AnimatedScalar,
748    target: f32,
749    theme: &DefaultTheme,
750    ctx: &mut EventCtx,
751) -> bool {
752    set_animation_target(
753        animation,
754        target,
755        theme.motion.focus_duration(),
756        theme.motion.focus_easing(),
757        ctx,
758    )
759}
760
761pub(super) fn set_action_card_animation_target(
762    animation: &mut AnimatedScalar,
763    target: f32,
764    duration: f64,
765    easing: crate::Easing,
766    ctx: &mut EventCtx,
767) {
768    set_animation_target(animation, target, duration, easing, ctx);
769}
770
771pub(super) fn set_action_card_hover_animation_target(
772    animation: &mut AnimatedScalar,
773    target: f32,
774    theme: &DefaultTheme,
775    ctx: &mut EventCtx,
776) {
777    set_action_card_animation_target(
778        animation,
779        target,
780        theme.motion.hover_duration(),
781        theme.motion.hover_easing(),
782        ctx,
783    );
784}
785
786pub(super) fn set_action_card_press_animation_target(
787    animation: &mut AnimatedScalar,
788    target: f32,
789    theme: &DefaultTheme,
790    ctx: &mut EventCtx,
791) {
792    set_action_card_animation_target(
793        animation,
794        target,
795        theme.motion.press_duration(),
796        theme.motion.press_easing(),
797        ctx,
798    );
799}
800
801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
802pub enum PropertyRowLayout {
803    Stacked,
804    Inline,
805}
806
807#[derive(Debug, Clone, Copy, PartialEq, Eq)]
808pub(super) enum PropertyRowDefaults {
809    Property,
810    Form,
811}
812
813pub struct PropertyRow {
814    pub(super) theme: Box<DefaultTheme>,
815    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
816    pub(super) label: String,
817    pub(super) defaults: PropertyRowDefaults,
818    pub(super) layout: PropertyRowLayout,
819    pub(super) label_width: Option<f32>,
820    pub(super) control_width: Option<f32>,
821    pub(super) auto_control_width: bool,
822    pub(super) gap: Option<f32>,
823    pub(super) label_style: Option<TextStyle>,
824    pub(super) child: SingleChild,
825    pub(super) label_measurement: Option<TextMeasurement>,
826}
827
828impl PropertyRow {
829    pub fn new<W>(label: impl Into<String>, control: W) -> Self
830    where
831        W: Widget + 'static,
832    {
833        Self {
834            theme: Box::new(DefaultTheme::default()),
835            theme_reader: None,
836            label: label.into(),
837            defaults: PropertyRowDefaults::Property,
838            layout: PropertyRowLayout::Stacked,
839            label_width: None,
840            control_width: None,
841            auto_control_width: true,
842            gap: None,
843            label_style: None,
844            child: SingleChild::new(control),
845            label_measurement: None,
846        }
847    }
848
849    pub fn theme(mut self, theme: DefaultTheme) -> Self {
850        self.theme = Box::new(theme);
851        self.theme_reader = None;
852        self
853    }
854
855    pub fn theme_when<F>(mut self, theme: F) -> Self
856    where
857        F: Fn() -> DefaultTheme + 'static,
858    {
859        self.theme_reader = Some(Box::new(theme));
860        self
861    }
862
863    pub fn layout(mut self, layout: PropertyRowLayout) -> Self {
864        self.layout = layout;
865        self
866    }
867
868    pub fn stacked(self) -> Self {
869        self.layout(PropertyRowLayout::Stacked)
870    }
871
872    pub fn inline(self) -> Self {
873        self.layout(PropertyRowLayout::Inline)
874    }
875
876    pub fn label_width(mut self, width: f32) -> Self {
877        self.label_width = Some(width.max(0.0));
878        self
879    }
880
881    pub fn control_width(mut self, width: f32) -> Self {
882        self.control_width = Some(width.max(0.0));
883        self.auto_control_width = false;
884        self
885    }
886
887    pub fn auto_control_width(mut self) -> Self {
888        self.control_width = None;
889        self.auto_control_width = true;
890        self
891    }
892
893    pub fn gap(mut self, gap: f32) -> Self {
894        self.gap = Some(gap.max(0.0));
895        self
896    }
897
898    pub fn label_style(mut self, style: TextStyle) -> Self {
899        self.label_style = Some(style);
900        self
901    }
902
903    pub fn child(&self) -> &sui_runtime::WidgetPod {
904        self.child.child()
905    }
906
907    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
908        self.child.child_mut()
909    }
910
911    pub(super) fn resolved_label_style(&self) -> TextStyle {
912        let theme = self.resolved_theme();
913        self.label_style
914            .clone()
915            .unwrap_or_else(|| text_token_style(&theme, theme.text.sm, theme.palette.text_muted))
916    }
917
918    pub(super) fn resolved_theme(&self) -> DefaultTheme {
919        self.theme_reader
920            .as_ref()
921            .map(|theme| theme())
922            .unwrap_or(*self.theme)
923    }
924
925    pub(super) fn with_form_defaults(mut self) -> Self {
926        self.defaults = PropertyRowDefaults::Form;
927        self.auto_control_width = true;
928        self
929    }
930
931    pub(super) fn resolved_label_width(&self, metrics: ControlMetrics) -> f32 {
932        self.label_width.unwrap_or(match self.defaults {
933            PropertyRowDefaults::Property => metrics.property_row_label_width,
934            PropertyRowDefaults::Form => metrics.form_row_label_width,
935        })
936    }
937
938    pub(super) fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
939        self.gap.unwrap_or(match self.defaults {
940            PropertyRowDefaults::Form => metrics.form_row_gap,
941            PropertyRowDefaults::Property => match self.layout {
942                PropertyRowLayout::Stacked => metrics.property_row_stacked_gap,
943                PropertyRowLayout::Inline => metrics.property_row_inline_gap,
944            },
945        })
946    }
947
948    pub(super) fn resolved_control_width(&self, metrics: ControlMetrics) -> Option<f32> {
949        if self.auto_control_width {
950            None
951        } else {
952            self.control_width.or_else(|| {
953                matches!(self.defaults, PropertyRowDefaults::Form)
954                    .then_some(metrics.form_row_control_width)
955            })
956        }
957    }
958
959    pub(super) fn label_height(&self, style: &TextStyle) -> f32 {
960        self.label_measurement
961            .map(|measurement| measurement.height)
962            .unwrap_or(style.line_height)
963            .max(style.line_height)
964    }
965
966    pub(super) fn child_constraints(
967        &self,
968        constraints: Constraints,
969        label_extent: f32,
970        metrics: ControlMetrics,
971    ) -> Constraints {
972        let max_width = constraints.max.width;
973        let gap = self.resolved_gap(metrics);
974        let available = match self.layout {
975            PropertyRowLayout::Stacked => max_width,
976            PropertyRowLayout::Inline => {
977                if max_width.is_finite() {
978                    (max_width - label_extent - gap).max(0.0)
979                } else {
980                    f32::INFINITY
981                }
982            }
983        };
984        let width = self
985            .resolved_control_width(metrics)
986            .map(|width| width.min(available).max(0.0));
987
988        match width {
989            Some(width) => Constraints::new(
990                Size::new(width, 0.0),
991                Size::new(width, constraints.max.height),
992            ),
993            None => Constraints::new(Size::ZERO, Size::new(available, constraints.max.height)),
994        }
995    }
996
997    pub(super) fn child_width_for_bounds(
998        &self,
999        bounds: Rect,
1000        label_extent: f32,
1001        metrics: ControlMetrics,
1002    ) -> f32 {
1003        let gap = self.resolved_gap(metrics);
1004        let available = match self.layout {
1005            PropertyRowLayout::Stacked => bounds.width(),
1006            PropertyRowLayout::Inline => (bounds.width() - label_extent - gap).max(0.0),
1007        };
1008        self.resolved_control_width(metrics)
1009            .unwrap_or(available)
1010            .min(available)
1011            .max(0.0)
1012    }
1013}
1014
1015impl Widget for PropertyRow {
1016    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1017        let theme = self.resolved_theme();
1018        let metrics = theme.metrics;
1019        let gap = self.resolved_gap(metrics);
1020        let label_style = self.resolved_label_style();
1021        let label_measurement = measure_text(ctx, &self.label, &label_style);
1022        self.label_measurement = Some(label_measurement);
1023        let label_height = self.label_height(&label_style);
1024        let label_extent = match self.layout {
1025            PropertyRowLayout::Stacked => label_measurement.width,
1026            PropertyRowLayout::Inline => self
1027                .resolved_label_width(metrics)
1028                .max(label_measurement.width),
1029        };
1030        let child_size = self.child.measure(
1031            ctx,
1032            self.child_constraints(constraints, label_extent, metrics),
1033        );
1034        let natural = match self.layout {
1035            PropertyRowLayout::Stacked => Size::new(
1036                label_measurement.width.max(child_size.width),
1037                label_height + gap + child_size.height,
1038            ),
1039            PropertyRowLayout::Inline => Size::new(
1040                label_extent + gap + child_size.width,
1041                label_height.max(child_size.height),
1042            ),
1043        };
1044
1045        constraints.clamp(natural)
1046    }
1047
1048    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1049        let theme = self.resolved_theme();
1050        let metrics = theme.metrics;
1051        let gap = self.resolved_gap(metrics);
1052        let label_style = self.resolved_label_style();
1053        let label_height = self.label_height(&label_style);
1054        let label_width = match self.layout {
1055            PropertyRowLayout::Stacked => bounds.width(),
1056            PropertyRowLayout::Inline => self
1057                .resolved_label_width(metrics)
1058                .min(bounds.width())
1059                .max(0.0),
1060        };
1061        let child_measured = self.child.child().measured_size();
1062        let child_width = self.child_width_for_bounds(bounds, label_width, metrics);
1063        let child_height = child_measured.height.min(bounds.height()).max(0.0);
1064
1065        let child_bounds = match self.layout {
1066            PropertyRowLayout::Stacked => Rect::new(
1067                bounds.x(),
1068                bounds.y() + label_height + gap,
1069                child_width,
1070                child_height.min((bounds.height() - label_height - gap).max(0.0)),
1071            ),
1072            PropertyRowLayout::Inline => Rect::new(
1073                bounds.x() + label_width + gap,
1074                bounds.y() + ((bounds.height() - child_height) * 0.5).max(0.0),
1075                child_width,
1076                child_height,
1077            ),
1078        };
1079        self.child.arrange(ctx, child_bounds);
1080    }
1081
1082    fn paint(&self, ctx: &mut PaintCtx) {
1083        let theme = self.resolved_theme();
1084        let metrics = theme.metrics;
1085        let label_style = self.resolved_label_style();
1086        let label_height = self.label_height(&label_style);
1087        let bounds = ctx.bounds();
1088        let label_rect = match self.layout {
1089            PropertyRowLayout::Stacked => {
1090                Rect::new(bounds.x(), bounds.y(), bounds.width(), label_height)
1091            }
1092            PropertyRowLayout::Inline => Rect::new(
1093                bounds.x(),
1094                bounds.y() + ((bounds.height() - label_height) * 0.5).max(0.0),
1095                self.resolved_label_width(metrics)
1096                    .min(bounds.width())
1097                    .max(0.0),
1098                label_height,
1099            ),
1100        };
1101        ctx.push_clip_rect(label_rect);
1102        paint_single_line_aligned_text(
1103            ctx,
1104            label_rect,
1105            &self.label,
1106            &label_style,
1107            label_height,
1108            0.0,
1109        );
1110        ctx.pop_clip();
1111        self.child.paint(ctx);
1112    }
1113
1114    fn semantics(&self, ctx: &mut SemanticsCtx) {
1115        let theme = self.resolved_theme();
1116        let metrics = theme.metrics;
1117        let mut row = SemanticsNode::new(
1118            ctx.widget_id(),
1119            SemanticsRole::GenericContainer,
1120            ctx.bounds(),
1121        );
1122        row.name = Some(self.label.clone());
1123        ctx.push(row);
1124
1125        let label_style = self.resolved_label_style();
1126        let label_height = self.label_height(&label_style);
1127        let label_bounds = match self.layout {
1128            PropertyRowLayout::Stacked => Rect::new(
1129                ctx.bounds().x(),
1130                ctx.bounds().y(),
1131                ctx.bounds().width(),
1132                label_height,
1133            ),
1134            PropertyRowLayout::Inline => Rect::new(
1135                ctx.bounds().x(),
1136                ctx.bounds().y() + ((ctx.bounds().height() - label_height) * 0.5).max(0.0),
1137                self.resolved_label_width(metrics)
1138                    .min(ctx.bounds().width())
1139                    .max(0.0),
1140                label_height,
1141            ),
1142        };
1143        let mut label = SemanticsNode::new(
1144            property_row_label_id(ctx.widget_id()),
1145            SemanticsRole::Text,
1146            label_bounds,
1147        );
1148        label.parent = Some(ctx.widget_id());
1149        label.name = Some(self.label.clone());
1150        label.value = Some(SemanticsValue::Text(self.label.clone()));
1151        ctx.push(label);
1152
1153        self.child.semantics(ctx);
1154    }
1155
1156    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1157        self.child.visit_children(visitor);
1158    }
1159
1160    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1161        self.child.visit_children_mut(visitor);
1162    }
1163}
1164
1165pub(super) fn property_row_label_id(parent: WidgetId) -> WidgetId {
1166    const TAG: u64 = 1_u64 << 51;
1167    const LOW_MASK: u64 = (1_u64 << 51) - 1;
1168
1169    WidgetId::new(TAG | (parent.get().wrapping_mul(271).wrapping_add(1) & LOW_MASK))
1170}
1171
1172pub struct SectionLabel {
1173    pub(super) theme: Box<DefaultTheme>,
1174    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1175    pub(super) label: String,
1176    pub(super) semantic_name: Option<String>,
1177    pub(super) color: Option<Color>,
1178}
1179
1180impl SectionLabel {
1181    pub fn new(label: impl Into<String>) -> Self {
1182        Self {
1183            theme: Box::new(DefaultTheme::default()),
1184            theme_reader: None,
1185            label: label.into(),
1186            semantic_name: None,
1187            color: None,
1188        }
1189    }
1190
1191    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1192        self.theme = Box::new(theme);
1193        self.theme_reader = None;
1194        self
1195    }
1196
1197    pub fn theme_when<F>(mut self, theme: F) -> Self
1198    where
1199        F: Fn() -> DefaultTheme + 'static,
1200    {
1201        self.theme_reader = Some(Box::new(theme));
1202        self
1203    }
1204
1205    pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
1206        self.semantic_name = Some(name.into());
1207        self
1208    }
1209
1210    pub fn color(mut self, color: Color) -> Self {
1211        self.color = Some(color);
1212        self
1213    }
1214
1215    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1216        self.theme_reader
1217            .as_ref()
1218            .map(|theme| theme())
1219            .unwrap_or(*self.theme)
1220    }
1221
1222    pub(super) fn display_text(&self) -> String {
1223        self.label.to_uppercase()
1224    }
1225
1226    pub(super) fn text_style(&self, theme: &DefaultTheme) -> TextStyle {
1227        section_label_text_style(theme, self.color)
1228    }
1229}
1230
1231impl Widget for SectionLabel {
1232    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1233        let theme = self.resolved_theme();
1234        let style = self.text_style(&theme);
1235        let text = self.display_text();
1236        let measured = measure_text(ctx, &text, &style);
1237        constraints.clamp(Size::new(measured.width, style.line_height))
1238    }
1239
1240    fn paint(&self, ctx: &mut PaintCtx) {
1241        let theme = self.resolved_theme();
1242        let style = self.text_style(&theme);
1243        let text = self.display_text();
1244        ctx.push_clip_rect(ctx.bounds());
1245        paint_single_line_aligned_text(ctx, ctx.bounds(), &text, &style, style.line_height, 0.0);
1246        ctx.pop_clip();
1247    }
1248
1249    fn semantics(&self, ctx: &mut SemanticsCtx) {
1250        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
1251        let name = self
1252            .semantic_name
1253            .clone()
1254            .unwrap_or_else(|| self.label.clone());
1255        node.name = Some(name.clone());
1256        node.value = Some(SemanticsValue::Text(name));
1257        ctx.push(node);
1258    }
1259}
1260
1261#[derive(Debug, Clone, Copy, Default)]
1262pub struct SectionLabelPaint {
1263    pub(super) color: Option<Color>,
1264}
1265
1266impl SectionLabelPaint {
1267    pub const fn new() -> Self {
1268        Self { color: None }
1269    }
1270
1271    pub const fn color(mut self, color: Color) -> Self {
1272        self.color = Some(color);
1273        self
1274    }
1275}
1276
1277pub fn paint_section_label(
1278    ctx: &mut PaintCtx,
1279    theme: &DefaultTheme,
1280    rect: Rect,
1281    label: &str,
1282    paint: SectionLabelPaint,
1283) {
1284    let style = section_label_text_style(theme, paint.color);
1285    let text = label.to_uppercase();
1286    ctx.push_clip_rect(rect);
1287    paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
1288    ctx.pop_clip();
1289}
1290
1291pub fn paint_section_label_detail(
1292    ctx: &mut PaintCtx,
1293    theme: &DefaultTheme,
1294    rect: Rect,
1295    label: &str,
1296    detail: &str,
1297    paint: SectionLabelPaint,
1298) {
1299    let style = section_label_text_style(theme, paint.color);
1300    let text = if detail.trim().is_empty() {
1301        label.to_uppercase()
1302    } else {
1303        format!("{} · {detail}", label.to_uppercase())
1304    };
1305    ctx.push_clip_rect(rect);
1306    paint_single_line_aligned_text(ctx, rect, &text, &style, style.line_height, 0.0);
1307    ctx.pop_clip();
1308}
1309
1310pub(super) fn section_label_text_style(theme: &DefaultTheme, color: Option<Color>) -> TextStyle {
1311    let mut style = text_token_style(
1312        theme,
1313        theme.text.xs,
1314        color.unwrap_or(theme.surfaces.text_faint),
1315    );
1316    style.weight = FontWeight::SEMIBOLD;
1317    style
1318}
1319
1320pub struct DetailRow {
1321    pub(super) theme: Box<DefaultTheme>,
1322    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1323    pub(super) label: String,
1324    pub(super) label_reader: Option<Box<dyn Fn() -> String>>,
1325    pub(super) value: String,
1326    pub(super) value_reader: Option<Box<dyn Fn() -> String>>,
1327    pub(super) max_value_lines: Option<usize>,
1328}
1329
1330impl DetailRow {
1331    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
1332        Self {
1333            theme: Box::new(DefaultTheme::default()),
1334            theme_reader: None,
1335            label: label.into(),
1336            label_reader: None,
1337            value: value.into(),
1338            value_reader: None,
1339            max_value_lines: None,
1340        }
1341    }
1342
1343    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1344        self.theme = Box::new(theme);
1345        self.theme_reader = None;
1346        self
1347    }
1348
1349    pub fn theme_when<F>(mut self, theme: F) -> Self
1350    where
1351        F: Fn() -> DefaultTheme + 'static,
1352    {
1353        self.theme_reader = Some(Box::new(theme));
1354        self
1355    }
1356
1357    pub fn label_when<F>(mut self, label: F) -> Self
1358    where
1359        F: Fn() -> String + 'static,
1360    {
1361        self.label_reader = Some(Box::new(label));
1362        self
1363    }
1364
1365    pub fn value_when<F>(mut self, value: F) -> Self
1366    where
1367        F: Fn() -> String + 'static,
1368    {
1369        self.value_reader = Some(Box::new(value));
1370        self
1371    }
1372
1373    pub fn max_value_lines(mut self, max_lines: usize) -> Self {
1374        self.max_value_lines = Some(max_lines.max(1));
1375        self
1376    }
1377
1378    pub(super) fn label(&self) -> String {
1379        self.label_reader
1380            .as_ref()
1381            .map(|reader| reader())
1382            .unwrap_or_else(|| self.label.clone())
1383    }
1384
1385    pub(super) fn value(&self) -> String {
1386        self.value_reader
1387            .as_ref()
1388            .map(|reader| reader())
1389            .unwrap_or_else(|| self.value.clone())
1390    }
1391
1392    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1393        self.theme_reader
1394            .as_ref()
1395            .map(|theme| theme())
1396            .unwrap_or(*self.theme)
1397    }
1398}
1399
1400impl Widget for DetailRow {
1401    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1402        let theme = self.resolved_theme();
1403        let label_style = detail_row_label_style(&theme);
1404        let value_style = detail_row_value_style(&theme);
1405        let width = if constraints.max.width.is_finite() {
1406            constraints.max.width.max(0.0)
1407        } else {
1408            let label = measure_text(ctx, &self.label().to_uppercase(), &label_style);
1409            let value = measure_text(ctx, &self.value(), &value_style);
1410            label.width.max(value.width)
1411        };
1412        let value = self.value();
1413        let lines = wrap_detail_row_value(&value, width, self.max_value_lines, |text| {
1414            measure_text(ctx, text, &value_style).width
1415        });
1416        constraints.clamp(Size::new(width, detail_row_height(&theme, lines.len())))
1417    }
1418
1419    fn paint(&self, ctx: &mut PaintCtx) {
1420        let theme = self.resolved_theme();
1421        paint_detail_row_at(
1422            ctx,
1423            &theme,
1424            Point::new(ctx.bounds().x(), ctx.bounds().y()),
1425            ctx.bounds().width(),
1426            &self.label(),
1427            &self.value(),
1428            self.max_value_lines,
1429        );
1430    }
1431
1432    fn semantics(&self, ctx: &mut SemanticsCtx) {
1433        let mut node = SemanticsNode::new(
1434            ctx.widget_id(),
1435            SemanticsRole::GenericContainer,
1436            ctx.bounds(),
1437        );
1438        node.name = Some(self.label());
1439        node.value = Some(SemanticsValue::Text(self.value()));
1440        ctx.push(node);
1441    }
1442}
1443
1444pub fn paint_detail_row_at(
1445    ctx: &mut PaintCtx,
1446    theme: &DefaultTheme,
1447    origin: Point,
1448    width: f32,
1449    label: &str,
1450    value: &str,
1451    max_value_lines: Option<usize>,
1452) -> f32 {
1453    let width = width.max(0.0);
1454    let label_style = detail_row_label_style(theme);
1455    let value_style = detail_row_value_style(theme);
1456    let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
1457        ctx.measure_text(text.to_string(), value_style.clone())
1458            .map(|measurement| measurement.width)
1459            .unwrap_or(0.0)
1460    });
1461    let height = detail_row_height(theme, lines.len());
1462    let clip = Rect::new(origin.x, origin.y, width, height);
1463
1464    ctx.push_clip_rect(clip);
1465    paint_aligned_text(
1466        ctx,
1467        Rect::new(origin.x, origin.y, width, label_style.line_height),
1468        &label.to_uppercase(),
1469        &label_style,
1470        label_style.line_height,
1471        0.0,
1472    );
1473
1474    let mut y = origin.y + label_style.line_height + detail_row_label_value_gap(theme);
1475    for line in lines {
1476        paint_aligned_text(
1477            ctx,
1478            Rect::new(origin.x, y, width, value_style.line_height),
1479            &line,
1480            &value_style,
1481            value_style.line_height,
1482            0.0,
1483        );
1484        y += value_style.line_height;
1485    }
1486    ctx.pop_clip();
1487    height
1488}
1489
1490pub fn detail_row_height_for_value(
1491    ctx: &PaintCtx,
1492    theme: &DefaultTheme,
1493    width: f32,
1494    value: &str,
1495    max_value_lines: Option<usize>,
1496) -> f32 {
1497    let width = width.max(0.0);
1498    let value_style = detail_row_value_style(theme);
1499    let lines = wrap_detail_row_value(value, width, max_value_lines, |text| {
1500        ctx.measure_text(text.to_string(), value_style.clone())
1501            .map(|measurement| measurement.width)
1502            .unwrap_or(0.0)
1503    });
1504    detail_row_height(theme, lines.len())
1505}
1506
1507pub(super) fn detail_row_label_style(theme: &DefaultTheme) -> TextStyle {
1508    let mut style = text_token_style(theme, theme.text.xs, theme.palette.text_muted);
1509    style.weight = FontWeight::SEMIBOLD;
1510    style
1511}
1512
1513pub(super) fn detail_row_value_style(theme: &DefaultTheme) -> TextStyle {
1514    text_token_style(theme, theme.text.sm, theme.palette.text)
1515}
1516
1517pub(super) fn detail_row_label_value_gap(theme: &DefaultTheme) -> f32 {
1518    (theme.metrics.icon_label_gap * 0.35).max(2.0)
1519}
1520
1521pub(super) fn detail_row_bottom_gap(theme: &DefaultTheme) -> f32 {
1522    theme.metrics.property_row_stacked_gap.max(6.0)
1523}
1524
1525pub(super) fn detail_row_height(theme: &DefaultTheme, value_lines: usize) -> f32 {
1526    let label_style = detail_row_label_style(theme);
1527    let value_style = detail_row_value_style(theme);
1528    label_style.line_height
1529        + detail_row_label_value_gap(theme)
1530        + value_style.line_height * value_lines.max(1) as f32
1531        + detail_row_bottom_gap(theme)
1532}
1533
1534pub(super) fn wrap_detail_row_value<F>(
1535    value: &str,
1536    width: f32,
1537    max_lines: Option<usize>,
1538    mut measure: F,
1539) -> Vec<String>
1540where
1541    F: FnMut(&str) -> f32,
1542{
1543    let max_lines = max_lines.unwrap_or(usize::MAX).max(1);
1544    let width = width.max(1.0);
1545    let mut lines = Vec::new();
1546
1547    for paragraph in value.split('\n') {
1548        if lines.len() >= max_lines {
1549            break;
1550        }
1551        let mut current = String::new();
1552        for word in paragraph.split_whitespace() {
1553            let candidate = if current.is_empty() {
1554                word.to_string()
1555            } else {
1556                format!("{current} {word}")
1557            };
1558            if current.is_empty() || measure(&candidate) <= width {
1559                current = candidate;
1560            } else {
1561                lines.push(std::mem::take(&mut current));
1562                if lines.len() >= max_lines {
1563                    break;
1564                }
1565                current = word.to_string();
1566            }
1567        }
1568        if lines.len() < max_lines {
1569            lines.push(current);
1570        }
1571    }
1572
1573    if lines.is_empty() {
1574        lines.push(String::new());
1575    }
1576    lines
1577}
1578
1579pub struct FormRow {
1580    pub(super) row: PropertyRow,
1581}
1582
1583impl FormRow {
1584    pub fn new<W>(label: impl Into<String>, control: W) -> Self
1585    where
1586        W: Widget + 'static,
1587    {
1588        Self {
1589            row: PropertyRow::new(label, control)
1590                .inline()
1591                .with_form_defaults(),
1592        }
1593    }
1594
1595    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1596        self.row = self.row.theme(theme);
1597        self
1598    }
1599
1600    pub fn theme_when<F>(mut self, theme: F) -> Self
1601    where
1602        F: Fn() -> DefaultTheme + 'static,
1603    {
1604        self.row = self.row.theme_when(theme);
1605        self
1606    }
1607
1608    pub fn stacked(mut self) -> Self {
1609        self.row = self.row.stacked();
1610        self
1611    }
1612
1613    pub fn inline(mut self) -> Self {
1614        self.row = self.row.inline();
1615        self
1616    }
1617
1618    pub fn label_width(mut self, width: f32) -> Self {
1619        self.row = self.row.label_width(width);
1620        self
1621    }
1622
1623    pub fn control_width(mut self, width: f32) -> Self {
1624        self.row = self.row.control_width(width);
1625        self
1626    }
1627
1628    pub fn auto_control_width(mut self) -> Self {
1629        self.row = self.row.auto_control_width();
1630        self
1631    }
1632
1633    pub fn gap(mut self, gap: f32) -> Self {
1634        self.row = self.row.gap(gap);
1635        self
1636    }
1637
1638    pub fn label_style(mut self, style: TextStyle) -> Self {
1639        self.row = self.row.label_style(style);
1640        self
1641    }
1642
1643    pub fn child(&self) -> &sui_runtime::WidgetPod {
1644        self.row.child()
1645    }
1646
1647    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
1648        self.row.child_mut()
1649    }
1650}
1651
1652impl Widget for FormRow {
1653    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1654        self.row.measure(ctx, constraints)
1655    }
1656
1657    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1658        self.row.arrange(ctx, bounds);
1659    }
1660
1661    fn paint(&self, ctx: &mut PaintCtx) {
1662        self.row.paint(ctx);
1663    }
1664
1665    fn semantics(&self, ctx: &mut SemanticsCtx) {
1666        self.row.semantics(ctx);
1667    }
1668
1669    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1670        self.row.visit_children(visitor);
1671    }
1672
1673    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1674        self.row.visit_children_mut(visitor);
1675    }
1676}
1677
1678pub struct FieldGroup {
1679    pub(super) theme: Box<DefaultTheme>,
1680    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1681    pub(super) children: WidgetChildren,
1682    pub(super) spacing: Option<f32>,
1683    pub(super) padding: Insets,
1684    pub(super) max_width: Option<f32>,
1685    pub(super) fill_width: bool,
1686}
1687
1688impl FieldGroup {
1689    pub fn new() -> Self {
1690        Self {
1691            theme: Box::new(DefaultTheme::default()),
1692            theme_reader: None,
1693            children: WidgetChildren::new(),
1694            spacing: None,
1695            padding: Insets::ZERO,
1696            max_width: None,
1697            fill_width: false,
1698        }
1699    }
1700
1701    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1702        self.theme = Box::new(theme);
1703        self.theme_reader = None;
1704        self
1705    }
1706
1707    pub fn theme_when<F>(mut self, theme: F) -> Self
1708    where
1709        F: Fn() -> DefaultTheme + 'static,
1710    {
1711        self.theme_reader = Some(Box::new(theme));
1712        self
1713    }
1714
1715    pub fn with_child<W>(mut self, child: W) -> Self
1716    where
1717        W: Widget + 'static,
1718    {
1719        self.children.push(child);
1720        self
1721    }
1722
1723    pub fn push<W>(&mut self, child: W)
1724    where
1725        W: Widget + 'static,
1726    {
1727        self.children.push(child);
1728    }
1729
1730    pub fn spacing(mut self, spacing: f32) -> Self {
1731        self.spacing = Some(spacing.max(0.0));
1732        self
1733    }
1734
1735    pub fn padding(mut self, padding: Insets) -> Self {
1736        self.padding = padding;
1737        self
1738    }
1739
1740    pub fn max_width(mut self, width: f32) -> Self {
1741        self.max_width = Some(width.max(0.0));
1742        self
1743    }
1744
1745    pub fn auto_width(mut self) -> Self {
1746        self.max_width = None;
1747        self
1748    }
1749
1750    pub fn fill_width(mut self) -> Self {
1751        self.fill_width = true;
1752        self
1753    }
1754
1755    pub fn children(&self) -> &[sui_runtime::WidgetPod] {
1756        self.children.as_slice()
1757    }
1758
1759    pub fn children_mut(&mut self) -> &mut [sui_runtime::WidgetPod] {
1760        self.children.as_mut_slice()
1761    }
1762
1763    pub(super) fn content_max_width(&self, constraints: Constraints) -> f32 {
1764        let available = if constraints.max.width.is_finite() {
1765            (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
1766        } else {
1767            f32::INFINITY
1768        };
1769        self.max_width
1770            .map(|width| width.min(available))
1771            .unwrap_or(available)
1772    }
1773
1774    pub(super) fn content_rect(&self, bounds: Rect) -> Rect {
1775        let inset = inset_rect(bounds, self.padding);
1776        let width = self
1777            .max_width
1778            .map(|max_width| max_width.min(inset.width()))
1779            .unwrap_or(inset.width())
1780            .max(0.0);
1781        Rect::new(inset.x(), inset.y(), width, inset.height())
1782    }
1783
1784    pub(super) fn resolved_theme(&self) -> DefaultTheme {
1785        self.theme_reader
1786            .as_ref()
1787            .map(|theme| theme())
1788            .unwrap_or(*self.theme)
1789    }
1790
1791    pub(super) fn resolved_spacing(&self) -> f32 {
1792        self.spacing
1793            .unwrap_or_else(|| self.resolved_theme().metrics.field_group_spacing)
1794    }
1795}
1796
1797impl Default for FieldGroup {
1798    fn default() -> Self {
1799        Self::new()
1800    }
1801}
1802
1803impl Widget for FieldGroup {
1804    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1805        let spacing = self.resolved_spacing();
1806        let content_max_width = self.content_max_width(constraints);
1807        let mut y: f32 = 0.0;
1808        let mut width: f32 = 0.0;
1809        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1810            if index > 0 {
1811                y += spacing;
1812            }
1813            let child_size = child.measure(
1814                ctx,
1815                Constraints::new(
1816                    Size::ZERO,
1817                    Size::new(content_max_width, constraints.max.height),
1818                ),
1819            );
1820            y += child_size.height;
1821            width = width.max(child_size.width);
1822        }
1823
1824        if self.fill_width && content_max_width.is_finite() {
1825            width = content_max_width;
1826        }
1827
1828        constraints.clamp(Size::new(
1829            width + self.padding.left + self.padding.right,
1830            y + self.padding.top + self.padding.bottom,
1831        ))
1832    }
1833
1834    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
1835        let spacing = self.resolved_spacing();
1836        let content = self.content_rect(bounds);
1837        let mut y = content.y();
1838        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
1839            if index > 0 {
1840                y += spacing;
1841            }
1842            let measured = child.measured_size();
1843            let width = if self.fill_width {
1844                content.width()
1845            } else {
1846                measured.width.min(content.width())
1847            };
1848            child.arrange(ctx, Rect::new(content.x(), y, width, measured.height));
1849            y += measured.height;
1850        }
1851    }
1852
1853    fn paint(&self, ctx: &mut PaintCtx) {
1854        self.children.paint(ctx);
1855    }
1856
1857    fn semantics(&self, ctx: &mut SemanticsCtx) {
1858        self.children.semantics(ctx);
1859    }
1860
1861    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
1862        self.children.visit_children(visitor);
1863    }
1864
1865    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
1866        self.children.visit_children_mut(visitor);
1867    }
1868}
1869
1870pub struct FormSection {
1871    pub(super) theme: Box<DefaultTheme>,
1872    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
1873    pub(super) title: String,
1874    pub(super) description: Option<String>,
1875    pub(super) title_style: Option<TextStyle>,
1876    pub(super) description_style: Option<TextStyle>,
1877    pub(super) header_action: Option<SingleChild>,
1878    pub(super) child: SingleChild,
1879    pub(super) padding: Option<Insets>,
1880    pub(super) body_gap: Option<f32>,
1881    pub(super) header_gap: Option<f32>,
1882    pub(super) description_gap: Option<f32>,
1883    pub(super) max_width: Option<f32>,
1884    pub(super) auto_width: bool,
1885    pub(super) radius: Option<f32>,
1886    pub(super) elevation: SurfaceElevation,
1887    pub(super) fill_width: bool,
1888    pub(super) title_measurement: Option<TextMeasurement>,
1889    pub(super) description_measurement: Option<TextMeasurement>,
1890}
1891
1892impl FormSection {
1893    pub fn new<W>(title: impl Into<String>, child: W) -> Self
1894    where
1895        W: Widget + 'static,
1896    {
1897        Self {
1898            theme: Box::new(DefaultTheme::default()),
1899            theme_reader: None,
1900            title: title.into(),
1901            description: None,
1902            title_style: None,
1903            description_style: None,
1904            header_action: None,
1905            child: SingleChild::new(child),
1906            padding: None,
1907            body_gap: None,
1908            header_gap: None,
1909            description_gap: None,
1910            max_width: None,
1911            auto_width: false,
1912            radius: None,
1913            elevation: SurfaceElevation::Small,
1914            fill_width: false,
1915            title_measurement: None,
1916            description_measurement: None,
1917        }
1918    }
1919
1920    pub fn theme(mut self, theme: DefaultTheme) -> Self {
1921        self.theme = Box::new(theme);
1922        self.theme_reader = None;
1923        self
1924    }
1925
1926    pub fn theme_when<F>(mut self, theme: F) -> Self
1927    where
1928        F: Fn() -> DefaultTheme + 'static,
1929    {
1930        self.theme_reader = Some(Box::new(theme));
1931        self
1932    }
1933
1934    pub fn description(mut self, description: impl Into<String>) -> Self {
1935        self.description = Some(description.into());
1936        self
1937    }
1938
1939    pub fn title_style(mut self, style: TextStyle) -> Self {
1940        self.title_style = Some(style);
1941        self
1942    }
1943
1944    pub fn description_style(mut self, style: TextStyle) -> Self {
1945        self.description_style = Some(style);
1946        self
1947    }
1948
1949    pub fn header_action<W>(mut self, action: W) -> Self
1950    where
1951        W: Widget + 'static,
1952    {
1953        self.header_action = Some(SingleChild::new(action));
1954        self
1955    }
1956
1957    pub fn padding(mut self, padding: Insets) -> Self {
1958        self.padding = Some(padding);
1959        self
1960    }
1961
1962    pub fn body_gap(mut self, gap: f32) -> Self {
1963        self.body_gap = Some(gap.max(0.0));
1964        self
1965    }
1966
1967    pub fn header_gap(mut self, gap: f32) -> Self {
1968        self.header_gap = Some(gap.max(0.0));
1969        self
1970    }
1971
1972    pub fn max_width(mut self, width: f32) -> Self {
1973        self.max_width = Some(width.max(0.0));
1974        self.auto_width = false;
1975        self
1976    }
1977
1978    pub fn auto_width(mut self) -> Self {
1979        self.max_width = None;
1980        self.auto_width = true;
1981        self
1982    }
1983
1984    pub fn fill_width(mut self) -> Self {
1985        self.fill_width = true;
1986        self
1987    }
1988
1989    pub fn radius(mut self, radius: f32) -> Self {
1990        self.radius = Some(radius.max(0.0));
1991        self
1992    }
1993
1994    pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
1995        self.elevation = elevation;
1996        self
1997    }
1998
1999    pub fn child(&self) -> &sui_runtime::WidgetPod {
2000        self.child.child()
2001    }
2002
2003    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
2004        self.child.child_mut()
2005    }
2006
2007    pub(super) fn resolved_theme(&self) -> DefaultTheme {
2008        self.theme_reader
2009            .as_ref()
2010            .map(|theme| theme())
2011            .unwrap_or(*self.theme)
2012    }
2013
2014    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
2015        self.padding.unwrap_or(metrics.form_section_padding)
2016    }
2017
2018    pub(super) fn resolved_body_gap(&self, metrics: ControlMetrics) -> f32 {
2019        self.body_gap.unwrap_or(metrics.form_section_body_gap)
2020    }
2021
2022    pub(super) fn resolved_header_gap(&self, metrics: ControlMetrics) -> f32 {
2023        self.header_gap.unwrap_or(metrics.form_section_header_gap)
2024    }
2025
2026    pub(super) fn resolved_description_gap(&self, metrics: ControlMetrics) -> f32 {
2027        self.description_gap
2028            .unwrap_or(metrics.form_section_description_gap)
2029    }
2030
2031    pub(super) fn resolved_max_width(&self, metrics: ControlMetrics) -> Option<f32> {
2032        if self.auto_width {
2033            None
2034        } else {
2035            Some(self.max_width.unwrap_or(metrics.form_section_max_width))
2036        }
2037    }
2038
2039    pub(super) fn resolved_radius(&self, metrics: ControlMetrics) -> f32 {
2040        self.radius.unwrap_or(metrics.form_section_radius).max(0.0)
2041    }
2042
2043    pub(super) fn resolved_title_style(&self) -> TextStyle {
2044        let theme = self.resolved_theme();
2045        self.title_style.clone().unwrap_or_else(|| TextStyle {
2046            weight: FontWeight::SEMIBOLD,
2047            ..text_token_style(&theme, theme.text.sm, theme.surfaces.text)
2048        })
2049    }
2050
2051    pub(super) fn resolved_description_style(&self) -> TextStyle {
2052        let theme = self.resolved_theme();
2053        self.description_style
2054            .clone()
2055            .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.surfaces.text_muted))
2056    }
2057
2058    pub(super) fn title_height(&self, style: &TextStyle) -> f32 {
2059        self.title_measurement
2060            .map(|measurement| measurement.height)
2061            .unwrap_or(style.line_height)
2062            .max(style.line_height)
2063    }
2064
2065    pub(super) fn description_height(&self, style: &TextStyle) -> f32 {
2066        if self.description.is_some() {
2067            self.description_measurement
2068                .map(|measurement| measurement.height)
2069                .unwrap_or(style.line_height)
2070                .max(style.line_height)
2071        } else {
2072            0.0
2073        }
2074    }
2075
2076    pub(super) fn text_block_height(
2077        &self,
2078        title_style: &TextStyle,
2079        description_style: &TextStyle,
2080    ) -> f32 {
2081        let title = self.title_height(title_style);
2082        let description = self.description_height(description_style);
2083        if description > 0.0 {
2084            let metrics = self.resolved_theme().metrics;
2085            title + self.resolved_description_gap(metrics) + description
2086        } else {
2087            title
2088        }
2089    }
2090
2091    pub(super) fn content_max_width(&self, available_width: f32) -> f32 {
2092        let theme = self.resolved_theme();
2093        let metrics = theme.metrics;
2094        let padding = self.resolved_padding(metrics);
2095        let available = if available_width.is_finite() {
2096            (available_width - padding.left - padding.right).max(0.0)
2097        } else {
2098            f32::INFINITY
2099        };
2100        self.resolved_max_width(metrics)
2101            .map(|width| width.min(available))
2102            .unwrap_or(available)
2103    }
2104
2105    pub(super) fn card_rect(&self, bounds: Rect) -> Rect {
2106        let theme = self.resolved_theme();
2107        let metrics = theme.metrics;
2108        let padding = self.resolved_padding(metrics);
2109        let width = if self.fill_width {
2110            bounds.width()
2111        } else {
2112            self.resolved_max_width(metrics)
2113                .map(|max_width| (max_width + padding.left + padding.right).min(bounds.width()))
2114                .unwrap_or(bounds.width())
2115        }
2116        .max(0.0);
2117        let x = if self.fill_width || width >= bounds.width() {
2118            bounds.x()
2119        } else {
2120            bounds.x() + ((bounds.width() - width) * 0.5)
2121        };
2122        Rect::new(x, bounds.y(), width, bounds.height())
2123    }
2124
2125    pub(super) fn content_rect(&self, bounds: Rect) -> Rect {
2126        let theme = self.resolved_theme();
2127        inset_rect(self.card_rect(bounds), self.resolved_padding(theme.metrics))
2128    }
2129
2130    pub(super) fn header_height(
2131        &self,
2132        title_style: &TextStyle,
2133        description_style: &TextStyle,
2134    ) -> f32 {
2135        let text_height = self.text_block_height(title_style, description_style);
2136        let action_height = self
2137            .header_action
2138            .as_ref()
2139            .map(|action| action.child().measured_size().height)
2140            .unwrap_or(0.0);
2141        text_height.max(action_height)
2142    }
2143}
2144
2145impl Widget for FormSection {
2146    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2147        let theme = self.resolved_theme();
2148        let metrics = theme.metrics;
2149        let padding = self.resolved_padding(metrics);
2150        let body_gap = self.resolved_body_gap(metrics);
2151        let header_gap = self.resolved_header_gap(metrics);
2152        let title_style = self.resolved_title_style();
2153        let description_style = self.resolved_description_style();
2154        let title = measure_text(ctx, &self.title, &title_style);
2155        self.title_measurement = Some(title);
2156        let description = self
2157            .description
2158            .as_ref()
2159            .map(|description| measure_text(ctx, description, &description_style));
2160        self.description_measurement = description;
2161
2162        let content_max_width = self.content_max_width(constraints.max.width);
2163        let action_size = self
2164            .header_action
2165            .as_mut()
2166            .map(|action| {
2167                action.measure(
2168                    ctx,
2169                    Constraints::new(
2170                        Size::ZERO,
2171                        Size::new(content_max_width, constraints.max.height),
2172                    ),
2173                )
2174            })
2175            .unwrap_or(Size::ZERO);
2176        let action_extent = if self.header_action.is_some() {
2177            action_size.width + header_gap
2178        } else {
2179            0.0
2180        };
2181        let text_width = title.width.max(
2182            description
2183                .map(|measurement| measurement.width)
2184                .unwrap_or(0.0),
2185        );
2186        let header_width = (text_width + action_extent).min(content_max_width);
2187        let child_size = self.child.measure(
2188            ctx,
2189            Constraints::new(
2190                Size::ZERO,
2191                Size::new(content_max_width, constraints.max.height),
2192            ),
2193        );
2194        let content_width = header_width.max(child_size.width).min(content_max_width);
2195        let header_height = self.header_height(&title_style, &description_style);
2196
2197        let mut width = content_width + padding.left + padding.right;
2198        if self.fill_width && constraints.max.width.is_finite() {
2199            width = constraints.max.width;
2200        }
2201        let height = padding.top + header_height + body_gap + child_size.height + padding.bottom;
2202        constraints.clamp(Size::new(width, height))
2203    }
2204
2205    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2206        let theme = self.resolved_theme();
2207        let metrics = theme.metrics;
2208        let body_gap = self.resolved_body_gap(metrics);
2209        let content = self.content_rect(bounds);
2210        let title_style = self.resolved_title_style();
2211        let description_style = self.resolved_description_style();
2212        let header_height = self.header_height(&title_style, &description_style);
2213
2214        if let Some(action) = &mut self.header_action {
2215            let action_size = action.child().measured_size();
2216            action.arrange(
2217                ctx,
2218                Rect::new(
2219                    content.max_x() - action_size.width,
2220                    content.y() + ((header_height - action_size.height) * 0.5).max(0.0),
2221                    action_size.width,
2222                    action_size.height,
2223                ),
2224            );
2225        }
2226
2227        let child_size = self.child.child().measured_size();
2228        self.child.arrange(
2229            ctx,
2230            Rect::new(
2231                content.x(),
2232                content.y() + header_height + body_gap,
2233                child_size.width.min(content.width()),
2234                child_size.height,
2235            ),
2236        );
2237    }
2238
2239    fn paint(&self, ctx: &mut PaintCtx) {
2240        let theme = self.resolved_theme();
2241        let metrics = theme.metrics;
2242        let card = self.card_rect(ctx.bounds());
2243        let radius = self
2244            .resolved_radius(metrics)
2245            .min(card.width().min(card.height()) * 0.5);
2246        let shadow = match self.elevation {
2247            SurfaceElevation::None => None,
2248            SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
2249            SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
2250            SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
2251        };
2252        if let Some(shadow) = shadow {
2253            paint_theme_shadow(ctx, card, [radius; 4], shadow);
2254        }
2255
2256        let background = theme.surfaces.panel;
2257        let border = theme.surfaces.border;
2258        let shape = rounded_rect_path(card, radius);
2259        ctx.fill(shape.clone(), background);
2260        ctx.stroke(
2261            shape,
2262            border,
2263            StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
2264        );
2265
2266        let content = inset_rect(card, self.resolved_padding(metrics));
2267        let title_style = self.resolved_title_style();
2268        let description_style = self.resolved_description_style();
2269        let title_height = self.title_height(&title_style);
2270        let description_height = self.description_height(&description_style);
2271        let header_gap = self.resolved_header_gap(metrics);
2272        let description_gap = self.resolved_description_gap(metrics);
2273        let action_width = self
2274            .header_action
2275            .as_ref()
2276            .map(|action| action.child().measured_size().width + header_gap)
2277            .unwrap_or(0.0)
2278            .min(content.width());
2279        let text_width = (content.width() - action_width).max(0.0);
2280        let text_block_height = self.text_block_height(&title_style, &description_style);
2281        let header_height = self.header_height(&title_style, &description_style);
2282        let text_y = content.y() + ((header_height - text_block_height) * 0.5).max(0.0);
2283        let title_slot = Rect::new(content.x(), text_y, text_width, title_height);
2284        ctx.push_clip_rect(title_slot);
2285        paint_aligned_text(
2286            ctx,
2287            title_slot,
2288            &self.title,
2289            &title_style,
2290            title_style.line_height,
2291            0.0,
2292        );
2293        ctx.pop_clip();
2294        if let Some(description) = &self.description {
2295            let description_slot = Rect::new(
2296                content.x(),
2297                title_slot.max_y() + description_gap,
2298                text_width,
2299                description_height,
2300            );
2301            ctx.push_clip_rect(description_slot);
2302            paint_aligned_text(
2303                ctx,
2304                description_slot,
2305                description,
2306                &description_style,
2307                description_style.line_height,
2308                0.0,
2309            );
2310            ctx.pop_clip();
2311        }
2312
2313        if let Some(action) = &self.header_action {
2314            action.paint(ctx);
2315        }
2316        self.child.paint(ctx);
2317    }
2318
2319    fn semantics(&self, ctx: &mut SemanticsCtx) {
2320        let card = self.card_rect(ctx.bounds());
2321        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::GenericContainer, card);
2322        node.name = Some(self.title.clone());
2323        node.description = self.description.clone();
2324        ctx.push(node);
2325        if let Some(action) = &self.header_action {
2326            action.semantics(ctx);
2327        }
2328        self.child.semantics(ctx);
2329    }
2330
2331    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2332        if let Some(action) = &self.header_action {
2333            action.visit_children(visitor);
2334        }
2335        self.child.visit_children(visitor);
2336    }
2337
2338    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2339        if let Some(action) = &mut self.header_action {
2340            action.visit_children_mut(visitor);
2341        }
2342        self.child.visit_children_mut(visitor);
2343    }
2344}
2345
2346pub struct PanelSection {
2347    pub(super) theme: Box<DefaultTheme>,
2348    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2349    pub(super) title: String,
2350    pub(super) gap: Option<f32>,
2351    pub(super) action_gap: Option<f32>,
2352    pub(super) title_style: Option<TextStyle>,
2353    pub(super) header_action: Option<SingleChild>,
2354    pub(super) child: SingleChild,
2355    pub(super) title_measurement: Option<TextMeasurement>,
2356    pub(super) collapsible: bool,
2357    pub(super) expanded: bool,
2358    pub(super) hovered_header: bool,
2359    pub(super) pressed_header: bool,
2360    pub(super) hover_animation: AnimatedScalar,
2361    pub(super) press_animation: AnimatedScalar,
2362    pub(super) focus_animation: AnimatedScalar,
2363}
2364
2365impl PanelSection {
2366    pub fn new<W>(title: impl Into<String>, child: W) -> Self
2367    where
2368        W: Widget + 'static,
2369    {
2370        Self {
2371            theme: Box::new(DefaultTheme::default()),
2372            theme_reader: None,
2373            title: title.into(),
2374            gap: None,
2375            action_gap: None,
2376            title_style: None,
2377            header_action: None,
2378            child: SingleChild::new(child),
2379            title_measurement: None,
2380            collapsible: false,
2381            expanded: true,
2382            hovered_header: false,
2383            pressed_header: false,
2384            hover_animation: AnimatedScalar::new(0.0),
2385            press_animation: AnimatedScalar::new(0.0),
2386            focus_animation: AnimatedScalar::new(0.0),
2387        }
2388    }
2389
2390    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2391        self.theme = Box::new(theme);
2392        self.theme_reader = None;
2393        self
2394    }
2395
2396    pub fn theme_when<F>(mut self, theme: F) -> Self
2397    where
2398        F: Fn() -> DefaultTheme + 'static,
2399    {
2400        self.theme_reader = Some(Box::new(theme));
2401        self
2402    }
2403
2404    pub fn gap(mut self, gap: f32) -> Self {
2405        self.gap = Some(gap.max(0.0));
2406        self
2407    }
2408
2409    pub fn title_style(mut self, style: TextStyle) -> Self {
2410        self.title_style = Some(style);
2411        self
2412    }
2413
2414    pub fn header_action<W>(mut self, action: W) -> Self
2415    where
2416        W: Widget + 'static,
2417    {
2418        self.header_action = Some(SingleChild::new(action));
2419        self
2420    }
2421
2422    pub fn action_gap(mut self, gap: f32) -> Self {
2423        self.action_gap = Some(gap.max(0.0));
2424        self
2425    }
2426
2427    pub fn collapsible(mut self, collapsible: bool) -> Self {
2428        self.collapsible = collapsible;
2429        self
2430    }
2431
2432    pub fn expanded(mut self, expanded: bool) -> Self {
2433        self.expanded = expanded;
2434        self
2435    }
2436
2437    pub fn collapsed(mut self) -> Self {
2438        self.expanded = false;
2439        self
2440    }
2441
2442    pub fn child(&self) -> &sui_runtime::WidgetPod {
2443        self.child.child()
2444    }
2445
2446    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
2447        self.child.child_mut()
2448    }
2449
2450    pub(super) fn resolved_title_style(&self) -> TextStyle {
2451        let theme = self.resolved_theme();
2452        self.title_style
2453            .clone()
2454            .unwrap_or_else(|| text_token_style(&theme, theme.text.xs, theme.palette.text_muted))
2455    }
2456
2457    pub(super) fn resolved_theme(&self) -> DefaultTheme {
2458        self.theme_reader
2459            .as_ref()
2460            .map(|theme| theme())
2461            .unwrap_or(*self.theme)
2462    }
2463
2464    pub(super) fn resolved_gap(&self, metrics: ControlMetrics) -> f32 {
2465        self.gap.unwrap_or(metrics.panel_section_gap)
2466    }
2467
2468    pub(super) fn resolved_action_gap(&self, metrics: ControlMetrics) -> f32 {
2469        self.action_gap.unwrap_or(metrics.panel_section_action_gap)
2470    }
2471
2472    pub(super) fn title_height(&self, style: &TextStyle) -> f32 {
2473        self.title_measurement
2474            .map(|measurement| measurement.height)
2475            .unwrap_or(style.line_height)
2476            .max(style.line_height)
2477    }
2478
2479    pub(super) fn header_height(&self, title_style: &TextStyle) -> f32 {
2480        let action_height = self
2481            .header_action
2482            .as_ref()
2483            .map(|action| action.child().measured_size().height)
2484            .unwrap_or(0.0);
2485        self.title_height(title_style).max(action_height)
2486    }
2487
2488    pub(super) fn is_expanded(&self) -> bool {
2489        !self.collapsible || self.expanded
2490    }
2491
2492    pub(super) fn disclosure_width(&self, metrics: ControlMetrics) -> f32 {
2493        if self.collapsible {
2494            metrics.panel_section_disclosure_size
2495        } else {
2496            0.0
2497        }
2498    }
2499
2500    pub(super) fn title_rect(&self, bounds: Rect, header_height: f32, title_height: f32) -> Rect {
2501        let metrics = self.resolved_theme().metrics;
2502        let action_width = self
2503            .header_action
2504            .as_ref()
2505            .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
2506            .unwrap_or(0.0)
2507            .min(bounds.width());
2508        let disclosure_width = self.disclosure_width(metrics);
2509        Rect::new(
2510            bounds.x() + disclosure_width,
2511            bounds.y() + ((header_height - title_height) * 0.5).max(0.0),
2512            (bounds.width() - action_width - disclosure_width).max(0.0),
2513            title_height,
2514        )
2515    }
2516
2517    pub(super) fn header_rect(&self, bounds: Rect) -> Rect {
2518        let title_style = self.resolved_title_style();
2519        let header_height = self.header_height(&title_style);
2520        Rect::new(bounds.x(), bounds.y(), bounds.width(), header_height)
2521    }
2522
2523    pub(super) fn header_hit_rect(&self, bounds: Rect) -> Rect {
2524        let metrics = self.resolved_theme().metrics;
2525        let header = self.header_rect(bounds);
2526        let action_width = self
2527            .header_action
2528            .as_ref()
2529            .map(|action| action.child().measured_size().width + self.resolved_action_gap(metrics))
2530            .unwrap_or(0.0)
2531            .min(header.width());
2532        Rect::new(
2533            header.x(),
2534            header.y(),
2535            (header.width() - action_width).max(0.0),
2536            header.height(),
2537        )
2538    }
2539
2540    pub(super) fn toggle(&mut self, ctx: &mut EventCtx) {
2541        if !self.collapsible {
2542            return;
2543        }
2544
2545        self.expanded = !self.expanded;
2546        self.set_pressed_header(false, ctx);
2547        ctx.request_measure();
2548        ctx.request_paint();
2549        ctx.request_semantics();
2550    }
2551
2552    pub(super) fn set_hovered_header(&mut self, hovered: bool, ctx: &mut EventCtx) {
2553        if self.hovered_header == hovered {
2554            return;
2555        }
2556        let theme = self.resolved_theme();
2557        self.hovered_header = hovered;
2558        set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
2559        ctx.request_paint();
2560        ctx.request_semantics();
2561    }
2562
2563    pub(super) fn set_pressed_header(&mut self, pressed: bool, ctx: &mut EventCtx) {
2564        if self.pressed_header == pressed {
2565            return;
2566        }
2567        let theme = self.resolved_theme();
2568        self.pressed_header = pressed;
2569        set_press_animation_target(&mut self.press_animation, pressed as u8 as f32, &theme, ctx);
2570        ctx.request_paint();
2571        ctx.request_semantics();
2572    }
2573
2574    pub(super) fn advance_animations(&mut self, time: f64) -> bool {
2575        self.hover_animation.advance(time)
2576            | self.press_animation.advance(time)
2577            | self.focus_animation.advance(time)
2578    }
2579}
2580
2581impl Widget for PanelSection {
2582    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
2583        if !self.collapsible {
2584            return;
2585        }
2586
2587        match event {
2588            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
2589                let hovered = self
2590                    .header_hit_rect(ctx.bounds())
2591                    .contains(pointer.position);
2592                self.set_hovered_header(hovered, ctx);
2593            }
2594            Event::Pointer(pointer)
2595                if pointer.kind == PointerEventKind::Down
2596                    && pointer.button == Some(PointerButton::Primary)
2597                    && self
2598                        .header_hit_rect(ctx.bounds())
2599                        .contains(pointer.position) =>
2600            {
2601                self.set_hovered_header(true, ctx);
2602                self.set_pressed_header(true, ctx);
2603                ctx.request_focus();
2604                ctx.request_pointer_capture(pointer.pointer_id);
2605                ctx.set_handled();
2606            }
2607            Event::Pointer(pointer)
2608                if pointer.kind == PointerEventKind::Up
2609                    && pointer.button == Some(PointerButton::Primary)
2610                    && self.pressed_header =>
2611            {
2612                let hovered = self
2613                    .header_hit_rect(ctx.bounds())
2614                    .contains(pointer.position);
2615                if hovered {
2616                    self.toggle(ctx);
2617                }
2618                self.set_hovered_header(hovered, ctx);
2619                self.set_pressed_header(false, ctx);
2620                ctx.release_pointer_capture(pointer.pointer_id);
2621                ctx.set_handled();
2622            }
2623            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
2624                self.set_hovered_header(false, ctx);
2625            }
2626            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
2627                if self.pressed_header || self.hovered_header {
2628                    self.set_hovered_header(false, ctx);
2629                    self.set_pressed_header(false, ctx);
2630                    ctx.release_pointer_capture(pointer.pointer_id);
2631                    ctx.set_handled();
2632                }
2633            }
2634            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
2635                match key.key.as_str() {
2636                    "Enter" | " " => {
2637                        self.toggle(ctx);
2638                        ctx.set_handled();
2639                    }
2640                    _ => {}
2641                }
2642            }
2643            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
2644                if self.advance_animations(*time) {
2645                    ctx.request_animation_frame();
2646                }
2647                ctx.request_paint();
2648            }
2649            _ => {}
2650        }
2651    }
2652
2653    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
2654        let theme = self.resolved_theme();
2655        let metrics = theme.metrics;
2656        let gap = self.resolved_gap(metrics);
2657        let action_gap = self.resolved_action_gap(metrics);
2658        let title_style = self.resolved_title_style();
2659        let title_measurement = measure_text(ctx, &self.title, &title_style);
2660        self.title_measurement = Some(title_measurement);
2661        let action_size = self
2662            .header_action
2663            .as_mut()
2664            .map(|action| {
2665                action.measure(
2666                    ctx,
2667                    Constraints::new(Size::ZERO, Size::new(constraints.max.width, f32::INFINITY)),
2668                )
2669            })
2670            .unwrap_or(Size::ZERO);
2671        let header_height = self.title_height(&title_style).max(action_size.height);
2672        let child_size = if self.is_expanded() {
2673            self.child.measure(ctx, constraints)
2674        } else {
2675            Size::ZERO
2676        };
2677        let header_width = if self.header_action.is_some() {
2678            self.disclosure_width(metrics)
2679                + title_measurement.width
2680                + action_gap
2681                + action_size.width
2682        } else {
2683            self.disclosure_width(metrics) + title_measurement.width
2684        };
2685        let natural = Size::new(
2686            header_width.max(child_size.width),
2687            header_height
2688                + if self.is_expanded() && child_size.height > 0.0 {
2689                    gap + child_size.height
2690                } else {
2691                    0.0
2692                },
2693        );
2694
2695        constraints.clamp(natural)
2696    }
2697
2698    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
2699        let theme = self.resolved_theme();
2700        let metrics = theme.metrics;
2701        let gap = self.resolved_gap(metrics);
2702        let title_style = self.resolved_title_style();
2703        let header_height = self.header_height(&title_style);
2704        if let Some(action) = &mut self.header_action {
2705            let action_size = action.child().measured_size();
2706            action.arrange(
2707                ctx,
2708                Rect::new(
2709                    bounds.max_x() - action_size.width.min(bounds.width()),
2710                    bounds.y() + ((header_height - action_size.height) * 0.5).max(0.0),
2711                    action_size.width.min(bounds.width()).max(0.0),
2712                    action_size.height,
2713                ),
2714            );
2715        }
2716        let child_size = if self.is_expanded() {
2717            self.child.child().measured_size()
2718        } else {
2719            Size::ZERO
2720        };
2721        let child_height = if self.is_expanded() {
2722            child_size
2723                .height
2724                .min((bounds.height() - header_height - gap).max(0.0))
2725        } else {
2726            0.0
2727        };
2728        self.child.arrange(
2729            ctx,
2730            Rect::new(
2731                bounds.x(),
2732                bounds.y() + header_height + gap,
2733                bounds.width().min(child_size.width).max(0.0),
2734                child_height,
2735            ),
2736        );
2737    }
2738
2739    fn paint(&self, ctx: &mut PaintCtx) {
2740        let theme = self.resolved_theme();
2741        let metrics = theme.metrics;
2742        let title_style = self.resolved_title_style();
2743        let title_height = self.title_height(&title_style);
2744        let header_height = self.header_height(&title_style);
2745        let title_slot = self.title_rect(ctx.bounds(), header_height, title_height);
2746        if self.collapsible {
2747            let header_hit = self.header_hit_rect(ctx.bounds());
2748            let hover_amount = self.hover_animation.value;
2749            let press_amount = self.press_animation.value;
2750            let focus_amount = self.focus_animation.value;
2751            if focus_amount > AnimatedScalar::EPSILON {
2752                let outset = physical_pixels(ctx, metrics.focus_ring_outset);
2753                ctx.stroke(
2754                    rounded_rect_path(
2755                        header_hit.inflate(outset, outset),
2756                        metrics.indicator_corner_radius + outset,
2757                    ),
2758                    theme
2759                        .palette
2760                        .focus_ring
2761                        .with_alpha(theme.palette.focus_ring.alpha * focus_amount),
2762                    StrokeStyle::new(physical_pixels(ctx, metrics.focus_ring_width)),
2763                );
2764            }
2765            let hover_alpha = (theme.interaction.hover_blend * 0.07 * hover_amount).min(0.08);
2766            let press_alpha = (theme.interaction.selected_blend * 0.48 * press_amount).min(0.14);
2767            let header_fill = if press_alpha > 0.0 {
2768                theme.palette.text.with_alpha(press_alpha)
2769            } else if hover_alpha > 0.0 {
2770                theme.palette.text.with_alpha(hover_alpha)
2771            } else {
2772                theme.palette.surface.with_alpha(0.001)
2773            };
2774            ctx.fill(
2775                rounded_rect_path(header_hit, metrics.indicator_corner_radius),
2776                header_fill,
2777            );
2778            paint_panel_section_disclosure(
2779                ctx,
2780                self.header_rect(ctx.bounds()),
2781                self.expanded,
2782                hover_amount,
2783                press_amount,
2784                &theme,
2785                metrics.panel_section_disclosure_size,
2786            );
2787        }
2788        ctx.push_clip_rect(title_slot);
2789        paint_aligned_text(
2790            ctx,
2791            title_slot,
2792            &self.title,
2793            &title_style,
2794            title_style.line_height,
2795            0.0,
2796        );
2797        ctx.pop_clip();
2798        if let Some(action) = &self.header_action {
2799            action.paint(ctx);
2800        }
2801        if self.is_expanded() {
2802            self.child.paint(ctx);
2803        }
2804    }
2805
2806    fn semantics(&self, ctx: &mut SemanticsCtx) {
2807        let mut section = SemanticsNode::new(
2808            ctx.widget_id(),
2809            SemanticsRole::GenericContainer,
2810            ctx.bounds(),
2811        );
2812        section.name = Some(self.title.clone());
2813        section.state.focused = ctx.is_focused();
2814        section.state.hovered = self.hovered_header;
2815        if self.collapsible {
2816            section.state.expanded = Some(self.expanded);
2817            section.actions = vec![
2818                SemanticsAction::Focus,
2819                SemanticsAction::Expand,
2820                SemanticsAction::Collapse,
2821            ];
2822        }
2823        ctx.push(section);
2824
2825        let title_style = self.resolved_title_style();
2826        let title_height = self.title_height(&title_style);
2827        let header_height = self.header_height(&title_style);
2828        let mut title = SemanticsNode::new(
2829            panel_section_title_id(ctx.widget_id()),
2830            SemanticsRole::Text,
2831            self.title_rect(ctx.bounds(), header_height, title_height),
2832        );
2833        title.parent = Some(ctx.widget_id());
2834        title.name = Some(self.title.clone());
2835        title.value = Some(SemanticsValue::Text(self.title.clone()));
2836        ctx.push(title);
2837
2838        if let Some(action) = &self.header_action {
2839            action.semantics(ctx);
2840        }
2841        if self.is_expanded() {
2842            self.child.semantics(ctx);
2843        }
2844    }
2845
2846    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
2847        if let Some(action) = &self.header_action {
2848            action.visit_children(visitor);
2849        }
2850        if self.is_expanded() {
2851            self.child.visit_children(visitor);
2852        }
2853    }
2854
2855    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
2856        if let Some(action) = &mut self.header_action {
2857            action.visit_children_mut(visitor);
2858        }
2859        if self.is_expanded() {
2860            self.child.visit_children_mut(visitor);
2861        }
2862    }
2863
2864    fn accepts_focus(&self) -> bool {
2865        self.collapsible
2866    }
2867
2868    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2869        if self.collapsible {
2870            let theme = self.resolved_theme();
2871            set_focus_animation_target(
2872                &mut self.focus_animation,
2873                focused as u8 as f32,
2874                &theme,
2875                ctx,
2876            );
2877            ctx.request_paint();
2878            ctx.request_semantics();
2879        }
2880    }
2881}
2882
2883pub(super) fn panel_section_title_id(parent: WidgetId) -> WidgetId {
2884    const TAG: u64 = 3_u64 << 50;
2885    const LOW_MASK: u64 = (1_u64 << 50) - 1;
2886
2887    WidgetId::new(TAG | (parent.get().wrapping_mul(431).wrapping_add(7) & LOW_MASK))
2888}
2889
2890pub(super) fn paint_panel_section_disclosure(
2891    ctx: &mut PaintCtx,
2892    header: Rect,
2893    expanded: bool,
2894    hover_amount: f32,
2895    press_amount: f32,
2896    theme: &DefaultTheme,
2897    disclosure_size: f32,
2898) {
2899    let palette = theme.palette;
2900    let center = Point::new(
2901        header.x() + disclosure_size * 0.5,
2902        header.y() + header.height() * 0.5,
2903    );
2904    let half = disclosure_size * 0.25;
2905    let tip = disclosure_size * 0.22;
2906    let base_color = palette.text.with_alpha(0.68);
2907    let hover_color = mix_color(base_color, palette.text, hover_amount);
2908    let color = mix_color(hover_color, palette.text, press_amount);
2909    let mut builder = PathBuilder::new();
2910    if expanded {
2911        builder
2912            .move_to(Point::new(center.x - half, center.y - tip * 0.55))
2913            .line_to(Point::new(center.x + half, center.y - tip * 0.55))
2914            .line_to(Point::new(center.x, center.y + tip));
2915    } else {
2916        builder
2917            .move_to(Point::new(center.x - tip * 0.55, center.y - half))
2918            .line_to(Point::new(center.x + tip, center.y))
2919            .line_to(Point::new(center.x - tip * 0.55, center.y + half));
2920    }
2921    ctx.fill(builder.build(), color);
2922}
2923
2924pub struct DockPanel {
2925    pub(super) theme: Box<DefaultTheme>,
2926    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
2927    pub(super) name: Option<String>,
2928    pub(super) title: String,
2929    pub(super) header_height: Option<f32>,
2930    pub(super) padding: Option<Insets>,
2931    pub(super) background: Option<Color>,
2932    pub(super) header_background: Option<Color>,
2933    pub(super) child: SingleChild,
2934    pub(super) title_measurement: Option<TextMeasurement>,
2935}
2936
2937impl DockPanel {
2938    pub fn new<W>(title: impl Into<String>, child: W) -> Self
2939    where
2940        W: Widget + 'static,
2941    {
2942        Self {
2943            theme: Box::new(DefaultTheme::default()),
2944            theme_reader: None,
2945            name: None,
2946            title: title.into(),
2947            header_height: None,
2948            padding: None,
2949            background: None,
2950            header_background: None,
2951            child: SingleChild::new(child),
2952            title_measurement: None,
2953        }
2954    }
2955
2956    pub fn theme(mut self, theme: DefaultTheme) -> Self {
2957        self.theme = Box::new(theme);
2958        self.theme_reader = None;
2959        self
2960    }
2961
2962    pub fn theme_when<F>(mut self, theme: F) -> Self
2963    where
2964        F: Fn() -> DefaultTheme + 'static,
2965    {
2966        self.theme_reader = Some(Box::new(theme));
2967        self
2968    }
2969
2970    pub fn name(mut self, name: impl Into<String>) -> Self {
2971        self.name = Some(name.into());
2972        self
2973    }
2974
2975    pub fn header_height(mut self, height: f32) -> Self {
2976        self.header_height = Some(height.max(0.0));
2977        self
2978    }
2979
2980    pub fn padding(mut self, padding: Insets) -> Self {
2981        self.padding = Some(padding);
2982        self
2983    }
2984
2985    pub fn background(mut self, color: Color) -> Self {
2986        self.background = Some(color);
2987        self
2988    }
2989
2990    pub fn header_background(mut self, color: Color) -> Self {
2991        self.header_background = Some(color);
2992        self
2993    }
2994
2995    pub fn child(&self) -> &sui_runtime::WidgetPod {
2996        self.child.child()
2997    }
2998
2999    pub fn child_mut(&mut self) -> &mut sui_runtime::WidgetPod {
3000        self.child.child_mut()
3001    }
3002
3003    pub(super) fn resolved_title_style(&self) -> TextStyle {
3004        let theme = self.resolved_theme();
3005        text_token_style(&theme, theme.text.sm, theme.palette.text)
3006    }
3007
3008    pub(super) fn resolved_theme(&self) -> DefaultTheme {
3009        self.theme_reader
3010            .as_ref()
3011            .map(|theme| theme())
3012            .unwrap_or(*self.theme)
3013    }
3014
3015    pub(super) fn resolved_header_height(&self, metrics: ControlMetrics) -> f32 {
3016        self.header_height
3017            .unwrap_or(metrics.dock_panel_header_height)
3018    }
3019
3020    pub(super) fn resolved_padding(&self, metrics: ControlMetrics) -> Insets {
3021        self.padding.unwrap_or(metrics.dock_panel_padding)
3022    }
3023
3024    pub(super) fn title_height(&self, style: &TextStyle) -> f32 {
3025        self.title_measurement
3026            .map(|measurement| measurement.height)
3027            .unwrap_or(style.line_height)
3028            .max(style.line_height)
3029    }
3030
3031    pub(super) fn header_rect(&self, bounds: Rect) -> Rect {
3032        let theme = self.resolved_theme();
3033        Rect::new(
3034            bounds.x(),
3035            bounds.y(),
3036            bounds.width(),
3037            self.resolved_header_height(theme.metrics),
3038        )
3039    }
3040
3041    pub(super) fn content_rect(&self, bounds: Rect) -> Rect {
3042        let theme = self.resolved_theme();
3043        let metrics = theme.metrics;
3044        let header_height = self.resolved_header_height(metrics);
3045        inset_rect(
3046            Rect::new(
3047                bounds.x(),
3048                bounds.y() + header_height,
3049                bounds.width(),
3050                (bounds.height() - header_height).max(0.0),
3051            ),
3052            self.resolved_padding(metrics),
3053        )
3054    }
3055
3056    pub(super) fn child_constraints(&self, constraints: Constraints) -> Constraints {
3057        let theme = self.resolved_theme();
3058        let metrics = theme.metrics;
3059        let padding = self.resolved_padding(metrics);
3060        let header_height = self.resolved_header_height(metrics);
3061        let width = if constraints.max.width.is_finite() {
3062            (constraints.max.width - padding.left - padding.right).max(0.0)
3063        } else {
3064            f32::INFINITY
3065        };
3066        let height = if constraints.max.height.is_finite() {
3067            (constraints.max.height - header_height - padding.top - padding.bottom).max(0.0)
3068        } else {
3069            f32::INFINITY
3070        };
3071        Constraints::new(Size::ZERO, Size::new(width, height))
3072    }
3073}
3074
3075impl Widget for DockPanel {
3076    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
3077        let theme = self.resolved_theme();
3078        let metrics = theme.metrics;
3079        let padding = self.resolved_padding(metrics);
3080        let header_height = self.resolved_header_height(metrics);
3081        let title_style = self.resolved_title_style();
3082        let title_measurement = measure_text(ctx, &self.title, &title_style);
3083        self.title_measurement = Some(title_measurement);
3084        let child_size = self.child.measure(ctx, self.child_constraints(constraints));
3085        let natural = Size::new(
3086            (title_measurement.width + padding.left + padding.right)
3087                .max(child_size.width + padding.left + padding.right),
3088            header_height + padding.top + child_size.height + padding.bottom,
3089        );
3090
3091        constraints.clamp(natural)
3092    }
3093
3094    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
3095        self.child.arrange(ctx, self.content_rect(bounds));
3096    }
3097
3098    fn paint(&self, ctx: &mut PaintCtx) {
3099        let theme = self.resolved_theme();
3100        let palette = theme.palette;
3101        let metrics = theme.metrics;
3102        let padding = self.resolved_padding(metrics);
3103        let bounds = ctx.bounds();
3104        let header = self.header_rect(bounds);
3105        let title_style = self.resolved_title_style();
3106        let title_height = self.title_height(&title_style);
3107        let title_slot = Rect::new(
3108            header.x() + padding.left,
3109            header.y() + ((header.height() - title_height) * 0.5).max(0.0),
3110            (header.width() - padding.left - padding.right).max(0.0),
3111            title_height,
3112        );
3113        let divider_height = physical_pixels(ctx, 1.0);
3114
3115        ctx.fill_rect(bounds, self.background.unwrap_or(palette.surface));
3116        ctx.fill_rect(
3117            header,
3118            self.header_background
3119                .unwrap_or_else(|| palette.surface_raised.with_alpha(0.72)),
3120        );
3121        ctx.fill_rect(
3122            Rect::new(
3123                header.x(),
3124                header.max_y() - divider_height,
3125                header.width(),
3126                divider_height,
3127            ),
3128            palette.border,
3129        );
3130        ctx.push_clip_rect(title_slot);
3131        paint_aligned_text(
3132            ctx,
3133            title_slot,
3134            &self.title,
3135            &title_style,
3136            title_style.line_height,
3137            0.0,
3138        );
3139        ctx.pop_clip();
3140
3141        self.child.paint(ctx);
3142    }
3143
3144    fn semantics(&self, ctx: &mut SemanticsCtx) {
3145        let theme = self.resolved_theme();
3146        let padding = self.resolved_padding(theme.metrics);
3147        let mut panel = SemanticsNode::new(
3148            ctx.widget_id(),
3149            SemanticsRole::GenericContainer,
3150            ctx.bounds(),
3151        );
3152        panel.name = Some(self.name.clone().unwrap_or_else(|| self.title.clone()));
3153        ctx.push(panel);
3154
3155        let title_style = self.resolved_title_style();
3156        let title_height = self.title_height(&title_style);
3157        let header = self.header_rect(ctx.bounds());
3158        let mut title = SemanticsNode::new(
3159            dock_panel_title_id(ctx.widget_id()),
3160            SemanticsRole::Text,
3161            Rect::new(
3162                header.x() + padding.left,
3163                header.y() + ((header.height() - title_height) * 0.5).max(0.0),
3164                (header.width() - padding.left - padding.right).max(0.0),
3165                title_height,
3166            ),
3167        );
3168        title.parent = Some(ctx.widget_id());
3169        title.name = Some(self.title.clone());
3170        title.value = Some(SemanticsValue::Text(self.title.clone()));
3171        ctx.push(title);
3172
3173        self.child.semantics(ctx);
3174    }
3175
3176    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
3177        self.child.visit_children(visitor);
3178    }
3179
3180    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
3181        self.child.visit_children_mut(visitor);
3182    }
3183}
3184
3185pub(super) fn dock_panel_title_id(parent: WidgetId) -> WidgetId {
3186    const TAG: u64 = 5_u64 << 50;
3187    const LOW_MASK: u64 = (1_u64 << 50) - 1;
3188
3189    WidgetId::new(TAG | (parent.get().wrapping_mul(467).wrapping_add(11) & LOW_MASK))
3190}