# Reorder List

A list whose rows are dragged by a handle to change their order, with haptics and move up and down actions.

Reorder List 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/reorder-list

![Preview](https://uim.suiss.app/previews/interactions-reorder-list--default.light.webp)

```tsx
import * as React from "react"
import { View } from "react-native"
import { ReorderList, ReorderListHandle, ReorderListItem } from "@/components/interactions/reorder-list"
import { ItemGroup } from "@/components/ui/item"
import { Text } from "@/components/ui/text"

const tasks: Record<string, { title: string; detail?: string }> = {
  inbox: { title: "Inbox", detail: "12 messages" },
  today: { title: "Today" },
  upcoming: { title: "Upcoming", detail: "Next 7 days" },
  someday: { title: "Someday" },
  archive: {
    title: "Archive",
    detail: "Everything you finished, kept for later reference",
  },
}

const initialOrder = Object.keys(tasks)

function renderRows(value: string[]) {
  return value.map((key) => {
    const task = tasks[key]
    return (
      <ReorderListItem key={key} value={key} className="ps-4">
        <View className="min-w-0 flex-1 py-3">
          <Text numberOfLines={1}>{task.title}</Text>
          {task.detail ? (
            <Text className="text-sm text-label-secondary">{task.detail}</Text>
          ) : null}
        </View>
        <ReorderListHandle accessibilityLabel={`Reorder ${task.title}`} />
      </ReorderListItem>
    )
  })
}

function ReorderDemo({ inset = false }: { inset?: boolean }) {
  const [value, setValue] = React.useState(initialOrder)
  return (
    <View className="gap-3">
      {inset ? (
        <ItemGroup variant="inset">
          <ReorderList value={value} onValueChange={setValue}>
            {renderRows(value)}
          </ReorderList>
        </ItemGroup>
      ) : (
        <ReorderList value={value} onValueChange={setValue}>
          {renderRows(value)}
        </ReorderList>
      )}
      <Text role="status" className="text-sm text-label-secondary">
        {value.map((key) => tasks[key].title).join(", ")}
      </Text>
    </View>
  )
}

export function ReorderListExample() {
  return (
    <ReorderDemo />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct ReorderListTask {
  let title: String
  var detail: String?
}

let reorderListTasks: [String: ReorderListTask] = [
  "inbox": ReorderListTask(title: "Inbox", detail: "12 messages"),
  "today": ReorderListTask(title: "Today"),
  "upcoming": ReorderListTask(title: "Upcoming", detail: "Next 7 days"),
  "someday": ReorderListTask(title: "Someday"),
  "archive": ReorderListTask(title: "Archive", detail: "Everything you finished, kept for later reference"),
]

let reorderListOrder = ["inbox", "today", "upcoming", "someday", "archive"]

struct ReorderListDemo: View {
  var inset = false

  @State private var value = reorderListOrder

  var body: some View {
    VStack(alignment: .leading, spacing: 12) {
      list
      Text(verbatim: value.compactMap { reorderListTasks[$0]?.title }.joined(separator: ", "))
        .textStyle(.sm)
        .foregroundStyle(Color.labelSecondary)
        .accessibilityAddTraits(.updatesFrequently)
    }
  }

  @ViewBuilder
  var list: some View {
    if inset {
      ItemGroup(.inset) {
        rows
      }
    } else {
      rows
    }
  }

  var rows: some View {
    ReorderList($value) { key in
      if let task = reorderListTasks[key] {
        VStack(alignment: .leading, spacing: 0) {
          Text(verbatim: task.title)
            .textStyle(.base)
            .foregroundStyle(Color.label)
            .lineLimit(1)
          if let detail = task.detail {
            Text(verbatim: detail)
              .textStyle(.sm)
              .foregroundStyle(Color.labelSecondary)
          }
        }
        .padding(.vertical, 12)
      }
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.ItemGroup
import com.esuiss.ui.components.ItemGroupVariant
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.ReorderList
import com.esuiss.ui.interactions.ReorderListHandle
import com.esuiss.ui.interactions.ReorderListItem
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

@Composable
fun ReorderListExample() {
    ReorderListDemo(inset = false)
}

class ReorderListTask(val title: String, val detail: String? = null)

val reorderListTasks = linkedMapOf(
    "inbox" to ReorderListTask("Inbox", "12 messages"),
    "today" to ReorderListTask("Today"),
    "upcoming" to ReorderListTask("Upcoming", "Next 7 days"),
    "someday" to ReorderListTask("Someday"),
    "archive" to ReorderListTask("Archive", "Everything you finished, kept for later reference"),
)

val reorderListInitial = reorderListTasks.keys.toList()

@Composable
fun ReorderListDemo(inset: Boolean) {
    val colors = EsuissTheme.colors
    var value by rememberSaveable { mutableStateOf(reorderListInitial) }
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        val list = @Composable {
            ReorderList(
                value = value,
                onValueChange = { value = it },
            ) { key ->
                val task = reorderListTasks.getValue(key)
                ReorderListItem {
                    Column(Modifier.weight(1f).padding(vertical = 12.dp)) {
                        Text(task.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
                        if (task.detail != null) {
                            Text(task.detail, style = Typography.sm.copy(color = colors.labelSecondary))
                        }
                    }
                    ReorderListHandle(contentDescription = "Reorder ${task.title}")
                }
            }
        }
        if (inset) ItemGroup(variant = ItemGroupVariant.Inset) { list() } else list()
        Text(
            value.joinToString(", ") { reorderListTasks.getValue(it).title },
            modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
            style = Typography.sm.copy(color = colors.labelSecondary),
        )
    }
}
```

`ReorderList` renders its `ReorderListItem`s in the order given by `value`. Dragging a row's `ReorderListHandle` lifts the row: a raised surface with a shadow fades in behind it and, outside an inset group, the row grows slightly. It follows the finger while the other rows spring out of the way.

On release the row springs into its new slot and `onValueChange` receives the new order. Rows can have different heights. Use it for ordering favorites, playlists or priorities.

## Installation

```bash title="Terminal"
npx @esuiss/uim@latest add reorder-list
```

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

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

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

### Manual

**Uniwind**

1. Install the dependencies:

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

2. Add the pieces it builds on: [Icon](/docs/components/icon), [Item](/docs/components/item), and the primitives `components/primitives/haptics.tsx`.

3. Copy the source into `components/interactions/reorder-list.tsx`:

```tsx title="uniwind/components/interactions/reorder-list.tsx"
import { cn } from "cn"
import { DotsSixVerticalIcon } from "phosphor-react-native"
import * as React from "react"
import { View, type ViewProps } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useReducedMotion,
  useSharedValue,
  withSpring,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"
import { ItemGroupContext } from "@/components/ui/item"

type ReorderListContextProps = {
  order: SharedValue<string[]>
  heights: SharedValue<Record<string, number>>
  active: SharedValue<string | null>
  start: SharedValue<number>
  target: SharedValue<number>
  dragY: SharedValue<number>
  lift: SharedValue<number>
  activeKey: string | null
  setActiveKey: (key: string | null) => void
  commit: (next: string[]) => void
  move: (key: string, delta: number) => void
  setHeight: (key: string, height: number) => void
  value: string[]
  moveUpLabel: string
  moveDownLabel: string
}

const ReorderListContext = React.createContext<ReorderListContextProps | null>(
  null
)

const ReorderListItemContext = React.createContext<string | null>(null)

function useReorderListItemKey(): string {
  const key = React.useContext(ReorderListItemContext)
  if (key === null) {
    throw new Error(
      "ReorderListHandle must be used within a <ReorderListItem />"
    )
  }
  return key
}

function useReorderList() {
  const context = React.useContext(ReorderListContext)
  if (!context) {
    throw new Error("useReorderList must be used within a <ReorderList />")
  }
  return context
}

const LIFT = {
  stiffness: 1500,
  damping: 78,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const SETTLE = {
  stiffness: 400,
  damping: 40,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

function moveItem(list: string[], from: number, to: number) {
  "worklet"
  const next = list.slice()
  const [item] = next.splice(from, 1)
  next.splice(to, 0, item)
  return next
}

function targetIndex(
  order: string[],
  heights: Record<string, number>,
  from: number,
  dy: number
) {
  "worklet"
  let target = from
  let travelled = 0
  if (dy > 0) {
    for (let index = from + 1; index < order.length; index += 1) {
      const height = heights[order[index]] ?? 0
      if (dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  } else {
    for (let index = from - 1; index >= 0; index -= 1) {
      const height = heights[order[index]] ?? 0
      if (-dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  }
  return target
}

function dropOffset(
  order: string[],
  heights: Record<string, number>,
  from: number,
  to: number
) {
  "worklet"
  let offset = 0
  if (to > from) {
    for (let index = from + 1; index <= to; index += 1) {
      offset += heights[order[index]] ?? 0
    }
  } else {
    for (let index = to; index < from; index += 1) {
      offset -= heights[order[index]] ?? 0
    }
  }
  return offset
}

function ReorderList({
  value,
  onValueChange,
  moveUpLabel = "Move up",
  moveDownLabel = "Move down",
  className,
  children,
  ...props
}: ViewProps & {
  value: string[]
  onValueChange: (value: string[]) => void
  moveUpLabel?: string
  moveDownLabel?: string
}) {
  const order = useSharedValue(value)
  const heights = useSharedValue<Record<string, number>>({})
  const active = useSharedValue<string | null>(null)
  const start = useSharedValue(-1)
  const target = useSharedValue(-1)
  const dragY = useSharedValue(0)
  const lift = useSharedValue(0)
  const [activeKey, setActiveKey] = React.useState<string | null>(null)
  const pendingRef = React.useRef(false)

  const reset = React.useCallback(() => {
    pendingRef.current = false
    active.value = null
    dragY.value = 0
    setActiveKey(null)
  }, [active, dragY])

  React.useLayoutEffect(() => {
    order.value = value
    if (pendingRef.current) reset()
  }, [value, order, reset])

  const commit = React.useCallback(
    (next: string[]) => {
      pendingRef.current = true
      onValueChange(next)
      requestAnimationFrame(() => {
        if (pendingRef.current) reset()
      })
    },
    [onValueChange, reset]
  )

  const move = React.useCallback(
    (key: string, delta: number) => {
      const from = value.indexOf(key)
      const to = Math.min(Math.max(from + delta, 0), value.length - 1)
      if (from < 0 || from === to) return
      onValueChange(moveItem(value, from, to))
    },
    [value, onValueChange]
  )

  const setHeight = React.useCallback(
    (key: string, height: number) => {
      heights.modify((current) => {
        "worklet"
        current[key] = height
        return current
      })
    },
    [heights]
  )

  const items = new Map<string, React.ReactNode>()
  for (const child of React.Children.toArray(children)) {
    if (React.isValidElement<{ value?: string }>(child) && child.props.value) {
      items.set(child.props.value, child)
    }
  }

  const context = React.useMemo<ReorderListContextProps>(
    () => ({
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      setActiveKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    }),
    [
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    ]
  )

  return (
    <ReorderListContext.Provider value={context}>
      <View className={className} {...props}>
        {value.map((key) => items.get(key) ?? null)}
      </View>
    </ReorderListContext.Provider>
  )
}

function ReorderListItem({
  value,
  className,
  style,
  onLayout,
  children,
  ...props
}: ViewProps & {
  value: string
}) {
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    activeKey,
    setHeight,
  } = useReorderList()
  const { inset } = React.useContext(ItemGroupContext)
  const reduced = useReducedMotion()
  const scaled = !inset && !reduced

  const animatedStyle = useAnimatedStyle(() => {
    const current = active.value
    if (current === null) {
      return { zIndex: 0, transform: [{ translateY: 0 }, { scale: 1 }] }
    }
    if (current === value) {
      return {
        zIndex: 10,
        transform: [
          { translateY: dragY.value },
          { scale: scaled ? 1 + 0.02 * lift.value : 1 },
        ],
      }
    }
    const index = order.value.indexOf(value)
    const from = start.value
    const to = target.value
    const height = heights.value[current] ?? 0
    let shift = 0
    if (from < index && index <= to) shift = -height
    else if (to <= index && index < from) shift = height
    return {
      zIndex: 0,
      transform: [{ translateY: withSpring(shift, SETTLE) }, { scale: 1 }],
    }
  })

  const raisedStyle = useAnimatedStyle(() => ({
    opacity: active.value === value ? lift.value : 0,
  }))

  return (
    <ReorderListItemContext.Provider value={value}>
      <AnimatedView
        className={cn("flex-row items-center gap-3", className)}
        style={[animatedStyle, style]}
        onLayout={(event) => {
          setHeight(value, event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {activeKey === value ? (
          <AnimatedView
            pointerEvents="none"
            className={cn(
              "absolute inset-0 bg-surface-raised shadow-lg",
              inset && "rounded-2xl"
            )}
            style={raisedStyle}
          />
        ) : null}
        {children}
      </AnimatedView>
    </ReorderListItemContext.Provider>
  )
}

function ReorderListHandle({
  className,
  accessibilityLabel = "Reorder",
  ...props
}: ViewProps) {
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    setActiveKey,
    commit,
    move,
    value,
    moveUpLabel,
    moveDownLabel,
  } = useReorderList()
  const key = useReorderListItemKey()
  const { impact, selection } = useHaptics()

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .minDistance(0)
        .onStart(() => {
          const index = order.value.indexOf(key)
          start.value = index
          target.value = index
          dragY.value = 0
          lift.value = 0
          active.value = key
          lift.value = withSpring(1, LIFT)
          runOnJS(setActiveKey)(key)
          runOnJS(impact)("medium")
        })
        .onUpdate((event) => {
          dragY.value = event.translationY
          const next = targetIndex(
            order.value,
            heights.value,
            start.value,
            event.translationY
          )
          if (next !== target.value) {
            target.value = next
            runOnJS(selection)()
          }
        })
        .onEnd(() => {
          runOnJS(impact)("light")
          const from = start.value
          const to = target.value
          lift.value = withSpring(0, SETTLE)
          if (from === to || from < 0) {
            dragY.value = withSpring(0, SETTLE, () => {
              active.value = null
              runOnJS(setActiveKey)(null)
            })
            return
          }
          const offset = dropOffset(order.value, heights.value, from, to)
          const next = moveItem(order.value, from, to)
          dragY.value = withSpring(offset, SETTLE, () => {
            runOnJS(commit)(next)
          })
        }),
    [
      key,
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      setActiveKey,
      commit,
      impact,
      selection,
    ]
  )

  const index = value.indexOf(key)
  const actions = [
    ...(index > 0 ? [{ name: "moveUp", label: moveUpLabel }] : []),
    ...(index >= 0 && index < value.length - 1
      ? [{ name: "moveDown", label: moveDownLabel }]
      : []),
  ]

  return (
    <GestureDetector gesture={gesture}>
      <View
        accessible
        role="button"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={actions}
        onAccessibilityAction={(event) => {
          if (event.nativeEvent.actionName === "moveUp") move(key, -1)
          if (event.nativeEvent.actionName === "moveDown") move(key, 1)
        }}
        className={cn("size-11 items-center justify-center", className)}
        {...props}
      >
        <Icon
          as={DotsSixVerticalIcon}
          weight="bold"
          className="size-5 text-label-tertiary"
        />
      </View>
    </GestureDetector>
  )
}

export { ReorderList, ReorderListHandle, ReorderListItem }
```

4. Update the import paths to match your project.

**NativeWind**

1. Install the dependencies:

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

2. Add the pieces it builds on: [Icon](/docs/components/icon), [Item](/docs/components/item), and the primitives `components/primitives/haptics.tsx`.

3. Copy the source into `components/interactions/reorder-list.tsx`:

```tsx title="nativewind/components/interactions/reorder-list.tsx"
import { cn } from "cn"
import { DotsSixVerticalIcon } from "phosphor-react-native"
import * as React from "react"
import { View, type ViewProps } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useReducedMotion,
  useSharedValue,
  withSpring,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"
import { ItemGroupContext } from "@/components/ui/item"

type ReorderListContextProps = {
  order: SharedValue<string[]>
  heights: SharedValue<Record<string, number>>
  active: SharedValue<string | null>
  start: SharedValue<number>
  target: SharedValue<number>
  dragY: SharedValue<number>
  lift: SharedValue<number>
  activeKey: string | null
  setActiveKey: (key: string | null) => void
  commit: (next: string[]) => void
  move: (key: string, delta: number) => void
  setHeight: (key: string, height: number) => void
  value: string[]
  moveUpLabel: string
  moveDownLabel: string
}

const ReorderListContext = React.createContext<ReorderListContextProps | null>(
  null
)

const ReorderListItemContext = React.createContext<string | null>(null)

function useReorderListItemKey(): string {
  const key = React.useContext(ReorderListItemContext)
  if (key === null) {
    throw new Error(
      "ReorderListHandle must be used within a <ReorderListItem />"
    )
  }
  return key
}

function useReorderList() {
  const context = React.useContext(ReorderListContext)
  if (!context) {
    throw new Error("useReorderList must be used within a <ReorderList />")
  }
  return context
}

const LIFT = {
  stiffness: 1500,
  damping: 78,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const SETTLE = {
  stiffness: 400,
  damping: 40,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

function moveItem(list: string[], from: number, to: number) {
  "worklet"
  const next = list.slice()
  const [item] = next.splice(from, 1)
  next.splice(to, 0, item)
  return next
}

function targetIndex(
  order: string[],
  heights: Record<string, number>,
  from: number,
  dy: number
) {
  "worklet"
  let target = from
  let travelled = 0
  if (dy > 0) {
    for (let index = from + 1; index < order.length; index += 1) {
      const height = heights[order[index]] ?? 0
      if (dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  } else {
    for (let index = from - 1; index >= 0; index -= 1) {
      const height = heights[order[index]] ?? 0
      if (-dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  }
  return target
}

function dropOffset(
  order: string[],
  heights: Record<string, number>,
  from: number,
  to: number
) {
  "worklet"
  let offset = 0
  if (to > from) {
    for (let index = from + 1; index <= to; index += 1) {
      offset += heights[order[index]] ?? 0
    }
  } else {
    for (let index = to; index < from; index += 1) {
      offset -= heights[order[index]] ?? 0
    }
  }
  return offset
}

function ReorderList({
  value,
  onValueChange,
  moveUpLabel = "Move up",
  moveDownLabel = "Move down",
  className,
  children,
  ...props
}: ViewProps & {
  value: string[]
  onValueChange: (value: string[]) => void
  moveUpLabel?: string
  moveDownLabel?: string
}) {
  const order = useSharedValue(value)
  const heights = useSharedValue<Record<string, number>>({})
  const active = useSharedValue<string | null>(null)
  const start = useSharedValue(-1)
  const target = useSharedValue(-1)
  const dragY = useSharedValue(0)
  const lift = useSharedValue(0)
  const [activeKey, setActiveKey] = React.useState<string | null>(null)
  const pendingRef = React.useRef(false)

  const reset = React.useCallback(() => {
    pendingRef.current = false
    active.value = null
    dragY.value = 0
    setActiveKey(null)
  }, [active, dragY])

  React.useLayoutEffect(() => {
    order.value = value
    if (pendingRef.current) reset()
  }, [value, order, reset])

  const commit = React.useCallback(
    (next: string[]) => {
      pendingRef.current = true
      onValueChange(next)
      requestAnimationFrame(() => {
        if (pendingRef.current) reset()
      })
    },
    [onValueChange, reset]
  )

  const move = React.useCallback(
    (key: string, delta: number) => {
      const from = value.indexOf(key)
      const to = Math.min(Math.max(from + delta, 0), value.length - 1)
      if (from < 0 || from === to) return
      onValueChange(moveItem(value, from, to))
    },
    [value, onValueChange]
  )

  const setHeight = React.useCallback(
    (key: string, height: number) => {
      heights.modify((current) => {
        "worklet"
        current[key] = height
        return current
      })
    },
    [heights]
  )

  const items = new Map<string, React.ReactNode>()
  for (const child of React.Children.toArray(children)) {
    if (React.isValidElement<{ value?: string }>(child) && child.props.value) {
      items.set(child.props.value, child)
    }
  }

  const context = React.useMemo<ReorderListContextProps>(
    () => ({
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      setActiveKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    }),
    [
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    ]
  )

  return (
    <ReorderListContext.Provider value={context}>
      <View className={className} {...props}>
        {value.map((key) => items.get(key) ?? null)}
      </View>
    </ReorderListContext.Provider>
  )
}

function ReorderListItem({
  value,
  className,
  style,
  onLayout,
  children,
  ...props
}: ViewProps & {
  value: string
}) {
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    activeKey,
    setHeight,
  } = useReorderList()
  const { inset } = React.useContext(ItemGroupContext)
  const reduced = useReducedMotion()
  const scaled = !inset && !reduced

  const animatedStyle = useAnimatedStyle(() => {
    const current = active.value
    if (current === null) {
      return { zIndex: 0, transform: [{ translateY: 0 }, { scale: 1 }] }
    }
    if (current === value) {
      return {
        zIndex: 10,
        transform: [
          { translateY: dragY.value },
          { scale: scaled ? 1 + 0.02 * lift.value : 1 },
        ],
      }
    }
    const index = order.value.indexOf(value)
    const from = start.value
    const to = target.value
    const height = heights.value[current] ?? 0
    let shift = 0
    if (from < index && index <= to) shift = -height
    else if (to <= index && index < from) shift = height
    return {
      zIndex: 0,
      transform: [{ translateY: withSpring(shift, SETTLE) }, { scale: 1 }],
    }
  })

  const raisedStyle = useAnimatedStyle(() => ({
    opacity: active.value === value ? lift.value : 0,
  }))

  return (
    <ReorderListItemContext.Provider value={value}>
      <AnimatedView
        className={cn("flex-row items-center gap-3", className)}
        style={[animatedStyle, style]}
        onLayout={(event) => {
          setHeight(value, event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {activeKey === value ? (
          <AnimatedView
            pointerEvents="none"
            className={cn(
              "absolute inset-0 bg-surface-raised shadow-lg",
              inset && "rounded-2xl"
            )}
            style={raisedStyle}
          />
        ) : null}
        {children}
      </AnimatedView>
    </ReorderListItemContext.Provider>
  )
}

function ReorderListHandle({
  className,
  accessibilityLabel = "Reorder",
  ...props
}: ViewProps) {
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    setActiveKey,
    commit,
    move,
    value,
    moveUpLabel,
    moveDownLabel,
  } = useReorderList()
  const key = useReorderListItemKey()
  const { impact, selection } = useHaptics()

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .minDistance(0)
        .onStart(() => {
          const index = order.value.indexOf(key)
          start.value = index
          target.value = index
          dragY.value = 0
          lift.value = 0
          active.value = key
          lift.value = withSpring(1, LIFT)
          runOnJS(setActiveKey)(key)
          runOnJS(impact)("medium")
        })
        .onUpdate((event) => {
          dragY.value = event.translationY
          const next = targetIndex(
            order.value,
            heights.value,
            start.value,
            event.translationY
          )
          if (next !== target.value) {
            target.value = next
            runOnJS(selection)()
          }
        })
        .onEnd(() => {
          runOnJS(impact)("light")
          const from = start.value
          const to = target.value
          lift.value = withSpring(0, SETTLE)
          if (from === to || from < 0) {
            dragY.value = withSpring(0, SETTLE, () => {
              active.value = null
              runOnJS(setActiveKey)(null)
            })
            return
          }
          const offset = dropOffset(order.value, heights.value, from, to)
          const next = moveItem(order.value, from, to)
          dragY.value = withSpring(offset, SETTLE, () => {
            runOnJS(commit)(next)
          })
        }),
    [
      key,
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      setActiveKey,
      commit,
      impact,
      selection,
    ]
  )

  const index = value.indexOf(key)
  const actions = [
    ...(index > 0 ? [{ name: "moveUp", label: moveUpLabel }] : []),
    ...(index >= 0 && index < value.length - 1
      ? [{ name: "moveDown", label: moveDownLabel }]
      : []),
  ]

  return (
    <GestureDetector gesture={gesture}>
      <View
        accessible
        role="button"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={actions}
        onAccessibilityAction={(event) => {
          if (event.nativeEvent.actionName === "moveUp") move(key, -1)
          if (event.nativeEvent.actionName === "moveDown") move(key, 1)
        }}
        className={cn("size-11 items-center justify-center", className)}
        {...props}
      >
        <Icon
          as={DotsSixVerticalIcon}
          weight="bold"
          className="size-5 text-label-tertiary"
        />
      </View>
    </GestureDetector>
  )
}

export { ReorderList, ReorderListHandle, ReorderListItem }
```

4. Update the import paths to match your project.

**StyleSheet**

1. Install the dependencies:

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

2. Add the pieces it builds on: [Icon](/docs/components/icon), [Item](/docs/components/item), and the primitives `components/primitives/haptics.tsx`.

3. Copy the source into `components/interactions/reorder-list.tsx`:

```tsx title="stylesheet/components/interactions/reorder-list.tsx"
import { DotsSixVerticalIcon } from "phosphor-react-native"
import * as React from "react"
import { StyleSheet, View, type ViewProps } from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useReducedMotion,
  useSharedValue,
  withSpring,
} from "react-native-reanimated"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon } from "@/components/ui/icon"
import { ItemGroupContext } from "@/components/ui/item"
import { radius, shadow, useTheme } from "@/components/ui/theme"

type ReorderListContextProps = {
  order: SharedValue<string[]>
  heights: SharedValue<Record<string, number>>
  active: SharedValue<string | null>
  start: SharedValue<number>
  target: SharedValue<number>
  dragY: SharedValue<number>
  lift: SharedValue<number>
  activeKey: string | null
  setActiveKey: (key: string | null) => void
  commit: (next: string[]) => void
  move: (key: string, delta: number) => void
  setHeight: (key: string, height: number) => void
  value: string[]
  moveUpLabel: string
  moveDownLabel: string
}

const ReorderListContext = React.createContext<ReorderListContextProps | null>(
  null
)

const ReorderListItemContext = React.createContext<string | null>(null)

function useReorderListItemKey(): string {
  const key = React.useContext(ReorderListItemContext)
  if (key === null) {
    throw new Error(
      "ReorderListHandle must be used within a <ReorderListItem />"
    )
  }
  return key
}

function useReorderList() {
  const context = React.useContext(ReorderListContext)
  if (!context) {
    throw new Error("useReorderList must be used within a <ReorderList />")
  }
  return context
}

const LIFT = {
  stiffness: 1500,
  damping: 78,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const SETTLE = {
  stiffness: 400,
  damping: 40,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const styles = StyleSheet.create({
  item: { flexDirection: "row", alignItems: "center", gap: 12 },
  raised: {
    position: "absolute",
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...shadow.lg,
  },
  raisedInset: { borderRadius: radius["2xl"] },
  handle: {
    width: 44,
    height: 44,
    alignItems: "center",
    justifyContent: "center",
  },
})

function moveItem(list: string[], from: number, to: number) {
  "worklet"
  const next = list.slice()
  const [item] = next.splice(from, 1)
  next.splice(to, 0, item)
  return next
}

function targetIndex(
  order: string[],
  heights: Record<string, number>,
  from: number,
  dy: number
) {
  "worklet"
  let target = from
  let travelled = 0
  if (dy > 0) {
    for (let index = from + 1; index < order.length; index += 1) {
      const height = heights[order[index]] ?? 0
      if (dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  } else {
    for (let index = from - 1; index >= 0; index -= 1) {
      const height = heights[order[index]] ?? 0
      if (-dy <= travelled + height / 2) break
      travelled += height
      target = index
    }
  }
  return target
}

function dropOffset(
  order: string[],
  heights: Record<string, number>,
  from: number,
  to: number
) {
  "worklet"
  let offset = 0
  if (to > from) {
    for (let index = from + 1; index <= to; index += 1) {
      offset += heights[order[index]] ?? 0
    }
  } else {
    for (let index = to; index < from; index += 1) {
      offset -= heights[order[index]] ?? 0
    }
  }
  return offset
}

function ReorderList({
  value,
  onValueChange,
  moveUpLabel = "Move up",
  moveDownLabel = "Move down",
  children,
  ...props
}: ViewProps & {
  value: string[]
  onValueChange: (value: string[]) => void
  moveUpLabel?: string
  moveDownLabel?: string
}) {
  const order = useSharedValue(value)
  const heights = useSharedValue<Record<string, number>>({})
  const active = useSharedValue<string | null>(null)
  const start = useSharedValue(-1)
  const target = useSharedValue(-1)
  const dragY = useSharedValue(0)
  const lift = useSharedValue(0)
  const [activeKey, setActiveKey] = React.useState<string | null>(null)
  const pendingRef = React.useRef(false)

  const reset = React.useCallback(() => {
    pendingRef.current = false
    active.value = null
    dragY.value = 0
    setActiveKey(null)
  }, [active, dragY])

  React.useLayoutEffect(() => {
    order.value = value
    if (pendingRef.current) reset()
  }, [value, order, reset])

  const commit = React.useCallback(
    (next: string[]) => {
      pendingRef.current = true
      onValueChange(next)
      requestAnimationFrame(() => {
        if (pendingRef.current) reset()
      })
    },
    [onValueChange, reset]
  )

  const move = React.useCallback(
    (key: string, delta: number) => {
      const from = value.indexOf(key)
      const to = Math.min(Math.max(from + delta, 0), value.length - 1)
      if (from < 0 || from === to) return
      onValueChange(moveItem(value, from, to))
    },
    [value, onValueChange]
  )

  const setHeight = React.useCallback(
    (key: string, height: number) => {
      heights.modify((current) => {
        "worklet"
        current[key] = height
        return current
      })
    },
    [heights]
  )

  const items = new Map<string, React.ReactNode>()
  for (const child of React.Children.toArray(children)) {
    if (React.isValidElement<{ value?: string }>(child) && child.props.value) {
      items.set(child.props.value, child)
    }
  }

  const context = React.useMemo<ReorderListContextProps>(
    () => ({
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      setActiveKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    }),
    [
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      activeKey,
      commit,
      move,
      setHeight,
      value,
      moveUpLabel,
      moveDownLabel,
    ]
  )

  return (
    <ReorderListContext.Provider value={context}>
      <View {...props}>{value.map((key) => items.get(key) ?? null)}</View>
    </ReorderListContext.Provider>
  )
}

function ReorderListItem({
  value,
  style,
  onLayout,
  children,
  ...props
}: ViewProps & {
  value: string
}) {
  const { colors } = useTheme()
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    activeKey,
    setHeight,
  } = useReorderList()
  const { inset } = React.useContext(ItemGroupContext)
  const reduced = useReducedMotion()
  const scaled = !inset && !reduced

  const animatedStyle = useAnimatedStyle(() => {
    const current = active.value
    if (current === null) {
      return { zIndex: 0, transform: [{ translateY: 0 }, { scale: 1 }] }
    }
    if (current === value) {
      return {
        zIndex: 10,
        transform: [
          { translateY: dragY.value },
          { scale: scaled ? 1 + 0.02 * lift.value : 1 },
        ],
      }
    }
    const index = order.value.indexOf(value)
    const from = start.value
    const to = target.value
    const height = heights.value[current] ?? 0
    let shift = 0
    if (from < index && index <= to) shift = -height
    else if (to <= index && index < from) shift = height
    return {
      zIndex: 0,
      transform: [{ translateY: withSpring(shift, SETTLE) }, { scale: 1 }],
    }
  })

  const raisedStyle = useAnimatedStyle(() => ({
    opacity: active.value === value ? lift.value : 0,
  }))

  return (
    <ReorderListItemContext.Provider value={value}>
      <AnimatedView
        style={[styles.item, animatedStyle, style]}
        onLayout={(event) => {
          setHeight(value, event.nativeEvent.layout.height)
          onLayout?.(event)
        }}
        {...props}
      >
        {activeKey === value ? (
          <AnimatedView
            pointerEvents="none"
            style={[
              styles.raised,
              { backgroundColor: colors.surfaceRaised },
              inset && styles.raisedInset,
              raisedStyle,
            ]}
          />
        ) : null}
        {children}
      </AnimatedView>
    </ReorderListItemContext.Provider>
  )
}

function ReorderListHandle({
  style,
  accessibilityLabel = "Reorder",
  ...props
}: ViewProps) {
  const {
    order,
    heights,
    active,
    start,
    target,
    dragY,
    lift,
    setActiveKey,
    commit,
    move,
    value,
    moveUpLabel,
    moveDownLabel,
  } = useReorderList()
  const { colors } = useTheme()
  const key = useReorderListItemKey()
  const { impact, selection } = useHaptics()

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .minDistance(0)
        .onStart(() => {
          const index = order.value.indexOf(key)
          start.value = index
          target.value = index
          dragY.value = 0
          lift.value = 0
          active.value = key
          lift.value = withSpring(1, LIFT)
          runOnJS(setActiveKey)(key)
          runOnJS(impact)("medium")
        })
        .onUpdate((event) => {
          dragY.value = event.translationY
          const next = targetIndex(
            order.value,
            heights.value,
            start.value,
            event.translationY
          )
          if (next !== target.value) {
            target.value = next
            runOnJS(selection)()
          }
        })
        .onEnd(() => {
          runOnJS(impact)("light")
          const from = start.value
          const to = target.value
          lift.value = withSpring(0, SETTLE)
          if (from === to || from < 0) {
            dragY.value = withSpring(0, SETTLE, () => {
              active.value = null
              runOnJS(setActiveKey)(null)
            })
            return
          }
          const offset = dropOffset(order.value, heights.value, from, to)
          const next = moveItem(order.value, from, to)
          dragY.value = withSpring(offset, SETTLE, () => {
            runOnJS(commit)(next)
          })
        }),
    [
      key,
      order,
      heights,
      active,
      start,
      target,
      dragY,
      lift,
      setActiveKey,
      commit,
      impact,
      selection,
    ]
  )

  const index = value.indexOf(key)
  const actions = [
    ...(index > 0 ? [{ name: "moveUp", label: moveUpLabel }] : []),
    ...(index >= 0 && index < value.length - 1
      ? [{ name: "moveDown", label: moveDownLabel }]
      : []),
  ]

  return (
    <GestureDetector gesture={gesture}>
      <View
        accessible
        role="button"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={actions}
        onAccessibilityAction={(event) => {
          if (event.nativeEvent.actionName === "moveUp") move(key, -1)
          if (event.nativeEvent.actionName === "moveDown") move(key, 1)
        }}
        style={[styles.handle, style]}
        {...props}
      >
        <Icon
          as={DotsSixVerticalIcon}
          weight="bold"
          size={20}
          color={colors.labelTertiary}
        />
      </View>
    </GestureDetector>
  )
}

export { ReorderList, ReorderListHandle, ReorderListItem }
```

4. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Add the Swift package to your app:

```swift title="Package.swift"
.package(url: "https://github.com/phosphor-icons/swift", from: "2.1.0")
```

3. 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)
}
```

4. Copy the source and every file it uses:

```swift title="swift/Interactions/ReorderList.swift"
import PhosphorSwift
import SwiftUI

