{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bookshelf",
  "title": "Bookshelf",
  "author": "ncdai <dai@chanhdai.com>",
  "description": "Shelf of book spines that turn to show their covers.",
  "dependencies": [
    "@base-ui/react",
    "motion"
  ],
  "files": [
    {
      "path": "src/registry/components/bookshelf/bookshelf.tsx",
      "content": "\"use client\"\n\nimport {\n  createContext,\n  use,\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\"\nimport type { CSSProperties, RefObject } from \"react\"\nimport { mergeProps } from \"@base-ui/react/merge-props\"\nimport { useRender } from \"@base-ui/react/use-render\"\nimport { useReducedMotion, useSpring } from \"motion/react\"\nimport type { MotionValue } from \"motion/react\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst OPEN_ANGLE = 90\nconst LIFT_DISTANCE = 8\nconst SPRING = { stiffness: 260, damping: 32 }\n\ntype CSSVariables = CSSProperties & Record<`--${string}`, string | number>\n\nfunction toRadians(deg: number) {\n  return (deg * Math.PI) / 180\n}\n\n// The projected footprint of the turned book, so neighbors are pushed aside\n// by exactly the space the cover takes up\nfunction getItemWidth(deg: number, spineWidth: number, coverWidth: number) {\n  const rad = toRadians(deg)\n  return spineWidth * Math.cos(rad) + coverWidth * Math.sin(rad)\n}\n\n// Pivots on the spine/cover edge, then shifts left so the turned spine starts\n// at the item's left edge instead of leaving a gap\nfunction getBookTransform(deg: number, spineWidth: number) {\n  const shift = spineWidth * (Math.cos(toRadians(deg)) - 1)\n  return `perspective(1200px) translateX(${shift}px) rotateY(${-deg}deg)`\n}\n\ntype BookshelfContextValue = {\n  openValue: string | null\n  instant: boolean\n  toggle: (value: string, fromKeyboard: boolean) => void\n}\n\nconst BookshelfContext = createContext<BookshelfContextValue | null>(null)\n\nfunction useBookshelf() {\n  const context = use(BookshelfContext)\n  if (!context) {\n    throw new Error(\"Bookshelf parts must be used within <Bookshelf>\")\n  }\n  return context\n}\n\ntype BookshelfItemContextValue = {\n  value: string\n  open: boolean\n  angle: MotionValue<number>\n  spineWidth: number\n}\n\nconst BookshelfItemContext = createContext<BookshelfItemContextValue | null>(\n  null\n)\n\nfunction useBookshelfItem() {\n  const context = use(BookshelfItemContext)\n  if (!context) {\n    throw new Error(\"BookshelfItem parts must be used within <BookshelfItem>\")\n  }\n  return context\n}\n\ntype BookshelfState = {\n  slot: string\n}\n\ntype BookshelfItemState = {\n  slot: string\n  open: boolean\n}\n\nexport type BookshelfProps = Omit<\n  useRender.ComponentProps<\"div\", BookshelfState>,\n  \"defaultValue\"\n> & {\n  /** The open book. At most one book is open at a time. */\n  value?: string | null\n  /** The book open on first render, when `value` is not controlled. */\n  defaultValue?: string | null\n  /** Called when a book opens or closes, with `null` when none is open. */\n  onValueChange?: (value: string | null) => void\n}\n\nexport function Bookshelf({\n  value: valueProp,\n  defaultValue = null,\n  onValueChange,\n  className,\n  render,\n  ...props\n}: BookshelfProps) {\n  const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue)\n  // Keyboard changes repeat too often to animate, so they snap\n  const [instant, setInstant] = useState(false)\n\n  const isControlled = valueProp !== undefined\n  const openValue = isControlled ? valueProp : uncontrolledValue\n\n  const setOpenValue = useCallback(\n    (next: string | null, fromKeyboard: boolean) => {\n      if (!isControlled) setUncontrolledValue(next)\n      setInstant(fromKeyboard)\n      onValueChange?.(next)\n    },\n    [isControlled, onValueChange]\n  )\n\n  const toggle = useCallback(\n    (value: string, fromKeyboard: boolean) => {\n      setOpenValue(openValue === value ? null : value, fromKeyboard)\n    },\n    [openValue, setOpenValue]\n  )\n\n  const context = useMemo<BookshelfContextValue>(\n    () => ({ openValue, instant, toggle }),\n    [instant, openValue, toggle]\n  )\n\n  const element = useRender({\n    defaultTagName: \"div\",\n    render,\n    state: { slot: \"bookshelf\" },\n    props: mergeProps<\"div\">(\n      {\n        className: cn(\"flex items-end justify-center gap-1\", className),\n        onKeyDown: (event) => {\n          if (event.key !== \"Escape\" || openValue === null) return\n          // Keeps an enclosing dialog open when Escape only closed a book\n          event.stopPropagation()\n          setOpenValue(null, true)\n        },\n      },\n      props\n    ),\n  })\n\n  return <BookshelfContext value={context}>{element}</BookshelfContext>\n}\n\nexport type BookshelfItemProps = useRender.ComponentProps<\n  \"div\",\n  BookshelfItemState\n> & {\n  /** Identifies the item for `value`. Generated when omitted. */\n  value?: string\n  /** Thickness of the spine in pixels, the item's width when closed. */\n  spineWidth: number\n  /** Width of the cover in pixels, the item's width when open. */\n  coverWidth: number\n}\n\nexport function BookshelfItem({\n  value: valueProp,\n  spineWidth,\n  coverWidth,\n  className,\n  style,\n  render,\n  ...props\n}: BookshelfItemProps) {\n  const { openValue, instant } = useBookshelf()\n  const generatedValue = useId()\n  const value = valueProp ?? generatedValue\n  const open = openValue === value\n\n  const itemRef = useRef<HTMLDivElement>(null)\n  const reduceMotion = useReducedMotion()\n  const [initialAngle] = useState(open ? OPEN_ANGLE : 0)\n  const angle = useSpring(initialAngle, SPRING)\n  const previousOpen = useRef(open)\n\n  useEffect(() => {\n    // Only a change of `open` moves the book; `instant` flipping alone must\n    // not snap a turn that is still in flight\n    if (previousOpen.current === open) return\n    previousOpen.current = open\n    const target = open ? OPEN_ANGLE : 0\n    if (reduceMotion || instant) angle.jump(target)\n    else angle.set(target)\n  }, [angle, instant, open, reduceMotion])\n\n  // Written straight to the element: a spring frame must not re-render React,\n  // and an animated CSS variable would restyle every descendant per frame\n  useEffect(() => {\n    const apply = (deg: number) => {\n      if (!itemRef.current) return\n      const width = getItemWidth(deg, spineWidth, coverWidth)\n      itemRef.current.style.width = `${width}px`\n    }\n    apply(angle.get())\n    return angle.on(\"change\", apply)\n  }, [angle, coverWidth, spineWidth])\n\n  const itemContext = useMemo(\n    () => ({ value, open, angle, spineWidth }),\n    [angle, open, spineWidth, value]\n  )\n\n  const element = useRender({\n    defaultTagName: \"div\",\n    render,\n    ref: itemRef,\n    state: { slot: \"bookshelf-item\", open },\n    props: mergeProps<\"div\">(\n      {\n        className: cn(\"relative shrink-0\", className),\n        style: {\n          \"--bookshelf-spine-width\": `${spineWidth}px`,\n          \"--bookshelf-cover-width\": `${coverWidth}px`,\n          width: getItemWidth(initialAngle, spineWidth, coverWidth),\n          ...style,\n        } as CSSVariables,\n      },\n      props\n    ),\n  })\n\n  return (\n    <BookshelfItemContext value={itemContext}>{element}</BookshelfItemContext>\n  )\n}\n\nexport function BookshelfTrigger({\n  className,\n  children,\n  render,\n  ...props\n}: useRender.ComponentProps<\"button\", BookshelfItemState>) {\n  const { toggle, instant } = useBookshelf()\n  const { value, open, angle, spineWidth } = useBookshelfItem()\n  const liftRef = useRef<HTMLSpanElement>(null)\n  const bookRef = useRef<HTMLSpanElement>(null)\n  const [initialAngle] = useState(() => angle.get())\n\n  const reduceMotion = useReducedMotion()\n  const [hovered, setHovered] = useState(false)\n  const [focusVisible, setFocusVisible] = useState(false)\n  // An open book stays raised, so opening it never drops it back down\n  const raised = !reduceMotion && (hovered || focusVisible || open)\n  const [initialLift] = useState(open ? 1 : 0)\n  // A spring rather than a CSS ease, so the lift glides and can be caught\n  // mid-way when the pointer moves on\n  const lift = useSpring(initialLift, SPRING)\n  const previousLiftInputs = useRef({ focusVisible, open })\n\n  useEffect(() => {\n    const previous = previousLiftInputs.current\n    previousLiftInputs.current = { focusVisible, open }\n    const fromKeyboard =\n      previous.focusVisible !== focusVisible ||\n      (previous.open !== open && instant)\n    const target = raised ? 1 : 0\n    if (fromKeyboard || reduceMotion) lift.jump(target)\n    else lift.set(target)\n  }, [focusVisible, instant, lift, open, raised, reduceMotion])\n\n  useEffect(() => {\n    const apply = (amount: number) => {\n      if (liftRef.current) {\n        liftRef.current.style.transform = `translateY(${-amount * LIFT_DISTANCE}px)`\n      }\n    }\n    apply(lift.get())\n    return lift.on(\"change\", apply)\n  }, [lift])\n\n  useEffect(() => {\n    const apply = (deg: number) => {\n      if (bookRef.current) {\n        bookRef.current.style.transform = getBookTransform(deg, spineWidth)\n      }\n    }\n    apply(angle.get())\n    return angle.on(\"change\", apply)\n  }, [angle, spineWidth])\n\n  useReducedMotionFade(bookRef, open)\n\n  return useRender({\n    defaultTagName: \"button\",\n    render,\n    state: { slot: \"bookshelf-trigger\", open },\n    props: mergeProps<\"button\">(\n      {\n        ...(render ? {} : { type: \"button\" as const }),\n        \"aria-expanded\": open,\n        className: cn(\n          \"group/bookshelf-trigger relative block size-full cursor-pointer outline-none\",\n          className\n        ),\n        // `detail` is 0 when Enter or Space fired the click\n        onClick: (event) => toggle(value, event.detail === 0),\n        onPointerEnter: (event) => {\n          if (event.pointerType === \"mouse\") setHovered(true)\n        },\n        onPointerLeave: () => setHovered(false),\n        onFocus: (event) => {\n          setFocusVisible(event.currentTarget.matches(\":focus-visible\"))\n        },\n        onBlur: () => setFocusVisible(false),\n        children: (\n          // Lifts instead of the trigger, so the hit area stays under the\n          // pointer and the hover cannot flicker on and off\n          <span\n            ref={liftRef}\n            data-slot=\"bookshelf-lift\"\n            className=\"absolute inset-0 group-focus-visible/bookshelf-trigger:ring-2 group-focus-visible/bookshelf-trigger:ring-ring group-focus-visible/bookshelf-trigger:ring-offset-2 group-focus-visible/bookshelf-trigger:ring-offset-background\"\n            style={{\n              transform: `translateY(${-initialLift * LIFT_DISTANCE}px)`,\n            }}\n          >\n            <span\n              ref={bookRef}\n              data-slot=\"bookshelf-book\"\n              className=\"absolute inset-y-0 left-0 w-(--bookshelf-spine-width) origin-right transform-3d\"\n              style={{ transform: getBookTransform(initialAngle, spineWidth) }}\n            >\n              {children}\n            </span>\n          </span>\n        ),\n      },\n      props\n    ),\n  })\n}\n\n// Reduced motion snaps the book without turning it, so a short fade keeps the\n// change legible without movement\nfunction useReducedMotionFade(\n  ref: RefObject<HTMLElement | null>,\n  open: boolean\n) {\n  const reduceMotion = useReducedMotion()\n  const previousOpen = useRef(open)\n\n  useEffect(() => {\n    if (previousOpen.current === open) return\n    previousOpen.current = open\n    if (reduceMotion) {\n      ref.current?.animate(\n        { opacity: [0, 1] },\n        { duration: 150, easing: \"ease\" }\n      )\n    }\n  }, [open, reduceMotion, ref])\n}\n\nexport function BookshelfSpine({\n  className,\n  render,\n  ...props\n}: useRender.ComponentProps<\"div\", BookshelfItemState>) {\n  const { open } = useBookshelfItem()\n\n  return useRender({\n    defaultTagName: \"div\",\n    render,\n    state: { slot: \"bookshelf-spine\", open },\n    props: mergeProps<\"div\">(\n      { className: cn(\"absolute inset-0 overflow-hidden\", className) },\n      props\n    ),\n  })\n}\n\nexport function BookshelfCover({\n  className,\n  render,\n  ...props\n}: useRender.ComponentProps<\"div\", BookshelfItemState>) {\n  const { open } = useBookshelfItem()\n\n  return useRender({\n    defaultTagName: \"div\",\n    render,\n    state: { slot: \"bookshelf-cover\", open },\n    props: mergeProps<\"div\">(\n      {\n        // Hidden from assistive tech while it faces away; the spine names the book\n        inert: !open,\n        className: cn(\n          \"absolute top-0 left-full h-full w-(--bookshelf-cover-width) origin-left rotate-y-90 overflow-hidden\",\n          className\n        ),\n      },\n      props\n    ),\n  })\n}\n",
      "type": "registry:component",
      "target": "@components/bookshelf.tsx"
    }
  ],
  "docs": "https://chanhdai.com/components/bookshelf",
  "categories": [
    "illustrations"
  ],
  "type": "registry:component"
}