lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `QRCode`: a QR code encoded in Rust, with no JavaScript or network request.
// cspell:words figcaption

use dioxus::prelude::*;

use super::qr_encoder::{encode_uri_component, render_qr_svg};
use crate::class::compose;

/// The `data:` URL of the QR code for `value`, byte for byte what lumen-react renders with
/// `uqr`. Returns `None` when the value does not fit in a QR code.
pub fn qr_code_data_url(value: &str) -> Option<String> {
    render_qr_svg(value)
        .map(|svg| format!("data:image/svg+xml;utf8,{}", encode_uri_component(&svg)))
}

/// Props for [`QRCode`].
#[derive(Props, Clone, PartialEq)]
pub struct QRCodeProps {
    /// Text or URL to encode. It is also shown as the caption.
    #[props(into)]
    pub value: Option<String>,
    /// A prebuilt QR code image to show instead of encoding `value`.
    #[props(into)]
    pub src: Option<String>,
    /// Rendered size in pixels. Defaults to 160.
    #[props(default = 160)]
    pub size: u32,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
    /// Shown in the frame when there is no image, for example a custom placeholder.
    pub children: Element,
}

/// A QR code for a URL or text, with the value as its caption.
///
/// The code is encoded in Rust (error correction level L, a one-module border) and embedded as
/// an SVG `data:` URL, the same image lumen-react produces.
#[component]
pub fn QRCode(props: QRCodeProps) -> Element {
    let value = props.value.clone().filter(|value| !value.is_empty());
    let image = match (&props.src, &value) {
        (Some(src), _) => Some(src.clone()),
        (None, Some(value)) => qr_code_data_url(value),
        (None, None) => None,
    };
    let alt = value.as_ref().map_or_else(
        || "QR code".to_string(),
        |value| format!("QR code for {value}"),
    );
    let class = compose([Some("ui-qr-code"), props.class.as_deref()]);
    let size = props.size;

    rsx! {
        figure {
            class,
            "data-ui-qr-code": "true",
            style: "--ui-qr-code-size: {size}px",
            ..props.attributes,
            div { class: "ui-qr-code__frame",
                if let Some(src) = image {
                    img {
                        alt,
                        class: "ui-qr-code__image",
                        height: "{size}",
                        src,
                        width: "{size}",
                    }
                } else {
                    {props.children}
                }
            }
            if let Some(value) = value {
                figcaption { class: "ui-qr-code__value", {value} }
            }
        }
    }
}