{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "word-cloud",
  "type": "registry:ui",
  "title": "Word Cloud",
  "description": "The room's words, live. Phones send a word or two with `WordEntry`; the shared screen shows them as a `WordCloud` in which the words the room repeats grow, the biggest sit in the middle, and every change moves into place rather than jumping there. Anyone…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [],
  "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/input.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/word-cloud.tsx",
      "target": "components/ui/games/word-cloud.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/word-cloud v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/word-cloud\n// What changed since: https://ds.interlace.tools/c/word-cloud#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — WordCloud and WordEntry\n *\n * The room's words, live. Phones send a word or two with `WordEntry`; the\n * shared screen shows them as a `WordCloud` in which the words the room\n * repeats grow, the biggest sit in the middle, and every change moves into\n * place rather than jumping there. Anyone in the room sees their voice land\n * within a second, without their name on it.\n *\n * ## Anatomy\n *\n *   WordCloud                       (div — data-slot=\"word-cloud\", @container)\n *     ├─ ul (FlipGroup)             (data-slot=\"word-cloud-list\", rank order in the DOM)\n *     │    ├─ li × n                (data-slot=\"word-cloud-word\", data-step=1…5, data-band, data-mine, data-top)\n *     │    └─ li × 2                (data-slot=\"word-cloud-break\": hidden line breaks between the bands)\n *     └─ p aria-live               (data-slot=\"word-cloud-status\": \"12 words from the room\", or the empty text)\n *\n *   WordEntry                       (form — data-slot=\"word-entry\")\n *     ├─ label + Input + Button     (data-slot=\"word-entry-field\")\n *     ├─ p aria-live               (data-slot=\"word-entry-message\": why a word was refused, or how many are left)\n *     └─ ul                         (data-slot=\"word-entry-sent\": the viewer's own words, as chips)\n *\n * ## Data\n *\n * `WordCloud` takes `entries` (what was typed, and by whom) and builds the\n * cloud with `buildCloud` from `word-cloud-model`, or a prebuilt `words`\n * list from a server. `WordEntry` checks each word with `checkText` from\n * `text-safety-model` before `onWord` fires, so a refused word never leaves\n * the phone; run the same check on the server, which is the one that counts.\n * Pass your room's `blocklist` to both.\n *\n * ## Motion\n *\n * The list is a FlipGroup: when a word climbs, it and its neighbours glide\n * to their new places (400ms, `--ease-move`), and a new word scales up from\n * where it lands. A word whose count went up gives one small pulse\n * (`transform` only, 250ms), so the eye finds what just changed. Under\n * reduced motion every word simply takes its place.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                     |\n * | ---- | ------------------------- | ------------------------------------------------------ |\n * | R4   | Extends native el         | `div` / `form` props                                   |\n * | R6   | data-slot per part        | word-cloud / -list / -word / -status, word-entry / …   |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                      |\n * | R9   | Controlled + uncontrolled | WordEntry `sent` / `defaultSent` / `onWord`            |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                   |\n * | R26  | A11y                      | list in rank order, each word with its count; refusals announced |\n */\n\nimport { FlipGroup } from '@/components/ui/effects/flip-group';\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { Button } from '@/components/ui/button';\nimport { Input } from '@/components/ui/input';\nimport { checkText, type TextRefusal, type TextRules } from '@/components/ui/games/text-safety-model';\nimport {\n  buildCloud,\n  CLOUD_BREAKS,\n  cloudOrder,\n  type CloudEntry,\n  type CloudOptions,\n  type CloudWord,\n} from '@/components/ui/games/word-cloud-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\n// --- WordCloud ------------------------------------------------------------------\n\ninterface WordCloudLabels {\n  /** Read with each word. @default (word, count) => `${word}, ${count}` */\n  word?: (text: string, count: number, formatted: string) => string;\n  /** Under the cloud. @default (total, formatted) => `${formatted} ${total === 1 ? 'word' : 'words'} from the room` */\n  status?: (total: number, formatted: string) => string;\n  /** While nothing has been sent. @default 'Words appear here as people send them.' */\n  empty?: string;\n  /** Marks the viewer's own words for screen readers. @default 'yours' */\n  mine?: string;\n}\n\ntype WordCloudProps = Omit<React.ComponentProps<'div'>, 'children'> &\n  Pick<CloudOptions, 'max' | 'stopwords' | 'viewer'> & {\n    /** What the room sent. Ignored when `words` is given. */\n    entries?: readonly (CloudEntry | string)[];\n    /** A cloud already built (for example by a server with `buildCloud`). */\n    words?: readonly CloudWord[];\n    /** `stage` for a shared screen across a room, `default` for a page or a phone. @default 'default' */\n    size?: 'default' | 'stage';\n    locale?: string;\n    labels?: WordCloudLabels;\n  };\n\nconst STEP_CLASS: Record<'default' | 'stage', readonly string[]> = {\n  default: ['text-sm', 'text-base', 'text-xl', 'text-3xl', 'text-5xl'],\n  stage: ['text-lg', 'text-2xl', 'text-4xl', 'text-6xl', 'text-8xl'],\n};\nconst WEIGHT = ['font-normal', 'font-normal', 'font-medium', 'font-semibold', 'font-bold'] as const;\n\nfunction WordCloud({\n  entries,\n  words: wordsProp,\n  max,\n  stopwords,\n  viewer,\n  size = 'default',\n  locale,\n  labels,\n  className,\n  ...props\n}: WordCloudProps) {\n  const reduced = useReducedMotion();\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const nf = React.useMemo(() => new Intl.NumberFormat(locale), [locale]);\n\n  const cloud = React.useMemo(() => {\n    if (wordsProp) {\n      return { words: [...wordsProp], total: wordsProp.reduce((a, w) => a + w.count, 0) };\n    }\n    return buildCloud(entries ?? [], { max, stopwords, viewer });\n  }, [wordsProp, entries, max, stopwords, viewer]);\n\n  const places = React.useMemo(() => cloudOrder(cloud.words.length), [cloud.words.length]);\n\n  // One pulse on each word whose count went up since the last render.\n  const counts = React.useRef(new Map<string, number>());\n  React.useEffect(() => {\n    const prev = counts.current;\n    const next = new Map(cloud.words.map((w) => [w.key, w.count]));\n    counts.current = next;\n    if (reduced || prev.size === 0) return;\n    const root = listRef.current;\n    if (!root) return;\n    for (const w of cloud.words) {\n      const before = prev.get(w.key);\n      if (before === undefined || before >= w.count) continue;\n      const el = root.querySelector<HTMLElement>(\n        `[data-word-key=\"${CSS.escape(w.key)}\"] [data-slot=\"word-cloud-text\"]`,\n      );\n      if (!el || typeof el.animate !== 'function') continue;\n      el.animate([{ transform: 'scale(1)' }, { transform: 'scale(1.18)' }, { transform: 'scale(1)' }], {\n        duration: motionDuration(el, 'medium'),\n        easing: motionEase(el, 'enter'),\n      });\n    }\n  }, [cloud.words, reduced]);\n\n  const sizes = STEP_CLASS[size];\n\n  return (\n    <div\n      data-slot=\"word-cloud\"\n      data-size={size}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('@container grid gap-4', className)}\n      {...props}\n    >\n      <div ref={listRef}>\n        <FlipGroup\n          render={<ul />}\n          data-slot=\"word-cloud-list\"\n          className={cn(\n            'flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-center',\n            size === 'stage' ? 'min-h-48 gap-x-8 gap-y-2' : 'min-h-32',\n          )}\n        >\n          {cloud.words.map((w, i) => {\n            const step = Math.min(sizes.length, Math.max(1, w.step)) - 1;\n            const formatted = nf.format(w.count);\n            const top = w.rank === 0 && cloud.words.length > 1;\n            return (\n              <li\n                key={w.key}\n                data-flip-id={w.key}\n                data-word-key={w.key}\n                data-slot=\"word-cloud-word\"\n                data-step={step + 1}\n                data-top={top ? '' : undefined}\n                data-mine={w.mine ? '' : undefined}\n                data-band={places[i]?.band}\n                style={{ order: places[i]?.order }}\n                className=\"max-w-full leading-tight\"\n              >\n                <span\n                  data-slot=\"word-cloud-text\"\n                  aria-hidden\n                  className={cn(\n                    'inline-block break-words font-heading tracking-tight',\n                    sizes[step],\n                    WEIGHT[step],\n                    top ? 'text-primary' : step <= 1 ? 'text-muted-foreground' : 'text-foreground',\n                    w.mine && 'decoration-primary underline decoration-2 underline-offset-4',\n                  )}\n                >\n                  {w.text}\n                </span>\n                <span className=\"sr-only\">\n                  {(labels?.word ?? ((t: string, _c: number, f: string) => `${t}, ${f}`))(w.text, w.count, formatted)}\n                  {w.mine ? `, ${labels?.mine ?? 'yours'}` : ''}\n                </span>\n              </li>\n            );\n          })}\n          {cloud.words.length > 1\n            ? CLOUD_BREAKS.map((order) => (\n                <li\n                  key={`break-${order}`}\n                  role=\"presentation\"\n                  aria-hidden\n                  data-slot=\"word-cloud-break\"\n                  className=\"h-0 basis-full\"\n                  style={{ order }}\n                />\n              ))\n            : null}\n        </FlipGroup>\n      </div>\n      <p\n        data-slot=\"word-cloud-status\"\n        aria-live=\"polite\"\n        className=\"text-muted-foreground text-center text-sm tabular-nums\"\n      >\n        {cloud.total === 0\n          ? (labels?.empty ?? 'Words appear here as people send them.')\n          : (labels?.status ?? ((n: number, f: string) => `${f} ${n === 1 ? 'word' : 'words'} from the room`))(\n              cloud.total,\n              nf.format(cloud.total),\n            )}\n      </p>\n    </div>\n  );\n}\nWordCloud.displayName = 'WordCloud';\n\n// --- WordEntry ------------------------------------------------------------------\n\ninterface WordEntryLabels {\n  /** The field's label. @default 'Your word' */\n  field?: string;\n  /** The button. @default 'Send' */\n  send?: string;\n  /** How many are left. @default (n) => `You can send ${n} more.` */\n  left?: (remaining: number) => string;\n  /** When every word is sent. @default 'Thanks. Your words are on the screen.' */\n  done?: string;\n  /** The list of sent words. @default 'Your words' */\n  sent?: string;\n  /** Why a word was refused. */\n  refused?: Partial<Record<TextRefusal | 'repeat', string>>;\n}\n\ntype WordEntryProps = Omit<React.ComponentProps<'form'>, 'onSubmit' | 'children'> &\n  Pick<TextRules, 'blocklist'> & {\n    /** Words each person may send. @default 3 */\n    maxWords?: number;\n    /** The longest word or phrase, in characters. @default 25 */\n    maxLength?: number;\n    /** Words in one entry (\"good food\" is two). @default 2 */\n    wordsPerEntry?: number;\n    /** The words sent so far, controlled. */\n    sent?: readonly string[];\n    /** The words sent so far, uncontrolled. */\n    defaultSent?: readonly string[];\n    /** Called once per accepted word. */\n    onWord?: (word: string) => void;\n    /** No more words (for example when the host closes the round). */\n    disabled?: boolean;\n    placeholder?: string;\n    labels?: WordEntryLabels;\n  };\n\nconst REFUSED: Record<TextRefusal | 'repeat', string> = {\n  empty: 'Type a word first.',\n  'too-long': 'That is too long. Try a shorter word.',\n  'too-many-words': 'One or two words, please.',\n  link: 'Links cannot be sent here.',\n  contact: 'Email addresses and phone numbers cannot be sent here.',\n  blocked: 'That word cannot be shown here. Try another.',\n  repeat: 'You already sent that one.',\n};\n\nfunction WordEntry({\n  maxWords = 3,\n  maxLength = 25,\n  wordsPerEntry = 2,\n  blocklist,\n  sent: sentProp,\n  defaultSent = [],\n  onWord,\n  disabled = false,\n  placeholder,\n  labels,\n  className,\n  ...props\n}: WordEntryProps) {\n  const [own, setOwn] = React.useState<readonly string[]>(defaultSent);\n  const sent = sentProp ?? own;\n  const [value, setValue] = React.useState('');\n  const [refusal, setRefusal] = React.useState<TextRefusal | 'repeat' | null>(null);\n  const inputId = React.useId();\n  const messageId = React.useId();\n  const remaining = Math.max(0, maxWords - sent.length);\n  const closed = disabled || remaining === 0;\n\n  const submit = (event: React.FormEvent<HTMLFormElement>) => {\n    event.preventDefault();\n    if (closed) return;\n    const check = checkText(value, { maxLength, maxWords: wordsPerEntry, blocklist });\n    if (!check.ok) {\n      setRefusal(check.reason);\n      return;\n    }\n    if (sent.some((s) => s.toLocaleLowerCase() === check.text.toLocaleLowerCase())) {\n      setRefusal('repeat');\n      return;\n    }\n    setRefusal(null);\n    setValue('');\n    if (sentProp === undefined) setOwn((prev) => [...prev, check.text]);\n    onWord?.(check.text);\n  };\n\n  const message = refusal\n    ? (labels?.refused?.[refusal] ?? REFUSED[refusal])\n    : remaining === 0\n      ? (labels?.done ?? 'Thanks. Your words are on the screen.')\n      : sent.length > 0\n        ? (labels?.left ?? ((n: number) => `You can send ${n} more.`))(remaining)\n        : '';\n\n  return (\n    <form\n      data-slot=\"word-entry\"\n      data-state={closed ? 'closed' : 'open'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      noValidate\n      onSubmit={submit}\n      className={cn('grid gap-3', className)}\n      {...props}\n    >\n      <div data-slot=\"word-entry-field\" className=\"grid gap-1.5\">\n        <label htmlFor={inputId} className=\"text-sm font-medium\">\n          {labels?.field ?? 'Your word'}\n        </label>\n        <div className=\"flex gap-2\">\n          <Input\n            id={inputId}\n            value={value}\n            onChange={(e) => {\n              setValue(e.target.value);\n              if (refusal) setRefusal(null);\n            }}\n            placeholder={placeholder}\n            disabled={closed}\n            autoComplete=\"off\"\n            autoCapitalize=\"none\"\n            enterKeyHint=\"send\"\n            maxLength={maxLength * 2}\n            aria-invalid={refusal ? true : undefined}\n            aria-describedby={messageId}\n            className=\"min-w-0 flex-1\"\n          />\n          <Button type=\"submit\" size=\"lg\" disabled={closed}>\n            {labels?.send ?? 'Send'}\n          </Button>\n        </div>\n      </div>\n      <p\n        id={messageId}\n        data-slot=\"word-entry-message\"\n        data-refused={refusal ?? undefined}\n        aria-live=\"polite\"\n        className={cn('min-h-5 text-sm', refusal ? 'text-destructive' : 'text-muted-foreground')}\n      >\n        {message}\n      </p>\n      {sent.length > 0 ? (\n        <ul data-slot=\"word-entry-sent\" aria-label={labels?.sent ?? 'Your words'} className=\"flex flex-wrap gap-2\">\n          {sent.map((w) => (\n            <li\n              key={w}\n              className=\"bg-primary/10 text-foreground motion-safe:animate-in motion-safe:zoom-in-90 motion-safe:duration-(--duration-base) motion-safe:ease-enter rounded-full px-3 py-1 text-sm font-medium\"\n            >\n              {w}\n            </li>\n          ))}\n        </ul>\n      ) : null}\n    </form>\n  );\n}\nWordEntry.displayName = 'WordEntry';\n\nexport { WordCloud, WordEntry };\nexport type { WordCloudProps, WordCloudLabels, WordEntryProps, WordEntryLabels };\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"
    },
    {
      "path": "registry/interlace-ui/games/word-cloud-model.ts",
      "target": "components/ui/games/word-cloud-model.ts",
      "type": "registry:ui",
      "content": "import { foldText, tidyText } from '@/components/ui/games/text-safety-model';\n\n/**\n * @interlace/ui — word-cloud-model\n *\n * Turns the words a room sent into the cloud it sees: grouped, counted,\n * ranked and sized. Pure, so a server can build the same cloud for a recap\n * page or an export.\n *\n * ## Grouping\n *\n * Two entries are the same word when their `foldText` forms match, so\n * \"Coffee\", \"coffee \" and \"COFFEE\" land on one word. The cloud shows the\n * spelling most people used (ties go to the first one sent). A sender (`by`)\n * counts once per word, and an entry with an `id` counts once however often\n * it arrives, so a reconnect that resends the room's words changes nothing. Stop words the\n * consumer passes are dropped; Interlace ships none, because they depend on\n * the language of the room.\n *\n * ## Size\n *\n * `step` is 1 to `steps` (default 5), on a square-root scale of the count, so\n * one runaway word does not shrink every other word to a dot. `share` is the\n * word's part of all words, 0 to 1.\n *\n * ## Order\n *\n * `words` come back in rank order (most first, then the first sent), the\n * order a screen reader hears. `cloudOrder` gives each rank a visual place:\n * the biggest words on a middle band, centre-out, with the smaller words\n * on bands above and below, which is how a cloud is read at a glance.\n */\n\nexport interface CloudEntry {\n  /** What was typed. */\n  text: string;\n  /** Who sent it, so `mine` can be marked. A person counts once per word. Optional. */\n  by?: string;\n  /** The entry's own id. An entry delivered twice (a reconnect, a retry) counts once. Optional. */\n  id?: string;\n}\n\nexport interface CloudWord {\n  /** Stable id for the word (its folded form). */\n  key: string;\n  /** The spelling to show. */\n  text: string;\n  count: number;\n  /** 0 to 1, of all counted words. */\n  share: number;\n  /** 1 (smallest) to `steps`. */\n  step: number;\n  /** 0 for the most-sent word. */\n  rank: number;\n  /** True when `viewer` sent it. */\n  mine: boolean;\n}\n\nexport interface CloudOptions {\n  /** Keep at most this many words, the most-sent first. @default 50 */\n  max?: number;\n  /** Size steps. @default 5 */\n  steps?: number;\n  /** Words to leave out, matched on their folded form. */\n  stopwords?: readonly string[];\n  /** Marks the words this sender sent. */\n  viewer?: string;\n}\n\nexport interface Cloud {\n  words: CloudWord[];\n  /** Every counted word, including those past `max`. */\n  total: number;\n  /** Distinct words, including those past `max`. */\n  distinct: number;\n}\n\nexport function buildCloud(entries: readonly (CloudEntry | string)[], options: CloudOptions = {}): Cloud {\n  const { max = 50, steps = 5, stopwords, viewer } = options;\n  const stop = new Set((stopwords ?? []).map(foldText));\n  const groups = new Map<string, { first: number; count: number; spellings: Map<string, number>; mine: boolean }>();\n  const seenIds = new Set<string>();\n  const seenVotes = new Set<string>();\n  let total = 0;\n\n  entries.forEach((entry, i) => {\n    const e = (typeof entry === 'string' ? { text: entry } : entry) as CloudEntry | null | undefined;\n    // A forged message (null, a number, no text) is left out, not a crash for the whole room.\n    if (!e || typeof e.text !== 'string') return;\n    const text = tidyText(e.text);\n    const key = foldText(text);\n    if (!key || stop.has(key)) return;\n    if (e.id !== undefined) {\n      if (seenIds.has(e.id)) return;\n      seenIds.add(e.id);\n    }\n    if (e.by !== undefined) {\n      const vote = `${e.by}\\u0000${key}`;\n      if (seenVotes.has(vote)) return;\n      seenVotes.add(vote);\n    }\n    total++;\n    let g = groups.get(key);\n    if (!g) {\n      g = { first: i, count: 0, spellings: new Map(), mine: false };\n      groups.set(key, g);\n    }\n    g.count++;\n    g.spellings.set(text, (g.spellings.get(text) ?? 0) + 1);\n    if (viewer !== undefined && e.by === viewer) g.mine = true;\n  });\n\n  const ranked = [...groups.entries()].sort((a, b) => b[1].count - a[1].count || a[1].first - b[1].first);\n  const kept = ranked.slice(0, Math.max(0, max));\n  const top = kept[0]?.[1].count ?? 0;\n  const lowest = kept[kept.length - 1]?.[1].count ?? 0;\n  const span = Math.sqrt(top) - Math.sqrt(lowest);\n  // A host config that is NaN or infinite falls back to the default, not a NaN step.\n  const n = Number.isFinite(steps) ? Math.max(1, Math.floor(steps)) : 5;\n\n  const words = kept.map(([key, g], rank): CloudWord => {\n    let best = '';\n    let bestN = 0;\n    for (const [s, c] of g.spellings) {\n      if (c > bestN) {\n        best = s;\n        bestN = c;\n      }\n    }\n    // All kept words sent equally often: they share the top step.\n    const t = span > 0 ? (Math.sqrt(g.count) - Math.sqrt(lowest)) / span : 1;\n    return {\n      key,\n      text: best,\n      count: g.count,\n      // A kept word was counted, so `total` is at least 1.\n      share: g.count / total,\n      step: 1 + Math.round(t * (n - 1)),\n      rank,\n      mine: g.mine,\n    };\n  });\n\n  return { words, total, distinct: groups.size };\n}\n\n/**\n * The visual slot for each rank among `n` words: rank 0 in the middle, then\n * alternating to either side, so the biggest words sit in the centre of a\n * wrapped, centred line of words.\n *\n *   centerOut(5) → [2, 3, 1, 4, 0]   (rank 0 at slot 2, rank 1 at slot 3, …)\n */\nexport function centerOut(n: number): number[] {\n  const size = Number.isFinite(n) ? Math.floor(Math.max(0, n)) : 0;\n  const mid = Math.floor((size - 1) / 2);\n  return Array.from({ length: size }, (_, rank) => {\n    const off = Math.ceil(rank / 2);\n    return rank % 2 === 1 ? mid + off : mid - off;\n  });\n}\n\n/** The band a word sits on, and its CSS `order`, from `cloudOrder`. */\nexport interface CloudPlace {\n  band: 'above' | 'middle' | 'below';\n  order: number;\n}\n\n/** CSS `order` of the break before the middle band and the one after it. */\nexport const CLOUD_BREAKS = [999, 1999] as const;\n\n/**\n * Where each rank goes among `n` words. The top `middle` ranks (default: a\n * third, at least 1 and at most 7) sit centre-out on the middle band; the\n * rest alternate above and below it, each band centre-out too, so the\n * small words frame the big ones.\n */\nexport function cloudOrder(n: number, middle?: number): CloudPlace[] {\n  const count = Number.isFinite(n) ? Math.floor(Math.max(0, n)) : 0;\n  // A third of the words, at most 7 (ceil gives at least 1 for any word at all).\n  const wanted =\n    middle === undefined || Number.isNaN(middle) ? Math.min(7, Math.ceil(count / 3)) : Math.floor(Math.max(0, middle));\n  const mid = Math.min(count, wanted);\n  const rest = count - mid;\n  const aboveN = Math.ceil(rest / 2);\n  const slotsMid = centerOut(mid);\n  const slotsAbove = centerOut(aboveN);\n  const slotsBelow = centerOut(rest - aboveN);\n  return Array.from({ length: count }, (_, rank): CloudPlace => {\n    if (rank < mid) return { band: 'middle', order: 1000 + (slotsMid[rank] as number) };\n    const r = rank - mid;\n    const i = Math.floor(r / 2);\n    return r % 2 === 0\n      ? { band: 'above', order: slotsAbove[i] as number }\n      : { band: 'below', order: 2000 + (slotsBelow[i] as number) };\n  });\n}\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.1.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/word-cloud\n\nInstalled to `components/ui/games/word-cloud.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/word-cloud';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/word-cloud\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
