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 FilledButtonThemeData {
31 pub style: Option<ButtonStyle>,
39}
40
41impl FilledButtonThemeData {
42 pub fn new() -> FilledButtonThemeData {
46 FilledButtonThemeData::default()
47 }
48
49 pub fn style(mut self, style: ButtonStyle) -> FilledButtonThemeData {
51 self.style = Some(style);
52 self
53 }
54
55 pub fn lerp(
57 a: Option<&FilledButtonThemeData>,
58 b: Option<&FilledButtonThemeData>,
59 t: f64,
60 ) -> Option<FilledButtonThemeData> {
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(FilledButtonThemeData {
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 FilledButtonTheme {
89 pub key: Option<KeyRef>,
90 pub data: FilledButtonThemeData,
92 pub child: WidgetRef,
93}
94
95impl FilledButtonTheme {
96 #[cfg_attr(debug_assertions, track_caller)]
98 pub fn new<K>(data: FilledButtonThemeData, child: impl IntoWidget<K>) -> FilledButtonTheme {
99 FilledButtonTheme {
100 key: None,
101 data,
102 child: child.into_widget(),
103 }
104 }
105
106 pub fn key(mut self, key: KeyRef) -> FilledButtonTheme {
108 self.key = Some(key);
109 self
110 }
111
112 pub fn of(app: &mut App, context: BuildContext) -> FilledButtonThemeData {
123 match context.depend_on_inherited_widget_of_exact_type::<FilledButtonTheme>(app) {
124 Some(button_theme) => button_theme.data.clone(),
125 None => Theme::of(app, context).filled_button_theme.clone(),
126 }
127 }
128}
129
130impl InheritedTheme for FilledButtonTheme {
131 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
132 FilledButtonTheme::new(self.data.clone(), child).into_widget()
133 }
134}
135
136impl InheritedWidget for FilledButtonTheme {
137 fn key(&self) -> Option<&KeyRef> {
138 self.key.as_ref()
139 }
140
141 fn child(&self) -> &WidgetRef {
142 &self.child
143 }
144
145 fn update_should_notify(&self, old_widget: &FilledButtonTheme) -> bool {
146 self.data != old_widget.data
147 }
148
149 fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
150 Some(self)
151 }
152}
153
154impl waft_foundation::Diagnosticable for FilledButtonThemeData {
155 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
156 properties.add(
157 DiagnosticsProperty::<crate::button_style::ButtonStyle>::new(
158 "style",
159 self.style.clone(),
160 )
161 .default_value(None),
162 );
163 }
164}
165
166impl std::fmt::Display for FilledButtonThemeData {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.write_str(&waft_foundation::Diagnosticable::to_string(self))
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 #![allow(deprecated)]
175
176 use std::cell::RefCell;
177 use std::rc::Rc;
178 use std::time::Duration;
179
180 use waft_embedder::{Color, FontWeight, Radius, Size};
181 use waft_foundation::Listener;
182 use waft_painting::{
183 Alignment, AlignmentGeometry, BorderRadius, BorderSide, BorderStyle, EdgeInsetsGeometry,
184 OutlinedBorderRef, RoundedRectangleBorder, ShapeBorder, StadiumBorder, TextStyle,
185 };
186 use waft_services::{MouseCursorRef, SystemMouseCursors};
187 use waft_widgets::testing::{WidgetTester, find, test_widgets};
188 use waft_widgets::{
189 Align, AnyElement, Builder, Center, Column, Icon, IconTheme, SizedBox, Text, WidgetState,
190 WidgetStateProperty, WidgetStates, downcast_widget,
191 };
192
193 use super::*;
194 use crate::button_style_button::IconAlignment;
195 use crate::color_scheme::ColorScheme;
196 use crate::colors::Colors;
197 use crate::filled_button::FilledButton;
198 use crate::icons::Icons;
199 use crate::ink_well::InkWell;
200 use crate::material::Material;
201 use crate::test_support::material_app;
202 use crate::theme_data::{MaterialTapTargetSize, ThemeData};
203
204 fn pressed() -> Option<Listener> {
205 Some(Listener::new(|_app| {}))
206 }
207
208 fn text(text: &str) -> WidgetRef {
209 Text::new(text).into_widget()
210 }
211
212 fn states(states: &[WidgetState]) -> WidgetStates {
213 states.iter().copied().collect()
214 }
215
216 fn is_inside<W: 'static>(tester: &WidgetTester, element: AnyElement) -> bool {
217 let ancestors = tester.ancestors(element);
218 let app = tester.cell.borrow();
219 ancestors
220 .into_iter()
221 .any(|ancestor| downcast_widget::<W>(&**ancestor.widget(&app)).is_some())
222 }
223
224 fn in_button<W: 'static>(tester: &WidgetTester) -> AnyElement {
226 find::by_type::<W>()
227 .evaluate(tester)
228 .into_iter()
229 .find(|element| is_inside::<FilledButton>(tester, *element))
230 .expect("a descendant of the button")
231 }
232
233 fn material<R>(tester: &WidgetTester, read: impl FnOnce(&Material) -> R) -> R {
234 tester.widget::<Material, R>(in_button::<Material>(tester), read)
235 }
236
237 fn text_color(material: &Material) -> Option<Color> {
238 material
239 .text_style
240 .as_ref()
241 .and_then(|text_style| text_style.color.as_ref())
242 .map(|color| color.color())
243 }
244
245 #[test]
247 fn lerp_of_nothing_is_nothing_and_of_a_theme_with_itself_is_that_theme() {
248 assert_eq!(FilledButtonThemeData::lerp(None, None, 0.0), None);
249 let data = FilledButtonThemeData::new();
250 assert_eq!(
251 FilledButtonThemeData::lerp(Some(&data), Some(&data), 0.5),
252 Some(data)
253 );
254 }
255
256 #[test]
258 fn without_a_button_theme_the_button_shows_its_defaults() {
259 test_widgets(|tester| {
260 let color_scheme = ColorScheme::light();
261 let theme = ThemeData::from(color_scheme.clone()).build(&tester.cell.borrow());
262 tester.pump_widget(material_app(
263 theme,
264 Center::new()
265 .child(FilledButton::new(pressed(), Some(text("button"))))
266 .into_widget(),
267 ));
268
269 material(tester, |material| {
270 assert_eq!(material.animation_duration, Duration::from_millis(200));
271 assert!(material.border_radius.is_none());
272 assert_eq!(material.color, Some(color_scheme.primary()));
273 assert_eq!(material.elevation, 0.0);
274 assert_eq!(material.shadow_color, Some(Color::new(0xff000000)));
275 let shape = material.shape.as_deref().expect("a shape");
276 assert!(shape.eq_shape(&StadiumBorder::default()));
277 assert_eq!(text_color(material), Some(color_scheme.on_primary()));
278 let text_style = material.text_style.as_ref().expect("a text style");
279 assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
280 assert_eq!(text_style.font_size, Some(14.0));
281 assert_eq!(text_style.font_weight, Some(FontWeight::W500));
282 });
283 let align = in_button::<Align>(tester);
284 tester.widget::<Align, _>(align, |align| {
285 assert!(align.alignment == AlignmentGeometry::from(Alignment::CENTER));
286 });
287 });
288 }
289
290 const FOREGROUND_COLOR: Color = Color::new(0xff000001);
291 const BACKGROUND_COLOR: Color = Color::new(0xff000002);
292 const DISABLED_FOREGROUND_COLOR: Color = Color::new(0xff000003);
293 const DISABLED_BACKGROUND_COLOR: Color = Color::new(0xff000004);
294 const SHADOW_COLOR: Color = Color::new(0xff000005);
295 const ELEVATION: f64 = 1.0;
296 const MINIMUM_SIZE: Size = Size::new(200.0, 200.0);
297 const ANIMATION_DURATION: Duration = Duration::from_millis(25);
298 const ENABLE_FEEDBACK: bool = false;
299 const ALIGNMENT: AlignmentGeometry = AlignmentGeometry::CENTER_LEFT;
300
301 fn side() -> BorderSide {
302 BorderSide::new(
303 Colors::GREEN.primary(),
304 2.0,
305 BorderStyle::Solid,
306 BorderSide::STROKE_ALIGN_INSIDE,
307 )
308 }
309
310 fn shape() -> RoundedRectangleBorder {
311 RoundedRectangleBorder::new(side(), BorderRadius::all(Radius::circular(2.0)).into())
312 }
313
314 fn override_style() -> ButtonStyle {
316 let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
317 let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
318 FilledButton::style_from()
319 .foreground_color(FOREGROUND_COLOR)
320 .disabled_foreground_color(DISABLED_FOREGROUND_COLOR)
321 .background_color(BACKGROUND_COLOR)
322 .disabled_background_color(DISABLED_BACKGROUND_COLOR)
323 .shadow_color(SHADOW_COLOR)
324 .elevation(ELEVATION)
325 .text_style(TextStyle::new().font_size(12.0))
326 .padding(EdgeInsetsGeometry::all(3.0))
327 .minimum_size(MINIMUM_SIZE)
328 .side(side())
329 .shape(OutlinedBorderRef::new(shape()))
330 .enabled_mouse_cursor(text)
331 .disabled_mouse_cursor(grab)
332 .tap_target_size(MaterialTapTargetSize::ShrinkWrap)
333 .animation_duration(ANIMATION_DURATION)
334 .enable_feedback(ENABLE_FEEDBACK)
335 .alignment(ALIGNMENT)
336 .build()
337 }
338
339 fn override_frame(
340 tester: &WidgetTester,
341 button_style: Option<ButtonStyle>,
342 theme_style: Option<ButtonStyle>,
343 overall_style: Option<ButtonStyle>,
344 ) -> WidgetRef {
345 let child = Builder::new(move |_app, _context| {
346 let mut button = FilledButton::new(pressed(), Some(text("button")));
347 if let Some(button_style) = &button_style {
348 button = button.style(button_style.clone());
349 }
350 button.into_widget()
351 })
352 .into_widget();
353 let mut overall = FilledButtonThemeData::new();
354 overall.style = overall_style;
355 let theme = ThemeData::from(ColorScheme::light())
356 .build(&tester.cell.borrow())
357 .copy_with()
358 .filled_button_theme(overall)
359 .build();
360 material_app(
361 theme,
362 Center::new()
363 .child(match theme_style {
366 None => child,
367 Some(theme_style) => FilledButtonTheme::new(
368 FilledButtonThemeData::new().style(theme_style),
369 child,
370 )
371 .into_widget(),
372 })
373 .into_widget(),
374 )
375 }
376
377 fn check_button(tester: &WidgetTester) {
378 material(tester, |material| {
379 assert_eq!(text_color(material), Some(FOREGROUND_COLOR));
380 assert_eq!(
381 material
382 .text_style
383 .as_ref()
384 .and_then(|text_style| text_style.font_size),
385 Some(12.0)
386 );
387 assert_eq!(material.color, Some(BACKGROUND_COLOR));
388 assert_eq!(material.shadow_color, Some(SHADOW_COLOR));
389 assert_eq!(material.elevation, ELEVATION);
390 assert!(material.border_radius.is_none());
391 assert!(material.shape.as_deref() == Some(&shape() as &dyn ShapeBorder));
392 assert_eq!(material.animation_duration, ANIMATION_DURATION);
393 });
394 tester.widget::<InkWell, _>(in_button::<InkWell>(tester), |ink_well| {
395 let response = &ink_well.ink_response;
396 let cursor = response.mouse_cursor.clone().expect("a mouse cursor");
397 let text: MouseCursorRef = SystemMouseCursors::TEXT.into();
398 let grab: MouseCursorRef = SystemMouseCursors::GRAB.into();
399 assert!(
400 *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&cursor, &states(&[]))
401 == *text
402 );
403 assert!(
404 *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
405 &cursor,
406 &states(&[WidgetState::Disabled])
407 ) == *grab
408 );
409 let overlay = response.overlay_color.as_ref().expect("an overlay color");
410 assert_eq!(
411 overlay.resolve(&states(&[WidgetState::Hovered])),
412 Some(FOREGROUND_COLOR.with_opacity(0.08))
413 );
414 assert_eq!(
415 overlay.resolve(&states(&[WidgetState::Focused])),
416 Some(FOREGROUND_COLOR.with_opacity(0.1))
417 );
418 assert_eq!(
419 overlay.resolve(&states(&[WidgetState::Pressed])),
420 Some(FOREGROUND_COLOR.with_opacity(0.1))
421 );
422 assert_eq!(response.enable_feedback, ENABLE_FEEDBACK);
423 });
424 let button = find::by_type::<FilledButton>().evaluate(tester)[0];
425 let size = tester.get_size(button);
426 assert_eq!(size, Size::new(200.0, 200.0));
427 let align = in_button::<Align>(tester);
428 tester.widget::<Align, _>(align, |align| assert!(align.alignment == ALIGNMENT));
429 }
430
431 #[test]
434 fn the_button_style_the_button_theme_and_the_overall_theme_each_override_the_defaults() {
435 let cases = || -> [[Option<ButtonStyle>; 3]; 6] {
437 let empty = || Some(ButtonStyle::new());
438 [
439 [Some(override_style()), None, None],
441 [None, Some(override_style()), None],
443 [None, None, Some(override_style())],
445 [Some(override_style()), empty(), empty()],
448 [empty(), Some(override_style()), empty()],
450 [empty(), None, Some(override_style())],
453 ]
454 };
455 for case in 0..cases().len() {
456 test_widgets(|tester| {
457 let [button_style, theme_style, overall_style] = cases()[case].clone();
458 let frame = override_frame(tester, button_style, theme_style, overall_style);
459 tester.pump_widget(frame);
460 tester.pump_and_settle(); check_button(tester);
462 });
463 }
464 }
465
466 #[test]
468 fn the_shadow_color_comes_from_the_button_then_its_theme() {
469 test_widgets(|tester| {
470 let shadow_color = Color::new(0xff000001);
471 let overridden_color = Color::new(0xff000002);
472 let build_frame = |tester: &WidgetTester,
473 overall_shadow_color: Option<Color>,
474 theme_shadow_color: Option<Color>,
475 button_shadow_color: Option<Color>| {
476 let theme = ThemeData::from(ColorScheme::light()).build(&tester.cell.borrow());
477 let theme = match overall_shadow_color {
478 Some(overall) => theme.copy_with().shadow_color(overall).build(),
479 None => theme,
480 };
481 let style_from = |color: Option<Color>| {
482 let mut style = FilledButton::style_from();
483 if let Some(color) = color {
484 style = style.shadow_color(color);
485 }
486 style.build()
487 };
488 let button_style = style_from(button_shadow_color);
489 material_app(
490 theme,
491 Center::new()
492 .child(FilledButtonTheme::new(
493 FilledButtonThemeData::new().style(style_from(theme_shadow_color)),
494 Builder::new(move |_app, _context| {
495 FilledButton::new(pressed(), Some(text("button")))
496 .style(button_style.clone())
497 .into_widget()
498 }),
499 ))
500 .into_widget(),
501 )
502 };
503 let shadow = |tester: &WidgetTester| material(tester, |material| material.shadow_color);
504
505 let frame = build_frame(tester, None, None, None);
506 tester.pump_widget(frame);
507 assert_eq!(shadow(tester), Some(Colors::BLACK)); for (overall, theme, button) in [
510 (None, Some(shadow_color), None),
511 (None, None, Some(shadow_color)),
512 (Some(overridden_color), Some(shadow_color), None),
513 (None, Some(overridden_color), Some(shadow_color)),
514 ] {
515 let frame = build_frame(tester, overall, theme, button);
516 tester.pump_widget(frame);
517 tester.pump_and_settle(); assert_eq!(shadow(tester), Some(shadow_color));
519 }
520 });
521 }
522
523 fn icon_button_frame(theme: ThemeData, tonal: bool) -> WidgetRef {
524 let button = if tonal {
525 FilledButton::tonal_icon(pressed(), text("button"))
526 } else {
527 FilledButton::icon(pressed(), text("button"))
528 }
529 .icon(Icon::new(Some(Icons::add())));
530 material_app(theme, Center::new().child(button).into_widget())
531 }
532
533 #[test]
537 fn an_icon_button_takes_its_icon_alignment_from_the_theme() {
538 for tonal in [false, true] {
539 test_widgets(|tester| {
540 let build = |tester: &WidgetTester, icon_alignment: Option<IconAlignment>| {
541 let mut style = ButtonStyle::new();
542 style.icon_alignment = icon_alignment;
543 let theme = ThemeData::builder()
544 .filled_button_theme(FilledButtonThemeData::new().style(style))
545 .build(&tester.cell.borrow());
546 icon_button_frame(theme, tonal)
547 };
548 let rects = |tester: &WidgetTester| {
549 let material = tester.get_rect(in_button::<Material>(tester));
550 let icon = tester.get_rect(find::by_type::<Icon>().evaluate(tester)[0]);
551 (material, icon)
552 };
553
554 let frame = build(tester, None);
555 tester.pump_widget(frame);
556 let (button, icon) = rects(tester);
557 assert_eq!(button.left, icon.left - 16.0);
558
559 let frame = build(tester, Some(IconAlignment::End));
560 tester.pump_widget(frame);
561 tester.pump_and_settle();
562 let (button, icon) = rects(tester);
563 let expected = icon.right + 24.0;
566 waft_widgets::testing::assert_f32_equals(button.right, expected);
567 });
568 }
569 }
570
571 #[test]
574 fn each_icon_takes_the_theme_foreground_color() {
575 test_widgets(|tester| {
576 let foreground_color = Color::new(0xFFFFA500);
577 let seen = Rc::new(RefCell::new(Vec::new()));
578 let probe = || {
579 let seen = Rc::clone(&seen);
580 Builder::new(move |app, context| {
581 seen.borrow_mut()
582 .push(IconTheme::of(app, context).color.map(|color| color.color()));
583 SizedBox::new().width(18.0).height(18.0).into_widget()
584 })
585 .into_widget()
586 };
587 let theme = ThemeData::builder()
588 .filled_button_theme(
589 FilledButtonThemeData::new().style(
590 FilledButton::style_from()
591 .foreground_color(foreground_color)
592 .build(),
593 ),
594 )
595 .build(&tester.cell.borrow());
596 tester.pump_widget(material_app(
597 theme,
598 Material::new()
599 .child(
600 Center::new().child(
601 Column::new().children([
602 FilledButton::icon(pressed(), text("Button"))
603 .icon(probe())
604 .into_widget(),
605 FilledButton::icon(pressed(), text("Button"))
606 .icon(probe())
607 .into_widget(),
608 ]),
609 ),
610 )
611 .into_widget(),
612 ));
613 assert_eq!(
614 *seen.borrow(),
615 vec![Some(foreground_color), Some(foreground_color)]
616 );
617 });
618 }
619 #[test]
621 fn a_filled_button_theme_data_describes_nothing_by_default() {
622 assert_eq!(
623 waft_widgets::testing::describe_properties(|properties| {
624 waft_foundation::Diagnosticable::debug_fill_properties(
625 &FilledButtonThemeData::new(),
626 properties,
627 )
628 }),
629 Vec::<String>::new()
630 );
631 }
632}