{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "lib-format",
  "title": "Text and date formatting helpers",
  "description": "A message filler that chooses plural forms and writes numbers in the session's language, and a long-form date formatter, shared by the blocks that render dynamic sentences.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0"
  ],
  "files": [
    {
      "path": "lib/format.ts",
      "content": "import { formatMessage } from \"@registrystack/app-runtime\";\nimport { createElement, Fragment, type ReactNode } from \"react\";\n\n/**\n * Fill a content template's placeholders with the given values, in `locale`\n * (`useLocale`). The template is one sentence that carries its own grammar,\n * an ICU message (`formatMessage`): a `{count, plural, ...}` chooses its\n * words by the locale's plural rules, and a number is written in the\n * locale's notation. Tokens are never reordered or joined with other\n * fragments. Unknown tokens stay visible so a missing value is caught instead\n * of silently dropped.\n */\nexport function fill(\n  template: string,\n  values: Readonly<Record<string, string | number>>,\n  locale: string,\n): string {\n  return formatMessage(template, values, locale);\n}\n\n/**\n * `fill` for a template whose values include page elements, such as a\n * reference set in monospace: text and number values are filled as `fill`\n * fills them, and each element takes its placeholder's place, wherever the\n * template's language puts it.\n */\nexport function fillNodes(\n  template: string,\n  values: Readonly<Record<string, ReactNode>>,\n  locale: string,\n): ReactNode {\n  const elements: ReactNode[] = [];\n  const texts: Record<string, string | number> = {};\n  for (const [name, value] of Object.entries(values)) {\n    if (typeof value === \"string\" || typeof value === \"number\") {\n      texts[name] = value;\n    } else {\n      texts[name] = `\\uE000${elements.length}\\uE001`;\n      elements.push(value);\n    }\n  }\n  const parts = fill(template, texts, locale).split(/\\uE000(\\d+)\\uE001/);\n  return createElement(\n    Fragment,\n    null,\n    ...parts.map((part, index) =>\n      index % 2 === 1 ? elements[Number(part)] : part,\n    ),\n  );\n}\n\n/**\n * Languages that write a common noun with a capital letter inside a sentence,\n * so a label keeps its own first letter there.\n */\nconst capitalisedNouns = new Set([\"de\", \"gsw\", \"lb\"]);\n\n/**\n * A registry label as it reads inside a sentence (\"Change {field}\"), in\n * `locale`. A label is written to stand alone, with a capital first letter;\n * inside a sentence its first word is lowered, unless that word is an\n * acronym (\"NHS number\") or the language capitalises its nouns. Words after\n * the first keep their own letters, since they may be names.\n */\nexport function inSentence(label: string, locale: string): string {\n  const language = locale.split(\"-\", 1)[0]!.toLowerCase();\n  if (capitalisedNouns.has(language)) return label;\n  const first = /^\\S+/.exec(label)?.[0] ?? \"\";\n  const letters = first.replace(/\\P{L}/gu, \"\");\n  if (letters.length > 1 && letters === letters.toLocaleUpperCase(locale))\n    return label;\n  return first.toLocaleLowerCase(locale) + label.slice(first.length);\n}\n\n/**\n * Items read in a line, such as a value's list of choices, joined by the\n * separators `locale` writes for a plain list.\n */\nexport function listOf(items: readonly string[], locale: string): string {\n  return new Intl.ListFormat(locale, { type: \"unit\", style: \"short\" }).format(\n    items,\n  );\n}\n\n/** A plain decimal: no exponent, no leading zero, no sign but a minus. */\nconst PLAIN_DECIMAL = /^-?(?:0|[1-9]\\d*)(?:\\.(\\d+))?$/;\n\n/**\n * A number as recorded, in the locale's notation: the locale's decimal mark,\n * minus sign and digits, no grouping, and exactly the recorded fraction\n * digits, so no digit is added, dropped or rounded. A plain decimal of up to\n * 15 significant digits is one a JavaScript number holds exactly; a longer\n * one, or a text that is not a plain decimal, such as an exponent, is shown\n * as recorded.\n */\nexport function recordedNumber(value: number | string, locale: string): string {\n  const text = String(value);\n  const plain = PLAIN_DECIMAL.exec(text);\n  const digits = plain?.[1]?.length ?? 0;\n  const significant = text.replace(/\\D/g, \"\").replace(/^0+/, \"\").length;\n  if (!plain || significant > 15 || digits > 100) return text;\n  return new Intl.NumberFormat(locale, {\n    useGrouping: false,\n    minimumFractionDigits: digits,\n    maximumFractionDigits: digits,\n  }).format(Number(text));\n}\n\n/**\n * An operation name read as words, for a control no content names: separators\n * and camel-case humps become spaces and the first letter is capitalised.\n */\nexport function humanizeName(name: string): string {\n  const words = name\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .replace(/[_\\-.\\s]+/g, \" \")\n    .trim()\n    .toLowerCase();\n  return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\n/** Whether a label already names a record type, in any case. */\nexport function mentions(label: string, record: string): boolean {\n  return label.toLowerCase().includes(record.toLowerCase());\n}\n\n/**\n * A control label that names the record type it finds, so \"Record code\"\n * beside an organization reads \"Organization record code\", in `locale`. A\n * label that already names the type stays as it is.\n */\nexport function namedFor(label: string, record: string, locale: string): string {\n  if (mentions(label, record)) return label;\n  return `${record} ${inSentence(label, locale)}`;\n}\n\n/**\n * A lookup selector label that names the record type: the registry's derived\n * \"By record code\" becomes \"By organization record code\", in `locale`. A\n * label the model words is its own wording and stays as declared.\n */\nexport function selectorNamedFor(\n  selector: { label: string; derived?: true },\n  record: string,\n  locale: string,\n): string {\n  const { label } = selector;\n  const derived = selector.derived && /^By (.+)$/.exec(label);\n  if (!derived || mentions(label, record)) return label;\n  return `By ${inSentence(record, locale)} ${inSentence(derived[1]!, locale)}`;\n}\n\n/**\n * Whole calendar days from `from` to `now`, midnight to midnight. Pure number:\n * every wording that renders it lives in content. Negative when `from` is\n * in the future; null when `from` is not a readable date.\n */\nexport function relativeDays(from: string, now = new Date()): number | null {\n  const start = new Date(from);\n  if (Number.isNaN(start.valueOf())) return null;\n  const day = 86400000;\n  const fromDay = Date.UTC(\n    start.getFullYear(),\n    start.getMonth(),\n    start.getDate(),\n  );\n  const nowDay = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());\n  return Math.round((nowDay - fromDay) / day);\n}\n/**\n * The distance from `from` to `now` in the unit a list reads it in: minutes\n * within the hour, hours within the day, calendar days beyond. Pure numbers,\n * negative for the future; every wording lives in content. Null when `from`\n * is not a readable date.\n */\nexport function relativeSpan(\n  from: string,\n  now = new Date(),\n): { unit: \"minute\" | \"hour\" | \"day\"; value: number } | null {\n  const start = new Date(from);\n  if (Number.isNaN(start.valueOf())) return null;\n  const minutes = Math.trunc((now.valueOf() - start.valueOf()) / 60000);\n  if (Math.abs(minutes) < 60) return { unit: \"minute\", value: minutes };\n  const hours = Math.trunc(minutes / 60);\n  if (Math.abs(hours) < 24) return { unit: \"hour\", value: hours };\n  return { unit: \"day\", value: relativeDays(from, now) ?? 0 };\n}\n\n/**\n * A full calendar date and time, in the reader's own words, written in\n * `locale`; null when the value cannot be read as a date. Unlike a pure\n * calendar date, this reads a moment (an upload, a verification) that did\n * occur in some time zone, so it is safe to render in the browser's own.\n */\nexport function longDate(value: string, locale: string): string | null {\n  const when = new Date(value);\n  if (Number.isNaN(when.valueOf())) return null;\n  return new Intl.DateTimeFormat(locale, { dateStyle: \"long\" }).format(when);\n}\n",
      "type": "registry:lib",
      "target": "@lib/format.ts"
    }
  ],
  "type": "registry:lib"
}