# Swipe Actions

Swipe a list row sideways to reveal action buttons, with full swipe to run the main action.

Swipe Actions is an open-source mobile interaction from suiss/uim for React Native and Expo, with SwiftUI and Jetpack Compose versions built from the same design tokens. The @esuiss/uim CLI copies its source into your project, so you own the code.

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

![Preview](https://uim.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-surface-secondary">
              <Item onPress={() => {}}>
                <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: .surfaceSecondary) {
          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.surfaceSecondary,
                ) {
                    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

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

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

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

The CLI also adds what it builds on: [Icon](/docs/components/icon), [Text](/docs/components/text).

### Manual

**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](/docs/components/icon), [Text](/docs/components/text), and the primitives `components/primitives/haptics.tsx`.

3. 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 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,
  ...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 [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
    return () => {
      mountedRef.current = false
      openRows.delete(close)
    }
  }, [close])

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    const value = next
      ? side
      : fullRef.current === side
        ? null
        : fullRef.current
    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
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    setTimeout(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      setTimeout(() => {
        action.props.onPress?.()
        setTimeout(() => {
          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-(\d+)$/.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
          }
        }}
        {...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-surface", 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-accent",
        destructive: "bg-danger",
        archive: "bg-purple",
        neutral: "bg-gray",
      },
    },
    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-on-accent">
      <IconClassContext.Provider value="size-5 text-on-accent">
        <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,
}
```

4. 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](/docs/components/icon), [Text](/docs/components/text), and the primitives `components/primitives/haptics.tsx`.

3. 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 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,
  ...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 [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
    return () => {
      mountedRef.current = false
      openRows.delete(close)
    }
  }, [close])

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    const value = next
      ? side
      : fullRef.current === side
        ? null
        : fullRef.current
    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
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    setTimeout(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      setTimeout(() => {
        action.props.onPress?.()
        setTimeout(() => {
          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-(\d+)$/.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
          }
        }}
        {...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-surface", 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-accent",
        destructive: "bg-danger",
        archive: "bg-purple",
        neutral: "bg-gray",
      },
    },
    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-on-accent">
      <IconClassContext.Provider value="size-5 text-on-accent">
        <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,
}
```

4. 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](/docs/components/icon), [Text](/docs/components/text), and the primitives `components/primitives/haptics.tsx`.

3. 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, 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>()

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,
  ...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 [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
    return () => {
      mountedRef.current = false
      openRows.delete(close)
    }
  }, [close])

  const setFullSide = (side: SwipeActionsSide) => (next: boolean) => {
    if (committingRef.current) return
    if (next && fullRef.current !== side) haptics.impact("medium")
    const value = next
      ? side
      : fullRef.current === side
        ? null
        : fullRef.current
    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
    const sign = side === leftSide ? 1 : -1
    offset.value = withTiming(sign * rowWidth.value, {
      duration: 180,
      easing: EASING,
    })
    setTimeout(() => {
      collapse.value = rowHeight.value
      collapse.value = withTiming(0, { duration: 220, easing: EASING })
      setTimeout(() => {
        action.props.onPress?.()
        setTimeout(() => {
          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-(\d+)$/.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
          }
        }}
        {...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.surface },
        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.danger
    case "archive":
      return colors.purple
    case "neutral":
      return colors.gray
    default:
      return colors.accent
  }
}

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.onAccent,
      }}
    >
      <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,
}
```

4. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Copy the theme files every view uses:

```swift title="swift/Theme/Theme.swift"
import SwiftUI
import UIKit

struct RGBA: Sendable {
  let red: CGFloat
  let green: CGFloat
  let blue: CGFloat
  let alpha: CGFloat

  init(_ hex: UInt32, _ alpha: CGFloat = 1) {
    red = CGFloat((hex >> 16) & 0xFF) / 255
    green = CGFloat((hex >> 8) & 0xFF) / 255
    blue = CGFloat(hex & 0xFF) / 255
    self.alpha = alpha
  }

  var uiColor: UIColor {
    UIColor(red: red, green: green, blue: blue, alpha: alpha)
  }
}

