Skip to main content

lumen_dioxus/navigation/
copy.rs

1//! `CopyButton`.
2
3use std::time::Duration;
4
5use dioxus::prelude::*;
6
7use crate::class::compose;
8use crate::form::Textarea;
9use crate::time::sleep;
10use crate::{ButtonSize, ButtonVariant};
11
12use super::web::{read_selector_text, write_clipboard};
13
14/// Feedback state of a [`CopyButton`].
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum CopyButtonState {
18    /// Waiting for a copy.
19    #[default]
20    Idle,
21    /// The last copy succeeded.
22    Copied,
23    /// The last copy failed.
24    Error,
25}
26
27impl CopyButtonState {
28    /// The `data-state` value.
29    pub fn as_str(self) -> &'static str {
30        match self {
31            Self::Idle => "idle",
32            Self::Copied => "copied",
33            Self::Error => "error",
34        }
35    }
36}
37
38/// The size class lumen-react's `Button` gives each [`ButtonSize`].
39pub(crate) fn button_size_class(size: ButtonSize) -> &'static str {
40    match size {
41        ButtonSize::Default => "ui-button--default-size",
42        ButtonSize::Sm => "ui-button--sm",
43        ButtonSize::Lg => "ui-button--lg",
44        ButtonSize::Icon => "ui-button--icon",
45    }
46}
47
48/// Props for [`CopyButton`].
49#[derive(Props, Clone, PartialEq)]
50pub struct CopyButtonProps {
51    /// The text to copy.
52    #[props(into)]
53    pub value: Option<String>,
54    /// A CSS selector whose element's value or text is copied when `value` is unset. Web and
55    /// desktop only.
56    #[props(into)]
57    pub target: Option<String>,
58    /// Copies through the app instead of the browser clipboard: called with the text, it returns
59    /// whether the copy succeeded. Use it on Dioxus Native, which has no clipboard API, for
60    /// example with a platform clipboard crate.
61    pub on_copy: Option<Callback<String, bool>>,
62    /// Accessible name while idle. Defaults to `Copy to clipboard`.
63    #[props(default = "Copy to clipboard".to_string(), into)]
64    pub label: String,
65    /// Accessible name and default feedback after a copy. Defaults to `Copied to clipboard`.
66    #[props(default = "Copied to clipboard".to_string(), into)]
67    pub copied_label: String,
68    /// Accessible name and default feedback after a failure. Defaults to
69    /// `Could not copy to clipboard`.
70    #[props(default = "Could not copy to clipboard".to_string(), into)]
71    pub error_label: String,
72    /// Content shown after a copy. Defaults to `copied_label`.
73    pub copied_content: Option<Element>,
74    /// Content shown after a failure. Defaults to `error_label`.
75    pub error_content: Option<Element>,
76    /// When set, failures reveal a read-only field with the text so it can be copied by hand,
77    /// and a status region announces the outcome.
78    #[props(into)]
79    pub recovery_label: Option<String>,
80    /// Milliseconds before the feedback returns to idle. Defaults to 2000.
81    #[props(default = 2000)]
82    pub reset_after: u64,
83    /// Button treatment. Defaults to outline.
84    #[props(default = ButtonVariant::Outline)]
85    pub variant: ButtonVariant,
86    /// Button size.
87    #[props(default)]
88    pub size: ButtonSize,
89    /// Disables the button.
90    #[props(default)]
91    pub disabled: bool,
92    /// Called on every activation, before copying.
93    pub onclick: Option<EventHandler<MouseEvent>>,
94    /// Called with the outcome after each copy.
95    pub on_state_change: Option<EventHandler<CopyButtonState>>,
96    /// Extra classes appended after the Lumen classes.
97    #[props(into)]
98    pub class: Option<String>,
99    /// Any other `<button>` or global attribute.
100    #[props(extends = GlobalAttributes, extends = button)]
101    pub attributes: Vec<Attribute>,
102    /// Idle content. Defaults to `Copy`.
103    pub children: Element,
104}
105
106/// Copies text and shows copied or failed feedback that resets after a moment.
107///
108/// It uses the browser clipboard on web and desktop. Dioxus Native has no clipboard API, so a
109/// copy there reports an error unless `on_copy` supplies one.
110#[component]
111pub fn CopyButton(props: CopyButtonProps) -> Element {
112    let mut state = use_signal(CopyButtonState::default);
113    let mut recovery_value = use_signal(|| None::<String>);
114    let mut operation = use_signal(|| 0_u64);
115    let variant = format!("ui-button--{}", props.variant.as_str());
116    let class = compose([
117        Some("ui-button"),
118        Some(variant.as_str()),
119        Some(button_size_class(props.size)),
120        Some("ui-copy-button"),
121        props.class.as_deref(),
122    ]);
123    let current = state();
124    let accessible_label = match current {
125        CopyButtonState::Idle => props.label.clone(),
126        CopyButtonState::Copied => props.copied_label.clone(),
127        CopyButtonState::Error => props.error_label.clone(),
128    };
129    let idle_content = if super::util::has_content(&props.children) {
130        props.children.clone()
131    } else {
132        rsx! { "Copy" }
133    };
134    let copied_content = props
135        .copied_content
136        .clone()
137        .unwrap_or_else(|| rsx! { "{props.copied_label}" });
138    let error_content = props
139        .error_content
140        .clone()
141        .unwrap_or_else(|| rsx! { "{props.error_label}" });
142    let status = match (current, recovery_value()) {
143        (CopyButtonState::Idle, _) => String::new(),
144        (_, Some(_)) => format!(
145            "{accessible_label} {}",
146            props.recovery_label.clone().unwrap_or_default()
147        ),
148        (_, None) => accessible_label.clone(),
149    };
150    let (value, target, on_copy) = (props.value.clone(), props.target.clone(), props.on_copy);
151    let (recovery_label, reset_after) = (props.recovery_label.clone(), props.reset_after);
152    let (onclick, on_state_change) = (props.onclick, props.on_state_change);
153
154    rsx! {
155        button {
156            aria_label: accessible_label.clone(),
157            class,
158            "data-slot": "copy-button",
159            "data-state": current.as_str(),
160            "data-ui-copy-button": "true",
161            "data-ui-owner": "dioxus",
162            disabled: props.disabled,
163            r#type: "button",
164            onclick: move |event| {
165                if let Some(handler) = onclick {
166                    handler.call(event);
167                }
168
169                let id = *operation.peek() + 1;
170                operation.set(id);
171                let (value, target, recovery_label) = (value.clone(), target.clone(), recovery_label.clone());
172
173                spawn(async move {
174                    let text = match (value, target) {
175                        (Some(value), _) => Some(value),
176                        (None, Some(selector)) => read_selector_text(selector).await,
177                        (None, None) => None,
178                    };
179                    let copied = match (&text, on_copy) {
180                        (None, _) => false,
181                        (Some(text), Some(copy)) => copy.call(text.clone()),
182                        (Some(text), None) => write_clipboard(text.clone()).await,
183                    };
184
185                    if *operation.peek() != id {
186                        return;
187                    }
188
189                    let next = if copied { CopyButtonState::Copied } else { CopyButtonState::Error };
190                    state.set(next);
191                    recovery_value.set(if copied { None } else { recovery_label.and(text) });
192
193                    if let Some(handler) = on_state_change {
194                        handler.call(next);
195                    }
196
197                    sleep(Duration::from_millis(reset_after)).await;
198
199                    if *operation.peek() == id {
200                        state.set(CopyButtonState::Idle);
201                    }
202                });
203            },
204            ..props.attributes,
205            span { class: "ui-button__content",
206                span { aria_hidden: "true", "data-slot": "copy-idle", hidden: current != CopyButtonState::Idle, {idle_content} }
207                span { aria_hidden: "true", "data-slot": "copy-copied", hidden: current != CopyButtonState::Copied, {copied_content} }
208                span { aria_hidden: "true", "data-slot": "copy-error", hidden: current != CopyButtonState::Error, {error_content} }
209            }
210        }
211        if let Some(recovery_label) = props.recovery_label {
212            span { aria_live: "polite", class: "ui-sr-only", role: "status", "{status}" }
213            if let Some(text) = recovery_value() {
214                label { class: "ui-copy-button__recovery",
215                    span { "{recovery_label}" }
216                    Textarea { aria_label: recovery_label.clone(), readonly: true, rows: 3, value: text }
217                }
218            }
219        }
220    }
221}