use std::sync::Arc;
use super::{
names,
part_style::{Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{OpacityLevel, PaletteColor, RadiusSize, Theme},
components::{Column, Row, Stack},
layout::layout_kind::Justify,
node::{
CursorIcon, Element, EventHandler, IntoMouseEventHandler, color::Color, dimension::Dimension, outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorSwatchPart {
Root,
Checker,
CheckerCell,
}
names!(ColorSwatchPart {
Root => "root",
Checker => "checker",
CheckerCell => "checker_cell",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorSwatchState {
Selected,
Round,
Pressable,
Disabled,
}
names!(ColorSwatchState {
Selected => "selected",
Round => "round",
Pressable => "pressable",
Disabled => "disabled",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColorSwatchSize {
Sm,
#[default]
Md,
Lg,
}
names!(ColorSwatchSize {
Sm => "sm",
Md => "md",
Lg => "lg",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ColorSwatchShape {
#[default]
Square,
Round,
}
pub type ColorSwatchRenderer = Arc<dyn Fn(ColorSwatchView) -> Element + Send + Sync>;
pub struct ColorSwatch {
color: Color,
label: Option<Arc<str>>,
size: Name,
shape: ColorSwatchShape,
selected: bool,
disabled: bool,
on_click: Vec<EventHandler<crate::app::events::MouseEvent>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ColorSwatch {
pub fn new(color: impl Into<Color>) -> Self {
Self {
color: color.into(),
label: None,
size: ColorSwatchSize::default().into(),
shape: ColorSwatchShape::default(),
selected: false,
disabled: false,
on_click: Vec::new(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn shape(mut self, shape: ColorSwatchShape) -> Self {
self.shape = shape;
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let pressable = !self.on_click.is_empty();
let case = Case {
variant: None,
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(ColorSwatchState::Selected, self.selected)
.state(ColorSwatchState::Round, self.shape == ColorSwatchShape::Round)
.state(ColorSwatchState::Pressable, pressable)
.state(ColorSwatchState::Disabled, self.disabled);
let view = ColorSwatchView {
color: self.color,
label: self.label.unwrap_or_else(|| Arc::from(self.color.to_hex_upper())),
selected: self.selected,
disabled: self.disabled,
recipe: theme
.resolve::<ColorSwatch>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
on_click: self.on_click,
forced: self.forced,
id: self.id,
key: self.key,
};
match theme.renderer::<ColorSwatch>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<ColorSwatch> for Element {
fn from(swatch: ColorSwatch) -> Self {
swatch.build(¤t_theme())
}
}
pub struct ColorSwatchView {
pub color: Color,
pub label: Arc<str>,
pub selected: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
on_click: Vec<EventHandler<crate::app::events::MouseEvent>>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ColorSwatchView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn fill(&self) -> Element {
let root = self.part(ColorSwatchPart::Root).rest();
let side = |length: Option<Length>| match length.and_then(|length| length.resolve(self.theme())) {
Some(Dimension::Px(px)) => px,
_ => 24.0,
};
let (width, height) = (side(root.width), side(root.height));
color_over_checker(
self.color,
width,
height,
&self.part(ColorSwatchPart::Checker),
&self.part(ColorSwatchPart::CheckerCell),
)
}
pub fn render(self) -> Element {
let part = self.part(ColorSwatchPart::Root);
let fill = self.fill();
if self.on_click.is_empty() {
let mut root = Row::new()
.part(&part)
.child(fill)
.describe("a11y_role", "img")
.describe("a11y_name", self.label.clone());
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
return root.into();
}
let mut root = pressable(&part, self.disabled)
.justify(Justify::Start)
.child(fill)
.describe("a11y_role", "button")
.describe("a11y_name", self.label.clone());
if self.selected {
root = root.describe("a11y_pressed", "true");
}
if !self.disabled {
for handler in &self.on_click {
root = root.on_click(handler.clone());
}
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
pub(crate) fn color_over_checker(
color: Color,
width: f32,
height: f32,
checker: &ResolvedPart,
cell: &ResolvedPart,
) -> Element {
let color_layer = Row::new().size(width, height).background(color);
if color.a() == 255 {
return color_layer.into();
}
Stack::new()
.size(width, height)
.child(checkerboard(width, height, checker, cell))
.child(color_layer)
.into()
}
pub(crate) fn checkerboard(width: f32, height: f32, checker: &ResolvedPart, cell: &ResolvedPart) -> Element {
let side = match cell.rest().width.and_then(|length| length.resolve(checker.theme())) {
Some(Dimension::Px(px)) if px > 0.0 => px,
_ => 4.0,
};
let (columns, rows) = ((width / side).ceil() as usize, (height / side).ceil() as usize);
let mut board = Column::new().size(width, height).part(checker);
for row in 0..rows {
let mut line = Row::new().height(side);
for column in 0..columns {
let square = Row::new().size(side, side);
line = line.child(if (row + column) % 2 == 1 {
square.part(cell)
} else {
square
});
}
board = board.child(line);
}
board.into()
}
impl crate::ui::Styled for ColorSwatch {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for ColorSwatch {
const NAME: &'static str = "color_swatch";
type Renderer = ColorSwatchRenderer;
fn parts() -> crate::ui::Declared {
ColorSwatchPart::declared()
}
fn states() -> crate::ui::Declared {
ColorSwatchState::declared()
}
fn recipe() -> Recipe {
use ColorSwatchPart::{Checker, CheckerCell, Root};
use PaletteColor::*;
Recipe::new()
.base(Root, |s| {
fading(s)
.square(24.0)
.radius(RadiusSize::Sm)
.border(crate::node::border::Border::inside(1.0, Border))
.cursor(CursorIcon::Default)
})
.base(Checker, |s| s.background(Background))
.base(CheckerCell, |s| s.square(4.0).background(Muted))
.size(ColorSwatchSize::Sm, Root, |s| s.square(20.0))
.size(ColorSwatchSize::Lg, Root, |s| s.square(32.0))
.state(ColorSwatchState::Round, Root, |s| s.radius(RadiusSize::Full))
.state(ColorSwatchState::Selected, Root, |s| {
s.outline(Outline::new(2.0, Foreground))
})
.state(ColorSwatchState::Pressable, Root, |s| s.cursor(CursorIcon::Pointer))
.focus_visible(Root, |s| s.focus_ring())
.state(ColorSwatchState::Disabled, Root, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
}
}