1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//! `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} }
}
}
}
}