{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"dynamic-island","type":"registry:component","title":"Dynamic island","description":"Morphs between live states with a springy, Apple-style bounce.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/dynamic-island.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion, useIsPresent } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type IslandState = \"idle\" | \"timer\" | \"music\" | \"ring\";\n\n// Pills keep radius at half their height; the expanded card uses a softer\n// corner so it reads as a card, not a capsule.\nconst SHAPES: Record<\n  IslandState,\n  { width: number; height: number; radius: number }\n> = {\n  idle: { width: 156, height: 42, radius: 21 },\n  timer: { width: 260, height: 46, radius: 23 },\n  ring: { width: 220, height: 46, radius: 23 },\n  music: { width: 390, height: 100, radius: 36 },\n};\n\nconst MAX_HEIGHT = Math.max(...Object.values(SHAPES).map((s) => s.height));\n// The widest shape is wider than a phone's content column; this caps the\n// island and its content at the viewport minus the page gutters instead.\nconst MAX_WIDTH = \"calc(100vw - 2rem)\";\n\n// The island is the playful exception: a bounce of 0.25 gives it the\n// elastic settle Apple uses. It runs past the 300ms norm because the\n// overshoot needs time to read; the content fade stays well under it.\nconst MORPH = { type: \"spring\", visualDuration: 0.4, bounce: 0.25 } as const;\nconst MORPH_REDUCED = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n\n// Keyframes are right here: the equalizer is an endless loop nothing\n// interrupts. Pausing freezes the bars in place rather than snapping them.\nconst CSS = `\n@keyframes dynamic-island-eq {\n  from { scale: 1 0.3; }\n  to { scale: 1 1; }\n}\n.dynamic-island-eq > span {\n  transform-origin: bottom;\n  animation: dynamic-island-eq ease-in-out infinite alternate;\n}\n.dynamic-island-eq[data-playing=\"false\"] > span {\n  animation-play-state: paused;\n}\n@media (prefers-reduced-motion: reduce) {\n  .dynamic-island-eq > span { animation: none; }\n}\n`;\n\n// Uneven durations and negative delays so the bars never fall into step.\n// `rest` is the static height shown under reduced motion.\nconst BARS = [\n  { duration: 520, delay: -120, rest: 0.55 },\n  { duration: 760, delay: -400, rest: 0.9 },\n  { duration: 610, delay: -250, rest: 0.4 },\n  { duration: 840, delay: -600, rest: 0.7 },\n];\n\nfunction pad(n: number) {\n  return String(n).padStart(2, \"0\");\n}\n\nexport function formatElapsed(seconds: number) {\n  return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}`;\n}\n\nexport function describeIsland(\n  state: IslandState,\n  { elapsed = 0, title = \"\", playing = false } = {},\n) {\n  if (state === \"timer\")\n    return `Timer, ${Math.floor(elapsed / 60)}:${pad(elapsed % 60)}`;\n  if (state === \"music\") return `${playing ? \"Playing\" : \"Paused\"}, ${title}`;\n  if (state === \"ring\") return \"Ringer on\";\n  return \"Idle\";\n}\n\nexport function DynamicIsland({\n  state,\n  elapsed = 0,\n  title = \"Midnight City\",\n  artist = \"M83\",\n  playing = true,\n  onPlayingChange,\n  className,\n}: {\n  state: IslandState;\n  elapsed?: number;\n  title?: string;\n  artist?: string;\n  playing?: boolean;\n  onPlayingChange?: (playing: boolean) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const shape = SHAPES[state];\n\n  return (\n    // Fixed to the tallest state and anchored at the top, so the island\n    // grows down and out symmetrically and nothing below it ever moves.\n    <div\n      className={cn(\"flex w-full justify-center\", className)}\n      style={{ height: MAX_HEIGHT }}\n    >\n      <style href=\"dynamic-island\" precedence=\"default\">\n        {CSS}\n      </style>\n      <motion.div\n        initial={false}\n        animate={{\n          width: shape.width,\n          height: shape.height,\n          borderRadius: shape.radius,\n        }}\n        transition={reduceMotion ? MORPH_REDUCED : MORPH}\n        style={{ maxWidth: MAX_WIDTH }}\n        className=\"relative overflow-hidden bg-foreground text-background\"\n      >\n        <AnimatePresence initial={false}>\n          <Content key={state} state={state} reduceMotion={reduceMotion}>\n            {state === \"idle\" && (\n              // A faint lens, like the camera sitting in the real cutout.\n              <span className=\"ml-auto size-3 rounded-full bg-background/15\" />\n            )}\n            {state === \"timer\" && (\n              <>\n                <svg\n                  viewBox=\"0 0 16 16\"\n                  className=\"size-5 shrink-0\"\n                  fill=\"none\"\n                  stroke=\"currentColor\"\n                  strokeWidth={2}\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                  aria-hidden\n                >\n                  <circle cx=\"8\" cy=\"9\" r=\"5.25\" />\n                  <path d=\"M8 6.5V9l1.5 1.25M6.5 1.75h3\" />\n                </svg>\n                <span className=\"ml-auto text-[15px] font-semibold tabular-nums\">\n                  {formatElapsed(elapsed)}\n                </span>\n              </>\n            )}\n            {state === \"ring\" && (\n              <>\n                <motion.svg\n                  viewBox=\"0 0 16 16\"\n                  className=\"size-5 shrink-0\"\n                  fill=\"none\"\n                  stroke=\"currentColor\"\n                  strokeWidth={1.5}\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                  aria-hidden\n                  // Swings from the hanger at the top, like a real bell.\n                  style={{ transformOrigin: \"50% 15%\" }}\n                  animate={\n                    reduceMotion ? undefined : { rotate: [0, -16, 13, -9, 5, 0] }\n                  }\n                  // One-shot and never interrupted, so keyframes fit. Waits\n                  // for the content fade so the wiggle is actually seen.\n                  transition={{ duration: 0.6, delay: 0.15, ease: \"easeInOut\" }}\n                >\n                  <path d=\"M4 11.25V7.5a4 4 0 0 1 8 0v3.75l1 1H3Z\" />\n                  <path d=\"M6.75 13.75a1.25 1.25 0 0 0 2.5 0\" />\n                </motion.svg>\n                <span className=\"ml-auto text-sm font-medium\">Ringer on</span>\n              </>\n            )}\n            {state === \"music\" && (\n              <>\n                <div className=\"flex min-w-0 flex-1 flex-col\">\n                  <span className=\"truncate text-[15px] font-semibold\">\n                    {title}\n                  </span>\n                  <span className=\"truncate text-sm text-background/60\">\n                    {artist}\n                  </span>\n                </div>\n                <span\n                  aria-hidden\n                  data-playing={playing}\n                  className=\"dynamic-island-eq flex h-5 items-end gap-1\"\n                >\n                  {BARS.map((bar, i) => (\n                    <span\n                      key={i}\n                      className=\"h-full w-1 rounded-full bg-background\"\n                      style={{\n                        scale: `1 ${bar.rest}`,\n                        animationDuration: `${bar.duration}ms`,\n                        animationDelay: `${bar.delay}ms`,\n                      }}\n                    />\n                  ))}\n                </span>\n                <button\n                  type=\"button\"\n                  aria-label={playing ? \"Pause\" : \"Play\"}\n                  onClick={() => onPlayingChange?.(!playing)}\n                  className=\"-mr-1.5 grid size-11 shrink-0 touch-manipulation place-items-center rounded-full outline-hidden transition-[scale,background-color] duration-150 ease-out hover:bg-background/10 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-background active:scale-[0.96] motion-reduce:transition-[background-color]\"\n                >\n                  <SwapIcon visible={!playing} reduceMotion={reduceMotion}>\n                    {/* Starts right of center so the triangle's mass, not its\n                        box, sits in the middle of the circle. */}\n                    <path d=\"M5.5 3.5v9l7-4.5Z\" fill=\"currentColor\" />\n                  </SwapIcon>\n                  <SwapIcon visible={playing} reduceMotion={reduceMotion}>\n                    <path d=\"M5 3.5v9M11 3.5v9\" />\n                  </SwapIcon>\n                </button>\n              </>\n            )}\n          </Content>\n        </AnimatePresence>\n      </motion.div>\n    </div>\n  );\n}\n\n// Each state's content is laid out at its own final size and centered, so\n// text never reflows or stretches while the pill morphs around it; the\n// pill's overflow clips it until the shape catches up.\nfunction Content({\n  state,\n  reduceMotion,\n  children,\n}: {\n  state: IslandState;\n  reduceMotion: boolean | null;\n  children: React.ReactNode;\n}) {\n  const present = useIsPresent();\n  const shape = SHAPES[state];\n  const hidden = reduceMotion\n    ? { opacity: 0 }\n    : { opacity: 0, filter: \"blur(4px)\", scale: 0.95 };\n  return (\n    <motion.div\n      initial={hidden}\n      animate={{ opacity: 1, filter: \"blur(0px)\", scale: 1 }}\n      // Old content clears out fast; the new one waits a beat so the two\n      // never read as overlapping text.\n      exit={{\n        opacity: 0,\n        filter: reduceMotion ? \"blur(0px)\" : \"blur(4px)\",\n        transition: { duration: 0.12, ease: EASE_OUT },\n      }}\n      transition={{ duration: 0.25, delay: 0.08, ease: EASE_OUT }}\n      className={cn(\n        \"absolute inset-x-0 top-0 mx-auto flex items-center gap-4\",\n        state === \"music\" ? \"px-6\" : \"px-[18px]\",\n        // Leaving content must never catch a click meant for the new state.\n        !present && \"pointer-events-none\",\n      )}\n      style={{ width: shape.width, height: shape.height, maxWidth: MAX_WIDTH }}\n    >\n      {children}\n    </motion.div>\n  );\n}\n\nfunction SwapIcon({\n  visible,\n  reduceMotion,\n  children,\n}: {\n  visible: boolean;\n  reduceMotion: boolean | null;\n  children: React.ReactNode;\n}) {\n  const hidden = reduceMotion\n    ? { opacity: 0 }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      className=\"col-start-1 row-start-1 size-5\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={2}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      aria-hidden\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={ICON_SWAP}\n    >\n      {children}\n    </motion.svg>\n  );\n}\n\nconst OPTIONS: { value: IslandState; label: string }[] = [\n  { value: \"idle\", label: \"Idle\" },\n  { value: \"timer\", label: \"Timer\" },\n  { value: \"music\", label: \"Music\" },\n  { value: \"ring\", label: \"Ring\" },\n];\n\nconst TITLE = \"Midnight City\";\n\nexport default function DynamicIslandDemo() {\n  const [state, setState] = useState<IslandState>(\"timer\");\n  // Starts partway in so the timer reads as already running.\n  const [elapsed, setElapsed] = useState(12);\n  const [playing, setPlaying] = useState(true);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const buttons = useRef(new Map<IslandState, HTMLButtonElement>());\n\n  useEffect(() => {\n    if (state !== \"timer\") return;\n    const id = setInterval(() => setElapsed((s) => s + 1), 1000);\n    return () => clearInterval(id);\n  }, [state]);\n\n  // Announced once per change rather than on every tick, so a screen\n  // reader is not read the clock every second.\n  const select = (next: IslandState) => {\n    setState(next);\n    setAnnouncement(describeIsland(next, { elapsed, title: TITLE, playing }));\n  };\n\n  const togglePlaying = (next: boolean) => {\n    setPlaying(next);\n    setAnnouncement(describeIsland(\"music\", { title: TITLE, playing: next }));\n  };\n\n  return (\n    <div className=\"flex w-[420px] max-w-full flex-col items-center gap-8\">\n      <DynamicIsland\n        state={state}\n        elapsed={elapsed}\n        title={TITLE}\n        playing={playing}\n        onPlayingChange={togglePlaying}\n      />\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n\n      <div\n        role=\"radiogroup\"\n        aria-label=\"Island state\"\n        className=\"flex gap-1 rounded-full bg-muted p-1.5 shadow-raised\"\n        onKeyDown={(e) => {\n          const index = OPTIONS.findIndex((o) => o.value === state);\n          const target = {\n            ArrowRight: index + 1,\n            ArrowDown: index + 1,\n            ArrowLeft: index - 1,\n            ArrowUp: index - 1,\n            Home: 0,\n            End: OPTIONS.length - 1,\n          }[e.key];\n          if (target === undefined) return;\n          e.preventDefault();\n          const next =\n            OPTIONS[(target + OPTIONS.length) % OPTIONS.length].value;\n          select(next);\n          buttons.current.get(next)?.focus();\n        }}\n      >\n        {OPTIONS.map((option) => {\n          const checked = option.value === state;\n          return (\n            <button\n              key={option.value}\n              ref={(el) => {\n                if (el) buttons.current.set(option.value, el);\n                else buttons.current.delete(option.value);\n              }}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={checked}\n              tabIndex={checked ? 0 : -1}\n              onClick={() => select(option.value)}\n              className={cn(\n                \"h-9 touch-manipulation rounded-full px-4 text-sm font-medium outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\",\n                checked\n                  ? \"bg-background text-foreground shadow-raised\"\n                  : \"text-muted-foreground hover:text-foreground\",\n              )}\n            >\n              {option.label}\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/dynamic-island"}