# Pull To Refresh

Adds pull to refresh to a scroll view or list, with a minimum spinner time and a light haptic.

Pull To Refresh 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/pull-to-refresh

![Preview](https://uim.suiss.app/previews/interactions-pull-to-refresh--default.light.webp)

```tsx
import * as React from "react"
import { View } from "react-native"
import { PullToRefresh } from "@/components/interactions/pull-to-refresh"
import { Item, ItemContent, ItemDescription, ItemGroup, ItemSeparator, ItemTitle } from "@/components/ui/item"
import { Text } from "@/components/ui/text"

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function Feed() {
  const [count, setCount] = React.useState(3)
  return (
    <PullToRefresh
      onRefresh={async () => {
        await wait(1200)
        setCount((current) => current + 1)
      }}
      contentContainerClassName="gap-3"
    >
      <Text className="text-sm text-label-secondary">Pull down to refresh</Text>
      <ItemGroup variant="inset">
        {Array.from({ length: count }, (_, index) => count - index).map(
          (update, index) => (
            <React.Fragment key={update}>
              {index > 0 ? <ItemSeparator /> : null}
              <Item>
                <ItemContent>
                  <ItemTitle>Update {update}</ItemTitle>
                  <ItemDescription>Fetched from the server</ItemDescription>
                </ItemContent>
              </Item>
            </React.Fragment>
          )
        )}
      </ItemGroup>
    </PullToRefresh>
  )
}

export function PullToRefreshExample() {
  return (
    <View className="flex-1">
      <Feed />
    </View>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct PullToRefreshFeed: View {
  @State private var count = 3

  var body: some View {
    PullToRefresh {
      try? await Task.sleep(for: .milliseconds(1200))
      count += 1
    } content: {
      VStack(alignment: .leading, spacing: 12) {
        Text("Pull down to refresh")
          .textStyle(.sm)
          .foregroundStyle(Color.labelSecondary)
        ItemGroup(.inset) {
          ForEach(Array((1...count).reversed()), id: \.self) { update in
            if update != count {
              ItemSeparator()
            }
            Item {
              ItemContent {
                ItemTitle(verbatim: "Update \(update)")
                ItemDescription("Fetched from the server")
              }
            }
          }
        }
      }
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Item
import com.esuiss.ui.components.ItemContent
import com.esuiss.ui.components.ItemDescription
import com.esuiss.ui.components.ItemGroup
import com.esuiss.ui.components.ItemGroupVariant
import com.esuiss.ui.components.ItemSeparator
import com.esuiss.ui.components.ItemTitle
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.PullToRefresh
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay

val pullToRefreshViewport = Modifier.fillMaxWidth().height(600.dp)

@Composable
fun PullToRefreshFeed() {
    var count by rememberSaveable { mutableIntStateOf(3) }
    PullToRefresh(
        onRefresh = {
            delay(1200)
            count += 1
        },
        modifier = pullToRefreshViewport,
    ) {
        Column(
            modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text("Pull down to refresh", style = Typography.sm.copy(color = EsuissTheme.colors.labelSecondary))
            ItemGroup(variant = ItemGroupVariant.Inset) {
                (count downTo 1).forEachIndexed { index, update ->
                    key(update) {
                        if (index > 0) ItemSeparator()
                        Item {
                            ItemContent {
                                ItemTitle("Update $update")
                                ItemDescription("Fetched from the server")
                            }
                        }
                    }
                }
            }
        }
    }
}
```

`PullToRefresh` is a `ScrollView` with a native `RefreshControl`. Pulling down past the top starts a refresh: a light impact haptic plays, the spinner shows, and `onRefresh` runs.

The spinner stays for at least 600 ms, even when `onRefresh` resolves sooner, so it does not flicker. It also hides if `onRefresh` throws or rejects. Use `PullToRefreshControl` to add the same behavior to a `FlatList` or `SectionList`.

## Installation

```bash title="Terminal"
npx @esuiss/uim@latest add pull-to-refresh
```

```bash title="Terminal"
npx @esuiss/uim@latest add pull-to-refresh --platform swift
```

```bash title="Terminal"
npx @esuiss/uim@latest add pull-to-refresh --platform kotlin
```

### Manual

**Uniwind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn uniwind
```

2. Add the pieces it builds on: the primitives `components/primitives/haptics.tsx`.

3. Copy the source into `components/interactions/pull-to-refresh.tsx`:

```tsx title="uniwind/components/interactions/pull-to-refresh.tsx"
import { cn } from "cn"
import * as React from "react"
import {
  type ColorValue,
  RefreshControl,
  type RefreshControlProps,
  ScrollView,
} from "react-native"
import { withUniwind } from "uniwind"
import { useHaptics } from "@/components/primitives/haptics"

const MIN_REFRESH = 600

type RefreshHandler = () => Promise<unknown> | unknown

function useRefresh(onRefresh: RefreshHandler) {
  const [refreshing, setRefreshing] = React.useState(false)
  const onRefreshRef = React.useRef(onRefresh)
  const mountedRef = React.useRef(true)
  const haptics = useHaptics()

  React.useEffect(() => {
    onRefreshRef.current = onRefresh
  }, [onRefresh])

  React.useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  const refresh = React.useCallback(async () => {
    haptics.impact("light")
    setRefreshing(true)
    const started = Date.now()
    await Promise.allSettled([
      new Promise((resolve) => resolve(onRefreshRef.current())),
    ])
    const elapsed = Date.now() - started
    await new Promise((resolve) =>
      setTimeout(resolve, Math.max(0, MIN_REFRESH - elapsed))
    )
    if (mountedRef.current) setRefreshing(false)
  }, [haptics])

  return { refreshing, refresh }
}

function RefreshIndicator({
  color,
  ...props
}: RefreshControlProps & { color?: ColorValue }) {
  return (
    <RefreshControl
      tintColor={color}
      colors={color ? [color] : undefined}
      {...props}
    />
  )
}

const StyledRefreshIndicator = withUniwind(RefreshIndicator)

function PullToRefreshControl({
  onRefresh,
  refreshing: refreshingProp,
  ...props
}: Omit<RefreshControlProps, "onRefresh" | "refreshing"> & {
  onRefresh: RefreshHandler
  refreshing?: boolean
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <StyledRefreshIndicator
      colorClassName="accent-label-secondary"
      progressBackgroundColorClassName="accent-surface-raised"
      accessibilityLabel={refreshing ? "Refreshing" : undefined}
      refreshing={refreshingProp ?? refreshing}
      onRefresh={refresh}
      {...props}
    />
  )
}

function PullToRefresh({
  onRefresh,
  className,
  children,
  ...props
}: React.ComponentProps<typeof ScrollView> & {
  onRefresh: RefreshHandler
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <ScrollView
      accessibilityState={{ busy: refreshing }}
      className={cn("flex-1", className)}
      refreshControl={
        <StyledRefreshIndicator
          colorClassName="accent-label-secondary"
          progressBackgroundColorClassName="accent-surface-raised"
          refreshing={refreshing}
          onRefresh={refresh}
        />
      }
      {...props}
    >
      {children}
    </ScrollView>
  )
}

export { PullToRefresh, PullToRefreshControl }
```

4. Update the import paths to match your project.

**NativeWind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn nativewind
```

2. Add the pieces it builds on: the primitives `components/primitives/haptics.tsx`.

3. Copy the source into `components/interactions/pull-to-refresh.tsx`:

```tsx title="nativewind/components/interactions/pull-to-refresh.tsx"
import { cn } from "cn"
import { cssInterop } from "nativewind"
import * as React from "react"
import {
  type ColorValue,
  RefreshControl,
  type RefreshControlProps,
  ScrollView,
} from "react-native"
import { useHaptics } from "@/components/primitives/haptics"

const MIN_REFRESH = 600

type RefreshHandler = () => Promise<unknown> | unknown

function useRefresh(onRefresh: RefreshHandler) {
  const [refreshing, setRefreshing] = React.useState(false)
  const onRefreshRef = React.useRef(onRefresh)
  const mountedRef = React.useRef(true)
  const haptics = useHaptics()

  React.useEffect(() => {
    onRefreshRef.current = onRefresh
  }, [onRefresh])

  React.useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  const refresh = React.useCallback(async () => {
    haptics.impact("light")
    setRefreshing(true)
    const started = Date.now()
    await Promise.allSettled([
      new Promise((resolve) => resolve(onRefreshRef.current())),
    ])
    const elapsed = Date.now() - started
    await new Promise((resolve) =>
      setTimeout(resolve, Math.max(0, MIN_REFRESH - elapsed))
    )
    if (mountedRef.current) setRefreshing(false)
  }, [haptics])

  return { refreshing, refresh }
}

function RefreshIndicator({
  color,
  ...props
}: RefreshControlProps & { color?: ColorValue }) {
  return (
    <RefreshControl
      tintColor={color}
      colors={color ? [color] : undefined}
      {...props}
    />
  )
}

const StyledRefreshIndicator = cssInterop(RefreshIndicator, {
  colorClassName: { target: false, nativeStyleToProp: { color: true } },
  progressBackgroundColorClassName: {
    target: false,
    nativeStyleToProp: { color: "progressBackgroundColor" },
  },
})

function PullToRefreshControl({
  onRefresh,
  refreshing: refreshingProp,
  ...props
}: Omit<RefreshControlProps, "onRefresh" | "refreshing"> & {
  onRefresh: RefreshHandler
  refreshing?: boolean
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <StyledRefreshIndicator
      colorClassName="text-label-secondary"
      progressBackgroundColorClassName="text-surface-raised"
      accessibilityLabel={refreshing ? "Refreshing" : undefined}
      refreshing={refreshingProp ?? refreshing}
      onRefresh={refresh}
      {...props}
    />
  )
}

function PullToRefresh({
  onRefresh,
  className,
  children,
  ...props
}: React.ComponentProps<typeof ScrollView> & {
  onRefresh: RefreshHandler
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <ScrollView
      accessibilityState={{ busy: refreshing }}
      className={cn("flex-1", className)}
      refreshControl={
        <StyledRefreshIndicator
          colorClassName="text-label-secondary"
          progressBackgroundColorClassName="text-surface-raised"
          refreshing={refreshing}
          onRefresh={refresh}
        />
      }
      {...props}
    >
      {children}
    </ScrollView>
  )
}

export { PullToRefresh, PullToRefreshControl }
```

4. Update the import paths to match your project.

**StyleSheet**

1. Add the pieces it builds on: the primitives `components/primitives/haptics.tsx`.

2. Copy the source into `components/interactions/pull-to-refresh.tsx`:

```tsx title="stylesheet/components/interactions/pull-to-refresh.tsx"
import * as React from "react"
import {
  RefreshControl,
  type RefreshControlProps,
  ScrollView,
} from "react-native"
import { useHaptics } from "@/components/primitives/haptics"
import { useTheme } from "@/components/ui/theme"

const MIN_REFRESH = 600

type RefreshHandler = () => Promise<unknown> | unknown

function useRefresh(onRefresh: RefreshHandler) {
  const [refreshing, setRefreshing] = React.useState(false)
  const onRefreshRef = React.useRef(onRefresh)
  const mountedRef = React.useRef(true)
  const haptics = useHaptics()

  React.useEffect(() => {
    onRefreshRef.current = onRefresh
  }, [onRefresh])

  React.useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  const refresh = React.useCallback(async () => {
    haptics.impact("light")
    setRefreshing(true)
    const started = Date.now()
    await Promise.allSettled([
      new Promise((resolve) => resolve(onRefreshRef.current())),
    ])
    const elapsed = Date.now() - started
    await new Promise((resolve) =>
      setTimeout(resolve, Math.max(0, MIN_REFRESH - elapsed))
    )
    if (mountedRef.current) setRefreshing(false)
  }, [haptics])

  return { refreshing, refresh }
}

function RefreshIndicator(props: RefreshControlProps) {
  const { colors } = useTheme()
  return (
    <RefreshControl
      tintColor={colors.labelSecondary}
      colors={[colors.labelSecondary]}
      progressBackgroundColor={colors.surfaceRaised}
      {...props}
    />
  )
}

function PullToRefreshControl({
  onRefresh,
  refreshing: refreshingProp,
  ...props
}: Omit<RefreshControlProps, "onRefresh" | "refreshing"> & {
  onRefresh: RefreshHandler
  refreshing?: boolean
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <RefreshIndicator
      accessibilityLabel={refreshing ? "Refreshing" : undefined}
      refreshing={refreshingProp ?? refreshing}
      onRefresh={refresh}
      {...props}
    />
  )
}

function PullToRefresh({
  onRefresh,
  style,
  children,
  ...props
}: React.ComponentProps<typeof ScrollView> & {
  onRefresh: RefreshHandler
}) {
  const { refreshing, refresh } = useRefresh(onRefresh)
  return (
    <ScrollView
      accessibilityState={{ busy: refreshing }}
      style={[{ flex: 1 }, style]}
      refreshControl={
        <RefreshIndicator refreshing={refreshing} onRefresh={refresh} />
      }
      {...props}
    >
      {children}
    </ScrollView>
  )
}

export { PullToRefresh, PullToRefreshControl }
```

3. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Copy the theme files every view uses:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3. Copy the source and every file it uses:

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

public struct PullToRefresh<Content: View>: View {
  let onRefresh: @MainActor @Sendable () async -> Void
  let content: Content

  @State private var refreshing = false

  public init(
    onRefresh: @escaping @MainActor @Sendable () async -> Void,
    @ViewBuilder content: () -> Content
  ) {
    self.onRefresh = onRefresh
    self.content = content()
  }

  public var body: some View {
    let onRefresh = onRefresh
    ScrollView {
      content
        .frame(maxWidth: .infinity, alignment: .top)
        .tint(Color.accent)
    }
    .pullToRefresh(onRefresh)
    .tint(Color.labelSecondary)
    .accessibilityAction(named: Text("Refresh")) {
      guard !refreshing else { return }
      refreshing = true
      Task { @MainActor in
        await PullToRefreshTiming.run(onRefresh)
        refreshing = false
      }
    }
  }
}

enum PullToRefreshTiming {
  static let minimum: Duration = .milliseconds(600)

  @MainActor
  static func run(_ action: @MainActor @Sendable () async -> Void) async {
    let clock = ContinuousClock()
    let started = clock.now
    await action()
    let elapsed = clock.now - started
    if elapsed < minimum {
      try? await Task.sleep(for: minimum - elapsed)
    }
  }
}

private struct PullToRefreshModifier: ViewModifier {
  let action: @MainActor @Sendable () async -> Void

  @State private var triggers = 0

  func body(content: Content) -> some View {
    let action = action
    let triggers = $triggers
    content
      .refreshable { @MainActor in
        triggers.wrappedValue += 1
        await PullToRefreshTiming.run(action)
      }
      .hapticFeedback(.impact(weight: .light), trigger: triggers.wrappedValue)
  }
}

extension View {
  public func pullToRefresh(_ action: @escaping @MainActor @Sendable () async -> Void) -> some View {
    modifier(PullToRefreshModifier(action: action))
  }
}
```

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

extension EnvironmentValues {
  @Entry public var hapticsEnabled = true
}

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

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

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

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

  @Environment(\.hapticsEnabled) private var enabled

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

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

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

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

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

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

  @State private var count = 0

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

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

4. Add the files to your app target.

**Jetpack Compose**

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

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

2. Copy the theme files every view uses:

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

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

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

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

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

val LocalColors = staticCompositionLocalOf { LightColors }

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

    val typography: Typography
        get() = Typography

    val radius: Radius
        get() = Radius

    val shadows: Shadows
        get() = Shadows
}

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

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

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

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

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

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

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

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

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

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

3. Copy the source and every file it uses:

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

import androidx.compose.animation.core.animate
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.FormEasing
import com.esuiss.ui.components.Spinner
import com.esuiss.ui.components.SpinnerSpokes
import com.esuiss.ui.components.drawSpinnerSpokes
import com.esuiss.ui.components.formReducedMotion
import com.esuiss.ui.components.rememberHaptics
import com.esuiss.ui.theme.EsuissTheme
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.exp
import kotlin.math.roundToInt

enum class PullToRefreshPhase { Idle, Pulling, Refreshing, Settling }

private val PullThreshold = 64.dp
private val PullHold = 52.dp
private val PullMax = 128.dp
private const val MinRefreshMillis = 600L
private const val SettleMillis = 400

@Composable
fun PullToRefresh(
    onRefresh: suspend () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    refreshLabel: String = "Refresh",
    content: @Composable () -> Unit,
) {
    val scope = rememberCoroutineScope()
    val refresh by rememberUpdatedState(onRefresh)
    var refreshing by remember { mutableStateOf(false) }
    PullToRefresh(
        refreshing = refreshing,
        onRefresh = {
            if (!refreshing) {
                refreshing = true
                scope.launch {
                    try {
                        refresh()
                    } finally {
                        refreshing = false
                    }
                }
            }
        },
        modifier = modifier,
        enabled = enabled,
        refreshLabel = refreshLabel,
        content = content,
    )
}

@Composable
fun PullToRefresh(
    refreshing: Boolean,
    onRefresh: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    refreshLabel: String = "Refresh",
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    val density = LocalDensity.current
    val haptics by rememberUpdatedState(rememberHaptics())
    val reduced = formReducedMotion()
    val scope = rememberCoroutineScope()
    val thresholdPx = with(density) { PullThreshold.toPx() }
    val holdPx = with(density) { PullHold.toPx() }
    val maxPx = with(density) { PullMax.toPx() }
    val trigger by rememberUpdatedState(onRefresh)
    var pull by remember { mutableFloatStateOf(0f) }
    var raw by remember { mutableFloatStateOf(0f) }
    var phase by remember { mutableStateOf(PullToRefreshPhase.Idle) }
    var requested by remember { mutableStateOf(false) }
    val active = refreshing || requested

    suspend fun animatePull(target: Float, millis: Int) {
        if (reduced) {
            pull = target
        } else {
            animate(pull, target, animationSpec = tween(millis, easing = FormEasing)) { value, _ -> pull = value }
        }
    }

    LaunchedEffect(active) {
        if (active) {
            phase = PullToRefreshPhase.Refreshing
            animatePull(holdPx, SettleMillis)
            if (requested) {
                delay(MinRefreshMillis)
                requested = false
            }
        } else if (phase == PullToRefreshPhase.Refreshing) {
            phase = PullToRefreshPhase.Settling
            animatePull(0f, SettleMillis)
            phase = PullToRefreshPhase.Idle
        }
    }

    fun resist(distance: Float): Float = maxPx * (1f - exp(-distance / (maxPx * 1.6f)))

    fun release() {
        raw = 0f
        if (pull >= thresholdPx) {
            haptics.perform(HapticFeedbackType.Confirm)
            requested = true
            trigger()
        } else {
            scope.launch {
                animatePull(0f, SettleMillis)
                if (phase == PullToRefreshPhase.Pulling) phase = PullToRefreshPhase.Idle
            }
        }
    }

    fun pullTo(distance: Float) {
        raw = distance.coerceAtLeast(0f)
        pull = resist(raw)
    }

    val connection = remember(enabled) {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                if (source != NestedScrollSource.UserInput || phase != PullToRefreshPhase.Pulling || available.y >= 0f) return Offset.Zero
                val before = raw
                pullTo(raw + available.y)
                return Offset(0f, raw - before)
            }

            override fun onPostScroll(consumed: Offset, available: Offset, source: NestedScrollSource): Offset {
                if (!enabled || source != NestedScrollSource.UserInput || available.y <= 0f) return Offset.Zero
                if (phase != PullToRefreshPhase.Idle && phase != PullToRefreshPhase.Pulling) return Offset.Zero
                phase = PullToRefreshPhase.Pulling
                pullTo(raw + available.y)
                return Offset(0f, available.y)
            }

            override suspend fun onPreFling(available: Velocity): Velocity {
                if (phase != PullToRefreshPhase.Pulling) return Velocity.Zero
                release()
                return available
            }
        }
    }

    val spinning = phase == PullToRefreshPhase.Refreshing || phase == PullToRefreshPhase.Settling
    val settleScale by animateFloatAsState(
        targetValue = if (phase == PullToRefreshPhase.Settling) 0f else 1f,
        animationSpec = tween(if (reduced) 0 else 300),
        label = "settle",
    )
    val refreshAction = remember(refreshLabel) {
        listOf(
            CustomAccessibilityAction(refreshLabel) {
                if (!refreshing && !requested) {
                    requested = true
                    trigger()
                }
                true
            },
        )
    }
    Box(
        modifier = modifier
            .clipToBounds()
            .nestedScroll(connection)
            .semantics { if (enabled) customActions = refreshAction },
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .clipToBounds()
                .layout { measurable, constraints ->
                    val height = pull.roundToInt().coerceAtLeast(0)
                    val placeable = measurable.measure(constraints.copy(minHeight = 0, maxHeight = Constraints.Infinity))
                    layout(placeable.width, height) {
                        placeable.place(0, (height - placeable.height) / 2)
                    }
                },
            contentAlignment = Alignment.Center,
        ) {
            if (spinning) {
                Spinner(
                    modifier = Modifier.graphicsLayer {
                        val scale = 0.5f + 0.5f * settleScale
                        scaleX = scale
                        scaleY = scale
                        alpha = settleScale
                    },
                    size = 24.dp,
                    color = colors.labelSecondary,
                    contentDescription = "Refreshing",
                )
            } else {
                val tint = colors.labelSecondary
                Canvas(modifier = Modifier.size(24.dp).clearAndSetSemantics {}) {
                    val progress = (pull / thresholdPx).coerceIn(0f, 1f)
                    drawSpinnerSpokes(tint) { index -> progress * SpinnerSpokes - index }
                }
            }
        }
        Box(modifier = Modifier.offset { IntOffset(0, pull.roundToInt()) }) {
            content()
        }
    }
}
```

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

import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.takeOrElse
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.EsuissTheme
import kotlin.math.floor

internal const val SpinnerSpokes = 8

internal fun spinnerSpokeOpacity(index: Int): Float = 0.2f + 0.8f * index / (SpinnerSpokes - 1)

internal fun DrawScope.drawSpinnerSpokes(color: Color, rotation: Float = 0f, opacity: (Int) -> Float) {
    val unit = size.minDimension / 24f
    val center = Offset(size.width / 2f, size.height / 2f)
    rotate(rotation, center) {
        for (index in 0 until SpinnerSpokes) {
            val alpha = opacity(index).coerceIn(0f, 1f)
            if (alpha <= 0f) continue
            rotate(index * 360f / SpinnerSpokes, center) {
                drawRoundRect(
                    color = color,
                    topLeft = Offset(center.x - 1.56f * unit, center.y - 11.5f * unit),
                    size = Size(3.12f * unit, 7.2f * unit),
                    cornerRadius = CornerRadius(1.56f * unit),
                    alpha = alpha * color.alpha,
                )
            }
        }
    }
}

@Composable
fun Spinner(
    modifier: Modifier = Modifier,
    size: Dp = 16.dp,
    color: Color = Color.Unspecified,
    contentDescription: String = "Loading",
) {
    val tint = color.takeOrElse { LocalContentColor.current.takeOrElse { EsuissTheme.colors.label } }
    val reduced = formReducedMotion()
    val step: State<Float> = if (reduced) {
        remember { mutableFloatStateOf(0f) }
    } else {
        rememberInfiniteTransition(label = "spinner").animateFloat(
            initialValue = 0f,
            targetValue = SpinnerSpokes.toFloat(),
            animationSpec = infiniteRepeatable(tween(800, easing = LinearEasing), RepeatMode.Restart),
            label = "step",
        )
    }
    Canvas(
        modifier = modifier
            .size(size)
            .semantics {
                this.contentDescription = contentDescription
                progressBarRangeInfo = ProgressBarRangeInfo.Indeterminate
                liveRegion = LiveRegionMode.Polite
            },
    ) {
        val rotation = (floor(step.value) % SpinnerSpokes) * 360f / SpinnerSpokes
        drawSpinnerSpokes(tint, rotation) { spinnerSpokeOpacity(it) }
    }
}
```

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

## Usage

```tsx
import { PullToRefreshControl, PullToRefresh } from "@/components/interactions/pull-to-refresh"
```

```tsx
<View className="flex-1">
  <Feed />
</View>
```

Pass an `onRefresh` that returns a promise, or nothing for synchronous work. All other `ScrollView` props pass through to `PullToRefresh`.

For lists, pass `<PullToRefreshControl onRefresh={...} />` as the list's `refreshControl`. It manages its own refreshing state; pass `refreshing` to override it. Other `RefreshControl` props pass through.

## Examples

### With flat list

Uses `PullToRefreshControl` as the `refreshControl` of a `FlatList`.

![Preview](https://uim.suiss.app/previews/interactions-pull-to-refresh--with-flat-list.light.webp)

```tsx
import { FlatList } from "react-native"
import { PullToRefreshControl } from "@/components/interactions/pull-to-refresh"
import { Text } from "@/components/ui/text"

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export function PullToRefreshWithFlatListExample() {
  return (
    <FlatList
      data={["Inbox", "Drafts", "Sent", "Archive"]}
      keyExtractor={(item) => item}
      refreshControl={<PullToRefreshControl onRefresh={() => wait(1000)} />}
      renderItem={({ item }) => <Text className="py-3 text-base">{item}</Text>}
    />
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct PullToRefreshWithFlatListExample: View {
  var body: some View {
    ScrollView {
      LazyVStack(alignment: .leading, spacing: 0) {
        ForEach(["Inbox", "Drafts", "Sent", "Archive"], id: \.self) { item in
          Text(verbatim: item)
            .textStyle(.base)
            .foregroundStyle(Color.label)
            .padding(.vertical, 12)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
      }
    }
    .pullToRefresh {
      try? await Task.sleep(for: .milliseconds(1000))
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.key
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.PullToRefresh
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay

val pullToRefreshViewport = Modifier.fillMaxWidth().height(600.dp)

@Composable
fun PullToRefreshFlatList() {
    PullToRefresh(onRefresh = { delay(1000) }, modifier = pullToRefreshViewport) {
        LazyColumn(Modifier.fillMaxSize()) {
            items(listOf("Inbox", "Drafts", "Sent", "Archive"), key = { it }) { item ->
                Text(item, modifier = Modifier.padding(vertical = 12.dp), style = Typography.base)
            }
        }
    }
}
```

## API Reference

### PullToRefreshControl

A `RefreshControl` for any list or scroll view.

### PullToRefresh

A `ScrollView` with built-in pull to refresh.

## Accessibility

- `PullToRefresh` exposes a `busy` state while refreshing.
- `PullToRefreshControl` is labelled `Refreshing` while active.

## Notes

- The haptic plays only if the app provides an adapter through `HapticsProvider`.
- The spinner uses the `label-secondary` color, and on Android its background uses `surface-raised`, so both follow light and dark mode.
