# Island

A floating pill at the top of the screen that shows live activities and brief notifications, like the Dynamic Island.

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

Source: https://ui.suiss.app/docs/interactions/island

**React**

**Example**

```tsx
import { BellIcon, ChatCircleIcon } from "@phosphor-icons/react"
import {
  Island,
  IslandProvider,
  useIsland,
} from "@/components/interactions/island"
import { Button } from "@/components/ui/button"

function NotifyButtons() {
  const { notify } = useIsland()

  return (
    <div className="flex flex-wrap justify-center gap-3">
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <ChatCircleIcon className="text-green-500 fill-current" />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        New message
      </Button>
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <BellIcon className="text-orange-500 fill-current" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        Reminder
      </Button>
    </div>
  )
}

export default function IslandNotification() {
  return (
    <IslandProvider>
      <div className="flex min-h-[60dvh] flex-col items-center justify-center gap-4 text-center">
        <Island />
        <p className="max-w-xs text-sm text-muted-foreground">
          The pill grows to show the notification and shrinks back on its own.
        </p>
        <NotifyButtons />
      </div>
    </IslandProvider>
  )
}
```

`Island` renders a dark pill fixed to the top of the viewport, below the safe-area inset. It morphs between four views: `hidden`, `compact`, `expanded`, and `notice`. The pill measures the active part and animates its width, height, and corner radius with a spring curve, so content changes feel continuous.

A live activity is an `IslandCompact` and `IslandExpanded` pair rendered inside `Island`. Mounting an `IslandCompact` shows the pill; tapping it expands to the details. Notifications come from the `notify` function returned by `useIsland`; a notice temporarily takes over the pill and then returns to the activity, or hides the pill when no activity is mounted. Use it for ongoing, glanceable status such as downloads, timers, or calls.

## Installation

### CLI

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

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

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

### Manual

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

2. Copy the source into `components/interactions/island.tsx`:

```tsx title="components/interactions/island.tsx"
"use client"

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

type IslandView = "hidden" | "compact" | "expanded" | "notice"

type IslandNotice = {
  icon?: React.ReactNode
  title: React.ReactNode
  description?: React.ReactNode
  duration?: number
}

type IslandContextProps = {
  view: IslandView
  notice: IslandNotice | null
  expanded: boolean
  setExpanded: (expanded: boolean) => void
  notify: (notice: IslandNotice) => void
  dismiss: () => void
  registerCompact: () => () => void
}

const IslandContext = React.createContext<IslandContextProps | null>(null)

function useIsland() {
  const context = React.useContext(IslandContext)

  if (!context) {
    throw new Error("useIsland must be used within an <Island />")
  }

  return context
}

const NOTICE_DURATION = 4000
const HIDDEN_SIZE = { width: 126, height: 36 }
const PART =
  "shrink-0 transition-[opacity,scale,filter] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] data-active:delay-100 data-active:duration-450 not-data-active:pointer-events-none not-data-active:invisible not-data-active:absolute not-data-active:top-0 not-data-active:left-1/2 not-data-active:-translate-x-1/2 not-data-active:scale-90 not-data-active:opacity-0 not-data-active:blur-sm not-data-active:duration-150 motion-reduce:transition-none"

function islandView(
  notice: IslandNotice | null,
  expanded: boolean,
  compactCount: number
): IslandView {
  if (notice) return "notice"
  if (compactCount <= 0) return "hidden"
  return expanded ? "expanded" : "compact"
}

function IslandProvider({ children }: { children?: React.ReactNode }) {
  const [expanded, setExpanded] = React.useState(false)
  const [notice, setNotice] = React.useState<IslandNotice | null>(null)
  const [compactCount, setCompactCount] = React.useState(0)
  const timerRef = React.useRef(0)

  const view = islandView(notice, expanded, compactCount)

  const dismiss = React.useCallback(() => {
    window.clearTimeout(timerRef.current)
    setNotice(null)
  }, [])

  const notify = React.useCallback(
    (next: IslandNotice) => {
      window.clearTimeout(timerRef.current)
      setNotice(next)
      timerRef.current = window.setTimeout(
        dismiss,
        next.duration ?? NOTICE_DURATION
      )
    },
    [dismiss]
  )

  const registerCompact = React.useCallback(() => {
    setCompactCount((count) => count + 1)
    return () => {
      setCompactCount((count) => count - 1)
      setExpanded(false)
    }
  }, [])

  React.useEffect(() => () => window.clearTimeout(timerRef.current), [])

  const contextValue = React.useMemo(
    () => ({
      view,
      notice,
      expanded,
      setExpanded,
      notify,
      dismiss,
      registerCompact,
    }),
    [view, notice, expanded, notify, dismiss, registerCompact]
  )

  return (
    <IslandContext.Provider value={contextValue}>
      {children}
    </IslandContext.Provider>
  )
}

function Island({
  className,
  children,
  ref: forwardedRef,
  ...props
}: React.ComponentProps<"div">) {
  const { view, notice, setExpanded, dismiss } = useIsland()
  const [size, setSize] = React.useState<{ width: number; height: number }>()
  const ref = React.useRef<HTMLDivElement>(null)

  React.useLayoutEffect(() => {
    const root = ref.current
    if (!root) return
    const measure = () => {
      const active = root.querySelector<HTMLElement>(
        `:scope > [data-island-part=${view}]`
      )
      setSize(
        active
          ? { width: active.offsetWidth, height: active.offsetHeight }
          : HIDDEN_SIZE
      )
    }
    measure()
    const observer = new ResizeObserver(measure)
    for (const part of root.querySelectorAll(":scope > [data-island-part]"))
      observer.observe(part)
    return () => observer.disconnect()
  }, [view])

  React.useEffect(() => {
    if (view !== "expanded") return
    const onPointerDown = (event: PointerEvent) => {
      if (!ref.current?.contains(event.target as Node)) setExpanded(false)
    }
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return
      const root = ref.current
      const inside = root?.contains(document.activeElement)
      setExpanded(false)
      if (inside)
        requestAnimationFrame(() =>
          root
            ?.querySelector<HTMLElement>("[data-island-part=compact]")
            ?.focus()
        )
    }
    document.addEventListener("pointerdown", onPointerDown)
    document.addEventListener("keydown", onKeyDown)
    return () => {
      document.removeEventListener("pointerdown", onPointerDown)
      document.removeEventListener("keydown", onKeyDown)
    }
  }, [view, setExpanded])

  return (
    <>
      <div
        ref={(node) => {
          ref.current = node
          if (typeof forwardedRef === "function") return forwardedRef(node)
          if (forwardedRef) forwardedRef.current = node
        }}
        data-slot="island"
        data-view={view}
        style={size}
        className={cn(
          "fixed inset-x-0 top-[max(--spacing(3),env(safe-area-inset-top))] z-50 mx-auto flex items-start justify-center overflow-hidden rounded-[1.125rem] bg-foreground text-start text-background shadow-xl [--island-spring:linear(0,0.032,0.112,0.219,0.338,0.459,0.573,0.676,0.766,0.84,0.9,0.947,0.982,1.007,1.023,1.033,1.037,1.038,1.037,1.033,1.029,1.024,1.02,1.015,1.012,1.008,1.006,1.003,1.002,1,1,0.999,1)] transition-[width,height,border-radius,opacity,scale,visibility] duration-650 ease-(--island-spring) transition-discrete data-[view=expanded]:rounded-[1.75rem] data-[view=hidden]:invisible data-[view=hidden]:scale-75 data-[view=hidden]:opacity-0 data-[view=hidden]:duration-400 data-[view=hidden]:ease-[cubic-bezier(0.32,0.72,0,1)] data-[view=notice]:rounded-[1.75rem] motion-reduce:transition-none dark:bg-background dark:text-foreground dark:ring-1 dark:ring-border",
          className
        )}
        {...props}
      >
        {children}
        <button
          type="button"
          data-island-part="notice"
          data-slot="island-notice"
          data-active={view === "notice" ? "" : undefined}
          tabIndex={view === "notice" ? 0 : -1}
          aria-hidden={view !== "notice"}
          onClick={dismiss}
          className={cn(
            PART,
            "flex w-[min(calc(100vw-(--spacing(6))),24rem)] items-center gap-3 p-3.5 text-start outline-none focus-visible:ring-3 focus-visible:ring-ring/50 rounded-[inherit] in-data-[slot=island]:focus-visible:ring-inset [&_svg:not([class*='size-'])]:size-6"
          )}
        >
          {notice?.icon && (
            <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-background/15 dark:bg-foreground/15">
              {notice.icon}
            </span>
          )}
          <span className="flex min-w-0 flex-1 flex-col">
            <span className="truncate text-sm font-semibold">
              {notice?.title}
            </span>
            {notice?.description && (
              <span className="truncate text-sm text-background/70 dark:text-muted-foreground">
                {notice.description}
              </span>
            )}
          </span>
        </button>
      </div>
      <div aria-live="polite" className="sr-only">
        {notice && (
          <>
            {notice.title} {notice.description}
          </>
        )}
      </div>
    </>
  )
}

function IslandCompact({
  className,
  children,
  onClick,
  ...props
}: React.ComponentProps<"button">) {
  const { view, setExpanded, registerCompact } = useIsland()

  React.useEffect(() => registerCompact(), [registerCompact])

  return (
    <button
      type="button"
      data-island-part="compact"
      data-slot="island-compact"
      data-active={view === "compact" ? "" : undefined}
      aria-expanded={view === "expanded"}
      tabIndex={view === "compact" ? 0 : -1}
      onClick={(event) => {
        onClick?.(event)
        if (event.defaultPrevented) return
        const root = event.currentTarget.parentElement
        setExpanded(true)
        requestAnimationFrame(() =>
          root
            ?.querySelector<HTMLElement>(
              "[data-island-part=expanded] :is(button, [href], input):not(:disabled)"
            )
            ?.focus()
        )
      }}
      className={cn(
        PART,
        "flex h-9 min-w-36 items-center justify-between gap-6 px-2.5 outline-none focus-visible:ring-3 focus-visible:ring-ring/50 rounded-[inherit] in-data-[slot=island]:focus-visible:ring-inset [&_svg:not([class*='size-'])]:size-5",
        className
      )}
      {...props}
    >
      {children}
    </button>
  )
}

function IslandExpanded({ className, ...props }: React.ComponentProps<"div">) {
  const { view } = useIsland()

  return (
    <div
      role="group"
      data-island-part="expanded"
      data-slot="island-expanded"
      data-active={view === "expanded" ? "" : undefined}
      inert={view !== "expanded"}
      className={cn(
        PART,
        "flex w-[min(calc(100vw-(--spacing(6))),24rem)] flex-col gap-3 p-4",
        className
      )}
      {...props}
    />
  )
}

function IslandRing({
  value,
  className,
  ...props
}: React.ComponentProps<"svg"> & { value: number }) {
  const radius = 8
  const circumference = 2 * Math.PI * radius

  return (
    <svg
      data-slot="island-ring"
      viewBox="0 0 20 20"
      aria-hidden
      className={cn("size-5 -rotate-90 text-primary", className)}
      {...props}
    >
      <circle
        cx="10"
        cy="10"
        r={radius}
        fill="none"
        strokeWidth="2.5"
        className="stroke-current opacity-25"
      />
      <circle
        cx="10"
        cy="10"
        r={radius}
        fill="none"
        stroke="currentColor"
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeDasharray={circumference}
        strokeDashoffset={circumference * (1 - Math.min(Math.max(value, 0), 1))}
        className="transition-[stroke-dashoffset] duration-300"
      />
    </svg>
  )
}

export {
  Island,
  IslandCompact,
  IslandExpanded,
  IslandProvider,
  IslandRing,
  useIsland,
}
```

3. Update the import paths to match your project.

## Usage

```tsx
import { IslandProvider, Island, IslandCompact, IslandExpanded, IslandRing } from "@/components/interactions/island"
```

```tsx
<IslandProvider>
  <div className="flex min-h-[60dvh] flex-col items-center justify-center gap-4 text-center">
    <Island />
    <p className="max-w-xs text-sm text-muted-foreground">
      The pill grows to show the notification and shrinks back on its own.
    </p>
    <NotifyButtons />
  </div>
</IslandProvider>
```

- Wrap the app, or the part of it that posts notifications, in `IslandProvider`. `Island`, `IslandCompact`, `IslandExpanded`, and `useIsland` throw outside of it.
- Render a single `Island`. Mount `IslandCompact` and `IslandExpanded` as its children only while an activity is running; unmounting the compact part hides the pill and collapses it.
- Call `notify({ icon, title, description, duration })` from `useIsland` to show a notice. It replaces any current notice and dismisses itself after `duration` milliseconds (4000 by default). Call `dismiss` to remove it early.
- `useIsland` also exposes `view`, `expanded`, and `setExpanded` for custom controls.

## Examples

### Live activity

A download runs as a live activity, with a progress ring in the compact pill and details plus a cancel button when expanded.

**Example**

```tsx
import {
  BellIcon,
  ChatCircleIcon,
  CheckCircleIcon,
  DownloadSimpleIcon,
  FileZipIcon,
} from "@phosphor-icons/react"
import * as React from "react"
import {
  Island,
  IslandCompact,
  IslandExpanded,
  IslandProvider,
  IslandRing,
  useIsland,
} from "@/components/interactions/island"
import { Button } from "@/components/ui/button"

const SIZE = 120

function NotifyButtons() {
  const { notify } = useIsland()

  return (
    <div className="flex flex-wrap justify-center gap-3">
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <ChatCircleIcon className="text-green-500 fill-current" />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        New message
      </Button>
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <BellIcon className="text-orange-500 fill-current" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        Reminder
      </Button>
    </div>
  )
}

function useDownload() {
  const [progress, setProgress] = React.useState<number | null>(null)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (progress === null || progress >= 1) return
    const timer = window.setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => window.clearTimeout(timer)
  }, [progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = window.setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <CheckCircleIcon className="fill-green-500 text-white" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => window.clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadActivity({
  progress,
  onCancel,
}: {
  progress: number
  onCancel: () => void
}) {
  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <>
      <IslandCompact aria-label={`Downloading Design-Kit.zip, ${percent}%`}>
        <DownloadSimpleIcon className="text-primary" />
        {done ? (
          <CheckCircleIcon className="fill-green-500 text-white" />
        ) : (
          <IslandRing value={progress} data-visual-mask />
        )}
      </IslandCompact>
      <IslandExpanded aria-label="Download">
        <div className="flex items-center gap-3">
          <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-background/15 dark:bg-foreground/15">
            <FileZipIcon className="size-6 text-primary" />
          </span>
          <span className="flex min-w-0 flex-1 flex-col">
            <span className="truncate text-sm font-semibold">
              Design-Kit.zip
            </span>
            <span className="text-sm text-background/70 tabular-nums dark:text-muted-foreground">
              {done
                ? "Downloaded"
                : `${Math.round(progress * SIZE)} MB of ${SIZE} MB`}
            </span>
          </span>
          <span className="text-2xl font-semibold tabular-nums">
            {percent}%
          </span>
        </div>
        <div
          role="progressbar"
          aria-label="Download progress"
          aria-valuenow={percent}
          aria-valuemin={0}
          aria-valuemax={100}
          className="h-1.5 overflow-hidden rounded-full bg-background/20 dark:bg-foreground/20"
        >
          <div
            className="h-full origin-left rounded-full bg-primary transition-[scale] duration-300 rtl:origin-right"
            style={{ scale: `${progress} 1` }}
          />
        </div>
        <button
          type="button"
          onClick={onCancel}
          disabled={done}
          className="h-11 rounded-full bg-background/15 text-sm font-semibold outline-none focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-foreground/15"
        >
          Cancel download
        </button>
      </IslandExpanded>
    </>
  )
}

function DownloadsExample({
  withNotifications,
}: {
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload()

  return (
    <div className="flex min-h-[60dvh] flex-col items-center justify-center gap-4 text-center">
      <Island>
        {progress !== null && (
          <DownloadActivity progress={progress} onCancel={cancel} />
        )}
      </Island>
      <p className="max-w-xs text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details.
      </p>
      <Button onClick={start} disabled={progress !== null}>
        {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
      </Button>
      {withNotifications && <NotifyButtons />}
    </div>
  )
}

export default function IslandLiveActivity() {
  return (
    <IslandProvider>
      <DownloadsExample />
    </IslandProvider>
  )
}
```

### Activity with notifications

A notification temporarily replaces a running live activity, which returns once the notice is dismissed.

**Example**

```tsx
import {
  BellIcon,
  ChatCircleIcon,
  CheckCircleIcon,
  DownloadSimpleIcon,
  FileZipIcon,
} from "@phosphor-icons/react"
import * as React from "react"
import {
  Island,
  IslandCompact,
  IslandExpanded,
  IslandProvider,
  IslandRing,
  useIsland,
} from "@/components/interactions/island"
import { Button } from "@/components/ui/button"

const SIZE = 120

function NotifyButtons() {
  const { notify } = useIsland()

  return (
    <div className="flex flex-wrap justify-center gap-3">
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <ChatCircleIcon className="text-green-500 fill-current" />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        New message
      </Button>
      <Button
        variant="secondary"
        onClick={() =>
          notify({
            icon: (
              <BellIcon className="text-orange-500 fill-current" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        Reminder
      </Button>
    </div>
  )
}

function useDownload() {
  const [progress, setProgress] = React.useState<number | null>(null)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (progress === null || progress >= 1) return
    const timer = window.setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => window.clearTimeout(timer)
  }, [progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = window.setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <CheckCircleIcon className="fill-green-500 text-white" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => window.clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadActivity({
  progress,
  onCancel,
}: {
  progress: number
  onCancel: () => void
}) {
  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <>
      <IslandCompact aria-label={`Downloading Design-Kit.zip, ${percent}%`}>
        <DownloadSimpleIcon className="text-primary" />
        {done ? (
          <CheckCircleIcon className="fill-green-500 text-white" />
        ) : (
          <IslandRing value={progress} data-visual-mask />
        )}
      </IslandCompact>
      <IslandExpanded aria-label="Download">
        <div className="flex items-center gap-3">
          <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-background/15 dark:bg-foreground/15">
            <FileZipIcon className="size-6 text-primary" />
          </span>
          <span className="flex min-w-0 flex-1 flex-col">
            <span className="truncate text-sm font-semibold">
              Design-Kit.zip
            </span>
            <span className="text-sm text-background/70 tabular-nums dark:text-muted-foreground">
              {done
                ? "Downloaded"
                : `${Math.round(progress * SIZE)} MB of ${SIZE} MB`}
            </span>
          </span>
          <span className="text-2xl font-semibold tabular-nums">
            {percent}%
          </span>
        </div>
        <div
          role="progressbar"
          aria-label="Download progress"
          aria-valuenow={percent}
          aria-valuemin={0}
          aria-valuemax={100}
          className="h-1.5 overflow-hidden rounded-full bg-background/20 dark:bg-foreground/20"
        >
          <div
            className="h-full origin-left rounded-full bg-primary transition-[scale] duration-300 rtl:origin-right"
            style={{ scale: `${progress} 1` }}
          />
        </div>
        <button
          type="button"
          onClick={onCancel}
          disabled={done}
          className="h-11 rounded-full bg-background/15 text-sm font-semibold outline-none focus-visible:ring-3 focus-visible:ring-ring/50 disabled:opacity-50 dark:bg-foreground/15"
        >
          Cancel download
        </button>
      </IslandExpanded>
    </>
  )
}

function DownloadsExample({
  withNotifications,
}: {
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload()

  return (
    <div className="flex min-h-[60dvh] flex-col items-center justify-center gap-4 text-center">
      <Island>
        {progress !== null && (
          <DownloadActivity progress={progress} onCancel={cancel} />
        )}
      </Island>
      <p className="max-w-xs text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details.
      </p>
      <Button onClick={start} disabled={progress !== null}>
        {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
      </Button>
      {withNotifications && <NotifyButtons />}
    </div>
  )
}

export default function IslandActivityWithNotifications() {
  return (
    <IslandProvider>
      <DownloadsExample withNotifications />
    </IslandProvider>
  )
}
```

