# Swipe Actions

A list row that reveals action buttons when swiped sideways, with optional full swipe to run an action.

Swipe Actions is an open-source interaction from suiss/ui for React, React Native, SwiftUI and Jetpack Compose. The @esuiss/ui CLI copies its source into your project, so you own the code.

Source: https://ui.suiss.app/docs/interactions/swipe-actions

**React**

**Example**

```tsx
import {
  ArchiveIcon,
  EnvelopeSimpleIcon,
  TrashIcon,
} from "@phosphor-icons/react"
import * as React from "react"
import {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
} from "@/components/interactions/swipe-actions"
import { Button } from "@/components/ui/button"

const initialMessages = [
  {
    id: 1,
    from: "Acme Store",
    subject: "Your order has shipped",
    preview: "Order #1042 will be delivered tomorrow.",
  },
  {
    id: 2,
    from: "Jordan Lee",
    subject: "Tomorrow's meeting",
    preview: "Does 10:00 work for you?",
  },
  {
    id: 3,
    from: "Cloud Drive",
    subject: "Your storage is almost full",
    preview: "Upgrade your plan to get more space.",
  },
  {
    id: 4,
    from: "Taylor Kim",
    subject: "Weekend plans",
    preview: "Are we still on for Saturday?",
  },
]

function MailExample({ withLeading = false }: { withLeading?: boolean }) {
  const [messages, setMessages] = React.useState(initialMessages)
  const [unread, setUnread] = React.useState<number[]>([])
  const [log, setLog] = React.useState("Swipe a message to the left.")

  const remove = (id: number, action: string) => {
    setMessages((current) => current.filter((message) => message.id !== id))
    setLog(`${action} message ${id}`)
  }

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-3">
      <ul className="overflow-hidden rounded-2xl border">
        {messages.map((message) => (
          <li key={message.id} className="not-first:border-t">
            <SwipeActions>
              {withLeading && (
                <SwipeActionsActions side="leading">
                  <SwipeAction
                    onClick={() => {
                      setUnread((current) =>
                        current.includes(message.id)
                          ? current.filter((id) => id !== message.id)
                          : [...current, message.id]
                      )
                      setLog(`Toggled unread on message ${message.id}`)
                    }}
                  >
                    <EnvelopeSimpleIcon />
                    Unread
                  </SwipeAction>
                </SwipeActionsActions>
              )}
              <SwipeActionsContent className="flex flex-col gap-0.5 px-4 py-3">
                <span className="flex items-center gap-2 font-semibold">
                  {unread.includes(message.id) && (
                    <span className="size-2 rounded-full bg-primary" />
                  )}
                  {message.from}
                </span>
                <span className="text-sm">{message.subject}</span>
                <span className="truncate text-sm text-muted-foreground">
                  {message.preview}
                </span>
              </SwipeActionsContent>
              <SwipeActionsActions>
                <SwipeAction
                  variant="archive"
                  onClick={() => remove(message.id, "Archived")}
                >
                  <ArchiveIcon />
                  Archive
                </SwipeAction>
                <SwipeAction
                  variant="destructive"
                  fullSwipe
                  onClick={() => remove(message.id, "Deleted")}
                >
                  <TrashIcon />
                  Delete
                </SwipeAction>
              </SwipeActionsActions>
            </SwipeActions>
          </li>
        ))}
      </ul>
      <div className="flex items-center justify-between gap-3">
        <p role="status" className="text-sm text-muted-foreground">
          {log}
        </p>
        <Button
          size="sm"
          variant="secondary"
          onClick={() => {
            setMessages(initialMessages)
            setUnread([])
            setLog("Swipe a message to the left.")
          }}
        >
          Reset
        </Button>
      </div>
    </div>
  )
}

export default function SwipeActionsDemo() {
  return <MailExample />
}
```

`SwipeActions` recreates iOS swipe actions for list rows. Dragging `SwipeActionsContent` sideways reveals the buttons in `SwipeActionsActions` on that side; releasing past half their width snaps the row open, otherwise it springs closed. Dragging past the actions meets increasing resistance, unless an action has `fullSwipe`: then dragging past 60% of the row width expands that action across the row, and releasing collapses the row and runs it.

Only one row stays open at a time. Tapping the content or pressing elsewhere closes an open row, and choosing an action closes it after the action runs. Use it for quick per-row actions such as archive, delete, or mark as unread.

## Installation

### CLI

```bash title="Terminal"
npx shadcn@latest add @esuiss/swipe-actions
```

