lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `ColorPicker` and `TimeField`: styled native inputs with value normalization.

use dioxus::prelude::*;

use crate::class::compose;

/// Reads `count` hex digits into a byte, doubling single digits (`#abc` -> `aa bb cc`).
fn hex_channel(digits: &[u8]) -> Option<u8> {
    let value = |digit: u8| char::from(digit).to_digit(16);

    match digits {
        [single] => value(*single).and_then(|digit| u8::try_from(digit * 17).ok()),
        [high, low] => u8::try_from(value(*high)? * 16 + value(*low)?).ok(),
        _ => None,
    }
}

/// Splits `name(a, b, c)` or `name(a b c / alpha)` into its first three arguments.
fn function_arguments<'a>(value: &'a str, name: &str) -> Option<[&'a str; 3]> {
    let lower_prefix = value.get(..name.len())?;

    if !lower_prefix.eq_ignore_ascii_case(name) {
        return None;
    }

    let rest = value[name.len()..].trim_start();
    let rest = rest.strip_prefix('(')?.strip_suffix(')')?;
    let rest = rest.split('/').next()?;
    let mut parts = rest
        .split(|character: char| character == ',' || character.is_whitespace())
        .filter(|part| !part.is_empty());
    let arguments = [parts.next()?, parts.next()?, parts.next()?];

    // An alpha channel after a comma is accepted and ignored; anything else is malformed.
    if parts.nth(1).is_some() {
        return None;
    }

    Some(arguments)
}

/// Parses a number with an optional unit suffix, rejecting anything that is not a plain decimal.
fn parse_number(value: &str, suffix: &str) -> Option<f64> {
    let number = value.strip_suffix(suffix).unwrap_or(value);

    if number.is_empty()
        || number.len() > 24
        || !number
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'.' | b'-' | b'+'))
    {
        return None;
    }

    number
        .parse::<f64>()
        .ok()
        .filter(|parsed| parsed.is_finite())
}

/// Rounds a clamped channel in `0.0..=255.0` to a byte.
fn to_byte(value: f64) -> u8 {
    // The value is clamped to 0..=255 first, so the cast cannot truncate or wrap.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let byte = value.clamp(0.0, 255.0).round() as u8;

    byte
}

fn rgb_channel(value: &str) -> Option<u8> {
    if let Some(percent) = parse_number(value, "%").filter(|_| value.ends_with('%')) {
        return Some(to_byte(percent * 2.55));
    }

    parse_number(value, "").map(to_byte)
}

fn hsl_to_rgb(hue: f64, saturation: f64, lightness: f64) -> [u8; 3] {
    let hue = hue.rem_euclid(360.0) / 360.0;
    let saturation = saturation.clamp(0.0, 1.0);
    let lightness = lightness.clamp(0.0, 1.0);
    let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
    let channel = |offset: f64| {
        let k = (offset + hue * 12.0).rem_euclid(12.0);
        let amount = chroma / 2.0 * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0);

        to_byte((lightness - amount) * 255.0)
    };

    [channel(0.0), channel(8.0), channel(4.0)]
}

/// Converts `#rgb`, `#rrggbb`, `rgb()`, or `hsl()` to the lowercase `#rrggbb` form a color
/// input accepts, with one linear scan. Returns `None` for anything else.
pub(crate) fn normalize_color_value(value: &str) -> Option<String> {
    let value = value.trim();

    if value.len() > 64 {
        return None;
    }

    let rgb = if let Some(hex) = value.strip_prefix('#') {
        let bytes = hex.as_bytes();

        match bytes.len() {
            3 | 4 => [
                hex_channel(&bytes[0..1])?,
                hex_channel(&bytes[1..2])?,
                hex_channel(&bytes[2..3])?,
            ],
            6 | 8 => [
                hex_channel(&bytes[0..2])?,
                hex_channel(&bytes[2..4])?,
                hex_channel(&bytes[4..6])?,
            ],
            _ => return None,
        }
    } else if let Some([red, green, blue]) =
        function_arguments(value, "rgba").or_else(|| function_arguments(value, "rgb"))
    {
        [rgb_channel(red)?, rgb_channel(green)?, rgb_channel(blue)?]
    } else if let Some([hue, saturation, lightness]) =
        function_arguments(value, "hsla").or_else(|| function_arguments(value, "hsl"))
    {
        let hue = parse_number(hue, "deg")?;
        let saturation = parse_number(saturation, "%")? / 100.0;
        let lightness = parse_number(lightness, "%")? / 100.0;

        hsl_to_rgb(hue, saturation, lightness)
    } else {
        return None;
    };

    Some(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]))
}

