{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"collapsible-sidebar","type":"registry:component","title":"Collapsible sidebar","description":"Folds down to an icon rail, with labels that step aside before it closes.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/collapsible-sidebar.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { LayoutGroup, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Item = { id: string; label: string; icon: React.ReactNode };\n\nconst EXPANDED = 240;\n// 48px items plus 8px padding each side, so a collapsed icon sits dead\n// center in the rail.\nconst COLLAPSED = 64;\n// Item row height plus the 4px gap between rows, for placing the tooltip.\nconst ROW = 44;\n// No bounce: an overshooting sidebar would shove the content back and\n// forth. 0.3s is the most a panel this size can take and still feel direct.\nconst WIDTH = { type: \"spring\", visualDuration: 0.3, bounce: 0 } as const;\nconst HIGHLIGHT = { type: \"spring\", visualDuration: 0.25, bounce: 0 } as const;\nconst INSTANT = { duration: 0 } as const;\n// Long enough that sweeping the pointer across the rail doesn't flash\n// tooltips, short enough to feel like the rail is answering.\nconst TOOLTIP_DELAY = 400;\n\nexport function CollapsibleSidebar({\n  items,\n  value,\n  onChange,\n  expanded,\n  onExpandedChange,\n  children,\n  className,\n}: {\n  items: readonly Item[];\n  value: string;\n  onChange: (id: string) => void;\n  expanded: boolean;\n  onExpandedChange: (expanded: boolean) => void;\n  children?: React.ReactNode;\n  className?: string;\n}) {\n  const reduce = useReducedMotion();\n  const base = useId();\n  const navId = `${base}-nav`;\n  const [tip, setTip] = useState<{ index: number; open: boolean }>({\n    index: 0,\n    open: false,\n  });\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  const hideTip = () => {\n    clearTimeout(timer.current);\n    setTip((t) => (t.open ? { ...t, open: false } : t));\n  };\n\n  // The first tooltip waits; once one is open, moving to a neighbour\n  // swaps it instantly, so scanning the rail stays fast.\n  const showTip = (index: number, immediate: boolean) => {\n    if (expanded) return;\n    clearTimeout(timer.current);\n    if (immediate || tip.open) setTip({ index, open: true });\n    else\n      timer.current = setTimeout(\n        () => setTip({ index, open: true }),\n        TOOLTIP_DELAY,\n      );\n  };\n\n  const toggle = () => {\n    hideTip();\n    onExpandedChange(!expanded);\n  };\n\n  return (\n    <LayoutGroup id={base}>\n      <div\n        className={cn(\n          \"relative flex overflow-hidden rounded-2xl bg-background shadow-raised\",\n          className,\n        )}\n      >\n        {/* Width, not scale: scaling the rail would squash every icon and\n            label inside it, and this is what pushes the content along. */}\n        <motion.nav\n          id={navId}\n          aria-label=\"Main\"\n          initial={false}\n          animate={{ width: expanded ? EXPANDED : COLLAPSED }}\n          transition={reduce ? INSTANT : WIDTH}\n          className=\"shrink-0 overflow-hidden border-r border-border\"\n          onPointerLeave={hideTip}\n        >\n          <ul className=\"flex flex-col gap-1 p-2\">\n            {items.map((item, i) => {\n              const current = item.id === value;\n              return (\n                <li key={item.id}>\n                  <button\n                    type=\"button\"\n                    aria-current={current ? \"page\" : undefined}\n                    onClick={() => onChange(item.id)}\n                    onPointerEnter={(e) => {\n                      if (e.pointerType !== \"touch\") showTip(i, false);\n                    }}\n                    onFocus={(e) => {\n                      if (e.currentTarget.matches(\":focus-visible\"))\n                        showTip(i, true);\n                    }}\n                    onBlur={hideTip}\n                    className={cn(\n                      \"group relative flex h-10 w-full touch-manipulation items-center gap-3 rounded-lg pl-3.5 text-sm font-medium whitespace-nowrap text-muted-foreground outline-hidden transition-[color] duration-150 ease-out select-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-foreground\",\n                      current && \"text-foreground\",\n                    )}\n                  >\n                    {current && (\n                      <motion.span\n                        layoutId=\"active\"\n                        // Only a change of item moves it. Without this, the\n                        // re-render that starts a collapse would try to\n                        // morph it too, fighting the width spring.\n                        layoutDependency={value}\n                        aria-hidden\n                        className=\"absolute inset-0 rounded-lg bg-muted\"\n                        transition={reduce ? INSTANT : HIGHLIGHT}\n                      />\n                    )}\n                    {/* Presses in on its own, so the 20px icon never moves\n                        relative to the rail it is centered in: 14px left\n                        padding puts its center 24px into the 48px row. */}\n                    <span className=\"relative size-5 shrink-0 transition-[scale] duration-150 ease-out group-active:scale-[0.96] motion-reduce:transition-none\">\n                      {item.icon}\n                    </span>\n                    {/* Collapsing, the label is gone in 100ms, well before\n                        the shrinking edge reaches it, so it is never seen\n                        being clipped. Expanding, it waits 120ms for the rail\n                        to open most of the way, then sharpens in. The\n                        timing follows whether the label is showing. */}\n                    <span\n                      className={cn(\n                        \"relative transition-[opacity,filter] ease-out\",\n                        expanded\n                          ? \"opacity-100 blur-[0px] delay-120 duration-200\"\n                          : \"opacity-0 blur-[4px] duration-100\",\n                      )}\n                    >\n                      {item.label}\n                    </span>\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n        </motion.nav>\n\n        {/* Sits outside the nav so its overflow can't clip it. Enters in\n            125ms and leaves in 100ms; moving between items only moves it. */}\n        <span\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute z-10 flex h-8 origin-left items-center rounded-md bg-foreground px-2.5 text-[13px] font-medium whitespace-nowrap text-background\",\n            \"transition-[opacity,scale,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n            tip.open && !expanded\n              ? \"translate-x-0 scale-100 opacity-100 duration-125\"\n              : \"-translate-x-1 scale-[0.97] opacity-0 duration-100 motion-reduce:translate-x-0 motion-reduce:scale-100\",\n          )}\n          // 8px of breathing room right of the rail, and 4px down so the\n          // 32px tip centers on the 40px row below the 8px padding.\n          style={{ left: COLLAPSED + 8, top: 8 + 4 + tip.index * ROW }}\n        >\n          {items[tip.index]?.label}\n        </span>\n\n        <div className=\"flex min-w-0 flex-1 flex-col\">\n          <div className=\"flex h-14 shrink-0 items-center gap-2 px-2\">\n            <button\n              type=\"button\"\n              aria-expanded={expanded}\n              aria-controls={navId}\n              aria-label={expanded ? \"Collapse sidebar\" : \"Expand sidebar\"}\n              onClick={toggle}\n              className=\"relative flex size-10 shrink-0 touch-manipulation items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\"\n            >\n              <svg className=\"size-5\" {...STROKE} aria-hidden>\n                <rect x=\"2.25\" y=\"2.75\" width=\"11.5\" height=\"10.5\" rx=\"2\" />\n                <path d=\"M6.25 2.75v10.5\" />\n              </svg>\n            </button>\n          </div>\n          {children}\n        </div>\n      </div>\n    </LayoutGroup>\n  );\n}\n\nconst STROKE = {\n  viewBox: \"0 0 16 16\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  strokeWidth: 1.5,\n  strokeLinecap: \"round\",\n  strokeLinejoin: \"round\",\n} as const;\n\nconst ITEMS: Item[] = [\n  {\n    id: \"home\",\n    label: \"Home\",\n    icon: (\n      <svg className=\"size-5\" {...STROKE} aria-hidden>\n        <path d=\"M2.75 7 8 2.75 13.25 7v5.25a1 1 0 0 1-1 1h-8.5a1 1 0 0 1-1-1Z\" />\n        <path d=\"M6.25 13.25V9.75h3.5v3.5\" />\n      </svg>\n    ),\n  },\n  {\n    id: \"inbox\",\n    label: \"Inbox\",\n    icon: (\n      <svg className=\"size-5\" {...STROKE} aria-hidden>\n        <path d=\"M2.75 9.25 4.5 3.5a1 1 0 0 1 1-.75h5a1 1 0 0 1 1 .75l1.75 5.75v3a1 1 0 0 1-1 1h-8.5a1 1 0 0 1-1-1Z\" />\n        <path d=\"M2.75 9.25h3l.75 1.5h3l.75-1.5h3\" />\n      </svg>\n    ),\n  },\n  {\n    id: \"projects\",\n    label: \"Projects\",\n    icon: (\n      <svg className=\"size-5\" {...STROKE} aria-hidden>\n        <path d=\"M2.75 4.25a1 1 0 0 1 1-1h2.5l1.5 1.5h4.5a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-8.5a1 1 0 0 1-1-1Z\" />\n      </svg>\n    ),\n  },\n  {\n    id: \"reports\",\n    label: \"Reports\",\n    icon: (\n      <svg className=\"size-5\" {...STROKE} aria-hidden>\n        <path d=\"M3.25 13.25V8.75M8 13.25v-10.5M12.75 13.25v-6.5\" />\n      </svg>\n    ),\n  },\n  {\n    id: \"settings\",\n    label: \"Settings\",\n    icon: (\n      <svg className=\"size-5\" {...STROKE} aria-hidden>\n        <circle cx=\"8\" cy=\"8\" r=\"2\" />\n        <path d=\"M8 1.75v1.5M8 12.75v1.5M1.75 8h1.5M12.75 8h1.5M3.6 3.6l1.05 1.05M11.35 11.35l1.05 1.05M3.6 12.4l1.05-1.05M11.35 4.65l1.05-1.05\" />\n      </svg>\n    ),\n  },\n];\n\nconst CONTENT: Record<string, { blurb: string; rows: [string, string][] }> = {\n  home: {\n    blurb: \"Everything that moved since you last checked in.\",\n    rows: [\n      [\"Q3 planning notes\", \"Edited 2h ago\"],\n      [\"Onboarding checklist\", \"Edited yesterday\"],\n      [\"Design review\", \"Edited Monday\"],\n    ],\n  },\n  inbox: {\n    blurb: \"Three threads are waiting on a reply from you.\",\n    rows: [\n      [\"Launch timeline\", \"Maya, 10m ago\"],\n      [\"Invoice #2048\", \"Billing, 1h ago\"],\n      [\"Welcome aboard\", \"Team, 3h ago\"],\n    ],\n  },\n  projects: {\n    blurb: \"Active work across the team, sorted by last update.\",\n    rows: [\n      [\"Mobile redesign\", \"12 open tasks\"],\n      [\"Billing migration\", \"4 open tasks\"],\n      [\"Docs refresh\", \"7 open tasks\"],\n    ],\n  },\n  reports: {\n    blurb: \"Weekly numbers, refreshed every Monday morning.\",\n    rows: [\n      [\"Active users\", \"+8% this week\"],\n      [\"Retention\", \"Flat since June\"],\n      [\"Revenue\", \"+3% this week\"],\n    ],\n  },\n  settings: {\n    blurb: \"Workspace preferences shared by everyone.\",\n    rows: [\n      [\"Members\", \"14 people\"],\n      [\"Notifications\", \"Daily digest\"],\n      [\"Billing\", \"Pro plan\"],\n    ],\n  },\n};\n\nexport default function CollapsibleSidebarDemo() {\n  const [value, setValue] = useState(\"home\");\n  const [expanded, setExpanded] = useState(true);\n  const current = ITEMS.find((item) => item.id === value) ?? ITEMS[0];\n  const content = CONTENT[current.id];\n\n  return (\n    <CollapsibleSidebar\n      items={ITEMS}\n      value={value}\n      onChange={setValue}\n      expanded={expanded}\n      onExpandedChange={setExpanded}\n      // 340px fits the five 40px rows, their gaps and padding with no scroll.\n      className=\"h-85 w-[min(560px,100%)]\"\n    >\n      {/* Fixed-width content, left aligned, so it slides with the rail's\n          edge instead of rewrapping on every frame. 280px is what's left\n          beside the expanded rail. */}\n      <div className=\"flex w-70 shrink-0 flex-col px-4 pt-1\">\n        <p className=\"text-lg font-semibold text-foreground\">{current.label}</p>\n        <p className=\"mt-1 text-sm text-muted-foreground\">{content.blurb}</p>\n        <ul className=\"mt-4 flex flex-col gap-2\">\n          {content.rows.map(([title, meta]) => (\n            <li\n              key={title}\n              className=\"flex h-12 items-center justify-between gap-3 rounded-xl bg-muted px-3.5\"\n            >\n              <span className=\"truncate text-sm font-medium text-foreground\">\n                {title}\n              </span>\n              <span className=\"shrink-0 text-xs text-muted-foreground\">{meta}</span>\n            </li>\n          ))}\n        </ul>\n      </div>\n    </CollapsibleSidebar>\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":["navigation"],"docs":"From ui lab: https://lab.xevrion.dev/lab/collapsible-sidebar"}