{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "galley-bracket",
  "title": "Galley Bracket",
  "description": "Remote collaborators' live selections drawn as proofreader's marks: thin corner brackets at each end of a range and a hairline underline, nesting outward by arrival order where ranges overlap, instead of overlapping tinted highlight fills.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/galley-bracket/component.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\n\n// ---------------------------------------------------------------------------\n// GalleyBracket — remote collaborators' live selections drawn as proofreader's\n// marks, not highlight washes: a thin corner bracket at each end of a range,\n// a hairline underline between them, and the selector's initials set small in\n// the left margin at the opening bracket. Ranges are measured off the real\n// rendered text with Range.getClientRects() (a Range over one text node, the\n// same primitive selecting the text and reading getClientRects() would use),\n// so a multi-line selection gets one underline per wrapped line and brackets\n// only at its true start/end — never one per line. When ranges overlap, the\n// only thing that varies per selection is its arrival index within that\n// overlap group (arrival order, not z-index or hue): later arrivals' brackets\n// stand outward from the text by index*3px and draw slightly lighter, so\n// concurrent selections nest like stacked proof brackets instead of blending\n// into a third, unreadable color. Marks draw in with a 160ms stroke-dashoffset\n// reveal on first arrival only — the same selection re-ranging (a drag) never\n// replays it, which is what keeps rapid re-selection from strobing. The SVG\n// layer is aria-hidden; the real accessible surface is a debounced (2s)\n// role=status summary (\"Ana selected 12 words\") plus a keyboard-reachable\n// list of jump buttons that move the platform's own Selection into the named\n// range. Every stroke is --foreground at reduced opacity — no filled\n// highlights, ever, because two overlapping fills produce a third value that\n// identifies nobody. DOM+SVG+CSS only, no canvas.\n// ---------------------------------------------------------------------------\n\nexport interface GalleyBracketSelection {\n  /** stable id for this collaborator's current range */\n  id: string;\n  /** full name — used in the debounced summary and the jump list */\n  name: string;\n  /** short code drawn small in the margin at the opening bracket; derived from `name` if omitted */\n  initials?: string;\n  /** character offset into `text` where the range starts */\n  start: number;\n  /** character offset into `text` where the range ends (exclusive) */\n  end: number;\n  /** arrival order key, lower = earlier. Defaults to this selection's index in the array, so\n   *  passing a freshly-appended selection last is enough to make it the latest arrival. */\n  arrivedAt?: number;\n}\n\nexport interface GalleyBracketProps {\n  /** the shared paragraph's plain text. One instance renders one paragraph — for a\n   *  multi-paragraph editor, render one GalleyBracket per paragraph so range offsets\n   *  stay simple character indices into a single text node. */\n  text: string;\n  /** remote collaborators' current ranges into `text` */\n  selections: GalleyBracketSelection[];\n  /** named in the debounced summary (\"Ana selected 12 words in paragraph 3\") */\n  contextLabel?: string;\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\ntype LocalRect = { left: number; top: number; right: number; bottom: number };\n\nconst BRACKET_ARM = 6; // px, horizontal foot length\nconst OFFSET_STEP = 3; // px, outward nesting distance per arrival index\nconst UNDER_GAP = 4; // px, underline distance below the line's own baseline box\nconst BASE_OPACITY = 0.55;\nconst OPACITY_STEP = 0.09;\nconst MIN_OPACITY = 0.22;\nconst DEBOUNCE_MS = 2000;\n\nfunction clamp(n: number, lo: number, hi: number): number {\n  return Math.max(lo, Math.min(n, hi));\n}\n\nfunction deriveInitials(name: string): string {\n  const parts = name.trim().split(/\\s+/).filter(Boolean);\n  if (parts.length === 0) return \"?\";\n  if (parts.length === 1) return (parts[0] ?? \"\").slice(0, 2).toUpperCase();\n  return `${parts[0]?.[0] ?? \"\"}${parts[1]?.[0] ?? \"\"}`.toUpperCase();\n}\n\nfunction wordCount(text: string, start: number, end: number): number {\n  const len = text.length;\n  const s = clamp(start, 0, len);\n  const e = clamp(end, s, len);\n  const slice = text.slice(s, e).trim();\n  return slice ? slice.split(/\\s+/).length : 0;\n}\n\nfunction opacityFor(localIndex: number): number {\n  return Math.max(MIN_OPACITY, BASE_OPACITY - localIndex * OPACITY_STEP);\n}\n\nfunction overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {\n  return a.start < b.end && b.start < a.end;\n}\n\n// Groups selections whose [start,end) ranges transitively overlap, then ranks each\n// member by arrival order within its own group. That local rank — not the raw\n// arrivedAt value, not DOM order — is the one scalar every other visual property\n// derives from (outward offset, stroke opacity).\nfunction computeArrivalIndex(sels: GalleyBracketSelection[]): Map<string, number> {\n  const n = sels.length;\n  const parent = Array.from({ length: n }, (_, i) => i);\n  const find = (x: number): number => {\n    while (parent[x] !== x) {\n      parent[x] = parent[parent[x] as number] as number;\n      x = parent[x] as number;\n    }\n    return x;\n  };\n  const union = (a: number, b: number) => {\n    const ra = find(a);\n    const rb = find(b);\n    if (ra !== rb) parent[ra] = rb;\n  };\n  for (let i = 0; i < n; i++) {\n    for (let j = i + 1; j < n; j++) {\n      const a = sels[i];\n      const b = sels[j];\n      if (a && b && overlaps(a, b)) union(i, j);\n    }\n  }\n  const arrivalKey = (i: number) => sels[i]?.arrivedAt ?? i;\n  const groups = new Map<number, number[]>();\n  for (let i = 0; i < n; i++) {\n    const r = find(i);\n    const g = groups.get(r);\n    if (g) g.push(i);\n    else groups.set(r, [i]);\n  }\n  const result = new Map<string, number>();\n  for (const idxs of groups.values()) {\n    idxs.sort((a, b) => arrivalKey(a) - arrivalKey(b));\n    idxs.forEach((idx, local) => {\n      const sel = sels[idx];\n      if (sel) result.set(sel.id, local);\n    });\n  }\n  return result;\n}\n\nfunction toLocal(rects: DOMRect[], originLeft: number, originTop: number): LocalRect[] {\n  return rects\n    .filter((r) => r.width > 0 && r.height > 0)\n    .map((r) => ({\n      left: r.left - originLeft,\n      top: r.top - originTop,\n      right: r.right - originLeft,\n      bottom: r.bottom - originTop,\n    }))\n    .sort((a, b) => a.top - b.top);\n}\n\nfunction BracketMark({\n  rect,\n  side,\n  localIndex,\n  opacity,\n}: {\n  rect: LocalRect;\n  side: \"open\" | \"close\";\n  localIndex: number;\n  opacity: number;\n}) {\n  const topY = rect.top - localIndex * OFFSET_STEP;\n  const footY = rect.bottom + UNDER_GAP + localIndex * OFFSET_STEP;\n  const x = side === \"open\" ? rect.left : rect.right;\n  const footX = side === \"open\" ? x + BRACKET_ARM : x - BRACKET_ARM;\n  return (\n    <>\n      <line\n        x1={x}\n        y1={topY}\n        x2={x}\n        y2={footY}\n        pathLength={1}\n        strokeDasharray={1}\n        className=\"ns-galley-draw\"\n        stroke=\"var(--foreground)\"\n        strokeWidth={1}\n        strokeLinecap=\"round\"\n        opacity={opacity}\n      />\n      <line\n        x1={x}\n        y1={footY}\n        x2={footX}\n        y2={footY}\n        pathLength={1}\n        strokeDasharray={1}\n        className=\"ns-galley-draw\"\n        stroke=\"var(--foreground)\"\n        strokeWidth={1}\n        strokeLinecap=\"round\"\n        opacity={opacity}\n      />\n    </>\n  );\n}\n\nexport function GalleyBracket({ text, selections, contextLabel, className = \"\" }: GalleyBracketProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n  const textRef = useRef<HTMLParagraphElement>(null);\n\n  const [size, setSize] = useState({ width: 0, height: 0 });\n  const [marks, setMarks] = useState<Record<string, LocalRect[]>>({});\n  const [liveMessage, setLiveMessage] = useState(\"\");\n  const [reducedMotion, setReducedMotion] = useState(false);\n\n  const prevSelRef = useRef<Map<string, { start: number; end: number }>>(new Map());\n  const debounceTimer = useRef(0);\n\n  const arrivalIndex = useMemo(() => computeArrivalIndex(selections), [selections]);\n\n  useEffect(() => {\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    setReducedMotion(mq.matches);\n    const onChange = () => setReducedMotion(mq.matches);\n    mq.addEventListener(\"change\", onChange);\n    return () => mq.removeEventListener(\"change\", onChange);\n  }, []);\n\n  const measure = useCallback(() => {\n    const container = containerRef.current;\n    const p = textRef.current;\n    if (!container || !p) return;\n    const box = container.getBoundingClientRect();\n    setSize({ width: box.width, height: box.height });\n    const node = p.firstChild;\n    if (!(node instanceof Text)) {\n      setMarks({});\n      return;\n    }\n    const len = node.data.length;\n    const next: Record<string, LocalRect[]> = {};\n    for (const sel of selections) {\n      const s = clamp(sel.start, 0, len);\n      const e = clamp(sel.end, s, len);\n      if (e <= s) continue;\n      const range = document.createRange();\n      try {\n        range.setStart(node, s);\n        range.setEnd(node, e);\n        const rects = toLocal(Array.from(range.getClientRects()), box.left, box.top);\n        if (rects.length) next[sel.id] = rects;\n      } catch {\n        // stale offsets against a text node mid-update — skip this selection's marks this frame\n      }\n    }\n    setMarks(next);\n  }, [selections]);\n\n  useLayoutEffect(() => {\n    measure();\n    const container = containerRef.current;\n    if (!container) return;\n    const ro = new ResizeObserver(() => measure());\n    ro.observe(container);\n    const onResize = () => measure();\n    window.addEventListener(\"resize\", onResize);\n    document.fonts?.ready?.then(() => measure()).catch(() => {});\n    return () => {\n      ro.disconnect();\n      window.removeEventListener(\"resize\", onResize);\n    };\n  }, [measure]);\n\n  // debounced accessible summary — announces only the range that most recently\n  // changed, 2s after changes stop, so a drag-selection in progress never floods\n  // the live region with one announcement per pointermove.\n  useEffect(() => {\n    const prev = prevSelRef.current;\n    let changed: GalleyBracketSelection | undefined;\n    for (const sel of selections) {\n      const p = prev.get(sel.id);\n      if (!p || p.start !== sel.start || p.end !== sel.end) changed = sel;\n    }\n    prevSelRef.current = new Map(selections.map((s) => [s.id, { start: s.start, end: s.end }]));\n    if (!changed) return;\n    const target = changed;\n    window.clearTimeout(debounceTimer.current);\n    debounceTimer.current = window.setTimeout(() => {\n      const words = wordCount(text, target.start, target.end);\n      const where = contextLabel ? ` in ${contextLabel}` : \"\";\n      setLiveMessage(`${target.name} selected ${words} word${words === 1 ? \"\" : \"s\"}${where}.`);\n    }, DEBOUNCE_MS);\n  }, [selections, text, contextLabel]);\n\n  useEffect(() => {\n    const timer = debounceTimer;\n    return () => window.clearTimeout(timer.current);\n  }, []);\n\n  const jumpTo = (sel: GalleyBracketSelection) => {\n    const node = textRef.current?.firstChild;\n    if (!(node instanceof Text)) return;\n    const len = node.data.length;\n    const s = clamp(sel.start, 0, len);\n    const e = clamp(sel.end, s, len);\n    if (e <= s) return;\n    const range = document.createRange();\n    try {\n      range.setStart(node, s);\n      range.setEnd(node, e);\n    } catch {\n      return;\n    }\n    const live = window.getSelection();\n    live?.removeAllRanges();\n    live?.addRange(range);\n    textRef.current?.scrollIntoView({\n      block: \"center\",\n      behavior: reducedMotion ? \"auto\" : \"smooth\",\n    });\n  };\n\n  return (\n    <div className={[\"ns-galley relative\", className].filter(Boolean).join(\" \")}>\n      <style>{`\n.ns-galley-draw{ stroke-dashoffset: 1; animation: ns-galley-draw-in 160ms cubic-bezier(0.16,1,0.3,1) forwards; }\n@keyframes ns-galley-draw-in{ from{ stroke-dashoffset: 1; } to{ stroke-dashoffset: 0; } }\n@media (prefers-reduced-motion: reduce){\n  .ns-galley-draw{ animation: none !important; stroke-dashoffset: 0 !important; }\n}\n`}</style>\n\n      <div ref={containerRef} className=\"relative py-2 pl-9 pr-2\">\n        <p ref={textRef} className=\"text-base leading-[2.2] text-foreground\">\n          {text}\n        </p>\n        <svg\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n          viewBox={`0 0 ${Math.max(size.width, 1)} ${Math.max(size.height, 1)}`}\n          preserveAspectRatio=\"none\"\n        >\n          {selections.map((sel) => {\n            const rects = marks[sel.id];\n            if (!rects || rects.length === 0) return null;\n            const first = rects[0];\n            const last = rects[rects.length - 1];\n            if (!first || !last) return null;\n            const local = arrivalIndex.get(sel.id) ?? 0;\n            const op = opacityFor(local);\n            const initials = sel.initials?.trim() || deriveInitials(sel.name);\n            return (\n              <g key={sel.id} data-selection={sel.id}>\n                {rects.map((r, i) => {\n                  const y = r.bottom + UNDER_GAP + local * OFFSET_STEP;\n                  return (\n                    <line\n                      key={i}\n                      x1={r.left}\n                      y1={y}\n                      x2={r.right}\n                      y2={y}\n                      pathLength={1}\n                      strokeDasharray={1}\n                      className=\"ns-galley-draw\"\n                      stroke=\"var(--foreground)\"\n                      strokeWidth={1}\n                      opacity={op}\n                    />\n                  );\n                })}\n                <BracketMark rect={first} side=\"open\" localIndex={local} opacity={op} />\n                <BracketMark rect={last} side=\"close\" localIndex={local} opacity={op} />\n                <text\n                  x={4}\n                  y={first.top - local * OFFSET_STEP + 9}\n                  className=\"font-mono text-[8px]\"\n                  fill=\"var(--foreground)\"\n                  opacity={op}\n                >\n                  {initials}\n                </text>\n              </g>\n            );\n          })}\n        </svg>\n      </div>\n\n      <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n        {liveMessage}\n      </div>\n\n      {selections.length > 0 && (\n        <div className=\"mt-4\">\n          <p className=\"mb-1.5 font-mono text-[10px] uppercase tracking-[0.14em] text-ns-muted\">\n            Active selections\n          </p>\n          <ul className=\"flex flex-wrap gap-2\">\n            {selections.map((sel) => {\n              const words = wordCount(text, sel.start, sel.end);\n              return (\n                <li key={sel.id}>\n                  <button\n                    type=\"button\"\n                    data-jump\n                    onClick={() => jumpTo(sel)}\n                    className=\"rounded-full border border-border px-2.5 py-1 font-mono text-[11px] text-ns-muted outline-none transition-colors hover:border-foreground/25 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ns-accent focus-visible:ring-offset-2 focus-visible:ring-offset-background\"\n                  >\n                    {sel.name} · {words} word{words === 1 ? \"\" : \"s\"}\n                  </button>\n                </li>\n              );\n            })}\n          </ul>\n        </div>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/galley-bracket.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff"
    },
    "dark": {
      "ns-muted": "#8f8f8f"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "collaboration",
      "presence",
      "selection",
      "editor",
      "svg",
      "accessibility",
      "realtime",
      "proofreading"
    ],
    "instruction": "A presence primitive for shared/collaborative text editing: given `text` (one paragraph's plain string) and `selections: { id, name, initials?, start, end, arrivedAt? }[]` (character offsets into `text`), it marks where OTHER people currently have something selected — never the viewer's own selection, which stays the platform's native blue. Each range is measured with `Range.getClientRects()` against the paragraph's own single text node (the same primitive a user dragging a selection and reading getClientRects() would hit), so a range that wraps across lines gets one hairline underline per wrapped line, while the corner brackets are drawn only at the range's true start and true end — never once per line. Every mark is a stroke, `var(--foreground)` at a base opacity of 0.55, never a filled highlight: two overlapping translucent fills produce a third color that identifies nobody, so instead, when ranges overlap, each selection's ONLY varying properties are derived from its arrival index within that overlap group (computed by union-find over interval overlap, then ranked by `arrivedAt` — defaulting to array position — within each connected group): outward offset (index × 3px, pushing the bracket's top edge up and its underline down, so later arrivals visibly embrace the earlier ones like nested proofreading brackets) and stroke opacity (index × -0.09, later arrivals slightly lighter, floored at 0.22). Nothing else — no hue, no fill, no z-order trick — varies per selection. The selector's initials (explicit `initials`, or derived from the first letters of `name`) are set small in a reserved left margin gutter, vertically aligned with the opening bracket's (offset) top. Marks draw in over 160ms via `stroke-dashoffset` the first time an id appears in the DOM — because React keys the mark group by `id`, a selection whose `start`/`end` merely change (a drag in progress) updates the existing element's coordinates without remounting it, so the reveal never replays and rapid re-selection never strobes. `prefers-reduced-motion` drops the reveal outright (marks appear at rest). The whole SVG layer is `aria-hidden`; it is decoration on top of an honestly-stated real surface: a `role=status aria-live=polite` region that announces the most recently changed selection 2 seconds after it stops changing (\"Ana Kader selected 12 words.\", plus \" in <contextLabel>\" when that prop is set) — the 2s debounce is what keeps a live drag-selection from flooding the region with one announcement per pointermove — and a keyboard-reachable list of jump buttons, one per active selection, each a real `<button>` whose accessible name is its own visible text (\"Ana Kader · 5 words\"); activating one moves the platform's own `Selection` object to that exact range via the same Range machinery used for measurement, so the collaborator's text is actually, natively highlighted and scrolled into view — not a custom paint standing in for it. Renders one paragraph per instance by design (multi-paragraph editors render one GalleyBracket per paragraph) so `start`/`end` stay simple indices into one text node rather than needing a cross-node offset scheme. Zero dependencies, DOM+SVG+CSS only, no canvas; every color is a token (`--background --foreground --ns-muted --border --ns-accent`) and `--ns-accent` appears only on the jump buttons' focus ring, never on a bracket or underline — the marks are strictly monochrome. Distinct from select-caustic: select-caustic is an effect on a `<select>` trigger/listbox, unrelated in domain. The component this is really meant to be read against is anything that would highlight a remote user's selection with a translucent fill — that approach gets muddier as more people select the same text; galley-bracket gets more articulate as ranges overlap, because overlap is exactly what arrival-order nesting is built to narrate."
  },
  "type": "registry:ui"
}