Swipeable List
List rows for touch screens that slide sideways to uncover action buttons, with separate actions for each side and neutral, primary, success, warning or danger tones for things like archive or delete.
Preview
Install
Add it with the shadcn CLI, or copy the source manually.
$ bunx --bun shadcn add @karaui/swipeable-list
Needs the theme tokens once. Already ran
shadcn init? You are set. Theme setupInstall dependencies
npm i clsx lucide-react motion tailwind-mergeAdd util files
TSXlib/touch.ts
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple
* HIG) on a coarse pointer, without changing what it looks like or the space
* it takes in layout. An invisible `::after` box, centered on the control and
* `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button
* reaches 6px past each edge, a wide 40px button only grows vertically, and a
* control already 44px or larger is left as it is. Hit-testing a pseudo
* element lands on its owner, so handlers, focus and `:active` all behave.
*
* Mouse and trackpad rendering is untouched — nothing here applies outside
* `pointer: coarse`. Requirements on the element it goes on:
* - It must be the containing block: add `relative` (and keep it mergeable, so
* a consumer's `absolute` still wins through `cn`).
* - It must not clip itself (`overflow-hidden`), or the overhang is clipped
* away along with its hit area.
* - It must render children: `<input>` and other void elements have no
* `::after`. Put it on the wrapper or label instead.
* - It must not already use `::after` for something visible.
*
* Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the
* later one wins that strip, which still ends well short of the earlier
* button's visual center. Below a ~32px pitch the later neighbour starts
* eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.
*
* The overhang is real geometry: inside a scroll container it counts as
* scrollable overflow, so a control flush against a scroller's edge can add a
* few pixels of scroll on touch screens. Give such a scroller a little padding
* on that side.
*/
export const TOUCH_TARGET_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter
* than ~32px apart in a row (pagination dots, dense swatches), where growing
* sideways would hand most of each control to its neighbour. Same rules.
*/
export const TOUCH_TARGET_Y_CLASS =
"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
TSXlib/utils.ts
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
Copy the source code
TSXcomponents/motion/swipeable-list.tsx
"use client";
// karaui.kamisama-v0.my.id/components/blocks/swipeable-list
import {
animate,
motion,
useMotionValue,
useReducedMotion,
type PanInfo,
} from "motion/react";
import {
useCallback,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";
import { TOUCH_GESTURE_CONTENT_CLASS } from "@/lib/touch";
import { cn } from "@/lib/utils";
export type SwipeSide = "left" | "right";
export type SwipeableListValue = {
id: string;
side: SwipeSide;
};
export type SwipeActionTone =
| "neutral"
| "primary"
| "success"
| "warning"
| "danger";
export type SwipeAction = {
id: string;
label: ReactNode;
icon: ReactNode;
tone?: SwipeActionTone;
disabled?: boolean;
onClick?: (item: SwipeableListItem) => void;
};
export type SwipeableListItem = {
id: string;
title?: ReactNode;
description?: ReactNode;
meta?: ReactNode;
leading?: ReactNode;
content?: ReactNode;
leftActions?: SwipeAction[];
rightActions?: SwipeAction[];
disabled?: boolean;
};
export type SwipeableListClassNames = {
root?: string;
item?: string;
rail?: string;
action?: string;
surface?: string;
leading?: string;
content?: string;
title?: string;
description?: string;
meta?: string;
};
export interface SwipeableListProps {
items: SwipeableListItem[];
value?: SwipeableListValue | null;
defaultValue?: SwipeableListValue | null;
onValueChange?: (value: SwipeableListValue | null) => void;
onAction?: (payload: {
item: SwipeableListItem;
action: SwipeAction;
side: SwipeSide;
}) => void;
actionWidth?: number;
revealThreshold?: number;
closeOnAction?: boolean;
className?: string;
classNames?: SwipeableListClassNames;
renderItem?: (item: SwipeableListItem) => ReactNode;
}
// Distance-based release spring keeps short rebounds and full reveals feeling
// equally direct, closer to native mobile list interactions.
const ROW_SETTLE = {
type: "spring",
stiffness: 560,
damping: 48,
mass: 0.82,
restDelta: 0.5,
restSpeed: 8,
} as const;
const OPEN_DISTANCE_RATIO = 0.46;
const CLOSE_DISTANCE_RATIO = 0.72;
const OPEN_VELOCITY = 720;
const CLOSE_VELOCITY = 320;
const FLING_DISTANCE = 14;
const RELEASE_VELOCITY_LIMIT = 1500;
const ACTION_TONE_CLASS: Record<SwipeActionTone, string> = {
neutral: "text-muted-foreground group-hover:text-foreground",
primary: "text-foreground",
success: "text-emerald-600 dark:text-emerald-400",
warning: "text-amber-600 dark:text-amber-400",
danger: "text-destructive",
};
function useControllableSwipeValue({
value,
defaultValue,
onValueChange,
}: {
value?: SwipeableListValue | null;
defaultValue?: SwipeableListValue | null;
onValueChange?: (value: SwipeableListValue | null) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? null);
const isControlled = value !== undefined;
const currentValue = value ?? internalValue;
const setValue = useCallback(
(next: SwipeableListValue | null) => {
if (!isControlled) {
setInternalValue(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange],
);
return [currentValue, setValue] as const;
}
function isActionableSide(value: number, sideWidth: number) {
return sideWidth > 0 && Math.abs(value) > 0;
}
function clampReleaseVelocity(velocity: number) {
return Math.max(
-RELEASE_VELOCITY_LIMIT,
Math.min(RELEASE_VELOCITY_LIMIT, velocity),
);
}
function SwipeActionButton({
action,
actionWidth,
side,
focusable,
onAction,
className,
}: {
action: SwipeAction;
actionWidth: number;
side: SwipeSide;
focusable: boolean;
onAction: (action: SwipeAction, side: SwipeSide) => void;
className?: string;
}) {
return (
<button
type="button"
disabled={action.disabled}
tabIndex={focusable ? 0 : -1}
aria-label={typeof action.label === "string" ? action.label : undefined}
onClick={() => onAction(action, side)}
className={cn(
"group flex h-full shrink-0 items-center justify-center outline-none",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"disabled:pointer-events-none disabled:opacity-50",
className,
)}
style={{ width: actionWidth }}
>
<span
className={cn(
"grid h-9 w-9 place-items-center rounded-full transition-[background-color,color,transform] duration-150 group-hover:bg-background group-active:scale-95",
ACTION_TONE_CLASS[action.tone ?? "neutral"],
)}
>
{action.icon}
</span>
<span className="sr-only">{action.label}</span>
</button>
);
}
function SwipeableListRow({
item,
actionWidth,
revealThreshold,
openValue,
setOpenValue,
closeOnAction,
onAction,
classNames,
renderItem,
}: {
item: SwipeableListItem;
actionWidth: number;
revealThreshold: number;
openValue: SwipeableListValue | null;
setOpenValue: (value: SwipeableListValue | null) => void;
closeOnAction: boolean;
onAction?: SwipeableListProps["onAction"];
classNames?: SwipeableListClassNames;
renderItem?: (item: SwipeableListItem) => ReactNode;
}) {
const reduce = useReducedMotion();
const x = useMotionValue(0);
const animationRef = useRef<{ stop: () => void } | null>(null);
const commandedTargetRef = useRef(0);
const leftActions = item.leftActions ?? [];
const rightActions = item.rightActions ?? [];
const leftWidth = leftActions.length * actionWidth;
const rightWidth = rightActions.length * actionWidth;
const openSide = openValue?.id === item.id ? openValue.side : null;
const targetX =
openSide === "left" ? leftWidth : openSide === "right" ? -rightWidth : 0;
const settleX = useCallback(
(nextX: number, velocity = 0) => {
commandedTargetRef.current = nextX;
animationRef.current?.stop();
if (reduce) {
x.set(nextX);
return;
}
animationRef.current = animate(x, nextX, {
...ROW_SETTLE,
velocity: clampReleaseVelocity(velocity),
onComplete: () => x.set(nextX),
});
},
[reduce, x],
);
useEffect(() => {
return () => animationRef.current?.stop();
}, []);
useEffect(() => {
if (commandedTargetRef.current === targetX) {
return;
}
settleX(targetX);
}, [settleX, targetX]);
const getTargetX = useCallback(
(side: SwipeSide | null) =>
side === "left" ? leftWidth : side === "right" ? -rightWidth : 0,
[leftWidth, rightWidth],
);
const snapTo = useCallback(
(side: SwipeSide | null, velocity = 0) => {
setOpenValue(side ? { id: item.id, side } : null);
settleX(getTargetX(side), velocity);
},
[getTargetX, item.id, setOpenValue, settleX],
);
const onDragStart = useCallback(() => {
animationRef.current?.stop();
if (openValue && openValue.id !== item.id) {
setOpenValue(null);
}
}, [item.id, openValue, setOpenValue]);
const onDragEnd = useCallback(
(_: PointerEvent, info: PanInfo) => {
const velocity = info.velocity.x;
const latest = x.get();
const leftOpenThreshold = Math.max(
revealThreshold,
leftWidth * OPEN_DISTANCE_RATIO,
);
const rightOpenThreshold = Math.max(
revealThreshold,
rightWidth * OPEN_DISTANCE_RATIO,
);
if (openSide === "left") {
if (
latest < leftWidth * CLOSE_DISTANCE_RATIO ||
velocity < -CLOSE_VELOCITY
) {
snapTo(null, velocity);
return;
}
snapTo("left", velocity);
return;
}
if (openSide === "right") {
if (
Math.abs(latest) < rightWidth * CLOSE_DISTANCE_RATIO ||
velocity > CLOSE_VELOCITY
) {
snapTo(null, velocity);
return;
}
snapTo("right", velocity);
return;
}
if (
isActionableSide(latest, leftWidth) &&
(latest > leftOpenThreshold ||
(velocity > OPEN_VELOCITY && latest > FLING_DISTANCE))
) {
snapTo("left", velocity);
return;
}
if (
isActionableSide(latest, rightWidth) &&
(latest < -rightOpenThreshold ||
(velocity < -OPEN_VELOCITY && latest < -FLING_DISTANCE))
) {
snapTo("right", velocity);
return;
}
snapTo(null, velocity);
},
[
leftWidth,
openSide,
revealThreshold,
rightWidth,
snapTo,
x,
],
);
const handleAction = useCallback(
(action: SwipeAction, side: SwipeSide) => {
action.onClick?.(item);
onAction?.({ item, action, side });
if (closeOnAction) {
snapTo(null);
}
},
[closeOnAction, item, onAction, snapTo],
);
const defaultContent = (
<div className="flex min-w-0 items-center gap-3">
{item.leading ? (
<div className={cn("shrink-0", classNames?.leading)}>
{item.leading}
</div>
) : null}
<div className={cn("min-w-0 flex-1", classNames?.content)}>
{item.title ? (
<div
className={cn(
"truncate text-sm font-medium text-foreground",
classNames?.title,
)}
>
{item.title}
</div>
) : null}
{item.description ? (
<div
className={cn(
"mt-0.5 truncate text-xs text-muted-foreground",
classNames?.description,
)}
>
{item.description}
</div>
) : null}
</div>
{item.meta ? (
<div
className={cn(
"shrink-0 text-xs font-medium text-muted-foreground",
classNames?.meta,
)}
>
{item.meta}
</div>
) : null}
</div>
);
return (
<div
className={cn(
"relative isolate overflow-hidden rounded-2xl bg-muted",
item.disabled && "opacity-60",
classNames?.item,
)}
>
<div
aria-hidden={!openSide}
inert={!openSide}
className={cn(
"absolute inset-0 z-0 flex overflow-hidden rounded-2xl",
classNames?.rail,
)}
>
<div className="flex h-full overflow-hidden rounded-l-2xl">
{leftActions.map((action) => (
<SwipeActionButton
key={action.id}
action={action}
actionWidth={actionWidth}
className={classNames?.action}
focusable={openSide === "left"}
onAction={handleAction}
side="left"
/>
))}
</div>
<div className="ml-auto flex h-full overflow-hidden rounded-r-2xl">
{rightActions.map((action) => (
<SwipeActionButton
key={action.id}
action={action}
actionWidth={actionWidth}
className={classNames?.action}
focusable={openSide === "right"}
onAction={handleAction}
side="right"
/>
))}
</div>
</div>
<motion.div
drag={item.disabled ? false : "x"}
dragConstraints={{ left: -rightWidth, right: leftWidth }}
dragElastic={0.04}
dragMomentum={false}
onDragStart={onDragStart}
onDragEnd={onDragEnd}
style={{ x }}
className={cn(
// `touch-pan-y`, not `touch-none`: the row owns the horizontal
// swipe, the page keeps the vertical scroll through it.
"relative z-10 min-h-[72px] cursor-grab touch-pan-y rounded-2xl border border-border bg-card px-4 py-3 shadow-sm active:cursor-grabbing",
// The swipe is the row's, but what it carries is the consumer's:
// selection is only suppressed where the platform runs its own press
// gestures, so a mouse can still select and copy the row's text.
TOUCH_GESTURE_CONTENT_CLASS,
classNames?.surface,
)}
>
{renderItem ? renderItem(item) : item.content ?? defaultContent}
</motion.div>
</div>
);
}
export function SwipeableList({
items,
value,
defaultValue = null,
onValueChange,
onAction,
actionWidth = 56,
revealThreshold = 34,
closeOnAction = true,
className,
classNames,
renderItem,
}: SwipeableListProps) {
const [openValue, setOpenValue] = useControllableSwipeValue({
value,
defaultValue,
onValueChange,
});
return (
<div className={cn("flex w-full flex-col gap-2", className, classNames?.root)}>
{items.map((item) => (
<SwipeableListRow
key={item.id}
item={item}
actionWidth={actionWidth}
revealThreshold={revealThreshold}
openValue={openValue}
setOpenValue={setOpenValue}
closeOnAction={closeOnAction}
onAction={onAction}
classNames={classNames}
renderItem={renderItem}
/>
))}
</div>
);
}
@karaui not found? Add it to components.json
{
"registries": {
"@karaui": "https://karaui.kamisama-v0.my.id/r/{name}.json"
}
}@karaui is in shadcn's public registry directory, so the latest CLI needs no setup. On an older CLI, merge this into the existing file once and every @karaui/… install resolves.
API Reference
itemsSwipeableListItem[]—value?SwipeableListValue | null—defaultValue?SwipeableListValue | nullnullonValueChange?((value: SwipeableListValue | null) => void)—onAction?((payload: { item: SwipeableListItem; action: SwipeAction; side: SwipeSide; }) => void)—actionWidth?number56revealThreshold?number34closeOnAction?booleantrueclassName?string—classNames?SwipeableListClassNames—renderItem?((item: SwipeableListItem) => ReactNode)—Keep in mind
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated