fc_ui/capabilities/controls/
copy_button.rs1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::time::Duration;
4
5pub struct CopyButtonState {
6 copied: bool,
7 text: SharedString,
8 copy_generation: usize,
9}
10
11impl CopyButtonState {
12 pub fn new(text: SharedString) -> Self {
13 Self {
14 copied: false,
15 text,
16 copy_generation: 0,
17 }
18 }
19
20 pub fn set_text(&mut self, text: SharedString) {
21 self.text = text;
22 }
23
24 pub fn copy(&mut self, window: &mut Window, cx: &mut Context<Self>) {
25 cx.write_to_clipboard(ClipboardItem::new_string(self.text.to_string()));
26 self.copied = true;
27 self.copy_generation = self.copy_generation.wrapping_add(1);
28 let generation = self.copy_generation;
29 cx.notify();
30
31 cx.spawn_in(window, async move |this, cx| {
32 smol::Timer::after(Duration::from_secs(2)).await;
33 let _ = this.update(cx, |state, cx| {
34 if state.copy_generation == generation {
35 state.copied = false;
36 cx.notify();
37 }
38 });
39 })
40 .detach();
41 }
42}
43
44#[derive(IntoElement)]
45pub struct CopyButton {
46 state: Entity<CopyButtonState>,
47 id: ElementId,
48 style: StyleRefinement,
49}
50
51impl CopyButton {
52 pub fn new(id: impl Into<ElementId>, state: Entity<CopyButtonState>) -> Self {
53 Self {
54 id: id.into(),
55 state,
56 style: StyleRefinement::default(),
57 }
58 }
59}
60
61impl RenderOnce for CopyButton {
62 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
63 let theme = use_theme(cx);
64 let copied = self.state.read(cx).copied;
65 let state = self.state.clone();
66 let user_style = self.style;
67
68 div()
69 .id(self.id)
70 .flex()
71 .items_center()
72 .justify_center()
73 .h(px(24.0))
74 .px(px(8.0))
75 .rounded(theme.tokens.radius_sm)
76 .cursor_pointer()
77 .text_size(px(12.0))
78 .text_color(theme.tokens.muted_foreground)
79 .hover(|s| s.bg(theme.tokens.muted))
80 .active(|s| s.opacity(0.7))
81 .when(copied, |el| {
82 el.text_color(hsla(142.0 / 360.0, 0.71, 0.45, 1.0))
83 })
84 .on_click(move |_, window, cx| {
85 state.update(cx, |s, cx| s.copy(window, cx));
86 })
87 .map(|this| {
88 let mut d = this;
89 d.style().refine(&user_style);
90 d
91 })
92 .child(if copied { "\u{2713}" } else { "\u{1F4CB}" })
93 }
94}
95
96impl Styled for CopyButton {
97 fn style(&mut self) -> &mut StyleRefinement {
98 &mut self.style
99 }
100}