extension Color {
  static func adaptive(light: RGBA, dark: RGBA) -> Color {
    let lightColor = light.uiColor
    let darkColor = dark.uiColor
    return Color(uiColor: UIColor { traits in
      traits.userInterfaceStyle == .dark ? darkColor : lightColor
    })
  }
}

public struct TextStyle: Sendable, Hashable {
  public let size: CGFloat
  public let lineHeight: CGFloat
  public let letterSpacing: CGFloat

  public init(size: CGFloat, lineHeight: CGFloat, letterSpacing: CGFloat) {
    self.size = size
    self.lineHeight = lineHeight
    self.letterSpacing = letterSpacing
  }

  public func font(weight: Font.Weight = .regular) -> Font {
    .system(size: size, weight: weight)
  }

  public var lineSpacing: CGFloat {
    max(0, lineHeight - UIFont.systemFont(ofSize: size).lineHeight)
  }
}

extension Hashable where Self == Font {
  public static func textStyle(_ style: TextStyle, weight: Font.Weight = .regular) -> Font {
    style.font(weight: weight)
  }
}

private struct TextStyleModifier: ViewModifier {
  let style: TextStyle
  let weight: Font.Weight

  func body(content: Content) -> some View {
    content
      .font(style.font(weight: weight))
      .tracking(style.letterSpacing)
      .lineSpacing(style.lineSpacing)
      .padding(.vertical, style.lineSpacing / 2)
  }
}

extension View {
  public func textStyle(_ style: TextStyle, weight: Font.Weight = .regular) -> some View {
    modifier(TextStyleModifier(style: style, weight: weight))
  }
}

public struct Shadow: Sendable, Hashable {
  public let color: Color
  public let radius: CGFloat
  public let x: CGFloat
  public let y: CGFloat

  public init(color: Color, radius: CGFloat, x: CGFloat = 0, y: CGFloat = 0) {
    self.color = color
    self.radius = radius
    self.x = x
    self.y = y
  }
}

extension View {
  public func shadow(_ shadow: Shadow) -> some View {
    self.shadow(color: shadow.color, radius: shadow.radius, x: shadow.x, y: shadow.y)
  }
}
```

```swift title="swift/Theme/Tokens.swift"
import SwiftUI

extension Color {
  public static let surface = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let surfaceSecondary = Color.adaptive(light: .init(0xF5F5F7), dark: .init(0x161617))
  public static let surfaceTertiary = Color.adaptive(light: .init(0xE8E8ED), dark: .init(0x2C2C2E))
  public static let surfaceRaised = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x1D1D1F))
  public static let label = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let labelSecondary = Color.adaptive(light: .init(0x6E6E73), dark: .init(0xA1A1A6))
  public static let labelTertiary = Color.adaptive(light: .init(0x86868B), dark: .init(0x86868B))
  public static let labelQuaternary = Color.adaptive(light: .init(0xD2D2D7), dark: .init(0x424245))
  public static let control = Color.adaptive(light: .init(0x000000, 0.04), dark: .init(0xFFFFFF, 0.1))
  public static let controlPressed = Color.adaptive(light: .init(0x000000, 0.12), dark: .init(0xFFFFFF, 0.22))
  public static let controlSelected = Color.adaptive(light: .init(0x1D1D1F), dark: .init(0xF5F5F7))
  public static let controlDisabled = Color.adaptive(light: .init(0x000000, 0.03), dark: .init(0xFFFFFF, 0.05))
  public static let onControlSelected = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0x000000))
  public static let itemPressed = Color.adaptive(light: .init(0x000000, 0.08), dark: .init(0xFFFFFF, 0.12))
  public static let itemSelected = Color.adaptive(light: .init(0x000000, 0.06), dark: .init(0xFFFFFF, 0.1))
  public static let separator = Color.adaptive(light: .init(0xD2D2D7), dark: .init(0x424245))
  public static let separatorStrong = Color.adaptive(light: .init(0x86868B), dark: .init(0x6E6E73))
  public static let accent = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let accentPressed = Color.adaptive(light: .init(0x005BB8), dark: .init(0x004D9E))
  public static let accentSelected = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let accentDisabled = Color.adaptive(light: .init(0x0071E3, 0.4), dark: .init(0x0071E3, 0.4))
  public static let onAccent = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let accentSurface = Color.adaptive(light: .init(0x0071E3, 0.09), dark: .init(0x0071E3, 0.18))
  public static let accentSurfacePressed = Color.adaptive(light: .init(0x0071E3, 0.18), dark: .init(0x0071E3, 0.3))
  public static let link = Color.adaptive(light: .init(0x0066CC), dark: .init(0x2997FF))
  public static let focus = Color.adaptive(light: .init(0x0071E3), dark: .init(0x0071E3))
  public static let scrim = Color.adaptive(light: .init(0x000000, 0.48), dark: .init(0x000000, 0.48))
  public static let media = Color.adaptive(light: .init(0x000000), dark: .init(0x000000))
  public static let onMedia = Color.adaptive(light: .init(0xFFFFFF), dark: .init(0xFFFFFF))
  public static let danger = Color.adaptive(light: .init(0xD0000A), dark: .init(0xFF5447))
  public static let dangerSurface = Color.adaptive(light: .init(0xD70015, 0.08), dark: .init(0xFF453A, 0.2))
  public static let dangerSurfacePressed = Color.adaptive(light: .init(0xD70015, 0.16), dark: .init(0xFF453A, 0.36))
  public static let success = Color.adaptive(light: .init(0x008009), dark: .init(0x30D158))
  public static let successSurface = Color.adaptive(light: .init(0xEFFAF1), dark: .init(0x30D158, 0.16))
  public static let warning = Color.adaptive(light: .init(0xB64400), dark: .init(0xFF9F0A))
  public static let warningSurface = Color.adaptive(light: .init(0xFFF5EA), dark: .init(0xFF9F0A, 0.16))
}

