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 OutlinedButtonThemeData {
31 pub style: Option<ButtonStyle>,
39}
40
41impl OutlinedButtonThemeData {
42 pub fn new() -> OutlinedButtonThemeData {
46 OutlinedButtonThemeData::default()
47 }
48
49 pub fn style(mut self, style: ButtonStyle) -> OutlinedButtonThemeData {
51 self.style = Some(style);
52 self
53 }
54
55 pub fn lerp(
57 a: Option<&OutlinedButtonThemeData>,
58 b: Option<&OutlinedButtonThemeData>,
59 t: f64,
60 ) -> Option<OutlinedButtonThemeData> {
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(OutlinedButtonThemeData {
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 OutlinedButtonTheme {
89 pub key: Option<KeyRef>,
90 pub data: OutlinedButtonThemeData,
92 pub child: WidgetRef,
93}
94
95impl OutlinedButtonTheme {
96 #[cfg_attr(debug_assertions, track_caller)]
98 pub fn new<K>(data: OutlinedButtonThemeData, child: impl IntoWidget<K>) -> OutlinedButtonTheme {
99 OutlinedButtonTheme {
100 key: None,
101 data,
102 child: child.into_widget(),
103 }
104 }
105
106 pub fn key(mut self, key: KeyRef) -> OutlinedButtonTheme {
108 self.key = Some(key);
109 self
110 }
111
112 pub fn of(app: &mut App, context: BuildContext) -> OutlinedButtonThemeData {
124 match context.depend_on_inherited_widget_of_exact_type::<OutlinedButtonTheme>(app) {
125 Some(button_theme) => button_theme.data.clone(),
126 None => Theme::of(app, context).outlined_button_theme.clone(),
127 }
128 }
129}
130
131impl InheritedTheme for OutlinedButtonTheme {
132 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
133 OutlinedButtonTheme::new(self.data.clone(), child).into_widget()
134 }
135}
136
137impl InheritedWidget for OutlinedButtonTheme {
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: &OutlinedButtonTheme) -> 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 OutlinedButtonThemeData {
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 OutlinedButtonThemeData {
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, Icon, Text, WidgetState, WidgetStateProperty, WidgetStates,
189 };
190
191 use waft_widgets::testing::{WidgetTester, find, test_widgets};
192
193 use super::*;
194 use crate::button_style::ButtonStyle;
195 use crate::button_style_button::IconAlignment;
196 use crate::color_scheme::ColorScheme;
197 use crate::colors::Colors;
198 use crate::icons::Icons;
199 use crate::ink_well::InkWell;
200 use crate::material::Material;
201 use crate::outlined_button::OutlinedButton;
202 use crate::test_support::material_app;
203 use crate::theme_data::{MaterialTapTargetSize, ThemeData};
204
205 fn pressed() -> Option<Listener> {
206 Some(Listener::new(|_app| {}))
207 }
208
209 fn side(color: Color) -> BorderSide {
210 BorderSide {
211 color,
212 ..BorderSide::default()
213 }
214 }
215
216 fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
218 let element = *find::by_type::<Material>()
219 .evaluate(tester)
220 .last()
221 .expect("the button's Material");
222 tester.widget(element, read)
223 }
224
225 fn ink_well<R>(tester: &WidgetTester, read: impl FnOnce(&InkWell) -> R) -> R {
226 let element = *find::by_type::<InkWell>()
227 .evaluate(tester)
228 .last()
229 .expect("an InkWell");
230 tester.widget(element, read)
231 }
232
233 fn align_of_label(tester: &WidgetTester) -> AlignmentGeometry {
234 let align =
235 tester.element(find::ancestor(find::text("button"), find::by_type::<Align>()).first());
236 tester.widget(align, |align: &Align| align.alignment)
237 }
238
239 #[test]
240 fn outlined_button_theme_data_lerp_special_cases() {
241 assert_eq!(OutlinedButtonThemeData::lerp(None, None, 0.0), None);
242 let data = OutlinedButtonThemeData::new();
243 assert_eq!(
245 OutlinedButtonThemeData::lerp(Some(&data), Some(&data), 0.5),
246 Some(data.clone())
247 );
248 }
249
250 fn no_theme_case(tester: &mut WidgetTester, use_material3: bool) {
251 let color_scheme = ColorScheme::light();
252 let theme = ThemeData::from(color_scheme.clone())
253 .use_material3(use_material3)
254 .build(&tester.cell.borrow());
255 tester.pump_widget(material_app(
256 theme,
257 Center::new()
258 .child(OutlinedButton::new(pressed(), Some(Text::new("button"))))
259 .into_widget(),
260 ));
261
262 material(tester, |material| {
263 assert_eq!(material.animation_duration, Duration::from_millis(200));
264 assert!(material.border_radius.is_none());
265 assert_eq!(material.color, Some(Colors::TRANSPARENT));
266 assert_eq!(material.elevation, 0.0);
267 assert_eq!(
268 material.shadow_color,
269 Some(if use_material3 {
270 Colors::TRANSPARENT
271 } else {
272 Colors::BLACK
273 })
274 );
275 let shape = material.shape.as_deref().expect("a shape");
276 if use_material3 {
277 let stadium = shape
278 .as_any()
279 .downcast_ref::<StadiumBorder>()
280 .expect("a StadiumBorder");
281 assert_eq!(stadium.side, side(color_scheme.outline()));
282 } else {
283 let rounded = shape
284 .as_any()
285 .downcast_ref::<RoundedRectangleBorder>()
286 .expect("a RoundedRectangleBorder");
287 assert_eq!(
288 rounded.side,
289 side(color_scheme.on_surface().with_opacity(0.12))
290 );
291 assert!(rounded.border_radius == BorderRadius::all(Radius::circular(4.0)).into());
292 }
293 let text_style = material.text_style.as_ref().expect("a text style");
294 assert_eq!(
295 text_style.color.as_deref().copied(),
296 Some(color_scheme.primary())
297 );
298 assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
299 assert_eq!(text_style.font_size, Some(14.0));
300 assert_eq!(text_style.font_weight, Some(FontWeight::W500));
301 });
302 assert!(align_of_label(tester) == AlignmentGeometry::CENTER);
303 }
304
305 #[test]
306 fn material_3_without_an_outlined_button_theme_the_defaults_apply() {
307 test_widgets(|tester| no_theme_case(tester, true));
308 }
309
310 #[test]
311 fn material_2_without_an_outlined_button_theme_the_defaults_apply() {
312 test_widgets(|tester| no_theme_case(tester, false));
313 }
314
315 mod style_overrides {
317 use super::*;
318
319 const FOREGROUND_COLOR: Color = Color::new(0xff000001);
320 const BACKGROUND_COLOR: Color = Color::new(0xff000002);
321 const DISABLED_COLOR: Color = Color::new(0xff000003);
322 const SHADOW_COLOR: Color = Color::new(0xff000004);
323 const ELEVATION: f64 = 3.0;
324
325 fn style_side() -> BorderSide {
326 BorderSide {
327 color: Colors::GREEN.primary(),
328 width: 2.0,
329 ..BorderSide::default()
330 }
331 }
332
333 fn shape() -> RoundedRectangleBorder {
334 RoundedRectangleBorder::new(
335 style_side(),
336 BorderRadius::all(Radius::circular(2.0)).into(),
337 )
338 }
339
340 fn style() -> ButtonStyle {
341 OutlinedButton::style_from()
342 .foreground_color(FOREGROUND_COLOR)
343 .disabled_foreground_color(DISABLED_COLOR)
344 .background_color(BACKGROUND_COLOR)
345 .disabled_background_color(DISABLED_COLOR)
346 .shadow_color(SHADOW_COLOR)
347 .elevation(ELEVATION)
348 .text_style(TextStyle::new().font_size(12.0))
349 .padding(EdgeInsetsGeometry::all(3.0))
350 .minimum_size(Size::new(200.0, 200.0))
351 .side(style_side())
352 .shape(shape())
353 .enabled_mouse_cursor(SystemMouseCursors::TEXT.into())
354 .disabled_mouse_cursor(SystemMouseCursors::GRAB.into())
355 .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
356 .animation_duration(Duration::from_millis(25))
357 .enable_feedback(false)
358 .alignment(AlignmentGeometry::CENTER_LEFT)
359 .build()
360 }
361
362 fn build_frame(
363 tester: &WidgetTester,
364 button_style: Option<ButtonStyle>,
365 theme_style: Option<ButtonStyle>,
366 overall_style: Option<ButtonStyle>,
367 ) -> WidgetRef {
368 let child = Builder::new(move |_app, _context| {
369 let mut button = OutlinedButton::new(pressed(), Some(Text::new("button")));
370 if let Some(button_style) = &button_style {
371 button = button.style(button_style.clone());
372 }
373 button.into_widget()
374 });
375 let mut overall = OutlinedButtonThemeData::new();
376 if let Some(overall_style) = overall_style {
377 overall = overall.style(overall_style);
378 }
379 let theme = ThemeData::from(ColorScheme::light())
380 .build(&tester.cell.borrow())
381 .copy_with()
382 .outlined_button_theme(overall)
383 .build();
384 let body = match theme_style {
387 None => child.into_widget(),
388 Some(theme_style) => OutlinedButtonTheme::new(
389 OutlinedButtonThemeData::new().style(theme_style),
390 child,
391 )
392 .into_widget(),
393 };
394 material_app(
395 theme,
396 Material::new()
397 .child(Center::new().child(body))
398 .into_widget(),
399 )
400 }
401
402 fn check_button(tester: &WidgetTester) {
403 let enabled = WidgetStates::new();
404 let disabled: WidgetStates = [WidgetState::Disabled].into_iter().collect();
405 let hovered: WidgetStates = [WidgetState::Hovered].into_iter().collect();
406 let focused: WidgetStates = [WidgetState::Focused].into_iter().collect();
407 material(tester, |material| {
408 let text_style = material.text_style.as_ref().expect("a text style");
409 assert_eq!(text_style.color.as_deref().copied(), Some(FOREGROUND_COLOR));
410 assert_eq!(text_style.font_size, Some(12.0));
411 assert_eq!(material.color, Some(BACKGROUND_COLOR));
412 assert_eq!(material.shadow_color, Some(SHADOW_COLOR));
413 assert_eq!(material.elevation, ELEVATION);
414 assert!(material.border_radius.is_none());
415 assert!(
416 material
417 .shape
418 .as_deref()
419 .expect("a shape")
420 .eq_shape(&shape())
421 );
422 assert_eq!(material.animation_duration, Duration::from_millis(25));
423 });
424 ink_well(tester, |ink_well| {
425 let mouse_cursor = ink_well
426 .ink_response
427 .mouse_cursor
428 .clone()
429 .expect("a mouse cursor");
430 let resolve = |states: &WidgetStates| {
431 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states)
432 };
433 assert!(resolve(&enabled) == MouseCursorRef::from(SystemMouseCursors::TEXT));
434 assert!(resolve(&disabled) == MouseCursorRef::from(SystemMouseCursors::GRAB));
435 let overlay_color = ink_well
436 .ink_response
437 .overlay_color
438 .clone()
439 .expect("an overlay color");
440 assert_eq!(
441 overlay_color.resolve(&hovered),
442 Some(FOREGROUND_COLOR.with_opacity(0.08))
443 );
444 assert_eq!(
445 overlay_color.resolve(&focused),
446 Some(FOREGROUND_COLOR.with_opacity(0.1))
447 );
448 assert!(!ink_well.ink_response.enable_feedback);
449 });
450 let button = *find::by_type::<OutlinedButton>()
451 .evaluate(tester)
452 .first()
453 .expect("an OutlinedButton");
454 let size = tester.get_size(button);
455 assert_eq!(size, Size::new(200.0, 200.0));
456 assert!(align_of_label(tester) == AlignmentGeometry::CENTER_LEFT);
457 }
458
459 #[derive(Clone, Copy)]
462 enum Given {
463 Null,
464 Empty,
465 Style,
466 }
467
468 impl Given {
469 fn style(self) -> Option<ButtonStyle> {
470 match self {
471 Given::Null => None,
472 Given::Empty => Some(ButtonStyle::new()),
473 Given::Style => Some(style()),
474 }
475 }
476 }
477
478 fn case(button_style: Given, theme_style: Given, overall_style: Given) {
479 test_widgets(|tester| {
480 let frame = build_frame(
481 tester,
482 button_style.style(),
483 theme_style.style(),
484 overall_style.style(),
485 );
486 tester.pump_widget(frame);
487 tester.pump_and_settle(); check_button(tester);
489 });
490 }
491
492 #[test]
493 fn the_button_style_overrides_the_defaults() {
494 case(Given::Style, Given::Null, Given::Null);
495 }
496
497 #[test]
498 fn the_button_theme_style_overrides_the_defaults() {
499 case(Given::Null, Given::Style, Given::Null);
500 }
501
502 #[test]
503 fn the_overall_themes_button_theme_style_overrides_the_defaults() {
504 case(Given::Null, Given::Null, Given::Style);
505 }
506
507 #[test]
510 fn the_button_style_overrides_the_defaults_over_empty_theme_and_overall_styles() {
511 case(Given::Style, Given::Empty, Given::Empty);
512 }
513
514 #[test]
515 fn the_button_theme_style_overrides_the_defaults_over_empty_button_and_overall_styles() {
516 case(Given::Empty, Given::Style, Given::Empty);
517 }
518
519 #[test]
520 fn the_overall_theme_style_overrides_the_defaults_with_no_theme_and_an_empty_button_style()
521 {
522 case(Given::Empty, Given::Null, Given::Style);
523 }
524 }
525
526 fn shadow_color_case(tester: &mut WidgetTester, use_material3: bool) {
527 let color_scheme = ColorScheme::light();
528 let shadow_color = Color::new(0xff000001);
529 let overridden_color = Color::new(0xff000002);
530
531 let frame = |tester: &WidgetTester,
532 overall_shadow_color: Option<Color>,
533 theme_shadow_color: Option<Color>,
534 button_shadow_color: Option<Color>| {
535 let theme = if use_material3 {
536 let mut scheme = color_scheme.copy_with();
537 if let Some(overall_shadow_color) = overall_shadow_color {
538 scheme = scheme.with_shadow(overall_shadow_color);
539 }
540 ThemeData::from(scheme).build(&tester.cell.borrow())
541 } else {
542 let theme = ThemeData::from(color_scheme.clone())
543 .use_material3(false)
544 .build(&tester.cell.borrow());
545 match overall_shadow_color {
546 Some(overall_shadow_color) => {
547 theme.copy_with().shadow_color(overall_shadow_color).build()
548 }
549 None => theme,
550 }
551 };
552 let style_with = |color: Option<Color>| {
553 let mut style = OutlinedButton::style_from();
554 if let Some(color) = color {
555 style = style.shadow_color(color);
556 }
557 style.build()
558 };
559 let button_style = style_with(button_shadow_color);
560 material_app(
561 theme,
562 Material::new()
563 .child(Center::new().child(OutlinedButtonTheme::new(
564 OutlinedButtonThemeData::new().style(style_with(theme_shadow_color)),
565 Builder::new(move |_app, _context| {
566 OutlinedButton::new(pressed(), Some(Text::new("button")))
567 .style(button_style.clone())
568 .into_widget()
569 }),
570 )))
571 .into_widget(),
572 )
573 };
574 let mut pump = |overall: Option<Color>, theme: Option<Color>, button: Option<Color>| {
575 let frame = frame(tester, overall, theme, button);
576 tester.pump_widget(frame);
577 tester.pump_and_settle(); material(tester, |material| material.shadow_color)
579 };
580
581 assert_eq!(
582 pump(None, None, None),
583 Some(if use_material3 {
584 Colors::TRANSPARENT
585 } else {
586 Colors::BLACK
587 })
588 );
589 assert_eq!(
590 pump(Some(shadow_color), None, None),
591 Some(if use_material3 {
592 Colors::TRANSPARENT
593 } else {
594 shadow_color
595 })
596 );
597 assert_eq!(pump(None, Some(shadow_color), None), Some(shadow_color));
598 assert_eq!(pump(None, None, Some(shadow_color)), Some(shadow_color));
599 assert_eq!(
600 pump(Some(overridden_color), Some(shadow_color), None),
601 Some(shadow_color)
602 );
603 assert_eq!(
604 pump(None, Some(overridden_color), Some(shadow_color)),
605 Some(shadow_color)
606 );
607 }
608
609 #[test]
610 fn material_3_the_shadow_color_comes_from_the_button_then_its_theme_and_never_the_scheme() {
611 test_widgets(|tester| shadow_color_case(tester, true));
612 }
613
614 #[test]
615 fn material_2_the_shadow_color_comes_from_the_button_then_its_theme_then_the_theme() {
616 test_widgets(|tester| shadow_color_case(tester, false));
617 }
618
619 #[test]
620 fn the_icon_follows_the_themes_style_icon_alignment() {
621 test_widgets(|tester| {
622 let mut case = |icon_alignment: Option<IconAlignment>| {
623 let mut style = ButtonStyle::new();
624 if let Some(icon_alignment) = icon_alignment {
625 style = style.icon_alignment(icon_alignment);
626 }
627 let theme = ThemeData::builder()
628 .outlined_button_theme(OutlinedButtonThemeData::new().style(style))
629 .build(&tester.cell.borrow());
630 tester.pump_widget(material_app(
631 theme,
632 Center::new()
633 .child(
634 OutlinedButton::icon(pressed(), Text::new("button"))
635 .icon(Icon::new(Some(Icons::add()))),
636 )
637 .into_widget(),
638 ));
639 tester.pump_and_settle();
640 let button = *find::by_type::<Material>()
641 .evaluate(tester)
642 .last()
643 .expect("a Material");
644 let icon = *find::by_type::<Icon>()
645 .evaluate(tester)
646 .first()
647 .expect("an Icon");
648 (tester.get_rect(button), tester.get_rect(icon))
649 };
650
651 let (button, icon) = case(None);
652 assert_eq!(button.left, icon.left - 16.0);
653
654 let (button, icon) = case(Some(IconAlignment::End));
655 assert_f32_equals(button.right, icon.right + 24.0);
656 });
657 }
658
659 #[test]
660 fn the_icon_takes_the_themes_foreground_color_over_the_default_icon_color() {
661 test_widgets(|tester| {
663 let foreground_color = Color::new(0xFFFFA500);
664 let theme = ThemeData::builder()
665 .outlined_button_theme(
666 OutlinedButtonThemeData::new().style(
667 OutlinedButton::style_from()
668 .foreground_color(foreground_color)
669 .build(),
670 ),
671 )
672 .build(&tester.cell.borrow());
673 tester.pump_widget(material_app(
674 theme,
675 Material::new()
676 .child(
677 Center::new().child(
678 OutlinedButton::icon(pressed(), Text::new("Button"))
679 .icon(Icon::new(Some(Icons::add()))),
680 ),
681 )
682 .into_widget(),
683 ));
684 assert_eq!(
685 tester.icon_style().color.as_deref().copied(),
686 Some(foreground_color)
687 );
688 });
689 }
690 #[test]
692 fn a_outlined_button_theme_data_describes_nothing_by_default() {
693 assert_eq!(
694 waft_widgets::testing::describe_properties(|properties| {
695 waft_foundation::Diagnosticable::debug_fill_properties(
696 &OutlinedButtonThemeData::new(),
697 properties,
698 )
699 }),
700 Vec::<String>::new()
701 );
702 }
703}