Works in any project with a `components.json`. See [Installation](https://ui.suiss.app/docs/installation#add-components) for the one-line registry setup. Or use the suiss/ui CLI:

```bash title="Terminal"
npx @esuiss/ui@latest add interactions swipe-actions
```

### Manual

1. Install the dependencies and add the [`cn` helper](https://ui.suiss.app/docs/installation#the-cn-helper):

```bash title="Terminal"
npm install class-variance-authority
```

2. Copy the source into `components/interactions/swipe-actions.tsx`:

```tsx title="components/interactions/swipe-actions.tsx"
"use client"

import { cva, type VariantProps } from "class-variance-authority"
import * as React from "react"
import { cn } from "@/lib/utils"

type SwipeActionsSide = "leading" | "trailing"

type SwipeActionsContextProps = {
  close: () => void
  onContentPointerDown: (event: React.PointerEvent<HTMLElement>) => void
  onContentClickCapture: (event: React.MouseEvent<HTMLElement>) => void
}

const SwipeActionsContext =
  React.createContext<SwipeActionsContextProps | null>(null)

function useSwipeActions() {
  const context = React.useContext(SwipeActionsContext)

  if (!context) {
    throw new Error("useSwipeActions must be used within a <SwipeActions />")
  }

  return context
}

const AXIS_LOCK = 8
const FULL_SWIPE_RATIO = 0.6
const OPEN_EVENT = "swipe-actions:open"

function actionsOf(root: HTMLElement, side: SwipeActionsSide) {
  return root.querySelector<HTMLElement>(
    `[data-slot=swipe-actions-actions][data-side=${side}]`
  )
}

function measureActions(root: HTMLElement, side: SwipeActionsSide) {
  const actions = actionsOf(root, side)
  if (!actions) return 0
  const previous = actions.style.width
  actions.style.width = ""
  const width = actions.scrollWidth
  actions.style.width = previous
  return width
}

function directionOf(root: HTMLElement) {
  return getComputedStyle(root).direction === "rtl" ? -1 : 1
}

function applyOffset(
  root: HTMLElement,
  offset: number,
  animate: boolean,
  full: SwipeActionsSide | null
) {
  root.toggleAttribute("data-animating", animate)
  root.style.setProperty(
    "--swipe-actions-offset",
    `${offset * directionOf(root)}px`
  )
  for (const side of ["leading", "trailing"] as const) {
    const actions = actionsOf(root, side)
    if (!actions) continue
    const revealed = side === "leading" ? offset : -offset
    actions.style.width = revealed > 0 ? `${revealed}px` : "0px"
  }
  if (full) root.dataset.full = full
  else delete root.dataset.full
  if (offset > 0) root.dataset.open = "leading"
  else if (offset < 0) root.dataset.open = "trailing"
  else delete root.dataset.open
}

function SwipeActions({
  className,
  children,
  ref,
  onKeyDown,
  onFocus,
  onBlur,
  ...props
}: React.ComponentProps<"div">) {
  const rootRef = React.useRef<HTMLDivElement>(null)
  const offsetRef = React.useRef(0)
  const draggedRef = React.useRef(false)
  const idRef = React.useRef(Symbol("swipe-actions"))

  const apply = (
    offset: number,
    animate: boolean,
    full: SwipeActionsSide | null = null
  ) => {
    const root = rootRef.current
    if (!root) return
    offsetRef.current = offset
    applyOffset(root, offset, animate, full)
  }

  const close = () => apply(0, true)
  const closeRef = React.useRef(close)
  closeRef.current = close

  const actionsFor = (side: SwipeActionsSide) =>
    rootRef.current ? actionsOf(rootRef.current, side) : null

  const naturalWidth = (side: SwipeActionsSide) =>
    rootRef.current ? measureActions(rootRef.current, side) : 0

  const direction = () => (rootRef.current ? directionOf(rootRef.current) : 1)

  const open = (side: SwipeActionsSide, width: number = naturalWidth(side)) => {
    if (!width) return close()
    apply(side === "leading" ? width : -width, true)
    document.dispatchEvent(
      new CustomEvent(OPEN_EVENT, { detail: idRef.current })
    )
  }

  const fullSwipe = (side: SwipeActionsSide) => {
    const root = rootRef.current
    const action =
      actionsFor(side)?.querySelector<HTMLElement>("[data-full-swipe]")
    if (!root || !action) return
    const width = root.offsetWidth
    apply(side === "leading" ? width : -width, true, side)
    const height = root.offsetHeight
    root.style.height = `${height}px`
    root.dataset.removing = ""
    window.setTimeout(() => {
      root.style.height = "0px"
      window.setTimeout(() => {
        action.click()
        window.setTimeout(() => {
          if (!root.isConnected) return
          delete root.dataset.removing
          root.style.height = ""
          apply(0, false)
        }, 50)
      }, 220)
    }, 180)
  }

  const onContentPointerDown = (event: React.PointerEvent<HTMLElement>) => {
    if (event.button !== 0) return
    const root = rootRef.current
    if (!root || root.hasAttribute("data-removing")) return
    const target = event.currentTarget
    const start = {
      x: event.clientX,
      y: event.clientY,
      offset: offsetRef.current,
    }
    let axis: "x" | "y" | null = null
    let full: SwipeActionsSide | null = null
    draggedRef.current = false
    root.removeAttribute("data-animating")
    const widths = {
      leading: naturalWidth("leading"),
      trailing: naturalWidth("trailing"),
    }
    const canFull = {
      leading: !!actionsFor("leading")?.querySelector("[data-full-swipe]"),
      trailing: !!actionsFor("trailing")?.querySelector("[data-full-swipe]"),
    }
    const rowWidth = root.offsetWidth

    const move = (moveEvent: PointerEvent) => {
      const dx = (moveEvent.clientX - start.x) * direction()
      const dy = moveEvent.clientY - start.y
      if (!axis) {
        if (Math.abs(dx) > AXIS_LOCK && Math.abs(dx) > Math.abs(dy)) {
          axis = "x"
          draggedRef.current = true
          target.setPointerCapture(moveEvent.pointerId)
        } else if (Math.abs(dy) > AXIS_LOCK) {
          axis = "y"
          return end()
        } else {
          return
        }
      }
      let next = start.offset + dx
      if (next > 0 && !widths.leading) next = 0
      if (next < 0 && !widths.trailing) next = 0
      const side: SwipeActionsSide = next > 0 ? "leading" : "trailing"
      const limit = side === "leading" ? widths.leading : widths.trailing
      const revealed = Math.abs(next)
      if (!canFull[side] && revealed > limit) {
        const extra = revealed - limit
        next = Math.sign(next) * (limit + extra / (1 + extra / 40))
      }
      full =
        canFull[side] && revealed > rowWidth * FULL_SWIPE_RATIO ? side : null
      apply(next, false, full)
    }

    const up = () => {
      end()
      if (axis !== "x") return
      const offset = offsetRef.current
      const side: SwipeActionsSide = offset > 0 ? "leading" : "trailing"
      if (full) return fullSwipe(full)
      const width = widths[side]
      if (width && Math.abs(offset) > width / 2) open(side, width)
      else close()
    }

    const end = () => {
      window.removeEventListener("pointermove", move)
      window.removeEventListener("pointerup", up)
      window.removeEventListener("pointercancel", up)
    }

    window.addEventListener("pointermove", move)
    window.addEventListener("pointerup", up)
    window.addEventListener("pointercancel", up)
  }

  const onContentClickCapture = (event: React.MouseEvent<HTMLElement>) => {
    if (!draggedRef.current && offsetRef.current === 0) return
    event.preventDefault()
    event.stopPropagation()
    if (!draggedRef.current) close()
    draggedRef.current = false
  }

  React.useEffect(() => {
    const root = rootRef.current
    if (!root) return
    const handleOpen = (event: Event) => {
      if ((event as CustomEvent).detail !== idRef.current) closeRef.current()
    }
    const handlePointerDown = (event: PointerEvent) => {
      if (offsetRef.current !== 0 && !root.contains(event.target as Node)) {
        closeRef.current()
      }
    }
    document.addEventListener(OPEN_EVENT, handleOpen)
    document.addEventListener("pointerdown", handlePointerDown)
    return () => {
      document.removeEventListener(OPEN_EVENT, handleOpen)
      document.removeEventListener("pointerdown", handlePointerDown)
    }
  }, [])

  return (
    <SwipeActionsContext.Provider
      value={{ close, onContentPointerDown, onContentClickCapture }}
    >
      <div
        ref={(node) => {
          rootRef.current = node
          if (typeof ref === "function") return ref(node)
          if (ref) ref.current = node
        }}
        role="group"
        data-slot="swipe-actions"
        className={cn(
          "group/swipe-actions relative overflow-hidden [--swipe-actions-offset:0px] data-removing:transition-[height] data-removing:duration-200 data-removing:ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:data-removing:transition-none",
          className
        )}
        onKeyDown={(event) => {
          onKeyDown?.(event)
          if (event.defaultPrevented) return
          if (event.key === "Escape" && offsetRef.current !== 0) {
            event.stopPropagation()
            close()
          }
        }}
        onFocus={(event) => {
          onFocus?.(event)
          const actions = (event.target as HTMLElement).closest<HTMLElement>(
            "[data-slot=swipe-actions-actions]"
          )
          const side = actions?.dataset.side as SwipeActionsSide | undefined
          if (side && rootRef.current?.dataset.open !== side) open(side)
        }}
        onBlur={(event) => {
          onBlur?.(event)
          if (!event.currentTarget.contains(event.relatedTarget as Node)) {
            close()
          }
        }}
        {...props}
      >
        {children}
      </div>
    </SwipeActionsContext.Provider>
  )
}

function SwipeActionsContent({
  className,
  onPointerDown,
  onClickCapture,
  ...props
}: React.ComponentProps<"div">) {
  const { onContentPointerDown, onContentClickCapture } = useSwipeActions()

  return (
    <div
      data-slot="swipe-actions-content"
      className={cn(
        "relative z-10 translate-x-(--swipe-actions-offset) touch-pan-y bg-background select-none group-data-animating/swipe-actions:transition-transform group-data-animating/swipe-actions:duration-300 group-data-animating/swipe-actions:ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:transition-none",
        className
      )}
      onPointerDown={(event) => {
        onPointerDown?.(event)
        if (!event.defaultPrevented) onContentPointerDown(event)
      }}
      onClickCapture={(event) => {
        onContentClickCapture(event)
        if (!event.isPropagationStopped()) onClickCapture?.(event)
      }}
      {...props}
    />
  )
}

function SwipeActionsActions({
  side = "trailing",
  className,
  ...props
}: React.ComponentProps<"div"> & { side?: SwipeActionsSide }) {
  return (
    <div
      data-slot="swipe-actions-actions"
      data-side={side}
      className={cn(
        "absolute inset-y-0 flex w-0 overflow-hidden group-data-animating/swipe-actions:transition-[width] group-data-animating/swipe-actions:duration-300 group-data-animating/swipe-actions:ease-[cubic-bezier(0.32,0.72,0,1)] data-[side=leading]:inset-s-0 data-[side=leading]:flex-row-reverse data-[side=trailing]:inset-e-0 motion-reduce:transition-none",
        className
      )}
      {...props}
    />
  )
}

const swipeActionVariants = cva(
  "flex min-w-18 flex-1 basis-0 flex-col items-center justify-center gap-1 overflow-hidden px-3 text-center text-xs font-medium wrap-break-word text-primary-foreground outline-none transition-[flex-grow,opacity] duration-200 focus-visible:ring-inset focus-visible:ring-3 focus-visible:ring-ring/50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-5",
  {
    variants: {
      variant: {
        default: "bg-primary",
        destructive:
          "bg-destructive dark:bg-[color-mix(in_oklab,var(--destructive),var(--background)_30%)]",
        archive:
          "bg-[color-mix(in_oklab,var(--color-purple-500),var(--foreground)_15%)] dark:bg-[color-mix(in_oklab,var(--color-purple-500),var(--background)_30%)]",
        neutral:
          "bg-[color-mix(in_oklab,var(--color-zinc-500),var(--foreground)_35%)] dark:bg-[color-mix(in_oklab,var(--color-zinc-500),var(--background)_40%)]",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

function SwipeAction({
  variant,
  fullSwipe = false,
  className,
  onClick,
  ...props
}: React.ComponentProps<"button"> &
  VariantProps<typeof swipeActionVariants> & {
    fullSwipe?: boolean
  }) {
  const { close } = useSwipeActions()

  return (
    <button
      type="button"
      data-slot="swipe-action"
      data-full-swipe={fullSwipe ? "" : undefined}
      className={cn(
        swipeActionVariants({ variant }),
        "group-data-full/swipe-actions:not-data-full-swipe:min-w-0 group-data-full/swipe-actions:not-data-full-swipe:grow-0 group-data-full/swipe-actions:not-data-full-swipe:px-0 group-data-full/swipe-actions:not-data-full-swipe:opacity-0 group-data-full/swipe-actions:data-full-swipe:grow-100",
        className
      )}
      onClick={(event) => {
        onClick?.(event)
        if (!event.currentTarget.closest("[data-removing]")) close()
      }}
      {...props}
    />
  )
}

export {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
  swipeActionVariants,
  useSwipeActions,
}
```

3. Update the import paths to match your project.

## Usage

```tsx
import { SwipeActions, SwipeActionsContent, SwipeActionsActions, SwipeAction } from "@/components/interactions/swipe-actions"
```

```tsx
<MailExample />
```

- Place `SwipeActionsContent` inside `SwipeActions`, with a `SwipeActionsActions` for each side that has actions. Rows can have leading actions, trailing actions, or both.
- Handle each action with `onClick`. A full swipe runs the action by clicking it, so the same handler covers both.
- `useSwipeActions` returns `close` for closing the row from custom controls.
- Gestures are detected with pointer events and locked to the horizontal axis after a few pixels, so vertical scrolling still works.

## Examples

### Both sides

A row with a leading Unread action on one side and trailing Archive and Delete actions on the other.

**Example**

```tsx
import {
  ArchiveIcon,
  EnvelopeSimpleIcon,
  TrashIcon,
} from "@phosphor-icons/react"
import * as React from "react"
import {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
} from "@/components/interactions/swipe-actions"
import { Button } from "@/components/ui/button"

const initialMessages = [
  {
    id: 1,
    from: "Acme Store",
    subject: "Your order has shipped",
    preview: "Order #1042 will be delivered tomorrow.",
  },
  {
    id: 2,
    from: "Jordan Lee",
    subject: "Tomorrow's meeting",
    preview: "Does 10:00 work for you?",
  },
  {
    id: 3,
    from: "Cloud Drive",
    subject: "Your storage is almost full",
    preview: "Upgrade your plan to get more space.",
  },
  {
    id: 4,
    from: "Taylor Kim",
    subject: "Weekend plans",
    preview: "Are we still on for Saturday?",
  },
]

function MailExample({ withLeading = false }: { withLeading?: boolean }) {
  const [messages, setMessages] = React.useState(initialMessages)
  const [unread, setUnread] = React.useState<number[]>([])
  const [log, setLog] = React.useState("Swipe a message to the left.")

  const remove = (id: number, action: string) => {
    setMessages((current) => current.filter((message) => message.id !== id))
    setLog(`${action} message ${id}`)
  }

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-3">
      <ul className="overflow-hidden rounded-2xl border">
        {messages.map((message) => (
          <li key={message.id} className="not-first:border-t">
            <SwipeActions>
              {withLeading && (
                <SwipeActionsActions side="leading">
                  <SwipeAction
                    onClick={() => {
                      setUnread((current) =>
                        current.includes(message.id)
                          ? current.filter((id) => id !== message.id)
                          : [...current, message.id]
                      )
                      setLog(`Toggled unread on message ${message.id}`)
                    }}
                  >
                    <EnvelopeSimpleIcon />
                    Unread
                  </SwipeAction>
                </SwipeActionsActions>
              )}
              <SwipeActionsContent className="flex flex-col gap-0.5 px-4 py-3">
                <span className="flex items-center gap-2 font-semibold">
                  {unread.includes(message.id) && (
                    <span className="size-2 rounded-full bg-primary" />
                  )}
                  {message.from}
                </span>
                <span className="text-sm">{message.subject}</span>
                <span className="truncate text-sm text-muted-foreground">
                  {message.preview}
                </span>
              </SwipeActionsContent>
              <SwipeActionsActions>
                <SwipeAction
                  variant="archive"
                  onClick={() => remove(message.id, "Archived")}
                >
                  <ArchiveIcon />
                  Archive
                </SwipeAction>
                <SwipeAction
                  variant="destructive"
                  fullSwipe
                  onClick={() => remove(message.id, "Deleted")}
                >
                  <TrashIcon />
                  Delete
                </SwipeAction>
              </SwipeActionsActions>
            </SwipeActions>
          </li>
        ))}
      </ul>
      <div className="flex items-center justify-between gap-3">
        <p role="status" className="text-sm text-muted-foreground">
          {log}
        </p>
        <Button
          size="sm"
          variant="secondary"
          onClick={() => {
            setMessages(initialMessages)
            setUnread([])
            setLog("Swipe a message to the left.")
          }}
        >
          Reset
        </Button>
      </div>
    </div>
  )
}

export default function SwipeActionsBothSides() {
  return <MailExample withLeading />
}
```

### Variants

The `default`, `neutral`, `archive`, and `destructive` action colors side by side.

**Example**

```tsx
import {
  ArchiveIcon,
  BellSlashIcon,
  FlagIcon,
  TrashIcon,
} from "@phosphor-icons/react"
import {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
} from "@/components/interactions/swipe-actions"

export default function SwipeActionsVariants() {
  return (
    <div className="mx-auto w-full max-w-md overflow-hidden rounded-2xl border">
      <SwipeActions>
        <SwipeActionsContent className="px-4 py-3">
          Swipe to see every action style
        </SwipeActionsContent>
        <SwipeActionsActions>
          <SwipeAction>
            <FlagIcon className="fill-current" />
            Flag
          </SwipeAction>
          <SwipeAction variant="neutral">
            <BellSlashIcon />
            Mute
          </SwipeAction>
          <SwipeAction variant="archive">
            <ArchiveIcon />
            Archive
          </SwipeAction>
          <SwipeAction variant="destructive">
            <TrashIcon />
            Delete
          </SwipeAction>
        </SwipeActionsActions>
      </SwipeActions>
    </div>
  )
}
```

## API Reference

- `SwipeActions`
- `SwipeActionsContent`
- `SwipeActionsActions`
  - `SwipeAction`

### SwipeActions

The row container that tracks the swipe and manages open state.

Also accepts the props of `React.ComponentProps<"div">`.

### SwipeActionsContent

The visible row content that moves with the swipe.

Also accepts the props of `React.ComponentProps<"div">`.

### SwipeActionsActions

The group of actions revealed on one side of the row.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `side` | `SwipeActionsSide` | `"trailing"` | The edge the actions appear on: `leading` or `trailing`. |

Also accepts the props of `React.ComponentProps<"div">`.

### SwipeAction

A single action button revealed by the swipe.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `"default" \| "destructive" \| "archive" \| "neutral"` | `"default"` | The background color of the action: `default`, `destructive`, `archive`, or `neutral`. |
| `fullSwipe` | `boolean` | `false` | Lets a long swipe expand this action across the row and run it. |

Also accepts the props of `React.ComponentProps<"button">`.

## Accessibility

- The row has `role="group"`, and actions are native buttons that stay in the tab order.
- Moving focus to an action opens its side of the row so the button is visible; moving focus out of the row closes it.
- `Escape` closes an open row.
- Leading and trailing sides follow the writing direction, so swipes mirror in right-to-left layouts.

## Notes

- The root uses `data-slot="swipe-actions"` and sets `data-open` (`leading` or `trailing`), `data-full` during a full swipe, and `data-removing` while the row collapses. Action groups expose `data-side`, and full-swipe actions set `data-full-swipe`.
- The `--swipe-actions-offset` custom property holds the current offset.
- `swipeActionVariants` is exported for styling other elements like an action.

**React Native, SwiftUI, Jetpack Compose**

![Preview](https://ui.suiss.app/previews/interactions-swipe-actions--default.light.webp)

```tsx
import { ArchiveIcon, BellSlashIcon, EnvelopeOpenIcon, TrashIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { SwipeAction, SwipeActions, SwipeActionsActions, SwipeActionsContent } from "@/components/interactions/swipe-actions"
import { Icon } from "@/components/ui/icon"
import { Item, ItemContent, ItemDescription, ItemGroup, ItemSeparator, ItemTitle } from "@/components/ui/item"
import { Text } from "@/components/ui/text"

const MESSAGES = [
  { id: "1", from: "Olivia Martin", subject: "Quarterly report is ready" },
  { id: "2", from: "Jackson Lee", subject: "Lunch on Friday?" },
  { id: "3", from: "Isabella Nguyen", subject: "Design review notes" },
]

function Inbox() {
  const [messages, setMessages] = React.useState(MESSAGES)
  const remove = (id: string) =>
    setMessages((current) => current.filter((message) => message.id !== id))
  return (
    <ItemGroup variant="inset">
      {messages.map((message, index) => (
        <React.Fragment key={message.id}>
          {index > 0 ? <ItemSeparator /> : null}
          <SwipeActions>
            <SwipeActionsActions side="leading">
              <SwipeAction>
                <Icon as={EnvelopeOpenIcon} />
                <Text>Read</Text>
              </SwipeAction>
            </SwipeActionsActions>
            <SwipeActionsContent className="bg-muted">
              <Item onPress={() => undefined}>
                <ItemContent>
                  <ItemTitle>{message.from}</ItemTitle>
                  <ItemDescription>{message.subject}</ItemDescription>
                </ItemContent>
              </Item>
            </SwipeActionsContent>
            <SwipeActionsActions side="trailing">
              <SwipeAction variant="neutral">
                <Icon as={BellSlashIcon} />
                <Text>Mute</Text>
              </SwipeAction>
              <SwipeAction variant="archive">
                <Icon as={ArchiveIcon} />
                <Text>Archive</Text>
              </SwipeAction>
              <SwipeAction
                variant="destructive"
                fullSwipe
                onPress={() => remove(message.id)}
              >
                <Icon as={TrashIcon} />
                <Text>Delete</Text>
              </SwipeAction>
            </SwipeActionsActions>
          </SwipeActions>
        </React.Fragment>
      ))}
    </ItemGroup>
  )
}

export function SwipeActionsExample() {
  return (
    <View>
      <Inbox />
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct SwipeActionsMessage: Identifiable {
  let id: String
  let from: String
  let subject: String
}

let swipeActionsMessages = [
  SwipeActionsMessage(id: "1", from: "Olivia Martin", subject: "Quarterly report is ready"),
  SwipeActionsMessage(id: "2", from: "Jackson Lee", subject: "Lunch on Friday?"),
  SwipeActionsMessage(id: "3", from: "Isabella Nguyen", subject: "Design review notes"),
]

struct SwipeActionsInbox: View {
  @State private var messages = swipeActionsMessages

  var body: some View {
    ItemGroup(.inset) {
      ForEach(Array(messages.enumerated()), id: \.element.id) { index, message in
        if index > 0 {
          ItemSeparator()
        }
        SwipeActions(background: EsuissColor.muted) {
          Item(action: {}) {
            ItemContent {
              ItemTitle(verbatim: message.from)
              ItemDescription(verbatim: message.subject)
            }
          }
        } leading: {
          SwipeAction("Read", icon: Ph.envelopeOpen.regular) {}
        } trailing: {
          SwipeAction("Mute", icon: Ph.bellSlash.regular, variant: .neutral) {}
          SwipeAction("Archive", icon: Ph.archive.regular, variant: .archive) {}
          SwipeAction("Delete", icon: Ph.trash.regular, variant: .destructive, fullSwipe: true) {
            messages.removeAll { $0.id == message.id }
          }
        }
      }
    }
  }
}
```

```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.Archive
import com.adamglin.phosphoricons.regular.BellSlash
import com.adamglin.phosphoricons.regular.EnvelopeOpen
import com.adamglin.phosphoricons.regular.Trash
import com.esuiss.ui.components.Item
import com.esuiss.ui.components.ItemContent
import com.esuiss.ui.components.ItemDescription
import com.esuiss.ui.components.ItemGroup
import com.esuiss.ui.components.ItemGroupVariant
import com.esuiss.ui.components.ItemSeparator
import com.esuiss.ui.components.ItemTitle
import com.esuiss.ui.interactions.SwipeAction
import com.esuiss.ui.interactions.SwipeActionVariant
import com.esuiss.ui.interactions.SwipeActions
import com.esuiss.ui.theme.EsuissTheme

class SwipeActionsMessage(val id: String, val from: String, val subject: String)

val swipeActionsMessages = listOf(
    SwipeActionsMessage("1", "Olivia Martin", "Quarterly report is ready"),
    SwipeActionsMessage("2", "Jackson Lee", "Lunch on Friday?"),
    SwipeActionsMessage("3", "Isabella Nguyen", "Design review notes"),
)

@Composable
fun SwipeActionsInbox() {
    var messages by remember { mutableStateOf(swipeActionsMessages) }
    ItemGroup(variant = ItemGroupVariant.Inset) {
        messages.forEachIndexed { index, message ->
            key(message.id) {
                if (index > 0) ItemSeparator()
                SwipeActions(
                    leading = listOf(SwipeAction("Read", {}, icon = PhosphorIcons.Regular.EnvelopeOpen)),
                    trailing = listOf(
                        SwipeAction("Mute", {}, icon = PhosphorIcons.Regular.BellSlash, variant = SwipeActionVariant.Neutral),
                        SwipeAction("Archive", {}, icon = PhosphorIcons.Regular.Archive, variant = SwipeActionVariant.Archive),
                        SwipeAction(
                            "Delete",
                            { messages = messages.filterNot { it.id == message.id } },
                            icon = PhosphorIcons.Regular.Trash,
                            variant = SwipeActionVariant.Destructive,
                            fullSwipe = true,
                        ),
                    ),
                    background = EsuissTheme.colors.muted,
                ) {
                    Item(onClick = {}) {
                        ItemContent {
                            ItemTitle(message.from)
                            ItemDescription(message.subject)
                        }
                    }
                }
            }
        }
    }
}
```

`SwipeActions` wraps a row so it can be dragged left or right to reveal `SwipeAction` buttons on the leading or trailing side. The buttons stretch to fill the revealed space, and opening one row closes any other open row.

When an action has `fullSwipe`, dragging past 60% of the row width expands that action over the others with a medium impact haptic. Releasing there slides the row off, collapses its height, then runs the action, which suits delete or archive. Use it for mail, message or task lists.

## Installation

**React Native**

```bash title="Terminal"
npx shadcn@latest add @esuiss-rn/swipe-actions
```

See [Installation](https://ui.suiss.app/docs/installation) for the `components.json` setup. Or use the suiss/ui CLI:

```bash title="Terminal"
npx @esuiss/ui@latest add swipe-actions
```

**SwiftUI**

```bash title="Terminal"
npx @esuiss/ui@latest add swipe-actions --platform swift
```

**Jetpack Compose**

```bash title="Terminal"
npx @esuiss/ui@latest add swipe-actions --platform kotlin
```

The CLI also adds what it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text). On React Native it also adds the animated view `components/ui/animated-view.tsx`.

### Manual

**React Native**

**Uniwind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install class-variance-authority cn react-native-gesture-handler react-native-reanimated react-native-worklets
```

2. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

3. Copy the animated view into `components/ui/animated-view.tsx`:

- `uniwind/components/ui/animated-view.tsx`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/uniwind/components/ui/animated-view.tsx)

4. Copy the source into `components/interactions/swipe-actions.tsx`:

```tsx title="uniwind/components/interactions/swipe-actions.tsx"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  Pressable,
  View,
  type ViewProps,
} from "react-native"
import ReanimatedSwipeable, {
  type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable"
import {
  Easing,
  runOnJS,
  type SharedValue,
  useAnimatedReaction,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { IconClassContext } from "@/components/ui/icon"
import { TextClassContext } from "@/components/ui/text"

type SwipeActionsSide = "leading" | "trailing"

type SwipeActionsContextProps = {
  close: () => void
  full: SwipeActionsSide | null
  offset: SharedValue<number>
  accessibilityActions: { name: string; label: string }[]
  onAccessibilityAction: (event: AccessibilityActionEvent) => void
}

const SwipeActionsContext =
  React.createContext<SwipeActionsContextProps | null>(null)

const SwipeActionsSideContext =
  React.createContext<SwipeActionsSide>("trailing")

function useSwipeActions() {
  const context = React.useContext(SwipeActionsContext)

  if (!context) {
    throw new Error("useSwipeActions must be used within a <SwipeActions />")
  }

  return context
}

const FULL_SWIPE_RATIO = 0.6
const SWIPE_ACTION_PATTERN = /^swipe-action-(\d+)$/
const EASING = Easing.bezier(0.32, 0.72, 0, 1)
const openRows = new Set<() => void>()

type SwipeActionElement = React.ReactElement<SwipeActionProps>

type SwipeActionsActionsElement = React.ReactElement<
  ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
>

function textOf(node: unknown): string {
  if (node == null || typeof node === "boolean") return ""
  if (typeof node === "string" || typeof node === "number") return String(node)
  if (Array.isArray(node)) return node.map(textOf).filter(Boolean).join(" ")
  if (React.isValidElement<{ children?: unknown }>(node)) {
    return textOf(node.props.children)
  }
  return ""
}

function actionsOf(element: SwipeActionsActionsElement | undefined) {
  if (!element) return []
  return React.Children.toArray(element.props.children).filter(
    (child): child is SwipeActionElement =>
      React.isValidElement(child) && child.type === SwipeAction
  )
}

function ActionsLayer({
  physical,
  translation,
  offset,
  rowWidth,
  canFull,
  onFullChange,
  element,
}: {
  physical: "left" | "right"
  translation: SharedValue<number>
  offset: SharedValue<number>
  rowWidth: SharedValue<number>
  canFull: boolean
  onFullChange: (full: boolean) => void
  element: SwipeActionsActionsElement
}) {
  const { side = "trailing", className, style, ...props } = element.props
  const sign = physical === "left" ? 1 : -1

  useAnimatedReaction(
    () =>
      canFull &&
      rowWidth.value > 0 &&
      sign * (translation.value + offset.value) >
        rowWidth.value * FULL_SWIPE_RATIO,
    (next, previous) => {
      if (next !== previous) runOnJS(onFullChange)(next)
    }
  )

  const animatedStyle = useAnimatedStyle(() => ({
    minWidth: Math.max(0, sign * (translation.value + offset.value)),
  }))

  return (
    <SwipeActionsSideContext.Provider value={side}>
      <AnimatedView
        className={cn(
          "h-full overflow-hidden",
          side === "leading" ? "flex-row-reverse" : "flex-row",
          className
        )}
        style={[animatedStyle, style]}
        {...props}
      />
    </SwipeActionsSideContext.Provider>
  )
}

function SwipeActions({
  className,
  style,
  children,
  onOpenChange,
  onLayout,
  ...props
}: ViewProps & {
  onOpenChange?: (side: SwipeActionsSide | null) => void
}) {
  const swipeableRef = React.useRef<SwipeableMethods>(null)
  const rowWidth = useSharedValue(0)
  const rowHeight = useSharedValue(0)
  const collapse = useSharedValue(-1)
  const offset = useSharedValue(0)
  const fullRef = React.useRef<SwipeActionsSide | null>(null)
  const committingRef = React.useRef(false)
  const mountedRef = React.useRef(true)
  const timersRef = React.useRef(new Set<ReturnType<typeof setTimeout>>())
  const pendingRef = React.useRef<(() => void) | null>(null)
  const [full, setFull] = React.useState<SwipeActionsSide | null>(null)
  const [openSide, setOpenSide] = React.useState<SwipeActionsSide | null>(null)
  const haptics = useHaptics()

  const nodes = React.Children.toArray(children)
  const isActions = (node: React.ReactNode) =>
    React.isValidElement(node) && node.type === SwipeActionsActions
  const actionElements = nodes.filter(isActions) as SwipeActionsActionsElement[]
  const leading = actionElements.find((node) => node.props.side === "leading")
  const trailing = actionElements.find(
    (node) => (node.props.side ?? "trailing") === "trailing"
  )
  const content = nodes.filter((node) => !isActions(node))
  const leadingActions = actionsOf(leading)
  const trailingActions = actionsOf(trailing)
  const canFull = {
    leading: leadingActions.some((action) => action.props.fullSwipe),
    trailing: trailingActions.some((action) => action.props.fullSwipe),
  }
  const leftSide: SwipeActionsSide = I18nManager.isRTL ? "trailing" : "leading"
  const rightSide: SwipeActionsSide = I18nManager.isRTL ? "leading" : "trailing"
  const elements = { leading, trailing }

  const close = React.useCallback(() => {
    swipeableRef.current?.close()
  }, [])

  React.useEffect(() => {
    mountedRef.current = true
    const timers = timersRef.current
    return () => {
      mountedRef.current = false
      openRows.delete(close)
      for (const timer of timers) clearTimeout(timer)
      timers.clear()
      const pending = pendingRef.current
      pendingRef.current = null
      pending?.()
    }
  }, [close])

  const schedule = (callback: () => void, delay: number) => {
    const timer = setTimeout(() => {
      timersRef.current.delete(timer)
      callback()
    }, delay)
    timersRef.current.add(timer)
  }

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    const released = fullRef.current === side ? null : fullRef.current
    const value = next ? side : released
    fullRef.current = value
    setFull(value)
  }

  const commit = (side: SwipeActionsSide) => {
    const action = (side === "leading" ? leadingActions : trailingActions).find(
      (item) => item.props.fullSwipe
    )
    if (!action) return
    committingRef.current = true
    pendingRef.current = () => action.props.onPress?.()
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    schedule(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      schedule(() => {
        pendingRef.current = null
        action.props.onPress?.()
        schedule(() => {
          if (!mountedRef.current) return
          swipeableRef.current?.reset()
          offset.value = 0
          collapse.value = -1
          committingRef.current = false
          fullRef.current = null
          setFull(null)
          setOpenSide(null)
          onOpenChange?.(null)
        }, 50)
      }, 220)
    }, 180)
  }

  const onWillOpen = (direction: "left" | "right") => {
    const side = direction === "right" ? leftSide : rightSide
    for (const closeRow of openRows) {
      if (closeRow !== close) closeRow()
    }
    openRows.add(close)
    if (fullRef.current === side) {
      commit(side)
      return
    }
    setOpenSide(side)
    onOpenChange?.(side)
  }

  const onClose = () => {
    openRows.delete(close)
    if (committingRef.current) return
    setOpenSide(null)
    onOpenChange?.(null)
  }

  const collapseStyle = useAnimatedStyle(() =>
    collapse.value < 0 ? {} : { height: collapse.value }
  )

  const allActions = [...leadingActions, ...trailingActions]
  const accessibilityActions = allActions.map((action, index) => ({
    name: `swipe-action-${index}`,
    label:
      action.props.accessibilityLabel ??
      (textOf(action.props.children) || "Action"),
  }))

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const match = SWIPE_ACTION_PATTERN.exec(event.nativeEvent.actionName)
    if (!match) return
    allActions[Number(match[1])]?.props.onPress?.()
  }

  const renderLayer =
    (physical: "left" | "right") =>
    (_progress: SharedValue<number>, translation: SharedValue<number>) => {
      const side = physical === "left" ? leftSide : rightSide
      const element = elements[side]
      if (!element) return null
      return (
        <View
          className="h-full"
          importantForAccessibility={
            openSide === side ? "auto" : "no-hide-descendants"
          }
          accessibilityElementsHidden={openSide !== side}
        >
          <ActionsLayer
            physical={physical}
            translation={translation}
            offset={offset}
            rowWidth={rowWidth}
            canFull={canFull[side]}
            onFullChange={setFullSide(side)}
            element={element}
          />
        </View>
      )
    }

  return (
    <SwipeActionsContext.Provider
      value={{
        close,
        full,
        offset,
        accessibilityActions,
        onAccessibilityAction,
      }}
    >
      <AnimatedView
        role="group"
        className={cn("relative overflow-hidden", className)}
        style={[collapseStyle, style]}
        onLayout={(event) => {
          rowWidth.value = event.nativeEvent.layout.width
          if (collapse.value < 0) {
            rowHeight.value = event.nativeEvent.layout.height
          }
          onLayout?.(event)
        }}
        {...props}
      >
        <ReanimatedSwipeable
          ref={swipeableRef}
          friction={1}
          overshootFriction={1}
          overshootLeft={canFull[leftSide]}
          overshootRight={canFull[rightSide]}
          renderLeftActions={
            elements[leftSide] ? renderLayer("left") : undefined
          }
          renderRightActions={
            elements[rightSide] ? renderLayer("right") : undefined
          }
          onSwipeableWillOpen={onWillOpen}
          onSwipeableClose={onClose}
        >
          {content}
        </ReanimatedSwipeable>
      </AnimatedView>
    </SwipeActionsContext.Provider>
  )
}

function SwipeActionsContent({
  className,
  style,
  accessibilityActions,
  onAccessibilityAction,
  ...props
}: ViewProps) {
  const context = useSwipeActions()
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: context.offset.value }],
  }))

  return (
    <AnimatedView
      accessible
      accessibilityActions={[
        ...(accessibilityActions ?? []),
        ...context.accessibilityActions,
      ]}
      onAccessibilityAction={(event) => {
        context.onAccessibilityAction(event)
        onAccessibilityAction?.(event)
      }}
      className={cn("relative z-10 bg-background", className)}
      style={[animatedStyle, style]}
      {...props}
    />
  )
}

