# Widget

A rounded card in the style of home screen widgets, with fixed sizes and optional drag-to-resize.

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

Source: https://ui.suiss.app/docs/components/widget

**React**

**Example**

```tsx
import { SunIcon } from "@phosphor-icons/react"
import {
  Widget,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

export default function WidgetDemo() {
  return (
    <Widget size="small" align="start">
      <WidgetHeader>
        <WidgetIcon>
          <SunIcon className="fill-current" />
        </WidgetIcon>
        <WidgetTitle>Istanbul</WidgetTitle>
      </WidgetHeader>
      <WidgetContent>
        <WidgetValue>24°</WidgetValue>
        <WidgetDescription>Partly cloudy</WidgetDescription>
      </WidgetContent>
      <WidgetFooter>H 27° · L 18°</WidgetFooter>
    </Widget>
  )
}
```

`Widget` is a rounded `muted` card that comes in four sizes: `small` (168 × 168), `medium` (352 × 168), `large` (352 × 352) and `extra-large` (720 × 352), or `auto` to fill its parent. Compose it from `WidgetHeader`, which holds a `WidgetIcon`, `WidgetTitle` and an optional `WidgetAction`, followed by `WidgetValue`, `WidgetDescription`, `WidgetContent` and a `WidgetFooter` pinned to the bottom.

With `resizable`, a corner handle lets people drag the widget to another size. While dragging, a dashed outline previews the size it will snap to on release. Use widgets for glanceable summaries on a dashboard; for general grouped content, use `Card`.

## Installation

### CLI

```bash title="Terminal"
npx shadcn@latest add @esuiss/widget
```

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

```bash title="Terminal"
npx @esuiss/ui@latest add widget
```

### Manual

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

2. Copy the source into `components/ui/widget.tsx`:

```tsx title="components/ui/widget.tsx"
"use client"

import * as React from "react"
import { cn } from "@/lib/utils"

type WidgetSize = "small" | "medium" | "large" | "extra-large"

const WIDGET_DIMENSIONS: Record<WidgetSize, [number, number]> = {
  small: [168, 168],
  medium: [352, 168],
  large: [352, 352],
  "extra-large": [720, 352],
}

function nearestSize(width: number, height: number, sizes: WidgetSize[]) {
  let best: WidgetSize | null = null
  let bestDistance = Number.POSITIVE_INFINITY
  for (const size of sizes) {
    const [w, h] = WIDGET_DIMENSIONS[size]
    const distance = (width - w) ** 2 + (height - h) ** 2
    if (distance < bestDistance) {
      best = size
      bestDistance = distance
    }
  }
  return best
}

function availableWidth(container: HTMLElement | null) {
  const parent = container?.parentElement
  if (!parent?.clientWidth) return Number.POSITIVE_INFINITY
  const { paddingInlineStart, paddingInlineEnd } = getComputedStyle(parent)
  return (
    parent.clientWidth -
    Number.parseFloat(paddingInlineStart) -
    Number.parseFloat(paddingInlineEnd)
  )
}

function sizesThatFit(sizes: WidgetSize[], room: number) {
  const fitting = sizes.filter((size) => WIDGET_DIMENSIONS[size][0] <= room)
  if (fitting.length > 0) return fitting
  const narrowest = sizes.reduce((best, size) =>
    WIDGET_DIMENSIONS[size][0] < WIDGET_DIMENSIONS[best][0] ? size : best
  )
  return [narrowest]
}

function WidgetHandle({
  placement,
  onPointerDown,
  onDoubleClick,
}: {
  placement: "inside" | "outside"
  onPointerDown: (event: React.PointerEvent<HTMLSpanElement>) => void
  onDoubleClick: () => void
}) {
  return (
    <span
      aria-hidden="true"
      data-slot="widget-handle"
      data-placement={placement}
      onPointerDown={onPointerDown}
      onDoubleClick={onDoubleClick}
      className="group/widget-handle absolute cursor-nwse-resize touch-none after:absolute after:-inset-3 after:content-[''] data-[placement=inside]:inset-e-0 data-[placement=inside]:bottom-0 data-[placement=inside]:size-7 data-[placement=outside]:-inset-e-1.5 data-[placement=outside]:-bottom-1.5 data-[placement=outside]:size-8.5 rtl:-scale-x-100 rtl:cursor-nesw-resize"
    >
      <svg
        aria-hidden
        viewBox={placement === "inside" ? "0 0 28 28" : "0 0 34 34"}
        fill="none"
        strokeWidth="4"
        strokeLinecap="round"
        className="pointer-events-none size-full overflow-visible stroke-border opacity-0 transition-[stroke,opacity] duration-200 group-hover/widget-handle:stroke-primary group-hover/widget-handle:opacity-100 group-data-dragging/widget-handle:stroke-primary group-data-dragging/widget-handle:opacity-100 pointer-coarse:opacity-100"
      >
        <path
          d={
            placement === "inside"
              ? "M19.9 9.3A22 22 0 0 1 9.3 19.9"
              : "M29.9 13.9A33 33 0 0 1 13.9 29.9"
          }
        />
      </svg>
    </span>
  )
}

function Widget({
  className,
  size,
  defaultSize,
  onSizeChange,
  sizes = ["small", "medium", "large", "extra-large"],
  resizable = false,
  handle = "outside",
  align = "start",
  style,
  ref,
  ...props
}: React.ComponentProps<"div"> & {
  size?: WidgetSize | "auto"
  defaultSize?: WidgetSize | "auto"
  onSizeChange?: (size: WidgetSize | "auto") => void
  sizes?: WidgetSize[]
  resizable?: boolean | "free"
  handle?: "inside" | "outside"
  align?: "start" | "center"
}) {
  const initialSize = defaultSize ?? (resizable ? "small" : "auto")
  const [uncontrolledSize, setUncontrolledSize] = React.useState(initialSize)
  const [freeSize, setFreeSize] = React.useState<[number, number] | null>(null)
  const [preview, setPreview] = React.useState<WidgetSize | null>(null)
  const widgetRef = React.useRef<HTMLDivElement>(null)
  const current = size ?? uncontrolledSize

  const select = (next: WidgetSize | "auto") => {
    if (size === undefined) setUncontrolledSize(next)
    onSizeChange?.(next)
  }

  const startResize = (event: React.PointerEvent<HTMLSpanElement>) => {
    const widget = widgetRef.current
    if (!widget || event.button !== 0) return
    event.preventDefault()
    const handle = event.currentTarget
    handle.setPointerCapture(event.pointerId)
    handle.dataset.dragging = ""
    widget.dataset.resizing = resizable === "free" ? "free" : "snap"
    const direction = getComputedStyle(widget).direction === "rtl" ? -1 : 1
    const startX = event.clientX
    const startY = event.clientY
    const startWidth = widget.offsetWidth
    const startHeight = widget.offsetHeight
    const [minWidth, minHeight] = WIDGET_DIMENSIONS.small
    const free = resizable === "free"
    const room = availableWidth(widget.parentElement)
    const reachable = sizesThatFit(sizes, room)
    const bounds = free ? sizes : reachable
    const maxWidth = Math.max(
      ...bounds.map((item) => WIDGET_DIMENSIONS[item][0])
    )
    const maxHeight = Math.max(
      ...bounds.map((item) => WIDGET_DIMENSIONS[item][1])
    )
    let last: WidgetSize | null = null
    const move = (moveEvent: PointerEvent) => {
      const width = startWidth + (moveEvent.clientX - startX) * direction
      const height = startHeight + moveEvent.clientY - startY
      const stretch = free ? 0 : 48
      setFreeSize([
        Math.max(minWidth, Math.min(maxWidth + stretch, room, width)),
        Math.max(minHeight, Math.min(maxHeight + stretch, height)),
      ])
      if (free) return
      const next = nearestSize(width, height, reachable)
      if (next !== last) {
        last = next
        setPreview(next)
      }
    }
    const end = () => {
      delete handle.dataset.dragging
      delete widget.dataset.resizing
      handle.removeEventListener("pointermove", move)
      handle.removeEventListener("pointerup", end)
      handle.removeEventListener("pointercancel", end)
      if (free) return
      setPreview(null)
      setFreeSize(null)
      if (last && last !== current) select(last)
    }
    handle.addEventListener("pointermove", move)
    handle.addEventListener("pointerup", end)
    handle.addEventListener("pointercancel", end)
  }

  const resetSize = () => {
    setFreeSize(null)
    select(initialSize)
  }

  const widget = (
    <div
      ref={(node) => {
        widgetRef.current = node
        if (typeof ref === "function") return ref(node)
        if (ref) ref.current = node
      }}
      data-slot="widget"
      data-size={current}
      data-align={align}
      style={
        freeSize ? { ...style, width: freeSize[0], height: freeSize[1] } : style
      }
      className={cn(
        "group/widget @container/widget flex max-w-full min-w-0 flex-col gap-3 overflow-hidden rounded-3xl bg-muted p-4 text-base text-foreground transition-[width,height] duration-500 ease-in-out data-[align=center]:items-center data-[align=center]:justify-center data-[align=center]:text-center data-resizing:transition-none data-[resizing=snap]:*:shrink-0 data-[size=auto]:size-full data-[size=extra-large]:h-88 data-[size=extra-large]:w-180 data-[size=large]:size-88 data-[size=medium]:h-42 data-[size=medium]:w-88 data-[size=small]:size-42 motion-reduce:transition-none",
        className
      )}
      {...props}
    />
  )

  if (!resizable) return widget

  return (
    <div
      data-slot="widget-container"
      data-size={current}
      className="relative w-fit max-w-full data-[size=auto]:size-full"
    >
      {preview && (
        <span
          aria-hidden="true"
          data-slot="widget-preview"
          className="pointer-events-none absolute inset-s-0 top-0 z-10 animate-in transition-[width,height] duration-500 ease-in-out fade-in-0 motion-reduce:transition-none"
          style={{
            width: WIDGET_DIMENSIONS[preview][0],
            height: WIDGET_DIMENSIONS[preview][1],
          }}
        >
          <svg
            aria-hidden
            fill="none"
            className="size-full overflow-visible stroke-foreground/25"
          >
            <rect
              width="100%"
              height="100%"
              rx="28"
              strokeWidth="1"
              strokeDasharray="3 3"
              strokeLinecap="round"
            />
          </svg>
        </span>
      )}
      {widget}
      <WidgetHandle
        placement={handle}
        onPointerDown={startResize}
        onDoubleClick={resetSize}
      />
    </div>
  )
}

function WidgetHeader({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="widget-header"
      className={cn(
        "flex max-w-full min-w-0 items-center gap-2 group-data-[align=center]/widget:flex-col group-data-[align=center]/widget:gap-3",
        className
      )}
      {...props}
    />
  )
}

function WidgetIcon({
  className,
  size = "default",
  ...props
}: React.ComponentProps<"span"> & {
  size?: "default" | "sm" | "lg"
}) {
  return (
    <span
      data-slot="widget-icon"
      data-size={size}
      aria-hidden="true"
      className={cn(
        "flex shrink-0 items-center justify-center text-foreground data-[size=default]:size-8 data-[size=default]:rounded-lg data-[size=default]:bg-secondary data-[size=lg]:size-13 data-[size=lg]:rounded-2xl data-[size=lg]:bg-secondary [&_svg]:pointer-events-none data-[size=default]:[&_svg:not([class*='size-'])]:size-4.5 data-[size=lg]:[&_svg:not([class*='size-'])]:size-6 data-[size=sm]:[&_svg:not([class*='size-'])]:size-3.5",
        className
      )}
      {...props}
    />
  )
}

function WidgetTitle({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="widget-title"
      className={cn(
        "max-w-full min-w-0 truncate text-sm font-semibold",
        className
      )}
      {...props}
    />
  )
}

function WidgetAction({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="widget-action"
      className={cn(
        "ms-auto flex shrink-0 items-center group-data-[align=center]/widget:hidden",
        className
      )}
      {...props}
    />
  )
}

function WidgetDescription({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="widget-description"
      className={cn("text-sm text-muted-foreground", className)}
      {...props}
    />
  )
}

function WidgetValue({ className, ...props }: React.ComponentProps<"p">) {
  return (
    <p
      data-slot="widget-value"
      className={cn(
        "text-3xl font-semibold tracking-tight tabular-nums",
        className
      )}
      {...props}
    />
  )
}

function WidgetContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="widget-content"
      className={cn("flex min-h-0 flex-1 flex-col gap-1", className)}
      {...props}
    />
  )
}

function WidgetFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="widget-footer"
      className={cn(
        "mt-auto flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground group-data-[align=center]/widget:mt-0 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",
        className
      )}
      {...props}
    />
  )
}

export {
  Widget,
  WidgetAction,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  type WidgetSize,
  WidgetTitle,
  WidgetValue,
}
```

3. Update the import paths to match your project.

## Usage

```tsx
import { Widget, WidgetHeader, WidgetIcon, WidgetTitle, WidgetAction, WidgetDescription, WidgetValue, WidgetContent, WidgetFooter } from "@/components/ui/widget"
```

```tsx
<Widget size="small" align="start">
  <WidgetHeader>
    <WidgetIcon>
      <SunIcon weight="fill" />
    </WidgetIcon>
    <WidgetTitle>Istanbul</WidgetTitle>
  </WidgetHeader>
  <WidgetContent>
    <WidgetValue>24°</WidgetValue>
    <WidgetDescription>Partly cloudy</WidgetDescription>
  </WidgetContent>
  <WidgetFooter>H 27° · L 18°</WidgetFooter>
</Widget>
```

Use `size` with `onSizeChange` to control the size, or `defaultSize` to set where an uncontrolled widget starts. Without either, a resizable widget starts `small` and a fixed widget is `auto`. Limit the sizes a drag can snap to with `sizes`.

Set `resizable="free"` to follow the pointer without snapping; the widget stays between the smallest size and the largest allowed size. Double-click the handle to return to the starting size.

Adapt the content to the current size with the `group/widget` group and `data-size`, for example `group-data-[size=small]/widget:hidden`.

## Examples

### Sales

Shows a resizable widget whose chart and list adapt to each size.

**Example**

```tsx
import { CashRegisterIcon } from "@phosphor-icons/react"
import type * as React from "react"
import {
  Widget,
  WidgetDescription,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

const hourly = [12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14]

const topItems = [
  { name: "Grilled meatballs", count: 38 },
  { name: "Lahmacun", count: 31 },
  { name: "Adana kebab", count: 24 },
  { name: "Künefe", count: 19 },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="mt-6 text-xs text-muted-foreground">{children}</p>
}

export default function WidgetSales() {
  return (
    <div>
      <Widget resizable defaultSize="large">
        <WidgetHeader className="gap-1.5 text-amber-600 dark:text-amber-400">
          <WidgetIcon size="sm" className="text-amber-600 dark:text-amber-400">
            <CashRegisterIcon />
          </WidgetIcon>
          <WidgetTitle>Hestia</WidgetTitle>
        </WidgetHeader>
        <div className="flex min-h-0 flex-col gap-3 group-data-[size=medium]/widget:flex-1 group-data-[size=medium]/widget:flex-row group-data-[size=medium]/widget:items-end">
          <div className="shrink-0">
            <WidgetValue>₺18,240</WidgetValue>
            <WidgetDescription className="text-xs">
              Today's revenue · 42 orders
            </WidgetDescription>
          </div>
          <div
            aria-hidden="true"
            className="flex h-14 shrink-0 items-end gap-1 group-data-[size=medium]/widget:h-full group-data-[size=medium]/widget:flex-1 group-data-[size=small]/widget:hidden"
          >
            {hourly.map((value, index) => (
              <span
                key={index}
                data-now={value === 100}
                className="flex-1 rounded-sm bg-secondary data-[now=true]:bg-orange-500"
                style={{ height: `${value}%` }}
              />
            ))}
          </div>
        </div>
        <ul className="flex flex-col group-data-[size=medium]/widget:hidden group-data-[size=small]/widget:hidden">
          {topItems.map((item) => (
            <li
              key={item.name}
              className="flex items-center justify-between border-t py-1.5 text-sm"
            >
              {item.name}
              <span className="text-muted-foreground tabular-nums">
                {item.count}
              </span>
            </li>
          ))}
        </ul>
      </Widget>
      <Hint>
        Hover the corner and drag the handle. Double-click it to reset.
      </Hint>
    </div>
  )
}
```

### Kitchen

Places the resize handle inside the widget's corner.

**Example**

```tsx
import { CookingPotIcon } from "@phosphor-icons/react"
import type * as React from "react"
import {
  Widget,
  WidgetDescription,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

const tickets = [
  { id: "#1042", place: "Table 4", minutes: 18 },
  { id: "#1043", place: "Takeaway", minutes: 15 },
  { id: "#1044", place: "Table 12", minutes: 9 },
  { id: "#1045", place: "Pickup", minutes: 7 },
  { id: "#1046", place: "Garden 3", minutes: 5 },
  { id: "#1047", place: "Table 7", minutes: 3 },
  { id: "#1048", place: "Takeaway", minutes: 1 },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="mt-6 text-xs text-muted-foreground">{children}</p>
}

export default function WidgetKitchen() {
  return (
    <div>
      <Widget
        resizable
        handle="inside"
        defaultSize="large"
        className="flex-row gap-4"
      >
        <div className="flex w-32 shrink-0 flex-col gap-1 group-data-[size=small]/widget:w-full">
          <WidgetHeader className="gap-1.5 text-amber-600 dark:text-amber-400">
            <WidgetIcon
              size="sm"
              className="text-amber-600 dark:text-amber-400"
            >
              <CookingPotIcon />
            </WidgetIcon>
            <WidgetTitle>Kitchen</WidgetTitle>
          </WidgetHeader>
          <WidgetValue className="mt-2 text-5xl">7</WidgetValue>
          <WidgetDescription className="text-xs">
            pending orders
          </WidgetDescription>
          <p className="text-xs font-medium text-destructive">2 running late</p>
        </div>
        <ul className="flex min-w-0 flex-1 flex-col group-data-[size=small]/widget:hidden">
          {tickets.map((ticket) => (
            <li
              key={ticket.id}
              className="flex items-center gap-2 border-b py-1.5 text-sm group-data-[size=medium]/widget:nth-[n+4]:hidden"
            >
              <span
                aria-hidden="true"
                data-late={ticket.minutes >= 15}
                className="size-1.5 shrink-0 rounded-full bg-orange-500 data-[late=true]:bg-red-500"
              />
              <span className="min-w-0 flex-1 truncate">
                {ticket.id} · {ticket.place}
              </span>
              <span
                data-late={ticket.minutes >= 15}
                className="text-xs text-muted-foreground tabular-nums data-[late=true]:font-medium data-[late=true]:text-destructive"
              >
                {ticket.minutes} min
              </span>
            </li>
          ))}
        </ul>
      </Widget>
      <Hint>Handle inside the corner. Hover the corner to reveal it.</Hint>
    </div>
  )
}
```

### Reservations

Limits resizing to the `small` and `medium` sizes.

**Example**

