lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! `ShareLinks` and the share-intent builders ported from `lumen-core/share`.
// cspell:words Ahttps Fexample

use dioxus::prelude::*;

use crate::class::compose;

use super::copy::CopyButton;
use super::util::{encode_uri_component, normalize_web_url};
use super::web::{native_share, native_share_supported};

/// A platform [`ShareLinks`] can build a share link for. Brand logos are not part of the contract.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ShareLinksTarget {
    /// A `mailto:` link.
    Email,
    /// `LinkedIn`.
    Linkedin,
    /// X (formerly Twitter).
    X,
    /// `WhatsApp`.
    Whatsapp,
    /// Bluesky.
    Bluesky,
    /// Reddit.
    Reddit,
}

impl ShareLinksTarget {
    /// The `data-target` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Email => "email",
            Self::Linkedin => "linkedin",
            Self::X => "x",
            Self::Whatsapp => "whatsapp",
            Self::Bluesky => "bluesky",
            Self::Reddit => "reddit",
        }
    }

    /// The English action label.
    pub fn default_label(self) -> &'static str {
        match self {
            Self::Bluesky => "Share on Bluesky",
            Self::Email => "Share by email",
            Self::Linkedin => "Share on LinkedIn",
            Self::Reddit => "Share on Reddit",
            Self::Whatsapp => "Share on WhatsApp",
            Self::X => "Share on X",
        }
    }

    /// Email opens the mail client in place; every web intent opens a new tab.
    pub fn opens_new_tab(self) -> bool {
        self != Self::Email
    }

    /// Parses a target name, ignoring case and surrounding whitespace.
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "email" => Some(Self::Email),
            "linkedin" => Some(Self::Linkedin),
            "x" => Some(Self::X),
            "whatsapp" => Some(Self::Whatsapp),
            "bluesky" => Some(Self::Bluesky),
            "reddit" => Some(Self::Reddit),
            _ => None,
        }
    }
}

/// The default targets: `LinkedIn`, X, and email.
pub const SHARE_LINKS_DEFAULT_TARGETS: [ShareLinksTarget; 3] = [
    ShareLinksTarget::Linkedin,
    ShareLinksTarget::X,
    ShareLinksTarget::Email,
];

/// Localized action labels for [`ShareLinks`]. Blank values keep the English default.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ShareLinksLabels {
    /// Email label.
    pub email: Option<String>,
    /// `LinkedIn` label.
    pub linkedin: Option<String>,
    /// X label.
    pub x: Option<String>,
    /// `WhatsApp` label.
    pub whatsapp: Option<String>,
    /// Bluesky label.
    pub bluesky: Option<String>,
    /// Reddit label.
    pub reddit: Option<String>,
}

impl ShareLinksLabels {
    fn get(&self, target: ShareLinksTarget) -> String {
        let value = match target {
            ShareLinksTarget::Email => &self.email,
            ShareLinksTarget::Linkedin => &self.linkedin,
            ShareLinksTarget::X => &self.x,
            ShareLinksTarget::Whatsapp => &self.whatsapp,
            ShareLinksTarget::Bluesky => &self.bluesky,
            ShareLinksTarget::Reddit => &self.reddit,
        };

        match value {
            Some(label) if !label.trim().is_empty() => label.clone(),
            _ => target.default_label().to_string(),
        }
    }
}

/// A resolved share link.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShareLinksLink {
    /// The platform.
    pub target: ShareLinksTarget,
    /// The share intent URL.
    pub href: String,
    /// The action label.
    pub label: String,
    /// Whether the link opens a new tab.
    pub new_tab: bool,
}

/// The normalized `http(s)` URL to share, or `None` for any other scheme, credentials, control
/// characters, or unparsable input, like `resolveLumenShareUrl`.
pub fn share_links_url(value: &str) -> Option<String> {
    normalize_web_url(value)
}

fn optional(value: Option<&str>) -> Option<&str> {
    value.map(str::trim).filter(|text| !text.is_empty())
}