public enum Radius {
  public static let xs: CGFloat = 3
  public static let sm: CGFloat = 5
  public static let md: CGFloat = 8
  public static let lg: CGFloat = 10
  public static let xl: CGFloat = 12
  public static let xl2: CGFloat = 18
  public static let xl3: CGFloat = 28
  public static let full: CGFloat = 9999
}

extension TextStyle {
  public static let xs3 = TextStyle(size: 11, lineHeight: 13, letterSpacing: 0.066)
  public static let xs2 = TextStyle(size: 12, lineHeight: 16, letterSpacing: 0)
  public static let xs = TextStyle(size: 13, lineHeight: 18, letterSpacing: -0.078)
  public static let sm = TextStyle(size: 15, lineHeight: 20, letterSpacing: -0.24)
  public static let md = TextStyle(size: 16, lineHeight: 21, letterSpacing: -0.32)
  public static let base = TextStyle(size: 17, lineHeight: 22, letterSpacing: -0.442)
  public static let lg = TextStyle(size: 20, lineHeight: 25, letterSpacing: -0.46)
  public static let xl = TextStyle(size: 22, lineHeight: 28, letterSpacing: -0.264)
  public static let xl2 = TextStyle(size: 28, lineHeight: 34, letterSpacing: 0.392)
  public static let xl3 = TextStyle(size: 34, lineHeight: 41, letterSpacing: 0.408)

  public static let allCases: [TextStyle] = [.xs3, .xs2, .xs, .sm, .md, .base, .lg, .xl, .xl2, .xl3]
}

