use super::flyout::shadow::PopupShadow;
use crate::*;
use std::{cell::Cell, collections::HashMap, fmt, rc::Rc, time::Duration};
use waft_animation::{AnimationStatus, AnimationStatusListener, AnyAnimation, Cubic, Curve};
use waft_embedder::{FontWeight, TextDirection};
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Completer, CompleterFuture, Handle, HandleId,
ListenableObject, Listener,
};
use waft_painting::BorderRadius;
use waft_rendering::{BoxConstraints, CrossAxisAlignment, MainAxisSize};
use waft_scheduler::{FrameCallback, SchedulerBinding};
use waft_services::{KeyEvent, LogicalKeyboardKey};
use waft_widgets::*;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ContentDialogButton {
#[default]
None,
Primary,
Secondary,
Close,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ContentDialogResult {
#[default]
None,
Primary,
Secondary,
}
pub type ContentDialogButtonClickDeferral = Deferral;
pub type ContentDialogClosingDeferral = Deferral;
pub struct ContentDialogButtonClickEventArgs {
cancel: Cell<bool>,
deferrals: Rc<DeferralManager>,
generation: u64,
}
impl ContentDialogButtonClickEventArgs {
pub fn cancel(&self) -> bool {
self.cancel.get()
}
pub fn set_cancel(&self, cancel: bool) {
self.cancel.set(cancel);
}
pub fn get_deferral(&self) -> Result<ContentDialogButtonClickDeferral, DeferralCompleted> {
self.deferrals.get_deferral(self.generation)
}
}
impl fmt::Debug for ContentDialogButtonClickEventArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ContentDialogButtonClickEventArgs")
.field("cancel", &self.cancel.get())
.finish_non_exhaustive()
}
}
pub struct ContentDialogClosingEventArgs {
result: ContentDialogResult,
cancel: Cell<bool>,
deferrals: Rc<DeferralManager>,
generation: u64,
}
impl ContentDialogClosingEventArgs {
pub fn result(&self) -> ContentDialogResult {
self.result
}
pub fn cancel(&self) -> bool {
self.cancel.get()
}
pub fn set_cancel(&self, cancel: bool) {
self.cancel.set(cancel);
}
pub fn get_deferral(&self) -> Result<ContentDialogClosingDeferral, DeferralCompleted> {
self.deferrals.get_deferral(self.generation)
}
}
impl fmt::Debug for ContentDialogClosingEventArgs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ContentDialogClosingEventArgs")
.field("result", &self.result)
.field("cancel", &self.cancel.get())
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug)]
pub struct ContentDialogClosedEventArgs {
pub result: ContentDialogResult,
}
pub type ContentDialogButtonClickHandler =
Rc<dyn Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>)>;
pub type ContentDialogClosingHandler = Rc<dyn Fn(&mut App, &Rc<ContentDialogClosingEventArgs>)>;
pub type ContentDialogClosedHandler = Rc<dyn Fn(&mut App, ContentDialogClosedEventArgs)>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContentDialogError {
MultipleOpen,
}
impl fmt::Display for ContentDialogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MultipleOpen => f.write_str("only one ContentDialog can be open at a time"),
}
}
}
impl std::error::Error for ContentDialogError {}
#[derive(Default)]
struct ContentDialogMetadata {
open: HashMap<HandleId, Handle<ContentDialog>>,
}
pub struct ContentDialog {
pub title: Option<WidgetRef>,
pub content: Option<WidgetRef>,
pub primary_button_text: String,
pub secondary_button_text: String,
pub close_button_text: String,
pub is_primary_button_enabled: bool,
pub is_secondary_button_enabled: bool,
pub default_button: ContentDialogButton,
pub full_size_desired: bool,
pub primary_button_click: Option<ContentDialogButtonClickHandler>,
pub secondary_button_click: Option<ContentDialogButtonClickHandler>,
pub close_button_click: Option<ContentDialogButtonClickHandler>,
pub opened: Option<Listener>,
pub closing: Option<ContentDialogClosingHandler>,
pub closed: Option<ContentDialogClosedHandler>,
notifier: ChangeNotifierData,
showing: Option<Showing>,
button_click_deferrals: Rc<DeferralManager>,
closing_deferrals: Rc<DeferralManager>,
disposed: bool,
}
struct Showing {
route: AnyRoute,
navigator: Handle<NavigatorState>,
completion: Completer<ContentDialogResult>,
result: ContentDialogResult,
hide_in_progress: bool,
skip_closing_event: bool,
resources: Rc<ThemeResources>,
direction: TextDirection,
}
impl fmt::Debug for ContentDialog {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ContentDialog")
.field("primary_button_text", &self.primary_button_text)
.field("secondary_button_text", &self.secondary_button_text)
.field("close_button_text", &self.close_button_text)
.field("default_button", &self.default_button)
.field("showing", &self.showing.is_some())
.finish_non_exhaustive()
}
}
impl ChangeNotifier for ContentDialog {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.notifier
}
}
impl ContentDialog {
pub fn new(app: &mut App) -> Handle<Self> {
app.create(Self {
title: None,
content: None,
primary_button_text: String::new(),
secondary_button_text: String::new(),
close_button_text: String::new(),
is_primary_button_enabled: true,
is_secondary_button_enabled: true,
default_button: ContentDialogButton::None,
full_size_desired: false,
primary_button_click: None,
secondary_button_click: None,
close_button_click: None,
opened: None,
closing: None,
closed: None,
notifier: ChangeNotifierData::new(),
showing: None,
button_click_deferrals: DeferralManager::new(),
closing_deferrals: DeferralManager::new(),
disposed: false,
})
}
pub fn title<K>(self: Handle<Self>, app: &mut App, title: impl IntoWidget<K>) -> Handle<Self> {
self.change(app, |dialog| dialog.title = Some(title.into_widget()))
}
pub fn content<K>(
self: Handle<Self>,
app: &mut App,
content: impl IntoWidget<K>,
) -> Handle<Self> {
self.change(app, |dialog| dialog.content = Some(content.into_widget()))
}
pub fn primary_button_text(
self: Handle<Self>,
app: &mut App,
text: impl Into<String>,
) -> Handle<Self> {
self.change(app, |dialog| dialog.primary_button_text = text.into())
}
pub fn secondary_button_text(
self: Handle<Self>,
app: &mut App,
text: impl Into<String>,
) -> Handle<Self> {
self.change(app, |dialog| dialog.secondary_button_text = text.into())
}
pub fn close_button_text(
self: Handle<Self>,
app: &mut App,
text: impl Into<String>,
) -> Handle<Self> {
self.change(app, |dialog| dialog.close_button_text = text.into())
}
pub fn is_primary_button_enabled(
self: Handle<Self>,
app: &mut App,
value: bool,
) -> Handle<Self> {
self.change(app, |dialog| dialog.is_primary_button_enabled = value)
}
pub fn is_secondary_button_enabled(
self: Handle<Self>,
app: &mut App,
value: bool,
) -> Handle<Self> {
self.change(app, |dialog| dialog.is_secondary_button_enabled = value)
}
pub fn default_button(
self: Handle<Self>,
app: &mut App,
button: ContentDialogButton,
) -> Handle<Self> {
self.change(app, |dialog| dialog.default_button = button)
}
pub fn full_size_desired(self: Handle<Self>, app: &mut App, value: bool) -> Handle<Self> {
self.change(app, |dialog| dialog.full_size_desired = value)
}
pub fn primary_button_click(
self: Handle<Self>,
app: &mut App,
handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
) -> Handle<Self> {
app.get_mut(self).primary_button_click = Some(Rc::new(handler));
self
}
pub fn secondary_button_click(
self: Handle<Self>,
app: &mut App,
handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
) -> Handle<Self> {
app.get_mut(self).secondary_button_click = Some(Rc::new(handler));
self
}
pub fn close_button_click(
self: Handle<Self>,
app: &mut App,
handler: impl Fn(&mut App, &Rc<ContentDialogButtonClickEventArgs>) + 'static,
) -> Handle<Self> {
app.get_mut(self).close_button_click = Some(Rc::new(handler));
self
}
pub fn opened(self: Handle<Self>, app: &mut App, handler: Listener) -> Handle<Self> {
app.get_mut(self).opened = Some(handler);
self
}
pub fn closing(
self: Handle<Self>,
app: &mut App,
handler: impl Fn(&mut App, &Rc<ContentDialogClosingEventArgs>) + 'static,
) -> Handle<Self> {
app.get_mut(self).closing = Some(Rc::new(handler));
self
}
pub fn closed(
self: Handle<Self>,
app: &mut App,
handler: impl Fn(&mut App, ContentDialogClosedEventArgs) + 'static,
) -> Handle<Self> {
app.get_mut(self).closed = Some(Rc::new(handler));
self
}
pub fn show_async(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> Result<CompleterFuture<ContentDialogResult>, ContentDialogError> {
assert!(
!app.get(self).disposed,
"cannot show a disposed ContentDialog"
);
let navigator = Navigator::of(app, context, true);
let metadata = app.singleton::<ContentDialogMetadata>();
if app.get(self).showing.is_some() || app.get(metadata).open.contains_key(&navigator.id()) {
return Err(ContentDialogError::MultipleOpen);
}
let resources = ThemeResources::of(app, context);
let direction = Directionality::maybe_of(app, context).unwrap_or(TextDirection::Ltr);
let dialog_route = self.dialog_route(app, &resources);
let route = dialog_route.as_route();
let completion = Completer::new();
let result = completion.future();
app.get_mut(self).showing = Some(Showing {
route,
navigator,
completion,
result: ContentDialogResult::None,
hide_in_progress: false,
skip_closing_event: true,
resources,
direction,
});
app.get_mut(metadata).open.insert(navigator.id(), self);
navigator
.push(app, route)
.then(app, move |app, _| self.route_popped(app, route));
self.finish_closing_when_dismissed(app, dialog_route);
Ok(result)
}
pub fn hide(self: Handle<Self>, app: &mut App) {
self.hide_internal(app, ContentDialogResult::None);
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
if app.get(self).disposed {
return;
}
app.get_mut(self).disposed = true;
if app.get(self).showing.is_none() {
self.notifier_dispose(app);
app.destroy(self);
return;
}
self.hide_internal(app, ContentDialogResult::None);
}
fn change(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut Self)) -> Handle<Self> {
change(app.get_mut(self));
self.notify_listeners(app);
self
}
fn dialog_route(
self: Handle<Self>,
app: &mut App,
resources: &ThemeResources,
) -> Handle<ContentDialogRoute> {
let smoke = resources.content_dialog_smoke_fill;
ContentDialogRoute::new(app, self, smoke)
}
fn finish_closing_when_dismissed(
self: Handle<Self>,
app: &mut App,
route: Handle<ContentDialogRoute>,
) {
let Some(animation) = TransitionRoute::animation(route, app) else {
return;
};
let shown = route.as_route();
animation.add_status_listener(
app,
AnimationStatusListener::new(move |status, app| {
if status == AnimationStatus::Dismissed {
self.finish_closing(app, shown);
}
}),
);
}
fn command_button_clicked(self: Handle<Self>, app: &mut App, button: ContentDialogButton) {
if !app.contains(self) || !self.is_accepting_commands(app) {
return;
}
let dialog = app.get(self);
let (handler, result) = match button {
ContentDialogButton::Primary => (
dialog.primary_button_click.clone(),
ContentDialogResult::Primary,
),
ContentDialogButton::Secondary => (
dialog.secondary_button_click.clone(),
ContentDialogResult::Secondary,
),
ContentDialogButton::Close => {
(dialog.close_button_click.clone(), ContentDialogResult::None)
}
ContentDialogButton::None => return,
};
let deferrals = Rc::clone(&dialog.button_click_deferrals);
let Some(generation) = deferrals.prepare() else {
return;
};
let args = Rc::new(ContentDialogButtonClickEventArgs {
cancel: Cell::new(false),
deferrals: Rc::clone(&deferrals),
generation,
});
if let Some(handler) = handler {
handler(app, &args);
}
deferrals.continue_with(app, move |app| {
if app.contains(self) && !args.cancel() {
self.hide_internal(app, result);
}
});
}
fn execute_close_action(self: Handle<Self>, app: &mut App) {
if app.get(self).close_button_text.is_empty() {
self.hide_internal(app, ContentDialogResult::None);
} else {
self.command_button_clicked(app, ContentDialogButton::Close);
}
}
fn invoke_default_button(self: Handle<Self>, app: &mut App) -> bool {
let dialog = app.get(self);
let enabled = match dialog.default_button {
ContentDialogButton::None => return false,
ContentDialogButton::Primary => dialog.is_primary_button_enabled,
ContentDialogButton::Secondary => dialog.is_secondary_button_enabled,
ContentDialogButton::Close => true,
};
if enabled {
let button = dialog.default_button;
self.command_button_clicked(app, button);
}
enabled
}
fn hide_internal(self: Handle<Self>, app: &mut App, result: ContentDialogResult) {
if !self.is_accepting_commands(app) {
return;
}
let deferrals = Rc::clone(&app.get(self).closing_deferrals);
let generation = deferrals
.prepare()
.expect("a close in progress stops new ones");
let dialog = app.get_mut(self);
let disposed = dialog.disposed;
let showing = dialog.showing.as_mut().expect("a showing dialog");
showing.hide_in_progress = true;
let fire_closing = !showing.skip_closing_event && !disposed;
let args = fire_closing.then(|| {
Rc::new(ContentDialogClosingEventArgs {
result,
cancel: Cell::new(false),
deferrals: Rc::clone(&deferrals),
generation,
})
});
if let Some(args) = &args
&& let Some(closing) = app.get(self).closing.clone()
{
closing(app, args);
}
deferrals.continue_with(app, move |app| {
if app.contains(self) {
let canceled = args.is_some_and(|args| args.cancel());
self.hide_after_deferral(app, canceled, result);
}
});
}
fn hide_after_deferral(
self: Handle<Self>,
app: &mut App,
canceled: bool,
result: ContentDialogResult,
) {
let disposed = app.get(self).disposed;
let Some(showing) = app.get(self).showing.as_ref() else {
return;
};
let (route, navigator) = (showing.route, showing.navigator);
let keep_open = canceled && !disposed && route.is_active(app);
let showing = app
.get_mut(self)
.showing
.as_mut()
.expect("a showing dialog");
if keep_open {
showing.hide_in_progress = false;
return;
}
showing.result = result;
self.leave_metadata(app, navigator);
if route.is_current(app) {
navigator.pop(app, None);
} else if route.is_active(app) {
navigator.remove_route(app, route, None);
}
}
fn is_accepting_commands(self: Handle<Self>, app: &App) -> bool {
app.get(self)
.showing
.as_ref()
.is_some_and(|showing| !showing.hide_in_progress)
}
fn finish_opening(self: Handle<Self>, app: &mut App, route: AnyRoute) {
let Some(showing) = self.showing_of(app, route) else {
return;
};
showing.skip_closing_event = false;
if let Some(opened) = app.get(self).opened.clone() {
opened.call(app);
}
}
fn route_popped(self: Handle<Self>, app: &mut App, route: AnyRoute) {
let Some(showing) = self.showing_of(app, route) else {
return;
};
if showing.hide_in_progress {
return;
}
showing.hide_in_progress = true;
showing.skip_closing_event = true;
showing.result = ContentDialogResult::None;
let navigator = showing.navigator;
self.leave_metadata(app, navigator);
}
fn finish_closing(self: Handle<Self>, app: &mut App, route: AnyRoute) {
if self.showing_of(app, route).is_none() {
return;
}
let showing = app.get_mut(self).showing.take().expect("a showing dialog");
self.leave_metadata(app, showing.navigator);
let result = showing.result;
if app.get(self).disposed {
showing.completion.complete(app, result);
self.notifier_dispose(app);
app.destroy(self);
return;
}
if let Some(closed) = app.get(self).closed.clone() {
closed(app, ContentDialogClosedEventArgs { result });
}
let dialog = app.get_mut(self);
dialog.button_click_deferrals.disconnect();
dialog.button_click_deferrals = DeferralManager::new();
showing.completion.complete(app, result);
}
fn showing_of(self: Handle<Self>, app: &mut App, route: AnyRoute) -> Option<&mut Showing> {
if !app.contains(self) {
return None;
}
app.get_mut(self)
.showing
.as_mut()
.filter(|showing| showing.route == route)
}
fn leave_metadata(self: Handle<Self>, app: &mut App, navigator: Handle<NavigatorState>) {
let metadata = app.singleton::<ContentDialogMetadata>();
let open = &mut app.get_mut(metadata).open;
if open.get(&navigator.id()) == Some(&self) {
open.remove(&navigator.id());
}
}
fn notifier_dispose(self: Handle<Self>, app: &mut App) {
app.get_mut(self).notifier.dispose();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(clippy::enum_variant_names, reason = "the template's state names")]
enum ButtonsVisibilityState {
AllVisible,
NoneVisible,
PrimaryVisible,
SecondaryVisible,
CloseVisible,
PrimaryAndSecondaryVisible,
PrimaryAndCloseVisible,
SecondaryAndCloseVisible,
}
impl ButtonsVisibilityState {
fn of(has_primary: bool, has_secondary: bool, has_close: bool) -> ButtonsVisibilityState {
use ButtonsVisibilityState::*;
match (has_primary, has_secondary, has_close) {
(true, true, true) => AllVisible,
(false, false, false) => NoneVisible,
(true, false, false) => PrimaryVisible,
(false, true, false) => SecondaryVisible,
(false, false, true) => CloseVisible,
(true, true, false) => PrimaryAndSecondaryVisible,
(true, false, true) => PrimaryAndCloseVisible,
(false, true, true) => SecondaryAndCloseVisible,
}
}
fn layout(self, r: &ThemeResources) -> Option<CommandLayout> {
use ButtonsVisibilityState::*;
let spacing = GridLength::pixel(r.content_dialog_button_spacing);
let mut columns = [
GridLength::STAR,
GridLength::pixel(0.0),
GridLength::pixel(0.0),
spacing,
GridLength::STAR,
];
let (primary, secondary, close) = match self {
NoneVisible => return None,
AllVisible => {
columns[1] = spacing;
columns[2] = GridLength::STAR;
(Some(0), Some(2), Some(4))
}
PrimaryVisible => (Some(4), None, None),
SecondaryVisible => (None, Some(4), None),
CloseVisible => (None, None, Some(4)),
PrimaryAndSecondaryVisible => (Some(0), Some(4), None),
PrimaryAndCloseVisible => (Some(0), None, Some(4)),
SecondaryAndCloseVisible => (None, Some(0), Some(4)),
};
Some(CommandLayout {
columns,
primary,
secondary,
close,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct CommandLayout {
columns: [GridLength; 5],
primary: Option<usize>,
secondary: Option<usize>,
close: Option<usize>,
}
fn accented_button(
default: ContentDialogButton,
focused: Option<ContentDialogButton>,
) -> ContentDialogButton {
match focused {
Some(focused) if focused != default => ContentDialogButton::None,
_ => default,
}
}
const OPEN_SCALE_DURATION: Duration = Duration::from_millis(250);
const CLOSE_SCALE_DURATION: Duration = Duration::from_millis(167);
const OPACITY_CHANGE_DURATION: Duration = Duration::from_millis(83);
const SCALED_FACTOR: f64 = 1.05;
fn open_close_transition(status: AnimationStatus, value: f64) -> (f64, f64) {
let easing = Cubic::new(0.0, 0.0, 0.0, 1.0);
let fade = OPACITY_CHANGE_DURATION.as_secs_f64();
let progress = |elapsed: f64, duration: f64| (elapsed / duration).clamp(0.0, 1.0);
if matches!(
status,
AnimationStatus::Reverse | AnimationStatus::Dismissed
) {
let close = CLOSE_SCALE_DURATION.as_secs_f64();
let elapsed = (1.0 - value) * close;
let opacity = 1.0 - progress(elapsed, fade);
let scale = 1.0 + (SCALED_FACTOR - 1.0) * easing.transform(progress(elapsed, close));
(opacity, scale)
} else {
let open = OPEN_SCALE_DURATION.as_secs_f64();
let elapsed = value * open;
let opacity = progress(elapsed, fade);
let scale =
SCALED_FACTOR - (SCALED_FACTOR - 1.0) * easing.transform(progress(elapsed, open));
(opacity, scale)
}
}
struct ContentDialogRoute {
route: RouteData,
overlay_route: OverlayRouteData,
transition_route: TransitionRouteData,
local_history: LocalHistoryRouteData,
modal_route: ModalRouteData,
raw_dialog_route: RawDialogRouteData,
}
impl ContentDialogRoute {
fn new(app: &mut App, dialog: Handle<ContentDialog>, smoke: Color) -> Handle<Self> {
let page_builder: RoutePageBuilder = Rc::new(move |_, _, animation, _| {
ContentDialogPresenter { dialog, animation }.into_widget()
});
let mut raw_dialog_route = RawDialogRouteData::new(page_builder);
raw_dialog_route.barrier_dismissible = false;
raw_dialog_route.barrier_color = Some(smoke);
raw_dialog_route.transition_duration = OPEN_SCALE_DURATION;
raw_dialog_route.transition_builder = Some(Rc::new(|_, _, _, _, child| child));
let mut modal_route = ModalRouteData::new(app);
modal_route.traversal_edge_behavior = Some(TraversalEdgeBehavior::ClosedLoop);
let route = RouteData::new(app, None, None);
let transition_route = TransitionRouteData::new(app);
app.create(ContentDialogRoute {
route,
overlay_route: OverlayRouteData::new(),
transition_route,
local_history: LocalHistoryRouteData::new(),
modal_route,
raw_dialog_route,
})
}
}
impl Route for ContentDialogRoute {
waft_widgets::modal_route_overrides!();
}
impl OverlayRoute for ContentDialogRoute {
waft_widgets::modal_overlay_route_overrides!();
}
impl PredictiveBackRoute for ContentDialogRoute {
waft_widgets::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
}
impl TransitionRoute for ContentDialogRoute {
waft_widgets::raw_dialog_route_transition_route_overrides!();
fn reverse_transition_duration(self: Handle<Self>, _app: &App) -> Duration {
CLOSE_SCALE_DURATION
}
}
impl LocalHistoryRoute for ContentDialogRoute {
waft_widgets::local_history_route_accessors!();
}
impl ModalRoute for ContentDialogRoute {
waft_widgets::raw_dialog_route_modal_route_overrides!();
}
impl PopupRoute for ContentDialogRoute {}
impl RawDialogRouteLeaf for ContentDialogRoute {
waft_widgets::raw_dialog_route_accessors!();
fn build_modal_barrier(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let animation = TransitionRoute::animation(self, app).expect("an installed route");
let smoke = self
.raw_dialog_route_data(app)
.barrier_color
.expect("the smoke fill");
ListenableBuilder::new(Rc::new(animation), move |app, _, _| {
let (opacity, _) = open_close_transition(animation.status(app), animation.value(app));
ModalBarrier::new()
.color(smoke.with_values(Some(smoke.a * opacity), None, None, None, None))
.dismissible(false)
.into_widget()
})
.into_widget()
}
}
#[derive(Debug)]
struct ContentDialogPresenter {
dialog: Handle<ContentDialog>,
animation: AnyAnimation<f64>,
}
struct ContentDialogPresenterState {
state: StateData<ContentDialogPresenter>,
route: Option<AnyRoute>,
content_focus: Option<Handle<FocusNode>>,
button_focus: Vec<(ContentDialogButton, Handle<FocusNode>)>,
rebuild: Option<Listener>,
}
impl StatefulWidget for ContentDialogPresenter {
type State = ContentDialogPresenterState;
fn create_state(&self) -> Self::State {
ContentDialogPresenterState {
state: StateData::new(),
route: None,
content_focus: None,
button_focus: Vec::new(),
rebuild: None,
}
}
}
impl State for ContentDialogPresenterState {
type Widget = ContentDialogPresenter;
waft_widgets::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let dialog = self.widget(app).dialog;
let route = app
.get(dialog)
.showing
.as_ref()
.map(|showing| showing.route);
let rebuild = Listener::new(move |app| {
if app.contains(self) && self.mounted(app) {
self.set_state(app, |_| {});
}
});
dialog.add_listener(app, rebuild.clone());
let content_focus = FocusNode::new(app);
let button_focus: Vec<_> = [
ContentDialogButton::Primary,
ContentDialogButton::Secondary,
ContentDialogButton::Close,
]
.into_iter()
.map(|button| {
let node = FocusNode::new(app);
node.as_node().add_listener(app, rebuild.clone());
(button, node)
})
.collect();
let state = app.get_mut(self);
state.route = route;
state.content_focus = Some(content_focus);
state.button_focus = button_focus;
state.rebuild = Some(rebuild);
self.open_after_first_frame(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let dialog = self.widget(app).dialog;
let state = app.get_mut(self);
let rebuild = state.rebuild.take().expect("an initialized presenter");
let nodes: Vec<_> = state
.button_focus
.drain(..)
.map(|(_, node)| node)
.chain(state.content_focus.take())
.collect();
let route = state.route;
if app.contains(dialog) {
dialog.remove_listener(app, &rebuild);
}
for node in nodes {
node.as_node().remove_listener(app, &rebuild);
node.as_node().dispose(app);
app.destroy(node);
}
if let Some(route) = route {
after_next_frame(
app,
None,
FrameCallback::new(move |app, _| dialog.finish_closing(app, route)),
);
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let dialog = self.widget(app).dialog;
let Some(showing) = app.get(dialog).showing.as_ref() else {
return SizedBox::shrink().into_widget();
};
let (resources, direction) = (showing.resources.clone(), showing.direction);
let background = self.background_element(app, &resources);
let animation = self.widget(app).animation;
let animated = ListenableBuilder::new(Rc::new(animation), move |app, _, child| {
let status = animation.status(app);
let (opacity, scale) = open_close_transition(status, animation.value(app));
IgnorePointer::new()
.ignoring(status == AnimationStatus::Reverse)
.child(
Opacity::new(opacity).child(
Transform::scale(Some(scale), None, None)
.child(child.cloned().expect("the dialog's background element")),
),
)
.into_widget()
})
.child(background);
let layout_root = Focus::new(Center::new().child(animated))
.can_request_focus(false)
.skip_traversal(true)
.on_key_event(Rc::new(move |app, _, event| {
layout_root_key(app, dialog, event)
}));
let back_request = PopScope::new(layout_root)
.can_pop(false)
.on_pop_invoked_with_result(Rc::new(move |app, did_pop, _| {
if !did_pop {
dialog.execute_close_action(app);
}
}));
ThemeScope::with_resources(resources, Directionality::new(direction, back_request))
.into_widget()
}
}
fn layout_root_key(
app: &mut App,
dialog: Handle<ContentDialog>,
event: &KeyEvent,
) -> KeyEventResult {
if !matches!(event, KeyEvent::Down(_)) || !app.contains(dialog) {
return KeyEventResult::Ignored;
}
match event.logical_key() {
LogicalKeyboardKey::ESCAPE => {
dialog.execute_close_action(app);
KeyEventResult::Handled
}
LogicalKeyboardKey::ENTER | LogicalKeyboardKey::NUMPAD_ENTER
if dialog.invoke_default_button(app) =>
{
KeyEventResult::Handled
}
_ => KeyEventResult::Ignored,
}
}
impl ContentDialogPresenterState {
fn background_element(
self: Handle<Self>,
app: &mut App,
resources: &ThemeResources,
) -> WidgetRef {
let dialog = app.get(self.widget(app).dialog);
let full_size = dialog.full_size_desired;
let r = &resources;
let dialog_space = self.dialog_space(app, resources);
let border = ControlBorder::new(
Brush::Solid(r.content_dialog_background),
Brush::Solid(r.content_dialog_border_brush),
)
.border_thickness_ltrb(r.content_dialog_border_width)
.corner_radius(r.overlay_corner_radius[0])
.background_sizing(BackgroundSizing::InnerBorderEdge)
.child(
ClipRRect::new()
.border_radius(BorderRadius::circular(r.overlay_corner_radius[0]).into())
.child(dialog_space),
);
let shadowed = CustomPaint::new()
.painter(PopupShadow::for_dialog(resources, resources.theme))
.child(border);
let sized = IntrinsicWidth::new().child(shadowed);
let sized = if full_size {
SizedBox::new()
.height(f64::INFINITY)
.child(sized)
.into_widget()
} else {
sized.into_widget()
};
ConstrainedBox::new(
BoxConstraints::new()
.min_width(r.content_dialog_min_width)
.max_width(r.content_dialog_max_width)
.min_height(r.content_dialog_min_height)
.max_height(r.content_dialog_max_height),
)
.child(sized)
.into_widget()
}
fn dialog_space(self: Handle<Self>, app: &mut App, resources: &ThemeResources) -> WidgetRef {
let full_size = app.get(self.widget(app).dialog).full_size_desired;
let content_area = ClipRect::new().child(self.content_area(app, resources));
let fit = if full_size {
FlexFit::Tight
} else {
FlexFit::Loose
};
let mut children = vec![Flexible::new(content_area).fit(fit).into_widget()];
if let Some(command_space) = self.command_space(app, resources) {
children.push(command_space);
}
Column::new()
.main_axis_size(MainAxisSize::Min)
.cross_axis_alignment(CrossAxisAlignment::Stretch)
.children(children)
.into_widget()
}
fn content_area(self: Handle<Self>, app: &mut App, resources: &ThemeResources) -> WidgetRef {
let dialog = app.get(self.widget(app).dialog);
let r = &resources;
let foreground = r.content_dialog_foreground;
let mut children = Vec::new();
if let Some(title) = dialog.title.clone() {
children.push(
Align::new()
.alignment(AlignmentDirectional::TOP_START.into())
.child(Margin::new(
r.content_dialog_title_margin,
DefaultTextStyle::new(
control_text_style(resources, 20.0, FontWeight::W600, foreground),
title,
)
.max_lines(2)
.soft_wrap(true),
))
.into_widget(),
);
}
if let Some(content) = dialog.content.clone() {
let focus = app
.get(self)
.content_focus
.expect("an initialized presenter");
children.push(
Focus::new(DefaultTextStyle::new(
control_text_style(
resources,
r.control_content_theme_font_size,
FontWeight::NORMAL,
foreground,
),
content,
))
.focus_node(focus.as_node())
.can_request_focus(false)
.skip_traversal(true)
.into_widget(),
);
}
ControlBorder::new(
Brush::Solid(r.content_dialog_top_overlay),
Brush::Solid(r.content_dialog_separator_border_brush),
)
.border_thickness_ltrb(r.content_dialog_separator_thickness)
.padding(r.content_dialog_padding)
.child(
Column::new()
.main_axis_size(MainAxisSize::Min)
.cross_axis_alignment(CrossAxisAlignment::Stretch)
.children(children),
)
.into_widget()
}
fn command_space(
self: Handle<Self>,
app: &mut App,
resources: &ThemeResources,
) -> Option<WidgetRef> {
let dialog_handle = self.widget(app).dialog;
let dialog = app.get(dialog_handle);
let layout = ButtonsVisibilityState::of(
!dialog.primary_button_text.is_empty(),
!dialog.secondary_button_text.is_empty(),
!dialog.close_button_text.is_empty(),
)
.layout(resources)?;
let accented = accented_button(dialog.default_button, self.focused_button(app));
let dialog = app.get(dialog_handle);
let buttons = [
(
ContentDialogButton::Primary,
layout.primary,
dialog.primary_button_text.clone(),
dialog.is_primary_button_enabled,
),
(
ContentDialogButton::Secondary,
layout.secondary,
dialog.secondary_button_text.clone(),
dialog.is_secondary_button_enabled,
),
(
ContentDialogButton::Close,
layout.close,
dialog.close_button_text.clone(),
true,
),
];
let cells: Vec<WidgetRef> = buttons
.into_iter()
.filter_map(|(button, column, text, enabled)| {
let column = column?;
let style = if button == accented {
ButtonStyle::Accent
} else {
ButtonStyle::Default
};
let node = self.focus_of(app, button);
let click =
Listener::new(move |app| dialog_handle.command_button_clicked(app, button));
let button = Button::text(text, click)
.style(style)
.is_enabled(enabled)
.focus_node(node.as_node());
Some(GridCell::new(button).column(column).into_widget())
})
.collect();
let background = resources.content_dialog_background;
Some(
Grid::new()
.column_definitions(layout.columns.map(ColumnDefinition::new))
.padding(resources.content_dialog_padding)
.background(Brush::Solid(background))
.children(cells)
.into_widget(),
)
}
fn focused_button(self: Handle<Self>, app: &mut App) -> Option<ContentDialogButton> {
let buttons = app.get(self).button_focus.clone();
buttons
.into_iter()
.find(|(_, node)| node.as_node().has_focus(app))
.map(|(button, _)| button)
}
fn focus_of(self: Handle<Self>, app: &App, button: ContentDialogButton) -> Handle<FocusNode> {
app.get(self)
.button_focus
.iter()
.find(|(candidate, _)| *candidate == button)
.map(|(_, node)| *node)
.expect("a command button")
}
fn open_after_first_frame(self: Handle<Self>, app: &mut App) {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if !app.contains(self) || !self.mounted(app) {
return;
}
let dialog = self.widget(app).dialog;
let Some(route) = app.get(self).route else {
return;
};
self.set_initial_focus(app);
dialog.finish_opening(app, route);
}),
View::maybe_id_of(app, self.context(app)),
);
}
fn set_initial_focus(self: Handle<Self>, app: &mut App) {
let content = app
.get(self)
.content_focus
.expect("an initialized presenter");
let first_in_content = content
.as_node()
.traversal_descendants(app)
.into_iter()
.find(|node| node.can_request_focus(app));
if let Some(node) = first_in_content {
node.request_focus(app, None);
return;
}
let default = app.get(self.widget(app).dialog).default_button;
let candidates = std::iter::once(default).chain([
ContentDialogButton::Primary,
ContentDialogButton::Secondary,
ContentDialogButton::Close,
]);
for button in candidates {
if button == ContentDialogButton::None {
continue;
}
let node = self.focus_of(app, button).as_node();
if node.context(app).is_some() && node.can_request_focus(app) {
node.request_focus(app, None);
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_set_of_button_texts_picks_its_columns() {
let r = ThemeResources::new(Theme::Light, AccentPalette::default());
let layout = |primary, secondary, close| {
ButtonsVisibilityState::of(primary, secondary, close).layout(&r)
};
let all = layout(true, true, true).unwrap();
assert_eq!(
(all.primary, all.secondary, all.close),
(Some(0), Some(2), Some(4))
);
assert_eq!(
all.columns[1],
GridLength::pixel(r.content_dialog_button_spacing)
);
let secondary_and_close = layout(false, true, true).unwrap();
assert_eq!(
(secondary_and_close.secondary, secondary_and_close.close),
(Some(0), Some(4))
);
let primary_alone = layout(true, false, false).unwrap();
assert_eq!(primary_alone.primary, Some(4));
assert_eq!(
ButtonsVisibilityState::of(false, false, false),
ButtonsVisibilityState::NoneVisible
);
assert_eq!(layout(false, false, false), None);
}
#[test]
fn focusing_another_command_button_takes_the_accent_from_the_default() {
use ContentDialogButton::{Close, Primary};
assert_eq!(accented_button(Primary, None), Primary);
assert_eq!(accented_button(Primary, Some(Primary)), Primary);
assert_eq!(
accented_button(Primary, Some(Close)),
ContentDialogButton::None
);
assert_eq!(
accented_button(ContentDialogButton::None, Some(Close)),
ContentDialogButton::None
);
}
#[test]
fn opening_and_closing_fade_in_83_ms_and_scale_over_their_own_durations() {
let fraction = |part: Duration, whole: Duration| part.as_secs_f64() / whole.as_secs_f64();
let (opacity, scale) = open_close_transition(AnimationStatus::Forward, 0.0);
assert_eq!((opacity, scale), (0.0, SCALED_FACTOR));
let faded_in = fraction(OPACITY_CHANGE_DURATION, OPEN_SCALE_DURATION);
let (opacity, scale) = open_close_transition(AnimationStatus::Forward, faded_in);
assert!((opacity - 1.0).abs() < 1e-9 && scale > 1.0);
assert_eq!(
open_close_transition(AnimationStatus::Completed, 1.0),
(1.0, 1.0)
);
let faded_out = 1.0 - fraction(OPACITY_CHANGE_DURATION, CLOSE_SCALE_DURATION);
let (opacity, scale) = open_close_transition(AnimationStatus::Reverse, faded_out);
assert!(opacity.abs() < 1e-9 && scale > 1.0 && scale < SCALED_FACTOR);
let (_, scale) = open_close_transition(AnimationStatus::Dismissed, 0.0);
assert!((scale - SCALED_FACTOR).abs() < 1e-9);
}
}