lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `DeviceFrame`: a phone, tablet, laptop, or desktop frame around a screenshot or live content.
// cspell:words hexdigit onresize

use dioxus::prelude::*;

use super::util::js_number;
use crate::class::compose;

/// The device a [`DeviceFrame`] draws.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeviceFrameDevice {
    /// A laptop, 1280 by 800.
    #[default]
    Laptop,
    /// A desktop monitor, 1440 by 900.
    Desktop,
    /// An iPhone, 390 by 844.
    Iphone,
    /// An Android phone, 412 by 915.
    Android,
    /// A tablet, 820 by 1180.
    Tablet,
    /// A `MacBook` Pro, 1280 by 800.
    MacbookPro,
    /// A `MacBook` Air, 1280 by 800.
    MacbookAir,
    /// An iMac, 1440 by 810.
    Imac,
    /// A Pixel phone, 412 by 915.
    Pixel,
    /// An iPad Pro, 834 by 1194.
    IpadPro,
}

impl DeviceFrameDevice {
    /// The `data-device` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Laptop => "laptop",
            Self::Desktop => "desktop",
            Self::Iphone => "iphone",
            Self::Android => "android",
            Self::Tablet => "tablet",
            Self::MacbookPro => "macbook-pro",
            Self::MacbookAir => "macbook-air",
            Self::Imac => "imac",
            Self::Pixel => "pixel",
            Self::IpadPro => "ipad-pro",
        }
    }

    /// The default screen size in CSS pixels, `(width, height)`.
    pub fn screen_size(self) -> (f64, f64) {
        match self {
            Self::Laptop | Self::MacbookPro | Self::MacbookAir => (1280.0, 800.0),
            Self::Desktop => (1440.0, 900.0),
            Self::Iphone => (390.0, 844.0),
            Self::Android | Self::Pixel => (412.0, 915.0),
            Self::Tablet => (820.0, 1180.0),
            Self::Imac => (1440.0, 810.0),
            Self::IpadPro => (834.0, 1194.0),
        }
    }
}

/// Orientation of a [`DeviceFrame`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DeviceFrameOrientation {
    /// Taller than wide.
    Portrait,
    /// Wider than tall.
    Landscape,
}

impl DeviceFrameOrientation {
    /// The `data-orientation` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Portrait => "portrait",
            Self::Landscape => "landscape",
        }
    }
}

/// Finish of a [`DeviceFrame`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DeviceFrameTone {
    /// Light hardware.
    Light,
    /// Dark hardware.
    #[default]
    Dark,
}

impl DeviceFrameTone {
    /// The `data-tone` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Light => "light",
            Self::Dark => "dark",
        }
    }
}

