use std::sync::Arc;
use super::{
color_swatch::{ColorSwatch, ColorSwatchPart, ColorSwatchSize, ColorSwatchState, color_over_checker},
names,
part_style::{Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{ChangeHandler, Chosen, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
events::KeyboardEvent,
theme::{BorderSize, PaletteColor, RadiusSize, ShadowStyle, Theme},
},
components::{Column, Row},
core::{Signal, SignalValue},
layout::layout_kind::Justify,
node::{Element, FocusGroup, border::Border, color::Color, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwatchPickerPart {
Root,
Row,
Swatch,
}
names!(SwatchPickerPart {
Root => "root",
Row => "row",
Swatch => "swatch",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwatchPickerState {
Framed,
Invalid,
Disabled,
}
names!(SwatchPickerState {
Framed => "framed",
Invalid => "invalid",
Disabled => "disabled",
});
pub type SwatchPickerRenderer = Arc<dyn Fn(SwatchPickerView) -> Element + Send + Sync>;
#[derive(Clone)]
pub struct Swatch<T = Color> {
value: T,
color: Color,
label: Option<Arc<str>>,
disabled: bool,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Swatch<Color> {
pub fn new(color: impl Into<Color>) -> Self {
let color = color.into();
Self::of(color, color)
}
}
impl<T> Swatch<T> {
pub fn of(value: T, color: impl Into<Color>) -> Self {
Self {
value,
color: color.into(),
label: None,
disabled: false,
id: None,
key: None,
}
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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
}
fn map<U>(self, map: impl FnOnce(T) -> U) -> Swatch<U> {
Swatch {
value: map(self.value),
color: self.color,
label: self.label,
disabled: self.disabled,
id: self.id,
key: self.key,
}
}
}
impl From<Color> for Swatch<Color> {
fn from(color: Color) -> Self {
Self::new(color)
}
}
impl From<&str> for Swatch<Color> {
fn from(hex: &str) -> Self {
Self::new(Color::from_hex(hex))
}
}
pub struct SwatchPicker<T = Color> {
swatches: Vec<Swatch<T>>,
chosen: Chosen<T>,
on_change: Vec<ChangeHandler<T>>,
columns: usize,
framed: bool,
size: Name,
label: Option<Arc<str>>,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> SwatchPicker<T> {
fn of(chosen: Chosen<T>, swatches: impl IntoIterator<Item = impl Into<Swatch<T>>>) -> Self {
Self {
swatches: swatches.into_iter().map(Into::into).collect(),
chosen,
on_change: Vec::new(),
columns: 6,
framed: true,
size: ColorSwatchSize::default().into(),
label: None,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn new(value: Signal<T>, swatches: impl IntoIterator<Item = impl Into<Swatch<T>>>) -> Self
where
T: SignalValue,
{
Self::of(Chosen::one(value), swatches)
}
pub fn controlled(
value: T,
swatches: impl IntoIterator<Item = impl Into<Swatch<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
Self::of(Chosen::held_one(value), swatches).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> SwatchPicker<Option<T>> {
pub fn optional(value: Signal<Option<T>>, swatches: impl IntoIterator<Item = impl Into<Swatch<T>>>) -> Self
where
Option<T>: SignalValue,
{
Self::of(
Chosen::one(value),
swatches
.into_iter()
.map(|swatch| Into::<Swatch<T>>::into(swatch).map(Some)),
)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> SwatchPicker<T> {
pub fn on_change(mut self, handler: impl Fn(&T) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn swatches(mut self, swatches: impl IntoIterator<Item = impl Into<Swatch<T>>>) -> Self {
self.swatches.extend(swatches.into_iter().map(Into::into));
self
}
pub fn swatch(mut self, swatch: impl Into<Swatch<T>>) -> Self {
self.swatches.push(swatch.into());
self
}
pub fn columns(mut self, columns: usize) -> Self {
self.columns = columns.max(1);
self
}
pub fn framed(mut self, framed: bool) -> Self {
self.framed = framed;
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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 mut case = Case::new()
.breakpoint(super::current_breakpoint())
.state(SwatchPickerState::Framed, self.framed)
.state(SwatchPickerState::Invalid, self.invalid)
.state(SwatchPickerState::Disabled, self.disabled);
for state in &self.states {
case = case.state(state.clone(), true);
}
let recipe = theme
.resolve::<SwatchPicker>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let swatch_rules = recipe.rules_for(SwatchPickerPart::Swatch, ColorSwatchPart::Root);
let handlers: Arc<[ChangeHandler<T>]> = self.on_change.into();
let items: Vec<SwatchItem> = self
.swatches
.into_iter()
.enumerate()
.map(|(index, swatch)| {
let selected = self.chosen.has(&swatch.value);
let disabled = self.disabled || swatch.disabled;
let swatch_case = Case::new()
.size(self.size.clone())
.breakpoint(super::current_breakpoint())
.state(ColorSwatchState::Selected, selected)
.state(ColorSwatchState::Pressable, true)
.state(ColorSwatchState::Disabled, disabled);
SwatchItem {
color: swatch.color,
label: swatch.label.unwrap_or_else(|| Arc::from(swatch.color.to_hex_upper())),
selected,
disabled,
recipe: theme
.resolve::<ColorSwatch>(&swatch_case, Some(&swatch_rules))
.owned_by(swatch.id.as_ref()),
choose: self.chosen.picker(swatch.value, handlers.clone()),
id: swatch.id,
key: swatch.key.unwrap_or_else(|| Arc::from(format!("swatch-{index}"))),
}
})
.collect();
let view = SwatchPickerView {
swatches: items,
columns: self.columns,
label: self.label,
invalid: self.invalid,
disabled: self.disabled,
recipe,
forced: self.forced,
id: self.id,
key: self.key,
};
match theme.renderer::<SwatchPicker>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> From<SwatchPicker<T>> for Element {
fn from(picker: SwatchPicker<T>) -> Self {
picker.build(¤t_theme())
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> super::FieldControl for SwatchPicker<T> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::text_box::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
}
pub struct SwatchItem {
pub color: Color,
pub label: Arc<str>,
pub selected: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
choose: Arc<dyn Fn() + Send + Sync>,
id: Option<Arc<str>>,
key: Arc<str>,
}
pub struct SwatchPickerView {
pub swatches: Vec<SwatchItem>,
pub columns: usize,
pub label: Option<Arc<str>>,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SwatchPickerView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn entry(&self) -> Option<usize> {
self
.swatches
.iter()
.position(|swatch| swatch.selected && !swatch.disabled)
.or_else(|| self.swatches.iter().position(|swatch| !swatch.disabled))
}
fn vertical(&self, index: usize, by: isize) -> Option<usize> {
let mut at = index as isize;
loop {
at += by * self.columns as isize;
let swatch = self.swatches.get(usize::try_from(at).ok()?)?;
if !swatch.disabled {
return Some(at as usize);
}
}
}
pub fn swatch(&self, index: usize) -> Element {
let item = &self.swatches[index];
let forced = self.forced.filter(|_| self.entry() == Some(index));
let part = |part: ColorSwatchPart| item.recipe.part(part).forced(forced);
let root = part(ColorSwatchPart::Root);
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.rest().width), side(root.rest().height));
let mut swatch = pressable(&root, item.disabled)
.justify(Justify::Start)
.key(item.key.clone())
.focus_entry(self.entry() == Some(index))
.child(color_over_checker(
item.color,
width,
height,
&part(ColorSwatchPart::Checker),
&part(ColorSwatchPart::CheckerCell),
))
.describe("a11y_role", "option")
.describe("a11y_name", item.label.clone())
.describe("a11y_selected", if item.selected { "true" } else { "false" });
if item.disabled {
swatch = swatch.describe("a11y_disabled", "true");
} else {
let choose = item.choose.clone();
swatch = swatch.on_click(move |_| choose());
}
let keys: Vec<Option<Arc<str>>> = [-1, 1]
.into_iter()
.map(|by| self.vertical(index, by).map(|to| self.swatches[to].key.clone()))
.collect();
let (up, down) = (keys[0].clone(), keys[1].clone());
swatch = swatch.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || event.ctrl || event.alt || event.meta || event.shift || event.composing {
return;
}
let to = match event.key.as_str() {
"ArrowUp" => &up,
"ArrowDown" => &down,
_ => return,
};
match to {
Some(key) => event.focus_key(key.clone()),
None => event.prevent_default(),
}
});
if let Some(id) = &item.id {
swatch = swatch.id(id.clone());
}
swatch.into()
}
pub fn root(&self) -> Column {
let mut root = Column::new()
.part(&self.part(SwatchPickerPart::Root))
.focus_group(FocusGroup::horizontal().one_stop(true).wrap(false))
.describe("a11y_role", "listbox");
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if self.invalid {
root = root.describe("a11y_invalid", "true");
}
if self.disabled {
root = root.describe("a11y_disabled", "true");
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn render(self) -> Element {
let mut root = self.root();
let count = self.swatches.len();
let mut start = 0;
while start < count {
let end = (start + self.columns).min(count);
let mut row = Row::new().part(&self.part(SwatchPickerPart::Row));
for index in start..end {
row = row.child(self.swatch(index));
}
root = root.child(row);
start = end;
}
root.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> crate::ui::Styled for SwatchPicker<T> {
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<T: Send + Sync + 'static> Themed for SwatchPicker<T> {
const NAME: &'static str = "swatch_picker";
type Renderer = SwatchPickerRenderer;
fn parts() -> crate::ui::Declared {
SwatchPickerPart::declared()
}
fn states() -> crate::ui::Declared {
SwatchPickerState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Border as Edge, Destructive, Popover, PopoverForeground, StatePressed};
use SwatchPickerPart::{Root, Row, Swatch};
use SwatchPickerState::{Framed, Invalid};
Recipe::new()
.base(Root, |s| s.gap(6.0))
.base(Row, |s| s.gap(6.0))
.base(Swatch, |s| s.border(Border::inside(BorderSize::Sm, StatePressed)))
.state(Framed, Root, |s| {
s.padding_x(10.0)
.padding_y(10.0)
.radius(RadiusSize::Lg)
.background(Popover)
.foreground(PopoverForeground)
.border(Border::inside(BorderSize::Sm, Edge))
.shadow(ShadowStyle::Md)
})
.when(super::recipe::Selector::new().state(Framed).state(Invalid), Root, |s| {
s.border(Border::inside(BorderSize::Sm, Destructive))
})
}
}