Skip to main content

lumen_dioxus/content/
device_frame.rs

1//! `DeviceFrame`: a phone, tablet, laptop, or desktop frame around a screenshot or live content.
2// cspell:words hexdigit onresize
3
4use dioxus::prelude::*;
5
6use super::util::js_number;
7use crate::class::compose;
8
9/// The device a [`DeviceFrame`] draws.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum DeviceFrameDevice {
13    /// A laptop, 1280 by 800.
14    #[default]
15    Laptop,
16    /// A desktop monitor, 1440 by 900.
17    Desktop,
18    /// An iPhone, 390 by 844.
19    Iphone,
20    /// An Android phone, 412 by 915.
21    Android,
22    /// A tablet, 820 by 1180.
23    Tablet,
24    /// A `MacBook` Pro, 1280 by 800.
25    MacbookPro,
26    /// A `MacBook` Air, 1280 by 800.
27    MacbookAir,
28    /// An iMac, 1440 by 810.
29    Imac,
30    /// A Pixel phone, 412 by 915.
31    Pixel,
32    /// An iPad Pro, 834 by 1194.
33    IpadPro,
34}
35
36impl DeviceFrameDevice {
37    /// The `data-device` value.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Self::Laptop => "laptop",
41            Self::Desktop => "desktop",
42            Self::Iphone => "iphone",
43            Self::Android => "android",
44            Self::Tablet => "tablet",
45            Self::MacbookPro => "macbook-pro",
46            Self::MacbookAir => "macbook-air",
47            Self::Imac => "imac",
48            Self::Pixel => "pixel",
49            Self::IpadPro => "ipad-pro",
50        }
51    }
52
53    /// The default screen size in CSS pixels, `(width, height)`.
54    pub fn screen_size(self) -> (f64, f64) {
55        match self {
56            Self::Laptop | Self::MacbookPro | Self::MacbookAir => (1280.0, 800.0),
57            Self::Desktop => (1440.0, 900.0),
58            Self::Iphone => (390.0, 844.0),
59            Self::Android | Self::Pixel => (412.0, 915.0),
60            Self::Tablet => (820.0, 1180.0),
61            Self::Imac => (1440.0, 810.0),
62            Self::IpadPro => (834.0, 1194.0),
63        }
64    }
65}
66
67/// Orientation of a [`DeviceFrame`].
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum DeviceFrameOrientation {
70    /// Taller than wide.
71    Portrait,
72    /// Wider than tall.
73    Landscape,
74}
75
76impl DeviceFrameOrientation {
77    /// The `data-orientation` value.
78    pub fn as_str(self) -> &'static str {
79        match self {
80            Self::Portrait => "portrait",
81            Self::Landscape => "landscape",
82        }
83    }
84}
85
86/// Finish of a [`DeviceFrame`].
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum DeviceFrameTone {
90    /// Light hardware.
91    Light,
92    /// Dark hardware.
93    #[default]
94    Dark,
95}
96
97impl DeviceFrameTone {
98    /// The `data-tone` value.
99    pub fn as_str(self) -> &'static str {
100        match self {
101            Self::Light => "light",
102            Self::Dark => "dark",
103        }
104    }
105}
106
107/// `white`, `black`, or a 3, 4, 6, or 8 digit hex color; anything else is dropped so it can't
108/// inject CSS into the inline style.
109pub(crate) fn resolve_device_frame_color(color: &str) -> Option<&str> {
110    if color == "white" || color == "black" {
111        return Some(color);
112    }
113
114    let digits = color.strip_prefix('#')?;
115
116    ([3, 4, 6, 8].contains(&digits.len()) && digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
117        .then_some(color)
118}
119
120/// The screen size, like `resolveLumenDeviceFrame`: custom sizes from 1 to 16384 pixels replace the
121/// defaults, and an orientation swaps them so the longer side matches it.
122pub(crate) fn resolve_device_frame_size(
123    device: DeviceFrameDevice,
124    orientation: Option<DeviceFrameOrientation>,
125    width: Option<f64>,
126    height: Option<f64>,
127) -> (f64, f64) {
128    let (default_width, default_height) = device.screen_size();
129    let dimension = |value: Option<f64>, fallback: f64| {
130        value
131            .filter(|value| value.is_finite() && (1.0..=16384.0).contains(value))
132            .unwrap_or(fallback)
133    };
134    let first = dimension(width, default_width);
135    let second = dimension(height, default_height);
136
137    match orientation {
138        None => (first, second),
139        Some(DeviceFrameOrientation::Landscape) => (first.max(second), first.min(second)),
140        Some(DeviceFrameOrientation::Portrait) => (first.min(second), first.max(second)),
141    }
142}
143
144/// Props for [`DeviceFrame`].
145#[derive(Props, Clone, PartialEq)]
146pub struct DeviceFrameProps {
147    /// The device.
148    #[props(default)]
149    pub device: DeviceFrameDevice,
150    /// Forces portrait or landscape.
151    pub orientation: Option<DeviceFrameOrientation>,
152    /// Hardware finish.
153    #[props(default)]
154    pub tone: DeviceFrameTone,
155    /// Hardware color: `white`, `black`, or a hex color.
156    #[props(into)]
157    pub color: Option<String>,
158    /// Screen width in CSS pixels, from 1 to 16384.
159    pub screen_width: Option<f64>,
160    /// Screen height in CSS pixels, from 1 to 16384.
161    pub screen_height: Option<f64>,
162    /// Lets the screen content scroll. On by default.
163    #[props(default = true)]
164    pub scroll: bool,
165    /// Extra classes appended after the Lumen class.
166    #[props(into)]
167    pub class: Option<String>,
168    /// Any other `<div>` or global attribute.
169    #[props(extends = GlobalAttributes, extends = div)]
170    pub attributes: Vec<Attribute>,
171    /// Screen content: an image, an `iframe`, or live markup.
172    pub children: Element,
173}
174
175/// A device frame around a screenshot, an `iframe`, or live content.
176///
177/// On the web and desktop the screen measures itself and scales `iframe` content to the device
178/// width; renderers without resize events show iframes at their natural size.
179#[component]
180pub fn DeviceFrame(props: DeviceFrameProps) -> Element {
181    let (width, height) = resolve_device_frame_size(
182        props.device,
183        props.orientation,
184        props.screen_width,
185        props.screen_height,
186    );
187    let mut scale = use_signal(|| None::<f64>);
188    let color = props
189        .color
190        .as_deref()
191        .and_then(resolve_device_frame_color)
192        .map(|color| format!("--ui-device-color: {color}"));
193    let (width_text, height_text) = (js_number(width), js_number(height));
194    let scale_text = scale().map_or_else(String::new, |scale| {
195        format!("; --ui-device-frame-scale: {}", js_number(scale))
196    });
197    let screen_style = format!(
198        "--ui-device-frame-height: {height_text}px; --ui-device-frame-width: {width_text}px; aspect-ratio: {width_text} / {height_text}{scale_text}"
199    );
200    let class = compose([Some("ui-device-frame"), props.class.as_deref()]);
201
202    rsx! {
203        div {
204            class,
205            "data-device": props.device.as_str(),
206            "data-tone": props.tone.as_str(),
207            "data-orientation": props.orientation.map(DeviceFrameOrientation::as_str),
208            style: color,
209            ..props.attributes,
210            div { class: "ui-device-frame__shell",
211                span { class: "ui-device-frame__hardware", aria_hidden: "true",
212                    span { class: "ui-device-frame__action" }
213                    span { class: "ui-device-frame__volume-up" }
214                    span { class: "ui-device-frame__volume-down" }
215                    span { class: "ui-device-frame__power" }
216                    span { class: "ui-device-frame__rail-left" }
217                    span { class: "ui-device-frame__rail-right" }
218                }
219                div { class: "ui-device-frame__glass",
220                    span { aria_hidden: "true", class: "ui-device-frame__camera" }
221                    div {
222                        class: "ui-device-frame__screen",
223                        "data-scroll": if props.scroll { "true" } else { "false" },
224                        style: screen_style,
225                        onresize: move |event: ResizeEvent| {
226                            if let Ok(size) = event.get_content_box_size()
227                                && size.width > 0.0
228                            {
229                                scale.set(Some(size.width / width));
230                            }
231                        },
232                        {props.children}
233                    }
234                }
235            }
236            span { aria_hidden: "true", class: "ui-device-frame__base" }
237        }
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::{
244        DeviceFrameDevice, DeviceFrameOrientation, resolve_device_frame_color,
245        resolve_device_frame_size,
246    };
247
248    #[test]
249    fn colors_are_bounded() {
250        assert_eq!(resolve_device_frame_color("white"), Some("white"));
251        assert_eq!(resolve_device_frame_color("#fff"), Some("#fff"));
252        assert_eq!(resolve_device_frame_color("#FF000080"), Some("#FF000080"));
253        assert_eq!(resolve_device_frame_color("#ff00"), Some("#ff00"));
254        assert_eq!(resolve_device_frame_color("#ff0"), Some("#ff0"));
255        assert_eq!(resolve_device_frame_color("#ff000"), None);
256        assert_eq!(resolve_device_frame_color("red"), None);
257        assert_eq!(resolve_device_frame_color("#ff0;x"), None);
258        assert_eq!(resolve_device_frame_color("#gggggg"), None);
259    }
260
261    #[test]
262    fn sizes_follow_lumen_core() {
263        let iphone = DeviceFrameDevice::Iphone;
264        assert_eq!(
265            resolve_device_frame_size(iphone, None, None, None),
266            (390.0, 844.0)
267        );
268        assert_eq!(
269            resolve_device_frame_size(iphone, Some(DeviceFrameOrientation::Landscape), None, None),
270            (844.0, 390.0)
271        );
272        assert_eq!(
273            resolve_device_frame_size(
274                DeviceFrameDevice::Tablet,
275                Some(DeviceFrameOrientation::Portrait),
276                Some(900.0),
277                Some(600.0)
278            ),
279            (600.0, 900.0)
280        );
281        assert_eq!(
282            resolve_device_frame_size(DeviceFrameDevice::Laptop, None, Some(0.5), Some(f64::NAN)),
283            (1280.0, 800.0)
284        );
285        assert_eq!(
286            resolve_device_frame_size(
287                DeviceFrameDevice::Laptop,
288                None,
289                Some(20_000.0),
290                Some(16384.0)
291            ),
292            (1280.0, 16384.0)
293        );
294    }
295}