{
  "schemaVersion": 1,
  "target": "react",
  "name": "view-stack",
  "version": "0.1.0",
  "category": "core",
  "title": "View Stack",
  "description": "Multi-step panels for a popover, dialog, or card that push and pop with a short blurred slide while the height eases to the new view.",
  "tags": [
    "navigation",
    "multi-step",
    "drill-in",
    "popover",
    "dialog",
    "panel",
    "motion"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/view-stack",
  "props": [
    {
      "name": "children",
      "type": "View elements",
      "description": "ViewStack: the views. The first is the root unless initialView names another."
    },
    {
      "name": "initialView",
      "type": "string",
      "description": "ViewStack: name of the view to start on."
    },
    {
      "name": "onStackChange",
      "type": "(stack: string[]) => void",
      "description": "ViewStack: called with the open view names after each push and pop."
    },
    {
      "name": "backLabel",
      "type": "string",
      "default": "\"Back to <previous title>\"",
      "description": "ViewStack: accessible name of the Back button."
    },
    {
      "name": "name",
      "type": "string",
      "description": "View: unique name used by push and ViewLink to."
    },
    {
      "name": "title / description",
      "type": "ReactNode",
      "description": "View: heading and supporting text. Focus moves to the heading when the view opens."
    },
    {
      "name": "to",
      "type": "string",
      "description": "ViewLink: the view to open."
    },
    {
      "name": "icon / meta",
      "type": "ReactNode",
      "description": "ViewLink: a 16px icon before the label, and trailing text such as the current value."
    },
    {
      "name": "useViewStack()",
      "type": "{ push, pop, reset, current, depth, stack }",
      "description": "Hook for any element inside a view, for example to go back after picking an option."
    }
  ],
  "accessibility": [
    "Pushing a view moves focus to its heading; going back returns focus to the control that opened the view.",
    "Escape goes back one view and stops there, so a surrounding Popover or Dialog stays open; on the root view Escape is left to them.",
    "The Back button is a labeled button (\"Back to Share run\") that is removed from the tab order on the root view.",
    "Views below the top of the stack stay mounted, keeping their state, but are inert and hidden, so focus and screen readers only reach the current view.",
    "With reduced motion preferred, views swap and the height changes instantly."
  ],
  "states": [
    "root",
    "pushed",
    "nested",
    "in popover",
    "in dialog"
  ],
  "files": [
    {
      "path": "ui/view-stack.tsx",
      "content": "\"use client\";\n\nimport { AnimatePresence, animate, motion, useReducedMotion, type AnimationPlaybackControls, type Variants } from \"motion/react\";\nimport {\n  Children,\n  type ComponentProps,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = [0.23, 1, 0.32, 1] as const;\n\n/** Reduced-motion preference, read only after hydration so server and client render the same markup first. */\nfunction useReducedMotionAfterMount() {\n  const reduce = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && reduce === true;\n}\n\ninterface StackContextValue {\n  /** Names of the open views, root first. */\n  stack: string[];\n  /** The view on top. */\n  current: string;\n  /** 0 on the root view. */\n  depth: number;\n  /** Opens a view on top of the current one. */\n  push: (name: string) => void;\n  /** Goes back one view. Does nothing on the root view. */\n  pop: () => void;\n  /** Goes back to the root view. */\n  reset: () => void;\n}\n\nconst StackContext = createContext<StackContextValue | null>(null);\nconst FrameContext = createContext<{ index: number }>({ index: 0 });\n\n/** Reads and drives the nearest ViewStack: `push`, `pop`, `reset`, the `current` view and the `depth`. */\nexport function useViewStack() {\n  const context = useContext(StackContext);\n  if (!context) throw new Error(\"useViewStack must be used inside a ViewStack.\");\n  return context;\n}\n\nexport interface ViewProps extends Omit<ComponentProps<\"div\">, \"title\"> {\n  /** Unique name, used by `push` and ViewLink `to`. */\n  name: string;\n  /** Heading of the view. Focus moves here when the view opens, and the Back button names it. */\n  title?: ReactNode;\n  /** Supporting text under the heading. */\n  description?: ReactNode;\n}\n\n/** One page of a ViewStack. Only the views on the stack are mounted. */\nexport function View({ name: _name, title, description, className, children, ...props }: ViewProps) {\n  const { index } = useContext(FrameContext);\n  return (\n    <div className={cx(\"grid gap-3\", className)} {...props}>\n      {title || description ? (\n        <div className={cx(\"grid min-h-7 content-center gap-0.5\", index > 0 && \"pl-7\")}>\n          {title ? (\n            <h2 tabIndex={-1} data-view-heading=\"\" className=\"text-sm leading-5 font-semibold text-zinc-950 outline-none dark:text-white\">\n              {title}\n            </h2>\n          ) : null}\n          {description ? <p className=\"text-sm leading-5 text-zinc-600 dark:text-zinc-400\">{description}</p> : null}\n        </div>\n      ) : null}\n      {children}\n    </div>\n  );\n}\n\nexport interface ViewLinkProps extends ComponentProps<\"button\"> {\n  /** Name of the view to open. */\n  to: string;\n  /** A 16px icon before the label. */\n  icon?: ReactNode;\n  /** Trailing secondary text, such as the current value of a setting. */\n  meta?: ReactNode;\n}\n\n/** A row that opens another view, with a chevron that nudges toward where the next view comes from. */\nexport function ViewLink({ to, icon, meta, className, children, onClick, type = \"button\", ...props }: ViewLinkProps) {\n  const { push } = useViewStack();\n  return (\n    <button\n      type={type}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) push(to);\n      }}\n      className={cx(\n        \"group/view-link -mx-2 flex h-9 cursor-default items-center gap-2.5 rounded-lg px-2 text-left text-sm text-zinc-700 select-none dark:text-zinc-300\",\n        \"transition-colors duration-150 ease-out motion-reduce:transition-none\",\n        \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n        \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n        \"[&_svg]:size-4 [&_svg]:shrink-0\",\n        className,\n      )}\n      {...props}\n    >\n      {icon ? (\n        <span className=\"flex text-zinc-500 group-hover/view-link:text-zinc-950 dark:group-hover/view-link:text-white\">{icon}</span>\n      ) : null}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {meta ? <span className=\"truncate text-xs text-zinc-500\">{meta}</span> : null}\n      <svg\n        aria-hidden=\"true\"\n        viewBox=\"0 0 16 16\"\n        fill=\"none\"\n        className=\"text-zinc-400 transition-transform duration-150 ease-out group-hover/view-link:translate-x-0.5 motion-reduce:transition-none dark:text-zinc-500\"\n      >\n        <path d=\"m6 4 4 4-4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n      </svg>\n    </button>\n  );\n}\n\nexport interface ViewStackProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** View elements. The first one is the root unless `initialView` names another. */\n  children: ReactNode;\n  /** Name of the view to start on. */\n  initialView?: string;\n  /** Called with the names of the open views after every push and pop. */\n  onStackChange?: (stack: string[]) => void;\n  /** Accessible name of the Back button. Defaults to \"Back to <previous title>\" when that title is text. */\n  backLabel?: string;\n}\n\n// Push: the new view comes in from 14px right while the old one drifts 10px left; both blur a\n// little so the direction reads without a long slide. Pop mirrors it.\nconst frameVariants: Variants = {\n  enter: (direction: number) => ({ x: direction > 0 ? 14 : -10, opacity: 0, filter: \"blur(4px)\" }),\n  current: { x: 0, opacity: 1, filter: \"blur(0px)\", visibility: \"visible\", transition: { duration: 0.28, ease } },\n  covered: { x: -10, opacity: 0, filter: \"blur(4px)\", transition: { duration: 0.2, ease }, transitionEnd: { visibility: \"hidden\" } },\n  exit: { x: 14, opacity: 0, filter: \"blur(4px)\", transition: { duration: 0.2, ease } },\n};\n\nconst stillVariants: Variants = {\n  enter: { opacity: 0 },\n  current: { opacity: 1, visibility: \"visible\", transition: { duration: 0 } },\n  covered: { opacity: 0, transition: { duration: 0 }, transitionEnd: { visibility: \"hidden\" } },\n  exit: { opacity: 0, transition: { duration: 0 } },\n};\n\n/**\n * Multi-step panels for a popover, dialog or card. Views push and pop with a short blurred slide,\n * the container height eases to the new view, a Back button fades in past the root, focus moves\n * to the new view's heading, and Escape or Back goes back one view (Escape on the root view is\n * left to the surrounding popover or dialog).\n */\nexport function ViewStack({ children, initialView, onStackChange, backLabel, className, ...props }: ViewStackProps) {\n  const views = useMemo(() => {\n    const map = new Map<string, ReactElement<ViewProps>>();\n    Children.forEach(children, (child) => {\n      if (isValidElement<ViewProps>(child) && typeof child.props.name === \"string\") map.set(child.props.name, child);\n    });\n    return map;\n  }, [children]);\n\n  const rootName = initialView ?? views.keys().next().value ?? \"\";\n  const [stack, setStack] = useState<string[]>([rootName]);\n  const [direction, setDirection] = useState(1);\n  const reduceMotion = useReducedMotionAfterMount();\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  const fromHeight = useRef<number | null>(null);\n  const heightAnimation = useRef<AnimationPlaybackControls | null>(null);\n  // The control that opened each view, so going back returns focus to it.\n  const openers = useRef<(HTMLElement | null)[]>([]);\n  const navigated = useRef<\"push\" | \"pop\" | null>(null);\n\n  const change = useCallback((next: (stack: string[]) => string[], kind: \"push\" | \"pop\") => {\n    setStack((previous) => {\n      const updated = next(previous);\n      if (updated === previous) return previous;\n      if (viewportRef.current) fromHeight.current = viewportRef.current.getBoundingClientRect().height;\n      navigated.current = kind;\n      return updated;\n    });\n    setDirection(kind === \"push\" ? 1 : -1);\n  }, []);\n\n  const pendingOpener = useRef<HTMLElement | null>(null);\n  const push = useCallback(\n    (name: string) => {\n      pendingOpener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n      change((previous) => (previous[previous.length - 1] === name ? previous : [...previous, name]), \"push\");\n    },\n    [change],\n  );\n  const pop = useCallback(() => change((previous) => (previous.length > 1 ? previous.slice(0, -1) : previous), \"pop\"), [change]);\n  const reset = useCallback(() => change((previous) => (previous.length > 1 ? previous.slice(0, 1) : previous), \"pop\"), [change]);\n\n  const depth = stack.length - 1;\n  const current = stack[depth] ?? rootName;\n\n  useEffect(() => {\n    if (navigated.current) onStackChange?.(stack);\n    // Only report changes the user made, not the first render.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [stack]);\n\n  // After a push or pop: animate the height from the old view to the new one, then move focus.\n  useLayoutEffect(() => {\n    const kind = navigated.current;\n    if (!kind) return;\n    navigated.current = null;\n\n    const viewport = viewportRef.current;\n    const content = contentRef.current;\n    const from = fromHeight.current;\n    fromHeight.current = null;\n    if (viewport && content && from != null && !reduceMotion) {\n      heightAnimation.current?.stop();\n      const to = content.getBoundingClientRect().height;\n      if (Math.abs(to - from) > 0.5) {\n        const controls = animate(viewport, { height: [from, to] }, { duration: 0.3, ease });\n        heightAnimation.current = controls;\n        // Back to auto height so content that grows inside a view is never clipped.\n        void controls.then(() => {\n          if (heightAnimation.current === controls) viewport.style.height = \"\";\n        });\n      } else {\n        viewport.style.height = \"\";\n      }\n    }\n\n    const frame = content?.querySelector<HTMLElement>(\"[data-view-frame][data-current]\");\n    // A view coming back from under the stack is still hidden from its covered state; show it now\n    // so it can take focus before its animation starts.\n    if (frame) frame.style.visibility = \"visible\";\n    let target: HTMLElement | null = null;\n    if (kind === \"push\") {\n      openers.current.push(pendingOpener.current);\n      pendingOpener.current = null;\n    } else {\n      while (openers.current.length > stack.length - 1) target = openers.current.pop() ?? null;\n      if (target && (!target.isConnected || !rootRef.current?.contains(target))) target = null;\n    }\n    target ??= frame?.querySelector<HTMLElement>(\"[data-view-heading]\") ?? frame ?? null;\n    target?.focus({ preventScroll: true });\n  }, [stack, reduceMotion]);\n\n  // Escape goes back one view and stops there, so the popover or dialog around it stays open.\n  // A native listener on the root runs before listeners on the document.\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.key !== \"Escape\" || event.defaultPrevented || stack.length < 2) return;\n      event.preventDefault();\n      event.stopPropagation();\n      pop();\n    };\n    root.addEventListener(\"keydown\", onKeyDown);\n    return () => root.removeEventListener(\"keydown\", onKeyDown);\n  }, [stack.length, pop]);\n\n  const previousTitle = depth > 0 ? views.get(stack[depth - 1] ?? \"\")?.props.title : undefined;\n  const back = backLabel ?? (typeof previousTitle === \"string\" ? `Back to ${previousTitle}` : \"Back\");\n  const context = useMemo<StackContextValue>(\n    () => ({ stack, current, depth, push, pop, reset }),\n    [stack, current, depth, push, pop, reset],\n  );\n  const variants = reduceMotion ? stillVariants : frameVariants;\n\n  return (\n    <StackContext.Provider value={context}>\n      <div ref={rootRef} data-depth={depth} className={cx(\"relative\", className)} {...props}>\n        <button\n          type=\"button\"\n          aria-label={back}\n          tabIndex={depth > 0 ? 0 : -1}\n          aria-hidden={depth > 0 ? undefined : true}\n          onClick={pop}\n          className={cx(\n            \"absolute top-0 -left-1.5 z-10 flex size-7 cursor-default items-center justify-center rounded-lg text-zinc-500\",\n            \"transition-[opacity,translate,background-color,color] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n            \"hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            depth > 0 ? \"translate-x-0 opacity-100\" : \"pointer-events-none translate-x-1 opacity-0\",\n          )}\n        >\n          <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n            <path d=\"m10 4-4 4 4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n          </svg>\n        </button>\n        {/* Clips only vertically, so the blurred edge of a sliding view is not cut at the sides. */}\n        <div ref={viewportRef} className=\"relative overflow-x-visible overflow-y-clip\">\n          <div ref={contentRef} className=\"relative\">\n            <AnimatePresence initial={false} custom={direction} mode=\"popLayout\">\n              {stack.map((name, index) => {\n                const isCurrent = index === depth;\n                return (\n                  <motion.div\n                    key={`${index}:${name}`}\n                    data-view-frame=\"\"\n                    data-current={isCurrent ? \"\" : undefined}\n                    custom={direction}\n                    variants={variants}\n                    initial=\"enter\"\n                    animate={isCurrent ? \"current\" : \"covered\"}\n                    exit=\"exit\"\n                    inert={!isCurrent}\n                    tabIndex={-1}\n                    className={cx(\"outline-none\", !isCurrent && \"absolute inset-x-0 top-0\")}\n                  >\n                    <FrameContext.Provider value={{ index }}>{views.get(name) ?? null}</FrameContext.Provider>\n                  </motion.div>\n                );\n              })}\n            </AnimatePresence>\n          </div>\n        </div>\n      </div>\n    </StackContext.Provider>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { View, ViewLink, ViewStack, useViewStack } from \"@/components/shaken/ui/view-stack\";\n\nconst accessOptions = [\n  { value: \"invited\", label: \"Only invited people\", hint: \"Nobody else can open it\" },\n  { value: \"workspace\", label: \"Anyone in Northwind\", hint: \"Members can view and comment\" },\n  { value: \"link\", label: \"Anyone with the link\", hint: \"No sign-in needed to view\" },\n];\n\nconst formats = [\"JSON\", \"Markdown\", \"OpenTelemetry\"];\n\nfunction Check() {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4 text-zinc-950 dark:text-white\">\n      <path d=\"M3.5 8.5 6.5 11.5 12.5 4.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nconst optionRow =\n  \"-mx-2 flex cursor-default items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 dark:hover:bg-white/[0.06]\";\n\n/** Choosing an option goes back to the previous view, where the new value shows. */\nfunction Options({\n  options,\n  value,\n  onChange,\n}: {\n  options: { value: string; label: string; hint?: string }[];\n  value: string;\n  onChange: (value: string) => void;\n}) {\n  const { pop } = useViewStack();\n  return (\n    <div className=\"grid\">\n      {options.map((option) => (\n        <button\n          key={option.value}\n          type=\"button\"\n          aria-pressed={option.value === value}\n          onClick={() => {\n            onChange(option.value);\n            pop();\n          }}\n          className={optionRow}\n        >\n          <span className=\"grid min-w-0 flex-1\">\n            <span className=\"text-sm text-zinc-950 dark:text-white\">{option.label}</span>\n            {option.hint ? <span className=\"text-xs text-zinc-500\">{option.hint}</span> : null}\n          </span>\n          {option.value === value ? <Check /> : null}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nexport default function ViewStackExample() {\n  const [access, setAccess] = useState(\"workspace\");\n  const [format, setFormat] = useState(\"JSON\");\n  const [toolOutputs, setToolOutputs] = useState(true);\n  const accessLabel = accessOptions.find((option) => option.value === access)?.label ?? \"\";\n\n  return (\n    <div className=\"w-full max-w-72 rounded-xl border border-zinc-950/10 bg-white p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\">\n      <ViewStack>\n        <View name=\"share\" title=\"Share run\" description=\"deploy-preview-482\">\n          <div className=\"grid\">\n            <ViewLink to=\"access\" meta={access === \"workspace\" ? \"Workspace\" : access === \"link\" ? \"Public\" : \"Invited\"}>\n              Link access\n            </ViewLink>\n            <ViewLink to=\"export\" meta={format}>\n              Export trace\n            </ViewLink>\n          </div>\n        </View>\n        <View name=\"access\" title=\"Link access\" description={accessLabel}>\n          <Options options={accessOptions} value={access} onChange={setAccess} />\n        </View>\n        <View name=\"export\" title=\"Export trace\">\n          <div className=\"grid\">\n            <ViewLink to=\"format\" meta={format}>\n              Format\n            </ViewLink>\n            <button type=\"button\" aria-pressed={toolOutputs} onClick={() => setToolOutputs((value) => !value)} className={optionRow}>\n              <span className=\"flex-1 text-sm text-zinc-700 dark:text-zinc-300\">Include tool outputs</span>\n              {toolOutputs ? <Check /> : null}\n            </button>\n          </div>\n          <button\n            type=\"button\"\n            className=\"inline-flex h-8 items-center justify-center rounded-lg bg-zinc-950 px-3 text-sm font-medium text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] transition-colors duration-150 ease-out hover:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:bg-white dark:text-black dark:hover:bg-zinc-200\"\n          >\n            Download {format}\n          </button>\n        </View>\n        <View name=\"format\" title=\"Format\">\n          <Options options={formats.map((value) => ({ value, label: value }))} value={format} onChange={setFormat} />\n        </View>\n      </ViewStack>\n    </div>\n  );\n}\n"
  }
}