## API Reference

- `IslandProvider`
- `Island`

### IslandProvider

Holds the island state and provides `notify`, `dismiss`, and the expanded state to everything inside it.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `React.ReactNode` | - | The content that can render the island and post notifications. |

### Island

The fixed pill that sizes itself to the active view and renders the built-in notice.

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

### IslandCompact

The button shown in the collapsed pill; tapping it expands the island.

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

### IslandExpanded

The detailed view shown when the island is expanded.

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

### IslandRing

A small circular progress ring for the compact pill.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number` | Required | Progress from `0` to `1`; values outside the range are clamped. |

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

## Accessibility

- `IslandCompact` is a button with `aria-expanded` reflecting the expanded state; give it an `aria-label` that describes the activity.
- Expanding moves focus to the first enabled button, link, or input inside `IslandExpanded`, which has `role="group"` and is `inert` while not shown.
- `Escape` or a pointer press outside collapses the expanded view. After `Escape`, focus returns to the compact button if it was inside the island.
- Notices render as a button that dismisses on press, and their title and description are announced through a polite live region.
- Inactive parts are removed from the tab order. `IslandRing` is `aria-hidden`.

## Notes

- The root exposes `data-slot="island"` and `data-view` with the current view. Parts use `data-slot` values `island-compact`, `island-expanded`, `island-notice`, and `island-ring`, and carry `data-active` while shown.
- Animations are disabled under `prefers-reduced-motion`.

**React Native, SwiftUI, Jetpack Compose**

**React Native, Jetpack Compose**

![Preview](https://ui.suiss.app/previews/interactions-island--compact.light.webp)

```tsx
import { BellIcon, ChatCircleIcon, CheckCircleIcon, DownloadSimpleIcon, FileZipIcon } from "phosphor-react-native"
import * as React from "react"
import { Pressable, View } from "react-native"
import { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland } from "@/components/interactions/island"
import { Button } from "@/components/ui/button"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

function NotifyButtons({ children }: { children?: React.ReactNode }) {
  const { notify } = useIsland()

  return (
    <View className="flex-row flex-wrap justify-center gap-3">
      {children}
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon
                as={ChatCircleIcon}
                weight="fill"
                className="text-green-500"
              />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        <Text>New message</Text>
      </Button>
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon as={BellIcon} weight="fill" className="text-orange-500" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        <Text>Reminder</Text>
      </Button>
    </View>
  )
}

function useDownload(initial: number | null = null) {
  const [progress, setProgress] = React.useState<number | null>(initial)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (initial !== null || progress === null || progress >= 1) return
    const timer = setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => clearTimeout(timer)
  }, [initial, progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadIsland({
  progress,
  onCancel,
}: {
  progress: number | null
  onCancel: () => void
}) {
  if (progress === null) return <Island />

  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <Island
      accessibilityLabel={`Downloading Design-Kit.zip, ${percent}%`}
      compactLeading={
        <Icon as={DownloadSimpleIcon} weight="bold" className="text-primary" />
      }
      compactTrailing={
        done ? (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ) : (
          <IslandRing value={progress} />
        )
      }
      minimal={<IslandRing value={progress} />}
    >
      <IslandExpandedRegion region="leading">
        <View className="size-10 items-center justify-center rounded-xl bg-white/15">
          <Icon
            as={FileZipIcon}
            weight="fill"
            className="size-6 text-primary"
          />
        </View>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="trailing">
        <Text className="text-2xl font-semibold">{percent}%</Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="center">
        <Text numberOfLines={1} className="text-sm font-semibold">
          {done ? "Downloaded" : "Downloading"}
        </Text>
        <Text numberOfLines={1} className="text-sm text-white/70">
          Design-Kit.zip
        </Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="bottom">
        <View
          role="progressbar"
          accessibilityLabel="Download progress"
          accessibilityValue={{ min: 0, max: 100, now: percent }}
          className="h-1.5 overflow-hidden rounded-full bg-white/20"
        >
          <View
            className="h-full rounded-full bg-primary"
            style={{ width: `${percent}%` }}
          />
        </View>
        <Pressable
          role="button"
          disabled={done}
          onPress={onCancel}
          className="h-11 items-center justify-center rounded-full bg-white/15 active:opacity-80 disabled:opacity-50"
        >
          <Text className="text-sm font-semibold">Cancel download</Text>
        </Pressable>
      </IslandExpandedRegion>
    </Island>
  )
}

