Skip to main content

gpui_component/
clipboard.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    App, ClipboardItem, ElementId, IntoElement, RenderOnce, SharedString, Window,
5    prelude::FluentBuilder,
6};
7use rust_i18n::t;
8
9use crate::{
10    IconName, Sizable, Size,
11    button::{Button, ButtonVariants as _},
12};
13
14/// An element that provides clipboard copy functionality.
15#[derive(IntoElement)]
16pub struct Clipboard {
17    id: ElementId,
18    value: SharedString,
19    value_fn: Option<Rc<dyn Fn(&mut Window, &mut App) -> SharedString>>,
20    on_copied: Option<Rc<dyn Fn(SharedString, &mut Window, &mut App)>>,
21    label: Option<SharedString>,
22    tooltip_text: Option<SharedString>,
23    tooltip_show_delay: Option<Duration>,
24    accessibility_label: Option<SharedString>,
25    size: Size,
26}
27
28impl Sizable for Clipboard {
29    fn with_size(mut self, size: impl Into<Size>) -> Self {
30        self.size = size.into();
31        self
32    }
33}
34
35impl Clipboard {
36    /// Create a new Clipboard element with the given ID.
37    pub fn new(id: impl Into<ElementId>) -> Self {
38        Self {
39            id: id.into(),
40            value: SharedString::default(),
41            value_fn: None,
42            on_copied: None,
43            label: None,
44            tooltip_text: None,
45            tooltip_show_delay: None,
46            accessibility_label: None,
47            size: Size::XSmall,
48        }
49    }
50
51    /// Set visible text for the clipboard button.
52    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
53        self.label = Some(label.into());
54        self
55    }
56
57    /// Set tooltip text for the clipboard button.
58    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
59        self.tooltip_text = Some(tooltip.into());
60        self
61    }
62
63    /// Overrides how long the pointer must rest before the tooltip shows.
64    ///
65    /// Defaults to [`gpui_base::TooltipDefaults::show_delay`].
66    pub fn tooltip_show_delay(mut self, delay: Duration) -> Self {
67        self.tooltip_show_delay = Some(delay);
68        self
69    }
70
71    /// Set the name a screen reader announces. Defaults to the localized "Copy".
72    ///
73    /// The clipboard button shows only an icon, so it has no visible label to
74    /// read, and its tooltip is a hint rather than a name.
75    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
76        self.accessibility_label = Some(label.into());
77        self
78    }
79
80    /// Set the value for copying to the clipboard. Default is an empty string.
81    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
82        self.value = value.into();
83        self
84    }
85
86    /// Set the value of the clipboard to the result of the given function. Default is None.
87    ///
88    /// When used this, the copy value will use the result of the function.
89    pub fn value_fn(
90        mut self,
91        value: impl Fn(&mut Window, &mut App) -> SharedString + 'static,
92    ) -> Self {
93        self.value_fn = Some(Rc::new(value));
94        self
95    }
96
97    /// Set a callback to be invoked when the content is copied to the clipboard.
98    pub fn on_copied<F>(mut self, handler: F) -> Self
99    where
100        F: Fn(SharedString, &mut Window, &mut App) + 'static,
101    {
102        self.on_copied = Some(Rc::new(handler));
103        self
104    }
105}
106
107impl RenderOnce for Clipboard {
108    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
109        let state = window.use_keyed_state(self.id.clone(), cx, |_, _| ClipboardState::default());
110
111        let value = self.value.clone();
112        let clipboard_id = self.id.clone();
113        let copied = state.read(cx).copied;
114        let value_fn = self.value_fn.clone();
115        let accessibility_label = self
116            .accessibility_label
117            .or_else(|| self.label.is_none().then(|| t!("Copy").into()));
118
119        Button::new(clipboard_id)
120            .icon(if copied {
121                IconName::Check
122            } else {
123                IconName::Copy
124            })
125            .when_some(self.label, |this, label| this.label(label))
126            .ghost()
127            .with_size(self.size)
128            .when_some(self.tooltip_text, |this, text| this.tooltip(text))
129            .when_some(self.tooltip_show_delay, |this, delay| {
130                this.tooltip_show_delay(delay)
131            })
132            .when_some(accessibility_label, |this, label| {
133                this.accessibility_label(label)
134            })
135            .when(!copied, |this| {
136                this.on_click({
137                    let state = state.clone();
138                    let on_copied = self.on_copied.clone();
139                    move |_, window, cx| {
140                        cx.stop_propagation();
141                        let value = value_fn
142                            .as_ref()
143                            .map(|f| f(window, cx))
144                            .unwrap_or_else(|| value.clone());
145                        cx.write_to_clipboard(ClipboardItem::new_string(value.to_string()));
146                        state.update(cx, |state, cx| {
147                            state.copied = true;
148                            cx.notify();
149                        });
150
151                        let state = state.clone();
152                        cx.spawn(async move |cx| {
153                            cx.background_executor().timer(Duration::from_secs(2)).await;
154                            _ = state.update(cx, |state, cx| {
155                                state.copied = false;
156                                cx.notify();
157                            });
158                        })
159                        .detach();
160
161                        if let Some(on_copied) = &on_copied {
162                            on_copied(value, window, cx);
163                        }
164                    }
165                })
166            })
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn test_clipboard_builder() {
176        let clipboard = Clipboard::new("copy").label("Copy value");
177
178        assert_eq!(clipboard.label.as_deref(), Some("Copy value"));
179        assert_eq!(clipboard.accessibility_label, None);
180
181        let clipboard = clipboard.accessibility_label("Copy current value");
182        assert_eq!(
183            clipboard.accessibility_label.as_deref(),
184            Some("Copy current value")
185        );
186        assert_eq!(clipboard.label.as_deref(), Some("Copy value"));
187    }
188}
189
190#[doc(hidden)]
191#[derive(Default)]
192struct ClipboardState {
193    copied: bool,
194}