# Page stack

> Pages that slide in and out like an iOS navigation stack, decided from the path, with an edge swipe to go back and a rising swap for list-and-detail panes.

Docs: https://plumbago.ochotzas.com/components/page-stack

## Installation

```sh
npx plumbago add page-stack
```

This copies `components/ui/page-stack.tsx` into your project, along with `cn`, `spring`.

## Usage

```tsx
import { PageStack, PageSwap } from "@/components/ui/page-stack"

const [path, setPath] = useState("/menu")

<PageStack path={path} onBack={() => setPath(parentOf(path))}>
  <Screen path={path} onOpen={setPath} />
</PageStack>

<PageSwap pageKey={dish.slug}>
  <DishDetail dish={dish} />
</PageSwap>
```

## Examples

### Preview

```tsx
import { BackButton } from "@/components/ui/back-button"
import { Island, ListRow, ListRowChevron, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { PageHeader, PageHeaderBar, PageHeaderTitle } from "@/components/ui/page-header"
import { PageStack } from "@/components/ui/page-stack"
import { useState } from "react"

const sections = [
  {
    slug: "starters",
    title: "Starters",
    dishes: [
      { slug: "burrata", title: "Burrata with blood orange", price: "€14.50", note: "Creamy burrata, blood orange, pistachio and a little chilli oil." },
      { slug: "tartare", title: "Beef tartare", price: "€16.00", note: "Hand-cut beef, capers, egg yolk and toasted sourdough." },
      { slug: "beets", title: "Roasted beet salad", price: "€11.00", note: "Roasted beets, goat cheese, walnuts and a honey vinaigrette." },
    ],
  },
  {
    slug: "mains",
    title: "Mains",
    dishes: [
      { slug: "risotto", title: "Wild mushroom risotto", price: "€21.00", note: "Carnaroli rice, wild mushrooms, parmesan and a little thyme." },
      { slug: "sea-bass", title: "Sea bass with fennel", price: "€26.00", note: "Pan-seared sea bass on shaved fennel with a lemon butter." },
      { slug: "lamb", title: "Lamb shoulder", price: "€28.50", note: "Slow-cooked for six hours, with white beans and rosemary." },
      { slug: "gnocchi", title: "Gnocchi with sage butter", price: "€18.00", note: "Potato gnocchi, browned sage butter and aged pecorino." },
    ],
  },
  {
    slug: "desserts",
    title: "Desserts",
    dishes: [
      { slug: "tiramisu", title: "Tiramisu", price: "€9.00", note: "Mascarpone, espresso-soaked savoiardi and dark cocoa." },
      { slug: "sorbet", title: "Lemon sorbet", price: "€7.00", note: "Sicilian lemons, nothing else." },
    ],
  },
]

const parentOf = (path: string) => path.slice(0, path.lastIndexOf("/"))

function Screen({ path, onOpen, onBack }: { path: string; onOpen: (path: string) => void; onBack: () => void }) {
  const [, , sectionSlug, dishSlug] = path.split("/")
  const section = sections.find((entry) => entry.slug === sectionSlug)
  const dish = section?.dishes.find((entry) => entry.slug === dishSlug)

  if (section && dish) {
    return (
      <PageHeader>
        <PageHeaderBar leading={<BackButton onClick={onBack}>{section.title}</BackButton>} />
        <PageHeaderTitle>{dish.title}</PageHeaderTitle>
        <div className="mx-auto flex max-w-app flex-col gap-4 px-gutter pb-6">
          <p className="text-body text-ink-2">{dish.note}</p>
          <Island variant="list">
            <ListRow>
              <ListRowText>
                <ListRowTitle>Price</ListRowTitle>
              </ListRowText>
              <ListRowValue>{dish.price}</ListRowValue>
            </ListRow>
          </Island>
        </div>
      </PageHeader>
    )
  }

  const rows = section
    ? section.dishes.map((entry) => ({ slug: entry.slug, title: entry.title, value: entry.price }))
    : sections.map((entry) => ({ slug: entry.slug, title: entry.title, value: `${entry.dishes.length} dishes` }))

  return (
    <PageHeader>
      <PageHeaderBar leading={section ? <BackButton onClick={onBack}>Menu</BackButton> : null} />
      <PageHeaderTitle>{section ? section.title : "Menu"}</PageHeaderTitle>
      <div className="mx-auto max-w-app px-gutter pb-6">
        <Island variant="list">
          {rows.map((row) => (
            <ListRow key={row.slug} render={<button type="button" onClick={() => onOpen(`${path}/${row.slug}`)} />}>
              <ListRowText>
                <ListRowTitle>{row.title}</ListRowTitle>
              </ListRowText>
              <ListRowValue>
                {row.value}
                <ListRowChevron />
              </ListRowValue>
            </ListRow>
          ))}
        </Island>
      </div>
    </PageHeader>
  )
}

export default function PageStackDemo() {
  const [path, setPath] = useState("/menu")
  const back = () => setPath(parentOf(path))

  return (
    <div className="h-[560px] w-full max-w-[390px] overflow-hidden rounded-xl border border-line">
      <PageStack path={path} onBack={back}>
        <Screen path={path} onOpen={setPath} onBack={back} />
      </PageStack>
    </div>
  )
}
```

