1use std::rc::Rc;
4
5use waft_foundation::{App, DiagnosticsProperty};
6use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
7
8use crate::button_style::ButtonStyle;
9use crate::theme::Theme;
10
11#[derive(Clone, Debug, Default)]
26pub struct SegmentedButtonThemeData {
27 pub style: Option<ButtonStyle>,
42
43 pub selected_icon: Option<WidgetRef>,
48}
49
50crate::theme_data_getters::theme_data_getters! {
51 pub trait SegmentedButtonThemeDataGetters for SegmentedButtonThemeData,
55 fields: segmented_button_theme_data {
56 style: Option<ButtonStyle>,
57 selected_icon: Option<WidgetRef>,
58 }
59}
60
61impl SegmentedButtonThemeData {
62 pub fn new() -> SegmentedButtonThemeData {
65 SegmentedButtonThemeData::default()
66 }
67
68 pub fn style(mut self, style: ButtonStyle) -> SegmentedButtonThemeData {
70 self.style = Some(style);
71 self
72 }
73
74 #[cfg_attr(debug_assertions, track_caller)]
76 pub fn selected_icon<K>(
77 mut self,
78 selected_icon: impl IntoWidget<K>,
79 ) -> SegmentedButtonThemeData {
80 self.selected_icon = Some(selected_icon.into_widget());
81 self
82 }
83
84 pub fn copy_with(&self) -> SegmentedButtonThemeData {
90 self.clone()
91 }
92
93 pub fn lerp(
95 a: Option<&SegmentedButtonThemeData>,
96 b: Option<&SegmentedButtonThemeData>,
97 t: f64,
98 ) -> SegmentedButtonThemeData {
99 if let (Some(a), Some(b)) = (a, b)
100 && std::ptr::eq(a, b)
101 {
102 return a.clone();
103 }
104 SegmentedButtonThemeData {
105 style: ButtonStyle::lerp(
106 a.and_then(|a| a.style.as_ref()),
107 b.and_then(|b| b.style.as_ref()),
108 t,
109 ),
110 selected_icon: if t < 0.5 {
111 a.and_then(|a| a.selected_icon.clone())
112 } else {
113 b.and_then(|b| b.selected_icon.clone())
114 },
115 }
116 }
117}
118
119impl PartialEq for SegmentedButtonThemeData {
121 fn eq(&self, other: &SegmentedButtonThemeData) -> bool {
122 self.style == other.style
123 && match (&self.selected_icon, &other.selected_icon) {
124 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
125 (None, None) => true,
126 _ => false,
127 }
128 }
129}
130
131#[derive(Debug)]
137pub struct SegmentedButtonTheme {
138 pub key: Option<KeyRef>,
139 pub data: SegmentedButtonThemeData,
142 pub child: WidgetRef,
143}
144
145impl SegmentedButtonTheme {
146 #[cfg_attr(debug_assertions, track_caller)]
149 pub fn new<K>(
150 data: SegmentedButtonThemeData,
151 child: impl IntoWidget<K>,
152 ) -> SegmentedButtonTheme {
153 SegmentedButtonTheme {
154 key: None,
155 data,
156 child: child.into_widget(),
157 }
158 }
159
160 pub fn key(mut self, key: KeyRef) -> SegmentedButtonTheme {
162 self.key = Some(key);
163 self
164 }
165
166 pub fn of(app: &mut App, context: BuildContext) -> SegmentedButtonThemeData {
183 match SegmentedButtonTheme::maybe_of(app, context) {
184 Some(data) => data,
185 None => Theme::of(app, context).segmented_button_theme.clone(),
186 }
187 }
188
189 pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<SegmentedButtonThemeData> {
213 context
214 .depend_on_inherited_widget_of_exact_type::<SegmentedButtonTheme>(app)
215 .map(|theme| theme.data.clone())
216 }
217}
218
219impl InheritedTheme for SegmentedButtonTheme {
220 fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
221 SegmentedButtonTheme::new(self.data.clone(), child).into_widget()
222 }
223}
224
225impl InheritedWidget for SegmentedButtonTheme {
226 fn key(&self) -> Option<&KeyRef> {
227 self.key.as_ref()
228 }
229
230 fn child(&self) -> &WidgetRef {
231 &self.child
232 }
233
234 fn update_should_notify(&self, old_widget: &SegmentedButtonTheme) -> bool {
235 self.data != old_widget.data
236 }
237
238 fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
239 Some(self)
240 }
241}
242
243impl waft_foundation::Diagnosticable for SegmentedButtonThemeData {
244 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
245 properties.add(
246 DiagnosticsProperty::<crate::button_style::ButtonStyle>::new(
247 "style",
248 self.style.clone(),
249 )
250 .default_value(None),
251 );
252 }
253}
254
255impl std::fmt::Display for SegmentedButtonThemeData {
256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
257 f.write_str(&waft_foundation::Diagnosticable::to_string(self))
258 }
259}
260
261#[cfg(test)]
262#[allow(deprecated, reason = "Dart's tests call `withOpacity`")]
263mod tests {
264 use std::time::Duration;
268
269 use waft_embedder::{Color, FontWeight};
270 use waft_painting::{RoundedRectangleBorder, TextStyle};
271 use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
272 use waft_widgets::{
273 Center, Icon, IconData, WidgetState, WidgetStateProperty, WidgetStatePropertyRef,
274 };
275
276 use waft_widgets::testing::{WidgetTester, find, test_widgets};
277
278 use super::*;
279 use crate::colors::Colors;
280 use crate::icons::Icons;
281 use crate::material::Material;
282 use crate::scaffold::Scaffold;
283 use crate::segmented_button::tests::{
284 argb, ink_rect_colors, label, mouse_at, numbered, text_center,
285 };
286 use crate::segmented_button::{ButtonSegment, SegmentedButton};
287 use crate::test_support::material_app;
288 use crate::theme_data::ThemeData;
289
290 #[test]
291 fn segmented_button_theme_data_copy_with_and_equality_basics() {
292 assert_eq!(
293 SegmentedButtonThemeData::new(),
294 SegmentedButtonThemeData::new().copy_with()
295 );
296
297 let custom = SegmentedButtonThemeData::new()
298 .style(ButtonStyle::new().background_color(Rc::new(
299 waft_widgets::WidgetStatePropertyAll::new(Some(Colors::GREEN.primary())),
300 )))
301 .selected_icon(Icon::new(Some(Icons::error())));
302 let copy = SegmentedButtonThemeData::new().copy_with();
303 let mut copy = copy;
304 copy.style = custom.style.clone();
305 copy.selected_icon = custom.selected_icon.clone();
306 assert_eq!(copy, custom);
307 }
308
309 #[test]
310 fn segmented_button_theme_data_lerp_special_cases() {
311 assert_eq!(
312 SegmentedButtonThemeData::lerp(None, None, 0.0),
313 SegmentedButtonThemeData::new()
314 );
315 let theme = SegmentedButtonThemeData::new();
316 assert_eq!(
317 SegmentedButtonThemeData::lerp(Some(&theme), Some(&theme), 0.5),
318 theme
319 );
320 }
321
322 fn colored_style(
326 disabled: (Color, Color),
327 selected: (Color, Color),
328 other_foreground: Color,
329 ) -> ButtonStyle {
330 let background: WidgetStatePropertyRef<Option<Color>> =
331 <dyn WidgetStateProperty<_>>::resolve_with(move |states| {
332 if states.contains(&WidgetState::Disabled) {
333 return Some(disabled.0);
334 }
335 if states.contains(&WidgetState::Selected) {
336 return Some(selected.0);
337 }
338 None
339 });
340 let foreground: WidgetStatePropertyRef<Option<Color>> =
341 <dyn WidgetStateProperty<_>>::resolve_with(move |states| {
342 if states.contains(&WidgetState::Disabled) {
343 return Some(disabled.1);
344 }
345 if states.contains(&WidgetState::Selected) {
346 return Some(selected.1);
347 }
348 Some(other_foreground)
349 });
350 ButtonStyle::new()
351 .background_color(background)
352 .foreground_color(foreground)
353 }
354
355 fn three_segments() -> Vec<ButtonSegment<i32>> {
356 let mut segments = numbered(&[1, 2, 3]);
357 segments[2].enabled = false;
358 segments
359 }
360
361 struct Expected {
363 animation_duration: bool,
364 color: Color,
365 text_color: Color,
366 selected_icon: Option<IconData>,
367 }
368
369 fn check_segment(tester: &WidgetTester, text: &str, expected: Expected) {
370 let parent =
371 tester.element(find::ancestor(find::text(text), find::by_type::<Material>()).first());
372 let icons = find::descendant(
373 find::ancestor(find::text(text), find::by_type::<Material>()).first(),
374 find::by_type::<Icon>(),
375 )
376 .evaluate(tester)
377 .into_iter()
378 .filter(|icon| {
379 tester.widget(*icon, |icon: &Icon| {
380 expected.selected_icon.is_some() && icon.icon == expected.selected_icon
381 })
382 })
383 .count();
384 tester.widget(parent, |material: &Material| {
385 if expected.animation_duration {
386 assert_eq!(material.animation_duration, Duration::from_millis(200));
387 assert_eq!(material.border_radius, None);
388 }
389 assert_eq!(material.color, Some(expected.color));
390 assert_eq!(
391 material.shape,
392 Some(waft_painting::ShapeBorderRef::new(
393 RoundedRectangleBorder::default()
394 ))
395 );
396 let text_style: &TextStyle = material.text_style.as_ref().expect("a text style");
397 assert_eq!(
398 text_style.color.as_deref().copied(),
399 Some(expected.text_color)
400 );
401 assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
402 assert_eq!(text_style.font_size, Some(14.0));
403 assert_eq!(text_style.font_weight, Some(FontWeight::W500));
404 });
405 assert_eq!(icons, usize::from(expected.selected_icon.is_some()));
406 }
407
408 fn pump_three(
409 tester: &mut WidgetTester,
410 theme: ThemeData,
411 home: impl FnOnce(WidgetRef) -> WidgetRef,
412 button: SegmentedButton<i32>,
413 ) {
414 let home = home(
415 Scaffold::new()
416 .body(Center::new().child(button))
417 .into_widget(),
418 );
419 tester.pump_widget(material_app(theme, home));
420 }
421
422 #[test]
424 fn with_no_other_configuration_the_defaults_are_used() {
425 test_widgets(|tester| {
426 let theme = ThemeData::new(&tester.cell.borrow());
427 let colors = theme.color_scheme.clone();
428 pump_three(
429 tester,
430 theme,
431 |home| home,
432 SegmentedButton::new(three_segments(), vec![2])
433 .on_selection_changed(|_app, _selected| {}),
434 );
435
436 check_segment(
438 tester,
439 "1",
440 Expected {
441 animation_duration: false,
442 color: Colors::TRANSPARENT,
443 text_color: colors.on_surface(),
444 selected_icon: None,
445 },
446 );
447 check_segment(
449 tester,
450 "2",
451 Expected {
452 animation_duration: false,
453 color: colors.secondary_container(),
454 text_color: colors.on_secondary_container(),
455 selected_icon: Some(Icons::check()),
456 },
457 );
458 check_segment(
460 tester,
461 "3",
462 Expected {
463 animation_duration: false,
464 color: Colors::TRANSPARENT,
465 text_color: colors.on_surface().with_opacity(0.38),
466 selected_icon: None,
467 },
468 );
469 });
470 }
471
472 fn global_theme_data() -> SegmentedButtonThemeData {
473 SegmentedButtonThemeData::new()
474 .style(colored_style(
475 (Colors::BLUE.primary(), Colors::YELLOW.primary()),
476 (Colors::PURPLE.primary(), Colors::BROWN.primary()),
477 Colors::CYAN.primary(),
478 ))
479 .selected_icon(Icon::new(Some(Icons::error())))
480 }
481
482 fn segmented_theme_data() -> SegmentedButtonThemeData {
483 SegmentedButtonThemeData::new()
484 .style(colored_style(
485 (Colors::LIGHT_BLUE.primary(), Colors::LIME.primary()),
486 (Colors::LIGHT_GREEN.primary(), Colors::AMBER.primary()),
487 Colors::DEEP_PURPLE.primary(),
488 ))
489 .selected_icon(Icon::new(Some(Icons::plus_one())))
490 }
491
492 #[test]
494 fn theme_data_segmented_button_theme_overrides_the_defaults() {
495 test_widgets(|tester| {
496 let theme = ThemeData::builder()
497 .segmented_button_theme(global_theme_data())
498 .build(&tester.cell.borrow());
499 pump_three(
500 tester,
501 theme,
502 |home| home,
503 SegmentedButton::new(three_segments(), vec![2])
504 .on_selection_changed(|_app, _selected| {}),
505 );
506
507 check_segment(
508 tester,
509 "1",
510 Expected {
511 animation_duration: false,
512 color: Colors::TRANSPARENT,
513 text_color: Colors::CYAN.primary(),
514 selected_icon: None,
515 },
516 );
517 check_segment(
518 tester,
519 "2",
520 Expected {
521 animation_duration: false,
522 color: Colors::PURPLE.primary(),
523 text_color: Colors::BROWN.primary(),
524 selected_icon: Some(Icons::error()),
525 },
526 );
527 check_segment(
528 tester,
529 "3",
530 Expected {
531 animation_duration: false,
532 color: Colors::BLUE.primary(),
533 text_color: Colors::YELLOW.primary(),
534 selected_icon: None,
535 },
536 );
537 });
538 }
539
540 #[test]
542 fn segmented_button_theme_overrides_theme_data_and_the_defaults() {
543 test_widgets(|tester| {
544 let theme = ThemeData::builder()
545 .segmented_button_theme(global_theme_data())
546 .build(&tester.cell.borrow());
547 pump_three(
548 tester,
549 theme,
550 |home| SegmentedButtonTheme::new(segmented_theme_data(), home).into_widget(),
551 SegmentedButton::new(three_segments(), vec![2])
552 .on_selection_changed(|_app, _selected| {}),
553 );
554
555 check_segment(
556 tester,
557 "1",
558 Expected {
559 animation_duration: true,
560 color: Colors::TRANSPARENT,
561 text_color: Colors::DEEP_PURPLE.primary(),
562 selected_icon: None,
563 },
564 );
565 check_segment(
566 tester,
567 "2",
568 Expected {
569 animation_duration: true,
570 color: Colors::LIGHT_GREEN.primary(),
571 text_color: Colors::AMBER.primary(),
572 selected_icon: Some(Icons::plus_one()),
573 },
574 );
575 check_segment(
576 tester,
577 "3",
578 Expected {
579 animation_duration: true,
580 color: Colors::LIGHT_BLUE.primary(),
581 text_color: Colors::LIME.primary(),
582 selected_icon: None,
583 },
584 );
585 });
586 }
587
588 #[test]
590 fn widget_parameters_override_the_segmented_theme_theme_data_and_the_defaults() {
591 test_widgets(|tester| {
592 let theme = ThemeData::builder()
593 .segmented_button_theme(global_theme_data())
594 .build(&tester.cell.borrow());
595 pump_three(
596 tester,
597 theme,
598 |home| SegmentedButtonTheme::new(segmented_theme_data(), home).into_widget(),
599 SegmentedButton::new(three_segments(), vec![2])
600 .on_selection_changed(|_app, _selected| {})
601 .style(colored_style(
602 (Colors::BLACK12, Colors::AMBER_ACCENT.primary()),
603 (Colors::GREY.primary(), Colors::DEEP_ORANGE.primary()),
604 Colors::DEEP_PURPLE_ACCENT.primary(),
605 ))
606 .selected_icon(Icon::new(Some(Icons::alarm()))),
607 );
608
609 check_segment(
610 tester,
611 "1",
612 Expected {
613 animation_duration: true,
614 color: Colors::TRANSPARENT,
615 text_color: Colors::DEEP_PURPLE_ACCENT.primary(),
616 selected_icon: None,
617 },
618 );
619 check_segment(
620 tester,
621 "2",
622 Expected {
623 animation_duration: true,
624 color: Colors::GREY.primary(),
625 text_color: Colors::DEEP_ORANGE.primary(),
626 selected_icon: Some(Icons::alarm()),
627 },
628 );
629 check_segment(
630 tester,
631 "3",
632 Expected {
633 animation_duration: true,
634 color: Colors::BLACK12,
635 text_color: Colors::AMBER_ACCENT.primary(),
636 selected_icon: None,
637 },
638 );
639 });
640 }
641
642 #[test]
645 fn the_theme_style_from_overlay_color_overrides_the_default_overlay_color() {
646 test_widgets(|tester| {
647 let overlay_color = Color::new(0xffff0000);
648 let theme = ThemeData::builder()
649 .segmented_button_theme(
650 SegmentedButtonThemeData::new().style(
651 SegmentedButton::<i32>::style_from()
652 .overlay_color(overlay_color)
653 .build(),
654 ),
655 )
656 .build(&tester.cell.borrow());
657 let segments = vec![
658 ButtonSegment::new(0).label(label("Option 1")),
659 ButtonSegment::new(1).label(label("Option 2")),
660 ];
661 pump_three(
662 tester,
663 theme,
664 |home| home,
665 SegmentedButton::new(segments, vec![1]).on_selection_changed(|_app, _selected| {}),
666 );
667 let hover = argb(overlay_color.with_opacity(0.08));
668 let press = argb(overlay_color.with_opacity(0.1));
669
670 let center = text_center(tester, "Option 1");
672 let mut gesture = mouse_at(tester, center);
673 tester.pump_and_settle();
674 assert!(ink_rect_colors(tester).contains(&hover));
675
676 let center = text_center(tester, "Option 2");
678 tester.move_to(&mut gesture, center, false);
679 tester.pump_and_settle();
680 assert!(ink_rect_colors(tester).contains(&hover));
681
682 let center = text_center(tester, "Option 1");
684 tester.down(&mut gesture, center);
685 tester.pump_and_settle();
686 let colors = ink_rect_colors(tester);
687 assert!(colors.contains(&hover) && colors.contains(&press));
688 tester.up(&gesture);
690 tester.pump_and_settle();
691 tester.move_to(&mut gesture, waft_embedder::Offset::new(0.0, 50.0), false);
692 tester.pump_and_settle();
693
694 let center = text_center(tester, "Option 2");
696 tester.down(&mut gesture, center);
697 tester.pump_and_settle();
698 let colors = ink_rect_colors(tester);
699 assert!(colors.contains(&hover) && colors.contains(&press));
700 tester.up(&gesture);
702 tester.pump_and_settle();
703 tester.move_to(&mut gesture, waft_embedder::Offset::new(0.0, 50.0), false);
704 tester.pump_and_settle();
705
706 tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
708 tester.pump_and_settle();
709 assert!(ink_rect_colors(tester).contains(&press));
710
711 tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
713 tester.pump_and_settle();
714 assert!(ink_rect_colors(tester).contains(&press));
715 });
716 }
717 #[test]
719 fn a_segmented_button_theme_data_describes_nothing_by_default() {
720 assert_eq!(
721 waft_widgets::testing::describe_properties(|properties| {
722 waft_foundation::Diagnosticable::debug_fill_properties(
723 &SegmentedButtonThemeData::new(),
724 properties,
725 )
726 }),
727 Vec::<String>::new()
728 );
729 }
730}