enum ReorderMath {
  static func move<Element>(_ items: [Element], from source: Int, to destination: Int) -> [Element] {
    guard items.indices.contains(source), items.indices.contains(destination), source != destination else {
      return items
    }
    var result = items
    let element = result.remove(at: source)
    result.insert(element, at: destination)
    return result
  }

  static func target(from index: Int, translation: CGFloat, heights: [CGFloat]) -> Int {
    guard heights.indices.contains(index) else { return index }
    var target = index
    if translation > 0 {
      var travelled: CGFloat = 0
      while target + 1 < heights.count {
        let next = heights[target + 1]
        guard translation > travelled + next / 2 else { break }
        travelled += next
        target += 1
      }
    } else if translation < 0 {
      var travelled: CGFloat = 0
      while target - 1 >= 0 {
        let previous = heights[target - 1]
        guard -translation > travelled + previous / 2 else { break }
        travelled += previous
        target -= 1
      }
    }
    return target
  }

  static func shift(for index: Int, dragging: Int, target: Int, height: CGFloat) -> CGFloat {
    if dragging < target, index > dragging, index <= target { return -height }
    if dragging > target, index < dragging, index >= target { return height }
    return 0
  }
}

public struct ReorderList<Value: Hashable, Row: View>: View {
  let value: Binding<[Value]>
  let row: (Value) -> Row