/// Props for [`ColorPicker`].
#[derive(Props, Clone, PartialEq)]
pub struct ColorPickerProps {
    /// The native input type. Defaults to `color`.
    #[props(default = "color".to_string(), into)]
    pub r#type: String,
    /// The color. `#rgb`, `#rrggbb`, `rgb()`, and `hsl()` values are converted to the `#rrggbb`
    /// form a color input needs; other values are passed through unchanged.
    #[props(into)]
    pub value: Option<String>,
    /// Called with the picked color as lowercase `#rrggbb`.
    pub on_value_change: Option<EventHandler<String>>,
    /// Fires on every edit.
    pub oninput: Option<EventHandler<FormEvent>>,
    /// Fires when the value is committed.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `id`, `name`, or `aria_label`.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// A native color input for brand swatches and color tokens.
///
/// Browsers and desktop webviews show their color dialog. Dioxus Native renders the value as a
/// plain field, so pair it with swatches or a text input there.
#[component]
pub fn ColorPicker(props: ColorPickerProps) -> Element {
    let class = compose([Some("ui-color-picker"), props.class.as_deref()]);
    let value = props
        .value
        .as_deref()
        .map(|value| normalize_color_value(value).unwrap_or_else(|| value.to_string()));
    let (oninput, onchange, on_value_change) =
        (props.oninput, props.onchange, props.on_value_change);

    rsx! {
        input {
            class,
            r#type: props.r#type,
            value,
            oninput: move |event: FormEvent| {
                if let Some(handler) = on_value_change
                    && let Some(color) = normalize_color_value(&event.value())
                {
                    handler.call(color);
                }

                if let Some(handler) = oninput {
                    handler.call(event);
                }
            },
            onchange: move |event| {
                if let Some(handler) = onchange {
                    handler.call(event);
                }
            },
            ..props.attributes,
        }
    }
}

/// Props for [`TimeField`].
#[derive(Props, Clone, PartialEq)]
pub struct TimeFieldProps {
    /// The native input type. Defaults to `time`.
    #[props(default = "time".to_string(), into)]
    pub r#type: String,
    /// Fires on every edit.
    pub oninput: Option<EventHandler<FormEvent>>,
    /// Fires when the value is committed.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `value`, `min`, `max`, or `step`.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// A native time input (`HH:MM`, or `HH:MM:SS` with a `step` below 60).
///
/// Browsers and desktop webviews show their time picker; Dioxus Native treats it as a text field.
#[component]
pub fn TimeField(props: TimeFieldProps) -> Element {
    let class = compose([Some("ui-input ui-time-field"), props.class.as_deref()]);
    let (oninput, onchange) = (props.oninput, props.onchange);

    rsx! {
        input {
            class,
            r#type: props.r#type,
            oninput: move |event| {
                if let Some(handler) = oninput {
                    handler.call(event);
                }
            },
            onchange: move |event| {
                if let Some(handler) = onchange {
                    handler.call(event);
                }
            },
            ..props.attributes,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::normalize_color_value;

    #[test]
    fn colors_normalize_to_lowercase_hex() {
        let color = |value: &str| normalize_color_value(value);
        assert_eq!(color("#3366FF").as_deref(), Some("#3366ff"));
        assert_eq!(color("#36f").as_deref(), Some("#3366ff"));
        assert_eq!(color(" #3366ff80 ").as_deref(), Some("#3366ff"));
        assert_eq!(color("rgb(51, 102, 255)").as_deref(), Some("#3366ff"));
        assert_eq!(color("RGB(100% 0% 0% / 50%)").as_deref(), Some("#ff0000"));
        assert_eq!(color("rgba(0,0,0,0.5)").as_deref(), Some("#000000"));
        assert_eq!(color("hsl(0, 100%, 50%)").as_deref(), Some("#ff0000"));
        assert_eq!(color("hsl(120deg 100% 25%)").as_deref(), Some("#008000"));
        assert_eq!(color("hsl(240, 100%, 50%)").as_deref(), Some("#0000ff"));
    }

    #[test]
    fn malformed_colors_are_rejected() {
        for value in [
            "",
            "#",
            "#12",
            "#12345",
            "#ggg",
            "red",
            "rgb(1,2)",
            "rgb(1,2,3,4,5)",
            "rgb(a,b,c)",
            "hsl(1,2)",
            "rgb(1,2,3",
        ] {
            assert_eq!(normalize_color_value(value), None, "{value}");
        }

        assert_eq!(normalize_color_value(&"#".repeat(100_000)), None);
        assert_eq!(
            normalize_color_value(&format!("rgb({})", "1,".repeat(50_000))),
            None
        );
    }
}