Skip to main content

waft_winui/controls/
item_container.rs

1//! `ItemContainer` (`controls/dev/ItemContainer`: `ItemContainer.xaml`, `ItemContainer_themeresources.xaml` and `ItemContainer.cpp`): the item of an `ItemsView`, which lights under the pointer, shows pressed and selected with its selection visual, shows a check box in `Multiple` mode, takes the focus, and tells its `ItemsView` of a click, a tap, a double tap, Enter and Space.
2//!
3//! Inside an `ItemsView` the container reads its index and its view from the scope the view puts around it, and listens to the view's selection for its own index, rebuilding only when its own selected state or tab stop changes. A later editor who has the view rebuild containers instead must keep that listener, or a container shows the selection it was built with.
4
5use crate::FocusState;
6use crate::*;
7use std::{fmt, rc::Rc, time::Duration, time::Instant};
8use waft_animation::{Cubic, Curve};
9use waft_embedder::{Color, Offset, PointerDeviceKind};
10use waft_foundation::{App, Handle, ListenableObject, Listener, OptionRetained, Ref};
11use waft_gestures::{K_DOUBLE_TAP_SLOP, K_DOUBLE_TAP_TIMEOUT, TapDownDetails};
12use waft_painting::AlignmentGeometry;
13use waft_rendering::HitTestBehavior;
14use waft_services::{KeyEvent, LogicalKeyboardKey};
15use waft_widgets::*;
16
17/// `ItemContainerUserSelectMode`: whether the user can select the item; `Auto` takes it from the `ItemsView`'s selection mode.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19pub enum ItemContainerUserSelectMode {
20    #[default]
21    Auto,
22    UserCanSelect,
23    UserCannotSelect,
24}
25
26/// `ItemContainerUserInvokeMode`: whether the user can invoke the item; `Auto` takes it from `ItemsView::is_item_invoked_enabled`.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub enum ItemContainerUserInvokeMode {
29    #[default]
30    Auto,
31    UserCanInvoke,
32    UserCannotInvoke,
33}
34
35/// `ItemContainerMultiSelectMode`: whether the item shows the check box of `Multiple` mode; `Auto` takes it from the `ItemsView`'s selection mode.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37pub enum ItemContainerMultiSelectMode {
38    #[default]
39    Auto,
40    Single,
41    Extended,
42    Multiple,
43}
44
45/// `ItemContainerInteractionTrigger`: what the user did to the item.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub(crate) enum ItemContainerInteractionTrigger {
48    PointerReleased,
49    Tap,
50    DoubleTap,
51    EnterKey,
52    SpaceKey,
53}
54
55/// What a container's template is built for: the `CombinedStates`, `MultiSelectStates` and `DisabledStates` the container is in, and whether the system focus visual shows.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub(crate) struct ItemContainerStates {
58    pub(crate) is_selected: bool,
59    /// `Normal`, `PointerOver`, `Pressed` or `Disabled`.
60    pub(crate) common: CommonState,
61    pub(crate) focused: bool,
62    /// `MultiSelectStates`' `Multiple`.
63    pub(crate) multiple: bool,
64}
65
66/// Builds a container's template for its states; `SelectorBarItem`'s style supplies one of its own.
67pub(crate) type ItemContainerTemplate =
68    Rc<dyn Fn(&ThemeResources, &ItemContainer, ItemContainerStates) -> WidgetRef>;
69
70/// XAML `ItemContainer`.
71#[derive(Clone)]
72pub struct ItemContainer {
73    /// `Child`: what the item shows.
74    pub child: WidgetRef,
75    /// `IsSelected`, for a container outside an `ItemsView`; inside one the view's selection decides.
76    pub is_selected: bool,
77    /// `IsEnabled`.
78    pub is_enabled: bool,
79    /// `CanUserSelect`.
80    pub can_user_select: ItemContainerUserSelectMode,
81    /// `CanUserInvoke`.
82    pub can_user_invoke: ItemContainerUserInvokeMode,
83    /// `MultiSelectMode`.
84    pub multi_select_mode: ItemContainerMultiSelectMode,
85    /// `Background`; `None` is the style's `ItemContainerBackground`.
86    pub background: Option<Brush>,
87    /// `CornerRadius`; `None` is the style's `ControlCornerRadius`.
88    pub corner_radius: Option<[f64; 4]>,
89    /// Identity retained across parent rebuilds.
90    pub key: Option<KeyRef>,
91    /// The template; `None` is `ItemContainer.xaml`'s.
92    pub(crate) template: Option<ItemContainerTemplate>,
93}
94
95impl ItemContainer {
96    /// Creates a container showing `child`.
97    #[cfg_attr(debug_assertions, track_caller)]
98    pub fn new<K>(child: impl IntoWidget<K>) -> Self {
99        Self {
100            child: child.into_widget(),
101            is_selected: false,
102            is_enabled: true,
103            can_user_select: ItemContainerUserSelectMode::Auto,
104            can_user_invoke: ItemContainerUserInvokeMode::Auto,
105            multi_select_mode: ItemContainerMultiSelectMode::Auto,
106            background: None,
107            corner_radius: None,
108            key: None,
109            template: None,
110        }
111    }
112
113    /// Sets the XAML `IsSelected`.
114    pub fn is_selected(mut self, value: bool) -> Self {
115        self.is_selected = value;
116        self
117    }
118
119    /// Sets the XAML `IsEnabled`.
120    pub fn is_enabled(mut self, value: bool) -> Self {
121        self.is_enabled = value;
122        self
123    }
124
125    /// Sets the XAML `CanUserSelect`.
126    pub fn can_user_select(mut self, value: ItemContainerUserSelectMode) -> Self {
127        self.can_user_select = value;
128        self
129    }
130
131    /// Sets the XAML `CanUserInvoke`.
132    pub fn can_user_invoke(mut self, value: ItemContainerUserInvokeMode) -> Self {
133        self.can_user_invoke = value;
134        self
135    }
136
137    /// Sets the XAML `MultiSelectMode`.
138    pub fn multi_select_mode(mut self, value: ItemContainerMultiSelectMode) -> Self {
139        self.multi_select_mode = value;
140        self
141    }
142
143    /// Sets the XAML `Background`.
144    pub fn background(mut self, value: Brush) -> Self {
145        self.background = Some(value);
146        self
147    }
148
149    /// Sets the XAML `CornerRadius`.
150    pub fn corner_radius(mut self, value: [f64; 4]) -> Self {
151        self.corner_radius = Some(value);
152        self
153    }
154
155    /// Sets the identity retained across rebuilds.
156    pub fn key(mut self, key: KeyRef) -> Self {
157        self.key = Some(key);
158        self
159    }
160
161    /// Gives the container another style's template.
162    pub(crate) fn template(mut self, template: ItemContainerTemplate) -> Self {
163        self.template = Some(template);
164        self
165    }
166}
167
168impl fmt::Debug for ItemContainer {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.debug_struct("ItemContainer")
171            .field("is_selected", &self.is_selected)
172            .field("is_enabled", &self.is_enabled)
173            .field("can_user_select", &self.can_user_select)
174            .field("can_user_invoke", &self.can_user_invoke)
175            .field("multi_select_mode", &self.multi_select_mode)
176            .finish_non_exhaustive()
177    }
178}
179
180impl StatefulWidget for ItemContainer {
181    type State = ItemContainerState;
182
183    fn key(&self) -> Option<&KeyRef> {
184        self.key.as_ref()
185    }
186
187    fn create_state(&self) -> ItemContainerState {
188        ItemContainerState {
189            state: StateData::new(),
190            focus_node: None,
191            pointer: PointerInfo::default(),
192            focused: false,
193            last_tap: None,
194            item: None,
195            selection_listener: None,
196            shown: ShownItem::default(),
197        }
198    }
199}
200
201/// `PointerInfo<ItemContainer>`: what the pointer is doing to the container.
202#[derive(Clone, Copy, Debug, Default)]
203struct PointerInfo {
204    /// A mouse is over the container.
205    mouse_over: bool,
206    /// A touch or pen press is over it, from its press to its release.
207    touch_over: bool,
208    /// A press is down on it.
209    pressed: bool,
210}
211
212impl PointerInfo {
213    fn is_pointer_over(self) -> bool {
214        self.mouse_over || self.touch_over
215    }
216}
217
218/// What the container last showed of its view's state, so that a selection change rebuilds only the containers it concerns.
219#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
220struct ShownItem {
221    selected: bool,
222    tab_stop: bool,
223}
224
225/// The container's pointer, focus and place in its view.
226pub struct ItemContainerState {
227    state: StateData<ItemContainer>,
228    focus_node: Option<Ref<FocusNode>>,
229    pointer: PointerInfo,
230    focused: bool,
231    /// When and where the last tap was, which a second tap near it soon after makes a double tap.
232    last_tap: Option<(Instant, Offset)>,
233    /// The item's index and its view, from the scope the view puts around it.
234    item: Option<ItemsViewItem>,
235    selection_listener: Option<(Handle<ItemsViewSource>, Listener)>,
236    shown: ShownItem,
237}
238
239impl ItemContainerState {
240    fn focus_node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
241        app.get(self)
242            .focus_node
243            .handle()
244            .expect("made in `init_state`")
245    }
246
247    /// What the view says of the item now; outside a view, the container's own `IsSelected`.
248    fn view_state(self: Handle<Self>, app: &App) -> ShownItem {
249        match app.get(self).item {
250            Some(item) => ShownItem {
251                selected: item.view.is_selected(app, item.index),
252                tab_stop: item.view.is_tab_stop(app, item.index),
253            },
254            None => ShownItem {
255                selected: self.widget(app).is_selected,
256                tab_stop: true,
257            },
258        }
259    }
260
261    /// The selection changed: the container rebuilds when what it shows of it did.
262    fn selection_changed(self: Handle<Self>, app: &mut App) {
263        let now = self.view_state(app);
264        if now != app.get(self).shown {
265            self.set_state(app, |state| state.shown = now);
266        }
267    }
268
269    /// Finds the view the container is an item of and listens to its selection.
270    fn attach_to_view(self: Handle<Self>, app: &mut App) {
271        let item = ItemsViewItem::of(app, self.context(app));
272        let previous = app.get(self).item;
273        if previous == item {
274            return;
275        }
276        if let Some(previous) = previous {
277            previous.view.unregister(app, previous.index, self);
278        }
279        self.stop_listening(app);
280        app.get_mut(self).item = item;
281        if let Some(item) = item {
282            item.view
283                .register(app, item.index, self, self.focus_node(app));
284            let selection = item.view.items_source(app);
285            let listener = Listener::new(move |app| self.selection_changed(app));
286            selection.add_listener(app, listener.clone());
287            app.get_mut(self).selection_listener = Some((selection, listener));
288        }
289        let shown = self.view_state(app);
290        app.get_mut(self).shown = shown;
291    }
292
293    fn stop_listening(self: Handle<Self>, app: &mut App) {
294        if let Some((selection, listener)) = app.get_mut(self).selection_listener.take()
295            && app.contains(selection)
296        {
297            selection.remove_listener(app, &listener);
298        }
299    }
300
301    /// The container's `MultiSelectMode`, `Auto` resolved by its view as `ItemsView::OnItemsRepeaterElementPrepared` does.
302    fn multi_select_mode(self: Handle<Self>, app: &App) -> ItemContainerMultiSelectMode {
303        let mode = self.widget(app).multi_select_mode;
304        match (mode, app.get(self).item) {
305            (ItemContainerMultiSelectMode::Auto, Some(item)) => item.view.multi_select_mode(app),
306            _ => mode,
307        }
308    }
309
310    /// `ItemContainer::CanRaiseItemInvoked`: the user can invoke the item, or can select it.
311    fn can_raise_item_invoked(self: Handle<Self>, app: &App) -> bool {
312        let Some(item) = app.get(self).item else {
313            return false;
314        };
315        let widget = self.widget(app);
316        item.view.can_user_invoke(app, widget.can_user_invoke)
317            || item.view.can_user_select(app, widget.can_user_select)
318    }
319
320    /// `RaiseItemInvoked`: tells the view, which answers whether it handled it.
321    fn raise_item_invoked(
322        self: Handle<Self>,
323        app: &mut App,
324        trigger: ItemContainerInteractionTrigger,
325    ) -> bool {
326        if !self.can_raise_item_invoked(app) {
327            return false;
328        }
329        let item = app
330            .get(self)
331            .item
332            .expect("checked by `can_raise_item_invoked`");
333        let widget = self.widget(app).clone();
334        item.view
335            .item_container_invoked(app, item.index, &widget, trigger)
336    }
337
338    fn update_pointer(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut PointerInfo)) {
339        let mut pointer = app.get(self).pointer;
340        change(&mut pointer);
341        let before = app.get(self).pointer;
342        if pointer.is_pointer_over() != before.is_pointer_over()
343            || pointer.pressed != before.pressed
344        {
345            self.set_state(app, |state| state.pointer = pointer);
346        } else {
347            app.get_mut(self).pointer = pointer;
348        }
349    }
350
351    /// `OnPointerPressed`.
352    fn pointer_pressed(self: Handle<Self>, app: &mut App, details: &TapDownDetails) {
353        let touch = !matches!(details.kind, Some(PointerDeviceKind::Mouse) | None);
354        self.update_pointer(app, |pointer| {
355            pointer.pressed = true;
356            if touch {
357                pointer.touch_over = true;
358            } else {
359                pointer.mouse_over = true;
360            }
361        });
362    }
363
364    /// `OnPointerReleased`: the press ends and, a left button or a touch, the view hears of it.
365    fn pointer_released(self: Handle<Self>, app: &mut App) {
366        if !app.get(self).pointer.pressed {
367            return;
368        }
369        self.update_pointer(app, |pointer| {
370            pointer.pressed = false;
371            pointer.touch_over = false;
372        });
373        self.raise_item_invoked(app, ItemContainerInteractionTrigger::PointerReleased);
374    }
375
376    /// `ProcessPointerCanceled`.
377    fn pointer_canceled(self: Handle<Self>, app: &mut App) {
378        self.update_pointer(app, |pointer| {
379            pointer.pressed = false;
380            pointer.touch_over = false;
381        });
382    }
383
384    /// `OnTapped` and `OnDoubleTapped`: a second tap soon after the first and near it is a double tap.
385    fn tapped(self: Handle<Self>, app: &mut App, position: Offset) {
386        let now = Instant::now();
387        let double = app.get(self).last_tap.is_some_and(|(at, from)| {
388            now.duration_since(at) <= K_DOUBLE_TAP_TIMEOUT
389                && (position - from).distance() <= K_DOUBLE_TAP_SLOP
390        });
391        app.get_mut(self).last_tap = if double { None } else { Some((now, position)) };
392        let trigger = if double {
393            ItemContainerInteractionTrigger::DoubleTap
394        } else {
395            ItemContainerInteractionTrigger::Tap
396        };
397        self.raise_item_invoked(app, trigger);
398    }
399
400    /// `OnKeyDown`: Enter and Space.
401    fn key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
402        if matches!(event, KeyEvent::Up(_)) {
403            return KeyEventResult::Ignored;
404        }
405        let trigger = match event.logical_key() {
406            LogicalKeyboardKey::ENTER => ItemContainerInteractionTrigger::EnterKey,
407            LogicalKeyboardKey::SPACE => ItemContainerInteractionTrigger::SpaceKey,
408            _ => return KeyEventResult::Ignored,
409        };
410        if self.raise_item_invoked(app, trigger) {
411            KeyEventResult::Handled
412        } else {
413            KeyEventResult::Ignored
414        }
415    }
416
417    fn focus_changed(self: Handle<Self>, app: &mut App, focused: bool) {
418        self.set_state(app, |state| state.focused = focused);
419        if focused && let Some(item) = app.get(self).item {
420            item.view.item_got_focus(app, item.index);
421        }
422    }
423
424    /// `UpdateVisualState` and `UpdateMultiSelectState`.
425    fn states(self: Handle<Self>, app: &mut App) -> ItemContainerStates {
426        let shows_focus_visual = FocusState::current(app).shows_focus_visual();
427        let widget = self.widget(app);
428        let state = app.get(self);
429        let common = if !widget.is_enabled {
430            CommonState::Disabled
431        } else if state.pointer.pressed {
432            CommonState::Pressed
433        } else if state.pointer.is_pointer_over() {
434            CommonState::PointerOver
435        } else {
436            CommonState::Normal
437        };
438        ItemContainerStates {
439            is_selected: state.shown.selected,
440            common,
441            focused: state.focused && shows_focus_visual,
442            multiple: self.multi_select_mode(app) == ItemContainerMultiSelectMode::Multiple,
443        }
444    }
445}
446
447impl State for ItemContainerState {
448    type Widget = ItemContainer;
449    waft_widgets::state_accessors!();
450
451    fn init_state(self: Handle<Self>, app: &mut App) {
452        InputDevice::initialize(app);
453        app.get_mut(self).focus_node = Some(FocusNode::new(app));
454    }
455
456    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
457        self.attach_to_view(app);
458    }
459
460    fn did_update_widget(self: Handle<Self>, app: &mut App, _old: &ItemContainer) {
461        self.attach_to_view(app);
462        if !self.widget(app).is_enabled {
463            // `OnIsEnabledChanged`: a disabled container drops the pointer.
464            app.get_mut(self).pointer = PointerInfo::default();
465        }
466        let shown = self.view_state(app);
467        app.get_mut(self).shown = shown;
468    }
469
470    fn dispose(self: Handle<Self>, app: &mut App) {
471        self.stop_listening(app);
472        if let Some(item) = app.get(self).item
473            && app.contains(item.view)
474        {
475            item.view.unregister(app, item.index, self);
476        }
477        if let Some(node) = app.get_mut(self).focus_node.take() {
478            node.dispose(app);
479        }
480    }
481
482    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
483        let resources = ThemeResources::of(app, context);
484        let widget = self.widget(app).clone();
485        let states = self.states(app);
486        let template = widget
487            .template
488            .clone()
489            .unwrap_or_else(|| Rc::new(item_container_template));
490        let visual = template(&resources, &widget, states);
491        let mut gesture = GestureDetector::new()
492            .behavior(HitTestBehavior::Opaque)
493            .child(visual);
494        if widget.is_enabled {
495            gesture = gesture
496                .on_tap_down(Rc::new(move |app, details| {
497                    self.pointer_pressed(app, &details)
498                }))
499                .on_tap_up(Rc::new(move |app, details| {
500                    self.pointer_released(app);
501                    self.tapped(app, details.global_position);
502                }))
503                .on_tap_cancel(Listener::new(move |app| self.pointer_canceled(app)));
504        }
505        let mouse = MouseRegion::new()
506            .on_enter(Rc::new(move |app, _| {
507                self.update_pointer(app, |pointer| pointer.mouse_over = true)
508            }))
509            .on_exit(Rc::new(move |app, _| {
510                // A button held down while the mouse leaves no longer presses the container.
511                self.update_pointer(app, |pointer| {
512                    pointer.mouse_over = false;
513                    pointer.pressed = false;
514                })
515            }))
516            .child(gesture);
517        Focus::new(mouse)
518            .focus_node(
519                app.get(self)
520                    .focus_node
521                    .as_ref()
522                    .expect("made in `init_state`")
523                    .erase(),
524            )
525            .can_request_focus(widget.is_enabled)
526            .skip_traversal(!app.get(self).shown.tab_stop)
527            .on_focus_change(move |app, focused| self.focus_changed(app, focused))
528            .on_key_event(Rc::new(move |app, _, event| self.key(app, event)))
529            .into_widget()
530    }
531}
532
533/// `ItemContainer.xaml`'s template: `PART_ContainerRoot` with the child, `PART_SelectionVisual`, `PART_CommonVisual` and `PART_SelectionCheckbox` over it, in that order.
534fn item_container_template(
535    r: &ThemeResources,
536    container: &ItemContainer,
537    states: ItemContainerStates,
538) -> WidgetRef {
539    let corner = container.corner_radius.unwrap_or(r.control_corner_radius);
540    let background = container
541        .background
542        .unwrap_or(Brush::Solid(r.item_container_background));
543    let visuals = CombinedVisuals::of(r, states);
544    let fast = r.control_fast_animation_duration;
545    let spline: Rc<dyn Curve> = Rc::new(Cubic::new(0.0, 0.0, 0.0, 1.0));
546    let disabled = states.common == CommonState::Disabled;
547    let mut children = vec![container.child.clone()];
548    if !disabled {
549        children.push(selection_visual(&visuals, corner, fast, spline.clone()));
550    }
551    children.push(common_visual(r, &visuals, corner));
552    children.push(selection_checkbox(r, states, fast, spline.clone()));
553    let root = Grid::new()
554        .background(background)
555        .corner_radius_corners(corner)
556        .children(
557            children
558                .into_iter()
559                .map(|child| GridCell::new(child).into_widget()),
560        );
561    // `DisabledStates`: the root fades to `ItemContainerDisabledOpacity`, and back at once.
562    let root = AnimatedOpacity::new(
563        if disabled {
564            r.item_container_disabled_opacity
565        } else {
566            1.0
567        },
568        if disabled { fast } else { Duration::ZERO },
569    )
570    .curve(spline)
571    .child(root);
572    FocusVisual::new(root, r.theme)
573        .visible(states.focused)
574        .corner_radius(corner[0])
575        .into_widget()
576}
577
578/// The `CombinedStates` storyboards' values for `PART_SelectionVisual` and `PART_CommonVisual`.
579struct CombinedVisuals {
580    /// `PART_SelectionVisual.Opacity`, and whether it fades in over `ControlFastAnimationDuration` rather than at once.
581    selection_opacity: (f64, bool),
582    selection_brush: Color,
583    common_fill: Option<Color>,
584    common_stroke: Color,
585    common_margin: [f64; 4],
586}
587
588impl CombinedVisuals {
589    /// The state `UpdateVisualState` chooses: pressed before pointer over before normal, each selected or not; a disabled container keeps its selected or unselected normal state.
590    fn of(r: &ThemeResources, states: ItemContainerStates) -> Self {
591        let selected = states.is_selected;
592        let unselected = |fill, stroke| CombinedVisuals {
593            selection_opacity: (0.0, false),
594            selection_brush: Color::new(0),
595            common_fill: fill,
596            common_stroke: stroke,
597            common_margin: [0.0; 4],
598        };
599        let selected_with = |fades, brush, fill| CombinedVisuals {
600            selection_opacity: (1.0, fades),
601            selection_brush: brush,
602            common_fill: Some(fill),
603            common_stroke: r.item_container_selected_inner_border_brush,
604            common_margin: r.item_container_selected_inner_margin,
605        };
606        match (selected, states.common) {
607            (false, CommonState::PointerOver) => unselected(
608                Some(r.item_container_pointer_over_background),
609                r.item_container_pointer_over_border_brush,
610            ),
611            (false, CommonState::Pressed) => unselected(
612                Some(r.item_container_pressed_background),
613                r.item_container_pressed_border_brush,
614            ),
615            (false, _) => unselected(None, r.item_container_border_brush),
616            (true, CommonState::PointerOver) => selected_with(
617                true,
618                r.item_container_selection_visual_pointer_over_background,
619                r.item_container_selected_pointer_over_background,
620            ),
621            (true, CommonState::Pressed) => selected_with(
622                true,
623                r.item_container_selection_visual_pressed_background,
624                r.item_container_selected_pressed_background,
625            ),
626            (true, _) => selected_with(
627                false,
628                r.item_container_selection_visual_background,
629                r.item_container_selected_background,
630            ),
631        }
632    }
633}
634
635/// `PART_SelectionVisual`: a 3 pixel border in the selection brush, taking no input.
636fn selection_visual(
637    visuals: &CombinedVisuals,
638    corner: [f64; 4],
639    fast: Duration,
640    spline: Rc<dyn Curve>,
641) -> WidgetRef {
642    let (opacity, fades) = visuals.selection_opacity;
643    IgnorePointer::new()
644        .child(
645            AnimatedOpacity::new(opacity, if fades { fast } else { Duration::ZERO })
646                .curve(spline)
647                .child(
648                    ControlBorder::new(
649                        Brush::Solid(Color::new(0)),
650                        Brush::Solid(visuals.selection_brush),
651                    )
652                    .border_thickness(3.0)
653                    .corner_radius_corners(corner),
654                ),
655        )
656        .into_widget()
657}
658
659/// `PART_CommonVisual`: a `Rectangle` filled and stroked by the state, its radii the corner radius's top left and bottom right, taking no input.
660fn common_visual(r: &ThemeResources, visuals: &CombinedVisuals, corner: [f64; 4]) -> WidgetRef {
661    let rectangle = ControlBorder::new_optional(
662        visuals.common_fill.map(Brush::Solid),
663        Some(Brush::Solid(visuals.common_stroke)),
664    )
665    .border_thickness_ltrb(r.item_container_selected_inner_thickness)
666    .corner_radius_corners([corner[0], corner[0], corner[2], corner[2]])
667    .background_sizing(BackgroundSizing::OuterBorderEdge);
668    IgnorePointer::new()
669        .child(Margin::new(visuals.common_margin, rectangle))
670        .into_widget()
671}
672
673/// `PART_SelectionCheckbox` in `ItemContainerSelectionCheckboxStyle`: a check box at the top right that shows the selection, fading in for `Multiple` and taking no input.
674fn selection_checkbox(
675    r: &ThemeResources,
676    states: ItemContainerStates,
677    fast: Duration,
678    spline: Rc<dyn Curve>,
679) -> WidgetRef {
680    let disabled = states.common == CommonState::Disabled;
681    // `CheckedDisabled` sets nothing, so a disabled selected box shows the template's own values.
682    let (fill, stroke, glyph, check) = match (states.is_selected, disabled) {
683        (true, false) => (
684            r.check_box_check_background_fill_checked,
685            r.check_box_check_background_stroke_checked,
686            r.check_box_check_glyph_foreground_checked,
687            CheckState::Checked,
688        ),
689        (false, true) => (
690            r.check_box_check_background_fill_unchecked_disabled,
691            r.check_box_check_background_stroke_unchecked_disabled,
692            r.check_box_check_glyph_foreground_unchecked_disabled,
693            CheckState::Unchecked,
694        ),
695        _ => (
696            r.item_container_checkbox_background_unchecked,
697            r.check_box_check_background_stroke_unchecked,
698            r.check_box_check_glyph_foreground_unchecked,
699            CheckState::Unchecked,
700        ),
701    };
702    let root_border = ControlBorder::new(Brush::Solid(fill), Brush::Solid(stroke))
703        .border_thickness(r.check_box_border_thickness)
704        .corner_radius_corners(r.control_corner_radius)
705        .child(Transform::translate(CHECK_GLYPH_OFFSET).child(CheckGlyph {
706            check,
707            color: glyph,
708        }));
709    let box_ = SizedBox::new()
710        .width(r.check_box_size)
711        .height(r.check_box_size)
712        .child(root_border);
713    let placed = Margin::new(
714        r.item_container_checkbox_margin,
715        Align::new()
716            .alignment(AlignmentGeometry::TOP_RIGHT)
717            .child(box_),
718    );
719    IgnorePointer::new()
720        .child(
721            AnimatedOpacity::new(
722                if states.multiple { 1.0 } else { 0.0 },
723                if states.multiple {
724                    fast
725                } else {
726                    Duration::ZERO
727                },
728            )
729            .curve(spline)
730            .child(placed),
731        )
732        .into_widget()
733}