  @State private var heights: [Value: CGFloat] = [:]
  @State private var dragging: Value?
  @State private var lifted: Value?
  @State private var translation: CGFloat = 0
  @State private var drops = 0
  @Environment(\.itemGroupInset) private var inset
  @Environment(\.accessibilityReduceMotion) private var reduceMotion

  public init(_ value: Binding<[Value]>, @ViewBuilder row: @escaping (Value) -> Row) {
    self.value = value
    self.row = row
  }

  private var items: [Value] { value.wrappedValue }

  private var sizes: [CGFloat] { items.map { heights[$0] ?? 0 } }

  private var draggingIndex: Int? { dragging.flatMap { items.firstIndex(of: $0) } }

  private var target: Int? {
    draggingIndex.map { ReorderMath.target(from: $0, translation: translation, heights: sizes) }
  }

  private func commit(from source: Int, to destination: Int) {
    let next = ReorderMath.move(items, from: source, to: destination)
    if reduceMotion {
      value.wrappedValue = next
    } else {
      withAnimation(ReorderMotion.settle) { value.wrappedValue = next }
    }
    AccessibilityNotification.Announcement(String(localized: "Moved to position \(destination + 1) of \(items.count)")).post()
  }

  public var body: some View {
    let draggingIndex = draggingIndex
    let target = target
    VStack(spacing: 0) {
      ForEach(Array(items.enumerated()), id: \.element) { index, item in
        let active = draggingIndex == index
        let shift = draggingIndex.flatMap { from in
          target.map { ReorderMath.shift(for: index, dragging: from, target: $0, height: sizes[from]) }
        } ?? 0
        rowView(item, index: index, active: active)
          .offset(y: active ? translation : shift)
          .animation(active || reduceMotion ? nil : ReorderMotion.settle, value: shift)
          .zIndex(active ? 1 : 0)
      }
    }
    .coordinateSpace(.named(ReorderSpace.name))
    .hapticFeedback(.impact(weight: .medium), trigger: dragging) { HapticMoments.lifted($0, $1) }
    .hapticFeedback(.selection, trigger: target) { HapticMoments.moved($0, $1) }
    .hapticFeedback(.impact(weight: .light), trigger: drops)
  }

  private func rowView(_ item: Value, index: Int, active: Bool) -> some View {
    let raised = lifted == item
    let shape = RoundedRectangle(cornerRadius: inset ? Radius.xl2 : 0, style: .continuous)
    return HStack(spacing: 12) {
      row(item)
        .frame(maxWidth: .infinity, alignment: .leading)
      Ph.dotsSixVertical.bold
        .frame(width: 20, height: 20)
        .foregroundStyle(raised ? Color.labelSecondary : .labelTertiary)
        .frame(width: 44, height: 44)
        .contentShape(Rectangle())
        .gesture(
          DragGesture(minimumDistance: 0, coordinateSpace: .named(ReorderSpace.name))
            .onChanged { gesture in
              if dragging != item {
                dragging = item
                withAnimation(reduceMotion ? nil : ReorderMotion.lift) { lifted = item }
              }
              translation = gesture.translation.height
            }
            .onEnded { gesture in
              drops += 1
              let destination = ReorderMath.target(from: index, translation: gesture.translation.height, heights: sizes)
              if destination != index {
                var transaction = Transaction()
                transaction.disablesAnimations = true
                withTransaction(transaction) {
                  value.wrappedValue = ReorderMath.move(items, from: index, to: destination)
                  translation = gesture.translation.height - travelled(from: index, to: destination)
                }
              }
              withAnimation(reduceMotion ? nil : ReorderMotion.settle) {
                translation = 0
                lifted = nil
              } completion: {
                dragging = nil
              }
            }
        )
        .accessibilityHidden(true)
    }
    .padding(.leading, 16)
    .padding(.trailing, 4)
    .frame(minHeight: 44)
    .background {
      shape
        .fill(Color.surfaceRaised)
        .shadow(.lg)
        .opacity(raised ? 1 : 0)
    }
    .overlay(alignment: .bottom) {
      if index < items.count - 1 && !active {
        Color.separator.frame(height: 1).padding(.leading, 16)
      }
    }
    .scaleEffect(raised && !reduceMotion && !inset ? 1.02 : 1)
    .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { heights[item] = $0 }
    .accessibilityElement(children: .combine)
    .accessibilityActions {
      if index > 0 {
        Button("Move up") { commit(from: index, to: index - 1) }
      }
      if index < items.count - 1 {
        Button("Move down") { commit(from: index, to: index + 1) }
      }
    }
  }

