{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "schedule-ascii-freebusy",
  "title": "Schedule ASCII Free/Busy",
  "description": "A meeting-time finder: one row of block glyphs per attendee and an underlined accent window marking the earliest slot where everyone required is free. Toggling a person optional recomputes the answer instantly.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/schedule-ascii-freebusy/component.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\n\n// ---------------------------------------------------------------------------\n// ScheduleAsciiFreebusy — a meeting-time finder that shows its own work.\n//\n// One row of block glyphs per attendee over 18 half-hour slots (09:00–18:00)\n// and an underlined accent window marking the earliest slot where everyone\n// required is actually free. The solver is a bitwise AND of the required\n// attendees' inverted busy masks followed by a single left-to-right\n// run-length scan — dropping one person to optional removes their mask from\n// the AND and the answer visibly moves, which is the whole argument of the\n// component.\n//\n// Status is glyph-encoded, never color-encoded: free ·, tentative ▒, busy █,\n// outside working hours blank. Pure DOM + tokens: no canvas, no rAF loop.\n// ---------------------------------------------------------------------------\n\nexport type SlotStatus = \"free\" | \"tentative\" | \"busy\" | \"out\";\n\nexport interface Attendee {\n  /** stable lowercase id, also used for [data-attendee-toggle] */\n  id: string;\n  name: string;\n  /** one status per slot; length must equal `slots` */\n  day: SlotStatus[];\n}\n\nexport interface ScheduleAsciiFreebusyProps {\n  /** attendees and their free/busy blocks, rendered as one row each */\n  attendees: Attendee[];\n  /** number of half-hour columns (default 18 = 09:00–18:00) */\n  slots?: number;\n  /** minutes at the first column (default 540 = 09:00) */\n  dayStartMinutes?: number;\n  /** initial meeting length in minutes; must be one of `durations` */\n  defaultDuration?: number;\n  /** offered meeting-length options, in minutes */\n  durations?: number[];\n  /** heading above the grid */\n  title?: string;\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\nconst GLYPH: Record<SlotStatus, string> = {\n  free: \"·\",\n  tentative: \"▒\",\n  busy: \"█\",\n  out: \" \",\n};\n\n// Resting ink. NOT `text-border` — --border is tuned for 1px hairlines and is\n// invisible as type on the light theme (#ebebeb on #fafafa), which would leave\n// the free cells and the rule blank at rest. Muted tints read in both themes\n// and still sit below the busy blocks in the hierarchy.\nconst FREE_INK = \"text-ns-muted/50\";\nconst RULE_INK = \"text-ns-muted/55\";\nconst OPTIONAL_INK = \"text-ns-muted/30\";\n\nconst GLYPH_CLASS: Record<SlotStatus, string> = {\n  free: FREE_INK,\n  tentative: \"text-ns-muted\",\n  busy: \"text-foreground\",\n  out: FREE_INK,\n};\n\nconst STATUS_WORD: Record<SlotStatus, string> = {\n  free: \"free\",\n  tentative: \"tentative\",\n  busy: \"busy\",\n  out: \"outside working hours\",\n};\n\n/** busy for solving purposes: a hard conflict or a slot outside working hours */\nconst isBlocked = (s: SlotStatus) => s === \"busy\" || s === \"out\";\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return Math.min(hi, Math.max(lo, v));\n}\n\ntype Run = { start: number; end: number };\n\n/** every maximal run of set bits in `mask` whose length is at least `min` */\nfunction maximalRuns(mask: boolean[], min: number): Run[] {\n  const runs: Run[] = [];\n  let start = -1;\n  for (let k = 0; k <= mask.length; k++) {\n    if (k < mask.length && mask[k]) {\n      if (start === -1) start = k;\n    } else if (start !== -1) {\n      if (k - start >= min) runs.push({ start, end: k - 1 });\n      start = -1;\n    }\n  }\n  return runs;\n}\n\nexport function ScheduleAsciiFreebusy({\n  attendees,\n  slots = 18,\n  dayStartMinutes = 9 * 60,\n  defaultDuration = 60,\n  durations = [30, 60, 90],\n  title = \"Design sync — find a time\",\n  className = \"\",\n}: ScheduleAsciiFreebusyProps) {\n  const [duration, setDuration] = useState(defaultDuration);\n  const [optional, setOptional] = useState<Record<string, boolean>>({});\n  const [hoverCol, setHoverCol] = useState<number | null>(null);\n  const [active, setActive] = useState<{ r: number; c: number }>({ r: 0, c: 0 });\n  const gridRef = useRef<HTMLDivElement>(null);\n  const durationRef = useRef<HTMLDivElement>(null);\n\n  const durationSlots = Math.max(1, Math.round(duration / 30));\n\n  const timeAt = useCallback(\n    (k: number) => {\n      const m = dayStartMinutes + k * 30;\n      const hh = String(Math.floor(m / 60)).padStart(2, \"0\");\n      const mm = String(m % 60).padStart(2, \"0\");\n      return `${hh}:${mm}`;\n    },\n    [dayStartMinutes]\n  );\n\n  const required = useMemo(() => attendees.filter((a) => !optional[a.id]), [attendees, optional]);\n\n  /** freeMask[k] = AND over required attendees of NOT blocked */\n  const freeMask = useMemo(() => {\n    const mask: boolean[] = [];\n    for (let k = 0; k < slots; k++) {\n      mask.push(required.length > 0 && required.every((a) => !isBlocked(a.day[k] ?? \"out\")));\n    }\n    return mask;\n  }, [required, slots]);\n\n  const runs = useMemo(() => maximalRuns(freeMask, durationSlots), [freeMask, durationSlots]);\n\n  /** earliest of the longest qualifying runs */\n  const best = useMemo(() => {\n    let win: Run | null = null;\n    for (const r of runs) {\n      const len = r.end - r.start + 1;\n      if (!win || len > win.end - win.start + 1) win = r;\n    }\n    return win;\n  }, [runs]);\n\n  /** when nothing qualifies: the window of `durationSlots` with the fewest blocked people */\n  const nearMiss = useMemo(() => {\n    if (best || required.length === 0) return null;\n    let winner: { start: number; names: string[] } | null = null;\n    for (let s = 0; s + durationSlots <= slots; s++) {\n      const names: string[] = [];\n      for (const a of required) {\n        for (let k = s; k < s + durationSlots; k++) {\n          if (isBlocked(a.day[k] ?? \"out\")) {\n            names.push(a.name);\n            break;\n          }\n        }\n      }\n      if (!winner || names.length < winner.names.length) winner = { start: s, names };\n    }\n    return winner;\n  }, [best, required, durationSlots, slots]);\n\n  const answer = useMemo(() => {\n    if (required.length === 0) return \"no one required — pick at least one attendee\";\n    if (best) {\n      const who =\n        required.length === attendees.length\n          ? `all ${required.length} free`\n          : `${required.length} required free`;\n      return `${timeAt(best.start)} → ${timeAt(best.end + 1)}   ${who}`;\n    }\n    if (nearMiss) {\n      const names = nearMiss.names.join(\", \");\n      return `no window — best is ${timeAt(nearMiss.start)} → ${timeAt(nearMiss.start + durationSlots)} with ${names} busy`;\n    }\n    return \"no window\";\n  }, [required, attendees.length, best, nearMiss, timeAt, durationSlots]);\n\n  const hoverLine = useMemo(() => {\n    if (hoverCol === null) return null;\n    const blocked = required.filter((a) => isBlocked(a.day[hoverCol] ?? \"out\"));\n    if (required.length === 0) return `${timeAt(hoverCol)} — no one required`;\n    if (blocked.length === 0) return `${timeAt(hoverCol)} — everyone free`;\n    const names = blocked\n      .map((a) => (a.day[hoverCol] === \"out\" ? `${a.name} (off)` : a.name))\n      .join(\", \");\n    return `${timeAt(hoverCol)} — ${blocked.length} of ${required.length} busy: ${names}`;\n  }, [hoverCol, required, timeAt]);\n\n  const restLine = `${runs.length} window${runs.length === 1 ? \"\" : \"s\"} ≥ ${duration} min · click a name to drop them to optional`;\n\n  const toggle = (id: string) => setOptional((o) => ({ ...o, [id]: !o[id] }));\n\n  const focusCell = (r: number, c: number) => {\n    gridRef.current\n      ?.querySelector<HTMLDivElement>(`[data-cell-r=\"${r}\"][data-cell-c=\"${c}\"]`)\n      ?.focus();\n  };\n\n  const onCellKeyDown = (e: React.KeyboardEvent, r: number, c: number) => {\n    if (e.key === \"Escape\") {\n      setHoverCol(null);\n      return;\n    }\n    const map: Record<string, [number, number]> = {\n      ArrowUp: [-1, 0],\n      ArrowDown: [1, 0],\n      ArrowLeft: [0, -1],\n      ArrowRight: [0, 1],\n    };\n    const d = map[e.key];\n    if (!d) return;\n    e.preventDefault();\n    const nr = clamp(r + d[0], 0, attendees.length - 1);\n    const nc = clamp(c + d[1], 0, slots - 1);\n    setActive({ r: nr, c: nc });\n    setHoverCol(nc);\n    focusCell(nr, nc);\n  };\n\n  /** radiogroup semantics: arrows move the selection and the single tab stop */\n  const onDurationKeyDown = (e: React.KeyboardEvent, i: number) => {\n    const step =\n      e.key === \"ArrowRight\" || e.key === \"ArrowDown\"\n        ? 1\n        : e.key === \"ArrowLeft\" || e.key === \"ArrowUp\"\n          ? -1\n          : 0;\n    if (!step) return;\n    e.preventDefault();\n    const next = durations[(i + step + durations.length) % durations.length];\n    if (next === undefined) return;\n    setDuration(next);\n    durationRef.current\n      ?.querySelector<HTMLButtonElement>(`[data-duration=\"${next}\"]`)\n      ?.focus();\n  };\n\n  const inBest = (k: number) => !!best && k >= best.start && k <= best.end;\n\n  const colTint = (k: number) =>\n    hoverCol === k ? \"bg-ns-accent/[0.10]\" : inBest(k) ? \"bg-ns-accent/[0.06]\" : \"\";\n\n  /** underline glyph for a window of `len` columns at offset `i` */\n  const underline = (len: number, i: number) => {\n    if (len === 1) return \"┴\";\n    if (i === 0) return \"└\";\n    if (i === len - 1) return \"┘\";\n    return \"─\";\n  };\n\n  const runAt = (k: number) => runs.find((r) => k >= r.start && k <= r.end) ?? null;\n\n  const cell = \"flex h-[1.35em] items-center justify-center select-none\";\n  const labelColumn = \"7em\";\n  const cellWidth = \"1.5em\";\n\n  return (\n    <div className={`inline-flex flex-col gap-3 font-mono text-[14px] ${className}`}>\n      <div className=\"flex flex-wrap items-center justify-between gap-4\">\n        <span className=\"text-[11px] uppercase tracking-[0.18em] text-ns-muted\">{title}</span>\n        <div\n          ref={durationRef}\n          role=\"radiogroup\"\n          aria-label=\"Meeting length\"\n          className=\"flex items-center rounded-sm border border-border\"\n        >\n          {durations.map((d, i) => {\n            const on = d === duration;\n            return (\n              <button\n                key={d}\n                type=\"button\"\n                role=\"radio\"\n                aria-checked={on}\n                data-duration={d}\n                tabIndex={on || (!durations.includes(duration) && i === 0) ? 0 : -1}\n                onClick={() => setDuration(d)}\n                onKeyDown={(e) => onDurationKeyDown(e, i)}\n                className={`px-2.5 py-1 text-[11px] tabular-nums outline-none transition-colors duration-150 first:rounded-l-sm last:rounded-r-sm motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ns-accent ${\n                  on ? \"bg-ns-accent/[0.14] text-foreground\" : \"text-ns-muted hover:text-foreground\"\n                }`}\n              >\n                {d} min\n              </button>\n            );\n          })}\n        </div>\n      </div>\n\n      <div\n        ref={gridRef}\n        role=\"grid\"\n        aria-label={`Attendee availability, ${timeAt(0)} to ${timeAt(slots)} in half-hour slots`}\n        aria-colcount={slots + 1}\n        onPointerLeave={() => setHoverCol(null)}\n        onKeyDown={(e) => {\n          if (e.key === \"Escape\") setHoverCol(null);\n        }}\n        className=\"grid rounded-sm border border-border bg-surface px-3 py-2.5\"\n        style={{ gridTemplateColumns: `${labelColumn} repeat(${slots}, ${cellWidth})` }}\n      >\n        {/* hour ruler */}\n        <div role=\"row\" className=\"contents\">\n          <div role=\"columnheader\" aria-colindex={1} className=\"h-[1.35em]\" />\n          {Array.from({ length: slots }, (_, k) =>\n            k % 2 === 0 ? (\n              <div\n                key={k}\n                role=\"columnheader\"\n                aria-colindex={k + 2}\n                aria-colspan={Math.min(2, slots - k)}\n                style={{ gridColumn: `span ${Math.min(2, slots - k)}` }}\n                className=\"flex h-[1.35em] items-center text-[10px] tabular-nums text-ns-muted\"\n              >\n                {timeAt(k).slice(0, 2)}\n              </div>\n            ) : null\n          )}\n        </div>\n\n        {/* one row per attendee */}\n        {attendees.map((a, r) => {\n          const off = !!optional[a.id];\n          return (\n            <div key={a.id} role=\"row\" className=\"contents\">\n              <div role=\"rowheader\" className=\"flex h-[1.35em] items-center pr-2\">\n                <button\n                  type=\"button\"\n                  data-attendee-toggle={a.id}\n                  aria-pressed={!off}\n                  aria-label={`${a.name} — ${off ? \"optional, excluded from the search\" : \"required\"}. Toggle.`}\n                  onClick={() => toggle(a.id)}\n                  className={`w-full truncate rounded-[2px] text-left text-[12px] outline-none transition-colors duration-150 motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ns-accent ${\n                    off ? \"text-ns-muted/60 hover:text-ns-muted\" : \"text-foreground hover:text-ns-accent\"\n                  }`}\n                >\n                  {off ? `(${a.name})` : a.name}\n                </button>\n              </div>\n              {Array.from({ length: slots }, (_, k) => {\n                const status = a.day[k] ?? \"out\";\n                const isActive = active.r === r && active.c === k;\n                const ruled = hoverCol === k && !isBlocked(status);\n                return (\n                  <div\n                    key={k}\n                    role=\"gridcell\"\n                    data-cell-r={r}\n                    data-cell-c={k}\n                    tabIndex={isActive ? 0 : -1}\n                    aria-selected={!off && inBest(k)}\n                    aria-label={`${a.name}, ${timeAt(k)}, ${STATUS_WORD[status]}${off ? \", optional\" : \"\"}`}\n                    onPointerEnter={() => setHoverCol(k)}\n                    onFocus={() => {\n                      setActive({ r, c: k });\n                      setHoverCol(k);\n                    }}\n                    onKeyDown={(e) => onCellKeyDown(e, r, k)}\n                    className={`${cell} rounded-[1px] outline-none transition-colors duration-150 motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ns-accent ${colTint(k)} ${\n                      off ? OPTIONAL_INK : GLYPH_CLASS[status]\n                    }`}\n                  >\n                    {ruled ? \"┊\" : GLYPH[status]}\n                  </div>\n                );\n              })}\n            </div>\n          );\n        })}\n\n        {/* separator rule */}\n        <div role=\"row\" aria-hidden className=\"contents\">\n          <div className=\"h-[1.1em]\" />\n          {Array.from({ length: slots }, (_, k) => (\n            <div key={k} className={`flex h-[1.1em] items-center justify-center ${RULE_INK}`}>\n              {k === 0 ? \"├\" : k === slots - 1 ? \"┤\" : \"─\"}\n            </div>\n          ))}\n        </div>\n\n        {/* every qualifying window underlined; the best one in accent */}\n        <div role=\"row\" aria-hidden className=\"contents\">\n          <div className=\"h-[1.1em]\" />\n          {Array.from({ length: slots }, (_, k) => {\n            const r = runAt(k);\n            const isBest = !!best && !!r && r.start === best.start;\n            const len = r ? r.end - r.start + 1 : 0;\n            return (\n              <div\n                key={k}\n                className={`flex h-[1.1em] items-center justify-center leading-none ${\n                  isBest ? \"text-ns-accent\" : \"text-ns-muted\"\n                }`}\n              >\n                {r ? underline(len, k - r.start) : \"\"}\n              </div>\n            );\n          })}\n        </div>\n\n        {/* the answer, seated under its own window */}\n        <div role=\"row\" className=\"contents\">\n          <div role=\"rowheader\" className=\"h-[1.35em]\" />\n          <div\n            role=\"gridcell\"\n            aria-live=\"polite\"\n            style={{ gridColumn: `${(best ? Math.min(best.start, 5) : 0) + 2} / -1` }}\n            className={`flex h-[1.35em] items-center whitespace-nowrap text-[12px] tabular-nums ${\n              best ? \"text-ns-accent\" : \"text-ns-muted\"\n            }`}\n          >\n            {answer}\n          </div>\n        </div>\n      </div>\n\n      {/* readout: hover detail crossfading with the resting hint */}\n      <div className=\"relative h-[1.4em] text-[11px] text-ns-muted\">\n        <span\n          className={`absolute inset-0 flex items-center whitespace-nowrap transition-opacity duration-150 motion-reduce:transition-none ${\n            hoverLine ? \"opacity-0\" : \"opacity-100\"\n          }`}\n        >\n          {restLine}\n        </span>\n        <span\n          aria-live=\"polite\"\n          className={`absolute inset-0 flex items-center whitespace-nowrap tabular-nums text-foreground transition-opacity duration-150 motion-reduce:transition-none ${\n            hoverLine ? \"opacity-100\" : \"opacity-0\"\n          }`}\n        >\n          {hoverLine ?? \"\"}\n        </span>\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/schedule-ascii-freebusy.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)",
      "color-ns-accent": "var(--ns-accent)",
      "color-surface": "var(--surface)"
    },
    "light": {
      "ns-muted": "#4d4d4d",
      "ns-accent": "#006bff",
      "surface": "#fafafa"
    },
    "dark": {
      "ns-muted": "#8f8f8f",
      "surface": "#171717"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "scheduling",
      "calendar",
      "availability",
      "ascii",
      "mono",
      "grid",
      "keyboard-navigation",
      "meetings"
    ],
    "instruction": "Build <ScheduleAsciiFreebusy attendees slots dayStartMinutes defaultDuration durations title className> as a pure-DOM availability matrix over slots=18 half-hour columns spanning 09:00–18:00, one row per attendee (default six: Dana, Priya, Marcus, Inés, Tobias, Wei). GRID: each attendee carries a SlotStatus[] of 'free' | 'tentative' | 'busy' | 'out', rendered strictly glyph-encoded and never color-encoded — free is · in text-ns-muted/50, tentative is ▒ in text-ns-muted, busy is █ in text-foreground (never text-border — --border is a 1px-hairline token and is invisible as type on the light theme, which would leave the resting grid blank), and a slot outside that person's working hours renders as a blank cell. SOLVER (the actual mechanism, not decoration): isBlocked = status is 'busy' or 'out'; freeMask[k] is the AND over every REQUIRED attendee of NOT isBlocked, i.e. the bitwise intersection of the inverted busy masks, computed only over attendees not currently marked optional. A single left-to-right run-length scan over freeMask collects every MAXIMAL run of set bits whose length is >= durationSlots (duration/30). Every qualifying run is drawn on a result row as └ + ─×(len−2) + ┘ in text-ns-muted (a length-1 run degenerates to ┴); the BEST run — earliest of the longest — is drawn in text-ns-accent, and an aria-live answer row seated under that window prints '10:30 → 11:30   all 6 free'. If no run qualifies the component never goes blank: it falls back to a minimum-conflict scan over every window of durationSlots, picking the one blocking the fewest required attendees, and prints 'no window — best is 10:00 → 11:30 with Dana busy'. A single ├────┤ rule separates the attendee rows from the result rows. There is no aggregate or density row of any kind: the six calendars are the only glyph rows. CONTROLS: a segmented role=radiogroup of 30 / 60 / 90 min (1 / 2 / 3 slots) re-runs the scan on click and on ArrowLeft/Right/Up/Down, which wrap around and move the group's single tab stop (roving tabindex parked on the checked radio); each attendee's name is an aria-pressed toggle button (data-attendee-toggle=\"<id>\") that flips them required↔optional — an optional attendee is excluded from the AND, is parenthesised, and their entire row dims to text-ns-muted/30, so with the default data dropping Dana visibly widens the accent window from 10:30 → 11:30 to 09:30 → 11:30. That jump is the component's whole argument and is what the landing-card autoplay presses. HOVER: entering any cell sets the hovered column, which tints that column bg-ns-accent/[0.10] and swaps the glyph to ┊ in every row where that person is not blocked — a dotted plumb line drawn through the free cells of the column, leaving the █ blocks intact — while a readout below crossfades (150ms opacity, motion-reduce:transition-none) from the resting hint to '14:00 — 2 of 6 busy: Dana, Priya', with an out-of-hours attendee listed as 'Wei (off)'. pointerleave on the grid clears it and the readout eases back. A11Y: role=grid on the matrix with role=row per line, role=columnheader on the hour ruler (each hour label carries aria-colspan=2 and an explicit aria-colindex, since it spans two half-hour columns), role=rowheader on the name/label column, role=gridcell on every slot with aria-selected true inside the best window and an aria-label naming attendee + time + status; a roving tabindex (exactly one cell with tabIndex 0) moves with ArrowUp/Down/Left/Right, Escape clears the column hover, and Space on a name button toggles required/optional through native button semantics. Every focusable control — cells, name toggles, duration radios — carries a visible focus-visible:ring-2 focus-visible:ring-ns-accent ring. COLOR: token-only (--foreground / --ns-muted / --border / --surface / --background / --ns-accent through Tailwind utilities and bg-ns-accent/[0.06|0.10|0.14] arbitrary-opacity tints), no hex anywhere, so both themes follow the tokens with nothing to re-derive. There is no canvas, no rAF loop and no animation beyond the 150ms color/opacity transitions, all of which are suppressed under prefers-reduced-motion via motion-reduce:transition-none."
  },
  "type": "registry:ui"
}