Installation
Run this in a project set up with shadcn/ui:
$ pnpm dlx shadcn@latest add https://uxelith.com/r/swipe-actions.jsonIt adds these packages for you:
clsxtailwind-mergeThe source lands in your components folder as
swipe-actions.tsx. It's yours: change anything.
Usage
"use client"
import * as React from "react"
import { SwipeActions } from "@/components/swipe-actions"
export function Inbox() {
const [rows, setRows] = React.useState(["Venue for the offsite", "Photos from Kyoto", "Bike route for Sunday"])
return (
<ul className="divide-y divide-border rounded-xl border border-border">
{rows.map((row) => (
<li key={row}>
<SwipeActions
label={row}
leading={[{ label: "Pin", tone: "primary", onAction: () => setRows((list) => [row, ...list.filter((r) => r !== row)]) }]}
trailing={[{ label: "Delete", tone: "danger", removes: true, onAction: () => setRows((list) => list.filter((r) => r !== row)) }]}
>
<div className="px-4 py-3 text-sm">{row}</div>
</SwipeActions>
</li>
))}
</ul>
)
}Source
One file, 320 lines, nothing hidden. Read it before you install it.
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
// Motion presets (ADR-010). The row follows the finger, then settles on this spring with the flick's speed.
const PANEL = { mass: 0.5, stiffness: 220, damping: 26 };
const COLLAPSE = { duration: 260, easing: "cubic-bezier(0.32, 0.72, 0, 1)" };
export interface SwipeAction {
label: string;
icon?: React.ReactNode;
tone?: "neutral" | "primary" | "info" | "success" | "warning" | "danger";
/** Runs when the action is chosen. */
onAction?: () => void;
/** Slides the row away and folds it up before `onAction` runs: delete, archive. */
removes?: boolean;
}
export interface SwipeActionsProps extends React.HTMLAttributes<HTMLDivElement> {
/** What the row is, for its actions button: "Actions for {label}". */
label: string;
/** Revealed by swiping right (from the start edge). */
leading?: SwipeAction[];
/** Revealed by swiping left (from the end edge). */
trailing?: SwipeAction[];
/** Swiping far runs the outermost action without a second tap. */
fullSwipe?: boolean;
/** Width of each action button, in px. */
actionWidth?: number;
disabled?: boolean;
}
const TONES: Record<NonNullable<SwipeAction["tone"]>, string> = {
neutral: "bg-muted text-foreground",
primary: "bg-primary text-primary-foreground",
info: "bg-blue-700 text-white",
success: "bg-emerald-700 text-white",
warning: "bg-amber-700 text-white",
danger: "bg-red-700 text-white",
};
/** One open row at a time, page-wide: a row that opens tells the others, and they close. */
const OPENED = "uxelith-swipe-open";
function prefersReducedMotion() {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function settle(from: number, to: number, velocity: number, onFrame: (x: number) => void, onDone?: () => void) {
if (prefersReducedMotion() || from === to) {
onFrame(to);
onDone?.();
return () => {};
}
let x = from;
let v = velocity;
let last = performance.now();
let frame = requestAnimationFrame(function step(now) {
const dt = Math.min((now - last) / 1000, 1 / 30);
last = now;
v += (((to - x) * PANEL.stiffness - v * PANEL.damping) / PANEL.mass) * dt;
x += v * dt;
if (Math.abs(to - x) < 0.4 && Math.abs(v) < 10) {
onFrame(to);
onDone?.();
return;
}
onFrame(x);
frame = requestAnimationFrame(step);
});
return () => cancelAnimationFrame(frame);
}
/**
* A list row with actions behind it: swipe right or left to reveal them, or
* swipe all the way to run the outermost one, as in Mail.
*
* - The gesture locks to one axis, so the list still scrolls; one row is
* open at a time.
* - Past the full-swipe point the outermost action stretches across the row
* (and the phone ticks, where it can); letting go runs it. Actions marked
* `removes` slide the row away and fold it up first.
* - Every action is a real button: the row's "Actions" button (shown on
* focus) opens them for keyboard and screen-reader users, and Escape closes.
* - Under `prefers-reduced-motion` the row moves straight to place.
*/
export function SwipeActions({ label, leading = [], trailing = [], fullSwipe = true, actionWidth = 76, disabled = false, className, children, ...props }: SwipeActionsProps) {
const rootRef = React.useRef<HTMLDivElement>(null);
const rowRef = React.useRef<HTMLDivElement>(null);
const toggleRef = React.useRef<HTMLButtonElement>(null);
const x = React.useRef(0);
const stop = React.useRef<() => void>(() => {});
const [open, setOpen] = React.useState<"leading" | "trailing" | null>(null);
const [armed, setArmed] = React.useState<"leading" | "trailing" | null>(null);
const [gone, setGone] = React.useState(false);
const drag = React.useRef<{ id: number; x0: number; y0: number; start: number; last: number; time: number; v: number; axis: "x" | "y" | null } | null>(null);
const suppress = React.useRef(false);
// Writes the offset and each action's width; a drag never re-renders except when it crosses the full-swipe point.
const paint = React.useCallback(
(value: number) => {
x.current = value;
const row = rowRef.current;
const root = rootRef.current;
if (!row || !root) return;
row.style.transform = value ? `translateX(${value}px)` : "";
const width = root.clientWidth || 1;
for (const side of ["leading", "trailing"] as const) {
const list = root.querySelectorAll<HTMLElement>(`[data-swipe-side="${side}"] [data-swipe-action]`);
const shown = side === "leading" ? Math.max(value, 0) : Math.max(-value, 0);
const far = fullSwipe && shown > width * 0.55;
list.forEach((el, i) => {
const outer = side === "leading" ? i === 0 : i === list.length - 1;
el.style.width = `${far ? (outer ? shown : 0) : shown / list.length}px`;
});
}
},
[fullSwipe],
);
const moveTo = React.useCallback(
(target: number, velocity = 0, done?: () => void) => {
stop.current();
stop.current = settle(x.current, target, velocity, paint, done);
},
[paint],
);
const close = React.useCallback(() => {
moveTo(0);
setOpen(null);
setArmed(null);
}, [moveTo]);
const announce = () => document.dispatchEvent(new CustomEvent(OPENED, { detail: rootRef.current }));
React.useEffect(() => {
const onOther = (event: Event) => {
if ((event as CustomEvent).detail !== rootRef.current && x.current !== 0) close();
};
document.addEventListener(OPENED, onOther);
return () => document.removeEventListener(OPENED, onOther);
}, [close]);
React.useEffect(() => () => stop.current(), []);
// A press anywhere outside an open row closes it.
React.useEffect(() => {
if (!open) return;
const outside = (event: PointerEvent) => {
if (!rootRef.current?.contains(event.target as Node)) close();
};
document.addEventListener("pointerdown", outside, true);
return () => document.removeEventListener("pointerdown", outside, true);
}, [open, close]);
const reveal = (side: "leading" | "trailing", velocity = 0) => {
announce();
const count = side === "leading" ? leading.length : trailing.length;
moveTo((side === "leading" ? 1 : -1) * count * actionWidth, velocity);
setOpen(side);
};
const run = (action: SwipeAction, side: "leading" | "trailing", velocity = 0) => {
if (!action.removes) {
close();
action.onAction?.();
return;
}
const root = rootRef.current;
const width = root?.clientWidth ?? 400;
const done = () => {
setGone(true);
action.onAction?.();
};
if (prefersReducedMotion() || !root?.animate) return done();
// Slide out, then fold the row's height away.
moveTo((side === "leading" ? 1 : -1) * width * 1.05, velocity || (side === "leading" ? 1200 : -1200), () => {
const fold = root.animate([{ height: `${root.offsetHeight}px` }, { height: "0px" }], { ...COLLAPSE, fill: "forwards" });
fold.onfinish = done;
});
};
const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (disabled || event.button !== 0 || (event.target as Element).closest("input, textarea, select, [contenteditable='true']")) return;
stop.current();
drag.current = { id: event.pointerId, x0: event.clientX, y0: event.clientY, start: x.current, last: event.clientX, time: event.timeStamp, v: 0, axis: null };
};
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== event.pointerId) return;
const dx = event.clientX - d.x0;
if (!d.axis) {
const dy = event.clientY - d.y0;
if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return;
d.axis = Math.abs(dx) > Math.abs(dy) ? "x" : "y";
if (d.axis === "y") return;
event.currentTarget.setPointerCapture?.(event.pointerId);
announce();
}
if (d.axis !== "x") return;
const dt = Math.max(event.timeStamp - d.time, 1);
d.v = 0.8 * (((event.clientX - d.last) / dt) * 1000) + 0.2 * d.v;
d.last = event.clientX;
d.time = event.timeStamp;
let next = d.start + dx;
// No actions on a side: it only stretches a little.
if ((next > 0 && !leading.length) || (next < 0 && !trailing.length)) next = Math.sign(next) * Math.sqrt(Math.abs(next)) * 2;
const width = rootRef.current?.clientWidth || 400;
const limit = fullSwipe ? width * 0.9 : Math.max(leading.length, trailing.length) * actionWidth;
if (Math.abs(next) > limit) next = Math.sign(next) * (limit + Math.sqrt(Math.abs(next) - limit) * 3);
paint(next);
const far = fullSwipe && Math.abs(next) > width * 0.55 ? (next > 0 && leading.length ? "leading" : next < 0 && trailing.length ? "trailing" : null) : null;
if (far !== armed) {
setArmed(far);
if (far) navigator.vibrate?.(8);
}
};
const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
const d = drag.current;
drag.current = null;
if (!d || d.id !== event.pointerId) return;
if (d.axis !== "x") {
// A tap on an open row closes it instead of pressing what's under the finger.
if (open && !d.axis) {
suppress.current = true;
close();
}
return;
}
suppress.current = true;
if (armed === "leading") return run(leading[0]!, "leading", d.v);
if (armed === "trailing") return run(trailing.at(-1)!, "trailing", d.v);
const projected = x.current + d.v * 0.15;
if (projected > (leading.length * actionWidth) / 2 && leading.length) reveal("leading", d.v);
else if (projected < (-trailing.length * actionWidth) / 2 && trailing.length) reveal("trailing", d.v);
else close();
};
if (gone) return null;
const side = (name: "leading" | "trailing", list: SwipeAction[]) =>
list.length > 0 && (
<div data-swipe-side={name} className={cn("flex h-full", name === "trailing" && "justify-end")}>
{list.map((action, i) => (
<button
key={action.label + i}
type="button"
data-swipe-action=""
tabIndex={open === name ? 0 : -1}
onClick={() => run(action, name)}
className={cn(
"flex h-full shrink-0 flex-col items-center justify-center gap-1 overflow-hidden whitespace-nowrap text-xs font-semibold outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
TONES[action.tone ?? "neutral"],
)}
style={{ width: 0 }}
>
{action.icon && (
<span aria-hidden="true" className={cn("transition-transform duration-200 [&_svg]:size-5", armed === name && "scale-125")}>
{action.icon}
</span>
)}
{action.label}
</button>
))}
</div>
);
return (
<div
ref={rootRef}
data-swipe={open ?? undefined}
className={cn("group/swipe relative isolate overflow-hidden", className)}
onKeyDown={(event) => {
if (event.key === "Escape" && open) {
event.stopPropagation();
close();
toggleRef.current?.focus();
}
}}
{...props}
>
<div aria-hidden={open ? undefined : true} className={cn("absolute inset-0 flex", leading.length ? "justify-between" : "justify-end")}>
{side("leading", leading)}
{side("trailing", trailing)}
</div>
<div
ref={rowRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerCancel={() => {
if (drag.current?.axis === "x") close();
drag.current = null;
}}
onClickCapture={(event) => {
if (suppress.current) {
suppress.current = false;
event.preventDefault();
event.stopPropagation();
}
}}
className="relative touch-pan-y select-none bg-background"
>
{children}
</div>
{(leading.length > 0 || trailing.length > 0) && !disabled && (
<button
ref={toggleRef}
type="button"
aria-expanded={open !== null}
onClick={() => {
if (open) return close();
reveal(trailing.length ? "trailing" : "leading");
requestAnimationFrame(() => rootRef.current?.querySelector<HTMLElement>(`[data-swipe-side="${trailing.length ? "trailing" : "leading"}"] [data-swipe-action]`)?.focus());
}}
className="sr-only rounded-full bg-foreground px-2.5 py-1 text-xs font-medium text-background focus-visible:not-sr-only focus-visible:absolute focus-visible:left-2 focus-visible:top-1/2 focus-visible:-translate-y-1/2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{open ? `Close actions for ${label}` : `Actions for ${label}`}
</button>
)}
</div>
);
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | — | What the row is, for its actions button: "Actions for {label}". |
| leading | SwipeAction[] | [] | Revealed by swiping right: { label, icon?, tone?, onAction, removes? }. |
| trailing | SwipeAction[] | [] | Revealed by swiping left. |
| fullSwipe | boolean | true | Swiping far runs the outermost action without a second tap. |
| actionWidth | number | 76 | Width of each action button, in px. |
| disabled | boolean | false | Turns the gesture and the actions off. |
| ...props | HTMLAttributes<HTMLDivElement> | — | Children are the row's content. |
Accessibility
- Every action is a real button. The row's Actions button (shown on keyboard focus) reveals them and moves focus to the first; Escape closes and returns focus.
- Hidden actions are out of the tab order and hidden from assistive technology until revealed.
- The gesture locks to one axis, so vertical scrolling and taps work as usual; a tap on an open row closes it instead of pressing what's under the finger.
- Under prefers-reduced-motion the row moves straight to place and removed rows disappear without folding.
Changelog
- v1.0.0Latest
First release.