  private func travelled(from source: Int, to destination: Int) -> CGFloat {
    if destination > source {
      return sizes[(source + 1)...destination].reduce(0, +)
    }
    return -sizes[destination..<source].reduce(0, +)
  }
}

enum ReorderMotion {
  static let lift = Animation.smooth(duration: 0.16)
  static let settle = Animation.smooth(duration: 0.3)
}

enum ReorderSpace {
  static let name = "reorder-list"
}
```

```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)
  }
}
```

```swift title="swift/Components/Item.swift"
import SwiftUI

public enum ItemVariant: CaseIterable, Sendable {
  case `default`, outline, muted
}

public enum ItemSize: CaseIterable, Sendable {
  case `default`, sm, xs

  var horizontalPadding: CGFloat {
    switch self {
    case .default: 16
    case .sm: 14
    case .xs: 12
    }
  }

  var verticalPadding: CGFloat {
    switch self {
    case .default: 14
    case .sm: 12
    case .xs: 10
    }
  }

  var gap: CGFloat {
    self == .xs ? 10 : 14
  }

  var groupGap: CGFloat {
    switch self {
    case .default: 16
    case .sm: 10
    case .xs: 8
    }
  }

  var mediaImage: CGFloat {
    switch self {
    case .default: 40
    case .sm: 32
    case .xs: 24
    }
  }
}

public enum ItemGroupVariant: CaseIterable, Sendable {
  case `default`, inset
}

extension EnvironmentValues {
  @Entry var itemSize: ItemSize = .default
  @Entry var itemGroupInset = false
  @Entry var itemHasDescription = false
}

struct ItemGapKey: PreferenceKey {
  static var defaultValue: CGFloat? { nil }

  static func reduce(value: inout CGFloat?, nextValue: () -> CGFloat?) {
    guard let next = nextValue() else { return }
    value = min(value ?? next, next)
  }
}

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

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

enum ItemSlot: Sendable {
  case media, content, actions, fullRow, other
}

struct ItemSlotKey: LayoutValueKey {
  static let defaultValue = ItemSlot.other
}

public struct ItemGroup<Content: View>: View {
  let variant: ItemGroupVariant
  let content: Content

  @State private var gap: CGFloat?

  public init(_ variant: ItemGroupVariant = .default, @ViewBuilder content: () -> Content) {
    self.variant = variant
    self.content = content()
  }

  public var body: some View {
    let inset = variant == .inset
    let shape = RoundedRectangle(cornerRadius: Radius.xl2, style: .continuous)
    VStack(alignment: .leading, spacing: inset ? 0 : gap ?? ItemSize.default.groupGap) {
      content
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .environment(\.itemGroupInset, inset)
    .onPreferenceChange(ItemGapKey.self) { gap = $0 }
    .transformPreference(ItemGapKey.self) { $0 = nil }
    .background(inset ? Color.surfaceSecondary : .clear, in: shape)
    .clipShape(inset ? AnyShape(shape) : AnyShape(Rectangle()))
    .accessibilityElement(children: .contain)
  }
}

public struct ItemSeparator: View {
  @Environment(\.itemGroupInset) private var inset

  public init() {}

  public var body: some View {
    Separator()
      .padding(.vertical, inset ? 0 : 8)
      .padding(.leading, inset ? 16 : 0)
  }
}

public struct Item<Content: View>: View {
  let variant: ItemVariant
  let size: ItemSize
  let action: (() -> Void)?
  let content: Content

  @State private var hasDescription = false
  @Environment(\.itemGroupInset) private var inset

  public init(
    _ variant: ItemVariant = .default,
    size: ItemSize = .default,
    action: (() -> Void)? = nil,
    @ViewBuilder content: () -> Content
  ) {
    self.variant = variant
    self.size = size
    self.action = action
    self.content = content()
  }

  public var body: some View {
    Group {
      if let action {
        Button(action: action) {
          surface
        }
        .buttonStyle(ItemButtonStyle(variant: variant, inset: inset))
      } else {
        surface.background(ItemBackground(variant: variant, inset: inset, pressed: false))
      }
    }
    .preference(key: ItemGapKey.self, value: size.groupGap)
  }

  private var surface: some View {
    ItemLayout(gap: size.gap, topAlignMedia: hasDescription) {
      content
    }
    .scaledFont(.base)
    .foregroundStyle(Color.label)
    .padding(.horizontal, size.horizontalPadding)
    .padding(.vertical, size.verticalPadding)
    .frame(maxWidth: .infinity, alignment: .leading)
    .environment(\.itemSize, size)
    .environment(\.itemHasDescription, hasDescription)
    .onPreferenceChange(ItemDescriptionKey.self) { hasDescription = $0 }
    .contentShape(Rectangle())
  }
}

private struct ItemBackground: View {
  let variant: ItemVariant
  let inset: Bool
  let pressed: Bool

  var body: some View {
    let shape = RoundedRectangle(cornerRadius: inset ? 0 : Radius.xl, style: .continuous)
    ZStack {
      shape.fill(variant == .muted ? Color.surfaceSecondary.opacity(0.5) : .clear)
      if pressed {
        shape.fill(Color.itemPressed)
      }
      if variant == .outline {
        shape.strokeBorder(Color.separator)
      }
    }
  }
}

private struct ItemButtonStyle: ButtonStyle {
  let variant: ItemVariant
  let inset: Bool

  @Environment(\.isEnabled) private var isEnabled

  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .background(ItemBackground(variant: variant, inset: inset, pressed: configuration.isPressed && isEnabled))
      .opacity(isEnabled ? 1 : 0.5)
  }
}

struct ItemLayout: Layout {
  var gap: CGFloat
  var topAlignMedia: Bool

  private struct Line {
    var indices: [Int]
    var full: Bool
  }

  private func lines(_ subviews: Subviews) -> [Line] {
    var result: [Line] = []
    var current: [Int] = []
    for index in subviews.indices {
      if subviews[index][ItemSlotKey.self] == .fullRow {
        if !current.isEmpty { result.append(Line(indices: current, full: false)) }
        current = []
        result.append(Line(indices: [index], full: true))
      } else {
        current.append(index)
      }
    }
    if !current.isEmpty { result.append(Line(indices: current, full: false)) }
    return result
  }

  private func widths(_ line: Line, subviews: Subviews, width: CGFloat?) -> [CGFloat] {
    if line.full {
      return [width ?? subviews[line.indices[0]].sizeThatFits(.unspecified).width]
    }
    let spacing = gap * CGFloat(max(line.indices.count - 1, 0))
    let flexible = line.indices.first { subviews[$0][ItemSlotKey.self] == .content }
    var fixed: [Int: CGFloat] = [:]
    for index in line.indices where index != flexible {
      fixed[index] = subviews[index].sizeThatFits(.unspecified).width
    }
    let used = fixed.values.reduce(0, +) + spacing
    return line.indices.map { index in
      if index == flexible {
        if let width { return max(width - used, 0) }
        return subviews[index].sizeThatFits(.unspecified).width
      }
      return fixed[index] ?? 0
    }
  }

  func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
    var height: CGFloat = 0
    var widest: CGFloat = 0
    let all = lines(subviews)
    for (position, line) in all.enumerated() {
      let sizes = widths(line, subviews: subviews, width: proposal.width)
      var lineHeight: CGFloat = 0
      for (index, width) in zip(line.indices, sizes) {
        lineHeight = max(lineHeight, subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil)).height)
      }
      let spacing = gap * CGFloat(max(line.indices.count - 1, 0))
      widest = max(widest, sizes.reduce(0, +) + (line.full ? 0 : spacing))
      height += lineHeight + (position > 0 ? gap : 0)
    }
    return CGSize(width: proposal.width ?? widest, height: height)
  }

  func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
    var y = bounds.minY
    for line in lines(subviews) {
      let sizes = widths(line, subviews: subviews, width: bounds.width)
      var heights: [CGFloat] = []
      for (index, width) in zip(line.indices, sizes) {
        heights.append(subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil)).height)
      }
      let lineHeight = heights.max() ?? 0
      var x = bounds.minX
      for (offset, index) in line.indices.enumerated() {
        let width = sizes[offset]
        let height = heights[offset]
        let top = topAlignMedia && subviews[index][ItemSlotKey.self] == .media
        let originY = top ? y + 2 : y + (lineHeight - height) / 2
        subviews[index].place(
          at: CGPoint(x: x, y: originY),
          anchor: .topLeading,
          proposal: ProposedViewSize(width: width, height: height)
        )
        x += width + gap
      }
      y += lineHeight + gap
    }
  }
}

public enum ItemMediaVariant: CaseIterable, Sendable {
  case `default`, icon, image
}

public struct ItemMedia<Content: View>: View {
  let variant: ItemMediaVariant
  let content: Content

  @Environment(\.itemSize) private var size

  public init(_ variant: ItemMediaVariant = .default, @ViewBuilder content: () -> Content) {
    self.variant = variant
    self.content = content()
  }

  public var body: some View {
    Group {
      switch variant {
      case .default:
        HStack(spacing: 8) { content }
      case .icon:
        content.frame(width: 16, height: 16)
      case .image:
        content
          .scaledToFill()
          .frame(width: size.mediaImage, height: size.mediaImage)
          .clipShape(RoundedRectangle(cornerRadius: size == .xs ? Radius.sm : Radius.md, style: .continuous))
      }
    }
    .accessibilityHidden(variant != .default)
    .layoutValue(key: ItemSlotKey.self, value: .media)
  }
}

public struct ItemContent<Content: View>: View {
  let content: Content

  @Environment(\.itemSize) private var size

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    VStack(alignment: .leading, spacing: size == .xs ? 2 : 4) {
      content
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .layoutValue(key: ItemSlotKey.self, value: .content)
  }
}

public struct ItemTitle<Content: View>: View {
  let content: Content

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    HStack(spacing: 8) {
      content
    }
    .scaledTextStyle(.base, weight: .semibold)
    .foregroundStyle(Color.label)
    .lineLimit(1)
    .accessibilityElement(children: .combine)
  }
}

extension ItemTitle where Content == Text {
  public init(_ title: LocalizedStringKey) {
    self.init { Text(title) }
  }

  public init(verbatim title: String) {
    self.init { Text(verbatim: title) }
  }
}

public struct ItemDescription: View {
  let text: Text

  public init(_ description: LocalizedStringKey) {
    text = Text(description)
  }

  public init(verbatim description: String) {
    text = Text(verbatim: description)
  }

  public var body: some View {
    text
      .scaledTextStyle(.sm)
      .foregroundStyle(Color.labelSecondary)
      .multilineTextAlignment(.leading)
      .lineLimit(2)
      .fixedSize(horizontal: false, vertical: true)
      .preference(key: ItemDescriptionKey.self, value: true)
  }
}

public struct ItemActions<Content: View>: View {
  let content: Content

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    HStack(spacing: 8) {
      content
    }
    .fixedSize()
    .layoutValue(key: ItemSlotKey.self, value: .actions)
  }
}

public struct ItemHeader<Content: View>: View {
  let content: Content

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    SpaceBetween(spacing: 8) {
      content
    }
    .frame(maxWidth: .infinity)
    .layoutValue(key: ItemSlotKey.self, value: .fullRow)
  }
}

public struct ItemFooter<Content: View>: View {
  let content: Content

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    SpaceBetween(spacing: 8) {
      content
    }
    .frame(maxWidth: .infinity)
    .layoutValue(key: ItemSlotKey.self, value: .fullRow)
  }
}

struct SpaceBetween: Layout {
  var spacing: CGFloat

  func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
    let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
    let natural = sizes.reduce(0) { $0 + $1.width } + spacing * CGFloat(max(subviews.count - 1, 0))
    return CGSize(width: proposal.width ?? natural, height: sizes.map(\.height).max() ?? 0)
  }

  func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
    let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
    let total = sizes.reduce(0) { $0 + $1.width }
    let gaps = CGFloat(max(subviews.count - 1, 0))
    let gap = subviews.count > 1 ? max(spacing, (bounds.width - total) / gaps) : 0
    var x = bounds.minX
    for (index, view) in subviews.enumerated() {
      let size = sizes[index]
      view.place(
        at: CGPoint(x: x, y: bounds.midY - size.height / 2),
        anchor: .topLeading,
        proposal: ProposedViewSize(size)
      )
      x += size.width + gap
    }
  }
}
```

```swift title="swift/Components/Separator.swift"
import SwiftUI

public struct Separator: View {
  let orientation: Axis

  public init(_ orientation: Axis = .horizontal) {
    self.orientation = orientation
  }

  public var body: some View {
    Rectangle()
      .fill(Color.separator)
      .frame(width: orientation == .vertical ? 1 : nil, height: orientation == .horizontal ? 1 : nil)
      .frame(maxWidth: orientation == .horizontal ? .infinity : nil, maxHeight: orientation == .vertical ? .infinity : nil)
      .accessibilityHidden(true)
  }
}
```

```swift title="swift/Components/TextVariant.swift"
import SwiftUI

public enum TextVariant: CaseIterable, Sendable {
  case `default`, h1, h2, h3, h4, p, blockquote, code, lead, large, small, muted

