use crate::*;
use std::{fmt, rc::Rc, time::Duration};
use waft_animation::{Cubic, Curve};
use waft_embedder::{FontWeight, Offset};
use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
use waft_painting::{Alignment, EdgeInsetsGeometry};
use waft_rendering::BoxConstraints;
use waft_scheduler::{FrameCallback, SchedulerBinding, Ticker};
use waft_widgets::*;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ExpandDirection {
#[default]
Down,
Up,
}
pub type ExpanderExpandedChangedHandler = Rc<dyn Fn(&mut App, bool)>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExpandState {
ExpandDown,
ExpandUp,
CollapseDown,
CollapseUp,
}
impl ExpandState {
pub fn is_expanded(self) -> bool {
matches!(self, ExpandState::ExpandDown | ExpandState::ExpandUp)
}
}
pub type ExpanderTemplate = Rc<
dyn Fn(
&mut App,
BuildContext,
&Expander,
ExpanderTemplateStates,
&ExpanderTemplateParts,
) -> WidgetRef,
>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExpanderTemplateStates {
pub expand: ExpandState,
}
pub struct ExpanderTemplateParts {
content_clip: Rc<dyn Fn(WidgetRef) -> WidgetRef>,
}
impl ExpanderTemplateParts {
#[cfg_attr(debug_assertions, track_caller)]
pub fn expander_content_clip<K>(&self, expander_content: impl IntoWidget<K>) -> WidgetRef {
(self.content_clip)(expander_content.into_widget())
}
}
#[derive(Clone)]
pub struct Expander {
pub is_expanded: bool,
pub is_expanded_changed: ExpanderExpandedChangedHandler,
pub header: Option<WidgetRef>,
pub content: Option<WidgetRef>,
pub expand_direction: ExpandDirection,
pub is_enabled: bool,
pub background: Option<Brush>,
pub border_brush: Option<Brush>,
pub padding: Option<[f64; 4]>,
pub corner_radius: Option<f64>,
pub min_width: Option<f64>,
pub min_height: Option<f64>,
pub expanding: Option<Listener>,
pub collapsed: Option<Listener>,
pub template: Option<ExpanderTemplate>,
pub key: Option<KeyRef>,
}
impl Expander {
pub fn new(is_expanded: bool, changed: impl Fn(&mut App, bool) + 'static) -> Self {
Self {
is_expanded,
is_expanded_changed: Rc::new(changed),
header: None,
content: None,
expand_direction: ExpandDirection::Down,
is_enabled: true,
background: None,
border_brush: None,
padding: None,
corner_radius: None,
min_width: None,
min_height: None,
expanding: None,
collapsed: None,
template: None,
key: None,
}
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
self.header = Some(value.into_widget());
self
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn content<K>(mut self, value: impl IntoWidget<K>) -> Self {
self.content = Some(value.into_widget());
self
}
pub fn expand_direction(mut self, value: ExpandDirection) -> Self {
self.expand_direction = value;
self
}
pub fn is_enabled(mut self, value: bool) -> Self {
self.is_enabled = value;
self
}
pub fn background(mut self, value: Brush) -> Self {
self.background = Some(value);
self
}
pub fn border_brush(mut self, value: Brush) -> Self {
self.border_brush = Some(value);
self
}
pub fn padding(mut self, value: [f64; 4]) -> Self {
self.padding = Some(value);
self
}
pub fn corner_radius(mut self, value: f64) -> Self {
self.corner_radius = Some(value);
self
}
pub fn min_width(mut self, value: f64) -> Self {
self.min_width = Some(value);
self
}
pub fn min_height(mut self, value: f64) -> Self {
self.min_height = Some(value);
self
}
pub fn expanding(mut self, value: Listener) -> Self {
self.expanding = Some(value);
self
}
pub fn collapsed(mut self, value: Listener) -> Self {
self.collapsed = Some(value);
self
}
pub fn template(
mut self,
builder: impl Fn(
&mut App,
BuildContext,
&Expander,
ExpanderTemplateStates,
&ExpanderTemplateParts,
) -> WidgetRef
+ 'static,
) -> Self {
self.template = Some(Rc::new(builder));
self
}
pub fn key(mut self, value: KeyRef) -> Self {
self.key = Some(value);
self
}
}
impl fmt::Debug for Expander {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Expander")
.field("is_expanded", &self.is_expanded)
.field("expand_direction", &self.expand_direction)
.finish_non_exhaustive()
}
}
pub struct ExpanderState {
state: StateData<Expander>,
single_ticker_provider: SingleTickerProviderStateMixinData,
ticker: Option<Ref<Ticker>>,
elapsed: Duration,
content_visible: bool,
motion_direction: ExpandDirection,
}
impl StatefulWidget for Expander {
type State = ExpanderState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ExpanderState {
ExpanderState {
state: StateData::new(),
single_ticker_provider: Default::default(),
ticker: None,
elapsed: Duration::ZERO,
content_visible: self.is_expanded,
motion_direction: self.expand_direction,
}
}
}
impl SingleTickerProviderStateMixin for ExpanderState {
fn single_ticker_provider_data(
self: Handle<Self>,
app: &App,
) -> &SingleTickerProviderStateMixinData {
&app.get(self).single_ticker_provider
}
fn single_ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SingleTickerProviderStateMixinData {
&mut app.get_mut(self).single_ticker_provider
}
}
impl ExpanderState {
fn duration(self: Handle<Self>, app: &App) -> Duration {
Duration::from_millis(if self.widget(app).is_expanded {
333
} else if app.get(self).motion_direction == ExpandDirection::Up {
200
} else {
167
})
}
fn tick(self: Handle<Self>, app: &mut App, elapsed: Duration) {
let finished = elapsed >= self.duration(app);
let expanded = self.widget(app).is_expanded;
self.set_state(app, |state| {
state.elapsed = elapsed;
if finished && !expanded {
state.content_visible = false;
}
});
if finished {
app.get(self).ticker.handle().unwrap().stop(app, false);
}
}
fn translation(self: Handle<Self>, app: &App) -> f64 {
let time = app.get(self).elapsed.as_secs_f64();
let sign = if app.get(self).motion_direction == ExpandDirection::Down {
-1.0
} else {
1.0
};
if self.widget(app).is_expanded {
sign * (1.0 - Cubic::new(0.0, 0.0, 0.0, 1.0).transform((time / 0.333).min(1.0)))
} else {
sign * Cubic::new(1.0, 1.0, 0.0, 1.0).transform((time / 0.167).min(1.0))
}
}
}
impl State for ExpanderState {
type Widget = Expander;
waft_widgets::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let ticker = SingleTickerProviderStateMixin::create_ticker(
self,
app,
FrameCallback::new(move |app, elapsed| self.tick(app, elapsed)),
);
app.get_mut(self).ticker = Some(ticker.clone());
if self.widget(app).is_expanded {
ticker.start(app);
}
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old: &Expander) {
let widget = self.widget(app).clone();
if old.is_expanded == widget.is_expanded {
return;
}
let ticker = app.get(self).ticker.clone().unwrap();
ticker.stop(app, false);
let state = app.get_mut(self);
state.elapsed = Duration::ZERO;
state.content_visible = true;
state.motion_direction = widget.expand_direction;
ticker.start(app);
let event = if widget.is_expanded {
widget.expanding
} else {
widget.collapsed
};
if let Some(event) = event {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if app.contains(self) && self.mounted(app) {
event.call(app);
}
}),
View::maybe_id_of(app, self.context(app)),
);
}
}
fn activate(self: Handle<Self>, app: &mut App) {
SingleTickerProviderStateMixin::activate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
app.get(self).ticker.handle().unwrap().dispose(app);
SingleTickerProviderStateMixin::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let widget = self.widget(app).clone();
let state = app.get(self);
let states = ExpanderTemplateStates {
expand: match (widget.is_expanded, state.motion_direction) {
(true, ExpandDirection::Down) => ExpandState::ExpandDown,
(true, ExpandDirection::Up) => ExpandState::ExpandUp,
(false, ExpandDirection::Down) => ExpandState::CollapseDown,
(false, ExpandDirection::Up) => ExpandState::CollapseUp,
},
};
let visible = state.content_visible;
let translation = Offset::new(0.0, self.translation(app));
let parts = ExpanderTemplateParts {
content_clip: Rc::new(move |expander_content| {
Offstage::new()
.offstage(!visible)
.child(TickerMode::new(
visible,
ExcludeFocus::new(ClipRect::new().child(
FractionalTranslation::new(translation).child(expander_content),
))
.excluding(!visible),
))
.into_widget()
}),
};
let template = match widget.template.clone() {
Some(template) => template(app, context, &widget, states, &parts),
None => {
let resources = ThemeResources::of(app, context);
default_template(&resources, &widget, states, &parts)
}
};
ExcludeFocus::new(
IgnorePointer::new()
.ignoring(!widget.is_enabled)
.child(template),
)
.excluding(!widget.is_enabled)
.into_widget()
}
}
fn default_template(
resources: &ThemeResources,
widget: &Expander,
states: ExpanderTemplateStates,
parts: &ExpanderTemplateParts,
) -> WidgetRef {
let header_widget = widget.clone();
let changed = widget.is_expanded_changed.clone();
let header = ToggleButton::new(Some(widget.is_expanded), move |app, value| {
changed(app, value == Some(true))
})
.content(
widget
.header
.clone()
.unwrap_or_else(|| SizedBox::shrink().into_widget()),
)
.is_enabled(widget.is_enabled)
.template(move |app, context, _, content, common| {
expander_header(
app,
context,
&header_widget,
states.expand,
content.unwrap_or_else(|| SizedBox::shrink().into_widget()),
common,
)
});
let down = widget.expand_direction == ExpandDirection::Down;
let corner_radius = widget
.corner_radius
.unwrap_or(resources.control_corner_radius[0]);
let content = ControlBorder::new(
widget
.background
.unwrap_or(Brush::Solid(resources.expander_content_background)),
widget
.border_brush
.unwrap_or(Brush::Solid(resources.expander_content_border_brush)),
)
.border_thickness_ltrb(if down {
resources.expander_content_down_border_thickness
} else {
resources.expander_content_up_border_thickness
})
.corner_radius_corners(if down {
[0.0, 0.0, corner_radius, corner_radius]
} else {
[corner_radius, corner_radius, 0.0, 0.0]
})
.padding(widget.padding.unwrap_or(resources.expander_content_padding))
.child(
widget
.content
.clone()
.unwrap_or_else(|| SizedBox::shrink().into_widget()),
);
let content = ConstrainedBox::new(
BoxConstraints::new()
.min_height(widget.min_height.unwrap_or(resources.expander_min_height)),
)
.child(content);
let grid = Grid::new()
.row_definitions([
RowDefinition::new(if down {
GridLength::AUTO
} else {
GridLength::STAR
}),
RowDefinition::new(if down {
GridLength::STAR
} else {
GridLength::AUTO
}),
])
.children([
GridCell::new(header)
.row(if down { 0 } else { 1 })
.into_widget(),
GridCell::new(parts.expander_content_clip(content))
.row(if down { 1 } else { 0 })
.into_widget(),
]);
ConstrainedBox::new(
BoxConstraints::new()
.min_width(widget.min_width.unwrap_or(resources.flyout_theme_min_width)),
)
.child(grid)
.into_widget()
}
fn expander_header(
app: &mut App,
context: BuildContext,
widget: &Expander,
expand: ExpandState,
content: WidgetRef,
states: ControlStates,
) -> WidgetRef {
let theme = ThemeResources::of(app, context);
let r = &theme;
let (foreground, border, chevron_fill, chevron_border, chevron_foreground) = match states.common
{
CommonState::PointerOver => (
r.expander_header_foreground_pointer_over,
r.expander_header_border_pointer_over_brush,
r.expander_chevron_pointer_over_background,
r.expander_chevron_border_pointer_over_brush,
r.expander_chevron_pointer_over_foreground,
),
CommonState::Pressed => (
r.expander_header_foreground_pressed,
r.expander_header_border_pressed_brush,
r.expander_chevron_pressed_background,
r.expander_chevron_border_pressed_brush,
r.expander_chevron_pressed_foreground,
),
CommonState::Disabled => (
r.expander_header_disabled_foreground,
r.expander_header_disabled_border_brush,
r.expander_chevron_background,
r.expander_header_disabled_border_brush,
r.expander_header_disabled_foreground,
),
_ => (
r.expander_header_foreground,
r.expander_header_border_brush,
r.expander_chevron_background,
r.expander_chevron_border_brush,
r.expander_chevron_foreground,
),
};
let corner_radius = widget.corner_radius.unwrap_or(r.control_corner_radius[0]);
let radii = match expand {
ExpandState::ExpandDown => [corner_radius, corner_radius, 0.0, 0.0],
ExpandState::ExpandUp => [0.0, 0.0, corner_radius, corner_radius],
ExpandState::CollapseDown | ExpandState::CollapseUp => [corner_radius; 4],
};
let points_up = widget.is_expanded == (widget.expand_direction == ExpandDirection::Down);
let chevron = AnimatedRotation::new(
if points_up { 0.5 } else { 0.0 },
r.control_normal_animation_duration,
)
.child(
FontIcon::symbol(FluentSymbol::ChevronDown)
.font_size(r.expander_chevron_glyph_size)
.foreground(chevron_foreground),
);
let chevron = Padding::new(EdgeInsetsGeometry::from_ltrb(
r.expander_chevron_margin[0],
r.expander_chevron_margin[1],
r.expander_chevron_margin[2],
r.expander_chevron_margin[3],
))
.child(
SizedBox::new()
.width(r.expander_chevron_button_size)
.height(r.expander_chevron_button_size)
.child(
ControlBorder::new(Brush::Solid(chevron_fill), Brush::Solid(chevron_border))
.border_thickness_ltrb(r.expander_chevron_border_thickness)
.corner_radius(r.control_corner_radius[0])
.child(Center::new().child(chevron)),
),
);
let layout = Grid::new()
.column_definitions([
ColumnDefinition::new(GridLength::STAR),
ColumnDefinition::new(GridLength::AUTO),
])
.children([
GridCell::new(
Align::new()
.alignment(Alignment::CENTER_LEFT.into())
.width_factor(1.0)
.height_factor(1.0)
.child(DefaultTextStyle::new(
control_text_style(
&theme,
r.control_content_theme_font_size,
FontWeight::NORMAL,
foreground,
),
content,
)),
)
.into_widget(),
GridCell::new(Center::new().child(chevron))
.column(1)
.into_widget(),
]);
FocusVisual::new(
ConstrainedBox::new(
BoxConstraints::new().min_height(widget.min_height.unwrap_or(r.expander_min_height)),
)
.child(
ControlBorder::new(
Brush::Solid(r.expander_header_background),
Brush::Solid(border),
)
.border_thickness_ltrb(r.expander_header_border_thickness)
.corner_radius_corners(radii)
.padding(r.expander_header_padding)
.child(layout),
),
theme.theme,
)
.visible(states.focused)
.into_widget()
}