```tsx
import { CalendarBlankIcon } from "@phosphor-icons/react"
import type * as React from "react"
import {
  Widget,
  WidgetAction,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="mt-6 text-xs text-muted-foreground">{children}</p>
}

export default function WidgetReservations() {
  return (
    <div>
      <Widget resizable defaultSize="medium" sizes={["small", "medium"]}>
        <WidgetHeader className="gap-1.5 text-primary">
          <WidgetIcon size="sm" className="text-primary">
            <CalendarBlankIcon />
          </WidgetIcon>
          <WidgetTitle>Reservations</WidgetTitle>
          <WidgetAction className="text-xs text-muted-foreground">
            Up next
          </WidgetAction>
        </WidgetHeader>
        <div>
          <WidgetValue>20:00</WidgetValue>
          <p className="text-sm">Ayşe Y. · 6 guests</p>
        </div>
        <div className="mt-auto flex flex-col gap-1 group-data-[size=small]/widget:hidden">
          <div className="flex justify-between text-xs text-muted-foreground tabular-nums">
            <span>18:00</span>
            <span>20:00</span>
            <span>22:00</span>
            <span>24:00</span>
          </div>
          <div className="relative h-2 rounded-full bg-secondary">
            <span className="absolute inset-y-0 start-[30%] w-[45%] rounded-full bg-blue-500" />
          </div>
        </div>
      </Widget>
      <Hint>Snaps between small and medium only.</Hint>
    </div>
  )
}
```

### Weekly report

Starts at `extra-large` and reveals extra content only at that size.

**Example**

```tsx
import { ChartBarIcon, TriangleIcon } from "@phosphor-icons/react"
import type * as React from "react"
import {
  Widget,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

const week = [
  { day: "Mon", value: 52 },
  { day: "Tue", value: 44 },
  { day: "Wed", value: 60 },
  { day: "Thu", value: 56 },
  { day: "Fri", value: 82 },
  { day: "Sat", value: 100 },
  { day: "Sun", value: 70 },
]

const channels = [
  { name: "Dine-in", amount: "₺64,200", tint: "bg-blue-500" },
  { name: "Takeaway", amount: "₺38,900", tint: "bg-orange-500" },
  { name: "Pickup", amount: "₺18,800", tint: "bg-green-500" },
]

const bestSellers = [
  { name: "Grilled meatballs", count: 238 },
  { name: "Lahmacun", count: 201 },
  { name: "Adana kebab", count: 164 },
  { name: "Künefe", count: 131 },
  { name: "Ayran", count: 120 },
  { name: "Lentil soup", count: 96 },
] as const

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="mt-6 text-xs text-muted-foreground">{children}</p>
}

export default function WidgetWeeklyReport() {
  return (
    <div>
      <Widget resizable defaultSize="extra-large" className="flex-row gap-6">
        <div className="flex min-w-0 flex-1 flex-col gap-3">
          <WidgetHeader className="gap-1.5 text-green-600 dark:text-green-400">
            <WidgetIcon
              size="sm"
              className="text-green-600 dark:text-green-400"
            >
              <ChartBarIcon />
            </WidgetIcon>
            <WidgetTitle>This week</WidgetTitle>
          </WidgetHeader>
          <div className="flex min-h-0 flex-col gap-3 group-data-[size=medium]/widget:flex-1 group-data-[size=medium]/widget:flex-row group-data-[size=medium]/widget:items-end">
            <div className="shrink-0">
              <WidgetValue>₺121,900</WidgetValue>
              <p className="flex items-center gap-1 text-xs font-medium text-green-600 dark:text-green-400">
                <TriangleIcon className="size-2.5 fill-current" />
                12% more than last week
              </p>
            </div>
            <div className="flex h-24 min-w-0 shrink-0 items-end gap-2 group-data-[size=medium]/widget:h-full group-data-[size=medium]/widget:gap-1.5 group-data-[size=medium]/widget:flex-1 group-data-[size=small]/widget:hidden">
              {week.map((day) => (
                <div
                  key={day.day}
                  className="flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-1"
                >
                  <div className="flex min-h-0 w-full flex-1 items-end">
                    <span
                      aria-hidden="true"
                      data-top={day.value === 100}
                      className="w-full rounded-md bg-secondary data-[top=true]:bg-green-500"
                      style={{ height: `${day.value}%` }}
                    />
                  </div>
                  <span className="text-xs text-muted-foreground group-data-[size=medium]/widget:hidden">
                    {day.day}
                  </span>
                </div>
              ))}
            </div>
          </div>
          <ul className="flex flex-col group-data-[size=medium]/widget:hidden group-data-[size=small]/widget:hidden">
            {channels.map((channel) => (
              <li
                key={channel.name}
                className="flex items-center gap-2 border-t py-1.5 text-sm"
              >
                <span
                  aria-hidden="true"
                  className={`size-2 rounded-full ${channel.tint}`}
                />
                <span className="flex-1">{channel.name}</span>
                <span className="text-muted-foreground tabular-nums">
                  {channel.amount}
                </span>
              </li>
            ))}
          </ul>
        </div>
        <div className="hidden w-72 shrink-0 flex-col gap-2 group-data-[size=extra-large]/widget:flex">
          <p className="text-xs font-semibold text-muted-foreground">
            Best sellers
          </p>
          {bestSellers.map((item) => (
            <div key={item.name} className="flex flex-col gap-1">
              <div className="flex justify-between text-sm">
                {item.name}
                <span className="text-muted-foreground tabular-nums">
                  {item.count}
                </span>
              </div>
              <div className="h-1 rounded-full bg-secondary">
                <div
                  className="h-full rounded-full bg-green-500"
                  style={{
                    width: `${(item.count / bestSellers[0].count) * 100}%`,
                  }}
                />
              </div>
            </div>
          ))}
        </div>
      </Widget>
      <Hint>Extra large shows best sellers, large hides them.</Hint>
    </div>
  )
}
```

### Free resize

Resizes freely with the pointer instead of snapping to sizes.

**Example**

```tsx
import {
  BowlFoodIcon,
  CoffeeIcon,
  HamburgerIcon,
  IceCreamIcon,
  OrangeSliceIcon,
  PizzaIcon,
} from "@phosphor-icons/react"
import * as React from "react"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Widget, WidgetTitle } from "@/components/ui/widget"

const menu = [
  {
    name: "Meatballs",
    price: "₺280",
    icon: (
      <HamburgerIcon />
    ),
  },
  {
    name: "Pide",
    price: "₺220",
    icon: (
      <PizzaIcon />
    ),
  },
  {
    name: "Soup",
    price: "₺90",
    icon: (
      <BowlFoodIcon />
    ),
  },
  {
    name: "Coffee",
    price: "₺75",
    icon: (
      <CoffeeIcon />
    ),
  },
  {
    name: "Künefe",
    price: "₺160",
    icon: (
      <IceCreamIcon />
    ),
  },
  {
    name: "Lemonade",
    price: "₺70",
    icon: (
      <OrangeSliceIcon />
    ),
  },
  {
    name: "Ayran",
    price: "₺40",
    icon: (
      <CoffeeIcon />
    ),
  },
  {
    name: "Baklava",
    price: "₺180",
    icon: (
      <IceCreamIcon />
    ),
  },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <p className="mt-6 text-xs text-muted-foreground">{children}</p>
}

function FreeResizeExample() {
  const ref = React.useRef<HTMLDivElement>(null)
  const [box, setBox] = React.useState({ width: 0, height: 0, columns: 0 })

  React.useEffect(() => {
    const widget = ref.current
    if (!widget) return
    const measure = () => {
      const grid = widget.querySelector<HTMLElement>("[data-menu-grid]")
      const columns = grid
        ? getComputedStyle(grid).gridTemplateColumns.split(" ").length
        : 0
      setBox({
        width: Math.round(widget.offsetWidth),
        height: Math.round(widget.offsetHeight),
        columns,
      })
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(widget)
    return () => observer.disconnect()
  }, [])

  return (
    <div>
      <Widget
        ref={ref}
        resizable="free"
        defaultSize="large"
        className="gap-0 p-0"
      >
        <div className="flex items-baseline justify-between px-4 pt-4 pb-3">
          <WidgetTitle className="text-xl">Hestia POS</WidgetTitle>
          <span className="text-sm text-muted-foreground tabular-nums">
            {box.columns} columns
          </span>
        </div>
        <ScrollArea className="min-h-0 flex-1">
          <div
            data-menu-grid
            className="grid grid-cols-2 gap-2 px-4 pb-4 @[30rem]/widget:grid-cols-3 @[44rem]/widget:grid-cols-4"
          >
            {menu.map((item) => (
              <div
                key={item.name}
                className="flex flex-col gap-2 rounded-2xl bg-card p-3"
              >
                <span
                  aria-hidden="true"
                  className="text-amber-600 dark:text-amber-400 [&_svg]:size-6"
                >
                  {item.icon}
                </span>
                <div>
                  <p className="text-sm font-semibold">{item.name}</p>
                  <p className="text-sm text-muted-foreground tabular-nums">
                    {item.price}
                  </p>
                </div>
              </div>
            ))}
          </div>
        </ScrollArea>
      </Widget>
      <Hint>
        Free resize · {box.width} × {box.height}
      </Hint>
    </div>
  )
}

export default function WidgetFreeResize() {
  return <FreeResizeExample />
}
```

### Auto resize

Fills its parent with `auto`, and snaps to fixed sizes when dragged.

**Example**

```tsx
import { CashRegisterIcon } from "@phosphor-icons/react"
import {
  Widget,
  WidgetDescription,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
} from "@/components/ui/widget"

export default function WidgetAutoResize() {
  return (
    <div className="h-60 w-full max-w-180">
      <Widget resizable defaultSize="auto">
        <WidgetHeader>
          <WidgetIcon>
            <CashRegisterIcon />
          </WidgetIcon>
          <WidgetTitle>Point of sale</WidgetTitle>
        </WidgetHeader>
        <WidgetDescription>
          Fills its parent. Drag to snap to a size, double-click to fill again.
        </WidgetDescription>
      </Widget>
    </div>
  )
}
```

### Centered

Centers the icon, title and description with `align="center"`.

**Example**

```tsx
import { CashRegisterIcon } from "@phosphor-icons/react"
import {
  Widget,
  WidgetDescription,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
} from "@/components/ui/widget"

export default function WidgetCentered() {
  return (
    <Widget size="small" align="center">
      <WidgetHeader>
        <WidgetIcon size="lg">
          <CashRegisterIcon />
        </WidgetIcon>
        <WidgetTitle>Point of sale</WidgetTitle>
      </WidgetHeader>
      <WidgetDescription>3 open orders</WidgetDescription>
    </Widget>
  )
}
```

### Sizes

Shows each fixed size side by side.

**Example**

```tsx
import {
  Widget,
  WidgetFooter,
  WidgetHeader,
  WidgetTitle,
} from "@/components/ui/widget"

const gridSpans = {
  small: "1 × 1",
  medium: "2 × 1",
  large: "2 × 2",
  "extra-large": "4 × 2",
}

export default function WidgetSizes() {
  return (
    <div className="flex flex-wrap items-start gap-4">
      {(["small", "medium", "large", "extra-large"] as const).map((size) => (
        <Widget key={size} size={size}>
          <WidgetHeader>
            <WidgetTitle className="capitalize">
              {size.replace("-", " ")}
            </WidgetTitle>
          </WidgetHeader>
          <WidgetFooter>{gridSpans[size]}</WidgetFooter>
        </Widget>
      ))}
    </div>
  )
}
```

### Dashboard

Arranges fixed widgets in a grid as a dashboard.

**Example**

```tsx
import {
  CalendarBlankIcon,
  CashRegisterIcon,
  CookingPotIcon,
  SunIcon,
} from "@phosphor-icons/react"
import {
  Widget,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  WidgetTitle,
  WidgetValue,
} from "@/components/ui/widget"

const tickets = [
  { id: "#1042", place: "Table 4", minutes: 18 },
  { id: "#1043", place: "Takeaway", minutes: 15 },
  { id: "#1044", place: "Table 12", minutes: 9 },
  { id: "#1045", place: "Pickup", minutes: 7 },
  { id: "#1046", place: "Garden 3", minutes: 5 },
  { id: "#1047", place: "Table 7", minutes: 3 },
  { id: "#1048", place: "Takeaway", minutes: 1 },
]

export default function WidgetDashboard() {
  return (
    <div className="grid max-w-4xl auto-rows-[10.5rem] grid-cols-2 gap-4 md:grid-cols-4">
      <Widget>
        <WidgetHeader>
          <WidgetIcon>
            <SunIcon className="fill-current" />
          </WidgetIcon>
          <WidgetTitle>Istanbul</WidgetTitle>
        </WidgetHeader>
        <WidgetValue>24°</WidgetValue>
        <WidgetFooter>Partly cloudy</WidgetFooter>
      </Widget>
      <Widget align="center">
        <WidgetHeader>
          <WidgetIcon size="lg">
            <CookingPotIcon />
          </WidgetIcon>
          <WidgetTitle>Kitchen display</WidgetTitle>
        </WidgetHeader>
        <WidgetDescription>5 tickets</WidgetDescription>
      </Widget>
      <Widget className="col-span-2">
        <WidgetHeader className="gap-1.5 text-amber-600 dark:text-amber-400">
          <WidgetIcon size="sm" className="text-amber-600 dark:text-amber-400">
            <CashRegisterIcon />
          </WidgetIcon>
          <WidgetTitle>Hestia</WidgetTitle>
        </WidgetHeader>
        <WidgetValue>₺18,240</WidgetValue>
        <WidgetFooter>Today's revenue · 42 orders</WidgetFooter>
      </Widget>
      <Widget className="col-span-2 row-span-2">
        <WidgetHeader className="gap-1.5 text-primary">
          <WidgetIcon size="sm" className="text-primary">
            <CalendarBlankIcon />
          </WidgetIcon>
          <WidgetTitle>Reservations</WidgetTitle>
        </WidgetHeader>
        <WidgetContent className="gap-2">
          {tickets.slice(0, 5).map((ticket, index) => (
            <div key={ticket.id} className="flex items-baseline gap-3 text-sm">
              <span className="w-11 shrink-0 text-muted-foreground tabular-nums">
                {`${18 + index}:00`}
              </span>
              <span className="truncate">{ticket.place}</span>
            </div>
          ))}
        </WidgetContent>
      </Widget>
      <Widget className="col-span-2 row-span-2" align="center">
        <WidgetHeader>
          <WidgetIcon size="lg">
            <CashRegisterIcon />
          </WidgetIcon>
          <WidgetTitle>Point of sale</WidgetTitle>
        </WidgetHeader>
        <WidgetDescription>3 open orders</WidgetDescription>
      </Widget>
    </div>
  )
}
```

## API Reference

- `Widget`
- `WidgetHeader`
  - `WidgetIcon`
  - `WidgetTitle`
  - `WidgetAction`
- `WidgetContent`
  - `WidgetValue`
  - `WidgetDescription`
- `WidgetFooter`
- `WidgetValue`
- `WidgetDescription`

### Widget

The rounded card that sets the size, alignment and resize behavior.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `WidgetSize \| "auto"` | - | Controls the current size, or `auto` to fill the parent. |
| `defaultSize` | `WidgetSize \| "auto"` | - | Sets the starting size when uncontrolled; double-clicking the handle also returns to it. |
| `onSizeChange` | `(size: WidgetSize \| "auto") => void` | - | Called with the new size when a drag snaps to a different size or the size is reset. |
| `sizes` | `WidgetSize[]` | `["small", "medium", "large", "extra-large"]` | Lists the sizes a drag can snap to; the largest also caps free resizing. |
| `resizable` | `boolean \| "free"` | `false` | Adds a resize handle; `true` snaps to `sizes`, and `free` follows the pointer. |
| `handle` | `"inside" \| "outside"` | `"outside"` | Places the resize handle `inside` or `outside` the bottom corner. |
| `align` | `"start" \| "center"` | `"start"` | Centers the content horizontally and vertically when set to `center`. |

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

### WidgetHeader

A row that holds the icon, title and action.

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

### WidgetIcon