extension Shadow {
  public static let md = Shadow(color: .black.opacity(0.08), radius: 6, x: 2, y: 4)
  public static let lg = Shadow(color: .black.opacity(0.12), radius: 12, y: 4)
}
```

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: .accent
    case .destructive: .adaptive(light: .init(0xD0000A), dark: .init(0xB33B32))
    case .archive: .adaptive(light: .init(0x994AC1), dark: .init(0x863FA9))
    case .neutral: .adaptive(light: .init(0x66666A), dark: .init(0x555558))
    }
  }
}

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 = .surface,
    @ViewBuilder content: () -> Content,
    @ViewBuilder leading: () -> Leading,
    @ViewBuilder trailing: () -> Trailing
  ) {
    self.init(background: background, revealed: 0, content: content, leading: leading, trailing: trailing)
  }

  init(
    background: Color = .surface,
    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 = .surface,
    @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 = .surface,
    @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())
          .font(TextStyle.xs.font(weight: .medium))
          .tracking(TextStyle.xs.letterSpacing)
          .multilineTextAlignment(.center)
          .foregroundStyle(Color.onAccent)
          .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 title="swift/Components/Haptics.swift"
import SwiftUI

extension EnvironmentValues {
  @Entry public var hapticsEnabled = true
}

extension View {
  public func haptics(_ enabled: Bool) -> some View {
    environment(\.hapticsEnabled, enabled)
  }

  func hapticFeedback<Trigger: Equatable>(_ feedback: SensoryFeedback, trigger: Trigger) -> some View {
    modifier(HapticFeedbackModifier(feedback: feedback, trigger: trigger) { _, _ in true })
  }

  func hapticFeedback<Trigger: Equatable>(
    _ feedback: SensoryFeedback,
    trigger: Trigger,
    condition: @escaping (Trigger, Trigger) -> Bool
  ) -> some View {
    modifier(HapticFeedbackModifier(feedback: feedback, trigger: trigger, condition: condition))
  }
}

private struct HapticFeedbackModifier<Trigger: Equatable>: ViewModifier {
  let feedback: SensoryFeedback
  let trigger: Trigger
  let condition: (Trigger, Trigger) -> Bool

  @Environment(\.hapticsEnabled) private var enabled

  func body(content: Content) -> some View {
    let enabled = enabled
    let condition = condition
    content.sensoryFeedback(feedback, trigger: trigger) { old, new in
      enabled && condition(old, new)
    }
  }
}

enum HapticMoments {
  static func step(_ value: Double, bounds: ClosedRange<Double>, step: Double?) -> Int? {
    guard let step, step > 0 else { return nil }
    return Int(((value - bounds.lowerBound) / step).rounded())
  }

  static func lifted<Value: Equatable>(_ old: Value?, _ new: Value?) -> Bool {
    new != nil && old != new
  }

  static func crossed<Value: Equatable>(_ old: Value?, _ new: Value?) -> Bool {
    old == nil && new != nil
  }

  static func moved(_ old: Int?, _ new: Int?) -> Bool {
    guard let old, let new else { return false }
    return old != new
  }
}

struct HapticButton<Style: ButtonStyle>: View {
  let feedback: SensoryFeedback
  let action: () -> Bool
  let style: Style

  @State private var count = 0

  init(_ feedback: SensoryFeedback = .selection, style: Style, action: @escaping () -> Bool) {
    self.feedback = feedback
    self.style = style
    self.action = action
  }

  var body: some View {
    Button {
      if action() { count += 1 }
    } label: {
      EmptyView()
    }
    .buttonStyle(style)
    .hapticFeedback(feedback, trigger: count)
  }
}
```

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:

```kt title="kotlin/theme/Theme.kt"
package com.esuiss.ui.theme

import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.dropShadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.shadow.Shadow as DropShadow
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.em
import androidx.compose.ui.unit.sp

internal fun textStyle(size: Double, lineHeight: Double, letterSpacing: Double) = TextStyle(
    fontSize = size.sp,
    lineHeight = lineHeight.sp,
    letterSpacing = letterSpacing.em,
    lineHeightStyle = LineHeightStyle(
        alignment = LineHeightStyle.Alignment.Center,
        trim = LineHeightStyle.Trim.None,
    ),
)

@Immutable
data class Shadow(
    val offsetX: Dp,
    val offsetY: Dp,
    val blur: Dp,
    val color: Color,
)

fun Modifier.shadow(shadow: Shadow, shape: Shape): Modifier = dropShadow(
    shape,
    DropShadow(
        radius = shadow.blur,
        color = shadow.color,
        offset = DpOffset(shadow.offsetX, shadow.offsetY),
    ),
)

val LocalColors = staticCompositionLocalOf { LightColors }

object EsuissTheme {
    val colors: Colors
        @Composable get() = LocalColors.current

    val typography: Typography
        get() = Typography

    val radius: Radius
        get() = Radius

    val shadows: Shadows
        get() = Shadows
}

@Composable
fun EsuissTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit,
) {
    CompositionLocalProvider(
        LocalColors provides if (darkTheme) DarkColors else LightColors,
        content = content,
    )
}
```

