# Zoom open

> A card that grows into its own screen the way iOS does it, with an edge swipe to shrink it back.

Docs: https://plumbago.ochotzas.com/components/zoom-open

## Installation

```sh
npx plumbago add zoom-open
```

This copies `components/ui/zoom-open.tsx` into your project, along with `cn`, `spring`, `back-button`, and installs `@base-ui/react`.

## Usage

```tsx
import { ZoomOpen, ZoomOpenCard, ZoomOpenCardImage, ZoomOpenContent, ZoomOpenHeaderImage, ZoomOpenScreen, ZoomOpenTitle } from "@/components/ui/zoom-open"

<ZoomOpen>
  <ZoomOpenCard>
    <ZoomOpenCardImage>
      <img src="/dishes/burrata.jpg" alt="" />
    </ZoomOpenCardImage>
    <span className="block p-4 font-medium">Burrata with figs</span>
  </ZoomOpenCard>
  <ZoomOpenScreen>
    <ZoomOpenHeaderImage>
      <img src="/dishes/burrata.jpg" alt="" />
    </ZoomOpenHeaderImage>
    <ZoomOpenContent>
      <ZoomOpenTitle>Burrata with figs</ZoomOpenTitle>
    </ZoomOpenContent>
  </ZoomOpenScreen>
</ZoomOpen>
```

## Examples

### Preview

```tsx
import { Island, IslandLabel, ListRow, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import {
  ZoomOpen,
  ZoomOpenCard,
  ZoomOpenCardImage,
  ZoomOpenContent,
  ZoomOpenDescription,
  ZoomOpenHeaderImage,
  ZoomOpenScreen,
  ZoomOpenTitle,
} from "@/components/ui/zoom-open"

const dishes = [
  {
    name: "Burrata with figs",
    time: "10 min",
    photo: "/dishes/burrata.webp",
    story: "A whole burrata torn open at the table, with roasted figs, a drizzle of aged balsamic and torn basil. Served with warm focaccia.",
    ingredients: [
      ["Burrata", "1 large"],
      ["Black figs", "4"],
      ["Aged balsamic", "2 tbsp"],
      ["Basil", "1 handful"],
    ],
  },
  {
    name: "Hand-cut tagliatelle",
    time: "40 min",
    photo: "/dishes/tagliatelle.webp",
    story: "Egg pasta rolled and cut every morning, tossed with brown butter, sage and a heavy grating of parmesan just before it leaves the pass.",
    ingredients: [
      ["00 flour", "300 g"],
      ["Eggs", "3"],
      ["Butter", "80 g"],
      ["Sage", "12 leaves"],
    ],
  },
  {
    name: "Beef tartare",
    time: "15 min",
    photo: "/dishes/tartare.webp",
    story: "Hand-chopped fillet with capers, shallot and a cured yolk, seasoned at the last minute and served with crisp potato.",
    ingredients: [
      ["Beef fillet", "240 g"],
      ["Capers", "1 tbsp"],
      ["Shallot", "1"],
      ["Cured yolk", "2"],
    ],
  },
]

export default function ZoomOpenDemo() {
  return (
    <div className="grid w-full max-w-3xl gap-3 sm:grid-cols-3">
      {dishes.map((dish) => (
        <ZoomOpen key={dish.name}>
          <ZoomOpenCard>
            <ZoomOpenCardImage className="h-32">
              <img src={dish.photo} alt="" />
            </ZoomOpenCardImage>
            <span className="block px-4 py-3">
              <span className="block font-medium">{dish.name}</span>
              <span className="block text-footnote text-ink-2">{dish.time}</span>
            </span>
          </ZoomOpenCard>
          <ZoomOpenScreen>
            <ZoomOpenHeaderImage>
              <img src={dish.photo} alt="" />
            </ZoomOpenHeaderImage>
            <ZoomOpenContent className="grid gap-8 pt-6 pb-16 lg:grid-cols-[minmax(0,1fr)_380px]">
              <div className="flex max-w-read flex-col gap-3">
                <ZoomOpenTitle>{dish.name}</ZoomOpenTitle>
                <ZoomOpenDescription>{dish.story}</ZoomOpenDescription>
                <p className="text-footnote text-ink-3">{dish.time} to cook</p>
              </div>
              <div>
                <IslandLabel>Ingredients</IslandLabel>
                <Island variant="list">
                  {dish.ingredients.map(([name, amount]) => (
                    <ListRow key={name}>
                      <ListRowText>
                        <ListRowTitle>{name}</ListRowTitle>
                      </ListRowText>
                      <ListRowValue>{amount}</ListRowValue>
                    </ListRow>
                  ))}
                </Island>
              </div>
            </ZoomOpenContent>
          </ZoomOpenScreen>
        </ZoomOpen>
      ))}
    </div>
  )
}
```

