{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dynamic-scroll-island-toc",
  "title": "Dynamic Scroll Island TOC",
  "author": "jyotirmoydas <jyotirmoydas12345@gmail.com>",
  "description": "An iOS Dynamic Island-style scroll progress indicator with expandable TOC navigation.",
  "dependencies": ["cn", "motion", "lucide-react"],
  "files": [
    {
      "path": "src/registry/dynamic-scroll-island-toc/dynamic-scroll-island-toc.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"cn\";\nimport { ChevronUpIcon, XIcon } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  MotionConfig,\n  type MotionValue,\n  type Transition,\n  useMotionValue,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport { type RefObject, useCallback, useEffect, useState } from \"react\";\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport interface TOCItem {\n  /** Display name of the item */\n  name: string;\n  /** Optional value for filtering. If undefined, this is an \"All\" option */\n  value?: string;\n}\n\nexport interface DynamicScrollIslandTOCProps {\n  /** Array of TOC items */\n  data: TOCItem[];\n  /** Currently selected item */\n  value?: TOCItem;\n  /** Callback when selection changes */\n  setValue?: (v: TOCItem) => void;\n  /** Ref to the scrollable container to track progress */\n  containerRef?: RefObject<HTMLElement | null>;\n  /** Custom transition settings */\n  transition?: Transition;\n  /** Additional CSS classes */\n  className?: string;\n  /** Layout ID prefix for nested instances */\n  layoutPrefix?: string;\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst CONTAINER_LAYOUT_ID = \"toc-wrapper\";\nconst ITEMS_LAYOUT_ID = \"toc-items\";\n\n// =============================================================================\n// Sub-components\n// =============================================================================\n\nfunction ProgressIndicator({\n  value,\n  setValue,\n  scrollProgress,\n  layoutPrefix,\n}: {\n  value?: TOCItem;\n  setValue?: (v: TOCItem) => void;\n  scrollProgress: MotionValue<number>;\n  layoutPrefix?: string;\n}) {\n  const [progress, setProgress] = useState(() =>\n    Math.round(scrollProgress.get() * 100)\n  );\n\n  useEffect(() => {\n    const unsubscribe = scrollProgress.on(\"change\", (v) =>\n      setProgress(Math.round(v * 100))\n    );\n    return () => unsubscribe();\n  }, [scrollProgress]);\n\n  const handleReset = (e: React.MouseEvent) => {\n    if (value?.value == null) return;\n    e.stopPropagation();\n    setValue?.({ name: \"All\" });\n  };\n\n  return (\n    <motion.button\n      layoutId={`${layoutPrefix}-toc-progress-x`}\n      onClick={handleReset}\n      className={cn(\n        \"relative flex h-8 w-14 items-center justify-center overflow-hidden rounded-full text-sm font-bold\",\n        \"bg-white/10 transition-colors hover:bg-white/15\"\n      )}\n    >\n      {value?.value ? <XIcon className=\"size-4\" /> : `${progress}%`}\n    </motion.button>\n  );\n}\n\nfunction ItemsList({\n  data,\n  setValue,\n}: {\n  data: TOCItem[];\n  setValue?: (v: TOCItem) => void;\n}) {\n  return (\n    <div className=\"group grid transition-opacity\">\n      {data.map((item) => (\n        <button\n          key={item.name}\n          onClick={() => setValue?.(item)}\n          aria-label={item.name}\n          className=\"cursor-pointer text-left font-semibold text-white/80 transition-all group-hover:opacity-40 hover:opacity-100!\"\n        >\n          {item.name}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nfunction ProgressText({\n  open,\n  value,\n  scrollProgress,\n  layoutPrefix,\n}: {\n  open: boolean;\n  value?: TOCItem;\n  scrollProgress: MotionValue<number>;\n  layoutPrefix?: string;\n}) {\n  const circumference = 2 * Math.PI * 10 - 0.5;\n  const offset = useTransform(scrollProgress, [0, 1], [circumference, 0]);\n  const springOffset = useSpring(offset, { visualDuration: 0.1, bounce: 0 });\n\n  return (\n    <div className=\"flex items-center gap-3\">\n      <motion.div layoutId={`${layoutPrefix}-toc-svg-progress`}>\n        <svg\n          width=\"32\"\n          height=\"32\"\n          viewBox=\"0 0 24 24\"\n          fill=\"none\"\n          xmlns=\"http://www.w3.org/2000/svg\"\n        >\n          <circle\n            cx=\"12\"\n            cy=\"12\"\n            r=\"10\"\n            className=\"stroke-white/20\"\n            strokeWidth=\"4\"\n            fill=\"none\"\n          />\n          <motion.circle\n            cx=\"12\"\n            cy=\"12\"\n            r=\"10\"\n            className=\"stroke-white/80\"\n            strokeWidth=\"4\"\n            fill=\"none\"\n            strokeDasharray={circumference}\n            strokeDashoffset={springOffset}\n            strokeLinecap=\"round\"\n            transform=\"rotate(-90 12 12)\"\n          />\n        </svg>\n      </motion.div>\n      <div className=\"flex items-center gap-2\">\n        <motion.p\n          layout=\"position\"\n          layoutId={`${layoutPrefix}-toc-text`}\n          className=\"font-bold\"\n        >\n          {value?.name}\n        </motion.p>\n        <motion.div className=\"mt-0.5 text-white/80\">\n          <motion.div\n            layout=\"position\"\n            layoutId={`${layoutPrefix}-toc-chevron`}\n            animate={{ rotate: open ? 0 : 180 }}\n          >\n            <ChevronUpIcon className=\"size-4\" strokeWidth={3} />\n          </motion.div>\n        </motion.div>\n      </div>\n    </div>\n  );\n}\n\n// =============================================================================\n// Main Component\n// =============================================================================\n\nfunction DynamicScrollIslandTOC({\n  data,\n  value: externalValue,\n  setValue: externalSetValue,\n  containerRef,\n  className,\n  layoutPrefix = \"\",\n  transition = { type: \"spring\", duration: 0.5, bounce: 0.1 },\n}: DynamicScrollIslandTOCProps) {\n  const [open, setOpen] = useState(false);\n  const [internalValue, setInternalValue] = useState(externalValue ?? data[0]);\n  const scrollProgress = useMotionValue(0);\n\n  const value = externalValue ?? internalValue;\n\n  // Track scroll progress\n  useEffect(() => {\n    const container = containerRef?.current || window;\n\n    const updateScrollProgress = () => {\n      const scrollTop =\n        container === window\n          ? window.scrollY\n          : (container as HTMLElement).scrollTop;\n      const scrollHeight =\n        container === window\n          ? document.body.scrollHeight\n          : (container as HTMLElement).scrollHeight;\n      const clientHeight =\n        container === window\n          ? window.innerHeight\n          : (container as HTMLElement).clientHeight;\n\n      const progress = scrollTop / (scrollHeight - clientHeight) || 0;\n\n      if (scrollHeight === clientHeight) scrollProgress.set(1);\n      else scrollProgress.set(progress);\n    };\n\n    container.addEventListener(\"scroll\", updateScrollProgress);\n\n    const resizeObserver = new ResizeObserver(updateScrollProgress);\n    resizeObserver.observe(\n      container === window\n        ? document.body\n        : ((container as HTMLElement).firstChild as HTMLElement)\n    );\n\n    return () => {\n      container.removeEventListener(\"scroll\", updateScrollProgress);\n      resizeObserver.disconnect();\n    };\n  }, [containerRef, scrollProgress]);\n\n  // Helper function to reset scroll position\n  const resetScrollPosition = useCallback(() => {\n    const containerElement = containerRef?.current;\n    if (containerElement) {\n      containerElement.scrollTop = 0; // eslint-disable-line\n      containerElement.dispatchEvent(new Event(\"scroll\"));\n    } else {\n      window.scrollTo(0, 0);\n      window.dispatchEvent(new Event(\"scroll\"));\n    }\n  }, [containerRef]);\n\n  // Handle closing the menu (with optional scroll reset)\n  const handleClose = useCallback(\n    (resetScroll = false) => {\n      if (resetScroll) {\n        resetScrollPosition();\n      }\n      setOpen(false);\n    },\n    [resetScrollPosition]\n  );\n\n  // Handle Escape key\n  useEffect(() => {\n    const handleKeyDown = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") handleClose();\n    };\n\n    window.addEventListener(\"keydown\", handleKeyDown);\n    return () => window.removeEventListener(\"keydown\", handleKeyDown);\n  }, [handleClose]);\n\n  function handleSelect(item: TOCItem) {\n    setInternalValue(item);\n    externalSetValue?.(item);\n    resetScrollPosition();\n    setOpen(false);\n  }\n\n  const sharedProps = {\n    data,\n    open,\n    value,\n    setValue: handleSelect,\n    scrollProgress,\n    layoutPrefix,\n  };\n\n  return (\n    <MotionConfig transition={transition}>\n      {/* Backdrop */}\n      <AnimatePresence initial={false}>\n        {open && (\n          <motion.div\n            role=\"button\"\n            aria-label=\"Close\"\n            onClick={() => handleClose()}\n            className=\"fixed inset-0 z-10 bg-background/10 backdrop-blur-xs\"\n            initial={{ opacity: 0, backdropFilter: \"blur(0px)\" }}\n            animate={{ opacity: 1, backdropFilter: \"blur(4px)\" }}\n            exit={{ opacity: 0, backdropFilter: \"blur(0px)\" }}\n          />\n        )}\n      </AnimatePresence>\n\n      <div\n        className={cn(\n          \"relative z-20 cursor-pointer select-none\",\n          \"[--height-opened:150px] [--width-opened:350px] [--width:220px]\",\n          \"text-white/80\",\n          className\n        )}\n      >\n        {/* Collapsed State */}\n        <motion.div\n          role=\"button\"\n          aria-label=\"Open\"\n          tabIndex={0}\n          onClick={() => setOpen((prev) => !prev)}\n          layoutId={`${layoutPrefix}-${CONTAINER_LAYOUT_ID}`}\n          style={{ borderRadius: 24 }}\n          className={cn(\n            \"relative flex h-10 cursor-pointer items-center overflow-hidden px-1 outline-hidden!\",\n            \"min-w-(--width) bg-zinc-900\"\n          )}\n        >\n          <div className=\"absolute top-0 left-1/2 h-full w-[calc(var(--width-opened)-50px)] -translate-x-1/2\">\n            <motion.div\n              layoutId={`${layoutPrefix}-${ITEMS_LAYOUT_ID}`}\n              layout=\"position\"\n              className=\"h-full w-full\"\n            />\n          </div>\n\n          <div className=\"w-full\">\n            <ProgressText {...sharedProps} />\n          </div>\n          <div className=\"absolute top-0 right-0 bottom-0 flex items-center pr-1\">\n            <ProgressIndicator {...sharedProps} />\n          </div>\n        </motion.div>\n\n        {/* Expanded State */}\n        <div className=\"absolute top-0 left-1/2 -translate-x-1/2\">\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {open && (\n              <motion.div\n                role=\"button\"\n                aria-label=\"Close\"\n                tabIndex={0}\n                onClick={() => handleClose()}\n                layoutId={`${layoutPrefix}-${CONTAINER_LAYOUT_ID}`}\n                className={cn(\n                  \"cursor-pointer justify-center overflow-hidden p-5 pt-14\",\n                  \"min-h-(--height-opened) w-(--width-opened) bg-zinc-900\"\n                )}\n                style={{ borderRadius: 24 }}\n              >\n                <motion.div\n                  layoutId={`${layoutPrefix}-${ITEMS_LAYOUT_ID}`}\n                  layout=\"position\"\n                >\n                  <ItemsList data={data} setValue={handleSelect} />\n                </motion.div>\n                <div className=\"absolute top-3 right-3 left-3\">\n                  <ProgressText {...sharedProps} />\n                </div>\n                <div className=\"absolute top-3 right-3\">\n                  <ProgressIndicator {...sharedProps} />\n                </div>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n\nexport { DynamicScrollIslandTOC };\n",
      "type": "registry:component"
    }
  ],
  "docs": "https://jyotimoydas.in/components/dynamic-scroll-island-toc",
  "type": "registry:component"
}
