ailloli_ui_widgets/controls/
switch.rs

1//! Accessible binary switches with controlled or two-way-bound state.
2
3use std::rc::Rc;
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::geometry::{Constraints, Rect, Size};
9use ailloli_ui_core::style::{
10    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
11};
12use ailloli_ui_core::{Color, Theme};
13use ailloli_ui_runtime::component::{Binding, IntoView, Memo, Signal, View, Widget};
14use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy};
15use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
16use ailloli_ui_runtime::scene::PaintCtx;
17use ailloli_ui_runtime::{DrawBorder, DrawBoxShadow, DrawCmd, DrawRRect};
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20/// Built-in geometry choices for a [`Switch`].
21///
22/// # Examples
23///
24/// ```
25/// use ailloli_ui_widgets::controls::SwitchSize;
26/// assert_eq!(SwitchSize::default(), SwitchSize::Default);
27/// ```
28pub enum SwitchSize {
29    /// `36 × 20` track with a 14-pixel thumb.
30    Compact,
31    /// `46 × 26` track with a 20-pixel thumb.
32    #[default]
33    Default,
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37/// Main axis along which a switch thumb moves.
38///
39/// # Examples
40///
41/// ```
42/// use ailloli_ui_widgets::controls::SwitchOrientation;
43/// assert_eq!(SwitchOrientation::default(), SwitchOrientation::Horizontal);
44/// ```
45pub enum SwitchOrientation {
46    /// Off is left and on is right.
47    #[default]
48    Horizontal,
49    /// Off is top and on is bottom.
50    Vertical,
51}
52
53#[derive(Clone, Debug, PartialEq)]
54/// Resolved paint and logical-pixel geometry for a [`Switch`].
55///
56/// # Examples
57///
58/// ```
59/// use ailloli_ui_core::Theme;
60/// use ailloli_ui_widgets::controls::{SwitchSize, SwitchStyle};
61/// let style = SwitchStyle::from_theme(Theme::dark(), SwitchSize::Compact);
62/// assert_eq!((style.width, style.height), (36.0, 20.0));
63/// assert_eq!(style.thumb_size, 14.0);
64/// ```
65pub struct SwitchStyle {
66    /// Idle off-track fill.
67    pub track_off: Color,
68    /// Hovered off-track fill.
69    pub track_off_hovered: Color,
70    /// Pressed off-track fill; pressed takes precedence over hover.
71    pub track_off_pressed: Color,
72    /// Idle on-track fill.
73    pub track_on: Color,
74    /// Hovered on-track fill.
75    pub track_on_hovered: Color,
76    /// Pressed on-track fill; pressed takes precedence over hover.
77    pub track_on_pressed: Color,
78    /// Enabled thumb fill.
79    pub thumb: Color,
80    /// Disabled thumb fill before opacity is applied.
81    pub thumb_disabled: Color,
82    /// Border used while off.
83    pub border_off: Border,
84    /// Border used while on.
85    pub border_on: Border,
86    /// Border painted outside a focused, enabled switch.
87    pub focus_ring: Border,
88    /// Track shadows painted in vector order.
89    pub shadows: Vec<BoxShadow>,
90    /// Horizontal-orientation intrinsic width in logical pixels.
91    pub width: f32,
92    /// Horizontal-orientation intrinsic height in logical pixels.
93    pub height: f32,
94    /// Requested square thumb size in logical pixels.
95    pub thumb_size: f32,
96    /// Thumb inset from the off/on end in logical pixels.
97    pub inset: f32,
98    /// Track corner radius in logical pixels.
99    pub track_radius: f32,
100    /// Thumb corner radius in logical pixels.
101    pub thumb_radius: f32,
102    /// Gap from track bounds to focus ring in logical pixels.
103    pub focus_ring_offset: f32,
104    /// Alpha multiplier applied to disabled paint, normally in `0.0..=1.0`.
105    pub disabled_opacity: f32,
106}
107
108impl Default for SwitchStyle {
109    fn default() -> Self {
110        Self::from_theme(Theme::default(), SwitchSize::Default)
111    }
112}
113
114impl SwitchStyle {
115    /// Resolves colors and geometry for `size` from `theme`.
116    ///
117    /// Both built-in sizes use a 3-logical-pixel inset and no shadows.
118    ///
119    /// # Examples
120    ///
121    /// ```
122    /// use ailloli_ui_core::Theme;
123    /// use ailloli_ui_widgets::controls::{SwitchSize, SwitchStyle};
124    /// let style = SwitchStyle::from_theme(Theme::dark(), SwitchSize::Default);
125    /// assert_eq!((style.width, style.height), (46.0, 26.0));
126    /// assert_eq!(style.inset, 3.0);
127    /// ```
128    pub fn from_theme(theme: Theme, size: SwitchSize) -> Self {
129        let palette = theme.palette();
130        let (width, height, thumb_size, inset) = match size {
131            SwitchSize::Compact => (36.0, 20.0, 14.0, 3.0),
132            SwitchSize::Default => (46.0, 26.0, 20.0, 3.0),
133        };
134        Self {
135            track_off: palette.surface_elevated,
136            track_off_hovered: Color::hex_rgb(0x20252A),
137            track_off_pressed: Color::hex_rgb(0x15191D),
138            track_on: palette.accent,
139            track_on_hovered: theme.button_bg_hover,
140            track_on_pressed: theme.button_bg_pressed,
141            thumb: palette.text,
142            thumb_disabled: palette.text_muted,
143            border_off: Border::new(1.0, palette.border),
144            border_on: Border::new(1.0, palette.accent.with_alpha(0.86)),
145            focus_ring: Border::new(2.0, palette.focus),
146            shadows: Vec::new(),
147            width,
148            height,
149            thumb_size,
150            inset,
151            track_radius: height * 0.5,
152            thumb_radius: thumb_size * 0.5,
153            focus_ring_offset: 3.0,
154            disabled_opacity: 0.45,
155        }
156    }
157
158    /// Expands `rect` to contain every shadow and the possible focus ring.
159    fn visual_bounds(&self, rect: Rect) -> Rect {
160        let mut bounds = rect;
161        for shadow in &self.shadows {
162            bounds = union_rect(bounds, shadow.paint_bounds(rect));
163        }
164        if self.focus_ring.is_visible() {
165            let inflate = self.focus_ring_offset + max_border_width(self.focus_ring);
166            bounds = union_rect(bounds, rect.inflate(inflate, inflate));
167        }
168        bounds
169    }
170}
171
172/// Shared callback receiving the proposed next checked state.
173type ChangeHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, bool)>;
174
175/// A focusable binary toggle supporting controlled and bound state modes.
176///
177/// Pointer activation occurs on left-button release inside the bounds;
178/// Enter and Space activate on a pressed key event. [`Switch::checked`] is
179/// controlled/read-only state: activation only reports `!checked` through the
180/// callback. [`Switch::bind`] first writes the signal, then calls the callback.
181/// With neither binding nor callback, activation is a no-op.
182///
183/// # Examples
184///
185/// ```
186/// use ailloli_ui_widgets::controls::Switch;
187/// let switch: Switch<()> = Switch::new().checked(true);
188/// let _ = switch;
189/// ```
190pub struct Switch<A = ()> {
191    /// Layout configuration used to resolve intrinsic geometry.
192    pub(crate) layout: LayoutStyle,
193    /// Flex-item behavior used by the parent layout.
194    pub(crate) flex_item: FlexItemStyle,
195    /// Current static or reactive checked state.
196    checked: Binding<bool>,
197    /// Writable signal in bound mode; `None` in controlled mode.
198    bound: Option<Signal<bool>>,
199    /// Current static or reactive disabled state.
200    disabled: Binding<bool>,
201    /// Optional callback receiving the proposed next value.
202    on_change: Option<ChangeHandler<A>>,
203    /// Thumb motion axis.
204    orientation: SwitchOrientation,
205    /// Resolved colors and geometry.
206    style: SwitchStyle,
207}
208
209crate::impl_layout_builders!(Switch);
210
211impl<A: 'static> Default for Switch<A> {
212    fn default() -> Self {
213        Self::new()
214    }
215}
216
217impl<A: 'static> Switch<A> {
218    /// Creates an off, enabled, horizontal switch with no callback.
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// use ailloli_ui_widgets::controls::Switch;
224    /// let switch: Switch<()> = Switch::new();
225    /// let _ = switch;
226    /// ```
227    pub fn new() -> Self {
228        Self {
229            layout: LayoutStyle::default(),
230            flex_item: FlexItemStyle::default(),
231            checked: Binding::Static(false),
232            bound: None,
233            disabled: Binding::Static(false),
234            on_change: None,
235            orientation: SwitchOrientation::Horizontal,
236            style: SwitchStyle::default(),
237        }
238    }
239
240    /// Sets controlled static or reactive checked state.
241    ///
242    /// This clears any writable signal previously installed by [`Self::bind`].
243    /// Activation does not mutate this binding; use [`Self::on_change`] to send
244    /// the proposed value back to application state.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use ailloli_ui_widgets::controls::Switch;
250    /// let switch: Switch<()> = Switch::new().checked(true);
251    /// let _ = switch;
252    /// ```
253    pub fn checked(mut self, checked: impl Into<Binding<bool>>) -> Self {
254        self.checked = checked.into();
255        self.bound = None;
256        self
257    }
258
259    /// Installs a writable signal for two-way checked state.
260    ///
261    /// Activation writes the negated current value before invoking an optional
262    /// change callback. A later [`Self::checked`] call returns to controlled mode.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use std::{cell::RefCell, rc::Rc};
268    /// use ailloli_ui_runtime::component::Signal;
269    /// use ailloli_ui_widgets::controls::Switch;
270    /// let checked = Signal::new(Rc::new(RefCell::new(false)), Rc::new(|| {}));
271    /// let switch: Switch<()> = Switch::new().bind(checked);
272    /// let _ = switch;
273    /// ```
274    pub fn bind(mut self, checked: impl Into<Signal<bool>>) -> Self {
275        let signal = checked.into();
276        self.checked = Binding::Signal(signal.clone());
277        self.bound = Some(signal);
278        self
279    }
280
281    /// Sets a static or reactive disabled binding.
282    ///
283    /// Disabled switches ignore activation, leave the bound signal unchanged,
284    /// are removed from focus traversal, and apply disabled paint.
285    ///
286    /// # Examples
287    ///
288    /// ```
289    /// use ailloli_ui_widgets::controls::Switch;
290    /// let switch: Switch<()> = Switch::new().disabled(true);
291    /// let _ = switch;
292    /// ```
293    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
294        self.disabled = disabled.into();
295        self
296    }
297
298    /// Convenience alias for [`Self::disabled`] with a reactive memo.
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use ailloli_ui_runtime::component::Memo;
304    /// use ailloli_ui_widgets::controls::Switch;
305    /// let switch: Switch<()> = Switch::new().disabled_signal(Memo::new(|| false));
306    /// let _ = switch;
307    /// ```
308    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
309        self.disabled(disabled)
310    }
311
312    /// Replaces the complete resolved style without clamping its values.
313    ///
314    /// A later [`Self::switch_size`] call discards this custom style.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// use ailloli_ui_core::Theme;
320    /// use ailloli_ui_widgets::controls::{Switch, SwitchSize, SwitchStyle};
321    /// let style = SwitchStyle::from_theme(Theme::dark(), SwitchSize::Compact);
322    /// let switch: Switch<()> = Switch::new().switch_style(style);
323    /// let _ = switch;
324    /// ```
325    pub fn switch_style(mut self, style: SwitchStyle) -> Self {
326        self.style = style;
327        self
328    }
329
330    /// Replaces the complete style with the default-theme built-in `size`.
331    ///
332    /// # Examples
333    ///
334    /// ```
335    /// use ailloli_ui_widgets::controls::{Switch, SwitchSize};
336    /// let switch: Switch<()> = Switch::new().switch_size(SwitchSize::Compact);
337    /// let _ = switch;
338    /// ```
339    pub fn switch_size(mut self, size: SwitchSize) -> Self {
340        self.style = SwitchStyle::from_theme(Theme::default(), size);
341        self
342    }
343
344    /// Sets the thumb motion axis.
345    ///
346    /// Vertical orientation swaps the style's intrinsic width and height.
347    /// Explicit layout builders may override either dimension.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use ailloli_ui_widgets::controls::{Switch, SwitchOrientation};
353    /// let switch: Switch<()> = Switch::new().orientation(SwitchOrientation::Vertical);
354    /// let _ = switch;
355    /// ```
356    pub fn orientation(mut self, orientation: SwitchOrientation) -> Self {
357        self.orientation = orientation;
358        self
359    }
360
361    /// Convenience builder for [`SwitchOrientation::Vertical`].
362    ///
363    /// # Examples
364    ///
365    /// ```
366    /// use ailloli_ui_widgets::controls::Switch;
367    /// let switch: Switch<()> = Switch::new().vertical();
368    /// let _ = switch;
369    /// ```
370    pub fn vertical(self) -> Self {
371        self.orientation(SwitchOrientation::Vertical)
372    }
373
374    /// Maps each proposed next value to an application action and dispatches it.
375    ///
376    /// The mapper runs after a bound signal is updated. A later change-handler
377    /// builder replaces it.
378    ///
379    /// # Examples
380    ///
381    /// ```
382    /// use ailloli_ui_widgets::controls::Switch;
383    /// enum Action { Changed(bool) }
384    /// let switch = Switch::new().on_change(Action::Changed);
385    /// let _ = switch;
386    /// ```
387    pub fn on_change(mut self, f: impl Fn(bool) -> A + 'static) -> Self {
388        self.on_change = Some(Rc::new(move |ctx, next| ctx.dispatch(f(next))));
389        self
390    }
391
392    /// Installs a context-aware callback for each proposed next value.
393    ///
394    /// The callback may dispatch zero or more actions. A later change-handler
395    /// builder replaces it.
396    ///
397    /// # Examples
398    ///
399    /// ```
400    /// use ailloli_ui_widgets::controls::Switch;
401    /// let switch = Switch::<()>::new().on_change_ctx(|ctx, _checked| ctx.request_repaint());
402    /// let _ = switch;
403    /// ```
404    pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, bool) + 'static) -> Self {
405        self.on_change = Some(Rc::new(f));
406        self
407    }
408}
409
410/// Retained leaf that reads bindings, mutates bound state, and paints the switch.
411struct SwitchWidget<A> {
412    /// Outer logical sizing policy.
413    layout: LayoutStyle,
414    /// Readable checked-state source.
415    checked: Binding<bool>,
416    /// Optional writable checked state for controlled interaction.
417    bound: Option<Signal<bool>>,
418    /// Reactive interaction-disable flag.
419    disabled: Binding<bool>,
420    /// Optional callback receiving changed checked state.
421    on_change: Option<ChangeHandler<A>>,
422    /// Horizontal or vertical track orientation.
423    orientation: SwitchOrientation,
424    /// Track/thumb colors and logical-pixel geometry.
425    style: SwitchStyle,
426}
427
428impl<A: 'static> Widget<A> for SwitchWidget<A> {
429    fn debug_name(&self) -> &'static str {
430        "Switch"
431    }
432
433    fn layout(
434        &self,
435        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
436        _ctx: &mut LayoutCtx<'_>,
437        _children: &mut [LayoutChild],
438        constraints: Constraints,
439    ) -> LayoutResult {
440        let intrinsic = switch_intrinsic_size(&self.style, self.orientation);
441        let size = apply_layout_size(intrinsic, self.layout, constraints);
442        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
443        LayoutResult {
444            size,
445            children: Vec::new(),
446            paint_bounds,
447            visual_bounds: self.style.visual_bounds(paint_bounds),
448            overlay_hit_bounds: Vec::new(),
449            clip: None,
450            is_window_root_clip: false,
451            artifact: None,
452        }
453    }
454
455    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
456        let checked = self.checked.read();
457        let disabled = self.disabled.read();
458        paint_switch(
459            ctx,
460            bounds,
461            checked,
462            disabled,
463            self.orientation,
464            &self.style,
465        );
466    }
467
468    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
469        if self.disabled.read() {
470            return;
471        }
472
473        match event {
474            Event::Pointer(PointerEvent::Button {
475                pos,
476                button: MouseButton::Left,
477                pressed: false,
478                ..
479            }) if bounds.contains(pos.x, pos.y) => self.toggle(ctx),
480            Event::Keyboard(key) if key.state == KeyState::Pressed => {
481                if matches!(
482                    &key.key,
483                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
484                ) {
485                    self.toggle(ctx);
486                }
487            }
488            _ => {}
489        }
490    }
491
492    fn focus_policy(&self) -> FocusPolicy {
493        if self.disabled.read() {
494            FocusPolicy::NotFocusable
495        } else {
496            FocusPolicy::Focusable
497        }
498    }
499
500    fn activation_policy(&self) -> ActivationPolicy {
501        ActivationPolicy::SuppressOnFocusOnly
502    }
503}
504
505impl<A: 'static> SwitchWidget<A> {
506    /// Applies the next value in bound mode, invokes the callback, and consumes input.
507    fn toggle(&self, ctx: &mut EventCtx<A>) {
508        if self.bound.is_none() && self.on_change.is_none() {
509            return;
510        }
511
512        let next = !self.checked.read();
513        if let Some(bound) = &self.bound {
514            bound.set(next);
515        }
516        if let Some(on_change) = &self.on_change {
517            on_change(ctx, next);
518        }
519        ctx.request_repaint();
520        ctx.stop_propagation();
521    }
522}
523
524impl<A: 'static> IntoView<A> for Switch<A> {
525    fn into_view(self) -> View<A> {
526        finish_view_sized(
527            View::leaf(SwitchWidget {
528                layout: self.layout,
529                checked: self.checked,
530                bound: self.bound,
531                disabled: self.disabled,
532                on_change: self.on_change,
533                orientation: self.orientation,
534                style: self.style,
535            }),
536            self.flex_item,
537            LayoutSizeHint::from_layout(self.layout),
538        )
539    }
540}
541
542/// Paints shadows, track, border, thumb, then an optional focus ring.
543fn paint_switch(
544    ctx: &mut PaintCtx<'_>,
545    bounds: Rect,
546    checked: bool,
547    disabled: bool,
548    orientation: SwitchOrientation,
549    style: &SwitchStyle,
550) {
551    let interaction = ctx.interaction();
552    let opacity = if disabled {
553        style.disabled_opacity
554    } else {
555        1.0
556    };
557    let track_color = resolve_track_color(style, checked, interaction.hovered, interaction.pressed);
558    let border = if checked {
559        style.border_on
560    } else {
561        style.border_off
562    };
563    let cross_axis = match orientation {
564        SwitchOrientation::Horizontal => bounds.h,
565        SwitchOrientation::Vertical => bounds.w,
566    };
567    let radius = Radius::uniform(style.track_radius.min(cross_axis * 0.5));
568
569    for shadow in style.shadows.iter().copied() {
570        let mut shadow = shadow;
571        shadow.color = apply_opacity(shadow.color, opacity);
572        if shadow.color.a > 0.0 {
573            ctx.push(DrawCmd::BoxShadow(DrawBoxShadow {
574                rect: bounds,
575                radius,
576                shadow,
577            }));
578        }
579    }
580
581    ctx.push(DrawCmd::RRect(DrawRRect {
582        rect: bounds,
583        radius: radius.tl,
584        color: apply_opacity(track_color, opacity),
585    }));
586
587    let border = apply_border_opacity(border, opacity);
588    if border.is_visible() {
589        ctx.push(DrawCmd::Border(DrawBorder {
590            rect: bounds,
591            radius,
592            border,
593        }));
594    }
595
596    let thumb = thumb_rect(bounds, checked, orientation, style);
597    ctx.push(DrawCmd::RRect(DrawRRect {
598        rect: thumb,
599        radius: style.thumb_radius.min(thumb.h * 0.5),
600        color: apply_opacity(
601            if disabled {
602                style.thumb_disabled
603            } else {
604                style.thumb
605            },
606            opacity,
607        ),
608    }));
609
610    if interaction.focused && !disabled && style.focus_ring.is_visible() {
611        ctx.push(DrawCmd::Border(DrawBorder {
612            rect: bounds.inflate(style.focus_ring_offset, style.focus_ring_offset),
613            radius: Radius::uniform(radius.tl + style.focus_ring_offset),
614            border: style.focus_ring,
615        }));
616    }
617}
618
619/// Resolves track color with pressed state taking precedence over hover.
620fn resolve_track_color(style: &SwitchStyle, checked: bool, hovered: bool, pressed: bool) -> Color {
621    match (checked, pressed, hovered) {
622        (true, true, _) => style.track_on_pressed,
623        (true, false, true) => style.track_on_hovered,
624        (true, false, false) => style.track_on,
625        (false, true, _) => style.track_off_pressed,
626        (false, false, true) => style.track_off_hovered,
627        (false, false, false) => style.track_off,
628    }
629}
630
631/// Returns style width/height, swapping axes for vertical orientation.
632fn switch_intrinsic_size(style: &SwitchStyle, orientation: SwitchOrientation) -> Size {
633    match orientation {
634        SwitchOrientation::Horizontal => Size::new(style.width, style.height),
635        SwitchOrientation::Vertical => Size::new(style.height, style.width),
636    }
637}
638
639/// Fits and positions a square thumb at the off or on end of `bounds`.
640fn thumb_rect(
641    bounds: Rect,
642    checked: bool,
643    orientation: SwitchOrientation,
644    style: &SwitchStyle,
645) -> Rect {
646    match orientation {
647        SwitchOrientation::Horizontal => {
648            let thumb = style
649                .thumb_size
650                .min((bounds.h - style.inset * 2.0).max(0.0));
651            let x = if checked {
652                bounds.right() - style.inset - thumb
653            } else {
654                bounds.x + style.inset
655            };
656            Rect::new(x, bounds.y + (bounds.h - thumb) * 0.5, thumb, thumb)
657        }
658        SwitchOrientation::Vertical => {
659            let thumb = style
660                .thumb_size
661                .min((bounds.w - style.inset * 2.0).max(0.0));
662            let y = if checked {
663                bounds.bottom() - style.inset - thumb
664            } else {
665                bounds.y + style.inset
666            };
667            Rect::new(bounds.x + (bounds.w - thumb) * 0.5, y, thumb, thumb)
668        }
669    }
670}
671
672/// Multiplies and clamps a color's alpha to `0.0..=1.0`.
673fn apply_opacity(mut color: Color, opacity: f32) -> Color {
674    color.a = (color.a * opacity).clamp(0.0, 1.0);
675    color
676}
677
678/// Applies [`apply_opacity`] independently to all four border colors.
679fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
680    border.colors.left = apply_opacity(border.colors.left, opacity);
681    border.colors.top = apply_opacity(border.colors.top, opacity);
682    border.colors.right = apply_opacity(border.colors.right, opacity);
683    border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
684    border
685}
686
687/// Returns the largest of a border's four logical-pixel widths.
688fn max_border_width(border: Border) -> f32 {
689    border
690        .widths
691        .left
692        .max(border.widths.top)
693        .max(border.widths.right)
694        .max(border.widths.bottom)
695}
696
697/// Returns the smallest axis-aligned rectangle containing `a` and `b`.
698fn union_rect(a: Rect, b: Rect) -> Rect {
699    let x0 = a.x.min(b.x);
700    let y0 = a.y.min(b.y);
701    let x1 = a.right().max(b.right());
702    let y1 = a.bottom().max(b.bottom());
703    Rect::new(x0, y0, x1 - x0, y1 - y0)
704}