{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "core-number-format",
  "type": "registry:lib",
  "title": "core/number-format",
  "description": "Framework-free behaviour shared by the ui-* components (number-format); no DOM, no lit. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/core/number-format.ts",
      "type": "registry:lib",
      "target": "components/ui/core/number-format.ts",
      "content": "/**\n * Locale-aware number formatting and parsing for `ui-number-input type=\"text\"` (Carbon NumberInput\n * `type=\"text\"` + `locale` + `formatOptions`). Formatting is `Intl.NumberFormat`; parsing reads the\n * locale's symbols from `formatToParts`, so whatever the formatter prints parses back:\n * `฿1,234.50`, `1.234,5` (de), `12 %`, `(1,000.00)` with `currencySign: 'accounting'`, `5 km`.\n *\n * Parsing also accepts what keyboards type instead of the exact symbol: `-` for the locale minus,\n * `'` for `’`, any space for a space group, and Latin, Arabic-Indic, Devanagari, Bengali, Thai,\n * full-width and Chinese digits in any locale. Pure TS (no DOM), so other renderers can share it.\n */\n\n/** The zero of each decimal digit block accepted while parsing (latn, arab, arabext, deva, beng, thai, fullwide). */\nconst DIGIT_ZEROS = [0x30, 0x660, 0x6f0, 0x966, 0x9e6, 0xe50, 0xff10];\nconst HAN_DIGITS = '〇一二三四五六七八九';\n/** Dashes people type or paste for a minus sign. */\nconst MINUS_SIGNS = /[−‒–—﹣－]/g;\n/** Parts that carry the number; everything else (currency, %, unit, literal text) is decoration. */\nconst NUMERIC_PARTS = new Set<string>(['integer', 'fraction', 'decimal', 'group', 'minusSign', 'plusSign']);\n/** Plain decimal after the symbols are swapped for ASCII. */\nconst PLAIN_NUMBER = /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i;\n/** One sample per plural form of every CLDR locale, so all spellings of a unit are known (\"1 day\", \"2 days\"). */\nconst PLURAL_SAMPLES = [0, 1, 2, 3, 4, 7, 11, 20, 21, 100, 0.1, 1.1];\n\nconst escapeRegExp = (text: string) => text.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\n/** `roundingIncrement` needs equal fraction digits (ECMA-402 SetNFDigitOptions); fill the missing one instead of throwing. */\nfunction normalizeOptions(options: Intl.NumberFormatOptions): Intl.NumberFormatOptions {\n    if (options.roundingIncrement === undefined || options.roundingIncrement === 1) return options;\n    const { minimumFractionDigits: min, maximumFractionDigits: max } = options;\n    if (min === undefined && max === undefined) return { ...options, minimumFractionDigits: 0, maximumFractionDigits: 0 };\n    if (max === undefined) return { ...options, maximumFractionDigits: min };\n    if (min === undefined) return { ...options, minimumFractionDigits: max };\n    return options;\n}\n\ninterface NumberSymbols {\n    decimal: string;\n    group: string;\n    minus: string;\n    /** Decoration to strip: currency, percent sign, unit names, literal text, white space, bidi marks. */\n    literals: RegExp;\n    /** Digit → ASCII digit for the locale's own numbering system. */\n    numerals: Map<string, string>;\n}\n\nfunction readSymbols(locale: string, resolved: Intl.ResolvedNumberFormatOptions): NumberSymbols {\n    const { style, currency, currencyDisplay, currencySign, unit, unitDisplay, numberingSystem } = resolved;\n    const base: Intl.NumberFormatOptions = { style, currency, currencyDisplay, currencySign, unit, unitDisplay, numberingSystem, useGrouping: true, maximumFractionDigits: 3 };\n    const parts = new Intl.NumberFormat(locale, { ...base, minimumFractionDigits: 1 }).formatToParts(-12345.678);\n    const find = (type: string) => parts.find((p) => p.type === type)?.value ?? '';\n    // whole samples too: \"1 day\" but \"1.0 days\"\n    const plural = new Intl.NumberFormat(locale, { ...base, minimumFractionDigits: 0 });\n    const decoration = [parts, ...[...PLURAL_SAMPLES, 12345.678].map((n) => plural.formatToParts(n))]\n        .flat()\n        .filter((p) => !NUMERIC_PARTS.has(p.type) && p.value.trim() !== '')\n        .map((p) => p.value.trim());\n    // longest first, so \"days\" goes before \"day\"\n    const alternatives = [...new Set(decoration)].sort((a, b) => b.length - a.length).map(escapeRegExp);\n    const literals = new RegExp([...alternatives, String.raw`\\p{White_Space}`, String.raw`\\p{Cf}`].join('|'), 'gu');\n    const digits = [...new Intl.NumberFormat(locale, { numberingSystem, useGrouping: false }).format(9876543210)].reverse();\n    return { decimal: find('decimal') || '.', group: find('group'), minus: find('minusSign') || '-', literals, numerals: new Map(digits.map((d, i) => [d, String(i)])) };\n}\n\n/** Any accepted digit → ASCII; other characters unchanged. */\nfunction asciiDigits(text: string, numerals: Map<string, string>): string {\n    let out = '';\n    for (const char of text) {\n        const own = numerals.get(char);\n        if (own !== undefined) {\n            out += own;\n            continue;\n        }\n        const code = char.codePointAt(0) ?? 0;\n        const zero = DIGIT_ZEROS.find((z) => code >= z && code <= z + 9);\n        const han = char === '零' ? 0 : HAN_DIGITS.indexOf(char);\n        if (zero !== undefined) out += String(code - zero);\n        else if (han >= 0) out += String(han);\n        else out += char;\n    }\n    return out;\n}\n\n/** \"12.5\" → \"0.125\" without binary rounding, by moving the exponent (\"12.5e-2\"). */\nfunction shiftPercent(plain: string): number {\n    const exponent = /^([^e]+)e([+-]?\\d+)$/i.exec(plain);\n    return exponent ? Number(`${exponent[1]}e${Number(exponent[2]) - 2}`) : Number(`${plain}e-2`);\n}\n\nexport class LocaleNumberFormat {\n    readonly locale: string;\n    private readonly formatter: Intl.NumberFormat;\n    private readonly resolved: Intl.ResolvedNumberFormatOptions;\n    private symbolCache?: NumberSymbols;\n\n    /** Throws a RangeError on an unknown locale or invalid options, as `Intl.NumberFormat` does. */\n    constructor(locale: string, options: Intl.NumberFormatOptions = {}) {\n        this.formatter = new Intl.NumberFormat(locale, normalizeOptions(options));\n        this.resolved = this.formatter.resolvedOptions();\n        this.locale = this.resolved.locale;\n    }\n\n    private get symbols(): NumberSymbols {\n        this.symbolCache ??= readSymbols(this.locale, this.resolved);\n        return this.symbolCache;\n    }\n\n    /** The display text; '' for NaN. */\n    format(value: number): string {\n        if (Number.isNaN(value)) return '';\n        return this.formatter.format(Object.is(value, -0) ? 0 : value);\n    }\n\n    /** The number in `text`, or NaN when it isn't one. A percent style gives the fraction (`50 %` → 0.5), as `format` expects. */\n    parse(text: string): number {\n        if (text.trim() === '') return Number.NaN;\n        const { decimal, group, minus, literals, numerals } = this.symbols;\n        const open = text.indexOf('(');\n        const accountingNegative = this.resolved.currencySign === 'accounting' && open >= 0 && text.indexOf(')', open) > open;\n        let plain = asciiDigits(text.replaceAll(/[()]/g, ''), numerals).replaceAll(literals, '');\n        plain = plain.replaceAll(minus, '-').replaceAll(MINUS_SIGNS, '-');\n        if (group && group.trim() !== '') {\n            const groups = group === '’' || group === \"'\" ? /['’]/g : new RegExp(escapeRegExp(group), 'g');\n            // grouping off: a group separator means the text isn't in this format\n            if (this.resolved.useGrouping === false && groups.test(plain)) return Number.NaN;\n            plain = plain.replaceAll(groups, '');\n        }\n        plain = plain.replaceAll('٬', '').replaceAll('٫', '.');\n        if (decimal !== '.') plain = plain.replaceAll(decimal, '.');\n        if (!PLAIN_NUMBER.test(plain)) return Number.NaN;\n        const value = this.resolved.style === 'percent' ? shiftPercent(plain) : Number(plain);\n        if (!Number.isFinite(value)) return Number.NaN;\n        return accountingNegative ? -Math.abs(value) : value;\n    }\n\n    /** What the display shows, as a number: `parse(format(value))`, e.g. 1.005 → 1.01 with two fraction digits. */\n    round(value: number): number {\n        return Number.isNaN(value) ? value : this.parse(this.format(value));\n    }\n}\n\nconst cache = new Map<string, LocaleNumberFormat>();\n\n/** A shared formatter per locale + options (building the symbol table runs several `formatToParts`). */\nexport function localeNumberFormat(locale: string, options: Intl.NumberFormatOptions = {}): LocaleNumberFormat {\n    const key = `${locale}|${JSON.stringify(Object.entries(options).sort(([a], [b]) => a.localeCompare(b)))}`;\n    let format = cache.get(key);\n    if (!format) {\n        format = new LocaleNumberFormat(locale, options);\n        if (cache.size > 100) cache.clear();\n        cache.set(key, format);\n    }\n    return format;\n}\n\n// ---- number input stepping (Carbon NumberInput) ----\n\n/** An HTML valid floating-point number (what `<input type=number>` accepts as its value). */\nexport const isFloatText = (text: string) => /^-?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][-+]?\\d+)?$/.test(text);\n\n/** Decimal places of a number, so 0.1 + 0.2 shows 0.3 (Carbon `getDecimalPlaces`). */\nexport function decimalsOf(n: number): number {\n    const text = String(n);\n    const dot = text.indexOf('.');\n    return dot === -1 ? 0 : text.length - dot - 1;\n}\n\nexport interface StepOptions {\n    step: number;\n    min?: number;\n    max?: number;\n    /** Where an empty field starts (Carbon `stepStartValue`); 0 = Carbon's rule. */\n    stepStartValue?: number;\n}\n\n/**\n * Carbon NumberInput stepper: `current` ± `step`, rounded to the precision of the value or the step\n * (whichever has more decimals) and clamped to min / max. From an empty field (NaN) it starts at\n * `stepStartValue`, else ±1 — or `min` when only a minimum is set (Carbon `_handleStep`).\n */\nexport function stepNumber(current: number, direction: 1 | -1, options: StepOptions): number {\n    const { step, min, max, stepStartValue = 0 } = options;\n    const empty = Number.isNaN(current);\n    let start: number = direction;\n    if (stepStartValue) start = stepStartValue;\n    else if (!max && min) start = min;\n    const raw = empty ? start : current + direction * step;\n    const rounded = Number(raw.toFixed(Math.max(empty ? 0 : decimalsOf(current), decimalsOf(step))));\n    return Math.min(Math.max(rounded, min ?? Number.NEGATIVE_INFINITY), max ?? Number.POSITIVE_INFINITY);\n}\n\n/** The steppers at the ends of the range: − is off at `min`, + at `max`. */\nexport const stepperLimits = (value: number, min?: number, max?: number) => ({ atMin: min !== undefined && value <= min, atMax: max !== undefined && value >= max });\n"
    }
  ]
}
