{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "signature",
  "title": "Signature",
  "description": "Draws SVG strokes as if by hand, with optional ink filling in behind the pen, on view or with the scroll.",
  "registryDependencies": [
    "@corsair-ui/utils",
    "@corsair-ui/use-in-view"
  ],
  "files": [
    {
      "path": "registry/default/ui/signature.tsx",
      "content": "\"use client\";\n\nimport {\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type Ref,\n} from \"react\";\n\nimport { useInView } from \"@/registry/default/hooks/use-in-view\";\nimport { cn } from \"@/registry/default/lib/utils\";\n\n// Strokes speed up and slow down like a pen.\nconst PEN = \"cubic-bezier(0.65, 0, 0.35, 1)\";\n// A hair past a full length, so round caps leave no dot before drawing starts.\nconst UNDRAWN = 1.01;\n\nfunction prefersReducedMotion() {\n  return window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\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\ninterface SignatureProps extends Omit<ComponentProps<\"svg\">, \"children\"> {\n  /** SVG path data, drawn in this order. Use the same coordinates as `viewBox`. */\n  paths: string[];\n  /**\n   * \"in-view\" draws once when the drawing scrolls into view. \"scroll\" draws\n   * with the scroll position, on CSS scroll-driven animations; browsers\n   * without them show it finished. Scroll follows the nearest scroll\n   * container: clip ancestors with `overflow-clip`, as `overflow-hidden` makes\n   * one that never scrolls. \"manual\" follows `progress` and nothing else,\n   * for drawings driven by your own timeline, a slider or a scroll hook.\n   */\n  trigger?: \"in-view\" | \"scroll\" | \"manual\";\n  /**\n   * Manual: how much is drawn, from 0 to 1. Strokes are drawn in order, each\n   * taking a share of the progress proportional to its length.\n   */\n  progress?: number;\n  /** In-view: total drawing time in ms; longer strokes get a bigger share. */\n  duration?: number;\n  /** In-view: wait before the first stroke, in ms. */\n  delay?: number;\n  /** Scroll: the CSS `animation-range` the drawing spans. */\n  scrollRange?: string;\n  /**\n   * Width of the pen. With `ink`, 0 draws the fill alone, without the\n   * outline strokes.\n   */\n  strokeWidth?: number;\n  /**\n   * Fill the shapes as the pen passes, like ink soaking into letters. For\n   * closed outlines such as glyphs; leave it off for open lines and routes.\n   */\n  ink?: boolean;\n  /** Ink: how wide it spreads behind the pen, in viewBox units. */\n  inkWidth?: number;\n}\n\n/**\n * Draws SVG strokes as if by hand: a signature, a route on a map, an\n * underline. Strokes use the current text colour; with `ink`, closed\n * shapes fill in behind the pen. Give it an `aria-label` when it carries\n * meaning; without one it is hidden from screen readers. With\n * `prefers-reduced-motion` it appears finished. To write any text in a\n * font of your choice, see TextSignature.\n *\n * In-view drawings start blank, so they need JavaScript to show up.\n *\n * With `trigger=\"manual\"` the drawing follows `progress` and nothing else:\n * no observer and no transition, and `prefers-reduced-motion` does not\n * finish it for you, as the parent is in charge. Pass 1 when it should\n * appear finished, e.g. when your own timeline is off for reduced motion.\n *\n * Outlines with holes (the counters of \"o\" or \"B\") fill correctly with\n * `fillRule=\"evenodd\"` on the component: the ink inherits it from the svg.\n *\n * @example\n * <Signature\n *   aria-label=\"Signed, the captain\"\n *   viewBox=\"0 0 200 60\"\n *   paths={[\"M10 40 C 40 10, 60 60, 90 30\", \"M100 35 L 190 35\"]}\n *   className=\"text-foreground w-48\"\n * />\n *\n * @example\n * // Driven by your own progress, from 0 to 1.\n * <Signature trigger=\"manual\" progress={value} paths={paths} viewBox=\"0 0 200 60\" />\n */\nfunction Signature({\n  paths,\n  trigger = \"in-view\",\n  duration = 2400,\n  delay = 0,\n  progress = 0,\n  scrollRange = \"entry 25% cover 50%\",\n  strokeWidth = 2,\n  ink = false,\n  inkWidth = 14,\n  className,\n  style,\n  ref,\n  \"aria-label\": label,\n  ...props\n}: SignatureProps) {\n  const id = useId().replace(/[^\\w-]/g, \"\");\n  const timeline = `--signature-${id}`;\n  const maskId = `signature-ink-${id}`;\n  // With ink and no pen, only the fill shows: the outline strokes are left out.\n  const showStrokes = !(ink && strokeWidth === 0);\n  // The paths measured for timing: the strokes, or the ink mask without them.\n  const measured = useRef<(SVGPathElement | null)[]>([]);\n  const measure = () =>\n    paths.map((_, index) => {\n      const path = measured.current[index];\n      return typeof path?.getTotalLength === \"function\" ? path.getTotalLength() : 1;\n    });\n  const [drawing, setDrawing] = useState<{ lengths: number[]; instant: boolean } | null>(null);\n  const [observe] = useInView<SVGSVGElement>({\n    once: true,\n    amount: 0.4,\n    onChange: (inView) => {\n      if (!inView) return;\n      setDrawing({ lengths: measure(), instant: prefersReducedMotion() });\n    },\n  });\n  // Manual: lengths are measured once mounted; until then every stroke gets an equal share.\n  const pathsKey = paths.join(\"\\n\");\n  const [manualLengths, setManualLengths] = useState<{ key: string; lengths: number[] } | null>(\n    null\n  );\n  useEffect(() => {\n    if (trigger !== \"manual\") return;\n    // Measured before the next paint, once layout has the paths.\n    const frame = requestAnimationFrame(() =>\n      setManualLengths({ key: pathsKey, lengths: measure() })\n    );\n    return () => cancelAnimationFrame(frame);\n    // `measure` reads the current paths, which `pathsKey` stands for.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [trigger, pathsKey, showStrokes]);\n  const mergedRef = useMemo(\n    () => mergeRefs(ref, trigger === \"in-view\" ? observe : undefined),\n    [ref, observe, trigger]\n  );\n\n  // Each stroke gets a share of `duration` proportional to its length, and\n  // starts when the previous one ends.\n  const total = drawing?.lengths.reduce((sum, length) => sum + length, 0) || 1;\n  const timings = (drawing?.lengths ?? []).map((length) => (length / total) * duration);\n  const waits = timings.map(\n    (_, index) => delay + timings.slice(0, index).reduce((sum, share) => sum + share, 0)\n  );\n\n  // Manual: where each stroke starts and ends along the whole drawing, from 0 to 1.\n  const manualShares = (() => {\n    if (trigger !== \"manual\") return [];\n    const lengths =\n      manualLengths?.key === pathsKey && manualLengths.lengths.length === paths.length\n        ? manualLengths.lengths\n        : paths.map(() => 1);\n    const sum = lengths.reduce((a, b) => a + b, 0) || 1;\n    let start = 0;\n    return lengths.map((length) => {\n      const share = { start: start / sum, size: length / sum };\n      start += length;\n      return share;\n    });\n  })();\n  const drawn = Math.min(Math.max(Number.isFinite(progress) ? progress : 0, 0), 1);\n\n  const drawClass =\n    trigger === \"scroll\"\n      ? \"supports-[animation-timeline:view()]:animate-signature-draw motion-reduce:!animate-none\"\n      : undefined;\n\n  const strokeStyle = (index: number): CSSProperties => {\n    if (trigger === \"manual\") {\n      const share = manualShares[index];\n      const local = share\n        ? share.size > 0\n          ? Math.min(Math.max((drawn - share.start) / share.size, 0), 1)\n          : drawn >= share.start\n            ? 1\n            : 0\n        : 0;\n      return { strokeDasharray: \"1 2\", strokeDashoffset: local <= 0 ? UNDRAWN : 1 - local };\n    }\n    if (trigger === \"scroll\") {\n      return {\n        strokeDasharray: \"1 2\",\n        strokeDashoffset: 0,\n        animationTimeline: timeline,\n        animationRange: scrollRange,\n      };\n    }\n    if (!drawing) return { strokeDasharray: \"1 2\", strokeDashoffset: UNDRAWN };\n    return {\n      strokeDasharray: \"1 2\",\n      strokeDashoffset: 0,\n      transition: drawing.instant\n        ? undefined\n        : `stroke-dashoffset ${timings[index] ?? 0}ms ${PEN} ${waits[index] ?? 0}ms`,\n    };\n  };\n\n  return (\n    <svg\n      ref={mergedRef}\n      data-slot=\"signature\"\n      data-trigger={trigger}\n      data-state={\n        trigger === \"in-view\"\n          ? drawing\n            ? \"drawn\"\n            : \"blank\"\n          : trigger === \"manual\"\n            ? drawn >= 1\n              ? \"drawn\"\n              : drawn <= 0\n                ? \"blank\"\n                : \"drawing\"\n            : undefined\n      }\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={strokeWidth}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      role={label ? \"img\" : undefined}\n      aria-label={label}\n      aria-hidden={label ? undefined : true}\n      className={cn(\"overflow-visible\", className)}\n      style={{ ...(trigger === \"scroll\" ? { viewTimelineName: timeline } : null), ...style }}\n      {...props}\n    >\n      {ink ? (\n        <>\n          {/*\n            Wide strokes drawn in step with the pen reveal the filled shapes\n            behind it. The mask region stays the default, around the shapes'\n            own box, so it covers them whatever the viewBox.\n          */}\n          <mask id={maskId}>\n            <g stroke=\"white\" strokeWidth={inkWidth}>\n              {paths.map((d, index) => (\n                <path\n                  key={index}\n                  ref={\n                    showStrokes\n                      ? undefined\n                      : (node) => {\n                          measured.current[index] = node;\n                        }\n                  }\n                  d={d}\n                  pathLength={1}\n                  className={drawClass}\n                  style={strokeStyle(index)}\n                />\n              ))}\n            </g>\n          </mask>\n          <g mask={`url(#${maskId})`} fill=\"currentColor\" stroke=\"none\">\n            {paths.map((d, index) => (\n              <path key={index} d={d} />\n            ))}\n          </g>\n        </>\n      ) : null}\n      {showStrokes\n        ? paths.map((d, index) => (\n            <path\n              key={index}\n              ref={(node) => {\n                measured.current[index] = node;\n              }}\n              d={d}\n              pathLength={1}\n              className={drawClass}\n              style={strokeStyle(index)}\n            />\n          ))\n        : null}\n    </svg>\n  );\n}\n\nexport { Signature, type SignatureProps };\n",
      "type": "registry:ui"
    }
  ],
  "tailwind": {
    "config": {
      "theme": {
        "extend": {
          "keyframes": {
            "signature-draw": {
              "from": {
                "stroke-dashoffset": "1.01"
              },
              "to": {
                "stroke-dashoffset": "0"
              }
            }
          },
          "animation": {
            "signature-draw": "signature-draw linear both"
          }
        }
      }
    }
  },
  "cssVars": {
    "theme": {
      "animate-signature-draw": "signature-draw linear both"
    }
  },
  "css": {
    "@keyframes signature-draw": {
      "from": {
        "stroke-dashoffset": "1.01"
      },
      "to": {
        "stroke-dashoffset": "0"
      }
    }
  },
  "categories": [
    "creative"
  ],
  "type": "registry:ui"
}