use std::fmt::{self, Debug};
use std::time::Duration;
use waft_embedder::{Brightness, Color, Radius};
use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty, FlagProperty};
use waft_painting::{
BorderRadiusGeometry, BorderSide, ColorProperty, EdgeInsetsGeometry, RoundedRectangleBorder,
ShapeBorderRef,
};
use waft_rendering::BoxConstraints;
use waft_widgets::{BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
use crate::color_scheme::ColorScheme;
use crate::colors::Colors;
use crate::constants::K_THEME_CHANGE_DURATION;
use crate::material_button::MaterialButton;
use crate::theme::Theme;
use crate::theme_data::{MaterialTapTargetSize, ThemeData};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ButtonTextTheme {
Normal,
Accent,
Primary,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ButtonBarLayoutBehavior {
Constrained,
Padded,
}
#[derive(Debug)]
pub struct ButtonTheme {
pub key: Option<KeyRef>,
pub data: ButtonThemeData,
pub child: WidgetRef,
}
impl ButtonTheme {
#[cfg_attr(debug_assertions, track_caller)]
pub fn new<K>(child: impl IntoWidget<K>) -> ButtonTheme {
ButtonTheme::from_button_theme_data(ButtonThemeData::new(), child)
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn from_button_theme_data<K>(
data: ButtonThemeData,
child: impl IntoWidget<K>,
) -> ButtonTheme {
ButtonTheme {
key: None,
data,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> ButtonTheme {
self.key = Some(key);
self
}
pub fn text_theme(mut self, text_theme: ButtonTextTheme) -> ButtonTheme {
self.data = self.data.with_text_theme(text_theme);
self
}
pub fn layout_behavior(mut self, layout_behavior: ButtonBarLayoutBehavior) -> ButtonTheme {
self.data = self.data.with_layout_behavior(layout_behavior);
self
}
pub fn min_width(mut self, min_width: f64) -> ButtonTheme {
self.data = self.data.with_min_width(min_width);
self
}
pub fn height(mut self, height: f64) -> ButtonTheme {
self.data = self.data.with_height(height);
self
}
pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ButtonTheme {
self.data = self.data.with_padding(padding);
self
}
pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> ButtonTheme {
self.data = self.data.with_shape(shape);
self
}
pub fn aligned_dropdown(mut self, aligned_dropdown: bool) -> ButtonTheme {
self.data = self.data.with_aligned_dropdown(aligned_dropdown);
self
}
pub fn button_color(mut self, button_color: Color) -> ButtonTheme {
self.data = self.data.with_button_color(button_color);
self
}
pub fn disabled_color(mut self, disabled_color: Color) -> ButtonTheme {
self.data = self.data.with_disabled_color(disabled_color);
self
}
pub fn focus_color(mut self, focus_color: Color) -> ButtonTheme {
self.data = self.data.with_focus_color(focus_color);
self
}
pub fn hover_color(mut self, hover_color: Color) -> ButtonTheme {
self.data = self.data.with_hover_color(hover_color);
self
}
pub fn highlight_color(mut self, highlight_color: Color) -> ButtonTheme {
self.data = self.data.with_highlight_color(highlight_color);
self
}
pub fn splash_color(mut self, splash_color: Color) -> ButtonTheme {
self.data = self.data.with_splash_color(splash_color);
self
}
pub fn color_scheme(mut self, color_scheme: ColorScheme) -> ButtonTheme {
self.data = self.data.with_color_scheme(color_scheme);
self
}
pub fn material_tap_target_size(
mut self,
material_tap_target_size: MaterialTapTargetSize,
) -> ButtonTheme {
self.data = self
.data
.with_material_tap_target_size(material_tap_target_size);
self
}
pub fn of(app: &mut App, context: BuildContext) -> ButtonThemeData {
let inherited_button_theme =
context.depend_on_inherited_widget_of_exact_type::<ButtonTheme>(app);
let mut button_theme = inherited_button_theme.map(|theme| theme.data.clone());
if button_theme
.as_ref()
.is_none_or(|button_theme| button_theme.color_scheme.is_none())
{
let theme = Theme::of(app, context);
let mut theme_button_theme = button_theme.unwrap_or_else(|| theme.button_theme.clone());
if theme_button_theme.color_scheme.is_none() {
theme_button_theme = theme_button_theme.copy_with().with_color_scheme(
theme
.button_theme
.color_scheme
.clone()
.unwrap_or_else(|| theme.color_scheme.clone()),
);
debug_assert!(theme_button_theme.color_scheme.is_some());
}
button_theme = Some(theme_button_theme);
}
button_theme.expect("filled above")
}
}
impl InheritedTheme for ButtonTheme {
fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
ButtonTheme::from_button_theme_data(self.data.clone(), child).into_widget()
}
}
impl InheritedWidget for ButtonTheme {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &ButtonTheme) -> bool {
self.data != old_widget.data
}
fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
Some(self)
}
}
#[derive(Clone)]
pub struct ButtonThemeData {
pub min_width: f64,
pub height: f64,
pub text_theme: ButtonTextTheme,
pub layout_behavior: ButtonBarLayoutBehavior,
padding: Option<EdgeInsetsGeometry>,
shape: Option<ShapeBorderRef>,
pub aligned_dropdown: bool,
button_color: Option<Color>,
disabled_color: Option<Color>,
focus_color: Option<Color>,
hover_color: Option<Color>,
highlight_color: Option<Color>,
splash_color: Option<Color>,
pub color_scheme: Option<ColorScheme>,
material_tap_target_size: Option<MaterialTapTargetSize>,
}
impl ButtonThemeData {
pub fn new() -> ButtonThemeData {
ButtonThemeData {
min_width: 88.0,
height: 36.0,
text_theme: ButtonTextTheme::Normal,
layout_behavior: ButtonBarLayoutBehavior::Padded,
padding: None,
shape: None,
aligned_dropdown: false,
button_color: None,
disabled_color: None,
focus_color: None,
hover_color: None,
highlight_color: None,
splash_color: None,
color_scheme: None,
material_tap_target_size: None,
}
}
pub fn with_text_theme(mut self, text_theme: ButtonTextTheme) -> ButtonThemeData {
self.text_theme = text_theme;
self
}
pub fn with_min_width(mut self, min_width: f64) -> ButtonThemeData {
debug_assert!(min_width >= 0.0);
self.min_width = min_width;
self
}
pub fn with_height(mut self, height: f64) -> ButtonThemeData {
debug_assert!(height >= 0.0);
self.height = height;
self
}
pub fn with_padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ButtonThemeData {
self.padding = Some(padding.into());
self
}
pub fn with_shape(mut self, shape: impl Into<ShapeBorderRef>) -> ButtonThemeData {
self.shape = Some(shape.into());
self
}
pub fn with_layout_behavior(
mut self,
layout_behavior: ButtonBarLayoutBehavior,
) -> ButtonThemeData {
self.layout_behavior = layout_behavior;
self
}
pub fn with_aligned_dropdown(mut self, aligned_dropdown: bool) -> ButtonThemeData {
self.aligned_dropdown = aligned_dropdown;
self
}
pub fn with_button_color(mut self, button_color: Color) -> ButtonThemeData {
self.button_color = Some(button_color);
self
}
pub fn with_disabled_color(mut self, disabled_color: Color) -> ButtonThemeData {
self.disabled_color = Some(disabled_color);
self
}
pub fn with_focus_color(mut self, focus_color: Color) -> ButtonThemeData {
self.focus_color = Some(focus_color);
self
}
pub fn with_hover_color(mut self, hover_color: Color) -> ButtonThemeData {
self.hover_color = Some(hover_color);
self
}
pub fn with_highlight_color(mut self, highlight_color: Color) -> ButtonThemeData {
self.highlight_color = Some(highlight_color);
self
}
pub fn with_splash_color(mut self, splash_color: Color) -> ButtonThemeData {
self.splash_color = Some(splash_color);
self
}
pub fn with_color_scheme(mut self, color_scheme: ColorScheme) -> ButtonThemeData {
self.color_scheme = Some(color_scheme);
self
}
pub fn with_material_tap_target_size(
mut self,
material_tap_target_size: MaterialTapTargetSize,
) -> ButtonThemeData {
self.material_tap_target_size = Some(material_tap_target_size);
self
}
pub fn constraints(&self) -> BoxConstraints {
BoxConstraints::new()
.min_width(self.min_width)
.min_height(self.height)
}
pub fn padding(&self) -> EdgeInsetsGeometry {
self.padding.unwrap_or(match self.text_theme {
ButtonTextTheme::Normal => EdgeInsetsGeometry::symmetric(0.0, 16.0),
ButtonTextTheme::Accent => EdgeInsetsGeometry::symmetric(0.0, 16.0),
ButtonTextTheme::Primary => EdgeInsetsGeometry::symmetric(0.0, 24.0),
})
}
pub fn shape(&self) -> ShapeBorderRef {
match &self.shape {
Some(shape) => shape.clone(),
None => match self.text_theme {
ButtonTextTheme::Normal | ButtonTextTheme::Accent => {
ShapeBorderRef::new(RoundedRectangleBorder::new(
BorderSide::NONE,
BorderRadiusGeometry::all(Radius::circular(2.0)),
))
}
ButtonTextTheme::Primary => ShapeBorderRef::new(RoundedRectangleBorder::new(
BorderSide::NONE,
BorderRadiusGeometry::all(Radius::circular(4.0)),
)),
},
}
}
fn color_scheme(&self) -> &ColorScheme {
self.color_scheme
.as_ref()
.expect("a button theme has a color scheme")
}
pub fn get_brightness(&self, button: &MaterialButton) -> Brightness {
button
.color_brightness
.unwrap_or_else(|| self.color_scheme().brightness())
}
pub fn get_text_theme(&self, button: &MaterialButton) -> ButtonTextTheme {
button.text_theme.unwrap_or(self.text_theme)
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_disabled_text_color(&self, button: &MaterialButton) -> Color {
button
.text_color
.or(button.disabled_text_color)
.unwrap_or_else(|| self.color_scheme().on_surface().with_opacity(0.38))
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_disabled_fill_color(&self, button: &MaterialButton) -> Color {
button
.disabled_color
.or(self.disabled_color)
.unwrap_or_else(|| self.color_scheme().on_surface().with_opacity(0.38))
}
pub fn get_fill_color(&self, button: &MaterialButton) -> Option<Color> {
if button.enabled() {
button.color
} else {
button.disabled_color
}
}
pub fn get_text_color(&self, button: &MaterialButton) -> Color {
if !button.enabled() {
return self.get_disabled_text_color(button);
}
if let Some(text_color) = button.text_color {
return text_color;
}
match self.get_text_theme(button) {
ButtonTextTheme::Normal => {
if self.get_brightness(button) == Brightness::Dark {
Colors::WHITE
} else {
Colors::BLACK87
}
}
ButtonTextTheme::Accent => self.color_scheme().secondary(),
ButtonTextTheme::Primary => {
let fill_is_dark = match self.get_fill_color(button) {
Some(fill_color) => {
ThemeData::estimate_brightness_for_color(fill_color) == Brightness::Dark
}
None => self.get_brightness(button) == Brightness::Dark,
};
if fill_is_dark {
Colors::WHITE
} else {
Colors::BLACK
}
}
}
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_splash_color(&self, button: &MaterialButton) -> Color {
if let Some(splash_color) = button.splash_color {
return splash_color;
}
if let Some(splash_color) = self.splash_color
&& matches!(
self.get_text_theme(button),
ButtonTextTheme::Normal | ButtonTextTheme::Accent
)
{
return splash_color;
}
self.get_text_color(button).with_opacity(0.12)
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_focus_color(&self, button: &MaterialButton) -> Color {
button
.focus_color
.or(self.focus_color)
.unwrap_or_else(|| self.get_text_color(button).with_opacity(0.12))
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_hover_color(&self, button: &MaterialButton) -> Color {
button
.hover_color
.or(self.hover_color)
.unwrap_or_else(|| self.get_text_color(button).with_opacity(0.04))
}
#[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
pub fn get_highlight_color(&self, button: &MaterialButton) -> Color {
if let Some(highlight_color) = button.highlight_color {
return highlight_color;
}
match self.get_text_theme(button) {
ButtonTextTheme::Normal | ButtonTextTheme::Accent => self
.highlight_color
.unwrap_or_else(|| self.get_text_color(button).with_opacity(0.16)),
ButtonTextTheme::Primary => Colors::TRANSPARENT,
}
}
pub fn get_elevation(&self, button: &MaterialButton) -> f64 {
button.elevation.unwrap_or(2.0)
}
pub fn get_focus_elevation(&self, button: &MaterialButton) -> f64 {
button.focus_elevation.unwrap_or(4.0)
}
pub fn get_hover_elevation(&self, button: &MaterialButton) -> f64 {
button.hover_elevation.unwrap_or(4.0)
}
pub fn get_highlight_elevation(&self, button: &MaterialButton) -> f64 {
button.highlight_elevation.unwrap_or(8.0)
}
pub fn get_disabled_elevation(&self, button: &MaterialButton) -> f64 {
button.disabled_elevation.unwrap_or(0.0)
}
pub fn get_padding(&self, button: &MaterialButton) -> EdgeInsetsGeometry {
button
.padding
.or(self.padding)
.unwrap_or_else(|| match self.get_text_theme(button) {
ButtonTextTheme::Normal | ButtonTextTheme::Accent => {
EdgeInsetsGeometry::symmetric(0.0, 16.0)
}
ButtonTextTheme::Primary => EdgeInsetsGeometry::symmetric(0.0, 24.0),
})
}
pub fn get_shape(&self, button: &MaterialButton) -> ShapeBorderRef {
button.shape.clone().unwrap_or_else(|| self.shape())
}
pub fn get_animation_duration(&self, button: &MaterialButton) -> Duration {
button.animation_duration.unwrap_or(K_THEME_CHANGE_DURATION)
}
pub fn get_constraints(&self, _button: &MaterialButton) -> BoxConstraints {
self.constraints()
}
pub fn get_material_tap_target_size(&self, button: &MaterialButton) -> MaterialTapTargetSize {
button
.material_tap_target_size
.or(self.material_tap_target_size)
.unwrap_or(MaterialTapTargetSize::Padded)
}
pub fn copy_with(&self) -> ButtonThemeData {
let mut copy = self.clone();
copy.padding = Some(self.padding());
copy.shape = Some(self.shape());
copy
}
}
impl Default for ButtonThemeData {
fn default() -> ButtonThemeData {
ButtonThemeData::new()
}
}
impl PartialEq for ButtonThemeData {
fn eq(&self, other: &ButtonThemeData) -> bool {
other.text_theme == self.text_theme
&& other.min_width == self.min_width
&& other.height == self.height
&& other.padding() == self.padding()
&& other.shape() == self.shape()
&& other.aligned_dropdown == self.aligned_dropdown
&& other.button_color == self.button_color
&& other.disabled_color == self.disabled_color
&& other.focus_color == self.focus_color
&& other.hover_color == self.hover_color
&& other.highlight_color == self.highlight_color
&& other.splash_color == self.splash_color
&& other.color_scheme == self.color_scheme
&& other.material_tap_target_size == self.material_tap_target_size
}
}
impl Debug for ButtonThemeData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let default_theme = ButtonThemeData::new();
let mut properties = f.debug_struct("ButtonThemeData");
if self.text_theme != default_theme.text_theme {
properties.field("textTheme", &self.text_theme);
}
if self.min_width != default_theme.min_width {
properties.field("minWidth", &self.min_width);
}
if self.height != default_theme.height {
properties.field("height", &self.height);
}
if self.padding() != default_theme.padding() {
properties.field("padding", &self.padding());
}
if self.shape() != default_theme.shape() {
properties.field("shape", &self.shape());
}
if self.aligned_dropdown != default_theme.aligned_dropdown {
properties.field("alignedDropdown", &"dropdown width matches button");
}
if let Some(button_color) = &self.button_color {
properties.field("buttonColor", button_color);
}
if let Some(disabled_color) = &self.disabled_color {
properties.field("disabledColor", disabled_color);
}
if let Some(focus_color) = &self.focus_color {
properties.field("focusColor", focus_color);
}
if let Some(hover_color) = &self.hover_color {
properties.field("hoverColor", hover_color);
}
if let Some(highlight_color) = &self.highlight_color {
properties.field("highlightColor", highlight_color);
}
if let Some(splash_color) = &self.splash_color {
properties.field("splashColor", splash_color);
}
if self.color_scheme.is_some() {
properties.field("colorScheme", &"ColorScheme");
}
if let Some(material_tap_target_size) = &self.material_tap_target_size {
properties.field("materialTapTargetSize", material_tap_target_size);
}
properties.finish()
}
}
impl waft_foundation::Diagnosticable for ButtonThemeData {
fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
let default_theme = ButtonThemeData::default();
properties.add(
EnumProperty::<ButtonTextTheme>::new("textTheme", Some(self.text_theme))
.default_value(Some(default_theme.text_theme)),
);
properties.add(
DoubleProperty::new("minWidth", self.min_width)
.default_value(Some(default_theme.min_width)),
);
properties.add(
DoubleProperty::new("height", self.height).default_value(Some(default_theme.height)),
);
properties.add(
DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", Some(self.padding()))
.default_value(Some(default_theme.padding())),
);
properties.add(
DiagnosticsProperty::<ShapeBorderRef>::new("shape", Some(self.shape()))
.default_value(Some(default_theme.shape())),
);
properties.add(
FlagProperty::new("alignedDropdown", self.aligned_dropdown)
.default_value(Some(default_theme.aligned_dropdown))
.if_true("dropdown width matches button"),
);
properties.add(ColorProperty::new("buttonColor", self.button_color).default_value(None));
properties
.add(ColorProperty::new("disabledColor", self.disabled_color).default_value(None));
properties.add(ColorProperty::new("focusColor", self.focus_color).default_value(None));
properties.add(ColorProperty::new("hoverColor", self.hover_color).default_value(None));
properties
.add(ColorProperty::new("highlightColor", self.highlight_color).default_value(None));
properties.add(ColorProperty::new("splashColor", self.splash_color).default_value(None));
properties.add(
DiagnosticsProperty::<ColorScheme>::new("colorScheme", self.color_scheme.clone())
.default_value(default_theme.color_scheme.clone()),
);
properties.add(
DiagnosticsProperty::<waft_foundation::DartEnum<MaterialTapTargetSize>>::new(
"materialTapTargetSize",
self.material_tap_target_size.map(waft_foundation::DartEnum),
)
.default_value(None),
);
}
}
impl std::fmt::Display for ButtonThemeData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&waft_foundation::Diagnosticable::to_string(self))
}
}
#[cfg(test)]
mod tests {
use waft_painting::StadiumBorder;
use super::*;
fn rounded(radius: f64) -> ShapeBorderRef {
ShapeBorderRef::new(RoundedRectangleBorder::new(
BorderSide::NONE,
BorderRadiusGeometry::all(Radius::circular(radius)),
))
}
fn rounded_rectangle_border() -> ShapeBorderRef {
ShapeBorderRef::new(RoundedRectangleBorder::new(
BorderSide::NONE,
BorderRadiusGeometry::ZERO,
))
}
#[test]
fn a_new_button_theme_data_has_dart_defaults() {
let theme = ButtonThemeData::new();
assert_eq!(theme.text_theme, ButtonTextTheme::Normal);
assert_eq!(
theme.constraints(),
BoxConstraints::new().min_width(88.0).min_height(36.0)
);
assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
assert!(!theme.aligned_dropdown);
assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Padded);
}
#[test]
fn the_given_values_override_the_defaults() {
let theme = ButtonThemeData::new()
.with_text_theme(ButtonTextTheme::Primary)
.with_min_width(100.0)
.with_height(200.0)
.with_padding(EdgeInsetsGeometry::ZERO)
.with_shape(rounded_rectangle_border())
.with_aligned_dropdown(true);
assert_eq!(theme.text_theme, ButtonTextTheme::Primary);
assert_eq!(
theme.constraints(),
BoxConstraints::new().min_width(100.0).min_height(200.0)
);
assert_eq!(theme.padding(), EdgeInsetsGeometry::ZERO);
assert_eq!(Some(theme.shape()), Some(rounded_rectangle_border()));
assert!(theme.aligned_dropdown);
}
#[test]
fn copy_with_keeps_every_value_and_replaces_the_given_ones() {
let theme = ButtonThemeData::new().copy_with();
assert_eq!(theme.text_theme, ButtonTextTheme::Normal);
assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Padded);
assert_eq!(
theme.constraints(),
BoxConstraints::new().min_width(88.0).min_height(36.0)
);
assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
assert!(!theme.aligned_dropdown);
assert!(theme.color_scheme.is_none());
let theme = ButtonThemeData::new()
.copy_with()
.with_text_theme(ButtonTextTheme::Primary)
.with_layout_behavior(ButtonBarLayoutBehavior::Constrained)
.with_min_width(100.0)
.with_height(200.0)
.with_padding(EdgeInsetsGeometry::ZERO)
.with_shape(StadiumBorder::new(BorderSide::NONE))
.with_aligned_dropdown(true)
.with_color_scheme(ColorScheme::dark())
.with_material_tap_target_size(MaterialTapTargetSize::ShrinkWrap);
assert_eq!(theme.text_theme, ButtonTextTheme::Primary);
assert_eq!(theme.layout_behavior, ButtonBarLayoutBehavior::Constrained);
assert_eq!(
theme.constraints(),
BoxConstraints::new().min_width(100.0).min_height(200.0)
);
assert_eq!(theme.padding(), EdgeInsetsGeometry::ZERO);
let stadium: ShapeBorderRef = ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE));
assert_eq!(Some(theme.shape()), Some(stadium));
assert!(theme.aligned_dropdown);
assert_eq!(theme.color_scheme, Some(ColorScheme::dark()));
}
#[test]
fn a_copy_keeps_the_padding_and_shape_of_the_original_text_theme() {
let theme = ButtonThemeData::new()
.copy_with()
.with_text_theme(ButtonTextTheme::Primary);
assert_eq!(theme.padding(), EdgeInsetsGeometry::symmetric(0.0, 16.0));
assert_eq!(Some(theme.shape()), Some(rounded(2.0)));
assert_ne!(
theme,
ButtonThemeData::new().with_text_theme(ButtonTextTheme::Primary)
);
}
}