{
  "schemaVersion": 1,
  "target": "react",
  "name": "resizable",
  "version": "0.1.0",
  "category": "layout",
  "title": "Resizable",
  "description": "Panels split by draggable hairline handles, horizontal or vertical, with min and max sizes, keyboard resizing, and optional saved layouts.",
  "tags": [
    "layout",
    "panels",
    "split",
    "resize"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/resizable",
  "props": [
    {
      "name": "ResizablePanelGroup direction",
      "type": "\"horizontal\" | \"vertical\"",
      "default": "\"horizontal\"",
      "description": "Side by side, or stacked."
    },
    {
      "name": "ResizablePanelGroup autoSaveId",
      "type": "string",
      "description": "Saves sizes to localStorage under this id and restores them before the first paint on the next visit."
    },
    {
      "name": "ResizablePanelGroup onLayout",
      "type": "(sizes: number[]) => void",
      "description": "Called with panel sizes in percent whenever they change."
    },
    {
      "name": "ResizablePanelGroup keyboardStep",
      "type": "number",
      "default": "5",
      "description": "Percent moved per arrow key press; Shift + arrow moves 1%."
    },
    {
      "name": "ResizablePanel defaultSize / minSize / maxSize",
      "type": "number",
      "default": "none / 0 / 100",
      "description": "Sizes in percent of the group. Panels without defaultSize share what is left."
    },
    {
      "name": "ResizableHandle withHandle",
      "type": "boolean",
      "default": "false",
      "description": "Shows a small grip on the hairline."
    },
    {
      "name": "ResizableHandle aria-label",
      "type": "string",
      "default": "\"Resize panels\"",
      "description": "Name of the separator, for example \"Resize conversation\"."
    }
  ],
  "accessibility": [
    "Each handle is a focusable role=\"separator\" with aria-orientation, aria-valuenow (the preceding panel's size in percent), aria-valuemin, aria-valuemax, and aria-controls pointing at that panel.",
    "Arrow keys along the group's axis resize by 5% (Shift for 1%), Home and End jump to the panel's minimum and maximum, and Enter collapses the panel to its minimum and restores it on the next press.",
    "Keyboard resizing and dragging change sizes immediately, without animation, so the layout tracks the input exactly.",
    "Handles have a 13px hit area around the 1px hairline, a resize cursor, and a sky focus ring; they brighten on hover and while dragged.",
    "Pointer capture keeps a drag working when the pointer leaves the handle, and text selection is suspended while dragging."
  ],
  "states": [
    "default",
    "hover",
    "dragging",
    "focus-visible"
  ],
  "files": [
    {
      "path": "ui/resizable.tsx",
      "content": "\"use client\";\n\nimport {\n  Children,\n  type ComponentProps,\n  createContext,\n  isValidElement,\n  type KeyboardEvent,\n  type PointerEvent,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport type ResizableDirection = \"horizontal\" | \"vertical\";\n\ninterface PanelConstraints {\n  id: string;\n  defaultSize: number | undefined;\n  minSize: number;\n  maxSize: number;\n}\n\ninterface GroupContextValue {\n  direction: ResizableDirection;\n  sizes: number[];\n  panels: PanelConstraints[];\n  draggingHandle: number | null;\n  keyboardStep: number;\n  startDrag: (handle: number, event: PointerEvent<HTMLElement>) => void;\n  moveDrag: (event: PointerEvent<HTMLElement>) => void;\n  endDrag: (event: PointerEvent<HTMLElement>) => void;\n  resizeTo: (handle: number, size: number) => void;\n}\n\nconst GroupContext = createContext<GroupContextValue | null>(null);\n/** Index of a panel among panels, or of a handle among handles, assigned by the group. */\nconst PositionContext = createContext(-1);\n\nfunction useGroup(part: string) {\n  const context = useContext(GroupContext);\n  if (!context) throw new Error(`${part} must be a direct child of ResizablePanelGroup.`);\n  return context;\n}\n\n/** Fills in sizes that were not given by sharing what is left equally, then scales the total to 100. */\nfunction initialSizes(panels: PanelConstraints[]) {\n  const given = panels.reduce((sum, panel) => sum + (panel.defaultSize ?? 0), 0);\n  const open = panels.filter((panel) => panel.defaultSize === undefined).length;\n  const share = open > 0 ? Math.max(0, 100 - given) / open : 0;\n  const raw = panels.map((panel) => panel.defaultSize ?? share);\n  const total = raw.reduce((sum, size) => sum + size, 0) || 1;\n  return raw.map((size) => (size / total) * 100);\n}\n\n/** Moves the boundary after panel `index` by `delta` percent, clamped so both neighbours stay within their limits. */\nfunction shift(sizes: number[], panels: PanelConstraints[], index: number, delta: number) {\n  const a = panels[index];\n  const b = panels[index + 1];\n  const sizeA = sizes[index];\n  const sizeB = sizes[index + 1];\n  if (!a || !b || sizeA === undefined || sizeB === undefined) return sizes;\n  const lower = Math.max(a.minSize - sizeA, sizeB - b.maxSize);\n  const upper = Math.min(a.maxSize - sizeA, sizeB - b.minSize);\n  const applied = Math.min(Math.max(delta, lower), upper);\n  if (applied === 0) return sizes;\n  const next = [...sizes];\n  next[index] = sizeA + applied;\n  next[index + 1] = sizeB - applied;\n  return next;\n}\n\nconst storageKey = (id: string) => `shaken-resizable:${id}`;\n\nexport interface ResizablePanelGroupProps extends ComponentProps<\"div\"> {\n  /** `horizontal` lays panels side by side; `vertical` stacks them. */\n  direction?: ResizableDirection;\n  /** Saves the layout to localStorage under this id and restores it on the next visit. */\n  autoSaveId?: string;\n  /** Called with the panel sizes, in percent, whenever they change. */\n  onLayout?: (sizes: number[]) => void;\n  /** Percent moved by each arrow key press on a focused handle. Shift with an arrow moves 1%. */\n  keyboardStep?: number;\n}\n\n/**\n * Lays out `ResizablePanel`s with `ResizableHandle`s between them. Panels and handles must be\n * direct children. Sizes are percentages of the space left after the handles; they follow the\n * pointer exactly while dragging and change in steps from the keyboard, without animation.\n */\nexport function ResizablePanelGroup({\n  direction = \"horizontal\",\n  autoSaveId,\n  onLayout,\n  keyboardStep = 5,\n  className,\n  children,\n  ...props\n}: ResizablePanelGroupProps) {\n  const baseId = useId();\n  const groupRef = useRef<HTMLDivElement>(null);\n\n  const panels: PanelConstraints[] = [];\n  let handleCount = 0;\n  const content = Children.map(children, (child) => {\n    if (!isValidElement(child)) return child;\n    if (child.type === ResizablePanel) {\n      const panel = child.props as ResizablePanelProps;\n      const index = panels.length;\n      panels.push({\n        id: panel.id ?? `${baseId}panel-${index}`,\n        defaultSize: panel.defaultSize,\n        minSize: panel.minSize ?? 0,\n        maxSize: panel.maxSize ?? 100,\n      });\n      return <PositionContext.Provider value={index}>{child}</PositionContext.Provider>;\n    }\n    if (child.type === ResizableHandle) {\n      return <PositionContext.Provider value={handleCount++}>{child}</PositionContext.Provider>;\n    }\n    return child;\n  });\n\n  const [stored, setSizes] = useState<number[]>(() => initialSizes(panels));\n  // If panels are added or removed, start again from their default sizes.\n  const sizes = stored.length === panels.length ? stored : initialSizes(panels);\n  const [draggingHandle, setDraggingHandle] = useState<number | null>(null);\n  const drag = useRef<{ handle: number; pointerId: number; start: number; base: number[]; space: number } | null>(null);\n  const latest = useRef(sizes);\n  latest.current = sizes;\n\n  // Restore a saved layout before the first paint, so the panels do not jump.\n  useLayoutEffect(() => {\n    if (!autoSaveId) return;\n    try {\n      const saved = JSON.parse(window.localStorage.getItem(storageKey(autoSaveId)) ?? \"null\") as unknown;\n      if (Array.isArray(saved) && saved.length === panels.length && saved.every((size) => typeof size === \"number\")) {\n        setSizes(saved);\n      }\n    } catch {\n      // Storage can be unavailable (private mode, blocked cookies); fall back to the defaults.\n    }\n  }, [autoSaveId]);\n\n  // Saved only after the person resizes (drag end or a key press), never on mount, so a restore\n  // can not be overwritten by the default layout.\n  const persist = (next: number[]) => {\n    if (!autoSaveId) return;\n    try {\n      window.localStorage.setItem(storageKey(autoSaveId), JSON.stringify(next.map((size) => Math.round(size * 100) / 100)));\n    } catch {\n      // Ignore storage failures; the layout still works for this visit.\n    }\n  };\n\n  const onLayoutRef = useRef(onLayout);\n  onLayoutRef.current = onLayout;\n  const sizesKey = sizes.map((size) => size.toFixed(3)).join(\",\");\n  useEffect(() => {\n    onLayoutRef.current?.(latest.current);\n  }, [sizesKey]);\n\n  const axis = (event: { clientX: number; clientY: number }) => (direction === \"horizontal\" ? event.clientX : event.clientY);\n\n  const value: GroupContextValue = {\n    direction,\n    sizes,\n    panels,\n    draggingHandle,\n    keyboardStep,\n    startDrag(handle, event) {\n      const group = groupRef.current;\n      if (!group || event.button !== 0) return;\n      event.preventDefault();\n      event.currentTarget.setPointerCapture(event.pointerId);\n      const rect = group.getBoundingClientRect();\n      const handles = group.querySelectorAll<HTMLElement>(\":scope > [data-slot=resizable-handle]\");\n      const handleSpace = [...handles].reduce((sum, el) => sum + (direction === \"horizontal\" ? el.offsetWidth : el.offsetHeight), 0);\n      const space = (direction === \"horizontal\" ? rect.width : rect.height) - handleSpace;\n      drag.current = { handle, pointerId: event.pointerId, start: axis(event), base: sizes, space: Math.max(space, 1) };\n      setDraggingHandle(handle);\n      document.documentElement.style.setProperty(\"cursor\", direction === \"horizontal\" ? \"col-resize\" : \"row-resize\");\n      document.documentElement.style.setProperty(\"user-select\", \"none\");\n    },\n    moveDrag(event) {\n      const current = drag.current;\n      if (!current || current.pointerId !== event.pointerId) return;\n      const delta = ((axis(event) - current.start) / current.space) * 100;\n      setSizes(shift(current.base, panels, current.handle, delta));\n    },\n    endDrag(event) {\n      const current = drag.current;\n      if (!current || current.pointerId !== event.pointerId) return;\n      drag.current = null;\n      setDraggingHandle(null);\n      persist(latest.current);\n      document.documentElement.style.removeProperty(\"cursor\");\n      document.documentElement.style.removeProperty(\"user-select\");\n    },\n    resizeTo(handle, size) {\n      setSizes((previous) => {\n        const base = previous.length === panels.length ? previous : sizes;\n        const next = shift(base, panels, handle, size - (base[handle] ?? 0));\n        persist(next);\n        return next;\n      });\n    },\n  };\n\n  return (\n    <GroupContext.Provider value={value}>\n      <div\n        ref={groupRef}\n        data-direction={direction}\n        data-dragging={draggingHandle !== null || undefined}\n        className={cx(\"flex h-full w-full min-w-0 overflow-hidden\", direction === \"vertical\" && \"flex-col\", className)}\n        {...props}\n      >\n        {content}\n      </div>\n    </GroupContext.Provider>\n  );\n}\n\nexport interface ResizablePanelProps extends ComponentProps<\"div\"> {\n  /** Starting size in percent. Panels without one share the remaining space equally. */\n  defaultSize?: number;\n  /** Smallest size in percent the panel can be dragged to. */\n  minSize?: number;\n  /** Largest size in percent the panel can be dragged to. */\n  maxSize?: number;\n}\n\n/** A region of the group. Its content scrolls or clips on its own; add `overflow-auto` for scrolling content. */\nexport function ResizablePanel({ defaultSize: _defaultSize, minSize: _minSize, maxSize: _maxSize, className, style, ...props }: ResizablePanelProps) {\n  const group = useGroup(\"ResizablePanel\");\n  const index = useContext(PositionContext);\n  const size = group.sizes[index] ?? 0;\n  const panel = group.panels[index];\n  return (\n    <div\n      data-slot=\"resizable-panel\"\n      id={panel?.id}\n      data-at-min={(panel && size <= panel.minSize + 0.01) || undefined}\n      className={cx(\"relative min-h-0 min-w-0 overflow-hidden\", className)}\n      style={{ ...style, flex: `${size} 1 0px` }}\n      {...props}\n    />\n  );\n}\n\nexport interface ResizableHandleProps extends ComponentProps<\"div\"> {\n  /** Shows a small grip on the hairline so the handle is easy to find at rest. */\n  withHandle?: boolean;\n  /** Accessible name. Name what it resizes, for example \"Resize sidebar\". */\n  \"aria-label\"?: string;\n}\n\n/**\n * The divider between two panels: a 1px hairline with a 13px hit area. Drag it, or focus it and\n * use the arrow keys (Shift for 1% steps), Home and End for the limits, and Enter to collapse the\n * panel before it to its minimum and restore it again. It brightens on hover and while dragged.\n */\nexport function ResizableHandle({\n  withHandle = false,\n  \"aria-label\": label = \"Resize panels\",\n  className,\n  onKeyDown,\n  ...props\n}: ResizableHandleProps) {\n  const group = useGroup(\"ResizableHandle\");\n  const index = useContext(PositionContext);\n  const before = group.panels[index];\n  const size = group.sizes[index] ?? 0;\n  const restoreSize = useRef<number | null>(null);\n  const horizontal = group.direction === \"horizontal\";\n  const dragging = group.draggingHandle === index;\n\n  function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || !before) return;\n    const step = event.shiftKey ? 1 : group.keyboardStep;\n    const back = horizontal ? \"ArrowLeft\" : \"ArrowUp\";\n    const forward = horizontal ? \"ArrowRight\" : \"ArrowDown\";\n    let target: number | null = null;\n    if (event.key === back) target = size - step;\n    else if (event.key === forward) target = size + step;\n    else if (event.key === \"Home\") target = before.minSize;\n    else if (event.key === \"End\") target = before.maxSize;\n    else if (event.key === \"Enter\") {\n      if (restoreSize.current !== null && size <= before.minSize + 0.01) {\n        target = restoreSize.current;\n        restoreSize.current = null;\n      } else {\n        restoreSize.current = size;\n        target = before.minSize;\n      }\n    }\n    if (target === null) return;\n    event.preventDefault();\n    group.resizeTo(index, target);\n  }\n\n  return (\n    <div\n      role=\"separator\"\n      tabIndex={0}\n      aria-label={label}\n      aria-orientation={horizontal ? \"vertical\" : \"horizontal\"}\n      aria-controls={before?.id}\n      aria-valuenow={Math.round(size)}\n      aria-valuemin={before?.minSize ?? 0}\n      aria-valuemax={before?.maxSize ?? 100}\n      data-slot=\"resizable-handle\"\n      data-dragging={dragging || undefined}\n      className={cx(\n        \"group/handle relative z-10 flex shrink-0 touch-none items-center justify-center select-none\",\n        \"bg-zinc-950/10 dark:bg-white/10\",\n        \"transition-[background-color] duration-150 ease-out motion-reduce:transition-none\",\n        \"hover:bg-zinc-950/30 data-[dragging]:bg-zinc-950/45 dark:hover:bg-white/30 dark:data-[dragging]:bg-white/50\",\n        \"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-500\",\n        // The 1px line gets a 13px invisible hit area.\n        \"after:absolute after:content-['']\",\n        horizontal\n          ? \"w-px cursor-col-resize after:inset-y-0 after:-inset-x-1.5\"\n          : \"h-px cursor-row-resize after:inset-x-0 after:-inset-y-1.5\",\n        className,\n      )}\n      onPointerDown={(event) => group.startDrag(index, event)}\n      onPointerMove={group.moveDrag}\n      onPointerUp={group.endDrag}\n      onPointerCancel={group.endDrag}\n      onLostPointerCapture={group.endDrag}\n      onKeyDown={handleKeyDown}\n      {...props}\n    >\n      {withHandle ? (\n        <span\n          aria-hidden=\"true\"\n          className={cx(\n            \"relative z-10 flex items-center justify-center gap-0.5 rounded-full border bg-white\",\n            \"border-zinc-950/15 shadow-[0_1px_2px_rgb(0_0_0/0.06)] dark:border-white/20 dark:bg-black dark:shadow-none\",\n            \"transition-[border-color] duration-150 ease-out motion-reduce:transition-none\",\n            \"group-hover/handle:border-zinc-950/30 group-data-[dragging]/handle:border-zinc-950/45\",\n            \"dark:group-hover/handle:border-white/35 dark:group-data-[dragging]/handle:border-white/50\",\n            \"group-focus-visible/handle:border-sky-500 dark:group-focus-visible/handle:border-sky-500\",\n            horizontal ? \"h-6 w-2.5 flex-col\" : \"h-2.5 w-6\",\n          )}\n        >\n          <span className=\"size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500\" />\n          <span className=\"size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500\" />\n          <span className=\"size-0.5 rounded-full bg-zinc-400 dark:bg-zinc-500\" />\n        </span>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { ResizableHandle, ResizablePanel, ResizablePanelGroup } from \"@/components/shaken/ui/resizable\";\n\nfunction PanelHeader({ title, size }: { title: string; size?: number }) {\n  return (\n    <div className=\"flex h-9 shrink-0 items-center justify-between border-b border-zinc-950/[0.07] px-3 dark:border-white/[0.08]\">\n      <span className=\"truncate text-xs font-medium text-zinc-500\">{title}</span>\n      {size !== undefined ? <span className=\"font-mono text-[11px] text-zinc-400 tabular-nums dark:text-zinc-600\">{Math.round(size)}%</span> : null}\n    </div>\n  );\n}\n\nexport default function ResizableExample() {\n  const [outer, setOuter] = useState<number[]>([]);\n  const [inner, setInner] = useState<number[]>([]);\n\n  return (\n    <div className=\"h-96 w-full max-w-3xl overflow-hidden rounded-xl border border-zinc-950/10 bg-white 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      <ResizablePanelGroup autoSaveId=\"example-workspace\" onLayout={setOuter}>\n        <ResizablePanel defaultSize={38} minSize={24} maxSize={60} className=\"flex flex-col\">\n          <PanelHeader title=\"Conversation\" size={outer[0]} />\n          <div className=\"flex min-h-0 flex-1 flex-col gap-3 overflow-auto p-3 text-sm\">\n            <p className=\"m-0 max-w-[32ch] self-end rounded-lg border border-zinc-950/10 px-3 py-2 text-zinc-950 dark:border-white/15 dark:text-white\">\n              The invoice totals are off by a cent. Can you find out why?\n            </p>\n            <p className=\"m-0 leading-relaxed text-zinc-600 dark:text-zinc-400\">\n              Tax is rounded after summing line items. I changed it to round each line first and the failing test now passes.\n            </p>\n          </div>\n        </ResizablePanel>\n        <ResizableHandle withHandle aria-label=\"Resize conversation\" />\n        <ResizablePanel minSize={30}>\n          <ResizablePanelGroup direction=\"vertical\" autoSaveId=\"example-workspace-right\" onLayout={setInner}>\n            <ResizablePanel defaultSize={62} minSize={25} className=\"flex flex-col\">\n              <PanelHeader title=\"src/invoices/tax.ts\" size={inner[0]} />\n              <pre className=\"m-0 min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed text-zinc-700 dark:text-zinc-300\">\n                {`export function invoiceTax(lines: Line[], rate: number) {\n  return lines.reduce(\n    (total, line) => total + roundCents(line.amount * rate),\n    0,\n  );\n}`}\n              </pre>\n            </ResizablePanel>\n            <ResizableHandle aria-label=\"Resize terminal\" />\n            <ResizablePanel minSize={20} className=\"flex flex-col\">\n              <PanelHeader title=\"Terminal\" size={inner[1]} />\n              <div className=\"min-h-0 flex-1 overflow-auto p-3 font-mono text-xs leading-relaxed text-zinc-500\">\n                <div>$ pnpm test invoices</div>\n                <div className=\"text-emerald-600 dark:text-emerald-400\">✓ 38 tests passed in 4.2s</div>\n              </div>\n            </ResizablePanel>\n          </ResizablePanelGroup>\n        </ResizablePanel>\n      </ResizablePanelGroup>\n    </div>\n  );\n}\n"
  }
}