/// Builds a platform share intent, or `None` when `url` is not a safe `http(s)` URL, like
/// `createLumenShareHref`.
pub fn share_links_href(
    target: ShareLinksTarget,
    url: &str,
    title: Option<&str>,
    text: Option<&str>,
) -> Option<String> {
    let url = share_links_url(url)?;
    let title = optional(title);
    let text = optional(text);
    let message = text.or(title);
    let encode = encode_uri_component;
    let joined = || message.map_or_else(|| url.clone(), |message| format!("{message} {url}"));
    let parameter = |name: &str, value: Option<&str>| {
        value.map_or_else(String::new, |value| format!("&{name}={}", encode(value)))
    };

    Some(match target {
        ShareLinksTarget::Bluesky => {
            format!("https://bsky.app/intent/compose?text={}", encode(&joined()))
        }
        ShareLinksTarget::Email => {
            let subject =
                title.map_or_else(String::new, |title| format!("subject={}&", encode(title)));
            let body = text.map_or_else(|| url.clone(), |text| format!("{text}\n\n{url}"));

            format!("mailto:?{subject}body={}", encode(&body))
        }
        ShareLinksTarget::Linkedin => {
            format!(
                "https://www.linkedin.com/sharing/share-offsite/?url={}",
                encode(&url)
            )
        }
        ShareLinksTarget::Reddit => format!(
            "https://www.reddit.com/submit?url={}{}",
            encode(&url),
            parameter("title", title)
        ),
        ShareLinksTarget::Whatsapp => {
            format!("https://api.whatsapp.com/send?text={}", encode(&joined()))
        }
        ShareLinksTarget::X => format!(
            "https://x.com/intent/post?url={}{}",
            encode(&url),
            parameter("text", message)
        ),
    })
}

/// Resolves targets (first-seen order, duplicates dropped), labels, and destinations, like
/// `createLumenShareLinks`. Unsafe URLs produce no links.
pub fn share_links(
    url: &str,
    title: Option<&str>,
    text: Option<&str>,
    targets: &[ShareLinksTarget],
    labels: &ShareLinksLabels,
) -> Vec<ShareLinksLink> {
    let mut seen: Vec<ShareLinksTarget> = Vec::new();

    targets
        .iter()
        .filter(|target| {
            if seen.contains(target) {
                false
            } else {
                seen.push(**target);
                true
            }
        })
        .filter_map(|target| {
            share_links_href(*target, url, title, text).map(|href| ShareLinksLink {
                target: *target,
                href,
                label: labels.get(*target),
                new_tab: target.opens_new_tab(),
            })
        })
        .collect()
}

/// Outcome of the platform share sheet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShareLinksResult {
    /// The user shared.
    Shared,
    /// The user dismissed the sheet.
    Aborted,
    /// Sharing failed.
    Failed,
    /// The renderer cannot share.
    Unsupported,
}

impl ShareLinksResult {
    fn parse(value: &str) -> Self {
        match value {
            "shared" => Self::Shared,
            "aborted" => Self::Aborted,
            "failed" => Self::Failed,
            _ => Self::Unsupported,
        }
    }
}

/// Layout of a [`ShareLinks`] list.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShareLinksVariant {
    /// A wrapping row.
    #[default]
    Inline,
    /// A column of full-width actions.
    Stacked,
}

impl ShareLinksVariant {
    /// The `data-variant` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Inline => "inline",
            Self::Stacked => "stacked",
        }
    }
}