  var style: TextStyle {
    switch self {
    case .h1: .xl3
    case .h2: .xl2
    case .h3: .xl
    case .h4, .lead, .large: .lg
    case .code, .small, .muted: .sm
    default: .base
    }
  }

  var weight: Font.Weight {
    switch self {
    case .h1, .h2: .bold
    case .h3, .h4, .large, .code: .semibold
    case .small: .medium
    default: .regular
    }
  }

  var color: Color {
    switch self {
    case .lead, .muted: .labelSecondary
    default: .label
    }
  }

  var isHeading: Bool {
    switch self {
    case .h1, .h2, .h3, .h4: true
    default: false
    }
  }
}

private struct TextVariantModifier: ViewModifier {
  let variant: TextVariant

  func body(content: Content) -> some View {
    switch variant {
    case .blockquote:
      styled(content)
        .italic()
        .padding(.leading, 12)
        .overlay(alignment: .leading) {
          Rectangle().fill(Color.separator).frame(width: 2)
        }
        .padding(.top, 16)
    case .code:
      styled(content)
        .monospaced()
        .padding(.horizontal, 4)
        .padding(.vertical, 2)
        .background(Color.surfaceSecondary, in: RoundedRectangle(cornerRadius: Radius.sm, style: .continuous))
    case .p:
      styled(content).padding(.top, 12)
    default:
      styled(content)
    }
  }

  private func styled(_ content: Content) -> some View {
    content
      .scaledTextStyle(variant.style, weight: variant.weight)
      .foregroundStyle(variant.color)
      .accessibilityAddTraits(variant.isHeading ? .isHeader : [])
  }
}

extension View {
  public func textVariant(_ variant: TextVariant) -> some View {
    modifier(TextVariantModifier(variant: variant))
  }
}

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

  @ScaledMetric(relativeTo: .body) private var scale: CGFloat = 1

  func body(content: Content) -> some View {
    let size = style.size * scale
    let lineSpacing = max(0, style.lineHeight * scale - UIFont.systemFont(ofSize: size).lineHeight)
    content
      .font(.system(size: size, weight: weight))
      .tracking(style.letterSpacing)
      .lineSpacing(lineSpacing)
      .padding(.vertical, lineSpacing / 2)
  }
}

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

  func scaledFont(_ style: TextStyle, weight: Font.Weight = .regular) -> some View {
    modifier(ScaledFontModifier(style: style, weight: weight))
  }
}

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

  @ScaledMetric(relativeTo: .body) private var scale: CGFloat = 1

  func body(content: Content) -> some View {
    content
      .font(.system(size: style.size * scale, weight: weight))
      .tracking(style.letterSpacing)
  }
}
```

5. 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")
implementation("com.adamglin:phosphor-icon-android:1.0.0")
```

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/ReorderList.kt"
package com.esuiss.ui.interactions

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateMapOf
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.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.DotsSixVertical
import com.esuiss.ui.components.Haptics
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.ItemGroupVariant
import com.esuiss.ui.components.LocalItemGroupVariant
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.formReducedMotion
import com.esuiss.ui.components.rememberHaptics
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Shadows
import com.esuiss.ui.theme.Typography
import com.esuiss.ui.theme.shadow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Stable
interface ReorderListScope {
    val key: String
    val index: Int
    val dragging: Boolean
}

private val liftSpring = spring<Float>(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = Spring.StiffnessMedium)

private val settleSpring = spring<Float>(dampingRatio = Spring.DampingRatioNoBouncy, stiffness = Spring.StiffnessMediumLow)

private class ReorderListItemScope(
    override val key: String,
    override val index: Int,
    override val dragging: Boolean,
) : ReorderListScope

@Stable
private class ReorderController {
    var order by mutableStateOf(emptyList<String>())
    var active by mutableStateOf<String?>(null)
    var settling by mutableStateOf<String?>(null)
    val raised: String? get() = active ?: settling
    var reduced = false
    var offset by mutableFloatStateOf(0f)
    val heights = mutableStateMapOf<String, Int>()
    var onChange: (List<String>) -> Unit = {}
    val placements = mutableMapOf<String, Animatable<Float, AnimationVector1D>>()
    var scope: CoroutineScope? = null
    var haptics: Haptics? = null

    fun start(key: String) {
        active = key
        offset = placements[key]?.value ?: 0f
        haptics?.perform(HapticFeedbackType.LongPress)
    }

    fun drag(delta: Float) {
        val key = active ?: return
        offset += delta
        var index = order.indexOf(key)
        if (index < 0) return
        while (true) {
            val next = order.getOrNull(index + 1)
            val previous = order.getOrNull(index - 1)
            val nextHeight = next?.let { heights[it] } ?: 0
            val previousHeight = previous?.let { heights[it] } ?: 0
            when {
                next != null && offset > nextHeight / 2f -> {
                    order = order.toMutableList().apply { add(index + 1, removeAt(index)) }
                    offset -= nextHeight
                    index += 1
                    haptics?.selection()
                }
                previous != null && offset < -previousHeight / 2f -> {
                    order = order.toMutableList().apply { add(index - 1, removeAt(index)) }
                    offset += previousHeight
                    index -= 1
                    haptics?.selection()
                }
                else -> break
            }
        }
        onChange(order)
    }

    fun end() {
        val key = active ?: return
        haptics?.perform(HapticFeedbackType.GestureEnd)
        val released = offset
        val placement = placements[key]
        val launcher = scope
        if (placement == null || launcher == null) {
            active = null
            offset = 0f
            return
        }
        launcher.launch {
            placement.snapTo(released)
            settling = key
            active = null
            offset = 0f
            try {
                if (reduced) placement.snapTo(0f) else placement.animateTo(0f, settleSpring)
            } finally {
                if (settling == key) settling = null
            }
        }
    }
}

private class ReorderHandleTarget(val controller: ReorderController, val key: String)

private val LocalReorderHandle = staticCompositionLocalOf<ReorderHandleTarget?> { null }

private val LocalReorderLift = staticCompositionLocalOf { 0f }

@Composable
fun ReorderList(
    value: List<String>,
    onValueChange: (List<String>) -> Unit,
    modifier: Modifier = Modifier,
    moveUpLabel: String = "Move up",
    moveDownLabel: String = "Move down",
    item: @Composable ReorderListScope.(String) -> Unit,
) {
    val colors = EsuissTheme.colors
    val scope = rememberCoroutineScope()
    val controller = remember { ReorderController() }
    val change by rememberUpdatedState(onValueChange)
    controller.onChange = { if (it != value) change(it) }
    controller.scope = scope
    controller.haptics = rememberHaptics()
    val reduced = formReducedMotion()
    controller.reduced = reduced
    val inset = LocalItemGroupVariant.current == ItemGroupVariant.Inset
    if (controller.active == null && controller.order != value) controller.order = value
    val order = controller.order
    Column(modifier = modifier) {
        order.forEachIndexed { index, itemKey ->
            key(itemKey) {
                val dragging = controller.active == itemKey
                val raised = controller.raised
                val previous = order.getOrNull(index - 1)
                val hideLine = index == 0 || itemKey == raised || previous == raised
                val placement = remember { Animatable(0f) }
                DisposableEffect(itemKey, placement) {
                    controller.placements[itemKey] = placement
                    onDispose { controller.placements.remove(itemKey) }
                }
                var placed by remember { mutableFloatStateOf(Float.NaN) }
                val lift by animateFloatAsState(
                    targetValue = if (dragging) 1f else 0f,
                    animationSpec = when {
                        reduced -> snap()
                        dragging -> liftSpring
                        else -> settleSpring
                    },
                    label = "lift",
                )
                val actions = buildList {
                    if (index > 0) {
                        add(
                            CustomAccessibilityAction(moveUpLabel) {
                                change(order.toMutableList().apply { add(index - 1, removeAt(index)) })
                                true
                            },
                        )
                    }
                    if (index < order.lastIndex) {
                        add(
                            CustomAccessibilityAction(moveDownLabel) {
                                change(order.toMutableList().apply { add(index + 1, removeAt(index)) })
                                true
                            },
                        )
                    }
                }
                Box(
                    modifier = Modifier
                        .zIndex(if (itemKey == raised || lift > 0f) 1f else 0f)
                        .onSizeChanged { controller.heights[itemKey] = it.height }
                        .onPlaced { coordinates ->
                            val y = coordinates.parentCoordinates?.let { parent ->
                                parent.localPositionOf(coordinates, Offset.Zero).y
                            } ?: 0f
                            val old = placed
                            placed = y
                            if (!old.isNaN() && old != y && controller.active != itemKey && !reduced) {
                                scope.launch {
                                    val velocity = placement.velocity
                                    placement.snapTo(placement.value + old - y)
                                    placement.animateTo(0f, settleSpring, velocity)
                                }
                            }
                        }
                        .graphicsLayer {
                            translationY = if (dragging) controller.offset else placement.value
                            val scale = if (reduced || inset) 1f else 1f + 0.02f * lift
                            scaleX = scale
                            scaleY = scale
                        }
                        .drawBehind {
                            if (!hideLine) {
                                val stroke = 1.dp.toPx()
                                val inset = 16.dp.toPx()
                                val start = if (layoutDirection == LayoutDirection.Rtl) 0f else inset
                                drawRect(colors.separator, Offset(start, 0f), Size(size.width - inset, stroke))
                            }
                        }
                        .semantics { customActions = actions },
                ) {
                    CompositionLocalProvider(
                        LocalReorderHandle provides ReorderHandleTarget(controller, itemKey),
                        LocalReorderLift provides lift,
                    ) {
                        ReorderListItemScope(itemKey, index, dragging).item(itemKey)
                    }
                }
            }
        }
    }
}

