use arc_motion::{
CubicBezier, ScalarTween, SpringSolver, TweenEase, is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, SpringSpec};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, MouseButton, MouseMoveEvent,
MouseUpEvent, ParentElement, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
Window, assets::IconName, base::StyledExt as _, canvas, div, prelude::*, px, svg,
};
use std::{cell::RefCell, collections::VecDeque, rc::Rc};
type ActionHandler = Rc<dyn Fn(&SwipeRowAction, &mut Window, &mut App)>;
type OpenHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
type HapticHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
#[derive(Clone)]
pub struct SwipeRowAction {
pub id: SharedString,
pub label: SharedString,
pub icon: Option<IconName>,
pub color: Option<Hsla>,
pub dismiss: bool,
pub on_select: Option<ActionHandler>,
}
impl SwipeRowAction {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
icon: None,
color: None,
dismiss: false,
on_select: None,
}
}
pub fn icon(mut self, v: IconName) -> Self {
self.icon = Some(v);
self
}
pub fn color(mut self, v: Hsla) -> Self {
self.color = Some(v);
self
}
pub fn dismiss(mut self, v: bool) -> Self {
self.dismiss = v;
self
}
pub fn on_select(mut self, v: impl Fn(&Self, &mut Window, &mut App) + 'static) -> Self {
self.on_select = Some(Rc::new(v));
self
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum SwipeRowDirection {
#[default]
Left,
Right,
}
impl SwipeRowDirection {
fn sign(self) -> f32 {
if self == Self::Left { -1. } else { 1. }
}
}
#[derive(Clone, Debug)]
pub struct SwipeRowConfig {
pub action_color: Option<Hsla>,
pub drawer_color: Option<Hsla>,
pub row_color: Option<Hsla>,
pub text_color: Option<Hsla>,
pub height: f32,
pub radius: f32,
pub action_width: f32,
pub direction: SwipeRowDirection,
pub snap_bounce: f32,
pub resistance: f32,
pub collapse_ms: f32,
pub commit_at: f32,
pub full_swipe: bool,
pub disabled: bool,
pub close_on_action: bool,
pub haptic: bool,
pub margin_bottom: f32,
}
impl Default for SwipeRowConfig {
fn default() -> Self {
Self {
action_color: None,
drawer_color: None,
row_color: None,
text_color: None,
height: 64.,
radius: 16.,
action_width: 80.,
direction: SwipeRowDirection::Left,
snap_bounce: 0.2,
resistance: 0.55,
collapse_ms: 200.,
commit_at: 0.6,
full_swipe: true,
disabled: false,
close_on_action: true,
haptic: true,
margin_bottom: 0.,
}
}
}
impl SwipeRowConfig {
fn normalized(&self) -> Self {
let mut c = self.clone();
let d = Self::default();
macro_rules! norm {
($f:ident,$lo:expr,$hi:expr) => {
c.$f = if c.$f.is_finite() {
c.$f.clamp($lo, $hi)
} else {
d.$f
};
};
}
norm!(height, 44., 240.);
norm!(radius, 0., 120.);
c.radius = c.radius.min(c.height / 2.);
norm!(action_width, 44., 240.);
norm!(snap_bounce, 0., 0.9);
norm!(resistance, 0.05, 1.);
norm!(collapse_ms, 0., 5000.);
norm!(commit_at, 0., 1.);
norm!(margin_bottom, 0., 80.);
c
}
}
#[derive(Clone, Copy)]
struct Geometry {
width: f32,
drawer: f32,
action: f32,
c: f32,
commit: f32,
can_commit: bool,
}
impl Geometry {
fn new(c: &SwipeRowConfig, n: usize, width: f32) -> Self {
let width = width.max(1.);
let drawer = n as f32 * c.action_width;
let commit = (c.commit_at * width).max(drawer + c.action_width / 2.);
Self {
width,
drawer,
action: c.action_width,
c: c.resistance,
commit,
can_commit: c.full_swipe && n > 0 && commit <= width,
}
}
fn rubber(&self, x: f32) -> f32 {
x * self.width * self.c / (self.width + self.c * x.abs())
}
fn unrubber(&self, x: f32) -> f32 {
x * self.width / (self.c * (self.width - x.abs()).max(1.))
}
fn map(&self, raw: f32) -> f32 {
if raw < 0. {
return self.rubber(raw);
}
if raw <= self.drawer {
return raw;
}
if !self.can_commit {
return self.drawer + self.rubber(raw - self.drawer);
}
let knee = self.drawer + (self.commit - self.drawer) / self.c;
if raw <= knee {
self.drawer + self.c * (raw - self.drawer)
} else {
self.commit + self.rubber(raw - knee)
}
}
fn inv(&self, ex: f32) -> f32 {
if ex < 0. {
return self.unrubber(ex);
}
if ex <= self.drawer {
return ex;
}
if !self.can_commit {
return self.drawer + self.unrubber(ex - self.drawer);
}
let knee = self.drawer + (self.commit - self.drawer) / self.c;
if ex <= self.commit {
self.drawer + (ex - self.drawer) / self.c
} else {
knee + self.unrubber(ex - self.commit)
}
}
fn release_target(&self, ex: f32, v: f32) -> f32 {
if v.abs() >= 110. {
if v > 0. { self.drawer } else { 0. }
} else if ex + (v / 1000.) * 0.998 / (1. - 0.998) > self.drawer / 2. {
self.drawer
} else {
0.
}
}
}
fn curve() -> TweenEase {
TweenEase::CubicBezier(CubicBezier::new(0.23, 1., 0.32, 1.))
}
struct Channel {
value: f32,
target: f32,
start: f64,
duration: f32,
spring: Option<SpringSolver>,
tween: ScalarTween,
}
impl Channel {
fn new(v: f32) -> Self {
Self {
value: v,
target: v,
start: 0.,
duration: 0.,
spring: None,
tween: ScalarTween::new(v),
}
}
fn set(&mut self, v: f32) {
*self = Self::new(v);
}
fn spring(&mut self, target: f32, now: f64, duration: f32, bounce: f32) {
self.target = target;
self.start = now;
self.duration = duration;
self.spring = Some(SpringSolver::new(
SpringSpec::duration(duration, bounce),
self.value as f64,
target as f64,
0.,
));
}
fn ease(&mut self, target: f32, now: f64, duration: f32) {
self.spring = None;
self.tween = ScalarTween::new(self.value);
self.tween
.retarget(target, now, duration, 0., curve(), false);
self.target = target;
self.start = now;
self.duration = duration;
}
fn tick(&mut self, now: f64) -> bool {
if self.value == self.target && self.duration == 0. {
return false;
}
let elapsed = (now - self.start).max(0.);
if elapsed >= self.duration as f64 {
self.set(self.target);
return false;
}
self.value = if let Some(s) = &self.spring {
s.sample(elapsed).value
} else {
self.tween.sample(now)
};
true
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Phase {
Idle,
Committing,
Collapsing,
Done,
}
struct Grip {
x0: f32,
y0: f32,
grab: Option<f32>,
vertical: bool,
hist: VecDeque<(f64, f32)>,
ax: f32,
ay: f32,
}
#[derive(Clone)]
struct Props {
config: SwipeRowConfig,
actions: Vec<SwipeRowAction>,
controlled: Option<bool>,
on_open: Option<OpenHandler>,
on_action: Option<ActionHandler>,
on_commit: Option<ActionHandler>,
on_haptic: Option<HapticHandler>,
}
struct State {
props: Props,
width: f32,
open: bool,
phase: Phase,
x: Channel,
spread: Channel,
landed: Channel,
fold: ScalarTween,
grip: Option<Grip>,
pending: Option<SwipeRowAction>,
focus: FocusHandle,
action_focus: Vec<FocusHandle>,
say: SharedString,
}
type Cell = Rc<RefCell<State>>;
impl State {
fn geometry(&self) -> Geometry {
Geometry::new(&self.props.config, self.props.actions.len(), self.width)
}
fn interactive(&self) -> bool {
!self.props.config.disabled && self.phase == Phase::Idle && !self.props.actions.is_empty()
}
fn effective_open(&self) -> bool {
self.props.controlled.unwrap_or(self.open)
}
fn change_open(&mut self, next: bool) -> Option<OpenHandler> {
if self.effective_open() == next {
return None;
}
self.open = next;
self.props.on_open.clone()
}
fn settle(&mut self, target: f32, v: f32, now: f64, reduced: bool) {
if reduced {
self.x.ease(target, now, 0.2);
} else {
self.x.spring(
target,
now,
if v.abs() >= 110. { 0.4 } else { 0.3 },
if v.abs() >= 110. {
self.props.config.snap_bounce
} else {
0.
},
);
}
}
fn spread(&mut self, on: bool, now: f64, reduced: bool) -> bool {
let target = if on { 1. } else { 0. };
if self.spread.target == target {
return false;
}
if reduced {
self.spread.set(target);
} else {
self.spread.spring(target, now, 0.3, 0.);
}
if on && let Some(a) = self.props.actions.first() {
self.say = format!("Release to {}", a.label).into();
}
on && self.props.config.haptic
}
fn commit(
&mut self,
action: SwipeRowAction,
primary: bool,
key: bool,
now: f64,
reduced: bool,
) -> Option<OpenHandler> {
self.phase = Phase::Committing;
self.grip = None;
self.say = action.label.clone();
self.pending = Some(action);
let cb = self.change_open(false);
if primary {
self.spread(true, now, reduced || key);
if reduced || key {
self.landed.set(1.);
} else {
self.landed.spring(1., now, 0.3, 0.);
}
}
if key {
self.x.set(self.width);
self.start_fold(now);
} else if reduced {
self.x.ease(self.width, now, 0.2);
} else {
self.x.spring(self.width, now, 0.3, 0.);
}
cb
}
fn start_fold(&mut self, now: f64) {
self.phase = Phase::Collapsing;
self.fold.retarget(
0.,
now,
self.props.config.collapse_ms / 1000.,
0.,
curve(),
false,
);
}
fn advance(&mut self, now: f64) -> (bool, Option<SwipeRowAction>) {
let mut running = self.x.tick(now) | self.spread.tick(now) | self.landed.tick(now);
if self.phase == Phase::Committing && !running {
self.start_fold(now);
}
if self.phase == Phase::Collapsing {
running |= !self.fold.settled(now);
if self.fold.settled(now) {
self.phase = Phase::Done;
return (false, self.pending.take());
}
}
(running, None)
}
}
fn notify_open(cb: Option<OpenHandler>, next: bool, window: &mut Window, cx: &mut App) {
if let Some(cb) = cb {
cb(&next, window, cx);
}
}
fn toggle(cell: &Cell, next: bool, window: &mut Window, cx: &mut App) {
let cb = {
let mut s = cell.borrow_mut();
if !s.interactive() {
return;
}
let cb = s.change_open(next);
let target = if next { s.geometry().drawer } else { 0. };
s.x.set(target);
s.spread.set(0.);
s.say = if next {
format!("{} actions revealed", s.props.actions.len()).into()
} else {
"Actions closed".into()
};
cb
};
notify_open(cb, next, window, cx);
window.refresh();
}
fn act(cell: &Cell, index: usize, key: bool, window: &mut Window, cx: &mut App) {
let now = motion_now(cx);
let red = is_reduced_motion(cx);
let (a, on_action) = {
let s = cell.borrow();
if !s.interactive() || !s.effective_open() {
return;
}
let Some(a) = s.props.actions.get(index).cloned() else {
return;
};
(a, s.props.on_action.clone())
};
if let Some(cb) = on_action {
cb(&a, window, cx);
}
if index == 0 || a.dismiss {
let cb = cell.borrow_mut().commit(a, index == 0, key, now, red);
notify_open(cb, false, window, cx);
} else {
if let Some(cb) = &a.on_select {
cb(&a, window, cx);
}
let cb = {
let mut s = cell.borrow_mut();
if !s.props.config.close_on_action {
return;
}
let cb = s.change_open(false);
if key {
s.x.set(0.);
} else {
s.settle(0., 0., now, red);
}
cb
};
notify_open(cb, false, window, cx);
}
window.refresh();
}
fn release(cell: &Cell, cancelled: bool, window: &mut Window, cx: &mut App) {
let now = motion_now(cx);
let red = is_reduced_motion(cx);
let result = {
let mut s = cell.borrow_mut();
let Some(g) = s.grip.take() else {
return;
};
if g.vertical {
return;
}
let geo = s.geometry();
if cancelled {
s.spread(false, now, red);
let target = if s.effective_open() { geo.drawer } else { 0. };
s.settle(target, 0., now, red);
None
} else if g.grab.is_none() {
if s.effective_open() {
let cb = s.change_open(false);
s.settle(0., 0., now, red);
Some((cb, false))
} else {
None
}
} else {
let v = match (g.hist.front(), g.hist.back()) {
(Some(a), Some(b)) => {
((b.1 - a.1) / ((b.0 - a.0).max(0.001) as f32)).clamp(-1500., 1500.)
}
_ => 0.,
};
if geo.can_commit && s.x.value >= geo.commit {
let a = s.props.actions[0].clone();
let cb = s.commit(a, true, false, now, red);
Some((cb, false))
} else {
let target = geo.release_target(s.x.value, v);
s.spread(false, now, red);
let next = target == geo.drawer;
let cb = s.change_open(next);
s.settle(target, v, now, red);
Some((cb, next))
}
}
};
if let Some((cb, next)) = result {
notify_open(cb, next, window, cx);
}
window.refresh();
}
#[derive(IntoElement)]
pub struct SwipeRow {
id: ElementId,
body: Option<AnyElement>,
label: SharedString,
props: Props,
default_open: bool,
}
impl SwipeRow {
pub fn new(id: impl Into<ElementId>, body: impl IntoElement) -> Self {
Self {
id: id.into(),
body: Some(body.into_any_element()),
label: "List item".into(),
default_open: false,
props: Props {
config: Default::default(),
actions: vec![SwipeRowAction::new("delete", "Delete")],
controlled: None,
on_open: None,
on_action: None,
on_commit: None,
on_haptic: None,
},
}
}
pub fn config(mut self, c: SwipeRowConfig) -> Self {
self.props.config = c;
self
}
pub fn actions(mut self, v: impl IntoIterator<Item = SwipeRowAction>) -> Self {
self.props.actions = v.into_iter().collect();
self
}
pub fn label(mut self, v: impl Into<SharedString>) -> Self {
self.label = v.into();
self
}
pub fn default_open(mut self, v: bool) -> Self {
self.default_open = v;
self
}
pub fn open(mut self, v: bool) -> Self {
self.props.controlled = Some(v);
self
}
pub fn disabled(mut self, v: bool) -> Self {
self.props.config.disabled = v;
self
}
pub fn on_open_change(mut self, v: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
self.props.on_open = Some(Rc::new(v));
self
}
pub fn on_action(
mut self,
v: impl Fn(&SwipeRowAction, &mut Window, &mut App) + 'static,
) -> Self {
self.props.on_action = Some(Rc::new(v));
self
}
pub fn on_commit(
mut self,
v: impl Fn(&SwipeRowAction, &mut Window, &mut App) + 'static,
) -> Self {
self.props.on_commit = Some(Rc::new(v));
self
}
pub fn on_haptic(mut self, v: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
self.props.on_haptic = Some(Rc::new(v));
self
}
}
fn on_color(c: Hsla) -> Hsla {
let rgb: gpui_kit::Rgba = c.into();
if (rgb.r * 299. + rgb.g * 587. + rgb.b * 114.) / 1000. >= 150. / 255. {
arc_tokens::hex(0x111111, 1.)
} else {
arc_tokens::hex(0xffffff, 1.)
}
}
impl RenderOnce for SwipeRow {
fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let now = motion_now(cx);
let red = is_reduced_motion(cx);
let colors = cx.arc_theme().colors;
self.props.config = self.props.config.normalized();
let config = self.props.config.clone();
let p = self.props.clone();
let initial_open = p.controlled.unwrap_or(self.default_open) && !p.actions.is_empty();
let cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "state".into()),
cx,
move |_, cx| {
let focus = cx.focus_handle().tab_index(0).tab_stop(true);
Rc::new(RefCell::new(State {
x: Channel::new(if initial_open {
p.actions.len() as f32 * p.config.action_width
} else {
0.
}),
props: p,
width: 360.,
open: initial_open,
phase: Phase::Idle,
spread: Channel::new(0.),
landed: Channel::new(0.),
fold: ScalarTween::new(1.),
grip: None,
pending: None,
focus,
action_focus: Vec::new(),
say: "".into(),
}))
},
)
.read(cx)
.clone();
let (running, pending) = {
let mut s = cell.borrow_mut();
let (mut running, pending) = s.advance(now);
let shape_changed = s.props.actions.iter().map(|a| &a.id).ne(self
.props
.actions
.iter()
.map(|a| &a.id))
|| s.props.config.direction != config.direction;
s.props = self.props.clone();
if s.phase == Phase::Idle {
if (config.disabled || shape_changed) && s.grip.take().is_some() {
s.spread(false, now, red);
let target = if s.effective_open() {
s.geometry().drawer
} else {
0.
};
s.settle(target, 0., now, red);
}
if shape_changed {
s.open = false;
s.x.set(0.);
}
if s.grip.is_none() {
let target = if s.effective_open() && !s.props.actions.is_empty() {
s.geometry().drawer
} else {
0.
};
if s.props.controlled.is_some() || shape_changed || s.props.actions.is_empty() {
if s.x.target != target {
s.settle(target, 0., now, red);
}
} else if s.open && s.x.target != target {
s.settle(target, 0., now, red);
}
}
}
while s.action_focus.len() < s.props.actions.len() {
s.action_focus
.push(cx.focus_handle().tab_index(0).tab_stop(true));
}
running |= s.x.duration > 0. || s.spread.duration > 0. || s.landed.duration > 0.;
(running, pending)
};
if running {
window.request_animation_frame();
}
if let Some(a) = pending {
let cb = self.props.on_commit.clone();
window.defer(cx, move |window, cx| {
if let Some(cb) = cb {
cb(&a, window, cx);
}
if let Some(cb) = &a.on_select {
cb(&a, window, cx);
}
});
}
let s = cell.borrow();
let ex = s.x.value;
let spread = s.spread.value;
let landed = s.landed.value;
let w = s.width;
let geo = s.geometry();
let open = s.effective_open();
let interactive = s.interactive();
let phase = s.phase;
let focus = s.focus.clone();
let action_focus = s.action_focus.clone();
let fold = s.fold.sample(now);
let say = s.say.clone();
let dragging = s.grip.as_ref().is_some_and(|g| g.grab.is_some());
drop(s);
let active = interactive && open;
let _ = focus.clone().tab_stop(interactive);
for fh in &action_focus {
let _ = fh.clone().tab_stop(active);
}
if !active && action_focus.iter().any(|fh| fh.is_focused(window)) {
if interactive {
window.focus(&focus, cx);
} else {
window.blur(cx);
}
}
let row_color = config.row_color.unwrap_or(colors.surface_muted);
let text = config.text_color.unwrap_or(colors.foreground);
let drawer = config.drawer_color.unwrap_or(colors.border_strong);
let primary = config.action_color.unwrap_or(colors.danger);
let sign = config.direction.sign();
let rail_offset = -sign * (geo.drawer - ex).max(0.);
let shift = spread * (ex - geo.action).max(0.);
let mut rail = div()
.absolute()
.top_0()
.left(px(rail_offset))
.w_full()
.h(px(config.height))
.bg(drawer);
for (i, a) in self.props.actions.iter().enumerate().skip(1) {
let bg = a.color.unwrap_or(drawer);
let st = cell.clone();
let fh = action_focus[i].clone();
let mouse_focus = fh.clone();
let button = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("action-{}", a.id).into(),
))
.test_support()
.role(Role::Button)
.aria_label(a.label.clone())
.absolute()
.top_0()
.w(px(geo.action))
.h(px(config.height))
.when(sign < 0., |el| el.right(px(i as f32 * geo.action)))
.when(sign > 0., |el| el.left(px(i as f32 * geo.action)))
.bg(bg)
.text_color(on_color(bg))
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(4.))
.when(active, |el| {
el.track_focus(&fh)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
window.focus(&mouse_focus, cx);
})
.on_click(move |e, window, cx| {
cx.stop_propagation();
act(&st, i, e.is_keyboard(), window, cx);
})
})
.when(!active, |el| el.tab_stop(false))
.when(fh.is_focused(window), |el| el.border_2().border_color(text))
.children(a.icon.map(|ic| svg().path(ic.path()).size(px(20.))))
.child(
div()
.text_size(px(11.))
.font_medium()
.child(a.label.clone()),
);
rail = rail.child(button);
}
if let Some(a) = self.props.actions.first() {
let base = if sign < 0. {
w - geo.action
} else {
geo.action - w
};
let block_left = base + sign * shift;
let glyph_shift = -sign * landed * (shift - (w - geo.action) / 2.);
let glyph_base = if sign < 0. { 0. } else { w - geo.action };
let st = cell.clone();
let fh = action_focus[0].clone();
let mouse_focus = fh.clone();
rail = rail.child(
div()
.absolute()
.top_0()
.left(px(block_left))
.w(px(w))
.h(px(config.height))
.bg(primary)
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
format!("action-{}", a.id).into(),
))
.test_support()
.role(Role::Button)
.aria_label(a.label.clone())
.absolute()
.top_0()
.left(px(glyph_base + glyph_shift))
.w(px(geo.action))
.h(px(config.height))
.text_color(on_color(primary))
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(4.))
.when(active, |el| {
el.track_focus(&fh)
.cursor_pointer()
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
window.focus(&mouse_focus, cx);
})
.on_click(move |e, window, cx| {
cx.stop_propagation();
act(&st, 0, e.is_keyboard(), window, cx);
})
})
.when(!active, |el| el.tab_stop(false))
.when(fh.is_focused(window), |el| el.border_2().border_color(text))
.child(
svg()
.path(a.icon.unwrap_or(IconName::Trash).path())
.size(px(20.)),
)
.child(
div()
.text_size(px(11.))
.font_medium()
.child(a.label.clone()),
),
),
);
}
let draw_state = cell.clone();
let measure = cell.clone();
let key_state = cell.clone();
let down_state = cell.clone();
let toggle_state = cell.clone();
let touch_state = cell.clone();
let tap_state = cell.clone();
let probe = canvas(
move |bounds, _, _| {
measure.borrow_mut().width = f32::from(bounds.size.width).max(1.);
},
move |_, _, window, _| {
if draw_state.borrow().grip.is_none() {
return;
}
let st = draw_state.clone();
window.on_mouse_event(move |e: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() {
return;
}
if st.borrow().grip.is_none() {
return;
}
if e.pressed_button != Some(MouseButton::Left) {
release(&st, true, window, cx);
return;
}
let now = motion_now(cx);
let red = is_reduced_motion(cx);
let (moved, haptic) = {
let mut s = st.borrow_mut();
let geo = s.geometry();
let sign = s.props.config.direction.sign();
let origin = geo.inv(s.x.value);
let Some(g) = s.grip.as_mut() else {
return;
};
if g.vertical {
return;
}
let x = f32::from(e.position.x);
let y = f32::from(e.position.y);
if g.grab.is_none() {
let dx = x - g.x0;
let dy = y - g.y0;
if dy.abs() >= 10. && dy.abs() > dx.abs() {
g.vertical = true;
return;
}
if dx.abs() < 10. || dx.abs() < dy.abs() {
return;
}
g.grab = Some(sign * (g.x0 + dx.signum() * 10.) - origin);
}
let ex = geo.map(sign * x - g.grab.unwrap());
g.hist.push_back((now, ex));
while g.hist.len() > 4 {
g.hist.pop_front();
}
s.x.set(ex);
let haptic = s.spread(geo.can_commit && ex >= geo.commit, now, red);
(
true,
if haptic && window.last_input_was_touch() {
s.props.on_haptic.clone()
} else {
None
},
)
};
if let Some(cb) = haptic {
cb(&(), window, cx);
}
if moved {
cx.stop_propagation();
window.refresh();
}
});
let st = draw_state.clone();
window.on_mouse_event(move |e: &MouseUpEvent, phase, window, cx| {
if phase.bubble() && e.button == MouseButton::Left {
release(&st, false, window, cx);
}
});
},
)
.absolute()
.size_full();
let toggle_visible = focus.is_focused(window) && interactive;
let mouse_focus = focus.clone();
let surface = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"surface".into(),
))
.test_support()
.absolute()
.top_0()
.left(px(sign * ex))
.w_full()
.h(px(config.height))
.px(px(16.))
.bg(row_color)
.text_color(text)
.flex()
.items_center()
.gap(px(12.))
.when(interactive, |el| el.cursor_grab())
.when(dragging, |el| el.cursor_grabbing())
.children(self.body.take())
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
if window.last_input_was_touch() {
release(&tap_state, false, window, cx);
}
})
.on_mouse_down(MouseButton::Left, move |e, window, cx| {
let mut s = down_state.borrow_mut();
if !s.interactive() {
return;
}
let v = s.x.value;
s.x.set(v);
s.grip = Some(Grip {
x0: f32::from(e.position.x),
y0: f32::from(e.position.y),
grab: None,
vertical: false,
hist: VecDeque::with_capacity(4),
ax: 0.,
ay: 0.,
});
window.refresh();
let _ = cx;
})
.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"toggle".into(),
))
.test_support()
.role(Role::Button)
.aria_label(format!("{} actions", self.props.actions.len()))
.aria_expanded(open)
.when(interactive, |el| el.track_focus(&focus))
.when(!interactive, |el| el.tab_stop(false))
.absolute()
.top(px(if toggle_visible {
(config.height - 24.) / 2.
} else {
config.height / 2.
}))
.when(sign < 0., |el| el.right(px(12.)))
.when(sign > 0., |el| el.left(px(12.)))
.w(px(if toggle_visible { 90. } else { 1. }))
.h(px(if toggle_visible { 24. } else { 1. }))
.overflow_hidden()
.rounded(px(12.))
.when(toggle_visible, |el| {
el.bg(row_color)
.border_1()
.border_color(text)
.flex()
.items_center()
.justify_center()
.text_size(px(12.))
.child(format!("{} actions", self.props.actions.len()))
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
window.focus(&mouse_focus, cx);
})
.on_click(move |e, window, cx| {
cx.stop_propagation();
if e.is_keyboard() {
let next = !toggle_state.borrow().effective_open();
toggle(&toggle_state, next, window, cx);
}
})
.on_key_down(move |e, window, cx| {
let key = e.keystroke.key.as_str();
let (ok, open, dir, can) = {
let s = key_state.borrow();
(
s.interactive(),
s.effective_open(),
s.props.config.direction,
s.geometry().can_commit,
)
};
if !ok {
return;
}
let open_key = if dir == SwipeRowDirection::Left {
"left"
} else {
"right"
};
let close_key = if dir == SwipeRowDirection::Left {
"right"
} else {
"left"
};
if key == open_key {
toggle(&key_state, true, window, cx);
} else if key == close_key || key == "escape" {
toggle(&key_state, false, window, cx);
} else if (key == "delete" || key == "backspace") && open && can {
let a = key_state.borrow().props.actions[0].clone();
let cb = key_state.borrow_mut().commit(
a,
true,
true,
motion_now(cx),
is_reduced_motion(cx),
);
notify_open(cb, false, window, cx);
window.refresh();
} else {
return;
}
cx.stop_propagation();
window.prevent_default();
}),
);
div()
.id(self.id)
.test_support()
.role(Role::Group)
.aria_label(format!(
"{} {}{}",
self.label,
say,
if config.disabled { " · disabled" } else { "" }
))
.on_scroll(move |e, window, cx| {
if !window.last_input_was_touch() {
return;
}
let delta = e.delta.pixel_delta(px(16.));
let dx = f32::from(delta.x);
let dy = f32::from(delta.y);
let now = motion_now(cx);
let red = is_reduced_motion(cx);
let ended = matches!(
e.touch_phase,
gpui_kit::TouchPhase::Ended | gpui_kit::TouchPhase::Cancelled
);
if ended {
release(
&touch_state,
e.touch_phase == gpui_kit::TouchPhase::Cancelled,
window,
cx,
);
cx.stop_propagation();
return;
}
let (moved, haptic) = {
let mut s = touch_state.borrow_mut();
if !s.interactive() {
return;
}
let sign = s.props.config.direction.sign();
if e.touch_phase == gpui_kit::TouchPhase::Started {
s.grip = Some(Grip {
x0: s.geometry().inv(s.x.value),
y0: 0.,
grab: None,
vertical: false,
hist: VecDeque::with_capacity(4),
ax: 0.,
ay: 0.,
});
}
let geo = s.geometry();
let Some(g) = s.grip.as_mut() else {
return;
};
if g.vertical {
return;
}
g.ax += sign * dx;
g.ay += dy;
if g.grab.is_none() {
if g.ay.abs() >= 10. && g.ay.abs() > g.ax.abs() {
g.vertical = true;
return;
}
if !g.ax.is_finite() || g.ax.abs() < 10. || g.ax.abs() <= g.ay.abs() {
return;
}
g.ax -= g.ax.signum() * 10.;
g.grab = Some(0.);
}
let ex = geo.map(g.x0 + g.ax);
g.hist.push_back((now, ex));
while g.hist.len() > 4 {
g.hist.pop_front();
}
s.x.set(ex);
let haptic = s.spread(geo.can_commit && ex >= geo.commit, now, red);
(
true,
if haptic {
s.props.on_haptic.clone()
} else {
None
},
)
};
if let Some(cb) = haptic {
cb(&(), window, cx);
}
if moved {
cx.stop_propagation();
window.refresh();
}
})
.relative()
.w_full()
.min_w_0()
.flex_none()
.h(px(config.height * fold))
.mb(px(config.margin_bottom * fold))
.overflow_hidden()
.opacity(fold * if config.disabled { 0.55 } else { 1. })
.when(phase != Phase::Done, |el| {
el.child(
div()
.relative()
.w_full()
.h(px(config.height))
.rounded(px(config.radius))
.overflow_hidden()
.bg(row_color)
.child(probe)
.child(rail)
.child(surface),
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext, point,
test::{TestEventExt as _, TestWindowExt as _},
};
struct Host {
config: SwipeRowConfig,
controlled: Option<bool>,
events: Vec<String>,
empty: bool,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let mut row = SwipeRow::new("sr-test", "Example")
.config(self.config.clone())
.actions(if self.empty {
vec![]
} else {
vec![
SwipeRowAction::new("delete", "Delete"),
SwipeRowAction::new("archive", "Archive").on_select(cx.listener(
|this, _: &SwipeRowAction, _, cx| {
this.events.push("select".into());
cx.notify();
},
)),
]
})
.on_action(cx.listener(|this, a: &SwipeRowAction, _, cx| {
this.events.push(format!("action:{}", a.id));
cx.notify();
}))
.on_open_change(cx.listener(|this, v: &bool, _, cx| {
this.events.push(format!("open:{v}"));
cx.notify();
}))
.on_commit(cx.listener(|this, a: &SwipeRowAction, _, cx| {
this.events.push(format!("commit:{}", a.id));
cx.notify();
}));
if let Some(open) = self.controlled {
row = row.open(open);
}
div().w(px(360.)).child(row)
}
}
fn id(v: &str) -> ElementId {
ElementId::NamedChild(ElementId::from("sr-test").into(), v.to_owned().into())
}
fn setup(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
});
}
#[gpui_kit::test]
fn swipe_row_keyboard_actions_controlled_and_disabled(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: SwipeRowConfig::default(),
controlled: None,
events: vec![],
empty: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
w.focus_next(cx);
w.press("left", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).events, vec!["open:true"]);
assert_eq!(w.find(id("surface")).bounds().left(), px(-160.));
w.press("enter", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).events.last().unwrap(), "open:false");
w.press("space", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).events.last().unwrap(), "open:true");
w.click(id("action-archive"), cx);
w.render_frame(cx);
assert!(view.read(cx).events.ends_with(&[
"action:archive".into(),
"select".into(),
"open:false".into()
]));
view.update(cx, |v, cx| {
v.config.disabled = true;
cx.notify();
});
w.render_frame(cx);
let before = view.read(cx).events.len();
w.press("left", cx);
w.render_frame(cx);
assert_eq!(view.read(cx).events.len(), before);
view.update(cx, |v, cx| {
v.config.disabled = false;
v.controlled = Some(true);
cx.notify();
});
w.render_frame(cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(350));
cx.update(|w, cx| {
w.render_frame(cx);
w.focus_next(cx);
w.press("escape", cx);
w.render_frame(cx);
assert!(w.find("sr-test").bounds().size.width == px(360.));
install_arc_theme(ThemeMode::Dark, Accent::Neutral, cx);
w.render_frame(cx);
});
}
#[gpui_kit::test]
fn swipe_row_full_swipe_outside_bounds_commits_after_fold_once(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: SwipeRowConfig::default(),
controlled: None,
events: vec![],
empty: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
let p = point(px(330.), px(30.));
w.pointer_down(p, MouseButton::Left, cx);
w.render_frame(cx);
w.pointer_move(point(px(315.), px(30.)), Some(MouseButton::Left), cx);
w.render_frame(cx);
w.pointer_move(point(px(-120.), px(30.)), Some(MouseButton::Left), cx);
w.render_frame(cx);
w.pointer_up(point(px(-120.), px(30.)), MouseButton::Left, cx);
w.render_frame(cx);
assert!(!view.read(cx).events.iter().any(|s| s.starts_with("commit")));
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(310));
cx.update(|w, cx| {
w.render_frame(cx);
assert!(view.read(cx).events.is_empty());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(210));
cx.update(|w, cx| {
w.render_frame(cx);
w.render_frame(cx);
});
cx.run_until_parked();
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(view.read(cx).events, vec!["commit:delete"]);
assert_eq!(w.find("sr-test").bounds().size.height, px(0.));
w.render_frame(cx);
assert_eq!(view.read(cx).events.len(), 1);
});
}
#[gpui_kit::test]
fn swipe_row_vertical_intent_and_empty_do_not_swipe(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: SwipeRowConfig::default(),
controlled: None,
events: vec![],
empty: false,
});
cx.update(|w, cx| {
w.render_frame(cx);
w.pointer_down(point(px(300.), px(20.)), MouseButton::Left, cx);
w.render_frame(cx);
w.pointer_move(point(px(299.), px(50.)), Some(MouseButton::Left), cx);
w.render_frame(cx);
w.pointer_move(point(px(-200.), px(50.)), Some(MouseButton::Left), cx);
w.render_frame(cx);
w.pointer_up(point(px(-200.), px(50.)), MouseButton::Left, cx);
w.render_frame(cx);
assert_eq!(w.find(id("surface")).bounds().left(), px(0.));
assert!(view.read(cx).events.is_empty());
view.update(cx, |v, cx| {
v.empty = true;
cx.notify();
});
w.render_frame(cx);
w.press("left", cx);
w.render_frame(cx);
assert!(view.read(cx).events.is_empty());
});
}
#[gpui_kit::test]
fn swipe_row_touch_pan_respects_vertical_and_cancel(cx: &mut TestAppContext) {
setup(cx);
let (view, cx) = cx.add_window_view(|_, _| Host {
config: SwipeRowConfig::default(),
controlled: None,
events: vec![],
empty: false,
});
let touch = |w: &mut Window, cx: &mut App, phase, x, y| {
w.dispatch_event(
gpui_kit::PlatformInput::Touch(gpui_kit::TouchEvent {
id: gpui_kit::TouchId(7),
phase,
position: point(px(x), px(y)),
predicted_position: None,
force: None,
}),
cx,
);
w.render_frame(cx);
};
cx.update(|w, cx| {
w.render_frame(cx);
touch(w, cx, gpui_kit::TouchPhase::Started, 300., 20.);
touch(w, cx, gpui_kit::TouchPhase::Moved, 299., 50.);
touch(w, cx, gpui_kit::TouchPhase::Ended, 299., 50.);
assert_eq!(w.find(id("surface")).bounds().left(), px(0.));
touch(w, cx, gpui_kit::TouchPhase::Started, 300., 20.);
touch(w, cx, gpui_kit::TouchPhase::Moved, 200., 20.);
assert!(w.find(id("surface")).bounds().left() < px(-50.));
touch(w, cx, gpui_kit::TouchPhase::Cancelled, 200., 20.);
assert!(view.read(cx).events.is_empty());
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(350));
cx.update(|w, cx| {
w.render_frame(cx);
assert_eq!(w.find(id("surface")).bounds().left(), px(0.));
});
}
#[test]
fn swipe_row_mapping_and_inverse_are_continuous() {
for n in [0, 1, 2, 5] {
for full in [false, true] {
let c = SwipeRowConfig {
full_swipe: full,
..Default::default()
};
let g = Geometry::new(&c, n, 360.);
let mut prev = f32::NEG_INFINITY;
for i in -300..1500 {
let raw = i as f32;
let ex = g.map(raw);
assert!(ex >= prev);
assert!((g.inv(ex) - raw).abs() < 0.01, "{n}/{full}/{raw}");
prev = ex;
}
}
}
}
#[test]
fn swipe_row_commit_guard_and_flick_projection() {
let c = SwipeRowConfig::default();
let g = Geometry::new(&c, 2, 360.);
assert!(g.can_commit);
assert!((g.commit - 216.).abs() < 0.001);
assert!(!Geometry::new(&c, 5, 360.).can_commit);
assert!(!Geometry::new(&c, 0, 360.).can_commit);
assert_eq!(g.release_target(10., 120.), 160.);
assert_eq!(g.release_target(150., -120.), 0.);
assert_eq!(g.release_target(70., 0.), 0.);
assert_eq!(g.release_target(90., 0.), 160.);
}
#[test]
fn swipe_row_duration_channels_and_fold_follow_clock() {
let mut x = Channel::new(0.);
x.spring(160., 1., 0.3, 0.);
assert!(x.tick(1.15));
assert!(x.value > 0. && x.value < 160.);
assert!(!x.tick(1.31));
assert_eq!(x.value, 160.);
let mut fold = ScalarTween::new(1.);
fold.retarget(0., 1., 0.2, 0., curve(), false);
assert!(fold.sample(1.1) < 0.2);
assert!(fold.settled(1.21));
}
}