@ncdai/react-swipe-actions 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ncdai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # React Swipe Actions
2
+
3
+ Swipe a row in a list to reveal actions on the left or right.
4
+
5
+ - Composable parts, no config props.
6
+ - Polymorphic `render` prop, so a row can be any element you want.
7
+ - Only one row open at a time.
8
+ - Keyboard, `Escape` and click-outside dismissal.
9
+ - Unstyled, with no CSS to import and no runtime dependencies.
10
+
11
+ → Live demo: https://react-primitives.chanhdai.com/swipe-actions
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm i @ncdai/react-swipe-actions motion
17
+ ```
18
+
19
+ `react` and `motion` are peer dependencies.
20
+
21
+ ## Usage
22
+
23
+ ```tsx
24
+ import {
25
+ SwipeAction,
26
+ SwipeActions,
27
+ SwipeContent,
28
+ SwipeItem,
29
+ SwipeRoot,
30
+ } from "@ncdai/react-swipe-actions"
31
+
32
+ function Inbox({ mails }: { mails: Mail[] }) {
33
+ return (
34
+ <SwipeRoot render={<ul />}>
35
+ {mails.map((mail) => (
36
+ <SwipeItem key={mail.id} render={<li />}>
37
+ <SwipeActions side="left">
38
+ <SwipeAction onClick={() => archive(mail.id)}>Archive</SwipeAction>
39
+ </SwipeActions>
40
+
41
+ <SwipeActions side="right">
42
+ <SwipeAction onClick={() => remove(mail.id)}>Delete</SwipeAction>
43
+ </SwipeActions>
44
+
45
+ <SwipeContent>{mail.subject}</SwipeContent>
46
+ </SwipeItem>
47
+ ))}
48
+ </SwipeRoot>
49
+ )
50
+ }
51
+ ```
52
+
53
+ `SwipeRoot` is optional. It only makes sibling rows close one another, so a
54
+ lone `SwipeItem` works on its own.
55
+
56
+ ## Styling
57
+
58
+ The package positions the strips behind the content and makes the content
59
+ draggable. Everything else is yours. Two things it cannot do for you:
60
+
61
+ - **Give `SwipeContent` an opaque background.** It is what hides the strips
62
+ while the row is closed.
63
+ - **Give `SwipeAction` a width.** The strip is measured to decide how far the
64
+ row opens, so zero-width actions never appear.
65
+
66
+ Enough to get a usable row, with Tailwind:
67
+
68
+ ```tsx
69
+ <SwipeRoot render={<ul />} className="divide-y border-y">
70
+ <SwipeItem render={<li />}>
71
+ <SwipeActions side="right">
72
+ <SwipeAction
73
+ className="w-20 bg-red-600 text-sm text-white"
74
+ onClick={() => remove(mail.id)}
75
+ >
76
+ Delete
77
+ </SwipeAction>
78
+ </SwipeActions>
79
+
80
+ <SwipeContent className="bg-white p-4 dark:bg-zinc-950">
81
+ {mail.subject}
82
+ </SwipeContent>
83
+ </SwipeItem>
84
+ </SwipeRoot>
85
+ ```
86
+
87
+ ## Parts
88
+
89
+ | Part | Renders | `render` prop |
90
+ | -------------- | ------------ | ------------- |
91
+ | `SwipeRoot` | `div` | yes |
92
+ | `SwipeItem` | `div` | yes |
93
+ | `SwipeActions` | `div` | yes |
94
+ | `SwipeAction` | `button` | yes |
95
+ | `SwipeContent` | `motion.div` | no |
96
+
97
+ `SwipeActions`, `SwipeAction` and `SwipeContent` must live inside a
98
+ `SwipeItem`. Every part forwards `ref` and passes unknown props through.
99
+
100
+ ### SwipeItem
101
+
102
+ | Prop | Default | Description |
103
+ | ---------------- | ------- | --------------------------------------------------------------------------------------- |
104
+ | `threshold` | `0.5` | Fraction of the strip the drag must cross to snap open |
105
+ | `velocityFactor` | `0.2` | Seconds of release velocity added to the position, so a flick opens without a full drag |
106
+ | `disabled` | `false` | Turns the gesture off |
107
+ | `closeOnScroll` | `false` | Close on any scroll on the page |
108
+ | `onOpenChange` | | Called with `"closed"`, `"left"` or `"right"` |
109
+
110
+ ### SwipeActions
111
+
112
+ | Prop | Description |
113
+ | ------ | ------------------------------- |
114
+ | `side` | `"left"` or `"right"`. Required |
115
+
116
+ ### SwipeAction
117
+
118
+ | Prop | Default | Description |
119
+ | -------------- | ------- | -------------------------------------------- |
120
+ | `closeOnClick` | `true` | Close the row once the click handler has run |
121
+
122
+ ## Data attributes
123
+
124
+ Style against these rather than tracking state yourself.
125
+
126
+ | Attribute | On | Value |
127
+ | --------------- | --------------------------- | ---------------------------------------------- |
128
+ | `data-state` | `SwipeItem` | `closed`, `left`, `right` |
129
+ | `data-disabled` | `SwipeItem` | present when disabled |
130
+ | `data-dragging` | `SwipeItem`, `SwipeContent` | present while dragging |
131
+ | `data-side` | `SwipeActions` | `left`, `right` |
132
+ | `data-slot` | every part | `swipe-root`, `swipe-item`, `swipe-actions`, … |
133
+
134
+ ## Accessibility
135
+
136
+ - Closed strips are `inert`, so their buttons stay out of the tab order, the
137
+ accessibility tree and hit testing.
138
+ - With focus inside a row, `ArrowLeft` and `ArrowRight` move it one step in that
139
+ direction and `Escape` closes it. Focusable row content is what carries focus
140
+ there.
141
+ - Under `prefers-reduced-motion` the row snaps into place instead of animating.
142
+
143
+ ## License
144
+
145
+ MIT © [ncdai](https://chanhdai.com)
@@ -0,0 +1,62 @@
1
+ import * as React from 'react';
2
+ import { HTMLMotionProps } from 'motion/react';
3
+
4
+ type RenderState = Record<string, unknown>;
5
+ type RenderFunction<TState extends RenderState> = (props: Record<string, unknown>, state: TState) => React.ReactElement | null;
6
+ type RenderProp<TState extends RenderState> = React.ReactElement | RenderFunction<TState>;
7
+ type UseRenderComponentProps<TElement extends React.ElementType, TState extends RenderState = RenderState> = React.ComponentPropsWithRef<TElement> & {
8
+ render?: RenderProp<TState>;
9
+ };
10
+
11
+ type SwipeSide = "left" | "right";
12
+ type SwipeState = "closed" | SwipeSide;
13
+ type SwipeRootProps = UseRenderComponentProps<"div">;
14
+ /**
15
+ * Holds the list, and lets only one item stay open at a time. The registry
16
+ * lives in a ref, so opening an item does not re-render its siblings.
17
+ */
18
+ declare function SwipeRoot({ render, ...props }: SwipeRootProps): React.JSX.Element;
19
+ /** Mirrored onto the element as `data-state`, `data-disabled`, `data-dragging`. */
20
+ type SwipeItemState = {
21
+ state: SwipeState;
22
+ disabled: boolean;
23
+ dragging: boolean;
24
+ };
25
+ type SwipeItemProps = UseRenderComponentProps<"div", SwipeItemState> & {
26
+ /**
27
+ * Fraction of the action strip the drag must pass to snap open.
28
+ * @defaultValue 0.5
29
+ */
30
+ threshold?: number;
31
+ /**
32
+ * Seconds of velocity projected onto the release position, so a quick flick
33
+ * opens the item without dragging all the way.
34
+ * @defaultValue 0.2
35
+ */
36
+ velocityFactor?: number;
37
+ /** @defaultValue false */
38
+ disabled?: boolean;
39
+ /**
40
+ * Close the item on any scroll on the page.
41
+ * @defaultValue false
42
+ */
43
+ closeOnScroll?: boolean;
44
+ onOpenChange?: (state: SwipeState) => void;
45
+ };
46
+ declare function SwipeItem({ render, threshold, velocityFactor, disabled, closeOnScroll, onOpenChange, ...props }: SwipeItemProps): React.JSX.Element;
47
+ type SwipeActionsProps = UseRenderComponentProps<"div"> & {
48
+ side: SwipeSide;
49
+ };
50
+ declare function SwipeActions({ render, side, ...props }: SwipeActionsProps): React.ReactElement<any, string | React.JSXElementConstructor<any>> | null;
51
+ type SwipeActionProps = UseRenderComponentProps<"button"> & {
52
+ /**
53
+ * Close the item once the click handler has run.
54
+ * @defaultValue true
55
+ */
56
+ closeOnClick?: boolean;
57
+ };
58
+ declare function SwipeAction({ render, closeOnClick, ...props }: SwipeActionProps): React.ReactElement<any, string | React.JSXElementConstructor<any>> | null;
59
+ type SwipeContentProps = HTMLMotionProps<"div">;
60
+ declare function SwipeContent({ style, ...props }: SwipeContentProps): React.JSX.Element;
61
+
62
+ export { SwipeAction, type SwipeActionProps, SwipeActions, type SwipeActionsProps, SwipeContent, type SwipeContentProps, SwipeItem, type SwipeItemProps, type SwipeItemState, SwipeRoot, type SwipeRootProps, type SwipeSide, type SwipeState };
@@ -0,0 +1,62 @@
1
+ import * as React from 'react';
2
+ import { HTMLMotionProps } from 'motion/react';
3
+
4
+ type RenderState = Record<string, unknown>;
5
+ type RenderFunction<TState extends RenderState> = (props: Record<string, unknown>, state: TState) => React.ReactElement | null;
6
+ type RenderProp<TState extends RenderState> = React.ReactElement | RenderFunction<TState>;
7
+ type UseRenderComponentProps<TElement extends React.ElementType, TState extends RenderState = RenderState> = React.ComponentPropsWithRef<TElement> & {
8
+ render?: RenderProp<TState>;
9
+ };
10
+
11
+ type SwipeSide = "left" | "right";
12
+ type SwipeState = "closed" | SwipeSide;
13
+ type SwipeRootProps = UseRenderComponentProps<"div">;
14
+ /**
15
+ * Holds the list, and lets only one item stay open at a time. The registry
16
+ * lives in a ref, so opening an item does not re-render its siblings.
17
+ */
18
+ declare function SwipeRoot({ render, ...props }: SwipeRootProps): React.JSX.Element;
19
+ /** Mirrored onto the element as `data-state`, `data-disabled`, `data-dragging`. */
20
+ type SwipeItemState = {
21
+ state: SwipeState;
22
+ disabled: boolean;
23
+ dragging: boolean;
24
+ };
25
+ type SwipeItemProps = UseRenderComponentProps<"div", SwipeItemState> & {
26
+ /**
27
+ * Fraction of the action strip the drag must pass to snap open.
28
+ * @defaultValue 0.5
29
+ */
30
+ threshold?: number;
31
+ /**
32
+ * Seconds of velocity projected onto the release position, so a quick flick
33
+ * opens the item without dragging all the way.
34
+ * @defaultValue 0.2
35
+ */
36
+ velocityFactor?: number;
37
+ /** @defaultValue false */
38
+ disabled?: boolean;
39
+ /**
40
+ * Close the item on any scroll on the page.
41
+ * @defaultValue false
42
+ */
43
+ closeOnScroll?: boolean;
44
+ onOpenChange?: (state: SwipeState) => void;
45
+ };
46
+ declare function SwipeItem({ render, threshold, velocityFactor, disabled, closeOnScroll, onOpenChange, ...props }: SwipeItemProps): React.JSX.Element;
47
+ type SwipeActionsProps = UseRenderComponentProps<"div"> & {
48
+ side: SwipeSide;
49
+ };
50
+ declare function SwipeActions({ render, side, ...props }: SwipeActionsProps): React.ReactElement<any, string | React.JSXElementConstructor<any>> | null;
51
+ type SwipeActionProps = UseRenderComponentProps<"button"> & {
52
+ /**
53
+ * Close the item once the click handler has run.
54
+ * @defaultValue true
55
+ */
56
+ closeOnClick?: boolean;
57
+ };
58
+ declare function SwipeAction({ render, closeOnClick, ...props }: SwipeActionProps): React.ReactElement<any, string | React.JSXElementConstructor<any>> | null;
59
+ type SwipeContentProps = HTMLMotionProps<"div">;
60
+ declare function SwipeContent({ style, ...props }: SwipeContentProps): React.JSX.Element;
61
+
62
+ export { SwipeAction, type SwipeActionProps, SwipeActions, type SwipeActionsProps, SwipeContent, type SwipeContentProps, SwipeItem, type SwipeItemProps, type SwipeItemState, SwipeRoot, type SwipeRootProps, type SwipeSide, type SwipeState };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";"use client";var pe=Object.create;var D=Object.defineProperty,ue=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,we=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable;var B=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,w=(t,e)=>{for(var n in e||(e={}))W.call(e,n)&&B(t,n,e[n]);if(M)for(var n of M(e))F.call(e,n)&&B(t,n,e[n]);return t},y=(t,e)=>ue(t,Se(e));var E=(t,e)=>{var n={};for(var o in t)W.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&M)for(var o of M(t))e.indexOf(o)<0&&F.call(t,o)&&(n[o]=t[o]);return n};var me=(t,e)=>{for(var n in e)D(t,n,{get:e[n],enumerable:!0})},Z=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Re(e))!W.call(t,r)&&r!==n&&D(t,r,{get:()=>e[r],enumerable:!(o=fe(e,r))||o.enumerable});return t};var $=(t,e,n)=>(n=t!=null?pe(we(t)):{},Z(e||!t||!t.__esModule?D(n,"default",{value:t,enumerable:!0}):n,t)),ge=t=>Z(D({},"__esModule",{value:!0}),t);var xe={};me(xe,{SwipeAction:()=>oe,SwipeActions:()=>ne,SwipeContent:()=>re,SwipeItem:()=>te,SwipeRoot:()=>X});module.exports=ge(xe);var s=$(require("react")),v=require("motion/react");var h=$(require("react"));function A({defaultTagName:t,props:e,render:n,state:o={},stateAttributesMapping:r}){let i=P(ye(o,r),e);if(!n)return h.createElement(t,i);if(typeof n=="function")return n(i,o);if(!h.isValidElement(n))return null;let c=n.props,f=P(i,c),l=y(w({},f),{ref:q(i.ref,c.ref)});return h.cloneElement(n,l)}function P(...t){let e={};for(let n of t){if(!n)continue;let o=n;for(let r of Object.keys(o)){let i=o[r];if(i===void 0)continue;let c=e[r];r==="className"?e[r]=[c,i].filter(Boolean).join(" "):r==="style"?e[r]=w(w({},c),i):r==="ref"?e[r]=q(c,i):Ee(r)&&typeof c=="function"&&typeof i=="function"?e[r]=ve(i,c):e[r]=i}}return e}function ye(t,e){var o;let n={};for(let r of Object.keys(t)){let i=t[r],c=(o=e==null?void 0:e[r])==null?void 0:o.call(e,i);if(c){Object.assign(n,c);continue}if(r==="slot"){n["data-slot"]=i;continue}let f=`data-${String(r).replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`;typeof i=="boolean"?n[f]=i?"":void 0:i!=null&&(n[f]=String(i))}return n}function ve(t,e){return function(o){t(o),o.defaultPrevented||e(o)}}function Ee(t){return/^on[A-Z]/.test(t)}function q(...t){let e=t.filter(Boolean);if(e.length!==0)return n=>{for(let o of e)typeof o=="function"?o(n):o&&(o.current=n)}}var L=require("react/jsx-runtime"),Pe={position:"relative",isolation:"isolate",overflow:"hidden"},Te={position:"absolute",top:0,bottom:0,zIndex:0,display:"flex"},Ce={position:"relative",zIndex:1},J={type:"spring",stiffness:500,damping:45,mass:.8},be=y(w({},J),{damping:36}),he=4,Q=s.createContext(null);function X(n){var o=n,{render:t}=o,e=E(o,["render"]);let r=s.useRef(new Map),i=s.useMemo(()=>({register(f,l){return r.current.set(f,l),()=>{r.current.delete(f)}},notifyOpen(f){for(let[l,p]of r.current)l!==f&&p()}}),[]),c=A({defaultTagName:"div",render:t,props:P({"data-slot":"swipe-root"},e)});return(0,L.jsx)(Q.Provider,{value:i,children:c})}var ee=s.createContext(null);function N(){let t=s.useContext(ee);if(!t)throw new Error("Swipe parts must be used within SwipeItem");return t}function te(f){var l=f,{render:t,threshold:e=.5,velocityFactor:n=.2,disabled:o=!1,closeOnScroll:r=!1,onOpenChange:i}=l,c=E(l,["render","threshold","velocityFactor","disabled","closeOnScroll","onOpenChange"]);let p=s.useId(),S=s.useContext(Q),U=(0,v.useReducedMotion)(),O=s.useRef(null),[u,se]=s.useState({left:0,right:0}),[T,ie]=s.useState("closed"),[I,V]=s.useState(!1),C=s.useRef("closed"),x=s.useRef(!1),m=(0,v.useMotionValue)(0),_=s.useCallback((a,d)=>{se(R=>R[a]===d?R:y(w({},R),{[a]:d}))},[]),g=s.useCallback((a,d)=>{let R=a==="left"?u.left:a==="right"?-u.right:0;(0,v.animate)(m,R,U?{duration:0}:d===void 0?J:y(w({},be),{velocity:d})),a!=="closed"&&(S==null||S.notifyOpen(p)),C.current!==a&&(C.current=a,ie(a),i==null||i(a))},[u,m,U,S,p,i]),b=s.useCallback(()=>g("closed"),[g]),k=s.useRef(()=>{});s.useEffect(()=>{k.current=b},[b]),s.useEffect(()=>S==null?void 0:S.register(p,()=>k.current()),[S,p]),s.useEffect(()=>{C.current==="left"&&m.set(u.left),C.current==="right"&&m.set(-u.right)},[u,m]);let K=s.useCallback(()=>{x.current=!1,V(!0),S==null||S.notifyOpen(p)},[S,p]),j=s.useCallback((a,d)=>{Math.abs(d.offset.x)>he&&(x.current=!0)},[]),G=s.useCallback((a,d)=>{V(!1);let R=m.get()+d.velocity.x*n;u.right>0&&R<=-u.right*e?g("right",d.velocity.x):u.left>0&&R>=u.left*e?g("left",d.velocity.x):g("closed",d.velocity.x)},[m,n,u,e,g]),z=s.useCallback(a=>{if(!(!x.current&&C.current==="closed")){if(a.preventDefault(),a.stopPropagation(),x.current){x.current=!1;return}b()}},[b]);s.useEffect(()=>{if(T==="closed")return;let a=H=>{var Y;(Y=O.current)!=null&&Y.contains(H.target)||k.current()},d=H=>{H.key==="Escape"&&k.current()},R=()=>k.current();return document.addEventListener("pointerdown",a,!0),document.addEventListener("keydown",d),r&&window.addEventListener("scroll",R,!0),()=>{document.removeEventListener("pointerdown",a,!0),document.removeEventListener("keydown",d),r&&window.removeEventListener("scroll",R,!0)}},[T,r]);let ae=s.useCallback(a=>{if(o||a.key!=="ArrowLeft"&&a.key!=="ArrowRight")return;let[d,R]=a.key==="ArrowLeft"?["left","right"]:["right","left"];if(C.current===d)g("closed");else if(u[R]>0)g(R);else return;a.preventDefault()},[o,u,g]),ce=s.useMemo(()=>({state:T,disabled:o,dragging:I}),[T,o,I]),de=s.useMemo(()=>({state:T,disabled:o,dragging:I,x:m,leftWidth:u.left,rightWidth:u.right,setStripWidth:_,close:b,onDragStart:K,onDrag:j,onDragEnd:G,onClickCapture:z}),[T,o,I,m,u,_,b,K,j,G,z]),le=A({defaultTagName:"div",render:t,state:ce,props:P({"data-slot":"swipe-item",ref:O,style:Pe,onKeyDown:ae},c)});return(0,L.jsx)(ee.Provider,{value:de,children:le})}function ne(o){var r=o,{render:t,side:e}=r,n=E(r,["render","side"]);let{state:i,setStripWidth:c}=N(),f=s.useRef(null);return s.useEffect(()=>{let l=f.current;if(!l)return;let p=new ResizeObserver(()=>c(e,l.offsetWidth));return p.observe(l),()=>{p.disconnect(),c(e,0)}},[e,c]),A({defaultTagName:"div",render:t,props:P({"data-slot":"swipe-actions","data-side":e,ref:f,style:y(w({},Te),{[e]:0}),inert:i!==e},n)})}function oe(o){var r=o,{render:t,closeOnClick:e=!0}=r,n=E(r,["render","closeOnClick"]);let{close:i}=N();return A({defaultTagName:"button",render:t,props:P({"data-slot":"swipe-action",type:"button",onClick:()=>{e&&i()}},n)})}function re(n){var o=n,{style:t}=o,e=E(o,["style"]);let S=N(),{x:r,disabled:i,dragging:c,leftWidth:f,rightWidth:l}=S,p=E(S,["x","disabled","dragging","leftWidth","rightWidth"]);return(0,L.jsx)(v.motion.div,y(w({"data-slot":"swipe-content"},e),{"data-dragging":c||void 0,style:y(w(w({},Ce),t),{x:r}),drag:i?!1:"x",dragConstraints:{left:-l,right:f},dragElastic:.2,dragMomentum:!1,onDragStart:p.onDragStart,onDrag:p.onDrag,onDragEnd:p.onDragEnd,onClickCapture:p.onClickCapture}))}0&&(module.exports={SwipeAction,SwipeActions,SwipeContent,SwipeItem,SwipeRoot});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ "use client";var ne=Object.defineProperty,oe=Object.defineProperties;var re=Object.getOwnPropertyDescriptors;var A=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var G=(t,e,n)=>e in t?ne(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,w=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&G(t,n,e[n]);if(A)for(var n of A(e))Y.call(e,n)&&G(t,n,e[n]);return t},y=(t,e)=>oe(t,re(e));var v=(t,e)=>{var n={};for(var o in t)z.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&A)for(var o of A(t))e.indexOf(o)<0&&Y.call(t,o)&&(n[o]=t[o]);return n};import*as r from"react";import{animate as ce,motion as de,useMotionValue as le,useReducedMotion as pe}from"motion/react";import*as b from"react";function k({defaultTagName:t,props:e,render:n,state:o={},stateAttributesMapping:s}){let i=E(se(o,s),e);if(!n)return b.createElement(t,i);if(typeof n=="function")return n(i,o);if(!b.isValidElement(n))return null;let c=n.props,f=E(i,c),l=y(w({},f),{ref:B(i.ref,c.ref)});return b.cloneElement(n,l)}function E(...t){let e={};for(let n of t){if(!n)continue;let o=n;for(let s of Object.keys(o)){let i=o[s];if(i===void 0)continue;let c=e[s];s==="className"?e[s]=[c,i].filter(Boolean).join(" "):s==="style"?e[s]=w(w({},c),i):s==="ref"?e[s]=B(c,i):ae(s)&&typeof c=="function"&&typeof i=="function"?e[s]=ie(i,c):e[s]=i}}return e}function se(t,e){var o;let n={};for(let s of Object.keys(t)){let i=t[s],c=(o=e==null?void 0:e[s])==null?void 0:o.call(e,i);if(c){Object.assign(n,c);continue}if(s==="slot"){n["data-slot"]=i;continue}let f=`data-${String(s).replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`;typeof i=="boolean"?n[f]=i?"":void 0:i!=null&&(n[f]=String(i))}return n}function ie(t,e){return function(o){t(o),o.defaultPrevented||e(o)}}function ae(t){return/^on[A-Z]/.test(t)}function B(...t){let e=t.filter(Boolean);if(e.length!==0)return n=>{for(let o of e)typeof o=="function"?o(n):o&&(o.current=n)}}import{jsx as L}from"react/jsx-runtime";var ue={position:"relative",isolation:"isolate",overflow:"hidden"},fe={position:"absolute",top:0,bottom:0,zIndex:0,display:"flex"},Se={position:"relative",zIndex:1},F={type:"spring",stiffness:500,damping:45,mass:.8},Re=y(w({},F),{damping:36}),we=4,Z=r.createContext(null);function me(n){var o=n,{render:t}=o,e=v(o,["render"]);let s=r.useRef(new Map),i=r.useMemo(()=>({register(f,l){return s.current.set(f,l),()=>{s.current.delete(f)}},notifyOpen(f){for(let[l,p]of s.current)l!==f&&p()}}),[]),c=k({defaultTagName:"div",render:t,props:E({"data-slot":"swipe-root"},e)});return L(Z.Provider,{value:i,children:c})}var $=r.createContext(null);function M(){let t=r.useContext($);if(!t)throw new Error("Swipe parts must be used within SwipeItem");return t}function ge(f){var l=f,{render:t,threshold:e=.5,velocityFactor:n=.2,disabled:o=!1,closeOnScroll:s=!1,onOpenChange:i}=l,c=v(l,["render","threshold","velocityFactor","disabled","closeOnScroll","onOpenChange"]);let p=r.useId(),S=r.useContext(Z),H=pe(),W=r.useRef(null),[u,q]=r.useState({left:0,right:0}),[P,J]=r.useState("closed"),[D,N]=r.useState(!1),T=r.useRef("closed"),h=r.useRef(!1),m=le(0),U=r.useCallback((a,d)=>{q(R=>R[a]===d?R:y(w({},R),{[a]:d}))},[]),g=r.useCallback((a,d)=>{let R=a==="left"?u.left:a==="right"?-u.right:0;ce(m,R,H?{duration:0}:d===void 0?F:y(w({},Re),{velocity:d})),a!=="closed"&&(S==null||S.notifyOpen(p)),T.current!==a&&(T.current=a,J(a),i==null||i(a))},[u,m,H,S,p,i]),C=r.useCallback(()=>g("closed"),[g]),x=r.useRef(()=>{});r.useEffect(()=>{x.current=C},[C]),r.useEffect(()=>S==null?void 0:S.register(p,()=>x.current()),[S,p]),r.useEffect(()=>{T.current==="left"&&m.set(u.left),T.current==="right"&&m.set(-u.right)},[u,m]);let O=r.useCallback(()=>{h.current=!1,N(!0),S==null||S.notifyOpen(p)},[S,p]),V=r.useCallback((a,d)=>{Math.abs(d.offset.x)>we&&(h.current=!0)},[]),_=r.useCallback((a,d)=>{N(!1);let R=m.get()+d.velocity.x*n;u.right>0&&R<=-u.right*e?g("right",d.velocity.x):u.left>0&&R>=u.left*e?g("left",d.velocity.x):g("closed",d.velocity.x)},[m,n,u,e,g]),K=r.useCallback(a=>{if(!(!h.current&&T.current==="closed")){if(a.preventDefault(),a.stopPropagation(),h.current){h.current=!1;return}C()}},[C]);r.useEffect(()=>{if(P==="closed")return;let a=I=>{var j;(j=W.current)!=null&&j.contains(I.target)||x.current()},d=I=>{I.key==="Escape"&&x.current()},R=()=>x.current();return document.addEventListener("pointerdown",a,!0),document.addEventListener("keydown",d),s&&window.addEventListener("scroll",R,!0),()=>{document.removeEventListener("pointerdown",a,!0),document.removeEventListener("keydown",d),s&&window.removeEventListener("scroll",R,!0)}},[P,s]);let Q=r.useCallback(a=>{if(o||a.key!=="ArrowLeft"&&a.key!=="ArrowRight")return;let[d,R]=a.key==="ArrowLeft"?["left","right"]:["right","left"];if(T.current===d)g("closed");else if(u[R]>0)g(R);else return;a.preventDefault()},[o,u,g]),X=r.useMemo(()=>({state:P,disabled:o,dragging:D}),[P,o,D]),ee=r.useMemo(()=>({state:P,disabled:o,dragging:D,x:m,leftWidth:u.left,rightWidth:u.right,setStripWidth:U,close:C,onDragStart:O,onDrag:V,onDragEnd:_,onClickCapture:K}),[P,o,D,m,u,U,C,O,V,_,K]),te=k({defaultTagName:"div",render:t,state:X,props:E({"data-slot":"swipe-item",ref:W,style:ue,onKeyDown:Q},c)});return L($.Provider,{value:ee,children:te})}function ye(o){var s=o,{render:t,side:e}=s,n=v(s,["render","side"]);let{state:i,setStripWidth:c}=M(),f=r.useRef(null);return r.useEffect(()=>{let l=f.current;if(!l)return;let p=new ResizeObserver(()=>c(e,l.offsetWidth));return p.observe(l),()=>{p.disconnect(),c(e,0)}},[e,c]),k({defaultTagName:"div",render:t,props:E({"data-slot":"swipe-actions","data-side":e,ref:f,style:y(w({},fe),{[e]:0}),inert:i!==e},n)})}function ve(o){var s=o,{render:t,closeOnClick:e=!0}=s,n=v(s,["render","closeOnClick"]);let{close:i}=M();return k({defaultTagName:"button",render:t,props:E({"data-slot":"swipe-action",type:"button",onClick:()=>{e&&i()}},n)})}function Ee(n){var o=n,{style:t}=o,e=v(o,["style"]);let S=M(),{x:s,disabled:i,dragging:c,leftWidth:f,rightWidth:l}=S,p=v(S,["x","disabled","dragging","leftWidth","rightWidth"]);return L(de.div,y(w({"data-slot":"swipe-content"},e),{"data-dragging":c||void 0,style:y(w(w({},Se),t),{x:s}),drag:i?!1:"x",dragConstraints:{left:-l,right:f},dragElastic:.2,dragMomentum:!1,onDragStart:p.onDragStart,onDrag:p.onDrag,onDragEnd:p.onDragEnd,onClickCapture:p.onClickCapture}))}export{ve as SwipeAction,ye as SwipeActions,Ee as SwipeContent,ge as SwipeItem,me as SwipeRoot};
package/package.json ADDED
@@ -0,0 +1,94 @@
1
+ {
2
+ "name": "@ncdai/react-swipe-actions",
3
+ "version": "0.1.0",
4
+ "description": "Unstyled swipe actions for React. Swipe a row in a list to reveal actions on the left or right.",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "commonjs",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ },
20
+ "require": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ },
24
+ "default": "./dist/index.js"
25
+ }
26
+ },
27
+ "tsup": {
28
+ "entry": [
29
+ "src/index.ts"
30
+ ],
31
+ "format": [
32
+ "esm",
33
+ "cjs"
34
+ ],
35
+ "bundle": true,
36
+ "clean": true,
37
+ "dts": true,
38
+ "outDir": "./dist"
39
+ },
40
+ "scripts": {
41
+ "dev": "tsup --watch",
42
+ "build": "tsup --minify",
43
+ "check-types": "tsc --noEmit",
44
+ "lint": "eslint .",
45
+ "lint:fix": "eslint . --fix",
46
+ "format:check": "prettier --check \"**/*.{ts,tsx}\" --cache",
47
+ "format:write": "prettier --write \"**/*.{ts,tsx}\" --cache"
48
+ },
49
+ "keywords": [
50
+ "react",
51
+ "swipe actions",
52
+ "swipe",
53
+ "swipe to reveal",
54
+ "swipe to delete",
55
+ "swipeable",
56
+ "list item",
57
+ "gesture",
58
+ "unstyled",
59
+ "headless"
60
+ ],
61
+ "author": "ncdai <dai@chanhdai.com>",
62
+ "license": "MIT",
63
+ "homepage": "https://react-primitives.chanhdai.com/swipe-actions",
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "git+https://github.com/ncdai/react-primitives.git",
67
+ "directory": "packages/react-swipe-actions"
68
+ },
69
+ "funding": "https://github.com/sponsors/ncdai",
70
+ "bugs": {
71
+ "url": "https://github.com/ncdai/react-primitives/issues"
72
+ },
73
+ "devDependencies": {
74
+ "@eslint/js": "9.27.0",
75
+ "@ianvs/prettier-plugin-sort-imports": "^4.7.1",
76
+ "@types/node": "^20",
77
+ "@types/react": "^19",
78
+ "eslint": "^9",
79
+ "eslint-config-prettier": "10.1.5",
80
+ "eslint-plugin-react": "7.37.5",
81
+ "eslint-plugin-react-hooks": "5.2.0",
82
+ "eslint-plugin-turbo": "^2.5.3",
83
+ "globals": "16.1.0",
84
+ "motion": "^12.39.0",
85
+ "react": "^19.0.0",
86
+ "tsup": "8.5.0",
87
+ "typescript": "^5.8.3",
88
+ "typescript-eslint": "8.32.1"
89
+ },
90
+ "peerDependencies": {
91
+ "motion": ">=12",
92
+ "react": "^18.0.0 || ^19.0.0"
93
+ }
94
+ }