@Composable
fun ReorderListItem(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    val colors = EsuissTheme.colors
    val lift = LocalReorderLift.current
    val shape = if (LocalItemGroupVariant.current == ItemGroupVariant.Inset) RoundedCornerShape(Radius.xl2) else RectangleShape
    val shadow = Shadows.lg
    Row(
        modifier = modifier
            .fillMaxWidth()
            .then(
                if (lift > 0f) {
                    Modifier
                        .shadow(shadow.copy(color = shadow.color.copy(alpha = shadow.color.alpha * lift)), shape)
                        .background(colors.surfaceRaised.copy(alpha = lift), shape)
                } else {
                    Modifier
                },
            )
            .heightIn(min = 52.dp)
            .padding(start = 16.dp, end = 4.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        CompositionLocalProvider(
            LocalContentStyle provides Typography.base.copy(color = colors.label),
            LocalContentColor provides colors.label,
        ) {
            content()
        }
    }
}

@Composable
fun ReorderListHandle(
    modifier: Modifier = Modifier,
    contentDescription: String = "Reorder",
) {
    val colors = EsuissTheme.colors
    val target = LocalReorderHandle.current ?: return
    val controller = target.controller
    val itemKey = target.key
    val state = rememberDraggableState { delta -> controller.drag(delta) }
    Box(
        modifier = modifier
            .size(44.dp)
            .draggable(
                state = state,
                orientation = Orientation.Vertical,
                startDragImmediately = true,
                onDragStarted = { controller.start(itemKey) },
                onDragStopped = { controller.end() },
            )
            .semantics { this.contentDescription = contentDescription },
        contentAlignment = Alignment.Center,
    ) {
        Icon(PhosphorIcons.Regular.DotsSixVertical, contentDescription = null, size = 20.dp, tint = colors.labelTertiary)
    }
}
```

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

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.Colors
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

enum class ButtonVariant { Default, Outline, Secondary, Tinted, Ghost, Plain, Destructive, Link }

enum class ButtonSize(
    val height: Dp,
    val horizontalPadding: Dp,
    val spacing: Dp,
    val iconSize: Dp,
    val blockRadius: Dp,
    val isIcon: Boolean,
) {
    Default(36.dp, 16.dp, 6.dp, 16.dp, Radius.md, false),
    Xs(24.dp, 11.dp, 4.dp, 12.dp, Radius.sm, false),
    Sm(32.dp, 12.dp, 4.dp, 16.dp, Radius.md, false),
    Lg(44.dp, 22.dp, 6.dp, 16.dp, Radius.lg, false),
    Xl(56.dp, 31.dp, 8.dp, 16.dp, Radius.xl, false),
    Icon(36.dp, 0.dp, 6.dp, 16.dp, Radius.md, true),
    IconXs(24.dp, 0.dp, 4.dp, 12.dp, Radius.sm, true),
    IconSm(32.dp, 0.dp, 4.dp, 16.dp, Radius.md, true),
    IconLg(44.dp, 0.dp, 6.dp, 16.dp, Radius.lg, true),
    IconXl(56.dp, 0.dp, 8.dp, 16.dp, Radius.xl, true),
    ;

    val textStyle: TextStyle
        get() = when (this) {
            Xs, IconXs -> Typography.xs2
            Lg, Xl -> Typography.base
            else -> Typography.sm
        }
}

@Composable
fun Button(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    variant: ButtonVariant = ButtonVariant.Default,
    size: ButtonSize = ButtonSize.Default,
    block: Boolean = false,
    enabled: Boolean = true,
    content: @Composable RowScope.() -> Unit,
) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    val foreground = buttonForeground(variant, colors, enabled)
    val group = LocalButtonGroup.current?.takeIf { variant != ButtonVariant.Ghost && variant != ButtonVariant.Plain }
    RegisterButtonGroupOutline(group, variant == ButtonVariant.Outline)
    val shape = group.itemShape(if (block) RoundedCornerShape(size.blockRadius) else CircleShape)
    val sizing = when {
        block -> Modifier.fillMaxWidth().height(size.height)
        size.isIcon -> Modifier.size(size.height)
        else -> Modifier.height(size.height)
    }

    Row(
        modifier = modifier
            .then(sizing)
            .clip(shape)
            .background(buttonBackground(variant, colors, pressed && enabled, enabled), shape)
            .then(
                when {
                    variant != ButtonVariant.Outline -> Modifier
                    group != null -> Modifier.buttonGroupEdge(group, colors.separator)
                    else -> Modifier.border(1.dp, colors.separator, shape)
                },
            )
            .clickable(
                interactionSource = interaction,
                indication = null,
                enabled = enabled,
                role = Role.Button,
                onClick = onClick,
            )
            .padding(horizontal = size.horizontalPadding),
        horizontalArrangement = Arrangement.spacedBy(size.spacing, Alignment.CenterHorizontally),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        CompositionLocalProvider(
            LocalButtonGroup provides null,
            LocalContentStyle provides size.textStyle.copy(
                color = foreground,
                textDecoration = if (variant == ButtonVariant.Link && pressed && enabled) {
                    TextDecoration.Underline
                } else {
                    null
                },
            ),
            LocalContentColor provides foreground,
            LocalIconSize provides size.iconSize,
        ) {
            content()
        }
    }
}

@Composable
fun Button(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    variant: ButtonVariant = ButtonVariant.Default,
    size: ButtonSize = ButtonSize.Default,
    block: Boolean = false,
    enabled: Boolean = true,
) {
    Button(onClick, modifier, variant, size, block, enabled) {
        BasicText(text, style = LocalContentStyle.current, maxLines = 1)
    }
}

private fun buttonForeground(variant: ButtonVariant, colors: Colors, enabled: Boolean): Color =
    when (variant) {
        ButtonVariant.Default -> colors.onAccent
        ButtonVariant.Outline, ButtonVariant.Secondary, ButtonVariant.Ghost ->
            if (enabled) colors.label else colors.labelQuaternary
        ButtonVariant.Tinted, ButtonVariant.Plain ->
            if (enabled) colors.link else colors.link.copy(alpha = 0.4f)
        ButtonVariant.Destructive ->
            if (enabled) colors.danger else colors.danger.copy(alpha = 0.4f)
        ButtonVariant.Link -> if (enabled) colors.link else colors.labelQuaternary
    }

private fun buttonBackground(variant: ButtonVariant, colors: Colors, pressed: Boolean, enabled: Boolean): Color =
    when (variant) {
        ButtonVariant.Default -> when {
            !enabled -> colors.accentDisabled
            pressed -> colors.accentPressed
            else -> colors.accent
        }
        ButtonVariant.Outline -> when {
            pressed -> colors.itemPressed
            colors.isDark -> Color.Transparent
            else -> colors.surface
        }
        ButtonVariant.Secondary -> when {
            !enabled -> colors.controlDisabled
            pressed -> colors.controlPressed
            else -> colors.control
        }
        ButtonVariant.Tinted -> if (pressed) colors.accentSurfacePressed else colors.accentSurface
        ButtonVariant.Ghost -> if (pressed) colors.itemPressed else Color.Transparent
        ButtonVariant.Plain -> if (pressed) colors.itemPressed else Color.Transparent
        ButtonVariant.Destructive -> if (pressed) colors.dangerSurfacePressed else colors.dangerSurface
        ButtonVariant.Link -> Color.Transparent
    }
```

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

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
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.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.semantics.isTraversalGroup
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Constraints
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.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

enum class ButtonGroupOrientation { Horizontal, Vertical }

@Stable
internal class ButtonGroupState(val orientation: ButtonGroupOrientation) {
    var nested by mutableIntStateOf(0)
    var outlined by mutableIntStateOf(0)
}

internal val LocalButtonGroup = compositionLocalOf<ButtonGroupState?> { null }

internal object ButtonGroupFill

private object ButtonGroupDivider

internal fun ButtonGroupState?.itemShape(default: Shape): Shape = if (this == null) default else RectangleShape

@Immutable
internal class ButtonGroupItem(val shape: Shape, val modifier: Modifier)

@Composable
internal fun rememberButtonGroupItem(group: ButtonGroupState?, default: Shape): ButtonGroupItem {
    var edges by remember { mutableIntStateOf(0) }
    val horizontal = group?.orientation != ButtonGroupOrientation.Vertical
    val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl
    val shape = remember(edges, horizontal) {
        val round = if (horizontal) CornerSize(50) else CornerSize(Radius.xl2)
        val square = CornerSize(0)
        val start = if (edges and 1 != 0) round else square
        val end = if (edges and 2 != 0) round else square
        if (horizontal) {
            RoundedCornerShape(topStart = start, topEnd = end, bottomEnd = end, bottomStart = start)
        } else {
            RoundedCornerShape(topStart = start, topEnd = start, bottomEnd = end, bottomStart = end)
        }
    }
    if (group == null || group.nested > 0) return ButtonGroupItem(default, Modifier)
    return ButtonGroupItem(
        shape = shape,
        modifier = Modifier.onPlaced { coordinates ->
            val parent = coordinates.parentLayoutCoordinates ?: return@onPlaced
            val bounds = parent.localBoundingBoxOf(coordinates, clipBounds = false)
            val first: Boolean
            val last: Boolean
            if (horizontal) {
                val left = bounds.left <= 0.5f
                val right = bounds.right >= parent.size.width - 0.5f
                first = if (rtl) right else left
                last = if (rtl) left else right
            } else {
                first = bounds.top <= 0.5f
                last = bounds.bottom >= parent.size.height - 0.5f
            }
            edges = (if (first) 1 else 0) or (if (last) 2 else 0)
        },
    )
}

internal fun Modifier.buttonGroupEdge(group: ButtonGroupState?, color: Color): Modifier {
    if (group == null) return this
    return drawBehind {
        val stroke = 1.dp.toPx()
        if (group.orientation == ButtonGroupOrientation.Horizontal) {
            val x = if (layoutDirection == LayoutDirection.Rtl) 0f else size.width - stroke
            drawRect(color, Offset(x, 0f), Size(stroke, size.height))
        } else {
            drawRect(color, Offset(0f, size.height - stroke), Size(size.width, stroke))
        }
    }
}

@Composable
internal fun RegisterButtonGroupOutline(group: ButtonGroupState?, outlined: Boolean) {
    DisposableEffect(group, outlined) {
        if (group != null && outlined) group.outlined += 1
        onDispose {
            if (group != null && outlined) group.outlined -= 1
        }
    }
}

@Composable
fun ButtonGroup(
    modifier: Modifier = Modifier,
    orientation: ButtonGroupOrientation = ButtonGroupOrientation.Horizontal,
    content: @Composable () -> Unit,
) {
    val parent = LocalButtonGroup.current
    DisposableEffect(parent) {
        parent?.let { it.nested += 1 }
        onDispose { parent?.let { it.nested -= 1 } }
    }
    val state = remember(orientation) { ButtonGroupState(orientation) }
    val colors = EsuissTheme.colors
    val joined = state.nested == 0
    val horizontal = orientation == ButtonGroupOrientation.Horizontal
    val shape = if (horizontal) CircleShape else RoundedCornerShape(Radius.xl2)
    val outline = colors.separator
    Layout(
        content = {
            CompositionLocalProvider(LocalButtonGroup provides state, content = content)
        },
        modifier = modifier
            .semantics { isTraversalGroup = true }
            .then(
                if (joined) {
                    Modifier
                        .clip(shape)
                        .drawWithContent {
                            drawContent()
                            if (state.outlined > 0) {
                                val stroke = 1.dp.toPx()
                                val inset = stroke / 2
                                val path = shape.createOutline(
                                    Size(size.width - stroke, size.height - stroke),
                                    layoutDirection,
                                    this,
                                )
                                translate(inset, inset) {
                                    drawOutline(path, outline, style = Stroke(stroke))
                                }
                            }
                        }
                } else {
                    Modifier
                },
            ),
    ) { measurables, constraints ->
        val gap = if (joined) 0 else 8.dp.roundToPx()
        val items = measurables.filter { it.layoutId != ButtonGroupDivider }
        if (horizontal) {
            val height = if (constraints.hasFixedHeight) {
                constraints.maxHeight
            } else {
                constraints.constrainHeight(items.maxOfOrNull { it.maxIntrinsicHeight(Constraints.Infinity) } ?: 0)
            }
            val fills = measurables.count { it.layoutId == ButtonGroupFill }
            val placeables = arrayOfNulls<Placeable>(measurables.size)
            var used = 0
            measurables.forEachIndexed { index, measurable ->
                if (measurable.layoutId != ButtonGroupFill) {
                    val placeable = measurable.measure(Constraints(minHeight = height, maxHeight = height))
                    placeables[index] = placeable
                    used += placeable.width
                }
            }
            val gaps = gap * (items.size - 1).coerceAtLeast(0)
            val remaining = if (constraints.hasBoundedWidth) {
                (constraints.maxWidth - used - gaps).coerceAtLeast(0)
            } else {
                0
            }
            measurables.forEachIndexed { index, measurable ->
                if (measurable.layoutId == ButtonGroupFill) {
                    val placeable = if (constraints.hasBoundedWidth) {
                        val width = remaining / fills
                        measurable.measure(Constraints(width, width, height, height))
                    } else {
                        measurable.measure(Constraints(minHeight = height, maxHeight = height))
                    }
                    placeables[index] = placeable
                    used += placeable.width
                }
            }
            val width = constraints.constrainWidth(used + gaps)
            layout(width, height) {
                var x = 0
                measurables.forEachIndexed { index, measurable ->
                    val placeable = placeables[index] ?: return@forEachIndexed
                    val divider = measurable.layoutId == ButtonGroupDivider
                    placeable.placeRelative(x, 0, zIndex = if (divider) 1f else 0f)
                    if (!divider) x += placeable.width + gap
                }
            }
        } else {
            val width = if (constraints.hasFixedWidth) {
                constraints.maxWidth
            } else {
                constraints.constrainWidth(items.maxOfOrNull { it.maxIntrinsicWidth(Constraints.Infinity) } ?: 0)
            }
            val placeables = measurables.map { it.measure(Constraints(minWidth = width, maxWidth = width)) }
            val gaps = gap * (items.size - 1).coerceAtLeast(0)
            val height = constraints.constrainHeight(
                placeables.filterIndexed { index, _ -> measurables[index].layoutId != ButtonGroupDivider }.sumOf { it.height } + gaps,
            )
            layout(width, height) {
                var y = 0
                measurables.forEachIndexed { index, measurable ->
                    val divider = measurable.layoutId == ButtonGroupDivider
                    placeables[index].placeRelative(0, y, zIndex = if (divider) 1f else 0f)
                    if (!divider) y += placeables[index].height + gap
                }
            }
        }
    }
}

@Composable
fun ButtonGroupText(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    val colors = EsuissTheme.colors
    val shape = LocalButtonGroup.current.itemShape(CircleShape)
    Row(
        modifier = modifier
            .clip(shape)
            .background(colors.control, shape)
            .padding(horizontal = 10.dp),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        CompositionLocalProvider(
            LocalButtonGroup provides null,
            LocalContentStyle provides Typography.sm.copy(color = colors.label),
            LocalContentColor provides colors.label,
            LocalIconSize provides 16.dp,
        ) {
            content()
        }
    }
}

@Composable
fun ButtonGroupSeparator(
    modifier: Modifier = Modifier,
    orientation: Orientation = Orientation.Vertical,
    color: Color = Color.Unspecified,
) {
    val line = color.takeOrElse { EsuissTheme.colors.label.copy(alpha = 0.2f) }
    Box(
        modifier = modifier
            .layoutId(ButtonGroupDivider)
            .then(
                if (orientation == Orientation.Vertical) {
                    Modifier.layout { measurable, constraints ->
                        val placeable = measurable.measure(constraints.copy(minWidth = 0, maxWidth = 0))
                        layout(0, placeable.height) { placeable.place(0, 0) }
                    }
                } else {
                    Modifier.layout { measurable, constraints ->
                        val placeable = measurable.measure(constraints.copy(minHeight = 0, maxHeight = 0))
                        layout(placeable.width, 0) { placeable.place(0, 0) }
                    }
                },
            )
            .drawBehind {
                val stroke = 1.dp.toPx()
                val inset = 9.dp.toPx()
                if (orientation == Orientation.Vertical) {
                    val x = if (layoutDirection == LayoutDirection.Rtl) -stroke else 0f
                    drawRect(line, Offset(x, inset), Size(stroke, (size.height - inset * 2).coerceAtLeast(0f)))
                } else {
                    drawRect(line, Offset(inset, 0f), Size((size.width - inset * 2).coerceAtLeast(0f), stroke))
                }
            },
    )
}
```

```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/Header.kt"
package com.esuiss.ui.components

import androidx.compose.animation.core.animate
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.regular.CaretLeft
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

private val HeaderBarHeight = 44.dp

private enum class HeaderSlot { Back, Start, End, Title, LargeTitle }

enum class HeaderActionsSide { Leading, Trailing }

@Stable
class HeaderState {
    internal var range by mutableFloatStateOf(0f)
    internal var offset by mutableFloatStateOf(0f)

    val collapsedFraction: Float
        get() = if (range <= 0f) 1f else (offset / range).coerceIn(0f, 1f)

    val nestedScrollConnection: NestedScrollConnection = object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            if (available.y >= 0f || range <= 0f) return Offset.Zero
            val next = (offset - available.y).coerceAtMost(range)
            val used = next - offset
            offset = next
            return Offset(0f, -used)
        }

        override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
            if (available.y <= 0f || range <= 0f) return Offset.Zero
            val next = (offset - available.y).coerceAtLeast(0f)
            val used = offset - next
            offset = next
            return Offset(0f, used)
        }

        override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
            settle()
            return Velocity.Zero
        }
    }

    internal suspend fun settle() {
        if (range <= 0f || offset <= 0f || offset >= range) return
        val target = if (offset < range / 2f) 0f else range
        animate(offset, target, animationSpec = tween(250)) { value, _ -> offset = value }
    }
}