```kt title="kotlin/theme/Tokens.kt"
package com.esuiss.ui.theme

import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Immutable
data class Colors(
    val surface: Color,
    val surfaceSecondary: Color,
    val surfaceTertiary: Color,
    val surfaceRaised: Color,
    val label: Color,
    val labelSecondary: Color,
    val labelTertiary: Color,
    val labelQuaternary: Color,
    val control: Color,
    val controlPressed: Color,
    val controlSelected: Color,
    val controlDisabled: Color,
    val onControlSelected: Color,
    val itemPressed: Color,
    val itemSelected: Color,
    val separator: Color,
    val separatorStrong: Color,
    val accent: Color,
    val accentPressed: Color,
    val accentSelected: Color,
    val accentDisabled: Color,
    val onAccent: Color,
    val accentSurface: Color,
    val accentSurfacePressed: Color,
    val link: Color,
    val focus: Color,
    val scrim: Color,
    val media: Color,
    val onMedia: Color,
    val danger: Color,
    val dangerSurface: Color,
    val dangerSurfacePressed: Color,
    val success: Color,
    val successSurface: Color,
    val warning: Color,
    val warningSurface: Color,
    val blue: Color,
    val green: Color,
    val orange: Color,
    val red: Color,
    val yellow: Color,
    val purple: Color,
    val pink: Color,
    val indigo: Color,
    val teal: Color,
    val mint: Color,
    val cyan: Color,
    val brown: Color,
    val gray: Color,
    val isDark: Boolean,
)

val LightColors = Colors(
    surface = Color(0xFFFFFFFF),
    surfaceSecondary = Color(0xFFF5F5F7),
    surfaceTertiary = Color(0xFFE8E8ED),
    surfaceRaised = Color(0xFFFFFFFF),
    label = Color(0xFF1D1D1F),
    labelSecondary = Color(0xFF6E6E73),
    labelTertiary = Color(0xFF86868B),
    labelQuaternary = Color(0xFFD2D2D7),
    control = Color(0xFF000000).copy(alpha = 0.04f),
    controlPressed = Color(0xFF000000).copy(alpha = 0.12f),
    controlSelected = Color(0xFF1D1D1F),
    controlDisabled = Color(0xFF000000).copy(alpha = 0.03f),
    onControlSelected = Color(0xFFFFFFFF),
    itemPressed = Color(0xFF000000).copy(alpha = 0.08f),
    itemSelected = Color(0xFF000000).copy(alpha = 0.06f),
    separator = Color(0xFFD2D2D7),
    separatorStrong = Color(0xFF86868B),
    accent = Color(0xFF0071E3),
    accentPressed = Color(0xFF005BB8),
    accentSelected = Color(0xFF0071E3),
    accentDisabled = Color(0xFF0071E3).copy(alpha = 0.4f),
    onAccent = Color(0xFFFFFFFF),
    accentSurface = Color(0xFF0071E3).copy(alpha = 0.09f),
    accentSurfacePressed = Color(0xFF0071E3).copy(alpha = 0.18f),
    link = Color(0xFF0066CC),
    focus = Color(0xFF0071E3),
    scrim = Color(0xFF000000).copy(alpha = 0.48f),
    media = Color(0xFF000000),
    onMedia = Color(0xFFFFFFFF),
    danger = Color(0xFFD0000A),
    dangerSurface = Color(0xFFD70015).copy(alpha = 0.08f),
    dangerSurfacePressed = Color(0xFFD70015).copy(alpha = 0.16f),
    success = Color(0xFF008009),
    successSurface = Color(0xFFEFFAF1),
    warning = Color(0xFFB64400),
    warningSurface = Color(0xFFFFF5EA),
    blue = Color(0xFF007AFF),
    green = Color(0xFF34C759),
    orange = Color(0xFFFF9500),
    red = Color(0xFFFF3B30),
    yellow = Color(0xFFFFCC00),
    purple = Color(0xFFAF52DE),
    pink = Color(0xFFFF2D55),
    indigo = Color(0xFF5856D6),
    teal = Color(0xFF30B0C7),
    mint = Color(0xFF00C7BE),
    cyan = Color(0xFF32ADE6),
    brown = Color(0xFFA2845E),
    gray = Color(0xFF8E8E93),
    isDark = false,
)

val DarkColors = Colors(
    surface = Color(0xFF000000),
    surfaceSecondary = Color(0xFF161617),
    surfaceTertiary = Color(0xFF2C2C2E),
    surfaceRaised = Color(0xFF1D1D1F),
    label = Color(0xFFF5F5F7),
    labelSecondary = Color(0xFFA1A1A6),
    labelTertiary = Color(0xFF86868B),
    labelQuaternary = Color(0xFF424245),
    control = Color(0xFFFFFFFF).copy(alpha = 0.1f),
    controlPressed = Color(0xFFFFFFFF).copy(alpha = 0.22f),
    controlSelected = Color(0xFFF5F5F7),
    controlDisabled = Color(0xFFFFFFFF).copy(alpha = 0.05f),
    onControlSelected = Color(0xFF000000),
    itemPressed = Color(0xFFFFFFFF).copy(alpha = 0.12f),
    itemSelected = Color(0xFFFFFFFF).copy(alpha = 0.1f),
    separator = Color(0xFF424245),
    separatorStrong = Color(0xFF6E6E73),
    accent = Color(0xFF0071E3),
    accentPressed = Color(0xFF004D9E),
    accentSelected = Color(0xFF0071E3),
    accentDisabled = Color(0xFF0071E3).copy(alpha = 0.4f),
    onAccent = Color(0xFFFFFFFF),
    accentSurface = Color(0xFF0071E3).copy(alpha = 0.18f),
    accentSurfacePressed = Color(0xFF0071E3).copy(alpha = 0.3f),
    link = Color(0xFF2997FF),
    focus = Color(0xFF0071E3),
    scrim = Color(0xFF000000).copy(alpha = 0.48f),
    media = Color(0xFF000000),
    onMedia = Color(0xFFFFFFFF),
    danger = Color(0xFFFF5447),
    dangerSurface = Color(0xFFFF453A).copy(alpha = 0.2f),
    dangerSurfacePressed = Color(0xFFFF453A).copy(alpha = 0.36f),
    success = Color(0xFF30D158),
    successSurface = Color(0xFF30D158).copy(alpha = 0.16f),
    warning = Color(0xFFFF9F0A),
    warningSurface = Color(0xFFFF9F0A).copy(alpha = 0.16f),
    blue = Color(0xFF0A84FF),
    green = Color(0xFF30D158),
    orange = Color(0xFFFF9F0A),
    red = Color(0xFFFF453A),
    yellow = Color(0xFFFFD60A),
    purple = Color(0xFFBF5AF2),
    pink = Color(0xFFFF375F),
    indigo = Color(0xFF5E5CE6),
    teal = Color(0xFF40C8E0),
    mint = Color(0xFF66D4CF),
    cyan = Color(0xFF64D2FF),
    brown = Color(0xFFAC8E68),
    gray = Color(0xFF8E8E93),
    isDark = true,
)

object Radius {
    val xs = 3.dp
    val sm = 5.dp
    val md = 8.dp
    val lg = 10.dp
    val xl = 12.dp
    val xl2 = 18.dp
    val xl3 = 28.dp
    val full = 9999.dp
}

object Typography {
    val xs3 = textStyle(11.0, 13.0, 0.006)
    val xs2 = textStyle(12.0, 16.0, 0.0)
    val xs = textStyle(13.0, 18.0, -0.006)
    val sm = textStyle(15.0, 20.0, -0.016)
    val md = textStyle(16.0, 21.0, -0.02)
    val base = textStyle(17.0, 22.0, -0.026)
    val lg = textStyle(20.0, 25.0, -0.023)
    val xl = textStyle(22.0, 28.0, -0.012)
    val xl2 = textStyle(28.0, 34.0, 0.014)
    val xl3 = textStyle(34.0, 41.0, 0.012)

    val all = listOf(xs3, xs2, xs, sm, md, base, lg, xl, xl2, xl3)
}

object Shadows {
    val md = Shadow(2.dp, 4.dp, 12.dp, Color.Black.copy(alpha = 0.08f))
    val lg = Shadow(0.dp, 4.dp, 24.dp, Color.Black.copy(alpha = 0.12f))
}
```

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.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
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.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.surface,
    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.accent
    SwipeActionVariant.Destructive -> if (colors.isDark) lerp(colors.danger, colors.surface, 0.3f) else colors.danger
    SwipeActionVariant.Archive -> if (colors.isDark) lerp(colors.purple, colors.surface, 0.3f) else lerp(colors.purple, colors.label, 0.15f)
    SwipeActionVariant.Neutral -> if (colors.isDark) lerp(colors.gray, colors.surface, 0.4f) else lerp(colors.gray, colors.label, 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)
    val fill = if (pressed) Color.Black.copy(alpha = 0.12f).compositeOver(base) else base
    Column(
        modifier = Modifier
            .background(fill)
            .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.onAccent)
        BasicText(
            action.label,
            style = Typography.xs.copy(color = colors.onAccent, fontWeight = FontWeight.Medium, textAlign = TextAlign.Center),
            maxLines = 2,
        )
    }
}
```

```kt title="kotlin/components/Content.kt"
package com.esuiss.ui.components

