1use waft_foundation::{App, DiagnosticsProperty};
4use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
5
6use crate::button_style::ButtonStyle;
7use crate::theme::Theme;
8
9#[derive(Clone, Debug, Default, PartialEq)]
30pub struct TextButtonThemeData {
31 pub style: Option<ButtonStyle>,
39}
40
41impl TextButtonThemeData {
42 pub fn new() -> TextButtonThemeData {
46 TextButtonThemeData::default()
47 }
48
49 pub fn style(mut self, style: ButtonStyle) -> TextButtonThemeData {
51 self.style = Some(style);
52 self
53 }
54
55 pub fn lerp(
57 a: Option<&TextButtonThemeData>,
58 b: Option<&TextButtonThemeData>,
59 t: f64,
60 ) -> Option<TextButtonThemeData> {
61 match (a, b) {
62 (None, None) => return None,
63 (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
64 _ => {}
65 }
66 Some(TextButtonThemeData {
67 style: ButtonStyle::lerp(
68 a.and_then(|a| a.style.as_ref()),
69 b.and_then(|b| b.style.as_ref()),
70 t,
71 ),
72 })
73 }
74}
75
76#[derive(Debug)]
88pub struct TextButtonTheme {
89 pub key: Option<KeyRef>,
90 pub data: TextButtonThemeData,
92 pub child: WidgetRef,
93}
94
95impl TextButtonTheme {
96 #[cfg_attr(debug_assertions, track_caller)]
98 pub fn new<K>(data: TextButtonThemeData, child: impl IntoWidget<K>) -> TextButtonTheme {
99 TextButtonTheme {
100 key: None,
101 data,
102 child: child.into_widget(),
103 }
104 }
105
106 pub fn key(mut self, key: KeyRef) -> TextButtonTheme {
108 self.key = Some(key);
109 self
110 }
111
112 pub fn of(app: &mut App, context: BuildContext) -> TextButtonThemeData {
124 match context.depend_on_inherited_widget_of_exact_type::<TextButtonTheme>(app) {
125 Some(button_theme) => button_theme.data.clone(),
126 None => Theme::of(app, context).text_button_theme.clone(),
127 }
128 }
129}
130
131impl InheritedTheme for TextButtonTheme {
132 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
133 TextButtonTheme::new(self.data.clone(), child).into_widget()
134 }
135}
136
137impl InheritedWidget for TextButtonTheme {
138 fn key(&self) -> Option<&KeyRef> {
139 self.key.as_ref()
140 }
141
142 fn child(&self) -> &WidgetRef {
143 &self.child
144 }
145
146 fn update_should_notify(&self, old_widget: &TextButtonTheme) -> bool {
147 self.data != old_widget.data
148 }
149
150 fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
151 Some(self)
152 }
153}
154
155impl waft_foundation::Diagnosticable for TextButtonThemeData {
156 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
157 properties.add(
158 DiagnosticsProperty::<crate::button_style::ButtonStyle>::new(
159 "style",
160 self.style.clone(),
161 )
162 .default_value(None),
163 );
164 }
165}
166
167impl std::fmt::Display for TextButtonThemeData {
168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169 f.write_str(&waft_foundation::Diagnosticable::to_string(self))
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 #![allow(deprecated)]
176 use waft_widgets::testing::assert_f32_equals;
177
178 use std::time::Duration;
179
180 use waft_embedder::{Color, FontWeight, Radius, Size};
181 use waft_foundation::Listener;
182 use waft_painting::{
183 AlignmentGeometry, BorderRadius, BorderSide, EdgeInsetsGeometry, RoundedRectangleBorder,
184 StadiumBorder, TextStyle,
185 };
186 use waft_services::{MouseCursorRef, SystemMouseCursors};
187 use waft_widgets::{
188 Align, Builder, Center, GlobalKey, Icon, KeyedSubtree, Text, WidgetState,
189 WidgetStateProperty, WidgetStates,
190 };
191
192 use waft_widgets::testing::{WidgetTester, find, test_widgets};
193
194 use super::*;
195 use crate::button_style::{ButtonLayerBuilder, ButtonStyle};
196 use crate::button_style_button::IconAlignment;
197 use crate::color_scheme::ColorScheme;
198 use crate::colors::Colors;
199 use crate::icons::Icons;
200 use crate::ink_well::InkWell;
201 use crate::material::Material;
202 use crate::test_support::material_app;
203 use crate::text_button::TextButton;
204 use crate::theme_data::{MaterialTapTargetSize, ThemeData};
205
206 fn pressed() -> Option<Listener> {
207 Some(Listener::new(|_app| {}))
208 }
209
210 fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
212 let element = *find::by_type::<Material>()
213 .evaluate(tester)
214 .last()
215 .expect("the button's Material");
216 tester.widget(element, read)
217 }
218
219 fn ink_well<R>(tester: &WidgetTester, read: impl FnOnce(&InkWell) -> R) -> R {
220 let element = *find::by_type::<InkWell>()
221 .evaluate(tester)
222 .last()
223 .expect("an InkWell");
224 tester.widget(element, read)
225 }
226
227 fn align_of_label(tester: &WidgetTester) -> AlignmentGeometry {
228 let align =
229 tester.element(find::ancestor(find::text("button"), find::by_type::<Align>()).first());
230 tester.widget(align, |align: &Align| align.alignment)
231 }
232
233 #[test]
234 fn text_button_theme_lerp_special_cases() {
235 assert_eq!(TextButtonThemeData::lerp(None, None, 0.0), None);
236 let data = TextButtonThemeData::new();
237 assert_eq!(
239 TextButtonThemeData::lerp(Some(&data), Some(&data), 0.5),
240 Some(data.clone())
241 );
242 }
243
244 fn no_theme_case(tester: &mut WidgetTester, use_material3: bool) {
245 let color_scheme = ColorScheme::light();
246 let theme = ThemeData::from(color_scheme.clone())
247 .use_material3(use_material3)
248 .build(&tester.cell.borrow());
249 tester.pump_widget(material_app(
250 theme,
251 Center::new()
252 .child(TextButton::new(pressed(), Some(Text::new("button"))))
253 .into_widget(),
254 ));
255
256 material(tester, |material| {
257 assert_eq!(material.animation_duration, Duration::from_millis(200));
258 assert!(material.border_radius.is_none());
259 assert_eq!(material.color, Some(Colors::TRANSPARENT));
260 assert_eq!(material.elevation, 0.0);
261 assert_eq!(
262 material.shadow_color,
263 Some(if use_material3 {
264 Colors::TRANSPARENT
265 } else {
266 Colors::BLACK
267 })
268 );
269 let shape = material.shape.as_deref().expect("a shape");
270 if use_material3 {
271 assert!(shape.eq_shape(&StadiumBorder::new(BorderSide::NONE)));
272 } else {
273 assert!(shape.eq_shape(&RoundedRectangleBorder::new(
274 BorderSide::NONE,
275 BorderRadius::all(Radius::circular(4.0)).into(),
276 )));
277 }
278 let text_style = material.text_style.as_ref().expect("a text style");
279 assert_eq!(
280 text_style.color.as_deref().copied(),
281 Some(color_scheme.primary())
282 );
283 assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
284 assert_eq!(text_style.font_size, Some(14.0));
285 assert_eq!(text_style.font_weight, Some(FontWeight::W500));
286 });
287 assert!(align_of_label(tester) == AlignmentGeometry::CENTER);
288 }
289
290 #[test]
291 fn material_3_without_a_text_button_theme_the_defaults_apply() {
292 test_widgets(|tester| no_theme_case(tester, true));
293 }
294
295 #[test]
296 fn material_2_without_a_text_button_theme_the_defaults_apply() {
297 test_widgets(|tester| no_theme_case(tester, false));
298 }
299
300 mod style_overrides {
302 use super::*;
303
304 const FOREGROUND_COLOR: Color = Color::new(0xff000001);
305 const BACKGROUND_COLOR: Color = Color::new(0xff000002);
306 const DISABLED_COLOR: Color = Color::new(0xff000003);
307 const SHADOW_COLOR: Color = Color::new(0xff000004);
308 const ELEVATION: f64 = 3.0;
309
310 fn style_side() -> BorderSide {
311 BorderSide {
312 color: Colors::GREEN.primary(),
313 width: 2.0,
314 ..BorderSide::default()
315 }
316 }
317
318 fn shape() -> RoundedRectangleBorder {
319 RoundedRectangleBorder::new(
320 style_side(),
321 BorderRadius::all(Radius::circular(2.0)).into(),
322 )
323 }
324
325 thread_local! {
326 static BACKGROUND_KEY: GlobalKey = GlobalKey::new();
327 static FOREGROUND_KEY: GlobalKey = GlobalKey::new();
328 }
329
330 fn background_key() -> GlobalKey {
331 BACKGROUND_KEY.with(GlobalKey::clone)
332 }
333
334 fn foreground_key() -> GlobalKey {
335 FOREGROUND_KEY.with(GlobalKey::clone)
336 }
337
338 fn background_builder(
339 _app: &mut App,
340 _context: BuildContext,
341 _states: &WidgetStates,
342 child: Option<WidgetRef>,
343 ) -> WidgetRef {
344 KeyedSubtree::new(child.expect("the button's child"))
345 .key(background_key().into())
346 .into_widget()
347 }
348
349 fn foreground_builder(
350 _app: &mut App,
351 _context: BuildContext,
352 _states: &WidgetStates,
353 child: Option<WidgetRef>,
354 ) -> WidgetRef {
355 KeyedSubtree::new(child.expect("the button's child"))
356 .key(foreground_key().into())
357 .into_widget()
358 }
359
360 fn style() -> ButtonStyle {
361 TextButton::style_from()
362 .foreground_color(FOREGROUND_COLOR)
363 .disabled_foreground_color(DISABLED_COLOR)
364 .background_color(BACKGROUND_COLOR)
365 .disabled_background_color(DISABLED_COLOR)
366 .shadow_color(SHADOW_COLOR)
367 .elevation(ELEVATION)
368 .text_style(TextStyle::new().font_size(12.0))
369 .padding(EdgeInsetsGeometry::all(3.0))
370 .minimum_size(Size::new(200.0, 200.0))
371 .side(style_side())
372 .shape(shape())
373 .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
374 .disabled_mouse_cursor(SystemMouseCursors::GRAB.into())
375 .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
376 .animation_duration(Duration::from_millis(25))
377 .enable_feedback(false)
378 .alignment(AlignmentGeometry::CENTER_LEFT)
379 .background_builder(ButtonLayerBuilder::function(background_builder))
380 .foreground_builder(ButtonLayerBuilder::function(foreground_builder))
381 .build()
382 }
383
384 fn build_frame(
385 tester: &WidgetTester,
386 button_style: Option<ButtonStyle>,
387 theme_style: Option<ButtonStyle>,
388 overall_style: Option<ButtonStyle>,
389 ) -> WidgetRef {
390 let child = Builder::new(move |_app, _context| {
391 let mut button = TextButton::new(pressed(), Some(Text::new("button")));
392 if let Some(button_style) = &button_style {
393 button = button.style(button_style.clone());
394 }
395 button.into_widget()
396 });
397 let mut overall = TextButtonThemeData::new();
398 if let Some(overall_style) = overall_style {
399 overall = overall.style(overall_style);
400 }
401 let theme = ThemeData::from(ColorScheme::light())
402 .build(&tester.cell.borrow())
403 .copy_with()
404 .text_button_theme(overall)
405 .build();
406 let body = match theme_style {
409 None => child.into_widget(),
410 Some(theme_style) => {
411 TextButtonTheme::new(TextButtonThemeData::new().style(theme_style), child)
412 .into_widget()
413 }
414 };
415 material_app(
416 theme,
417 Material::new()
418 .child(Center::new().child(body))
419 .into_widget(),
420 )
421 }
422
423 fn check_button(tester: &WidgetTester) {
424 let enabled = WidgetStates::new();
425 let disabled: WidgetStates = [WidgetState::Disabled].into_iter().collect();
426 let hovered: WidgetStates = [WidgetState::Hovered].into_iter().collect();
427 let focused: WidgetStates = [WidgetState::Focused].into_iter().collect();
428 material(tester, |material| {
429 let text_style = material.text_style.as_ref().expect("a text style");
430 assert_eq!(text_style.color.as_deref().copied(), Some(FOREGROUND_COLOR));
431 assert_eq!(text_style.font_size, Some(12.0));
432 assert_eq!(material.color, Some(BACKGROUND_COLOR));
433 assert_eq!(material.shadow_color, Some(SHADOW_COLOR));
434 assert_eq!(material.elevation, ELEVATION);
435 assert!(material.border_radius.is_none());
436 assert!(
437 material
438 .shape
439 .as_deref()
440 .expect("a shape")
441 .eq_shape(&shape())
442 );
443 assert_eq!(material.animation_duration, Duration::from_millis(25));
444 });
445 ink_well(tester, |ink_well| {
446 let mouse_cursor = ink_well
447 .ink_response
448 .mouse_cursor
449 .clone()
450 .expect("a mouse cursor");
451 let resolve = |states: &WidgetStates| {
452 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states)
453 };
454 assert!(resolve(&enabled) == MouseCursorRef::from(SystemMouseCursors::TEXT));
455 assert!(resolve(&disabled) == MouseCursorRef::from(SystemMouseCursors::GRAB));
456 let overlay_color = ink_well
457 .ink_response
458 .overlay_color
459 .clone()
460 .expect("an overlay color");
461 assert_eq!(
462 overlay_color.resolve(&hovered),
463 Some(FOREGROUND_COLOR.with_opacity(0.08))
464 );
465 assert_eq!(
466 overlay_color.resolve(&focused),
467 Some(FOREGROUND_COLOR.with_opacity(0.1))
468 );
469 assert!(!ink_well.ink_response.enable_feedback);
470 });
471 let button = *find::by_type::<TextButton>()
472 .evaluate(tester)
473 .first()
474 .expect("an TextButton");
475 let size = tester.get_size(button);
476 assert_eq!(size, Size::new(200.0, 200.0));
477 assert!(align_of_label(tester) == AlignmentGeometry::CENTER_LEFT);
478 let is_below = |key: GlobalKey, ancestor: waft_widgets::AnyElement| {
479 let keyed = key
480 .current_context(&tester.cell.borrow_mut())
481 .expect("the keyed subtree is mounted");
482 tester.ancestors(keyed).contains(&ancestor)
483 };
484 let material = *find::by_type::<Material>()
485 .evaluate(tester)
486 .last()
487 .expect("a Material");
488 let ink_well = *find::by_type::<InkWell>()
489 .evaluate(tester)
490 .last()
491 .expect("an InkWell");
492 assert!(is_below(background_key(), material));
493 assert!(is_below(foreground_key(), ink_well));
494 }
495
496 #[derive(Clone, Copy)]
499 enum Given {
500 Null,
501 Empty,
502 Style,
503 }
504
505 impl Given {
506 fn style(self) -> Option<ButtonStyle> {
507 match self {
508 Given::Null => None,
509 Given::Empty => Some(ButtonStyle::new()),
510 Given::Style => Some(style()),
511 }
512 }
513 }
514
515 fn case(button_style: Given, theme_style: Given, overall_style: Given) {
516 test_widgets(|tester| {
517 let frame = build_frame(
518 tester,
519 button_style.style(),
520 theme_style.style(),
521 overall_style.style(),
522 );
523 tester.pump_widget(frame);
524 tester.pump_and_settle(); check_button(tester);
526 });
527 }
528
529 #[test]
530 fn the_button_style_overrides_the_defaults() {
531 case(Given::Style, Given::Null, Given::Null);
532 }
533
534 #[test]
535 fn the_button_theme_style_overrides_the_defaults() {
536 case(Given::Null, Given::Style, Given::Null);
537 }
538
539 #[test]
540 fn the_overall_themes_button_theme_style_overrides_the_defaults() {
541 case(Given::Null, Given::Null, Given::Style);
542 }
543
544 #[test]
547 fn the_button_style_overrides_the_defaults_over_empty_theme_and_overall_styles() {
548 case(Given::Style, Given::Empty, Given::Empty);
549 }
550
551 #[test]
552 fn the_button_theme_style_overrides_the_defaults_over_empty_button_and_overall_styles() {
553 case(Given::Empty, Given::Style, Given::Empty);
554 }
555
556 #[test]
557 fn the_overall_theme_style_overrides_the_defaults_with_no_theme_and_an_empty_button_style()
558 {
559 case(Given::Empty, Given::Null, Given::Style);
560 }
561 }
562
563 fn shadow_color_case(tester: &mut WidgetTester, use_material3: bool) {
564 let color_scheme = ColorScheme::light();
565 let shadow_color = Color::new(0xff000001);
566 let overridden_color = Color::new(0xff000002);
567
568 let frame = |tester: &WidgetTester,
569 overall_shadow_color: Option<Color>,
570 theme_shadow_color: Option<Color>,
571 button_shadow_color: Option<Color>| {
572 let theme = if use_material3 {
573 let mut scheme = color_scheme.copy_with();
574 if let Some(overall_shadow_color) = overall_shadow_color {
575 scheme = scheme.with_shadow(overall_shadow_color);
576 }
577 ThemeData::from(scheme).build(&tester.cell.borrow())
578 } else {
579 let theme = ThemeData::from(color_scheme.clone())
580 .use_material3(false)
581 .build(&tester.cell.borrow());
582 match overall_shadow_color {
583 Some(overall_shadow_color) => {
584 theme.copy_with().shadow_color(overall_shadow_color).build()
585 }
586 None => theme,
587 }
588 };
589 let style_with = |color: Option<Color>| {
590 let mut style = TextButton::style_from();
591 if let Some(color) = color {
592 style = style.shadow_color(color);
593 }
594 style.build()
595 };
596 let button_style = style_with(button_shadow_color);
597 material_app(
598 theme,
599 Material::new()
600 .child(Center::new().child(TextButtonTheme::new(
601 TextButtonThemeData::new().style(style_with(theme_shadow_color)),
602 Builder::new(move |_app, _context| {
603 TextButton::new(pressed(), Some(Text::new("button")))
604 .style(button_style.clone())
605 .into_widget()
606 }),
607 )))
608 .into_widget(),
609 )
610 };
611 let mut pump = |overall: Option<Color>, theme: Option<Color>, button: Option<Color>| {
612 let frame = frame(tester, overall, theme, button);
613 tester.pump_widget(frame);
614 tester.pump_and_settle(); material(tester, |material| material.shadow_color)
616 };
617
618 assert_eq!(
619 pump(None, None, None),
620 Some(if use_material3 {
621 Colors::TRANSPARENT
622 } else {
623 Colors::BLACK
624 })
625 );
626 assert_eq!(
627 pump(Some(shadow_color), None, None),
628 Some(if use_material3 {
629 Colors::TRANSPARENT
630 } else {
631 shadow_color
632 })
633 );
634 assert_eq!(pump(None, Some(shadow_color), None), Some(shadow_color));
635 assert_eq!(pump(None, None, Some(shadow_color)), Some(shadow_color));
636 assert_eq!(
637 pump(Some(overridden_color), Some(shadow_color), None),
638 Some(shadow_color)
639 );
640 assert_eq!(
641 pump(None, Some(overridden_color), Some(shadow_color)),
642 Some(shadow_color)
643 );
644 }
645
646 #[test]
647 fn material_3_the_shadow_color_comes_from_the_button_then_its_theme_and_never_the_scheme() {
648 test_widgets(|tester| shadow_color_case(tester, true));
649 }
650
651 #[test]
652 fn material_2_the_shadow_color_comes_from_the_button_then_its_theme_then_the_theme() {
653 test_widgets(|tester| shadow_color_case(tester, false));
654 }
655
656 #[test]
657 fn the_icon_follows_the_themes_style_icon_alignment() {
658 test_widgets(|tester| {
659 let mut case = |icon_alignment: Option<IconAlignment>| {
660 let mut style = ButtonStyle::new();
661 if let Some(icon_alignment) = icon_alignment {
662 style = style.icon_alignment(icon_alignment);
663 }
664 let theme = ThemeData::builder()
665 .text_button_theme(TextButtonThemeData::new().style(style))
666 .build(&tester.cell.borrow());
667 tester.pump_widget(material_app(
668 theme,
669 Center::new()
670 .child(
671 TextButton::icon(pressed(), Text::new("button"))
672 .icon(Icon::new(Some(Icons::add()))),
673 )
674 .into_widget(),
675 ));
676 tester.pump_and_settle();
677 let button = *find::by_type::<Material>()
678 .evaluate(tester)
679 .last()
680 .expect("a Material");
681 let icon = *find::by_type::<Icon>()
682 .evaluate(tester)
683 .first()
684 .expect("an Icon");
685 (tester.get_rect(button), tester.get_rect(icon))
686 };
687
688 let (button, icon) = case(None);
689 assert_eq!(button.left, icon.left - 12.0);
690
691 let (button, icon) = case(Some(IconAlignment::End));
692 assert_f32_equals(button.right, icon.right + 16.0);
693 });
694 }
695
696 #[test]
697 fn the_icon_takes_the_themes_foreground_color_over_the_default_icon_color() {
698 test_widgets(|tester| {
700 let foreground_color = Color::new(0xFFFFA500);
701 let theme = ThemeData::builder()
702 .text_button_theme(
703 TextButtonThemeData::new().style(
704 TextButton::style_from()
705 .foreground_color(foreground_color)
706 .build(),
707 ),
708 )
709 .build(&tester.cell.borrow());
710 tester.pump_widget(material_app(
711 theme,
712 Material::new()
713 .child(
714 Center::new().child(
715 TextButton::icon(pressed(), Text::new("Button"))
716 .icon(Icon::new(Some(Icons::add()))),
717 ),
718 )
719 .into_widget(),
720 ));
721 assert_eq!(
722 tester.icon_style().color.as_deref().copied(),
723 Some(foreground_color)
724 );
725 });
726 }
727 #[test]
729 fn a_text_button_theme_data_describes_nothing_by_default() {
730 assert_eq!(
731 waft_widgets::testing::describe_properties(|properties| {
732 waft_foundation::Diagnosticable::debug_fill_properties(
733 &TextButtonThemeData::new(),
734 properties,
735 )
736 }),
737 Vec::<String>::new()
738 );
739 }
740}