Skip to main content

lumen_dioxus/pickers/
native_inputs.rs

1//! `ColorPicker` and `TimeField`: styled native inputs with value normalization.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6
7/// Reads `count` hex digits into a byte, doubling single digits (`#abc` -> `aa bb cc`).
8fn hex_channel(digits: &[u8]) -> Option<u8> {
9    let value = |digit: u8| char::from(digit).to_digit(16);
10
11    match digits {
12        [single] => value(*single).and_then(|digit| u8::try_from(digit * 17).ok()),
13        [high, low] => u8::try_from(value(*high)? * 16 + value(*low)?).ok(),
14        _ => None,
15    }
16}
17
18/// Splits `name(a, b, c)` or `name(a b c / alpha)` into its first three arguments.
19fn function_arguments<'a>(value: &'a str, name: &str) -> Option<[&'a str; 3]> {
20    let lower_prefix = value.get(..name.len())?;
21
22    if !lower_prefix.eq_ignore_ascii_case(name) {
23        return None;
24    }
25
26    let rest = value[name.len()..].trim_start();
27    let rest = rest.strip_prefix('(')?.strip_suffix(')')?;
28    let rest = rest.split('/').next()?;
29    let mut parts = rest
30        .split(|character: char| character == ',' || character.is_whitespace())
31        .filter(|part| !part.is_empty());
32    let arguments = [parts.next()?, parts.next()?, parts.next()?];
33
34    // An alpha channel after a comma is accepted and ignored; anything else is malformed.
35    if parts.nth(1).is_some() {
36        return None;
37    }
38
39    Some(arguments)
40}
41
42/// Parses a number with an optional unit suffix, rejecting anything that is not a plain decimal.
43fn parse_number(value: &str, suffix: &str) -> Option<f64> {
44    let number = value.strip_suffix(suffix).unwrap_or(value);
45
46    if number.is_empty()
47        || number.len() > 24
48        || !number
49            .bytes()
50            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'.' | b'-' | b'+'))
51    {
52        return None;
53    }
54
55    number
56        .parse::<f64>()
57        .ok()
58        .filter(|parsed| parsed.is_finite())
59}
60
61/// Rounds a clamped channel in `0.0..=255.0` to a byte.
62fn to_byte(value: f64) -> u8 {
63    // The value is clamped to 0..=255 first, so the cast cannot truncate or wrap.
64    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
65    let byte = value.clamp(0.0, 255.0).round() as u8;
66
67    byte
68}
69
70fn rgb_channel(value: &str) -> Option<u8> {
71    if let Some(percent) = parse_number(value, "%").filter(|_| value.ends_with('%')) {
72        return Some(to_byte(percent * 2.55));
73    }
74
75    parse_number(value, "").map(to_byte)
76}
77
78fn hsl_to_rgb(hue: f64, saturation: f64, lightness: f64) -> [u8; 3] {
79    let hue = hue.rem_euclid(360.0) / 360.0;
80    let saturation = saturation.clamp(0.0, 1.0);
81    let lightness = lightness.clamp(0.0, 1.0);
82    let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
83    let channel = |offset: f64| {
84        let k = (offset + hue * 12.0).rem_euclid(12.0);
85        let amount = chroma / 2.0 * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0);
86
87        to_byte((lightness - amount) * 255.0)
88    };
89
90    [channel(0.0), channel(8.0), channel(4.0)]
91}
92
93/// Converts `#rgb`, `#rrggbb`, `rgb()`, or `hsl()` to the lowercase `#rrggbb` form a color
94/// input accepts, with one linear scan. Returns `None` for anything else.
95pub(crate) fn normalize_color_value(value: &str) -> Option<String> {
96    let value = value.trim();
97
98    if value.len() > 64 {
99        return None;
100    }
101
102    let rgb = if let Some(hex) = value.strip_prefix('#') {
103        let bytes = hex.as_bytes();
104
105        match bytes.len() {
106            3 | 4 => [
107                hex_channel(&bytes[0..1])?,
108                hex_channel(&bytes[1..2])?,
109                hex_channel(&bytes[2..3])?,
110            ],
111            6 | 8 => [
112                hex_channel(&bytes[0..2])?,
113                hex_channel(&bytes[2..4])?,
114                hex_channel(&bytes[4..6])?,
115            ],
116            _ => return None,
117        }
118    } else if let Some([red, green, blue]) =
119        function_arguments(value, "rgba").or_else(|| function_arguments(value, "rgb"))
120    {
121        [rgb_channel(red)?, rgb_channel(green)?, rgb_channel(blue)?]
122    } else if let Some([hue, saturation, lightness]) =
123        function_arguments(value, "hsla").or_else(|| function_arguments(value, "hsl"))
124    {
125        let hue = parse_number(hue, "deg")?;
126        let saturation = parse_number(saturation, "%")? / 100.0;
127        let lightness = parse_number(lightness, "%")? / 100.0;
128
129        hsl_to_rgb(hue, saturation, lightness)
130    } else {
131        return None;
132    };
133
134    Some(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))
135}
136
137/// Props for [`ColorPicker`].
138#[derive(Props, Clone, PartialEq)]
139pub struct ColorPickerProps {
140    /// The native input type. Defaults to `color`.
141    #[props(default = "color".to_string(), into)]
142    pub r#type: String,
143    /// The color. `#rgb`, `#rrggbb`, `rgb()`, and `hsl()` values are converted to the `#rrggbb`
144    /// form a color input needs; other values are passed through unchanged.
145    #[props(into)]
146    pub value: Option<String>,
147    /// Called with the picked color as lowercase `#rrggbb`.
148    pub on_value_change: Option<EventHandler<String>>,
149    /// Fires on every edit.
150    pub oninput: Option<EventHandler<FormEvent>>,
151    /// Fires when the value is committed.
152    pub onchange: Option<EventHandler<FormEvent>>,
153    /// Extra classes appended after the Lumen class.
154    #[props(into)]
155    pub class: Option<String>,
156    /// Any other `<input>` or global attribute, such as `id`, `name`, or `aria_label`.
157    #[props(extends = GlobalAttributes, extends = input)]
158    pub attributes: Vec<Attribute>,
159}
160
161/// A native color input for brand swatches and color tokens.
162///
163/// Browsers and desktop webviews show their color dialog. Dioxus Native renders the value as a
164/// plain field, so pair it with swatches or a text input there.
165#[component]
166pub fn ColorPicker(props: ColorPickerProps) -> Element {
167    let class = compose([Some("ui-color-picker"), props.class.as_deref()]);
168    let value = props
169        .value
170        .as_deref()
171        .map(|value| normalize_color_value(value).unwrap_or_else(|| value.to_string()));
172    let (oninput, onchange, on_value_change) =
173        (props.oninput, props.onchange, props.on_value_change);
174
175    rsx! {
176        input {
177            class,
178            r#type: props.r#type,
179            value,
180            oninput: move |event: FormEvent| {
181                if let Some(handler) = on_value_change
182                    && let Some(color) = normalize_color_value(&event.value())
183                {
184                    handler.call(color);
185                }
186
187                if let Some(handler) = oninput {
188                    handler.call(event);
189                }
190            },
191            onchange: move |event| {
192                if let Some(handler) = onchange {
193                    handler.call(event);
194                }
195            },
196            ..props.attributes,
197        }
198    }
199}
200
201/// Props for [`TimeField`].
202#[derive(Props, Clone, PartialEq)]
203pub struct TimeFieldProps {
204    /// The native input type. Defaults to `time`.
205    #[props(default = "time".to_string(), into)]
206    pub r#type: String,
207    /// Fires on every edit.
208    pub oninput: Option<EventHandler<FormEvent>>,
209    /// Fires when the value is committed.
210    pub onchange: Option<EventHandler<FormEvent>>,
211    /// Extra classes appended after the Lumen classes.
212    #[props(into)]
213    pub class: Option<String>,
214    /// Any other `<input>` or global attribute, such as `value`, `min`, `max`, or `step`.
215    #[props(extends = GlobalAttributes, extends = input)]
216    pub attributes: Vec<Attribute>,
217}
218
219/// A native time input (`HH:MM`, or `HH:MM:SS` with a `step` below 60).
220///
221/// Browsers and desktop webviews show their time picker; Dioxus Native treats it as a text field.
222#[component]
223pub fn TimeField(props: TimeFieldProps) -> Element {
224    let class = compose([Some("ui-input ui-time-field"), props.class.as_deref()]);
225    let (oninput, onchange) = (props.oninput, props.onchange);
226
227    rsx! {
228        input {
229            class,
230            r#type: props.r#type,
231            oninput: move |event| {
232                if let Some(handler) = oninput {
233                    handler.call(event);
234                }
235            },
236            onchange: move |event| {
237                if let Some(handler) = onchange {
238                    handler.call(event);
239                }
240            },
241            ..props.attributes,
242        }
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::normalize_color_value;
249
250    #[test]
251    fn colors_normalize_to_lowercase_hex() {
252        let color = |value: &str| normalize_color_value(value);
253        assert_eq!(color("#3366FF").as_deref(), Some("#3366ff"));
254        assert_eq!(color("#36f").as_deref(), Some("#3366ff"));
255        assert_eq!(color(" #3366ff80 ").as_deref(), Some("#3366ff"));
256        assert_eq!(color("rgb(51, 102, 255)").as_deref(), Some("#3366ff"));
257        assert_eq!(color("RGB(100% 0% 0% / 50%)").as_deref(), Some("#ff0000"));
258        assert_eq!(color("rgba(0,0,0,0.5)").as_deref(), Some("#000000"));
259        assert_eq!(color("hsl(0, 100%, 50%)").as_deref(), Some("#ff0000"));
260        assert_eq!(color("hsl(120deg 100% 25%)").as_deref(), Some("#008000"));
261        assert_eq!(color("hsl(240, 100%, 50%)").as_deref(), Some("#0000ff"));
262    }
263
264    #[test]
265    fn malformed_colors_are_rejected() {
266        for value in [
267            "",
268            "#",
269            "#12",
270            "#12345",
271            "#ggg",
272            "red",
273            "rgb(1,2)",
274            "rgb(1,2,3,4,5)",
275            "rgb(a,b,c)",
276            "hsl(1,2)",
277            "rgb(1,2,3",
278        ] {
279            assert_eq!(normalize_color_value(value), None, "{value}");
280        }
281
282        assert_eq!(normalize_color_value(&"#".repeat(100_000)), None);
283        assert_eq!(
284            normalize_color_value(&format!("rgb({})", "1,".repeat(50_000))),
285            None
286        );
287    }
288}