@Composable
fun rememberHeaderState(): HeaderState = remember { HeaderState() }

private val LocalHeaderState = staticCompositionLocalOf<HeaderState?> { null }

@Composable
fun Header(
    modifier: Modifier = Modifier,
    state: HeaderState = rememberHeaderState(),
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    val collapsed = state.range > 0f && state.offset >= state.range
    val separator by animateFloatAsState(if (state.range <= 0f || collapsed) 1f else 0f, tween(150), label = "separator")
    CompositionLocalProvider(LocalHeaderState provides state) {
        Layout(
            content = content,
            modifier = modifier
                .clipToBounds()
                .drawWithContent {
                    drawContent()
                    val stroke = 1.dp.toPx()
                    drawRect(colors.separator.copy(alpha = colors.separator.alpha * separator), Offset(0f, size.height - stroke), Size(size.width, stroke))
                },
        ) { measurables, constraints ->
            val width = constraints.maxWidth
            val bar = HeaderBarHeight.roundToPx()
            val inset = 8.dp.roundToPx()
            val loose = Constraints(maxWidth = width, maxHeight = bar)
            val back = measurables.firstOrNull { it.layoutId == HeaderSlot.Back }?.measure(loose)
            val start = measurables.firstOrNull { it.layoutId == HeaderSlot.Start }?.measure(loose)
            val end = measurables.firstOrNull { it.layoutId == HeaderSlot.End }?.measure(loose)
            val leading = (back?.width ?: 0) + (start?.width ?: 0)
            val side = maxOf(leading, end?.width ?: 0) + inset
            val titleWidth = (width - side * 2).coerceAtLeast(0)
            val title = measurables.firstOrNull { it.layoutId == HeaderSlot.Title }
                ?.measure(Constraints(maxWidth = titleWidth, maxHeight = bar))
            val large = measurables.firstOrNull { it.layoutId == HeaderSlot.LargeTitle }
                ?.measure(Constraints(minWidth = width, maxWidth = width))
            val range = (large?.height ?: 0).toFloat()
            if (state.range != range) state.range = range
            val offset = state.offset.coerceIn(0f, range).toInt()
            val height = bar + (large?.height ?: 0) - offset
            layout(width, height) {
                var x = inset
                back?.let {
                    it.placeRelative(x, (bar - it.height) / 2)
                    x += it.width
                }
                start?.placeRelative(x, (bar - (start.height)) / 2)
                end?.let { it.placeRelative(width - inset - it.width, (bar - it.height) / 2) }
                title?.placeRelative((width - title.width) / 2, (bar - title.height) / 2)
                large?.placeRelative(0, bar - offset)
            }
        }
    }
}