function DownloadsExample({
  initial = null,
  view = "compact",
  withNotifications = false,
}: {
  initial?: number | null
  view?: "compact" | "expanded" | "minimal"
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload(initial)
  const { expand, minimize } = useIsland()

  React.useEffect(() => {
    if (view === "expanded") expand()
    else if (view === "minimal") minimize()
  }, [view, expand, minimize])

  return (
    <View className="flex-1 items-center justify-center gap-4">
      <DownloadIsland progress={progress} onCancel={cancel} />
      <Text className="max-w-xs text-center text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details. Swipe
        up on it to close.
      </Text>
      {initial === null ? (
        <Button onPress={start} disabled={progress !== null}>
          <Text>
            {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
          </Text>
        </Button>
      ) : null}
      {withNotifications ? (
        <NotifyButtons>
          <Button
            variant="secondary"
            disabled={progress === null}
            onPress={minimize}
          >
            <Text>Minimize</Text>
          </Button>
        </NotifyButtons>
      ) : null}
    </View>
  )
}

export function IslandCompactExample() {
  return (
    <IslandProvider>
      <DownloadsExample initial={0.42} />
    </IslandProvider>
  )
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.bold.DownloadSimple
import com.adamglin.phosphoricons.fill.Bell
import com.adamglin.phosphoricons.fill.ChatCircle
import com.adamglin.phosphoricons.fill.CheckCircle
import com.esuiss.ui.components.Button
import com.esuiss.ui.components.ButtonVariant
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.Island
import com.esuiss.ui.interactions.IslandProvider
import com.esuiss.ui.interactions.IslandRegion
import com.esuiss.ui.interactions.IslandRing
import com.esuiss.ui.interactions.useIsland
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay
import kotlin.math.roundToInt

@Composable
fun IslandCompactExample() {
    IslandProvider { IslandDownloads(initial = 0.42f) }
}

enum class IslandStart { Compact, Expanded, Minimal }

@Composable
fun IslandNotifyButtons(extra: @Composable () -> Unit = {}) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Button(
            "New message",
            onClick = {
                island.notify(
                    title = "Jordan Lee",
                    description = "Are we still on for Saturday?",
                    icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        Button(
            "Reminder",
            onClick = {
                island.notify(
                    title = "Design review",
                    description = "Starts in 10 minutes",
                    icon = { Icon(PhosphorIcons.Fill.Bell, contentDescription = null, tint = Palette.orange500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        extra()
    }
}

@Composable
fun IslandProgress(progress: Float) {
    val colors = EsuissTheme.colors
    if (progress >= 1f) {
        Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500)
    } else {
        IslandRing(progress)
    }
}

@Composable
fun IslandDownloadIsland(progress: Float?, onCancel: () -> Unit) {
    val colors = EsuissTheme.colors
    val current = progress ?: 0f
    val done = current >= 1f
    val percent = (current * 100).roundToInt()
    Island(
        compactLeading = progress?.let {
            { Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, tint = colors.primary) }
        },
        compactTrailing = progress?.let { value -> { IslandProgress(value) } },
        minimal = progress?.let { value -> { IslandProgress(value) } },
        modifier = Modifier.semantics { contentDescription = "Downloading Design-Kit.zip, $percent%" },
    ) {
        IslandExpandedRegion(IslandRegion.Leading) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(foreground.copy(alpha = 0.15f), RoundedCornerShape(Radius.xl)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, size = 24.dp, tint = colors.primary)
            }
        }
        IslandExpandedRegion(IslandRegion.Trailing) {
            Text("$percent%", style = Typography.xl2.copy(color = LocalContentColor.current, fontWeight = FontWeight.SemiBold))
        }
        IslandExpandedRegion(IslandRegion.Center) {
            val foreground = LocalContentColor.current
            Text(
                if (done) "Downloaded" else "Downloading",
                style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            Text(
                if (done) "Design-Kit.zip" else "Design-Kit.zip · ${(current * IslandSize).roundToInt()} of $IslandSize MB",
                style = Typography.sm.copy(color = foreground.copy(alpha = 0.7f)),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
        IslandExpandedRegion(IslandRegion.Bottom) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(CircleShape)
                    .background(foreground.copy(alpha = 0.2f))
                    .semantics {
                        contentDescription = "Download progress"
                        progressBarRangeInfo = ProgressBarRangeInfo(percent.toFloat(), 0f..100f)
                    },
            ) {
                Box(
                    Modifier
                        .fillMaxWidth(current.coerceIn(0f, 1f))
                        .fillMaxHeight()
                        .background(colors.primary, CircleShape),
                )
            }
            Spacer(Modifier.height(12.dp))
            val interaction = remember { MutableInteractionSource() }
            val pressed by interaction.collectIsPressedAsState()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(44.dp)
                    .alpha(if (done) 0.5f else 1f)
                    .clip(CircleShape)
                    .alpha(if (pressed) 0.8f else 1f)
                    .background(foreground.copy(alpha = 0.15f))
                    .clickable(interactionSource = interaction, indication = null, enabled = !done, role = Role.Button, onClick = onCancel),
                contentAlignment = Alignment.Center,
            ) {
                Text("Cancel download", style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold))
            }
        }
    }
}

@Composable
fun IslandDownloads(initial: Float? = null, start: IslandStart = IslandStart.Compact, withNotifications: Boolean = false) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    var progress by rememberSaveable { mutableStateOf(initial) }
    LaunchedEffect(progress) {
        val current = progress ?: return@LaunchedEffect
        if (initial != null) return@LaunchedEffect
        if (current < 1f) {
            delay(150)
            progress = minOf(current + 0.01f, 1f)
        } else {
            delay(1200)
            progress = null
            island.notify(
                title = "Download complete",
                description = "Design-Kit.zip",
                icon = { Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500) },
            )
        }
    }
    LaunchedEffect(start) {
        when (start) {
            IslandStart.Expanded -> island.expand()
            IslandStart.Minimal -> island.minimize()
            IslandStart.Compact -> Unit
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        IslandDownloadIsland(progress) { progress = null }
        Text(
            "Start a download, then tap the pill at the top to see the details. Swipe up on it to close.",
            modifier = Modifier.widthIn(max = 320.dp),
            style = Typography.sm.copy(color = colors.mutedForeground),
            textAlign = TextAlign.Center,
        )
        if (initial == null) {
            Button(
                if (progress == null) "Download Design-Kit.zip" else "Downloading…",
                onClick = { progress = 0f },
                enabled = progress == null,
            )
        }
        if (withNotifications) {
            IslandNotifyButtons {
                Button(
                    "Minimize",
                    onClick = island::minimize,
                    variant = ButtonVariant.Secondary,
                    enabled = progress != null,
                )
            }
        }
    }
}
```

`Island` floats below the top safe area and morphs between views: `hidden`, `compact`, `minimal`, `expanded` and `notice`. Its width, height and corner radius spring to the measured size of the active view, and views cross-fade as it changes.

Content is passed through slots. `compactLeading` and `compactTrailing` sit at the two ends of the compact pill, `minimal` is a single small circle, and `IslandExpandedRegion` children fill the expanded view. The island appears while it has compact or minimal content and hides when it has none. Pressing it expands; pressing outside, swiping up or the Android back button collapses it. `notify` shows a notice that replaces the current view and dismisses itself after 4 seconds, on press or on swipe up. Use it for ongoing activity such as a download, timer or call.

## Installation

**React Native**

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

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 island
```

**SwiftUI**

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

**Jetpack Compose**

```bash title="Terminal"
npx @esuiss/ui@latest add island --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-safe-area-context 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/hooks.tsx`, `components/primitives/portal.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/interactions/island.tsx`:

```tsx title="uniwind/components/interactions/island.tsx"
import { cn } from "cn"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  AccessibilityInfo,
  Pressable,
  useWindowDimensions,
  View,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
  withTiming,
} from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import Svg, { Circle } from "react-native-svg"
import { useBackHandler } from "@/components/primitives/hooks"
import { Portal } from "@/components/primitives/portal"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type IslandView = "hidden" | "compact" | "minimal" | "expanded" | "notice"

type IslandMode = "compact" | "minimal" | "expanded"

type IslandPartName = Exclude<IslandView, "hidden">

type IslandRegion = "leading" | "trailing" | "center" | "bottom"

type IslandNotice = {
  icon?: React.ReactNode
  title: React.ReactNode
  description?: React.ReactNode
  duration?: number
}

type IslandContextProps = {
  view: IslandView
  notice: IslandNotice | null
  expand: () => void
  collapse: () => void
  minimize: () => void
  notify: (notice: IslandNotice) => void
  dismiss: () => void
  registerActivity: () => () => void
}

type IslandSize = { width: number; height: number }

type IslandStageContextProps = {
  view: IslandView
  stageWidth: number
  reportSize: (part: IslandPartName, size: IslandSize) => void
}

const IslandContext = React.createContext<IslandContextProps | null>(null)

const IslandPauseContext = React.createContext<(paused: boolean) => void>(
  () => undefined
)

const IslandStageContext = React.createContext<IslandStageContextProps | null>(
  null
)

function useIsland() {
  const context = React.useContext(IslandContext)

  if (!context) {
    throw new Error("useIsland must be used within an <IslandProvider />")
  }

  return context
}

const NOTICE_DURATION = 4000

const HIDDEN_SIZE: IslandSize = { width: 126, height: 36 }

const MAX_WIDTH = 384

const SPRING = {
  damping: 22,
  stiffness: 260,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const RADIUS: Record<IslandView, number> = {
  hidden: 18,
  compact: 18,
  minimal: 18,
  expanded: 28,
  notice: 28,
}

function islandView(
  notice: IslandNotice | null,
  mode: IslandMode,
  activityCount: number
): IslandView {
  if (notice) return "notice"
  if (activityCount <= 0) return "hidden"
  return mode
}

function availableView(
  view: IslandView,
  hasCompact: boolean,
  hasMinimal: boolean
): IslandView {
  if (view === "minimal" && !hasMinimal) return "compact"
  if (view === "compact" && !hasCompact) return "minimal"
  return view
}

function plainText(node: React.ReactNode) {
  return typeof node === "string" || typeof node === "number"
    ? String(node)
    : ""
}

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

function IslandProvider({ children }: { children?: React.ReactNode }) {
  const [mode, setMode] = React.useState<IslandMode>("compact")
  const [notice, setNotice] = React.useState<
    (IslandNotice & { id: number }) | null
  >(null)
  const [activityCount, setActivityCount] = React.useState(0)
  const [paused, setPaused] = React.useState(false)
  const idRef = React.useRef(0)

  const view = islandView(notice, mode, activityCount)

  const expand = React.useCallback(() => setMode("expanded"), [])

  const collapse = React.useCallback(() => setMode("compact"), [])

  const minimize = React.useCallback(() => setMode("minimal"), [])

  const dismiss = React.useCallback(() => {
    setNotice(null)
    setPaused(false)
  }, [])

  const notify = React.useCallback((next: IslandNotice) => {
    idRef.current += 1
    setNotice({ ...next, id: idRef.current })
  }, [])

  const registerActivity = React.useCallback(() => {
    setActivityCount((count) => count + 1)
    return () => {
      setActivityCount((count) => count - 1)
      setMode("compact")
    }
  }, [])

  React.useEffect(() => {
    if (!notice) return
    const message = [plainText(notice.title), plainText(notice.description)]
      .filter(Boolean)
      .join(", ")
    if (message) AccessibilityInfo.announceForAccessibility(message)
  }, [notice])

  React.useEffect(() => {
    if (!notice || paused) return
    const duration = notice.duration ?? NOTICE_DURATION
    if (!Number.isFinite(duration) || duration <= 0) return
    const timer = setTimeout(dismiss, duration)
    return () => clearTimeout(timer)
  }, [notice, paused, dismiss])

  const contextValue = React.useMemo(
    () => ({
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    }),
    [
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    ]
  )

  return (
    <IslandContext.Provider value={contextValue}>
      <IslandPauseContext.Provider value={setPaused}>
        {children}
      </IslandPauseContext.Provider>
    </IslandContext.Provider>
  )
}

function IslandPart({
  part,
  className,
  style,
  children,
}: {
  part: IslandPartName
  className?: string
  style?: React.ComponentProps<typeof View>["style"]
  children?: React.ReactNode
}) {
  const stage = React.useContext(IslandStageContext)
  const active = stage?.view === part
  const progress = useSharedValue(active ? 1 : 0)

  React.useEffect(() => {
    progress.value = withTiming(active ? 1 : 0, {
      duration: active ? 300 : 150,
      reduceMotion: ReduceMotion.System,
    })
  }, [active, progress])

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: progress.value,
    transform: [{ scale: 0.9 + progress.value * 0.1 }],
  }))

  return (
    <AnimatedView
      pointerEvents={active ? "box-none" : "none"}
      accessibilityElementsHidden={!active}
      importantForAccessibility={active ? "auto" : "no-hide-descendants"}
      onLayout={(event) => {
        const { width, height } = event.nativeEvent.layout
        stage?.reportSize(part, { width, height })
      }}
      className={cn("absolute top-0", className)}
      style={[style, animatedStyle]}
    >
      {children}
    </AnimatedView>
  )
}

function IslandNoticeView({ current }: { current: IslandNotice | null }) {
  const { dismiss } = useIsland()
  const lastRef = React.useRef(current)
  if (current) lastRef.current = current
  const notice = current ?? lastRef.current
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)

  return (
    <IslandPart part="notice" style={{ width }}>
      <Pressable
        role="button"
        accessibilityActions={[{ name: "activate" }, { name: "dismiss" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "activate" || action === "dismiss") dismiss()
        }}
        onPress={dismiss}
        className="w-full flex-row items-center gap-3 p-3.5"
      >
        {notice?.icon ? (
          <IconClassContext.Provider value="size-6 text-white">
            <View className="size-10 shrink-0 items-center justify-center rounded-xl bg-white/15">
              {notice.icon}
            </View>
          </IconClassContext.Provider>
        ) : null}
        <View className="min-w-0 flex-1">
          {wrapText(notice?.title, "text-sm font-semibold", 1)}
          {notice?.description !== undefined
            ? wrapText(notice.description, "text-sm text-white/70", 1)
            : null}
        </View>
      </Pressable>
    </IslandPart>
  )
}

function IslandStage({
  width,
  stageWidth,
  stageHeight,
  children,
}: {
  width: SharedValue<number>
  stageWidth: number
  stageHeight: number
  children?: React.ReactNode
}) {
  const animatedStyle = useAnimatedStyle(() => ({
    left: (width.value - stageWidth) / 2,
  }))

  return (
    <AnimatedView
      pointerEvents="box-none"
      className="absolute top-0 items-center"
      style={[{ width: stageWidth, height: stageHeight }, animatedStyle]}
    >
      {children}
    </AnimatedView>
  )
}

type IslandExpandedRegionProps = React.ComponentProps<typeof View> & {
  region: IslandRegion
  className?: string
}

const REGION_CLASS: Record<IslandRegion, string> = {
  leading: "shrink-0",
  trailing: "shrink-0 items-end",
  center: "min-w-0 flex-1",
  bottom: "w-full gap-3",
}

function IslandExpandedRegion({
  region,
  className,
  ...props
}: IslandExpandedRegionProps) {
  return <View className={cn(REGION_CLASS[region], className)} {...props} />
}

type IslandRegions = Record<IslandRegion, React.ReactElement[]>

function collectRegions(
  children: React.ReactNode,
  regions: IslandRegions = {
    leading: [],
    trailing: [],
    center: [],
    bottom: [],
  }
) {
  for (const child of React.Children.toArray(children)) {
    if (!React.isValidElement(child)) continue
    if (child.type === React.Fragment) {
      collectRegions(
        (child.props as { children?: React.ReactNode }).children,
        regions
      )
    } else if (child.type === IslandExpandedRegion) {
      const { region } = child.props as IslandExpandedRegionProps
      regions[region].push(child)
    }
  }
  return regions
}

function IslandExpandedView({
  regions,
  accessibilityLabel,
}: {
  regions: IslandRegions
  accessibilityLabel?: string
}) {
  const { collapse } = useIsland()
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)
  const hasTop =
    regions.leading.length > 0 ||
    regions.center.length > 0 ||
    regions.trailing.length > 0

  return (
    <IslandPart part="expanded" style={{ width }}>
      <View
        role="group"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={[{ name: "escape" }, { name: "collapse" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "escape" || action === "collapse") collapse()
        }}
        onAccessibilityEscape={collapse}
        className="w-full flex-col gap-3 p-4"
      >
        {hasTop ? (
          <View className="w-full flex-row items-center gap-3">
            {regions.leading}
            {regions.center.length > 0 ? (
              regions.center
            ) : (
              <View className="flex-1" />
            )}
            {regions.trailing}
          </View>
        ) : null}
        {regions.bottom}
      </View>
    </IslandPart>
  )
}

function Island({
  className,
  style,
  children,
  compactLeading,
  compactTrailing,
  minimal,
  accessibilityLabel,
  portalHost,
  onAccessibilityEscape,
  ...props
}: React.ComponentProps<typeof View> & {
  className?: string
  compactLeading?: React.ReactNode
  compactTrailing?: React.ReactNode
  minimal?: React.ReactNode
  portalHost?: string
}) {
  const context = useIsland()
  const setPaused = React.useContext(IslandPauseContext)
  const { notice, expand, collapse, dismiss, registerActivity } = context
  const insets = useSafeAreaInsets()
  const window = useWindowDimensions()
  const id = React.useId()
  const [sizes, setSizes] = React.useState<
    Partial<Record<IslandPartName, IslandSize>>
  >({})
  const width = useSharedValue(HIDDEN_SIZE.width)
  const height = useSharedValue(HIDDEN_SIZE.height)
  const radius = useSharedValue(RADIUS.hidden)
  const visible = useSharedValue(0)
  const translateY = useSharedValue(0)

  const hasCompact = compactLeading != null || compactTrailing != null
  const hasMinimal = minimal != null
  const active = hasCompact || hasMinimal

  React.useEffect(() => {
    if (!active) return
    return registerActivity()
  }, [active, registerActivity])

  React.useEffect(() => () => setPaused(false), [setPaused])

  const view = availableView(context.view, hasCompact, hasMinimal)

  const regions = collectRegions(children)

  const reportSize = React.useCallback(
    (part: IslandPartName, size: IslandSize) => {
      setSizes((current) => {
        const previous = current[part]
        if (
          previous &&
          previous.width === size.width &&
          previous.height === size.height
        ) {
          return current
        }
        return { ...current, [part]: size }
      })
    },
    []
  )

  const target = view === "hidden" ? HIDDEN_SIZE : (sizes[view] ?? HIDDEN_SIZE)

  React.useEffect(() => {
    width.value = withSpring(target.width, SPRING)
    height.value = withSpring(target.height, SPRING)
    radius.value = withSpring(RADIUS[view], SPRING)
    visible.value = withTiming(view === "hidden" ? 0 : 1, {
      duration: view === "hidden" ? 400 : 300,
      reduceMotion: ReduceMotion.System,
    })
  }, [target.width, target.height, view, width, height, radius, visible])

  const swipeUp = React.useCallback(() => {
    if (view === "notice") dismiss()
    else if (view === "expanded") collapse()
  }, [view, dismiss, collapse])

  useBackHandler(view === "expanded", collapse)

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .activeOffsetY([-8, 8])
        .onStart(() => {
          runOnJS(setPaused)(true)
        })
        .onUpdate((event) => {
          translateY.value =
            event.translationY < 0
              ? event.translationY * 0.5
              : event.translationY * 0.15
        })
        .onEnd((event) => {
          translateY.value = withSpring(0, SPRING)
          runOnJS(setPaused)(false)
          if (event.translationY < -24 || event.velocityY < -500) {
            runOnJS(swipeUp)()
          }
        }),
    [translateY, setPaused, swipeUp]
  )

  const animatedStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
    borderRadius: radius.value,
    opacity: visible.value,
    transform: [
      { translateY: translateY.value },
      { scale: 0.75 + visible.value * 0.25 },
    ],
  }))

  const stage = React.useMemo(
    () => ({ view, stageWidth: window.width, reportSize }),
    [view, window.width, reportSize]
  )

  const expandActions = [{ name: "activate" }, { name: "expand" }]

  const onExpandAction = (event: AccessibilityActionEvent) => {
    const action = event.nativeEvent.actionName
    if (action === "activate" || action === "expand") expand()
  }

  return (
    <Portal name={`island-${id}`} hostName={portalHost}>
      <IslandContext.Provider value={context}>
        <IslandPauseContext.Provider value={setPaused}>
          {view === "expanded" ? (
            <Pressable
              accessible={false}
              importantForAccessibility="no"
              onPress={collapse}
              className="absolute inset-0 z-40"
            />
          ) : null}
          <View
            pointerEvents="box-none"
            className="absolute inset-x-0 z-50 items-center"
            style={{ top: Math.max(12, insets.top + 4) }}
          >
            <GestureDetector gesture={gesture}>
              <AnimatedView
                {...props}
                pointerEvents={view === "hidden" ? "none" : "auto"}
                onAccessibilityEscape={
                  view === "expanded"
                    ? () => {
                        collapse()
                        onAccessibilityEscape?.()
                      }
                    : onAccessibilityEscape
                }
                className={cn("overflow-hidden bg-black shadow-xl", className)}
                style={[style, animatedStyle]}
              >
                <TextClassContext.Provider value="text-white">
                  <IconClassContext.Provider value="size-5 text-white">
                    <IslandStageContext.Provider value={stage}>
                      <IslandStage
                        width={width}
                        stageWidth={window.width}
                        stageHeight={window.height}
                      >
                        {hasCompact ? (
                          <IslandPart part="compact">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              className="h-9 min-w-36 flex-row items-center justify-between gap-6 px-2.5"
                            >
                              {compactLeading ?? <View />}
                              {compactTrailing ?? <View />}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        {hasMinimal ? (
                          <IslandPart part="minimal">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              className="size-9 items-center justify-center"
                            >
                              {minimal}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        <IslandExpandedView
                          regions={regions}
                          accessibilityLabel={accessibilityLabel}
                        />
                        <IslandNoticeView current={notice} />
                      </IslandStage>
                    </IslandStageContext.Provider>
                  </IconClassContext.Provider>
                </TextClassContext.Provider>
              </AnimatedView>
            </GestureDetector>
          </View>
        </IslandPauseContext.Provider>
      </IslandContext.Provider>
    </Portal>
  )
}

const IslandRingValueContext = React.createContext(0)

const RING_RADIUS = 8

const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS

function IslandRingShape({ color, size, style }: PhosphorIconProps) {
  const value = React.useContext(IslandRingValueContext)
  return (
    <Svg
      width={size}
      height={size}
      viewBox="0 0 20 20"
      style={[style, { transform: [{ rotate: "-90deg" }] }]}
    >
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeOpacity={0.25}
        strokeWidth="2.5"
      />
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeDasharray={RING_CIRCUMFERENCE}
        strokeDashoffset={
          RING_CIRCUMFERENCE * (1 - Math.min(Math.max(value, 0), 1))
        }
      />
    </Svg>
  )
}

function IslandRing({
  value,
  className,
}: {
  value: number
  className?: string
}) {
  return (
    <IslandRingValueContext.Provider value={value}>
      <View
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
      >
        <Icon
          as={IslandRingShape}
          className={cn("size-5 text-primary", className)}
        />
      </View>
    </IslandRingValueContext.Provider>
  )
}

export type { IslandNotice, IslandRegion, IslandView }
export { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland }
```

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-safe-area-context 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/hooks.tsx`, `components/primitives/portal.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/interactions/island.tsx`:

```tsx title="nativewind/components/interactions/island.tsx"
import { cn } from "cn"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  AccessibilityInfo,
  Pressable,
  useWindowDimensions,
  View,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
  withTiming,
} from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import Svg, { Circle } from "react-native-svg"
import { useBackHandler } from "@/components/primitives/hooks"
import { Portal } from "@/components/primitives/portal"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type IslandView = "hidden" | "compact" | "minimal" | "expanded" | "notice"

type IslandMode = "compact" | "minimal" | "expanded"

type IslandPartName = Exclude<IslandView, "hidden">

type IslandRegion = "leading" | "trailing" | "center" | "bottom"

type IslandNotice = {
  icon?: React.ReactNode
  title: React.ReactNode
  description?: React.ReactNode
  duration?: number
}

type IslandContextProps = {
  view: IslandView
  notice: IslandNotice | null
  expand: () => void
  collapse: () => void
  minimize: () => void
  notify: (notice: IslandNotice) => void
  dismiss: () => void
  registerActivity: () => () => void
}

type IslandSize = { width: number; height: number }

type IslandStageContextProps = {
  view: IslandView
  stageWidth: number
  reportSize: (part: IslandPartName, size: IslandSize) => void
}

const IslandContext = React.createContext<IslandContextProps | null>(null)

const IslandPauseContext = React.createContext<(paused: boolean) => void>(
  () => undefined
)

const IslandStageContext = React.createContext<IslandStageContextProps | null>(
  null
)

function useIsland() {
  const context = React.useContext(IslandContext)

  if (!context) {
    throw new Error("useIsland must be used within an <IslandProvider />")
  }

  return context
}

const NOTICE_DURATION = 4000

const HIDDEN_SIZE: IslandSize = { width: 126, height: 36 }

const MAX_WIDTH = 384

const SPRING = {
  damping: 22,
  stiffness: 260,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const RADIUS: Record<IslandView, number> = {
  hidden: 18,
  compact: 18,
  minimal: 18,
  expanded: 28,
  notice: 28,
}

function islandView(
  notice: IslandNotice | null,
  mode: IslandMode,
  activityCount: number
): IslandView {
  if (notice) return "notice"
  if (activityCount <= 0) return "hidden"
  return mode
}

function availableView(
  view: IslandView,
  hasCompact: boolean,
  hasMinimal: boolean
): IslandView {
  if (view === "minimal" && !hasMinimal) return "compact"
  if (view === "compact" && !hasCompact) return "minimal"
  return view
}

function plainText(node: React.ReactNode) {
  return typeof node === "string" || typeof node === "number"
    ? String(node)
    : ""
}

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

function IslandProvider({ children }: { children?: React.ReactNode }) {
  const [mode, setMode] = React.useState<IslandMode>("compact")
  const [notice, setNotice] = React.useState<
    (IslandNotice & { id: number }) | null
  >(null)
  const [activityCount, setActivityCount] = React.useState(0)
  const [paused, setPaused] = React.useState(false)
  const idRef = React.useRef(0)

  const view = islandView(notice, mode, activityCount)

  const expand = React.useCallback(() => setMode("expanded"), [])

  const collapse = React.useCallback(() => setMode("compact"), [])

  const minimize = React.useCallback(() => setMode("minimal"), [])

  const dismiss = React.useCallback(() => {
    setNotice(null)
    setPaused(false)
  }, [])

  const notify = React.useCallback((next: IslandNotice) => {
    idRef.current += 1
    setNotice({ ...next, id: idRef.current })
  }, [])

  const registerActivity = React.useCallback(() => {
    setActivityCount((count) => count + 1)
    return () => {
      setActivityCount((count) => count - 1)
      setMode("compact")
    }
  }, [])

  React.useEffect(() => {
    if (!notice) return
    const message = [plainText(notice.title), plainText(notice.description)]
      .filter(Boolean)
      .join(", ")
    if (message) AccessibilityInfo.announceForAccessibility(message)
  }, [notice])

  React.useEffect(() => {
    if (!notice || paused) return
    const duration = notice.duration ?? NOTICE_DURATION
    if (!Number.isFinite(duration) || duration <= 0) return
    const timer = setTimeout(dismiss, duration)
    return () => clearTimeout(timer)
  }, [notice, paused, dismiss])

  const contextValue = React.useMemo(
    () => ({
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    }),
    [
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    ]
  )

  return (
    <IslandContext.Provider value={contextValue}>
      <IslandPauseContext.Provider value={setPaused}>
        {children}
      </IslandPauseContext.Provider>
    </IslandContext.Provider>
  )
}

function IslandPart({
  part,
  className,
  style,
  children,
}: {
  part: IslandPartName
  className?: string
  style?: React.ComponentProps<typeof View>["style"]
  children?: React.ReactNode
}) {
  const stage = React.useContext(IslandStageContext)
  const active = stage?.view === part
  const progress = useSharedValue(active ? 1 : 0)

  React.useEffect(() => {
    progress.value = withTiming(active ? 1 : 0, {
      duration: active ? 300 : 150,
      reduceMotion: ReduceMotion.System,
    })
  }, [active, progress])

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: progress.value,
    transform: [{ scale: 0.9 + progress.value * 0.1 }],
  }))

  return (
    <AnimatedView
      pointerEvents={active ? "box-none" : "none"}
      accessibilityElementsHidden={!active}
      importantForAccessibility={active ? "auto" : "no-hide-descendants"}
      onLayout={(event) => {
        const { width, height } = event.nativeEvent.layout
        stage?.reportSize(part, { width, height })
      }}
      className={cn("absolute top-0", className)}
      style={[style, animatedStyle]}
    >
      {children}
    </AnimatedView>
  )
}

function IslandNoticeView({ current }: { current: IslandNotice | null }) {
  const { dismiss } = useIsland()
  const lastRef = React.useRef(current)
  if (current) lastRef.current = current
  const notice = current ?? lastRef.current
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)

  return (
    <IslandPart part="notice" style={{ width }}>
      <Pressable
        role="button"
        accessibilityActions={[{ name: "activate" }, { name: "dismiss" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "activate" || action === "dismiss") dismiss()
        }}
        onPress={dismiss}
        className="w-full flex-row items-center gap-3 p-3.5"
      >
        {notice?.icon ? (
          <IconClassContext.Provider value="size-6 text-white">
            <View className="size-10 shrink-0 items-center justify-center rounded-xl bg-white/15">
              {notice.icon}
            </View>
          </IconClassContext.Provider>
        ) : null}
        <View className="min-w-0 flex-1">
          {wrapText(notice?.title, "text-sm font-semibold", 1)}
          {notice?.description !== undefined
            ? wrapText(notice.description, "text-sm text-white/70", 1)
            : null}
        </View>
      </Pressable>
    </IslandPart>
  )
}

