Skip to main content

arc_ui/actions/
swipe_actions.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/swipe-actions/swipe-actions.tsx` & `.module.css`
3//!
4//! P5 Component #2: `swipe-actions`
5//!
6//! - Mail-inbox style list where rows reveal `leading` (left) or `trailing` (right) actions on horizontal swipe.
7//! - Resting action width: `ACTION_WIDTH = 76px`; drag slop: `8px`; velocity projection: `0.10s`;
8//!   flick speed threshold: `900 px/s`; past-limit rubber-band resistance (`0.55` coefficient).
9//! - Revealed actions share the uncovered width evenly, scale their icon (`0.6 -> 1.0`) and fade in
10//!   their label (`72% -> 96%` of `76px`).
11//! - Full swipe threshold (`max(open_width + 48px, row_width * 0.56)`): stretches the outermost action
12//!   across the revealed area on `motion.spring.morph` (`cover: 0 -> 1`).
13//! - Only one row stays open at a time across the list; every row also includes a `More actions` (`⋯`)
14//!   button and accessible floating menu with the same actions for keyboard / mouse users.
15
16use std::{cell::RefCell, collections::HashMap, rc::Rc};
17
18use arc_motion::{
19    arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
20};
21use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
22use gpui_kit::{
23    AnyElement, App, Bounds, ElementId, FocusHandle, IntoElement, KeyDownEvent, MouseButton,
24    MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, RenderOnce, Role,
25    SharedString, Styled, Window, assets::IconName, base::StyledExt as _, canvas, deferred, div,
26    point, prelude::*, px, size, svg,
27};
28
29type ActionCallback = Rc<dyn Fn(&(), &mut Window, &mut App)>;
30
31/// Resting width (`76px`) of one revealed action button.
32pub const SWIPE_ACTION_WIDTH_PX: f64 = 76.0;
33/// Pointer movement (`8px`) required before locking into a horizontal swipe.
34pub const SWIPE_SLOP_PX: f64 = 8.0;
35/// Seconds of travel (`0.10s`) projected from release velocity.
36pub const SWIPE_PROJECTION_SECS: f64 = 0.10;
37/// Release speed (`900 px/s`) that counts as an outward flick.
38pub const SWIPE_FLICK_VELOCITY: f64 = 900.0;
39
40#[inline]
41fn clamp01(value: f64) -> f64 {
42    value.clamp(0.0, 1.0)
43}
44
45/// Asymptotic rubber-band curve (`0.55` factor) past the action stop.
46#[inline]
47pub fn swipe_rubber_band(overshoot: f64, dimension: f64) -> f64 {
48    let dim = dimension.max(1.0);
49    (1.0 - 1.0 / (overshoot.max(0.0) * 0.55 / dim + 1.0)) * dim
50}
51
52/// Computes the full-swipe arm threshold (`max(open_width + 48, row_width * 0.56)`).
53#[inline]
54pub fn swipe_full_threshold(open_width: f64, row_width: f64) -> f64 {
55    (open_width + 48.0).max(row_width * 0.56)
56}
57
58/// Constrains raw horizontal displacement `raw_x` given the side's action count, `full_swipe`, and `row_width`.
59#[inline]
60pub fn swipe_constrain_x(raw_x: f64, action_count: usize, full_swipe: bool, row_width: f64) -> f64 {
61    if raw_x == 0.0 {
62        return 0.0;
63    }
64    let dim = if row_width > 1.0 { row_width } else { 360.0 };
65    let open_width = action_count as f64 * SWIPE_ACTION_WIDTH_PX;
66    let limit = if action_count == 0 {
67        0.0
68    } else if full_swipe {
69        dim
70    } else {
71        open_width
72    };
73    let distance = raw_x.abs();
74    let constrained = if distance <= limit {
75        distance
76    } else {
77        limit + swipe_rubber_band(distance - limit, dim)
78    };
79    raw_x.signum() * constrained
80}
81
82/// Computes the visual metrics of a single revealed action layer (`rank` from inner `0` to outer `count - 1`).
83///
84/// Returns `(inner_inset_px, width_px, icon_reveal_0_to_1, label_reveal_0_to_1)`.
85#[inline]
86pub fn swipe_action_layer_metrics(
87    revealed_px: f64,
88    rank: usize,
89    count: usize,
90    cover_rank: Option<usize>,
91    cover_progress: f64,
92) -> (f64, f64, f64, f64) {
93    if count == 0 || revealed_px <= 0.0 {
94        return (0.0, 0.0, 0.0, 0.0);
95    }
96    let progress = clamp01(cover_progress);
97    let share = revealed_px / (count as f64);
98
99    let edge_inset = |r: usize| -> f64 {
100        if r >= count {
101            return 0.0;
102        }
103        let base = ((count - r) as f64) * revealed_px / (count as f64);
104        if cover_rank == Some(r) {
105            base + progress * (revealed_px - base)
106        } else if let Some(cr) = cover_rank {
107            if r > cr {
108                base * (1.0 - progress)
109            } else {
110                base
111            }
112        } else {
113            base
114        }
115    };
116
117    let inner_inset = edge_inset(rank);
118    let outer_inset = edge_inset(rank + 1);
119    let width = (inner_inset - outer_inset).max(0.0);
120
121    let own_icon = clamp01((share - SWIPE_ACTION_WIDTH_PX * 0.25) / (SWIPE_ACTION_WIDTH_PX * 0.55));
122    let icon_reveal = if cover_rank == Some(rank) {
123        own_icon.max(progress)
124    } else if cover_rank.is_none() {
125        own_icon
126    } else {
127        own_icon * (1.0 - progress)
128    };
129
130    let own_label =
131        clamp01((share - SWIPE_ACTION_WIDTH_PX * 0.72) / (SWIPE_ACTION_WIDTH_PX * 0.24));
132    let label_reveal = if cover_rank == Some(rank) {
133        own_label.max(progress)
134    } else if cover_rank.is_none() {
135        own_label
136    } else {
137        own_label * (1.0 - progress)
138    };
139
140    (inner_inset, width, icon_reveal, label_reveal)
141}
142
143#[derive(Clone, Copy, Debug, Eq, PartialEq)]
144pub enum SwipeSide {
145    Leading,
146    Trailing,
147}
148
149impl SwipeSide {
150    #[inline]
151    pub const fn direction(self) -> f64 {
152        match self {
153            Self::Leading => 1.0,
154            Self::Trailing => -1.0,
155        }
156    }
157
158    #[inline]
159    pub fn from_offset(x: f64) -> Option<Self> {
160        if x > 0.0 {
161            Some(Self::Leading)
162        } else if x < 0.0 {
163            Some(Self::Trailing)
164        } else {
165            None
166        }
167    }
168}
169
170/// Semantic colour fill of a [`SwipeAction`].
171#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
172pub enum SwipeActionTone {
173    #[default]
174    Neutral,
175    Accent,
176    Danger,
177}
178
179/// One action revealed under the leading or trailing edge of a [`SwipeActionsRow`].
180#[derive(Clone)]
181pub struct SwipeAction {
182    pub label: SharedString,
183    pub icon: IconName,
184    pub tone: SwipeActionTone,
185    pub keep_row: bool,
186    pub on_select: Option<ActionCallback>,
187}
188
189impl SwipeAction {
190    pub fn new(label: impl Into<SharedString>, icon: IconName) -> Self {
191        Self {
192            label: label.into(),
193            icon,
194            tone: SwipeActionTone::Neutral,
195            keep_row: false,
196            on_select: None,
197        }
198    }
199
200    pub fn tone(mut self, tone: SwipeActionTone) -> Self {
201        self.tone = tone;
202        self
203    }
204
205    pub fn keep_row(mut self, keep_row: bool) -> Self {
206        self.keep_row = keep_row;
207        self
208    }
209
210    pub fn on_select(mut self, callback: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
211        self.on_select = Some(Rc::new(callback));
212        self
213    }
214}
215
216/// One swipeable row inside [`SwipeActions`].
217pub struct SwipeActionsRow {
218    id: SharedString,
219    label: SharedString,
220    leading: Vec<SwipeAction>,
221    trailing: Vec<SwipeAction>,
222    full_swipe: bool,
223    body: Option<AnyElement>,
224}
225
226impl SwipeActionsRow {
227    pub fn new(
228        id: impl Into<SharedString>,
229        label: impl Into<SharedString>,
230        body: impl IntoElement,
231    ) -> Self {
232        Self {
233            id: id.into(),
234            label: label.into(),
235            leading: Vec::new(),
236            trailing: Vec::new(),
237            full_swipe: true,
238            body: Some(body.into_any_element()),
239        }
240    }
241
242    pub fn leading(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
243        self.leading = actions.into_iter().collect();
244        self
245    }
246
247    pub fn trailing(mut self, actions: impl IntoIterator<Item = SwipeAction>) -> Self {
248        self.trailing = actions.into_iter().collect();
249        self
250    }
251
252    pub fn full_swipe(mut self, full_swipe: bool) -> Self {
253        self.full_swipe = full_swipe;
254        self
255    }
256}
257
258#[derive(Clone, Copy, Debug)]
259struct DragSession {
260    start_x: f64,
261    start_y: f64,
262    origin_x: f64,
263    locked_x: bool,
264    locked_y: bool,
265    samples: [(f64, f64); 12],
266    sample_len: usize,
267}
268
269impl DragSession {
270    fn new(start_x: f64, start_y: f64, origin_x: f64, now_secs: f64) -> Self {
271        let mut samples = [(0.0, 0.0); 12];
272        samples[0] = (now_secs, start_x);
273        Self {
274            start_x,
275            start_y,
276            origin_x,
277            locked_x: false,
278            locked_y: false,
279            samples,
280            sample_len: 1,
281        }
282    }
283
284    fn push_sample(&mut self, now_secs: f64, client_x: f64) {
285        if self.sample_len < 12 {
286            self.samples[self.sample_len] = (now_secs, client_x);
287            self.sample_len += 1;
288        } else {
289            self.samples.copy_within(1..12, 0);
290            self.samples[11] = (now_secs, client_x);
291        }
292    }
293
294    fn velocity_px_per_sec(&self) -> f64 {
295        if self.sample_len < 2 {
296            return 0.0;
297        }
298        let (last_t, last_x) = self.samples[self.sample_len - 1];
299        let mut first = self.samples[self.sample_len - 1];
300        for i in 0..self.sample_len {
301            if last_t - self.samples[i].0 <= 0.080 {
302                first = self.samples[i];
303                break;
304            }
305        }
306        let elapsed = last_t - first.0;
307        if elapsed > 1e-4 {
308            (last_x - first.1) / elapsed
309        } else {
310            0.0
311        }
312    }
313}
314
315#[derive(Clone)]
316struct RowRuntime {
317    x_current: f64,
318    x_target: f64,
319    release_velocity: f32,
320    cover_current: f64,
321    cover_target: f64,
322    covering: Option<(SwipeSide, usize)>,
323    armed: bool,
324    drag: Option<DragSession>,
325    row_bounds: Option<Bounds<Pixels>>,
326    more_bounds: Option<Bounds<Pixels>>,
327    swallow_click: bool,
328    focus_handle: FocusHandle,
329}
330
331impl RowRuntime {
332    fn new(cx: &mut App) -> Self {
333        Self {
334            x_current: 0.0,
335            x_target: 0.0,
336            release_velocity: 0.0,
337            cover_current: 0.0,
338            cover_target: 0.0,
339            covering: None,
340            armed: false,
341            drag: None,
342            row_bounds: None,
343            more_bounds: None,
344            swallow_click: false,
345            focus_handle: cx.focus_handle(),
346        }
347    }
348
349    fn row_width(&self) -> f64 {
350        self.row_bounds
351            .map(|b| f64::from(b.size.width).max(200.0))
352            .unwrap_or(420.0)
353    }
354
355    fn stretch_to(&mut self, target: f64, reduced: bool) {
356        self.cover_target = target;
357        if reduced {
358            self.cover_current = target;
359        }
360    }
361
362    fn settle_to(&mut self, target: f64, velocity: f64, reduced: bool) {
363        if self.armed || (target != 0.0 && self.cover_target != 0.0) {
364            self.stretch_to(0.0, reduced);
365        }
366        self.armed = false;
367        self.x_target = target;
368        let from = self.x_current;
369        let toward_home = target == 0.0 && velocity.signum() == -from.signum();
370        let launch = if toward_home {
371            velocity.signum() * velocity.abs().min(from.abs() * 12.0)
372        } else {
373            velocity
374        };
375        self.release_velocity = launch as f32;
376        if reduced {
377            self.x_current = target;
378            if target == 0.0 {
379                self.cover_current = 0.0;
380                self.cover_target = 0.0;
381                self.covering = None;
382            }
383        }
384    }
385}
386
387#[derive(Clone, Default)]
388struct SwipeGroupState {
389    open_row_id: Option<SharedString>,
390    menu_row_id: Option<SharedString>,
391    rows: HashMap<SharedString, RowRuntime>,
392}
393
394/// Mail-inbox style list with horizontal swipe-to-reveal and full-swipe actions (`swipe-actions`).
395#[derive(IntoElement)]
396pub struct SwipeActions {
397    id: ElementId,
398    label: SharedString,
399    rows: Vec<SwipeActionsRow>,
400}
401
402impl SwipeActions {
403    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
404        Self {
405            id: id.into(),
406            label: label.into(),
407            rows: Vec::new(),
408        }
409    }
410
411    pub fn row(mut self, row: SwipeActionsRow) -> Self {
412        self.rows.push(row);
413        self
414    }
415
416    pub fn rows(mut self, rows: impl IntoIterator<Item = SwipeActionsRow>) -> Self {
417        self.rows.extend(rows);
418        self
419    }
420}
421
422impl RenderOnce for SwipeActions {
423    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
424        let theme = cx.arc_theme().clone();
425        let colors = theme.colors;
426        let motion = theme.motion;
427        let reduced = is_reduced_motion(cx);
428        let _ = &self.label;
429
430        let state_cell = window
431            .use_keyed_state(
432                ElementId::NamedChild(self.id.clone().into(), SharedString::from("group-state")),
433                cx,
434                |_, _| RefCell::new(SwipeGroupState::default()),
435            )
436            .read(cx)
437            .clone();
438
439        {
440            let mut state = state_cell.borrow_mut();
441            let open_id = state.open_row_id.clone();
442            for row in &self.rows {
443                let entry = state
444                    .rows
445                    .entry(row.id.clone())
446                    .or_insert_with(|| RowRuntime::new(cx));
447                if open_id.as_ref() != Some(&row.id)
448                    && entry.drag.is_none()
449                    && entry.x_target != 0.0
450                {
451                    entry.settle_to(0.0, 0.0, reduced);
452                }
453            }
454        }
455
456        if self.rows.is_empty() {
457            return div().id(self.id).into_any_element();
458        }
459
460        let total_rows = self.rows.len();
461        let mut rendered_rows = Vec::with_capacity(total_rows);
462        let mut open_menu_portal: Option<AnyElement> = None;
463
464        for (row_idx, mut row) in self.rows.into_iter().enumerate() {
465            let row_id = row.id.clone();
466            let leading = Rc::new(row.leading);
467            let trailing = Rc::new(row.trailing);
468            let full_swipe = row.full_swipe;
469            let is_last = row_idx + 1 == total_rows;
470
471            let (
472                is_dragging_x,
473                drag_x,
474                x_target,
475                release_vel,
476                cover_target,
477                covering,
478                is_menu_open,
479                focus_handle,
480                more_bounds,
481            ) = {
482                let state = state_cell.borrow();
483                let rt = state.rows.get(&row_id).expect("row initialized");
484                let dragging_x = rt.drag.map(|d| d.locked_x).unwrap_or(false);
485                (
486                    dragging_x,
487                    rt.x_current,
488                    rt.x_target,
489                    rt.release_velocity,
490                    rt.cover_target,
491                    rt.covering,
492                    state.menu_row_id.as_ref() == Some(&row_id),
493                    rt.focus_handle.clone(),
494                    rt.more_bounds,
495                )
496            };
497
498            let x_key = ElementId::NamedChild(
499                self.id.clone().into(),
500                SharedString::from(format!("x-spring-{row_id}")),
501            );
502            let cover_key = ElementId::NamedChild(
503                self.id.clone().into(),
504                SharedString::from(format!("cover-spring-{row_id}")),
505            );
506            let x_spec = if x_target == 0.0 {
507                motion.spring.smooth
508            } else {
509                motion.spring.snappy
510            };
511
512            let x_current = if is_dragging_x || reduced {
513                let v = if is_dragging_x { drag_x } else { x_target };
514                let _ = arc_spring_with_options(
515                    x_key,
516                    v as f32,
517                    SpringOptions::new(x_spec).with_initial_value(v as f32),
518                    window,
519                    cx,
520                );
521                v
522            } else {
523                f64::from(
524                    arc_spring_with_options(
525                        x_key,
526                        x_target as f32,
527                        SpringOptions::new(x_spec).with_initial_velocity(release_vel),
528                        window,
529                        cx,
530                    )
531                    .value,
532                )
533            };
534
535            let cover_current = if reduced {
536                let _ = arc_spring_with_options(
537                    cover_key,
538                    cover_target as f32,
539                    SpringOptions::new(motion.spring.morph).with_initial_value(cover_target as f32),
540                    window,
541                    cx,
542                );
543                cover_target
544            } else {
545                f64::from(arc_spring(
546                    cover_key,
547                    cover_target as f32,
548                    motion.spring.morph,
549                    window,
550                    cx,
551                ))
552            };
553
554            {
555                let mut state = state_cell.borrow_mut();
556                if let Some(rt) = state.rows.get_mut(&row_id) {
557                    rt.x_current = x_current;
558                    rt.cover_current = cover_current;
559                    rt.release_velocity = 0.0;
560                    if x_target == 0.0 && x_current.abs() < 0.5 && !is_dragging_x {
561                        rt.covering = None;
562                    }
563                }
564            }
565
566            // Measure row bounds for width-dependent full-swipe threshold & rubber-band
567            let bounds_state = state_cell.clone();
568            let bounds_row_id = row_id.clone();
569            let bounds_probe = canvas(
570                move |bounds, _, _| {
571                    if let Some(rt) = bounds_state.borrow_mut().rows.get_mut(&bounds_row_id) {
572                        rt.row_bounds = Some(bounds);
573                    }
574                },
575                |_, _, _, _| {},
576            )
577            .size_full()
578            .absolute()
579            .top_0()
580            .left_0();
581
582            // Render revealed action layers behind the content
583            let mut action_layers: Vec<AnyElement> = Vec::new();
584            let revealed_side = SwipeSide::from_offset(x_current);
585            if let Some(side) = revealed_side {
586                let revealed_px = x_current.abs();
587                let side_actions = match side {
588                    SwipeSide::Leading => leading.as_slice(),
589                    SwipeSide::Trailing => trailing.as_slice(),
590                };
591                let count = side_actions.len();
592                let cover_rank = covering.and_then(|(c_side, c_idx)| {
593                    if c_side == side && count > 0 {
594                        Some(match side {
595                            SwipeSide::Leading => count.saturating_sub(1).saturating_sub(c_idx),
596                            SwipeSide::Trailing => c_idx,
597                        })
598                    } else {
599                        None
600                    }
601                });
602
603                let neutral_bg = oklab_mix(colors.foreground, colors.surface, 0.20);
604                for (action_idx, action) in side_actions.iter().enumerate() {
605                    let rank = match side {
606                        SwipeSide::Leading => count - 1 - action_idx,
607                        SwipeSide::Trailing => action_idx,
608                    };
609                    let (inner_inset, layer_w, icon_reveal, label_reveal) =
610                        swipe_action_layer_metrics(
611                            revealed_px,
612                            rank,
613                            count,
614                            cover_rank,
615                            cover_current,
616                        );
617                    let (layer_bg, layer_fg) = match action.tone {
618                        SwipeActionTone::Neutral => (neutral_bg, colors.foreground),
619                        SwipeActionTone::Accent => (colors.accent, colors.accent_foreground),
620                        SwipeActionTone::Danger => (colors.danger, colors.background),
621                    };
622                    let icon_scale = 0.6 + 0.4 * icon_reveal;
623                    let icon_px = (20.0 * icon_scale).round().max(12.0);
624                    let action_cb = action.on_select.clone();
625                    let click_state = state_cell.clone();
626                    let click_row_id = row_id.clone();
627
628                    let mut layer = div()
629                        .id(ElementId::NamedChild(
630                            self.id.clone().into(),
631                            SharedString::from(format!("action-{row_id}-{side:?}-{action_idx}")),
632                        ))
633                        .absolute()
634                        .top_0()
635                        .bottom_0()
636                        .w(px(layer_w.max(1.0) as f32))
637                        .bg(layer_bg)
638                        .text_color(layer_fg)
639                        .cursor_pointer()
640                        .overflow_hidden()
641                        .flex()
642                        .flex_col()
643                        .items_center()
644                        .justify_center()
645                        .gap(px(3.0))
646                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
647                            cx.stop_propagation();
648                        })
649                        .on_mouse_up(MouseButton::Left, move |_, window, cx| {
650                            cx.stop_propagation();
651                            let red = is_reduced_motion(cx);
652                            {
653                                let mut st = click_state.borrow_mut();
654                                if let Some(rt) = st.rows.get_mut(&click_row_id) {
655                                    rt.covering = Some((side, action_idx));
656                                    rt.settle_to(0.0, 0.0, red);
657                                }
658                                st.open_row_id = None;
659                            }
660                            if let Some(cb) = &action_cb {
661                                cb(&(), window, cx);
662                            }
663                            window.refresh();
664                        });
665
666                    layer = match side {
667                        SwipeSide::Leading => {
668                            layer.left(px((inner_inset - layer_w).max(0.0) as f32))
669                        }
670                        SwipeSide::Trailing => {
671                            layer.right(px((inner_inset - layer_w).max(0.0) as f32))
672                        }
673                    };
674
675                    layer = layer
676                        .child(
677                            svg()
678                                .path(action.icon.path())
679                                .size(px(icon_px as f32))
680                                .text_color(layer_fg.opacity(icon_reveal as f32)),
681                        )
682                        .child(
683                            div()
684                                .text_size(Typography::TEXT_XS)
685                                .font_medium()
686                                .whitespace_nowrap()
687                                .text_color(layer_fg.opacity(label_reveal as f32))
688                                .child(action.label.clone()),
689                        );
690
691                    action_layers.push(layer.into_any_element());
692                }
693            }
694
695            // Build `More actions` trigger button
696            let has_any_actions = !leading.is_empty() || !trailing.is_empty();
697            let more_button = if has_any_actions {
698                let more_state_probe = state_cell.clone();
699                let more_row_id_probe = row_id.clone();
700                let more_state_click = state_cell.clone();
701                let more_row_id_click = row_id.clone();
702
703                let more_bg = if is_menu_open {
704                    colors.surface_muted
705                } else {
706                    gpui_kit::transparent_black()
707                };
708                let more_fg = if is_menu_open {
709                    colors.foreground
710                } else {
711                    colors.text_muted
712                };
713
714                Some(
715                    div()
716                        .id(ElementId::NamedChild(
717                            self.id.clone().into(),
718                            SharedString::from(format!("more-{row_id}")),
719                        ))
720                        .relative()
721                        .w(px(32.0))
722                        .h(px(32.0))
723                        .flex_none()
724                        .rounded(px(8.0))
725                        .bg(more_bg)
726                        .text_color(more_fg)
727                        .hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
728                        .cursor_pointer()
729                        .flex()
730                        .items_center()
731                        .justify_center()
732                        .child(
733                            canvas(
734                                move |bounds, _, _| {
735                                    if let Some(rt) = more_state_probe
736                                        .borrow_mut()
737                                        .rows
738                                        .get_mut(&more_row_id_probe)
739                                    {
740                                        rt.more_bounds = Some(bounds);
741                                    }
742                                },
743                                |_, _, _, _| {},
744                            )
745                            .size_full()
746                            .absolute()
747                            .top_0()
748                            .left_0(),
749                        )
750                        .child(
751                            svg()
752                                .path(IconName::Ellipsis.path())
753                                .size(px(18.0))
754                                .text_color(more_fg),
755                        )
756                        .on_mouse_down(MouseButton::Left, |_, _, cx| {
757                            cx.stop_propagation();
758                        })
759                        .on_mouse_up(MouseButton::Left, move |_, window, cx| {
760                            cx.stop_propagation();
761                            let red = is_reduced_motion(cx);
762                            {
763                                let mut st = more_state_click.borrow_mut();
764                                if st.menu_row_id.as_ref() == Some(&more_row_id_click) {
765                                    st.menu_row_id = None;
766                                } else {
767                                    st.menu_row_id = Some(more_row_id_click.clone());
768                                    if let Some(open_id) = st.open_row_id.take()
769                                        && let Some(rt) = st.rows.get_mut(&open_id)
770                                    {
771                                        rt.settle_to(0.0, 0.0, red);
772                                    }
773                                }
774                            }
775                            window.refresh();
776                        })
777                        .into_any_element(),
778                )
779            } else {
780                None
781            };
782
783            // Build floating menu portal if this row's menu is open
784            if is_menu_open {
785                let anchor = more_bounds.unwrap_or_else(|| {
786                    Bounds::new(point(px(280.0), px(120.0)), size(px(32.0), px(32.0)))
787                });
788                let menu_w = px(184.0);
789                let menu_left = (anchor.origin.x + anchor.size.width - menu_w).max(px(12.0));
790                let menu_top = anchor.origin.y + anchor.size.height + px(6.0);
791
792                let backdrop_state = state_cell.clone();
793                let mut menu_items_list: Vec<AnyElement> = Vec::new();
794                let all_actions: Vec<(SwipeSide, usize, SwipeAction)> = leading
795                    .iter()
796                    .enumerate()
797                    .map(|(i, a)| (SwipeSide::Leading, i, a.clone()))
798                    .chain(
799                        trailing
800                            .iter()
801                            .enumerate()
802                            .map(|(i, a)| (SwipeSide::Trailing, i, a.clone())),
803                    )
804                    .collect();
805
806                for (order, (_side, _idx, action)) in all_actions.into_iter().enumerate() {
807                    let is_danger = action.tone == SwipeActionTone::Danger;
808                    let item_fg = if is_danger {
809                        colors.danger
810                    } else {
811                        colors.foreground
812                    };
813                    let icon_fg = if is_danger {
814                        colors.danger
815                    } else {
816                        colors.text_secondary
817                    };
818                    let hover_bg = if is_danger {
819                        oklab_mix(colors.danger, colors.surface_raised, 0.08)
820                    } else {
821                        colors.surface_muted
822                    };
823                    let item_state = state_cell.clone();
824                    let item_cb = action.on_select.clone();
825                    let item_row_id = row_id.clone();
826
827                    menu_items_list.push(
828                        div()
829                            .id(ElementId::NamedChild(
830                                self.id.clone().into(),
831                                SharedString::from(format!("menu-item-{item_row_id}-{order}")),
832                            ))
833                            .min_h(px(30.0))
834                            .px(px(10.0))
835                            .rounded(px(6.0))
836                            .flex()
837                            .flex_row()
838                            .items_center()
839                            .gap(px(10.0))
840                            .cursor_pointer()
841                            .text_size(Typography::TEXT_SM)
842                            .text_color(item_fg)
843                            .hover(move |s| s.bg(hover_bg))
844                            .on_mouse_down(MouseButton::Left, |_, _, cx| {
845                                cx.stop_propagation();
846                            })
847                            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
848                                cx.stop_propagation();
849                                item_state.borrow_mut().menu_row_id = None;
850                                if let Some(cb) = &item_cb {
851                                    cb(&(), window, cx);
852                                }
853                                window.refresh();
854                            })
855                            .child(
856                                svg()
857                                    .path(action.icon.path())
858                                    .size(px(16.0))
859                                    .text_color(icon_fg),
860                            )
861                            .child(action.label)
862                            .into_any_element(),
863                    );
864                }
865
866                open_menu_portal = Some(
867                    deferred(
868                        div()
869                            .id(ElementId::NamedChild(
870                                self.id.clone().into(),
871                                SharedString::from(format!("menu-backdrop-{row_id}")),
872                            ))
873                            .occlude()
874                            .absolute()
875                            .inset_0()
876                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
877                                cx.stop_propagation();
878                                backdrop_state.borrow_mut().menu_row_id = None;
879                                window.refresh();
880                            })
881                            .child(
882                                div()
883                                    .absolute()
884                                    .left(menu_left)
885                                    .top(menu_top)
886                                    .min_w(menu_w)
887                                    .p(px(5.0))
888                                    .rounded(Radii::PANEL)
889                                    .bg(colors.surface_raised)
890                                    .border_1()
891                                    .border_color(colors.border)
892                                    .shadow(Shadows::floating(theme.mode))
893                                    .flex()
894                                    .flex_col()
895                                    .gap(px(2.0))
896                                    .children(menu_items_list),
897                            ),
898                    )
899                    .with_priority(120)
900                    .into_any_element(),
901                );
902            }
903
904            // Pointer gesture handlers on the row content surface
905            let down_state = state_cell.clone();
906            let down_row_id = row_id.clone();
907
908            let move_state = state_cell.clone();
909            let move_row_id = row_id.clone();
910            let move_leading = leading.clone();
911            let move_trailing = trailing.clone();
912
913            let up_state = state_cell.clone();
914            let up_row_id = row_id.clone();
915            let up_leading = leading.clone();
916            let up_trailing = trailing.clone();
917
918            let key_state = state_cell.clone();
919            let key_row_id = row_id.clone();
920            let _ = &row.label;
921
922            let content = div()
923                .id(ElementId::NamedChild(
924                    self.id.clone().into(),
925                    SharedString::from(format!("content-{row_id}")),
926                ))
927                .relative()
928                .left(px(x_current as f32))
929                .w_full()
930                .min_h(px(64.0))
931                .pl(Spacing::S4)
932                .pr(Spacing::S2)
933                .py(Spacing::S3)
934                .bg(colors.surface)
935                .flex()
936                .flex_row()
937                .items_center()
938                .gap(Spacing::S2)
939                .cursor_grab()
940                .when(!is_last, |this| {
941                    this.border_b_1().border_color(colors.border)
942                })
943                .child(div().flex_1().min_w_0().children(row.body.take()))
944                .children(more_button);
945
946            let row_el = div()
947                .id(ElementId::NamedChild(
948                    self.id.clone().into(),
949                    SharedString::from(format!("row-{row_id}")),
950                ))
951                .track_focus(&focus_handle)
952                .relative()
953                .w_full()
954                .overflow_hidden()
955                .child(bounds_probe)
956                .children(action_layers)
957                .child(content)
958                .on_key_down(move |event: &KeyDownEvent, window, cx| {
959                    if event.keystroke.key == "escape" {
960                        let red = is_reduced_motion(cx);
961                        let mut st = key_state.borrow_mut();
962                        st.menu_row_id = None;
963                        if let Some(rt) = st.rows.get_mut(&key_row_id) {
964                            rt.settle_to(0.0, 0.0, red);
965                        }
966                        if st.open_row_id.as_ref() == Some(&key_row_id) {
967                            st.open_row_id = None;
968                        }
969                        window.refresh();
970                    }
971                })
972                .on_mouse_down(
973                    MouseButton::Left,
974                    move |event: &MouseDownEvent, window, cx| {
975                        let now = motion_now(cx);
976                        let red = is_reduced_motion(cx);
977                        let mut st = down_state.borrow_mut();
978                        st.menu_row_id = None;
979                        // Close any other open row when touching this row
980                        if let Some(prev_open) = st.open_row_id.clone()
981                            && prev_open != down_row_id
982                        {
983                            if let Some(other_rt) = st.rows.get_mut(&prev_open) {
984                                other_rt.settle_to(0.0, 0.0, red);
985                            }
986                            st.open_row_id = None;
987                        }
988                        if let Some(rt) = st.rows.get_mut(&down_row_id) {
989                            rt.swallow_click = false;
990                            rt.drag = Some(DragSession::new(
991                                f64::from(event.position.x),
992                                f64::from(event.position.y),
993                                rt.x_current,
994                                now,
995                            ));
996                        }
997                        window.refresh();
998                    },
999                )
1000                .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
1001                    if event.pressed_button != Some(MouseButton::Left) {
1002                        return;
1003                    }
1004                    let now = motion_now(cx);
1005                    let red = is_reduced_motion(cx);
1006                    let client_x = f64::from(event.position.x);
1007                    let client_y = f64::from(event.position.y);
1008
1009                    let mut st = move_state.borrow_mut();
1010                    let mut became_open = false;
1011                    if let Some(rt) = st.rows.get_mut(&move_row_id) {
1012                        let row_w = rt.row_width();
1013                        let Some(mut drag) = rt.drag else {
1014                            return;
1015                        };
1016                        if drag.locked_y {
1017                            return;
1018                        }
1019                        if !drag.locked_x {
1020                            let dx = client_x - drag.start_x;
1021                            let dy = client_y - drag.start_y;
1022                            if dx.hypot(dy) < SWIPE_SLOP_PX {
1023                                return;
1024                            }
1025                            if dy.abs() > dx.abs() {
1026                                drag.locked_y = true;
1027                                rt.drag = Some(drag);
1028                                return;
1029                            }
1030                            drag.locked_x = true;
1031                            drag.start_x = client_x;
1032                            became_open = true;
1033                        }
1034
1035                        let raw = drag.origin_x + (client_x - drag.start_x);
1036                        let side = SwipeSide::from_offset(raw);
1037                        let side_count = match side {
1038                            Some(SwipeSide::Leading) => move_leading.len(),
1039                            Some(SwipeSide::Trailing) => move_trailing.len(),
1040                            None => 0,
1041                        };
1042                        let value = swipe_constrain_x(raw, side_count, full_swipe, row_w);
1043                        rt.x_current = value;
1044                        rt.x_target = value;
1045                        drag.push_sample(now, client_x);
1046                        rt.drag = Some(drag);
1047
1048                        // Full-swipe arm check with 20px hysteresis
1049                        if let Some(s) = SwipeSide::from_offset(value) {
1050                            let count = match s {
1051                                SwipeSide::Leading => move_leading.len(),
1052                                SwipeSide::Trailing => move_trailing.len(),
1053                            };
1054                            let open_w = count as f64 * SWIPE_ACTION_WIDTH_PX;
1055                            let limit = swipe_full_threshold(open_w, row_w);
1056                            let can_commit = full_swipe && count > 0;
1057                            let trigger = if rt.armed { limit - 20.0 } else { limit };
1058                            let next_armed = can_commit && value.abs() > trigger;
1059                            if next_armed != rt.armed {
1060                                rt.armed = next_armed;
1061                                if next_armed {
1062                                    let outermost = match s {
1063                                        SwipeSide::Leading => 0,
1064                                        SwipeSide::Trailing => count.saturating_sub(1),
1065                                    };
1066                                    rt.covering = Some((s, outermost));
1067                                }
1068                                rt.stretch_to(if next_armed { 1.0 } else { 0.0 }, red);
1069                            }
1070                        } else if rt.armed {
1071                            rt.armed = false;
1072                            rt.stretch_to(0.0, red);
1073                        }
1074                    }
1075                    if became_open {
1076                        st.open_row_id = Some(move_row_id.clone());
1077                    }
1078                    window.refresh();
1079                })
1080                .on_mouse_up(
1081                    MouseButton::Left,
1082                    move |event: &MouseUpEvent, window, cx| {
1083                        let now = motion_now(cx);
1084                        let red = is_reduced_motion(cx);
1085                        let client_x = f64::from(event.position.x);
1086
1087                        let mut committed_cb: Option<ActionCallback> = None;
1088                        {
1089                            let mut st = up_state.borrow_mut();
1090                            let mut next_open_id = st.open_row_id.clone();
1091
1092                            if let Some(rt) = st.rows.get_mut(&up_row_id) {
1093                                let row_w = rt.row_width();
1094                                if let Some(mut drag) = rt.drag.take() {
1095                                    if drag.locked_x {
1096                                        rt.swallow_click = true;
1097                                        drag.push_sample(now, client_x);
1098                                        let velocity = drag.velocity_px_per_sec();
1099                                        let value = rt.x_current;
1100
1101                                        if let Some(side) = SwipeSide::from_offset(value) {
1102                                            let actions = match side {
1103                                                SwipeSide::Leading => up_leading.as_slice(),
1104                                                SwipeSide::Trailing => up_trailing.as_slice(),
1105                                            };
1106                                            let count = actions.len();
1107                                            if count == 0 {
1108                                                rt.settle_to(0.0, velocity, red);
1109                                                if next_open_id.as_ref() == Some(&up_row_id) {
1110                                                    next_open_id = None;
1111                                                }
1112                                            } else {
1113                                                let direction = side.direction();
1114                                                let distance = value.abs();
1115                                                let outward = velocity * direction;
1116                                                let open_w = count as f64 * SWIPE_ACTION_WIDTH_PX;
1117                                                let projected =
1118                                                    distance + outward * SWIPE_PROJECTION_SECS;
1119                                                let limit = swipe_full_threshold(open_w, row_w);
1120                                                let flung = distance > open_w
1121                                                    && outward > SWIPE_FLICK_VELOCITY
1122                                                    && projected > limit;
1123                                                let can_commit = full_swipe && count > 0;
1124
1125                                                if can_commit
1126                                                    && ((rt.armed
1127                                                        && outward > -SWIPE_FLICK_VELOCITY)
1128                                                        || flung)
1129                                                {
1130                                                    let outermost = match side {
1131                                                        SwipeSide::Leading => 0,
1132                                                        SwipeSide::Trailing => count - 1,
1133                                                    };
1134                                                    rt.covering = Some((side, outermost));
1135                                                    committed_cb =
1136                                                        actions[outermost].on_select.clone();
1137                                                    rt.settle_to(0.0, velocity, red);
1138                                                    if next_open_id.as_ref() == Some(&up_row_id) {
1139                                                        next_open_id = None;
1140                                                    }
1141                                                } else if projected > open_w * 0.5 {
1142                                                    rt.settle_to(direction * open_w, velocity, red);
1143                                                    next_open_id = Some(up_row_id.clone());
1144                                                } else {
1145                                                    rt.settle_to(0.0, velocity, red);
1146                                                    if next_open_id.as_ref() == Some(&up_row_id) {
1147                                                        next_open_id = None;
1148                                                    }
1149                                                }
1150                                            }
1151                                        } else {
1152                                            rt.settle_to(0.0, velocity, red);
1153                                            if next_open_id.as_ref() == Some(&up_row_id) {
1154                                                next_open_id = None;
1155                                            }
1156                                        }
1157                                    } else if !drag.locked_y && rt.x_current.abs() > 0.5 {
1158                                        // A tap on an open row closes it
1159                                        rt.swallow_click = true;
1160                                        rt.settle_to(0.0, 0.0, red);
1161                                        if next_open_id.as_ref() == Some(&up_row_id) {
1162                                            next_open_id = None;
1163                                        }
1164                                    }
1165                                }
1166                            }
1167                            st.open_row_id = next_open_id;
1168                        }
1169
1170                        if let Some(cb) = committed_cb {
1171                            cb(&(), window, cx);
1172                        }
1173                        window.refresh();
1174                    },
1175                );
1176
1177            rendered_rows.push(row_el.into_any_element());
1178        }
1179
1180        let border_color = colors.border;
1181        let surface_bg = colors.surface;
1182        let radius = Radii::PANEL;
1183
1184        div()
1185            .id(self.id)
1186            .role(Role::List)
1187            .relative()
1188            .w_full()
1189            .rounded(radius)
1190            .bg(surface_bg)
1191            .border_1()
1192            .border_color(border_color)
1193            .overflow_hidden()
1194            .flex()
1195            .flex_col()
1196            .children(rendered_rows)
1197            .children(open_menu_portal)
1198            .into_any_element()
1199    }
1200}
1201
1202#[cfg(test)]
1203mod tests {
1204    use super::*;
1205
1206    #[test]
1207    fn swipe_rubber_band_and_constrain_resist_past_open_width() {
1208        // Without full_swipe, dragging past 2 * 76 = 152px applies rubber-band resistance
1209        let open_w = 2.0 * SWIPE_ACTION_WIDTH_PX;
1210        let at_limit = swipe_constrain_x(-open_w, 2, false, 400.0);
1211        assert!((at_limit - (-open_w)).abs() < 1e-6);
1212
1213        let beyond = swipe_constrain_x(-(open_w + 100.0), 2, false, 400.0);
1214        assert!(beyond < -open_w);
1215        assert!(beyond > -(open_w + 55.0));
1216
1217        // When a side has 0 actions, displacement is resisted immediately from 0
1218        let empty_side = swipe_constrain_x(80.0, 0, true, 400.0);
1219        assert!(empty_side > 0.0 && empty_side < 44.0);
1220    }
1221
1222    #[test]
1223    fn swipe_action_layer_metrics_divide_evenly_and_stretch_when_armed() {
1224        // 2 actions revealed by 152px -> each gets 76px share
1225        let (inset0, w0, icon0, label0) = swipe_action_layer_metrics(152.0, 0, 2, None, 0.0);
1226        let (inset1, w1, icon1, label1) = swipe_action_layer_metrics(152.0, 1, 2, None, 0.0);
1227        assert!((inset0 - 152.0).abs() < 1e-6);
1228        assert!((w0 - 76.0).abs() < 1e-6);
1229        assert!((inset1 - 76.0).abs() < 1e-6);
1230        assert!((w1 - 76.0).abs() < 1e-6);
1231        assert!(icon0 > 0.99 && icon1 > 0.99);
1232        assert!(label0 > 0.99 && label1 > 0.99);
1233
1234        // When outermost action (rank 1) covers the row (cover_progress = 1.0), rank 1 stretches to full 240px
1235        let (_, w0_covered, icon0_cov, _) = swipe_action_layer_metrics(240.0, 0, 2, Some(1), 1.0);
1236        let (inset1_cov, w1_covered, icon1_cov, label1_cov) =
1237            swipe_action_layer_metrics(240.0, 1, 2, Some(1), 1.0);
1238        assert!(w0_covered.abs() < 1e-6);
1239        assert!(icon0_cov.abs() < 1e-6);
1240        assert!((inset1_cov - 240.0).abs() < 1e-6);
1241        assert!((w1_covered - 240.0).abs() < 1e-6);
1242        assert!((icon1_cov - 1.0).abs() < 1e-6);
1243        assert!((label1_cov - 1.0).abs() < 1e-6);
1244    }
1245}