{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "semaphore",
  "type": "registry:ui",
  "title": "Semaphore",
  "description": "The uptime bar, alive — labeled status-tracker rows that stack into an ops wall with a shared time axis. Boots with a sub-second left-to-right ignition cascade on first view, pulses the newest bucket, slides new buckets in on a live interval (suspended offscreen), and raises a hover chip with bucket detail. Statuses are shape-and-brightness coded, not just hue: dim operational, notched degraded, saturated glowing incident. Pure CSS animation, zero dependencies, visually-hidden textual summary per row, static wall under reduced motion.",
  "dependencies": [],
  "registryDependencies": [
    "https://crucibleui.com/r/use-reduced-motion.json",
    "https://crucibleui.com/r/use-visibility-pause.json"
  ],
  "files": [
    {
      "path": "registry/default/data/semaphore/semaphore.tsx",
      "type": "registry:ui",
      "target": "components/crucible/semaphore.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { useVisibilityPause } from \"@/hooks/use-visibility-pause\";\n\nexport interface SemaphoreSegment {\n  /** Status key, resolved against the `colors` map (e.g. \"operational\"). */\n  status: string;\n  /** Short bucket label shown in the hover chip (e.g. \"12 min ago\"). */\n  label?: string;\n  /** Longer detail line for the hover chip (e.g. \"p99 latency above threshold\"). */\n  detail?: string;\n}\n\nexport interface SemaphoreRow {\n  /** Row label rendered left of the track (e.g. a service name). */\n  label?: string;\n  /** Time buckets, oldest first — the last segment is \"now\" and carries the pulse. */\n  segments: SemaphoreSegment[];\n}\n\nexport interface SemaphoreStatusStyle {\n  /** CSS color of segments with this status. */\n  color: string;\n  /** Resting opacity, `0`–`1` — the brightness half of the status coding. @default 1 */\n  opacity?: number;\n  /** Cut a hairline notch across the segment (the \"degraded\" shape cue). @default false */\n  notch?: boolean;\n  /** Saturated emphasis: soft glow + slightly taller (the \"incident\" treatment). @default false */\n  emphasis?: boolean;\n}\n\nexport interface SemaphoreProps extends Omit<React.ComponentPropsWithoutRef<\"div\">, \"children\"> {\n  /**\n   * Single-row tracker: time buckets, oldest first. Ignored when `rows` is\n   * set. Omit both for a seeded sample row.\n   */\n  segments?: SemaphoreSegment[];\n  /**\n   * Wall composition: multiple labeled tracker rows sharing one time axis.\n   * Takes precedence over `segments`.\n   */\n  rows?: SemaphoreRow[];\n  /**\n   * Status → style map, merged over the built-in\n   * `operational` / `degraded` / `incident` / `empty` styles. A plain color\n   * string keeps that status's default shape/brightness coding.\n   */\n  colors?: Record<string, string | SemaphoreStatusStyle>;\n  /**\n   * Live mode: advance every N milliseconds — the oldest bucket drops, a new\n   * one slides in from the right. `0` = static (no timers, zero JS work).\n   * Suspends offscreen and on hidden tabs. @default 0\n   */\n  liveInterval?: number;\n  /**\n   * Produces the incoming bucket in live mode. Defaults to a deterministic\n   * mostly-operational feed.\n   */\n  nextSegment?: (rowIndex: number, tick: number) => SemaphoreSegment;\n  /**\n   * Boot cascade on first scroll into view (once): segments ignite\n   * left-to-right like a self-test. @default true\n   */\n  cascade?: boolean;\n  /** Cascade speed multiplier — `2` boots twice as fast. @default 1 */\n  cascadeSpeed?: number;\n  /** Breathing pulse on each row's newest segment. @default true */\n  pulse?: boolean;\n  /** Segment width in px. @default 6 */\n  segmentWidth?: number;\n  /** Segment height in px. @default 26 */\n  segmentHeight?: number;\n  /** Gap between segments in px. @default 3 */\n  gap?: number;\n  /** Segment corner radius in px. @default 2 */\n  radius?: number;\n  /** Shared time-axis labels rendered under the wall: `[oldest, newest]`. */\n  axis?: readonly [string, string];\n  /** Show the hover chip with bucket detail. @default true */\n  showChip?: boolean;\n  /** Custom hover-chip contents; the default chip shows status, label, and detail. */\n  renderChip?: (\n    segment: SemaphoreSegment,\n    context: { rowIndex: number; segmentIndex: number; rowLabel?: string }\n  ) => React.ReactNode;\n  /** Freeze everything at the fully-populated wall (also stops live mode). @default false */\n  paused?: boolean;\n}\n\n/* Railway-semaphore discipline: statuses are shape-and-brightness coded, not\n * just hue. Operational sits dim and calm, degraded carries a hairline notch,\n * incident is the only saturated (and glowing, slightly taller) element. */\nconst DEFAULT_STATUS_STYLES: Record<string, Required<SemaphoreStatusStyle>> = {\n  operational: { color: \"#8b9bb4\", opacity: 0.34, notch: false, emphasis: false },\n  degraded: { color: \"#c2913c\", opacity: 0.85, notch: true, emphasis: false },\n  incident: { color: \"#e0552e\", opacity: 1, notch: false, emphasis: true },\n  empty: { color: \"#57616f\", opacity: 0.14, notch: false, emphasis: false },\n};\n\nconst FALLBACK_STYLE = DEFAULT_STATUS_STYLES.operational;\n\n/* Boot-cascade budget: full wall self-tests in under a second at speed 1. */\nconst SWEEP_S = 0.5; // left-to-right sweep across the widest row\nconst IGNITE_S = 0.35; // one segment's flare-and-settle\nconst ROW_OFFSET_S = 0.035; // slight per-row lag for a diagonal wavefront\n\nconst STYLE = `\n[data-crucible=\"semaphore\"] .sem-seg {\n  position: relative;\n  flex: none;\n  width: var(--sem-w);\n  height: var(--sem-h);\n  border-radius: var(--sem-r);\n  opacity: var(--seg-o, 1);\n}\n[data-crucible=\"semaphore\"] .sem-notch {\n  position: absolute;\n  left: 0;\n  right: 0;\n  top: 30%;\n  height: 2px;\n  background: rgba(8, 10, 14, 0.9);\n  pointer-events: none;\n}\n@keyframes crucible-sem-ignite {\n  0%  { opacity: 0; filter: brightness(0.4); }\n  45% { opacity: 1; filter: brightness(2.1); }\n  /* no 100% frame: settles to the element's own status opacity/brightness */\n}\n@keyframes crucible-sem-pulse {\n  0%, 100% { opacity: var(--seg-o, 1); filter: brightness(1); }\n  50%      { opacity: calc(var(--seg-o, 1) + 0.45); filter: brightness(1.4); }\n}\n@keyframes crucible-sem-enter {\n  0% { opacity: 0; transform: translateX(calc(var(--sem-w) + 4px)); }\n}\n@keyframes crucible-sem-chip {\n  0% { opacity: 0; transform: translate(-50%, 3px); }\n}\n[data-crucible=\"semaphore\"][data-boot=\"pending\"] .sem-seg { opacity: 0; }\n[data-crucible=\"semaphore\"][data-boot=\"go\"] .sem-seg {\n  animation: crucible-sem-ignite var(--sem-ignite) cubic-bezier(0.2, 0.7, 0.3, 1) var(--seg-delay, 0s) backwards;\n}\n[data-crucible=\"semaphore\"][data-boot=\"go\"][data-pulse=\"true\"] .sem-latest {\n  animation:\n    crucible-sem-ignite var(--sem-ignite) cubic-bezier(0.2, 0.7, 0.3, 1) var(--seg-delay, 0s) backwards,\n    crucible-sem-pulse 2.4s ease-in-out calc(var(--seg-delay, 0s) + var(--sem-ignite)) infinite;\n}\n[data-crucible=\"semaphore\"][data-boot=\"done\"][data-pulse=\"true\"] .sem-latest {\n  animation: crucible-sem-pulse 2.4s ease-in-out infinite;\n}\n[data-crucible=\"semaphore\"][data-boot=\"done\"] .sem-new {\n  animation: crucible-sem-enter 0.35s ease-out backwards;\n}\n[data-crucible=\"semaphore\"][data-boot=\"done\"][data-pulse=\"true\"] .sem-latest.sem-new {\n  animation:\n    crucible-sem-enter 0.35s ease-out backwards,\n    crucible-sem-pulse 2.4s ease-in-out 0.35s infinite;\n}\n[data-crucible=\"semaphore\"] .sem-chip {\n  position: absolute;\n  bottom: calc(100% + 8px);\n  transform: translateX(-50%);\n  z-index: 20;\n  pointer-events: none;\n  white-space: nowrap;\n  animation: crucible-sem-chip 0.16s ease-out;\n}\n/* Paused → the designed resting frame: fully-populated wall, no motion. */\n[data-crucible=\"semaphore\"][data-paused=\"true\"] .sem-seg {\n  animation: none !important;\n  opacity: var(--seg-o, 1) !important;\n}\n/* Reduced motion → same static wall: no cascade, no pulse, no slide. */\n@media (prefers-reduced-motion: reduce) {\n  [data-crucible=\"semaphore\"] .sem-seg {\n    animation: none !important;\n    opacity: var(--seg-o, 1) !important;\n  }\n  [data-crucible=\"semaphore\"] .sem-chip { animation: none !important; }\n}\n`;\n\n/** Deterministic PRNG — no Math.random(), so SSR and hydration always agree. */\nfunction mulberry32(seed: number): () => number {\n  let a = seed >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nfunction seededSegments(seed: number, count: number): SemaphoreSegment[] {\n  const rand = mulberry32(seed);\n  return Array.from({ length: count }, (_, i) => {\n    const v = rand();\n    const status = v > 0.985 ? \"incident\" : v > 0.9 ? \"degraded\" : \"operational\";\n    return {\n      status,\n      label: i === count - 1 ? \"Just now\" : `${count - 1 - i} min ago`,\n      detail:\n        status === \"incident\"\n          ? \"Health check failed\"\n          : status === \"degraded\"\n            ? \"Latency above threshold\"\n            : \"All checks passing\",\n    };\n  });\n}\n\nconst DEFAULT_ROWS: SemaphoreRow[] = [{ segments: seededSegments(42, 48) }];\n\nfunction defaultNextSegment(rowIndex: number, tick: number): SemaphoreSegment {\n  const v = mulberry32(rowIndex * 92821 + tick * 68917)();\n  const status = v > 0.94 ? \"degraded\" : \"operational\";\n  return {\n    status,\n    label: \"Just now\",\n    detail: status === \"degraded\" ? \"Latency above threshold\" : \"All checks passing\",\n  };\n}\n\nfunction resolveStatusStyle(\n  status: string,\n  colors: SemaphoreProps[\"colors\"]\n): Required<SemaphoreStatusStyle> {\n  const base = DEFAULT_STATUS_STYLES[status] ?? FALLBACK_STYLE;\n  const user = colors?.[status];\n  if (typeof user === \"string\") return { ...base, color: user };\n  if (user) return { ...base, ...user };\n  return base;\n}\n\nfunction summarizeRow(row: SemaphoreRow, rowIndex: number): string {\n  const total = row.segments.length;\n  const counts = new Map<string, number>();\n  for (const seg of row.segments) counts.set(seg.status, (counts.get(seg.status) ?? 0) + 1);\n  const parts = [...counts].map(([status, n]) => `${n} ${status}`);\n  const latest = row.segments[total - 1];\n  return `${row.label ?? `Row ${rowIndex + 1}`}: ${total} buckets — ${parts.join(\", \")}. Latest: ${\n    latest?.status ?? \"none\"\n  }.`;\n}\n\ninterface InternalSegment extends SemaphoreSegment {\n  __id: string;\n}\ninterface InternalRow {\n  label?: string;\n  segments: InternalSegment[];\n}\n\n/**\n * Semaphore — the uptime bar, alive. Rows of thin time-bucket segments colored\n * by status, stacking into a labeled status wall with a shared time axis. On\n * first scroll into view the wall boots: segments ignite left-to-right in a\n * sub-second self-test cascade. Each row's newest bucket carries a breathing\n * pulse, and in live mode new buckets slide in from the right on an interval\n * (suspended offscreen and on hidden tabs). Hovering a segment raises a chip\n * with its bucket detail.\n *\n * Statuses follow railway-semaphore discipline — shape-and-brightness coded,\n * not just hue: operational sits dim and calm, degraded carries a hairline\n * notch, and incident is the only saturated element (glowing, slightly\n * taller), so the wall reads without color vision. Segments are decorative\n * (`aria-hidden`) behind a visually-hidden textual summary per row. Reduced\n * motion: fully-populated wall, no cascade, no pulse. Pure CSS animation,\n * zero dependencies.\n */\nexport function Semaphore({\n  segments,\n  rows,\n  colors,\n  liveInterval = 0,\n  nextSegment,\n  cascade = true,\n  cascadeSpeed = 1,\n  pulse = true,\n  segmentWidth = 6,\n  segmentHeight = 26,\n  gap = 3,\n  radius = 2,\n  axis,\n  showChip = true,\n  renderChip,\n  paused = false,\n  className,\n  style,\n  ...rest\n}: SemaphoreProps) {\n  const reducedMotion = useReducedMotion();\n  const speed = Math.max(cascadeSpeed, 0.05);\n  const live = liveInterval > 0;\n\n  const baseRows = React.useMemo<InternalRow[]>(() => {\n    const src = rows ?? (segments ? [{ segments }] : DEFAULT_ROWS);\n    return src.map((row, ri) => ({\n      label: row.label,\n      segments: row.segments.map((seg, i) => ({ ...seg, __id: `s${ri}-${i}` })),\n    }));\n  }, [rows, segments]);\n\n  // Live mode owns the data after its first tick; static mode never allocates.\n  const [liveState, setLiveState] = React.useState<{ rows: InternalRow[]; tick: number } | null>(\n    null\n  );\n  const shownRows = liveState?.rows ?? baseRows;\n\n  const baseRowsRef = React.useRef(baseRows);\n  const nextRef = React.useRef(nextSegment);\n  React.useEffect(() => {\n    baseRowsRef.current = baseRows;\n    nextRef.current = nextSegment;\n  });\n\n  const advance = React.useCallback(() => {\n    setLiveState((prev) => {\n      const tick = (prev?.tick ?? 0) + 1;\n      const current = prev?.rows ?? baseRowsRef.current;\n      return {\n        tick,\n        rows: current.map((row, ri) => {\n          const incoming = (nextRef.current ?? defaultNextSegment)(ri, tick);\n          return {\n            label: row.label,\n            segments: [...row.segments.slice(1), { ...incoming, __id: `l${tick}-${ri}` }],\n          };\n        }),\n      };\n    });\n  }, []);\n\n  // The visibility-paused rAF is the live scheduler: it suspends offscreen and\n  // on hidden tabs, never starts when not live, and tears down on unmount.\n  const intervalS = live ? liveInterval / 1000 : Infinity;\n  const lastAdvanceRef = React.useRef(0);\n  const hostRef = useVisibilityPause<HTMLDivElement>(\n    (elapsed) => {\n      // The hook's clock restarts when `paused` toggles; re-anchor if it did.\n      if (elapsed < lastAdvanceRef.current) lastAdvanceRef.current = elapsed;\n      if (elapsed - lastAdvanceRef.current < intervalS) return;\n      lastAdvanceRef.current = elapsed;\n      advance();\n    },\n    { paused: paused || !live }\n  );\n\n  // Boot cascade — first in-view only.\n  const maxCols = React.useMemo(\n    () => Math.max(1, ...shownRows.map((r) => r.segments.length)),\n    [shownRows]\n  );\n  const colStepS = SWEEP_S / speed / Math.max(1, maxCols - 1);\n  const rowStepS = ROW_OFFSET_S / speed;\n  const igniteS = IGNITE_S / speed;\n\n  type Boot = \"pending\" | \"go\" | \"done\";\n  const [boot, setBoot] = React.useState<Boot>(\"pending\");\n  const bootedRef = React.useRef(false);\n  // No cascade (or reduced motion) → the wall renders fully populated at once.\n  const effectiveBoot: Boot = !cascade || reducedMotion ? \"done\" : boot;\n\n  React.useEffect(() => {\n    if (bootedRef.current || !cascade || reducedMotion) return;\n    const el = hostRef.current;\n    if (!el) return;\n    let timeout = 0;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        io.disconnect();\n        bootedRef.current = true;\n        setBoot(\"go\");\n        const totalMs =\n          ((maxCols - 1) * colStepS + (shownRows.length - 1) * rowStepS + igniteS) * 1000 + 120;\n        timeout = window.setTimeout(() => setBoot(\"done\"), totalMs);\n      },\n      { threshold: 0.25 }\n    );\n    io.observe(el);\n    return () => {\n      io.disconnect();\n      window.clearTimeout(timeout);\n    };\n    // Cascade timing is captured at ignition; data churn must not re-arm it.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [cascade, reducedMotion]);\n\n  const [hover, setHover] = React.useState<{ row: number; index: number } | null>(null);\n\n  const hasLabels = shownRows.some((row) => row.label != null && row.label !== \"\");\n\n  const vars = {\n    \"--sem-w\": `${segmentWidth}px`,\n    \"--sem-h\": `${segmentHeight}px`,\n    \"--sem-r\": `${Math.max(0, radius)}px`,\n    \"--sem-ignite\": `${igniteS.toFixed(3)}s`,\n    ...style,\n  } as React.CSSProperties;\n\n  return (\n    <div\n      {...rest}\n      ref={hostRef}\n      data-crucible=\"semaphore\"\n      data-boot={effectiveBoot}\n      data-pulse={pulse && !reducedMotion && !paused ? \"true\" : \"false\"}\n      data-paused={paused ? \"true\" : undefined}\n      className={cn(\n        \"inline-grid items-center gap-x-3 gap-y-2.5\",\n        hasLabels ? \"grid-cols-[auto_1fr]\" : \"grid-cols-1\",\n        className\n      )}\n      style={vars}\n    >\n      <style>{STYLE}</style>\n\n      {shownRows.map((row, ri) => {\n        const chipSegment =\n          showChip && hover?.row === ri ? row.segments[hover.index] : undefined;\n        return (\n          <React.Fragment key={ri}>\n            {hasLabels && (\n              <span className=\"text-xs font-medium leading-none text-neutral-400\">\n                {row.label}\n              </span>\n            )}\n            <div className=\"relative\">\n              {/* The real status surface for assistive tech. */}\n              <span className=\"sr-only\">{summarizeRow(row, ri)}</span>\n\n              <div\n                aria-hidden\n                className=\"flex items-center\"\n                style={{ gap: `${gap}px` }}\n                onMouseOver={\n                  showChip\n                    ? (e) => {\n                        const target = (e.target as HTMLElement).closest<HTMLElement>(\n                          \"[data-sem-idx]\"\n                        );\n                        if (!target) return;\n                        const index = Number(target.dataset.semIdx);\n                        setHover((h) =>\n                          h && h.row === ri && h.index === index ? h : { row: ri, index }\n                        );\n                      }\n                    : undefined\n                }\n                onMouseLeave={showChip ? () => setHover(null) : undefined}\n              >\n                {row.segments.map((seg, i) => {\n                  const st = resolveStatusStyle(seg.status, colors);\n                  const isLatest = i === row.segments.length - 1;\n                  const segStyle = {\n                    backgroundColor: st.color,\n                    \"--seg-o\": st.opacity,\n                    \"--seg-delay\": `${(i * colStepS + ri * rowStepS).toFixed(3)}s`,\n                    ...(st.emphasis\n                      ? {\n                          boxShadow: `0 0 9px 1px color-mix(in oklab, ${st.color} 55%, transparent)`,\n                          transform: \"scaleY(1.16)\",\n                        }\n                      : null),\n                  } as React.CSSProperties;\n                  return (\n                    <span\n                      key={seg.__id}\n                      data-sem-idx={i}\n                      className={cn(\n                        \"sem-seg\",\n                        isLatest && \"sem-latest\",\n                        isLatest && liveState !== null && \"sem-new\"\n                      )}\n                      style={segStyle}\n                    >\n                      {st.notch && <span className=\"sem-notch\" />}\n                    </span>\n                  );\n                })}\n              </div>\n\n              {chipSegment && hover && (\n                <div\n                  aria-hidden\n                  className=\"sem-chip rounded-md border border-white/10 bg-neutral-900/95 px-2.5 py-1.5 text-[11px] leading-tight text-neutral-200 shadow-lg shadow-black/40\"\n                  style={{ left: hover.index * (segmentWidth + gap) + segmentWidth / 2 }}\n                >\n                  {renderChip ? (\n                    renderChip(chipSegment, {\n                      rowIndex: ri,\n                      segmentIndex: hover.index,\n                      rowLabel: row.label,\n                    })\n                  ) : (\n                    <>\n                      <span className=\"flex items-center gap-1.5\">\n                        <span\n                          className=\"inline-block size-1.5 rounded-full\"\n                          style={{\n                            backgroundColor: resolveStatusStyle(chipSegment.status, colors).color,\n                          }}\n                        />\n                        <span className=\"font-medium capitalize text-neutral-100\">\n                          {chipSegment.status}\n                        </span>\n                        {chipSegment.label && (\n                          <span className=\"text-neutral-500\">{chipSegment.label}</span>\n                        )}\n                      </span>\n                      {chipSegment.detail && (\n                        <span className=\"mt-0.5 block text-neutral-400\">{chipSegment.detail}</span>\n                      )}\n                    </>\n                  )}\n                </div>\n              )}\n            </div>\n          </React.Fragment>\n        );\n      })}\n\n      {axis && (\n        <>\n          {hasLabels && <span aria-hidden />}\n          <div\n            aria-hidden\n            className=\"flex justify-between text-[10px] uppercase tracking-[0.18em] text-neutral-600\"\n          >\n            <span>{axis[0]}</span>\n            <span>{axis[1]}</span>\n          </div>\n        </>\n      )}\n    </div>\n  );\n}\n"
    }
  ]
}