function IslandStage({
  width,
  stageWidth,
  stageHeight,
  children,
}: {
  width: SharedValue<number>
  stageWidth: number
  stageHeight: number
  children?: React.ReactNode
}) {
  const animatedStyle = useAnimatedStyle(() => ({
    left: (width.value - stageWidth) / 2,
  }))

  return (
    <AnimatedView
      pointerEvents="box-none"
      className="absolute top-0 items-center"
      style={[{ width: stageWidth, height: stageHeight }, animatedStyle]}
    >
      {children}
    </AnimatedView>
  )
}

type IslandExpandedRegionProps = React.ComponentProps<typeof View> & {
  region: IslandRegion
  className?: string
}

const REGION_CLASS: Record<IslandRegion, string> = {
  leading: "shrink-0",
  trailing: "shrink-0 items-end",
  center: "min-w-0 flex-1",
  bottom: "w-full gap-3",
}

function IslandExpandedRegion({
  region,
  className,
  ...props
}: IslandExpandedRegionProps) {
  return <View className={cn(REGION_CLASS[region], className)} {...props} />
}

type IslandRegions = Record<IslandRegion, React.ReactElement[]>

function collectRegions(
  children: React.ReactNode,
  regions: IslandRegions = {
    leading: [],
    trailing: [],
    center: [],
    bottom: [],
  }
) {
  for (const child of React.Children.toArray(children)) {
    if (!React.isValidElement(child)) continue
    if (child.type === React.Fragment) {
      collectRegions(
        (child.props as { children?: React.ReactNode }).children,
        regions
      )
    } else if (child.type === IslandExpandedRegion) {
      const { region } = child.props as IslandExpandedRegionProps
      regions[region].push(child)
    }
  }
  return regions
}

function IslandExpandedView({
  regions,
  accessibilityLabel,
}: {
  regions: IslandRegions
  accessibilityLabel?: string
}) {
  const { collapse } = useIsland()
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)
  const hasTop =
    regions.leading.length > 0 ||
    regions.center.length > 0 ||
    regions.trailing.length > 0

  return (
    <IslandPart part="expanded" style={{ width }}>
      <View
        role="group"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={[{ name: "escape" }, { name: "collapse" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "escape" || action === "collapse") collapse()
        }}
        onAccessibilityEscape={collapse}
        className="w-full flex-col gap-3 p-4"
      >
        {hasTop ? (
          <View className="w-full flex-row items-center gap-3">
            {regions.leading}
            {regions.center.length > 0 ? (
              regions.center
            ) : (
              <View className="flex-1" />
            )}
            {regions.trailing}
          </View>
        ) : null}
        {regions.bottom}
      </View>
    </IslandPart>
  )
}