### Without image

```tsx
import { Island, ListRow, ListRowSubtitle, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { ZoomOpen, ZoomOpenCard, ZoomOpenContent, ZoomOpenScreen, ZoomOpenTitle } from "@/components/ui/zoom-open"

const bookings = [
  ["Haddad", "4 guests", "18:30", "Window table"],
  ["Okafor", "2 guests", "19:00", "Anniversary"],
  ["Lindqvist", "6 guests", "19:45", "One vegan"],
  ["Moreau", "3 guests", "20:30", "High chair"],
]

export default function ZoomOpenWithoutImage() {
  return (
    <ZoomOpen>
      <ZoomOpenCard className="w-full max-w-sm">
        <span className="block p-4">
          <span className="block text-footnote text-ink-2">Tonight</span>
          <span className="block text-headline font-semibold">Bookings</span>
          <span className="block text-footnote text-ink-2">{bookings.length} tables, first seating 18:30</span>
        </span>
      </ZoomOpenCard>
      <ZoomOpenScreen>
        <ZoomOpenContent className="max-w-read pt-20 pb-16">
          <ZoomOpenTitle className="mb-6">Tonight's bookings</ZoomOpenTitle>
          <Island variant="list">
            {bookings.map(([name, guests, time, note]) => (
              <ListRow key={name}>
                <ListRowText>
                  <ListRowTitle>{name}</ListRowTitle>
                  <ListRowSubtitle>
                    {guests} · {note}
                  </ListRowSubtitle>
                </ListRowText>
                <ListRowValue>{time}</ListRowValue>
              </ListRow>
            ))}
          </Island>
        </ZoomOpenContent>
      </ZoomOpenScreen>
    </ZoomOpen>
  )
}
```

## Built on Base UI

Zoom open wraps these Base UI parts and keeps their props:

- [Dialog](https://base-ui.com/react/components/dialog)
- [Merge props](https://base-ui.com/react/utils/merge-props)
- [Use render](https://base-ui.com/react/utils/use-render)

## Source

```tsx
import { Dialog } from "@base-ui/react/dialog"
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cn } from "@/lib/cn"
import { createVelocityTracker, type Settle, settleSpring } from "@/lib/spring"
import { BackButton } from "@/components/ui/back-button"
import { type ComponentProps, createContext, type ReactNode, type RefObject, useCallback, useContext, useEffect, useRef, useState } from "react"

const edgeWidth = 28
const dragSpan = 0.9
const closeBelow = 0.6
const flingSpeed = 500
const dimOpacity = 0.12
const velocityWindowMs = 90
const lockDistance = 8
const lockRatio = 1.2
const fadeStart = 0.25
const fadeEnd = 0.55
const solidAt = 0.2
const cardImageSlot = "[data-slot=zoom-open-card-image]"
const headerImageSlot = "[data-slot=zoom-open-header-image]"
const scrollerSlot = "[data-slot=zoom-open-scroller]"

const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value))
const lerp = (from: number, to: number, amount: number) => from + (to - from) * amount

const readDuration = (value: string) => {
  const amount = Number.parseFloat(value)
  if (!amount) return 220
  return value.trim().endsWith("ms") ? amount : amount * 1000
}

type Callbacks = { closed: () => void }

function createZoom() {
  let progress = 0
  let popup: HTMLElement | null = null
  let backdrop: HTMLElement | null = null
  let card: HTMLElement | null = null
  let pending: number | null = null
  let target: number | null = null
  let settling: Settle | null = null
  let tracker = createVelocityTracker()
  let size = { width: 1, height: 1, hero: 0 }
  let from = { x: 0, y: 0, w: 1, h: 1, hero: 0 }
  let cardRadius = 22
  const callbacks: Callbacks = { closed: () => {} }

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

  const measure = () => {
    if (!popup || !card) return
    const previousScale = card.style.scale
    const previousTransition = card.style.transition
    card.style.transition = "none"
    card.style.scale = "none"
    const rect = card.getBoundingClientRect()
    const cardStyle = getComputedStyle(card)
    const scale = Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--pb-corner-scale")) || 1
    const squircle = /squircle|superellipse/.test(cardStyle.getPropertyValue("corner-top-left-shape"))
    cardRadius = (Number.parseFloat(cardStyle.borderTopLeftRadius) || 0) / (squircle ? scale : 1)
    const image = card.querySelector(cardImageSlot)
    const imageHeight = image ? image.getBoundingClientRect().height : 0
    card.style.scale = previousScale
    void card.offsetWidth
    card.style.transition = previousTransition
    const header = popup.querySelector<HTMLElement>(headerImageSlot)
    size = { width: popup.offsetWidth || 1, height: popup.offsetHeight || 1, hero: header ? header.offsetHeight : 0 }
    from = { x: rect.left, y: rect.top, w: rect.width || 1, h: rect.height, hero: header ? (imageHeight * size.width) / (rect.width || 1) : 0 }
  }

  const render = (value: number) => {
    progress = value
    if (!popup) return
    const reveal = clamp(value, 0, 1)
    popup.style.visibility = ""
    card?.setAttribute("data-zooming", "")
    if (backdrop) backdrop.style.opacity = String(dimOpacity * reveal)
    const content = String(clamp((value - fadeStart) / (fadeEnd - fadeStart), 0, 1))
    popup.style.willChange = "transform, clip-path, opacity"
    if (reducedMotion()) {
      popup.style.opacity = String(reveal)
      popup.style.transform = ""
      popup.style.clipPath = ""
      popup.style.setProperty("--zoom-content", "1")
      return
    }
    const { width, height, hero } = size
    const frameWidth = lerp(from.w, width, value)
    const frameHeight = lerp(from.h, height, value)
    const scale = frameWidth / width
    const radius = Math.max(0, lerp(cardRadius, 0, reveal))
    const shown = lerp(from.hero, hero, value)
    popup.style.transform = `translate(${lerp(from.x, 0, value)}px, ${lerp(from.y, 0, value)}px) scale(${scale})`
    popup.style.clipPath = `inset(0 0 ${Math.max(0, height - frameHeight / scale)}px 0 round ${radius / scale}px)`
    popup.style.background = `color-mix(in srgb, var(--pb-bg) ${Math.round(clamp(value / solidAt, 0, 1) * 100)}%, transparent)`
    popup.style.setProperty("--zoom-hero-height", `${shown}px`)
    popup.style.setProperty("--zoom-lift", `${hero ? shown - hero : 0}px`)
    popup.style.setProperty("--zoom-content", content)
  }

  const rest = () => {
    if (!popup) return
    for (const property of ["transform", "clip-path", "background", "will-change", "opacity"]) popup.style.removeProperty(property)
    for (const property of ["--zoom-hero-height", "--zoom-lift", "--zoom-content"]) popup.style.removeProperty(property)
    if (backdrop) backdrop.style.opacity = String(dimOpacity)
  }

  const stop = () => {
    settling?.stop()
    settling = null
  }

  const tween = (to: number, onDone: () => void): Settle => {
    const start = progress
    const duration = readDuration(popup ? getComputedStyle(popup).getPropertyValue("--pb-dur-base") : "")
    const begin = performance.now()
    let frame = requestAnimationFrame(tick)
    function tick(now: number) {
      const amount = clamp((now - begin) / duration, 0, 1)
      render(lerp(start, to, 1 - (1 - amount) ** 3))
      if (amount >= 1) onDone()
      else frame = requestAnimationFrame(tick)
    }
    return { stop: () => cancelAnimationFrame(frame) }
  }

  const finish = (to: number) => {
    settling = null
    target = null
    tracker = createVelocityTracker()
    if (to === 1) {
      rest()
      return
    }
    render(0)
    if (popup) popup.style.visibility = "hidden"
    card?.removeAttribute("data-zooming")
    if (backdrop) backdrop.style.opacity = "0"
    callbacks.closed()
  }

  const settle = (to: number, velocity = tracker.velocity()) => {
    stop()
    target = to
    if (!popup) {
      pending = to === 1 ? 1 : null
      return
    }
    if (to === 0) {
      const scroller = popup.querySelector<HTMLElement>(scrollerSlot)
      if (scroller) scroller.scrollTop = 0
      measure()
    }
    const update = (value: number) => {
      tracker.add(value)
      render(value)
    }
    settling = reducedMotion()
      ? tween(to, () => finish(to))
      : settleSpring(progress, to, velocity, update, () => finish(to), { restSpeed: 0.01, restDistance: 0.001 })
  }

  const attach = (element: HTMLElement) => {
    popup = element
    measure()
    render(progress)
    const frame = requestAnimationFrame(() => {
      measure()
      render(progress)
    })
    if (pending !== null) {
      const target = pending
      pending = null
      settle(target)
    }
    const onResize = () => {
      measure()
      if (!settling && progress === 1) return
      render(progress)
    }
    window.addEventListener("resize", onResize)
    return () => {
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", onResize)
      if (settling && target === 1) pending = 1
      stop()
      card?.removeAttribute("data-zooming")
      popup = null
      progress = 0
    }
  }

  const bindEdgeDrag = (element: HTMLElement) => {
    let origin: { id: number; x: number; y: number; progress: number } | null = null
    let dragging = false
    let dragTracker = createVelocityTracker()
    let lastMoveAt = 0
    const spanOf = () => size.width * dragSpan

    const onDown = (event: PointerEvent) => {
      if (!event.isPrimary || (event.pointerType === "mouse" && event.button !== 0)) return
      if (event.clientX > edgeWidth) return
      const grabbed = settling !== null
      stop()
      origin = { id: event.pointerId, x: event.clientX, y: event.clientY, progress }
      dragTracker = createVelocityTracker()
      dragTracker.add(event.clientX)
      lastMoveAt = performance.now()
      dragging = grabbed
      if (grabbed) {
        element.setPointerCapture(event.pointerId)
        element.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 (!dragging) {
        if (Math.abs(dx) > lockDistance && dx > lockRatio * Math.abs(dy)) {
          dragging = true
          element.setPointerCapture(event.pointerId)
          element.style.userSelect = "none"
        } else if (Math.abs(dy) > lockDistance) {
          origin = null
          return
        } else return
      }
      dragTracker.add(event.clientX)
      lastMoveAt = performance.now()
      render(clamp(origin.progress - dx / spanOf(), 0, 1))
    }
    const onEnd = (event: PointerEvent) => {
      if (!origin || event.pointerId !== origin.id) return
      const wasDragging = dragging
      origin = null
      dragging = false
      element.style.removeProperty("user-select")
      if (!wasDragging) return
      const velocity = performance.now() - lastMoveAt > velocityWindowMs ? 0 : dragTracker.velocity()
      const closing = event.type === "pointerup" && (progress < closeBelow || velocity > flingSpeed)
      settle(closing ? 0 : 1, -velocity / spanOf())
    }
    element.addEventListener("pointerdown", onDown)
    element.addEventListener("pointermove", onMove)
    element.addEventListener("pointerup", onEnd)
    element.addEventListener("pointercancel", onEnd)
    return () => {
      element.removeEventListener("pointerdown", onDown)
      element.removeEventListener("pointermove", onMove)
      element.removeEventListener("pointerup", onEnd)
      element.removeEventListener("pointercancel", onEnd)
    }
  }

  return {
    callbacks,
    settle,
    bindEdgeDrag,
    attach,
    setBackdrop: (element: HTMLElement | null) => {
      backdrop = element
    },
    setCard: (element: HTMLElement | null) => {
      card = element
    },
    isMounted: () => popup !== null,
    cancelPending: () => {
      pending = null
    },
  }
}

type Zoom = ReturnType<typeof createZoom>

type ZoomOpenContextValue = {
  cardRef: RefObject<HTMLElement | null>
  zoom: Zoom
  open: boolean
  mounted: boolean
  setOpen: (open: boolean) => void
}

const ZoomOpenContext = createContext<ZoomOpenContextValue | null>(null)

function useZoomOpen() {
  const context = useContext(ZoomOpenContext)
  if (!context) throw new Error("Zoom open parts must be used inside <ZoomOpen>")
  return context
}

export type ZoomOpenProps = {
  open?: boolean
  defaultOpen?: boolean
  onOpenChange?: (open: boolean) => void
  children?: ReactNode
}

export function ZoomOpen({ open: openProp, defaultOpen = false, onOpenChange, children }: ZoomOpenProps) {
  const [ownOpen, setOwnOpen] = useState(defaultOpen)
  const [mounted, setMounted] = useState(false)
  const cardRef = useRef<HTMLElement | null>(null)
  const zoomRef = useRef<Zoom | null>(null)
  zoomRef.current ??= createZoom()
  const zoom = zoomRef.current
  const controlled = openProp !== undefined
  const open = controlled ? openProp : ownOpen
  const setOpen = (next: boolean) => {
    if (!controlled) setOwnOpen(next)
    onOpenChange?.(next)
  }
  const latest = useRef({ open, setOpen })
  latest.current = { open, setOpen }

  zoom.callbacks.closed = () => {
    setMounted(false)
    if (latest.current.open) latest.current.setOpen(false)
  }

  useEffect(() => {
    zoom.setCard(cardRef.current)
    if (open) {
      setMounted(true)
      zoom.settle(1)
      return
    }
    if (zoom.isMounted()) zoom.settle(0)
    else zoom.cancelPending()
  }, [open, zoom])

  return <ZoomOpenContext value={{ cardRef, zoom, open, mounted, setOpen }}>{children}</ZoomOpenContext>
}

export type ZoomOpenCardProps = Omit<useRender.ComponentProps<"button">, "className"> & { className?: string }

export function ZoomOpenCard({ render, className, onClick, ref, ...props }: ZoomOpenCardProps) {
  const { cardRef, zoom, open, setOpen } = useZoomOpen()
  const setRef = useCallback(
    (element: HTMLElement | null) => {
      cardRef.current = element
      zoom.setCard(element)
    },
    [cardRef, zoom],
  )
  const dataAttributes = { "data-slot": "zoom-open-card" }
  return useRender({
    defaultTagName: "button",
    render,
    ref: ref ? [ref, setRef] : setRef,
    props: mergeProps<"button">(
      {
        ...dataAttributes,
        type: render ? undefined : "button",
        "aria-haspopup": "dialog",
        "aria-expanded": open,
        onClick: (event: React.MouseEvent<HTMLButtonElement>) => {
          event.preventDefault()
          zoom.setCard(event.currentTarget)
          setOpen(true)
        },
        className: cn(
          "on-surface flex w-full flex-col cursor-pointer overflow-hidden rounded-lg bg-surface text-left text-ink [&[data-zooming]_[data-slot=zoom-open-card-image]]:opacity-0",
          "transition-transform duration-spring ease-spring active:scale-press active:duration-[90ms] [-webkit-tap-highlight-color:transparent]",
          className,
        ),
      },
      { ...props, onClick },
    ),
  })
}

export type ZoomOpenCardImageProps = Omit<ComponentProps<"span">, "className"> & { className?: string }

export function ZoomOpenCardImage({ className, ...props }: ZoomOpenCardImageProps) {
  return (
    <span data-slot="zoom-open-card-image" className={cn("block h-24 w-full overflow-hidden [&_img]:size-full [&_img]:object-cover", className)} {...props} />
  )
}

export type ZoomOpenScreenProps = Omit<Dialog.Popup.Props, "className" | "finalFocus"> & {
  backLabel?: ReactNode
  className?: string
}

export function ZoomOpenScreen({ backLabel = "Back", className, children, ...props }: ZoomOpenScreenProps) {
  const { cardRef, zoom, mounted, setOpen } = useZoomOpen()
  const popupRef = useCallback(
    (element: HTMLDivElement | null) => {
      if (!element) return
      const detach = zoom.attach(element)
      const unbind = zoom.bindEdgeDrag(element)
      return () => {
        unbind()
        detach()
      }
    },
    [zoom],
  )
  const backdropRef = useCallback(
    (element: HTMLDivElement | null) => {
      zoom.setBackdrop(element)
    },
    [zoom],
  )
  return (
    <Dialog.Root
      open={mounted}
      onOpenChange={(next) => {
        if (!next) setOpen(false)
      }}
    >
      <Dialog.Portal>
        <Dialog.Backdrop ref={backdropRef} data-slot="zoom-open-backdrop" className="fixed inset-0 z-50 bg-black opacity-0" />
        <Dialog.Popup
          {...props}
          ref={popupRef}
          finalFocus={cardRef}
          aria-modal="true"
          data-slot="zoom-open-screen"
          className={cn("on-bg fixed inset-0 z-50 origin-top-left touch-pan-y overflow-hidden bg-bg text-ink outline-none", className)}
        >
          <div data-slot="zoom-open-scroller" className="h-full overflow-x-hidden overflow-y-auto overscroll-contain">
            {children}
          </div>
          <div
            data-slot="zoom-open-bar"
            className="pointer-events-none absolute inset-x-0 top-0 z-10 pt-[max(12px,env(safe-area-inset-top))] opacity-[var(--zoom-content,1)]"
          >
            <div className="mx-auto max-w-app px-gutter">
              <Dialog.Close
                data-slot="zoom-open-back"
                render={
                  <BackButton className="pointer-events-auto ml-0 rounded-full bg-bg/80 pr-3.5 pl-2 backdrop-blur-md [@media(prefers-reduced-transparency:reduce)]:backdrop-blur-none" />
                }
              >
                {backLabel}
              </Dialog.Close>
            </div>
          </div>
        </Dialog.Popup>
      </Dialog.Portal>
    </Dialog.Root>
  )
}

export type ZoomOpenHeaderImageProps = Omit<ComponentProps<"div">, "className"> & { className?: string }

export function ZoomOpenHeaderImage({ className, children, ...props }: ZoomOpenHeaderImageProps) {
  return (
    <div data-slot="zoom-open-header-image" className={cn("relative z-1 h-[clamp(220px,32vw,420px)] w-full", className)} {...props}>
      <div
        data-slot="zoom-open-header-picture"
        className="absolute inset-x-0 top-0 h-(--zoom-hero-height,100%) overflow-hidden [&_img]:size-full [&_img]:object-cover"
      >
        {children}
      </div>
    </div>
  )
}

export type ZoomOpenContentProps = Omit<ComponentProps<"div">, "className"> & { className?: string }

export function ZoomOpenContent({ className, ...props }: ZoomOpenContentProps) {
  return (
    <div
      data-slot="zoom-open-content"
      className={cn("mx-auto w-full max-w-app p-gutter opacity-[var(--zoom-content,1)] [transform:translateY(var(--zoom-lift,0px))]", className)}
      {...props}
    />
  )
}

export type ZoomOpenTitleProps = Omit<Dialog.Title.Props, "className"> & { className?: string }

export function ZoomOpenTitle({ className, ...props }: ZoomOpenTitleProps) {
  return <Dialog.Title data-slot="zoom-open-title" className={cn("text-title1 font-bold text-ink", className)} {...props} />
}

export type ZoomOpenDescriptionProps = Omit<Dialog.Description.Props, "className"> & { className?: string }

export function ZoomOpenDescription({ className, ...props }: ZoomOpenDescriptionProps) {
  return <Dialog.Description data-slot="zoom-open-description" className={cn("text-body text-ink-2", className)} {...props} />
}
```