### Tabs

```tsx
import { BackButton } from "@/components/ui/back-button"
import { Island, ListRow, ListRowChevron, ListRowSubtitle, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { PageHeader, PageHeaderBar, PageHeaderTitle } from "@/components/ui/page-header"
import { PageStack } from "@/components/ui/page-stack"
import { TabBarItem, TabBarList, TabBarRoot } from "@/components/ui/tab-bar"
import { ReceiptText, UtensilsCrossed } from "lucide-react"
import { useState } from "react"

const dishes = [
  ["risotto", "Wild mushroom risotto", "€21.00"],
  ["sea-bass", "Sea bass with fennel", "€26.00"],
  ["lamb", "Lamb shoulder", "€28.50"],
  ["tiramisu", "Tiramisu", "€9.00"],
]

const orders = [
  ["4021", "Table 6", "2 mains, 1 starter"],
  ["4020", "Table 2", "1 main, 2 desserts"],
  ["4019", "Takeaway", "3 mains"],
]

const parentOf = (path: string) => path.slice(0, path.lastIndexOf("/"))

function Screen({ path, onOpen, onBack }: { path: string; onOpen: (path: string) => void; onBack: () => void }) {
  const [, tab, id] = path.split("/")
  const dish = dishes.find(([slug]) => slug === id)
  const order = orders.find(([number]) => number === id)

  if (dish || order) {
    return (
      <PageHeader>
        <PageHeaderBar leading={<BackButton onClick={onBack}>{tab === "menu" ? "Menu" : "Orders"}</BackButton>} />
        <PageHeaderTitle>{dish ? dish[1] : `Order ${order?.[0]}`}</PageHeaderTitle>
        <p className="mx-auto max-w-app px-gutter text-body text-ink-2">{dish ? dish[2] : `${order?.[1]}: ${order?.[2]}`}</p>
      </PageHeader>
    )
  }

  return (
    <PageHeader>
      <PageHeaderBar />
      <PageHeaderTitle>{tab === "menu" ? "Menu" : "Orders"}</PageHeaderTitle>
      <div className="mx-auto max-w-app px-gutter pb-6">
        <Island variant="list">
          {tab === "menu"
            ? dishes.map(([slug, title, price]) => (
                <ListRow key={slug} render={<button type="button" onClick={() => onOpen(`${path}/${slug}`)} />}>
                  <ListRowText>
                    <ListRowTitle>{title}</ListRowTitle>
                  </ListRowText>
                  <ListRowValue>
                    {price}
                    <ListRowChevron />
                  </ListRowValue>
                </ListRow>
              ))
            : orders.map(([number, table, items]) => (
                <ListRow key={number} render={<button type="button" onClick={() => onOpen(`${path}/${number}`)} />}>
                  <ListRowText>
                    <ListRowTitle>{table}</ListRowTitle>
                    <ListRowSubtitle>{items}</ListRowSubtitle>
                  </ListRowText>
                  <ListRowValue>
                    <ListRowChevron />
                  </ListRowValue>
                </ListRow>
              ))}
        </Island>
      </div>
    </PageHeader>
  )
}

export default function PageStackTabs() {
  const [path, setPath] = useState("/menu")
  const tab = path.split("/")[1] ?? "menu"
  const back = () => setPath(parentOf(path))

  return (
    <TabBarRoot
      value={tab}
      onValueChange={(next) => setPath(`/${next}`)}
      className="h-[600px] w-full max-w-[390px] overflow-hidden rounded-xl border border-line"
    >
      <PageStack path={path} onBack={back} className="h-auto min-h-0 flex-1">
        <Screen path={path} onOpen={setPath} onBack={back} />
      </PageStack>
      <TabBarList aria-label="Main" className="pb-[22px]">
        <TabBarItem value="menu" icon={<UtensilsCrossed strokeWidth={1.75} />} activeIcon={<UtensilsCrossed strokeWidth={2.5} />}>
          Menu
        </TabBarItem>
        <TabBarItem value="orders" icon={<ReceiptText strokeWidth={1.75} />} activeIcon={<ReceiptText strokeWidth={2.5} />}>
          Orders
        </TabBarItem>
      </TabBarList>
    </TabBarRoot>
  )
}
```