import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

val LocalContentStyle = compositionLocalOf { TextStyle.Default }

val LocalContentColor = compositionLocalOf { Color.Unspecified }

val LocalIconSize = compositionLocalOf { 20.dp }
```

```kt title="kotlin/components/FormSupport.kt"
package com.esuiss.ui.components

import android.provider.Settings
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.Colors
import com.esuiss.ui.theme.Shadow

internal val FormShadowXs = Shadow(0.dp, 1.dp, 2.dp, Color.Black.copy(alpha = 0.05f))

internal val FormShadowSm = Shadow(0.dp, 1.dp, 3.dp, Color.Black.copy(alpha = 0.1f))

internal val FormEasing = CubicBezierEasing(0.32f, 0.72f, 0f, 1f)

internal fun Modifier.formTouchTarget(): Modifier = layout { measurable, constraints ->
    val minimum = 48.dp.roundToPx()
    val placeable = measurable.measure(constraints)
    val width = constraints.constrainWidth(maxOf(placeable.width, minimum))
    val height = constraints.constrainHeight(maxOf(placeable.height, minimum))
    layout(width, height) {
        placeable.place((width - placeable.width) / 2, (height - placeable.height) / 2)
    }
}

@Composable
internal fun formReducedMotion(): Boolean {
    val context = LocalContext.current
    return remember(context) {
        Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) == 0f
    }
}

