use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
CubicBezier, PathPoint, PolylinePath, TransformOrigin, arc_spring, arc_spring_with_options,
is_reduced_motion, motion_now, scaled_bounds, spring::SpringOptions,
};
use arc_tokens::{
ActiveArcLocale as _, ActiveArcTheme as _, ControlHeights, Radii, Spacing, SpringSpec,
Typography,
};
use gpui_kit::{
App, BorderStyle, ClipboardItem, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement,
KeyDownEvent, KeyUpEvent, MouseButton, ParentElement, RenderOnce, SharedString, Styled, Window,
assets::IconName, base::Button as BaseButton, canvas, div, prelude::*, px, quad,
};
type CopiedHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
const RESIZE_SPRING: SpringSpec = SpringSpec::visual(0.22, 0.0);
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum CopyButtonVariant {
#[default]
Outline,
Plain,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum CopyFeedbackState {
#[default]
Idle,
Copied,
Error,
}
#[derive(Clone)]
struct CopyButtonInternal {
state: CopyFeedbackState,
state_changed_at_secs: f64,
reset_at_secs: Option<f64>,
pressed: bool,
hovered: bool,
last_text: SharedString,
morph_armed_until_secs: f64,
measured_label_width: Rc<RefCell<f32>>,
has_measured: Rc<RefCell<bool>>,
}
impl CopyButtonInternal {
fn new(initial_text: SharedString, now: f64) -> Self {
Self {
state: CopyFeedbackState::Idle,
state_changed_at_secs: now - 10.0,
reset_at_secs: None,
pressed: false,
hovered: false,
last_text: initial_text,
morph_armed_until_secs: f64::NEG_INFINITY,
measured_label_width: Rc::new(RefCell::new(0.0)),
has_measured: Rc::new(RefCell::new(false)),
}
}
}
#[derive(IntoElement)]
pub struct CopyButton {
id: ElementId,
value: SharedString,
label: Option<SharedString>,
copied_label: Option<SharedString>,
error_label: Option<SharedString>,
icon_only: bool,
variant: CopyButtonVariant,
disabled: bool,
reset_after: Duration,
focus_handle: Option<FocusHandle>,
on_copied: Option<CopiedHandler>,
}
impl CopyButton {
pub fn new(id: impl Into<ElementId>, value: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
value: value.into(),
label: None,
copied_label: None,
error_label: None,
icon_only: false,
variant: CopyButtonVariant::Outline,
disabled: false,
reset_after: Duration::from_millis(1900),
focus_handle: None,
on_copied: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn copied_label(mut self, label: impl Into<SharedString>) -> Self {
self.copied_label = Some(label.into());
self
}
pub fn error_label(mut self, label: impl Into<SharedString>) -> Self {
self.error_label = Some(label.into());
self
}
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.icon_only = icon_only;
self
}
pub fn variant(mut self, variant: CopyButtonVariant) -> Self {
self.variant = variant;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn reset_after(mut self, duration: Duration) -> Self {
self.reset_after = duration;
self
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus_handle = Some(handle.clone());
self
}
pub fn on_copied(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.on_copied = Some(Rc::new(handler));
self
}
}
fn check_path_16() -> PolylinePath {
let s = 16.0 / 24.0;
PolylinePath::new(vec![
PathPoint::new(4.0 * s, 12.0 * s),
PathPoint::new(9.0 * s, 17.0 * s),
PathPoint::new(20.0 * s, 6.0 * s),
])
}
impl RenderOnce for CopyButton {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let locale = cx.arc_locale();
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let idle_label = self
.label
.unwrap_or_else(|| locale.text("复制", "Copy").into());
let copied_label = self
.copied_label
.unwrap_or_else(|| locale.text("已复制", "Copied").into());
let error_label = self
.error_label
.unwrap_or_else(|| locale.text("复制失败", "Failed").into());
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-copy-button-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| {
CopyButtonInternal::new(idle_label.clone(), now)
});
{
let reset_at = internal.read(cx).reset_at_secs;
if let Some(deadline) = reset_at {
if now >= deadline {
internal.update(cx, |s, _| {
s.reset_at_secs = None;
s.state = CopyFeedbackState::Idle;
s.state_changed_at_secs = now;
});
} else {
window.request_animation_frame();
}
}
}
let current_state = internal.read(cx).state;
let current_text = match current_state {
CopyFeedbackState::Idle => idle_label.clone(),
CopyFeedbackState::Copied => copied_label,
CopyFeedbackState::Error => error_label,
};
{
let prev_text = internal.read(cx).last_text.clone();
if prev_text != current_text {
internal.update(cx, |s, _| {
s.last_text = current_text.clone();
s.morph_armed_until_secs = now + 0.7;
});
}
}
let snap = internal.read(cx).clone();
let target_scale = if !self.disabled && !reduced && snap.pressed {
if self.icon_only { 0.96 } else { 0.97 }
} else {
1.0
};
let animated_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "press-scale"),
target_scale,
motion.spring.snappy,
window,
cx,
)
};
let elapsed = (now - snap.state_changed_at_secs).max(0.0);
let fade_dur = if reduced { 0.0 } else { 0.16 };
let (fade_op, text_y) = if fade_dur > 0.0 && elapsed < fade_dur {
window.request_animation_frame();
let t = (elapsed / fade_dur).clamp(0.0, 1.0) as f32;
let e = CubicBezier::from_spec(motion.ease.standard).sample(t);
(e, 2.0 * (1.0 - e))
} else {
(1.0, 0.0)
};
let measured_w = *snap.measured_label_width.borrow();
let morph_active = !self.icon_only
&& !reduced
&& *snap.has_measured.borrow()
&& measured_w > 0.0
&& now <= snap.morph_armed_until_secs;
let morphed_w = if !self.icon_only && measured_w > 0.0 {
let sample = arc_spring_with_options(
(self.id.clone(), "label-width"),
measured_w,
SpringOptions::new(RESIZE_SPRING),
window,
cx,
);
if morph_active {
Some(sample.value)
} else {
None
}
} else {
None
};
let (bg, border, fg) = match self.variant {
CopyButtonVariant::Outline => {
if !self.disabled && (snap.hovered || snap.pressed) {
(
colors.surface_muted,
colors.border_strong,
colors.foreground,
)
} else {
(colors.surface, colors.border, colors.foreground)
}
}
CopyButtonVariant::Plain => {
if !self.disabled && (snap.hovered || snap.pressed) {
(
colors.surface_muted,
Hsla::transparent_black(),
colors.foreground,
)
} else {
(
Hsla::transparent_black(),
Hsla::transparent_black(),
colors.text_secondary,
)
}
}
};
let backdrop = canvas(
|_, _, _| {},
move |rect, _, window, _| {
let paint_rect = scaled_bounds(
rect,
animated_scale,
animated_scale,
TransformOrigin::CENTER,
);
if bg.a > 0.0 || border.a > 0.0 {
window.paint_quad(quad(
paint_rect,
Corners::all(Radii::CONTROL),
bg,
Edges::all(px(1.0)),
border,
BorderStyle::Solid,
));
}
},
)
.absolute()
.inset_0();
let icon_el = match current_state {
CopyFeedbackState::Idle => div()
.w(px(16.0))
.h(px(16.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.opacity(fade_op)
.child(IconName::Copy)
.into_any_element(),
CopyFeedbackState::Copied => {
let progress = if reduced {
1.0
} else {
let delayed = (elapsed - 0.04).max(0.0);
if delayed < 0.22 {
window.request_animation_frame();
let t = (delayed / 0.22).clamp(0.0, 1.0) as f32;
CubicBezier::from_spec(motion.ease.standard).sample(t)
} else {
1.0
}
};
let success_color = Hsla {
a: colors.success.a * fade_op,
..colors.success
};
let path = check_path_16();
div()
.w(px(16.0))
.h(px(16.0))
.flex_none()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let sliced = path.slice(0.0, progress);
if let Some(builder) =
sliced.to_stroke_builder(rect.origin.x, rect.origin.y, px(1.75))
&& let Ok(built) = builder.build()
{
window.paint_path(built, success_color);
}
},
)
.size_full(),
)
.into_any_element()
}
CopyFeedbackState::Error => div()
.w(px(16.0))
.h(px(16.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.text_color(colors.danger)
.opacity(fade_op)
.child(IconName::CircleAlert)
.into_any_element(),
};
let label_el = if self.icon_only {
None
} else {
let label_w_ref = snap.measured_label_width.clone();
let has_m_ref = snap.has_measured.clone();
let probe = canvas(
move |rect, window, _| {
let w = f32::from(rect.size.width);
let prev = *label_w_ref.borrow();
*label_w_ref.borrow_mut() = w;
if w > 0.0 {
*has_m_ref.borrow_mut() = true;
}
if (w - prev).abs() > 0.5 && prev > 0.0 {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
Some(
div()
.relative()
.flex()
.items_center()
.justify_center()
.when_some(morphed_w, |this, w| this.w(px(w)).overflow_hidden())
.child(
div()
.relative()
.flex_none()
.mt(px(text_y))
.opacity(fade_op)
.child(probe)
.child(current_text),
),
)
};
let internal_click = internal.clone();
let internal_hover = internal.clone();
let internal_down = internal.clone();
let internal_up = internal.clone();
let internal_up_out = internal.clone();
let internal_kd = internal.clone();
let internal_ku = internal.clone();
let value = self.value;
let reset_secs = self.reset_after.as_secs_f64();
let on_copied = self.on_copied;
let is_disabled = self.disabled;
let mut base = BaseButton::new(self.id.clone())
.disabled(self.disabled)
.accessibility_label(idle_label)
.on_click(move |_, window, cx| {
if is_disabled {
return;
}
cx.write_to_clipboard(ClipboardItem::new_string(value.to_string()));
let t_now = motion_now(cx);
internal_click.update(cx, |s, _| {
s.state = CopyFeedbackState::Copied;
s.state_changed_at_secs = t_now;
s.reset_at_secs = if reset_secs > 0.0 {
Some(t_now + reset_secs)
} else {
None
};
});
if let Some(handler) = &on_copied {
handler(&(), window, cx);
}
window.refresh();
});
if let Some(handle) = &self.focus_handle {
base = base.track_focus(handle);
}
base.relative()
.self_start()
.flex()
.flex_row()
.items_center()
.justify_center()
.gap(Spacing::S2)
.min_h(ControlHeights::SM)
.when(self.icon_only, |this| this.w(ControlHeights::SM))
.when(!self.icon_only, |this| this.px(Spacing::S3))
.rounded(Radii::CONTROL)
.text_size(Typography::TEXT_SM)
.text_color(fg)
.when(self.disabled, |this| this.opacity(0.5))
.when(!self.disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
internal_hover.update(cx, |s, _| {
s.hovered = *hovered;
if !*hovered {
s.pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if is_disabled {
return;
}
internal_down.update(cx, |s, _| s.pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
internal_up.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
internal_up_out.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if is_disabled {
return;
}
if event.keystroke.key == "space" || event.keystroke.key == "enter" {
internal_kd.update(cx, |s, _| s.pressed = true);
window.refresh();
}
})
.on_key_up(move |event: &KeyUpEvent, window, cx| {
if event.keystroke.key == "space" || event.keystroke.key == "enter" {
internal_ku.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
.child(backdrop)
.child(icon_el)
.when_some(label_el, |this, el| this.child(el))
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_motion::{CurveTrace, SpringSolver, max_curve_error_pct};
use arc_tokens::{Accent, Locale, ThemeMode, install_arc_theme, set_locale};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct CopyHost {
copied: Rc<Cell<usize>>,
}
impl Render for CopyHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let copied = self.copied.clone();
div().p(Spacing::S4).child(
CopyButton::new("copy-id", "sk-arc-123456")
.label("Copy model id")
.on_copied(cx.listener(move |_, _, _, _| {
copied.set(copied.get() + 1);
})),
)
}
}
#[gpui_kit::test]
fn copy_button_writes_clipboard_and_invokes_callback(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
set_locale(Locale::EnUs, cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
let copied = Rc::new(Cell::new(0usize));
let (_view, cx) = cx.add_window_view(|_, _| CopyHost {
copied: copied.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Copy model id");
assert_eq!(btn.role(), Some(Role::Button));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(copied.get(), 1);
});
cx.read(|cx| {
let clip = cx
.read_from_clipboard()
.and_then(|item| item.text())
.unwrap_or_default();
assert_eq!(clip, "sk-arc-123456");
});
}
#[test]
fn copy_button_resize_spring_matches_0_22s_critically_damped_curve() {
let solver = SpringSolver::new(RESIZE_SPRING, 108.0, 56.0, 0.0);
let omega0 = std::f64::consts::TAU / (0.22 * 1.2);
let mut actual = CurveTrace::new("copy_button", "width");
let mut expected = CurveTrace::new("copy_button", "width");
for frame in 0..=28 {
let t_ms = frame as f64 * 16.0;
let t = t_ms / 1000.0;
let ref_w = 56.0 + (-omega0 * t).exp() * (52.0 + omega0 * 52.0 * t);
expected.push(t_ms, ref_w);
actual.push(t_ms, f64::from(solver.sample(t).value));
}
let err = max_curve_error_pct(&actual, &expected);
assert!(err < 5.0, "CopyButton resize spring error {err:.3}% >= 5%");
}
}