### List and detail

```tsx
import { Island, ListRow, ListRowChevron, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { PageSwap } from "@/components/ui/page-stack"
import { useState } from "react"

const dishes = [
  {
    slug: "risotto",
    title: "Wild mushroom risotto",
    price: "€21.00",
    note: "Carnaroli rice, wild mushrooms, parmesan and a little thyme.",
    allergens: "Dairy, celery",
  },
  {
    slug: "sea-bass",
    title: "Sea bass with fennel",
    price: "€26.00",
    note: "Pan-seared sea bass on shaved fennel with a lemon butter.",
    allergens: "Fish, dairy",
  },
  { slug: "lamb", title: "Lamb shoulder", price: "€28.50", note: "Slow-cooked for six hours, with white beans and rosemary.", allergens: "None" },
  {
    slug: "gnocchi",
    title: "Gnocchi with sage butter",
    price: "€18.00",
    note: "Potato gnocchi, browned sage butter and aged pecorino.",
    allergens: "Gluten, dairy, egg",
  },
]

export default function PageStackListAndDetail() {
  const [slug, setSlug] = useState("risotto")
  const dish = dishes.find((entry) => entry.slug === slug) ?? dishes[0]

  return (
    <div className="@container w-full">
      <div className="grid gap-6 @xl:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
        <Island variant="list" className="self-start">
          {dishes.map((entry) => (
            <ListRow
              key={entry.slug}
              aria-current={entry.slug === slug ? "true" : undefined}
              className="aria-[current=true]:bg-press"
              render={<button type="button" onClick={() => setSlug(entry.slug)} />}
            >
              <ListRowText>
                <ListRowTitle>{entry.title}</ListRowTitle>
              </ListRowText>
              <ListRowValue>
                {entry.price}
                <ListRowChevron />
              </ListRowValue>
            </ListRow>
          ))}
        </Island>
        <PageSwap pageKey={slug} className="flex flex-col gap-4 py-2">
          <h2 className="text-title1 font-bold text-ink">{dish?.title}</h2>
          <p className="max-w-read text-body text-ink-2">{dish?.note}</p>
          <Island variant="list">
            <ListRow>
              <ListRowText>
                <ListRowTitle>Price</ListRowTitle>
              </ListRowText>
              <ListRowValue>{dish?.price}</ListRowValue>
            </ListRow>
            <ListRow>
              <ListRowText>
                <ListRowTitle>Allergens</ListRowTitle>
              </ListRowText>
              <ListRowValue>{dish?.allergens}</ListRowValue>
            </ListRow>
          </Island>
        </PageSwap>
      </div>
    </div>
  )
}
```

## Source

