1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum ExpandDirection {
16 #[default]
18 Down,
19
20 Up,
22}
23
24pub type ExpanderExpandedChangedHandler = Rc<dyn Fn(&mut App, bool)>;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum ExpandState {
30 ExpandDown,
32 ExpandUp,
34 CollapseDown,
36 CollapseUp,
38}
39
40impl ExpandState {
41 pub fn is_expanded(self) -> bool {
43 matches!(self, ExpandState::ExpandDown | ExpandState::ExpandUp)
44 }
45}
46
47pub type ExpanderTemplate = Rc<
49 dyn Fn(
50 &mut App,
51 BuildContext,
52 &Expander,
53 ExpanderTemplateStates,
54 &ExpanderTemplateParts,
55 ) -> WidgetRef,
56>;
57
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct ExpanderTemplateStates {
61 pub expand: ExpandState,
63}
64
65pub struct ExpanderTemplateParts {
67 content_clip: Rc<dyn Fn(WidgetRef) -> WidgetRef>,
69}
70
71impl ExpanderTemplateParts {
72 #[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#[derive(Clone)]
81pub struct Expander {
82 pub is_expanded: bool,
84
85 pub is_expanded_changed: ExpanderExpandedChangedHandler,
87
88 pub header: Option<WidgetRef>,
90
91 pub content: Option<WidgetRef>,
93
94 pub expand_direction: ExpandDirection,
96
97 pub is_enabled: bool,
99
100 pub background: Option<Brush>,
102
103 pub border_brush: Option<Brush>,
105
106 pub padding: Option<[f64; 4]>,
108
109 pub corner_radius: Option<f64>,
111
112 pub min_width: Option<f64>,
114
115 pub min_height: Option<f64>,
117
118 pub expanding: Option<Listener>,
120
121 pub collapsed: Option<Listener>,
123
124 pub template: Option<ExpanderTemplate>,
126
127 pub key: Option<KeyRef>,
129}
130
131impl Expander {
132 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 #[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 #[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 pub fn expand_direction(mut self, value: ExpandDirection) -> Self {
170 self.expand_direction = value;
171 self
172 }
173
174 pub fn is_enabled(mut self, value: bool) -> Self {
176 self.is_enabled = value;
177 self
178 }
179
180 pub fn background(mut self, value: Brush) -> Self {
182 self.background = Some(value);
183 self
184 }
185
186 pub fn border_brush(mut self, value: Brush) -> Self {
188 self.border_brush = Some(value);
189 self
190 }
191
192 pub fn padding(mut self, value: [f64; 4]) -> Self {
194 self.padding = Some(value);
195 self
196 }
197
198 pub fn corner_radius(mut self, value: f64) -> Self {
200 self.corner_radius = Some(value);
201 self
202 }
203
204 pub fn min_width(mut self, value: f64) -> Self {
206 self.min_width = Some(value);
207 self
208 }
209
210 pub fn min_height(mut self, value: f64) -> Self {
212 self.min_height = Some(value);
213 self
214 }
215
216 pub fn expanding(mut self, value: Listener) -> Self {
218 self.expanding = Some(value);
219 self
220 }
221
222 pub fn collapsed(mut self, value: Listener) -> Self {
224 self.collapsed = Some(value);
225 self
226 }
227
228 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 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
260pub struct ExpanderState {
262 state: StateData<Expander>,
264
265 single_ticker_provider: SingleTickerProviderStateMixinData,
267
268 ticker: Option<Ref<Ticker>>,
270
271 elapsed: Duration,
273
274 content_visible: bool,
276
277 motion_direction: ExpandDirection,
279}
280
281impl StatefulWidget for Expander {
282 type State = ExpanderState;
283
284 fn key(&self) -> Option<&KeyRef> {
286 self.key.as_ref()
287 }
288
289 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 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 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 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 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 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 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 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 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
469fn 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
562fn 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 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 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}