{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"constellation-preloader","type":"registry:component","title":"Constellation Preloader","description":"A single dot bursts into a ring of twelve, a thread runs from dot to dot and weaves a star, spokes fill it into a sunburst that turns one step, then it all folds back into one dot, which opens up to reveal the page.","dependencies":["framer-motion"],"files":[{"path":"registry/dot/constellation-preloader.tsx","type":"registry:component","target":"components/dot/constellation-preloader.tsx","content":"\"use client\";\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { animate, motion, useMotionTemplate, useMotionValue, useReducedMotion, useTransform, type MotionStyle, type TargetAndTransition } from \"framer-motion\";\n\nexport type ConstellationExitStyle = \"expand\" | \"collapse\" | \"fade\";\n\nexport interface ConstellationPreloaderProps {\n  /** Dots on the ring (8–16) */\n  dots?: number;\n  /** Seconds each shape holds */\n  stepDuration?: number;\n  /** Size of the figure in px; it shrinks on small screens */\n  size?: number;\n  backgroundColor?: string;\n  /** Dots and lines */\n  color?: string;\n  /** Opacity of the lines (0–1) */\n  lineOpacity?: number;\n  /** \"expand\": the last dot opens up to reveal the page · \"collapse\": the screen shrinks into the dot · \"fade\" */\n  exitStyle?: ConstellationExitStyle;\n  /** Seconds for the reveal */\n  exitDuration?: number;\n  /** Cover the viewport (true) or fill the nearest positioned parent (false) */\n  fullscreen?: boolean;\n  /** Prevent page scrolling while the preloader is visible (fullscreen only) */\n  lockScroll?: boolean;\n  showOncePerSession?: boolean;\n  zIndex?: number;\n  onComplete?: () => void;\n  className?: string;\n}\n\nconst OUT = [0.22, 1, 0.36, 1] as const;\nconst IN_OUT = [0.76, 0, 0.24, 1] as const;\n\n// Figure in a 240-unit box centred on 0,0\nconst R = 96;\nconst DOT_R = 4.4;\ntype P = readonly [number, number];\nconst polar = (deg: number, radius: number): P => {\n  const a = (deg * Math.PI) / 180;\n  return [Math.cos(a) * radius, Math.sin(a) * radius];\n};\n\nconst SESSION_KEY = \"dot-constellation-preloader-shown\";\nconst noopSubscribe = () => () => {};\nfunction readShownThisSession() {\n  try {\n    return sessionStorage.getItem(SESSION_KEY) === \"true\";\n  } catch {\n    return false; // storage blocked: just play\n  }\n}\n\n/** 0 one dot · 1 ring · 2 star · 3 sunburst · 4 back to one dot · 5 reveal · 6 done */\ntype Phase = 0 | 1 | 2 | 3 | 4 | 5 | 6;\n\n/**\n * Fullscreen preloader: one dot bursts into a ring of dots around a centre dot, a thread runs from\n * dot to dot and weaves a star, then spokes reach out from the centre to every dot and the whole\n * figure turns one step. It all folds back into one dot, which opens up to reveal the page.\n * Pauses while offscreen.\n */\nexport function ConstellationPreloader({\n  dots = 12,\n  stepDuration = 1.2,\n  size = 220,\n  backgroundColor = \"#000000\",\n  color = \"#FFFFFF\",\n  lineOpacity = 0.8,\n  exitStyle = \"expand\",\n  exitDuration = 0.9,\n  fullscreen = true,\n  lockScroll = true,\n  showOncePerSession = false,\n  zIndex = 9999,\n  onComplete,\n  className,\n}: ConstellationPreloaderProps) {\n  const reduceMotion = useReducedMotion() ?? false;\n  const n = Math.max(8, Math.min(16, Math.round(dots)));\n  const step = Math.max(0.5, stepDuration);\n\n  const [phase, setPhase] = useState<Phase>(0);\n  const exit = reduceMotion ? \"fade\" : exitStyle;\n\n  // \"expand\": a hole opens from the centre dot (a radial mask whose radius grows to every corner)\n  const hole = useMotionValue(0);\n  const holeEdge = useTransform(hole, (v) => (v === 0 ? 0 : v + 0.4));\n  const mask = useMotionTemplate`radial-gradient(circle at 50% 50%, transparent ${hole}%, #000 ${holeEdge}%)`;\n  useEffect(() => {\n    if (phase !== 5 || exit !== \"expand\") return;\n    const controls = animate(hole, 100, {\n      duration: exitDuration,\n      ease: [0.7, 0, 0.2, 1],\n    });\n    return () => controls.stop();\n  }, [phase, exit, exitDuration, hole]);\n\n  const [inView, setInView] = useState(true);\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const onCompleteRef = useRef(onComplete);\n  useEffect(() => {\n    onCompleteRef.current = onComplete;\n  });\n\n  const shownThisSession = useSyncExternalStore(noopSubscribe, readShownThisSession, () => false);\n  const skipped = showOncePerSession && shownThisSession && phase === 0;\n  useEffect(() => {\n    if (skipped) onCompleteRef.current?.();\n  }, [skipped]);\n\n  useEffect(() => {\n    const node = rootRef.current;\n    if (!node || typeof IntersectionObserver === \"undefined\") return;\n    const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting), { threshold: 0.05 });\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  useEffect(() => {\n    if (!fullscreen || !lockScroll || phase === 6 || skipped) return;\n    const html = document.documentElement;\n    const previous = html.style.overflow;\n    html.style.overflow = \"hidden\";\n    return () => {\n      html.style.overflow = previous;\n    };\n  }, [fullscreen, lockScroll, phase, skipped]);\n\n  // Pause while offscreen until the fold back; after that always finish (the exit moves the\n  // preloader out of view, which must not stall it)\n  const paused = phase < 4 && !inView;\n\n  // One shape at a time, then fold back, reveal and finish. The star holds a little longer while\n  // its thread is drawn.\n  useEffect(() => {\n    if (skipped || paused || phase === 6) return;\n    const ms = phase === 0 ? step * 650 : phase === 2 ? step * 1000 + 400 : phase < 4 ? step * 1000 : phase === 4 ? 650 : exitDuration * 1000 + 80;\n    const timer = setTimeout(() => {\n      if (phase === 5) {\n        if (showOncePerSession) {\n          try {\n            sessionStorage.setItem(SESSION_KEY, \"true\");\n          } catch {\n            // ignore: worst case it shows again\n          }\n        }\n        onCompleteRef.current?.();\n      }\n      setPhase((p) => (p + 1) as Phase);\n    }, ms);\n    return () => clearTimeout(timer);\n  }, [phase, paused, skipped, step, exitDuration, showOncePerSession]);\n\n  if (phase === 6 || skipped) return null;\n\n  const revealing = phase === 5;\n  const shaped = phase >= 1 && phase <= 3;\n  const bloom = phase === 3;\n  // Where each ring dot sits: on the ring, or at the centre before and after\n  const pos = (i: number): P => (shaped ? polar(-90 + (360 / n) * i, R) : [0, 0]);\n  const points = Array.from({ length: n }, (_, i) => pos(i));\n  // The star: each dot to the one `skip` places on, drawn one chord after another like a thread\n  // (a step that shares no factor with the dot count, so one thread visits every dot)\n  const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);\n  let skip = Math.floor(n / 2) - 1;\n  while (skip > 2 && gcd(n, skip) !== 1) skip--;\n  const order = Array.from({ length: n }, (_, k) => (k * skip) % n);\n  const threadTime = 0.9 + step * 0.3;\n\n  const move = (i: number) =>\n    reduceMotion ? { duration: 0.3 } : phase === 1 ? { duration: 0.85, ease: OUT, delay: i * 0.025 } : { duration: 0.55, ease: IN_OUT };\n  const lineStyle = {\n    stroke: color,\n    strokeOpacity: lineOpacity,\n    strokeWidth: 1.1,\n    vectorEffect: \"non-scaling-stroke\" as const,\n    fill: \"none\",\n    strokeLinecap: \"round\" as const,\n  };\n  const dotR = revealing && exit !== \"collapse\" ? 0 : phase === 0 || phase === 4 ? DOT_R * 1.3 : DOT_R;\n\n  const reveal: TargetAndTransition = !revealing\n    ? { opacity: 1, clipPath: \"circle(150% at 50% 50%)\" }\n    : exit === \"collapse\"\n      ? { clipPath: \"circle(0% at 50% 50%)\" }\n      : exit === \"fade\"\n        ? { opacity: 0 }\n        : {};\n\n  const root: MotionStyle = {\n    position: fullscreen ? \"fixed\" : \"absolute\",\n    inset: 0,\n    zIndex,\n    overflow: \"hidden\",\n    containerType: \"size\",\n    background: backgroundColor,\n    userSelect: \"none\",\n    WebkitUserSelect: \"none\",\n    pointerEvents: revealing ? \"none\" : \"auto\",\n    ...(exit === \"expand\" ? { maskImage: mask, WebkitMaskImage: mask } : {}),\n  };\n\n  return (\n    <motion.div\n      ref={rootRef}\n      role=\"status\"\n      aria-live=\"polite\"\n      aria-label=\"Loading\"\n      aria-busy={!revealing}\n      className={className}\n      initial={false}\n      animate={reveal}\n      transition={{ duration: revealing ? exitDuration : 0, ease: IN_OUT }}\n      style={root}\n    >\n      <div\n        style={{\n          position: \"absolute\",\n          left: \"50%\",\n          top: \"50%\",\n          width: `min(${size}px, 50cqmin)`,\n          aspectRatio: \"1\",\n          transform: \"translate(-50%, -50%)\",\n        }}\n      >\n        <svg\n          viewBox=\"-120 -120 240 240\"\n          aria-hidden\n          style={{\n            display: \"block\",\n            width: \"100%\",\n            height: \"100%\",\n            overflow: \"visible\",\n          }}\n        >\n          {/* A ripple while it's a single dot */}\n          {phase === 0 && !reduceMotion && (\n            <motion.circle\n              cx={0}\n              cy={0}\n              fill=\"none\"\n              stroke={color}\n              strokeWidth={1}\n              vectorEffect=\"non-scaling-stroke\"\n              initial={{ r: DOT_R, opacity: 0.6 }}\n              animate={{ r: 40, opacity: 0 }}\n              transition={{\n                duration: Math.max(0.6, step * 0.65),\n                ease: \"easeOut\",\n                delay: 0.15,\n              }}\n            />\n          )}\n\n          {/* Everything below turns one dot-step in the sunburst */}\n          <motion.g\n            initial={false}\n            animate={{ rotate: phase >= 3 ? 360 / n : 0 }}\n            transition={phase === 3 && !reduceMotion ? { duration: 0.9, ease: IN_OUT, delay: 0.35 } : { duration: 0 }}\n          >\n            {/* Sunburst: spokes from the centre to every dot */}\n            {points.map((_, i) => {\n              const [x, y] = polar(-90 + (360 / n) * i, R);\n              return (\n                <motion.line\n                  key={`s${i}`}\n                  x1={0}\n                  y1={0}\n                  x2={x}\n                  y2={y}\n                  {...lineStyle}\n                  initial={{ pathLength: 0, opacity: 0 }}\n                  animate={{\n                    pathLength: bloom ? 1 : 0,\n                    opacity: bloom ? 1 : 0,\n                  }}\n                  transition={\n                    reduceMotion\n                      ? { duration: 0.3 }\n                      : bloom\n                        ? {\n                            pathLength: {\n                              duration: 0.5,\n                              ease: OUT,\n                              delay: i * 0.02,\n                            },\n                            opacity: { duration: 0.15, delay: i * 0.02 },\n                          }\n                        : { duration: 0.3 }\n                  }\n                />\n              );\n            })}\n\n            {/* Star: a thread from dot to dot */}\n            {order.map((a, k) => {\n              const b = order[(k + 1) % n];\n              const on = phase === 2 || bloom;\n              return (\n                <motion.line\n                  key={`c${a}-${b}`}\n                  {...lineStyle}\n                  initial={{\n                    x1: 0,\n                    y1: 0,\n                    x2: 0,\n                    y2: 0,\n                    pathLength: 0,\n                    opacity: 0,\n                  }}\n                  animate={{\n                    x1: points[a][0],\n                    y1: points[a][1],\n                    x2: points[b][0],\n                    y2: points[b][1],\n                    pathLength: on ? 1 : 0,\n                    opacity: on ? 1 : 0,\n                  }}\n                  transition={\n                    reduceMotion\n                      ? { duration: 0.3 }\n                      : {\n                          default: move(a),\n                          pathLength:\n                            phase === 2\n                              ? {\n                                  duration: threadTime / n + 0.12,\n                                  ease: \"linear\",\n                                  delay: (k * threadTime) / n,\n                                }\n                              : { duration: 0.3 },\n                          opacity: phase === 2 ? { duration: 0.05, delay: (k * threadTime) / n } : { duration: 0.3 },\n                        }\n                  }\n                />\n              );\n            })}\n\n            {/* Centre dot, then the ring */}\n            <motion.circle fill={color} cx={0} cy={0} initial={{ r: 0 }} animate={{ r: dotR }} transition={{ duration: 0.45, ease: OUT }} />\n            {points.map(([x, y], i) => (\n              <motion.circle\n                key={`d${i}`}\n                fill={color}\n                initial={{ cx: 0, cy: 0, r: 0 }}\n                animate={{\n                  cx: x,\n                  cy: y,\n                  r: phase === 0 ? 0 : shaped ? DOT_R : dotR,\n                }}\n                transition={move(i)}\n              />\n            ))}\n          </motion.g>\n        </svg>\n      </div>\n    </motion.div>\n  );\n}\n"}],"docs":"Constellation Preloader is ready. Props and a live canvas: https://bydot.co/component/constellation-preloader","meta":{"tier":"free","category":"Preloaders","version":"1.0.0"}}