A decorative icon, shown on a tile in the `default` and `lg` sizes.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"default" \| "sm" \| "lg"` | `"default"` | Sets the icon size: `sm` without a tile, or `default` and `lg` on a rounded tile. |

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

### WidgetTitle

The widget's title, truncated to one line.

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

### WidgetAction

A slot at the end of the header for a control; hidden when centered.

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

### WidgetDescription

Secondary text that explains the content.

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

### WidgetValue

A large figure in tabular numbers, such as a total or temperature.

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

### WidgetContent

A flexible column that fills the remaining space.

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

### WidgetFooter

Small secondary text pinned to the bottom of the widget.

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

## Accessibility

- `WidgetIcon` is hidden from assistive technologies, so make sure the title conveys its meaning.
- The resize handle is hidden from assistive technologies and works with a pointer only. Offer another way to change the size, such as a control that sets `size`, if it matters.

## Notes

- `Widget` sets `data-size` and `data-align`, and `data-resizing` while dragging. It's also a `@container/widget` container for container queries.
- Parts carry `data-slot` attributes such as `widget`, `widget-container`, `widget-handle`, `widget-preview` and `widget-header`.
- The handle is visible on hover and always visible on touch screens. It mirrors in right-to-left layouts.
- Size changes animate over `500ms`, and the animation is removed when reduced motion is preferred.

**React Native, SwiftUI, Jetpack Compose**

![Preview](https://ui.suiss.app/previews/components-widget--default.light.webp)

```tsx
import { SunIcon } from "phosphor-react-native"
import { Icon } from "@/components/ui/icon"
import { Widget, WidgetContent, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

function Weather() {
  return (
    <>
      <WidgetHeader>
        <WidgetIcon>
          <Icon as={SunIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle>Istanbul</WidgetTitle>
      </WidgetHeader>
      <WidgetContent>
        <WidgetValue>24°</WidgetValue>
        <WidgetDescription>Partly cloudy</WidgetDescription>
      </WidgetContent>
      <WidgetFooter>H 27° · L 18°</WidgetFooter>
    </>
  )
}

export function WidgetExample() {
  return (
    <Widget size="small" align="start">
      <Weather />
    </Widget>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetExample: View {
  var body: some View {
    Widget(.small) {
      WidgetWeather()
    }
  }
}

struct WidgetWeather: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon {
        Ph.sun.fill
      }
      WidgetTitle("Istanbul")
    }
    WidgetContent {
      WidgetValue(verbatim: "24°")
      WidgetDescription("Partly cloudy")
    }
    WidgetFooter(verbatim: "H 27° · L 18°")
  }
}
```

```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.style.TextOverflow
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.Sun
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue

@Composable
fun WidgetExample() {
    Widget(size = WidgetSize.Small) { WidgetWeather() }
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetWeather() {
    WidgetHeader {
        WidgetIcon { Icon(PhosphorIcons.Fill.Sun, contentDescription = null) }
        WidgetTitle("Istanbul")
    }
    WidgetContent {
        WidgetValue("24°")
        WidgetDescription("Partly cloudy")
    }
    WidgetFooterText("H 27° · L 18°")
}
```

`Widget` is a `View` with a rounded, filled surface. It comes in four fixed sizes, `small` (168×168), `medium` (352×168), `large` (352×352) and `extra-large` (720×352), or `auto`, which fills its parent. Fixed sizes animate with Reanimated when the size changes.

With `resizable`, a corner handle lets the user drag the widget between sizes: a dashed outline previews the size it will snap to, a selection haptic plays on each new snap (when a haptics adapter is provided through `HapticsContext`), and double-tapping the handle returns to the initial size. Only sizes that fit the available width are offered. Set `align="center"` to center the content, which also hides `WidgetAction`.

## Installation

**React Native**

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

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

```bash title="Terminal"
npx @esuiss/ui@latest add widget
```

**SwiftUI**

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

**Jetpack Compose**

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

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

### Manual

**React Native**

**Uniwind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install 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](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/ui/widget.tsx`:

```tsx title="uniwind/components/ui/widget.tsx"
import { cn } from "cn"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  View,
  type ViewProps,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  Easing,
  ReduceMotion,
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import Svg, { Path } from "react-native-svg"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type WidgetSize = "small" | "medium" | "large" | "extra-large"

type WidgetAlign = "start" | "center"

type WidgetHandlePlacement = "inside" | "outside"

const WIDGET_DIMENSIONS: Record<WidgetSize, [number, number]> = {
  small: [168, 168],
  medium: [352, 168],
  large: [352, 352],
  "extra-large": [720, 352],
}

const ALL_SIZES: WidgetSize[] = ["small", "medium", "large", "extra-large"]

const STRETCH = 48

const TIMING = {
  duration: 500,
  easing: Easing.inOut(Easing.ease),
  reduceMotion: ReduceMotion.System,
}

const ACTIONS = [{ name: "increment" }, { name: "decrement" }] as const

const WidgetContext = React.createContext<{
  size: WidgetSize | "auto"
  align: WidgetAlign
}>({ size: "auto", align: "start" })

function useWidget() {
  return React.useContext(WidgetContext)
}

function sizesThatFit(sizes: WidgetSize[], room: number) {
  const fitting = sizes.filter((size) => WIDGET_DIMENSIONS[size][0] <= room)
  if (fitting.length > 0) return fitting
  const narrowest = sizes.reduce((best, size) =>
    WIDGET_DIMENSIONS[size][0] < WIDGET_DIMENSIONS[best][0] ? size : best
  )
  return [narrowest]
}

function actionStep(actionName: string) {
  if (actionName === "increment") return 1
  if (actionName === "decrement") return -1
  return 0
}

function wrapText(children: React.ReactNode) {
  if (typeof children === "string" || typeof children === "number") {
    return <Text>{children}</Text>
  }
  return children
}

function InsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 28 28" fill="none">
      <Path
        d="M19.9 9.3A22 22 0 0 1 9.3 19.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function OutsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 34 34" fill="none">
      <Path
        d="M29.9 13.9A33 33 0 0 1 13.9 29.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function WidgetFrame({
  className,
  current,
  align,
  fill,
  style,
  children,
  ...props
}: ViewProps & {
  className?: string
  current: WidgetSize | "auto"
  align: WidgetAlign
  fill: boolean
}) {
  const context = React.useMemo(
    () => ({ size: current, align }),
    [current, align]
  )
  return (
    <WidgetContext.Provider value={context}>
      <TextClassContext.Provider
        value={cn(
          "text-base text-foreground",
          align === "center" && "text-center"
        )}
      >
        <View
          className={cn(
            "max-w-full min-w-0 flex-col gap-3 overflow-hidden rounded-3xl bg-muted p-4",
            align === "center" && "items-center justify-center",
            fill && "size-full",
            className
          )}
          style={style}
          {...props}
        >
          {children}
        </View>
      </TextClassContext.Provider>
    </WidgetContext.Provider>
  )
}

function Widget({
  className,
  size,
  defaultSize,
  onSizeChange,
  sizes = ALL_SIZES,
  resizable = false,
  handle = "outside",
  align = "start",
  resizeLabel = "Resize widget",
  style,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
    size?: WidgetSize | "auto"
    defaultSize?: WidgetSize | "auto"
    onSizeChange?: (size: WidgetSize | "auto") => void
    sizes?: WidgetSize[]
    resizable?: boolean
    handle?: WidgetHandlePlacement
    align?: WidgetAlign
    resizeLabel?: string
  }) {
  const initialSize = defaultSize ?? (resizable ? "small" : "auto")
  const [uncontrolledSize, setUncontrolledSize] = React.useState(initialSize)
  const current = size ?? uncontrolledSize
  const { selection } = useHaptics()
  const [room, setRoom] = React.useState(Number.POSITIVE_INFINITY)
  const [preview, setPreview] = React.useState<WidgetSize | null>(null)
  const [dragging, setDragging] = React.useState(false)
  const [settled, setSettled] = React.useState(0)

  const reachable = React.useMemo(
    () => sizesThatFit(sizes, room),
    [sizes, room]
  )
  const fixed = current === "auto" ? null : WIDGET_DIMENSIONS[current]

  const width = useSharedValue(fixed?.[0] ?? 0)
  const height = useSharedValue(fixed?.[1] ?? 0)
  const startWidth = useSharedValue(0)
  const startHeight = useSharedValue(0)
  const measuredWidth = useSharedValue(0)
  const measuredHeight = useSharedValue(0)
  const previewWidth = useSharedValue(0)
  const previewHeight = useSharedValue(0)
  const last = useSharedValue(-1)
  const active = useSharedValue(0)

  const select = React.useCallback(
    (next: WidgetSize | "auto") => {
      if (size === undefined) setUncontrolledSize(next)
      onSizeChange?.(next)
    },
    [size, onSizeChange]
  )

  React.useEffect(() => {
    if (dragging || !fixed || settled < 0) return
    width.value = withTiming(fixed[0], TIMING)
    height.value = withTiming(fixed[1], TIMING)
  }, [fixed, dragging, settled, width, height])

  const snap = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      if (!next) return
      selection()
      setPreview(next)
    },
    [reachable, selection]
  )

  const release = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      setPreview(null)
      setDragging(false)
      setSettled((count) => count + 1)
      if (next && next !== current) select(next)
    },
    [reachable, current, select]
  )

  const begin = React.useCallback(() => setDragging(true), [])

  const reset = React.useCallback(() => {
    if (initialSize === current) return
    selection()
    select(initialSize)
  }, [initialSize, current, select, selection])

  const gesture = React.useMemo(() => {
    const dimensions = reachable.flatMap((item) => WIDGET_DIMENSIONS[item])
    const currentIndex =
      current === "auto" ? -1 : reachable.indexOf(current as WidgetSize)
    const direction = I18nManager.isRTL ? -1 : 1
    const [minWidth, minHeight] = WIDGET_DIMENSIONS.small
    let maxWidth = 0
    let maxHeight = 0
    for (let index = 0; index < dimensions.length; index += 2) {
      maxWidth = Math.max(maxWidth, dimensions[index] ?? 0)
      maxHeight = Math.max(maxHeight, dimensions[index + 1] ?? 0)
    }
    const limit = room
    const pan = Gesture.Pan()
      .minDistance(2)
      .onStart(() => {
        const startW = currentIndex < 0 ? measuredWidth.value : width.value
        const startH = currentIndex < 0 ? measuredHeight.value : height.value
        startWidth.value = startW
        startHeight.value = startH
        width.value = startW
        height.value = startH
        last.value = currentIndex
        active.value = 1
        if (currentIndex >= 0) {
          previewWidth.value = dimensions[currentIndex * 2] ?? startW
          previewHeight.value = dimensions[currentIndex * 2 + 1] ?? startH
        }
        runOnJS(begin)()
      })
      .onUpdate((event) => {
        const nextWidth = startWidth.value + event.translationX * direction
        const nextHeight = startHeight.value + event.translationY
        width.value = Math.max(
          minWidth,
          Math.min(maxWidth + STRETCH, limit, nextWidth)
        )
        height.value = Math.max(
          minHeight,
          Math.min(maxHeight + STRETCH, nextHeight)
        )
        let best = -1
        let bestDistance = Number.POSITIVE_INFINITY
        for (let index = 0; index * 2 < dimensions.length; index += 1) {
          const distance =
            (nextWidth - (dimensions[index * 2] ?? 0)) ** 2 +
            (nextHeight - (dimensions[index * 2 + 1] ?? 0)) ** 2
          if (distance < bestDistance) {
            best = index
            bestDistance = distance
          }
        }
        if (best >= 0 && best !== last.value) {
          last.value = best
          previewWidth.value = withTiming(dimensions[best * 2] ?? 0, TIMING)
          previewHeight.value = withTiming(
            dimensions[best * 2 + 1] ?? 0,
            TIMING
          )
          runOnJS(snap)(best)
        }
      })
      .onFinalize(() => {
        if (!active.value) return
        active.value = 0
        const index = last.value
        if (index >= 0) {
          width.value = withTiming(dimensions[index * 2] ?? 0, TIMING)
          height.value = withTiming(dimensions[index * 2 + 1] ?? 0, TIMING)
        }
        runOnJS(release)(index)
      })
    const doubleTap = Gesture.Tap()
      .numberOfTaps(2)
      .onEnd(() => {
        runOnJS(reset)()
      })
    return Gesture.Exclusive(pan, doubleTap)
  }, [
    reachable,
    current,
    room,
    width,
    height,
    startWidth,
    startHeight,
    measuredWidth,
    measuredHeight,
    previewWidth,
    previewHeight,
    last,
    active,
    begin,
    snap,
    release,
    reset,
  ])

  const sizeStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
  }))

  const previewStyle = useAnimatedStyle(() => ({
    width: previewWidth.value,
    height: previewHeight.value,
  }))

  const animated = fixed !== null || dragging

  if (!resizable) {
    if (!fixed) {
      return (
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
      )
    }
    return (
      <AnimatedView className="max-w-full" style={sizeStyle}>
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
      </AnimatedView>
    )
  }

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const step = actionStep(event.nativeEvent.actionName)
    if (!step) return
    const index = current === "auto" ? -1 : reachable.indexOf(current)
    const next =
      reachable[Math.max(0, Math.min(reachable.length - 1, index + step))]
    if (!next || next === current) return
    selection()
    select(next)
  }

  return (
    <View
      className={cn("w-full items-start", current === "auto" && "h-full")}
      onLayout={(event) => setRoom(event.nativeEvent.layout.width)}
    >
      <AnimatedView
        className={cn("relative max-w-full", !animated && "size-full")}
        style={animated ? sizeStyle : undefined}
        onLayout={(event) => {
          measuredWidth.value = event.nativeEvent.layout.width
          measuredHeight.value = event.nativeEvent.layout.height
        }}
      >
        {preview ? (
          <AnimatedView
            pointerEvents="none"
            accessibilityElementsHidden
            importantForAccessibility="no-hide-descendants"
            className="absolute start-0 top-0 z-10 rounded-3xl border border-dashed border-foreground/25"
            style={previewStyle}
          />
        ) : null}
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
        <GestureDetector gesture={gesture}>
          <View
            accessible
            accessibilityRole="adjustable"
            accessibilityLabel={resizeLabel}
            accessibilityValue={{ text: current }}
            accessibilityActions={ACTIONS}
            onAccessibilityAction={onAccessibilityAction}
            hitSlop={12}
            className={cn(
              "absolute",
              handle === "inside"
                ? "end-0 bottom-0 size-7"
                : "-end-1.5 -bottom-1.5 size-8.5"
            )}
            style={
              I18nManager.isRTL ? { transform: [{ scaleX: -1 }] } : undefined
            }
          >
            <IconClassContext.Provider value={undefined}>
              <TextClassContext.Provider value={undefined}>
                <Icon
                  as={
                    handle === "inside" ? InsideHandleShape : OutsideHandleShape
                  }
                  className={cn(
                    handle === "inside" ? "size-7" : "size-8.5",
                    dragging ? "text-primary" : "text-muted-foreground/50"
                  )}
                />
              </TextClassContext.Provider>
            </IconClassContext.Provider>
          </View>
        </GestureDetector>
      </AnimatedView>
    </View>
  )
}

function WidgetHeader({
  className,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  return (
    <View
      className={cn(
        "max-w-full min-w-0 shrink-0 flex-row items-center gap-2",
        align === "center" && "flex-col gap-3",
        className
      )}
      {...props}
    />
  )
}

const WIDGET_ICON_SIZE = {
  default: { frame: "size-8 rounded-lg bg-secondary", icon: "size-4.5" },
  sm: { frame: "", icon: "size-3.5" },
  lg: { frame: "size-13 rounded-2xl bg-secondary", icon: "size-6" },
} as const

function WidgetIcon({
  className,
  iconClassName,
  size = "default",
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
    iconClassName?: string
    size?: "default" | "sm" | "lg"
  }) {
  return (
    <IconClassContext.Provider
      value={cn(WIDGET_ICON_SIZE[size].icon, "text-foreground", iconClassName)}
    >
      <View
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
        className={cn(
          "shrink-0 items-center justify-center",
          WIDGET_ICON_SIZE[size].frame,
          className
        )}
        {...props}
      />
    </IconClassContext.Provider>
  )
}

function WidgetTitle({
  className,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      role="heading"
      numberOfLines={1}
      className={cn(
        "max-w-full min-w-0 shrink text-sm font-semibold",
        className
      )}
      {...props}
    />
  )
}

function WidgetAction({
  className,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  if (align === "center") return null
  return (
    <View
      className={cn("ms-auto shrink-0 flex-row items-center", className)}
      {...props}
    />
  )
}

function WidgetDescription({
  className,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      className={cn("text-sm text-muted-foreground", className)}
      {...props}
    />
  )
}

function WidgetValue({
  className,
  style,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      className={cn("text-3xl font-semibold tracking-tight", className)}
      style={[{ fontVariant: ["tabular-nums"] }, style]}
      {...props}
    />
  )
}

function WidgetContent({
  className,
  children,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  return (
    <View
      className={cn(
        "min-h-0 shrink grow flex-col gap-1 overflow-hidden",
        className
      )}
      {...props}
    >
      {wrapText(children)}
    </View>
  )
}

function WidgetFooter({
  className,
  children,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  return (
    <TextClassContext.Provider value="text-xs text-muted-foreground">
      <IconClassContext.Provider value="size-3.5 shrink-0 text-muted-foreground">
        <View
          className={cn(
            "min-w-0 shrink-0 flex-row items-center gap-1.5",
            align === "center" ? "mt-0" : "mt-auto",
            className
          )}
          {...props}
        >
          {wrapText(children)}
        </View>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  useWidget,
  Widget,
  WidgetAction,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  type WidgetSize,
  WidgetTitle,
  WidgetValue,
}
```

5. 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](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/ui/widget.tsx`:

```tsx title="nativewind/components/ui/widget.tsx"
import { cn } from "cn"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  View,
  type ViewProps,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  Easing,
  ReduceMotion,
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import Svg, { Path } from "react-native-svg"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type WidgetSize = "small" | "medium" | "large" | "extra-large"

type WidgetAlign = "start" | "center"

type WidgetHandlePlacement = "inside" | "outside"

const WIDGET_DIMENSIONS: Record<WidgetSize, [number, number]> = {
  small: [168, 168],
  medium: [352, 168],
  large: [352, 352],
  "extra-large": [720, 352],
}

const ALL_SIZES: WidgetSize[] = ["small", "medium", "large", "extra-large"]

const STRETCH = 48

const TIMING = {
  duration: 500,
  easing: Easing.inOut(Easing.ease),
  reduceMotion: ReduceMotion.System,
}

const ACTIONS = [{ name: "increment" }, { name: "decrement" }] as const

const WidgetContext = React.createContext<{
  size: WidgetSize | "auto"
  align: WidgetAlign
}>({ size: "auto", align: "start" })

function useWidget() {
  return React.useContext(WidgetContext)
}

function sizesThatFit(sizes: WidgetSize[], room: number) {
  const fitting = sizes.filter((size) => WIDGET_DIMENSIONS[size][0] <= room)
  if (fitting.length > 0) return fitting
  const narrowest = sizes.reduce((best, size) =>
    WIDGET_DIMENSIONS[size][0] < WIDGET_DIMENSIONS[best][0] ? size : best
  )
  return [narrowest]
}

function actionStep(actionName: string) {
  if (actionName === "increment") return 1
  if (actionName === "decrement") return -1
  return 0
}

function wrapText(children: React.ReactNode) {
  if (typeof children === "string" || typeof children === "number") {
    return <Text>{children}</Text>
  }
  return children
}

function InsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 28 28" fill="none">
      <Path
        d="M19.9 9.3A22 22 0 0 1 9.3 19.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function OutsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 34 34" fill="none">
      <Path
        d="M29.9 13.9A33 33 0 0 1 13.9 29.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function WidgetFrame({
  className,
  current,
  align,
  fill,
  style,
  children,
  ...props
}: ViewProps & {
  className?: string
  current: WidgetSize | "auto"
  align: WidgetAlign
  fill: boolean
}) {
  const context = React.useMemo(
    () => ({ size: current, align }),
    [current, align]
  )
  return (
    <WidgetContext.Provider value={context}>
      <TextClassContext.Provider
        value={cn(
          "text-base text-foreground",
          align === "center" && "text-center"
        )}
      >
        <View
          className={cn(
            "max-w-full min-w-0 flex-col gap-3 overflow-hidden rounded-3xl bg-muted p-4",
            align === "center" && "items-center justify-center",
            fill && "size-full",
            className
          )}
          style={style}
          {...props}
        >
          {children}
        </View>
      </TextClassContext.Provider>
    </WidgetContext.Provider>
  )
}

