1use super::element::{
6 ApplicationViewState, CommandBarLabelPosition, ElementHost, ElementPresentation,
7};
8use crate::{
9 Brush, ColorTransition, ColumnDefinition, CommonState, CommonStates, ControlBorder,
10 ControlStates, FluentSymbol, FocusVisual, FontIcon, Grid, GridCell, GridLength, InputDevice,
11 Margin, RowDefinition, TextBlockStyle, ThemeResources, ToolTip, ToolTipService,
12 control_text_style,
13};
14use crate::{Flyout, FlyoutPlacementMode, FlyoutShowOptions, FlyoutTarget};
15use std::{fmt, rc::Rc};
16use waft_embedder::{Color, FontWeight, TextAlign};
17use waft_foundation::{App, Listener, Ref};
18use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry, TextStyle};
19use waft_rendering::BoxConstraints;
20use waft_widgets::*;
21
22pub(crate) const APP_BAR_BUTTON_FOCUS_VISUAL_MARGIN: [f64; 4] = [-3.0; 4];
24pub(crate) const APP_BAR_BUTTON_WIDTH: f64 = 68.0;
26
27#[derive(Clone)]
29pub struct AppBarButton {
30 pub label: String,
32 pub click: Listener,
34 pub icon: Option<WidgetRef>,
36 pub label_position: CommandBarLabelPosition,
38 pub flyout: Option<Ref<Flyout>>,
40 pub is_enabled: bool,
42 pub dynamic_overflow_order: i32,
44 pub keyboard_accelerator_text_override: String,
46 pub(crate) presentation: ElementPresentation,
47 pub(crate) host: Option<ElementHost>,
48 pub key: Option<KeyRef>,
50}
51
52impl AppBarButton {
53 pub fn new(label: impl Into<String>, click: Listener) -> Self {
55 Self {
56 label: label.into(),
57 click,
58 icon: None,
59 label_position: CommandBarLabelPosition::Default,
60 flyout: None,
61 is_enabled: true,
62 dynamic_overflow_order: 0,
63 keyboard_accelerator_text_override: String::new(),
64 presentation: ElementPresentation::default(),
65 host: None,
66 key: None,
67 }
68 }
69
70 #[cfg_attr(debug_assertions, track_caller)]
72 pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> Self {
73 self.icon = Some(icon.into_widget());
74 self
75 }
76
77 pub fn label_position(mut self, position: CommandBarLabelPosition) -> Self {
79 self.label_position = position;
80 self
81 }
82
83 pub fn flyout(mut self, flyout: Ref<Flyout>) -> Self {
85 self.flyout = Some(flyout);
86 self
87 }
88
89 pub fn is_enabled(mut self, enabled: bool) -> Self {
91 self.is_enabled = enabled;
92 self
93 }
94
95 pub fn dynamic_overflow_order(mut self, order: i32) -> Self {
97 self.dynamic_overflow_order = order;
98 self
99 }
100
101 pub fn keyboard_accelerator_text_override(mut self, text: impl Into<String>) -> Self {
103 self.keyboard_accelerator_text_override = text.into();
104 self
105 }
106
107 pub fn key(mut self, key: KeyRef) -> Self {
109 self.key = Some(key);
110 self
111 }
112
113 fn on_click(&self, target: BuildContext) -> Listener {
115 let (click, flyout) = (self.click.clone(), self.flyout.clone());
116 let host = self.host.clone();
117 let in_overflow = self.presentation.use_overflow_style;
118 Listener::new(move |app| {
119 if flyout.is_none()
120 && let Some(host) = &host
121 {
122 host.executed.call(app);
123 }
124 click.call(app);
125 if let Some(flyout) = &flyout {
126 if in_overflow {
127 let options = FlyoutShowOptions {
128 placement: Some(FlyoutPlacementMode::RightEdgeAlignedTop),
129 show_mode: app.get(flyout).show_mode,
130 ..Default::default()
131 };
132 flyout.show_at_with_options(app, target, options);
133 } else {
134 flyout.show_at(app, target);
135 }
136 }
137 })
138 }
139}
140
141impl fmt::Debug for AppBarButton {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.debug_struct("AppBarButton")
144 .field("label", &self.label)
145 .field("label_position", &self.label_position)
146 .field("is_enabled", &self.is_enabled)
147 .field("dynamic_overflow_order", &self.dynamic_overflow_order)
148 .finish_non_exhaustive()
149 }
150}
151
152impl StatelessWidget for AppBarButton {
153 fn key(&self) -> Option<&KeyRef> {
154 self.key.as_ref()
155 }
156
157 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
158 let widget = self.clone();
159 FlyoutTarget::new(Builder::new(move |_app, target| {
160 let template_widget = widget.clone();
161 let mut states =
162 CommonStates::new(widget.on_click(target), move |app, context, states| {
163 let sub_menu_open = template_widget
164 .flyout
165 .as_ref()
166 .is_some_and(|flyout| flyout.is_open(app));
167 template(app, context, &template_widget, states, sub_menu_open)
168 })
169 .is_enabled(widget.is_enabled);
170 if let Some(host) = &widget.host {
171 states = states.focus_node(host.focus_node.clone());
172 }
173 let button = match widget.flyout.clone() {
174 Some(flyout) if widget.presentation.use_overflow_style => {
176 let states = states.clone();
177 ListenableBuilder::new(Rc::new(flyout), move |_, _, _| {
178 states.clone().into_widget()
179 })
180 .into_widget()
181 }
182 _ => states.into_widget(),
183 };
184 with_tool_tip(
185 button,
186 &widget.label,
187 &widget.keyboard_accelerator_text_override,
188 &widget.presentation,
189 )
190 }))
191 .into_widget()
192 }
193}
194
195pub(crate) fn with_tool_tip(
197 button: WidgetRef,
198 label: &str,
199 accelerator: &str,
200 presentation: &ElementPresentation,
201) -> WidgetRef {
202 if presentation.use_overflow_style || accelerator.is_empty() {
203 return button;
204 }
205 ToolTipService::new(button, ToolTip::text(format!("{label} ({accelerator})"))).into_widget()
206}
207
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210enum AppBarButtonCommonState {
211 Normal,
212 PointerOver,
213 Pressed,
214 Disabled,
215 OverflowNormal,
216 OverflowPointerOver,
217 OverflowPressed,
218 OverflowSubMenuOpened,
219}
220
221impl AppBarButtonCommonState {
222 fn of(presentation: &ElementPresentation, states: ControlStates, sub_menu_open: bool) -> Self {
224 let base = match states.common {
225 CommonState::Normal => Self::Normal,
226 CommonState::PointerOver => Self::PointerOver,
227 CommonState::Pressed => Self::Pressed,
228 CommonState::Disabled => Self::Disabled,
229 };
230 if !(presentation.use_overflow_style && presentation.with_icons) {
231 return base;
232 }
233 if sub_menu_open {
234 Self::OverflowSubMenuOpened
235 } else {
236 match base {
237 Self::Pressed => Self::OverflowPressed,
238 Self::PointerOver => Self::OverflowPointerOver,
239 Self::Disabled => Self::Disabled,
240 _ => Self::OverflowNormal,
241 }
242 }
243 }
244}
245
246#[derive(Clone, Copy, Debug)]
248struct AppBarButtonBrushes {
249 background: Color,
250 border: Color,
251 foreground: Color,
252 chevron: Color,
253 accelerator: Color,
254}
255
256fn brushes(r: &ThemeResources, state: AppBarButtonCommonState) -> AppBarButtonBrushes {
257 use AppBarButtonCommonState::*;
258 let set = |background, border, foreground, chevron, accelerator| AppBarButtonBrushes {
259 background,
260 border,
261 foreground,
262 chevron,
263 accelerator,
264 };
265 match state {
266 Normal | OverflowNormal => set(
268 r.app_bar_button_background,
269 r.app_bar_button_border_brush,
270 r.app_bar_button_foreground,
271 r.app_bar_button_sub_item_chevron_foreground,
272 r.app_bar_button_keyboard_accelerator_text_foreground,
273 ),
274 PointerOver | OverflowPointerOver => set(
275 r.app_bar_button_background_pointer_over,
276 r.app_bar_button_border_brush_pointer_over,
277 r.app_bar_button_foreground_pointer_over,
278 r.app_bar_button_sub_item_chevron_foreground_pointer_over,
279 r.app_bar_button_keyboard_accelerator_text_foreground_pointer_over,
280 ),
281 Pressed | OverflowPressed => set(
282 r.app_bar_button_background_pressed,
283 r.app_bar_button_border_brush_pressed,
284 r.app_bar_button_foreground_pressed,
285 r.app_bar_button_sub_item_chevron_foreground_pressed,
286 r.app_bar_button_keyboard_accelerator_text_foreground_pressed,
287 ),
288 Disabled => set(
289 r.app_bar_button_background_disabled,
290 r.app_bar_button_border_brush_disabled,
291 r.app_bar_button_foreground_disabled,
292 r.app_bar_button_sub_item_chevron_foreground_disabled,
293 r.app_bar_button_keyboard_accelerator_text_foreground_disabled,
294 ),
295 OverflowSubMenuOpened => set(
296 r.app_bar_button_background_sub_menu_opened,
297 r.app_bar_button_border_brush_sub_menu_opened,
298 r.app_bar_button_foreground_sub_menu_opened,
299 r.app_bar_button_sub_item_chevron_foreground_sub_menu_opened,
300 r.app_bar_button_keyboard_accelerator_text_foreground_sub_menu_opened,
301 ),
302 }
303}
304
305fn template(
307 app: &mut App,
308 context: BuildContext,
309 widget: &AppBarButton,
310 states: ControlStates,
311 sub_menu_open: bool,
312) -> WidgetRef {
313 let r = ThemeResources::of(app, context);
314 let presentation = widget.presentation;
315 let view = ApplicationViewState::of(&presentation, widget.label_position);
316 let common = AppBarButtonCommonState::of(&presentation, states, sub_menu_open);
317 let brushes = brushes(&r, common);
318 let overflow_common = matches!(
319 common,
320 AppBarButtonCommonState::OverflowNormal
321 | AppBarButtonCommonState::OverflowPointerOver
322 | AppBarButtonCommonState::OverflowPressed
323 | AppBarButtonCommonState::OverflowSubMenuOpened
324 );
325 let touch = presentation.input_mode == InputDevice::Touch;
326 let label_style =
327 |size: f64, color: Color| control_text_style(&r, size, FontWeight::NORMAL, color);
328 let mut cells = Vec::new();
329
330 if !matches!(
332 view,
333 ApplicationViewState::Overflow | ApplicationViewState::OverflowWithToggleButtons
334 ) {
335 let icon = widget.icon.clone().map(|icon| {
336 DefaultTextStyle::new(
337 label_style(r.control_content_theme_font_size, brushes.foreground),
338 icon,
339 )
340 .into_widget()
341 });
342 cells.push(GridCell::new(content_viewbox(&r, view, icon, false)).into_widget());
343 }
344 match view {
346 ApplicationViewState::FullSize => cells.push(
347 GridCell::new(Margin::new(
348 r.app_bar_button_text_label_margin,
349 Text::new(widget.label.clone())
350 .style(label_style(
351 r.app_bar_button_label_font_size,
352 brushes.foreground,
353 ))
354 .text_align(TextAlign::Center),
355 ))
356 .row(1)
357 .into_widget(),
358 ),
359 ApplicationViewState::LabelOnRight => cells.push(
360 GridCell::new(Margin::new(
361 r.app_bar_button_text_label_on_right_margin,
362 Text::new(widget.label.clone())
363 .style(label_style(
364 r.app_bar_button_label_font_size,
365 brushes.foreground,
366 ))
367 .text_align(TextAlign::Left),
368 ))
369 .column(1)
370 .into_widget(),
371 ),
372 _ => {}
373 }
374 if view.is_overflow() {
376 let margin = match view {
377 ApplicationViewState::Overflow => [12.0, 0.0, 12.0, 0.0],
378 ApplicationViewState::OverflowWithToggleButtonsAndMenuIcons => [76.0, 0.0, 12.0, 0.0],
379 _ => [38.0, 0.0, 12.0, 0.0],
380 };
381 let padding = if touch {
382 r.app_bar_button_overflow_text_touch_margin
383 } else {
384 r.app_bar_button_overflow_text_label_padding
385 };
386 cells.push(
387 GridCell::new(overflow_text_label(
388 &widget.label,
389 label_style(r.control_content_theme_font_size, brushes.foreground),
390 margin,
391 padding,
392 ))
393 .into_widget(),
394 );
395 }
396 if let Some(cell) = keyboard_accelerator_text_label(
398 &r,
399 &presentation,
400 &widget.keyboard_accelerator_text_override,
401 brushes.accelerator,
402 ) {
403 cells.push(GridCell::new(cell).column(1).into_widget());
404 }
405 if widget.flyout.is_some() && !presentation.in_command_bar {
407 let chevron = if overflow_common {
408 Margin::new(
410 r.app_bar_button_secondary_sub_item_chevron_margin,
411 Align::new()
412 .alignment(AlignmentGeometry::CENTER)
413 .height_factor(1.0)
414 .child(
415 FontIcon::symbol(FluentSymbol::ChevronRight)
416 .font_size(r.app_bar_button_secondary_sub_item_chevron_font_size)
417 .mirrored_when_right_to_left(true)
418 .foreground(r.app_bar_button_sub_item_chevron_foreground),
419 ),
420 )
421 } else {
422 Margin::new(
424 if view == ApplicationViewState::LabelOnRight {
425 r.app_bar_button_sub_item_chevron_label_on_right_margin
426 } else {
427 r.app_bar_button_sub_item_chevron_margin
428 },
429 Align::new()
430 .alignment(AlignmentGeometry::TOP_CENTER)
431 .height_factor(1.0)
432 .child(
433 FontIcon::symbol(FluentSymbol::ChevronRight)
434 .font_size(r.app_bar_button_sub_item_chevron_font_size)
435 .mirrored_when_right_to_left(true)
436 .foreground(brushes.chevron),
437 ),
438 )
439 };
440 cells.push(GridCell::new(chevron).column(2).into_widget());
441 }
442
443 let content_root =
444 ConstrainedBox::new(BoxConstraints::new().min_height(content_root_min_height(&r, view)))
445 .child(
446 Grid::new()
447 .column_definitions([
448 ColumnDefinition::new(GridLength::STAR),
449 ColumnDefinition::new(GridLength::AUTO),
450 ColumnDefinition::new(GridLength::AUTO),
451 ])
452 .row_definitions([
453 RowDefinition::new(GridLength::AUTO),
454 RowDefinition::new(GridLength::AUTO),
455 ])
456 .children(cells),
457 );
458 let inner_border = inner_border(
459 &r,
460 Brush::Solid(brushes.background),
461 Brush::Solid(brushes.border),
462 0.0,
463 crate::BackgroundSizing::InnerBorderEdge,
464 states.focused,
465 );
466 root(
467 view,
468 Margin::new(inner_border_margin(&r, view), inner_border),
469 content_root.into_widget(),
470 )
471}
472
473pub(crate) fn inner_border_margin(r: &ThemeResources, view: ApplicationViewState) -> [f64; 4] {
475 match view {
476 ApplicationViewState::Compact => r.app_bar_button_inner_border_compact_margin,
477 view if view.is_overflow() => r.app_bar_button_inner_border_overflow_margin,
478 _ => r.app_bar_button_inner_border_margin,
479 }
480}
481
482pub(crate) fn content_root_min_height(r: &ThemeResources, view: ApplicationViewState) -> f64 {
484 match view {
485 ApplicationViewState::LabelOnRight | ApplicationViewState::LabelCollapsed => {
486 r.app_bar_theme_compact_height
487 }
488 view if view.is_overflow() => 0.0,
489 _ => r.app_bar_theme_min_height,
490 }
491}
492
493pub(crate) fn inner_border(
495 r: &ThemeResources,
496 background: Brush,
497 border: Brush,
498 border_thickness: f64,
499 background_sizing: crate::BackgroundSizing,
500 focused: bool,
501) -> WidgetRef {
502 let corner_radius = r.control_corner_radius;
503 let background_color = background.representative_color();
504 let presenter = ColorTransition::new(
505 background_color,
506 r.control_faster_animation_duration,
507 move |_app, background| {
508 ControlBorder::new(Brush::Solid(background), border)
509 .border_thickness(border_thickness)
510 .corner_radius_corners(corner_radius)
511 .background_sizing(background_sizing)
512 .into_widget()
513 },
514 );
515 FocusVisual::new(presenter, r.theme)
516 .visible(focused)
517 .margin(APP_BAR_BUTTON_FOCUS_VISUAL_MARGIN)
518 .corner_radius(corner_radius[0])
519 .into_widget()
520}
521
522#[cfg_attr(debug_assertions, track_caller)]
524pub(crate) fn root(
525 view: ApplicationViewState,
526 inner_border: Margin,
527 content_root: WidgetRef,
528) -> WidgetRef {
529 let root = Grid::new().children([inner_border.into_widget(), content_root]);
530 if view == ApplicationViewState::LabelOnRight || view.is_overflow() {
531 root.into_widget()
532 } else {
533 SizedBox::new()
534 .width(APP_BAR_BUTTON_WIDTH)
535 .child(root)
536 .into_widget()
537 }
538}
539
540pub(crate) fn content_viewbox(
542 r: &ThemeResources,
543 view: ApplicationViewState,
544 icon: Option<WidgetRef>,
545 toggle: bool,
546) -> WidgetRef {
547 let scaled = |icon: Option<WidgetRef>| match icon {
548 Some(icon) => FittedBox::new().child(icon).into_widget(),
549 None => SizedBox::shrink().into_widget(),
550 };
551 match view {
552 ApplicationViewState::OverflowWithMenuIcons
553 | ApplicationViewState::OverflowWithToggleButtonsAndMenuIcons => {
554 let margin = if view == ApplicationViewState::OverflowWithMenuIcons && !toggle {
555 [12.0, 0.0, 12.0, 0.0]
556 } else {
557 [38.0, 0.0, 12.0, 0.0]
558 };
559 let square = if toggle {
560 ConstrainedBox::new(BoxConstraints::new().max_width(16.0).max_height(16.0))
561 .child(scaled(icon))
562 .into_widget()
563 } else {
564 SizedBox::new()
565 .width(16.0)
566 .height(16.0)
567 .child(scaled(icon))
568 .into_widget()
569 };
570 Margin::new(
571 margin,
572 Align::new()
573 .alignment(AlignmentGeometry::CENTER_LEFT)
574 .height_factor(1.0)
575 .child(square),
576 )
577 .into_widget()
578 }
579 _ => {
580 let margin = if view == ApplicationViewState::LabelOnRight {
581 r.app_bar_button_content_viewbox_margin
582 } else {
583 r.app_bar_button_content_viewbox_collapsed_margin
584 };
585 Margin::new(
586 margin,
587 SizedBox::new()
588 .height(r.app_bar_button_content_height)
589 .child(scaled(icon)),
590 )
591 .into_widget()
592 }
593 }
594}
595
596pub(crate) fn overflow_text_label(
598 label: &str,
599 style: TextStyle,
600 margin: [f64; 4],
601 padding: [f64; 4],
602) -> WidgetRef {
603 let [left, top, right, bottom] = padding;
604 Margin::new(
605 margin,
606 Align::new()
607 .alignment(AlignmentGeometry::CENTER_LEFT)
608 .height_factor(1.0)
609 .child(
610 Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom)).child(
611 Text::new(label.to_string())
612 .style(style)
613 .max_lines(1)
614 .soft_wrap(false)
615 .text_align(TextAlign::Left),
616 ),
617 ),
618 )
619 .into_widget()
620}
621
622pub(crate) fn keyboard_accelerator_text_label(
624 r: &ThemeResources,
625 presentation: &ElementPresentation,
626 text: &str,
627 color: Color,
628) -> Option<WidgetRef> {
629 if !(presentation.with_keyboard_accelerator_text && presentation.use_overflow_style) {
630 return None;
631 }
632 Some(
633 Margin::new(
634 [24.0, 0.0, 12.0, 0.0],
635 Align::new()
636 .alignment(AlignmentGeometry::CENTER_RIGHT)
637 .height_factor(1.0)
638 .width_factor(1.0)
639 .child(
640 ConstrainedBox::new(
641 BoxConstraints::new()
642 .min_width(presentation.keyboard_accelerator_text_min_width),
643 )
644 .child(
645 Text::new(text.to_string())
646 .style(TextBlockStyle::Caption.text_style(r, color))
647 .max_lines(1)
648 .soft_wrap(false),
649 ),
650 ),
651 )
652 .into_widget(),
653 )
654}