```tsx
import { cn } from "@/lib/cn"
import { createVelocityTracker, type Settle, settleSpring, springEasing } from "@/lib/spring"
import { type ComponentProps, type ReactNode, type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"
import { flushSync } from "react-dom"

const edgeWidth = 28
const commitPast = 0.4
const flingSpeed = 500
const underShift = 0.28
const underFade = 0.3
const lockDistance = 8
const lockRatio = 1.2
const velocityWindowMs = 90
const leaveMs = 160
const backWaitMs = 150
const titleSelector = "[data-page-title], h1"

export type PageTransition = "push" | "pop" | "tab" | "swap"
export type NavigationType = "push" | "pop" | "replace" | "traverse"

const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value))

function segmentsOf(path: string) {
  return (path.split(/[?#]/)[0] ?? "").split("/").filter(Boolean)
}

function extendsPath(longer: string[], shorter: string[]) {
  return longer.length > shorter.length && shorter.every((segment, index) => longer[index] === segment)
}

function samePath(first: string, second: string) {
  return segmentsOf(first).join("/") === segmentsOf(second).join("/")
}

export function pageTransitionFor(fromPath: string, toPath: string, navigationType?: NavigationType): PageTransition {
  const from = segmentsOf(fromPath)
  const to = segmentsOf(toPath)
  if (from.length > 0 && to.length > 0 && from[0] !== to[0]) return "tab"
  if (navigationType === "traverse" || navigationType === "replace") return "swap"
  if (extendsPath(to, from)) return "push"
  if (extendsPath(from, to)) return "pop"
  return "swap"
}

type Page = { id: number; path: string }
type StoredPage = Page & { node: ReactNode }

type Stage = {
  path: string
  current: Page
  leaving: StoredPage | null
  history: StoredPage[]
  kind: PageTransition | null
  run: number
  nextId: number
  belowId: number
}

function lastIndexWhere<T>(items: T[], test: (item: T) => boolean) {
  for (let index = items.length - 1; index >= 0; index--) {
    const item = items[index]
    if (item !== undefined && test(item)) return index
  }
  return -1
}

function advance(stage: Stage, path: string, navigationType: NavigationType | undefined, previousNode: ReactNode): Stage {
  const kind = pageTransitionFor(stage.path, path, navigationType)
  const leaving: StoredPage = { ...stage.current, node: previousNode }
  let { history, nextId, belowId } = stage
  const matched = kind === "pop" || kind === "swap" ? lastIndexWhere(history, (page) => samePath(page.path, path)) : -1
  const revisited = matched >= 0 ? history[matched] : undefined
  let current: Page
  if (revisited) {
    current = { id: revisited.id, path }
    history = history.slice(0, matched)
  } else if (kind === "pop") {
    current = { id: belowId, path }
    belowId -= 1
  } else {
    current = { id: nextId, path }
    nextId += 1
    if (kind === "push") history = [...history, leaving]
    if (kind === "tab") history = []
  }
  return { path, current, leaving, history, kind, run: stage.run + 1, nextId, belowId }
}

type Pending = { progress: number; velocity: number }

type Motion = {
  settle: Settle | null
  animations: Animation[]
  progress: number
  topId: number
  underId: number
  pending: Pending | null
  timer: number
}

const createMotion = (): Motion => ({ settle: null, animations: [], progress: 1, topId: 0, underId: 0, pending: null, timer: 0 })

const prefersReducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

function token(element: Element, name: string, fallback: string) {
  return getComputedStyle(element).getPropertyValue(name).trim() || fallback
}

function duration(element: Element, name: string, fallback: number) {
  const value = token(element, name, "")
  const amount = Number.parseFloat(value)
  if (!amount) return fallback
  return value.endsWith("ms") ? amount : amount * 1000
}

function paintLayers(layers: Map<number, HTMLElement>, motion: Motion, progress: number, width: number) {
  const top = layers.get(motion.topId)
  const under = layers.get(motion.underId)
  motion.progress = progress
  if (top) top.style.transform = `translateX(${(1 - progress) * width}px)`
  if (under) {
    under.style.transform = `translateX(${-underShift * width * progress}px)`
    under.style.opacity = String(1 - underFade * progress)
  }
}

function resetLayers(layers: Map<number, HTMLElement>) {
  for (const element of layers.values()) {
    element.style.removeProperty("transform")
    element.style.removeProperty("opacity")
  }
}

function stopMotion(motion: Motion, layers: Map<number, HTMLElement>) {
  motion.settle?.stop()
  motion.settle = null
  for (const animation of motion.animations) animation.cancel()
  motion.animations = []
  window.clearTimeout(motion.timer)
  resetLayers(layers)
}

function play(motion: Motion, element: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions) {
  const animation = element.animate(keyframes, options)
  motion.animations.push(animation)
  return animation
}

function focusTitle(layer: HTMLElement, leavingLayer: HTMLElement | undefined) {
  const active = document.activeElement
  const insideStack = active && active !== document.body && !leavingLayer?.contains(active)
  if (insideStack) return
  const target = layer.querySelector<HTMLElement>(titleSelector) ?? layer
  if (!target.hasAttribute("tabindex")) target.setAttribute("tabindex", "-1")
  target.focus({ preventScroll: true })
}

export type PageStackProps = Omit<ComponentProps<"div">, "className" | "ref"> & {
  path: string
  navigationType?: NavigationType
  onBack?: () => void
  below?: ReactNode
  className?: string
}

type PageLayerProps = {
  id: number
  role: "current" | "leaving" | "below"
  top: boolean
  layers: RefObject<Map<number, HTMLElement>>
  scrolls: RefObject<Map<number, number>>
  children: ReactNode
}

function PageLayer({ id, role, top, layers, scrolls, children }: PageLayerProps) {
  const attach = useCallback(
    (element: HTMLDivElement | null) => {
      if (!element) return
      layers.current.set(id, element)
      const saved = scrolls.current.get(id)
      if (saved) element.scrollTop = saved
      return () => {
        layers.current.delete(id)
      }
    },
    [id, layers, scrolls],
  )
  return (
    <div
      ref={attach}
      data-slot="page-stack-page"
      data-role={role}
      inert={role !== "current"}
      onScroll={(event) => scrolls.current.set(id, event.currentTarget.scrollTop)}
      className={cn(
        "absolute inset-0 overflow-x-hidden overflow-y-auto overscroll-contain bg-bg outline-none",
        "[&_h1:focus]:outline-none [&_[data-page-title]:focus]:outline-none",
        top ? "z-2" : "z-1",
      )}
    >
      {children}
    </div>
  )
}

export function PageStack({ path, navigationType, onBack, below, className, children, ...props }: PageStackProps) {
  const [stage, setStage] = useState<Stage>(() => ({
    path,
    current: { id: 0, path },
    leaving: null,
    history: [],
    kind: null,
    run: 0,
    nextId: 1,
    belowId: -1,
  }))
  const [dragging, setDragging] = useState(false)
  const rootRef = useRef<HTMLDivElement>(null)
  const layers = useRef(new Map<number, HTMLElement>())
  const scrolls = useRef(new Map<number, number>())
  const motion = useRef(createMotion())
  const lastNode = useRef<ReactNode>(children)
  const latest = useRef({ stage, onBack, hasBelow: below !== undefined })
  latest.current = { stage, onBack, hasBelow: below !== undefined }

  if (!samePath(stage.path, path)) setStage(advance(stage, path, navigationType, lastNode.current))

  useLayoutEffect(() => {
    lastNode.current = children
  })

  const run = stage.run

  useLayoutEffect(() => {
    const root = rootRef.current
    const { stage: now } = latest.current
    const control = motion.current
    if (!root || run === 0 || !now.kind || !now.leaving) return
    const kind = now.kind
    const enterId = now.current.id
    const leaveId = now.leaving.id
    const enter = layers.current.get(enterId)
    const leave = layers.current.get(leaveId)
    const pending = control.pending
    control.pending = null
    stopMotion(control, layers.current)
    setDragging(false)
    if (!enter) return
    focusTitle(enter, leave)

    const finish = () => setStage((current) => (current.run === run ? { ...current, leaving: null, kind: null } : current))

    if (prefersReducedMotion()) {
      const settings = { duration: duration(enter, "--pb-dur-base", 220), easing: token(enter, "--pb-ease-out", "ease-out") }
      play(control, enter, [{ opacity: 0 }, { opacity: 1 }], settings)
      if (leave) play(control, leave, [{ opacity: 1 }, { opacity: 0 }], { ...settings, fill: "forwards" }).onfinish = finish
      else finish()
      return
    }

    if (kind === "tab" || kind === "swap") {
      play(
        control,
        enter,
        [
          { opacity: 0, filter: "blur(8px)", transform: "translateY(6px) scale(0.98)" },
          { opacity: 1, filter: "blur(0)", transform: "none" },
        ],
        { duration: duration(enter, "--pb-dur-spring", 350), easing: springEasing(enter) },
      )
      if (leave) {
        play(
          control,
          leave,
          [
            { opacity: 1, filter: "blur(0)", transform: "none" },
            { opacity: 0, filter: "blur(8px)", transform: "translateY(-4px) scale(0.98)" },
          ],
          { duration: leaveMs, easing: token(leave, "--pb-ease-in", "ease-in"), fill: "forwards" },
        ).onfinish = finish
      } else finish()
      return
    }

    const popping = kind === "pop"
    const from = popping ? (pending?.progress ?? 1) : 0
    const to = popping ? 0 : 1
    control.topId = popping ? leaveId : enterId
    control.underId = popping ? enterId : leaveId
    const width = root.offsetWidth
    paintLayers(layers.current, control, from, width)
    control.settle = settleSpring(
      from,
      to,
      popping ? (pending?.velocity ?? 0) : 0,
      (value) => paintLayers(layers.current, control, value, width),
      () => {
        control.settle = null
        flushSync(finish)
        resetLayers(layers.current)
      },
      { restSpeed: 0.01, restDistance: 0.001 },
    )
  }, [run])

  useEffect(() => {
    const root = rootRef.current
    const control = motion.current
    if (!root) return
    let origin: { id: number; x: number; y: number; progress: number; active: boolean } | null = null
    let tracker = createVelocityTracker()
    let lastMoveAt = 0

    const finishPush = () => setStage((current) => (current.kind === "push" ? { ...current, leaving: null, kind: null } : current))

    const springBack = (velocity: number) => {
      const done = () => {
        control.settle = null
        resetLayers(layers.current)
        setDragging(false)
        finishPush()
      }
      if (prefersReducedMotion()) {
        done()
        return
      }
      const width = root.offsetWidth || 1
      control.settle = settleSpring(control.progress, 1, velocity, (value) => paintLayers(layers.current, control, value, width), done, {
        restSpeed: 0.01,
        restDistance: 0.001,
      })
    }

    const onDown = (event: PointerEvent) => {
      const { stage: now, onBack: back, hasBelow } = latest.current
      if (!back || !event.isPrimary || (event.pointerType === "mouse" && event.button !== 0)) return
      if (event.clientX - root.getBoundingClientRect().left > edgeWidth) return
      const grabbing = now.kind === "push" && control.settle !== null
      if (now.kind && !grabbing) return
      if (!grabbing && now.history.length === 0 && !hasBelow) return
      if (grabbing) {
        control.settle?.stop()
        control.settle = null
      }
      origin = { id: event.pointerId, x: event.clientX, y: event.clientY, progress: grabbing ? control.progress : 1, active: grabbing }
      tracker = createVelocityTracker()
      tracker.add(event.clientX)
      lastMoveAt = performance.now()
      if (grabbing) {
        root.setPointerCapture(event.pointerId)
        root.style.userSelect = "none"
      }
    }

    const onMove = (event: PointerEvent) => {
      if (!origin || event.pointerId !== origin.id) return
      const dx = event.clientX - origin.x
      const dy = event.clientY - origin.y
      if (!origin.active) {
        if (Math.abs(dx) > lockDistance && dx > lockRatio * Math.abs(dy)) {
          origin.active = true
          root.setPointerCapture(event.pointerId)
          root.style.userSelect = "none"
          const { stage: now } = latest.current
          flushSync(() => setDragging(true))
          control.topId = now.current.id
          control.underId = now.history[now.history.length - 1]?.id ?? now.belowId
        } else if (Math.abs(dy) > lockDistance) {
          origin = null
          return
        } else return
      }
      tracker.add(event.clientX)
      lastMoveAt = performance.now()
      const width = root.offsetWidth || 1
      paintLayers(layers.current, control, clamp(origin.progress - dx / width, 0, 1), width)
    }

    const onEnd = (event: PointerEvent) => {
      if (!origin || event.pointerId !== origin.id) return
      const wasActive = origin.active
      origin = null
      root.style.removeProperty("user-select")
      if (!wasActive) return
      const width = root.offsetWidth || 1
      const speed = performance.now() - lastMoveAt > velocityWindowMs ? 0 : tracker.velocity()
      const commit = event.type === "pointerup" && ((control.progress < 1 - commitPast && speed > -flingSpeed) || speed > flingSpeed)
      if (!commit) {
        springBack(-speed / width)
        return
      }
      control.pending = { progress: control.progress, velocity: -speed / width }
      latest.current.onBack?.()
      control.timer = window.setTimeout(() => {
        if (!control.pending) return
        control.pending = null
        springBack(-speed / width)
      }, backWaitMs)
    }

    root.addEventListener("pointerdown", onDown)
    root.addEventListener("pointermove", onMove)
    root.addEventListener("pointerup", onEnd)
    root.addEventListener("pointercancel", onEnd)
    return () => {
      root.removeEventListener("pointerdown", onDown)
      root.removeEventListener("pointermove", onMove)
      root.removeEventListener("pointerup", onEnd)
      root.removeEventListener("pointercancel", onEnd)
    }
  }, [])

  useEffect(() => {
    const control = motion.current
    const mounted = layers.current
    return () => stopMotion(control, mounted)
  }, [])

  const belowPage: StoredPage | null = stage.history[stage.history.length - 1] ?? (below === undefined ? null : { id: stage.belowId, path: "", node: below })
  const pages: { id: number; role: PageLayerProps["role"]; node: ReactNode }[] = []
  if (dragging && !stage.kind && belowPage) pages.push({ id: belowPage.id, role: "below", node: belowPage.node })
  if (stage.leaving) pages.push({ id: stage.leaving.id, role: "leaving", node: stage.leaving.node })
  pages.push({ id: stage.current.id, role: "current", node: children })
  pages.sort((first, second) => first.id - second.id)

  return (
    <div
      ref={rootRef}
      data-slot="page-stack"
      className={cn("relative isolate h-full w-full touch-pan-y touch-pinch-zoom overflow-hidden bg-bg", className)}
      {...props}
    >
      {pages.map((page) => (
        <PageLayer
          key={page.id}
          id={page.id}
          role={page.role}
          top={stage.kind === "pop" ? page.role === "leaving" : page.role === "current"}
          layers={layers}
          scrolls={scrolls}
        >
          {page.node}
        </PageLayer>
      ))}
    </div>
  )
}

export type PageSwapProps = Omit<ComponentProps<"div">, "className"> & {
  pageKey: string | number
  className?: string
}

type SwapPane = { key: string | number; node: ReactNode }

const swapLeaveMs = 140

export function PageSwap({ pageKey, className, children, ...props }: PageSwapProps) {
  const [current, setCurrent] = useState<string | number>(pageKey)
  const [leaving, setLeaving] = useState<SwapPane[]>([])
  const lastNode = useRef<ReactNode>(children)

  if (current !== pageKey) {
    setLeaving((panes) => [...panes.filter((pane) => pane.key !== pageKey), { key: current, node: lastNode.current }])
    setCurrent(pageKey)
  }

  useLayoutEffect(() => {
    lastNode.current = children
  })

  useEffect(() => {
    if (leaving.length === 0) return
    const timer = window.setTimeout(() => setLeaving([]), swapLeaveMs)
    return () => window.clearTimeout(timer)
  }, [leaving])

  return (
    <div data-slot="page-swap" className="grid" {...props}>
      {leaving.map((pane) => (
        <div
          key={`leaving-${pane.key}`}
          inert
          aria-hidden="true"
          className={cn(
            "pointer-events-none col-start-1 row-start-1 -translate-y-1 scale-98 opacity-0 transition-[opacity,translate,scale,filter] duration-[140ms] ease-in starting:translate-y-0 starting:scale-100 starting:opacity-100 motion-safe:blur-[8px] motion-safe:starting:blur-none motion-reduce:translate-y-0 motion-reduce:scale-100",
            className,
          )}
        >
          {pane.node}
        </div>
      ))}
      <div
        key={current}
        className={cn(
          "col-start-1 row-start-1 min-w-0 transition-[opacity,translate,scale,filter] delay-[90ms] duration-spring ease-spring starting:translate-y-1.5 starting:scale-98 starting:opacity-0 motion-safe:starting:blur-[8px] motion-reduce:starting:translate-y-0 motion-reduce:starting:scale-100",
          className,
        )}
      >
        {children}
      </div>
    </div>
  )
}
```