function Widget({
  className,
  size,
  defaultSize,
  onSizeChange,
  sizes = ALL_SIZES,
  resizable = false,
  handle = "outside",
  align = "start",
  resizeLabel = "Resize widget",
  style,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
    size?: WidgetSize | "auto"
    defaultSize?: WidgetSize | "auto"
    onSizeChange?: (size: WidgetSize | "auto") => void
    sizes?: WidgetSize[]
    resizable?: boolean
    handle?: WidgetHandlePlacement
    align?: WidgetAlign
    resizeLabel?: string
  }) {
  const initialSize = defaultSize ?? (resizable ? "small" : "auto")
  const [uncontrolledSize, setUncontrolledSize] = React.useState(initialSize)
  const current = size ?? uncontrolledSize
  const { selection } = useHaptics()
  const [room, setRoom] = React.useState(Number.POSITIVE_INFINITY)
  const [preview, setPreview] = React.useState<WidgetSize | null>(null)
  const [dragging, setDragging] = React.useState(false)
  const [settled, setSettled] = React.useState(0)

  const reachable = React.useMemo(
    () => sizesThatFit(sizes, room),
    [sizes, room]
  )
  const fixed = current === "auto" ? null : WIDGET_DIMENSIONS[current]

  const width = useSharedValue(fixed?.[0] ?? 0)
  const height = useSharedValue(fixed?.[1] ?? 0)
  const startWidth = useSharedValue(0)
  const startHeight = useSharedValue(0)
  const measuredWidth = useSharedValue(0)
  const measuredHeight = useSharedValue(0)
  const previewWidth = useSharedValue(0)
  const previewHeight = useSharedValue(0)
  const last = useSharedValue(-1)
  const active = useSharedValue(0)

  const select = React.useCallback(
    (next: WidgetSize | "auto") => {
      if (size === undefined) setUncontrolledSize(next)
      onSizeChange?.(next)
    },
    [size, onSizeChange]
  )

  React.useEffect(() => {
    if (dragging || !fixed || settled < 0) return
    width.value = withTiming(fixed[0], TIMING)
    height.value = withTiming(fixed[1], TIMING)
  }, [fixed, dragging, settled, width, height])

  const snap = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      if (!next) return
      selection()
      setPreview(next)
    },
    [reachable, selection]
  )

  const release = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      setPreview(null)
      setDragging(false)
      setSettled((count) => count + 1)
      if (next && next !== current) select(next)
    },
    [reachable, current, select]
  )

  const begin = React.useCallback(() => setDragging(true), [])

  const reset = React.useCallback(() => {
    if (initialSize === current) return
    selection()
    select(initialSize)
  }, [initialSize, current, select, selection])

  const gesture = React.useMemo(() => {
    const dimensions = reachable.flatMap((item) => WIDGET_DIMENSIONS[item])
    const currentIndex =
      current === "auto" ? -1 : reachable.indexOf(current as WidgetSize)
    const direction = I18nManager.isRTL ? -1 : 1
    const [minWidth, minHeight] = WIDGET_DIMENSIONS.small
    let maxWidth = 0
    let maxHeight = 0
    for (let index = 0; index < dimensions.length; index += 2) {
      maxWidth = Math.max(maxWidth, dimensions[index] ?? 0)
      maxHeight = Math.max(maxHeight, dimensions[index + 1] ?? 0)
    }
    const limit = room
    const pan = Gesture.Pan()
      .minDistance(2)
      .onStart(() => {
        const startW = currentIndex < 0 ? measuredWidth.value : width.value
        const startH = currentIndex < 0 ? measuredHeight.value : height.value
        startWidth.value = startW
        startHeight.value = startH
        width.value = startW
        height.value = startH
        last.value = currentIndex
        active.value = 1
        if (currentIndex >= 0) {
          previewWidth.value = dimensions[currentIndex * 2] ?? startW
          previewHeight.value = dimensions[currentIndex * 2 + 1] ?? startH
        }
        runOnJS(begin)()
      })
      .onUpdate((event) => {
        const nextWidth = startWidth.value + event.translationX * direction
        const nextHeight = startHeight.value + event.translationY
        width.value = Math.max(
          minWidth,
          Math.min(maxWidth + STRETCH, limit, nextWidth)
        )
        height.value = Math.max(
          minHeight,
          Math.min(maxHeight + STRETCH, nextHeight)
        )
        let best = -1
        let bestDistance = Number.POSITIVE_INFINITY
        for (let index = 0; index * 2 < dimensions.length; index += 1) {
          const distance =
            (nextWidth - (dimensions[index * 2] ?? 0)) ** 2 +
            (nextHeight - (dimensions[index * 2 + 1] ?? 0)) ** 2
          if (distance < bestDistance) {
            best = index
            bestDistance = distance
          }
        }
        if (best >= 0 && best !== last.value) {
          last.value = best
          previewWidth.value = withTiming(dimensions[best * 2] ?? 0, TIMING)
          previewHeight.value = withTiming(
            dimensions[best * 2 + 1] ?? 0,
            TIMING
          )
          runOnJS(snap)(best)
        }
      })
      .onFinalize(() => {
        if (!active.value) return
        active.value = 0
        const index = last.value
        if (index >= 0) {
          width.value = withTiming(dimensions[index * 2] ?? 0, TIMING)
          height.value = withTiming(dimensions[index * 2 + 1] ?? 0, TIMING)
        }
        runOnJS(release)(index)
      })
    const doubleTap = Gesture.Tap()
      .numberOfTaps(2)
      .onEnd(() => {
        runOnJS(reset)()
      })
    return Gesture.Exclusive(pan, doubleTap)
  }, [
    reachable,
    current,
    room,
    width,
    height,
    startWidth,
    startHeight,
    measuredWidth,
    measuredHeight,
    previewWidth,
    previewHeight,
    last,
    active,
    begin,
    snap,
    release,
    reset,
  ])

  const sizeStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
  }))

  const previewStyle = useAnimatedStyle(() => ({
    width: previewWidth.value,
    height: previewHeight.value,
  }))

  const animated = fixed !== null || dragging

  if (!resizable) {
    if (!fixed) {
      return (
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
      )
    }
    return (
      <AnimatedView className="max-w-full" style={sizeStyle}>
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
      </AnimatedView>
    )
  }

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const step = actionStep(event.nativeEvent.actionName)
    if (!step) return
    const index = current === "auto" ? -1 : reachable.indexOf(current)
    const next =
      reachable[Math.max(0, Math.min(reachable.length - 1, index + step))]
    if (!next || next === current) return
    selection()
    select(next)
  }

  return (
    <View
      className={cn("w-full items-start", current === "auto" && "h-full")}
      onLayout={(event) => setRoom(event.nativeEvent.layout.width)}
    >
      <AnimatedView
        className={cn("relative max-w-full", !animated && "size-full")}
        style={animated ? sizeStyle : undefined}
        onLayout={(event) => {
          measuredWidth.value = event.nativeEvent.layout.width
          measuredHeight.value = event.nativeEvent.layout.height
        }}
      >
        {preview ? (
          <AnimatedView
            pointerEvents="none"
            accessibilityElementsHidden
            importantForAccessibility="no-hide-descendants"
            className="absolute start-0 top-0 z-10 rounded-3xl border border-dashed border-foreground-25"
            style={previewStyle}
          />
        ) : null}
        <WidgetFrame
          className={className}
          current={current}
          align={align}
          fill
          style={style}
          {...props}
        />
        <GestureDetector gesture={gesture}>
          <View
            accessible
            accessibilityRole="adjustable"
            accessibilityLabel={resizeLabel}
            accessibilityValue={{ text: current }}
            accessibilityActions={ACTIONS}
            onAccessibilityAction={onAccessibilityAction}
            hitSlop={12}
            className={cn(
              "absolute",
              handle === "inside"
                ? "end-0 bottom-0 size-7"
                : "-end-1.5 -bottom-1.5 size-[2.125rem]"
            )}
            style={
              I18nManager.isRTL ? { transform: [{ scaleX: -1 }] } : undefined
            }
          >
            <IconClassContext.Provider value={undefined}>
              <TextClassContext.Provider value={undefined}>
                <Icon
                  as={
                    handle === "inside" ? InsideHandleShape : OutsideHandleShape
                  }
                  className={cn(
                    handle === "inside" ? "size-7" : "size-[2.125rem]",
                    dragging ? "text-primary" : "text-muted-foreground-50"
                  )}
                />
              </TextClassContext.Provider>
            </IconClassContext.Provider>
          </View>
        </GestureDetector>
      </AnimatedView>
    </View>
  )
}