/// Props for [`ShareLinks`].
#[derive(Props, Clone, PartialEq)]
pub struct ShareLinksProps {
    /// Absolute `http(s)` URL to share. Relative or unsafe values render nothing.
    #[props(into)]
    pub url: String,
    /// Page title, used as the email subject and in some intents.
    #[props(into)]
    pub title: Option<String>,
    /// Share message. Defaults to the title in intents that take one.
    #[props(into)]
    pub text: Option<String>,
    /// Platforms, in order. Defaults to `LinkedIn`, X, and email.
    #[props(default = SHARE_LINKS_DEFAULT_TARGETS.to_vec())]
    pub targets: Vec<ShareLinksTarget>,
    /// Localized action labels.
    #[props(default)]
    pub labels: ShareLinksLabels,
    /// Shows a copy-link button first. Defaults to true.
    #[props(default = true)]
    pub copy: bool,
    /// Copy button text and accessible name. Defaults to `Copy link`.
    #[props(default = "Copy link".to_string(), into)]
    pub copy_label: String,
    /// Announced after a copy. Defaults to `Link copied`.
    #[props(default = "Link copied".to_string(), into)]
    pub copied_label: String,
    /// Announced when copying fails. Defaults to `Could not copy the link`.
    #[props(default = "Could not copy the link".to_string(), into)]
    pub copy_error_label: String,
    /// Label of the manual-copy field shown after a failed copy.
    #[props(default = "Copy the link manually".to_string(), into)]
    pub recovery_label: String,
    /// Copies through the app instead of the browser clipboard (see `CopyButton::on_copy`).
    pub on_copy: Option<Callback<String, bool>>,
    /// Offers the platform share sheet where the browser supports it (web and desktop).
    #[props(default)]
    pub native_share: bool,
    /// Native share button text. Defaults to `Share`.
    #[props(default = "Share".to_string(), into)]
    pub native_share_label: String,
    /// Called with the outcome of the native share sheet.
    pub on_share_result: Option<EventHandler<ShareLinksResult>>,
    /// Screen-reader suffix for links that open a new tab.
    #[props(default = "(opens in a new tab)".to_string(), into)]
    pub new_tab_label: String,
    /// Accessible name of the group. Defaults to `Share`.
    #[props(default = "Share".to_string(), into)]
    pub label: String,
    /// Overrides `label` as the group's accessible name.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Row or column layout.
    #[props(default)]
    pub variant: ShareLinksVariant,
    /// 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>,
}

