Skip to main content

waft_winui/controls/
expander.rs

1//! Expander.xaml, Expander header styles and Expander.cpp state transitions.
2
3use crate::*;
4use std::{fmt, rc::Rc, time::Duration};
5use waft_animation::{Cubic, Curve};
6use waft_embedder::{FontWeight, Offset};
7use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
8use waft_painting::{Alignment, EdgeInsetsGeometry};
9use waft_rendering::BoxConstraints;
10use waft_scheduler::{FrameCallback, SchedulerBinding, Ticker};
11use waft_widgets::*;
12
13/// Direction in which an Expander reveals its content.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum ExpandDirection {
16    /// The header is above its content.
17    #[default]
18    Down,
19
20    /// The header is below its content.
21    Up,
22}
23
24/// Requests an owner update to IsExpanded.
25pub type ExpanderExpandedChangedHandler = Rc<dyn Fn(&mut App, bool)>;
26
27/// The `ExpandStates` group, which `Expander::UpdateExpandState` picks from `IsExpanded` and the `ExpandDirection` at the time it changed.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum ExpandState {
30    /// Expanded below the header, whose bottom corners are square.
31    ExpandDown,
32    /// Expanded above the header, whose top corners are square.
33    ExpandUp,
34    /// Collapsed after showing below the header.
35    CollapseDown,
36    /// Collapsed after showing above the header.
37    CollapseUp,
38}
39
40impl ExpandState {
41    /// Whether the state is one of the two expanded ones.
42    pub fn is_expanded(self) -> bool {
43        matches!(self, ExpandState::ExpandDown | ExpandState::ExpandUp)
44    }
45}
46
47/// An Expander `ControlTemplate` replacing `DefaultExpanderStyle`'s, as another style sets one; the Expander keeps its expanding and collapsing of the content.
48pub type ExpanderTemplate = Rc<
49    dyn Fn(
50        &mut App,
51        BuildContext,
52        &Expander,
53        ExpanderTemplateStates,
54        &ExpanderTemplateParts,
55    ) -> WidgetRef,
56>;
57
58/// What an Expander template is built for. `ExpandDirectionStates` follows [`Expander::expand_direction`].
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct ExpanderTemplateStates {
61    /// `ExpandStates`.
62    pub expand: ExpandState,
63}
64
65/// The template parts `Expander::OnApplyTemplate` attaches its behaviour to.
66pub struct ExpanderTemplateParts {
67    /// Wraps `ExpanderContent` in the clip and the `ExpandStates` storyboards.
68    content_clip: Rc<dyn Fn(WidgetRef) -> WidgetRef>,
69}
70
71impl ExpanderTemplateParts {
72    /// `ExpanderContentClip`: `expander_content` clipped to its own bounds, and shown, slid and hidden as the `ExpandStates` storyboards move `ExpanderContent`. Collapsed content stays mounted.
73    #[cfg_attr(debug_assertions, track_caller)]
74    pub fn expander_content_clip<K>(&self, expander_content: impl IntoWidget<K>) -> WidgetRef {
75        (self.content_clip)(expander_content.into_widget())
76    }
77}
78
79/// A header toggle that reveals or hides retained content using the Fluent template.
80#[derive(Clone)]
81pub struct Expander {
82    /// Whether the content is expanded.
83    pub is_expanded: bool,
84
85    /// Requests a new expanded value from the owner.
86    pub is_expanded_changed: ExpanderExpandedChangedHandler,
87
88    /// Content displayed by the header toggle.
89    pub header: Option<WidgetRef>,
90
91    /// Content retained while the Expander is collapsed.
92    pub content: Option<WidgetRef>,
93
94    /// Whether content is above or below the header.
95    pub expand_direction: ExpandDirection,
96
97    /// Whether the header and content accept input.
98    pub is_enabled: bool,
99
100    /// Optional content background.
101    pub background: Option<Brush>,
102
103    /// Optional content border.
104    pub border_brush: Option<Brush>,
105
106    /// Content padding in left, top, right, bottom order; the theme's `ExpanderContentPadding` when `None`.
107    pub padding: Option<[f64; 4]>,
108
109    /// Corner radius shared by the header and content; the theme's `ControlCornerRadius` when `None`.
110    pub corner_radius: Option<f64>,
111
112    /// Minimum width of the control; the theme's `FlyoutThemeMinWidth` when `None`.
113    pub min_width: Option<f64>,
114
115    /// Minimum height of both header and content borders; the theme's `ExpanderMinHeight` when `None`.
116    pub min_height: Option<f64>,
117
118    /// Called when IsExpanded changes to true, before the opening animation completes.
119    pub expanding: Option<Listener>,
120
121    /// Called when IsExpanded changes to false, rather than after the collapse animation.
122    pub collapsed: Option<Listener>,
123
124    /// The template of another style; `None` is `DefaultExpanderStyle`'s.
125    pub template: Option<ExpanderTemplate>,
126
127    /// Stable identity across rebuilds.
128    pub key: Option<KeyRef>,
129}
130
131impl Expander {
132    /// Creates an Expander whose expanded value is owned by its caller.
133    pub fn new(is_expanded: bool, changed: impl Fn(&mut App, bool) + 'static) -> Self {
134        Self {
135            is_expanded,
136            is_expanded_changed: Rc::new(changed),
137            header: None,
138            content: None,
139            expand_direction: ExpandDirection::Down,
140            is_enabled: true,
141            background: None,
142            border_brush: None,
143            padding: None,
144            corner_radius: None,
145            min_width: None,
146            min_height: None,
147            expanding: None,
148            collapsed: None,
149            template: None,
150            key: None,
151        }
152    }
153
154    /// Sets Header.
155    #[cfg_attr(debug_assertions, track_caller)]
156    pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
157        self.header = Some(value.into_widget());
158        self
159    }
160
161    /// Sets Content.
162    #[cfg_attr(debug_assertions, track_caller)]
163    pub fn content<K>(mut self, value: impl IntoWidget<K>) -> Self {
164        self.content = Some(value.into_widget());
165        self
166    }
167
168    /// Sets ExpandDirection.
169    pub fn expand_direction(mut self, value: ExpandDirection) -> Self {
170        self.expand_direction = value;
171        self
172    }
173
174    /// Sets IsEnabled.
175    pub fn is_enabled(mut self, value: bool) -> Self {
176        self.is_enabled = value;
177        self
178    }
179
180    /// Sets Background.
181    pub fn background(mut self, value: Brush) -> Self {
182        self.background = Some(value);
183        self
184    }
185
186    /// Sets BorderBrush.
187    pub fn border_brush(mut self, value: Brush) -> Self {
188        self.border_brush = Some(value);
189        self
190    }
191
192    /// Sets Padding.
193    pub fn padding(mut self, value: [f64; 4]) -> Self {
194        self.padding = Some(value);
195        self
196    }
197
198    /// Sets CornerRadius.
199    pub fn corner_radius(mut self, value: f64) -> Self {
200        self.corner_radius = Some(value);
201        self
202    }
203
204    /// Sets MinWidth.
205    pub fn min_width(mut self, value: f64) -> Self {
206        self.min_width = Some(value);
207        self
208    }
209
210    /// Sets MinHeight.
211    pub fn min_height(mut self, value: f64) -> Self {
212        self.min_height = Some(value);
213        self
214    }
215
216    /// Sets Expanding.
217    pub fn expanding(mut self, value: Listener) -> Self {
218        self.expanding = Some(value);
219        self
220    }
221
222    /// Sets Collapsed.
223    pub fn collapsed(mut self, value: Listener) -> Self {
224        self.collapsed = Some(value);
225        self
226    }
227
228    /// Sets the `ControlTemplate` of a style that replaces `DefaultExpanderStyle`'s.
229    pub fn template(
230        mut self,
231        builder: impl Fn(
232            &mut App,
233            BuildContext,
234            &Expander,
235            ExpanderTemplateStates,
236            &ExpanderTemplateParts,
237        ) -> WidgetRef
238        + 'static,
239    ) -> Self {
240        self.template = Some(Rc::new(builder));
241        self
242    }
243
244    /// Sets Key.
245    pub fn key(mut self, value: KeyRef) -> Self {
246        self.key = Some(value);
247        self
248    }
249}
250
251impl fmt::Debug for Expander {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        f.debug_struct("Expander")
254            .field("is_expanded", &self.is_expanded)
255            .field("expand_direction", &self.expand_direction)
256            .finish_non_exhaustive()
257    }
258}
259
260/// Expander's animation and retained content lifecycle.
261pub struct ExpanderState {
262    /// Framework state identity.
263    state: StateData<Expander>,
264
265    /// Native TickerMode subscription.
266    single_ticker_provider: SingleTickerProviderStateMixinData,
267
268    /// Clock for the explicit ExpandStates storyboard.
269    ticker: Option<Ref<Ticker>>,
270
271    /// Elapsed time since the last IsExpanded change.
272    elapsed: Duration,
273
274    /// Whether the collapsed visibility key has executed.
275    content_visible: bool,
276
277    /// Direction captured by ExpandStates, independent of ExpandDirectionStates.
278    motion_direction: ExpandDirection,
279}
280
281impl StatefulWidget for Expander {
282    type State = ExpanderState;
283
284    /// Returns the identity used to retain this control across owner rebuilds.
285    fn key(&self) -> Option<&KeyRef> {
286        self.key.as_ref()
287    }
288
289    /// Initializes template state from the first widget description.
290    fn create_state(&self) -> ExpanderState {
291        ExpanderState {
292            state: StateData::new(),
293            single_ticker_provider: Default::default(),
294            ticker: None,
295            elapsed: Duration::ZERO,
296            content_visible: self.is_expanded,
297            motion_direction: self.expand_direction,
298        }
299    }
300}
301
302impl SingleTickerProviderStateMixin for ExpanderState {
303    fn single_ticker_provider_data(
304        self: Handle<Self>,
305        app: &App,
306    ) -> &SingleTickerProviderStateMixinData {
307        &app.get(self).single_ticker_provider
308    }
309
310    fn single_ticker_provider_data_mut(
311        self: Handle<Self>,
312        app: &mut App,
313    ) -> &mut SingleTickerProviderStateMixinData {
314        &mut app.get_mut(self).single_ticker_provider
315    }
316}
317
318impl ExpanderState {
319    /// Duration of the last storyboard key, including CollapseDown's delayed visibility key.
320    fn duration(self: Handle<Self>, app: &App) -> Duration {
321        Duration::from_millis(if self.widget(app).is_expanded {
322            333
323        } else if app.get(self).motion_direction == ExpandDirection::Up {
324            200
325        } else {
326            167
327        })
328    }
329
330    /// Applies the source translate keys and collapses only at the visibility key.
331    fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
332        let finished = elapsed >= self.duration(app);
333        let expanded = self.widget(app).is_expanded;
334        self.set_state(app, |state| {
335            state.elapsed = elapsed;
336            if finished && !expanded {
337                state.content_visible = false;
338            }
339        });
340
341        if finished {
342            app.get(self).ticker.handle().unwrap().stop(app, false);
343        }
344    }
345
346    /// Translation as a fraction of the actual content height, avoiding a delayed size sample.
347    fn translation(self: Handle<Self>, app: &App) -> f64 {
348        let time = app.get(self).elapsed.as_secs_f64();
349        let sign = if app.get(self).motion_direction == ExpandDirection::Down {
350            -1.0
351        } else {
352            1.0
353        };
354        if self.widget(app).is_expanded {
355            sign * (1.0 - Cubic::new(0.0, 0.0, 0.0, 1.0).transform((time / 0.333).min(1.0)))
356        } else {
357            sign * Cubic::new(1.0, 1.0, 0.0, 1.0).transform((time / 0.167).min(1.0))
358        }
359    }
360}
361
362impl State for ExpanderState {
363    type Widget = Expander;
364    waft_widgets::state_accessors!();
365
366    /// Creates the native clock for the source storyboards.
367    fn init_state(self: Handle<Self>, app: &mut App) {
368        let ticker = SingleTickerProviderStateMixin::create_ticker(
369            self,
370            app,
371            FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
372        );
373        app.get_mut(self).ticker = Some(ticker.clone());
374        if self.widget(app).is_expanded {
375            ticker.start(app);
376        }
377    }
378
379    /// Applies source property-change behavior when the owner supplies new values.
380    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &Expander) {
381        let widget = self.widget(app).clone();
382        if old.is_expanded == widget.is_expanded {
383            return;
384        }
385
386        let ticker = app.get(self).ticker.clone().unwrap();
387        ticker.stop(app, false);
388        let state = app.get_mut(self);
389        state.elapsed = Duration::ZERO;
390        state.content_visible = true;
391        state.motion_direction = widget.expand_direction;
392        ticker.start(app);
393
394        let event = if widget.is_expanded {
395            widget.expanding
396        } else {
397            widget.collapsed
398        };
399        if let Some(event) = event {
400            SchedulerBinding::add_post_frame_callback(
401                app,
402                FrameCallback::new(move |app, _| {
403                    if app.contains(self) && self.mounted(app) {
404                        event.call(app);
405                    }
406                }),
407                View::maybe_id_of(app, self.context(app)),
408            );
409        }
410    }
411
412    fn activate(self: Handle<Self>, app: &mut App) {
413        SingleTickerProviderStateMixin::activate(self, app);
414    }
415
416    /// Releases the storyboard clock before disposing its ticker provider.
417    fn dispose(self: Handle<Self>, app: &mut App) {
418        app.get(self).ticker.handle().unwrap().dispose(app);
419        SingleTickerProviderStateMixin::dispose(self, app);
420    }
421
422    /// Builds the style's template for the current visual state.
423    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
424        let widget = self.widget(app).clone();
425        let state = app.get(self);
426        let states = ExpanderTemplateStates {
427            expand: match (widget.is_expanded, state.motion_direction) {
428                (true, ExpandDirection::Down) => ExpandState::ExpandDown,
429                (true, ExpandDirection::Up) => ExpandState::ExpandUp,
430                (false, ExpandDirection::Down) => ExpandState::CollapseDown,
431                (false, ExpandDirection::Up) => ExpandState::CollapseUp,
432            },
433        };
434        let visible = state.content_visible;
435        let translation = Offset::new(0.0, self.translation(app));
436        let parts = ExpanderTemplateParts {
437            // ExpanderContentClip contains the translated ExpanderContent; height is reserved immediately.
438            content_clip: Rc::new(move |expander_content| {
439                Offstage::new()
440                    .offstage(!visible)
441                    .child(TickerMode::new(
442                        visible,
443                        ExcludeFocus::new(ClipRect::new().child(
444                            FractionalTranslation::new(translation).child(expander_content),
445                        ))
446                        .excluding(!visible),
447                    ))
448                    .into_widget()
449            }),
450        };
451        let template = match widget.template.clone() {
452            Some(template) => template(app, context, &widget, states, &parts),
453            None => {
454                let resources = ThemeResources::of(app, context);
455                default_template(&resources, &widget, states, &parts)
456            }
457        };
458
459        ExcludeFocus::new(
460            IgnorePointer::new()
461                .ignoring(!widget.is_enabled)
462                .child(template),
463        )
464        .excluding(!widget.is_enabled)
465        .into_widget()
466    }
467}
468
469/// `DefaultExpanderStyle`'s template: `ExpanderHeader` and `ExpanderContentClip` in the two rows the direction orders.
470fn default_template(
471    resources: &ThemeResources,
472    widget: &Expander,
473    states: ExpanderTemplateStates,
474    parts: &ExpanderTemplateParts,
475) -> WidgetRef {
476    let header_widget = widget.clone();
477    let changed = widget.is_expanded_changed.clone();
478    let header = ToggleButton::new(Some(widget.is_expanded), move |app, value| {
479        changed(app, value == Some(true))
480    })
481    .content(
482        widget
483            .header
484            .clone()
485            .unwrap_or_else(|| SizedBox::shrink().into_widget()),
486    )
487    .is_enabled(widget.is_enabled)
488    .template(move |app, context, _, content, common| {
489        expander_header(
490            app,
491            context,
492            &header_widget,
493            states.expand,
494            content.unwrap_or_else(|| SizedBox::shrink().into_widget()),
495            common,
496        )
497    });
498
499    let down = widget.expand_direction == ExpandDirection::Down;
500    let corner_radius = widget
501        .corner_radius
502        .unwrap_or(resources.control_corner_radius[0]);
503    let content = ControlBorder::new(
504        widget
505            .background
506            .unwrap_or(Brush::Solid(resources.expander_content_background)),
507        widget
508            .border_brush
509            .unwrap_or(Brush::Solid(resources.expander_content_border_brush)),
510    )
511    .border_thickness_ltrb(if down {
512        resources.expander_content_down_border_thickness
513    } else {
514        resources.expander_content_up_border_thickness
515    })
516    .corner_radius_corners(if down {
517        [0.0, 0.0, corner_radius, corner_radius]
518    } else {
519        [corner_radius, corner_radius, 0.0, 0.0]
520    })
521    .padding(widget.padding.unwrap_or(resources.expander_content_padding))
522    .child(
523        widget
524            .content
525            .clone()
526            .unwrap_or_else(|| SizedBox::shrink().into_widget()),
527    );
528    let content = ConstrainedBox::new(
529        BoxConstraints::new()
530            .min_height(widget.min_height.unwrap_or(resources.expander_min_height)),
531    )
532    .child(content);
533    let grid = Grid::new()
534        .row_definitions([
535            RowDefinition::new(if down {
536                GridLength::AUTO
537            } else {
538                GridLength::STAR
539            }),
540            RowDefinition::new(if down {
541                GridLength::STAR
542            } else {
543                GridLength::AUTO
544            }),
545        ])
546        .children([
547            GridCell::new(header)
548                .row(if down { 0 } else { 1 })
549                .into_widget(),
550            GridCell::new(parts.expander_content_clip(content))
551                .row(if down { 1 } else { 0 })
552                .into_widget(),
553        ]);
554    ConstrainedBox::new(
555        BoxConstraints::new()
556            .min_width(widget.min_width.unwrap_or(resources.flyout_theme_min_width)),
557    )
558    .child(grid)
559    .into_widget()
560}
561
562/// ExpanderHeaderDownStyle / ExpanderHeaderUpStyle common and checked visual states.
563fn expander_header(
564    app: &mut App,
565    context: BuildContext,
566    widget: &Expander,
567    expand: ExpandState,
568    content: WidgetRef,
569    states: ControlStates,
570) -> WidgetRef {
571    let theme = ThemeResources::of(app, context);
572    let r = &theme;
573    let (foreground, border, chevron_fill, chevron_border, chevron_foreground) = match states.common
574    {
575        CommonState::PointerOver => (
576            r.expander_header_foreground_pointer_over,
577            r.expander_header_border_pointer_over_brush,
578            r.expander_chevron_pointer_over_background,
579            r.expander_chevron_border_pointer_over_brush,
580            r.expander_chevron_pointer_over_foreground,
581        ),
582        CommonState::Pressed => (
583            r.expander_header_foreground_pressed,
584            r.expander_header_border_pressed_brush,
585            r.expander_chevron_pressed_background,
586            r.expander_chevron_border_pressed_brush,
587            r.expander_chevron_pressed_foreground,
588        ),
589        CommonState::Disabled => (
590            r.expander_header_disabled_foreground,
591            r.expander_header_disabled_border_brush,
592            r.expander_chevron_background,
593            r.expander_header_disabled_border_brush,
594            r.expander_header_disabled_foreground,
595        ),
596        _ => (
597            r.expander_header_foreground,
598            r.expander_header_border_brush,
599            r.expander_chevron_background,
600            r.expander_chevron_border_brush,
601            r.expander_chevron_foreground,
602        ),
603    };
604    let corner_radius = widget.corner_radius.unwrap_or(r.control_corner_radius[0]);
605    // `ExpandDown` and `ExpandUp` set `ExpanderHeader.CornerRadius` through the corner filters.
606    let radii = match expand {
607        ExpandState::ExpandDown => [corner_radius, corner_radius, 0.0, 0.0],
608        ExpandState::ExpandUp => [0.0, 0.0, corner_radius, corner_radius],
609        ExpandState::CollapseDown | ExpandState::CollapseUp => [corner_radius; 4],
610    };
611    let points_up = widget.is_expanded == (widget.expand_direction == ExpandDirection::Down);
612
613    // Native rotation is the established AnimatedIcon substitute used by NavigationView.
614    let chevron = AnimatedRotation::new(
615        if points_up { 0.5 } else { 0.0 },
616        r.control_normal_animation_duration,
617    )
618    .child(
619        FontIcon::symbol(FluentSymbol::ChevronDown)
620            .font_size(r.expander_chevron_glyph_size)
621            .foreground(chevron_foreground),
622    );
623    let chevron = Padding::new(EdgeInsetsGeometry::from_ltrb(
624        r.expander_chevron_margin[0],
625        r.expander_chevron_margin[1],
626        r.expander_chevron_margin[2],
627        r.expander_chevron_margin[3],
628    ))
629    .child(
630        SizedBox::new()
631            .width(r.expander_chevron_button_size)
632            .height(r.expander_chevron_button_size)
633            .child(
634                ControlBorder::new(Brush::Solid(chevron_fill), Brush::Solid(chevron_border))
635                    .border_thickness_ltrb(r.expander_chevron_border_thickness)
636                    .corner_radius(r.control_corner_radius[0])
637                    .child(Center::new().child(chevron)),
638            ),
639    );
640    let layout = Grid::new()
641        .column_definitions([
642            ColumnDefinition::new(GridLength::STAR),
643            ColumnDefinition::new(GridLength::AUTO),
644        ])
645        .children([
646            GridCell::new(
647                Align::new()
648                    .alignment(Alignment::CENTER_LEFT.into())
649                    .width_factor(1.0)
650                    .height_factor(1.0)
651                    .child(DefaultTextStyle::new(
652                        control_text_style(
653                            &theme,
654                            r.control_content_theme_font_size,
655                            FontWeight::NORMAL,
656                            foreground,
657                        ),
658                        content,
659                    )),
660            )
661            .into_widget(),
662            GridCell::new(Center::new().child(chevron))
663                .column(1)
664                .into_widget(),
665        ]);
666    FocusVisual::new(
667        ConstrainedBox::new(
668            BoxConstraints::new().min_height(widget.min_height.unwrap_or(r.expander_min_height)),
669        )
670        .child(
671            ControlBorder::new(
672                Brush::Solid(r.expander_header_background),
673                Brush::Solid(border),
674            )
675            .border_thickness_ltrb(r.expander_header_border_thickness)
676            .corner_radius_corners(radii)
677            .padding(r.expander_header_padding)
678            .child(layout),
679        ),
680        theme.theme,
681    )
682    .visible(states.focused)
683    .into_widget()
684}