use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{
BlurFallback, CubicBezier, arc_spring, arc_spring_with_options, is_reduced_motion, motion_now,
spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, KeyUpEvent, MouseButton,
ParentElement, PathBuilder, Pixels, RenderOnce, SharedString, Styled, Window, assets::IconName,
base::Button as BaseButton, canvas, div, point, prelude::*, px,
};
type ValueChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ActionSwapTone {
#[default]
Neutral,
Accent,
Success,
Warning,
Quiet,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum ActionSwapSize {
Sm,
#[default]
Md,
Lg,
}
impl ActionSwapSize {
pub const fn height(self) -> Pixels {
match self {
Self::Sm => ControlHeights::SM,
Self::Md => ControlHeights::MD,
Self::Lg => ControlHeights::LG,
}
}
pub const fn pad_x(self) -> Pixels {
match self {
Self::Sm => Spacing::S3,
Self::Md => Spacing::S4,
Self::Lg => Spacing::S5,
}
}
}
#[derive(Clone)]
pub struct ActionSwapState {
pub id: SharedString,
pub label: SharedString,
pub icon: Option<IconName>,
pub tone: ActionSwapTone,
pub pending_label: Option<SharedString>,
pub hold_for: Option<Duration>,
}
impl ActionSwapState {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
tone: ActionSwapTone::Neutral,
pending_label: None,
hold_for: None,
}
}
pub fn icon(mut self, icon: IconName) -> Self {
self.icon = Some(icon);
self
}
pub fn tone(mut self, tone: ActionSwapTone) -> Self {
self.tone = tone;
self
}
pub fn pending_label(mut self, label: impl Into<SharedString>) -> Self {
self.pending_label = Some(label.into());
self
}
pub fn hold_for(mut self, duration: Duration) -> Self {
self.hold_for = Some(duration);
self
}
}
#[derive(Clone)]
struct ActionSwapInternal {
uncontrolled_value: SharedString,
working_target_id: Option<SharedString>,
working_until_secs: Option<f64>,
hold_until_secs: Option<f64>,
last_view_key: SharedString,
morph_armed_until_secs: f64,
phase_changed_at_secs: f64,
hovered: bool,
pressed: bool,
measured_label_w: Rc<RefCell<f32>>,
has_measured: Rc<RefCell<bool>>,
}
impl ActionSwapInternal {
fn new(initial: SharedString, now: f64) -> Self {
Self {
uncontrolled_value: initial.clone(),
working_target_id: None,
working_until_secs: None,
hold_until_secs: None,
last_view_key: initial,
morph_armed_until_secs: f64::NEG_INFINITY,
phase_changed_at_secs: now - 10.0,
hovered: false,
pressed: false,
measured_label_w: Rc::new(RefCell::new(0.0)),
has_measured: Rc::new(RefCell::new(false)),
}
}
}
#[derive(IntoElement)]
pub struct ActionSwap {
id: ElementId,
states: Vec<ActionSwapState>,
value: Option<SharedString>,
default_value: Option<SharedString>,
working_duration: Duration,
size: ActionSwapSize,
disabled: bool,
focus_handle: Option<FocusHandle>,
on_value_change: Option<ValueChangeHandler>,
}
impl ActionSwap {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
states: Vec::new(),
value: None,
default_value: None,
working_duration: Duration::ZERO,
size: ActionSwapSize::Md,
disabled: false,
focus_handle: None,
on_value_change: None,
}
}
pub fn state(mut self, state: ActionSwapState) -> Self {
self.states.push(state);
self
}
pub fn states(mut self, states: impl IntoIterator<Item = ActionSwapState>) -> Self {
self.states.extend(states);
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = Some(value.into());
self
}
pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
self.default_value = Some(value.into());
self
}
pub fn working_duration(mut self, duration: Duration) -> Self {
self.working_duration = duration;
self
}
pub fn size(mut self, size: ActionSwapSize) -> Self {
self.size = size;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus_handle = Some(handle.clone());
self
}
pub fn on_value_change(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_value_change = Some(Rc::new(handler));
self
}
}
fn paint_ring_spinner(
cx: f32,
cy: f32,
radius: f32,
angle_rad: f32,
fg: Hsla,
window: &mut Window,
) {
let track_c = Hsla {
a: fg.a * 0.24,
..fg
};
let mut track = PathBuilder::stroke(px(1.5));
for i in 0..=24 {
let a = std::f32::consts::TAU * (i as f32 / 24.0);
let p = point(px(cx + radius * a.cos()), px(cy + radius * a.sin()));
if i == 0 {
track.move_to(p);
} else {
track.line_to(p);
}
}
if let Ok(path) = track.build() {
window.paint_path(path, track_c);
}
let mut arc = PathBuilder::stroke(px(1.5));
let sweep = std::f32::consts::FRAC_PI_2 * 1.15;
for i in 0..=12 {
let a = angle_rad + sweep * (i as f32 / 12.0);
let p = point(px(cx + radius * a.cos()), px(cy + radius * a.sin()));
if i == 0 {
arc.move_to(p);
} else {
arc.line_to(p);
}
}
if let Ok(path) = arc.build() {
window.paint_path(path, fg);
}
}
impl RenderOnce for ActionSwap {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
if self.states.is_empty() {
return div().id(self.id).into_any_element();
}
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let is_controlled = self.value.is_some();
let initial_id = self
.default_value
.clone()
.unwrap_or_else(|| self.states[0].id.clone());
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-action-swap-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| {
ActionSwapInternal::new(initial_id.clone(), now)
});
{
let snap = internal.read(cx).clone();
let mut committed_next: Option<SharedString> = None;
let mut keep_ticking = false;
if let Some(work_until) = snap.working_until_secs {
if now >= work_until {
let next_id = snap.working_target_id.clone();
if let Some(target_id) = next_id {
let hold = self
.states
.iter()
.find(|s| s.id == target_id)
.and_then(|s| s.hold_for);
internal.update(cx, |s, _| {
s.working_target_id = None;
s.working_until_secs = None;
if !is_controlled {
s.uncontrolled_value = target_id.clone();
}
s.hold_until_secs = hold.map(|d| now + d.as_secs_f64());
});
committed_next = Some(target_id);
}
} else {
keep_ticking = true;
}
} else if let Some(hold_until) = snap.hold_until_secs {
if now >= hold_until {
let cur_val = self
.value
.clone()
.unwrap_or_else(|| snap.uncontrolled_value.clone());
let cur_idx = self
.states
.iter()
.position(|s| s.id == cur_val)
.unwrap_or(0);
let next_state = &self.states[(cur_idx + 1) % self.states.len()];
let next_id = next_state.id.clone();
let next_hold = next_state.hold_for;
internal.update(cx, |s, _| {
if !is_controlled {
s.uncontrolled_value = next_id.clone();
}
s.hold_until_secs = next_hold.map(|d| now + d.as_secs_f64());
});
committed_next = Some(next_id);
} else {
keep_ticking = true;
}
}
if let Some(next_id) = committed_next
&& let Some(handler) = &self.on_value_change
{
handler(&next_id, window, cx);
}
if keep_ticking {
window.request_animation_frame();
}
}
let snap = internal.read(cx).clone();
let active_value = self
.value
.clone()
.unwrap_or_else(|| snap.uncontrolled_value.clone());
let active_idx = self
.states
.iter()
.position(|s| s.id == active_value)
.unwrap_or(0);
let active_state = &self.states[active_idx];
let next_state = &self.states[(active_idx + 1) % self.states.len()];
let working_target = snap
.working_target_id
.as_ref()
.and_then(|id| self.states.iter().find(|s| &s.id == id));
let working = working_target.is_some();
let folded = working_target.is_some_and(|t| t.pending_label.is_none());
let (view_key, view_label, view_tone, view_icon): (
SharedString,
SharedString,
ActionSwapTone,
Option<IconName>,
) = if let Some(target) = working_target {
let lbl = target.pending_label.clone().unwrap_or_default();
(
SharedString::from(format!("working:{lbl}")),
lbl,
active_state.tone,
None,
)
} else {
(
SharedString::from(format!("state:{}", active_state.id)),
active_state.label.clone(),
active_state.tone,
active_state.icon,
)
};
if snap.last_view_key != view_key {
internal.update(cx, |s, _| {
s.last_view_key = view_key.clone();
s.morph_armed_until_secs = now + 0.7;
s.phase_changed_at_secs = now;
});
}
let snap = internal.read(cx).clone();
let inactive = self.disabled || self.states.len() < 2;
let inert = inactive || working;
let fold = if reduced {
if folded { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "fold"),
if folded { 1.0 } else { 0.0 },
motion.spring.morph,
window,
cx,
)
.clamp(0.0, 1.0)
};
let h_px = f32::from(self.size.height());
let base_pad = f32::from(self.size.pad_x());
let circle_pad = ((h_px - 18.0) * 0.5).max(8.0);
let pad_x = base_pad + (circle_pad - base_pad) * fold;
let target_label_w = if folded {
0.0
} else {
*snap.measured_label_w.borrow()
};
let morph_active =
!reduced && *snap.has_measured.borrow() && now <= snap.morph_armed_until_secs;
let morphed_label_w = if *snap.has_measured.borrow() {
let sample = arc_spring_with_options(
(self.id.clone(), "label-width"),
target_label_w,
SpringOptions::new(motion.spring.morph),
window,
cx,
);
if morph_active || folded {
Some(sample.value.max(0.0))
} else {
None
}
} else {
None
};
let elapsed = (now - snap.phase_changed_at_secs).max(0.0);
let dur = if reduced {
motion.duration.instant.as_secs_f64()
} else {
motion.duration.standard.as_secs_f64()
};
let (phase_op, phase_y) = if elapsed < dur {
window.request_animation_frame();
let t = (elapsed / dur).clamp(0.0, 1.0) as f32;
let e = if reduced {
t
} else {
CubicBezier::from_spec(motion.ease.enter).sample(t)
};
let blur = BlurFallback::evaluate(px((1.0 - e) * f32::from(motion.blur.soft)), reduced);
(
(e * blur.opacity_multiplier).clamp(0.0, 1.0),
if reduced { 0.0 } else { 4.0 * (1.0 - e) },
)
} else {
(1.0, 0.0)
};
let hovered = !inert && snap.hovered;
let (bg, border, fg, icon_tint) = match view_tone {
ActionSwapTone::Neutral => {
let c = if hovered {
colors.text_secondary
} else {
colors.foreground
};
(c, c, colors.background, colors.background)
}
ActionSwapTone::Accent => {
let c = if hovered {
colors.accent_strong
} else {
colors.accent
};
(c, c, colors.accent_foreground, colors.accent_foreground)
}
ActionSwapTone::Quiet => (
if hovered {
colors.surface_muted
} else {
colors.surface
},
if hovered {
colors.border_strong
} else {
colors.border
},
colors.foreground,
colors.foreground,
),
ActionSwapTone::Success => (
oklab_mix(colors.success, colors.surface, 0.10),
oklab_mix(
colors.success,
colors.border,
if hovered { 0.42 } else { 0.25 },
),
colors.foreground,
colors.success,
),
ActionSwapTone::Warning => (
oklab_mix(colors.warning, colors.surface, 0.12),
oklab_mix(
colors.warning,
colors.border,
if hovered { 0.48 } else { 0.30 },
),
colors.foreground,
colors.warning,
),
};
let backdrop = div()
.absolute()
.inset_0()
.rounded(Radii::PILL)
.bg(bg)
.border_1()
.border_color(border)
.when(snap.pressed && !inert, |this| this.opacity(0.92));
let label_w_ref = snap.measured_label_w.clone();
let has_m_ref = snap.has_measured.clone();
let label_probe = canvas(
move |rect, window, _| {
let w = f32::from(rect.size.width);
let prev = *label_w_ref.borrow();
if w > 0.0 {
*label_w_ref.borrow_mut() = w;
*has_m_ref.borrow_mut() = true;
}
if (w - prev).abs() > 0.5 && prev > 0.0 {
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let icon_slot = if working {
let spin_angle = if reduced {
0.0
} else {
window.request_animation_frame();
((now % 0.75) / 0.75) as f32 * std::f32::consts::TAU
};
Some(
div()
.w(px(16.0))
.h(px(16.0))
.flex_none()
.child(
canvas(
|_, _, _| {},
move |rect, _, window, _| {
let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
paint_ring_spinner(cx, cy, 6.2, spin_angle, fg, window);
},
)
.size_full(),
)
.into_any_element(),
)
} else {
view_icon.map(|icon| {
div()
.w(px(16.0))
.h(px(16.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.text_color(icon_tint)
.opacity(phase_op)
.child(icon)
.into_any_element()
})
};
let has_icon = icon_slot.is_some();
let has_text = !view_label.is_empty();
let next_id_for_click = next_state.id.clone();
let next_hold_for_click = next_state.hold_for;
let work_secs = self.working_duration.as_secs_f64();
let on_change = self.on_value_change;
let int_click = internal.clone();
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_kd = internal.clone();
let int_ku = internal.clone();
let mut base = BaseButton::new(self.id.clone())
.disabled(inactive)
.accessibility_label(if view_label.is_empty() {
active_state.label.clone()
} else {
view_label.clone()
})
.on_click(move |_, window, cx| {
if inert {
return;
}
let t_now = motion_now(cx);
if work_secs > 0.0 {
int_click.update(cx, |s, _| {
s.hold_until_secs = None;
s.working_target_id = Some(next_id_for_click.clone());
s.working_until_secs = Some(t_now + work_secs);
});
} else {
int_click.update(cx, |s, _| {
if !is_controlled {
s.uncontrolled_value = next_id_for_click.clone();
}
s.hold_until_secs = next_hold_for_click.map(|d| t_now + d.as_secs_f64());
});
if let Some(handler) = &on_change {
handler(&next_id_for_click, 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()
.min_w(self.size.height())
.min_h(self.size.height())
.px(px(pad_x))
.rounded(Radii::PILL)
.overflow_hidden()
.text_size(Typography::TEXT_SM)
.text_color(fg)
.when(inactive, |this| this.opacity(0.6))
.when(!inert, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
s.hovered = *hovered;
if !*hovered {
s.pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if inert {
return;
}
int_down.update(cx, |s, _| s.pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if inert {
return;
}
if event.keystroke.key == "space" || event.keystroke.key == "enter" {
int_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" {
int_ku.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
.child(backdrop)
.when_some(icon_slot, |this, icon| this.child(icon))
.child(
div()
.relative()
.flex()
.items_center()
.when_some(morphed_label_w, |this, w| this.w(px(w)).overflow_hidden())
.child(
div()
.relative()
.flex_none()
.when(has_icon && has_text, |this| this.pl(Spacing::S2))
.mt(px(phase_y))
.opacity(if folded { 0.0 } else { phase_op })
.child(label_probe)
.child(view_label),
),
)
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use std::{cell::RefCell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct SwapHost {
last: Rc<RefCell<SharedString>>,
}
impl Render for SwapHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let last = self.last.clone();
div().p(Spacing::S4).child(
ActionSwap::new("send-swap")
.default_value("send")
.states([
ActionSwapState::new("send", "Send").tone(ActionSwapTone::Neutral),
ActionSwapState::new("sent", "Sent").tone(ActionSwapTone::Success),
])
.on_value_change(cx.listener(move |_, val: &SharedString, _, _| {
*last.borrow_mut() = val.clone();
})),
)
}
}
#[gpui_kit::test]
fn action_swap_advances_through_state_cycle(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let last = Rc::new(RefCell::new(SharedString::from("")));
let (_view, cx) = cx.add_window_view(|_, _| SwapHost { last: last.clone() });
cx.update(|window, cx| {
window.render_frame(cx);
let btn = window.find_by_label("Send");
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!(*last.borrow(), "sent");
});
}
}