{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "path-beam",
  "title": "Path Beam",
  "description": "A beam of light travelling along the paths of a flow diagram, one after another, on view, with the scroll or from your own progress.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-in-view",
    "@corsair-ui/use-media-query"
  ],
  "files": [
    {
      "path": "registry/default/ui/path-beam.tsx",
      "content": "\"use client\";\n\nimport {\n  useMemo,\n  useRef,\n  useState,\n  type AnimationEvent,\n  type ComponentProps,\n  type CSSProperties,\n  type Ref,\n} from \"react\";\n\nimport { useInView } from \"@/registry/default/hooks/use-in-view\";\nimport { useMediaQuery } from \"@/registry/default/hooks/use-media-query\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// Scroll mode animates the overall progress on the svg and every beam reads\n// it. Registered as an inherited number so CSS interpolates it smoothly; an\n// unregistered custom property would jump from start to end instead.\nif (typeof CSS !== \"undefined\" && \"registerProperty\" in CSS) {\n  try {\n    CSS.registerProperty({\n      name: \"--path-beam-progress\",\n      syntax: \"<number>\",\n      inherits: true,\n      initialValue: \"0\",\n    });\n  } catch {\n    // Already registered by another copy of the component.\n  }\n}\n\nfunction mergeRefs<T>(...refs: (Ref<T> | undefined)[]) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    }\n  };\n}\n\nconst clamp01 = (value: number) => Math.min(Math.max(Number.isFinite(value) ? value : 0, 0), 1);\nconst round = (value: number) => Math.round(value * 1e4) / 1e4;\n\ntype PathBeamState = \"idle\" | \"running\" | \"done\";\n\ninterface PathBeamProps extends Omit<ComponentProps<\"svg\">, \"children\"> {\n  /** SVG path data, travelled in this order. Use the same coordinates as `viewBox`. */\n  paths: string[];\n  /** Draw each path in full underneath, as a faint track. */\n  track?: boolean;\n  /** Classes for the track strokes. */\n  trackClassName?: string;\n  /** Classes for the beam and its glow, usually a stroke colour. */\n  beamClassName?: string;\n  /** A wider, fainter copy of the beam underneath it. */\n  glow?: boolean;\n  /** Length of the beam, as a fraction of each path, from 0 to 1. */\n  beamLength?: number;\n  /** Width of the track and the beam; the glow is four times as wide. */\n  strokeWidth?: number;\n  /**\n   * \"in-view\" sends the beam when the diagram scrolls into view. \"scroll\"\n   * moves it with the scroll position, on CSS scroll-driven animations;\n   * browsers without them show the track alone. \"manual\" follows `progress`\n   * and nothing else, for diagrams driven by your own timeline.\n   */\n  trigger?: \"in-view\" | \"scroll\" | \"manual\";\n  /** In-view: play the first time only. Otherwise it plays again each time it comes back. */\n  once?: boolean;\n  /**\n   * Manual: where the beam is, from 0 to 1 over the whole sequence. With n\n   * paths, path i covers [i / n, (i + 1) / n].\n   */\n  progress?: number;\n  /** In-view: time for the beam to cross one path, in ms. */\n  duration?: number;\n  /** In-view: wait before the first path, in ms. With `loop`, before every cycle. */\n  delay?: number;\n  /**\n   * In-view: wait between the end of one path and the start of the next, in\n   * ms. Path i starts at `delay + i * (duration + stagger)`; negative values overlap them.\n   */\n  stagger?: number;\n  /** In-view: run the sequence again and again. It pauses while off screen. */\n  loop?: boolean;\n  /** Scroll: the CSS `animation-range` the whole sequence spans. */\n  range?: string;\n  /** In-view: called once the last path has been crossed. Never called with `loop`. */\n  onComplete?: () => void;\n  /** In-view: called each time the beam leaves a path, with its index. */\n  onPathComplete?: (index: number) => void;\n}\n\n/**\n * A beam of light that travels along the lines of a flow diagram, one path\n * after another, so each step lights up as it arrives. Draw the lines as SVG\n * paths over your nodes; the beam is a bright dash with a cheap glow (a\n * wider, fainter copy of the same dash, no filters) moving by\n * `stroke-dashoffset` alone.\n *\n * State for lighting the nodes: the svg has `data-state` (\"idle\",\n * \"running\", \"done\") and each path's group (`data-slot=\"path-beam-path\"`,\n * with `data-index`) its own, \"running\" while the beam is on it and \"done\"\n * once it has passed. Style a node from it, or listen to `onPathComplete`.\n * In manual mode the svg also sets `--path-beam-progress` (0 to 1).\n *\n * The svg is decorative and hidden from screen readers: label the diagram\n * itself. With `prefers-reduced-motion` the track shows, the beam does not,\n * and in-view diagrams are \"done\" straight away without calling\n * `onComplete`. Without JavaScript the track shows and the beam does not run.\n * Scroll mode is CSS alone, with no state on the paths: use \"manual\" with\n * your own scroll hook when nodes have to follow it. Manual mode is not\n * changed by reduced motion, as the parent is in charge.\n *\n * Looping restarts the sequence when the last path ends, so every cycle\n * waits `delay` again, and pauses while off screen.\n *\n * @example\n * <div className=\"relative\" aria-label=\"From player to venue account\" role=\"img\">\n *   <PathBeam\n *     viewBox=\"0 0 300 40\"\n *     paths={[\"M10 20 H140\", \"M160 20 H290\"]}\n *     onPathComplete={(index) => setReached(index + 1)}\n *     className=\"absolute inset-0 size-full\"\n *   />\n * </div>\n *\n * @example\n * // Driven by your own progress, from 0 to 1.\n * <PathBeam trigger=\"manual\" progress={value} paths={paths} viewBox=\"0 0 300 40\" />\n */\nfunction PathBeam({\n  paths,\n  track = true,\n  trackClassName = \"stroke-border\",\n  beamClassName = \"stroke-primary\",\n  glow = true,\n  beamLength = 0.2,\n  strokeWidth = 2,\n  trigger = \"in-view\",\n  once = true,\n  progress = 0,\n  duration = 1200,\n  delay = 0,\n  stagger = 0,\n  loop = false,\n  range = \"entry 25% cover 60%\",\n  onComplete,\n  onPathComplete,\n  className,\n  style,\n  ref,\n  ...props\n}: PathBeamProps) {\n  const count = paths.length;\n  const length = round(clamp01(beamLength));\n  const reduced = useMediaQuery(\"(prefers-reduced-motion: reduce)\");\n  const timed = trigger === \"in-view\";\n\n  // In-view: the sequence's phase, which paths the beam has reached and left,\n  // and a cycle number that remounts the beams to restart their animations.\n  const [phase, setPhase] = useState<PathBeamState>(\"idle\");\n  const [cycle, setCycle] = useState(0);\n  const [started, setStarted] = useState<ReadonlySet<number>>(() => new Set());\n  const [ended, setEnded] = useState<ReadonlySet<number>>(() => new Set());\n  const endedRef = useRef(new Set<number>());\n\n  const reset = () => {\n    endedRef.current = new Set();\n    setStarted(new Set());\n    setEnded(new Set());\n  };\n\n  const [observe, inView] = useInView<SVGSVGElement>({\n    // A loop keeps watching to pause off screen.\n    once: once && !loop,\n    amount: 0.3,\n    onChange: (visible) => {\n      if (!timed) return;\n      if (visible) {\n        setPhase((current) => (current === \"idle\" ? \"running\" : current));\n      } else if (!once && !loop) {\n        // Rearm, and remount the beams so a late animationend cannot count.\n        setPhase(\"idle\");\n        setCycle((current) => current + 1);\n        reset();\n      }\n    },\n  });\n  const mergedRef = useMemo(\n    () => mergeRefs(ref, timed ? observe : undefined),\n    [ref, observe, timed]\n  );\n\n  // Path i starts at delay + i * (duration + stagger).\n  const starts = paths.map((_, index) => Math.max(0, delay + index * (duration + stagger)));\n  // The path whose beam ends last; with equal durations, the last to start.\n  const lastIndex = starts.reduce(\n    (last, start, index) => (start >= starts[last]! ? index : last),\n    0\n  );\n\n  const handleEnd = (index: number) => (event: AnimationEvent<SVGPathElement>) => {\n    if (event.target !== event.currentTarget || endedRef.current.has(index)) return;\n    endedRef.current.add(index);\n    setEnded(new Set(endedRef.current));\n    onPathComplete?.(index);\n    if (index !== lastIndex) return;\n    if (loop) {\n      setCycle((current) => current + 1);\n      reset();\n      return;\n    }\n    setPhase(\"done\");\n    onComplete?.();\n  };\n  const handleStart = (index: number) => (event: AnimationEvent<SVGPathElement>) => {\n    if (event.target !== event.currentTarget) return;\n    setStarted((current) => (current.has(index) ? current : new Set(current).add(index)));\n  };\n\n  const drawn = clamp01(progress);\n  // Manual: how far along its own path the beam is, from 0 to 1.\n  const local = (index: number) => clamp01(drawn * count - index);\n\n  const rootState: PathBeamState | undefined =\n    trigger === \"manual\"\n      ? drawn >= 1\n        ? \"done\"\n        : drawn <= 0\n          ? \"idle\"\n          : \"running\"\n      : trigger === \"scroll\"\n        ? undefined\n        : reduced\n          ? \"done\"\n          : phase;\n\n  const pathState = (index: number): PathBeamState | undefined => {\n    if (trigger === \"manual\") {\n      const at = local(index);\n      return at >= 1 ? \"done\" : at <= 0 ? \"idle\" : \"running\";\n    }\n    if (trigger === \"scroll\") return undefined;\n    if (rootState === \"done\" || ended.has(index)) return \"done\";\n    if (rootState === \"running\" && started.has(index)) return \"running\";\n    return \"idle\";\n  };\n\n  // The dash is `length` long with a gap of one path: at an offset of\n  // `length` it sits just before the start, at -1 just past the end.\n  const beamStyle = (index: number): CSSProperties => {\n    if (trigger === \"manual\") {\n      return { strokeDashoffset: round(length - (length + 1) * local(index)) };\n    }\n    if (trigger === \"scroll\") {\n      // Each beam takes its share of the overall progress the svg animates.\n      const share = `clamp(0, var(--path-beam-progress, 0) * ${count} - ${index}, 1)`;\n      return {\n        strokeDashoffset: `calc((${length} - ${round(length + 1)} * ${share}) * 1px)`,\n        opacity: reduced ? 0 : undefined,\n      };\n    }\n    if (reduced) return { strokeDashoffset: -1, opacity: 0 };\n    if (phase === \"done\") return { strokeDashoffset: -1 };\n    if (phase === \"idle\") return { strokeDashoffset: length };\n    return {\n      strokeDashoffset: length,\n      animationDuration: `${duration}ms`,\n      animationDelay: `${starts[index]}ms`,\n      animationIterationCount: 1,\n      animationPlayState: loop && !inView ? \"paused\" : undefined,\n    };\n  };\n\n  const animated = timed && !reduced && phase === \"running\";\n  const beamClass = animated ? \"motion-safe:animate-path-beam\" : undefined;\n\n  return (\n    <svg\n      ref={mergedRef}\n      data-slot=\"path-beam\"\n      data-trigger={trigger}\n      data-state={rootState}\n      aria-hidden=\"true\"\n      focusable=\"false\"\n      fill=\"none\"\n      strokeWidth={strokeWidth}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={cn(\n        \"overflow-visible\",\n        trigger === \"scroll\" &&\n          \"supports-[animation-timeline:view()]:animate-path-beam-progress motion-reduce:!animate-none\",\n        className\n      )}\n      style={\n        {\n          \"--path-beam-length\": length,\n          ...(trigger === \"manual\" ? { \"--path-beam-progress\": round(drawn) } : null),\n          // After the utility's shorthand, which would reset them.\n          ...(trigger === \"scroll\" ? { animationTimeline: \"view()\", animationRange: range } : null),\n          ...style,\n        } as CSSProperties\n      }\n      {...props}\n    >\n      {paths.map((d, index) => {\n        const state = pathState(index);\n        const beam = beamStyle(index);\n        // Butt caps: a round cap would leave a dot at either end while the dash waits there.\n        const dash = {\n          d,\n          pathLength: 1,\n          strokeDasharray: `${length} 1`,\n          strokeLinecap: \"butt\",\n        } as const;\n        return (\n          <g key={index} data-slot=\"path-beam-path\" data-index={index} data-state={state}>\n            {track ? <path data-slot=\"path-beam-track\" d={d} className={trackClassName} /> : null}\n            {glow ? (\n              <path\n                key={`glow-${cycle}`}\n                data-slot=\"path-beam-glow\"\n                {...dash}\n                strokeWidth={strokeWidth * 4}\n                className={cn(\"opacity-25\", beamClassName, beamClass)}\n                style={beam}\n              />\n            ) : null}\n            <path\n              key={`beam-${cycle}`}\n              data-slot=\"path-beam-beam\"\n              {...dash}\n              className={cn(beamClassName, beamClass)}\n              style={beam}\n              onAnimationStart={timed ? handleStart(index) : undefined}\n              onAnimationEnd={timed ? handleEnd(index) : undefined}\n            />\n          </g>\n        );\n      })}\n    </svg>\n  );\n}\n\nexport { PathBeam, type PathBeamProps };\n",
      "type": "registry:ui"
    }
  ],
  "tailwind": {
    "config": {
      "theme": {
        "extend": {
          "keyframes": {
            "path-beam": {
              "from": {
                "stroke-dashoffset": "var(--path-beam-length, 0.2)"
              },
              "to": {
                "stroke-dashoffset": "-1"
              }
            },
            "path-beam-progress": {
              "from": {
                "--path-beam-progress": "0"
              },
              "to": {
                "--path-beam-progress": "1"
              }
            }
          },
          "animation": {
            "path-beam": "path-beam 1.2s ease-in-out both",
            "path-beam-progress": "path-beam-progress linear both"
          }
        }
      }
    }
  },
  "cssVars": {
    "theme": {
      "animate-path-beam": "path-beam 1.2s ease-in-out both",
      "animate-path-beam-progress": "path-beam-progress linear both"
    }
  },
  "css": {
    "@keyframes path-beam": {
      "from": {
        "stroke-dashoffset": "var(--path-beam-length, 0.2)"
      },
      "to": {
        "stroke-dashoffset": "-1"
      }
    },
    "@keyframes path-beam-progress": {
      "from": {
        "--path-beam-progress": "0"
      },
      "to": {
        "--path-beam-progress": "1"
      }
    }
  },
  "categories": [
    "creative"
  ],
  "type": "registry:ui"
}