function WidgetHeader({
  className,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  return (
    <View
      className={cn(
        "max-w-full min-w-0 shrink-0 flex-row items-center gap-2",
        align === "center" && "flex-col gap-3",
        className
      )}
      {...props}
    />
  )
}

const WIDGET_ICON_SIZE = {
  default: { frame: "size-8 rounded-lg bg-secondary", icon: "size-[1.125rem]" },
  sm: { frame: "", icon: "size-3.5" },
  lg: { frame: "size-[3.25rem] rounded-2xl bg-secondary", icon: "size-6" },
} as const

function WidgetIcon({
  className,
  iconClassName,
  size = "default",
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
    iconClassName?: string
    size?: "default" | "sm" | "lg"
  }) {
  return (
    <IconClassContext.Provider
      value={cn(WIDGET_ICON_SIZE[size].icon, "text-foreground", iconClassName)}
    >
      <View
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
        className={cn(
          "shrink-0 items-center justify-center",
          WIDGET_ICON_SIZE[size].frame,
          className
        )}
        {...props}
      />
    </IconClassContext.Provider>
  )
}

function WidgetTitle({
  className,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      role="heading"
      numberOfLines={1}
      className={cn(
        "max-w-full min-w-0 shrink text-sm font-semibold",
        className
      )}
      {...props}
    />
  )
}

function WidgetAction({
  className,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  if (align === "center") return null
  return (
    <View
      className={cn("ms-auto shrink-0 flex-row items-center", className)}
      {...props}
    />
  )
}

function WidgetDescription({
  className,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      className={cn("text-sm text-muted-foreground", className)}
      {...props}
    />
  )
}

function WidgetValue({
  className,
  style,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      className={cn("text-3xl font-semibold tracking-tight", className)}
      style={[{ fontVariant: ["tabular-nums"] }, style]}
      {...props}
    />
  )
}

function WidgetContent({
  className,
  children,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  return (
    <View
      className={cn(
        "min-h-0 shrink grow flex-col gap-1 overflow-hidden",
        className
      )}
      {...props}
    >
      {wrapText(children)}
    </View>
  )
}

function WidgetFooter({
  className,
  children,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    className?: string
  }) {
  const { align } = useWidget()
  return (
    <TextClassContext.Provider value="text-xs text-muted-foreground">
      <IconClassContext.Provider value="size-3.5 shrink-0 text-muted-foreground">
        <View
          className={cn(
            "min-w-0 shrink-0 flex-row items-center gap-1.5",
            align === "center" ? "mt-0" : "mt-auto",
            className
          )}
          {...props}
        >
          {wrapText(children)}
        </View>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  useWidget,
  Widget,
  WidgetAction,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  type WidgetSize,
  WidgetTitle,
  WidgetValue,
}
```

5. 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](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/haptics.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/ui/widget.tsx`:

```tsx title="stylesheet/components/ui/widget.tsx"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  I18nManager,
  type StyleProp,
  StyleSheet,
  type TextStyle,
  View,
  type ViewProps,
  type ViewStyle,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  Easing,
  ReduceMotion,
  runOnJS,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from "react-native-reanimated"
import Svg, { Path } from "react-native-svg"
import { useHaptics } from "@/components/primitives/haptics"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconSizeContext } from "@/components/ui/icon"
import { Text, TextStyleContext } from "@/components/ui/text"
import { fontSize, radius, useTheme } from "@/components/ui/theme"

type WidgetSize = "small" | "medium" | "large" | "extra-large"

type WidgetAlign = "start" | "center"

type WidgetHandlePlacement = "inside" | "outside"

const WIDGET_DIMENSIONS: Record<WidgetSize, [number, number]> = {
  small: [168, 168],
  medium: [352, 168],
  large: [352, 352],
  "extra-large": [720, 352],
}

const ALL_SIZES: WidgetSize[] = ["small", "medium", "large", "extra-large"]

const STRETCH = 48

const TIMING = {
  duration: 500,
  easing: Easing.inOut(Easing.ease),
  reduceMotion: ReduceMotion.System,
}

const ACTIONS = [{ name: "increment" }, { name: "decrement" }] as const

const WidgetContext = React.createContext<{
  size: WidgetSize | "auto"
  align: WidgetAlign
}>({ size: "auto", align: "start" })

function actionStep(actionName: string) {
  if (actionName === "increment") return 1
  if (actionName === "decrement") return -1
  return 0
}

function withAlpha(color: string, alpha: number) {
  if (!color.startsWith("#") || color.length !== 7) return color
  const r = Number.parseInt(color.slice(1, 3), 16)
  const g = Number.parseInt(color.slice(3, 5), 16)
  const b = Number.parseInt(color.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

function useWidget() {
  return React.useContext(WidgetContext)
}

function sizesThatFit(sizes: WidgetSize[], room: number) {
  const fitting = sizes.filter((size) => WIDGET_DIMENSIONS[size][0] <= room)
  if (fitting.length > 0) return fitting
  const narrowest = sizes.reduce((best, size) =>
    WIDGET_DIMENSIONS[size][0] < WIDGET_DIMENSIONS[best][0] ? size : best
  )
  return [narrowest]
}

const styles = StyleSheet.create({
  frame: {
    maxWidth: "100%",
    minWidth: 0,
    flexDirection: "column",
    gap: 12,
    overflow: "hidden",
    borderRadius: radius["3xl"],
    padding: 16,
  },
  center: { alignItems: "center", justifyContent: "center" },
  fill: { width: "100%", height: "100%" },
  sized: { maxWidth: "100%" },
  room: { width: "100%", alignItems: "flex-start" },
  roomFill: { height: "100%" },
  stage: { position: "relative", maxWidth: "100%" },
  preview: {
    position: "absolute",
    start: 0,
    top: 0,
    zIndex: 10,
    borderRadius: radius["3xl"],
    borderWidth: 1,
    borderStyle: "dashed",
  },
  handleInside: {
    position: "absolute",
    end: 0,
    bottom: 0,
    width: 28,
    height: 28,
  },
  handleOutside: {
    position: "absolute",
    end: -6,
    bottom: -6,
    width: 34,
    height: 34,
  },
  header: {
    maxWidth: "100%",
    minWidth: 0,
    flexShrink: 0,
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  headerCenter: { flexDirection: "column", gap: 12 },
  icon: { flexShrink: 0, alignItems: "center", justifyContent: "center" },
  iconDefault: { width: 32, height: 32, borderRadius: radius.lg },
  iconLarge: { width: 52, height: 52, borderRadius: radius["2xl"] },
  title: {
    maxWidth: "100%",
    minWidth: 0,
    flexShrink: 1,
    ...fontSize.sm,
    fontWeight: "600",
  },
  description: { ...fontSize.sm },
  value: {
    ...fontSize["3xl"],
    fontWeight: "600",
    letterSpacing: fontSize["3xl"].fontSize * -0.025,
    fontVariant: ["tabular-nums"],
  },
  action: {
    marginStart: "auto",
    flexShrink: 0,
    flexDirection: "row",
    alignItems: "center",
  },
  content: {
    minHeight: 0,
    flexShrink: 1,
    flexGrow: 1,
    overflow: "hidden",
    flexDirection: "column",
    gap: 4,
  },
  footer: {
    minWidth: 0,
    flexShrink: 0,
    flexDirection: "row",
    alignItems: "center",
    gap: 6,
  },
})

const ICON_SIZE = { default: 18, sm: 14, lg: 24 } as const

function wrapText(children: React.ReactNode) {
  if (typeof children === "string" || typeof children === "number") {
    return <Text>{children}</Text>
  }
  return children
}

function InsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 28 28" fill="none">
      <Path
        d="M19.9 9.3A22 22 0 0 1 9.3 19.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function OutsideHandleShape({ color, size }: PhosphorIconProps) {
  return (
    <Svg width={size} height={size} viewBox="0 0 34 34" fill="none">
      <Path
        d="M29.9 13.9A33 33 0 0 1 13.9 29.9"
        stroke={color}
        strokeWidth={4}
        strokeLinecap="round"
      />
    </Svg>
  )
}

function WidgetFrame({
  current,
  align,
  style,
  children,
  ...props
}: ViewProps & {
  current: WidgetSize | "auto"
  align: WidgetAlign
}) {
  const { colors } = useTheme()
  const context = React.useMemo(
    () => ({ size: current, align }),
    [current, align]
  )
  return (
    <WidgetContext.Provider value={context}>
      <TextStyleContext.Provider
        value={{
          ...fontSize.base,
          color: colors.foreground,
          textAlign: align === "center" ? "center" : undefined,
        }}
      >
        <View
          style={[
            styles.frame,
            { backgroundColor: colors.muted },
            align === "center" && styles.center,
            styles.fill,
            style,
          ]}
          {...props}
        >
          {children}
        </View>
      </TextStyleContext.Provider>
    </WidgetContext.Provider>
  )
}

function Widget({
  size,
  defaultSize,
  onSizeChange,
  sizes = ALL_SIZES,
  resizable = false,
  handle = "outside",
  align = "start",
  resizeLabel = "Resize widget",
  style,
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    size?: WidgetSize | "auto"
    defaultSize?: WidgetSize | "auto"
    onSizeChange?: (size: WidgetSize | "auto") => void
    sizes?: WidgetSize[]
    resizable?: boolean
    handle?: WidgetHandlePlacement
    align?: WidgetAlign
    resizeLabel?: string
  }) {
  const { colors } = useTheme()
  const initialSize = defaultSize ?? (resizable ? "small" : "auto")
  const [uncontrolledSize, setUncontrolledSize] = React.useState(initialSize)
  const current = size ?? uncontrolledSize
  const { selection } = useHaptics()
  const [room, setRoom] = React.useState(Number.POSITIVE_INFINITY)
  const [preview, setPreview] = React.useState<WidgetSize | null>(null)
  const [dragging, setDragging] = React.useState(false)
  const [settled, setSettled] = React.useState(0)

  const reachable = React.useMemo(
    () => sizesThatFit(sizes, room),
    [sizes, room]
  )
  const fixed = current === "auto" ? null : WIDGET_DIMENSIONS[current]

  const width = useSharedValue(fixed?.[0] ?? 0)
  const height = useSharedValue(fixed?.[1] ?? 0)
  const startWidth = useSharedValue(0)
  const startHeight = useSharedValue(0)
  const measuredWidth = useSharedValue(0)
  const measuredHeight = useSharedValue(0)
  const previewWidth = useSharedValue(0)
  const previewHeight = useSharedValue(0)
  const last = useSharedValue(-1)
  const active = useSharedValue(0)

  const select = React.useCallback(
    (next: WidgetSize | "auto") => {
      if (size === undefined) setUncontrolledSize(next)
      onSizeChange?.(next)
    },
    [size, onSizeChange]
  )

  React.useEffect(() => {
    if (dragging || !fixed || settled < 0) return
    width.value = withTiming(fixed[0], TIMING)
    height.value = withTiming(fixed[1], TIMING)
  }, [fixed, dragging, settled, width, height])

  const snap = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      if (!next) return
      selection()
      setPreview(next)
    },
    [reachable, selection]
  )

  const release = React.useCallback(
    (index: number) => {
      const next = reachable[index]
      setPreview(null)
      setDragging(false)
      setSettled((count) => count + 1)
      if (next && next !== current) select(next)
    },
    [reachable, current, select]
  )

  const begin = React.useCallback(() => setDragging(true), [])

  const reset = React.useCallback(() => {
    if (initialSize === current) return
    selection()
    select(initialSize)
  }, [initialSize, current, select, selection])

  const gesture = React.useMemo(() => {
    const dimensions = reachable.flatMap((item) => WIDGET_DIMENSIONS[item])
    const currentIndex =
      current === "auto" ? -1 : reachable.indexOf(current as WidgetSize)
    const direction = I18nManager.isRTL ? -1 : 1
    const [minWidth, minHeight] = WIDGET_DIMENSIONS.small
    let maxWidth = 0
    let maxHeight = 0
    for (let index = 0; index < dimensions.length; index += 2) {
      maxWidth = Math.max(maxWidth, dimensions[index] ?? 0)
      maxHeight = Math.max(maxHeight, dimensions[index + 1] ?? 0)
    }
    const limit = room
    const pan = Gesture.Pan()
      .minDistance(2)
      .onStart(() => {
        const startW = currentIndex < 0 ? measuredWidth.value : width.value
        const startH = currentIndex < 0 ? measuredHeight.value : height.value
        startWidth.value = startW
        startHeight.value = startH
        width.value = startW
        height.value = startH
        last.value = currentIndex
        active.value = 1
        if (currentIndex >= 0) {
          previewWidth.value = dimensions[currentIndex * 2] ?? startW
          previewHeight.value = dimensions[currentIndex * 2 + 1] ?? startH
        }
        runOnJS(begin)()
      })
      .onUpdate((event) => {
        const nextWidth = startWidth.value + event.translationX * direction
        const nextHeight = startHeight.value + event.translationY
        width.value = Math.max(
          minWidth,
          Math.min(maxWidth + STRETCH, limit, nextWidth)
        )
        height.value = Math.max(
          minHeight,
          Math.min(maxHeight + STRETCH, nextHeight)
        )
        let best = -1
        let bestDistance = Number.POSITIVE_INFINITY
        for (let index = 0; index * 2 < dimensions.length; index += 1) {
          const distance =
            (nextWidth - (dimensions[index * 2] ?? 0)) ** 2 +
            (nextHeight - (dimensions[index * 2 + 1] ?? 0)) ** 2
          if (distance < bestDistance) {
            best = index
            bestDistance = distance
          }
        }
        if (best >= 0 && best !== last.value) {
          last.value = best
          previewWidth.value = withTiming(dimensions[best * 2] ?? 0, TIMING)
          previewHeight.value = withTiming(
            dimensions[best * 2 + 1] ?? 0,
            TIMING
          )
          runOnJS(snap)(best)
        }
      })
      .onFinalize(() => {
        if (!active.value) return
        active.value = 0
        const index = last.value
        if (index >= 0) {
          width.value = withTiming(dimensions[index * 2] ?? 0, TIMING)
          height.value = withTiming(dimensions[index * 2 + 1] ?? 0, TIMING)
        }
        runOnJS(release)(index)
      })
    const doubleTap = Gesture.Tap()
      .numberOfTaps(2)
      .onEnd(() => {
        runOnJS(reset)()
      })
    return Gesture.Exclusive(pan, doubleTap)
  }, [
    reachable,
    current,
    room,
    width,
    height,
    startWidth,
    startHeight,
    measuredWidth,
    measuredHeight,
    previewWidth,
    previewHeight,
    last,
    active,
    begin,
    snap,
    release,
    reset,
  ])

  const sizeStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
  }))

  const previewStyle = useAnimatedStyle(() => ({
    width: previewWidth.value,
    height: previewHeight.value,
  }))

  const animated = fixed !== null || dragging

  if (!resizable) {
    if (!fixed) {
      return (
        <WidgetFrame current={current} align={align} style={style} {...props} />
      )
    }
    return (
      <AnimatedView style={[styles.sized, sizeStyle]}>
        <WidgetFrame current={current} align={align} style={style} {...props} />
      </AnimatedView>
    )
  }

  const onAccessibilityAction = (event: AccessibilityActionEvent) => {
    const step = actionStep(event.nativeEvent.actionName)
    if (!step) return
    const index = current === "auto" ? -1 : reachable.indexOf(current)
    const next =
      reachable[Math.max(0, Math.min(reachable.length - 1, index + step))]
    if (!next || next === current) return
    selection()
    select(next)
  }

  return (
    <View
      style={[styles.room, current === "auto" && styles.roomFill]}
      onLayout={(event) => setRoom(event.nativeEvent.layout.width)}
    >
      <AnimatedView
        style={[styles.stage, animated ? sizeStyle : styles.fill]}
        onLayout={(event) => {
          measuredWidth.value = event.nativeEvent.layout.width
          measuredHeight.value = event.nativeEvent.layout.height
        }}
      >
        {preview ? (
          <AnimatedView
            pointerEvents="none"
            accessibilityElementsHidden
            importantForAccessibility="no-hide-descendants"
            style={[
              styles.preview,
              {
                borderColor: withAlpha(colors.foreground, 0.25),
              },
              previewStyle,
            ]}
          />
        ) : null}
        <WidgetFrame current={current} align={align} style={style} {...props} />
        <GestureDetector gesture={gesture}>
          <View
            accessible
            accessibilityRole="adjustable"
            accessibilityLabel={resizeLabel}
            accessibilityValue={{ text: current }}
            accessibilityActions={ACTIONS}
            onAccessibilityAction={onAccessibilityAction}
            hitSlop={12}
            style={[
              handle === "inside" ? styles.handleInside : styles.handleOutside,
              I18nManager.isRTL ? { transform: [{ scaleX: -1 }] } : null,
            ]}
          >
            <Icon
              as={handle === "inside" ? InsideHandleShape : OutsideHandleShape}
              size={handle === "inside" ? 28 : 34}
              color={
                dragging
                  ? colors.primary
                  : withAlpha(colors.mutedForeground, 0.5)
              }
            />
          </View>
        </GestureDetector>
      </AnimatedView>
    </View>
  )
}

function WidgetHeader({
  style,
  ...props
}: ViewProps & React.RefAttributes<React.ComponentRef<typeof View>>) {
  const { align } = useWidget()
  return (
    <View
      style={[styles.header, align === "center" && styles.headerCenter, style]}
      {...props}
    />
  )
}

function WidgetIcon({
  style,
  iconColor,
  size = "default",
  ...props
}: ViewProps &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    iconColor?: string
    size?: "default" | "sm" | "lg"
  }) {
  const { colors } = useTheme()
  return (
    <IconSizeContext.Provider value={ICON_SIZE[size]}>
      <TextStyleContext.Provider
        value={{ color: iconColor ?? colors.foreground }}
      >
        <View
          accessibilityElementsHidden
          importantForAccessibility="no-hide-descendants"
          style={[
            styles.icon,
            size === "default" && [
              styles.iconDefault,
              { backgroundColor: colors.secondary },
            ],
            size === "lg" && [
              styles.iconLarge,
              { backgroundColor: colors.secondary },
            ],
            style,
          ]}
          {...props}
        />
      </TextStyleContext.Provider>
    </IconSizeContext.Provider>
  )
}

function WidgetTitle({
  style,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return (
    <Text
      role="heading"
      numberOfLines={1}
      style={[styles.title, style]}
      {...props}
    />
  )
}

function WidgetAction({
  style,
  ...props
}: ViewProps & React.RefAttributes<React.ComponentRef<typeof View>>) {
  const { align } = useWidget()
  if (align === "center") return null
  return <View style={[styles.action, style]} {...props} />
}

function WidgetDescription({
  style,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  const { colors } = useTheme()
  return (
    <Text
      style={[styles.description, { color: colors.mutedForeground }, style]}
      {...props}
    />
  )
}

function WidgetValue({
  style,
  ...props
}: React.ComponentProps<typeof Text> &
  React.RefAttributes<React.ComponentRef<typeof Text>>) {
  return <Text style={[styles.value, style]} {...props} />
}

function WidgetContent({
  style,
  children,
  ...props
}: ViewProps & React.RefAttributes<React.ComponentRef<typeof View>>) {
  return (
    <View style={[styles.content, style]} {...props}>
      {wrapText(children)}
    </View>
  )
}

function WidgetFooter({
  style,
  children,
  ...props
}: ViewProps & React.RefAttributes<React.ComponentRef<typeof View>>) {
  const { colors } = useTheme()
  const { align } = useWidget()
  const text: StyleProp<TextStyle> = {
    ...fontSize.xs,
    color: colors.mutedForeground,
  }
  const footer: StyleProp<ViewStyle> = [
    styles.footer,
    { marginTop: align === "center" ? 0 : "auto" },
    style,
  ]
  return (
    <TextStyleContext.Provider value={text as TextStyle}>
      <IconSizeContext.Provider value={14}>
        <View style={footer} {...props}>
          {wrapText(children)}
        </View>
      </IconSizeContext.Provider>
    </TextStyleContext.Provider>
  )
}

export {
  useWidget,
  Widget,
  WidgetAction,
  WidgetContent,
  WidgetDescription,
  WidgetFooter,
  WidgetHeader,
  WidgetIcon,
  type WidgetSize,
  WidgetTitle,
  WidgetValue,
}
```

5. 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/Theme/Theme.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Theme/Theme.swift)

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

4. Copy the source and every file it uses:

```swift title="swift/Components/Widget.swift"
import PhosphorSwift
import SwiftUI

public enum WidgetSize: CaseIterable, Sendable {
  case small, medium, large, extraLarge

  public var dimensions: CGSize {
    switch self {
    case .small: CGSize(width: 168, height: 168)
    case .medium: CGSize(width: 352, height: 168)
    case .large: CGSize(width: 352, height: 352)
    case .extraLarge: CGSize(width: 720, height: 352)
    }
  }
}

public enum WidgetAlign: CaseIterable, Sendable {
  case start, center
}

public enum WidgetHandlePlacement: CaseIterable, Sendable {
  case inside, outside
}

extension EnvironmentValues {
  @Entry public var widgetSize: WidgetSize?
  @Entry var widgetAlign = WidgetAlign.start
}

enum WidgetMath {
  static let stretch: CGFloat = 48

  static func nearest(width: CGFloat, height: CGFloat, sizes: [WidgetSize]) -> WidgetSize? {
    var best: WidgetSize?
    var distance = CGFloat.infinity
    for size in sizes {
      let target = size.dimensions
      let next = (width - target.width) * (width - target.width) + (height - target.height) * (height - target.height)
      if next < distance {
        best = size
        distance = next
      }
    }
    return best
  }

  static func fitting(_ sizes: [WidgetSize], room: CGFloat) -> [WidgetSize] {
    let fitting = sizes.filter { $0.dimensions.width <= room }
    if !fitting.isEmpty { return fitting }
    guard let narrowest = sizes.min(by: { $0.dimensions.width < $1.dimensions.width }) else { return [] }
    return [narrowest]
  }

  static func frame(start: CGSize, translation: CGSize, room: CGFloat, sizes: [WidgetSize]) -> CGSize {
    let reachable = fitting(sizes, room: room)
    let maxWidth = reachable.map(\.dimensions.width).max() ?? start.width
    let maxHeight = reachable.map(\.dimensions.height).max() ?? start.height
    let minimum = WidgetSize.small.dimensions
    return CGSize(
      width: max(minimum.width, min(maxWidth + stretch, room, start.width + translation.width)),
      height: max(minimum.height, min(maxHeight + stretch, start.height + translation.height))
    )
  }

  static func target(start: CGSize, translation: CGSize, room: CGFloat, sizes: [WidgetSize]) -> WidgetSize? {
    nearest(
      width: start.width + translation.width,
      height: start.height + translation.height,
      sizes: fitting(sizes, room: room)
    )
  }
}

public struct Widget<Content: View>: View {
  let size: WidgetSize?
  let binding: Binding<WidgetSize>?
  let sizes: [WidgetSize]
  let editing: Bool
  let handle: WidgetHandlePlacement
  let align: WidgetAlign
  let resetSize: WidgetSize?
  let content: Content
  let preview: (WidgetSize, CGSize)?

  @State private var drag: CGSize?
  @State private var target: WidgetSize?
  @State private var room = CGFloat.infinity
  @Environment(\.layoutDirection) private var layoutDirection
  @Environment(\.accessibilityReduceMotion) private var reduceMotion

  public init(_ size: WidgetSize? = .small, align: WidgetAlign = .start, @ViewBuilder content: () -> Content) {
    self.size = size
    binding = nil
    sizes = WidgetSize.allCases
    editing = false
    handle = .outside
    self.align = align
    resetSize = nil
    self.content = content()
    preview = nil
  }

  public init(
    size: Binding<WidgetSize>,
    sizes: [WidgetSize] = WidgetSize.allCases,
    editing: Bool,
    handle: WidgetHandlePlacement = .outside,
    align: WidgetAlign = .start,
    resetSize: WidgetSize? = nil,
    @ViewBuilder content: () -> Content
  ) {
    self.size = size.wrappedValue
    binding = size
    self.sizes = sizes
    self.editing = editing
    self.handle = handle
    self.align = align
    self.resetSize = resetSize
    self.content = content()
    preview = nil
  }

  init(
    size: WidgetSize,
    editing: Bool,
    handle: WidgetHandlePlacement,
    preview: (WidgetSize, CGSize),
    @ViewBuilder content: () -> Content
  ) {
    self.size = size
    binding = nil
    sizes = WidgetSize.allCases
    self.editing = editing
    self.handle = handle
    align = .start
    resetSize = nil
    self.content = content()
    self.preview = preview
  }

  public var body: some View {
    if binding == nil && preview == nil {
      card(frame: size?.dimensions)
    } else {
      editable
    }
  }

  private var current: WidgetSize {
    binding?.wrappedValue ?? size ?? .small
  }

  private var editable: some View {
    let dragging = drag != nil || preview != nil
    let frame = preview?.1 ?? drag ?? current.dimensions
    let snap = preview?.0 ?? target
    return card(frame: frame, animated: !dragging)
      .overlay(alignment: .topLeading) {
        if let snap, dragging {
          RoundedRectangle(cornerRadius: Radius.xl3, style: .continuous)
            .strokeBorder(EsuissColor.foreground.opacity(0.25), style: StrokeStyle(lineWidth: 1, lineCap: .round, dash: [3, 3]))
            .frame(width: snap.dimensions.width, height: snap.dimensions.height)
            .transition(.opacity)
            .animation(reduceMotion ? nil : .timingCurve(0.32, 0.72, 0, 1, duration: 0.5), value: snap)
            .allowsHitTesting(false)
        }
      }
      .overlay(alignment: .bottomTrailing) {
        if editing {
          WidgetHandle(placement: handle, dragging: dragging)
            .gesture(resizeGesture)
            .onTapGesture(count: 2) { reset() }
            .transition(.opacity)
        }
      }
      .hapticFeedback(.selection, trigger: target) { old, new in
        HapticMoments.lifted(old, new)
      }
      .frame(maxWidth: .infinity, alignment: .leading)
      .onGeometryChange(for: CGFloat.self) { proxy in
        proxy.size.width
      } action: { width in
        room = width
      }
  }

  private var resizeGesture: some Gesture {
    DragGesture(minimumDistance: 2, coordinateSpace: .global)
      .onChanged { value in
        let start = current.dimensions
        let direction: CGFloat = layoutDirection == .rightToLeft ? -1 : 1
        let translation = CGSize(width: value.translation.width * direction, height: value.translation.height)
        drag = WidgetMath.frame(start: start, translation: translation, room: room, sizes: sizes)
        target = WidgetMath.target(start: start, translation: translation, room: room, sizes: sizes)
      }
      .onEnded { _ in
        let next = target
        withAnimation(reduceMotion ? nil : .timingCurve(0.32, 0.72, 0, 1, duration: 0.5)) {
          drag = nil
          target = nil
          if let next, next != current { binding?.wrappedValue = next }
        }
      }
  }

  private func reset() {
    guard let resetSize else { return }
    withAnimation(reduceMotion ? nil : .timingCurve(0.32, 0.72, 0, 1, duration: 0.5)) {
      binding?.wrappedValue = resetSize
    }
  }

  private func card(frame: CGSize?, animated: Bool = true) -> some View {
    let shape = RoundedRectangle(cornerRadius: Radius.xl3, style: .continuous)
    let center = align == .center
    return VStack(alignment: center ? .center : .leading, spacing: 12) {
      content
    }
    .padding(16)
    .frame(
      maxWidth: frame == nil ? .infinity : nil,
      maxHeight: frame == nil ? .infinity : nil,
      alignment: center ? .center : .topLeading
    )
    .frame(width: frame?.width, height: frame?.height, alignment: center ? .center : .topLeading)
    .multilineTextAlignment(center ? .center : .leading)
    .scaledFont(TextStyle.base)
    .foregroundStyle(EsuissColor.foreground)
    .background(EsuissColor.muted, in: shape)
    .clipShape(shape)
    .environment(\.widgetSize, frame == nil ? nil : (binding?.wrappedValue ?? size))
    .environment(\.widgetAlign, align)
    .animation(animated && !reduceMotion ? .timingCurve(0.42, 0, 0.58, 1, duration: 0.5) : nil, value: frame?.width)
    .animation(animated && !reduceMotion ? .timingCurve(0.42, 0, 0.58, 1, duration: 0.5) : nil, value: frame?.height)
  }
}

struct WidgetHandle: View {
  let placement: WidgetHandlePlacement
  let dragging: Bool

  var body: some View {
    let inside = placement == .inside
    let side: CGFloat = inside ? 28 : 34
    Canvas { context, size in
      var path = Path()
      if inside {
        path.move(to: CGPoint(x: 19.9, y: 9.3))
        path.addQuadCurve(to: CGPoint(x: 9.3, y: 19.9), control: CGPoint(x: 17.6, y: 17.6))
      } else {
        path.move(to: CGPoint(x: 29.9, y: 13.9))
        path.addQuadCurve(to: CGPoint(x: 13.9, y: 29.9), control: CGPoint(x: 26.4, y: 26.4))
      }
      context.stroke(
        path,
        with: .color(dragging ? EsuissColor.primary : EsuissColor.border),
        style: StrokeStyle(lineWidth: 4, lineCap: .round)
      )
    }
    .frame(width: side, height: side)
    .contentShape(Rectangle().inset(by: -12))
    .offset(x: inside ? 0 : 6, y: inside ? 0 : 6)
    .accessibilityHidden(true)
  }
}

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

  @Environment(\.widgetAlign) private var align

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

  public var body: some View {
    if align == .center {
      VStack(spacing: 12) { content }
    } else {
      HStack(spacing: 8) { content }
        .frame(maxWidth: .infinity, alignment: .leading)
    }
  }
}

public enum WidgetIconSize: CaseIterable, Sendable {
  case `default`, sm, lg
}

public struct WidgetIcon<Content: View>: View {
  let size: WidgetIconSize
  let content: Content

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

  public var body: some View {
    switch size {
    case .sm:
      content
        .frame(width: 14, height: 14)
        .accessibilityHidden(true)
    case .default:
      content
        .frame(width: 18, height: 18)
        .frame(width: 32, height: 32)
        .background(EsuissColor.secondary, in: RoundedRectangle(cornerRadius: Radius.lg, style: .continuous))
        .accessibilityHidden(true)
    case .lg:
      content
        .frame(width: 24, height: 24)
        .frame(width: 52, height: 52)
        .background(EsuissColor.secondary, in: RoundedRectangle(cornerRadius: Radius.xl2, style: .continuous))
        .accessibilityHidden(true)
    }
  }
}

public struct WidgetTitle: View {
  let text: Text

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

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

  public var body: some View {
    text
      .scaledFont(.sm, weight: .semibold)
      .lineLimit(1)
      .truncationMode(.tail)
  }
}

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

  @Environment(\.widgetAlign) private var align

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

  public var body: some View {
    if align != .center {
      Spacer(minLength: 0)
      content
    }
  }
}

public struct WidgetDescription: 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(EsuissColor.mutedForeground)
  }
}

public struct WidgetValue: View {
  let text: Text

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

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

  public var body: some View {
    text
      .scaledFont(.xl2, weight: .semibold)
      .tracking(-0.6)
      .monospacedDigit()
      .lineLimit(1)
      .fixedSize(horizontal: false, vertical: true)
  }
}

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

  @Environment(\.widgetAlign) private var align

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

  public var body: some View {
    VStack(alignment: align == .center ? .center : .leading, spacing: 4) {
      content
    }
    .fixedSize(horizontal: false, vertical: true)
    .frame(maxWidth: .infinity, alignment: align == .center ? .center : .leading)
  }
}

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

  @Environment(\.widgetAlign) private var align

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

  public var body: some View {
    VStack(spacing: 0) {
      if align != .center {
        Spacer(minLength: 0)
      }
      HStack(spacing: 6) {
        content
      }
      .scaledFont(.xs)
      .foregroundStyle(EsuissColor.mutedForeground)
      .lineLimit(1)
    }
  }
}

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

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

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

- `swift/Components/ButtonGroup.swift`: see [Button Group](https://ui.suiss.app/docs/components/button-group.md)

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

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

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

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

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

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

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

- `swift/Patterns/Preview.swift`: see [Preview](https://ui.suiss.app/docs/patterns/preview.md)

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

2. Copy the theme files every view uses:

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

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

3. Copy the source and every file it uses:

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

import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
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.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
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.semantics.stateDescription
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.Dp
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

enum class WidgetSize(val width: Dp, val height: Dp, internal val label: String) {
    Auto(0.dp, 0.dp, "auto"),
    Small(168.dp, 168.dp, "small"),
    Medium(352.dp, 168.dp, "medium"),
    Large(352.dp, 352.dp, "large"),
    ExtraLarge(720.dp, 352.dp, "extra large"),
}

enum class WidgetHandlePlacement { Inside, Outside }

enum class WidgetAlign { Start, Center }

enum class WidgetIconSize { Default, Sm, Lg }

@Stable
interface WidgetScope {
    val size: WidgetSize
}

private class WidgetScopeImpl(override val size: WidgetSize) : WidgetScope

private val LocalWidgetAlign = staticCompositionLocalOf { WidgetAlign.Start }

private val DefaultWidgetSizes = listOf(WidgetSize.Small, WidgetSize.Medium, WidgetSize.Large, WidgetSize.ExtraLarge)

private const val WidgetStretch = 48f

private fun nearestSize(width: Float, height: Float, sizes: List<WidgetSize>): WidgetSize? =
    sizes.minByOrNull {
        val dx = width - it.width.value
        val dy = height - it.height.value
        dx * dx + dy * dy
    }

private fun sizesThatFit(sizes: List<WidgetSize>, room: Dp): List<WidgetSize> {
    val fixed = sizes.filter { it != WidgetSize.Auto }
    val fitting = fixed.filter { it.width <= room }
    if (fitting.isNotEmpty()) return fitting
    return listOfNotNull(fixed.minByOrNull { it.width })
}

private object WidgetContentSlot

private object WidgetFooterSlot

private object WidgetActionSlot

@Composable
fun Widget(
    modifier: Modifier = Modifier,
    size: WidgetSize? = null,
    defaultSize: WidgetSize? = null,
    onSizeChange: ((WidgetSize) -> Unit)? = null,
    sizes: List<WidgetSize> = DefaultWidgetSizes,
    resizable: Boolean = false,
    handle: WidgetHandlePlacement = WidgetHandlePlacement.Outside,
    align: WidgetAlign = WidgetAlign.Start,
    content: @Composable WidgetScope.() -> Unit,
) {
    val initial = defaultSize ?: if (resizable) WidgetSize.Small else WidgetSize.Auto
    var uncontrolled by remember { mutableStateOf(initial) }
    val current = size ?: uncontrolled
    val sizeChange by rememberUpdatedState(onSizeChange)
    val select: (WidgetSize) -> Unit = { next ->
        if (size == null) uncontrolled = next
        sizeChange?.invoke(next)
    }
    BoxWithConstraints {
        val room = maxWidth
        val reachable = sizesThatFit(sizes, room)
        var drag by remember { mutableStateOf<Offset?>(null) }
        var preview by remember { mutableStateOf<WidgetSize?>(null) }
        val haptics = rememberHaptics()
        val reduced = formReducedMotion()
        val auto = current == WidgetSize.Auto
        val targetWidth = if (auto) room else minOf(current.width, room)
        val targetHeight = current.height
        val dragging = drag != null
        val spec = if (dragging || reduced) snap<Dp>() else tween(500, easing = FormEasing)
        val boundsWidth = reachable.maxOfOrNull { it.width } ?: WidgetSize.Small.width
        val boundsHeight = reachable.maxOfOrNull { it.height } ?: WidgetSize.Small.height
        val dragWidth = drag?.let {
            (targetWidth.value + it.x).coerceIn(WidgetSize.Small.width.value, minOf(boundsWidth.value + WidgetStretch, room.value)).dp
        }
        val dragHeight = drag?.let {
            (targetHeight.value + it.y).coerceIn(WidgetSize.Small.height.value, boundsHeight.value + WidgetStretch).dp
        }
        val width by animateDpAsState(dragWidth ?: targetWidth, spec, label = "width")
        val height by animateDpAsState(dragHeight ?: targetHeight, spec, label = "height")
        val colors = EsuissTheme.colors
        val surface = @Composable {
            WidgetSurface(
                modifier = modifier
                    .then(if (auto && !resizable) Modifier.fillMaxWidth() else Modifier.size(width, height)),
                size = current,
                align = align,
                content = content,
            )
        }
        if (!resizable) {
            surface()
            return@BoxWithConstraints
        }
        val accent = colors.primary
        val idle = colors.border
        val outline = colors.foreground.copy(alpha = 0.25f)
        Box(
            modifier = Modifier.drawWithContent {
                drawContent()
                val shown = preview ?: return@drawWithContent
                val stroke = 1.dp.toPx()
                drawRoundRect(
                    color = outline,
                    size = Size(minOf(shown.width, room).toPx(), shown.height.toPx()),
                    cornerRadius = CornerRadius(28.dp.toPx()),
                    style = Stroke(stroke, pathEffect = PathEffect.dashPathEffect(floatArrayOf(3.dp.toPx(), 3.dp.toPx())), cap = StrokeCap.Round),
                )
            },
        ) {
            surface()
            val outside = handle == WidgetHandlePlacement.Outside
            Box(
                modifier = Modifier
                    .offset { IntOffset((width - 48.dp).roundToPx(), (height - 48.dp).roundToPx()) }
                    .size(48.dp)
                    .drawBehind {
                        val corner = 28.dp.toPx()
                        val radius = (if (outside) 33.dp else 22.dp).toPx()
                        val center = Offset(this.size.width - corner, this.size.height - corner)
                        drawArc(
                            color = if (dragging) accent else idle,
                            startAngle = 24.9f,
                            sweepAngle = 40.2f,
                            useCenter = false,
                            topLeft = center - Offset(radius, radius),
                            size = Size(radius * 2, radius * 2),
                            style = Stroke(4.dp.toPx(), cap = StrokeCap.Round),
                        )
                    }
                    .semantics {
                        contentDescription = "Resize widget"
                        stateDescription = current.label
                        customActions = reachable.filter { it != current }.map { option ->
                            CustomAccessibilityAction("Resize to ${option.label}") {
                                select(option)
                                true
                            }
                        }
                    }
                    .pointerInput(initial) {
                        detectTapGestures(onDoubleTap = { select(initial) })
                    }
                    .pointerInput(reachable, current, targetWidth) {
                        var last: WidgetSize? = null
                        detectDragGestures(
                            onDragStart = {
                                last = null
                                drag = Offset.Zero
                            },
                            onDrag = { change, amount ->
                                change.consume()
                                val next = (drag ?: Offset.Zero) + Offset(amount.x / density, amount.y / density)
                                drag = next
                                val nearest = nearestSize(targetWidth.value + next.x, targetHeight.value + next.y, reachable)
                                if (nearest != last) {
                                    if (last != null || nearest != current) haptics.selection()
                                    last = nearest
                                    preview = nearest
                                }
                            },
                            onDragEnd = {
                                drag = null
                                preview = null
                                val chosen = last
                                if (chosen != null && chosen != current) select(chosen)
                            },
                            onDragCancel = {
                                drag = null
                                preview = null
                            },
                        )
                    },
            )
        }
    }
}

@Composable
private fun WidgetSurface(
    modifier: Modifier,
    size: WidgetSize,
    align: WidgetAlign,
    content: @Composable WidgetScope.() -> Unit,
) {
    val colors = EsuissTheme.colors
    val shape = RoundedCornerShape(Radius.xl3)
    val scope = remember(size) { WidgetScopeImpl(size) }
    val center = align == WidgetAlign.Center
    CompositionLocalProvider(
        LocalWidgetAlign provides align,
        LocalContentStyle provides Typography.base.copy(color = colors.foreground, textAlign = if (center) TextAlign.Center else TextAlign.Unspecified),
        LocalContentColor provides colors.foreground,
    ) {
        Layout(
            content = { scope.content() },
            modifier = modifier
                .clip(shape)
                .background(colors.muted, shape)
                .semantics(mergeDescendants = false) { stateDescription = size.label },
        ) { measurables, constraints ->
            val padding = 16.dp.roundToPx()
            val gap = 12.dp.roundToPx()
            val innerWidth = (constraints.maxWidth - padding * 2).coerceAtLeast(0)
            val bounded = constraints.hasBoundedHeight
            val innerHeight = if (bounded) (constraints.maxHeight - padding * 2).coerceAtLeast(0) else Int.MAX_VALUE
            val child = constraints.copy(minWidth = 0, maxWidth = innerWidth, minHeight = 0)
            val flexible = measurables.indexOfFirst { it.layoutId == WidgetContentSlot }
            val placeables = arrayOfNulls<Placeable>(measurables.size)
            var used = 0
            measurables.forEachIndexed { i, measurable ->
                if (i == flexible) return@forEachIndexed
                val placeable = measurable.measure(child.copy(maxHeight = if (bounded) innerHeight else Int.MAX_VALUE))
                placeables[i] = placeable
                used += placeable.height
            }
            val gaps = gap * (measurables.size - 1).coerceAtLeast(0)
            if (flexible >= 0) {
                val remaining = if (bounded) (innerHeight - used - gaps).coerceAtLeast(0) else Int.MAX_VALUE
                placeables[flexible] = measurables[flexible].measure(child.copy(maxHeight = remaining))
            }
            val items = placeables.map { it!! }
            val stacked = items.sumOf { it.height } + gaps
            val width = constraints.maxWidth.takeIf { constraints.hasBoundedWidth } ?: (items.maxOfOrNull { it.width } ?: 0) + padding * 2
            val height = if (bounded && constraints.minHeight == constraints.maxHeight) constraints.maxHeight else constraints.constrainHeight(stacked + padding * 2)
            val footerIndex = measurables.indexOfFirst { it.layoutId == WidgetFooterSlot }
            layout(width, height) {
                val contentHeight = height - padding * 2
                var y = padding + if (center) ((contentHeight - stacked) / 2).coerceAtLeast(0) else 0
                items.forEachIndexed { i, placeable ->
                    val x = padding + if (center) (innerWidth - placeable.width) / 2 else 0
                    val top = if (!center && i == footerIndex && i == items.lastIndex) {
                        maxOf(y, height - padding - placeable.height)
                    } else {
                        y
                    }
                    placeable.place(x, top)
                    y = top + placeable.height + gap
                }
            }
        }
    }
}

@Composable
fun WidgetHeader(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    val center = LocalWidgetAlign.current == WidgetAlign.Center
    Layout(content = content, modifier = modifier) { measurables, constraints ->
        val loose = constraints.copy(minWidth = 0, minHeight = 0)
        if (center) {
            val gap = 12.dp.roundToPx()
            val placeables = measurables.filter { it.layoutId != WidgetActionSlot }.map { it.measure(loose) }
            val width = placeables.maxOfOrNull { it.width } ?: 0
            val height = placeables.sumOf { it.height } + gap * (placeables.size - 1).coerceAtLeast(0)
            layout(width, height) {
                var y = 0
                placeables.forEach {
                    it.place((width - it.width) / 2, y)
                    y += it.height + gap
                }
            }
        } else {
            val gap = 8.dp.roundToPx()
            val actionIndex = measurables.indexOfFirst { it.layoutId == WidgetActionSlot }
            val action = actionIndex.takeIf { it >= 0 }?.let { measurables[it].measure(loose) }
            var remaining = constraints.maxWidth - (action?.let { it.width + gap } ?: 0)
            val placeables = measurables.mapIndexedNotNull { i, measurable ->
                if (i == actionIndex) return@mapIndexedNotNull null
                val placeable = measurable.measure(loose.copy(maxWidth = remaining.coerceAtLeast(0)))
                remaining -= placeable.width + gap
                placeable
            }
            val height = maxOf(placeables.maxOfOrNull { it.height } ?: 0, action?.height ?: 0)
            val width = constraints.maxWidth
            layout(width, height) {
                var x = 0
                placeables.forEach {
                    it.place(x, (height - it.height) / 2)
                    x += it.width + gap
                }
                action?.place(width - action.width, (height - action.height) / 2)
            }
        }
    }
}

@Composable
fun WidgetIcon(
    modifier: Modifier = Modifier,
    size: WidgetIconSize = WidgetIconSize.Default,
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    val (box, icon, radius) = when (size) {
        WidgetIconSize.Default -> Triple(32.dp, 18.dp, Radius.lg)
        WidgetIconSize.Lg -> Triple(52.dp, 24.dp, Radius.xl2)
        WidgetIconSize.Sm -> Triple(14.dp, 14.dp, 0.dp)
    }
    val shape = RoundedCornerShape(radius)
    Box(
        modifier = modifier
            .size(box)
            .then(if (size == WidgetIconSize.Sm) Modifier else Modifier.background(colors.secondary, shape)),
        contentAlignment = Alignment.Center,
    ) {
        CompositionLocalProvider(LocalIconSize provides icon) {
            content()
        }
    }
}

@Composable
fun WidgetTitle(text: String, modifier: Modifier = Modifier) {
    BasicText(
        text,
        modifier = modifier,
        style = LocalContentStyle.current.merge(Typography.sm).copy(fontWeight = FontWeight.SemiBold),
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
    )
}

@Composable
fun WidgetAction(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    Row(modifier = modifier.layoutId(WidgetActionSlot), verticalAlignment = Alignment.CenterVertically) {
        content()
    }
}

@Composable
fun WidgetDescription(text: String, modifier: Modifier = Modifier) {
    BasicText(
        text,
        modifier = modifier,
        style = LocalContentStyle.current.merge(Typography.sm).copy(color = EsuissTheme.colors.mutedForeground),
    )
}

@Composable
fun WidgetValue(text: String, modifier: Modifier = Modifier) {
    BasicText(
        text,
        modifier = modifier,
        style = LocalContentStyle.current.merge(Typography.xl3).copy(
            fontWeight = FontWeight.SemiBold,
            letterSpacing = (-0.025).em,
            fontFeatureSettings = "tnum",
        ),
        maxLines = 1,
    )
}

@Composable
fun WidgetContent(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    val center = LocalWidgetAlign.current == WidgetAlign.Center
    Column(
        modifier = modifier.layoutId(WidgetContentSlot),
        verticalArrangement = Arrangement.spacedBy(4.dp),
        horizontalAlignment = if (center) Alignment.CenterHorizontally else Alignment.Start,
    ) {
        content()
    }
}

@Composable
fun WidgetFooter(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    val colors = EsuissTheme.colors
    CompositionLocalProvider(
        LocalContentStyle provides LocalContentStyle.current.merge(Typography.xs).copy(color = colors.mutedForeground),
        LocalContentColor provides colors.mutedForeground,
        LocalIconSize provides 14.dp,
    ) {
        Row(
            modifier = modifier.layoutId(WidgetFooterSlot),
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            content()
        }
    }
}
```

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

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

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

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

## Usage

```tsx
import { Widget, WidgetHeader, WidgetIcon, WidgetTitle, WidgetAction, WidgetDescription, WidgetValue, WidgetContent, WidgetFooter } from "@/components/ui/widget"
```

```tsx
<Widget size="small" align="start">
  <Weather />
</Widget>
```

Compose the content from `WidgetHeader` (with `WidgetIcon`, `WidgetTitle` and `WidgetAction`), then `WidgetValue`, `WidgetDescription` or `WidgetContent`, and `WidgetFooter`, which sticks to the bottom. Plain strings passed to `WidgetContent` and `WidgetFooter` are wrapped in `Text`.

The size is uncontrolled with `defaultSize`, or controlled with `size` and `onSizeChange`. Use `sizes` to limit which sizes the user can pick. A non-resizable widget defaults to `auto`; a resizable one defaults to `small`.

`useWidget` returns the current `size` and `align` so custom content can adapt to the widget size.

## Examples

### Sizes

The four fixed sizes side by side.

![Preview](https://ui.suiss.app/previews/components-widget--sizes.light.webp)

```tsx
import { ScrollView } from "react-native"
import { Widget, WidgetFooter, WidgetHeader, type WidgetSize, WidgetTitle } from "@/components/ui/widget"

const gridSpans: Record<WidgetSize, string> = {
  small: "1 × 1",
  medium: "2 × 1",
  large: "2 × 2",
  "extra-large": "4 × 2",
}

export function WidgetSizesExample() {
  return (
    <ScrollView
      horizontal
      contentContainerClassName="items-start gap-4"
      showsHorizontalScrollIndicator={false}
    >
      {(["small", "medium", "large", "extra-large"] as const).map((size) => (
        <Widget key={size} size={size}>
          <WidgetHeader>
            <WidgetTitle className="capitalize">
              {size.replace("-", " ")}
            </WidgetTitle>
          </WidgetHeader>
          <WidgetFooter>{gridSpans[size]}</WidgetFooter>
        </Widget>
      ))}
    </ScrollView>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct WidgetSizesExample: View {
  var body: some View {
    ScrollView(.horizontal, showsIndicators: false) {
      HStack(alignment: .top, spacing: 16) {
        ForEach(widgetSizeNames, id: \.title) { entry in
          Widget(entry.size) {
            WidgetHeader {
              WidgetTitle(verbatim: entry.title)
            }
            WidgetFooter(verbatim: entry.span)
          }
        }
      }
    }
  }
}

struct WidgetSizeName {
  let size: WidgetSize
  let title: String
  let span: String
}

let widgetSizeNames = [
  WidgetSizeName(size: .small, title: "Small", span: "1 × 1"),
  WidgetSizeName(size: .medium, title: "Medium", span: "2 × 1"),
  WidgetSizeName(size: .large, title: "Large", span: "2 × 2"),
  WidgetSizeName(size: .extraLarge, title: "Extra large", span: "4 × 2"),
]
```

```kotlin
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
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.components.Widget
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle

fun widgetSizeName(size: WidgetSize): String = when (size) {
    WidgetSize.Auto -> "auto"
    WidgetSize.Small -> "small"
    WidgetSize.Medium -> "medium"
    WidgetSize.Large -> "large"
    WidgetSize.ExtraLarge -> "extra-large"
}

fun widgetGridSpan(size: WidgetSize): String = when (size) {
    WidgetSize.Small -> "1 × 1"
    WidgetSize.Medium -> "2 × 1"
    WidgetSize.Large -> "2 × 2"
    else -> "4 × 2"
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetSizes() {
    Row(
        Modifier.horizontalScroll(rememberScrollState()),
        horizontalArrangement = Arrangement.spacedBy(16.dp),
        verticalAlignment = Alignment.Top,
    ) {
        listOf(WidgetSize.Small, WidgetSize.Medium, WidgetSize.Large, WidgetSize.ExtraLarge).forEach { size ->
            Widget(size = size) {
                WidgetHeader {
                    WidgetTitle(
                        widgetSizeName(size).split("-").joinToString(" ") { word -> word.replaceFirstChar { it.uppercaseChar() } },
                    )
                }
                WidgetFooterText(widgetGridSpan(size))
            }
        }
    }
}
```

### Editing

A resizable widget starting at `large`.

![Preview](https://ui.suiss.app/previews/components-widget--editing.light.webp)

```tsx
import { CashRegisterIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
import { useWidget, Widget, WidgetContent, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

const hourly = [12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14].map(
  (value, hour) => ({ hour: hour + 10, value })
)

const topItems = [
  { name: "Grilled meatballs", count: 38 },
  { name: "Lahmacun", count: 31 },
  { name: "Adana kebab", count: 24 },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <Text className="mt-6 text-xs text-muted-foreground">{children}</Text>
}

function SalesBody() {
  const { size } = useWidget()
  return (
    <>
      <WidgetHeader className="gap-1.5">
        <WidgetIcon
          size="sm"
          iconClassName="text-amber-600 dark:text-amber-400"
        >
          <Icon as={CashRegisterIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle className="text-amber-600 dark:text-amber-400">
          Hestia
        </WidgetTitle>
      </WidgetHeader>
      <View
        className={
          size === "medium"
            ? "min-h-0 grow flex-row items-end gap-3"
            : "min-h-0 gap-3"
        }
      >
        <WidgetContent className="grow-0">
          <WidgetValue>₺18,240</WidgetValue>
          <WidgetDescription>Today's revenue</WidgetDescription>
        </WidgetContent>
        {size === "small" ? null : (
          <View
            className={
              size === "medium"
                ? "h-full flex-1 flex-row items-end gap-1"
                : "h-14 flex-row items-end gap-1"
            }
          >
            {hourly.map(({ hour, value }) => (
              <View
                key={hour}
                className={
                  value === 100
                    ? "flex-1 rounded-sm bg-amber-500"
                    : "flex-1 rounded-sm bg-amber-500/40"
                }
                style={{ height: `${value}%` }}
              />
            ))}
          </View>
        )}
      </View>
      {size === "large" || size === "extra-large" ? (
        <View className="min-h-0 shrink overflow-hidden">
          {topItems.map((item) => (
            <View
              key={item.name}
              className="flex-row items-center justify-between border-b border-border py-1.5"
            >
              <Text className="text-sm">{item.name}</Text>
              <Text className="text-sm text-muted-foreground">
                {item.count}
              </Text>
            </View>
          ))}
        </View>
      ) : null}
      <WidgetFooter>42 orders · 18:42</WidgetFooter>
    </>
  )
}

export function WidgetEditingExample() {
  return (
    <View className="w-full">
      <Widget resizable defaultSize="large">
        <SalesBody />
      </Widget>
      <Hint>
        Drag the corner handle to snap between sizes. Double tap it to reset.
      </Hint>
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetEditingExample: View {
  var body: some View {
    VStack(alignment: .leading, spacing: 0) {
      WidgetEditable(initial: .large) {
        WidgetSales()
      }
      WidgetHint(text: "Drag the corner handle to snap between sizes. Double tap it to reset.")
    }
    .frame(maxWidth: .infinity, alignment: .leading)
  }
}

let widgetHourly: [CGFloat] = [12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14]

struct WidgetTopItem {
  let name: String
  let count: Int
}

let widgetTopItems = [
  WidgetTopItem(name: "Grilled meatballs", count: 38),
  WidgetTopItem(name: "Lahmacun", count: 31),
  WidgetTopItem(name: "Adana kebab", count: 24),
]

struct WidgetHint: View {
  let text: String

  var body: some View {
    Text(verbatim: text)
      .textStyle(.xs)
      .foregroundStyle(EsuissColor.mutedForeground)
      .padding(.top, 24)
  }
}

struct WidgetEditable<Content: View>: View {
  let sizes: [WidgetSize]
  let handle: WidgetHandlePlacement
  let resetSize: WidgetSize
  @ViewBuilder let content: () -> Content

  @State private var size: WidgetSize

  init(
    initial: WidgetSize,
    sizes: [WidgetSize] = WidgetSize.allCases,
    handle: WidgetHandlePlacement = .outside,
    @ViewBuilder content: @escaping () -> Content
  ) {
    self.sizes = sizes
    self.handle = handle
    resetSize = initial
    self.content = content
    _size = State(initialValue: initial)
  }

  var body: some View {
    Widget(size: $size, sizes: sizes, editing: true, handle: handle, resetSize: resetSize) {
      content()
    }
  }
}

struct WidgetSalesHeader: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon(size: .sm) {
        Ph.cashRegister.fill.foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
      }
      WidgetTitle("Hestia")
        .foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
    }
  }
}

struct WidgetBars: View {
  var body: some View {
    GeometryReader { proxy in
      HStack(alignment: .bottom, spacing: 4) {
        ForEach(Array(widgetHourly.enumerated()), id: \.offset) { _, value in
          RoundedRectangle(cornerRadius: Radius.sm, style: .continuous)
            .fill(value == 100 ? Palette.amber500 : Palette.amber500.opacity(0.4))
            .frame(height: proxy.size.height * value / 100)
            .frame(maxWidth: .infinity)
        }
      }
      .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
    }
    .accessibilityHidden(true)
  }
}

struct WidgetSales: View {
  @Environment(\.widgetSize) private var size

  var body: some View {
    WidgetSalesHeader()
    if size == .medium {
      HStack(alignment: .bottom, spacing: 12) {
        revenue
        WidgetBars()
      }
      .frame(maxHeight: .infinity)
    } else {
      VStack(alignment: .leading, spacing: 12) {
        revenue
        if size != .small {
          WidgetBars().frame(height: 56)
        }
      }
    }
    if size == .large || size == .extraLarge {
      VStack(spacing: 0) {
        ForEach(widgetTopItems, id: \.name) { item in
          HStack {
            Text(verbatim: item.name)
              .textStyle(.sm)
            Spacer(minLength: 8)
            Text(verbatim: "\(item.count)")
              .textStyle(.sm)
              .foregroundStyle(EsuissColor.mutedForeground)
          }
          .padding(.vertical, 6)
          .overlay(alignment: .bottom) {
            EsuissColor.border.frame(height: 1)
          }
        }
      }
      .clipped()
    }
    WidgetFooter(verbatim: "42 orders · 18:42")
  }

  var revenue: some View {
    WidgetContent {
      WidgetValue(verbatim: "₺18,240")
      WidgetDescription("Today's revenue")
    }
    .fixedSize(horizontal: true, vertical: false)
  }
}
```

```kotlin
import androidx.compose.foundation.background
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.CashRegister
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.Separator
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetIconSize
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

val widgetHourly = listOf(12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14)

val widgetTopItems = listOf(
    "Grilled meatballs" to 38,
    "Lahmacun" to 31,
    "Adana kebab" to 24,
)

@Composable
fun WidgetTintedTitle(text: String, color: Color) {
    CompositionLocalProvider(LocalContentStyle provides LocalContentStyle.current.copy(color = color)) {
        WidgetTitle(text)
    }
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetHint(text: String) {
    Text(
        text,
        Modifier.padding(top = 24.dp),
        style = Typography.xs,
        color = EsuissTheme.colors.mutedForeground,
    )
}

@Composable
fun WidgetSalesHeader() {
    val warning = if (EsuissTheme.colors.isDark) Palette.amber400 else Palette.amber600
    WidgetHeader {
        WidgetIcon(size = WidgetIconSize.Sm) { Icon(PhosphorIcons.Fill.CashRegister, contentDescription = null, tint = warning) }
        WidgetTintedTitle("Hestia", warning)
    }
}

@Composable
fun WidgetRevenue() {
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        WidgetValue("₺18,240")
        WidgetDescription("Today's revenue")
    }
}

@Composable
fun WidgetBars(modifier: Modifier) {
    val warning = if (EsuissTheme.colors.isDark) Palette.amber400 else Palette.amber600
    Row(modifier, horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.Bottom) {
        widgetHourly.forEach { value ->
            Box(
                Modifier
                    .weight(1f)
                    .fillMaxHeight(value / 100f)
                    .background(if (value == 100) warning else warning.copy(alpha = 0.4f), RoundedCornerShape(Radius.sm)),
            )
        }
    }
}

@Composable
fun WidgetSalesBody(size: WidgetSize) {
    WidgetSalesHeader()
    if (size == WidgetSize.Medium) {
        WidgetContent {
            Row(
                Modifier.fillMaxWidth().fillMaxHeight(),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.Bottom,
            ) {
                WidgetRevenue()
                WidgetBars(Modifier.weight(1f).fillMaxHeight())
            }
        }
    } else {
        WidgetContent {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                WidgetRevenue()
                if (size != WidgetSize.Small) WidgetBars(Modifier.fillMaxWidth().height(56.dp))
            }
        }
    }
    if (size == WidgetSize.Large || size == WidgetSize.ExtraLarge) {
        Column {
            widgetTopItems.forEach { (name, count) ->
                Row(
                    Modifier.fillMaxWidth().padding(vertical = 6.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(name, style = Typography.sm)
                    Text(count.toString(), style = Typography.sm, color = EsuissTheme.colors.mutedForeground)
                }
                Separator()
            }
        }
    }
    WidgetFooterText("42 orders · 18:42")
}

@Composable
fun WidgetEditing() {
    Column(Modifier.fillMaxWidth()) {
        Widget(resizable = true, defaultSize = WidgetSize.Large) { WidgetSalesBody(size) }
        WidgetHint("Drag the corner handle to snap between sizes. Double tap it to reset.")
    }
}
```

### Inside handle

A resizable widget with the handle drawn inside the corner.

![Preview](https://ui.suiss.app/previews/components-widget--inside-handle.light.webp)

```tsx
import { CashRegisterIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
import { useWidget, Widget, WidgetContent, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

const hourly = [12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14].map(
  (value, hour) => ({ hour: hour + 10, value })
)

const topItems = [
  { name: "Grilled meatballs", count: 38 },
  { name: "Lahmacun", count: 31 },
  { name: "Adana kebab", count: 24 },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <Text className="mt-6 text-xs text-muted-foreground">{children}</Text>
}

function SalesBody() {
  const { size } = useWidget()
  return (
    <>
      <WidgetHeader className="gap-1.5">
        <WidgetIcon
          size="sm"
          iconClassName="text-amber-600 dark:text-amber-400"
        >
          <Icon as={CashRegisterIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle className="text-amber-600 dark:text-amber-400">
          Hestia
        </WidgetTitle>
      </WidgetHeader>
      <View
        className={
          size === "medium"
            ? "min-h-0 grow flex-row items-end gap-3"
            : "min-h-0 gap-3"
        }
      >
        <WidgetContent className="grow-0">
          <WidgetValue>₺18,240</WidgetValue>
          <WidgetDescription>Today's revenue</WidgetDescription>
        </WidgetContent>
        {size === "small" ? null : (
          <View
            className={
              size === "medium"
                ? "h-full flex-1 flex-row items-end gap-1"
                : "h-14 flex-row items-end gap-1"
            }
          >
            {hourly.map(({ hour, value }) => (
              <View
                key={hour}
                className={
                  value === 100
                    ? "flex-1 rounded-sm bg-amber-500"
                    : "flex-1 rounded-sm bg-amber-500/40"
                }
                style={{ height: `${value}%` }}
              />
            ))}
          </View>
        )}
      </View>
      {size === "large" || size === "extra-large" ? (
        <View className="min-h-0 shrink overflow-hidden">
          {topItems.map((item) => (
            <View
              key={item.name}
              className="flex-row items-center justify-between border-b border-border py-1.5"
            >
              <Text className="text-sm">{item.name}</Text>
              <Text className="text-sm text-muted-foreground">
                {item.count}
              </Text>
            </View>
          ))}
        </View>
      ) : null}
      <WidgetFooter>42 orders · 18:42</WidgetFooter>
    </>
  )
}

export function WidgetInsideHandleExample() {
  return (
    <View className="w-full">
      <Widget resizable handle="inside" defaultSize="medium">
        <SalesBody />
      </Widget>
      <Hint>The handle sits inside the corner.</Hint>
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetInsideHandleExample: View {
  var body: some View {
    VStack(alignment: .leading, spacing: 0) {
      WidgetEditable(initial: .medium, handle: .inside) {
        WidgetSales()
      }
      WidgetHint(text: "The handle sits inside the corner.")
    }
    .frame(maxWidth: .infinity, alignment: .leading)
  }
}

let widgetHourly: [CGFloat] = [12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14]

struct WidgetTopItem {
  let name: String
  let count: Int
}

let widgetTopItems = [
  WidgetTopItem(name: "Grilled meatballs", count: 38),
  WidgetTopItem(name: "Lahmacun", count: 31),
  WidgetTopItem(name: "Adana kebab", count: 24),
]

struct WidgetHint: View {
  let text: String

  var body: some View {
    Text(verbatim: text)
      .textStyle(.xs)
      .foregroundStyle(EsuissColor.mutedForeground)
      .padding(.top, 24)
  }
}

struct WidgetEditable<Content: View>: View {
  let sizes: [WidgetSize]
  let handle: WidgetHandlePlacement
  let resetSize: WidgetSize
  @ViewBuilder let content: () -> Content

  @State private var size: WidgetSize

  init(
    initial: WidgetSize,
    sizes: [WidgetSize] = WidgetSize.allCases,
    handle: WidgetHandlePlacement = .outside,
    @ViewBuilder content: @escaping () -> Content
  ) {
    self.sizes = sizes
    self.handle = handle
    resetSize = initial
    self.content = content
    _size = State(initialValue: initial)
  }

  var body: some View {
    Widget(size: $size, sizes: sizes, editing: true, handle: handle, resetSize: resetSize) {
      content()
    }
  }
}

struct WidgetSalesHeader: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon(size: .sm) {
        Ph.cashRegister.fill.foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
      }
      WidgetTitle("Hestia")
        .foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
    }
  }
}

struct WidgetBars: View {
  var body: some View {
    GeometryReader { proxy in
      HStack(alignment: .bottom, spacing: 4) {
        ForEach(Array(widgetHourly.enumerated()), id: \.offset) { _, value in
          RoundedRectangle(cornerRadius: Radius.sm, style: .continuous)
            .fill(value == 100 ? Palette.amber500 : Palette.amber500.opacity(0.4))
            .frame(height: proxy.size.height * value / 100)
            .frame(maxWidth: .infinity)
        }
      }
      .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
    }
    .accessibilityHidden(true)
  }
}

struct WidgetSales: View {
  @Environment(\.widgetSize) private var size

  var body: some View {
    WidgetSalesHeader()
    if size == .medium {
      HStack(alignment: .bottom, spacing: 12) {
        revenue
        WidgetBars()
      }
      .frame(maxHeight: .infinity)
    } else {
      VStack(alignment: .leading, spacing: 12) {
        revenue
        if size != .small {
          WidgetBars().frame(height: 56)
        }
      }
    }
    if size == .large || size == .extraLarge {
      VStack(spacing: 0) {
        ForEach(widgetTopItems, id: \.name) { item in
          HStack {
            Text(verbatim: item.name)
              .textStyle(.sm)
            Spacer(minLength: 8)
            Text(verbatim: "\(item.count)")
              .textStyle(.sm)
              .foregroundStyle(EsuissColor.mutedForeground)
          }
          .padding(.vertical, 6)
          .overlay(alignment: .bottom) {
            EsuissColor.border.frame(height: 1)
          }
        }
      }
      .clipped()
    }
    WidgetFooter(verbatim: "42 orders · 18:42")
  }

  var revenue: some View {
    WidgetContent {
      WidgetValue(verbatim: "₺18,240")
      WidgetDescription("Today's revenue")
    }
    .fixedSize(horizontal: true, vertical: false)
  }
}
```

```kotlin
import androidx.compose.foundation.background
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.CashRegister
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.Separator
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHandlePlacement
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetIconSize
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography

val widgetHourly = listOf(12, 18, 14, 30, 44, 34, 22, 40, 100, 46, 30, 14)

val widgetTopItems = listOf(
    "Grilled meatballs" to 38,
    "Lahmacun" to 31,
    "Adana kebab" to 24,
)

@Composable
fun WidgetTintedTitle(text: String, color: Color) {
    CompositionLocalProvider(LocalContentStyle provides LocalContentStyle.current.copy(color = color)) {
        WidgetTitle(text)
    }
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetHint(text: String) {
    Text(
        text,
        Modifier.padding(top = 24.dp),
        style = Typography.xs,
        color = EsuissTheme.colors.mutedForeground,
    )
}

@Composable
fun WidgetSalesHeader() {
    val warning = if (EsuissTheme.colors.isDark) Palette.amber400 else Palette.amber600
    WidgetHeader {
        WidgetIcon(size = WidgetIconSize.Sm) { Icon(PhosphorIcons.Fill.CashRegister, contentDescription = null, tint = warning) }
        WidgetTintedTitle("Hestia", warning)
    }
}

@Composable
fun WidgetRevenue() {
    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        WidgetValue("₺18,240")
        WidgetDescription("Today's revenue")
    }
}

@Composable
fun WidgetBars(modifier: Modifier) {
    val warning = if (EsuissTheme.colors.isDark) Palette.amber400 else Palette.amber600
    Row(modifier, horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.Bottom) {
        widgetHourly.forEach { value ->
            Box(
                Modifier
                    .weight(1f)
                    .fillMaxHeight(value / 100f)
                    .background(if (value == 100) warning else warning.copy(alpha = 0.4f), RoundedCornerShape(Radius.sm)),
            )
        }
    }
}

@Composable
fun WidgetSalesBody(size: WidgetSize) {
    WidgetSalesHeader()
    if (size == WidgetSize.Medium) {
        WidgetContent {
            Row(
                Modifier.fillMaxWidth().fillMaxHeight(),
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.Bottom,
            ) {
                WidgetRevenue()
                WidgetBars(Modifier.weight(1f).fillMaxHeight())
            }
        }
    } else {
        WidgetContent {
            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
                WidgetRevenue()
                if (size != WidgetSize.Small) WidgetBars(Modifier.fillMaxWidth().height(56.dp))
            }
        }
    }
    if (size == WidgetSize.Large || size == WidgetSize.ExtraLarge) {
        Column {
            widgetTopItems.forEach { (name, count) ->
                Row(
                    Modifier.fillMaxWidth().padding(vertical = 6.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(name, style = Typography.sm)
                    Text(count.toString(), style = Typography.sm, color = EsuissTheme.colors.mutedForeground)
                }
                Separator()
            }
        }
    }
    WidgetFooterText("42 orders · 18:42")
}

@Composable
fun WidgetInsideHandle() {
    Column(Modifier.fillMaxWidth()) {
        Widget(resizable = true, handle = WidgetHandlePlacement.Inside, defaultSize = WidgetSize.Medium) { WidgetSalesBody(size) }
        WidgetHint("The handle sits inside the corner.")
    }
}
```

### Limited sizes

Resizing limited to `small` and `medium`.

![Preview](https://ui.suiss.app/previews/components-widget--limited-sizes.light.webp)

```tsx
import { CalendarBlankIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
import { useWidget, Widget, WidgetContent, WidgetDescription, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

const reservations = [
  { time: "18:00", place: "Table 4" },
  { time: "19:00", place: "Garden 3" },
  { time: "20:00", place: "Table 12" },
  { time: "21:00", place: "Table 7" },
]

function Hint({ children }: { children: React.ReactNode }) {
  return <Text className="mt-6 text-xs text-muted-foreground">{children}</Text>
}

function ReservationsBody() {
  const { size } = useWidget()
  return (
    <>
      <WidgetHeader className="gap-1.5">
        <WidgetIcon size="sm" iconClassName="text-primary">
          <Icon as={CalendarBlankIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle className="text-primary">Reservations</WidgetTitle>
      </WidgetHeader>
      <View className="min-h-0 grow flex-row items-end gap-4">
        <WidgetContent className="grow-0">
          <WidgetValue>12</WidgetValue>
          <WidgetDescription>Tonight</WidgetDescription>
        </WidgetContent>
        {size === "medium" ? (
          <View className="flex-1 gap-1">
            {reservations.slice(0, 3).map((item) => (
              <View key={item.time} className="flex-row gap-3">
                <Text className="w-11 text-sm text-muted-foreground">
                  {item.time}
                </Text>
                <Text className="flex-1 text-sm" numberOfLines={1}>
                  {item.place}
                </Text>
              </View>
            ))}
          </View>
        ) : null}
      </View>
    </>
  )
}

export function WidgetLimitedSizesExample() {
  return (
    <View className="w-full">
      <Widget resizable defaultSize="medium" sizes={["small", "medium"]}>
        <ReservationsBody />
      </Widget>
      <Hint>Only small and medium are offered.</Hint>
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetLimitedSizesExample: View {
  var body: some View {
    VStack(alignment: .leading, spacing: 0) {
      WidgetEditable(initial: .medium, sizes: [.small, .medium]) {
        WidgetReservations()
      }
      WidgetHint(text: "Only small and medium are offered.")
    }
    .frame(maxWidth: .infinity, alignment: .leading)
  }
}

struct WidgetReservation {
  let time: String
  let place: String
}

let widgetReservations = [
  WidgetReservation(time: "18:00", place: "Table 4"),
  WidgetReservation(time: "19:00", place: "Garden 3"),
  WidgetReservation(time: "20:00", place: "Table 12"),
  WidgetReservation(time: "21:00", place: "Table 7"),
]

struct WidgetHint: View {
  let text: String

  var body: some View {
    Text(verbatim: text)
      .textStyle(.xs)
      .foregroundStyle(EsuissColor.mutedForeground)
      .padding(.top, 24)
  }
}

struct WidgetEditable<Content: View>: View {
  let sizes: [WidgetSize]
  let handle: WidgetHandlePlacement
  let resetSize: WidgetSize
  @ViewBuilder let content: () -> Content

  @State private var size: WidgetSize

  init(
    initial: WidgetSize,
    sizes: [WidgetSize] = WidgetSize.allCases,
    handle: WidgetHandlePlacement = .outside,
    @ViewBuilder content: @escaping () -> Content
  ) {
    self.sizes = sizes
    self.handle = handle
    resetSize = initial
    self.content = content
    _size = State(initialValue: initial)
  }

  var body: some View {
    Widget(size: $size, sizes: sizes, editing: true, handle: handle, resetSize: resetSize) {
      content()
    }
  }
}

struct WidgetReservations: View {
  @Environment(\.widgetSize) private var size

  var body: some View {
    WidgetHeader {
      WidgetIcon(size: .sm) {
        Ph.calendarBlank.fill.foregroundStyle(EsuissColor.primary)
      }
      WidgetTitle("Reservations")
        .foregroundStyle(EsuissColor.primary)
    }
    HStack(alignment: .bottom, spacing: 16) {
      WidgetContent {
        WidgetValue(verbatim: "12")
        WidgetDescription("Tonight")
      }
      .fixedSize(horizontal: true, vertical: false)
      if size == .medium {
        VStack(alignment: .leading, spacing: 4) {
          ForEach(widgetReservations.prefix(3), id: \.time) { item in
            HStack(spacing: 12) {
              Text(verbatim: item.time)
                .textStyle(.sm)
                .foregroundStyle(EsuissColor.mutedForeground)
                .frame(width: 44, alignment: .leading)
              Text(verbatim: item.place)
                .textStyle(.sm)
                .lineLimit(1)
                .frame(maxWidth: .infinity, alignment: .leading)
            }
          }
        }
        .frame(maxWidth: .infinity)
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.CalendarBlank
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetIconSize
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

val widgetReservations = listOf(
    "18:00" to "Table 4",
    "19:00" to "Garden 3",
    "20:00" to "Table 12",
    "21:00" to "Table 7",
)

@Composable
fun WidgetTintedTitle(text: String, color: Color) {
    CompositionLocalProvider(LocalContentStyle provides LocalContentStyle.current.copy(color = color)) {
        WidgetTitle(text)
    }
}

@Composable
fun WidgetHint(text: String) {
    Text(
        text,
        Modifier.padding(top = 24.dp),
        style = Typography.xs,
        color = EsuissTheme.colors.mutedForeground,
    )
}

@Composable
fun WidgetReservationsBody(size: WidgetSize) {
    val colors = EsuissTheme.colors
    WidgetHeader {
        WidgetIcon(size = WidgetIconSize.Sm) { Icon(PhosphorIcons.Fill.CalendarBlank, contentDescription = null, tint = colors.primary) }
        WidgetTintedTitle("Reservations", colors.primary)
    }
    WidgetContent {
        Row(
            Modifier.fillMaxWidth().fillMaxHeight(),
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            verticalAlignment = Alignment.Bottom,
        ) {
            Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                WidgetValue("12")
                WidgetDescription("Tonight")
            }
            if (size == WidgetSize.Medium) {
                Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    widgetReservations.take(3).forEach { (time, place) ->
                        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                            Text(time, Modifier.width(44.dp), style = Typography.sm, color = colors.mutedForeground)
                            Text(place, Modifier.weight(1f), style = Typography.sm, maxLines = 1, overflow = TextOverflow.Ellipsis)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun WidgetLimitedSizes() {
    Column(Modifier.fillMaxWidth()) {
        Widget(
            resizable = true,
            defaultSize = WidgetSize.Medium,
            sizes = listOf(WidgetSize.Small, WidgetSize.Medium),
        ) { WidgetReservationsBody(size) }
        WidgetHint("Only small and medium are offered.")
    }
}
```

### Controlled

Controls the size with `size` and `onSizeChange`.

![Preview](https://ui.suiss.app/previews/components-widget--controlled.light.webp)

```tsx
import { SunIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"
import { Widget, WidgetContent, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, type WidgetSize, WidgetTitle, WidgetValue } from "@/components/ui/widget"

function Hint({ children }: { children: React.ReactNode }) {
  return <Text className="mt-6 text-xs text-muted-foreground">{children}</Text>
}

function Weather() {
  return (
    <>
      <WidgetHeader>
        <WidgetIcon>
          <Icon as={SunIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle>Istanbul</WidgetTitle>
      </WidgetHeader>
      <WidgetContent>
        <WidgetValue>24°</WidgetValue>
        <WidgetDescription>Partly cloudy</WidgetDescription>
      </WidgetContent>
      <WidgetFooter>H 27° · L 18°</WidgetFooter>
    </>
  )
}

function ControlledEditing() {
  const [size, setSize] = React.useState<WidgetSize | "auto">("small")
  return (
    <View className="w-full">
      <Widget resizable size={size} onSizeChange={setSize}>
        <Weather />
      </Widget>
      <Hint>{`Size: ${size}`}</Hint>
    </View>
  )
}

export function WidgetControlledExample() {
  return (
    <ControlledEditing />
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

func widgetSizeValue(_ size: WidgetSize) -> String {
  switch size {
  case .small: "small"
  case .medium: "medium"
  case .large: "large"
  case .extraLarge: "extra-large"
  }
}

struct WidgetHint: View {
  let text: String

  var body: some View {
    Text(verbatim: text)
      .textStyle(.xs)
      .foregroundStyle(EsuissColor.mutedForeground)
      .padding(.top, 24)
  }
}

struct WidgetControlled: View {
  @State private var size: WidgetSize = .small

  var body: some View {
    VStack(alignment: .leading, spacing: 0) {
      Widget(size: $size, editing: true) {
        WidgetWeather()
      }
      WidgetHint(text: "Size: \(widgetSizeValue(size))")
    }
    .frame(maxWidth: .infinity, alignment: .leading)
  }
}

struct WidgetWeather: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon {
        Ph.sun.fill
      }
      WidgetTitle("Istanbul")
    }
    WidgetContent {
      WidgetValue(verbatim: "24°")
      WidgetDescription("Partly cloudy")
    }
    WidgetFooter(verbatim: "H 27° · L 18°")
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
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.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.Sun
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

fun widgetSizeName(size: WidgetSize): String = when (size) {
    WidgetSize.Auto -> "auto"
    WidgetSize.Small -> "small"
    WidgetSize.Medium -> "medium"
    WidgetSize.Large -> "large"
    WidgetSize.ExtraLarge -> "extra-large"
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetHint(text: String) {
    Text(
        text,
        Modifier.padding(top = 24.dp),
        style = Typography.xs,
        color = EsuissTheme.colors.mutedForeground,
    )
}

@Composable
fun WidgetWeather() {
    WidgetHeader {
        WidgetIcon { Icon(PhosphorIcons.Fill.Sun, contentDescription = null) }
        WidgetTitle("Istanbul")
    }
    WidgetContent {
        WidgetValue("24°")
        WidgetDescription("Partly cloudy")
    }
    WidgetFooterText("H 27° · L 18°")
}

@Composable
fun WidgetControlled() {
    var size by rememberSaveable { mutableStateOf(WidgetSize.Small) }
    Column(Modifier.fillMaxWidth()) {
        Widget(size = size, onSizeChange = { size = it }, resizable = true) { WidgetWeather() }
        WidgetHint("Size: ${widgetSizeName(size)}")
    }
}
```

### Centered

Centered content with `align="center"`.

![Preview](https://ui.suiss.app/previews/components-widget--centered.light.webp)

```tsx
import { CashRegisterIcon } from "phosphor-react-native"
import { Icon } from "@/components/ui/icon"
import { Widget, WidgetDescription, WidgetHeader, WidgetIcon, WidgetTitle } from "@/components/ui/widget"

export function WidgetCenteredExample() {
  return (
    <Widget size="small" align="center">
      <WidgetHeader>
        <WidgetIcon size="lg">
          <Icon as={CashRegisterIcon} />
        </WidgetIcon>
        <WidgetTitle>Point of sale</WidgetTitle>
      </WidgetHeader>
      <WidgetDescription>3 open orders</WidgetDescription>
    </Widget>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetCenteredExample: View {
  var body: some View {
    Widget(.small, align: .center) {
      WidgetHeader {
        WidgetIcon(size: .lg) {
          Ph.cashRegister.regular
        }
        WidgetTitle("Point of sale")
      }
      WidgetDescription("3 open orders")
    }
  }
}
```

```kotlin
import androidx.compose.runtime.Composable
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Regular
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetAlign
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetIconSize
import com.esuiss.ui.components.WidgetSize
import com.esuiss.ui.components.WidgetTitle

@Composable
fun WidgetCentered() {
    Widget(size = WidgetSize.Small, align = WidgetAlign.Center) {
        WidgetHeader {
            WidgetIcon(size = WidgetIconSize.Lg) { Icon(PhosphorIcons.Regular.CashRegisterRegular, contentDescription = null) }
            WidgetTitle("Point of sale")
        }
        WidgetDescription("3 open orders")
    }
}
```

### Auto

An `auto` widget that fills its parent.

![Preview](https://ui.suiss.app/previews/components-widget--auto.light.webp)

```tsx
import { SunIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Widget, WidgetContent, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

function Weather() {
  return (
    <>
      <WidgetHeader>
        <WidgetIcon>
          <Icon as={SunIcon} weight="fill" />
        </WidgetIcon>
        <WidgetTitle>Istanbul</WidgetTitle>
      </WidgetHeader>
      <WidgetContent>
        <WidgetValue>24°</WidgetValue>
        <WidgetDescription>Partly cloudy</WidgetDescription>
      </WidgetContent>
      <WidgetFooter>H 27° · L 18°</WidgetFooter>
    </>
  )
}

export function WidgetAutoExample() {
  return (
    <View className="h-48 w-full">
      <Widget>
        <Weather />
      </Widget>
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetAutoExample: View {
  var body: some View {
    Widget(nil) {
      WidgetWeather()
    }
    .frame(maxWidth: .infinity)
    .frame(height: 192)
  }
}

struct WidgetWeather: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon {
        Ph.sun.fill
      }
      WidgetTitle("Istanbul")
    }
    WidgetContent {
      WidgetValue(verbatim: "24°")
      WidgetDescription("Partly cloudy")
    }
    WidgetFooter(verbatim: "H 27° · L 18°")
  }
}
```

```kotlin
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.Sun
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetContent
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue

@Composable
fun WidgetAutoExample() {
    Widget(Modifier.height(192.dp)) { WidgetWeather() }
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetWeather() {
    WidgetHeader {
        WidgetIcon { Icon(PhosphorIcons.Fill.Sun, contentDescription = null) }
        WidgetTitle("Istanbul")
    }
    WidgetContent {
        WidgetValue("24°")
        WidgetDescription("Partly cloudy")
    }
    WidgetFooterText("H 27° · L 18°")
}
```

### Dashboard

Several auto-sized widgets arranged in a grid.

![Preview](https://ui.suiss.app/previews/components-widget--dashboard.light.webp)

```tsx
import { CashRegisterIcon, CookingPotIcon, SunIcon } from "phosphor-react-native"
import { ScrollView, View } from "react-native"
import { Icon } from "@/components/ui/icon"
import { Widget, WidgetDescription, WidgetFooter, WidgetHeader, WidgetIcon, WidgetTitle, WidgetValue } from "@/components/ui/widget"

export function WidgetDashboardExample() {
  return (
    <ScrollView contentContainerClassName="gap-4">
      <View className="h-42 flex-row gap-4">
        <View className="flex-1">
          <Widget>
            <WidgetHeader>
              <WidgetIcon>
                <Icon as={SunIcon} weight="fill" />
              </WidgetIcon>
              <WidgetTitle>Istanbul</WidgetTitle>
            </WidgetHeader>
            <WidgetValue>24°</WidgetValue>
            <WidgetFooter>Partly cloudy</WidgetFooter>
          </Widget>
        </View>
        <View className="flex-1">
          <Widget align="center">
            <WidgetHeader>
              <WidgetIcon size="lg">
                <Icon as={CookingPotIcon} />
              </WidgetIcon>
              <WidgetTitle>Kitchen display</WidgetTitle>
            </WidgetHeader>
            <WidgetDescription>5 tickets</WidgetDescription>
          </Widget>
        </View>
      </View>
      <View className="h-42">
        <Widget>
          <WidgetHeader className="gap-1.5">
            <WidgetIcon
              size="sm"
              iconClassName="text-amber-600 dark:text-amber-400"
            >
              <Icon as={CashRegisterIcon} weight="fill" />
            </WidgetIcon>
            <WidgetTitle className="text-amber-600 dark:text-amber-400">
              Hestia
            </WidgetTitle>
          </WidgetHeader>
          <WidgetValue>₺18,240</WidgetValue>
          <WidgetFooter>Today's revenue · 42 orders</WidgetFooter>
        </Widget>
      </View>
    </ScrollView>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct WidgetDashboardExample: View {
  var body: some View {
    VStack(spacing: 16) {
      HStack(spacing: 16) {
        Widget(nil) {
          WidgetHeader {
            WidgetIcon {
              Ph.sun.fill
            }
            WidgetTitle("Istanbul")
          }
          WidgetValue(verbatim: "24°")
          WidgetFooter("Partly cloudy")
        }
        Widget(nil, align: .center) {
          WidgetHeader {
            WidgetIcon(size: .lg) {
              Ph.cookingPot.regular
            }
            WidgetTitle("Kitchen display")
          }
          WidgetDescription("5 tickets")
        }
      }
      .frame(height: 168)
      Widget(nil) {
        WidgetSalesHeader()
        WidgetValue(verbatim: "₺18,240")
        WidgetFooter("Today's revenue · 42 orders")
      }
      .frame(height: 168)
    }
    .frame(maxWidth: .infinity)
  }
}

struct WidgetSalesHeader: View {
  var body: some View {
    WidgetHeader {
      WidgetIcon(size: .sm) {
        Ph.cashRegister.fill.foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
      }
      WidgetTitle("Hestia")
        .foregroundStyle(Color.adaptive(light: Palette.amber600, dark: Palette.amber400))
    }
  }
}
```

```kotlin
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.Regular
import com.adamglin.phosphoricons.fill.CashRegister
import com.adamglin.phosphoricons.fill.Sun
import com.adamglin.phosphoricons.regular.CookingPot
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.Text
import com.esuiss.ui.components.Widget
import com.esuiss.ui.components.WidgetAlign
import com.esuiss.ui.components.WidgetDescription
import com.esuiss.ui.components.WidgetFooter
import com.esuiss.ui.components.WidgetHeader
import com.esuiss.ui.components.WidgetIcon
import com.esuiss.ui.components.WidgetIconSize
import com.esuiss.ui.components.WidgetTitle
import com.esuiss.ui.components.WidgetValue
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette

@Composable
fun WidgetTintedTitle(text: String, color: Color) {
    CompositionLocalProvider(LocalContentStyle provides LocalContentStyle.current.copy(color = color)) {
        WidgetTitle(text)
    }
}

@Composable
fun WidgetFooterText(text: String) {
    WidgetFooter {
        Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis)
    }
}

@Composable
fun WidgetDashboard() {
    val warning = if (EsuissTheme.colors.isDark) Palette.amber400 else Palette.amber600
    val tall = Modifier.height(168.dp)
    Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
            Box(Modifier.weight(1f)) {
                Widget(tall) {
                    WidgetHeader {
                        WidgetIcon { Icon(PhosphorIcons.Fill.Sun, contentDescription = null) }
                        WidgetTitle("Istanbul")
                    }
                    WidgetValue("24°")
                    WidgetFooterText("Partly cloudy")
                }
            }
            Box(Modifier.weight(1f)) {
                Widget(tall, align = WidgetAlign.Center) {
                    WidgetHeader {
                        WidgetIcon(size = WidgetIconSize.Lg) { Icon(PhosphorIcons.Regular.CookingPot, contentDescription = null) }
                        WidgetTitle("Kitchen display")
                    }
                    WidgetDescription("5 tickets")
                }
            }
        }
        Widget(tall) {
            WidgetHeader {
                WidgetIcon(size = WidgetIconSize.Sm) { Icon(PhosphorIcons.Fill.CashRegister, contentDescription = null, tint = warning) }
                WidgetTintedTitle("Hestia", warning)
            }
            WidgetValue("₺18,240")
            WidgetFooterText("Today's revenue · 42 orders")
        }
    }
}
```

## API Reference

### Widget

The card surface and optional resize handle.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |
| `size` | `WidgetSize \| "auto"` | - | Controlled size: `small`, `medium`, `large`, `extra-large` or `auto`. |
| `defaultSize` | `WidgetSize \| "auto"` | - | Initial size when uncontrolled. |
| `onSizeChange` | `(size: WidgetSize \| "auto") => void` | - | Called with the new size after a resize. |
| `sizes` | `WidgetSize[]` | `ALL_SIZES` | Sizes the user can resize to. Defaults to all four. |
| `resizable` | `boolean` | `false` | Shows a drag handle for resizing. |
| `handle` | `WidgetHandlePlacement` | `"outside"` | Handle placement: `outside` the corner or `inside` it. Defaults to `outside`. |
| `align` | `WidgetAlign` | `"start"` | `start` or `center` content alignment. |
| `resizeLabel` | `string` | `"Resize widget"` | Accessibility label for the handle. Defaults to "Resize widget". |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

### WidgetHeader

Row for the icon, title and action.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

### WidgetIcon

Icon frame in `default`, `sm` or `lg` size.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |
| `iconClassName` | `string` | - | Classes applied to the icon inside. |
| `size` | `"default" \| "sm" \| "lg"` | `"default"` | `default`, `sm` or `lg`. |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

### WidgetTitle

Single-line heading.

Also accepts the props of `React.ComponentProps<typeof Text>`, `React.RefAttributes<typeof Text>`.

### WidgetAction

Trailing slot in the header; hidden when centered.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

### WidgetDescription

Secondary text.

Also accepts the props of `React.ComponentProps<typeof Text>`, `React.RefAttributes<typeof Text>`.

### WidgetValue

Large number with tabular figures.

Also accepts the props of `React.ComponentProps<typeof Text>`, `React.RefAttributes<typeof Text>`.

### WidgetContent

Flexible body area that clips overflow.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

### WidgetFooter

Small secondary text and icons pinned to the bottom.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |

Also accepts the props of `ViewProps`, `React.RefAttributes<View>`.

## Accessibility

- The resize handle has the `adjustable` role, its `resizeLabel` and the current size as its value; increment and decrement actions step through the available sizes, so VoiceOver and TalkBack users can resize without dragging.
- `WidgetTitle` has the `heading` role.
- `WidgetIcon` and the resize preview outline are hidden from assistive technology.
- Size animations respect the system reduce motion setting.

## Notes

- Uses `bg-muted` for the surface, `bg-secondary` for icon frames, and `text-muted-foreground/50` for the handle, which turns `text-primary` while dragging.
- The handle and drag direction mirror in right-to-left layouts.
- Light and dark colors follow the system appearance.

