{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "reflection-card",
  "type": "registry:ui",
  "title": "Reflection Card",
  "description": "A quiet minute in a loud room: one prompt (\"What surprised you today?\"), a field, and a promise that the answer is yours. It is private by default; when the session allows it, the writer can choose to share it with the room without their name, and only…",
  "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/checkbox.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/textarea.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/reflection-card.tsx",
      "target": "components/ui/games/reflection-card.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/reflection-card v1.1.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/reflection-card\n// What changed since: https://ds.interlace.tools/c/reflection-card#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — ReflectionCard\n *\n * A quiet minute in a loud room: one prompt (\"What surprised you today?\"),\n * a field, and a promise that the answer is yours. It is private by\n * default; when the session allows it, the writer can choose to share it\n * with the room without their name, and only then is it checked like any\n * other room text (no links, no contact details, the blocklist). Saving\n * keeps the words in the card; where they are stored (this device, an\n * account) is the app's choice, and `privacy` says so in its own words.\n *\n * ## Anatomy\n *\n *   ReflectionCard                 (form — data-slot=\"reflection-card\", data-state=writing|saved)\n *     ├─ div                       (data-slot=\"reflection-card-meta\": e.g. \"1 of 3\", optional)\n *     ├─ label                     (data-slot=\"reflection-card-prompt\": names the field)\n *     ├─ Textarea                  (data-slot=\"reflection-card-field\": described by privacy + count)\n *     ├─ p                         (data-slot=\"reflection-card-privacy\": \"Only you see this.\")\n *     ├─ label + Checkbox          (data-slot=\"reflection-card-share\", when `shareable`)\n *     ├─ Button                    (data-slot=\"reflection-card-save\")\n *     └─ p aria-live               (data-slot=\"reflection-card-message\": saved, shared, or why not)\n *\n * ## Motion\n *\n * None beyond the controls' own. A reflection is not a reveal.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                                   |\n * | ---- | ------------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el         | `form` props                                         |\n * | R6   | data-slot per part        | reflection-card / -meta / -prompt / -field / -privacy / -share / -save / -message |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                    |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onChange` / `onSave`     |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                 |\n * | R26  | A11y                      | labelled field; privacy and count describe it; outcome announced |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { Checkbox } from '@/components/ui/checkbox';\nimport { Textarea } from '@/components/ui/textarea';\nimport { checkText, visibleLength, type TextRefusal } from '@/components/ui/games/text-safety-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\ninterface ReflectionCardLabels {\n  /** @default 'Only you see this.' */\n  privacy?: string;\n  /** @default 'Share it with the room, without my name' */\n  share?: string;\n  /** @default 'Save' */\n  save?: string;\n  /** @default 'Saved.' */\n  saved?: string;\n  /** @default 'Saved, and shared without your name.' */\n  shared?: string;\n  /** @default (n) => `${n} characters left` */\n  left?: (remaining: number) => string;\n  /** Why a shared reflection was not sent. It is still saved. */\n  refused?: Partial<Record<TextRefusal, string>>;\n}\n\ntype ReflectionCardProps = Omit<React.ComponentProps<'form'>, 'children' | 'onChange' | 'defaultValue' | 'onSubmit'> & {\n  prompt: React.ReactNode;\n  /** Above the prompt, e.g. \"1 of 3\". */\n  meta?: React.ReactNode;\n  value?: string;\n  defaultValue?: string;\n  onChange?: (text: string) => void;\n  /** Called on save with the text and whether it is shared. A shared text has passed the room's checks. */\n  onSave?: (text: string, options: { shared: boolean }) => void;\n  /** Offer to share it with the room, without a name. @default false */\n  shareable?: boolean;\n  /** Words the room refuses, for a shared reflection. */\n  blocklist?: readonly string[];\n  /** @default 500 */\n  maxLength?: number;\n  /** @default 4 */\n  rows?: number;\n  placeholder?: string;\n  labels?: ReflectionCardLabels;\n};\n\nconst REFUSED: Record<TextRefusal, string> = {\n  empty: 'Write something first.',\n  'too-long': 'Saved. It is too long to share; try a shorter version.',\n  'too-many-words': 'Saved. It is too long to share; try a shorter version.',\n  link: 'Saved, not shared: links cannot be shared with the room.',\n  contact: 'Saved, not shared: email addresses and phone numbers cannot be shared.',\n  blocked: 'Saved, not shared: try other words to share it.',\n};\n\ntype Status = { kind: 'writing' } | { kind: 'saved'; shared: boolean } | { kind: 'refused'; reason: TextRefusal };\n\nfunction ReflectionCard({\n  prompt,\n  meta,\n  value: valueProp,\n  defaultValue = '',\n  onChange,\n  onSave,\n  shareable = false,\n  blocklist,\n  maxLength = 500,\n  rows = 4,\n  placeholder,\n  labels,\n  className,\n  ...props\n}: ReflectionCardProps) {\n  const [own, setOwn] = React.useState(defaultValue);\n  const text = valueProp ?? own;\n  const [share, setShare] = React.useState(false);\n  const [status, setStatus] = React.useState<Status>({ kind: 'writing' });\n  const fieldId = React.useId();\n  const privacyId = React.useId();\n  const countId = React.useId();\n  const remaining = maxLength - visibleLength(text);\n\n  const submit = (e: React.FormEvent<HTMLFormElement>) => {\n    e.preventDefault();\n    // Saved or refused already, and nothing changed since (an edit or the share box resets it): a second tap must not post it again.\n    if (status.kind === 'saved' || (status.kind === 'refused' && status.reason !== 'empty')) return;\n    const trimmed = text.trim();\n    if (!trimmed) {\n      setStatus({ kind: 'refused', reason: 'empty' });\n      return;\n    }\n    if (share) {\n      const check = checkText(trimmed, { maxLength, blocklist });\n      if (!check.ok) {\n        // A private reflection is never refused: it is saved, just not shared.\n        onSave?.(trimmed, { shared: false });\n        setStatus({ kind: 'refused', reason: check.reason });\n        return;\n      }\n      onSave?.(check.text, { shared: true });\n      setStatus({ kind: 'saved', shared: true });\n      return;\n    }\n    onSave?.(trimmed, { shared: false });\n    setStatus({ kind: 'saved', shared: false });\n  };\n\n  const message =\n    status.kind === 'saved'\n      ? status.shared\n        ? (labels?.shared ?? 'Saved, and shared without your name.')\n        : (labels?.saved ?? 'Saved.')\n      : status.kind === 'refused'\n        ? (labels?.refused?.[status.reason] ?? REFUSED[status.reason])\n        : '';\n\n  return (\n    <form\n      data-slot=\"reflection-card\"\n      data-state={status.kind === 'saved' ? 'saved' : 'writing'}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      noValidate\n      onSubmit={submit}\n      className={cn('bg-card grid max-w-144 gap-3 rounded-xl border p-5', className)}\n      {...props}\n    >\n      {meta ? (\n        <div data-slot=\"reflection-card-meta\" className=\"text-muted-foreground text-sm font-medium\">\n          {meta}\n        </div>\n      ) : null}\n      <label\n        htmlFor={fieldId}\n        data-slot=\"reflection-card-prompt\"\n        className=\"font-heading text-lg font-semibold text-balance\"\n      >\n        {prompt}\n      </label>\n      <Textarea\n        id={fieldId}\n        data-slot=\"reflection-card-field\"\n        value={text}\n        rows={rows}\n        placeholder={placeholder}\n        aria-describedby={`${privacyId} ${countId}`}\n        aria-invalid={status.kind === 'refused' && status.reason === 'empty' ? true : undefined}\n        onChange={(e) => {\n          if (valueProp === undefined) setOwn(e.target.value);\n          onChange?.(e.target.value);\n          if (status.kind !== 'writing') setStatus({ kind: 'writing' });\n        }}\n      />\n      <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-1\">\n        <p id={privacyId} data-slot=\"reflection-card-privacy\" className=\"text-muted-foreground text-sm\">\n          {labels?.privacy ?? 'Only you see this.'}\n        </p>\n        <span\n          id={countId}\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      </div>\n      {shareable ? (\n        <label data-slot=\"reflection-card-share\" className=\"flex items-start gap-3 text-sm\">\n          <Checkbox\n            checked={share}\n            onCheckedChange={(v) => {\n              setShare(v === true);\n              if (status.kind !== 'writing') setStatus({ kind: 'writing' });\n            }}\n            className=\"mt-0.5\"\n          />\n          <span>{labels?.share ?? 'Share it with the room, without my name'}</span>\n        </label>\n      ) : null}\n      <div className=\"flex flex-wrap items-center gap-3\">\n        <Button data-slot=\"reflection-card-save\" type=\"submit\">\n          {labels?.save ?? 'Save'}\n        </Button>\n        <p\n          data-slot=\"reflection-card-message\"\n          aria-live=\"polite\"\n          className={cn('text-sm', status.kind === 'refused' ? 'text-destructive' : 'text-muted-foreground')}\n        >\n          {message}\n        </p>\n      </div>\n    </form>\n  );\n}\nReflectionCard.displayName = 'ReflectionCard';\n\nexport { ReflectionCard };\nexport type { ReflectionCardProps, ReflectionCardLabels };\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/reflection-card\n\nInstalled to `components/ui/games/reflection-card.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/reflection-card';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/reflection-card\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