function Island({
  className,
  style,
  children,
  compactLeading,
  compactTrailing,
  minimal,
  accessibilityLabel,
  portalHost,
  onAccessibilityEscape,
  ...props
}: React.ComponentProps<typeof View> & {
  className?: string
  compactLeading?: React.ReactNode
  compactTrailing?: React.ReactNode
  minimal?: React.ReactNode
  portalHost?: string
}) {
  const context = useIsland()
  const setPaused = React.useContext(IslandPauseContext)
  const { notice, expand, collapse, dismiss, registerActivity } = context
  const insets = useSafeAreaInsets()
  const window = useWindowDimensions()
  const id = React.useId()
  const [sizes, setSizes] = React.useState<
    Partial<Record<IslandPartName, IslandSize>>
  >({})
  const width = useSharedValue(HIDDEN_SIZE.width)
  const height = useSharedValue(HIDDEN_SIZE.height)
  const radius = useSharedValue(RADIUS.hidden)
  const visible = useSharedValue(0)
  const translateY = useSharedValue(0)

  const hasCompact = compactLeading != null || compactTrailing != null
  const hasMinimal = minimal != null
  const active = hasCompact || hasMinimal

  React.useEffect(() => {
    if (!active) return
    return registerActivity()
  }, [active, registerActivity])

  React.useEffect(() => () => setPaused(false), [setPaused])

  const view = availableView(context.view, hasCompact, hasMinimal)

  const regions = collectRegions(children)

  const reportSize = React.useCallback(
    (part: IslandPartName, size: IslandSize) => {
      setSizes((current) => {
        const previous = current[part]
        if (
          previous &&
          previous.width === size.width &&
          previous.height === size.height
        ) {
          return current
        }
        return { ...current, [part]: size }
      })
    },
    []
  )

  const target = view === "hidden" ? HIDDEN_SIZE : (sizes[view] ?? HIDDEN_SIZE)

  React.useEffect(() => {
    width.value = withSpring(target.width, SPRING)
    height.value = withSpring(target.height, SPRING)
    radius.value = withSpring(RADIUS[view], SPRING)
    visible.value = withTiming(view === "hidden" ? 0 : 1, {
      duration: view === "hidden" ? 400 : 300,
      reduceMotion: ReduceMotion.System,
    })
  }, [target.width, target.height, view, width, height, radius, visible])

  const swipeUp = React.useCallback(() => {
    if (view === "notice") dismiss()
    else if (view === "expanded") collapse()
  }, [view, dismiss, collapse])

  useBackHandler(view === "expanded", collapse)

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .activeOffsetY([-8, 8])
        .onStart(() => {
          runOnJS(setPaused)(true)
        })
        .onUpdate((event) => {
          translateY.value =
            event.translationY < 0
              ? event.translationY * 0.5
              : event.translationY * 0.15
        })
        .onEnd((event) => {
          translateY.value = withSpring(0, SPRING)
          runOnJS(setPaused)(false)
          if (event.translationY < -24 || event.velocityY < -500) {
            runOnJS(swipeUp)()
          }
        }),
    [translateY, setPaused, swipeUp]
  )

  const animatedStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
    borderRadius: radius.value,
    opacity: visible.value,
    transform: [
      { translateY: translateY.value },
      { scale: 0.75 + visible.value * 0.25 },
    ],
  }))

  const stage = React.useMemo(
    () => ({ view, stageWidth: window.width, reportSize }),
    [view, window.width, reportSize]
  )

  const expandActions = [{ name: "activate" }, { name: "expand" }]

  const onExpandAction = (event: AccessibilityActionEvent) => {
    const action = event.nativeEvent.actionName
    if (action === "activate" || action === "expand") expand()
  }

  return (
    <Portal name={`island-${id}`} hostName={portalHost}>
      <IslandContext.Provider value={context}>
        <IslandPauseContext.Provider value={setPaused}>
          {view === "expanded" ? (
            <Pressable
              accessible={false}
              importantForAccessibility="no"
              onPress={collapse}
              className="absolute inset-0 z-40"
            />
          ) : null}
          <View
            pointerEvents="box-none"
            className="absolute inset-x-0 z-50 items-center"
            style={{ top: Math.max(12, insets.top + 4) }}
          >
            <GestureDetector gesture={gesture}>
              <AnimatedView
                {...props}
                pointerEvents={view === "hidden" ? "none" : "auto"}
                onAccessibilityEscape={
                  view === "expanded"
                    ? () => {
                        collapse()
                        onAccessibilityEscape?.()
                      }
                    : onAccessibilityEscape
                }
                className={cn("overflow-hidden bg-black shadow-xl", className)}
                style={[style, animatedStyle]}
              >
                <TextClassContext.Provider value="text-white">
                  <IconClassContext.Provider value="size-5 text-white">
                    <IslandStageContext.Provider value={stage}>
                      <IslandStage
                        width={width}
                        stageWidth={window.width}
                        stageHeight={window.height}
                      >
                        {hasCompact ? (
                          <IslandPart part="compact">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              className="h-9 min-w-36 flex-row items-center justify-between gap-6 px-2.5"
                            >
                              {compactLeading ?? <View />}
                              {compactTrailing ?? <View />}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        {hasMinimal ? (
                          <IslandPart part="minimal">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              className="size-9 items-center justify-center"
                            >
                              {minimal}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        <IslandExpandedView
                          regions={regions}
                          accessibilityLabel={accessibilityLabel}
                        />
                        <IslandNoticeView current={notice} />
                      </IslandStage>
                    </IslandStageContext.Provider>
                  </IconClassContext.Provider>
                </TextClassContext.Provider>
              </AnimatedView>
            </GestureDetector>
          </View>
        </IslandPauseContext.Provider>
      </IslandContext.Provider>
    </Portal>
  )
}

const IslandRingValueContext = React.createContext(0)

const RING_RADIUS = 8

const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS

function IslandRingShape({ color, size, style }: PhosphorIconProps) {
  const value = React.useContext(IslandRingValueContext)
  return (
    <Svg
      width={size}
      height={size}
      viewBox="0 0 20 20"
      style={[style, { transform: [{ rotate: "-90deg" }] }]}
    >
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeOpacity={0.25}
        strokeWidth="2.5"
      />
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeDasharray={RING_CIRCUMFERENCE}
        strokeDashoffset={
          RING_CIRCUMFERENCE * (1 - Math.min(Math.max(value, 0), 1))
        }
      />
    </Svg>
  )
}

function IslandRing({
  value,
  className,
}: {
  value: number
  className?: string
}) {
  return (
    <IslandRingValueContext.Provider value={value}>
      <View
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
      >
        <Icon
          as={IslandRingShape}
          className={cn("size-5 text-primary", className)}
        />
      </View>
    </IslandRingValueContext.Provider>
  )
}

export type { IslandNotice, IslandRegion, IslandView }
export { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland }
```

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-safe-area-context 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/hooks.tsx`, `components/primitives/portal.tsx`, and the animated view `components/ui/animated-view.tsx` from the next step.

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

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

4. Copy the source into `components/interactions/island.tsx`:

```tsx title="stylesheet/components/interactions/island.tsx"
import type { IconProps as PhosphorIconProps } from "phosphor-react-native"
import * as React from "react"
import {
  type AccessibilityActionEvent,
  AccessibilityInfo,
  Pressable,
  type StyleProp,
  StyleSheet,
  type TextStyle,
  useWindowDimensions,
  View,
  type ViewStyle,
} from "react-native"
import { Gesture, GestureDetector } from "react-native-gesture-handler"
import {
  ReduceMotion,
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
  useSharedValue,
  withSpring,
  withTiming,
} from "react-native-reanimated"
import { useSafeAreaInsets } from "react-native-safe-area-context"
import Svg, { Circle } from "react-native-svg"
import { useBackHandler } from "@/components/primitives/hooks"
import { Portal } from "@/components/primitives/portal"
import { AnimatedView } from "@/components/ui/animated-view"
import { Icon, IconSizeContext } from "@/components/ui/icon"
import { Text, TextStyleContext } from "@/components/ui/text"
import { fontSize, palette, shadow, useTheme } from "@/components/ui/theme"

type IslandView = "hidden" | "compact" | "minimal" | "expanded" | "notice"

type IslandMode = "compact" | "minimal" | "expanded"

type IslandPartName = Exclude<IslandView, "hidden">

type IslandRegion = "leading" | "trailing" | "center" | "bottom"

type IslandNotice = {
  icon?: React.ReactNode
  title: React.ReactNode
  description?: React.ReactNode
  duration?: number
}

type IslandContextProps = {
  view: IslandView
  notice: IslandNotice | null
  expand: () => void
  collapse: () => void
  minimize: () => void
  notify: (notice: IslandNotice) => void
  dismiss: () => void
  registerActivity: () => () => void
}

type IslandSize = { width: number; height: number }

type IslandStageContextProps = {
  view: IslandView
  stageWidth: number
  reportSize: (part: IslandPartName, size: IslandSize) => void
}

const IslandContext = React.createContext<IslandContextProps | null>(null)

const IslandPauseContext = React.createContext<(paused: boolean) => void>(
  () => undefined
)

const IslandStageContext = React.createContext<IslandStageContextProps | null>(
  null
)

function useIsland() {
  const context = React.useContext(IslandContext)

  if (!context) {
    throw new Error("useIsland must be used within an <IslandProvider />")
  }

  return context
}

const NOTICE_DURATION = 4000

const HIDDEN_SIZE: IslandSize = { width: 126, height: 36 }

const MAX_WIDTH = 384

const SPRING = {
  damping: 22,
  stiffness: 260,
  mass: 1,
  reduceMotion: ReduceMotion.System,
}

const RADIUS: Record<IslandView, number> = {
  hidden: 18,
  compact: 18,
  minimal: 18,
  expanded: 28,
  notice: 28,
}

function islandView(
  notice: IslandNotice | null,
  mode: IslandMode,
  activityCount: number
): IslandView {
  if (notice) return "notice"
  if (activityCount <= 0) return "hidden"
  return mode
}

const styles = StyleSheet.create({
  part: { position: "absolute", top: 0 },
  notice: {
    width: "100%",
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
    padding: 14,
  },
  noticeIcon: {
    width: 40,
    height: 40,
    flexShrink: 0,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 12,
  },
  noticeBody: { minWidth: 0, flex: 1 },
  title: { ...fontSize.sm, fontWeight: "600" },
  description: { ...fontSize.sm },
  stage: { position: "absolute", top: 0, alignItems: "center" },
  backdrop: { ...StyleSheet.absoluteFill, zIndex: 40 },
  frame: {
    position: "absolute",
    left: 0,
    right: 0,
    zIndex: 50,
    alignItems: "center",
  },
  island: { overflow: "hidden", ...shadow.xl },
  compact: {
    height: 36,
    minWidth: 144,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 24,
    paddingHorizontal: 10,
  },
  minimal: {
    width: 36,
    height: 36,
    alignItems: "center",
    justifyContent: "center",
  },
  expanded: { width: "100%", flexDirection: "column", gap: 12, padding: 16 },
  expandedTop: {
    width: "100%",
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
  },
  spacer: { flex: 1 },
})

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 plainText(node: React.ReactNode) {
  return typeof node === "string" || typeof node === "number"
    ? String(node)
    : ""
}

function wrapText(
  children: React.ReactNode,
  style: StyleProp<TextStyle>,
  numberOfLines?: number
) {
  if (typeof children === "string" || typeof children === "number") {
    return (
      <Text style={style} numberOfLines={numberOfLines}>
        {children}
      </Text>
    )
  }
  return children
}

function IslandProvider({ children }: { children?: React.ReactNode }) {
  const [mode, setMode] = React.useState<IslandMode>("compact")
  const [notice, setNotice] = React.useState<
    (IslandNotice & { id: number }) | null
  >(null)
  const [activityCount, setActivityCount] = React.useState(0)
  const [paused, setPaused] = React.useState(false)
  const idRef = React.useRef(0)

  const view = islandView(notice, mode, activityCount)

  const expand = React.useCallback(() => setMode("expanded"), [])

  const collapse = React.useCallback(() => setMode("compact"), [])

  const minimize = React.useCallback(() => setMode("minimal"), [])

  const dismiss = React.useCallback(() => {
    setNotice(null)
    setPaused(false)
  }, [])

  const notify = React.useCallback((next: IslandNotice) => {
    idRef.current += 1
    setNotice({ ...next, id: idRef.current })
  }, [])

  const registerActivity = React.useCallback(() => {
    setActivityCount((count) => count + 1)
    return () => {
      setActivityCount((count) => count - 1)
      setMode("compact")
    }
  }, [])

  React.useEffect(() => {
    if (!notice) return
    const message = [plainText(notice.title), plainText(notice.description)]
      .filter(Boolean)
      .join(", ")
    if (message) AccessibilityInfo.announceForAccessibility(message)
  }, [notice])

  React.useEffect(() => {
    if (!notice || paused) return
    const duration = notice.duration ?? NOTICE_DURATION
    if (!Number.isFinite(duration) || duration <= 0) return
    const timer = setTimeout(dismiss, duration)
    return () => clearTimeout(timer)
  }, [notice, paused, dismiss])

  const contextValue = React.useMemo(
    () => ({
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    }),
    [
      view,
      notice,
      expand,
      collapse,
      minimize,
      notify,
      dismiss,
      registerActivity,
    ]
  )

  return (
    <IslandContext.Provider value={contextValue}>
      <IslandPauseContext.Provider value={setPaused}>
        {children}
      </IslandPauseContext.Provider>
    </IslandContext.Provider>
  )
}

function IslandPart({
  part,
  style,
  children,
}: {
  part: IslandPartName
  style?: StyleProp<ViewStyle>
  children?: React.ReactNode
}) {
  const stage = React.useContext(IslandStageContext)
  const active = stage?.view === part
  const progress = useSharedValue(active ? 1 : 0)

  React.useEffect(() => {
    progress.value = withTiming(active ? 1 : 0, {
      duration: active ? 300 : 150,
      reduceMotion: ReduceMotion.System,
    })
  }, [active, progress])

  const animatedStyle = useAnimatedStyle(() => ({
    opacity: progress.value,
    transform: [{ scale: 0.9 + progress.value * 0.1 }],
  }))

  return (
    <AnimatedView
      pointerEvents={active ? "box-none" : "none"}
      accessibilityElementsHidden={!active}
      importantForAccessibility={active ? "auto" : "no-hide-descendants"}
      onLayout={(event) => {
        const { width, height } = event.nativeEvent.layout
        stage?.reportSize(part, { width, height })
      }}
      style={[styles.part, style, animatedStyle]}
    >
      {children}
    </AnimatedView>
  )
}

function IslandNoticeView({ current }: { current: IslandNotice | null }) {
  const { dismiss } = useIsland()
  const lastRef = React.useRef(current)
  if (current) lastRef.current = current
  const notice = current ?? lastRef.current
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)

  return (
    <IslandPart part="notice" style={{ width }}>
      <Pressable
        role="button"
        accessibilityActions={[{ name: "activate" }, { name: "dismiss" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "activate" || action === "dismiss") dismiss()
        }}
        onPress={dismiss}
        style={styles.notice}
      >
        {notice?.icon ? (
          <IconSizeContext.Provider value={24}>
            <View
              style={[
                styles.noticeIcon,
                { backgroundColor: withAlpha(palette.white, 0.15) },
              ]}
            >
              {notice.icon}
            </View>
          </IconSizeContext.Provider>
        ) : null}
        <View style={styles.noticeBody}>
          {wrapText(notice?.title, styles.title, 1)}
          {notice?.description !== undefined
            ? wrapText(
                notice.description,
                [styles.description, { color: withAlpha(palette.white, 0.7) }],
                1
              )
            : null}
        </View>
      </Pressable>
    </IslandPart>
  )
}

function IslandStage({
  width,
  stageWidth,
  stageHeight,
  children,
}: {
  width: SharedValue<number>
  stageWidth: number
  stageHeight: number
  children?: React.ReactNode
}) {
  const animatedStyle = useAnimatedStyle(() => ({
    left: (width.value - stageWidth) / 2,
  }))

  return (
    <AnimatedView
      pointerEvents="box-none"
      style={[
        styles.stage,
        { width: stageWidth, height: stageHeight },
        animatedStyle,
      ]}
    >
      {children}
    </AnimatedView>
  )
}

type IslandExpandedRegionProps = React.ComponentProps<typeof View> & {
  region: IslandRegion
}

const regionStyles = StyleSheet.create({
  leading: { flexShrink: 0 },
  trailing: { flexShrink: 0, alignItems: "flex-end" },
  center: { minWidth: 0, flex: 1 },
  bottom: { width: "100%", gap: 12 },
})

function IslandExpandedRegion({
  region,
  style,
  ...props
}: IslandExpandedRegionProps) {
  return <View style={[regionStyles[region], style]} {...props} />
}

type IslandRegions = Record<IslandRegion, React.ReactElement[]>

function collectRegions(
  children: React.ReactNode,
  regions: IslandRegions = {
    leading: [],
    trailing: [],
    center: [],
    bottom: [],
  }
) {
  for (const child of React.Children.toArray(children)) {
    if (!React.isValidElement(child)) continue
    if (child.type === React.Fragment) {
      collectRegions(
        (child.props as { children?: React.ReactNode }).children,
        regions
      )
    } else if (child.type === IslandExpandedRegion) {
      const { region } = child.props as IslandExpandedRegionProps
      regions[region].push(child)
    }
  }
  return regions
}

function IslandExpandedView({
  regions,
  accessibilityLabel,
}: {
  regions: IslandRegions
  accessibilityLabel?: string
}) {
  const { collapse } = useIsland()
  const stage = React.useContext(IslandStageContext)
  const width = Math.min((stage?.stageWidth ?? MAX_WIDTH) - 24, MAX_WIDTH)
  const hasTop =
    regions.leading.length > 0 ||
    regions.center.length > 0 ||
    regions.trailing.length > 0

  return (
    <IslandPart part="expanded" style={{ width }}>
      <View
        role="group"
        accessibilityLabel={accessibilityLabel}
        accessibilityActions={[{ name: "escape" }, { name: "collapse" }]}
        onAccessibilityAction={(event) => {
          const action = event.nativeEvent.actionName
          if (action === "escape" || action === "collapse") collapse()
        }}
        onAccessibilityEscape={collapse}
        style={styles.expanded}
      >
        {hasTop ? (
          <View style={styles.expandedTop}>
            {regions.leading}
            {regions.center.length > 0 ? (
              regions.center
            ) : (
              <View style={styles.spacer} />
            )}
            {regions.trailing}
          </View>
        ) : null}
        {regions.bottom}
      </View>
    </IslandPart>
  )
}

function Island({
  style,
  children,
  compactLeading,
  compactTrailing,
  minimal,
  accessibilityLabel,
  portalHost,
  onAccessibilityEscape,
  ...props
}: React.ComponentProps<typeof View> & {
  compactLeading?: React.ReactNode
  compactTrailing?: React.ReactNode
  minimal?: React.ReactNode
  portalHost?: string
}) {
  const context = useIsland()
  const setPaused = React.useContext(IslandPauseContext)
  const { notice, expand, collapse, dismiss, registerActivity } = context
  const insets = useSafeAreaInsets()
  const window = useWindowDimensions()
  const id = React.useId()
  const [sizes, setSizes] = React.useState<
    Partial<Record<IslandPartName, IslandSize>>
  >({})
  const width = useSharedValue(HIDDEN_SIZE.width)
  const height = useSharedValue(HIDDEN_SIZE.height)
  const radius = useSharedValue(RADIUS.hidden)
  const visible = useSharedValue(0)
  const translateY = useSharedValue(0)

  const hasCompact = compactLeading != null || compactTrailing != null
  const hasMinimal = minimal != null
  const active = hasCompact || hasMinimal

  React.useEffect(() => {
    if (!active) return
    return registerActivity()
  }, [active, registerActivity])

  React.useEffect(() => () => setPaused(false), [setPaused])

  let view: IslandView = context.view
  if (context.view === "minimal" && !hasMinimal) view = "compact"
  else if (context.view === "compact" && !hasCompact) view = "minimal"

  const regions = collectRegions(children)

  const reportSize = React.useCallback(
    (part: IslandPartName, size: IslandSize) => {
      setSizes((current) => {
        const previous = current[part]
        if (
          previous &&
          previous.width === size.width &&
          previous.height === size.height
        ) {
          return current
        }
        return { ...current, [part]: size }
      })
    },
    []
  )

  const target = view === "hidden" ? HIDDEN_SIZE : (sizes[view] ?? HIDDEN_SIZE)

  React.useEffect(() => {
    width.value = withSpring(target.width, SPRING)
    height.value = withSpring(target.height, SPRING)
    radius.value = withSpring(RADIUS[view], SPRING)
    visible.value = withTiming(view === "hidden" ? 0 : 1, {
      duration: view === "hidden" ? 400 : 300,
      reduceMotion: ReduceMotion.System,
    })
  }, [target.width, target.height, view, width, height, radius, visible])

  const swipeUp = React.useCallback(() => {
    if (view === "notice") dismiss()
    else if (view === "expanded") collapse()
  }, [view, dismiss, collapse])

  useBackHandler(view === "expanded", collapse)

  const gesture = React.useMemo(
    () =>
      Gesture.Pan()
        .activeOffsetY([-8, 8])
        .onStart(() => {
          runOnJS(setPaused)(true)
        })
        .onUpdate((event) => {
          translateY.value =
            event.translationY < 0
              ? event.translationY * 0.5
              : event.translationY * 0.15
        })
        .onEnd((event) => {
          translateY.value = withSpring(0, SPRING)
          runOnJS(setPaused)(false)
          if (event.translationY < -24 || event.velocityY < -500) {
            runOnJS(swipeUp)()
          }
        }),
    [translateY, setPaused, swipeUp]
  )

  const animatedStyle = useAnimatedStyle(() => ({
    width: width.value,
    height: height.value,
    borderRadius: radius.value,
    opacity: visible.value,
    transform: [
      { translateY: translateY.value },
      { scale: 0.75 + visible.value * 0.25 },
    ],
  }))

  const stage = React.useMemo(
    () => ({ view, stageWidth: window.width, reportSize }),
    [view, window.width, reportSize]
  )

  const expandActions = [{ name: "activate" }, { name: "expand" }]

  const onExpandAction = (event: AccessibilityActionEvent) => {
    const action = event.nativeEvent.actionName
    if (action === "activate" || action === "expand") expand()
  }

  return (
    <Portal name={`island-${id}`} hostName={portalHost}>
      <IslandContext.Provider value={context}>
        <IslandPauseContext.Provider value={setPaused}>
          {view === "expanded" ? (
            <Pressable
              accessible={false}
              importantForAccessibility="no"
              onPress={collapse}
              style={styles.backdrop}
            />
          ) : null}
          <View
            pointerEvents="box-none"
            style={[styles.frame, { top: Math.max(12, insets.top + 4) }]}
          >
            <GestureDetector gesture={gesture}>
              <AnimatedView
                {...props}
                pointerEvents={view === "hidden" ? "none" : "auto"}
                onAccessibilityEscape={
                  view === "expanded"
                    ? () => {
                        collapse()
                        onAccessibilityEscape?.()
                      }
                    : onAccessibilityEscape
                }
                style={[
                  styles.island,
                  { backgroundColor: palette.black },
                  style,
                  animatedStyle,
                ]}
              >
                <TextStyleContext.Provider value={{ color: palette.white }}>
                  <IconSizeContext.Provider value={20}>
                    <IslandStageContext.Provider value={stage}>
                      <IslandStage
                        width={width}
                        stageWidth={window.width}
                        stageHeight={window.height}
                      >
                        {hasCompact ? (
                          <IslandPart part="compact">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              style={styles.compact}
                            >
                              {compactLeading ?? <View />}
                              {compactTrailing ?? <View />}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        {hasMinimal ? (
                          <IslandPart part="minimal">
                            <Pressable
                              role="button"
                              accessibilityLabel={accessibilityLabel}
                              accessibilityState={{ expanded: false }}
                              accessibilityActions={expandActions}
                              onAccessibilityAction={onExpandAction}
                              onPress={expand}
                              style={styles.minimal}
                            >
                              {minimal}
                            </Pressable>
                          </IslandPart>
                        ) : null}
                        <IslandExpandedView
                          regions={regions}
                          accessibilityLabel={accessibilityLabel}
                        />
                        <IslandNoticeView current={notice} />
                      </IslandStage>
                    </IslandStageContext.Provider>
                  </IconSizeContext.Provider>
                </TextStyleContext.Provider>
              </AnimatedView>
            </GestureDetector>
          </View>
        </IslandPauseContext.Provider>
      </IslandContext.Provider>
    </Portal>
  )
}

const IslandRingValueContext = React.createContext(0)

const RING_RADIUS = 8

const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS

function IslandRingShape({ color, size, style }: PhosphorIconProps) {
  const value = React.useContext(IslandRingValueContext)
  return (
    <Svg
      width={size}
      height={size}
      viewBox="0 0 20 20"
      style={[style, { transform: [{ rotate: "-90deg" }] }]}
    >
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeOpacity={0.25}
        strokeWidth="2.5"
      />
      <Circle
        cx="10"
        cy="10"
        r={RING_RADIUS}
        fill="none"
        stroke={color}
        strokeWidth="2.5"
        strokeLinecap="round"
        strokeDasharray={RING_CIRCUMFERENCE}
        strokeDashoffset={
          RING_CIRCUMFERENCE * (1 - Math.min(Math.max(value, 0), 1))
        }
      />
    </Svg>
  )
}

function IslandRing({
  value,
  size = 20,
  color,
}: {
  value: number
  size?: number
  color?: string
}) {
  const { colors } = useTheme()
  return (
    <IslandRingValueContext.Provider value={value}>
      <View
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
      >
        <Icon
          as={IslandRingShape}
          size={size}
          color={color ?? colors.primary}
        />
      </View>
    </IslandRingValueContext.Provider>
  )
}

export type { IslandNotice, IslandRegion, IslandView }
export { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland }
```

5. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Copy the theme files every view uses:

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

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

3. Copy the source:

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

enum IslandMath {
  static func ringProgress(_ value: Double) -> Double {
    min(max(value, 0), 1)
  }
}

public struct IslandRing: View {
  let value: Double
  let color: Color

  public init(value: Double, color: Color = EsuissColor.primary) {
    self.value = value
    self.color = color
  }

  public var body: some View {
    let progress = IslandMath.ringProgress(value)
    ZStack {
      Circle()
        .stroke(color.opacity(0.25), lineWidth: 2.5)
      Circle()
        .trim(from: 0, to: progress)
        .stroke(color, style: StrokeStyle(lineWidth: 2.5, lineCap: .round))
        .rotationEffect(.degrees(-90))
        .animation(.easeOut(duration: 0.3), value: progress)
    }
    .padding(2)
    .frame(width: 20, height: 20)
    .accessibilityHidden(true)
  }
}
```

4. Add the files to your app target.

**Jetpack Compose**

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

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

2. Copy the theme files every view uses:

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

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

3. Copy the source and every file it uses:

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

import android.graphics.RectF
import android.os.Build
import android.view.View
import android.view.Window
import android.view.WindowInsets as PlatformWindowInsets
import android.view.WindowInsetsController
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.snap
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsIgnoringVisibility
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.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.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.layout.positionOnScreen
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalWindowInfo
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.collapse
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.customActions
import androidx.compose.ui.semantics.dismiss
import androidx.compose.ui.semantics.expand
import androidx.compose.ui.semantics.liveRegion
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.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import com.esuiss.ui.components.FormEasing
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.LocalContentStyle
import com.esuiss.ui.components.LocalIconSize
import com.esuiss.ui.components.findActivity
import com.esuiss.ui.components.formReducedMotion
import com.esuiss.ui.theme.DarkColors
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.LocalColors
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Shadow
import com.esuiss.ui.theme.Typography
import com.esuiss.ui.theme.shadow
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

enum class IslandView { Hidden, Compact, Minimal, Expanded, Notice }

enum class IslandRegion { Leading, Trailing, Center, Bottom }

@Immutable
class IslandNotice(
    val title: String,
    val description: String? = null,
    val duration: Long = IslandNoticeDuration,
    val icon: (@Composable () -> Unit)? = null,
)

const val IslandNoticeDuration = 4000L

private enum class IslandMode { Compact, Minimal, Expanded }

@Stable
class IslandState internal constructor() {
    private var mode by mutableStateOf(IslandMode.Compact)

    val expanded: Boolean
        get() = view == IslandView.Expanded
    var notice by mutableStateOf<IslandNotice?>(null)
        private set
    internal var activeCount by mutableIntStateOf(0)
    internal var hasMinimal by mutableStateOf(false)
    internal var noticeId by mutableIntStateOf(0)

    val view: IslandView
        get() = when {
            notice != null -> IslandView.Notice
            activeCount <= 0 -> IslandView.Hidden
            mode == IslandMode.Expanded -> IslandView.Expanded
            mode == IslandMode.Minimal && hasMinimal -> IslandView.Minimal
            else -> IslandView.Compact
        }

    fun expand() {
        mode = IslandMode.Expanded
    }

    fun collapse() {
        mode = IslandMode.Compact
    }

    fun minimize() {
        mode = IslandMode.Minimal
    }

    fun notify(notice: IslandNotice) {
        this.notice = notice
        noticeId += 1
    }

    fun notify(
        title: String,
        description: String? = null,
        duration: Long = IslandNoticeDuration,
        icon: (@Composable () -> Unit)? = null,
    ) = notify(IslandNotice(title, description, duration, icon))

    fun dismiss() {
        notice = null
    }

    internal fun register(): () -> Unit {
        activeCount += 1
        return {
            activeCount -= 1
            if (activeCount <= 0) mode = IslandMode.Compact
        }
    }
}

private val LocalIsland = staticCompositionLocalOf<IslandState?> { null }

@Composable
fun useIsland(): IslandState = checkNotNull(LocalIsland.current) { "useIsland must be used within an IslandProvider" }

@Composable
fun IslandProvider(content: @Composable () -> Unit) {
    val state = remember { IslandState() }
    val notice = state.notice
    LaunchedEffect(state.noticeId, notice) {
        if (notice == null) return@LaunchedEffect
        delay(notice.duration)
        state.dismiss()
    }
    CompositionLocalProvider(LocalIsland provides state, content = content)
}

private class IslandPosition(private val center: Float?) : PopupPositionProvider {
    override fun calculatePosition(
        anchorBounds: IntRect,
        windowSize: IntSize,
        layoutDirection: LayoutDirection,
        popupContentSize: IntSize,
    ): IntOffset {
        val x = center?.let { (it - popupContentSize.width / 2f).toInt() } ?: ((windowSize.width - popupContentSize.width) / 2)
        return IntOffset(x.coerceIn(0, (windowSize.width - popupContentSize.width).coerceAtLeast(0)), 0)
    }
}

private class IslandCamera(val centerX: Float, val centerY: Float, val width: Float, val bottom: Float)

@Composable
private fun rememberIslandCamera(): IslandCamera? {
    val view = LocalView.current
    val configuration = LocalConfiguration.current
    var camera by remember { mutableStateOf<IslandCamera?>(null) }
    DisposableEffect(view, configuration) {
        fun read() {
            camera = islandCamera(view)
        }
        read()
        val listener = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> read() }
        view.addOnLayoutChangeListener(listener)
        onDispose { view.removeOnLayoutChangeListener(listener) }
    }
    return camera
}

private fun islandCamera(view: View): IslandCamera? {
    if (Build.VERSION.SDK_INT < 28) return null
    val cutout = view.rootWindowInsets?.displayCutout ?: return null
    val width = view.rootView.width.takeIf { it > 0 } ?: return null
    if (view.rootView.height <= width) return null
    if (Build.VERSION.SDK_INT >= 31) {
        val path = cutout.cutoutPath
        if (path != null) {
            val bounds = RectF()
            @Suppress("DEPRECATION")
            path.computeBounds(bounds, true)
            if (bounds.width() > 0f && bounds.top < width * 0.2f && bounds.width() < width * 0.3f) {
                return IslandCamera(bounds.centerX(), bounds.centerY(), bounds.width(), bounds.bottom)
            }
        }
    }
    val rect = cutout.boundingRects.firstOrNull { it.top <= 0 && it.width() > 0 && it.width() < width * 0.3f } ?: return null
    return IslandCamera(rect.exactCenterX(), rect.exactCenterY(), rect.width().toFloat(), rect.bottom.toFloat())
}

@Suppress("DEPRECATION")
private fun Window.showStatusBar(visible: Boolean) {
    if (Build.VERSION.SDK_INT >= 30) {
        val controller = insetsController ?: return
        if (visible) {
            controller.show(PlatformWindowInsets.Type.statusBars())
        } else {
            controller.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
            controller.hide(PlatformWindowInsets.Type.statusBars())
        }
        return
    }
    val flags = decorView.systemUiVisibility
    val next = if (visible) flags and View.SYSTEM_UI_FLAG_FULLSCREEN.inv() else flags or View.SYSTEM_UI_FLAG_FULLSCREEN
    if (next != flags) decorView.systemUiVisibility = next
}

@Composable
private fun IslandStatusBar(hide: Boolean) {
    val view = LocalView.current
    DisposableEffect(view, hide) {
        val window = if (hide && !view.isInEditMode) view.context.findActivity()?.window else null
        window?.showStatusBar(false)
        onDispose { window?.showStatusBar(true) }
    }
}

private val IslandSpring = spring<IntSize>(dampingRatio = 0.72f, stiffness = Spring.StiffnessMediumLow)

@Composable
internal fun islandWideWidth(): Dp {
    val density = LocalDensity.current
    val container = LocalWindowInfo.current.containerSize
    val available = with(density) { container.width.toDp() } - 24.dp
    return if (container.width > 0 && available < 384.dp) available else 384.dp
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun Island(
    compactLeading: (@Composable RowScope.() -> Unit)? = null,
    compactTrailing: (@Composable RowScope.() -> Unit)? = null,
    minimal: (@Composable () -> Unit)? = null,
    modifier: Modifier = Modifier,
    expanded: @Composable IslandExpandedScope.() -> Unit = {},
) {
    val state = useIsland()
    val active = compactLeading != null || compactTrailing != null
    DisposableEffect(state, active) {
        val release = if (active) state.register() else null
        onDispose { release?.invoke() }
    }
    val withMinimal = minimal != null
    DisposableEffect(state, withMinimal) {
        state.hasMinimal = withMinimal
        onDispose { state.hasMinimal = false }
    }
    val colors = EsuissTheme.colors
    val density = LocalDensity.current
    val reduced = formReducedMotion()
    val scope = rememberCoroutineScope()
    val view = state.view
    val hidden = view == IslandView.Hidden
    var present by remember { mutableStateOf(!hidden) }
    if (!hidden) present = true
    LaunchedEffect(hidden) {
        if (!hidden) return@LaunchedEffect
        delay(if (reduced) 0 else 400)
        present = false
    }
    val shown by animateFloatAsState(if (hidden) 0f else 1f, if (reduced) tween(0) else tween(400, easing = FormEasing), label = "shown")
    val small = view == IslandView.Compact || view == IslandView.Minimal || hidden
    val radius by animateDpAsState(
        if (small) 18.dp else 28.dp,
        if (reduced) tween(0) else tween(450, easing = FormEasing),
        label = "radius",
    )
    val camera = rememberIslandCamera()
    val belowBar = maxOf(with(density) { WindowInsets.statusBarsIgnoringVisibility.getTop(density).toDp() }, 12.dp)
    val atCamera = camera?.let { with(density) { (it.centerY.toDp() - 18.dp).coerceAtLeast(4.dp) } }
    val top by animateDpAsState(
        atCamera ?: belowBar,
        if (reduced) tween(0) else tween(450, easing = FormEasing),
        label = "top",
    )
    var origin by remember { mutableStateOf<Float?>(null) }
    val offset = origin?.let { with(density) { (top.toPx() - it).coerceAtLeast(0f).toDp() } } ?: top
    val target = camera?.let {
        if (view == IslandView.Minimal) it.centerX + it.width / 2f + with(density) { 26.dp.toPx() } else it.centerX
    }
    val anchor = remember { Animatable(0f) }
    var anchored by remember { mutableStateOf(false) }
    LaunchedEffect(target) {
        if (target == null) {
            anchored = false
            return@LaunchedEffect
        }
        if (!anchored || reduced) {
            anchor.snapTo(target)
            anchored = true
        } else {
            anchor.animateTo(target, tween(450, easing = FormEasing))
        }
    }
    val center = if (anchored) anchor.value else null
    val provider = remember(center) { IslandPosition(center) }
    val drag = remember { Animatable(0f) }
    val dragState = rememberDraggableState { delta ->
        scope.launch { drag.snapTo((drag.value + delta).coerceAtMost(with(density) { 8.dp.toPx() })) }
    }
    val shape = RoundedCornerShape(radius)
    val background = Palette.black
    val foreground = Palette.white
    val hole = camera?.let { with(density) { it.width.toDp() } }
    val clearance = if (camera != null && atCamera != null) {
        with(density) { (camera.bottom.toDp() - atCamera - 8.dp).coerceAtLeast(0.dp) }
    } else {
        0.dp
    }
    val reach = camera != null && (view == IslandView.Compact || view == IslandView.Minimal)
    IslandStatusBar(camera != null && (view == IslandView.Expanded || view == IslandView.Notice))
    Popup(
        popupPositionProvider = provider,
        onDismissRequest = { if (state.view == IslandView.Expanded) state.collapse() },
        properties = PopupProperties(
            clippingEnabled = false,
            focusable = view == IslandView.Expanded,
            dismissOnBackPress = true,
            dismissOnClickOutside = view == IslandView.Expanded,
        ),
    ) {
        IslandReach(
            modifier = Modifier
                .onGloballyPositioned { origin = it.positionOnScreen().y }
                .then(if (present) Modifier.padding(top = offset, start = 12.dp, end = 12.dp, bottom = if (reach) 0.dp else 24.dp) else Modifier),
        ) {
            Box(
                modifier = if (!present) {
                    Modifier.size(0.dp)
                } else {
                    modifier
                        .graphicsLayer {
                            translationY = drag.value
                            alpha = shown
                            scaleX = 0.75f + 0.25f * shown
                            scaleY = scaleX
                        }
                        .shadow(Shadow(0.dp, 20.dp, 25.dp, Color.Black.copy(alpha = 0.1f)), shape)
                        .clip(shape)
                        .background(background, shape)
                        .animateContentSize(if (reduced) snap() else IslandSpring)
                        .then(if (hidden) Modifier.size(126.dp, 36.dp) else Modifier)
                        .draggable(
                            state = dragState,
                            orientation = Orientation.Vertical,
                            enabled = !hidden,
                            onDragStopped = { velocity ->
                                val threshold = with(density) { 24.dp.toPx() }
                                if (drag.value < -threshold || velocity < -800f) {
                                    when (state.view) {
                                        IslandView.Notice -> state.dismiss()
                                        IslandView.Expanded -> state.collapse()
                                        else -> Unit
                                    }
                                }
                                drag.animateTo(0f, tween(200))
                            },
                        )
                        .padding(top = if (view == IslandView.Notice) clearance else 0.dp)
                },
                contentAlignment = Alignment.TopCenter,
            ) {
                CompositionLocalProvider(
                    LocalColors provides DarkColors,
                    LocalContentColor provides foreground,
                    LocalContentStyle provides Typography.sm.copy(color = foreground),
                    LocalIconSize provides 20.dp,
                    LocalIslandForeground provides foreground,
                ) {
                    IslandCompactView(state, compactLeading, compactTrailing, hole, reduced)
                    if (minimal != null) IslandMinimalView(state, minimal, reduced)
                    IslandExpandedView(state, clearance, expanded, reduced)
                    IslandNoticeView(state, reduced)
                }
            }
            if (present && reach) {
                Box(
                    modifier = Modifier
                        .clickable(
                            interactionSource = remember { MutableInteractionSource() },
                            indication = null,
                            role = Role.Button,
                            onClickLabel = "Expand",
                            onClick = state::expand,
                        )
                        .semantics { contentDescription = "Expand" },
                )
            }
        }
    }
}

@Composable
private fun IslandReach(modifier: Modifier, content: @Composable () -> Unit) {
    Layout(content = content, modifier = modifier) { measurables, constraints ->
        val pill = measurables[0].measure(constraints.copy(minWidth = 0, minHeight = 0))
        val reach = measurables.getOrNull(1)?.measure(Constraints.fixed(pill.width, 28.dp.roundToPx()))
        layout(pill.width, pill.height + (reach?.height ?: 0)) {
            pill.place(0, 0)
            reach?.place(0, pill.height)
        }
    }
}

private val LocalIslandForeground = staticCompositionLocalOf { Color.Unspecified }

@Composable
private fun islandPartEnter(reduced: Boolean): EnterTransition =
    if (reduced) EnterTransition.None else fadeIn(tween(450, 100, FormEasing)) + scaleIn(tween(450, 100, FormEasing), initialScale = 0.9f)

@Composable
private fun islandPartExit(reduced: Boolean): ExitTransition =
    if (reduced) ExitTransition.None else fadeOut(tween(150, easing = FormEasing)) + scaleOut(tween(150, easing = FormEasing), targetScale = 0.9f)

@Composable
private fun IslandNoticeView(state: IslandState, reduced: Boolean) {
    val foreground = LocalIslandForeground.current
    var shown by remember { mutableStateOf(state.notice) }
    if (state.notice != null) shown = state.notice
    AnimatedVisibility(
        visible = state.view == IslandView.Notice,
        enter = islandPartEnter(reduced),
        exit = islandPartExit(reduced),
    ) {
        val notice = shown ?: return@AnimatedVisibility
        Row(
            modifier = Modifier
                .width(islandWideWidth())
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    role = Role.Button,
                    onClick = state::dismiss,
                )
                .semantics(mergeDescendants = true) {
                    liveRegion = LiveRegionMode.Polite
                    dismiss {
                        state.dismiss()
                        true
                    }
                }
                .padding(14.dp),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (notice.icon != null) {
                Box(
                    modifier = Modifier
                        .size(40.dp)
                        .background(
                            foreground.copy(alpha = 0.15f),
                            RoundedCornerShape(12.dp),
                        ),
                    contentAlignment = Alignment.Center,
                ) {
                    CompositionLocalProvider(LocalIconSize provides 24.dp) {
                        notice.icon.invoke()
                    }
                }
            }
            Column(modifier = Modifier.weight(1f)) {
                BasicText(
                    notice.title,
                    style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold),
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                if (notice.description != null) {
                    BasicText(
                        notice.description,
                        style = Typography.sm.copy(
                            color = foreground.copy(alpha = 0.7f),
                        ),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                    )
                }
            }
        }
    }
}

@Composable
private fun IslandCompactView(
    state: IslandState,
    leading: (@Composable RowScope.() -> Unit)?,
    trailing: (@Composable RowScope.() -> Unit)?,
    hole: Dp?,
    reduced: Boolean,
) {
    AnimatedVisibility(
        visible = state.view == IslandView.Compact,
        enter = islandPartEnter(reduced),
        exit = islandPartExit(reduced),
    ) {
        Layout(
            content = {
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
                    leading?.invoke(this)
                }
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
                    trailing?.invoke(this)
                }
            },
            modifier = Modifier
                .height(36.dp)
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    role = Role.Button,
                    onClick = state::expand,
                )
                .semantics(mergeDescendants = true) {
                    stateDescription = "Collapsed"
                    expand {
                        state.expand()
                        true
                    }
                }
                .padding(horizontal = 10.dp),
        ) { measurables, constraints ->
            val loose = constraints.copy(minWidth = 0, minHeight = 0)
            val start = measurables[0].measure(loose)
            val end = measurables[1].measure(loose)
            val split = hole != null || (leading != null && trailing != null)
            val gap = (if (hole != null) hole + 16.dp else 24.dp).roundToPx()
            val minimum = (if (hole != null) maxOf(144.dp, hole + 112.dp) else 144.dp).roundToPx() - 20.dp.roundToPx()
            val side = maxOf(start.width, end.width)
            val width = (if (split) maxOf(minimum, side * 2 + gap) else maxOf(minimum, side))
                .coerceIn(constraints.minWidth, constraints.maxWidth)
            val height = maxOf(constraints.minHeight, start.height, end.height)
            layout(width, height) {
                if (split) {
                    start.placeRelative(0, (height - start.height) / 2)
                    end.placeRelative(width - end.width, (height - end.height) / 2)
                } else {
                    val only = if (leading != null) start else end
                    only.placeRelative((width - only.width) / 2, (height - only.height) / 2)
                }
            }
        }
    }
}

@Composable
private fun IslandMinimalView(state: IslandState, content: @Composable () -> Unit, reduced: Boolean) {
    AnimatedVisibility(
        visible = state.view == IslandView.Minimal,
        enter = islandPartEnter(reduced),
        exit = islandPartExit(reduced),
    ) {
        Box(
            modifier = Modifier
                .size(36.dp)
                .clickable(
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null,
                    role = Role.Button,
                    onClick = state::expand,
                )
                .semantics(mergeDescendants = true) {
                    stateDescription = "Minimized"
                    expand {
                        state.expand()
                        true
                    }
                },
            contentAlignment = Alignment.Center,
        ) {
            content()
        }
    }
}

@Stable
class IslandExpandedScope internal constructor() {
    @Composable
    fun IslandExpandedRegion(
        region: IslandRegion,
        modifier: Modifier = Modifier,
        content: @Composable ColumnScope.() -> Unit,
    ) {
        Column(modifier = Modifier.layoutId(region).then(modifier), content = content)
    }
}

private val IslandExpandedScopeInstance = IslandExpandedScope()

@Composable
private fun IslandExpandedView(
    state: IslandState,
    clearance: Dp,
    content: @Composable IslandExpandedScope.() -> Unit,
    reduced: Boolean,
) {
    AnimatedVisibility(
        visible = state.view == IslandView.Expanded,
        enter = islandPartEnter(reduced),
        exit = islandPartExit(reduced),
    ) {
        Layout(
            content = { IslandExpandedScopeInstance.content() },
            modifier = Modifier
                .width(islandWideWidth())
                .semantics {
                    stateDescription = "Expanded"
                    collapse {
                        state.collapse()
                        true
                    }
                    customActions = listOfNotNull(
                        CustomAccessibilityAction("Collapse") {
                            state.collapse()
                            true
                        },
                        if (state.hasMinimal) {
                            CustomAccessibilityAction("Minimize") {
                                state.minimize()
                                true
                            }
                        } else {
                            null
                        },
                    )
                }
                .padding(16.dp),
        ) { measurables, constraints ->
            val width = constraints.maxWidth
            val gap = 12.dp.roundToPx()
            fun region(region: IslandRegion) = measurables.firstOrNull { it.layoutId == region }
            val leading = region(IslandRegion.Leading)?.measure(Constraints(maxWidth = width))
            val trailing = region(IslandRegion.Trailing)?.measure(
                Constraints(maxWidth = (width - (leading?.let { it.width + gap } ?: 0)).coerceAtLeast(0)),
            )
            val startX = leading?.let { it.width + gap } ?: 0
            val endX = width - (trailing?.let { it.width + gap } ?: 0)
            val center = region(IslandRegion.Center)?.measure(Constraints.fixedWidth((endX - startX).coerceAtLeast(0)))
            val bottom = region(IslandRegion.Bottom)?.measure(Constraints.fixedWidth(width))
            val drop = clearance.roundToPx()
            val band = maxOf(leading?.height ?: 0, trailing?.height ?: 0)
            val centerHeight = center?.height ?: 0
            val row = if (drop > 0 && center != null) maxOf(band, drop + centerHeight) else maxOf(band, centerHeight)
            val bottomY = if (row > 0 && bottom != null) row + gap else row
            val height = (bottomY + (bottom?.height ?: 0)).coerceAtLeast(constraints.minHeight)
            layout(width, height) {
                leading?.placeRelative(0, if (drop > 0) 0 else (row - leading.height) / 2)
                trailing?.placeRelative(width - trailing.width, if (drop > 0) 0 else (row - trailing.height) / 2)
                center?.placeRelative(startX, if (drop > 0) drop else (row - centerHeight) / 2)
                bottom?.placeRelative(0, bottomY)
            }
        }
    }
}

@Composable
fun IslandRing(
    value: Float,
    modifier: Modifier = Modifier,
    color: Color = EsuissTheme.colors.primary,
) {
    val progress = value.coerceIn(0f, 1f)
    Canvas(modifier = modifier.size(20.dp)) {
        val stroke = 2.5f * size.minDimension / 20f
        val radius = 8f * size.minDimension / 20f
        val topLeft = center - Offset(radius, radius)
        val arc = Size(radius * 2, radius * 2)
        drawCircle(color.copy(alpha = color.alpha * 0.25f), radius, style = Stroke(stroke))
        drawArc(color, -90f, 360f * progress, false, topLeft, arc, style = Stroke(stroke, cap = StrokeCap.Round))
    }
}
```

- `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/Screen.kt`: see [Screen](https://ui.suiss.app/docs/components/screen.md)

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

## Usage

```tsx
import { IslandProvider, IslandExpandedRegion, Island, IslandRing } from "@/components/interactions/island"
```

```tsx
<IslandProvider>
  <DownloadsExample initial={0.42} />
</IslandProvider>
```

Wrap the app in `IslandProvider` and render one `Island`. Pass `compactLeading`, `compactTrailing` and `minimal` only while there is activity to show, and add `IslandExpandedRegion`s as children with a `region` of `leading`, `trailing`, `center` or `bottom`. Leading, center and trailing form a top row; bottom regions stack below it at full width. If only one of the compact and minimal slots is given, the island uses it for both views.

`useIsland` returns `view`, `notice`, `expand`, `collapse`, `minimize`, `notify` and `dismiss`. A notice is `{ icon?, title, description?, duration? }`; pass a `duration` of `0` or `Infinity` to keep it until dismissed. Dragging the island pauses the notice timer. Use `IslandRing` for circular progress. The `IslandNotice`, `IslandRegion` and `IslandView` types are exported.

## Examples

**React Native, Jetpack Compose**

### Expanded

Starts with the island expanded to show download details.

![Preview](https://ui.suiss.app/previews/interactions-island--expanded.light.webp)

```tsx
import { BellIcon, ChatCircleIcon, CheckCircleIcon, DownloadSimpleIcon, FileZipIcon } from "phosphor-react-native"
import * as React from "react"
import { Pressable, View } from "react-native"
import { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland } from "@/components/interactions/island"
import { Button } from "@/components/ui/button"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

function NotifyButtons({ children }: { children?: React.ReactNode }) {
  const { notify } = useIsland()

  return (
    <View className="flex-row flex-wrap justify-center gap-3">
      {children}
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon
                as={ChatCircleIcon}
                weight="fill"
                className="text-green-500"
              />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        <Text>New message</Text>
      </Button>
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon as={BellIcon} weight="fill" className="text-orange-500" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        <Text>Reminder</Text>
      </Button>
    </View>
  )
}

function useDownload(initial: number | null = null) {
  const [progress, setProgress] = React.useState<number | null>(initial)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (initial !== null || progress === null || progress >= 1) return
    const timer = setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => clearTimeout(timer)
  }, [initial, progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadIsland({
  progress,
  onCancel,
}: {
  progress: number | null
  onCancel: () => void
}) {
  if (progress === null) return <Island />

  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <Island
      accessibilityLabel={`Downloading Design-Kit.zip, ${percent}%`}
      compactLeading={
        <Icon as={DownloadSimpleIcon} weight="bold" className="text-primary" />
      }
      compactTrailing={
        done ? (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ) : (
          <IslandRing value={progress} />
        )
      }
      minimal={<IslandRing value={progress} />}
    >
      <IslandExpandedRegion region="leading">
        <View className="size-10 items-center justify-center rounded-xl bg-white/15">
          <Icon
            as={FileZipIcon}
            weight="fill"
            className="size-6 text-primary"
          />
        </View>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="trailing">
        <Text className="text-2xl font-semibold">{percent}%</Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="center">
        <Text numberOfLines={1} className="text-sm font-semibold">
          {done ? "Downloaded" : "Downloading"}
        </Text>
        <Text numberOfLines={1} className="text-sm text-white/70">
          Design-Kit.zip
        </Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="bottom">
        <View
          role="progressbar"
          accessibilityLabel="Download progress"
          accessibilityValue={{ min: 0, max: 100, now: percent }}
          className="h-1.5 overflow-hidden rounded-full bg-white/20"
        >
          <View
            className="h-full rounded-full bg-primary"
            style={{ width: `${percent}%` }}
          />
        </View>
        <Pressable
          role="button"
          disabled={done}
          onPress={onCancel}
          className="h-11 items-center justify-center rounded-full bg-white/15 active:opacity-80 disabled:opacity-50"
        >
          <Text className="text-sm font-semibold">Cancel download</Text>
        </Pressable>
      </IslandExpandedRegion>
    </Island>
  )
}

function DownloadsExample({
  initial = null,
  view = "compact",
  withNotifications = false,
}: {
  initial?: number | null
  view?: "compact" | "expanded" | "minimal"
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload(initial)
  const { expand, minimize } = useIsland()

  React.useEffect(() => {
    if (view === "expanded") expand()
    else if (view === "minimal") minimize()
  }, [view, expand, minimize])

  return (
    <View className="flex-1 items-center justify-center gap-4">
      <DownloadIsland progress={progress} onCancel={cancel} />
      <Text className="max-w-xs text-center text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details. Swipe
        up on it to close.
      </Text>
      {initial === null ? (
        <Button onPress={start} disabled={progress !== null}>
          <Text>
            {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
          </Text>
        </Button>
      ) : null}
      {withNotifications ? (
        <NotifyButtons>
          <Button
            variant="secondary"
            disabled={progress === null}
            onPress={minimize}
          >
            <Text>Minimize</Text>
          </Button>
        </NotifyButtons>
      ) : null}
    </View>
  )
}

export function IslandExpandedExample() {
  return (
    <IslandProvider>
      <DownloadsExample initial={0.42} view="expanded" />
    </IslandProvider>
  )
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.bold.DownloadSimple
import com.adamglin.phosphoricons.fill.Bell
import com.adamglin.phosphoricons.fill.ChatCircle
import com.adamglin.phosphoricons.fill.CheckCircle
import com.esuiss.ui.components.Button
import com.esuiss.ui.components.ButtonVariant
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.Island
import com.esuiss.ui.interactions.IslandProvider
import com.esuiss.ui.interactions.IslandRegion
import com.esuiss.ui.interactions.IslandRing
import com.esuiss.ui.interactions.useIsland
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay
import kotlin.math.roundToInt

@Composable
fun IslandExpandedExample() {
    IslandProvider { IslandDownloads(initial = 0.42f, start = IslandStart.Expanded) }
}

enum class IslandStart { Compact, Expanded, Minimal }

@Composable
fun IslandNotifyButtons(extra: @Composable () -> Unit = {}) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Button(
            "New message",
            onClick = {
                island.notify(
                    title = "Jordan Lee",
                    description = "Are we still on for Saturday?",
                    icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        Button(
            "Reminder",
            onClick = {
                island.notify(
                    title = "Design review",
                    description = "Starts in 10 minutes",
                    icon = { Icon(PhosphorIcons.Fill.Bell, contentDescription = null, tint = Palette.orange500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        extra()
    }
}

@Composable
fun IslandProgress(progress: Float) {
    val colors = EsuissTheme.colors
    if (progress >= 1f) {
        Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500)
    } else {
        IslandRing(progress)
    }
}

@Composable
fun IslandDownloadIsland(progress: Float?, onCancel: () -> Unit) {
    val colors = EsuissTheme.colors
    val current = progress ?: 0f
    val done = current >= 1f
    val percent = (current * 100).roundToInt()
    Island(
        compactLeading = progress?.let {
            { Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, tint = colors.primary) }
        },
        compactTrailing = progress?.let { value -> { IslandProgress(value) } },
        minimal = progress?.let { value -> { IslandProgress(value) } },
        modifier = Modifier.semantics { contentDescription = "Downloading Design-Kit.zip, $percent%" },
    ) {
        IslandExpandedRegion(IslandRegion.Leading) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(foreground.copy(alpha = 0.15f), RoundedCornerShape(Radius.xl)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, size = 24.dp, tint = colors.primary)
            }
        }
        IslandExpandedRegion(IslandRegion.Trailing) {
            Text("$percent%", style = Typography.xl2.copy(color = LocalContentColor.current, fontWeight = FontWeight.SemiBold))
        }
        IslandExpandedRegion(IslandRegion.Center) {
            val foreground = LocalContentColor.current
            Text(
                if (done) "Downloaded" else "Downloading",
                style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            Text(
                if (done) "Design-Kit.zip" else "Design-Kit.zip · ${(current * IslandSize).roundToInt()} of $IslandSize MB",
                style = Typography.sm.copy(color = foreground.copy(alpha = 0.7f)),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
        IslandExpandedRegion(IslandRegion.Bottom) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(CircleShape)
                    .background(foreground.copy(alpha = 0.2f))
                    .semantics {
                        contentDescription = "Download progress"
                        progressBarRangeInfo = ProgressBarRangeInfo(percent.toFloat(), 0f..100f)
                    },
            ) {
                Box(
                    Modifier
                        .fillMaxWidth(current.coerceIn(0f, 1f))
                        .fillMaxHeight()
                        .background(colors.primary, CircleShape),
                )
            }
            Spacer(Modifier.height(12.dp))
            val interaction = remember { MutableInteractionSource() }
            val pressed by interaction.collectIsPressedAsState()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(44.dp)
                    .alpha(if (done) 0.5f else 1f)
                    .clip(CircleShape)
                    .alpha(if (pressed) 0.8f else 1f)
                    .background(foreground.copy(alpha = 0.15f))
                    .clickable(interactionSource = interaction, indication = null, enabled = !done, role = Role.Button, onClick = onCancel),
                contentAlignment = Alignment.Center,
            ) {
                Text("Cancel download", style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold))
            }
        }
    }
}

@Composable
fun IslandDownloads(initial: Float? = null, start: IslandStart = IslandStart.Compact, withNotifications: Boolean = false) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    var progress by rememberSaveable { mutableStateOf(initial) }
    LaunchedEffect(progress) {
        val current = progress ?: return@LaunchedEffect
        if (initial != null) return@LaunchedEffect
        if (current < 1f) {
            delay(150)
            progress = minOf(current + 0.01f, 1f)
        } else {
            delay(1200)
            progress = null
            island.notify(
                title = "Download complete",
                description = "Design-Kit.zip",
                icon = { Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500) },
            )
        }
    }
    LaunchedEffect(start) {
        when (start) {
            IslandStart.Expanded -> island.expand()
            IslandStart.Minimal -> island.minimize()
            IslandStart.Compact -> Unit
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        IslandDownloadIsland(progress) { progress = null }
        Text(
            "Start a download, then tap the pill at the top to see the details. Swipe up on it to close.",
            modifier = Modifier.widthIn(max = 320.dp),
            style = Typography.sm.copy(color = colors.mutedForeground),
            textAlign = TextAlign.Center,
        )
        if (initial == null) {
            Button(
                if (progress == null) "Download Design-Kit.zip" else "Downloading…",
                onClick = { progress = 0f },
                enabled = progress == null,
            )
        }
        if (withNotifications) {
            IslandNotifyButtons {
                Button(
                    "Minimize",
                    onClick = island::minimize,
                    variant = ButtonVariant.Secondary,
                    enabled = progress != null,
                )
            }
        }
    }
}
```

**React Native, Jetpack Compose**

### Minimal

Starts in the minimal view with only the progress ring.

![Preview](https://ui.suiss.app/previews/interactions-island--minimal.light.webp)

```tsx
import { BellIcon, ChatCircleIcon, CheckCircleIcon, DownloadSimpleIcon, FileZipIcon } from "phosphor-react-native"
import * as React from "react"
import { Pressable, View } from "react-native"
import { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland } from "@/components/interactions/island"
import { Button } from "@/components/ui/button"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

function NotifyButtons({ children }: { children?: React.ReactNode }) {
  const { notify } = useIsland()

  return (
    <View className="flex-row flex-wrap justify-center gap-3">
      {children}
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon
                as={ChatCircleIcon}
                weight="fill"
                className="text-green-500"
              />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        <Text>New message</Text>
      </Button>
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon as={BellIcon} weight="fill" className="text-orange-500" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        <Text>Reminder</Text>
      </Button>
    </View>
  )
}

function useDownload(initial: number | null = null) {
  const [progress, setProgress] = React.useState<number | null>(initial)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (initial !== null || progress === null || progress >= 1) return
    const timer = setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => clearTimeout(timer)
  }, [initial, progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadIsland({
  progress,
  onCancel,
}: {
  progress: number | null
  onCancel: () => void
}) {
  if (progress === null) return <Island />

  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <Island
      accessibilityLabel={`Downloading Design-Kit.zip, ${percent}%`}
      compactLeading={
        <Icon as={DownloadSimpleIcon} weight="bold" className="text-primary" />
      }
      compactTrailing={
        done ? (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ) : (
          <IslandRing value={progress} />
        )
      }
      minimal={<IslandRing value={progress} />}
    >
      <IslandExpandedRegion region="leading">
        <View className="size-10 items-center justify-center rounded-xl bg-white/15">
          <Icon
            as={FileZipIcon}
            weight="fill"
            className="size-6 text-primary"
          />
        </View>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="trailing">
        <Text className="text-2xl font-semibold">{percent}%</Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="center">
        <Text numberOfLines={1} className="text-sm font-semibold">
          {done ? "Downloaded" : "Downloading"}
        </Text>
        <Text numberOfLines={1} className="text-sm text-white/70">
          Design-Kit.zip
        </Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="bottom">
        <View
          role="progressbar"
          accessibilityLabel="Download progress"
          accessibilityValue={{ min: 0, max: 100, now: percent }}
          className="h-1.5 overflow-hidden rounded-full bg-white/20"
        >
          <View
            className="h-full rounded-full bg-primary"
            style={{ width: `${percent}%` }}
          />
        </View>
        <Pressable
          role="button"
          disabled={done}
          onPress={onCancel}
          className="h-11 items-center justify-center rounded-full bg-white/15 active:opacity-80 disabled:opacity-50"
        >
          <Text className="text-sm font-semibold">Cancel download</Text>
        </Pressable>
      </IslandExpandedRegion>
    </Island>
  )
}

function DownloadsExample({
  initial = null,
  view = "compact",
  withNotifications = false,
}: {
  initial?: number | null
  view?: "compact" | "expanded" | "minimal"
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload(initial)
  const { expand, minimize } = useIsland()

  React.useEffect(() => {
    if (view === "expanded") expand()
    else if (view === "minimal") minimize()
  }, [view, expand, minimize])

  return (
    <View className="flex-1 items-center justify-center gap-4">
      <DownloadIsland progress={progress} onCancel={cancel} />
      <Text className="max-w-xs text-center text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details. Swipe
        up on it to close.
      </Text>
      {initial === null ? (
        <Button onPress={start} disabled={progress !== null}>
          <Text>
            {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
          </Text>
        </Button>
      ) : null}
      {withNotifications ? (
        <NotifyButtons>
          <Button
            variant="secondary"
            disabled={progress === null}
            onPress={minimize}
          >
            <Text>Minimize</Text>
          </Button>
        </NotifyButtons>
      ) : null}
    </View>
  )
}

export function IslandMinimalExample() {
  return (
    <IslandProvider>
      <DownloadsExample initial={0.42} view="minimal" />
    </IslandProvider>
  )
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.bold.DownloadSimple
import com.adamglin.phosphoricons.fill.Bell
import com.adamglin.phosphoricons.fill.ChatCircle
import com.adamglin.phosphoricons.fill.CheckCircle
import com.esuiss.ui.components.Button
import com.esuiss.ui.components.ButtonVariant
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.Island
import com.esuiss.ui.interactions.IslandProvider
import com.esuiss.ui.interactions.IslandRegion
import com.esuiss.ui.interactions.IslandRing
import com.esuiss.ui.interactions.useIsland
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay
import kotlin.math.roundToInt

@Composable
fun IslandMinimalExample() {
    IslandProvider { IslandDownloads(initial = 0.42f, start = IslandStart.Minimal) }
}

enum class IslandStart { Compact, Expanded, Minimal }

@Composable
fun IslandNotifyButtons(extra: @Composable () -> Unit = {}) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Button(
            "New message",
            onClick = {
                island.notify(
                    title = "Jordan Lee",
                    description = "Are we still on for Saturday?",
                    icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        Button(
            "Reminder",
            onClick = {
                island.notify(
                    title = "Design review",
                    description = "Starts in 10 minutes",
                    icon = { Icon(PhosphorIcons.Fill.Bell, contentDescription = null, tint = Palette.orange500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        extra()
    }
}

@Composable
fun IslandProgress(progress: Float) {
    val colors = EsuissTheme.colors
    if (progress >= 1f) {
        Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500)
    } else {
        IslandRing(progress)
    }
}

@Composable
fun IslandDownloadIsland(progress: Float?, onCancel: () -> Unit) {
    val colors = EsuissTheme.colors
    val current = progress ?: 0f
    val done = current >= 1f
    val percent = (current * 100).roundToInt()
    Island(
        compactLeading = progress?.let {
            { Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, tint = colors.primary) }
        },
        compactTrailing = progress?.let { value -> { IslandProgress(value) } },
        minimal = progress?.let { value -> { IslandProgress(value) } },
        modifier = Modifier.semantics { contentDescription = "Downloading Design-Kit.zip, $percent%" },
    ) {
        IslandExpandedRegion(IslandRegion.Leading) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(foreground.copy(alpha = 0.15f), RoundedCornerShape(Radius.xl)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, size = 24.dp, tint = colors.primary)
            }
        }
        IslandExpandedRegion(IslandRegion.Trailing) {
            Text("$percent%", style = Typography.xl2.copy(color = LocalContentColor.current, fontWeight = FontWeight.SemiBold))
        }
        IslandExpandedRegion(IslandRegion.Center) {
            val foreground = LocalContentColor.current
            Text(
                if (done) "Downloaded" else "Downloading",
                style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            Text(
                if (done) "Design-Kit.zip" else "Design-Kit.zip · ${(current * IslandSize).roundToInt()} of $IslandSize MB",
                style = Typography.sm.copy(color = foreground.copy(alpha = 0.7f)),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
        IslandExpandedRegion(IslandRegion.Bottom) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(CircleShape)
                    .background(foreground.copy(alpha = 0.2f))
                    .semantics {
                        contentDescription = "Download progress"
                        progressBarRangeInfo = ProgressBarRangeInfo(percent.toFloat(), 0f..100f)
                    },
            ) {
                Box(
                    Modifier
                        .fillMaxWidth(current.coerceIn(0f, 1f))
                        .fillMaxHeight()
                        .background(colors.primary, CircleShape),
                )
            }
            Spacer(Modifier.height(12.dp))
            val interaction = remember { MutableInteractionSource() }
            val pressed by interaction.collectIsPressedAsState()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(44.dp)
                    .alpha(if (done) 0.5f else 1f)
                    .clip(CircleShape)
                    .alpha(if (pressed) 0.8f else 1f)
                    .background(foreground.copy(alpha = 0.15f))
                    .clickable(interactionSource = interaction, indication = null, enabled = !done, role = Role.Button, onClick = onCancel),
                contentAlignment = Alignment.Center,
            ) {
                Text("Cancel download", style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold))
            }
        }
    }
}

@Composable
fun IslandDownloads(initial: Float? = null, start: IslandStart = IslandStart.Compact, withNotifications: Boolean = false) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    var progress by rememberSaveable { mutableStateOf(initial) }
    LaunchedEffect(progress) {
        val current = progress ?: return@LaunchedEffect
        if (initial != null) return@LaunchedEffect
        if (current < 1f) {
            delay(150)
            progress = minOf(current + 0.01f, 1f)
        } else {
            delay(1200)
            progress = null
            island.notify(
                title = "Download complete",
                description = "Design-Kit.zip",
                icon = { Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500) },
            )
        }
    }
    LaunchedEffect(start) {
        when (start) {
            IslandStart.Expanded -> island.expand()
            IslandStart.Minimal -> island.minimize()
            IslandStart.Compact -> Unit
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        IslandDownloadIsland(progress) { progress = null }
        Text(
            "Start a download, then tap the pill at the top to see the details. Swipe up on it to close.",
            modifier = Modifier.widthIn(max = 320.dp),
            style = Typography.sm.copy(color = colors.mutedForeground),
            textAlign = TextAlign.Center,
        )
        if (initial == null) {
            Button(
                if (progress == null) "Download Design-Kit.zip" else "Downloading…",
                onClick = { progress = 0f },
                enabled = progress == null,
            )
        }
        if (withNotifications) {
            IslandNotifyButtons {
                Button(
                    "Minimize",
                    onClick = island::minimize,
                    variant = ButtonVariant.Secondary,
                    enabled = progress != null,
                )
            }
        }
    }
}
```

**React Native, Jetpack Compose**

### Notice

Shows a notice on mount.

![Preview](https://ui.suiss.app/previews/interactions-island--notice.light.webp)

```tsx
import { BellIcon, ChatCircleIcon } from "phosphor-react-native"
import * as React from "react"
import { View } from "react-native"
import { Island, IslandProvider, useIsland } from "@/components/interactions/island"
import { Button } from "@/components/ui/button"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

function NotifyButtons({ children }: { children?: React.ReactNode }) {
  const { notify } = useIsland()

  return (
    <View className="flex-row flex-wrap justify-center gap-3">
      {children}
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon
                as={ChatCircleIcon}
                weight="fill"
                className="text-green-500"
              />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        <Text>New message</Text>
      </Button>
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon as={BellIcon} weight="fill" className="text-orange-500" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        <Text>Reminder</Text>
      </Button>
    </View>
  )
}

function NoticeOnMount() {
  const { notify } = useIsland()
  const shownRef = React.useRef(false)

  React.useEffect(() => {
    if (shownRef.current) return
    shownRef.current = true
    notify({
      icon: (
        <Icon as={ChatCircleIcon} weight="fill" className="text-green-500" />
      ),
      title: "Jordan Lee",
      description: "Are we still on for Saturday?",
      duration: 600000,
    })
  }, [notify])

  return (
    <View className="flex-1 items-center justify-center gap-4">
      <Island />
      <Text className="max-w-xs text-center text-sm text-muted-foreground">
        The pill grows to show the notification and shrinks back on its own.
      </Text>
      <NotifyButtons />
    </View>
  )
}

export function IslandNoticeExample() {
  return (
    <IslandProvider>
      <NoticeOnMount />
    </IslandProvider>
  )
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.fill.Bell
import com.adamglin.phosphoricons.fill.ChatCircle
import com.esuiss.ui.components.Button
import com.esuiss.ui.components.ButtonVariant
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.Island
import com.esuiss.ui.interactions.IslandProvider
import com.esuiss.ui.interactions.useIsland
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Typography

@Composable
fun IslandNoticeExample() {
    IslandProvider { IslandNoticeOnMount() }
}

@Composable
fun IslandNotifyButtons(extra: @Composable () -> Unit = {}) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Button(
            "New message",
            onClick = {
                island.notify(
                    title = "Jordan Lee",
                    description = "Are we still on for Saturday?",
                    icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        Button(
            "Reminder",
            onClick = {
                island.notify(
                    title = "Design review",
                    description = "Starts in 10 minutes",
                    icon = { Icon(PhosphorIcons.Fill.Bell, contentDescription = null, tint = Palette.orange500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        extra()
    }
}

@Composable
fun IslandNoticeOnMount() {
    val island = useIsland()
    val colors = EsuissTheme.colors
    var shown by rememberSaveable { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        if (shown) return@LaunchedEffect
        shown = true
        island.notify(
            title = "Jordan Lee",
            description = "Are we still on for Saturday?",
            duration = 600000L,
            icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
        )
    }
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        Island()
        Text(
            "The pill grows to show the notification and shrinks back on its own.",
            modifier = Modifier.widthIn(max = 320.dp),
            style = Typography.sm.copy(color = colors.mutedForeground),
            textAlign = TextAlign.Center,
        )
        IslandNotifyButtons()
    }
}
```

### Live activity

A download that starts on press, with buttons that minimize the island and send notices over it.

![Preview](https://ui.suiss.app/previews/interactions-island--live-activity.light.webp)

```tsx
import { BellIcon, ChatCircleIcon, CheckCircleIcon, DownloadSimpleIcon, FileZipIcon } from "phosphor-react-native"
import * as React from "react"
import { Pressable, View } from "react-native"
import { Island, IslandExpandedRegion, IslandProvider, IslandRing, useIsland } from "@/components/interactions/island"
import { Button } from "@/components/ui/button"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

function NotifyButtons({ children }: { children?: React.ReactNode }) {
  const { notify } = useIsland()

  return (
    <View className="flex-row flex-wrap justify-center gap-3">
      {children}
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon
                as={ChatCircleIcon}
                weight="fill"
                className="text-green-500"
              />
            ),
            title: "Jordan Lee",
            description: "Are we still on for Saturday?",
          })
        }
      >
        <Text>New message</Text>
      </Button>
      <Button
        variant="secondary"
        onPress={() =>
          notify({
            icon: (
              <Icon as={BellIcon} weight="fill" className="text-orange-500" />
            ),
            title: "Design review",
            description: "Starts in 10 minutes",
          })
        }
      >
        <Text>Reminder</Text>
      </Button>
    </View>
  )
}

function useDownload(initial: number | null = null) {
  const [progress, setProgress] = React.useState<number | null>(initial)
  const { notify } = useIsland()

  React.useEffect(() => {
    if (initial !== null || progress === null || progress >= 1) return
    const timer = setTimeout(
      () => setProgress((value) => Math.min((value ?? 0) + 0.01, 1)),
      150
    )
    return () => clearTimeout(timer)
  }, [initial, progress])

  React.useEffect(() => {
    if (progress !== 1) return
    const timer = setTimeout(() => {
      setProgress(null)
      notify({
        icon: (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ),
        title: "Download complete",
        description: "Design-Kit.zip",
      })
    }, 1200)
    return () => clearTimeout(timer)
  }, [progress, notify])

  return {
    progress,
    start: () => setProgress(0),
    cancel: () => setProgress(null),
  }
}

function DownloadIsland({
  progress,
  onCancel,
}: {
  progress: number | null
  onCancel: () => void
}) {
  if (progress === null) return <Island />

  const done = progress >= 1
  const percent = Math.round(progress * 100)

  return (
    <Island
      accessibilityLabel={`Downloading Design-Kit.zip, ${percent}%`}
      compactLeading={
        <Icon as={DownloadSimpleIcon} weight="bold" className="text-primary" />
      }
      compactTrailing={
        done ? (
          <Icon as={CheckCircleIcon} weight="fill" className="text-green-500" />
        ) : (
          <IslandRing value={progress} />
        )
      }
      minimal={<IslandRing value={progress} />}
    >
      <IslandExpandedRegion region="leading">
        <View className="size-10 items-center justify-center rounded-xl bg-white/15">
          <Icon
            as={FileZipIcon}
            weight="fill"
            className="size-6 text-primary"
          />
        </View>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="trailing">
        <Text className="text-2xl font-semibold">{percent}%</Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="center">
        <Text numberOfLines={1} className="text-sm font-semibold">
          {done ? "Downloaded" : "Downloading"}
        </Text>
        <Text numberOfLines={1} className="text-sm text-white/70">
          Design-Kit.zip
        </Text>
      </IslandExpandedRegion>
      <IslandExpandedRegion region="bottom">
        <View
          role="progressbar"
          accessibilityLabel="Download progress"
          accessibilityValue={{ min: 0, max: 100, now: percent }}
          className="h-1.5 overflow-hidden rounded-full bg-white/20"
        >
          <View
            className="h-full rounded-full bg-primary"
            style={{ width: `${percent}%` }}
          />
        </View>
        <Pressable
          role="button"
          disabled={done}
          onPress={onCancel}
          className="h-11 items-center justify-center rounded-full bg-white/15 active:opacity-80 disabled:opacity-50"
        >
          <Text className="text-sm font-semibold">Cancel download</Text>
        </Pressable>
      </IslandExpandedRegion>
    </Island>
  )
}

function DownloadsExample({
  initial = null,
  view = "compact",
  withNotifications = false,
}: {
  initial?: number | null
  view?: "compact" | "expanded" | "minimal"
  withNotifications?: boolean
}) {
  const { progress, start, cancel } = useDownload(initial)
  const { expand, minimize } = useIsland()

  React.useEffect(() => {
    if (view === "expanded") expand()
    else if (view === "minimal") minimize()
  }, [view, expand, minimize])

  return (
    <View className="flex-1 items-center justify-center gap-4">
      <DownloadIsland progress={progress} onCancel={cancel} />
      <Text className="max-w-xs text-center text-sm text-muted-foreground">
        Start a download, then tap the pill at the top to see the details. Swipe
        up on it to close.
      </Text>
      {initial === null ? (
        <Button onPress={start} disabled={progress !== null}>
          <Text>
            {progress === null ? "Download Design-Kit.zip" : "Downloading…"}
          </Text>
        </Button>
      ) : null}
      {withNotifications ? (
        <NotifyButtons>
          <Button
            variant="secondary"
            disabled={progress === null}
            onPress={minimize}
          >
            <Text>Minimize</Text>
          </Button>
        </NotifyButtons>
      ) : null}
    </View>
  )
}

export function IslandLiveActivityExample() {
  return (
    <IslandProvider>
      <DownloadsExample withNotifications />
    </IslandProvider>
  )
}
```

```swift
import ActivityKit
import EsuissUI
import SwiftUI

struct IslandLiveActivity: View {
  @State private var activity: Activity<DownloadActivityAttributes>?
  @State private var state = DownloadActivityAttributes.ContentState(progress: 0, fileName: "Design-Kit.zip", finished: false)
  @State private var failure: String?

  var body: some View {
    VStack(alignment: .leading, spacing: 16) {
      Text("Start a download, then leave the app. The activity shows in the Dynamic Island and on the Lock Screen.")
        .textStyle(.sm)
        .foregroundStyle(EsuissColor.mutedForeground)
      FlowRow(spacing: 12) {
        Button("Start") { start() }
          .buttonStyle(.variant())
          .disabled(activity != nil)
        Button("Update (+10%)") { advance() }
          .buttonStyle(.variant(.secondary))
          .disabled(activity == nil || state.finished)
        Button("Finish") { finish() }
          .buttonStyle(.variant(.secondary))
          .disabled(activity == nil || state.finished)
        Button("End") { end() }
          .buttonStyle(.variant(.destructive))
          .disabled(activity == nil)
      }
      Text(verbatim: activity == nil ? "No activity" : "\(state.fileName) · \(state.percent)%")
        .textStyle(.sm, weight: .semibold)
        .monospacedDigit()
      if let failure {
        Text(verbatim: failure)
          .textStyle(.sm)
          .foregroundStyle(EsuissColor.destructive)
      }
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .task {
      activity = Activity<DownloadActivityAttributes>.activities.first
      if let current = activity?.content.state { state = current }
    }
  }

  func start() {
    guard ActivityAuthorizationInfo().areActivitiesEnabled else {
      failure = "Live Activities are turned off for this app."
      return
    }
    let next = DownloadActivityAttributes.ContentState(progress: 0, fileName: "Design-Kit.zip", finished: false)
    do {
      activity = try Activity.request(
        attributes: DownloadActivityAttributes(),
        content: ActivityContent(state: next, staleDate: nil)
      )
      state = next
      failure = nil
    } catch {
      failure = error.localizedDescription
    }
  }

  func advance() {
    state.progress = min(state.progress + 0.1, 1)
    state.finished = state.progress >= 1
    push()
  }

  func finish() {
    state.progress = 1
    state.finished = true
    push()
  }

  func push() {
    guard let id = activity?.id else { return }
    let next = state
    Task { await Self.send(next, to: id, ending: false) }
  }

  func end() {
    guard let id = activity?.id else { return }
    let next = state
    activity = nil
    Task { await Self.send(next, to: id, ending: true) }
  }

  private nonisolated static func send(_ state: DownloadActivityAttributes.ContentState, to id: String, ending: Bool) async {
    guard let activity = Activity<DownloadActivityAttributes>.activities.first(where: { $0.id == id }) else { return }
    let content = ActivityContent(state: state, staleDate: nil)
    if ending {
      await activity.end(content, dismissalPolicy: .immediate)
    } else {
      await activity.update(content)
    }
  }
}
```

```kotlin
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.Fill
import com.adamglin.phosphoricons.bold.DownloadSimple
import com.adamglin.phosphoricons.fill.Bell
import com.adamglin.phosphoricons.fill.ChatCircle
import com.adamglin.phosphoricons.fill.CheckCircle
import com.esuiss.ui.components.Button
import com.esuiss.ui.components.ButtonVariant
import com.esuiss.ui.components.Icon
import com.esuiss.ui.components.LocalContentColor
import com.esuiss.ui.components.Text
import com.esuiss.ui.interactions.Island
import com.esuiss.ui.interactions.IslandProvider
import com.esuiss.ui.interactions.IslandRegion
import com.esuiss.ui.interactions.IslandRing
import com.esuiss.ui.interactions.useIsland
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Palette
import com.esuiss.ui.theme.Radius
import com.esuiss.ui.theme.Typography
import kotlinx.coroutines.delay
import kotlin.math.roundToInt

@Composable
fun IslandLiveActivityExample() {
    IslandProvider { IslandDownloads(withNotifications = true) }
}

enum class IslandStart { Compact, Expanded, Minimal }

@Composable
fun IslandNotifyButtons(extra: @Composable () -> Unit = {}) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp),
    ) {
        Button(
            "New message",
            onClick = {
                island.notify(
                    title = "Jordan Lee",
                    description = "Are we still on for Saturday?",
                    icon = { Icon(PhosphorIcons.Fill.ChatCircle, contentDescription = null, tint = Palette.green500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        Button(
            "Reminder",
            onClick = {
                island.notify(
                    title = "Design review",
                    description = "Starts in 10 minutes",
                    icon = { Icon(PhosphorIcons.Fill.Bell, contentDescription = null, tint = Palette.orange500) },
                )
            },
            variant = ButtonVariant.Secondary,
        )
        extra()
    }
}

@Composable
fun IslandProgress(progress: Float) {
    val colors = EsuissTheme.colors
    if (progress >= 1f) {
        Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500)
    } else {
        IslandRing(progress)
    }
}

@Composable
fun IslandDownloadIsland(progress: Float?, onCancel: () -> Unit) {
    val colors = EsuissTheme.colors
    val current = progress ?: 0f
    val done = current >= 1f
    val percent = (current * 100).roundToInt()
    Island(
        compactLeading = progress?.let {
            { Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, tint = colors.primary) }
        },
        compactTrailing = progress?.let { value -> { IslandProgress(value) } },
        minimal = progress?.let { value -> { IslandProgress(value) } },
        modifier = Modifier.semantics { contentDescription = "Downloading Design-Kit.zip, $percent%" },
    ) {
        IslandExpandedRegion(IslandRegion.Leading) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .background(foreground.copy(alpha = 0.15f), RoundedCornerShape(Radius.xl)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(PhosphorIcons.Bold.DownloadSimple, contentDescription = null, size = 24.dp, tint = colors.primary)
            }
        }
        IslandExpandedRegion(IslandRegion.Trailing) {
            Text("$percent%", style = Typography.xl2.copy(color = LocalContentColor.current, fontWeight = FontWeight.SemiBold))
        }
        IslandExpandedRegion(IslandRegion.Center) {
            val foreground = LocalContentColor.current
            Text(
                if (done) "Downloaded" else "Downloading",
                style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
            Text(
                if (done) "Design-Kit.zip" else "Design-Kit.zip · ${(current * IslandSize).roundToInt()} of $IslandSize MB",
                style = Typography.sm.copy(color = foreground.copy(alpha = 0.7f)),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
            )
        }
        IslandExpandedRegion(IslandRegion.Bottom) {
            val foreground = LocalContentColor.current
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(CircleShape)
                    .background(foreground.copy(alpha = 0.2f))
                    .semantics {
                        contentDescription = "Download progress"
                        progressBarRangeInfo = ProgressBarRangeInfo(percent.toFloat(), 0f..100f)
                    },
            ) {
                Box(
                    Modifier
                        .fillMaxWidth(current.coerceIn(0f, 1f))
                        .fillMaxHeight()
                        .background(colors.primary, CircleShape),
                )
            }
            Spacer(Modifier.height(12.dp))
            val interaction = remember { MutableInteractionSource() }
            val pressed by interaction.collectIsPressedAsState()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(44.dp)
                    .alpha(if (done) 0.5f else 1f)
                    .clip(CircleShape)
                    .alpha(if (pressed) 0.8f else 1f)
                    .background(foreground.copy(alpha = 0.15f))
                    .clickable(interactionSource = interaction, indication = null, enabled = !done, role = Role.Button, onClick = onCancel),
                contentAlignment = Alignment.Center,
            ) {
                Text("Cancel download", style = Typography.sm.copy(color = foreground, fontWeight = FontWeight.SemiBold))
            }
        }
    }
}

@Composable
fun IslandDownloads(initial: Float? = null, start: IslandStart = IslandStart.Compact, withNotifications: Boolean = false) {
    val island = useIsland()
    val colors = EsuissTheme.colors
    var progress by rememberSaveable { mutableStateOf(initial) }
    LaunchedEffect(progress) {
        val current = progress ?: return@LaunchedEffect
        if (initial != null) return@LaunchedEffect
        if (current < 1f) {
            delay(150)
            progress = minOf(current + 0.01f, 1f)
        } else {
            delay(1200)
            progress = null
            island.notify(
                title = "Download complete",
                description = "Design-Kit.zip",
                icon = { Icon(PhosphorIcons.Fill.CheckCircle, contentDescription = null, tint = Palette.green500) },
            )
        }
    }
    LaunchedEffect(start) {
        when (start) {
            IslandStart.Expanded -> island.expand()
            IslandStart.Minimal -> island.minimize()
            IslandStart.Compact -> Unit
        }
    }
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        IslandDownloadIsland(progress) { progress = null }
        Text(
            "Start a download, then tap the pill at the top to see the details. Swipe up on it to close.",
            modifier = Modifier.widthIn(max = 320.dp),
            style = Typography.sm.copy(color = colors.mutedForeground),
            textAlign = TextAlign.Center,
        )
        if (initial == null) {
            Button(
                if (progress == null) "Download Design-Kit.zip" else "Downloading…",
                onClick = { progress = 0f },
                enabled = progress == null,
            )
        }
        if (withNotifications) {
            IslandNotifyButtons {
                Button(
                    "Minimize",
                    onClick = island::minimize,
                    variant = ButtonVariant.Secondary,
                    enabled = progress != null,
                )
            }
        }
    }
}
```

## API Reference

### IslandProvider

Holds the island mode, the notice and the notice timer.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `React.ReactNode` | - |  |

### IslandExpandedRegion

A region of the expanded view.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `region` | `"leading" \| "trailing" \| "center" \| "bottom"` | Required | Where the content sits in the expanded view. |

Also accepts the props of `IslandExpandedRegionProps`.

### Island

The floating pill, rendered in a portal, with slots for the compact and minimal views.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` | - |  |
| `compactLeading` | `React.ReactNode` | - | Content at the start of the compact pill. |
| `compactTrailing` | `React.ReactNode` | - | Content at the end of the compact pill. |
| `minimal` | `React.ReactNode` | - | Content of the minimal view. |
| `portalHost` | `string` | - | Name of a portal host to render into. |

Also accepts the props of `React.ComponentProps<typeof View>`.

### IslandRing

A small circular progress ring.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number` | Required | Progress from `0` to `1`. |
| `className` | `string` | - |  |

## Accessibility

- Notices are announced with their title and description when they are text.
- The compact and minimal views are buttons that expose `expanded` and have `activate` and `expand` actions.
- The expanded view has the `group` role, a `collapse` action and closes on the escape gesture.
- The notice is a button with `activate` and `dismiss` actions.
- Inactive views and the progress ring are hidden from screen readers.

## Notes

- The island uses `bg-black` with `text-white`.
- Expanded and notice views are up to 384 points wide.
- Size and fade animations respect the system reduce motion setting.