internal fun formSelectionColors(colors: Colors) = TextSelectionColors(
    handleColor = colors.accent,
    backgroundColor = colors.accent.copy(alpha = 0.3f),
)

internal fun Modifier.formInputSurface(
    colors: Colors,
    shape: Shape,
    focused: Boolean,
    invalid: Boolean,
    enabled: Boolean,
): Modifier {
    val background = when {
        !enabled -> colors.controlDisabled
        invalid -> colors.danger.copy(alpha = if (colors.isDark) 0.1f else 0.05f)
        else -> colors.control
    }
    val border = when {
        invalid -> colors.danger
        focused -> colors.focus
        else -> Color.Transparent
    }
    return clip(shape).background(background, shape).border(1.dp, border, shape)
}

@Composable
internal fun FormDividedStack(
    orientation: Orientation,
    dividerColor: Color,
    modifier: Modifier = Modifier,
    dividerInsetStart: Dp = 0.dp,
    content: @Composable () -> Unit,
) {
    val boundaries = remember { mutableStateOf(IntArray(0)) }
    val vertical = orientation == Orientation.Vertical
    Layout(
        content = content,
        modifier = modifier.drawWithContent {
            drawContent()
            val stroke = 1.dp.toPx()
            val inset = dividerInsetStart.toPx()
            boundaries.value.forEach { position ->
                if (vertical) {
                    val start = if (layoutDirection == LayoutDirection.Rtl) 0f else inset
                    drawRect(dividerColor, Offset(start, position.toFloat()), Size(size.width - inset, stroke))
                } else {
                    val x = if (layoutDirection == LayoutDirection.Rtl) size.width - position - stroke else position.toFloat()
                    drawRect(dividerColor, Offset(x, 0f), Size(stroke, size.height))
                }
            }
        },
    ) { measurables, constraints ->
        if (vertical) {
            val width = if (constraints.hasFixedWidth) {
                constraints.maxWidth
            } else {
                constraints.constrainWidth(measurables.maxOfOrNull { it.maxIntrinsicWidth(Constraints.Infinity) } ?: 0)
            }
            val placeables = measurables.map {
                it.measure(Constraints(minWidth = width, maxWidth = width))
            }
            val offsets = IntArray(placeables.size)
            var y = 0
            placeables.forEachIndexed { index, placeable ->
                offsets[index] = y
                y += placeable.height
            }
            val next = offsets.drop(1).toIntArray()
            if (!next.contentEquals(boundaries.value)) boundaries.value = next
            layout(width, constraints.constrainHeight(y)) {
                placeables.forEachIndexed { index, placeable -> placeable.placeRelative(0, offsets[index]) }
            }
        } else {
            val height = if (constraints.hasFixedHeight) {
                constraints.maxHeight
            } else {
                constraints.constrainHeight(measurables.maxOfOrNull { it.maxIntrinsicHeight(Constraints.Infinity) } ?: 0)
            }
            val placeables = measurables.map {
                it.measure(Constraints(minHeight = height, maxHeight = height))
            }
            val offsets = IntArray(placeables.size)
            var x = 0
            placeables.forEachIndexed { index, placeable ->
                offsets[index] = x
                x += placeable.width
            }
            val next = offsets.drop(1).toIntArray()
            if (!next.contentEquals(boundaries.value)) boundaries.value = next
            layout(constraints.constrainWidth(x), height) {
                placeables.forEachIndexed { index, placeable -> placeable.placeRelative(offsets[index], 0) }
            }
        }
    }
}
```

```kt title="kotlin/components/Haptics.kt"
package com.esuiss.ui.components

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalHapticFeedback

