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};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ShareLinksTarget {
Email,
Linkedin,
X,
Whatsapp,
Bluesky,
Reddit,
}
impl ShareLinksTarget {
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",
}
}
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",
}
}
pub fn opens_new_tab(self) -> bool {
self != Self::Email
}
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,
}
}
}
pub const SHARE_LINKS_DEFAULT_TARGETS: [ShareLinksTarget; 3] = [
ShareLinksTarget::Linkedin,
ShareLinksTarget::X,
ShareLinksTarget::Email,
];
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ShareLinksLabels {
pub email: Option<String>,
pub linkedin: Option<String>,
pub x: Option<String>,
pub whatsapp: Option<String>,
pub bluesky: Option<String>,
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(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShareLinksLink {
pub target: ShareLinksTarget,
pub href: String,
pub label: String,
pub new_tab: bool,
}
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())
}
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)
),
})
}
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()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShareLinksResult {
Shared,
Aborted,
Failed,
Unsupported,
}
impl ShareLinksResult {
fn parse(value: &str) -> Self {
match value {
"shared" => Self::Shared,
"aborted" => Self::Aborted,
"failed" => Self::Failed,
_ => Self::Unsupported,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShareLinksVariant {
#[default]
Inline,
Stacked,
}
impl ShareLinksVariant {
pub fn as_str(self) -> &'static str {
match self {
Self::Inline => "inline",
Self::Stacked => "stacked",
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct ShareLinksProps {
#[props(into)]
pub url: String,
#[props(into)]
pub title: Option<String>,
#[props(into)]
pub text: Option<String>,
#[props(default = SHARE_LINKS_DEFAULT_TARGETS.to_vec())]
pub targets: Vec<ShareLinksTarget>,
#[props(default)]
pub labels: ShareLinksLabels,
#[props(default = true)]
pub copy: bool,
#[props(default = "Copy link".to_string(), into)]
pub copy_label: String,
#[props(default = "Link copied".to_string(), into)]
pub copied_label: String,
#[props(default = "Could not copy the link".to_string(), into)]
pub copy_error_label: String,
#[props(default = "Copy the link manually".to_string(), into)]
pub recovery_label: String,
pub on_copy: Option<Callback<String, bool>>,
#[props(default)]
pub native_share: bool,
#[props(default = "Share".to_string(), into)]
pub native_share_label: String,
pub on_share_result: Option<EventHandler<ShareLinksResult>>,
#[props(default = "(opens in a new tab)".to_string(), into)]
pub new_tab_label: String,
#[props(default = "Share".to_string(), into)]
pub label: String,
#[props(into)]
pub aria_label: Option<String>,
#[props(default)]
pub variant: ShareLinksVariant,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
}
#[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;
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);
}
}