Skip to main content

arc_ui/actions/
copy_button.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/copy-button/copy-button.tsx` & `.module.css`
3//!
4//! P2 Component #3: `copy-button`
5//!
6//! - Writes `value` directly to the OS clipboard via `cx.write_to_clipboard` and shows quiet
7//!   `Copied` / `Failed` feedback that auto-resets after `1900ms` (matches `use-copy-feedback.ts`).
8//! - Variants: `Outline` (default) and `Plain`, plus `icon_only` square compact button.
9//! - Motion:
10//!   - Press scale (`0.97` normal / `0.96` icon-only) in backdrop canvas with spring release.
11//!   - Label width spring (`SpringSpec::visual(0.22, 0.0)`, critically damped) + 160ms `2px -> 0`
12//!     text crossfade.
13//!   - 16×16 icon slot: `Copy` → hand-drawn `pathLength` checkmark (`220ms`, `40ms` delay,
14//!     `colors.success`) → `CircleAlert` (`colors.danger`) on error.
15
16use std::{cell::RefCell, rc::Rc, time::Duration};
17
18use arc_motion::{
19    CubicBezier, PathPoint, PolylinePath, TransformOrigin, arc_spring, arc_spring_with_options,
20    is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
21};
22use arc_tokens::{
23    ActiveArcLocale as _, ActiveArcTheme as _, ControlHeights, Radii, Spacing, SpringSpec,
24    Typography,
25};
26use gpui_kit::{
27    App, BorderStyle, ClipboardItem, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
28    KeyDownEvent, KeyUpEvent, MouseButton, ParentElement, RenderOnce, SharedString, Styled, Window,
29    assets::IconName, base::Button as BaseButton, canvas, div, prelude::*, px, quad,
30};
31
32type CopiedHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
33
34/// Critically damped label width spring from `copy-button.tsx` line 27 (`0.22s, bounce: 0`).
35const RESIZE_SPRING: SpringSpec = SpringSpec::visual(0.22, 0.0);
36
37/// Visual surface style for [`CopyButton`].
38#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
39pub enum CopyButtonVariant {
40    #[default]
41    Outline,
42    Plain,
43}
44
45/// Current clipboard feedback phase of [`CopyButton`].
46#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
47pub enum CopyFeedbackState {
48    #[default]
49    Idle,
50    Copied,
51    Error,
52}
53
54#[derive(Clone)]
55struct CopyButtonInternal {
56    state: CopyFeedbackState,
57    state_changed_at_secs: f64,
58    reset_at_secs: Option<f64>,
59    pressed: bool,
60    hovered: bool,
61    last_text: SharedString,
62    morph_armed_until_secs: f64,
63    measured_label_width: Rc<RefCell<f32>>,
64    has_measured: Rc<RefCell<bool>>,
65}
66
67impl CopyButtonInternal {
68    fn new(initial_text: SharedString, now: f64) -> Self {
69        Self {
70            state: CopyFeedbackState::Idle,
71            state_changed_at_secs: now - 10.0,
72            reset_at_secs: None,
73            pressed: false,
74            hovered: false,
75            last_text: initial_text,
76            morph_armed_until_secs: f64::NEG_INFINITY,
77            measured_label_width: Rc::new(RefCell::new(0.0)),
78            has_measured: Rc::new(RefCell::new(false)),
79        }
80    }
81}
82
83/// Arc `CopyButton` with OS clipboard write, hand-drawn `pathLength` checkmark, and zero-overshoot
84/// label width morphing.
85#[derive(IntoElement)]
86pub struct CopyButton {
87    id: ElementId,
88    value: SharedString,
89    label: Option<SharedString>,
90    copied_label: Option<SharedString>,
91    error_label: Option<SharedString>,
92    icon_only: bool,
93    variant: CopyButtonVariant,
94    disabled: bool,
95    reset_after: Duration,
96    focus_handle: Option<FocusHandle>,
97    on_copied: Option<CopiedHandler>,
98}
99
100impl CopyButton {
101    pub fn new(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
102        Self {
103            id: id.into(),
104            value: value.into(),
105            label: None,
106            copied_label: None,
107            error_label: None,
108            icon_only: false,
109            variant: CopyButtonVariant::Outline,
110            disabled: false,
111            reset_after: Duration::from_millis(1900),
112            focus_handle: None,
113            on_copied: None,
114        }
115    }
116
117    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
118        self.label = Some(label.into());
119        self
120    }
121
122    pub fn copied_label(mut self, label: impl Into<SharedString>) -> Self {
123        self.copied_label = Some(label.into());
124        self
125    }
126
127    pub fn error_label(mut self, label: impl Into<SharedString>) -> Self {
128        self.error_label = Some(label.into());
129        self
130    }
131
132    pub fn icon_only(mut self, icon_only: bool) -> Self {
133        self.icon_only = icon_only;
134        self
135    }
136
137    pub fn variant(mut self, variant: CopyButtonVariant) -> Self {
138        self.variant = variant;
139        self
140    }
141
142    pub fn disabled(mut self, disabled: bool) -> Self {
143        self.disabled = disabled;
144        self
145    }
146
147    pub fn reset_after(mut self, duration: Duration) -> Self {
148        self.reset_after = duration;
149        self
150    }
151
152    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
153        self.focus_handle = Some(handle.clone());
154        self
155    }
156
157    pub fn on_copied(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
158        self.on_copied = Some(Rc::new(handler));
159        self
160    }
161}
162
163fn check_path_16() -> PolylinePath {
164    let s = 16.0 / 24.0;
165    PolylinePath::new(vec![
166        PathPoint::new(4.0 * s, 12.0 * s),
167        PathPoint::new(9.0 * s, 17.0 * s),
168        PathPoint::new(20.0 * s, 6.0 * s),
169    ])
170}
171
172impl RenderOnce for CopyButton {
173    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
174        let theme = cx.arc_theme().clone();
175        let colors = theme.colors;
176        let motion = theme.motion;
177        let locale = cx.arc_locale();
178        let reduced = is_reduced_motion(cx);
179        let now = motion_now(cx);
180
181        let idle_label = self
182            .label
183            .unwrap_or_else(|| locale.text("复制", "Copy").into());
184        let copied_label = self
185            .copied_label
186            .unwrap_or_else(|| locale.text("已复制", "Copied").into());
187        let error_label = self
188            .error_label
189            .unwrap_or_else(|| locale.text("复制失败", "Failed").into());
190
191        let state_id =
192            ElementId::NamedChild(self.id.clone().into(), "__arc-copy-button-state".into());
193        let internal = window.use_keyed_state(state_id, cx, |_, _| {
194            CopyButtonInternal::new(idle_label.clone(), now)
195        });
196
197        // Tick auto-reset timer (1900ms default).
198        {
199            let reset_at = internal.read(cx).reset_at_secs;
200            if let Some(deadline) = reset_at {
201                if now >= deadline {
202                    internal.update(cx, |s, _| {
203                        s.reset_at_secs = None;
204                        s.state = CopyFeedbackState::Idle;
205                        s.state_changed_at_secs = now;
206                    });
207                } else {
208                    window.request_animation_frame();
209                }
210            }
211        }
212
213        let current_state = internal.read(cx).state;
214        let current_text = match current_state {
215            CopyFeedbackState::Idle => idle_label.clone(),
216            CopyFeedbackState::Copied => copied_label,
217            CopyFeedbackState::Error => error_label,
218        };
219
220        {
221            let prev_text = internal.read(cx).last_text.clone();
222            if prev_text != current_text {
223                internal.update(cx, |s, _| {
224                    s.last_text = current_text.clone();
225                    s.morph_armed_until_secs = now + 0.7;
226                });
227            }
228        }
229
230        let snap = internal.read(cx).clone();
231        let target_scale = if !self.disabled && !reduced && snap.pressed {
232            if self.icon_only { 0.96 } else { 0.97 }
233        } else {
234            1.0
235        };
236        let animated_scale = if reduced {
237            1.0
238        } else {
239            arc_spring(
240                (self.id.clone(), "press-scale"),
241                target_scale,
242                motion.spring.snappy,
243                window,
244                cx,
245            )
246        };
247
248        let elapsed = (now - snap.state_changed_at_secs).max(0.0);
249        let fade_dur = if reduced { 0.0 } else { 0.16 };
250        let (fade_op, text_y) = if fade_dur > 0.0 && elapsed < fade_dur {
251            window.request_animation_frame();
252            let t = (elapsed / fade_dur).clamp(0.0, 1.0) as f32;
253            let e = CubicBezier::from_spec(motion.ease.standard).sample(t);
254            (e, 2.0 * (1.0 - e))
255        } else {
256            (1.0, 0.0)
257        };
258
259        // Zero-overshoot 0.22s width morph for text label.
260        let measured_w = *snap.measured_label_width.borrow();
261        let morph_active = !self.icon_only
262            && !reduced
263            && *snap.has_measured.borrow()
264            && measured_w > 0.0
265            && now <= snap.morph_armed_until_secs;
266        let morphed_w = if !self.icon_only && measured_w > 0.0 {
267            let sample = arc_spring_with_options(
268                (self.id.clone(), "label-width"),
269                measured_w,
270                SpringOptions::new(RESIZE_SPRING),
271                window,
272                cx,
273            );
274            if morph_active {
275                Some(sample.value)
276            } else {
277                None
278            }
279        } else {
280            None
281        };
282
283        let (bg, border, fg) = match self.variant {
284            CopyButtonVariant::Outline => {
285                if !self.disabled && (snap.hovered || snap.pressed) {
286                    (
287                        colors.surface_muted,
288                        colors.border_strong,
289                        colors.foreground,
290                    )
291                } else {
292                    (colors.surface, colors.border, colors.foreground)
293                }
294            }
295            CopyButtonVariant::Plain => {
296                if !self.disabled && (snap.hovered || snap.pressed) {
297                    (
298                        colors.surface_muted,
299                        Hsla::transparent_black(),
300                        colors.foreground,
301                    )
302                } else {
303                    (
304                        Hsla::transparent_black(),
305                        Hsla::transparent_black(),
306                        colors.text_secondary,
307                    )
308                }
309            }
310        };
311
312        let backdrop = canvas(
313            |_, _, _| {},
314            move |rect, _, window, _| {
315                let paint_rect = scaled_bounds(
316                    rect,
317                    animated_scale,
318                    animated_scale,
319                    TransformOrigin::CENTER,
320                );
321                if bg.a > 0.0 || border.a > 0.0 {
322                    window.paint_quad(quad(
323                        paint_rect,
324                        Corners::all(Radii::CONTROL),
325                        bg,
326                        Edges::all(px(1.0)),
327                        border,
328                        BorderStyle::Solid,
329                    ));
330                }
331            },
332        )
333        .absolute()
334        .inset_0();
335
336        let icon_el = match current_state {
337            CopyFeedbackState::Idle => div()
338                .w(px(16.0))
339                .h(px(16.0))
340                .flex_none()
341                .flex()
342                .items_center()
343                .justify_center()
344                .opacity(fade_op)
345                .child(IconName::Copy)
346                .into_any_element(),
347            CopyFeedbackState::Copied => {
348                let progress = if reduced {
349                    1.0
350                } else {
351                    let delayed = (elapsed - 0.04).max(0.0);
352                    if delayed < 0.22 {
353                        window.request_animation_frame();
354                        let t = (delayed / 0.22).clamp(0.0, 1.0) as f32;
355                        CubicBezier::from_spec(motion.ease.standard).sample(t)
356                    } else {
357                        1.0
358                    }
359                };
360                let success_color = Hsla {
361                    a: colors.success.a * fade_op,
362                    ..colors.success
363                };
364                let path = check_path_16();
365                div()
366                    .w(px(16.0))
367                    .h(px(16.0))
368                    .flex_none()
369                    .child(
370                        canvas(
371                            |_, _, _| {},
372                            move |rect, _, window, _| {
373                                let sliced = path.slice(0.0, progress);
374                                if let Some(builder) =
375                                    sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(1.75))
376                                    && let Ok(built) = builder.build()
377                                {
378                                    window.paint_path(built, success_color);
379                                }
380                            },
381                        )
382                        .size_full(),
383                    )
384                    .into_any_element()
385            }
386            CopyFeedbackState::Error => div()
387                .w(px(16.0))
388                .h(px(16.0))
389                .flex_none()
390                .flex()
391                .items_center()
392                .justify_center()
393                .text_color(colors.danger)
394                .opacity(fade_op)
395                .child(IconName::CircleAlert)
396                .into_any_element(),
397        };
398
399        let label_el = if self.icon_only {
400            None
401        } else {
402            let label_w_ref = snap.measured_label_width.clone();
403            let has_m_ref = snap.has_measured.clone();
404            let probe = canvas(
405                move |rect, window, _| {
406                    let w = f32::from(rect.size.width);
407                    let prev = *label_w_ref.borrow();
408                    *label_w_ref.borrow_mut() = w;
409                    if w > 0.0 {
410                        *has_m_ref.borrow_mut() = true;
411                    }
412                    if (w - prev).abs() > 0.5 && prev > 0.0 {
413                        window.request_animation_frame();
414                    }
415                },
416                |_, _, _, _| {},
417            )
418            .absolute()
419            .inset_0();
420
421            Some(
422                div()
423                    .relative()
424                    .flex()
425                    .items_center()
426                    .justify_center()
427                    .when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
428                    .child(
429                        div()
430                            .relative()
431                            .flex_none()
432                            .mt(px(text_y))
433                            .opacity(fade_op)
434                            .child(probe)
435                            .child(current_text),
436                    ),
437            )
438        };
439
440        let internal_click = internal.clone();
441        let internal_hover = internal.clone();
442        let internal_down = internal.clone();
443        let internal_up = internal.clone();
444        let internal_up_out = internal.clone();
445        let internal_kd = internal.clone();
446        let internal_ku = internal.clone();
447        let value = self.value;
448        let reset_secs = self.reset_after.as_secs_f64();
449        let on_copied = self.on_copied;
450        let is_disabled = self.disabled;
451
452        let mut base = BaseButton::new(self.id.clone())
453            .disabled(self.disabled)
454            .accessibility_label(idle_label)
455            .on_click(move |_, window, cx| {
456                if is_disabled {
457                    return;
458                }
459                cx.write_to_clipboard(ClipboardItem::new_string(value.to_string()));
460                let t_now = motion_now(cx);
461                internal_click.update(cx, |s, _| {
462                    s.state = CopyFeedbackState::Copied;
463                    s.state_changed_at_secs = t_now;
464                    s.reset_at_secs = if reset_secs > 0.0 {
465                        Some(t_now + reset_secs)
466                    } else {
467                        None
468                    };
469                });
470                if let Some(handler) = &on_copied {
471                    handler(&(), window, cx);
472                }
473                window.refresh();
474            });
475
476        if let Some(handle) = &self.focus_handle {
477            base = base.track_focus(handle);
478        }
479
480        base.relative()
481            .self_start()
482            .flex()
483            .flex_row()
484            .items_center()
485            .justify_center()
486            .gap(Spacing::S2)
487            .min_h(ControlHeights::SM)
488            .when(self.icon_only, |this| this.w(ControlHeights::SM))
489            .when(!self.icon_only, |this| this.px(Spacing::S3))
490            .rounded(Radii::CONTROL)
491            .text_size(Typography::TEXT_SM)
492            .text_color(fg)
493            .when(self.disabled, |this| this.opacity(0.5))
494            .when(!self.disabled, |this| this.cursor_pointer())
495            .on_hover(move |hovered, window, cx| {
496                internal_hover.update(cx, |s, _| {
497                    s.hovered = *hovered;
498                    if !*hovered {
499                        s.pressed = false;
500                    }
501                });
502                window.refresh();
503            })
504            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
505                if is_disabled {
506                    return;
507                }
508                internal_down.update(cx, |s, _| s.pressed = true);
509                window.refresh();
510            })
511            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
512                internal_up.update(cx, |s, _| s.pressed = false);
513                window.refresh();
514            })
515            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
516                internal_up_out.update(cx, |s, _| s.pressed = false);
517                window.refresh();
518            })
519            .on_key_down(move |event: &KeyDownEvent, window, cx| {
520                if is_disabled {
521                    return;
522                }
523                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
524                    internal_kd.update(cx, |s, _| s.pressed = true);
525                    window.refresh();
526                }
527            })
528            .on_key_up(move |event: &KeyUpEvent, window, cx| {
529                if event.keystroke.key == "space" || event.keystroke.key == "enter" {
530                    internal_ku.update(cx, |s, _| s.pressed = false);
531                    window.refresh();
532                }
533            })
534            .child(backdrop)
535            .child(icon_el)
536            .when_some(label_el, |this, el| this.child(el))
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use std::{cell::Cell, rc::Rc};
543
544    use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
545    use arc_tokens::{Accent, Locale, ThemeMode, install_arc_theme, set_locale};
546    use gpui_kit::{
547        Context, MouseButton, Render, Role, TestAppContext, div,
548        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
549    };
550
551    use super::*;
552
553    struct CopyHost {
554        copied: Rc<Cell<usize>>,
555    }
556
557    impl Render for CopyHost {
558        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
559            let copied = self.copied.clone();
560            div().p(Spacing::S4).child(
561                CopyButton::new("copy-id", "sk-arc-123456")
562                    .label("Copy model id")
563                    .on_copied(cx.listener(move |_, _, _, _| {
564                        copied.set(copied.get() + 1);
565                    })),
566            )
567        }
568    }
569
570    #[gpui_kit::test]
571    fn copy_button_writes_clipboard_and_invokes_callback(cx: &mut TestAppContext) {
572        cx.update(|cx| {
573            gpui_kit::init(cx);
574            set_locale(Locale::EnUs, cx);
575            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
576        });
577        let copied = Rc::new(Cell::new(0usize));
578        let (_view, cx) = cx.add_window_view(|_, _| CopyHost {
579            copied: copied.clone(),
580        });
581
582        cx.update(|window, cx| {
583            window.render_frame(cx);
584            let btn = window.find_by_label("Copy model id");
585            assert_eq!(btn.role(), Some(Role::Button));
586            let pos = btn.bounds().center();
587            window.pointer_down(pos, MouseButton::Left, cx);
588            window.pointer_up(pos, MouseButton::Left, cx);
589            assert_eq!(copied.get(), 1);
590        });
591
592        cx.read(|cx| {
593            let clip = cx
594                .read_from_clipboard()
595                .and_then(|item| item.text())
596                .unwrap_or_default();
597            assert_eq!(clip, "sk-arc-123456");
598        });
599    }
600
601    #[test]
602    fn copy_button_resize_spring_matches_0_22s_critically_damped_curve() {
603        let solver = SpringSolver::new(RESIZE_SPRING, 108.0, 56.0, 0.0);
604        let omega0 = std::f64::consts::TAU / (0.22 * 1.2);
605        let mut actual = CurveTrace::new("copy_button", "width");
606        let mut expected = CurveTrace::new("copy_button", "width");
607        for frame in 0..=28 {
608            let t_ms = frame as f64 * 16.0;
609            let t = t_ms / 1000.0;
610            let ref_w = 56.0 + (-omega0 * t).exp() * (52.0 + omega0 * 52.0 * t);
611            expected.push(t_ms, ref_w);
612            actual.push(t_ms, f64::from(solver.sample(t).value));
613        }
614        let err = max_curve_error_pct(&actual, &expected);
615        assert!(err < 5.0, "CopyButton resize spring error {err:.3}% >= 5%");
616    }
617}