use std::{
cell::RefCell,
collections::{HashMap, hash_map::DefaultHasher},
hash::{Hash, Hasher},
panic::Location,
sync::{Arc, Weak},
};
use super::{
color_picker::{ColorFormat, ColorPicker},
color_swatch::{ColorSwatch, ColorSwatchPart, ColorSwatchSize},
field::{FieldControl, InField},
icon::Icon,
icons, names,
part_style::{FontFamily, Length, PartStyle},
popover::{Popover, PopoverPart},
recipe::{Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::fading,
text_box::{self, BoxStates, Judgment, TextBoxSize},
theme::{Themed, current_theme},
};
use crate::{
app::{
ctx::Placement,
events::{KeyboardEvent, MouseEvent},
theme::{ControlSize, IconSize, PaletteColor, RadiusSize, Theme},
},
components::{self, Row, Stack},
core::{ElementRef, Signal, SignalValue},
eyedropper::EyeDropper,
layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::FontWeight},
node::{CursorIcon, Element, HitTestBehavior, color::Color, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorFieldPart {
Root,
Control,
Placeholder,
Swatch,
Trigger,
TriggerIcon,
Panel,
}
names!(ColorFieldPart {
Root => "root",
Control => "control",
Placeholder => "placeholder",
Swatch => "swatch",
Trigger => "trigger",
TriggerIcon => "trigger_icon",
Panel => "panel",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorFieldState {
Invalid,
Warning,
Valid,
ReadOnly,
Disabled,
FullWidth,
Open,
Fluid,
}
names!(ColorFieldState {
Invalid => "invalid",
Warning => "warning",
Valid => "valid",
ReadOnly => "read_only",
Disabled => "disabled",
FullWidth => "full_width",
Open => "open",
Fluid => "fluid",
});
pub type ColorFieldSize = TextBoxSize;
pub type ColorFieldRenderer = Arc<dyn Fn(ColorFieldView) -> Element + Send + Sync>;
pub trait FieldColor: Copy + PartialEq + Send + Sync + SignalValue + 'static {
fn color(self) -> Option<Color>;
fn of(color: Color) -> Self;
fn none() -> Option<Self>;
}
impl FieldColor for Color {
fn color(self) -> Option<Color> {
Some(self)
}
fn of(color: Color) -> Self {
color
}
fn none() -> Option<Self> {
None
}
}
impl FieldColor for Option<Color> {
fn color(self) -> Option<Color> {
self
}
fn of(color: Color) -> Self {
Some(color)
}
fn none() -> Option<Self> {
Some(None)
}
}
#[derive(Clone)]
enum Bound<V: FieldColor> {
Value(Signal<V>),
Controlled(V),
}
#[derive(Clone)]
struct Words {
trigger: Arc<str>,
swatch: Arc<str>,
panel: Arc<str>,
}
pub struct ColorField<V: FieldColor = Color> {
bound: Bound<V>,
binding: usize,
at: Option<&'static Location<'static>>,
placeholder: Option<Arc<str>>,
boxed: BoxStates,
full_width: bool,
alpha: bool,
format: ColorFormat,
formats: Vec<ColorFormat>,
swatches: Vec<Color>,
placement: Placement,
eyedropper: bool,
words: Words,
on_change: Vec<Arc<dyn Fn(V) + Send + Sync>>,
name: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ColorField<Color> {
pub fn new(value: Signal<Color>) -> Self {
let binding = value.id();
Self::of(Bound::Value(value), binding, None)
}
}
impl ColorField<Option<Color>> {
pub fn optional(value: Signal<Option<Color>>) -> Self {
let binding = value.id();
Self::of(Bound::Value(value), binding, None)
}
}
impl<V: FieldColor> ColorField<V> {
#[track_caller]
pub fn controlled(value: V, on_change: impl Fn(V) + Send + Sync + 'static) -> Self {
let at = Location::caller();
Self::of(Bound::Controlled(value), controlled_binding(at, None), Some(at)).on_change(on_change)
}
fn of(bound: Bound<V>, binding: usize, at: Option<&'static Location<'static>>) -> Self {
Self {
bound,
binding,
at,
placeholder: None,
boxed: BoxStates::default(),
full_width: false,
alpha: false,
format: ColorFormat::Hex,
formats: Vec::new(),
swatches: Vec::new(),
placement: Placement::BottomStart,
eyedropper: true,
words: Words {
trigger: super::current_locale().fields.pick_from_screen.clone(),
swatch: super::current_locale().fields.choose_color.clone(),
panel: super::current_locale().fields.color.clone(),
},
on_change: Vec::new(),
name: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.placeholder = Some(Arc::from(placeholder));
self
}
pub fn label(mut self, label: &str) -> Self {
self.boxed.label = Some(Arc::from(label));
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.boxed.size = size.into();
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.boxed.invalid = invalid;
self
}
pub fn warning(mut self, warning: bool) -> Self {
self.boxed.warning = warning;
self
}
pub fn valid(mut self, valid: bool) -> Self {
self.boxed.valid = valid;
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.boxed.read_only = read_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.boxed.disabled = disabled;
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn alpha(mut self, alpha: bool) -> Self {
self.alpha = alpha;
self
}
pub fn format(mut self, format: ColorFormat) -> Self {
self.format = format;
self
}
pub fn formats(mut self, formats: impl IntoIterator<Item = ColorFormat>) -> Self {
self.formats = formats.into_iter().collect();
self
}
pub fn swatch(mut self, color: impl Into<Color>) -> Self {
self.swatches.push(color.into());
self
}
pub fn swatches(mut self, colors: impl IntoIterator<Item = impl Into<Color>>) -> Self {
self.swatches.extend(colors.into_iter().map(Into::into));
self
}
pub fn placement(mut self, placement: Placement) -> Self {
self.placement = placement;
self
}
pub fn eyedropper(mut self, eyedropper: bool) -> Self {
self.eyedropper = eyedropper;
self
}
pub fn trigger_label(mut self, label: &str) -> Self {
self.words.trigger = Arc::from(label);
self
}
pub fn swatch_label(mut self, label: &str) -> Self {
self.words.swatch = Arc::from(label);
self
}
pub fn panel_label(mut self, label: &str) -> Self {
self.words.panel = Arc::from(label);
self
}
pub fn on_change(mut self, handler: impl Fn(V) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.name = Some(name.into());
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 binding = match self.at {
Some(at) => controlled_binding(at, self.id.as_deref().or(self.key.as_deref())),
None => self.binding,
};
let kept = kept(binding);
let value = match &self.bound {
Bound::Value(signal) => signal.get(),
Bound::Controlled(value) => *value,
};
let open = kept.open.get() && !self.boxed.disabled && !self.boxed.read_only;
let bound = self.bound.clone();
let actions = Model {
bound: self.bound,
on_change: self.on_change,
}
.actions();
let value = match kept.picked.get() {
Some(color) => {
kept.picked.set(None);
if !self.boxed.disabled && !self.boxed.read_only {
(actions.choose)(color);
}
match &bound {
Bound::Value(signal) => signal.get_untracked(),
Bound::Controlled(value) => *value,
}
}
None => value,
};
let case = self
.boxed
.case(self.states.clone())
.state(ColorFieldState::FullWidth, self.full_width)
.state(ColorFieldState::Open, open);
let view = ColorFieldView {
value: value.color(),
placeholder: self.placeholder,
label: self.boxed.label.clone(),
invalid: self.boxed.judgment() == Some(Judgment::Invalid),
read_only: self.boxed.read_only,
disabled: self.boxed.disabled,
open,
alpha: self.alpha,
format: self.format,
formats: self.formats,
swatches: self.swatches,
placement: self.placement,
eyedropper: self.eyedropper && EyeDropper::is_supported(),
recipe: theme
.resolve::<ColorField>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
words: self.words,
text: Signal::new(value.color().map(display).unwrap_or_default()),
actions,
kept,
binding,
boxed: self.boxed,
name: self.name,
forced: self.forced,
id: self.id,
key: self.key,
};
match theme.renderer::<ColorField>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl<V: FieldColor> From<ColorField<V>> for Element {
fn from(field: ColorField<V>) -> Self {
field.build(¤t_theme())
}
}
impl<V: FieldColor> FieldControl for ColorField<V> {
fn in_field(mut self, field: &InField) -> Element {
self.boxed.in_field(field);
self.into()
}
fn has_fluid_form(&self) -> bool {
true
}
}
fn display(color: Color) -> String {
color.to_hex_upper()
}
fn controlled_binding(at: &'static Location<'static>, name: Option<&str>) -> usize {
let mut hasher = DefaultHasher::new();
(at.file(), at.line(), at.column(), name, "color_field").hash(&mut hasher);
(hasher.finish() as usize) | (1 << (usize::BITS - 1))
}
struct Kept {
open: Signal<bool>,
anchor: ElementRef,
picked: Signal<Option<Color>>,
}
thread_local! {
static KEPT: RefCell<HashMap<usize, Weak<Kept>>> = RefCell::new(HashMap::new());
}
fn kept(binding: usize) -> Arc<Kept> {
KEPT.with(|all| {
let mut all = all.borrow_mut();
if let Some(kept) = all.get(&binding).and_then(Weak::upgrade) {
return kept;
}
all.retain(|_, kept| kept.strong_count() > 0);
let kept = Arc::new(Kept {
open: Signal::new(false),
anchor: ElementRef::new(),
picked: Signal::new(None),
});
all.insert(binding, Arc::downgrade(&kept));
kept
})
}
#[derive(Clone)]
struct Model<V: FieldColor> {
bound: Bound<V>,
on_change: Vec<Arc<dyn Fn(V) + Send + Sync>>,
}
#[derive(Clone)]
struct Actions {
commit: Arc<dyn Fn(&Signal<String>) + Send + Sync>,
choose: Arc<dyn Fn(Color) + Send + Sync>,
}
impl<V: FieldColor> Model<V> {
fn current(&self) -> V {
match &self.bound {
Bound::Value(signal) => signal.get_untracked(),
Bound::Controlled(value) => *value,
}
}
fn write(&self, value: V) {
if self.current() == value {
return;
}
if let Bound::Value(signal) = &self.bound {
signal.set(value);
}
for handler in &self.on_change {
handler(value);
}
}
fn actions(self) -> Actions {
let chooser = self.clone();
Actions {
commit: Arc::new(move |text| self.commit(text)),
choose: Arc::new(move |color| chooser.write(V::of(color))),
}
}
fn commit(&self, text: &Signal<String>) {
let typed = text.get_untracked();
if typed.trim().is_empty() {
if let Some(none) = V::none() {
self.write(none);
}
} else if let Some(color) = Color::parse(&typed) {
self.write(V::of(color));
}
let shown = self.current().color().map(display).unwrap_or_default();
if text.get_untracked() != shown {
text.set(shown);
}
}
}
impl Kept {
fn set_open(&self, open: bool) {
if self.open.get_untracked() != open {
self.open.set(open);
}
}
fn toggle(&self) {
self.set_open(!self.open.get_untracked());
}
}
pub struct ColorFieldView {
pub value: Option<Color>,
pub placeholder: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub invalid: bool,
pub read_only: bool,
pub disabled: bool,
pub open: bool,
pub alpha: bool,
pub format: ColorFormat,
pub formats: Vec<ColorFormat>,
pub swatches: Vec<Color>,
pub placement: Placement,
pub eyedropper: bool,
pub recipe: ResolvedRecipe,
words: Words,
text: Signal<String>,
actions: Actions,
kept: Arc<Kept>,
binding: usize,
boxed: BoxStates,
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl ColorFieldView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn px(&self, length: Option<Length>) -> f32 {
match length.and_then(|length| length.resolve(self.theme())) {
Some(Dimension::Px(px)) => px,
_ => 0.0,
}
}
fn sub_id(&self, suffix: &str) -> Option<String> {
self.id.as_ref().map(|id| format!("{id}-{suffix}"))
}
fn swatch_size(&self) -> ColorSwatchSize {
if self.boxed.size == Name::from(TextBoxSize::Sm) {
ColorSwatchSize::Sm
} else if self.boxed.size == Name::from(TextBoxSize::Lg) {
ColorSwatchSize::Lg
} else {
ColorSwatchSize::Md
}
}
pub fn control(&self) -> components::TextInput {
let part = self.part(ColorFieldPart::Control);
let placeholder = self.part(ColorFieldPart::Placeholder);
let control = components::TextInput::new(self.text.clone())
.single_line()
.text_style(text_box::ink(self.theme(), &part.rest()))
.placeholder_style(text_box::ink(self.theme(), &part.rest().merged(&placeholder.rest())))
.part(&part)
.keep_text_while_focused(true);
let states = BoxStates {
role: Some("combobox"),
..self.boxed.clone()
};
let mut control = text_box::text_box_as(control, &states, Vec::new(), "combobox")
.describe("a11y_haspopup", "dialog")
.describe("a11y_expanded", if self.open { "true" } else { "false" });
if let Some(placeholder) = &self.placeholder {
control = control.placeholder(placeholder);
}
if !self.read_only && !self.disabled {
let (actions, kept, text) = (self.actions.clone(), self.kept.clone(), self.text.clone());
control = control.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || event.ctrl || event.meta || event.composing {
return;
}
match event.key.as_str() {
"ArrowDown" if !kept.open.get_untracked() => {
event.prevent_default();
kept.set_open(true);
}
"Enter" => (actions.commit)(&text),
_ => {}
}
});
let (blur, text) = (self.actions.clone(), self.text.clone());
control = control.on_blur(move || (blur.commit)(&text));
}
#[cfg(feature = "form")]
if let Some(name) = &self.name {
control = control.name(name.clone());
}
if let Some(id) = &self.id {
control = control.id(id.clone());
}
control
}
pub fn swatch(&self) -> Element {
let rules = self
.recipe
.lend("color_swatch")
.extend(&self.recipe.rules_for(ColorFieldPart::Swatch, ColorSwatchPart::Root));
let color = self.value.unwrap_or(Color::new(0, 0, 0, 0));
let inner = ColorSwatch::new(color)
.size(self.swatch_size())
.rules(&rules)
.build(self.theme());
let kept = self.kept.clone();
let mut swatch = components::Button::empty()
.focusable(false)
.disabled(self.disabled || self.read_only)
.describe("a11y_name", self.words.swatch.clone())
.describe("a11y_haspopup", "dialog")
.child(inner)
.on_click(move |_: MouseEvent| kept.toggle());
if let Some(id) = self.sub_id("swatch") {
swatch = swatch.id(id);
}
swatch.into()
}
pub fn trigger(&self) -> Option<Element> {
if !self.eyedropper {
return None;
}
let part = self.part(ColorFieldPart::Trigger);
let icon = self.part(ColorFieldPart::TriggerIcon);
let side = icon.rest().width.unwrap_or(Length::Icon(IconSize::Md));
let (picked, theme) = (self.kept.picked.clone(), self.theme().clone());
let mut trigger = components::Button::empty()
.justify(Justify::Center)
.align_items(Alignment::Center)
.part(&part)
.focusable(false)
.disabled(self.disabled || self.read_only)
.describe("a11y_name", self.words.trigger.clone())
.child(
Row::new()
.part(&icon)
.child(Icon::new(icons::EYEDROPPER).size(side).build(self.theme())),
)
.on_click(move |_: MouseEvent| {
let picked = picked.clone();
EyeDropper::new().theme(&theme).pick_then(move |answer| {
if let Ok(Some(color)) = answer {
picked.set(Some(color));
}
});
});
if let Some(id) = self.sub_id("trigger") {
trigger = trigger.id(id);
}
Some(trigger.into())
}
pub fn field(&self) -> Stack {
let root = self.part(ColorFieldPart::Root);
let swatch_side = match self.swatch_size() {
ColorSwatchSize::Sm => 20.0,
ColorSwatchSize::Md => 24.0,
ColorSwatchSize::Lg => 32.0,
};
let trigger = self.trigger();
let trigger_side = if trigger.is_some() {
self.px(self.part(ColorFieldPart::Trigger).rest().width)
} else {
0.0
};
let edge = 6.0;
Stack::new()
.stack_align(StackAlignment::CenterStart)
.part(&root)
.ref_element(self.kept.anchor.clone())
.child(
self
.control()
.padding_left(edge + swatch_side + 8.0)
.padding_right(edge + trigger_side),
)
.child(
Row::new()
.width(Dimension::Pct(100.0))
.padding_left(edge)
.padding_right(if trigger_side > 0.0 {
edge - (trigger_side - 16.0) / 2.0
} else {
edge
})
.padding_top(text_box::value_line(
&self.part(ColorFieldPart::Control).rest(),
self.theme(),
))
.align_items(Alignment::Center)
.justify(Justify::SpaceBetween)
.hit_test(HitTestBehavior::ContentOnly)
.child(self.swatch())
.with_children(trigger),
)
}
pub fn panel(&self) -> Element {
let choose = self.actions.choose.clone();
let color = self.value.unwrap_or(Color::new(0, 0, 0, 255));
let mut picker = ColorPicker::controlled(color, move |color| choose(color))
.kept_by(self.binding ^ 0x5bd1_e995)
.bare(true)
.alpha(self.alpha)
.format(self.format)
.formats(self.formats.clone())
.swatches(self.swatches.clone())
.eyedropper(false)
.disabled(self.disabled);
if let Some(id) = self.sub_id("picker") {
picker = picker.id(id);
}
let rules = self.recipe.rules_for(ColorFieldPart::Panel, PopoverPart::Panel);
let mut popover = Popover::new(self.kept.open.clone(), self.kept.anchor.clone())
.placement(self.placement)
.label(&self.words.panel)
.rules(&rules)
.child(picker.build(self.theme()));
if let Some(id) = self.sub_id("panel") {
popover = popover.id(id);
}
popover.into()
}
pub fn render(self) -> Element {
let mut root = Row::new()
.max_width(Dimension::Pct(100.0))
.child(self.field())
.child(self.panel());
if self.boxed.fluid {
root = root.width(Dimension::Pct(100.0));
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
impl crate::ui::Styled for ColorField {
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 ColorField {
const NAME: &'static str = "color_field";
const ROOT: &'static str = "control";
type Renderer = ColorFieldRenderer;
fn parts() -> crate::ui::Declared {
ColorFieldPart::declared()
}
fn states() -> crate::ui::Declared {
ColorFieldState::declared()
}
fn recipe() -> Recipe {
use ColorFieldPart::{Control, Panel, Placeholder, Root, Trigger, TriggerIcon};
use PaletteColor::{Foreground, Highlight, MutedForeground};
let recipe = Recipe::new()
.base(Root, |s| s.width(180.0))
.base(Control, |s| {
text_box::box_style(s)
.height(ControlSize::Md)
.foreground(Foreground)
.font_family(FontFamily::Mono)
.font_size(13.0)
.weight(FontWeight::Normal)
})
.base(Trigger, |s| {
fading(
s.square(24.0)
.radius(RadiusSize::Sm)
.foreground(MutedForeground)
.cursor(CursorIcon::Pointer),
)
})
.hovered(Trigger, |s| s.background(Highlight))
.base(TriggerIcon, |s| s.square(IconSize::Md))
.base(Panel, |s| s.width(Length::Auto).padding_x(0.0).padding_y(0.0).gap(0.0))
.state(ColorFieldState::FullWidth, Root, |s| s.width(Length::Fill))
.state(ColorFieldState::Disabled, Trigger, |s| s.cursor(CursorIcon::Default))
.state(ColorFieldState::ReadOnly, Trigger, |s| s.cursor(CursorIcon::Default))
.when(Selector::new().state(ColorFieldState::Open), Control, |s| {
s.border(text_box::edge(PaletteColor::Ring))
});
let recipe = text_box::box_sizes(recipe, Control, true);
let recipe = text_box::box_rules(recipe, Root, Control, Placeholder);
let open = Selector::new()
.state(ColorFieldState::Fluid)
.state(ColorFieldState::Open);
text_box::fluid_rules(recipe, Root, Control).when(open, Control, |s| text_box::fluid_line(s, PaletteColor::Ring))
}
}