/// `white`, `black`, or a 3, 4, 6, or 8 digit hex color; anything else is dropped so it can't
/// inject CSS into the inline style.
pub(crate) fn resolve_device_frame_color(color: &str) -> Option<&str> {
    if color == "white" || color == "black" {
        return Some(color);
    }

    let digits = color.strip_prefix('#')?;

    ([3, 4, 6, 8].contains(&digits.len()) && digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
        .then_some(color)
}

/// The screen size, like `resolveLumenDeviceFrame`: custom sizes from 1 to 16384 pixels replace the
/// defaults, and an orientation swaps them so the longer side matches it.
pub(crate) fn resolve_device_frame_size(
    device: DeviceFrameDevice,
    orientation: Option<DeviceFrameOrientation>,
    width: Option<f64>,
    height: Option<f64>,
) -> (f64, f64) {
    let (default_width, default_height) = device.screen_size();
    let dimension = |value: Option<f64>, fallback: f64| {
        value
            .filter(|value| value.is_finite() && (1.0..=16384.0).contains(value))
            .unwrap_or(fallback)
    };
    let first = dimension(width, default_width);
    let second = dimension(height, default_height);

    match orientation {
        None => (first, second),
        Some(DeviceFrameOrientation::Landscape) => (first.max(second), first.min(second)),
        Some(DeviceFrameOrientation::Portrait) => (first.min(second), first.max(second)),
    }
}

/// Props for [`DeviceFrame`].
#[derive(Props, Clone, PartialEq)]
pub struct DeviceFrameProps {
    /// The device.
    #[props(default)]
    pub device: DeviceFrameDevice,
    /// Forces portrait or landscape.
    pub orientation: Option<DeviceFrameOrientation>,
    /// Hardware finish.
    #[props(default)]
    pub tone: DeviceFrameTone,
    /// Hardware color: `white`, `black`, or a hex color.
    #[props(into)]
    pub color: Option<String>,
    /// Screen width in CSS pixels, from 1 to 16384.
    pub screen_width: Option<f64>,
    /// Screen height in CSS pixels, from 1 to 16384.
    pub screen_height: Option<f64>,
    /// Lets the screen content scroll. On by default.
    #[props(default = true)]
    pub scroll: bool,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// Screen content: an image, an `iframe`, or live markup.
    pub children: Element,
}

/// A device frame around a screenshot, an `iframe`, or live content.
///
/// On the web and desktop the screen measures itself and scales `iframe` content to the device
/// width; renderers without resize events show iframes at their natural size.
#[component]
pub fn DeviceFrame(props: DeviceFrameProps) -> Element {
    let (width, height) = resolve_device_frame_size(
        props.device,
        props.orientation,
        props.screen_width,
        props.screen_height,
    );
    let mut scale = use_signal(|| None::<f64>);
    let color = props
        .color
        .as_deref()
        .and_then(resolve_device_frame_color)
        .map(|color| format!("--ui-device-color: {color}"));
    let (width_text, height_text) = (js_number(width), js_number(height));
    let scale_text = scale().map_or_else(String::new, |scale| {
        format!("; --ui-device-frame-scale: {}", js_number(scale))
    });
    let screen_style = format!(
        "--ui-device-frame-height: {height_text}px; --ui-device-frame-width: {width_text}px; aspect-ratio: {width_text} / {height_text}{scale_text}"
    );
    let class = compose([Some("ui-device-frame"), props.class.as_deref()]);

    rsx! {
        div {
            class,
            "data-device": props.device.as_str(),
            "data-tone": props.tone.as_str(),
            "data-orientation": props.orientation.map(DeviceFrameOrientation::as_str),
            style: color,
            ..props.attributes,
            div { class: "ui-device-frame__shell",
                span { class: "ui-device-frame__hardware", aria_hidden: "true",
                    span { class: "ui-device-frame__action" }
                    span { class: "ui-device-frame__volume-up" }
                    span { class: "ui-device-frame__volume-down" }
                    span { class: "ui-device-frame__power" }
                    span { class: "ui-device-frame__rail-left" }
                    span { class: "ui-device-frame__rail-right" }
                }
                div { class: "ui-device-frame__glass",
                    span { aria_hidden: "true", class: "ui-device-frame__camera" }
                    div {
                        class: "ui-device-frame__screen",
                        "data-scroll": if props.scroll { "true" } else { "false" },
                        style: screen_style,
                        onresize: move |event: ResizeEvent| {
                            if let Ok(size) = event.get_content_box_size()
                                && size.width > 0.0
                            {
                                scale.set(Some(size.width / width));
                            }
                        },
                        {props.children}
                    }
                }
            }
            span { aria_hidden: "true", class: "ui-device-frame__base" }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        DeviceFrameDevice, DeviceFrameOrientation, resolve_device_frame_color,
        resolve_device_frame_size,
    };

    #[test]
    fn colors_are_bounded() {
        assert_eq!(resolve_device_frame_color("white"), Some("white"));
        assert_eq!(resolve_device_frame_color("#fff"), Some("#fff"));
        assert_eq!(resolve_device_frame_color("#FF000080"), Some("#FF000080"));
        assert_eq!(resolve_device_frame_color("#ff00"), Some("#ff00"));
        assert_eq!(resolve_device_frame_color("#ff0"), Some("#ff0"));
        assert_eq!(resolve_device_frame_color("#ff000"), None);
        assert_eq!(resolve_device_frame_color("red"), None);
        assert_eq!(resolve_device_frame_color("#ff0;x"), None);
        assert_eq!(resolve_device_frame_color("#gggggg"), None);
    }

    #[test]
    fn sizes_follow_lumen_core() {
        let iphone = DeviceFrameDevice::Iphone;
        assert_eq!(
            resolve_device_frame_size(iphone, None, None, None),
            (390.0, 844.0)
        );
        assert_eq!(
            resolve_device_frame_size(iphone, Some(DeviceFrameOrientation::Landscape), None, None),
            (844.0, 390.0)
        );
        assert_eq!(
            resolve_device_frame_size(
                DeviceFrameDevice::Tablet,
                Some(DeviceFrameOrientation::Portrait),
                Some(900.0),
                Some(600.0)
            ),
            (600.0, 900.0)
        );
        assert_eq!(
            resolve_device_frame_size(DeviceFrameDevice::Laptop, None, Some(0.5), Some(f64::NAN)),
            (1280.0, 800.0)
        );
        assert_eq!(
            resolve_device_frame_size(
                DeviceFrameDevice::Laptop,
                None,
                Some(20_000.0),
                Some(16384.0)
            ),
            (1280.0, 16384.0)
        );
    }
}