val LocalHapticsEnabled = staticCompositionLocalOf { true }

@Composable
fun ProvideHaptics(enabled: Boolean, content: @Composable () -> Unit) {
    CompositionLocalProvider(LocalHapticsEnabled provides enabled, content = content)
}

internal class Haptics(private val feedback: HapticFeedback, private val enabled: Boolean) {
    fun perform(type: HapticFeedbackType) {
        if (enabled) feedback.performHapticFeedback(type)
    }

    fun toggle(on: Boolean) = perform(if (on) HapticFeedbackType.ToggleOn else HapticFeedbackType.ToggleOff)

    fun selection() = perform(HapticFeedbackType.SegmentTick)
}

@Composable
internal fun rememberHaptics(): Haptics {
    val feedback = LocalHapticFeedback.current
    val enabled = LocalHapticsEnabled.current
    return remember(feedback, enabled) { Haptics(feedback, enabled) }
}
```

```kt title="kotlin/components/Icon.kt"
package com.esuiss.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.Dp
import com.esuiss.ui.theme.EsuissTheme

@Composable
fun Icon(
    imageVector: ImageVector,
    contentDescription: String?,
    modifier: Modifier = Modifier,
    size: Dp = LocalIconSize.current,
    tint: Color = LocalContentColor.current.takeOrElse { EsuissTheme.colors.label },
) {
    Image(
        imageVector = imageVector,
        contentDescription = contentDescription,
        modifier = modifier.size(size),
        colorFilter = ColorFilter.tint(tint),
    )
}
```

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.

### SwipeActionsContent

The row content that slides.

### SwipeActionsActions

The group of actions for one side.

### SwipeAction

One action button.

## 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-accent`, `bg-danger`, `bg-purple` and `bg-gray` with `text-on-accent` labels and icons; the content uses `bg-surface`.