/// Copy-link, native share, and platform share links for one URL.
#[component]
pub fn ShareLinks(props: ShareLinksProps) -> Element {
    let mut supported = use_signal(|| false);
    let mut busy = use_signal(|| false);
    let wants_native = props.native_share;

    // Checks when native share is first wanted, including when the prop turns on after mount,
    // like lumen-react, which mounts its native item only then.
    use_effect(use_reactive((&wants_native,), move |(wants_native,)| {
        if wants_native && !*supported.peek() {
            spawn(async move {
                if native_share_supported().await {
                    supported.set(true);
                }
            });
        }
    }));

    let Some(url) = share_links_url(&props.url) else {
        return rsx! {};
    };

    let links = share_links(
        &url,
        props.title.as_deref(),
        props.text.as_deref(),
        &props.targets,
        &props.labels,
    );
    let class = compose([Some("ui-share-links"), props.class.as_deref()]);
    let group_label = props.aria_label.unwrap_or(props.label);
    let is_supported = supported();
    let share_input = (url.clone(), props.title.clone(), props.text.clone());
    let on_share_result = props.on_share_result;
    let new_tab_label = props.new_tab_label;

    rsx! {
        div {
            aria_label: group_label,
            class,
            "data-slot": "share-links",
            "data-variant": props.variant.as_str(),
            role: "group",
            ..props.attributes,
            ul { class: "ui-share-links__list", role: "list",
                if props.copy {
                    li { class: "ui-share-links__item", "data-slot": "share-links-copy",
                        CopyButton {
                            copied_label: props.copied_label,
                            error_label: props.copy_error_label,
                            label: props.copy_label.clone(),
                            on_copy: props.on_copy,
                            recovery_label: props.recovery_label,
                            value: url.clone(),
                            "{props.copy_label}"
                        }
                    }
                }
                if props.native_share {
                    li { class: "ui-share-links__item", "data-slot": "share-links-native", hidden: !is_supported,
                        button {
                            aria_busy: busy().then_some("true"),
                            class: "ui-button ui-button--outline ui-button--default-size ui-share-links__native",
                            "data-slot": "button",
                            "data-ui-owner": "dioxus",
                            "data-ui-share-native": "",
                            hidden: !is_supported,
                            r#type: "button",
                            onclick: move |_| {
                                if *busy.peek() {
                                    return;
                                }

                                busy.set(true);
                                let (url, title, text) = share_input.clone();

                                spawn(async move {
                                    let result = native_share(url, title, text).await;
                                    busy.set(false);

                                    if let Some(handler) = on_share_result {
                                        handler.call(ShareLinksResult::parse(&result));
                                    }
                                });
                            },
                            span { class: "ui-button__content", "{props.native_share_label}" }
                        }
                    }
                }
                for link in links {
                    li {
                        key: "{link.target.as_str()}",
                        class: "ui-share-links__item",
                        "data-slot": "share-links-target",
                        "data-target": link.target.as_str(),
                        a {
                            class: "ui-share-links__link",
                            "data-target": link.target.as_str(),
                            href: link.href,
                            rel: link.new_tab.then_some("noopener noreferrer"),
                            target: link.new_tab.then_some("_blank"),
                            "{link.label}"
                            if link.new_tab {
                                span { class: "ui-sr-only", " {new_tab_label}" }
                            }
                        }
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        SHARE_LINKS_DEFAULT_TARGETS, ShareLinksLabels, ShareLinksTarget, share_links,
        share_links_href,
    };

    #[test]
    fn intents_match_lumen_core() {
        let url = "https://example.com";
        assert_eq!(
            share_links_href(ShareLinksTarget::Linkedin, url, None, None).as_deref(),
            Some(
                "https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fexample.com%2F"
            )
        );
        assert_eq!(
            share_links_href(ShareLinksTarget::X, url, Some("T"), None).as_deref(),
            Some("https://x.com/intent/post?url=https%3A%2F%2Fexample.com%2F&text=T")
        );
        assert_eq!(
            share_links_href(ShareLinksTarget::Email, url, Some("T"), Some("Read")).as_deref(),
            Some("mailto:?subject=T&body=Read%0A%0Ahttps%3A%2F%2Fexample.com%2F")
        );
        assert_eq!(
            share_links_href(ShareLinksTarget::Whatsapp, url, Some("A b"), None).as_deref(),
            Some("https://api.whatsapp.com/send?text=A%20b%20https%3A%2F%2Fexample.com%2F")
        );
        assert_eq!(
            share_links_href(ShareLinksTarget::Reddit, url, None, None).as_deref(),
            Some("https://www.reddit.com/submit?url=https%3A%2F%2Fexample.com%2F")
        );
        assert_eq!(
            share_links_href(ShareLinksTarget::Bluesky, url, None, Some("  ")).as_deref(),
            Some("https://bsky.app/intent/compose?text=https%3A%2F%2Fexample.com%2F")
        );
    }

    #[test]
    fn unsafe_urls_and_duplicates_are_dropped() {
        let labels = ShareLinksLabels::default();
        assert_eq!(
            share_links(
                "javascript:alert(1)",
                None,
                None,
                &SHARE_LINKS_DEFAULT_TARGETS,
                &labels
            ),
            Vec::new()
        );
        assert_eq!(
            share_links(
                "/relative",
                None,
                None,
                &SHARE_LINKS_DEFAULT_TARGETS,
                &labels
            ),
            Vec::new()
        );
        let links = share_links(
            "https://example.com/a",
            None,
            None,
            &[
                ShareLinksTarget::X,
                ShareLinksTarget::X,
                ShareLinksTarget::Email,
            ],
            &ShareLinksLabels {
                x: Some("Post".to_string()),
                email: Some(" ".to_string()),
                ..ShareLinksLabels::default()
            },
        );
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].label, "Post");
        assert_eq!(links[1].label, "Share by email");
        assert!(links[0].new_tab && !links[1].new_tab);
        assert_eq!(
            ShareLinksTarget::parse(" LinkedIn "),
            Some(ShareLinksTarget::Linkedin)
        );
        assert_eq!(ShareLinksTarget::parse("myspace"), None);
    }
}