{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "question-board",
  "type": "registry:ui",
  "title": "Question Board",
  "description": "Questions from the room, ranked by the room. People ask from their phone (`QuestionAsk`), vote up the questions they want answered (`QuestionBoard`), and a moderator approves, pins, answers or hides them (`QuestionQueue`) before anything typed reaches a…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/flip-group.json",
    "https://ds.interlace.tools/r/textarea.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/question-board.tsx",
      "target": "components/ui/games/question-board.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { ArrowUp, Check, EyeOff, Pin, PinOff, RotateCcw } from 'lucide-react';\n\n// @interlace/question-board v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/question-board\n// What changed since: https://ds.interlace.tools/c/question-board#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — QuestionBoard, QuestionAsk and QuestionQueue\n *\n * Questions from the room, ranked by the room. People ask from their phone\n * (`QuestionAsk`), vote up the questions they want answered\n * (`QuestionBoard`), and a moderator approves, pins, answers or hides them\n * (`QuestionQueue`) before anything typed reaches a shared screen.\n *\n * ## Who uses which part\n *\n * | Phase            | Who        | Part                                   |\n * | ---------------- | ---------- | -------------------------------------- |\n * | Asking           | Everyone   | `QuestionAsk`                          |\n * | In review        | Moderator  | `QuestionQueue` (review list)          |\n * | Live and voting  | Everyone   | `QuestionBoard` (vote buttons)         |\n * | Answering now    | Moderator  | `QuestionQueue` pin → board highlights |\n * | Answered, hidden | Moderator  | `QuestionQueue` answer / dismiss       |\n *\n * State lives in your app as a `BoardState` from `question-board-model`;\n * every part takes the ranked questions and sends events back. Run the same\n * `applyBoardEvent` on the host or server: it is the one that counts.\n *\n * ## Anatomy\n *\n *   QuestionBoard                   (section — data-slot=\"question-board\")\n *     ├─ ol (FlipGroup)             (data-slot=\"question-board-list\")\n *     │    └─ li × n                (data-slot=\"question-board-item\", data-pinned, data-mine)\n *     │         ├─ p                (data-slot=\"question-board-text\")\n *     │         └─ Button | span    (data-slot=\"question-board-vote\", aria-pressed; or \"question-board-count\"\n *     │                              where nobody can vote: a shared screen, or the viewer's own)\n *     └─ p aria-live               (data-slot=\"question-board-status\")\n *\n *   QuestionAsk                     (form — data-slot=\"question-ask\": Textarea, counter, Send, message)\n *   QuestionQueue                   (div — data-slot=\"question-queue\": review and live lists with actions)\n *\n * ## Motion\n *\n * When a vote changes the order, questions glide to their new places\n * (FlipGroup, 400ms, `--ease-move`); the vote count ticks with a short rise\n * of the new number (transform only). The pinned question carries a quiet\n * accent edge. Under reduced motion, everything simply takes its place.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                     |\n * | ---- | ------------------------- | ------------------------------------------------------ |\n * | R4   | Extends native el         | `section` / `form` / `div` props                       |\n * | R6   | data-slot per part        | question-board / -list / -item / -text / -vote / …     |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                      |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                   |\n * | R26  | A11y                      | ordered list; vote is a toggle button with its count in its name |\n */\n\nimport * as React from 'react';\n\nimport { FlipGroup } from '@/components/ui/effects/flip-group';\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { Textarea } from '@/components/ui/textarea';\nimport type { BoardEvent, RankedQuestion } from '@/components/ui/games/question-board-model';\nimport { checkText, visibleLength, type TextRefusal, type TextRules } from '@/components/ui/games/text-safety-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n// --- QuestionBoard ----------------------------------------------------------------\n\ninterface QuestionBoardLabels {\n  /** The vote button's name. @default (count, voted) => voted ? `Remove your vote, ${count} votes` : `Vote up, ${count} votes` */\n  vote?: (count: number, voted: boolean, formatted: string) => string;\n  /** The count where there is no vote button (a shared screen, or the viewer's own). @default (n) => `${n} votes` */\n  count?: (count: number, formatted: string) => string;\n  /** Beside the pinned question. @default 'Answering now' */\n  pinned?: string;\n  /** Beside the viewer's own. @default 'Your question' */\n  mine?: string;\n  /** Under the list. @default (n) => `${n} questions` */\n  status?: (count: number, formatted: string) => string;\n  /** With no live questions. @default 'No questions yet. Ask the first one.' */\n  empty?: string;\n}\n\ntype QuestionBoardProps = Omit<React.ComponentProps<'section'>, 'children'> & {\n  /** Live questions, ranked (`rankQuestions`). */\n  questions: readonly RankedQuestion[];\n  /** Called when the viewer votes (`true`) or takes a vote back (`false`). Leave out for a shared screen: counts show without buttons. */\n  onVote?: (id: string, on: boolean) => void;\n  /** `stage` for a shared screen. @default 'default' */\n  size?: 'default' | 'stage';\n  locale?: string;\n  labels?: QuestionBoardLabels;\n};\n\nconst VOTE: NonNullable<QuestionBoardLabels['vote']> = (n, voted, f) =>\n  `${voted ? 'Remove your vote' : 'Vote up'}, ${f} ${n === 1 ? 'vote' : 'votes'}`;\n\nconst COUNT: NonNullable<QuestionBoardLabels['count']> = (n, f) => `${f} ${n === 1 ? 'vote' : 'votes'}`;\n\nfunction VoteCount({ value, formatted }: { value: number; formatted: string }) {\n  // Re-keyed on change, so the new number rises into place once.\n  return (\n    <span\n      key={value}\n      aria-hidden\n      className=\"motion-safe:animate-in motion-safe:slide-in-from-bottom-1 motion-safe:duration-(--duration-base) motion-safe:ease-enter inline-block tabular-nums\"\n    >\n      {formatted}\n    </span>\n  );\n}\n\nfunction QuestionBoard({\n  questions,\n  onVote,\n  size = 'default',\n  locale,\n  labels,\n  className,\n  ...props\n}: QuestionBoardProps) {\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const stage = size === 'stage';\n\n  return (\n    <section\n      data-slot=\"question-board\"\n      data-size={size}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-4', className)}\n      {...props}\n    >\n      {questions.length > 0 ? (\n        <FlipGroup render={<ol />} data-slot=\"question-board-list\" className=\"grid gap-3\">\n          {questions.map((q) => {\n            const formatted = nf.format(q.count);\n            return (\n              <li\n                key={q.id}\n                data-flip-id={q.id}\n                data-slot=\"question-board-item\"\n                data-pinned={q.pinned ? '' : undefined}\n                data-mine={q.mine ? '' : undefined}\n                className={cn(\n                  'bg-card relative grid grid-cols-[1fr_auto] items-start gap-4 rounded-lg border p-4',\n                  'transition-[border-color,box-shadow] duration-(--duration-medium) ease-enter',\n                  q.pinned && 'border-primary shadow-sm',\n                  stage && 'p-6',\n                )}\n              >\n                {q.pinned ? (\n                  <span aria-hidden className=\"bg-primary absolute inset-y-3 start-0 w-1 rounded-e-full\" />\n                ) : null}\n                <div className=\"grid min-w-0 gap-1.5\">\n                  {q.pinned || q.mine ? (\n                    <p className=\"flex flex-wrap gap-x-3 text-xs font-semibold\">\n                      {q.pinned ? (\n                        <span className=\"text-primary inline-flex items-center gap-1\">\n                          <Pin aria-hidden className=\"size-3.5\" />\n                          {labels?.pinned ?? 'Answering now'}\n                        </span>\n                      ) : null}\n                      {q.mine ? <span className=\"text-muted-foreground\">{labels?.mine ?? 'Your question'}</span> : null}\n                    </p>\n                  ) : null}\n                  <p\n                    data-slot=\"question-board-text\"\n                    className={cn('break-words text-pretty', stage ? 'text-2xl leading-snug' : 'text-base')}\n                  >\n                    {q.text}\n                  </p>\n                </div>\n                {onVote && !q.mine ? (\n                  <Button\n                    type=\"button\"\n                    data-slot=\"question-board-vote\"\n                    variant={q.voted ? 'default' : 'outline'}\n                    size={stage ? 'lg' : 'default'}\n                    aria-pressed={q.voted}\n                    aria-label={(labels?.vote ?? VOTE)(q.count, q.voted, formatted)}\n                    onClick={() => onVote(q.id, !q.voted)}\n                    className=\"h-auto min-h-11 min-w-14 flex-col gap-0 py-1.5\"\n                  >\n                    <ArrowUp\n                      aria-hidden\n                      className={cn(\n                        'size-4 transition-transform duration-(--duration-fast) ease-enter',\n                        q.voted && 'motion-safe:-translate-y-0.5',\n                      )}\n                    />\n                    <VoteCount value={q.count} formatted={formatted} />\n                  </Button>\n                ) : (\n                  <span\n                    data-slot=\"question-board-count\"\n                    className={cn(\n                      'text-muted-foreground flex min-h-11 min-w-14 flex-col items-center justify-center text-sm font-medium',\n                      stage && 'text-lg',\n                    )}\n                  >\n                    <ArrowUp aria-hidden className=\"size-4\" />\n                    <VoteCount value={q.count} formatted={formatted} />\n                    <span className=\"sr-only\">{(labels?.count ?? COUNT)(q.count, formatted)}</span>\n                  </span>\n                )}\n              </li>\n            );\n          })}\n        </FlipGroup>\n      ) : null}\n      <p data-slot=\"question-board-status\" aria-live=\"polite\" className=\"text-muted-foreground text-sm\">\n        {questions.length === 0\n          ? (labels?.empty ?? 'No questions yet. Ask the first one.')\n          : (labels?.status ?? ((n: number, f: string) => `${f} ${n === 1 ? 'question' : 'questions'}`))(\n              questions.length,\n              nf.format(questions.length),\n            )}\n      </p>\n    </section>\n  );\n}\nQuestionBoard.displayName = 'QuestionBoard';\n\n// --- QuestionAsk ------------------------------------------------------------------\n\ninterface QuestionAskLabels {\n  /** @default 'Your question' */\n  field?: string;\n  /** @default 'Ask' */\n  send?: string;\n  /** After sending, when the room is moderated. @default 'Sent. A moderator will check it before it shows.' */\n  sentReview?: string;\n  /** After sending, when it goes live at once. @default 'Sent. It is on the board.' */\n  sentLive?: string;\n  /** Characters left. @default (n) => `${n} characters left` */\n  left?: (remaining: number) => string;\n  /** When asking is closed. @default 'Questions are closed for now.' */\n  closed?: string;\n  refused?: Partial<Record<TextRefusal, string>>;\n}\n\ntype QuestionAskProps = Omit<React.ComponentProps<'form'>, 'onSubmit' | 'children'> &\n  Pick<TextRules, 'blocklist'> & {\n    /** Called with the checked text. */\n    onAsk?: (text: string) => void;\n    /** New questions wait for review (changes the thanks). @default true */\n    moderated?: boolean;\n    /** @default 200 */\n    maxLength?: number;\n    disabled?: boolean;\n    placeholder?: string;\n    labels?: QuestionAskLabels;\n  };\n\nconst ASK_REFUSED: Record<TextRefusal, string> = {\n  empty: 'Type a question first.',\n  'too-long': 'That is too long. Try a shorter question.',\n  'too-many-words': 'That is too long. Try a shorter question.',\n  link: 'Links cannot be sent here.',\n  contact: 'Email addresses and phone numbers cannot be sent here.',\n  blocked: 'That question cannot be shown here. Try other words.',\n};\n\nfunction QuestionAsk({\n  onAsk,\n  moderated = true,\n  maxLength = 200,\n  blocklist,\n  disabled = false,\n  placeholder,\n  labels,\n  className,\n  ...props\n}: QuestionAskProps) {\n  const [value, setValue] = React.useState('');\n  const [state, setState] = React.useState<\n    { kind: 'idle' } | { kind: 'sent' } | { kind: 'refused'; reason: TextRefusal }\n  >({\n    kind: 'idle',\n  });\n  const fieldId = React.useId();\n  const messageId = React.useId();\n  const remaining = maxLength - visibleLength(value);\n\n  const submit = (event: React.FormEvent<HTMLFormElement>) => {\n    event.preventDefault();\n    if (disabled) return;\n    const check = checkText(value, { maxLength, blocklist });\n    if (!check.ok) {\n      setState({ kind: 'refused', reason: check.reason });\n      return;\n    }\n    setValue('');\n    setState({ kind: 'sent' });\n    onAsk?.(check.text);\n  };\n\n  const message = disabled\n    ? (labels?.closed ?? 'Questions are closed for now.')\n    : state.kind === 'refused'\n      ? (labels?.refused?.[state.reason] ?? ASK_REFUSED[state.reason])\n      : state.kind === 'sent'\n        ? moderated\n          ? (labels?.sentReview ?? 'Sent. A moderator will check it before it shows.')\n          : (labels?.sentLive ?? 'Sent. It is on the board.')\n        : '';\n\n  return (\n    <form\n      data-slot=\"question-ask\"\n      data-state={disabled ? 'closed' : state.kind}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      noValidate\n      onSubmit={submit}\n      className={cn('grid gap-2', className)}\n      {...props}\n    >\n      <label htmlFor={fieldId} className=\"text-sm font-medium\">\n        {labels?.field ?? 'Your question'}\n      </label>\n      <Textarea\n        id={fieldId}\n        value={value}\n        rows={3}\n        disabled={disabled}\n        placeholder={placeholder}\n        aria-invalid={state.kind === 'refused' ? true : undefined}\n        aria-describedby={messageId}\n        onChange={(e) => {\n          setValue(e.target.value);\n          if (state.kind !== 'idle') setState({ kind: 'idle' });\n        }}\n      />\n      <div className=\"flex items-center justify-between gap-3\">\n        <span\n          data-slot=\"question-ask-count\"\n          className={cn('text-xs tabular-nums', remaining < 0 ? 'text-destructive' : 'text-muted-foreground')}\n        >\n          {(labels?.left ?? ((n: number) => `${n} characters left`))(remaining)}\n        </span>\n        <Button type=\"submit\" disabled={disabled}>\n          {labels?.send ?? 'Ask'}\n        </Button>\n      </div>\n      <p\n        id={messageId}\n        data-slot=\"question-ask-message\"\n        aria-live=\"polite\"\n        className={cn('min-h-5 text-sm', state.kind === 'refused' ? 'text-destructive' : 'text-muted-foreground')}\n      >\n        {message}\n      </p>\n    </form>\n  );\n}\nQuestionAsk.displayName = 'QuestionAsk';\n\n// --- QuestionQueue ----------------------------------------------------------------\n\ninterface QuestionQueueLabels {\n  /** @default 'In review' */\n  review?: string;\n  /** @default 'On the board' */\n  live?: string;\n  /** @default 'Answered and hidden' */\n  done?: string;\n  /** @default 'Nothing waiting.' */\n  emptyReview?: string;\n  approve?: string;\n  dismiss?: string;\n  pin?: string;\n  unpin?: string;\n  answer?: string;\n  restore?: string;\n  /** Vote count beside a live question. @default (n) => `${n} votes` */\n  votes?: (count: number, formatted: string) => string;\n}\n\ntype QuestionQueueProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** Questions waiting for review, oldest first. */\n  review: readonly RankedQuestion[];\n  /** Live questions, ranked. */\n  live: readonly RankedQuestion[];\n  /** Answered and dismissed questions, to restore. */\n  done?: readonly RankedQuestion[];\n  /** Every action sends one event for `applyBoardEvent`. */\n  onEvent: (event: BoardEvent) => void;\n  locale?: string;\n  labels?: QuestionQueueLabels;\n};\n\nfunction QueueRow({ q, children, meta }: { q: RankedQuestion; children: React.ReactNode; meta?: React.ReactNode }) {\n  return (\n    <li\n      data-flip-id={q.id}\n      data-slot=\"question-queue-item\"\n      data-status={q.status}\n      data-pinned={q.pinned ? '' : undefined}\n      className={cn('grid gap-2 rounded-md border p-3', q.pinned && 'border-primary')}\n    >\n      <p className=\"break-words text-sm\">{q.text}</p>\n      <div className=\"flex flex-wrap items-center gap-2\">\n        {meta ? <span className=\"text-muted-foreground me-auto text-xs tabular-nums\">{meta}</span> : null}\n        {children}\n      </div>\n    </li>\n  );\n}\n\nfunction QueueSection({ title, count, children }: { title: string; count: number; children: React.ReactNode }) {\n  const id = React.useId();\n  return (\n    <section aria-labelledby={id} className=\"grid gap-2\">\n      <h3 id={id} className=\"flex items-baseline gap-2 text-sm font-semibold\">\n        {title}\n        <span className=\"text-muted-foreground text-xs font-normal tabular-nums\">{count}</span>\n      </h3>\n      {children}\n    </section>\n  );\n}\n\nfunction QuestionQueue({ review, live, done = [], onEvent, locale, labels, className, ...props }: QuestionQueueProps) {\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n  const votes = labels?.votes ?? ((n: number, f: string) => `${f} ${n === 1 ? 'vote' : 'votes'}`);\n  return (\n    <div\n      data-slot=\"question-queue\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('grid gap-6', className)}\n      {...props}\n    >\n      <QueueSection title={labels?.review ?? 'In review'} count={review.length}>\n        {review.length === 0 ? (\n          <p className=\"text-muted-foreground text-sm\">{labels?.emptyReview ?? 'Nothing waiting.'}</p>\n        ) : (\n          <FlipGroup render={<ul />} className=\"grid gap-2\">\n            {review.map((q) => (\n              <QueueRow key={q.id} q={q}>\n                <Button size=\"sm\" onClick={() => onEvent({ type: 'approve', id: q.id })}>\n                  <Check aria-hidden />\n                  {labels?.approve ?? 'Approve'}\n                </Button>\n                <Button size=\"sm\" variant=\"ghost\" onClick={() => onEvent({ type: 'dismiss', id: q.id })}>\n                  <EyeOff aria-hidden />\n                  {labels?.dismiss ?? 'Dismiss'}\n                </Button>\n              </QueueRow>\n            ))}\n          </FlipGroup>\n        )}\n      </QueueSection>\n\n      <QueueSection title={labels?.live ?? 'On the board'} count={live.length}>\n        <FlipGroup render={<ul />} className=\"grid gap-2\">\n          {live.map((q) => (\n            <QueueRow key={q.id} q={q} meta={votes(q.count, nf.format(q.count))}>\n              <Button\n                size=\"sm\"\n                variant={q.pinned ? 'default' : 'outline'}\n                aria-pressed={q.pinned}\n                onClick={() => onEvent({ type: 'pin', id: q.pinned ? null : q.id })}\n              >\n                {q.pinned ? <PinOff aria-hidden /> : <Pin aria-hidden />}\n                {q.pinned ? (labels?.unpin ?? 'Unpin') : (labels?.pin ?? 'Pin')}\n              </Button>\n              <Button size=\"sm\" variant=\"outline\" onClick={() => onEvent({ type: 'answer', id: q.id })}>\n                <Check aria-hidden />\n                {labels?.answer ?? 'Answered'}\n              </Button>\n              <Button size=\"sm\" variant=\"ghost\" onClick={() => onEvent({ type: 'dismiss', id: q.id })}>\n                <EyeOff aria-hidden />\n                {labels?.dismiss ?? 'Hide'}\n              </Button>\n            </QueueRow>\n          ))}\n        </FlipGroup>\n      </QueueSection>\n\n      {done.length > 0 ? (\n        <QueueSection title={labels?.done ?? 'Answered and hidden'} count={done.length}>\n          <ul className=\"grid gap-2\">\n            {done.map((q) => (\n              <QueueRow key={q.id} q={q}>\n                <Button size=\"sm\" variant=\"ghost\" onClick={() => onEvent({ type: 'restore', id: q.id })}>\n                  <RotateCcw aria-hidden />\n                  {labels?.restore ?? 'Back to the board'}\n                </Button>\n              </QueueRow>\n            ))}\n          </ul>\n        </QueueSection>\n      ) : null}\n    </div>\n  );\n}\nQuestionQueue.displayName = 'QuestionQueue';\n\nexport { QuestionBoard, QuestionAsk, QuestionQueue };\nexport type {\n  QuestionBoardProps,\n  QuestionBoardLabels,\n  QuestionAskProps,\n  QuestionAskLabels,\n  QuestionQueueProps,\n  QuestionQueueLabels,\n};\n"
    },
    {
      "path": "registry/interlace-ui/games/question-board-model.ts",
      "target": "components/ui/games/question-board-model.ts",
      "type": "registry:ui",
      "content": "import { checkText, type TextRefusal, type TextRules } from '@/components/ui/games/text-safety-model';\n\n/**\n * @interlace/ui — question-board-model\n *\n * A room's questions, as one state the host owns: people ask, the room\n * votes the ones it wants answered up, and a moderator decides what reaches\n * the shared screen. Pure, so the host's device, a server and a recap page\n * all agree on the order.\n *\n * ## Lifecycle of a question\n *\n *   ask ──▶ review ──approve──▶ live ──answer──▶ answered\n *             │                  │  ▲\n *             └──dismiss──▶ dismissed ◀──dismiss──┘ │\n *                               └────restore────────┘\n *\n * With `moderated` off, a question skips review and goes live at once.\n * `pin` marks the one live question being answered now (at most one).\n *\n * ## Votes\n *\n * One vote per person per question, toggled with `vote` / `unvote`. Nobody\n * votes for their own question, and only live questions take votes.\n *\n * ## Order\n *\n * `rankQuestions` sorts live questions: the pinned one first, then most\n * votes, then the oldest, so a question that has waited longer wins a tie.\n */\n\nexport type QuestionStatus = 'review' | 'live' | 'answered' | 'dismissed';\n\nexport interface BoardQuestion {\n  id: string;\n  text: string;\n  /** Who asked. Never shown unless the consumer chooses to. */\n  by: string;\n  /** When it arrived, in ms (host clock). */\n  at: number;\n  status: QuestionStatus;\n  /** Ids of the people who voted it up. */\n  votes: string[];\n}\n\nexport interface BoardState {\n  questions: BoardQuestion[];\n  /** New questions wait for review. @default true */\n  moderated: boolean;\n  /** Taking new questions. */\n  open: boolean;\n  /** The live question being answered now. */\n  pinned: string | null;\n  /** Bumped on every change. */\n  seq: number;\n}\n\nexport interface BoardRules extends Pick<TextRules, 'blocklist' | 'allowLinks' | 'allowContact'> {\n  /** The longest question, in characters. @default 200 */\n  maxLength?: number;\n  /** Questions one person may ask. @default 5 */\n  maxPerPerson?: number;\n}\n\nexport type BoardEvent =\n  | { type: 'ask'; id: string; text: string; by: string; at: number }\n  | { type: 'vote'; id: string; by: string }\n  | { type: 'unvote'; id: string; by: string }\n  | { type: 'approve'; id: string }\n  | { type: 'dismiss'; id: string }\n  | { type: 'restore'; id: string }\n  | { type: 'answer'; id: string }\n  | { type: 'pin'; id: string | null }\n  | { type: 'moderate'; on: boolean }\n  | { type: 'open'; on: boolean };\n\nexport type BoardRejection =\n  | TextRefusal\n  | 'closed'\n  | 'limit'\n  | 'duplicate-id'\n  | 'unknown'\n  | 'not-live'\n  | 'own'\n  | 'already'\n  | 'not-voted'\n  | 'wrong-status';\n\nexport type BoardResult = { ok: true; state: BoardState } | { ok: false; reason: BoardRejection; state: BoardState };\n\nexport function createBoard(init: { moderated?: boolean; open?: boolean } = {}): BoardState {\n  return { questions: [], moderated: init.moderated ?? true, open: init.open ?? true, pinned: null, seq: 0 };\n}\n\nconst isQuestion = (q: unknown): q is BoardQuestion => Boolean(q);\n/** A room's slice is the room's to forge: a question may arrive without a votes list. */\nconst votesOf = (q: BoardQuestion): string[] => (Array.isArray(q.votes) ? q.votes : []);\n/** A forged time (NaN, Infinity) waits behind every real one, and stays a number a sort can subtract. */\nconst whenOf = (q: BoardQuestion): number => (Number.isFinite(q.at) ? q.at : Number.MAX_VALUE);\n\nconst FROM: Record<'approve' | 'dismiss' | 'restore' | 'answer', readonly QuestionStatus[]> = {\n  approve: ['review'],\n  dismiss: ['review', 'live', 'answered'],\n  restore: ['dismissed', 'answered'],\n  answer: ['live'],\n};\nconst TO: Record<'approve' | 'dismiss' | 'restore' | 'answer', QuestionStatus> = {\n  approve: 'live',\n  dismiss: 'dismissed',\n  restore: 'live',\n  answer: 'answered',\n};\n\n/** Applies one event, or says why it cannot. The state is never mutated. */\nexport function applyBoardEvent(state: BoardState, event: BoardEvent, rules: BoardRules = {}): BoardResult {\n  const no = (reason: BoardRejection): BoardResult => ({ ok: false, reason, state });\n  const next = (patch: Partial<BoardState>): BoardResult => ({\n    ok: true,\n    state: { ...state, ...patch, seq: state.seq + 1 },\n  });\n  const find = (id: string) => state.questions.find((q) => isQuestion(q) && q.id === id);\n  // Only the first question of an id is the one `find` returned; a forged twin keeps its own text.\n  const replace = (q: BoardQuestion) => {\n    let done = false;\n    return state.questions.map((x) => {\n      if (done || !isQuestion(x) || x.id !== q.id) return x;\n      done = true;\n      return q;\n    });\n  };\n\n  switch (event.type) {\n    case 'ask': {\n      if (!state.open) return no('closed');\n      if (find(event.id)) return no('duplicate-id');\n      if (typeof event.text !== 'string') return no('empty');\n      const { maxLength = 200, maxPerPerson = 5, ...textRules } = rules;\n      const check = checkText(event.text, { ...textRules, maxLength });\n      if (!check.ok) return no(check.reason);\n      if (state.questions.filter((q) => q.by === event.by).length >= maxPerPerson) return no('limit');\n      const q: BoardQuestion = {\n        id: event.id,\n        text: check.text,\n        by: event.by,\n        at: event.at,\n        status: state.moderated ? 'review' : 'live',\n        votes: [],\n      };\n      return next({ questions: [...state.questions, q] });\n    }\n    case 'vote':\n    case 'unvote': {\n      const q = find(event.id);\n      if (!q) return no('unknown');\n      if (q.status !== 'live') return no('not-live');\n      const votes = votesOf(q);\n      const has = votes.includes(event.by);\n      if (event.type === 'vote') {\n        if (q.by === event.by) return no('own');\n        if (has) return no('already');\n        return next({ questions: replace({ ...q, votes: [...votes, event.by] }) });\n      }\n      if (!has) return no('not-voted');\n      return next({ questions: replace({ ...q, votes: votes.filter((v) => v !== event.by) }) });\n    }\n    case 'approve':\n    case 'dismiss':\n    case 'restore':\n    case 'answer': {\n      const q = find(event.id);\n      if (!q) return no('unknown');\n      if (!FROM[event.type].includes(q.status)) return no('wrong-status');\n      return next({\n        questions: replace({ ...q, status: TO[event.type] }),\n        pinned: state.pinned === q.id ? null : state.pinned,\n      });\n    }\n    case 'pin': {\n      if (event.id === null) return next({ pinned: null });\n      const q = find(event.id);\n      if (!q) return no('unknown');\n      if (q.status !== 'live') return no('not-live');\n      return next({ pinned: q.id });\n    }\n    case 'moderate':\n      return next({ moderated: event.on });\n    case 'open':\n      return next({ open: event.on });\n  }\n}\n\nexport interface RankedQuestion extends BoardQuestion {\n  /** Votes, as a number. */\n  count: number;\n  pinned: boolean;\n  /** The viewer asked it. */\n  mine: boolean;\n  /** The viewer voted for it. */\n  voted: boolean;\n}\n\n/** Questions in one status, ranked: pinned first, then most votes, then oldest. */\nexport function rankQuestions(\n  state: BoardState,\n  options: { viewer?: string; status?: QuestionStatus } = {},\n): RankedQuestion[] {\n  const { viewer, status = 'live' } = options;\n  return state.questions\n    .filter((q) => isQuestion(q) && q.status === status)\n    .map(\n      (q): RankedQuestion => ({\n        ...q,\n        votes: votesOf(q),\n        count: votesOf(q).length,\n        pinned: state.pinned === q.id,\n        mine: viewer !== undefined && q.by === viewer,\n        voted: viewer !== undefined && votesOf(q).includes(viewer),\n      }),\n    )\n    .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.count - a.count || whenOf(a) - whenOf(b));\n}\n\n/** How many questions are in each status. */\nexport function boardCounts(state: BoardState): Record<QuestionStatus, number> {\n  const out: Record<QuestionStatus, number> = { review: 0, live: 0, answered: 0, dismissed: 0 };\n  for (const q of state.questions) if (isQuestion(q) && Object.hasOwn(out, q.status)) out[q.status]++;\n  return out;\n}\n"
    },
    {
      "path": "registry/interlace-ui/games/text-safety-model.ts",
      "target": "components/ui/games/text-safety-model.ts",
      "type": "registry:ui",
      "content": "export type TextRefusal = 'empty' | 'too-long' | 'too-many-words' | 'link' | 'contact' | 'blocked';\n\nexport interface TextRules {\n  /** The most characters, as the reader counts them. @default 200 */\n  maxLength?: number;\n  /** The most words. @default Infinity */\n  maxWords?: number;\n  /** Words the room refuses. Matched whole, after `foldText`. */\n  blocklist?: readonly string[];\n  /** Let links through. @default false */\n  allowLinks?: boolean;\n  /** Let email addresses and phone numbers through. @default false */\n  allowContact?: boolean;\n}\n\nexport type TextCheck = { ok: true; text: string } | { ok: false; reason: TextRefusal };\n\nconst SWAPS: Record<string, string> = { '0': 'o', '1': 'i', '3': 'e', '4': 'a', '5': 's', '7': 't', '@': 'a', $: 's' };\n\n/** Trims, collapses runs of white space and applies Unicode NFC, so the same word typed twice is the same string. */\nexport function tidyText(input: string): string {\n  return input.normalize('NFC').replace(/\\s+/gu, ' ').trim();\n}\n\n/** How many characters a reader sees (grapheme clusters, so an emoji or a letter with marks counts once). */\nexport function visibleLength(text: string): number {\n  if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n    let n = 0;\n    for (const _ of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text)) n++;\n    return n;\n  }\n  return Array.from(text).length;\n}\n\n/** Splits into words on white space. */\nexport function wordsOf(text: string): string[] {\n  const t = tidyText(text);\n  return t ? t.split(' ') : [];\n}\n\n/**\n * The form used for matching, never for showing: lowercase, no accents or\n * combining marks (Latin accents, Hebrew points, Arabic short vowels), the\n * common letter swaps folded, and spelled-out letters joined.\n */\nexport function foldText(input: string): string {\n  const base = input\n    .normalize('NFKD')\n    .replace(/\\p{M}+/gu, '')\n    .toLowerCase()\n    .replace(/[013457@$]/g, (c) => SWAPS[c] as string);\n  // \"b a d\", \"b.a.d\", \"b-a-d\" → \"bad\": three or more single letters in a row.\n  const joined = base.replace(\n    /(?<![\\p{L}\\p{N}])\\p{L}(?:[\\s.\\-_*]+\\p{L})(?:[\\s.\\-_*]+\\p{L})+(?![\\p{L}\\p{N}])/gu,\n    (run) => run.replace(/[\\s.\\-_*]+/g, ''),\n  );\n  return joined\n    .replace(/[^\\p{L}\\p{N}\\s]+/gu, ' ')\n    .replace(/\\s+/gu, ' ')\n    .trim();\n}\n\nconst LINK =\n  /(?:https?:\\/\\/|www\\.)\\S+|\\b[\\p{L}\\p{N}-]+\\.(?:com|net|org|io|co|me|ly|gg|app|dev|info|xyz|tv|link|site|online)\\b/iu;\n// Matched per word and anchored, with classes that cannot overlap, so a long\n// run of one character costs linear time, not quadratic.\nconst EMAIL_WORD = /^[^@]+@[^@.]+(?:\\.[^@.]+)+$/u;\nconst hasEmail = (text: string) => text.split(' ').some((word) => EMAIL_WORD.test(word));\n// Seven or more digits, allowing the usual separators (spaces, dots,\n// dashes, brackets, a leading plus) between them. A single pass, so no input\n// can make it slow.\nconst PHONE_SEPARATORS = new Set([' ', '\\t', '\\n', '(', ')', '.', '-', '+']);\nfunction hasPhone(text: string): boolean {\n  let digits = 0;\n  for (const ch of text) {\n    if (ch >= '0' && ch <= '9') {\n      digits += 1;\n      if (digits >= 7) return true;\n    } else if (!PHONE_SEPARATORS.has(ch)) {\n      digits = 0;\n    }\n  }\n  return false;\n}\n\n/** Runs every rule and says the first one the text breaks. */\nexport function checkText(input: string, rules: TextRules = {}): TextCheck {\n  const {\n    maxLength = 200,\n    maxWords = Number.POSITIVE_INFINITY,\n    blocklist,\n    allowLinks = false,\n    allowContact = false,\n  } = rules;\n  const text = tidyText(input);\n  if (!text) return { ok: false, reason: 'empty' };\n  if (visibleLength(text) > maxLength) return { ok: false, reason: 'too-long' };\n  if (!allowContact && (hasEmail(text) || hasPhone(text))) return { ok: false, reason: 'contact' };\n  if (!allowLinks && LINK.test(text)) return { ok: false, reason: 'link' };\n  if (blocklist && blocklist.length > 0 && isBlocked(text, blocklist)) return { ok: false, reason: 'blocked' };\n  if (wordsOf(text).length > maxWords) return { ok: false, reason: 'too-many-words' };\n  return { ok: true, text };\n}\n\n/**\n * True when any whole word, or run of words, of `text` is on the list.\n * Letters spelled out with spaces (\"b a d\") fold back into a word anywhere in\n * the text. Other splits (\"ba d\") are caught only when they are the whole\n * text, so a moderation queue still matters for open text.\n */\nexport function isBlocked(text: string, blocklist: readonly string[]): boolean {\n  const hay = ` ${foldText(text)} `;\n  const squeezed = ` ${hay.replace(/\\s+/g, '')} `;\n  for (const raw of blocklist) {\n    const needle = foldText(raw);\n    if (!needle) continue;\n    if (hay.includes(` ${needle} `)) return true;\n    // The whole text is the word with its spaces taken out (\"ba d\").\n    if (!needle.includes(' ') && squeezed === ` ${needle} `) return true;\n  }\n  return false;\n}\n\n/**\n * @interlace/ui — text-safety-model\n *\n * The checks a short piece of typed text passes before a room shows it on a\n * shared screen: a word for a word cloud, a question for a Q&A board, a line\n * for an open wall. Pure, so the phone that sends it and the server that\n * receives it run the same rules and agree on the reason.\n *\n * ## What it checks, in order\n *\n *   1. empty            nothing left after trimming\n *   2. too-long         more than `maxLength` characters (counted as the reader sees them)\n *   3. contact          an email address or a phone number\n *   4. link             a URL or a bare domain\n *   5. blocked          a word on the consumer's `blocklist`\n *   6. too-many-words   more than `maxWords` words\n *\n * `blocked` comes before the word count, so \"b a d\" is refused for what it\n * says, not for having three words.\n *\n * Interlace ships no word list of its own: what is unwelcome depends on the\n * room, its language and its audience, so the consumer passes one. Matching\n * runs on `foldText`, which lowercases, strips accents and marks, folds the\n * common letter swaps (0→o, 1→i, 3→e, 4→a, 5→s, 7→t, @→a, $→s) and joins\n * letters spelled out with spaces or dots (\"b a d\" → \"bad\"), so the usual\n * dodges do not get through. Whole words only: a blocked word inside a\n * longer, innocent word is not a match.\n *\n * A filter is one layer, never the only one. Rooms that show typed text to\n * a crowd should also hold it for review (see `question-board-model`).\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/question-board\n\nInstalled to `components/ui/games/question-board.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/question-board';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/question-board\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
