Skip to main content

sui_widgets/composites/
surfaces.rs

1use crate::DefaultTheme;
2use crate::SemanticTone;
3use crate::composites::forms::set_hover_animation_target;
4use crate::composites::indicators::{inset_rect, mix_color, physical_pixels, rounded_rect_path};
5use crate::composites::popups::AnimatedScalar;
6use crate::paint_theme_shadow;
7use sui_core::Color;
8use sui_core::Event;
9use sui_core::PointerEventKind;
10use sui_core::Rect;
11use sui_core::SemanticsNode;
12use sui_core::SemanticsRole;
13use sui_core::Size;
14use sui_core::WakeEvent;
15use sui_core::WidgetId;
16use sui_layout::Constraints;
17use sui_layout::Padding as Insets;
18use sui_runtime::ArrangeCtx;
19use sui_runtime::EventCtx;
20use sui_runtime::MeasureCtx;
21use sui_runtime::PaintCtx;
22use sui_runtime::SemanticsCtx;
23use sui_runtime::SingleChild;
24use sui_runtime::Widget;
25use sui_runtime::WidgetPod;
26use sui_runtime::WidgetPodMutVisitor;
27use sui_runtime::WidgetPodVisitor;
28use sui_scene::StrokeStyle;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SurfaceRole {
32    Window,
33    Sidebar,
34    Panel,
35    Titlebar,
36    Field,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum SurfaceBorder {
41    None,
42    All,
43    Top,
44    Right,
45    Bottom,
46    Left,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum SurfaceElevation {
51    None,
52    Small,
53    Medium,
54    Large,
55}
56
57#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
58pub enum SurfaceAppearance {
59    /// The surface token associated with [`SurfaceRole`].
60    #[default]
61    Standard,
62    /// The shared raised-surface token, useful for elevated chips and cards.
63    Raised,
64    /// A low-emphasis semantic wash.
65    Soft,
66    /// A solid semantic fill.
67    Filled,
68}
69
70pub struct Surface {
71    pub(super) theme: Box<DefaultTheme>,
72    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
73    pub(super) name: Option<String>,
74    pub(super) role: SurfaceRole,
75    pub(super) appearance: SurfaceAppearance,
76    pub(super) tone: SemanticTone,
77    pub(super) border: SurfaceBorder,
78    pub(super) elevation: SurfaceElevation,
79    pub(super) radius: f32,
80    pub(super) padding: Insets,
81    pub(super) fill_width: bool,
82    pub(super) fill_height: bool,
83    pub(super) child: SingleChild,
84}
85
86impl Surface {
87    pub fn new<W>(role: SurfaceRole, child: W) -> Self
88    where
89        W: Widget + 'static,
90    {
91        Self {
92            theme: Box::new(DefaultTheme::default()),
93            theme_reader: None,
94            name: None,
95            role,
96            appearance: SurfaceAppearance::Standard,
97            tone: SemanticTone::Neutral,
98            border: SurfaceBorder::None,
99            elevation: SurfaceElevation::None,
100            radius: 0.0,
101            padding: Insets::ZERO,
102            fill_width: false,
103            fill_height: false,
104            child: SingleChild::new(child),
105        }
106    }
107
108    pub fn window<W>(child: W) -> Self
109    where
110        W: Widget + 'static,
111    {
112        Self::new(SurfaceRole::Window, child)
113    }
114
115    pub fn sidebar<W>(child: W) -> Self
116    where
117        W: Widget + 'static,
118    {
119        Self::new(SurfaceRole::Sidebar, child).border(SurfaceBorder::Right)
120    }
121
122    pub fn panel<W>(child: W) -> Self
123    where
124        W: Widget + 'static,
125    {
126        Self::new(SurfaceRole::Panel, child)
127            .border(SurfaceBorder::All)
128            .radius(8.0)
129    }
130
131    pub fn titlebar<W>(child: W) -> Self
132    where
133        W: Widget + 'static,
134    {
135        Self::new(SurfaceRole::Titlebar, child).border(SurfaceBorder::Bottom)
136    }
137
138    pub fn field<W>(child: W) -> Self
139    where
140        W: Widget + 'static,
141    {
142        Self::new(SurfaceRole::Field, child)
143            .border(SurfaceBorder::All)
144            .radius(6.0)
145    }
146
147    pub fn theme(mut self, theme: DefaultTheme) -> Self {
148        self.theme = Box::new(theme);
149        self.theme_reader = None;
150        self
151    }
152
153    pub fn theme_when<F>(mut self, theme: F) -> Self
154    where
155        F: Fn() -> DefaultTheme + 'static,
156    {
157        self.theme_reader = Some(Box::new(theme));
158        self
159    }
160
161    pub fn name(mut self, name: impl Into<String>) -> Self {
162        self.name = Some(name.into());
163        self
164    }
165
166    pub fn border(mut self, border: SurfaceBorder) -> Self {
167        self.border = border;
168        self
169    }
170
171    pub fn appearance(mut self, appearance: SurfaceAppearance) -> Self {
172        self.appearance = appearance;
173        self
174    }
175
176    pub fn tone(mut self, tone: SemanticTone) -> Self {
177        self.tone = tone;
178        self
179    }
180
181    pub fn elevation(mut self, elevation: SurfaceElevation) -> Self {
182        self.elevation = elevation;
183        self
184    }
185
186    pub fn radius(mut self, radius: f32) -> Self {
187        self.radius = radius.max(0.0);
188        self
189    }
190
191    pub fn padding(mut self, padding: Insets) -> Self {
192        self.padding = padding;
193        self
194    }
195
196    pub fn fill(mut self) -> Self {
197        self.fill_width = true;
198        self.fill_height = true;
199        self
200    }
201
202    pub fn fill_width(mut self) -> Self {
203        self.fill_width = true;
204        self
205    }
206
207    pub fn fill_height(mut self) -> Self {
208        self.fill_height = true;
209        self
210    }
211
212    pub(super) fn resolved_theme(&self) -> DefaultTheme {
213        self.theme_reader
214            .as_ref()
215            .map(|theme| theme())
216            .unwrap_or(*self.theme)
217    }
218
219    pub(super) fn background_for_role(theme: &DefaultTheme, role: SurfaceRole) -> Color {
220        match role {
221            SurfaceRole::Window => theme.surfaces.window,
222            SurfaceRole::Sidebar => theme.surfaces.sidebar,
223            SurfaceRole::Panel => theme.surfaces.panel,
224            SurfaceRole::Titlebar => theme.surfaces.titlebar,
225            SurfaceRole::Field => theme.surfaces.field,
226        }
227    }
228
229    pub(super) fn resolved_colors(&self, theme: &DefaultTheme) -> (Color, Color) {
230        match self.appearance {
231            SurfaceAppearance::Standard => (
232                Self::background_for_role(theme, self.role),
233                theme.surfaces.border,
234            ),
235            SurfaceAppearance::Raised => (theme.palette.surface_raised, theme.surfaces.border),
236            SurfaceAppearance::Soft => {
237                let (fill, _) = theme.semantic_tone_soft_colors(self.tone);
238                let border = if self.tone == SemanticTone::Neutral {
239                    theme.surfaces.border
240                } else {
241                    theme.semantic_tone_color(self.tone).with_alpha(0.36)
242                };
243                (fill, border)
244            }
245            SurfaceAppearance::Filled => {
246                let (fill, _) = theme.semantic_tone_colors(self.tone);
247                (fill, fill)
248            }
249        }
250    }
251
252    pub(super) fn content_rect(&self, bounds: Rect) -> Rect {
253        inset_rect(bounds, self.padding)
254    }
255}
256
257impl Widget for Surface {
258    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
259        let max_child = Size::new(
260            if constraints.max.width.is_finite() {
261                (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
262            } else {
263                f32::INFINITY
264            },
265            if constraints.max.height.is_finite() {
266                (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
267            } else {
268                f32::INFINITY
269            },
270        );
271        // `arrange` always gives the child the complete content rect. Keep the
272        // measurement constraints consistent with that contract so
273        // width-dependent children (notably wrapping text in a flex item) are
274        // not measured narrowly and then stretched without being remeasured.
275        // A filling surface makes the corresponding content axis tight even
276        // when its own parent supplied loose constraints.
277        let min_child = Size::new(
278            if self.fill_width && max_child.width.is_finite() {
279                max_child.width
280            } else {
281                (constraints.min.width - self.padding.left - self.padding.right)
282                    .max(0.0)
283                    .min(max_child.width)
284            },
285            if self.fill_height && max_child.height.is_finite() {
286                max_child.height
287            } else {
288                (constraints.min.height - self.padding.top - self.padding.bottom)
289                    .max(0.0)
290                    .min(max_child.height)
291            },
292        );
293        let child_size = self
294            .child
295            .measure(ctx, Constraints::new(min_child, max_child));
296        let mut size = Size::new(
297            child_size.width + self.padding.left + self.padding.right,
298            child_size.height + self.padding.top + self.padding.bottom,
299        );
300        if self.fill_width && constraints.max.width.is_finite() {
301            size.width = constraints.max.width;
302        }
303        if self.fill_height && constraints.max.height.is_finite() {
304            size.height = constraints.max.height;
305        }
306        constraints.clamp(size)
307    }
308
309    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
310        self.child.arrange(ctx, self.content_rect(bounds));
311    }
312
313    fn paint(&self, ctx: &mut PaintCtx) {
314        let theme = self.resolved_theme();
315        let bounds = ctx.bounds();
316        let radius = self.radius.min(bounds.width().min(bounds.height()) * 0.5);
317
318        let shadow = match self.elevation {
319            SurfaceElevation::None => None,
320            SurfaceElevation::Small => Some(&theme.shadows.box_shadow.sm),
321            SurfaceElevation::Medium => Some(&theme.shadows.box_shadow.md),
322            SurfaceElevation::Large => Some(&theme.shadows.box_shadow.lg),
323        };
324        if let Some(shadow) = shadow {
325            paint_theme_shadow(ctx, bounds, [radius; 4], shadow);
326        }
327
328        let (background, border) = self.resolved_colors(&theme);
329        if radius > 0.0 {
330            ctx.fill(rounded_rect_path(bounds, radius), background);
331        } else {
332            ctx.fill_rect(bounds, background);
333        }
334
335        let stroke_width = physical_pixels(ctx, theme.metrics.border_width.max(1.0));
336        match self.border {
337            SurfaceBorder::None => {}
338            SurfaceBorder::All => {
339                ctx.stroke(
340                    rounded_rect_path(bounds, radius),
341                    border,
342                    StrokeStyle::new(stroke_width),
343                );
344            }
345            SurfaceBorder::Top => ctx.fill_rect(
346                Rect::new(bounds.x(), bounds.y(), bounds.width(), stroke_width),
347                border,
348            ),
349            SurfaceBorder::Right => ctx.fill_rect(
350                Rect::new(
351                    bounds.max_x() - stroke_width,
352                    bounds.y(),
353                    stroke_width,
354                    bounds.height(),
355                ),
356                border,
357            ),
358            SurfaceBorder::Bottom => ctx.fill_rect(
359                Rect::new(
360                    bounds.x(),
361                    bounds.max_y() - stroke_width,
362                    bounds.width(),
363                    stroke_width,
364                ),
365                border,
366            ),
367            SurfaceBorder::Left => ctx.fill_rect(
368                Rect::new(bounds.x(), bounds.y(), stroke_width, bounds.height()),
369                border,
370            ),
371        }
372
373        self.child.paint(ctx);
374    }
375
376    fn semantics(&self, ctx: &mut SemanticsCtx) {
377        if let Some(name) = &self.name {
378            let mut node = SemanticsNode::new(
379                ctx.widget_id(),
380                SemanticsRole::GenericContainer,
381                ctx.bounds(),
382            );
383            node.name = Some(name.clone());
384            ctx.push(node);
385        }
386        self.child.semantics(ctx);
387    }
388
389    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
390        self.child.visit_children(visitor);
391    }
392
393    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
394        self.child.visit_children_mut(visitor);
395    }
396}
397
398/// A reusable field frame for compound editors such as search/composer rows.
399///
400/// The child owns editing, focus, and semantics. The frame owns only the
401/// standard field surface and border, which avoids applications repainting
402/// control chrome around otherwise stock SUI editors. Use [`Self::focused_when`]
403/// when the wrapped editor publishes its focus state.
404pub struct FramedField {
405    pub(super) theme: Box<DefaultTheme>,
406    pub(super) theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
407    pub(super) name: Option<String>,
408    pub(super) description: Option<String>,
409    pub(super) padding: Insets,
410    pub(super) min_height: Option<f32>,
411    pub(super) fill_width: bool,
412    pub(super) focused: Option<bool>,
413    pub(super) focused_reader: Option<Box<dyn Fn() -> bool>>,
414    pub(super) invalid: bool,
415    pub(super) invalid_reader: Option<Box<dyn Fn() -> bool>>,
416    pub(super) hovered: bool,
417    pub(super) hover_animation: AnimatedScalar,
418    pub(super) child: SingleChild,
419}
420
421impl FramedField {
422    pub fn new<W>(child: W) -> Self
423    where
424        W: Widget + 'static,
425    {
426        Self {
427            theme: Box::new(DefaultTheme::default()),
428            theme_reader: None,
429            name: None,
430            description: None,
431            padding: Insets::ZERO,
432            min_height: None,
433            fill_width: false,
434            focused: None,
435            focused_reader: None,
436            invalid: false,
437            invalid_reader: None,
438            hovered: false,
439            hover_animation: AnimatedScalar::new(0.0),
440            child: SingleChild::new(child),
441        }
442    }
443
444    pub fn theme(mut self, theme: DefaultTheme) -> Self {
445        self.theme = Box::new(theme);
446        self.theme_reader = None;
447        self
448    }
449
450    pub fn theme_when<F>(mut self, theme: F) -> Self
451    where
452        F: Fn() -> DefaultTheme + 'static,
453    {
454        self.theme_reader = Some(Box::new(theme));
455        self
456    }
457
458    pub fn name(mut self, name: impl Into<String>) -> Self {
459        self.name = Some(name.into());
460        self
461    }
462
463    pub fn description(mut self, description: impl Into<String>) -> Self {
464        self.description = Some(description.into());
465        self
466    }
467
468    pub fn padding(mut self, padding: Insets) -> Self {
469        self.padding = padding;
470        self
471    }
472
473    pub fn min_height(mut self, min_height: f32) -> Self {
474        self.min_height = Some(min_height.max(0.0));
475        self
476    }
477
478    pub fn fill_width(mut self) -> Self {
479        self.fill_width = true;
480        self
481    }
482
483    pub fn focused(mut self, focused: bool) -> Self {
484        self.focused = Some(focused);
485        self.focused_reader = None;
486        self
487    }
488
489    pub fn focused_when<F>(mut self, focused: F) -> Self
490    where
491        F: Fn() -> bool + 'static,
492    {
493        self.focused_reader = Some(Box::new(focused));
494        self
495    }
496
497    pub fn invalid(mut self, invalid: bool) -> Self {
498        self.invalid = invalid;
499        self.invalid_reader = None;
500        self
501    }
502
503    pub fn invalid_when<F>(mut self, invalid: F) -> Self
504    where
505        F: Fn() -> bool + 'static,
506    {
507        self.invalid_reader = Some(Box::new(invalid));
508        self
509    }
510
511    pub(super) fn resolved_theme(&self) -> DefaultTheme {
512        self.theme_reader
513            .as_ref()
514            .map(|theme| theme())
515            .unwrap_or(*self.theme)
516    }
517
518    pub(super) fn child_contains(&self, target: WidgetId) -> bool {
519        if self.child.child().id() == target {
520            return true;
521        }
522        struct Finder {
523            target: WidgetId,
524            found: bool,
525        }
526        impl WidgetPodVisitor for Finder {
527            fn visit(&mut self, child: &WidgetPod) {
528                if self.found {
529                    return;
530                }
531                if child.id() == self.target {
532                    self.found = true;
533                } else {
534                    child.visit_children(self);
535                }
536            }
537        }
538        let mut finder = Finder {
539            target,
540            found: false,
541        };
542        self.child.child().visit_children(&mut finder);
543        finder.found
544    }
545
546    pub(super) fn is_focused(&self, focused_widget_id: Option<WidgetId>) -> bool {
547        if let Some(focused) = &self.focused_reader {
548            return focused();
549        }
550        if let Some(focused) = self.focused {
551            return focused;
552        }
553        focused_widget_id
554            .map(|focused| self.child_contains(focused))
555            .unwrap_or(false)
556    }
557
558    pub(super) fn is_invalid(&self) -> bool {
559        self.invalid_reader
560            .as_ref()
561            .map(|invalid| invalid())
562            .unwrap_or(self.invalid)
563    }
564
565    pub(super) fn content_rect(&self, bounds: Rect) -> Rect {
566        inset_rect(bounds, self.padding)
567    }
568
569    pub(super) fn set_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
570        if self.hovered == hovered {
571            return;
572        }
573        self.hovered = hovered;
574        let theme = self.resolved_theme();
575        set_hover_animation_target(&mut self.hover_animation, hovered as u8 as f32, &theme, ctx);
576        ctx.request_paint();
577    }
578}
579
580impl Widget for FramedField {
581    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
582        match event {
583            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
584                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
585            }
586            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Enter => {
587                self.set_hovered(ctx.bounds().contains(pointer.position), ctx);
588            }
589            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Leave => {
590                self.set_hovered(false, ctx);
591            }
592            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
593                let previous = self.hover_animation.value;
594                if self.hover_animation.advance(*time) {
595                    ctx.request_animation_frame();
596                }
597                if self.hover_animation.changed_since(previous) {
598                    ctx.request_paint();
599                }
600            }
601            _ => {}
602        }
603    }
604
605    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
606        let max_child = Size::new(
607            if constraints.max.width.is_finite() {
608                (constraints.max.width - self.padding.left - self.padding.right).max(0.0)
609            } else {
610                f32::INFINITY
611            },
612            if constraints.max.height.is_finite() {
613                (constraints.max.height - self.padding.top - self.padding.bottom).max(0.0)
614            } else {
615                f32::INFINITY
616            },
617        );
618        let child = self
619            .child
620            .measure(ctx, Constraints::new(Size::ZERO, max_child));
621        let theme = self.resolved_theme();
622        let mut size = Size::new(
623            child.width + self.padding.left + self.padding.right,
624            (child.height + self.padding.top + self.padding.bottom)
625                .max(self.min_height.unwrap_or(theme.metrics.min_height)),
626        );
627        if self.fill_width && constraints.max.width.is_finite() {
628            size.width = constraints.max.width;
629        }
630        constraints.clamp(size)
631    }
632
633    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
634        self.child.arrange(ctx, self.content_rect(bounds));
635    }
636
637    fn paint(&self, ctx: &mut PaintCtx) {
638        let theme = self.resolved_theme();
639        let bounds = ctx.bounds();
640        let radius = theme
641            .metrics
642            .corner_radius
643            .min(bounds.width().min(bounds.height()) * 0.5);
644        let invalid = self.is_invalid();
645        let focused = self.is_focused(ctx.focused_widget_id());
646        let interaction_border = mix_color(
647            theme.palette.border,
648            theme.palette.border_hover,
649            self.hover_animation.value,
650        );
651        let border = if invalid {
652            theme.semantic_tone_color(SemanticTone::Danger)
653        } else if focused {
654            theme.palette.border_focus
655        } else {
656            interaction_border
657        };
658        let background = mix_color(
659            theme.surfaces.field,
660            theme.palette.surface_focus,
661            focused as u8 as f32,
662        );
663        ctx.fill(rounded_rect_path(bounds, radius), background);
664        ctx.stroke(
665            rounded_rect_path(bounds, radius),
666            border,
667            StrokeStyle::new(physical_pixels(ctx, theme.metrics.border_width.max(1.0))),
668        );
669        if focused {
670            let outset = physical_pixels(ctx, theme.metrics.focus_ring_outset);
671            ctx.stroke(
672                rounded_rect_path(bounds.inflate(outset, outset), radius + outset),
673                if invalid {
674                    theme.semantic_tone_color(SemanticTone::Danger)
675                } else {
676                    theme.palette.focus_ring
677                },
678                StrokeStyle::new(physical_pixels(ctx, theme.metrics.focus_ring_width)),
679            );
680        }
681        self.child.paint(ctx);
682    }
683
684    fn semantics(&self, ctx: &mut SemanticsCtx) {
685        if self.name.is_some() || self.description.is_some() {
686            let mut node = SemanticsNode::new(
687                ctx.widget_id(),
688                SemanticsRole::GenericContainer,
689                ctx.bounds(),
690            );
691            node.name = self.name.clone();
692            node.description = self.description.clone();
693            node.state.focused = self.is_focused(ctx.focused_widget_id());
694            node.state.hovered = self.hovered;
695            ctx.push(node);
696        }
697        self.child.semantics(ctx);
698    }
699
700    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
701        self.child.visit_children(visitor);
702    }
703
704    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
705        self.child.visit_children_mut(visitor);
706    }
707}