@Composable
fun HeaderTitle(
    text: String,
    modifier: Modifier = Modifier,
    subtitle: String? = null,
) {
    val colors = EsuissTheme.colors
    val state = LocalHeaderState.current
    Column(
        modifier = modifier
            .layoutId(HeaderSlot.Title)
            .graphicsLayer {
                val fraction = state?.collapsedFraction ?: 1f
                alpha = if (state == null || state.range <= 0f) 1f else ((fraction - 0.6f) / 0.4f).coerceIn(0f, 1f)
            }
            .semantics { heading() },
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        BasicText(
            text,
            style = Typography.base.copy(color = colors.label, fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        if (subtitle != null) {
            BasicText(
                subtitle,
                style = Typography.xs2.copy(color = colors.labelSecondary, textAlign = TextAlign.Center),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}

@Composable
fun HeaderLargeTitle(
    text: String,
    modifier: Modifier = Modifier,
    subtitle: String? = null,
) {
    val colors = EsuissTheme.colors
    val state = LocalHeaderState.current
    Column(
        modifier = modifier
            .layoutId(HeaderSlot.LargeTitle)
            .graphicsLayer {
                val fraction = state?.collapsedFraction ?: 0f
                alpha = (1f - fraction * 1.4f).coerceIn(0f, 1f)
            }
            .padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 8.dp),
        verticalArrangement = Arrangement.spacedBy(2.dp),
    ) {
        BasicText(
            text,
            modifier = Modifier.semantics { heading() },
            style = Typography.xl3.copy(color = colors.label, fontWeight = FontWeight.Bold),
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
        if (subtitle != null) {
            BasicText(subtitle, style = Typography.sm.copy(color = colors.labelSecondary))
        }
    }
}

@Composable
fun HeaderBack(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    text: String? = "Back",
    contentDescription: String = text ?: "Back",
) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    Row(
        modifier = modifier
            .layoutId(HeaderSlot.Back)
            .height(HeaderBarHeight)
            .clickable(
                interactionSource = interaction,
                indication = null,
                role = Role.Button,
                onClickLabel = contentDescription,
                onClick = onClick,
            )
            .graphicsLayer { alpha = if (pressed) 0.4f else 1f }
            .padding(end = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(2.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Icon(PhosphorIcons.Regular.CaretLeft, contentDescription = if (text == null) contentDescription else null, size = 24.dp, tint = colors.link)
        if (text != null) {
            BasicText(text, style = Typography.base.copy(color = colors.link), maxLines = 1)
        }
    }
}

@Composable
fun HeaderActions(
    modifier: Modifier = Modifier,
    side: HeaderActionsSide = HeaderActionsSide.Trailing,
    content: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = modifier.layoutId(if (side == HeaderActionsSide.Leading) HeaderSlot.Start else HeaderSlot.End),
        horizontalArrangement = Arrangement.spacedBy(4.dp),
        verticalAlignment = Alignment.CenterVertically,
        content = content,
    )
}
```

```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),
    )
}
```

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

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.combinedClickable
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.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.isTraversalGroup
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

enum class ItemVariant { Default, Outline, Muted }

enum class ItemSize(
    internal val horizontalPadding: Dp,
    internal val verticalPadding: Dp,
    internal val gap: Dp,
    internal val contentGap: Dp,
    internal val imageSize: Dp,
) {
    Default(16.dp, 14.dp, 14.dp, 4.dp, 40.dp),
    Sm(14.dp, 12.dp, 14.dp, 4.dp, 32.dp),
    Xs(12.dp, 10.dp, 10.dp, 2.dp, 24.dp),
}

enum class ItemGroupVariant { Default, Inset }

enum class ItemMediaVariant { Default, Icon, Image }

private enum class ItemSlot { Media, Content, Actions, Header, Footer }

@Stable
private class ItemState(val size: ItemSize) {
    var descriptions by mutableIntStateOf(0)
}

private val LocalItemState = staticCompositionLocalOf<ItemState?> { null }

internal val LocalItemGroupVariant = staticCompositionLocalOf<ItemGroupVariant?> { null }

@Composable
fun ItemGroup(
    modifier: Modifier = Modifier,
    variant: ItemGroupVariant = ItemGroupVariant.Default,
    content: @Composable ColumnScope.() -> Unit,
) {
    val colors = EsuissTheme.colors
    val inset = variant == ItemGroupVariant.Inset
    val shape = RoundedCornerShape(Radius.xl2)
    Column(
        modifier = modifier
            .fillMaxWidth()
            .then(if (inset) Modifier.clip(shape).background(colors.surfaceSecondary, shape) else Modifier)
            .semantics { isTraversalGroup = true },
        verticalArrangement = if (inset) Arrangement.Top else Arrangement.spacedBy(16.dp),
    ) {
        CompositionLocalProvider(LocalItemGroupVariant provides variant) {
            content()
        }
    }
}

@Composable
fun ItemSeparator(modifier: Modifier = Modifier) {
    val inset = LocalItemGroupVariant.current == ItemGroupVariant.Inset
    Box(
        modifier = modifier
            .fillMaxWidth()
            .padding(start = if (inset) 16.dp else 0.dp)
            .padding(vertical = if (inset) 0.dp else 8.dp)
            .height(1.dp)
            .background(EsuissTheme.colors.separator),
    )
}

@Composable
fun Item(
    modifier: Modifier = Modifier,
    variant: ItemVariant = ItemVariant.Default,
    size: ItemSize = ItemSize.Default,
    onClick: (() -> Unit)? = null,
    onLongClick: (() -> Unit)? = null,
    enabled: Boolean = true,
    selected: Boolean? = null,
    role: Role? = Role.Button,
    onClickLabel: String? = null,
    content: @Composable () -> Unit,
) {
    val inset = LocalItemGroupVariant.current == ItemGroupVariant.Inset
    val shape = if (inset) RectangleShape else RoundedCornerShape(Radius.xl)
    ItemFrame(
        modifier = modifier,
        variant = variant,
        size = size,
        shape = shape,
        padding = PaddingValues(horizontal = size.horizontalPadding, vertical = size.verticalPadding),
        onClick = onClick,
        onLongClick = onLongClick,
        enabled = enabled,
        selected = selected,
        role = role,
        onClickLabel = onClickLabel,
        content = content,
    )
}

@Composable
internal fun ItemFrame(
    modifier: Modifier,
    variant: ItemVariant,
    size: ItemSize,
    shape: Shape,
    padding: PaddingValues,
    onClick: (() -> Unit)?,
    onLongClick: (() -> Unit)?,
    enabled: Boolean,
    selected: Boolean?,
    role: Role?,
    onClickLabel: String?,
    minHeight: Dp = 0.dp,
    gap: Dp = size.gap,
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    val interaction = remember { MutableInteractionSource() }
    val pressed by interaction.collectIsPressedAsState()
    val state = remember(size) { ItemState(size) }
    val interactive = onClick != null || onLongClick != null
    val background = when {
        pressed && enabled && interactive -> colors.itemPressed
        selected == true -> colors.itemSelected
        variant == ItemVariant.Muted -> colors.surfaceSecondary.copy(alpha = colors.surfaceSecondary.alpha * 0.5f)
        else -> Color.Transparent
    }
    val foreground = if (enabled) colors.label else colors.labelQuaternary
    val behaviour = if (interactive) {
        Modifier
            .heightIn(min = maxOf(minHeight, 48.dp))
            .combinedClickable(
                interactionSource = interaction,
                indication = null,
                enabled = enabled,
                onClickLabel = onClickLabel,
                role = role,
                onLongClick = onLongClick,
                onClick = onClick ?: {},
            )
    } else {
        Modifier
            .heightIn(min = minHeight)
            .semantics(mergeDescendants = true) {}
    }
    Box(
        modifier = modifier
            .fillMaxWidth()
            .clip(shape)
            .background(background, shape)
            .then(if (variant == ItemVariant.Outline) Modifier.border(1.dp, colors.separator, shape) else Modifier)
            .then(if (selected != null) Modifier.semantics { this.selected = selected } else Modifier)
            .then(behaviour)
            .padding(padding),
        contentAlignment = Alignment.CenterStart,
    ) {
        CompositionLocalProvider(
            LocalItemState provides state,
            LocalContentStyle provides Typography.base.copy(color = foreground),
            LocalContentColor provides foreground,
            LocalIconSize provides 16.dp,
        ) {
            ItemLayout(gap, state.descriptions > 0, content)
        }
    }
}

@Composable
private fun ItemLayout(gap: Dp, mediaAtTop: Boolean, content: @Composable () -> Unit) {
    Layout(content = content, modifier = Modifier.fillMaxWidth()) { measurables, constraints ->
        val gapPx = gap.roundToPx()
        val nudge = if (mediaAtTop) 2.dp.roundToPx() else 0
        val lines = mutableListOf<List<Measurable>>()
        var current = mutableListOf<Measurable>()
        measurables.forEach { measurable ->
            val slot = measurable.layoutId
            if (slot == ItemSlot.Header || slot == ItemSlot.Footer) {
                if (current.isNotEmpty()) lines += current
                lines += listOf(measurable)
                current = mutableListOf()
            } else {
                current += measurable
            }
        }
        if (current.isNotEmpty()) lines += current
        val bounded = constraints.hasBoundedWidth
        val available = if (bounded) constraints.maxWidth else Constraints.Infinity
        val measured = lines.map { line ->
            val placeables = arrayOfNulls<Placeable>(line.size)
            val flexIndex = line.indexOfFirst { it.layoutId == ItemSlot.Content }
            var used = gapPx * (line.size - 1).coerceAtLeast(0)
            line.forEachIndexed { index, measurable ->
                if (index == flexIndex) return@forEachIndexed
                val full = measurable.layoutId == ItemSlot.Header || measurable.layoutId == ItemSlot.Footer
                val childConstraints = when {
                    full && bounded -> Constraints(minWidth = available, maxWidth = available)
                    bounded -> Constraints(maxWidth = (available - used).coerceAtLeast(0))
                    else -> Constraints()
                }
                val placeable = measurable.measure(childConstraints)
                placeables[index] = placeable
                used += placeable.width
            }
            if (flexIndex >= 0) {
                val remaining = (available - used).coerceAtLeast(0)
                placeables[flexIndex] = line[flexIndex].measure(
                    if (bounded) Constraints(minWidth = remaining, maxWidth = remaining) else Constraints(),
                )
            }
            placeables.requireNoNulls().toList()
        }
        val width = if (bounded) {
            constraints.maxWidth
        } else {
            measured.maxOfOrNull { line -> line.sumOf { it.width } + gapPx * (line.size - 1).coerceAtLeast(0) } ?: 0
        }
        val lineHeights = measured.mapIndexed { lineIndex, line ->
            line.mapIndexed { index, placeable ->
                val isMedia = lines[lineIndex][index].layoutId == ItemSlot.Media
                placeable.height + if (isMedia) nudge else 0
            }.maxOrNull() ?: 0
        }
        val height = (lineHeights.sum() + gapPx * (measured.size - 1).coerceAtLeast(0))
            .coerceIn(constraints.minHeight, constraints.maxHeight)
        layout(width, height) {
            var y = 0
            measured.forEachIndexed { lineIndex, line ->
                val lineHeight = lineHeights[lineIndex]
                var x = 0
                line.forEachIndexed { index, placeable ->
                    val isMedia = lines[lineIndex][index].layoutId == ItemSlot.Media
                    val top = if (isMedia && mediaAtTop) nudge else (lineHeight - placeable.height) / 2
                    placeable.placeRelative(x, y + top)
                    x += placeable.width + gapPx
                }
                y += lineHeight + gapPx
            }
        }
    }
}

@Composable
fun ItemMedia(
    modifier: Modifier = Modifier,
    variant: ItemMediaVariant = ItemMediaVariant.Default,
    content: @Composable BoxScope.() -> Unit,
) {
    val size = LocalItemState.current?.size ?: ItemSize.Default
    val sizing = when (variant) {
        ItemMediaVariant.Image -> {
            val shape = RoundedCornerShape(if (size == ItemSize.Xs) Radius.sm else Radius.md)
            Modifier.size(size.imageSize).clip(shape)
        }
        else -> Modifier
    }
    Box(
        modifier = modifier.layoutId(ItemSlot.Media).then(sizing),
        contentAlignment = Alignment.Center,
    ) {
        CompositionLocalProvider(LocalIconSize provides if (variant == ItemMediaVariant.Icon) 16.dp else LocalIconSize.current) {
            content()
        }
    }
}

@Composable
fun ItemContent(
    modifier: Modifier = Modifier,
    content: @Composable ColumnScope.() -> Unit,
) {
    val size = LocalItemState.current?.size ?: ItemSize.Default
    Column(
        modifier = modifier.layoutId(ItemSlot.Content),
        verticalArrangement = Arrangement.spacedBy(size.contentGap),
        content = content,
    )
}

@Composable
fun ItemTitle(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    val color = LocalContentColor.current
    Row(
        modifier = modifier,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        CompositionLocalProvider(
            LocalContentStyle provides Typography.base.copy(color = color, fontWeight = FontWeight.SemiBold),
        ) {
            content()
        }
    }
}

@Composable
fun ItemTitle(text: String, modifier: Modifier = Modifier) {
    val color = LocalContentColor.current
    BasicText(
        text,
        modifier = modifier,
        style = Typography.base.copy(color = color, fontWeight = FontWeight.SemiBold),
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )
}

@Composable
fun ItemDescription(text: String, modifier: Modifier = Modifier) {
    val state = LocalItemState.current
    if (state != null) {
        DisposableEffect(state) {
            state.descriptions += 1
            onDispose { state.descriptions -= 1 }
        }
    }
    BasicText(
        text,
        modifier = modifier,
        style = Typography.sm.copy(color = EsuissTheme.colors.labelSecondary),
        maxLines = 2,
        overflow = TextOverflow.Ellipsis,
    )
}

@Composable
fun ItemActions(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = modifier.layoutId(ItemSlot.Actions),
        horizontalArrangement = Arrangement.spacedBy(8.dp),
        verticalAlignment = Alignment.CenterVertically,
        content = content,
    )
}

@Composable
fun ItemHeader(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = modifier.layoutId(ItemSlot.Header),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        content = content,
    )
}

@Composable
fun ItemFooter(
    modifier: Modifier = Modifier,
    content: @Composable RowScope.() -> Unit,
) {
    Row(
        modifier = modifier.layoutId(ItemSlot.Footer),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        content = content,
    )
}
```

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

## Usage

```tsx
import { ReorderList, ReorderListItem, ReorderListHandle } from "@/components/interactions/reorder-list"
```

```tsx
<ReorderDemo />
```

`ReorderList` is controlled: pass `value` as an array of item keys and update it in `onValueChange`. Give each `ReorderListItem` a `value` matching its key, and place a `ReorderListHandle` anywhere inside it, at the start or end. Place the list inside an `ItemGroup` with the `inset` variant for a rounded group; the lifted row then keeps the group's shape.

Only the handle starts a drag, so the rest of the row can still be pressed or scrolled.

## Examples

### Inset

Rows inside an inset `ItemGroup`.

![Preview](https://uim.suiss.app/previews/interactions-reorder-list--inset.light.webp)

```tsx
import * as React from "react"
import { View } from "react-native"
import { ReorderList, ReorderListHandle, ReorderListItem } from "@/components/interactions/reorder-list"
import { ItemGroup } from "@/components/ui/item"
import { Text } from "@/components/ui/text"

const tasks: Record<string, { title: string; detail?: string }> = {
  inbox: { title: "Inbox", detail: "12 messages" },
  today: { title: "Today" },
  upcoming: { title: "Upcoming", detail: "Next 7 days" },
  someday: { title: "Someday" },
  archive: {
    title: "Archive",
    detail: "Everything you finished, kept for later reference",
  },
}

const initialOrder = Object.keys(tasks)

function renderRows(value: string[]) {
  return value.map((key) => {
    const task = tasks[key]
    return (
      <ReorderListItem key={key} value={key} className="ps-4">
        <View className="min-w-0 flex-1 py-3">
          <Text numberOfLines={1}>{task.title}</Text>
          {task.detail ? (
            <Text className="text-sm text-label-secondary">{task.detail}</Text>
          ) : null}
        </View>
        <ReorderListHandle accessibilityLabel={`Reorder ${task.title}`} />
      </ReorderListItem>
    )
  })
}

function ReorderDemo({ inset = false }: { inset?: boolean }) {
  const [value, setValue] = React.useState(initialOrder)
  return (
    <View className="gap-3">
      {inset ? (
        <ItemGroup variant="inset">
          <ReorderList value={value} onValueChange={setValue}>
            {renderRows(value)}
          </ReorderList>
        </ItemGroup>
      ) : (
        <ReorderList value={value} onValueChange={setValue}>
          {renderRows(value)}
        </ReorderList>
      )}
      <Text role="status" className="text-sm text-label-secondary">
        {value.map((key) => tasks[key].title).join(", ")}
      </Text>
    </View>
  )
}

export function ReorderListInsetExample() {
  return (
    <ReorderDemo inset />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct ReorderListInsetExample: View {
  var body: some View {
    ReorderListDemo(inset: true)
  }
}

struct ReorderListTask {
  let title: String
  var detail: String?
}

let reorderListTasks: [String: ReorderListTask] = [
  "inbox": ReorderListTask(title: "Inbox", detail: "12 messages"),
  "today": ReorderListTask(title: "Today"),
  "upcoming": ReorderListTask(title: "Upcoming", detail: "Next 7 days"),
  "someday": ReorderListTask(title: "Someday"),
  "archive": ReorderListTask(title: "Archive", detail: "Everything you finished, kept for later reference"),
]

let reorderListOrder = ["inbox", "today", "upcoming", "someday", "archive"]

struct ReorderListDemo: View {
  var inset = false

  @State private var value = reorderListOrder

  var body: some View {
    VStack(alignment: .leading, spacing: 12) {
      list
      Text(verbatim: value.compactMap { reorderListTasks[$0]?.title }.joined(separator: ", "))
        .textStyle(.sm)
        .foregroundStyle(Color.labelSecondary)
        .accessibilityAddTraits(.updatesFrequently)
    }
  }

  @ViewBuilder
  var list: some View {
    if inset {
      ItemGroup(.inset) {
        rows
      }
    } else {
      rows
    }
  }

  var rows: some View {
    ReorderList($value) { key in
      if let task = reorderListTasks[key] {
        VStack(alignment: .leading, spacing: 0) {
          Text(verbatim: task.title)
            .textStyle(.base)
            .foregroundStyle(Color.label)
            .lineLimit(1)
          if let detail = task.detail {
            Text(verbatim: detail)
              .textStyle(.sm)
              .foregroundStyle(Color.labelSecondary)
          }
        }
        .padding(.vertical, 12)
      }
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.ItemGroup
import com.esuiss.ui.components.ItemGroupVariant
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.ReorderList
import com.esuiss.ui.interactions.ReorderListHandle
import com.esuiss.ui.interactions.ReorderListItem
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

@Composable
fun ReorderListInsetExample() {
    ReorderListDemo(inset = true)
}

class ReorderListTask(val title: String, val detail: String? = null)

val reorderListTasks = linkedMapOf(
    "inbox" to ReorderListTask("Inbox", "12 messages"),
    "today" to ReorderListTask("Today"),
    "upcoming" to ReorderListTask("Upcoming", "Next 7 days"),
    "someday" to ReorderListTask("Someday"),
    "archive" to ReorderListTask("Archive", "Everything you finished, kept for later reference"),
)

val reorderListInitial = reorderListTasks.keys.toList()

@Composable
fun ReorderListDemo(inset: Boolean) {
    val colors = EsuissTheme.colors
    var value by rememberSaveable { mutableStateOf(reorderListInitial) }
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        val list = @Composable {
            ReorderList(
                value = value,
                onValueChange = { value = it },
            ) { key ->
                val task = reorderListTasks.getValue(key)
                ReorderListItem {
                    Column(Modifier.weight(1f).padding(vertical = 12.dp)) {
                        Text(task.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
                        if (task.detail != null) {
                            Text(task.detail, style = Typography.sm.copy(color = colors.labelSecondary))
                        }
                    }
                    ReorderListHandle(contentDescription = "Reorder ${task.title}")
                }
            }
        }
        if (inset) ItemGroup(variant = ItemGroupVariant.Inset) { list() } else list()
        Text(
            value.joinToString(", ") { reorderListTasks.getValue(it).title },
            modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite },
            style = Typography.sm.copy(color = colors.labelSecondary),
        )
    }
}
```

### Leading handle

Places the handle at the start of each row.

![Preview](https://uim.suiss.app/previews/interactions-reorder-list--leading-handle.light.webp)

```tsx
import * as React from "react"
import { ReorderList, ReorderListHandle, ReorderListItem } from "@/components/interactions/reorder-list"
import { Text } from "@/components/ui/text"

const tasks: Record<string, { title: string; detail?: string }> = {
  inbox: { title: "Inbox", detail: "12 messages" },
  today: { title: "Today" },
  upcoming: { title: "Upcoming", detail: "Next 7 days" },
  someday: { title: "Someday" },
  archive: {
    title: "Archive",
    detail: "Everything you finished, kept for later reference",
  },
}

const initialOrder = Object.keys(tasks)

function LeadingHandleDemo() {
  const [value, setValue] = React.useState(initialOrder)
  return (
    <ReorderList
      value={value}
      onValueChange={setValue}
      moveUpLabel="Move earlier"
      moveDownLabel="Move later"
    >
      {value.map((key) => (
        <ReorderListItem key={key} value={key} className="pe-4">
          <ReorderListHandle
            accessibilityLabel={`Reorder ${tasks[key].title}`}
          />
          <Text numberOfLines={1} className="flex-1 py-3">
            {tasks[key].title}
          </Text>
        </ReorderListItem>
      ))}
    </ReorderList>
  )
}

export function ReorderListLeadingHandleExample() {
  return (
    <LeadingHandleDemo />
  )
}
```

```kotlin
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.ReorderList
import com.esuiss.ui.interactions.ReorderListHandle
import com.esuiss.ui.interactions.ReorderListItem

class ReorderListTask(val title: String, val detail: String? = null)

val reorderListTasks = linkedMapOf(
    "inbox" to ReorderListTask("Inbox", "12 messages"),
    "today" to ReorderListTask("Today"),
    "upcoming" to ReorderListTask("Upcoming", "Next 7 days"),
    "someday" to ReorderListTask("Someday"),
    "archive" to ReorderListTask("Archive", "Everything you finished, kept for later reference"),
)

val reorderListInitial = reorderListTasks.keys.toList()

@Composable
fun ReorderListLeadingHandle() {
    var value by rememberSaveable { mutableStateOf(reorderListInitial) }
    ReorderList(
        value = value,
        onValueChange = { value = it },
        moveUpLabel = "Move earlier",
        moveDownLabel = "Move later",
    ) { key ->
        val task = reorderListTasks.getValue(key)
        ReorderListItem(Modifier.padding(end = 12.dp)) {
            ReorderListHandle(contentDescription = "Reorder ${task.title}")
            Text(
                task.title,
                modifier = Modifier.weight(1f).padding(vertical = 12.dp),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}
```

## API Reference

### ReorderList

The root that renders items in `value` order.

### ReorderListItem

One row, keyed by its `value`.

### ReorderListHandle

The grip that starts a drag.

## Accessibility

- The handle has the `button` role and offers `moveUp` and `moveDown` accessibility actions, so screen reader users can reorder without dragging.
- Move up is omitted on the first row and move down on the last.

## Notes

- Haptics play when the drag starts (medium impact), each time the target slot changes (selection) and on release (light impact), if the app provides an adapter through `HapticsProvider`.
- The dragged row shows a `bg-surface-raised` layer with a shadow, rounded inside an inset group.
- The lift scale is skipped inside an inset group and when reduce motion is on; springs respect the system reduce motion setting.