function SwipeActionsActions(
  _props: ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
) {
  return null
}

const swipeActionVariants = cva(
  "min-w-18 flex-1 basis-0 flex-col items-center justify-center gap-1 overflow-hidden px-3",
  {
    variants: {
      variant: {
        default: "bg-primary",
        destructive: "bg-destructive",
        archive: "bg-purple-500",
        neutral: "bg-zinc-500",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

type SwipeActionProps = Omit<
  React.ComponentProps<typeof Pressable>,
  "onPress"
> &
  VariantProps<typeof swipeActionVariants> & {
    fullSwipe?: boolean
    onPress?: () => void
  }

function SwipeAction({
  variant,
  fullSwipe = false,
  className,
  onPress,
  ...props
}: SwipeActionProps) {
  const { close, full } = useSwipeActions()
  const side = React.useContext(SwipeActionsSideContext)
  const expanding = full === side
  return (
    <TextClassContext.Provider value="text-center text-xs font-medium text-primary-foreground">
      <IconClassContext.Provider value="size-5 text-primary-foreground">
        <Pressable
          role="button"
          className={cn(
            swipeActionVariants({ variant }),
            "active:opacity-80",
            expanding && !fullSwipe && "w-0 min-w-0 grow-0 px-0 opacity-0",
            className
          )}
          onPress={() => {
            onPress?.()
            close()
          }}
          {...props}
        />
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
  swipeActionVariants,
  useSwipeActions,
}
```

5. Update the import paths to match your project.

**NativeWind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install class-variance-authority cn react-native-gesture-handler react-native-reanimated react-native-worklets
```

2. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

3. Copy the animated view into `components/ui/animated-view.tsx`:

- `nativewind/components/ui/animated-view.tsx`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/nativewind/components/ui/animated-view.tsx)

4. Copy the source into `components/interactions/swipe-actions.tsx`:

```tsx title="nativewind/components/interactions/swipe-actions.tsx"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  Pressable,
  View,
  type ViewProps,
} from "react-native"
import ReanimatedSwipeable, {
  type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable"
import {
  Easing,
  runOnJS,
  type SharedValue,
  useAnimatedReaction,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { IconClassContext } from "@/components/ui/icon"
import { TextClassContext } from "@/components/ui/text"

type SwipeActionsSide = "leading" | "trailing"

type SwipeActionsContextProps = {
  close: () => void
  full: SwipeActionsSide | null
  offset: SharedValue<number>
  accessibilityActions: { name: string; label: string }[]
  onAccessibilityAction: (event: AccessibilityActionEvent) => void
}

const SwipeActionsContext =
  React.createContext<SwipeActionsContextProps | null>(null)

const SwipeActionsSideContext =
  React.createContext<SwipeActionsSide>("trailing")

function useSwipeActions() {
  const context = React.useContext(SwipeActionsContext)

  if (!context) {
    throw new Error("useSwipeActions must be used within a <SwipeActions />")
  }

  return context
}

const FULL_SWIPE_RATIO = 0.6
const SWIPE_ACTION_PATTERN = /^swipe-action-(\d+)$/
const EASING = Easing.bezier(0.32, 0.72, 0, 1)
const openRows = new Set<() => void>()

type SwipeActionElement = React.ReactElement<SwipeActionProps>

type SwipeActionsActionsElement = React.ReactElement<
  ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
>

function textOf(node: unknown): string {
  if (node == null || typeof node === "boolean") return ""
  if (typeof node === "string" || typeof node === "number") return String(node)
  if (Array.isArray(node)) return node.map(textOf).filter(Boolean).join(" ")
  if (React.isValidElement<{ children?: unknown }>(node)) {
    return textOf(node.props.children)
  }
  return ""
}

function actionsOf(element: SwipeActionsActionsElement | undefined) {
  if (!element) return []
  return React.Children.toArray(element.props.children).filter(
    (child): child is SwipeActionElement =>
      React.isValidElement(child) && child.type === SwipeAction
  )
}

function ActionsLayer({
  physical,
  translation,
  offset,
  rowWidth,
  canFull,
  onFullChange,
  element,
}: {
  physical: "left" | "right"
  translation: SharedValue<number>
  offset: SharedValue<number>
  rowWidth: SharedValue<number>
  canFull: boolean
  onFullChange: (full: boolean) => void
  element: SwipeActionsActionsElement
}) {
  const { side = "trailing", className, style, ...props } = element.props
  const sign = physical === "left" ? 1 : -1

  useAnimatedReaction(
    () =>
      canFull &&
      rowWidth.value > 0 &&
      sign * (translation.value + offset.value) >
        rowWidth.value * FULL_SWIPE_RATIO,
    (next, previous) => {
      if (next !== previous) runOnJS(onFullChange)(next)
    }
  )

  const animatedStyle = useAnimatedStyle(() => ({
    minWidth: Math.max(0, sign * (translation.value + offset.value)),
  }))

  return (
    <SwipeActionsSideContext.Provider value={side}>
      <AnimatedView
        className={cn(
          "h-full overflow-hidden",
          side === "leading" ? "flex-row-reverse" : "flex-row",
          className
        )}
        style={[animatedStyle, style]}
        {...props}
      />
    </SwipeActionsSideContext.Provider>
  )
}

function SwipeActions({
  className,
  style,
  children,
  onOpenChange,
  onLayout,
  ...props
}: ViewProps & {
  onOpenChange?: (side: SwipeActionsSide | null) => void
}) {
  const swipeableRef = React.useRef<SwipeableMethods>(null)
  const rowWidth = useSharedValue(0)
  const rowHeight = useSharedValue(0)
  const collapse = useSharedValue(-1)
  const offset = useSharedValue(0)
  const fullRef = React.useRef<SwipeActionsSide | null>(null)
  const committingRef = React.useRef(false)
  const mountedRef = React.useRef(true)
  const timersRef = React.useRef(new Set<ReturnType<typeof setTimeout>>())
  const pendingRef = React.useRef<(() => void) | null>(null)
  const [full, setFull] = React.useState<SwipeActionsSide | null>(null)
  const [openSide, setOpenSide] = React.useState<SwipeActionsSide | null>(null)
  const haptics = useHaptics()

  const nodes = React.Children.toArray(children)
  const isActions = (node: React.ReactNode) =>
    React.isValidElement(node) && node.type === SwipeActionsActions
  const actionElements = nodes.filter(isActions) as SwipeActionsActionsElement[]
  const leading = actionElements.find((node) => node.props.side === "leading")
  const trailing = actionElements.find(
    (node) => (node.props.side ?? "trailing") === "trailing"
  )
  const content = nodes.filter((node) => !isActions(node))
  const leadingActions = actionsOf(leading)
  const trailingActions = actionsOf(trailing)
  const canFull = {
    leading: leadingActions.some((action) => action.props.fullSwipe),
    trailing: trailingActions.some((action) => action.props.fullSwipe),
  }
  const leftSide: SwipeActionsSide = I18nManager.isRTL ? "trailing" : "leading"
  const rightSide: SwipeActionsSide = I18nManager.isRTL ? "leading" : "trailing"
  const elements = { leading, trailing }

  const close = React.useCallback(() => {
    swipeableRef.current?.close()
  }, [])

  React.useEffect(() => {
    mountedRef.current = true
    const timers = timersRef.current
    return () => {
      mountedRef.current = false
      openRows.delete(close)
      for (const timer of timers) clearTimeout(timer)
      timers.clear()
      const pending = pendingRef.current
      pendingRef.current = null
      pending?.()
    }
  }, [close])

  const schedule = (callback: () => void, delay: number) => {
    const timer = setTimeout(() => {
      timersRef.current.delete(timer)
      callback()
    }, delay)
    timersRef.current.add(timer)
  }

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    const released = fullRef.current === side ? null : fullRef.current
    const value = next ? side : released
    fullRef.current = value
    setFull(value)
  }

  const commit = (side: SwipeActionsSide) => {
    const action = (side === "leading" ? leadingActions : trailingActions).find(
      (item) => item.props.fullSwipe
    )
    if (!action) return
    committingRef.current = true
    pendingRef.current = () => action.props.onPress?.()
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    schedule(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      schedule(() => {
        pendingRef.current = null
        action.props.onPress?.()
        schedule(() => {
          if (!mountedRef.current) return
          swipeableRef.current?.reset()
          offset.value = 0
          collapse.value = -1
          committingRef.current = false
          fullRef.current = null
          setFull(null)
          setOpenSide(null)
          onOpenChange?.(null)
        }, 50)
      }, 220)
    }, 180)
  }

  const onWillOpen = (direction: "left" | "right") => {
    const side = direction === "right" ? leftSide : rightSide
    for (const closeRow of openRows) {
      if (closeRow !== close) closeRow()
    }
    openRows.add(close)
    if (fullRef.current === side) {
      commit(side)
      return
    }
    setOpenSide(side)
    onOpenChange?.(side)
  }

  const onClose = () => {
    openRows.delete(close)
    if (committingRef.current) return
    setOpenSide(null)
    onOpenChange?.(null)
  }

  const collapseStyle = useAnimatedStyle(() =>
    collapse.value < 0 ? {} : { height: collapse.value }
  )

  const allActions = [...leadingActions, ...trailingActions]
  const accessibilityActions = allActions.map((action, index) => ({
    name: `swipe-action-${index}`,
    label:
      action.props.accessibilityLabel ??
      (textOf(action.props.children) || "Action"),
  }))

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const match = SWIPE_ACTION_PATTERN.exec(event.nativeEvent.actionName)
    if (!match) return
    allActions[Number(match[1])]?.props.onPress?.()
  }

  const renderLayer =
    (physical: "left" | "right") =>
    (_progress: SharedValue<number>, translation: SharedValue<number>) => {
      const side = physical === "left" ? leftSide : rightSide
      const element = elements[side]
      if (!element) return null
      return (
        <View
          className="h-full"
          importantForAccessibility={
            openSide === side ? "auto" : "no-hide-descendants"
          }
          accessibilityElementsHidden={openSide !== side}
        >
          <ActionsLayer
            physical={physical}
            translation={translation}
            offset={offset}
            rowWidth={rowWidth}
            canFull={canFull[side]}
            onFullChange={setFullSide(side)}
            element={element}
          />
        </View>
      )
    }

  return (
    <SwipeActionsContext.Provider
      value={{
        close,
        full,
        offset,
        accessibilityActions,
        onAccessibilityAction,
      }}
    >
      <AnimatedView
        role="group"
        className={cn("relative overflow-hidden", className)}
        style={[collapseStyle, style]}
        onLayout={(event) => {
          rowWidth.value = event.nativeEvent.layout.width
          if (collapse.value < 0) {
            rowHeight.value = event.nativeEvent.layout.height
          }
          onLayout?.(event)
        }}
        {...props}
      >
        <ReanimatedSwipeable
          ref={swipeableRef}
          friction={1}
          overshootFriction={1}
          overshootLeft={canFull[leftSide]}
          overshootRight={canFull[rightSide]}
          renderLeftActions={
            elements[leftSide] ? renderLayer("left") : undefined
          }
          renderRightActions={
            elements[rightSide] ? renderLayer("right") : undefined
          }
          onSwipeableWillOpen={onWillOpen}
          onSwipeableClose={onClose}
        >
          {content}
        </ReanimatedSwipeable>
      </AnimatedView>
    </SwipeActionsContext.Provider>
  )
}

function SwipeActionsContent({
  className,
  style,
  accessibilityActions,
  onAccessibilityAction,
  ...props
}: ViewProps) {
  const context = useSwipeActions()
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: context.offset.value }],
  }))

  return (
    <AnimatedView
      accessible
      accessibilityActions={[
        ...(accessibilityActions ?? []),
        ...context.accessibilityActions,
      ]}
      onAccessibilityAction={(event) => {
        context.onAccessibilityAction(event)
        onAccessibilityAction?.(event)
      }}
      className={cn("relative z-10 bg-background", className)}
      style={[animatedStyle, style]}
      {...props}
    />
  )
}

function SwipeActionsActions(
  _props: ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
) {
  return null
}

const swipeActionVariants = cva(
  "min-w-[4.5rem] flex-1 basis-0 flex-col items-center justify-center gap-1 overflow-hidden px-3",
  {
    variants: {
      variant: {
        default: "bg-primary",
        destructive: "bg-destructive",
        archive: "bg-purple-500",
        neutral: "bg-zinc-500",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

type SwipeActionProps = Omit<
  React.ComponentProps<typeof Pressable>,
  "onPress"
> &
  VariantProps<typeof swipeActionVariants> & {
    fullSwipe?: boolean
    onPress?: () => void
  }

function SwipeAction({
  variant,
  fullSwipe = false,
  className,
  onPress,
  ...props
}: SwipeActionProps) {
  const { close, full } = useSwipeActions()
  const side = React.useContext(SwipeActionsSideContext)
  const expanding = full === side
  return (
    <TextClassContext.Provider value="text-center text-xs font-medium text-primary-foreground">
      <IconClassContext.Provider value="size-5 text-primary-foreground">
        <Pressable
          role="button"
          className={cn(
            swipeActionVariants({ variant }),
            "active:opacity-80",
            expanding && !fullSwipe && "w-0 min-w-0 grow-0 px-0 opacity-0",
            className
          )}
          onPress={() => {
            onPress?.()
            close()
          }}
          {...props}
        />
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
  swipeActionVariants,
  useSwipeActions,
}
```

5. Update the import paths to match your project.

**StyleSheet**

1. Install the dependencies:

```bash title="Terminal"
npx expo install react-native-gesture-handler react-native-reanimated react-native-worklets
```

2. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

3. Copy the animated view into `components/ui/animated-view.tsx`:

- `stylesheet/components/ui/animated-view.tsx`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/stylesheet/components/ui/animated-view.tsx)

4. Copy the source into `components/interactions/swipe-actions.tsx`:

```tsx title="stylesheet/components/interactions/swipe-actions.tsx"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  Pressable,
  StyleSheet,
  View,
  type ViewProps,
} from "react-native"
import ReanimatedSwipeable, {
  type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable"
import {
  Easing,
  runOnJS,
  type SharedValue,
  useAnimatedReaction,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { IconSizeContext } from "@/components/ui/icon"
import { TextStyleContext } from "@/components/ui/text"
import {
  fontSize,
  palette,
  type ThemeColors,
  useTheme,
} from "@/components/ui/theme"

type SwipeActionsSide = "leading" | "trailing"

type SwipeActionsContextProps = {
  close: () => void
  full: SwipeActionsSide | null
  offset: SharedValue<number>
  accessibilityActions: { name: string; label: string }[]
  onAccessibilityAction: (event: AccessibilityActionEvent) => void
}

const SwipeActionsContext =
  React.createContext<SwipeActionsContextProps | null>(null)

const SwipeActionsSideContext =
  React.createContext<SwipeActionsSide>("trailing")

function useSwipeActions() {
  const context = React.useContext(SwipeActionsContext)

  if (!context) {
    throw new Error("useSwipeActions must be used within a <SwipeActions />")
  }

  return context
}

const FULL_SWIPE_RATIO = 0.6
const EASING = Easing.bezier(0.32, 0.72, 0, 1)
const openRows = new Set<() => void>()
const SWIPE_ACTION_NAME = /^swipe-action-(\d+)$/

type SwipeActionElement = React.ReactElement<SwipeActionProps>

type SwipeActionsActionsElement = React.ReactElement<
  ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
>

function textOf(node: unknown): string {
  if (node == null || typeof node === "boolean") return ""
  if (typeof node === "string" || typeof node === "number") return String(node)
  if (Array.isArray(node)) return node.map(textOf).filter(Boolean).join(" ")
  if (React.isValidElement<{ children?: unknown }>(node)) {
    return textOf(node.props.children)
  }
  return ""
}

function actionsOf(element: SwipeActionsActionsElement | undefined) {
  if (!element) return []
  return React.Children.toArray(element.props.children).filter(
    (child): child is SwipeActionElement =>
      React.isValidElement(child) && child.type === SwipeAction
  )
}

function ActionsLayer({
  physical,
  translation,
  offset,
  rowWidth,
  canFull,
  onFullChange,
  element,
}: {
  physical: "left" | "right"
  translation: SharedValue<number>
  offset: SharedValue<number>
  rowWidth: SharedValue<number>
  canFull: boolean
  onFullChange: (full: boolean) => void
  element: SwipeActionsActionsElement
}) {
  const { side = "trailing", style, ...props } = element.props
  const sign = physical === "left" ? 1 : -1

  useAnimatedReaction(
    () =>
      canFull &&
      rowWidth.value > 0 &&
      sign * (translation.value + offset.value) >
        rowWidth.value * FULL_SWIPE_RATIO,
    (next, previous) => {
      if (next !== previous) runOnJS(onFullChange)(next)
    }
  )

  const animatedStyle = useAnimatedStyle(() => ({
    minWidth: Math.max(0, sign * (translation.value + offset.value)),
  }))

  return (
    <SwipeActionsSideContext.Provider value={side}>
      <AnimatedView
        style={[
          styles.layer,
          { flexDirection: side === "leading" ? "row-reverse" : "row" },
          animatedStyle,
          style,
        ]}
        {...props}
      />
    </SwipeActionsSideContext.Provider>
  )
}

function SwipeActions({
  style,
  children,
  onOpenChange,
  onLayout,
  ...props
}: ViewProps & {
  onOpenChange?: (side: SwipeActionsSide | null) => void
}) {
  const swipeableRef = React.useRef<SwipeableMethods>(null)
  const rowWidth = useSharedValue(0)
  const rowHeight = useSharedValue(0)
  const collapse = useSharedValue(-1)
  const offset = useSharedValue(0)
  const fullRef = React.useRef<SwipeActionsSide | null>(null)
  const committingRef = React.useRef(false)
  const mountedRef = React.useRef(true)
  const timersRef = React.useRef(new Set<ReturnType<typeof setTimeout>>())
  const pendingRef = React.useRef<(() => void) | null>(null)
  const [full, setFull] = React.useState<SwipeActionsSide | null>(null)
  const [openSide, setOpenSide] = React.useState<SwipeActionsSide | null>(null)
  const haptics = useHaptics()

  const nodes = React.Children.toArray(children)
  const isActions = (node: React.ReactNode) =>
    React.isValidElement(node) && node.type === SwipeActionsActions
  const actionElements = nodes.filter(isActions) as SwipeActionsActionsElement[]
  const leading = actionElements.find((node) => node.props.side === "leading")
  const trailing = actionElements.find(
    (node) => (node.props.side ?? "trailing") === "trailing"
  )
  const content = nodes.filter((node) => !isActions(node))
  const leadingActions = actionsOf(leading)
  const trailingActions = actionsOf(trailing)
  const canFull = {
    leading: leadingActions.some((action) => action.props.fullSwipe),
    trailing: trailingActions.some((action) => action.props.fullSwipe),
  }
  const leftSide: SwipeActionsSide = I18nManager.isRTL ? "trailing" : "leading"
  const rightSide: SwipeActionsSide = I18nManager.isRTL ? "leading" : "trailing"
  const elements = { leading, trailing }

  const close = React.useCallback(() => {
    swipeableRef.current?.close()
  }, [])

  React.useEffect(() => {
    mountedRef.current = true
    const timers = timersRef.current
    return () => {
      mountedRef.current = false
      openRows.delete(close)
      for (const timer of timers) clearTimeout(timer)
      timers.clear()
      const pending = pendingRef.current
      pendingRef.current = null
      pending?.()
    }
  }, [close])

  const schedule = (callback: () => void, delay: number) => {
    const timer = setTimeout(() => {
      timersRef.current.delete(timer)
      callback()
    }, delay)
    timersRef.current.add(timer)
  }

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    let value = fullRef.current === side ? null : fullRef.current
    if (next) value = side
    fullRef.current = value
    setFull(value)
  }

  const commit = (side: SwipeActionsSide) => {
    const action = (side === "leading" ? leadingActions : trailingActions).find(
      (item) => item.props.fullSwipe
    )
    if (!action) return
    committingRef.current = true
    pendingRef.current = () => action.props.onPress?.()
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    schedule(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      schedule(() => {
        pendingRef.current = null
        action.props.onPress?.()
        schedule(() => {
          if (!mountedRef.current) return
          swipeableRef.current?.reset()
          offset.value = 0
          collapse.value = -1
          committingRef.current = false
          fullRef.current = null
          setFull(null)
          setOpenSide(null)
          onOpenChange?.(null)
        }, 50)
      }, 220)
    }, 180)
  }

  const onWillOpen = (direction: "left" | "right") => {
    const side = direction === "right" ? leftSide : rightSide
    for (const closeRow of openRows) {
      if (closeRow !== close) closeRow()
    }
    openRows.add(close)
    if (fullRef.current === side) {
      commit(side)
      return
    }
    setOpenSide(side)
    onOpenChange?.(side)
  }

  const onClose = () => {
    openRows.delete(close)
    if (committingRef.current) return
    setOpenSide(null)
    onOpenChange?.(null)
  }

  const collapseStyle = useAnimatedStyle(() =>
    collapse.value < 0 ? {} : { height: collapse.value }
  )

  const allActions = [...leadingActions, ...trailingActions]
  const accessibilityActions = allActions.map((action, index) => ({
    name: `swipe-action-${index}`,
    label:
      action.props.accessibilityLabel ??
      (textOf(action.props.children) || "Action"),
  }))

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const match = SWIPE_ACTION_NAME.exec(event.nativeEvent.actionName)
    if (!match) return
    allActions[Number(match[1])]?.props.onPress?.()
  }

  const renderLayer =
    (physical: "left" | "right") =>
    (_progress: SharedValue<number>, translation: SharedValue<number>) => {
      const side = physical === "left" ? leftSide : rightSide
      const element = elements[side]
      if (!element) return null
      return (
        <View
          style={styles.fill}
          importantForAccessibility={
            openSide === side ? "auto" : "no-hide-descendants"
          }
          accessibilityElementsHidden={openSide !== side}
        >
          <ActionsLayer
            physical={physical}
            translation={translation}
            offset={offset}
            rowWidth={rowWidth}
            canFull={canFull[side]}
            onFullChange={setFullSide(side)}
            element={element}
          />
        </View>
      )
    }

  return (
    <SwipeActionsContext.Provider
      value={{
        close,
        full,
        offset,
        accessibilityActions,
        onAccessibilityAction,
      }}
    >
      <AnimatedView
        role="group"
        style={[styles.root, collapseStyle, style]}
        onLayout={(event) => {
          rowWidth.value = event.nativeEvent.layout.width
          if (collapse.value < 0) {
            rowHeight.value = event.nativeEvent.layout.height
          }
          onLayout?.(event)
        }}
        {...props}
      >
        <ReanimatedSwipeable
          ref={swipeableRef}
          friction={1}
          overshootFriction={1}
          overshootLeft={canFull[leftSide]}
          overshootRight={canFull[rightSide]}
          renderLeftActions={
            elements[leftSide] ? renderLayer("left") : undefined
          }
          renderRightActions={
            elements[rightSide] ? renderLayer("right") : undefined
          }
          onSwipeableWillOpen={onWillOpen}
          onSwipeableClose={onClose}
        >
          {content}
        </ReanimatedSwipeable>
      </AnimatedView>
    </SwipeActionsContext.Provider>
  )
}

function SwipeActionsContent({
  style,
  accessibilityActions,
  onAccessibilityAction,
  ...props
}: ViewProps) {
  const context = useSwipeActions()
  const { colors } = useTheme()
  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: context.offset.value }],
  }))

  return (
    <AnimatedView
      accessible
      accessibilityActions={[
        ...(accessibilityActions ?? []),
        ...context.accessibilityActions,
      ]}
      onAccessibilityAction={(event) => {
        context.onAccessibilityAction(event)
        onAccessibilityAction?.(event)
      }}
      style={[
        styles.content,
        { backgroundColor: colors.background },
        animatedStyle,
        style,
      ]}
      {...props}
    />
  )
}

function SwipeActionsActions(
  _props: ViewProps & { side?: SwipeActionsSide; children?: React.ReactNode }
) {
  return null
}

type SwipeActionVariant = "default" | "destructive" | "archive" | "neutral"

function swipeActionColor(variant: SwipeActionVariant, colors: ThemeColors) {
  switch (variant) {
    case "destructive":
      return colors.destructive
    case "archive":
      return palette.purple500
    case "neutral":
      return palette.zinc500
    default:
      return colors.primary
  }
}

const styles = StyleSheet.create({
  root: { position: "relative", overflow: "hidden" },
  fill: { height: "100%" },
  layer: { height: "100%", overflow: "hidden" },
  content: { position: "relative", zIndex: 10 },
  action: {
    minWidth: 72,
    flex: 1,
    flexBasis: 0,
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    gap: 4,
    overflow: "hidden",
    paddingHorizontal: 12,
  },
  collapsed: {
    width: 0,
    minWidth: 0,
    flexGrow: 0,
    paddingHorizontal: 0,
    opacity: 0,
  },
})

type SwipeActionProps = Omit<
  React.ComponentProps<typeof Pressable>,
  "onPress"
> & {
  variant?: SwipeActionVariant
  fullSwipe?: boolean
  onPress?: () => void
}

function SwipeAction({
  variant = "default",
  fullSwipe = false,
  style,
  onPress,
  ...props
}: SwipeActionProps) {
  const { close, full } = useSwipeActions()
  const side = React.useContext(SwipeActionsSideContext)
  const { colors } = useTheme()
  const expanding = full === side
  return (
    <TextStyleContext.Provider
      value={{
        ...fontSize.xs,
        fontWeight: "500",
        textAlign: "center",
        color: colors.primaryForeground,
      }}
    >
      <IconSizeContext.Provider value={20}>
        <Pressable
          role="button"
          style={(state) => [
            styles.action,
            { backgroundColor: swipeActionColor(variant, colors) },
            state.pressed && { opacity: 0.8 },
            expanding && !fullSwipe && styles.collapsed,
            typeof style === "function" ? style(state) : style,
          ]}
          onPress={() => {
            onPress?.()
            close()
          }}
          {...props}
        />
      </IconSizeContext.Provider>
    </TextStyleContext.Provider>
  )
}

export {
  SwipeAction,
  SwipeActions,
  SwipeActionsActions,
  SwipeActionsContent,
  useSwipeActions,
}
```

5. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Copy the theme files every view uses:

- `swift/Theme/Theme.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Theme/Theme.swift)

- `swift/Theme/Tokens.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Theme/Tokens.swift)

3. Copy the source and every file it uses:

```swift title="swift/Interactions/SwipeActions.swift"
import SwiftUI

public enum SwipeActionVariant: CaseIterable, Sendable {
  case `default`, destructive, archive, neutral

  var color: Color {
    switch self {
    case .default: EsuissColor.primary
    case .destructive: EsuissColor.destructive
    case .archive: Palette.purple500
    case .neutral: Palette.zinc500
    }
  }
}

enum SwipeActionsMode: Sendable {
  case native, custom, accessibility
}

struct SwipeActionsContext: Sendable {
  var mode: SwipeActionsMode = .native
  var full = false
  var trigger = 0
  var direction: LayoutDirection = .leftToRight
  var close: @MainActor @Sendable () -> Void = {}
}

extension EnvironmentValues {
  @Entry var swipeActions = SwipeActionsContext()
}

struct SwipeFullKey: PreferenceKey {
  static var defaultValue: Bool { false }

  static func reduce(value: inout Bool, nextValue: () -> Bool) {
    value = value || nextValue()
  }
}

extension Notification.Name {
  static let swipeActionsOpen = Notification.Name("swipe-actions.open")
}

public struct SwipeActions<Content: View, Leading: View, Trailing: View>: View {
  let background: Color
  let content: Content
  let leading: Leading
  let trailing: Trailing

  @State private var id = UUID()
  @State private var offset: CGFloat = 0
  @State private var start: CGFloat?
  @State private var axis: Axis?
  @State private var rowWidth: CGFloat = 0
  @State private var rowHeight: CGFloat = 0
  @State private var leadingWidth: CGFloat = 0
  @State private var trailingWidth: CGFloat = 0
  @State private var leadingFull = false
  @State private var trailingFull = false
  @State private var full: HorizontalEdge?
  @State private var collapsed: CGFloat?
  @State private var trigger = 0
  @Environment(\.layoutDirection) private var layoutDirection
  @Environment(\.accessibilityReduceMotion) private var reduceMotion

  public init(
    background: Color = EsuissColor.background,
    @ViewBuilder content: () -> Content,
    @ViewBuilder leading: () -> Leading,
    @ViewBuilder trailing: () -> Trailing
  ) {
    self.init(background: background, revealed: 0, content: content, leading: leading, trailing: trailing)
  }

  init(
    background: Color = EsuissColor.background,
    revealed: CGFloat,
    full: HorizontalEdge? = nil,
    @ViewBuilder content: () -> Content,
    @ViewBuilder leading: () -> Leading,
    @ViewBuilder trailing: () -> Trailing
  ) {
    self.background = background
    self.content = content()
    self.leading = leading()
    self.trailing = trailing()
    _offset = State(initialValue: revealed)
    _full = State(initialValue: full)
  }

  public var body: some View {
    let close = closeAction
    ZStack {
      if offset > 0 {
        actions(leading, edge: .leading, revealed: offset, close: close)
      }
      if offset < 0 {
        actions(trailing, edge: .trailing, revealed: -offset, close: close)
      }
      content
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(background)
        .overlay {
          if offset != 0 {
            Color.clear
              .contentShape(Rectangle())
              .onTapGesture { settle(0) }
              .accessibilityHidden(true)
          }
        }
        .offset(x: offset)
        .simultaneousGesture(drag)
        .accessibilityActions {
          Group {
            leading
            trailing
          }
          .environment(\.swipeActions, SwipeActionsContext(mode: .accessibility, close: close))
        }
    }
    .onGeometryChange(for: CGSize.self) { $0.size } action: { size in
      rowWidth = size.width
      if collapsed == nil { rowHeight = size.height }
    }
    .background {
      ZStack {
        measure(leading) { leadingWidth = $0 }
          .onPreferenceChange(SwipeFullKey.self) { leadingFull = $0 }
        measure(trailing) { trailingWidth = $0 }
          .onPreferenceChange(SwipeFullKey.self) { trailingFull = $0 }
      }
      .hidden()
      .accessibilityHidden(true)
      .allowsHitTesting(false)
    }
    .frame(height: collapsed, alignment: .top)
    .clipped()
    .hapticFeedback(.impact(weight: .medium), trigger: full) { HapticMoments.crossed($0, $1) }
    .accessibilityElement(children: .contain)
    .accessibilityAction(.escape) { settle(0) }
    .onReceive(NotificationCenter.default.publisher(for: .swipeActionsOpen)) { note in
      if let other = note.object as? UUID, other != id, offset != 0 {
        settle(0)
      }
    }
  }

  private var closeAction: @MainActor @Sendable () -> Void {
    let offset = $offset
    let full = $full
    let animation = settleAnimation
    return {
      withAnimation(animation) {
        offset.wrappedValue = 0
        full.wrappedValue = nil
      }
    }
  }

  private var settleAnimation: Animation? {
    reduceMotion ? .easeOut(duration: 0.15) : .timingCurve(0.32, 0.72, 0, 1, duration: 0.3)
  }

  private func measure<V: View>(_ view: V, _ update: @escaping (CGFloat) -> Void) -> some View {
    HStack(spacing: 0) { view }
      .environment(\.swipeActions, SwipeActionsContext(mode: .custom))
      .fixedSize()
      .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { update($0) }
  }

  private func actions<V: View>(_ view: V, edge: HorizontalEdge, revealed: CGFloat, close: @escaping @MainActor @Sendable () -> Void) -> some View {
    let flipped: LayoutDirection = layoutDirection == .leftToRight ? .rightToLeft : .leftToRight
    return HStack(spacing: 0) { view }
      .environment(
        \.swipeActions,
        SwipeActionsContext(mode: .custom, full: full == edge, trigger: trigger, direction: layoutDirection, close: close)
      )
      .environment(\.layoutDirection, edge == .leading ? flipped : layoutDirection)
      .frame(width: max(revealed, 0), alignment: edge == .leading ? .trailing : .leading)
      .frame(maxHeight: .infinity)
      .clipped()
      .frame(maxWidth: .infinity, alignment: edge == .leading ? .leading : .trailing)
      .accessibilityHidden(true)
  }

  private var drag: some Gesture {
    DragGesture(minimumDistance: 8)
      .onChanged { value in
        if collapsed != nil { return }
        if axis == nil {
          let dx = abs(value.translation.width)
          let dy = abs(value.translation.height)
          if dx > 8 && dx > dy {
            axis = .horizontal
            start = offset
          } else if dy > 8 {
            axis = .vertical
          } else {
            return
          }
        }
        guard axis == .horizontal, let start else { return }
        var next = start + value.translation.width
        if next > 0 && leadingWidth == 0 { next = 0 }
        if next < 0 && trailingWidth == 0 { next = 0 }
        let edge: HorizontalEdge = next > 0 ? .leading : .trailing
        let limit = edge == .leading ? leadingWidth : trailingWidth
        let canFull = edge == .leading ? leadingFull : trailingFull
        let revealed = abs(next)
        if !canFull && revealed > limit {
          let extra = revealed - limit
          next = (next > 0 ? 1 : -1) * (limit + extra / (1 + extra / 40))
        }
        let nextFull: HorizontalEdge? = canFull && revealed > rowWidth * 0.6 ? edge : nil
        if nextFull != full {
          withAnimation(.easeOut(duration: 0.2)) { full = nextFull }
        }
        offset = next
      }
      .onEnded { _ in
        defer {
          axis = nil
          start = nil
        }
        guard axis == .horizontal else { return }
        if let full {
          fullSwipe(full)
          return
        }
        let edge: HorizontalEdge = offset > 0 ? .leading : .trailing
        let width = edge == .leading ? leadingWidth : trailingWidth
        if width > 0 && abs(offset) > width / 2 {
          settle(edge == .leading ? width : -width)
        } else {
          settle(0)
        }
      }
  }

  private func settle(_ value: CGFloat) {
    withAnimation(settleAnimation) {
      offset = value
      if value == 0 { full = nil }
    }
    if value != 0 {
      NotificationCenter.default.post(name: .swipeActionsOpen, object: id)
    }
  }

  private func fullSwipe(_ edge: HorizontalEdge) {
    let width = rowWidth
    let height = rowHeight
    withAnimation(.timingCurve(0.32, 0.72, 0, 1, duration: 0.18)) {
      offset = edge == .leading ? width : -width
    } completion: {
      collapsed = height
      withAnimation(reduceMotion ? nil : .timingCurve(0.32, 0.72, 0, 1, duration: 0.2)) {
        collapsed = 0
      } completion: {
        trigger += 1
        Task { @MainActor in
          try? await Task.sleep(for: .milliseconds(50))
          var transaction = Transaction()
          transaction.disablesAnimations = true
          withTransaction(transaction) {
            offset = 0
            full = nil
            collapsed = nil
          }
        }
      }
    }
  }
}

extension SwipeActions where Leading == EmptyView {
  public init(
    background: Color = EsuissColor.background,
    @ViewBuilder content: () -> Content,
    @ViewBuilder trailing: () -> Trailing
  ) {
    self.init(background: background, content: content, leading: { EmptyView() }, trailing: trailing)
  }
}

extension SwipeActions where Trailing == EmptyView {
  public init(
    background: Color = EsuissColor.background,
    @ViewBuilder content: () -> Content,
    @ViewBuilder leading: () -> Leading
  ) {
    self.init(background: background, content: content, leading: leading, trailing: { EmptyView() })
  }
}

public struct SwipeAction<Label: View>: View {
  let title: Text
  let variant: SwipeActionVariant
  let fullSwipe: Bool
  let action: () -> Void
  let label: Label

  @Environment(\.swipeActions) private var context

  public init(
    _ title: LocalizedStringKey,
    variant: SwipeActionVariant = .default,
    fullSwipe: Bool = false,
    action: @escaping () -> Void,
    @ViewBuilder label: () -> Label
  ) {
    self.title = Text(title)
    self.variant = variant
    self.fullSwipe = fullSwipe
    self.action = action
    self.label = label()
  }

  public var body: some View {
    switch context.mode {
    case .native:
      Button(role: variant == .destructive ? .destructive : nil, action: action) {
        label
      }
      .tint(variant.color)
    case .accessibility:
      Button(action: action) {
        title
      }
    case .custom:
      let hidden = context.full && !fullSwipe
      let grow = context.full && fullSwipe
      Button {
        action()
        context.close()
      } label: {
        label
          .labelStyle(SwipeActionLabelStyle())
          .scaledFont(TextStyle.xs, weight: .medium)
          .multilineTextAlignment(.center)
          .foregroundStyle(EsuissColor.primaryForeground)
          .environment(\.layoutDirection, context.direction)
          .padding(.horizontal, hidden ? 0 : 12)
          .frame(minWidth: hidden ? 0 : 72, maxWidth: hidden ? 0 : .infinity, maxHeight: .infinity)
          .opacity(hidden ? 0 : 1)
          .background(variant.color)
          .contentShape(Rectangle())
      }
      .buttonStyle(SwipeActionButtonStyle())
      .layoutPriority(grow ? 1 : 0)
      .preference(key: SwipeFullKey.self, value: fullSwipe)
      .onChange(of: context.trigger) {
        if grow { action() }
      }
    }
  }
}

extension SwipeAction where Label == SwiftUI.Label<Text, Image> {
  public init(
    _ title: LocalizedStringKey,
    icon: Image,
    variant: SwipeActionVariant = .default,
    fullSwipe: Bool = false,
    action: @escaping () -> Void
  ) {
    self.init(title, variant: variant, fullSwipe: fullSwipe, action: action) {
      SwiftUI.Label { Text(title) } icon: { icon }
    }
  }
}

extension SwipeAction where Label == Text {
  public init(
    _ title: LocalizedStringKey,
    variant: SwipeActionVariant = .default,
    fullSwipe: Bool = false,
    action: @escaping () -> Void
  ) {
    self.init(title, variant: variant, fullSwipe: fullSwipe, action: action) { Text(title) }
  }
}

private struct SwipeActionLabelStyle: LabelStyle {
  func makeBody(configuration: Configuration) -> some View {
    VStack(spacing: 4) {
      configuration.icon.frame(width: 20, height: 20)
      configuration.title
    }
  }
}

private struct SwipeActionButtonStyle: ButtonStyle {
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .brightness(configuration.isPressed ? -0.08 : 0)
  }
}
```

- `swift/Components/Haptics.swift`: see [Haptics](https://ui.suiss.app/docs/components/haptics.md)

4. Add the files to your app target.

**Jetpack Compose**

1. Set `minSdk` to 24 or higher and add the dependencies:

```kotlin title="build.gradle.kts"
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.ui:ui")
```

2. Copy the theme files every view uses:

- `kotlin/theme/Theme.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/theme/Theme.kt)

- `kotlin/theme/Tokens.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/theme/Tokens.kt)

3. Copy the source and every file it uses:

```kt title="kotlin/interactions/SwipeActions.kt"
package com.esuiss.ui.interactions

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.AnchoredDraggableDefaults
import androidx.compose.foundation.gestures.AnchoredDraggableState
import androidx.compose.foundation.gestures.DraggableAnchors
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.anchoredDraggable
import androidx.compose.foundation.gestures.animateTo
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.snapTo
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.FormEasing
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.formReducedMotion
import com.esuiss.ui.components.rememberHaptics
import com.esuiss.ui.theme.Colors
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.roundToInt
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter

enum class SwipeActionsSide { Leading, Trailing }

enum class SwipeActionVariant { Default, Destructive, Archive, Neutral }

@Immutable
class SwipeAction(
    val label: String,
    val onClick: () -> Unit,
    val icon: ImageVector? = null,
    val variant: SwipeActionVariant = SwipeActionVariant.Default,
    val fullSwipe: Boolean = false,
)

internal enum class SwipeActionsValue { Closed, Leading, Trailing, LeadingFull, TrailingFull }

private val SwipeSpec = tween<Float>(300, easing = FormEasing)

@Stable
class SwipeActionsState internal constructor() {
    internal val anchored = AnchoredDraggableState(SwipeActionsValue.Closed)
    internal var scope: CoroutineScope? = null
    internal var reduced = false

    val openSide: SwipeActionsSide?
        get() = when (anchored.currentValue) {
            SwipeActionsValue.Leading, SwipeActionsValue.LeadingFull -> SwipeActionsSide.Leading
            SwipeActionsValue.Trailing, SwipeActionsValue.TrailingFull -> SwipeActionsSide.Trailing
            SwipeActionsValue.Closed -> null
        }

    suspend fun close() = moveTo(SwipeActionsValue.Closed)

    suspend fun open(side: SwipeActionsSide) =
        moveTo(if (side == SwipeActionsSide.Leading) SwipeActionsValue.Leading else SwipeActionsValue.Trailing)

    internal fun requestClose() {
        scope?.launch { close() }
    }

    private suspend fun moveTo(target: SwipeActionsValue) {
        if (anchored.anchors.size == 0) snapshotFlow { anchored.anchors.size }.first { it > 0 }
        if (!anchored.anchors.hasPositionFor(target)) return
        if (reduced) anchored.snapTo(target) else anchored.animateTo(target, SwipeSpec)
    }
}

@Composable
fun rememberSwipeActionsState(): SwipeActionsState = remember { SwipeActionsState() }

private object SwipeActionsRegistry {
    var open: SwipeActionsState? = null

    fun claim(state: SwipeActionsState) {
        val previous = open
        open = state
        if (previous != null && previous !== state) previous.requestClose()
    }

    fun release(state: SwipeActionsState) {
        if (open === state) open = null
    }
}

@Composable
fun SwipeActions(
    modifier: Modifier = Modifier,
    leading: List<SwipeAction> = emptyList(),
    trailing: List<SwipeAction> = emptyList(),
    state: SwipeActionsState = rememberSwipeActionsState(),
    enabled: Boolean = true,
    background: Color = EsuissTheme.colors.background,
    content: @Composable () -> Unit,
) {
    val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl
    val reduced = formReducedMotion()
    val scope = rememberCoroutineScope()
    SideEffect {
        state.scope = scope
        state.reduced = reduced
    }
    DisposableEffect(state) {
        onDispose { SwipeActionsRegistry.release(state) }
    }
    var rowWidth by remember { mutableIntStateOf(0) }
    var leadingWidth by remember { mutableIntStateOf(0) }
    var trailingWidth by remember { mutableIntStateOf(0) }
    var removing by remember { mutableStateOf(false) }
    val removal = remember { Animatable(1f) }
    val leadingFull = leading.any { it.fullSwipe }
    val trailingFull = trailing.any { it.fullSwipe }
    val currentLeading by rememberUpdatedState(leading)
    val currentTrailing by rememberUpdatedState(trailing)
    val hasLeading = leading.isNotEmpty()
    val hasTrailing = trailing.isNotEmpty()

    LaunchedEffect(rowWidth, leadingWidth, trailingWidth, hasLeading, hasTrailing, leadingFull, trailingFull) {
        if (rowWidth == 0) return@LaunchedEffect
        val anchors = DraggableAnchors {
            SwipeActionsValue.Closed at 0f
            if (hasLeading && leadingWidth > 0) {
                SwipeActionsValue.Leading at leadingWidth.toFloat()
                if (leadingFull && rowWidth > leadingWidth) SwipeActionsValue.LeadingFull at rowWidth.toFloat()
            }
            if (hasTrailing && trailingWidth > 0) {
                SwipeActionsValue.Trailing at -trailingWidth.toFloat()
                if (trailingFull && rowWidth > trailingWidth) SwipeActionsValue.TrailingFull at -rowWidth.toFloat()
            }
        }
        val target = state.anchored.targetValue
        state.anchored.updateAnchors(anchors, if (anchors.hasPositionFor(target)) target else SwipeActionsValue.Closed)
    }

    LaunchedEffect(state) {
        snapshotFlow { state.anchored.settledValue }.collect { value ->
            when (value) {
                SwipeActionsValue.Closed -> SwipeActionsRegistry.release(state)
                SwipeActionsValue.Leading, SwipeActionsValue.Trailing -> SwipeActionsRegistry.claim(state)
                SwipeActionsValue.LeadingFull, SwipeActionsValue.TrailingFull -> {
                    SwipeActionsRegistry.release(state)
                    val actions = if (value == SwipeActionsValue.LeadingFull) currentLeading else currentTrailing
                    val action = actions.firstOrNull { it.fullSwipe }
                    removing = true
                    if (!state.reduced) {
                        delay(180)
                        removal.animateTo(0f, tween(220, easing = FormEasing))
                    }
                    action?.onClick?.invoke()
                    delay(50)
                    state.anchored.snapTo(SwipeActionsValue.Closed)
                    removal.snapTo(1f)
                    removing = false
                }
            }
        }
    }

    val offsetState = remember(state) {
        derivedStateOf { state.anchored.offset.let { if (it.isNaN()) 0f else it } }
    }
    val fullSide by remember(state) {
        derivedStateOf {
            val anchors = state.anchored.anchors
            val offset = offsetState.value
            when {
                offset > 0f && anchors.hasPositionFor(SwipeActionsValue.LeadingFull) -> {
                    val open = anchors.positionOf(SwipeActionsValue.Leading)
                    val full = anchors.positionOf(SwipeActionsValue.LeadingFull)
                    if (offset > (open + full) / 2f) SwipeActionsSide.Leading else null
                }
                offset < 0f && anchors.hasPositionFor(SwipeActionsValue.TrailingFull) -> {
                    val open = anchors.positionOf(SwipeActionsValue.Trailing)
                    val full = anchors.positionOf(SwipeActionsValue.TrailingFull)
                    if (offset < (open + full) / 2f) SwipeActionsSide.Trailing else null
                }
                else -> null
            }
        }
    }
    val currentHaptics by rememberUpdatedState(rememberHaptics())
    LaunchedEffect(state) {
        snapshotFlow { fullSide }
            .drop(1)
            .filter { it != null }
            .collect { currentHaptics.perform(HapticFeedbackType.GestureThresholdActivate) }
    }
    val fullProgress = animateFloatAsState(
        targetValue = if (fullSide != null) 1f else 0f,
        animationSpec = if (reduced) tween(0) else tween(200, easing = FormEasing),
        label = "full",
    )
    val revealedSide by remember(state) {
        derivedStateOf {
            val offset = offsetState.value
            when {
                offset > 0.5f -> SwipeActionsSide.Leading
                offset < -0.5f -> SwipeActionsSide.Trailing
                else -> null
            }
        }
    }
    val isOpen = revealedSide != null
    val accessibilityActions = remember(leading, trailing) {
        (leading + trailing).map { action ->
            CustomAccessibilityAction(action.label) {
                action.onClick()
                true
            }
        }
    }

    Box(
        modifier = modifier
            .fillMaxWidth()
            .onSizeChanged { rowWidth = it.width }
            .layout { measurable, constraints ->
                val placeable = measurable.measure(constraints)
                val height = (placeable.height * removal.value).roundToInt()
                layout(placeable.width, height) { placeable.place(0, 0) }
            }
            .clipToBounds()
            .anchoredDraggable(
                state = state.anchored,
                orientation = Orientation.Horizontal,
                enabled = enabled && !removing,
                reverseDirection = rtl,
                flingBehavior = AnchoredDraggableDefaults.flingBehavior(
                    state = state.anchored,
                    positionalThreshold = { it * 0.5f },
                    animationSpec = SwipeSpec,
                ),
            ),
    ) {
        if (hasLeading) {
            SwipeActionsStrip(
                actions = leading,
                side = SwipeActionsSide.Leading,
                offset = offsetState,
                fullProgress = fullProgress,
                fullActive = fullSide == SwipeActionsSide.Leading,
                visible = revealedSide == SwipeActionsSide.Leading,
                onNaturalWidth = { leadingWidth = it },
                onAction = { state.requestClose() },
                modifier = Modifier.matchParentSize(),
            )
        }
        if (hasTrailing) {
            SwipeActionsStrip(
                actions = trailing,
                side = SwipeActionsSide.Trailing,
                offset = offsetState,
                fullProgress = fullProgress,
                fullActive = fullSide == SwipeActionsSide.Trailing,
                visible = revealedSide == SwipeActionsSide.Trailing,
                onNaturalWidth = { trailingWidth = it },
                onAction = { state.requestClose() },
                modifier = Modifier.matchParentSize(),
            )
        }
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .offset { IntOffset(offsetState.value.roundToInt(), 0) }
                .background(background)
                .pointerInput(Unit) {}
                .semantics(mergeDescendants = true) {
                    if (enabled) customActions = accessibilityActions
                },
        ) {
            content()
            if (isOpen) {
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .clearAndSetSemantics {}
                        .pointerInput(state) {
                            detectTapGestures { state.requestClose() }
                        },
                )
            }
        }
    }
}

internal fun swipeActionColor(variant: SwipeActionVariant, colors: Colors): Color = when (variant) {
    SwipeActionVariant.Default -> colors.primary
    SwipeActionVariant.Destructive -> if (colors.isDark) lerp(colors.destructive, colors.background, 0.3f) else colors.destructive
    SwipeActionVariant.Archive -> if (colors.isDark) lerp(Palette.purple500, colors.background, 0.3f) else lerp(Palette.purple500, colors.foreground, 0.15f)
    SwipeActionVariant.Neutral -> if (colors.isDark) lerp(Palette.zinc500, colors.background, 0.4f) else lerp(Palette.zinc500, colors.foreground, 0.35f)
}

@Composable
private fun SwipeActionsStrip(
    actions: List<SwipeAction>,
    side: SwipeActionsSide,
    offset: State<Float>,
    fullProgress: State<Float>,
    fullActive: Boolean,
    visible: Boolean,
    onNaturalWidth: (Int) -> Unit,
    onAction: () -> Unit,
    modifier: Modifier,
) {
    val fullIndex = actions.indexOfFirst { it.fullSwipe }
    Layout(
        modifier = modifier.then(if (visible) Modifier else Modifier.clearAndSetSemantics {}),
        content = {
            actions.forEachIndexed { index, action ->
                SwipeActionButton(action, hidden = fullActive && index != fullIndex, onAction = onAction)
            }
        },
    ) { measurables, constraints ->
        val height = constraints.maxHeight
        val width = constraints.maxWidth
        val minimum = 72.dp.roundToPx()
        val natural = measurables.sumOf { maxOf(minimum, it.maxIntrinsicWidth(height)) }
        onNaturalWidth(natural)
        val raw = offset.value
        val revealed = (if (side == SwipeActionsSide.Leading) raw else -raw).coerceAtLeast(0f)
        val count = measurables.size
        val base = maxOf(minimum.toFloat(), revealed / count)
        val progress = if (fullIndex >= 0) fullProgress.value else 0f
        val widths = IntArray(count) { index ->
            val target = when {
                fullIndex < 0 -> base
                index == fullIndex -> base + (revealed - base) * progress
                else -> base * (1f - progress)
            }
            if (revealed <= 0f) 0 else target.roundToInt().coerceAtLeast(0)
        }
        val placeables = measurables.mapIndexed { index, measurable ->
            measurable.measure(Constraints.fixed(widths[index], height))
        }
        layout(width, height) {
            if (side == SwipeActionsSide.Trailing) {
                var x = width - revealed.roundToInt()
                placeables.forEachIndexed { index, placeable ->
                    val alpha = if (fullIndex >= 0 && index != fullIndex) 1f - progress else 1f
                    placeable.placeRelativeWithLayer(x, 0) { this.alpha = alpha }
                    x += placeable.width
                }
            } else {
                var x = revealed.roundToInt()
                placeables.forEachIndexed { index, placeable ->
                    x -= placeable.width
                    val alpha = if (fullIndex >= 0 && index != fullIndex) 1f - progress else 1f
                    placeable.placeRelativeWithLayer(x, 0) { this.alpha = alpha }
                }
            }
        }
    }
}

@Composable
private fun SwipeActionButton(action: SwipeAction, hidden: Boolean, onAction: () -> Unit) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    val base = swipeActionColor(action.variant, colors)
    Column(
        modifier = Modifier
            .alpha(if (pressed) 0.8f else 1f)
            .background(base)
            .then(if (hidden) Modifier.clearAndSetSemantics {} else Modifier)
            .clickable(
                interactionSource = interaction,
                indication = null,
                role = Role.Button,
                onClick = {
                    action.onClick()
                    onAction()
                },
            )
            .padding(horizontal = 12.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically),
    ) {
        if (action.icon != null) Icon(action.icon, contentDescription = null, size = 20.dp, tint = colors.primaryForeground)
        BasicText(
            action.label,
            style = Typography.xs.copy(color = colors.primaryForeground, fontWeight = FontWeight.Medium, textAlign = TextAlign.Center),
            maxLines = 2,
        )
    }
}
```

- `kotlin/components/Content.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/components/Content.kt)

- `kotlin/components/FormSupport.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/components/FormSupport.kt)

- `kotlin/components/Haptics.kt`: see [Haptics](https://ui.suiss.app/docs/components/haptics.md)

- `kotlin/components/Icon.kt`: see [Icon](https://ui.suiss.app/docs/components/icon.md)

4. Update the `com.esuiss.ui` package names to match your project.

## Usage

```tsx
import { SwipeActions, SwipeActionsContent, SwipeActionsActions, SwipeAction } from "@/components/interactions/swipe-actions"
```

```tsx
<View>
  <Inbox />
</View>
```

Put the row in `SwipeActionsContent`, and the buttons in one `SwipeActionsActions` per side, with `side` set to `leading` or `trailing` (the default). Leading actions are on the left in left-to-right layouts and on the right in right-to-left layouts.

Pressing an action runs `onPress` and closes the row. For a full-swipe action, `onPress` runs after the row collapses, so remove the item from your data there. `useSwipeActions` returns `close` for closing the row from inside it. `swipeActionVariants` is also exported.

## API Reference

### SwipeActions

The root that handles the swipe gesture.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onOpenChange` | `(side: SwipeActionsSide \| null) => void` | - | Called with `leading`, `trailing` or `null` when the row opens or closes. |

Also accepts the props of `ViewProps`.

### SwipeActionsContent

The row content that slides.

Also accepts the props of `ViewProps`.

### SwipeActionsActions

The group of actions for one side.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `side` | `SwipeActionsSide` | - | `leading` or `trailing`. Defaults to `trailing`. |
| `children` | `React.ReactNode` | - |  |

Also accepts the props of `ViewProps`.

### SwipeAction

One action button.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `"default" \| "destructive" \| "archive" \| "neutral"` | `"default"` | Background color of the action. |
| `fullSwipe` | `boolean` | `false` | Runs the action when the row is swiped all the way. |
| `onPress` | `() => void` | - | Called when the action is pressed or fully swiped. |

Also accepts the props of `SwipeActionProps`.

## Accessibility

- Every action is offered as an accessibility action on `SwipeActionsContent`, labelled by its `accessibilityLabel` or text, so screen reader users can run it without swiping.
- Hidden actions are removed from the accessibility tree until their side is open.
- The row has the `group` role and each action the `button` role.

## Notes

- The full-swipe haptic plays only if the app provides an adapter through `HapticsProvider`.
- Action colors use `bg-primary`, `bg-destructive`, `bg-purple-500` and `bg-zinc-500` with `text-primary-foreground` labels and icons; the content uses `bg-background`.

