@gridkitjs/forms-core 0.0.0-dev-20261206092422 → 0.0.0-dev-20261206150419
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1038 -181
- package/dist/index.js +1281 -27
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/parse.ts","../src/boolean.ts","../src/localeKey.ts","../src/date/values.ts","../src/date/format.ts","../src/date/week.ts","../src/date/calendar.ts","../src/number/digits.ts","../src/date/text.ts","../src/date/layout.ts","../src/date/shortcuts.ts","../src/date/reading.ts","../src/date/zone.ts","../src/date/dateField.ts","../src/range/range.ts","../src/date/relative.ts","../src/date/dateRange.ts","../src/date/duration.ts","../src/date/period.ts","../src/date/limits.ts","../src/date/rangePick.ts","../src/date/segments.ts","../src/date/timeColumns.ts","../src/direction.ts","../src/messages/severity.ts","../src/messages/fieldMessage.ts","../src/text.ts","../src/validation/validators.ts","../src/field/state.ts","../src/field/fieldReducer.ts","../src/field/plan.ts","../src/field/createFieldController.ts","../src/field/createCompositeController.ts","../src/mask/grammar.ts","../src/mask/layout.ts","../src/mask/applyMask.ts","../src/mask/maskField.ts","../src/mask/rules.ts","../src/mask/presets.ts","../src/messages/formsMessages.ts","../src/number/decimal.ts","../src/number/options.ts","../src/number/symbols.ts","../src/number/formatNumber.ts","../src/number/reading.ts","../src/number/cleanPastedNumber.ts","../src/number/parseNumber.ts","../src/number/numberEntry.ts","../src/number/stepNumber.ts","../src/number/numberField.ts","../src/number/numberRange.ts","../src/number/rules.ts","../src/popup.ts","../src/range/rangeField.ts","../src/range/rules.ts","../src/registry.ts","../src/typeahead.ts","../src/virtualization.ts"],"sourcesContent":["import type { FormsMessages } from \"./messages/formsMessages\";\n\n/** How text reads: a value (`null` for empty), or why it cannot be read. */\nexport type ParseResult<V> =\n | { readonly kind: \"value\"; readonly value: V | null }\n | { readonly kind: \"unreadable\"; readonly message: string };\n\n/** What a parser knows beside the text. */\nexport interface ParseContext<V> {\n /** The input's own reading, to fall back on. */\n readonly defaultParse: (text: string) => ParseResult<V>;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/**\n * Reads typed text as a value. An app's parser receives the input's own in\n * its context, so it can change one case and leave the rest to it:\n *\n * ```ts\n * const parse: Parser<string> = (text, { defaultParse }) =>\n * text === \"n/a\" ? parsed(null) : defaultParse(text);\n * ```\n */\nexport type Parser<V> = (\n text: string,\n context: ParseContext<V>,\n) => ParseResult<V>;\n\n/**\n * What a value is written for: `edit` while the field has focus, `display`\n * otherwise and in display mode. A number input writes plain digits to\n * edit and grouped digits to display; a text input writes the same for both.\n */\nexport type FormatPurpose = \"display\" | \"edit\";\n\n/** What a formatter knows beside the value. */\nexport interface FormatContext<V> {\n /** The input's own formatting, to fall back on. */\n readonly defaultFormat: (value: V | null) => string;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n readonly purpose: FormatPurpose;\n}\n\n/** Writes a value as the text a field shows, `null` included. */\nexport type Formatter<V> = (\n value: V | null,\n context: FormatContext<V>,\n) => string;\n\n/** Text that reads as `value`; `null` for empty. */\nexport function parsed<V>(value: V | null): ParseResult<V> {\n return { kind: \"value\", value };\n}\n\n/** Text that cannot be read, and why, in words the user sees. */\nexport function unreadable<V>(message: string): ParseResult<V> {\n return { kind: \"unreadable\", message };\n}\n","import type { FormsMessages } from \"./messages/formsMessages\";\nimport {\n parsed,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"./parse\";\n\n/**\n * The value a checkbox takes when it is flipped. Without `threeState`,\n * `false` and `null` go to `true` and `true` to `false`, so an app's\n * `null` (a \"select all\" over a partial selection) checks on the first\n * flip. With it, `false` → `true` → `null` → `false`.\n */\nexport function nextCheckedValue(\n value: boolean | null,\n threeState: boolean,\n): boolean | null {\n if (value === true) {\n return threeState ? null : false;\n }\n return value === null && threeState ? false : true;\n}\n\n/** The words a toggle reads as: one for `true`, one for `false`. */\nexport interface BooleanWords {\n readonly on: (messages: FormsMessages) => string;\n readonly off: (messages: FormsMessages) => string;\n}\n\n/** A checkbox reads \"Yes\" or \"No\" (`displayChecked`, `displayUnchecked`). */\nexport const CHECKBOX_WORDS: BooleanWords = {\n on: (messages) => messages.displayChecked,\n off: (messages) => messages.displayUnchecked,\n};\n\n/** A switch reads \"On\" or \"Off\" (`displayOn`, `displayOff`). */\nexport const SWITCH_WORDS: BooleanWords = {\n on: (messages) => messages.displayOn,\n off: (messages) => messages.displayOff,\n};\n\n/**\n * A toggle's value as text: its words for `true` and `false`, `\"\"` for\n * `null`. The text a toggle's events carry and display mode shows.\n */\nexport function booleanFormatter(\n words: BooleanWords,\n): (value: boolean | null, context: FormatContext<boolean>) => string {\n return (value, { messages }) => {\n if (value === null) {\n return \"\";\n }\n return value ? words.on(messages) : words.off(messages);\n };\n}\n\n/** Reads a toggle's words back as its value; anything else is `null`. */\nexport function booleanParser(\n words: BooleanWords,\n): (text: string, context: ParseContext<boolean>) => ParseResult<boolean> {\n return (text, { messages }) => {\n if (text === words.on(messages)) {\n return parsed(true);\n }\n return parsed(text === words.off(messages) ? false : null);\n };\n}\n","/** `locale` as a cache key: the same text for the same locales. */\nexport function localeKey(locale: Intl.LocalesArgument): string {\n if (locale === undefined) {\n return \"\";\n }\n return typeof locale === \"string\" || locale instanceof Intl.Locale\n ? String(locale)\n : locale.map(String).join(\",\");\n}\n","// Calendar arithmetic runs on a `Date`'s UTC fields only, so the process\n// zone never enters it. Days become day numbers through `setUTCFullYear`,\n// never `Date.UTC`, which reads the years 0 to 99 as 1900 to 1999.\n\n/** A calendar day, no time, no zone: \"2026-03-14\". */\nexport type PlainDate = `${number}-${number}-${number}`;\n/** A time of day, no date, no zone: \"15:05\", \"15:05:09\", \"15:05:09.250\". */\nexport type PlainTime = `${number}:${number}` | `${number}:${number}:${number}`;\n/** A wall-clock date and time, no zone: \"2026-03-14T15:05\". */\nexport type PlainDateTime = `${PlainDate}T${PlainTime}`;\n/** An exact moment, always written in UTC: \"2026-03-14T14:05:00.000Z\". */\nexport type Instant = `${PlainDate}T${PlainTime}Z`;\n/** ISO weekday: 1 is Monday, 7 Sunday, as `Intl.Locale#getWeekInfo` numbers them. */\nexport type Weekday = 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** A day's fields: month 1 to 12, day 1 to 31. */\nexport interface DateParts {\n readonly year: number;\n readonly month: number;\n readonly day: number;\n}\n\n/** A time's fields: hour 0 to 23. */\nexport interface TimeParts {\n readonly hour: number;\n readonly minute: number;\n readonly second: number;\n readonly millisecond: number;\n}\n\nconst DAY_MS = 86_400_000;\nexport const MIN_YEAR = 1;\nexport const MAX_YEAR = 9999;\n\nconst DATE_TEXT = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst TIME_TEXT = /^(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?$/;\nconst OFFSET_TEXT = /^(?:Z|([+-])(\\d{2}):?(\\d{2}))$/i;\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\n/** Whether `year` has a 29 February in the proleptic Gregorian calendar. */\nexport function isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nconst MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n/** The days in `month` of `year`: 28 to 31. A month outside 1 to 12 counts on into the years either side. */\nexport function daysInMonth(year: number, month: number): number {\n const index = year * 12 + month - 1;\n const fullYear = Math.floor(index / 12);\n const monthIndex = index - fullYear * 12;\n const length = MONTH_LENGTHS[monthIndex] ?? 31;\n return monthIndex === 1 && isLeapYear(fullYear) ? length + 1 : length;\n}\n\nfunction isDay(year: number, month: number, day: number): boolean {\n return (\n Number.isInteger(year) &&\n Number.isInteger(month) &&\n Number.isInteger(day) &&\n year >= MIN_YEAR &&\n year <= MAX_YEAR &&\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= daysInMonth(year, month)\n );\n}\n\nfunction isTime(parts: TimeParts): boolean {\n const { hour, minute, second, millisecond } = parts;\n return (\n [hour, minute, second, millisecond].every(Number.isInteger) &&\n hour >= 0 &&\n hour <= 23 &&\n minute >= 0 &&\n minute <= 59 &&\n second >= 0 &&\n second <= 59 &&\n millisecond >= 0 &&\n millisecond <= 999\n );\n}\n\n/** The day `year-month-day`. Throws a `RangeError` for a day that does not exist or a year outside 1 to 9999. */\nexport function plainDate(year: number, month: number, day: number): PlainDate {\n if (!isDay(year, month, day)) {\n throw new RangeError(`${[year, month, day].join(\"-\")} is not a day`);\n }\n return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}` as PlainDate;\n}\n\n/**\n * The time `hour:minute`, with seconds when they or the milliseconds are\n * set, and milliseconds when set: \"15:05\", \"15:05:09\", \"15:05:09.250\".\n * Throws a `RangeError` for a time that does not exist (24:00 included).\n */\nexport function plainTime(\n hour: number,\n minute: number,\n second = 0,\n millisecond = 0,\n): PlainTime {\n if (!isTime({ hour, minute, second, millisecond })) {\n throw new RangeError(\n `${[hour, minute, second].join(\":\")} is not a time of day`,\n );\n }\n const base = `${pad(hour, 2)}:${pad(minute, 2)}`;\n if (second === 0 && millisecond === 0) {\n return base as PlainTime;\n }\n const seconds = `${base}:${pad(second, 2)}`;\n return (\n millisecond === 0 ? seconds : `${seconds}.${pad(millisecond, 3)}`\n ) as PlainTime;\n}\n\n/** `date` at `time`. */\nexport function plainDateTime(date: PlainDate, time: PlainTime): PlainDateTime {\n return `${date}T${time}`;\n}\n\nfunction datePartsOf(text: string): DateParts | null {\n const match = DATE_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const parts = {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n };\n return isDay(parts.year, parts.month, parts.day) ? parts : null;\n}\n\nfunction timePartsOf(text: string): TimeParts | null {\n const match = TIME_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const parts = {\n hour: Number(match[1]),\n minute: Number(match[2]),\n second: Number(match[3] ?? 0),\n millisecond: Number((match[4] ?? \"\").padEnd(3, \"0\").slice(0, 3)),\n };\n return isTime(parts) ? parts : null;\n}\n\n/** `text` as a day when it is one in ISO form (\"2026-03-14\"); `null` otherwise. */\nexport function toPlainDate(text: string): PlainDate | null {\n const parts = datePartsOf(text);\n return parts === null ? null : plainDate(parts.year, parts.month, parts.day);\n}\n\n/**\n * `text` as a time of day when it is one in ISO form, in its shortest\n * form (\"15:05:00\" is \"15:05\"; digits past milliseconds are dropped);\n * `null` otherwise.\n */\nexport function toPlainTime(text: string): PlainTime | null {\n const parts = timePartsOf(text);\n return parts === null\n ? null\n : plainTime(parts.hour, parts.minute, parts.second, parts.millisecond);\n}\n\n/** `text` as a wall clock when it is one in ISO form (\"2026-03-14T15:05\"), its time shortest; `null` otherwise. */\nexport function toPlainDateTime(text: string): PlainDateTime | null {\n const [date = \"\", time = \"\", ...rest] = text.split(\"T\");\n if (rest.length > 0) {\n return null;\n }\n const day = toPlainDate(date);\n const clock = toPlainTime(time);\n return day === null || clock === null ? null : plainDateTime(day, clock);\n}\n\n/**\n * `text` as an exact moment when it is an ISO date and time with `Z` or\n * an offset (`+01:00`), written as `Date#toISOString` writes it; `null`\n * otherwise.\n */\nexport function toInstant(text: string): Instant | null {\n const match = /^(.+T[\\d:.]+)(Z|[+-]\\d{2}:?\\d{2})$/i.exec(text);\n const local = match?.[1] === undefined ? null : toPlainDateTime(match[1]);\n const offset = OFFSET_TEXT.exec(match?.[2] ?? \"\");\n if (local === null || offset === null) {\n return null;\n }\n const [, sign, hours = \"0\", minutes = \"0\"] = offset;\n const offsetMs =\n (sign === \"-\" ? -1 : 1) * (Number(hours) * 60 + Number(minutes)) * 60_000;\n const epoch = epochOfWallClock(local) - offsetMs;\n return inYears(epoch) ? instantFromEpoch(epoch) : null;\n}\n\n/** Whether the moment `epoch` falls in the years 1 to 9999, in UTC. */\nfunction inYears(epoch: number): boolean {\n const year = new Date(epoch).getUTCFullYear();\n return year >= MIN_YEAR && year <= MAX_YEAR;\n}\n\n/** Whether `value` is a day in canonical form. */\nexport function isPlainDate(value: unknown): value is PlainDate {\n return typeof value === \"string\" && toPlainDate(value) === value;\n}\n\n/** Whether `value` is a time of day in canonical (shortest) form. */\nexport function isPlainTime(value: unknown): value is PlainTime {\n return typeof value === \"string\" && toPlainTime(value) === value;\n}\n\n/** Whether `value` is a wall clock in canonical form. */\nexport function isPlainDateTime(value: unknown): value is PlainDateTime {\n return typeof value === \"string\" && toPlainDateTime(value) === value;\n}\n\n/** Whether `value` is an exact moment in canonical form. */\nexport function isInstant(value: unknown): value is Instant {\n return typeof value === \"string\" && toInstant(value) === value;\n}\n\n/** A day's fields. Throws a `RangeError` for text that is not a day. */\nexport function dateParts(date: PlainDate): DateParts {\n const parts = datePartsOf(date);\n if (parts === null) {\n throw new RangeError(`${date} is not a day`);\n }\n return parts;\n}\n\n/** A time's fields. Throws a `RangeError` for text that is not a time of day. */\nexport function timeParts(time: PlainTime): TimeParts {\n const parts = timePartsOf(time);\n if (parts === null) {\n throw new RangeError(`${time} is not a time of day`);\n }\n return parts;\n}\n\n/** A wall clock's day and time. */\nexport function splitDateTime(dateTime: PlainDateTime): {\n readonly date: PlainDate;\n readonly time: PlainTime;\n} {\n const [date = \"\", time = \"\"] = dateTime.split(\"T\");\n return { date: date as PlainDate, time: time as PlainTime };\n}\n\n// Day numbers use Howard Hinnant's `days_from_civil` and `civil_from_days`\n// (public domain, \"chrono-Compatible Low-Level Date Algorithms\", the\n// algorithms behind C++20 <chrono>): whole numbers only, exact in the\n// proleptic Gregorian calendar, counted in 400-year eras of 146 097 days\n// that start on 1 March, with 719 468 the day number of 0000-03-01 from\n// 1970-01-01. `Math.floor` keeps the division right for negative eras.\nconst DAYS_PER_ERA = 146_097;\nconst EPOCH_SHIFT = 719_468;\n\n/**\n * Days since 1970-01-01 for a day's fields, any year. A month outside 1\n * to 12 counts on into the years either side, and a day outside the\n * month into the months either side, as `Date` would.\n */\nexport function dayNumberOf(year: number, month: number, day: number): number {\n const index = year * 12 + month - 1;\n const monthIndex = index - Math.floor(index / 12) * 12;\n // The year from 1 March, so 29 February ends it.\n const marchYear = Math.floor(index / 12) - (monthIndex < 2 ? 1 : 0);\n const era = Math.floor(marchYear / 400);\n const yearOfEra = marchYear - era * 400;\n const marchMonth = monthIndex < 2 ? monthIndex + 10 : monthIndex - 2;\n const dayOfYear = Math.floor((153 * marchMonth + 2) / 5) + day - 1;\n const dayOfEra =\n yearOfEra * 365 +\n Math.floor(yearOfEra / 4) -\n Math.floor(yearOfEra / 100) +\n dayOfYear;\n return era * DAYS_PER_ERA + dayOfEra - EPOCH_SHIFT;\n}\n\n/** A day's fields for `dayNumber` days after 1970-01-01, any year. */\nfunction fieldsOfDayNumber(dayNumber: number): DateParts {\n const shifted = Math.floor(dayNumber) + EPOCH_SHIFT;\n const era = Math.floor(shifted / DAYS_PER_ERA);\n const dayOfEra = shifted - era * DAYS_PER_ERA;\n const yearOfEra = Math.floor(\n (dayOfEra -\n Math.floor(dayOfEra / 1460) +\n Math.floor(dayOfEra / 36_524) -\n Math.floor(dayOfEra / 146_096)) /\n 365,\n );\n const dayOfYear =\n dayOfEra -\n (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));\n const marchMonth = Math.floor((5 * dayOfYear + 2) / 153);\n const month = marchMonth < 10 ? marchMonth + 3 : marchMonth - 9;\n return {\n year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0),\n month,\n day: dayOfYear - Math.floor((153 * marchMonth + 2) / 5) + 1,\n };\n}\n\n/** The day `dayNumber` days after 1970-01-01. Throws a `RangeError` outside the years 1 to 9999. */\nexport function dateOfDayNumber(dayNumber: number): PlainDate {\n const { year, month, day } = fieldsOfDayNumber(dayNumber);\n return plainDate(year, month, day);\n}\n\nfunction dayNumber(date: PlainDate): number {\n const { year, month, day } = dateParts(date);\n return dayNumberOf(year, month, day);\n}\n\n/** `days` days after `date` (before, when negative). */\nexport function addDays(date: PlainDate, days: number): PlainDate {\n return dateOfDayNumber(dayNumber(date) + days);\n}\n\n/** `months` months after `date`, the day clamped to the month's length: 31 January plus a month is the last day of February. */\nexport function addMonths(date: PlainDate, months: number): PlainDate {\n const { year, month, day } = dateParts(date);\n const index = year * 12 + (month - 1) + months;\n const nextYear = Math.floor(index / 12);\n const nextMonth = index - nextYear * 12 + 1;\n return plainDate(\n nextYear,\n nextMonth,\n Math.min(day, daysInMonth(nextYear, nextMonth)),\n );\n}\n\n/** `years` years after `date`; 29 February becomes 28 February in a year that has none. */\nexport function addYears(date: PlainDate, years: number): PlainDate {\n return addMonths(date, years * 12);\n}\n\n/** Days from `start` to `end`: negative when `end` comes first. */\nexport function daysBetween(start: PlainDate, end: PlainDate): number {\n return dayNumber(end) - dayNumber(start);\n}\n\n/** The ISO weekday of `date`: 1 for Monday to 7 for Sunday. */\nexport function dayOfWeek(date: PlainDate): Weekday {\n // Day 0, 1970-01-01, was a Thursday (4). Adding 10 (3, then a week)\n // keeps the remainder of a day before 1970 from going negative.\n return ((((dayNumber(date) % 7) + 10) % 7) + 1) as Weekday;\n}\n\n/** The first day of `date`'s month. */\nexport function startOfMonth(date: PlainDate): PlainDate {\n const { year, month } = dateParts(date);\n return plainDate(year, month, 1);\n}\n\n/** The last day of `date`'s month. */\nexport function endOfMonth(date: PlainDate): PlainDate {\n const { year, month } = dateParts(date);\n return plainDate(year, month, daysInMonth(year, month));\n}\n\n/** Negative when `a` comes first, 0 for the same day, positive after. */\nexport function compareDates(a: PlainDate, b: PlainDate): number {\n return dayNumber(a) - dayNumber(b);\n}\n\n/** Milliseconds into the day. */\nfunction millisecondsOfDay(time: PlainTime): number {\n const { hour, minute, second, millisecond } = timeParts(time);\n return ((hour * 60 + minute) * 60 + second) * 1000 + millisecond;\n}\n\n/** Minutes into the day, seconds as a fraction: \"01:30\" is 90. */\nexport function minutesOfDay(time: PlainTime): number {\n return millisecondsOfDay(time) / 60_000;\n}\n\n/** Negative when `a` comes first in the day, 0 for the same time, positive after. */\nexport function compareTimes(a: PlainTime, b: PlainTime): number {\n return millisecondsOfDay(a) - millisecondsOfDay(b);\n}\n\n/** Milliseconds since the epoch of `dateTime` read as if it were UTC. */\nexport function epochOfWallClock(dateTime: PlainDateTime): number {\n const { date, time } = splitDateTime(dateTime);\n return dayNumber(date) * DAY_MS + millisecondsOfDay(time);\n}\n\n/** The wall clock `epoch` milliseconds since the epoch shows in UTC. */\nexport function wallClockOfEpoch(epoch: number): PlainDateTime {\n const date = new Date(epoch);\n return plainDateTime(\n plainDate(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()),\n plainTime(\n date.getUTCHours(),\n date.getUTCMinutes(),\n date.getUTCSeconds(),\n date.getUTCMilliseconds(),\n ),\n );\n}\n\n/** Negative when `a` comes first, 0 for the same wall clock, positive after. */\nexport function compareDateTimes(a: PlainDateTime, b: PlainDateTime): number {\n return epochOfWallClock(a) - epochOfWallClock(b);\n}\n\n/** Milliseconds since the epoch. */\nexport function epochOfInstant(instant: Instant): number {\n return Date.parse(instant);\n}\n\n/** The moment `epoch` milliseconds since the epoch. Throws a `RangeError` outside the years 1 to 9999. */\nexport function instantFromEpoch(epoch: number): Instant {\n if (!inYears(epoch)) {\n throw new RangeError(`${String(epoch)} is outside the years 1 to 9999`);\n }\n return new Date(epoch).toISOString() as Instant;\n}\n\n/** Negative when `a` comes first, 0 for the same moment, positive after. */\nexport function compareInstants(a: Instant, b: Instant): number {\n return epochOfInstant(a) - epochOfInstant(b);\n}\n\n/**\n * `date` as a `Date` at local midnight, as the grid reads a `yyyy-mm-dd`\n * cell, where `new Date(\"2026-03-01\")` would be midnight in UTC: the day\n * before west of UTC.\n */\nexport function dateFromPlainDate(date: PlainDate): Date {\n const { year, month, day } = dateParts(date);\n const local = new Date(0);\n local.setFullYear(year, month - 1, day);\n local.setHours(0, 0, 0, 0);\n return local;\n}\n\n/** `dateTime` as a `Date` at that local wall clock. */\nexport function dateFromPlainDateTime(dateTime: PlainDateTime): Date {\n const { date, time } = splitDateTime(dateTime);\n const local = dateFromPlainDate(date);\n const { hour, minute, second, millisecond } = timeParts(time);\n local.setHours(hour, minute, second, millisecond);\n return local;\n}\n\n/** The local day of a `Date`, as the grid writes a date cell. */\nexport function plainDateFromDate(date: Date): PlainDate {\n return plainDate(date.getFullYear(), date.getMonth() + 1, date.getDate());\n}\n\n/** `instant` as a `Date`: exact. */\nexport function dateFromInstant(instant: Instant): Date {\n return new Date(epochOfInstant(instant));\n}\n\n/** A `Date` as an exact moment. */\nexport function instantFromDate(date: Date): Instant {\n return instantFromEpoch(date.getTime());\n}\n","import { localeKey } from \"../localeKey\";\nimport {\n epochOfInstant,\n epochOfWallClock,\n plainDateTime,\n timeParts,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\n\n// Wall clocks are formatted as the UTC moment of the same wall clock, with\n// `timeZone: \"UTC\"`, so the process zone never shifts the text; an instant\n// is formatted in the zone its input names. Every format passes\n// `calendar: \"gregory\"`: the forms read the Gregorian calendar only.\n\n/** Formatters already built, by locale and options. */\nconst formats = new Map<string, Intl.DateTimeFormat>();\n\n/** A Gregorian `Intl.DateTimeFormat` for `locale` and `options`, cached. */\nexport function dateTimeFormat(\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key = `${localeKey(locale)}|${JSON.stringify(options)}`;\n let format = formats.get(key);\n if (format === undefined) {\n format = new Intl.DateTimeFormat(locale, {\n ...options,\n calendar: \"gregory\",\n });\n formats.set(key, format);\n }\n return format;\n}\n\nconst DATE_STYLE: Intl.DateTimeFormatOptions = { dateStyle: \"medium\" };\n\n/** `timeStyle: \"short\"`, or `\"medium\"` when `time` has seconds. */\nfunction timeStyleFor(time: PlainTime): Intl.DateTimeFormatOptions {\n const { second, millisecond } = timeParts(time);\n return { timeStyle: second === 0 && millisecond === 0 ? \"short\" : \"medium\" };\n}\n\n/** `options` for a wall clock: the caller's, written in UTC. */\nfunction inUtc(\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormatOptions {\n return { ...options, timeZone: \"UTC\" };\n}\n\n/** A day as display mode writes it: `dateStyle: \"medium\"` unless `options` say otherwise (\"Mar 14, 2026\", \"14.03.2026\"). */\nexport function formatDate(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions = DATE_STYLE,\n): string {\n return dateTimeFormat(locale, inUtc(options)).format(\n epochOfWallClock(plainDateTime(date, \"00:00\")),\n );\n}\n\n/** A time of day as display mode writes it: `timeStyle: \"short\"`, `\"medium\"` with seconds, unless `options` say otherwise. */\nexport function formatTime(\n time: PlainTime,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions = timeStyleFor(time),\n): string {\n return dateTimeFormat(locale, inUtc(options)).format(\n epochOfWallClock(plainDateTime(\"1970-01-01\", time)),\n );\n}\n\n/** A wall clock as display mode writes it: the date and time styles together unless `options` say otherwise. */\nexport function formatDateTime(\n dateTime: PlainDateTime,\n locale: Intl.LocalesArgument,\n options?: Intl.DateTimeFormatOptions,\n): string {\n const time = dateTime.slice(11) as PlainTime;\n return dateTimeFormat(\n locale,\n inUtc(options ?? { ...DATE_STYLE, ...timeStyleFor(time) }),\n ).format(epochOfWallClock(dateTime));\n}\n\n/** A moment as display mode writes it in `timeZone`, as `formatDateTime` writes its wall clock. */\nexport function formatInstant(\n instant: Instant,\n timeZone: string,\n locale: Intl.LocalesArgument,\n options?: Intl.DateTimeFormatOptions,\n): string {\n const time = instant.slice(11, -1) as PlainTime;\n return dateTimeFormat(locale, {\n ...(options ?? { ...DATE_STYLE, ...timeStyleFor(time) }),\n timeZone,\n }).format(epochOfInstant(instant));\n}\n","import {\n addDays,\n dateParts,\n dayOfWeek,\n daysBetween,\n plainDate,\n type PlainDate,\n type Weekday,\n} from \"./values\";\n\n/** The day a week starts on in a locale, and its weekend days. */\nexport interface WeekInfo {\n readonly firstDay: Weekday;\n readonly weekend: readonly Weekday[];\n}\n\n/**\n * How weeks are numbered: `\"iso\"`, weeks from Monday with week 1 holding\n * the year's first Thursday (ISO 8601); `\"simple\"`, weeks from the first\n * day of week with week 1 holding 1 January (US practice).\n */\nexport type WeekNumbering = \"iso\" | \"simple\";\n\n/** A week of a year: `{ year: 2026, week: 11 }` is 2026-W11. */\nexport interface WeekOfYear {\n readonly year: number;\n readonly week: number;\n}\n\n/** What weekInfo reads from an `Intl.Locale`: the method, the getter some engines shipped before it, or the region. */\nexport interface WeekInfoSource {\n readonly getWeekInfo?: (() => Partial<WeekInfo>) | undefined;\n readonly weekInfo?: Partial<WeekInfo> | undefined;\n readonly maximize: () => { readonly region?: string | undefined };\n}\n\n// CLDR's first day of week by region, for an engine without week info.\nconst SUNDAY_FIRST = new Set(\n \"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW\".split(\n \" \",\n ),\n);\nconst SATURDAY_FIRST = new Set(\n \"AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY\".split(\" \"),\n);\n// CLDR's weekends that are not Saturday and Sunday.\nconst FRIDAY_SATURDAY = new Set(\n \"AE BH DZ EG IL IQ JO KW LY OM QA SA SD SY YE\".split(\" \"),\n);\nconst OTHER_WEEKENDS: Readonly<Record<string, readonly Weekday[]>> = {\n AF: [4, 5],\n IR: [5],\n IN: [7],\n UG: [7],\n};\n\nfunction isWeekday(day: unknown): day is Weekday {\n return (\n typeof day === \"number\" && Number.isInteger(day) && day >= 1 && day <= 7\n );\n}\n\n/** Week info from the region alone, CLDR's data for an engine that has none. */\nfunction regionWeekInfo(region: string | undefined): WeekInfo {\n const code = region ?? \"\";\n const firstDay: Weekday = SUNDAY_FIRST.has(code)\n ? 7\n : SATURDAY_FIRST.has(code)\n ? 6\n : 1;\n const weekend: readonly Weekday[] =\n OTHER_WEEKENDS[code] ?? (FRIDAY_SATURDAY.has(code) ? [5, 6] : [6, 7]);\n return { firstDay, weekend };\n}\n\n/**\n * Week info from `source`: `getWeekInfo()`, else the `weekInfo` getter,\n * else the table by region (`maximize().region`).\n */\nexport function weekInfoOf(source: WeekInfoSource): WeekInfo {\n const info = source.getWeekInfo?.() ?? source.weekInfo;\n if (info !== undefined && isWeekday(info.firstDay)) {\n const weekend = (info.weekend ?? []).filter(isWeekday);\n return { firstDay: info.firstDay, weekend };\n }\n return regionWeekInfo(source.maximize().region);\n}\n\n/** Week info already read, by locale. */\nconst weekInfos = new Map<string, WeekInfo>();\n\n/**\n * The first day of week and the weekend in `locale`: Sunday in `en-US`,\n * Monday in `de-DE`, Saturday in `ar-EG`. Read from\n * `Intl.Locale#getWeekInfo`, else the getter some engines shipped before\n * it, else CLDR's table by region. A field's `firstDayOfWeek` overrides\n * it.\n */\nexport function weekInfo(locale: Intl.LocalesArgument): WeekInfo {\n const tag = new Intl.DateTimeFormat(locale).resolvedOptions().locale;\n let info = weekInfos.get(tag);\n if (info === undefined) {\n info = weekInfoOf(new Intl.Locale(tag));\n weekInfos.set(tag, info);\n }\n return info;\n}\n\n/**\n * The numbering a field uses unless told: `\"iso\"` when weeks start on\n * Monday, `\"simple\"` otherwise. `Intl` no longer reports a locale's\n * minimal days in the first week, so the numbering cannot come from it.\n */\nexport function defaultWeekNumbering(firstDay: Weekday): WeekNumbering {\n return firstDay === 1 ? \"iso\" : \"simple\";\n}\n\n/** The first day of the week `date` falls in, weeks starting on `firstDay`. */\nexport function startOfWeek(date: PlainDate, firstDay: Weekday): PlainDate {\n return addDays(date, -((dayOfWeek(date) - firstDay + 7) % 7));\n}\n\n/**\n * The week `date` falls in. ISO: weeks from Monday, the week belonging to\n * the year of its Thursday (`firstDay` is ignored). Simple: weeks from\n * `firstDay`, the week belonging to the year of its last day, week 1\n * holding 1 January. Days in the first or last week of the years 1 and\n * 9999 may have no week to count from and throw a `RangeError`.\n */\nexport function weekOf(\n date: PlainDate,\n numbering: WeekNumbering,\n firstDay: Weekday,\n): WeekOfYear {\n if (numbering === \"iso\") {\n const thursday = addDays(date, 4 - dayOfWeek(date));\n const { year } = dateParts(thursday);\n const week =\n Math.floor(daysBetween(plainDate(year, 1, 1), thursday) / 7) + 1;\n return { year, week };\n }\n const start = startOfWeek(date, firstDay);\n const { year } = dateParts(addDays(start, 6));\n const first = startOfWeek(plainDate(year, 1, 1), firstDay);\n return { year, week: daysBetween(first, start) / 7 + 1 };\n}\n","import { dateTimeFormat } from \"./format\";\nimport {\n defaultWeekNumbering,\n startOfWeek,\n weekOf,\n type WeekNumbering,\n type WeekOfYear,\n} from \"./week\";\nimport {\n addDays,\n compareDates,\n dateOfDayNumber,\n dateParts,\n dayNumberOf,\n dayOfWeek,\n daysInMonth,\n epochOfWallClock,\n MAX_YEAR,\n MIN_YEAR,\n plainDate,\n plainDateTime,\n type PlainDate,\n type Weekday,\n} from \"./values\";\n\n/** One day in a month grid. */\nexport interface CalendarDay {\n readonly date: PlainDate;\n readonly weekday: Weekday;\n /** False for the days of the months before and after that fill the first and last weeks. */\n readonly inMonth: boolean;\n}\n\n/** One row of a month grid: seven days and the week they make. */\nexport interface CalendarWeek {\n readonly week: WeekOfYear;\n readonly days: readonly CalendarDay[];\n}\n\n/** A month laid out for a calendar. */\nexport interface MonthGrid {\n readonly year: number;\n readonly month: number;\n /** The weekdays in column order, `firstDayOfWeek` first. */\n readonly weekdays: readonly Weekday[];\n /** Always six, so a calendar's height never changes from month to month. */\n readonly weeks: readonly CalendarWeek[];\n}\n\nexport interface MonthGridOptions {\n readonly firstDayOfWeek: Weekday;\n /** By default `\"iso\"` when weeks start on Monday, `\"simple\"` otherwise. */\n readonly weekNumbering?: WeekNumbering | undefined;\n}\n\n/**\n * `month` of `year` as six weeks of days from `firstDayOfWeek`, with the\n * days of the months either side filling the first and last weeks, and\n * each week's number. A row's number is its fourth day's week, which is\n * the week most of its days belong to even when the numbering's weeks\n * start on another day (ISO weeks in a Sunday-first grid). Throws a\n * `RangeError` for a month whose six weeks reach before 0001-01-01 or\n * after 9999-12-31.\n */\nexport function monthGrid(\n year: number,\n month: number,\n options: MonthGridOptions,\n): MonthGrid {\n const { firstDayOfWeek } = options;\n const numbering =\n options.weekNumbering ?? defaultWeekNumbering(firstDayOfWeek);\n const first = startOfWeek(plainDate(year, month, 1), firstDayOfWeek);\n const weeks = Array.from({ length: 6 }, (_, row): CalendarWeek => {\n const days = Array.from({ length: 7 }, (_, column): CalendarDay => {\n const date = addDays(first, row * 7 + column);\n const parts = dateParts(date);\n return {\n date,\n weekday: dayOfWeek(date),\n inMonth: parts.year === year && parts.month === month,\n };\n });\n const middle = days[3]?.date ?? first;\n return { week: weekOf(middle, numbering, firstDayOfWeek), days };\n });\n const weekdays = Array.from(\n { length: 7 },\n (_, column) => (((firstDayOfWeek - 1 + column) % 7) + 1) as Weekday,\n );\n return { year, month, weekdays, weeks };\n}\n\n/** A month a calendar shows, as `yyyy-mm`: \"2026-03\". */\nexport type CalendarMonth = `${number}-${number}`;\n\nconst MONTH_TEXT = /^(\\d{4})-(\\d{2})$/;\n\n// A month's six weeks reach into the months either side, so a calendar\n// shows no month before February of the year 1 or after November of 9999:\n// its grid never leaves the days a PlainDate holds.\nconst FIRST_MONTH = monthIndexOf(MIN_YEAR, 2);\nconst LAST_MONTH = monthIndexOf(MAX_YEAR, 11);\nconst FIRST_DAY = dayNumberOf(MIN_YEAR, 2, 1);\nconst LAST_DAY = dayNumberOf(MAX_YEAR, 11, 30);\n\n/** Months since the start of the year 0, so months add as numbers. */\nfunction monthIndexOf(year: number, month: number): number {\n return year * 12 + month - 1;\n}\n\nfunction monthIndex(month: CalendarMonth): number {\n const parts = calendarMonthParts(month);\n return monthIndexOf(parts.year, parts.month);\n}\n\nfunction monthAt(index: number): CalendarMonth {\n const year = Math.floor(index / 12);\n return calendarMonth(year, index - year * 12 + 1);\n}\n\nfunction dayNumber(date: PlainDate): number {\n const { year, month, day } = dateParts(date);\n return dayNumberOf(year, month, day);\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(Math.max(value, low), high);\n}\n\n/** Whether `value` is a month as a calendar holds one: \"2026-03\", years 1 to 9999. */\nexport function isCalendarMonth(value: unknown): value is CalendarMonth {\n if (typeof value !== \"string\") {\n return false;\n }\n const match = MONTH_TEXT.exec(value);\n const year = Number(match?.[1]);\n const month = Number(match?.[2]);\n return year >= MIN_YEAR && year <= MAX_YEAR && month >= 1 && month <= 12;\n}\n\n/** The month `month` (1 to 12) of `year`. Throws a `RangeError` for a month that does not exist. */\nexport function calendarMonth(year: number, month: number): CalendarMonth {\n const text = `${String(year).padStart(4, \"0\")}-${String(month).padStart(2, \"0\")}`;\n if (!Number.isInteger(year) || !isCalendarMonth(text)) {\n throw new RangeError(`${String(year)}-${String(month)} is not a month`);\n }\n return text;\n}\n\n/** A month's year and its number, 1 to 12. */\nexport function calendarMonthParts(month: CalendarMonth): {\n readonly year: number;\n readonly month: number;\n} {\n return { year: Number(month.slice(0, -3)), month: Number(month.slice(-2)) };\n}\n\n/** The month `date` falls in. */\nexport function monthOfDate(date: PlainDate): CalendarMonth {\n return date.slice(0, 7) as CalendarMonth;\n}\n\n/** Negative when `a` comes first, 0 for the same month, positive after. */\nexport function compareCalendarMonths(\n a: CalendarMonth,\n b: CalendarMonth,\n): number {\n return monthIndex(a) - monthIndex(b);\n}\n\n/** The days a calendar lets a user reach and choose. */\nexport interface CalendarLimits {\n /** The first day that can be chosen, inclusive. */\n readonly min?: PlainDate | undefined;\n /** The last day that can be chosen, inclusive. */\n readonly max?: PlainDate | undefined;\n /** Days that show but cannot be chosen. */\n readonly isDateDisabled?: ((date: PlainDate) => boolean) | undefined;\n}\n\n/** The first and last days focus can reach, as day numbers: the calendar's reach within `min` and `max`. */\nfunction dayReach(limits: CalendarLimits): {\n readonly first: number;\n readonly last: number;\n} {\n const first = Math.max(\n FIRST_DAY,\n limits.min === undefined ? FIRST_DAY : dayNumber(limits.min),\n );\n const last = Math.min(\n LAST_DAY,\n limits.max === undefined ? LAST_DAY : dayNumber(limits.max),\n );\n return { first: Math.min(first, LAST_DAY), last: Math.max(first, last) };\n}\n\n/** The first and last months that hold a day focus can reach, as month indexes. */\nfunction monthReach(limits: CalendarLimits): {\n readonly first: number;\n readonly last: number;\n} {\n const { first, last } = dayReach(limits);\n return {\n first: monthIndex(monthOfDate(dateOfDayNumber(first))),\n last: monthIndex(monthOfDate(dateOfDayNumber(last))),\n };\n}\n\n/**\n * Whether a calendar shows `date` as one that cannot be chosen: before\n * `min`, after `max`, marked by `isDateDisabled`, or outside the months a\n * calendar shows (before February of the year 1, after November of 9999).\n */\nexport function isCalendarDayDisabled(\n date: PlainDate,\n limits: CalendarLimits,\n): boolean {\n const day = dayNumber(date);\n return (\n day < FIRST_DAY ||\n day > LAST_DAY ||\n (limits.min !== undefined && compareDates(date, limits.min) < 0) ||\n (limits.max !== undefined && compareDates(date, limits.max) > 0) ||\n limits.isDateDisabled?.(date) === true\n );\n}\n\n/** Whether month `month` of `year` holds no day within the calendar's limits, so its month view disables it. */\nexport function isCalendarMonthDisabled(\n year: number,\n month: number,\n limits: CalendarLimits,\n): boolean {\n const { first, last } = monthReach(limits);\n const index = monthIndexOf(year, month);\n return index < first || index > last;\n}\n\n/**\n * `month` moved where a calendar showing `visibleMonths` months from it\n * can be: no earlier than the month of `min`, and its last month no later\n * than the month of `max`, nor than November of 9999.\n */\nexport function clampCalendarMonth(\n month: CalendarMonth,\n limits: CalendarLimits,\n visibleMonths = 1,\n): CalendarMonth {\n return clampMonthIndex(monthIndex(month), limits, visibleMonths);\n}\n\n/** `clampCalendarMonth` for a month index, which may lie outside the years a month holds. */\nfunction clampMonthIndex(\n index: number,\n limits: CalendarLimits,\n visibleMonths: number,\n): CalendarMonth {\n const { first, last } = monthReach(limits);\n const lastStart = Math.min(\n Math.max(first, last - (visibleMonths - 1)),\n LAST_MONTH - (visibleMonths - 1),\n );\n return monthAt(clamp(index, Math.min(first, lastStart), lastStart));\n}\n\n/** `date` moved into the days focus can reach. */\nexport function clampCalendarDate(\n date: PlainDate,\n limits: CalendarLimits,\n): PlainDate {\n const { first, last } = dayReach(limits);\n return dateOfDayNumber(clamp(dayNumber(date), first, last));\n}\n\n/** `date`'s day of the month in `month`, clamped to the month's length: the 31st in February is the 28th or 29th. */\nexport function sameDayIn(month: CalendarMonth, date: PlainDate): PlainDate {\n const parts = calendarMonthParts(month);\n const { day } = dateParts(date);\n return plainDate(\n parts.year,\n parts.month,\n Math.min(day, daysInMonth(parts.year, parts.month)),\n );\n}\n\n/** The years a calendar's month view lists: from `min` to `max`, else 100 either side of `year`. */\nexport function calendarYears(\n year: number,\n limits: CalendarLimits,\n): { readonly first: number; readonly last: number } {\n const { first, last } = monthReach(limits);\n const firstYear = Math.floor(first / 12);\n const lastYear = Math.floor(last / 12);\n return {\n first:\n limits.min === undefined ? Math.max(firstYear, year - 100) : firstYear,\n last: limits.max === undefined ? Math.min(lastYear, year + 100) : lastYear,\n };\n}\n\n/** Where a key moves focus in a calendar's grid. */\nexport type CalendarMove =\n | \"previousDay\"\n | \"nextDay\"\n | \"previousWeek\"\n | \"nextWeek\"\n | \"startOfWeek\"\n | \"endOfWeek\"\n | \"previousMonth\"\n | \"nextMonth\"\n | \"previousYear\"\n | \"nextYear\";\n\n/**\n * The day `move` takes focus to from `date`, weeks starting on\n * `firstDayOfWeek`: a day or a week on, the week's first or last day, or\n * the same day of the month or year before or after (clamped to the\n * month's length). Clamped to the days focus can reach, so at the edge a\n * key does nothing.\n */\nexport function moveCalendarDate(\n date: PlainDate,\n move: CalendarMove,\n firstDayOfWeek: Weekday,\n limits: CalendarLimits,\n): PlainDate {\n const day = dayNumber(date);\n const { year, month, day: dayOfMonth } = dateParts(date);\n const sameDayMonthsOn = (months: number): number => {\n const index = monthIndexOf(year, month) + months;\n const nextYear = Math.floor(index / 12);\n const nextMonth = index - nextYear * 12 + 1;\n return dayNumberOf(\n nextYear,\n nextMonth,\n Math.min(dayOfMonth, daysInMonth(nextYear, nextMonth)),\n );\n };\n const intoWeek = (dayOfWeek(date) - firstDayOfWeek + 7) % 7;\n const targets: Readonly<Record<CalendarMove, () => number>> = {\n previousDay: () => day - 1,\n nextDay: () => day + 1,\n previousWeek: () => day - 7,\n nextWeek: () => day + 7,\n startOfWeek: () => day - intoWeek,\n endOfWeek: () => day + 6 - intoWeek,\n previousMonth: () => sameDayMonthsOn(-1),\n nextMonth: () => sameDayMonthsOn(1),\n previousYear: () => sameDayMonthsOn(-12),\n nextYear: () => sameDayMonthsOn(12),\n };\n const { first, last } = dayReach(limits);\n return dateOfDayNumber(clamp(targets[move](), first, last));\n}\n\n/** What a calendar's panel shows: the days of its months, or its months and years to jump to. */\nexport type CalendarView =\n | { readonly kind: \"days\" }\n | {\n readonly kind: \"months\";\n /** The year whose months show. */\n readonly year: number;\n /** Which of the months shown the jump replaces, 0 for the first. */\n readonly panel: number;\n };\n\n/** Where a calendar is: the months it shows, the day focus is on, its view. */\nexport interface CalendarState {\n /** The first month shown. */\n readonly month: CalendarMonth;\n /** The day that takes focus in the grid: always in a month shown. */\n readonly focused: PlainDate;\n readonly view: CalendarView;\n}\n\n/** What the calendar reducer is told. */\nexport interface CalendarContext {\n readonly firstDayOfWeek: Weekday;\n /** How many months show side by side. */\n readonly visibleMonths: number;\n readonly limits: CalendarLimits;\n}\n\n/** What can happen to a calendar. */\nexport type CalendarAction =\n /** A key moved focus in the grid. */\n | { readonly type: \"move\"; readonly move: CalendarMove }\n /** A day took focus: a click, or a day of another month chosen. */\n | { readonly type: \"focus\"; readonly date: PlainDate }\n /** The previous or next month button: the months shown move by `months`. */\n | { readonly type: \"page\"; readonly months: number }\n /** The app's `month`: shown first. */\n | { readonly type: \"show\"; readonly month: CalendarMonth }\n /** A month's title: the month view opens in its place. */\n | { readonly type: \"openMonths\"; readonly panel: number }\n /** A year chosen in the month view. */\n | { readonly type: \"showYear\"; readonly year: number }\n /** A month (1 to 12) of the view's year chosen: the days show again, from it. */\n | { readonly type: \"chooseMonth\"; readonly month: number }\n /** Escape in the month view: the days show again, unchanged. */\n | { readonly type: \"closeMonths\" };\n\nconst DAYS: CalendarView = { kind: \"days\" };\n\n/** `focused` with the first month moved, as little as it takes, for `focused` to be shown. */\nfunction reveal(\n month: CalendarMonth,\n focused: PlainDate,\n context: CalendarContext,\n): Pick<CalendarState, \"month\" | \"focused\"> {\n const start = monthIndex(month);\n const index = monthIndex(monthOfDate(focused));\n const visible = context.visibleMonths;\n const first =\n index < start\n ? index\n : index > start + visible - 1\n ? index - visible + 1\n : start;\n return {\n month: clampMonthIndex(first, context.limits, visible),\n focused,\n };\n}\n\n/** Whether `date` falls in one of the months shown from `month`. */\nfunction isShown(\n date: PlainDate,\n month: CalendarMonth,\n visibleMonths: number,\n): boolean {\n const offset = monthIndex(monthOfDate(date)) - monthIndex(month);\n return offset >= 0 && offset < visibleMonths;\n}\n\n/**\n * Where a calendar starts: showing `month` (the app's), else the month of\n * `focus`, with focus on `focus` when it is shown, else on its day of the\n * month in the first month shown.\n */\nexport function calendarStart(\n focus: PlainDate,\n month: CalendarMonth | undefined,\n context: CalendarContext,\n): CalendarState {\n const { limits, visibleMonths } = context;\n const target = clampCalendarDate(focus, limits);\n const first = clampCalendarMonth(\n month ?? monthOfDate(target),\n limits,\n visibleMonths,\n );\n const focused = isShown(target, first, visibleMonths)\n ? target\n : clampCalendarDate(sameDayIn(first, target), limits);\n return { ...reveal(first, focused, context), view: DAYS };\n}\n\n/**\n * The calendar after `action`: every way focus moves between days and\n * months, and the month view opens and closes. Focus stays on a day in a\n * month shown and within the limits; the months shown move as little as\n * it takes.\n */\nexport function calendarReducer(\n state: CalendarState,\n action: CalendarAction,\n context: CalendarContext,\n): CalendarState {\n const { limits, firstDayOfWeek, visibleMonths } = context;\n switch (action.type) {\n case \"move\": {\n const focused = moveCalendarDate(\n state.focused,\n action.move,\n firstDayOfWeek,\n limits,\n );\n return { ...state, ...reveal(state.month, focused, context) };\n }\n case \"focus\":\n return {\n ...state,\n ...reveal(state.month, clampCalendarDate(action.date, limits), context),\n };\n case \"page\": {\n const month = clampMonthIndex(\n monthIndex(state.month) + action.months,\n limits,\n visibleMonths,\n );\n const panel =\n monthIndex(monthOfDate(state.focused)) - monthIndex(state.month);\n const focused = clampCalendarDate(\n sameDayIn(monthAt(monthIndex(month) + panel), state.focused),\n limits,\n );\n return { ...state, ...reveal(month, focused, context) };\n }\n case \"show\": {\n const month = clampCalendarMonth(action.month, limits, visibleMonths);\n const focused = isShown(state.focused, month, visibleMonths)\n ? state.focused\n : clampCalendarDate(sameDayIn(month, state.focused), limits);\n return { ...state, ...reveal(month, focused, context) };\n }\n case \"openMonths\": {\n const panel = clamp(action.panel, 0, visibleMonths - 1);\n const { year } = calendarMonthParts(\n monthAt(monthIndex(state.month) + panel),\n );\n return { ...state, view: { kind: \"months\", year, panel } };\n }\n case \"showYear\":\n return state.view.kind === \"months\"\n ? {\n ...state,\n view: {\n ...state.view,\n year: clamp(action.year, MIN_YEAR, MAX_YEAR),\n },\n }\n : state;\n case \"chooseMonth\": {\n if (state.view.kind !== \"months\") {\n return state;\n }\n const { year, panel } = state.view;\n const chosen = monthAt(\n clamp(monthIndexOf(year, action.month), FIRST_MONTH, LAST_MONTH),\n );\n const month = clampMonthIndex(\n monthIndex(chosen) - panel,\n limits,\n visibleMonths,\n );\n const focused = clampCalendarDate(\n sameDayIn(chosen, state.focused),\n limits,\n );\n return { ...reveal(month, focused, context), view: DAYS };\n }\n case \"closeMonths\":\n return state.view.kind === \"days\" ? state : { ...state, view: DAYS };\n }\n}\n\n/** A wall clock's day at midnight, as `Intl` formats it in UTC. */\nfunction formatDay(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions,\n): string {\n return dateTimeFormat(locale, { ...options, timeZone: \"UTC\" }).format(\n epochOfWallClock(plainDateTime(date, \"00:00\")),\n );\n}\n\n// A Monday, so weekday `n` is `n - 1` days after it.\nconst A_MONDAY: PlainDate = \"2026-03-09\";\n\n/** A month as a calendar's title writes it: \"March 2026\", \"März 2026\". */\nexport function formatCalendarMonth(\n month: CalendarMonth,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(sameDayIn(month, \"2026-01-01\"), locale, {\n month: \"long\",\n year: \"numeric\",\n });\n}\n\n/** A month's name alone: \"Mar\", \"March\". */\nexport function formatMonthName(\n month: number,\n locale: Intl.LocalesArgument,\n width: \"short\" | \"long\",\n): string {\n return formatDay(plainDate(2026, month, 1), locale, { month: width });\n}\n\n/** A weekday's name: \"M\", \"Mon\", \"Monday\". */\nexport function formatWeekday(\n weekday: Weekday,\n locale: Intl.LocalesArgument,\n width: \"narrow\" | \"short\" | \"long\",\n): string {\n return formatDay(addDays(A_MONDAY, weekday - 1), locale, {\n weekday: width,\n });\n}\n\n/** A day of the month as a calendar's cell writes it, in the locale's digits: \"14\". */\nexport function formatDayOfMonth(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(date, locale, { day: \"numeric\" });\n}\n\n/** A year as a calendar's year list writes it, in the locale's digits. */\nexport function formatCalendarYear(\n year: number,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(plainDate(year, 6, 1), locale, { year: \"numeric\" });\n}\n","const DIGIT = /^\\p{Nd}$/u;\n\n/** Whether `char` is one Unicode decimal digit, in any script. */\nexport function isDigit(char: string): boolean {\n return DIGIT.test(char);\n}\n\nfunction isDigitCode(code: number): boolean {\n return code >= 0 && isDigit(String.fromCodePoint(code));\n}\n\n/**\n * The value of the decimal digit `char`. Unicode keeps every decimal digit\n * in a run of ten from zero to nine, and runs that touch (the mathematical\n * digits) follow on from each other, so the value is the digit's distance\n * from the start of its run, modulo 10: no table needed.\n */\nexport function digitValue(char: string): number {\n const code = char.codePointAt(0) ?? 0;\n let start = code;\n while (isDigitCode(start - 1)) {\n start -= 1;\n }\n return (code - start) % 10;\n}\n\n/** Intl's numbering systems by the code point of their zero, built on first use. */\nlet systemsByZero: ReadonlyMap<number, string> | undefined;\n\nfunction numberingSystems(): ReadonlyMap<number, string> {\n if (systemsByZero === undefined) {\n const systems = new Map<number, string>();\n for (const system of Intl.supportedValuesOf(\"numberingSystem\")) {\n const format = new Intl.NumberFormat(\"en\", { numberingSystem: system });\n const zero = format.format(0);\n // An engine without the system falls back to Latin digits.\n if (\n format.resolvedOptions().numberingSystem === system &&\n isDigit(zero)\n ) {\n systems.set(zero.codePointAt(0) ?? 0, system);\n }\n }\n systemsByZero = systems;\n }\n return systemsByZero;\n}\n\n/** The Intl numbering system of the digit `char` (`\"latn\"`, `\"arab\"`, `\"fullwide\"`), or `\"unknown\"`. */\nexport function numberingSystemOf(char: string): string {\n const zero = (char.codePointAt(0) ?? 0) - digitValue(char);\n return numberingSystems().get(zero) ?? \"unknown\";\n}\n","import { digitValue, isDigit } from \"../number/digits\";\n\nconst BIDI_MARKS = /[\\u{200E}\\u{200F}\\u{061C}\\u{2066}-\\u{2069}]/gu;\nconst SPACES = /[\\u{00A0}\\u{2007}\\u{2009}\\u{202F}\\u{3000}]/gu;\nconst FULL_WIDTH = /[\\u{FF01}-\\u{FF5E}]/gu;\n\n/** `text` with every decimal digit, in any script, written as ASCII. */\nexport function asciiDigits(text: string): string {\n let result = \"\";\n for (const char of text) {\n result += isDigit(char) ? String(digitValue(char)) : char;\n }\n return result;\n}\n\n/**\n * `text` as the date readers take it: trimmed, direction marks dropped,\n * no-break, narrow and thin spaces as plain spaces, full-width forms\n * (which Chinese and Japanese input methods type) as ASCII, and every\n * digit as ASCII.\n */\nexport function cleanDateText(text: string): string {\n return asciiDigits(\n text\n .replace(BIDI_MARKS, \"\")\n .replace(SPACES, \" \")\n .replace(FULL_WIDTH, (char) =>\n String.fromCharCode(char.charCodeAt(0) - 0xfee0),\n ),\n ).trim();\n}\n\n/** `text` lower-cased with its accents removed and a trailing dot dropped, for matching words. */\nexport function foldWord(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .toLocaleLowerCase(\"en\")\n .replace(/\\.$/, \"\");\n}\n","import { localeKey } from \"../localeKey\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { digitValue, isDigit } from \"../number/digits\";\nimport { dateTimeFormat } from \"./format\";\nimport { foldWord } from \"./text\";\n\n/** A segment of a date, time or date-time field. */\nexport type DateSegmentType =\n \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"dayPeriod\";\n\n/** Any segment a field types in: a date's, or a period's quarter or fiscal period. */\nexport type SegmentType = DateSegmentType | \"quarter\" | \"period\";\n\n/** One segment of a layout. */\nexport interface DateSegment {\n readonly type: SegmentType;\n /** The lowest and highest value it takes: month 1 to 12, hour 1 to 12 in a 12-hour cycle, 0 and 1 for the day period. */\n readonly min: number;\n readonly max: number;\n /** Characters it is shown with once left: 2 for \"03\", 1 for \"3\", 4 for a year. */\n readonly width: number;\n /** Shown while empty: \"mm\", \"dd\", \"yyyy\", \"--\" (messages). */\n readonly placeholder: string;\n /** Read with the field's label: \"month\" (messages). */\n readonly label: string;\n}\n\n/** One part of a layout: a segment (by its index in `segments`), or text drawn between them. */\nexport type DateLayoutPart =\n | { readonly kind: \"segment\"; readonly index: number }\n | { readonly kind: \"literal\"; readonly text: string };\n\n/** How a field lays out its segments in a locale. */\nexport interface DateLayout {\n /** In the order `Intl.DateTimeFormat#formatToParts` gives them. */\n readonly parts: readonly DateLayoutPart[];\n /** The segments alone, in typing order. */\n readonly segments: readonly DateSegment[];\n readonly hourCycle: \"h11\" | \"h12\" | \"h23\" | \"h24\" | null;\n /** The locale's two day-period texts, morning first (\"AM\", \"PM\"). */\n readonly dayPeriods: readonly [string, string];\n /** The ten digits the locale writes, \"0\" to \"9\" first. */\n readonly digits: string;\n}\n\n/** What a field's layout is made for. */\nexport type DateLayoutFields = \"date\" | \"time\" | \"dateTime\" | \"month\" | \"year\";\n\nexport interface DateLayoutOptions {\n readonly locale: Intl.LocalesArgument;\n readonly fields: DateLayoutFields;\n /** The locale's hour cycle unless given. */\n readonly hourCycle?: \"h12\" | \"h23\" | undefined;\n /** `\"minute\"` by default; `\"second\"` adds a seconds segment. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n}\n\n/** A layout before its segments are named by the messages. */\nexport interface LayoutShape {\n readonly parts: readonly (\n | { readonly kind: \"segment\"; readonly type: SegmentType }\n | { readonly kind: \"literal\"; readonly text: string }\n )[];\n readonly widths: Partial<Record<SegmentType, number>>;\n readonly hourCycle: DateLayout[\"hourCycle\"];\n readonly dayPeriods: readonly [string, string];\n readonly digits: string;\n}\n\nconst SEGMENT_TYPES: ReadonlySet<string> = new Set<SegmentType>([\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\nfunction isSegmentType(type: string): type is DateSegmentType {\n return SEGMENT_TYPES.has(type);\n}\n\n/** 14 March 2026, 15:05:09, the moment a layout is read from. */\nconst SAMPLE = Date.UTC(2026, 2, 14, 15, 5, 9);\n/** 2 January 2026, 03:04:05: one-digit values, to see which segments pad. */\nconst SHORT_SAMPLE = Date.UTC(2026, 0, 2, 3, 4, 5);\nconst MORNING = Date.UTC(2026, 0, 2, 3);\n\nfunction intlOptions(options: DateLayoutOptions): Intl.DateTimeFormatOptions {\n const date: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n };\n const time: Intl.DateTimeFormatOptions = {\n hour: \"numeric\",\n minute: \"2-digit\",\n ...(options.precision === \"second\" ? { second: \"2-digit\" } : {}),\n ...(options.hourCycle === undefined\n ? {}\n : { hourCycle: options.hourCycle }),\n };\n const fields: Record<DateLayoutFields, Intl.DateTimeFormatOptions> = {\n date,\n time,\n dateTime: { ...date, ...time },\n month: { year: \"numeric\", month: \"2-digit\" },\n year: { year: \"numeric\" },\n };\n return {\n ...fields[options.fields],\n timeZone: \"UTC\",\n ...(options.numberingSystem === undefined\n ? {}\n : { numberingSystem: options.numberingSystem }),\n };\n}\n\n/** The ten digits of `numberingSystem`, \"0\" to \"9\". */\nfunction digitsOf(numberingSystem: string): string {\n const format = new Intl.NumberFormat(\"en\", {\n numberingSystem,\n useGrouping: false,\n });\n return Array.from({ length: 10 }, (_, digit) => format.format(digit)).join(\n \"\",\n );\n}\n\n/** The day-period texts `locale` writes beside a 12-hour hour. */\nfunction dayPeriodsOf(\n locale: Intl.LocalesArgument,\n numberingSystem: string,\n): readonly [string, string] {\n const format = dateTimeFormat(locale, {\n hour: \"numeric\",\n hourCycle: \"h12\",\n timeZone: \"UTC\",\n numberingSystem,\n });\n const text = (moment: number) =>\n format.formatToParts(moment).find((part) => part.type === \"dayPeriod\")\n ?.value ?? \"\";\n return [text(MORNING) || \"AM\", text(SAMPLE) || \"PM\"];\n}\n\nfunction readShape(options: DateLayoutOptions): LayoutShape {\n const format = dateTimeFormat(options.locale, intlOptions(options));\n const resolved = format.resolvedOptions();\n const parts: LayoutShape[\"parts\"][number][] = [];\n for (const part of format.formatToParts(SAMPLE)) {\n if (part.type === \"literal\") {\n const last = parts.at(-1);\n if (last?.kind === \"literal\") {\n parts[parts.length - 1] = {\n kind: \"literal\",\n text: last.text + part.value,\n };\n } else {\n parts.push({ kind: \"literal\", text: part.value });\n }\n } else if (isSegmentType(part.type)) {\n parts.push({ kind: \"segment\", type: part.type });\n }\n }\n const widths: Partial<Record<SegmentType, number>> = {};\n for (const part of format.formatToParts(SHORT_SAMPLE)) {\n if (isSegmentType(part.type)) {\n widths[part.type] = part.value.length;\n }\n }\n return {\n parts,\n widths,\n hourCycle: resolved.hourCycle ?? null,\n dayPeriods: dayPeriodsOf(options.locale, resolved.numberingSystem),\n digits: digitsOf(resolved.numberingSystem),\n };\n}\n\n/** The range a segment of `type` takes in a layout with `hourCycle`. */\nfunction rangeOf(\n type: SegmentType,\n hourCycle: DateLayout[\"hourCycle\"],\n): readonly [number, number] {\n switch (type) {\n case \"year\":\n return [1, 9999];\n case \"month\":\n case \"period\":\n return [1, 12];\n case \"day\":\n return [1, 31];\n case \"quarter\":\n return [1, 4];\n case \"dayPeriod\":\n return [0, 1];\n case \"minute\":\n case \"second\":\n return [0, 59];\n case \"hour\":\n switch (hourCycle) {\n case \"h11\":\n return [0, 11];\n case \"h12\":\n return [1, 12];\n case \"h24\":\n return [1, 24];\n default:\n return [0, 23];\n }\n }\n}\n\n/** Names a shape's segments from `messages`, making the layout. */\nexport function layoutOf(\n shape: LayoutShape,\n messages: FormsMessages,\n): DateLayout {\n const segments: DateSegment[] = [];\n const parts = shape.parts.map((part): DateLayoutPart => {\n if (part.kind === \"literal\") {\n return part;\n }\n const [min, max] = rangeOf(part.type, shape.hourCycle);\n const width =\n part.type === \"year\"\n ? 4\n : part.type === \"dayPeriod\"\n ? Math.max(...shape.dayPeriods.map((text) => text.length))\n : Math.max(shape.widths[part.type] ?? 2, 1);\n segments.push({\n type: part.type,\n min,\n max,\n width,\n placeholder: messages.dateSegmentPlaceholder(part.type),\n label: messages.dateSegmentName(part.type),\n });\n return { kind: \"segment\", index: segments.length - 1 };\n });\n return {\n parts,\n segments,\n hourCycle: shape.hourCycle,\n dayPeriods: shape.dayPeriods,\n digits: shape.digits,\n };\n}\n\n/** Shapes already read, by locale and options: reading one builds several formatters. */\nconst shapes = new Map<string, LayoutShape>();\n/** Layouts already named, per messages object. */\nconst layouts = new WeakMap<FormsMessages, Map<string, DateLayout>>();\n\n/**\n * How a field lays out its segments in a locale, read from\n * `Intl.DateTimeFormat#formatToParts` for a sample moment (14 March 2026,\n * 15:05:09): each year, month, day, hour, minute, second or day-period\n * part becomes a segment, each literal the text drawn between them, in\n * the order the engine gives. Whether a segment pads is read from a second\n * sample with one-digit values, so `en-US` hours stay unpadded (\"3:05 PM\").\n * Nothing is written per locale: each engine shows its own. Gregorian\n * only. Cached per locale, options and messages.\n */\nexport function dateLayout(\n options: DateLayoutOptions,\n messages: FormsMessages,\n): DateLayout {\n const key = [\n localeKey(options.locale),\n options.fields,\n options.hourCycle ?? \"\",\n options.precision ?? \"\",\n options.numberingSystem ?? \"\",\n ].join(\"|\");\n let named = layouts.get(messages);\n if (named === undefined) {\n named = new Map();\n layouts.set(messages, named);\n }\n let layout = named.get(key);\n if (layout === undefined) {\n let shape = shapes.get(key);\n if (shape === undefined) {\n shape = readShape(options);\n shapes.set(key, shape);\n }\n layout = layoutOf(shape, messages);\n named.set(key, layout);\n }\n return layout;\n}\n\n/** The index of the first segment of `type`, or -1. */\nexport function segmentIndex(layout: DateLayout, type: SegmentType): number {\n return layout.segments.findIndex((segment) => segment.type === type);\n}\n\n/** `value` written in the layout's digits, padded to `width`. */\nexport function writeDigits(\n layout: DateLayout,\n value: number,\n width: number,\n): string {\n return String(value)\n .padStart(width, \"0\")\n .replace(/\\d/g, (digit) => layout.digits[Number(digit)] ?? digit);\n}\n\n/**\n * Segment `index` written for `value`: digits in the layout's digits,\n * padded to the segment's width; a day period's text for 0 or 1.\n */\nexport function writeSegment(\n layout: DateLayout,\n index: number,\n value: number,\n): string {\n const segment = layout.segments[index];\n if (segment === undefined) {\n return \"\";\n }\n return segment.type === \"dayPeriod\"\n ? layout.dayPeriods[value === 0 ? 0 : 1]\n : writeDigits(layout, value, segment.width);\n}\n\n/** The day period `text` names: 0 for the morning, 1 for the afternoon; the locale's texts or `a`, `am`, `p`, `pm`. */\nexport function dayPeriodOf(layout: DateLayout, text: string): 0 | 1 | null {\n const folded = foldWord(text).replace(/\\./g, \"\");\n const [morning, afternoon] = layout.dayPeriods.map((period) =>\n foldWord(period).replace(/\\./g, \"\"),\n );\n if (folded === \"\") {\n return null;\n }\n if (folded === morning || folded === \"am\" || folded === \"a\") {\n return 0;\n }\n if (folded === afternoon || folded === \"pm\" || folded === \"p\") {\n return 1;\n }\n return null;\n}\n\n/** The number segment `index`'s text holds, digits in any script; `null` while empty or for text that is not its value. */\nexport function segmentValue(\n layout: DateLayout,\n index: number,\n text: string,\n): number | null {\n const segment = layout.segments[index];\n if (segment === undefined || text === \"\") {\n return null;\n }\n if (segment.type === \"dayPeriod\") {\n return dayPeriodOf(layout, text);\n }\n let value = 0;\n for (const char of text) {\n if (!isDigit(char)) {\n return null;\n }\n value = value * 10 + digitValue(char);\n }\n return value;\n}\n\n/** How many digits segment `index` takes at most: 4 for a year, 2 for a month. */\nexport function maxDigits(layout: DateLayout, index: number): number {\n const segment = layout.segments[index];\n return segment === undefined ? 0 : String(segment.max).length;\n}\n\n/**\n * The field's text for these segment texts: joined by the layout's\n * literals, an empty segment written as nothing (\"03//2026\"), and `\"\"`\n * when every segment is empty.\n */\nexport function joinSegments(\n layout: DateLayout,\n texts: readonly string[],\n): string {\n if (texts.every((text) => text === \"\")) {\n return \"\";\n }\n return layout.parts\n .map((part) =>\n part.kind === \"literal\" ? part.text : (texts[part.index] ?? \"\"),\n )\n .join(\"\");\n}\n\n/** An hour of the day (0 to 23) as an hour segment in `hourCycle` shows it: 15 is 3 in a 12-hour cycle. */\nexport function shownHour(\n hour: number,\n hourCycle: DateLayout[\"hourCycle\"],\n): number {\n switch (hourCycle) {\n case \"h12\":\n return hour % 12 === 0 ? 12 : hour % 12;\n case \"h11\":\n return hour % 12;\n case \"h24\":\n return hour === 0 ? 24 : hour;\n default:\n return hour;\n }\n}\n\n/** The field's text for each segment type's number: written and joined; a segment with no number stays empty. */\nexport function formatSegments(\n layout: DateLayout,\n values: Partial<Record<SegmentType, number>>,\n): string {\n return joinSegments(\n layout,\n layout.segments.map((segment, index) => {\n const value = values[segment.type];\n return value === undefined ? \"\" : writeSegment(layout, index, value);\n }),\n );\n}\n\n/** The length of the segment text at `position` in `text`, or -1 when none fits. */\nfunction segmentLength(\n layout: DateLayout,\n index: number,\n text: string,\n position: number,\n): number {\n const segment = layout.segments[index];\n if (segment?.type === \"dayPeriod\") {\n const match = layout.dayPeriods\n .filter(\n (period) =>\n foldWord(text.slice(position, position + period.length)) ===\n foldWord(period),\n )\n .sort((a, b) => b.length - a.length)[0];\n return match?.length ?? 0;\n }\n let length = 0;\n for (const char of text.slice(position)) {\n if (!isDigit(char)) {\n break;\n }\n length += char.length;\n }\n return length <= maxDigits(layout, index) ? length : -1;\n}\n\n/**\n * Each segment's text in the field's text, or `null` for text that is\n * not segments (free text: a shortcut, a pasted date in another form).\n * `\"\"` is every segment empty.\n */\nexport function splitSegments(\n layout: DateLayout,\n text: string,\n): readonly string[] | null {\n const texts = layout.segments.map(() => \"\");\n if (text === \"\") {\n return texts;\n }\n let position = 0;\n for (const part of layout.parts) {\n if (part.kind === \"literal\") {\n if (!text.startsWith(part.text, position)) {\n return null;\n }\n position += part.text.length;\n continue;\n }\n const length = segmentLength(layout, part.index, text, position);\n if (length < 0) {\n return null;\n }\n texts[part.index] = text.slice(position, position + length);\n position += length;\n }\n return position === text.length ? texts : null;\n}\n\n/** Where each segment's text sits in the field's text, as `[start, end)`; `null` for text that is not segments. */\nexport function segmentSpans(\n layout: DateLayout,\n text: string,\n): readonly (readonly [number, number])[] | null {\n const texts = splitSegments(layout, text);\n if (texts === null) {\n return null;\n }\n const spans: (readonly [number, number])[] = [];\n let position = 0;\n for (const part of layout.parts) {\n if (part.kind === \"literal\") {\n position += text === \"\" ? 0 : part.text.length;\n } else {\n const length = texts[part.index]?.length ?? 0;\n spans[part.index] = [position, position + length];\n position += length;\n }\n }\n return spans;\n}\n\n/** A stretch of a layout's parts drawn together. */\nexport interface SegmentRun {\n /** Indexes into the layout's `parts`, in order. */\n readonly parts: readonly number[];\n /** Whether the renderer wraps it in `dir=\"ltr\"`: a run of several number segments in a right-to-left field. */\n readonly leftToRight: boolean;\n}\n\nconst RIGHT_TO_LEFT =\n /[\\u{0590}-\\u{08FF}\\u{FB1D}-\\u{FDFF}\\u{FE70}-\\u{FEFF}\\u{200F}\\u{061C}]/u;\n\n/**\n * The layout's parts grouped into runs for a field written in\n * `direction`. A right-to-left field cannot simply reverse its segments:\n * `he-IL` and `fa-IR` write a date left to right even in right-to-left\n * text (digits and `.` or `/` form one number run under the Unicode bidi\n * rules), while `ar-EG` leads each `/` with a right-to-left mark, so its\n * date runs right to left. So consecutive number segments joined by\n * literals with no right-to-left character or mark form one run, read\n * left to right; a literal with one, or a right-to-left day period,\n * breaks it. Every other part is a run of its own. A left-to-right field\n * is one run.\n */\nexport function segmentRuns(\n layout: DateLayout,\n direction: \"ltr\" | \"rtl\",\n): readonly SegmentRun[] {\n const all = layout.parts.map((_, index) => index);\n if (direction === \"ltr\") {\n return [{ parts: all, leftToRight: false }];\n }\n const joins = (index: number): boolean => {\n const part = layout.parts[index];\n if (part === undefined) {\n return false;\n }\n if (part.kind === \"literal\") {\n return !RIGHT_TO_LEFT.test(part.text);\n }\n return (\n layout.segments[part.index]?.type !== \"dayPeriod\" ||\n !layout.dayPeriods.some((period) => RIGHT_TO_LEFT.test(period))\n );\n };\n const isSegment = (index: number) => layout.parts[index]?.kind === \"segment\";\n const runs: SegmentRun[] = [];\n let index = 0;\n while (index < all.length) {\n if (!isSegment(index) || !joins(index)) {\n runs.push({ parts: [index], leftToRight: false });\n index += 1;\n continue;\n }\n // Extend over joining parts, ending on the last joining segment.\n let end = index;\n for (let next = index + 1; next < all.length && joins(next); next += 1) {\n if (isSegment(next)) {\n end = next;\n }\n }\n const parts = all.slice(index, end + 1);\n runs.push({\n parts,\n leftToRight: parts.filter(isSegment).length > 1,\n });\n index = end + 1;\n }\n return runs;\n}\n","import { cleanDateText } from \"./text\";\nimport {\n addDays,\n addMonths,\n addYears,\n endOfMonth,\n startOfMonth,\n type PlainDate,\n} from \"./values\";\n\n// shortcut := \"t\" | anchor | offset [anchor]\n// offset := sign digits [unit] sign: +, - or U+2212; unit: d (default) w m y\n// anchor := \"s\" | \"e\" start or end of the month\nconst SHORTCUT = /^(?:(t)|([se])|([+\\-\\u{2212}])(\\d+)([dwmy])?([se])?)$/iu;\n\n/** `date` moved `count` units (`d`, `w`, `m` or `y`) on, back when `count` is negative. */\nfunction offset(date: PlainDate, count: number, unit: string): PlainDate {\n switch (unit) {\n case \"w\":\n return addDays(date, count * 7);\n case \"m\":\n return addMonths(date, count);\n case \"y\":\n return addYears(date, count);\n default:\n return addDays(date, count);\n }\n}\n\nfunction anchored(date: PlainDate, anchor: string | undefined): PlainDate {\n if (anchor === undefined) {\n return date;\n }\n return anchor === \"s\" ? startOfMonth(date) : endOfMonth(date);\n}\n\n/**\n * The day a typed shortcut names, always counted from `today`, never from\n * the field's value: `t` today; `+3` or `+3d` three days on, `-1w` a week\n * back, `+2m` and `-1y` months and years (clamped to the month's length);\n * `s` and `e` the start and end of this month; an offset then an anchor,\n * `+1ms` the start of next month, `-1me` the end of last. Case-insensitive,\n * digits in any script. `null` for anything else, or a day past the years\n * 1 to 9999.\n */\nexport function readDateShortcut(\n text: string,\n today: PlainDate,\n): PlainDate | null {\n const match = SHORTCUT.exec(cleanDateText(text).toLowerCase());\n if (match === null) {\n return null;\n }\n const [, todayKey, anchor, sign, digits, unit = \"d\", offsetAnchor] = match;\n if (todayKey !== undefined) {\n return today;\n }\n if (anchor !== undefined) {\n return anchored(today, anchor);\n }\n const count = Number(digits) * (sign === \"+\" ? 1 : -1);\n try {\n return anchored(offset(today, count, unit), offsetAnchor);\n } catch {\n return null;\n }\n}\n","import { localeKey } from \"../localeKey\";\nimport { dateTimeFormat } from \"./format\";\nimport {\n dayPeriodOf,\n segmentIndex,\n segmentValue,\n splitSegments,\n type DateLayout,\n type SegmentType,\n} from \"./layout\";\nimport { readDateShortcut } from \"./shortcuts\";\nimport { cleanDateText, foldWord } from \"./text\";\nimport {\n dateParts,\n daysInMonth,\n plainDate,\n plainTime,\n type PlainDate,\n type PlainTime,\n} from \"./values\";\n\n/** How a text was read as a date or time. */\nexport type DateReadingInfo =\n | { readonly kind: \"segments\" }\n | { readonly kind: \"iso\" }\n | {\n readonly kind: \"numeric\";\n /** The order the numbers were read in: `\"mdy\"`, `\"dmy\"`, `\"ymd\"`. */\n readonly order: string;\n /** A one- or two-digit year took its century from the pivot. */\n readonly pivotedYear: boolean;\n }\n | { readonly kind: \"monthName\"; readonly pivotedYear: boolean }\n | { readonly kind: \"shortcut\"; readonly shortcut: string }\n /** A time of day from pasted or free text: \"3:05 PM\", \"1505\". */\n | { readonly kind: \"time\" };\n\n/** Why a text cannot be read as a date or time. */\nexport type DateUnreadableReason =\n | \"dateIncomplete\"\n | \"timeIncomplete\"\n | \"nonexistent\"\n | \"yearDigits\"\n | \"unreadable\";\n\n/**\n * What a text reads as, before a field makes its value from it: nothing;\n * a day and a time of day (either may be absent), with the offset a\n * pasted ISO text named; or why it cannot be read.\n */\nexport type DateTextReading =\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"read\";\n readonly date: PlainDate | null;\n readonly time: PlainTime | null;\n /** Minutes east of UTC a pasted text gave (\"Z\", \"+01:00\"); `null` without one. */\n readonly offset: number | null;\n readonly info: DateReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: DateUnreadableReason };\n\n/** What the two-digit year pivot is told. */\nexport interface PivotOptions {\n /** Its year is the current year. */\n readonly today: PlainDate;\n /** A year after `max`'s takes the century before. */\n readonly max?: PlainDate | null | undefined;\n /** A year before `min`'s takes the century after. */\n readonly min?: PlainDate | null | undefined;\n}\n\n/** What the readers need to know about the field. */\nexport interface DateReadOptions extends PivotOptions {\n /** What the field holds: a day, a time of day, or both. */\n readonly fields: \"date\" | \"time\" | \"dateTime\";\n /** The field's layout: its order and day periods. */\n readonly layout: DateLayout;\n /** For month and weekday names; English names are read too. */\n readonly locale: Intl.LocalesArgument;\n /** Whether `t`, `+3` and the rest read. */\n readonly shortcuts: boolean;\n /**\n * The segment the user is typing in, if any: a short year there is\n * still being typed, so it reads as incomplete rather than pivoted.\n */\n readonly activeSegment?: number | null | undefined;\n}\n\nconst EMPTY: DateTextReading = { kind: \"empty\" };\n\nfunction unreadableBecause(reason: DateUnreadableReason): DateTextReading {\n return { kind: \"unreadable\", reason };\n}\n\nfunction read(\n date: PlainDate | null,\n time: PlainTime | null,\n info: DateReadingInfo,\n offset: number | null = null,\n): DateTextReading {\n return { kind: \"read\", date, time, offset, info };\n}\n\n/**\n * The year ending in `digits` (one or two digits) within the hundred\n * years from 80 before the current year (ICU's rule): in 2026, 26 is 2026,\n * 45 is 2045, 46 is 1946. A year after `max`'s takes the century before,\n * one before `min`'s the century after, so a birthday field whose `max`\n * is today reads 36 as 1936.\n */\nexport function pivotYear(digits: number, options: PivotOptions): number {\n const current = dateParts(options.today).year;\n const start = current - 80;\n let year = start + ((((digits - start) % 100) + 100) % 100);\n if (options.max != null && year > dateParts(options.max).year) {\n year -= 100;\n } else if (options.min != null && year < dateParts(options.min).year) {\n year += 100;\n }\n return year;\n}\n\n/** A year typed with `length` digits: four as written, one or two pivoted; `null` for three or more than four. */\nfunction yearOf(\n value: number,\n length: number,\n options: PivotOptions,\n): { readonly year: number; readonly pivoted: boolean } | null {\n if (length === 4) {\n return { year: value, pivoted: false };\n }\n return length === 1 || length === 2\n ? { year: pivotYear(value, options), pivoted: true }\n : null;\n}\n\n/** A day from its numbers: the day, or why there is none. */\nfunction dayReading(\n year: number,\n month: number,\n day: number,\n info: DateReadingInfo,\n): DateTextReading {\n if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) {\n return unreadableBecause(\"unreadable\");\n }\n return day > daysInMonth(year, month)\n ? unreadableBecause(\"nonexistent\")\n : read(plainDate(year, month, day), null, info);\n}\n\n/** The hour of the day for a 12-hour cycle's hour and its day period, or another cycle's hour; `null` out of range. */\nfunction hourOfDay(\n hour: number,\n dayPeriod: 0 | 1 | null,\n hourCycle: DateLayout[\"hourCycle\"],\n): number | null {\n if (dayPeriod !== null) {\n const twelve = hourCycle === \"h11\" ? hour : hour === 12 ? 0 : hour;\n return twelve >= 0 && twelve <= 11 ? twelve + dayPeriod * 12 : null;\n }\n if (hourCycle === \"h24\") {\n return hour >= 1 && hour <= 24 ? hour % 24 : null;\n }\n return hour >= 0 && hour <= 23 ? hour : null;\n}\n\nconst TIME_TYPES: ReadonlySet<SegmentType> = new Set<SegmentType>([\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\n/** The order of the layout's date segments, as `\"mdy\"`; `\"ymd\"` without them. */\nexport function dateOrder(layout: DateLayout): string {\n const order = layout.segments\n .map((segment) => segment.type)\n .filter((type) => type === \"year\" || type === \"month\" || type === \"day\")\n .map((type) => type.charAt(0))\n .join(\"\");\n return order.length === 3 ? order : \"ymd\";\n}\n\n/**\n * Segment texts read strictly, as the field holds them while typed:\n * every segment empty is nothing; a date with an empty segment, or a year\n * still being typed (`activeSegment`), is incomplete; a year left with one\n * or two digits is pivoted, with three it is refused; a day the month does\n * not have does not exist; a 12-hour time without its day period is\n * incomplete. A date-time whose time segments are all empty reads with no\n * time, which the field fills with its default.\n */\nexport function readDateSegments(\n texts: readonly string[],\n options: DateReadOptions,\n): DateTextReading {\n const { layout } = options;\n if (texts.every((text) => text === \"\")) {\n return EMPTY;\n }\n const value = (type: SegmentType): number | null => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const filled = (index: number) => (texts[index] ?? \"\") !== \"\";\n const indexes = layout.segments.map((_, index) => index);\n const dateIndexes = indexes.filter(\n (index) => !TIME_TYPES.has(layout.segments[index]?.type ?? \"hour\"),\n );\n const timeIndexes = indexes.filter((index) => !dateIndexes.includes(index));\n\n let date: PlainDate | null = null;\n let info: DateReadingInfo = { kind: \"segments\" };\n if (dateIndexes.length > 0) {\n const yearIndex = segmentIndex(layout, \"year\");\n const yearLength = (texts[yearIndex] ?? \"\").length;\n if (\n !dateIndexes.every(filled) ||\n (options.activeSegment === yearIndex && yearLength < 4)\n ) {\n return unreadableBecause(\"dateIncomplete\");\n }\n const year = yearOf(value(\"year\") ?? 0, yearLength, options);\n if (year === null) {\n return unreadableBecause(\"yearDigits\");\n }\n if (year.pivoted) {\n info = { kind: \"numeric\", order: dateOrder(layout), pivotedYear: true };\n }\n const day = dayReading(\n year.year,\n value(\"month\") ?? 0,\n value(\"day\") ?? 0,\n info,\n );\n if (day.kind !== \"read\") {\n return day;\n }\n date = day.date;\n }\n if (timeIndexes.length === 0) {\n return read(date, null, info);\n }\n const filledTimes = timeIndexes.filter(filled).length;\n if (filledTimes === 0 && options.fields === \"dateTime\") {\n return read(date, null, info);\n }\n if (filledTimes < timeIndexes.length) {\n return unreadableBecause(\"timeIncomplete\");\n }\n const time = timeOfSegments(texts, layout);\n return time === null\n ? unreadableBecause(\"unreadable\")\n : read(date, time, info);\n}\n\n/** The time of day filled time segments hold; `null` for an hour outside the cycle or minutes past 59. */\nfunction timeOfSegments(\n texts: readonly string[],\n layout: DateLayout,\n): PlainTime | null {\n const value = (type: SegmentType): number | null => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const dayPeriod = value(\"dayPeriod\");\n const hour = hourOfDay(\n value(\"hour\") ?? -1,\n dayPeriod === null ? null : dayPeriod === 0 ? 0 : 1,\n layout.hourCycle,\n );\n const minute = value(\"minute\") ?? 0;\n const second = value(\"second\") ?? 0;\n return hour === null || minute > 59 || second > 59\n ? null\n : plainTime(hour, minute, second);\n}\n\n/**\n * The time of day a field's segments hold once every time segment is\n * filled, whatever its date segments hold: a date-time field keeps it when\n * a shortcut sets the date. `null` for text that is not segments, a layout\n * without time segments, or a time not yet complete.\n */\nexport function segmentsTime(\n layout: DateLayout,\n text: string,\n): PlainTime | null {\n const texts = splitSegments(layout, text);\n const timeIndexes = layout.segments\n .map((segment, index) => (TIME_TYPES.has(segment.type) ? index : -1))\n .filter((index) => index >= 0);\n if (\n texts === null ||\n timeIndexes.length === 0 ||\n timeIndexes.some((index) => (texts[index] ?? \"\") === \"\")\n ) {\n return null;\n }\n return timeOfSegments(texts, layout);\n}\n\nconst ISO =\n /^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:[.,](\\d{1,9}))?)?)?\\s*(Z|[+-]\\d{2}(?::?\\d{2})?)?$/i;\n\n/** Minutes east of UTC for an ISO offset: `Z`, `+01:00`, `-0800`, `+05`. */\nfunction offsetMinutes(text: string): number {\n if (text.toUpperCase() === \"Z\") {\n return 0;\n }\n const sign = text.startsWith(\"-\") ? -1 : 1;\n const digits = text.slice(1).replace(\":\", \"\");\n return (\n sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2) || 0))\n );\n}\n\n/** An ISO date or date-time, or `null` for text in another form. */\nfunction readIso(text: string): DateTextReading | null {\n const match = ISO.exec(text);\n if (match === null) {\n return null;\n }\n const [, year, month, day, hour, minute, second, fraction, offset] = match;\n const iso: DateReadingInfo = { kind: \"iso\" };\n const date = dayReading(Number(year), Number(month), Number(day), iso);\n if (date.kind !== \"read\") {\n return date;\n }\n if (hour === undefined || minute === undefined) {\n return date;\n }\n const clock = [Number(hour), Number(minute), Number(second ?? 0)] as const;\n if (clock[0] > 23 || clock[1] > 59 || clock[2] > 59) {\n return unreadableBecause(\"unreadable\");\n }\n const time = plainTime(\n ...clock,\n Number((fraction ?? \"\").padEnd(3, \"0\").slice(0, 3)),\n );\n return read(\n date.date,\n time,\n iso,\n offset === undefined ? null : offsetMinutes(offset),\n );\n}\n\n/** Three numbers in `order` (\"mdy\") as a day; the year one, two or four digits. */\nfunction readNumbers(\n numbers: readonly string[],\n order: string,\n options: PivotOptions,\n): DateTextReading {\n const byType = new Map(\n Array.from(order, (type, index) => [type, numbers[index] ?? \"\"]),\n );\n const yearText = byType.get(\"y\") ?? \"\";\n const monthText = byType.get(\"m\") ?? \"\";\n const dayText = byType.get(\"d\") ?? \"\";\n if (monthText.length > 2 || dayText.length > 2) {\n return unreadableBecause(\"unreadable\");\n }\n const year = yearOf(Number(yearText), yearText.length, options);\n if (year === null) {\n return unreadableBecause(\n yearText.length === 3 ? \"yearDigits\" : \"unreadable\",\n );\n }\n return dayReading(year.year, Number(monthText), Number(dayText), {\n kind: \"numeric\",\n order,\n pivotedYear: year.pivoted,\n });\n}\n\n/** Month and weekday names a locale writes, folded, with English beside them. */\ninterface Names {\n readonly months: ReadonlyMap<string, number>;\n readonly weekdays: ReadonlySet<string>;\n}\n\nconst namesByLocale = new Map<string, Names>();\n\n/** The letters glued to a literal's end or start next to a name: Hebrew writes \"במרץ\" in \"14 במרץ\". */\nfunction glued(text: string | undefined, end: \"start\" | \"end\"): string {\n const match = (end === \"end\" ? /\\p{L}+$/u : /^\\p{L}+/u).exec(text ?? \"\");\n return match?.[0] ?? \"\";\n}\n\n/**\n * Month names alone and inside a date, where some languages change the\n * word (Russian writes the genitive \"марта\"), long and short; weekday\n * names long and short; in `locale` and in English.\n */\nfunction namesOf(locale: Intl.LocalesArgument): Names {\n const key = localeKey(locale);\n const known = namesByLocale.get(key);\n if (known !== undefined) {\n return known;\n }\n const months = new Map<string, number>();\n const weekdays = new Set<string>();\n for (const language of [locale, \"en\"]) {\n for (const width of [\"long\", \"short\"] as const) {\n const alone = dateTimeFormat(language, { month: width, timeZone: \"UTC\" });\n const inDate = dateTimeFormat(language, {\n day: \"numeric\",\n month: width,\n timeZone: \"UTC\",\n });\n const weekday = dateTimeFormat(language, {\n weekday: width,\n timeZone: \"UTC\",\n });\n for (let month = 1; month <= 12; month += 1) {\n const moment = Date.UTC(2026, month - 1, 15);\n months.set(foldWord(alone.format(moment)), month);\n const parts = inDate.formatToParts(moment);\n const at = parts.findIndex((part) => part.type === \"month\");\n const name = parts[at]?.value ?? \"\";\n months.set(foldWord(name), month);\n months.set(\n foldWord(\n glued(parts[at - 1]?.value, \"end\") +\n name +\n glued(parts[at + 1]?.value, \"start\"),\n ),\n month,\n );\n }\n // 9 to 15 March 2026 run from Monday to Sunday.\n for (let day = 9; day <= 15; day += 1) {\n weekdays.add(foldWord(weekday.format(Date.UTC(2026, 2, day))));\n }\n }\n }\n months.delete(\"\");\n const names = { months, weekdays };\n namesByLocale.set(key, names);\n return names;\n}\n\n/** The month a word names in `locale` or in English, long or short, without case, accents or a trailing dot; `null` for none. */\nexport function monthOfName(\n word: string,\n locale: Intl.LocalesArgument,\n): number | null {\n return namesOf(locale).months.get(foldWord(word)) ?? null;\n}\n\nconst TOKENS = /\\p{L}[\\p{L}\\p{M}]*\\.?|\\d+/gu;\n\n/**\n * A date written with numbers and words: a month name (long or short, in\n * the locale or in English, without case, accents or a trailing dot),\n * four digits for the year, and the day; of two short numbers, the\n * locale's order decides which is the day. Weekday names and words of one\n * or two letters (\"de\", \"of\", a CJK \"年\") are passed over, so\n * \"2026年3月14日\" is three numbers. `null` when a longer word is no name,\n * or there is no month name and not three numbers either.\n */\nfunction readWords(\n text: string,\n options: DateReadOptions,\n): DateTextReading | null {\n const { months, weekdays } = namesOf(options.locale);\n const numbers: string[] = [];\n let month: number | null = null;\n for (const token of text.match(TOKENS) ?? []) {\n if (/^\\d/.test(token)) {\n numbers.push(token);\n continue;\n }\n const word = foldWord(token);\n const named = months.get(word);\n if (named !== undefined) {\n if (month !== null && month !== named) {\n return unreadableBecause(\"unreadable\");\n }\n month = named;\n } else if (!weekdays.has(word) && Array.from(word).length > 2) {\n return null;\n }\n }\n const order = dateOrder(options.layout);\n if (month === null) {\n return numbers.length === 3 ? readNumbers(numbers, order, options) : null;\n }\n const long = numbers.filter((number) => number.length === 4);\n const short = numbers.filter((number) => number.length <= 2);\n if (long.length + short.length !== numbers.length) {\n return unreadableBecause(\n numbers.some((number) => number.length === 3)\n ? \"yearDigits\"\n : \"unreadable\",\n );\n }\n const dayFirst = order.indexOf(\"d\") < order.indexOf(\"y\");\n const [dayText, yearText] =\n long.length === 1 && short.length === 1\n ? [short[0], long[0]]\n : long.length === 0 && short.length === 2\n ? dayFirst\n ? [short[0], short[1]]\n : [short[1], short[0]]\n : [undefined, undefined];\n if (dayText === undefined || yearText === undefined) {\n return unreadableBecause(\"unreadable\");\n }\n const year = yearOf(Number(yearText), yearText.length, options);\n return year === null\n ? unreadableBecause(\"unreadable\")\n : dayReading(year.year, month, Number(dayText), {\n kind: \"monthName\",\n pivotedYear: year.pivoted,\n });\n}\n\n/** `text` cut into numbers of the given widths. */\nfunction cut(text: string, widths: readonly number[]): string[] {\n let at = 0;\n return widths.map((width) => {\n const piece = text.slice(at, at + width);\n at += width;\n return piece;\n });\n}\n\n/** A day alone, read leniently: ISO, eight digits, three numbers, or a month name. */\nfunction readDay(text: string, options: DateReadOptions): DateTextReading {\n const iso = readIso(text);\n if (iso !== null) {\n return iso.kind === \"read\" ? read(iso.date, null, iso.info) : iso;\n }\n const order = dateOrder(options.layout);\n if (/^\\d{8}$/.test(text)) {\n const compact = readNumbers(cut(text, [4, 2, 2]), \"ymd\", options);\n if (compact.kind === \"read\" || order === \"ymd\") {\n return compact;\n }\n const widths = Array.from(order, (type) => (type === \"y\" ? 4 : 2));\n return readNumbers(cut(text, widths), order, options);\n }\n if (/^\\d+(?:\\D+\\d+){2}$/u.test(text) && !/\\p{L}/u.test(text)) {\n const numbers = text.split(/\\D+/u);\n return readNumbers(\n numbers,\n numbers[0]?.length === 4 ? \"ymd\" : order,\n options,\n );\n }\n return readWords(text, options) ?? unreadableBecause(\"unreadable\");\n}\n\nconst TIME_CORE = /^(\\D*?)\\s*(\\d(?:[\\d\\s:.,hH]*\\d)?)\\s*(\\D*)$/u;\nconst TIME_SEPARATOR = /^\\s*(?:[:.,hH]|\\s)\\s*$/;\n\n/** The numbers of a time's core: \"1505\" is 15 and 05, \"15:05:09.250\" four numbers. */\nfunction clockNumbers(core: string, hasDayPeriod: boolean): string[] | null {\n const separators = core.split(/\\d+/).slice(1, -1);\n if (separators.some((separator) => !TIME_SEPARATOR.test(separator))) {\n return null;\n }\n const groups = core.split(/\\D+/);\n const [only = \"\"] = groups;\n if (groups.length > 1) {\n return groups.length <= 4 ? groups : null;\n }\n if (only.length === 3 || only.length === 4) {\n return cut(only, [only.length - 2, 2]);\n }\n if (only.length === 6) {\n return cut(only, [2, 2, 2]);\n }\n return hasDayPeriod && only.length <= 2 ? [only] : null;\n}\n\n/**\n * A time of day read leniently: \"15:05\", \"15.05\", \"1505\", \"15 h 05\",\n * \"3:05 PM\", \"3:05pm\", \"3 pm\", \"15:05:09.250\", the locale's day-period\n * texts before or after it (\"오후 3:05\") or English `am`, `pm`, `a`, `p`.\n * An hour alone needs its day period. `null` for anything else.\n */\nexport function readTimeText(\n text: string,\n layout: DateLayout,\n): PlainTime | null {\n const match = TIME_CORE.exec(cleanDateText(text));\n if (match === null) {\n return null;\n }\n const [, before = \"\", core = \"\", after = \"\"] = match;\n const words = [before.trim(), after.trim()].filter((word) => word !== \"\");\n const [word] = words;\n const dayPeriod = word === undefined ? null : dayPeriodOf(layout, word);\n if (words.length > 1 || (word !== undefined && dayPeriod === null)) {\n return null;\n }\n const numbers = clockNumbers(core, dayPeriod !== null);\n if (numbers === null) {\n return null;\n }\n const [hour = \"\", minute = \"\", second = \"\", fraction = \"\"] = numbers;\n if (\n hour.length > 2 ||\n (minute !== \"\" && minute.length !== 2) ||\n (second !== \"\" && second.length !== 2)\n ) {\n return null;\n }\n const hours = hourOfDay(\n Number(hour),\n dayPeriod,\n dayPeriod === null ? \"h23\" : layout.hourCycle === \"h11\" ? \"h11\" : \"h12\",\n );\n const minutes = Number(minute || 0);\n const seconds = Number(second || 0);\n if (hours === null || minutes > 59 || seconds > 59) {\n return null;\n }\n return plainTime(\n hours,\n minutes,\n seconds,\n Number(fraction.padEnd(3, \"0\").slice(0, 3)),\n );\n}\n\n/** Where a date-time text may split into its date and its time: at each space, comma or `T`. */\nfunction splitPoints(text: string): number[] {\n const points: number[] = [];\n for (let index = 1; index < text.length; index += 1) {\n if (/[\\s,T]/.test(text.charAt(index))) {\n points.push(index);\n }\n }\n return points;\n}\n\n/**\n * A pasted or free text read whole, leniently:\n *\n * 1. Cleaned: trimmed, digits in any script as ASCII, direction marks\n * dropped, every kind of space a space.\n * 2. With shortcuts on, the shortcut grammar (`t`, `+3`, `-1me`).\n * 3. ISO: `2026-03-14`, `2026-03-14T15:05`, seconds and fractions\n * optional, a trailing `Z` or offset. A date field takes the day, a\n * time field the time.\n * 4. Eight digits: `YYYYMMDD` when that is a real day, else the locale's\n * order as 2-2-4.\n * 5. Three numbers with anything between: in the locale's order, except\n * that four digits first always means year, month, day.\n * 6. A month name with the day and year, weekday names passed over.\n * 7. A time after the date (or alone, in a time field): \"15:05\",\n * \"3:05 PM\", \"3 pm\", the locale's day periods or English ones.\n *\n * One- and two-digit years pivot (`pivotYear`). Anything else is\n * unreadable.\n */\nexport function readDateText(\n text: string,\n options: DateReadOptions,\n): DateTextReading {\n const clean = cleanDateText(text);\n if (clean === \"\") {\n return EMPTY;\n }\n const iso = readIso(clean);\n if (options.fields === \"time\") {\n if (iso?.kind === \"read\" && iso.time !== null) {\n return read(null, iso.time, iso.info);\n }\n const time = readTimeText(clean, options.layout);\n return time === null\n ? unreadableBecause(\"unreadable\")\n : read(null, time, { kind: \"time\" });\n }\n if (options.shortcuts) {\n const shortcut = readDateShortcut(clean, options.today);\n if (shortcut !== null) {\n return read(shortcut, null, { kind: \"shortcut\", shortcut: clean });\n }\n }\n if (iso !== null) {\n return options.fields === \"date\" && iso.kind === \"read\"\n ? read(iso.date, null, iso.info)\n : iso;\n }\n const whole = readDay(clean, options);\n if (whole.kind === \"read\") {\n return whole;\n }\n for (const point of splitPoints(clean)) {\n const day = readDay(clean.slice(0, point).replace(/[\\s,]+$/, \"\"), options);\n const time = readTimeText(clean.slice(point + 1), options.layout);\n if (day.kind === \"read\" && time !== null) {\n return read(day.date, options.fields === \"date\" ? null : time, day.info);\n }\n }\n return whole;\n}\n\n/**\n * The field's text read as the field reads it: its segments (`texts`,\n * `null` for text that is not segments) strictly, so a date still being\n * typed is incomplete; anything else, or segments that make no date but\n * a lenient reading does, by `readDateText`.\n */\nexport function readDateField(\n text: string,\n texts: readonly string[] | null,\n options: DateReadOptions,\n): DateTextReading {\n if (texts === null) {\n return readDateText(text, options);\n }\n const strict = readDateSegments(texts, options);\n if (\n strict.kind !== \"unreadable\" ||\n strict.reason === \"dateIncomplete\" ||\n strict.reason === \"timeIncomplete\" ||\n strict.reason === \"yearDigits\"\n ) {\n return strict;\n }\n const lenient = readDateText(text, options);\n return lenient.kind === \"read\" ? lenient : strict;\n}\n","import {\n epochOfInstant,\n epochOfWallClock,\n instantFromEpoch,\n plainDateTime,\n splitDateTime,\n wallClockOfEpoch,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n} from \"./values\";\n\n/** Which moment a wall clock in a skipped or repeated hour means: Temporal's four answers. */\nexport type TimeZoneDisambiguation =\n \"compatible\" | \"earlier\" | \"later\" | \"reject\";\n\n/**\n * How a wall clock met a zone: as typed (`exact`); in an hour the clocks\n * skipped, read as `wallClock` (`skipped`); in an hour that happens twice,\n * read as one moment with the `other` beside it (`repeated`); or, with\n * `\"reject\"`, refused, with why.\n */\nexport type ZonedReading =\n | { readonly kind: \"exact\"; readonly instant: Instant }\n | {\n readonly kind: \"skipped\";\n readonly instant: Instant;\n readonly wallClock: PlainDateTime;\n }\n | {\n readonly kind: \"repeated\";\n readonly instant: Instant;\n readonly other: Instant;\n }\n | { readonly kind: \"rejected\"; readonly reason: \"skipped\" | \"repeated\" };\n\nconst DAY_MS = 86_400_000;\n\n/** Formatters per zone: building an `Intl.DateTimeFormat` costs far more than using one. */\nconst zoneFormats = new Map<string, Intl.DateTimeFormat>();\n\nfunction zoneFormat(timeZone: string): Intl.DateTimeFormat {\n let format = zoneFormats.get(timeZone);\n if (format === undefined) {\n format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n calendar: \"gregory\",\n numberingSystem: \"latn\",\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n });\n zoneFormats.set(timeZone, format);\n }\n return format;\n}\n\n/** The wall clock `timeZone` shows at `epoch`, as the epoch of that wall clock read as UTC. */\nfunction wallEpochAt(epoch: number, timeZone: string): number {\n const whole = Math.floor(epoch / 1000) * 1000;\n const fields: Partial<Record<Intl.DateTimeFormatPartTypes, number>> = {};\n for (const part of zoneFormat(timeZone).formatToParts(whole)) {\n fields[part.type] = Number(part.value);\n }\n const wall = new Date(0);\n wall.setUTCFullYear(\n fields.year ?? 1970,\n (fields.month ?? 1) - 1,\n fields.day ?? 1,\n );\n wall.setUTCHours(fields.hour ?? 0, fields.minute ?? 0, fields.second ?? 0);\n return wall.getTime() + (epoch - whole);\n}\n\n/** Milliseconds `timeZone`'s clocks are ahead of UTC at `epoch`. */\nfunction offsetAt(epoch: number, timeZone: string): number {\n return wallEpochAt(epoch, timeZone) - epoch;\n}\n\n/**\n * The zone the runtime runs in. The one place forms-core reads it: only\n * an input whose prop says it defaults to the runtime's zone asks.\n */\nexport function runtimeTimeZone(): string {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n}\n\n/** Whether `name` is a time zone `Intl` knows (\"Europe/Berlin\", \"UTC\"). */\nexport function isTimeZone(name: string): boolean {\n try {\n zoneFormat(name);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The day it is in `timeZone` at `now` (milliseconds since the epoch). */\nexport function todayIn(timeZone: string, now: number): PlainDate {\n return splitDateTime(nowIn(timeZone, now)).date;\n}\n\n/** The wall clock in `timeZone` at `now` (milliseconds since the epoch). */\nexport function nowIn(timeZone: string, now: number): PlainDateTime {\n return wallClockOfEpoch(wallEpochAt(now, timeZone));\n}\n\n/** The wall clock `timeZone` shows at `instant`. */\nexport function wallClockOf(instant: Instant, timeZone: string): PlainDateTime {\n return nowIn(timeZone, epochOfInstant(instant));\n}\n\n/** How far `timeZone` is from UTC at `instant`: \"+01:00\", \"-08:00\", \"+05:30\" (with seconds when it has them). */\nexport function offsetOf(instant: Instant, timeZone: string): string {\n const offset = offsetAt(epochOfInstant(instant), timeZone) / 1000;\n const size = Math.abs(offset);\n const pad = (value: number) => String(value).padStart(2, \"0\");\n const hours = pad(Math.floor(size / 3600));\n const minutes = pad(Math.floor(size / 60) % 60);\n const seconds = size % 60;\n return `${offset < 0 ? \"-\" : \"+\"}${hours}:${minutes}${\n seconds === 0 ? \"\" : `:${pad(seconds)}`\n }`;\n}\n\n/**\n * The moment `dateTime` is in `timeZone`. A candidate is the wall clock\n * less an offset the zone has on the day before or the day after it, kept\n * when the zone really has that offset at the candidate: two candidates\n * are a repeated hour, none a skipped one. `disambiguation` picks as\n * Temporal does: `\"compatible\"` (the default) takes the earlier of a\n * repeated hour and reads a skipped one with the offset from before the\n * change, so 02:30 on the night clocks go from 02:00 to 03:00 is 03:30;\n * `\"earlier\"` reads it with the offset after (01:30); `\"later\"` takes the\n * later of a repeated hour; `\"reject\"` refuses both. Throws a\n * `RangeError` for a moment outside the years 1 to 9999.\n */\nexport function instantOf(\n dateTime: PlainDateTime,\n timeZone: string,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): ZonedReading {\n const meeting = meet(dateTime, timeZone);\n const { candidates } = meeting;\n const [first, second] = candidates;\n if (first !== undefined && second === undefined) {\n return { kind: \"exact\", instant: instantFromEpoch(first) };\n }\n if (disambiguation === \"reject\") {\n return {\n kind: \"rejected\",\n reason: first === undefined ? \"skipped\" : \"repeated\",\n };\n }\n const epoch = chosen(meeting, disambiguation);\n if (first !== undefined && second !== undefined) {\n return {\n kind: \"repeated\",\n instant: instantFromEpoch(epoch),\n other: instantFromEpoch(epoch === first ? second : first),\n };\n }\n return {\n kind: \"skipped\",\n instant: instantFromEpoch(epoch),\n wallClock: wallClockOfEpoch(wallEpochAt(epoch, timeZone)),\n };\n}\n\n/** A wall clock met with a zone: the offsets either side of it, and the moments it can be. */\ninterface Meeting {\n readonly local: number;\n readonly before: number;\n readonly after: number;\n /** Earliest first: one when the wall clock is plain, two when repeated, none when skipped. */\n readonly candidates: readonly number[];\n}\n\nfunction meet(dateTime: PlainDateTime, timeZone: string): Meeting {\n const local = epochOfWallClock(dateTime);\n const before = offsetAt(local - DAY_MS, timeZone);\n const after = offsetAt(local + DAY_MS, timeZone);\n const candidates = [...new Set([before, after])]\n .map((offset) => local - offset)\n .filter((epoch) => offsetAt(epoch, timeZone) === local - epoch)\n .sort((a, b) => a - b);\n return { local, before, after, candidates };\n}\n\n/** The moment a disambiguation that does not refuse picks, as epoch milliseconds. */\nfunction chosen(\n { local, before, after, candidates }: Meeting,\n disambiguation: Exclude<TimeZoneDisambiguation, \"reject\">,\n): number {\n const [first, second] = candidates;\n if (first !== undefined) {\n return disambiguation === \"later\" ? (second ?? first) : first;\n }\n return local - (disambiguation === \"earlier\" ? after : before);\n}\n\n/**\n * The moment `dateTime` is in `timeZone`, by `disambiguation`; where it\n * would refuse (`\"reject\"`), as `\"compatible\"` reads it. For measuring a\n * span between wall clocks, which needs a moment either way.\n */\nexport function exactInstantOf(\n dateTime: PlainDateTime,\n timeZone: string,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): Instant {\n return instantFromEpoch(\n chosen(\n meet(dateTime, timeZone),\n disambiguation === \"reject\" ? \"compatible\" : disambiguation,\n ),\n );\n}\n\n/**\n * The moment `date` starts in `timeZone`: its midnight, or the first\n * moment after it when the clocks skipped midnight (01:00 that day).\n */\nexport function startOfDayIn(date: PlainDate, timeZone: string): Instant {\n return exactInstantOf(plainDateTime(date, \"00:00\"), timeZone);\n}\n","import type { ChangeCause } from \"../field/plan\";\nimport type { FieldState } from \"../field/state\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n dateTimeFormat,\n formatDate,\n formatDateTime,\n formatInstant,\n formatTime,\n} from \"./format\";\nimport {\n dateLayout,\n formatSegments,\n segmentSpans,\n shownHour,\n splitSegments,\n type DateLayout,\n type DateLayoutFields,\n type DateSegmentType,\n type SegmentType,\n} from \"./layout\";\nimport {\n readDateField,\n type DateReadingInfo,\n type DateTextReading,\n type DateUnreadableReason,\n} from \"./reading\";\nimport {\n dateFromInstant,\n dateFromPlainDate,\n dateFromPlainDateTime,\n dateParts,\n epochOfInstant,\n epochOfWallClock,\n instantFromEpoch,\n plainDateTime,\n plainTime,\n splitDateTime,\n timeParts,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\nimport {\n instantOf,\n offsetOf,\n wallClockOf,\n type TimeZoneDisambiguation,\n} from \"./zone\";\n\n/** What a date input adds to every event it fires. */\nexport interface DateDetails {\n /** The day as a JS `Date` at local midnight, as the grid reads a day; `null` when empty. */\n readonly date: Date | null;\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The segment the edit was in; `null` for a paste, a pick or a change from code. */\n readonly segment: DateSegmentType | null;\n /** The shortcut typed (\"t\", \"+3\", \"-1me\"); `null` otherwise. */\n readonly shortcut: string | null;\n /** How the text on screen reads; `null` while it shows the value. */\n readonly reading: DateReadingInfo | null;\n}\n\n/** What a time input adds to every event. */\nexport type TimeDetails = Omit<DateDetails, \"date\" | \"shortcut\">;\n\n/** What a date-time input adds to every event. */\nexport interface DateTimeDetails extends DateDetails {\n /** For an instant: how the wall clock was read in the zone; `null` for a local date-time. */\n readonly zone: {\n readonly reading: \"exact\" | \"skipped\" | \"repeated\";\n readonly offset: string;\n } | null;\n}\n\n/** What every date, time and date-time field is told. */\ninterface SegmentedFieldOptions {\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n /** How display mode writes the value; `Intl` styles by default. */\n readonly displayFormat?: Intl.DateTimeFormatOptions | undefined;\n /** The segment the user is typing in, if any, which a renderer knows: a short year there is not pivoted yet. */\n readonly activeSegment?: (() => number | null) | undefined;\n}\n\n/** How a date field reads and writes. */\nexport interface DateFieldOptions extends SegmentedFieldOptions {\n /** Today in the field's zone: shortcuts count from it, and the year pivot. */\n readonly today: () => PlainDate;\n /** Typing \"t\", \"+3\", \"-1w\", \"s\", \"e\"; on by default. */\n readonly shortcuts?: boolean | undefined;\n /** The limits, which the two-digit year pivot respects. */\n readonly min?: PlainDate | null | undefined;\n readonly max?: PlainDate | null | undefined;\n}\n\n/** How a time field reads and writes. */\nexport interface TimeFieldOptions extends SegmentedFieldOptions {\n /** The locale's hour cycle unless given. */\n readonly hourCycle?: \"h12\" | \"h23\" | undefined;\n /** `\"minute\"` by default; `\"second\"` keeps seconds. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n}\n\n/** How a local date-time field reads and writes. */\nexport interface DateTimeFieldOptions\n extends\n Omit<DateFieldOptions, \"min\" | \"max\">,\n Omit<TimeFieldOptions, keyof SegmentedFieldOptions> {\n /** The time a date gets when its time is left empty; \"00:00\" by default. */\n readonly defaultTime?: PlainTime | undefined;\n readonly min?: PlainDateTime | null | undefined;\n readonly max?: PlainDateTime | null | undefined;\n}\n\n/** How an instant field reads and writes: wall clocks in `timeZone`. */\nexport interface InstantFieldOptions extends Omit<\n DateTimeFieldOptions,\n \"min\" | \"max\"\n> {\n readonly timeZone: string;\n /** Which moment a wall clock in a skipped or repeated hour means; `\"compatible\"` by default. */\n readonly disambiguation?: TimeZoneDisambiguation | undefined;\n readonly min?: Instant | null | undefined;\n readonly max?: Instant | null | undefined;\n}\n\ntype AnyFieldOptions = SegmentedFieldOptions &\n Partial<Pick<DateFieldOptions, \"today\" | \"shortcuts\">> &\n Partial<Pick<TimeFieldOptions, \"hourCycle\" | \"precision\">>;\n\n/** The layout a field of `fields` uses, in the field's locale unless its options name one. */\nfunction layoutFor(\n fields: DateLayoutFields,\n options: AnyFieldOptions,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): DateLayout {\n return dateLayout(\n {\n locale: options.locale ?? locale,\n fields,\n hourCycle: options.hourCycle,\n precision: options.precision,\n numberingSystem: options.numberingSystem,\n },\n messages,\n );\n}\n\n/** The hours, minutes and seconds each segment type shows for a time of day. */\nfunction timeValues(\n time: PlainTime,\n hourCycle: DateLayout[\"hourCycle\"],\n): Partial<Record<SegmentType, number>> {\n const { hour, minute, second } = timeParts(time);\n return {\n hour: shownHour(hour, hourCycle),\n minute,\n second,\n dayPeriod: hour >= 12 ? 1 : 0,\n };\n}\n\n/** A day written in a date layout's segments: \"03/14/2026\", \"14.03.2026\". */\nexport function formatDateSegments(\n layout: DateLayout,\n date: PlainDate,\n): string {\n return formatSegments(layout, dateParts(date));\n}\n\n/** A time of day written in a time layout's segments: \"3:05 PM\", \"15:05\". */\nexport function formatTimeSegments(\n layout: DateLayout,\n time: PlainTime,\n): string {\n return formatSegments(layout, timeValues(time, layout.hourCycle));\n}\n\n/** A wall clock written in a date-time layout's segments: \"03/14/2026, 3:05 PM\". */\nexport function formatDateTimeSegments(\n layout: DateLayout,\n dateTime: PlainDateTime,\n): string {\n const { date, time } = splitDateTime(dateTime);\n return formatSegments(layout, {\n ...dateParts(date),\n ...timeValues(time, layout.hourCycle),\n });\n}\n\n/** `time` at the field's precision: seconds dropped unless it keeps them, milliseconds always. */\nfunction atPrecision(\n time: PlainTime,\n precision: TimeFieldOptions[\"precision\"],\n): PlainTime {\n const { hour, minute, second } = timeParts(time);\n return plainTime(hour, minute, precision === \"second\" ? second : 0);\n}\n\n/** The message for text a field cannot read; `example` writes the example the field gives. */\nfunction messageFor(\n reason: DateUnreadableReason,\n messages: FormsMessages,\n example: () => string,\n fields: \"date\" | \"time\" | \"dateTime\",\n): string {\n switch (reason) {\n case \"dateIncomplete\":\n return messages.dateIncomplete;\n case \"timeIncomplete\":\n return messages.timeIncomplete;\n case \"nonexistent\":\n return messages.dateNonexistent;\n case \"yearDigits\":\n return messages.dateYearDigits;\n case \"unreadable\":\n return fields === \"time\"\n ? messages.timeUnreadable(example())\n : messages.dateUnreadable(example());\n }\n}\n\n/** How a state's typed text reads; `null` while it shows its value or cannot be read. */\nfunction readState<V>(\n state: FieldState<V>,\n reader: (text: string) => DateTextReading,\n): DateReadingInfo | null {\n if (state.draft.kind !== \"text\") {\n return null;\n }\n const reading = reader(state.draft.text);\n return reading.kind === \"read\" ? reading.info : null;\n}\n\n/**\n * The segment an edit was in, from where the cause says it happened in\n * the field's text; `null` for a paste or drop, a change from code, or\n * text that is not segments.\n */\nfunction segmentOf(\n layout: DateLayout,\n text: string,\n cause: ChangeCause<unknown> | null,\n): DateSegmentType | null {\n const at = cause?.input?.selectionStart ?? null;\n if (\n cause === null ||\n at === null ||\n cause.source === \"paste\" ||\n cause.source === \"drop\"\n ) {\n return null;\n }\n const spans = segmentSpans(layout, text);\n if (spans === null) {\n return null;\n }\n const starting = spans.findIndex(([start]) => start === at);\n const index =\n starting >= 0\n ? starting\n : spans.findIndex(([start, end]) => start <= at && at <= end);\n const type = layout.segments[index]?.type;\n return type === undefined || type === \"quarter\" || type === \"period\"\n ? null\n : type;\n}\n\n/** The text a state shows: its draft, or its value written by `write`. */\nfunction shownText<V>(\n state: FieldState<V>,\n write: (value: V) => string,\n): string {\n if (state.draft.kind === \"text\") {\n return state.draft.text;\n }\n return state.value === null ? \"\" : write(state.value);\n}\n\n/**\n * A date field's own reading: its segments strictly, pasted and free text\n * leniently (shortcuts, ISO, numbers in the locale's order, month names),\n * empty as `null`, with the messages for text that is incomplete, a day\n * that does not exist, a three-digit year, or text that is no date (\"Enter\n * a date such as 03/14/2026\", today in the field's segments).\n */\nexport function dateParser(\n options: DateFieldOptions,\n): (text: string, context: ParseContext<PlainDate>) => ParseResult<PlainDate> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"date\", options, locale, messages);\n const reading = readDate(text, \"date\", layout, options, locale);\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => formatDateSegments(layout, options.today()),\n \"date\",\n ),\n );\n }\n return parsed(reading.kind === \"empty\" ? null : reading.date);\n };\n}\n\nfunction readDate(\n text: string,\n fields: \"date\" | \"time\" | \"dateTime\",\n layout: DateLayout,\n options: AnyFieldOptions & {\n readonly min?: PlainDate | null | undefined;\n readonly max?: PlainDate | null | undefined;\n },\n locale: Intl.LocalesArgument,\n): DateTextReading {\n return readDateField(text, splitSegments(layout, text), {\n fields,\n layout,\n locale: options.locale ?? locale,\n shortcuts: fields !== \"time\" && options.shortcuts !== false,\n // A time field reads no day, so it has no today to pass.\n today: options.today?.() ?? \"2000-01-01\",\n min: options.min,\n max: options.max,\n activeSegment: options.activeSegment?.(),\n });\n}\n\n/** A date field's own writing: the day in its segments, whatever the purpose; `\"\"` for `null`. */\nexport function dateFormatter(\n options: Pick<DateFieldOptions, \"locale\" | \"numberingSystem\"> = {},\n): (value: PlainDate | null, context: FormatContext<PlainDate>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateSegments(layoutFor(\"date\", options, locale, messages), value);\n}\n\n/** What a date field's events carry, for its state and the event's cause. */\nexport function dateDetails(\n state: FieldState<PlainDate>,\n cause: ChangeCause<unknown> | null,\n options: DateFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"date\", options, locale, messages);\n const reading = readState(state, (text) =>\n readDate(text, \"date\", layout, options, locale),\n );\n const { value } = state;\n return {\n date: value === null ? null : dateFromPlainDate(value),\n formatted:\n value === null ? \"\" : formatDate(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (date) => formatDateSegments(layout, date)),\n cause,\n ),\n shortcut: reading?.kind === \"shortcut\" ? reading.shortcut : null,\n reading,\n };\n}\n\n/** A sample time an unreadable time's message gives: 15:05 in the field's segments. */\nconst EXAMPLE_TIME: PlainTime = \"15:05\";\n\n/**\n * A time field's own reading: its segments strictly, pasted and free text\n * leniently (\"15:05\", \"3:05 PM\", \"1505\", an ISO date-time's time), at the\n * field's precision; empty as `null`.\n */\nexport function timeParser(\n options: TimeFieldOptions = {},\n): (text: string, context: ParseContext<PlainTime>) => ParseResult<PlainTime> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"time\", options, locale, messages);\n const reading = readDate(text, \"time\", layout, options, locale);\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => formatTimeSegments(layout, EXAMPLE_TIME),\n \"time\",\n ),\n );\n }\n return parsed(\n reading.kind === \"empty\" || reading.time === null\n ? null\n : atPrecision(reading.time, options.precision),\n );\n };\n}\n\n/** A time field's own writing: the time in its segments; `\"\"` for `null`. */\nexport function timeFormatter(\n options: TimeFieldOptions = {},\n): (value: PlainTime | null, context: FormatContext<PlainTime>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatTimeSegments(layoutFor(\"time\", options, locale, messages), value);\n}\n\n/** What a time field's events carry. */\nexport function timeDetails(\n state: FieldState<PlainTime>,\n cause: ChangeCause<unknown> | null,\n options: TimeFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): TimeDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"time\", options, locale, messages);\n const { value } = state;\n return {\n formatted:\n value === null ? \"\" : formatTime(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (time) => formatTimeSegments(layout, time)),\n cause,\n ),\n reading: readState(state, (text) =>\n readDate(text, \"time\", layout, options, locale),\n ),\n };\n}\n\n/** The date part of a wall-clock limit, for the year pivot. */\nfunction dayOf(limit: string | null | undefined): PlainDate | null {\n return limit == null ? null : (limit.slice(0, 10) as PlainDate);\n}\n\n/** A date-time text read as a wall clock: a date without a time takes `defaultTime`. */\nfunction readWallClock(\n text: string,\n layout: DateLayout,\n options: DateTimeFieldOptions | InstantFieldOptions,\n locale: Intl.LocalesArgument,\n limits: { readonly min: PlainDate | null; readonly max: PlainDate | null },\n):\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"read\";\n readonly dateTime: PlainDateTime;\n readonly offset: number | null;\n readonly info: DateReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: DateUnreadableReason } {\n const reading = readDate(\n text,\n \"dateTime\",\n layout,\n { ...options, ...limits },\n locale,\n );\n if (reading.kind !== \"read\") {\n return reading;\n }\n if (reading.date === null) {\n return { kind: \"unreadable\", reason: \"dateIncomplete\" };\n }\n const time = atPrecision(\n reading.time ?? options.defaultTime ?? \"00:00\",\n options.precision,\n );\n return {\n kind: \"read\",\n dateTime: plainDateTime(reading.date, time),\n offset: reading.offset,\n info: reading.info,\n };\n}\n\n/** The example an unreadable date-time's message gives: today at the default time, in the field's segments. */\nfunction dateTimeExample(\n layout: DateLayout,\n options: DateTimeFieldOptions | InstantFieldOptions,\n): string {\n return formatDateTimeSegments(\n layout,\n plainDateTime(options.today(), options.defaultTime ?? \"00:00\"),\n );\n}\n\n/**\n * A local date-time field's own reading: as `dateParser` reads the date\n * and `timeParser` the time; a date whose time is left empty takes\n * `defaultTime`; a pasted offset is dropped, the wall clock kept.\n */\nexport function dateTimeParser(\n options: DateTimeFieldOptions,\n): (\n text: string,\n context: ParseContext<PlainDateTime>,\n) => ParseResult<PlainDateTime> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const reading = readWallClock(text, layout, options, locale, {\n min: dayOf(options.min),\n max: dayOf(options.max),\n });\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => dateTimeExample(layout, options),\n \"dateTime\",\n ),\n );\n }\n return parsed(reading.kind === \"empty\" ? null : reading.dateTime);\n };\n}\n\n/** A local date-time field's own writing: the wall clock in its segments; `\"\"` for `null`. */\nexport function dateTimeFormatter(\n options: Omit<TimeFieldOptions, \"displayFormat\"> = {},\n): (\n value: PlainDateTime | null,\n context: FormatContext<PlainDateTime>,\n) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateTimeSegments(\n layoutFor(\"dateTime\", options, locale, messages),\n value,\n );\n}\n\n/** What a local date-time field's events carry; `date` is the wall clock as a local `Date`. */\nexport function dateTimeDetails(\n state: FieldState<PlainDateTime>,\n cause: ChangeCause<unknown> | null,\n options: DateTimeFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateTimeDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const limits = { min: dayOf(options.min), max: dayOf(options.max) };\n const reading = readState(state, (text) =>\n readDate(text, \"dateTime\", layout, { ...options, ...limits }, locale),\n );\n const { value } = state;\n return {\n date: value === null ? null : dateFromPlainDateTime(value),\n formatted:\n value === null\n ? \"\"\n : formatDateTime(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (dateTime) => formatDateTimeSegments(layout, dateTime)),\n cause,\n ),\n shortcut: reading?.kind === \"shortcut\" ? reading.shortcut : null,\n reading,\n zone: null,\n };\n}\n\n/**\n * An instant field's own reading: the wall clock as a local date-time\n * field reads it, then the moment it is in `timeZone` by\n * `disambiguation`; a pasted text with an offset is that moment exactly.\n * A wall clock `\"reject\"` refuses is unreadable (\"02:30 doesn't exist\n * here: clocks go forward\").\n */\nexport function instantParser(\n options: InstantFieldOptions,\n): (text: string, context: ParseContext<Instant>) => ParseResult<Instant> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const { timeZone } = options;\n const reading = readWallClock(text, layout, options, locale, {\n min:\n options.min == null ? null : dayOf(wallClockOf(options.min, timeZone)),\n max:\n options.max == null ? null : dayOf(wallClockOf(options.max, timeZone)),\n });\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => dateTimeExample(layout, options),\n \"dateTime\",\n ),\n );\n }\n if (reading.kind === \"empty\") {\n return parsed(null);\n }\n const { dateTime, offset } = reading;\n if (offset !== null) {\n return parsed(\n instantFromEpoch(epochOfWallClock(dateTime) - offset * 60_000),\n );\n }\n const zoned = instantOf(dateTime, timeZone, options.disambiguation);\n if (zoned.kind !== \"rejected\") {\n return parsed(zoned.instant);\n }\n const typed = formatTime(\n splitDateTime(dateTime).time,\n options.locale ?? locale,\n );\n return unreadable(\n zoned.reason === \"skipped\"\n ? messages.timeNonexistent(typed)\n : messages.timeAmbiguous(typed),\n );\n };\n}\n\n/** An instant field's own writing: its wall clock in `timeZone`, in the field's segments; `\"\"` for `null`. */\nexport function instantFormatter(\n options: Pick<InstantFieldOptions, \"timeZone\"> &\n Omit<TimeFieldOptions, \"displayFormat\">,\n): (value: Instant | null, context: FormatContext<Instant>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateTimeSegments(\n layoutFor(\"dateTime\", options, locale, messages),\n wallClockOf(value, options.timeZone),\n );\n}\n\n/**\n * What an instant field's events carry: `date` is the exact `Date`;\n * `zone` says how the wall clock shown was read in the zone (a skipped\n * hour read as the hour after, a repeated one) and the offset it has.\n */\nexport function instantDetails(\n state: FieldState<Instant>,\n cause: ChangeCause<unknown> | null,\n options: InstantFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateTimeDetails {\n const { locale, messages, timeZone } = options;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const typed =\n state.draft.kind === \"text\"\n ? readWallClock(state.draft.text, layout, options, locale, {\n min: null,\n max: null,\n })\n : null;\n const { value } = state;\n const wallClock =\n typed?.kind === \"read\" && typed.offset === null\n ? typed.dateTime\n : value === null\n ? null\n : wallClockOf(value, timeZone);\n const zoned =\n wallClock === null\n ? null\n : instantOf(wallClock, timeZone, options.disambiguation);\n return {\n date: value === null ? null : dateFromInstant(value),\n formatted:\n value === null\n ? \"\"\n : formatInstant(value, timeZone, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (instant) =>\n formatDateTimeSegments(layout, wallClockOf(instant, timeZone)),\n ),\n cause,\n ),\n shortcut:\n typed?.kind === \"read\" && typed.info.kind === \"shortcut\"\n ? typed.info.shortcut\n : null,\n reading: typed?.kind === \"read\" ? typed.info : null,\n zone:\n value === null || zoned === null || zoned.kind === \"rejected\"\n ? null\n : { reading: zoned.kind, offset: offsetOf(value, timeZone) },\n };\n}\n\n/** The zone's offset at `instant` as `locale` names it: \"GMT+02:00\". */\nfunction offsetName(\n instant: Instant,\n timeZone: string,\n locale: Intl.LocalesArgument,\n): string {\n return (\n dateTimeFormat(locale, { timeZone, timeZoneName: \"longOffset\" })\n .formatToParts(epochOfInstant(instant))\n .find((part) => part.type === \"timeZoneName\")?.value ??\n offsetOf(instant, timeZone)\n );\n}\n\n/**\n * The info message an instant field shows while the wall clock in `text`\n * falls in an hour its zone skips (\"Clocks go forward here: 02:30 is read\n * as 03:30\") or repeats (\"02:30 happens twice; read as GMT+02:00\"), times\n * as display mode writes them; `null` for any other text, a text with an\n * offset of its own included.\n */\nexport function instantZoneMessage(\n text: string,\n options: InstantFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): string | null {\n const { messages, timeZone } = options;\n const locale = options.locale;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const typed = readWallClock(text, layout, options, locale, {\n min: null,\n max: null,\n });\n if (typed.kind !== \"read\" || typed.offset !== null) {\n return null;\n }\n const timeOf = (dateTime: PlainDateTime) =>\n formatTime(splitDateTime(dateTime).time, locale);\n const zoned = instantOf(typed.dateTime, timeZone, options.disambiguation);\n switch (zoned.kind) {\n case \"skipped\":\n return messages.timeSkipped(\n timeOf(typed.dateTime),\n timeOf(zoned.wallClock),\n );\n case \"repeated\":\n return messages.timeRepeated(\n timeOf(typed.dateTime),\n offsetName(zoned.instant, timeZone, locale),\n );\n default:\n return null;\n }\n}\n","/** No per-type flags. */\nexport type NoFlags = Record<never, never>;\n\n/**\n * A stretch of values of one type. Either end may be `null` (open). `F` is\n * the type's own flags, carried in the value beside the ends (a time range\n * over midnight carries `overnight`); a flag is never named `start`,\n * `end` or `rule` (which marks a `RelativeRange`).\n * A range with both ends open is no range: an input holding one holds\n * `null`.\n */\nexport type Range<T, F extends object = NoFlags> = {\n readonly start: T | null;\n readonly end: T | null;\n} & Readonly<F>;\n\n/**\n * Whether `end` belongs to the range: `\"[)\"`, half-open (`end` is the first\n * value after it, as a date range stores the day after its last day), or\n * `\"[]\"`, closed.\n */\nexport type RangeBounds = \"[)\" | \"[]\";\n\n/** One end of a range. */\nexport type RangeEnd = \"start\" | \"end\";\n\n/** A range kept as a rule (\"the last 7 days\"), resolved to ends on demand. */\nexport interface RelativeRange<R> {\n readonly kind: \"relative\";\n readonly rule: R;\n}\n\n/** What a range input holds: fixed ends, or (for a type with rules) a rule. */\nexport type RangeValue<T, F extends object = NoFlags, R = never> = [R] extends [\n never,\n]\n ? Range<T, F>\n : Range<T, F> | RelativeRange<R>;\n\n/** How two present ends stand: in order, with the flags that makes, or reversed. */\nexport type RangeOrientation<F extends object> =\n | { readonly kind: \"ordered\"; readonly flags: F }\n | { readonly kind: \"reversed\" };\n\n/**\n * Everything the range model needs to know about one value type, which the\n * type supplies. `S` is its span (a number for numbers, a duration for\n * dates); `C` the context its functions need (a time zone, whether\n * `overnight` is allowed); `R` its relative rule, `never` when it has none.\n * The model orders, checks and measures only through these functions.\n */\nexport interface RangeKind<\n T,\n F extends object = NoFlags,\n S = number,\n C = undefined,\n R = never,\n> {\n /** Negative when `a` comes before `b`, 0 when they are one, positive after. */\n readonly compare: (a: T, b: T) => number;\n /** How `end` stands to `start`: a time range may call an earlier end \"ordered, overnight\". */\n readonly orient: (start: T, end: T, context: C) => RangeOrientation<F>;\n /** The flags of a range with an open end. */\n readonly openFlags: F;\n /** The length from `start` to `end`, both present, as stored. */\n readonly span: (start: T, end: T, flags: F, context: C) => S;\n readonly compareSpans: (a: S, b: S) => number;\n /**\n * The stored end of a half-open range for an end shown inclusive (a date:\n * the next day). Without it, the end shown is the end stored.\n */\n readonly toStoredEnd?: ((shown: T, context: C) => T) | undefined;\n /** The end shown inclusive for a half-open range's stored end; the inverse of `toStoredEnd`. */\n readonly toShownEnd?: ((stored: T, context: C) => T) | undefined;\n /** The ends a rule stands for, now. Required when `R` is not `never`. */\n readonly resolve?: ((rule: R, context: C) => Range<T, F>) | undefined;\n /**\n * Whether two rules are one. Without it, rules are compared as plain\n * data: the same keys holding the same values, deeply.\n */\n readonly sameRule?: ((a: R, b: R) => boolean) | undefined;\n}\n\n/** How a range input reads two ends. */\nexport interface RangeOptions<S> {\n /** `\"[)\"` by default: whether the stored `end` belongs to the range. */\n readonly bounds?: RangeBounds | undefined;\n /** What an end before its start does: swapped (default) or an error. */\n readonly reversed?: \"swap\" | \"error\" | undefined;\n /** Whether a start equal to its end is allowed when that holds nothing (half-open). */\n readonly allowEmpty?: boolean | undefined;\n readonly minSpan?: S | undefined;\n readonly maxSpan?: S | undefined;\n}\n\n/**\n * Two ends as typed, made into a range: no range (both open), an ordered\n * range (`swapped` when the ends changed places), or refused with why.\n */\nexport type RangeReading<T, F extends object> =\n | { readonly kind: \"none\" }\n | {\n readonly kind: \"range\";\n readonly range: Range<T, F>;\n readonly swapped: boolean;\n }\n | { readonly kind: \"unreadable\"; readonly reason: \"reversed\" | \"empty\" };\n\n/** A range from its parts. The one place a `Range` is built, so its flags sit beside the ends. */\nfunction rangeOf<T, F extends object>(\n start: T | null,\n end: T | null,\n flags: F,\n): Range<T, F> {\n return { ...flags, start, end };\n}\n\n/** `range`'s own flags, without its ends. */\nexport function rangeFlags<T, F extends object>(range: Range<T, F>): F {\n const flags: Record<string, unknown> = { ...range };\n delete flags.start;\n delete flags.end;\n // What is left of a `Range<T, F>` without its ends is its `F`.\n return flags as F;\n}\n\n/** `end` as stored, for a range with `bounds`: the kind's `toStoredEnd` for a half-open one. */\nfunction storedEnd<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n end: T,\n bounds: RangeBounds,\n context: C,\n): T {\n return bounds === \"[)\" && kind.toStoredEnd !== undefined\n ? kind.toStoredEnd(end, context)\n : end;\n}\n\n/**\n * Makes two ends as shown into the stored range. Both open is no range; one\n * open end keeps the kind's `openFlags`. Two present ends are oriented by\n * the kind: reversed ends are swapped (the default) or refused with\n * `\"reversed\"`. The end is then stored through `toStoredEnd` for a\n * half-open range, and a half-open range whose start is its stored end\n * holds nothing, so it is refused with `\"empty\"` unless `allowEmpty`.\n */\nexport function orderRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n start: T | null,\n end: T | null,\n options: RangeOptions<S>,\n context: C,\n): RangeReading<T, F> {\n const bounds = options.bounds ?? \"[)\";\n if (start === null && end === null) {\n return { kind: \"none\" };\n }\n if (start === null || end === null) {\n return {\n kind: \"range\",\n range: rangeOf(\n start,\n end === null ? null : storedEnd(kind, end, bounds, context),\n kind.openFlags,\n ),\n swapped: false,\n };\n }\n let first = start;\n let last = end;\n let orientation = kind.orient(first, last, context);\n const swapped = orientation.kind === \"reversed\";\n if (swapped) {\n if (options.reversed === \"error\") {\n return { kind: \"unreadable\", reason: \"reversed\" };\n }\n [first, last] = [end, start];\n orientation = kind.orient(first, last, context);\n }\n if (orientation.kind === \"reversed\") {\n return { kind: \"unreadable\", reason: \"reversed\" };\n }\n const stored = storedEnd(kind, last, bounds, context);\n if (\n bounds === \"[)\" &&\n options.allowEmpty !== true &&\n kind.compare(first, stored) === 0\n ) {\n return { kind: \"unreadable\", reason: \"empty\" };\n }\n return {\n kind: \"range\",\n range: rangeOf(first, stored, orientation.flags),\n swapped,\n };\n}\n\n/** The end a stored range shows: the kind's `toShownEnd` for a half-open one. */\nexport function shownEnd<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n bounds: RangeBounds,\n context: C,\n): T | null {\n const { end } = range;\n return end !== null && bounds === \"[)\" && kind.toShownEnd !== undefined\n ? kind.toShownEnd(end, context)\n : end;\n}\n\n/** From `range`'s start to its stored end, by the kind; `null` while an end is open. */\nexport function rangeSpan<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n context: C,\n): S | null {\n const { start, end } = range;\n return start === null || end === null\n ? null\n : kind.span(start, end, rangeFlags(range), context);\n}\n\n/**\n * Whether `value` lies in `range`. An open end reaches as far as values go.\n * A range whose stored end comes before its start (a time range over\n * midnight) wraps: it holds what comes from its start on, and what comes\n * before its end.\n */\nexport function rangeIncludes<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n value: T,\n bounds: RangeBounds,\n): boolean {\n const { start, end } = range;\n const fromStart = start === null || kind.compare(value, start) >= 0;\n const toEnd =\n end === null ||\n (bounds === \"[)\"\n ? kind.compare(value, end) < 0\n : kind.compare(value, end) <= 0);\n const wraps = start !== null && end !== null && kind.compare(end, start) < 0;\n return wraps ? fromStart || toEnd : fromStart && toEnd;\n}\n\n/** Whether `value` is a rule rather than fixed ends. */\nexport function isRelativeRange<T, F extends object, R>(\n value: Range<T, F> | RelativeRange<R>,\n): value is RelativeRange<R> {\n return \"rule\" in value;\n}\n\n/**\n * The ends `value` stands for now: itself, or its rule resolved by the\n * kind. Throws a `TypeError` for a rule when the kind has no `resolve`.\n */\nexport function resolveRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n value: RangeValue<T, F, R>,\n context: C,\n): Range<T, F> {\n // `RangeValue` is one of the two members, whatever `R` is.\n const either = value as Range<T, F> | RelativeRange<R>;\n if (!isRelativeRange(either)) {\n return either;\n }\n if (kind.resolve === undefined) {\n throw new TypeError(\"This range kind has no rules to resolve.\");\n }\n return kind.resolve(either.rule, context);\n}\n\n/** Whether `a` and `b` are the same plain data: primitives by `Object.is`, arrays and objects key by key. */\nfunction samePlainData(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null ||\n Array.isArray(a) !== Array.isArray(b)\n ) {\n return false;\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => key in right && samePlainData(left[key], right[key]))\n );\n}\n\n/**\n * Whether two ranges are one: the same ends by the kind's `compare`, and\n * the same flags; or two rules the kind's `sameRule` calls one (equal plain\n * data without it), so a rule written inline, a new object each render,\n * is still the value held.\n */\nexport function sameRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n a: RangeValue<T, F, R>,\n b: RangeValue<T, F, R>,\n): boolean {\n const left = a as Range<T, F> | RelativeRange<R>;\n const right = b as Range<T, F> | RelativeRange<R>;\n if (isRelativeRange(left) || isRelativeRange(right)) {\n return (\n isRelativeRange(left) &&\n isRelativeRange(right) &&\n (kind.sameRule ?? samePlainData)(left.rule, right.rule)\n );\n }\n const sameEnd = (x: T | null, y: T | null) =>\n x === null || y === null ? x === y : kind.compare(x, y) === 0;\n const leftFlags = rangeFlags(left) as Record<string, unknown>;\n const rightFlags = rangeFlags(right) as Record<string, unknown>;\n const keys = Object.keys(leftFlags);\n return (\n sameEnd(left.start, right.start) &&\n sameEnd(left.end, right.end) &&\n keys.length === Object.keys(rightFlags).length &&\n keys.every((key) => Object.is(leftFlags[key], rightFlags[key]))\n );\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport type { Range, RelativeRange } from \"../range/range\";\nimport {\n addDays,\n addMonths,\n dateParts,\n startOfMonth,\n type PlainDate,\n type Weekday,\n} from \"./values\";\nimport { startOfWeek } from \"./week\";\n\n/** A unit of the calendar a rule counts in. */\nexport type CalendarUnit = \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\n/**\n * A date range kept as a rule, resolved against today in a zone whenever\n * it is shown or read. Plain data: it serializes as JSON, so a saved\n * filter still means \"the last 7 days\" next month.\n */\nexport type RelativeDateRule =\n | {\n /** The unit `offset` units from the one today is in: this month (0), last month (-1). */\n readonly kind: \"period\";\n readonly unit: CalendarUnit;\n readonly offset: number;\n /** Quarters and years counted from the fiscal year's start. */\n readonly fiscal?: boolean | undefined;\n }\n | {\n /** The `count` units up to today (`includeToday`) or up to yesterday; \"next\" looks ahead from tomorrow, or from today. */\n readonly kind: \"last\" | \"next\";\n readonly unit: \"day\" | \"week\" | \"month\" | \"year\";\n readonly count: number;\n readonly includeToday: boolean;\n }\n | {\n /** From the start of the unit today is in, through today. */\n readonly kind: \"toDate\";\n readonly unit: \"week\" | \"month\" | \"quarter\" | \"year\";\n readonly fiscal?: boolean | undefined;\n };\n\n/** What a rule is resolved against. */\nexport interface DateRuleContext {\n /** Today in the input's zone. */\n readonly today: () => PlainDate;\n readonly firstDayOfWeek: Weekday;\n /** The month the fiscal year starts in, 1 to 12. */\n readonly fiscalYearStart: number;\n}\n\n/** `date` moved `count` units on (back when negative); months clamp to the month's length. */\nfunction addUnits(\n date: PlainDate,\n unit: CalendarUnit,\n count: number,\n): PlainDate {\n switch (unit) {\n case \"day\":\n return addDays(date, count);\n case \"week\":\n return addDays(date, count * 7);\n case \"month\":\n return addMonths(date, count);\n case \"quarter\":\n return addMonths(date, count * 3);\n case \"year\":\n return addMonths(date, count * 12);\n }\n}\n\n/** The first day of the `unit` `date` is in; quarters and years from the fiscal start when `fiscal`. */\nfunction startOfUnit(\n date: PlainDate,\n unit: CalendarUnit,\n context: DateRuleContext,\n fiscal: boolean,\n): PlainDate {\n if (unit === \"day\") {\n return date;\n }\n if (unit === \"week\") {\n return startOfWeek(date, context.firstDayOfWeek);\n }\n const month = startOfMonth(date);\n const first = fiscal ? context.fiscalYearStart : 1;\n const intoYear = (dateParts(date).month - first + 12) % 12;\n switch (unit) {\n case \"month\":\n return month;\n case \"quarter\":\n return addMonths(month, -(intoYear % 3));\n case \"year\":\n return addMonths(month, -intoYear);\n }\n}\n\n/**\n * The days a rule stands for at `context.today()`, half-open:\n *\n * - `period`: the unit `offset` units from the one today is in (a week by\n * `firstDayOfWeek`; a quarter or year from `fiscalYearStart` when\n * `fiscal`).\n * - `last`: the `count` units up to tomorrow with `includeToday`, else up\n * to today; `next`: the `count` units from tomorrow, or from today with\n * `includeToday`. Months clamp to the month's length.\n * - `toDate`: from the start of the unit today is in through today.\n */\nexport function resolveDateRule(\n rule: RelativeDateRule,\n context: DateRuleContext,\n): Range<PlainDate> {\n const today = context.today();\n const tomorrow = addDays(today, 1);\n switch (rule.kind) {\n case \"period\": {\n const start = addUnits(\n startOfUnit(today, rule.unit, context, rule.fiscal === true),\n rule.unit,\n rule.offset,\n );\n return { start, end: addUnits(start, rule.unit, 1) };\n }\n case \"last\": {\n const end = rule.includeToday ? tomorrow : today;\n return { start: addUnits(end, rule.unit, -rule.count), end };\n }\n case \"next\": {\n const start = rule.includeToday ? today : tomorrow;\n return { start, end: addUnits(start, rule.unit, rule.count) };\n }\n case \"toDate\":\n return {\n start: startOfUnit(today, rule.unit, context, rule.fiscal === true),\n end: tomorrow,\n };\n }\n}\n\n/** Whether two rules stand for the same days, compared by value; `fiscal` absent is false. */\nexport function sameRule(a: RelativeDateRule, b: RelativeDateRule): boolean {\n switch (a.kind) {\n case \"period\":\n return (\n b.kind === \"period\" &&\n a.unit === b.unit &&\n a.offset === b.offset &&\n (a.fiscal === true) === (b.fiscal === true)\n );\n case \"last\":\n case \"next\":\n return (\n b.kind === a.kind &&\n a.unit === b.unit &&\n a.count === b.count &&\n a.includeToday === b.includeToday\n );\n case \"toDate\":\n return (\n b.kind === \"toDate\" &&\n a.unit === b.unit &&\n (a.fiscal === true) === (b.fiscal === true)\n );\n }\n}\n\nconst UNITS: readonly string[] = [\"day\", \"week\", \"month\", \"quarter\", \"year\"];\n\nfunction isInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value);\n}\n\n/**\n * Whether `value` is a rule, as read back from JSON: the right kind, a\n * unit that kind takes, whole numbers, `count` not negative. For checking\n * a stored filter before using it.\n */\nexport function isRelativeDateRule(value: unknown): value is RelativeDateRule {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const rule = value as Record<string, unknown>;\n const fiscal = rule.fiscal === undefined || typeof rule.fiscal === \"boolean\";\n const unit = typeof rule.unit === \"string\" ? rule.unit : \"\";\n switch (rule.kind) {\n case \"period\":\n return UNITS.includes(unit) && isInteger(rule.offset) && fiscal;\n case \"last\":\n case \"next\":\n return (\n unit !== \"quarter\" &&\n UNITS.includes(unit) &&\n isInteger(rule.count) &&\n rule.count >= 0 &&\n typeof rule.includeToday === \"boolean\"\n );\n case \"toDate\":\n return unit !== \"day\" && UNITS.includes(unit) && fiscal;\n default:\n return false;\n }\n}\n\n/** A preset: a rule (kept as the rule) or fixed ends; a rule's label comes from the messages when absent. */\nexport interface DatePreset<V> {\n readonly id: string;\n readonly label?: string | undefined;\n readonly value: V;\n}\n\n/** A preset that stores `rule` as the value, named by `label` or `messages.relativeRangeLabel`. */\nexport function relativePreset(\n id: string,\n rule: RelativeDateRule,\n label?: string,\n): DatePreset<RelativeRange<RelativeDateRule>> {\n return {\n id,\n ...(label === undefined ? {} : { label }),\n value: { kind: \"relative\", rule },\n };\n}\n\n/**\n * The presets most date range inputs want, each a rule: today, yesterday,\n * this week, the last 7 days (today included), this month, last month,\n * this quarter and year to date. A range input shows none unless it is\n * given a list.\n */\nexport const commonDatePresets: readonly DatePreset<\n RelativeRange<RelativeDateRule>\n>[] = [\n relativePreset(\"today\", { kind: \"period\", unit: \"day\", offset: 0 }),\n relativePreset(\"yesterday\", { kind: \"period\", unit: \"day\", offset: -1 }),\n relativePreset(\"thisWeek\", { kind: \"period\", unit: \"week\", offset: 0 }),\n relativePreset(\"last7Days\", {\n kind: \"last\",\n unit: \"day\",\n count: 7,\n includeToday: true,\n }),\n relativePreset(\"thisMonth\", { kind: \"period\", unit: \"month\", offset: 0 }),\n relativePreset(\"lastMonth\", { kind: \"period\", unit: \"month\", offset: -1 }),\n relativePreset(\"thisQuarter\", { kind: \"period\", unit: \"quarter\", offset: 0 }),\n relativePreset(\"yearToDate\", { kind: \"toDate\", unit: \"year\" }),\n];\n\n/** What a preset is called: its own label, a rule's from the messages, else its id. */\nexport function datePresetLabel<V>(\n preset: DatePreset<V>,\n messages: FormsMessages,\n): string {\n if (preset.label !== undefined) {\n return preset.label;\n }\n const { value } = preset;\n return typeof value === \"object\" &&\n value !== null &&\n \"rule\" in value &&\n isRelativeDateRule(value.rule)\n ? messages.relativeRangeLabel(value.rule)\n : preset.id;\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n resolveRange,\n type NoFlags,\n type Range,\n type RangeBounds,\n type RangeKind,\n type RangeValue,\n} from \"../range/range\";\nimport type { SpanFormatter } from \"../range/rules\";\nimport { dateTimeFormat, formatDate, formatTime } from \"./format\";\nimport {\n resolveDateRule,\n sameRule,\n type DateRuleContext,\n type RelativeDateRule,\n} from \"./relative\";\nimport {\n addDays,\n compareDates,\n compareDateTimes,\n compareInstants,\n compareTimes,\n daysBetween,\n epochOfInstant,\n epochOfWallClock,\n minutesOfDay,\n plainDateTime,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\nimport {\n exactInstantOf,\n startOfDayIn,\n type TimeZoneDisambiguation,\n} from \"./zone\";\n\n/** A range of days, stored half-open: `end` is the day after the last. */\nexport type DateRange = Range<PlainDate>;\n\n/** A time range's flag: its end is on the day after its start (22:00 to 06:00). */\nexport interface OvernightFlags {\n readonly overnight: boolean;\n}\n\n/** A range of times of day, which may cross midnight. */\nexport type TimeRange = Range<PlainTime, OvernightFlags>;\n\n/** What a time range kind is told: whether an end before its start means the next day. */\nexport interface TimeRangeContext {\n readonly overnight: boolean;\n}\n\n/** A date-time range's one zone, with what its rules need. */\nexport interface ZonedRangeContext extends DateRuleContext {\n readonly timeZone: string;\n readonly disambiguation: TimeZoneDisambiguation;\n}\n\n/**\n * Days, stored half-open: the end shown is the last day, the end stored\n * the day after, so 1 to 31 March stores `end: \"2026-04-01\"` and one day\n * shown is not an empty range. Span in days. Its rules resolve against\n * today; two rules are one when they are equal by value.\n */\nexport const dateRangeKind: RangeKind<\n PlainDate,\n NoFlags,\n number,\n DateRuleContext,\n RelativeDateRule\n> = {\n compare: compareDates,\n orient: (start, end) =>\n compareDates(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end) => daysBetween(start, end),\n compareSpans: (a, b) => a - b,\n toStoredEnd: (shown) => addDays(shown, 1),\n toShownEnd: (stored) => addDays(stored, -1),\n resolve: resolveDateRule,\n sameRule,\n};\n\n/**\n * Times of day. An end before its start is the next day (\"overnight\")\n * when the context allows it, else reversed; a range ending at midnight\n * crosses into the next day too. The end shown is the end stored\n * (09:00 to 17:00 stores `end: \"17:00\"`). Span in wall-clock minutes.\n */\nexport const timeRangeKind: RangeKind<\n PlainTime,\n OvernightFlags,\n number,\n TimeRangeContext\n> = {\n compare: compareTimes,\n orient: (start, end, { overnight }) => {\n if (compareTimes(end, start) >= 0) {\n return { kind: \"ordered\", flags: { overnight: false } };\n }\n return overnight\n ? { kind: \"ordered\", flags: { overnight: true } }\n : { kind: \"reversed\" };\n },\n openFlags: { overnight: false },\n span: (start, end, { overnight }) =>\n minutesOfDay(end) - minutesOfDay(start) + (overnight ? 24 * 60 : 0),\n compareSpans: (a, b) => a - b,\n};\n\n/** Milliseconds between two wall clocks in a zone: 23 hours across the night clocks go forward. */\nfunction zonedSpan(\n start: PlainDateTime,\n end: PlainDateTime,\n { timeZone, disambiguation }: ZonedRangeContext,\n): number {\n return (\n epochOfInstant(exactInstantOf(end, timeZone, disambiguation)) -\n epochOfInstant(exactInstantOf(start, timeZone, disambiguation))\n );\n}\n\n/**\n * Wall clocks, measured in the range's one zone: 29 March 2026 in Berlin,\n * midnight to midnight, is 23 hours. The end shown is the end stored. A\n * rule resolves to the start of its days. Span in milliseconds.\n */\nexport const dateTimeRangeKind: RangeKind<\n PlainDateTime,\n NoFlags,\n number,\n ZonedRangeContext,\n RelativeDateRule\n> = {\n compare: compareDateTimes,\n orient: (start, end) =>\n compareDateTimes(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end, _flags, context) => zonedSpan(start, end, context),\n compareSpans: (a, b) => a - b,\n resolve: (rule, context) => {\n const { start, end } = resolveDateRule(rule, context);\n return {\n start: start === null ? null : plainDateTime(start, \"00:00\"),\n end: end === null ? null : plainDateTime(end, \"00:00\"),\n };\n },\n sameRule,\n};\n\n/**\n * Exact moments; the zone is the one they are typed in, and where a\n * rule's days start. Span in milliseconds.\n */\nexport const instantRangeKind: RangeKind<\n Instant,\n NoFlags,\n number,\n ZonedRangeContext,\n RelativeDateRule\n> = {\n compare: compareInstants,\n orient: (start, end) =>\n compareInstants(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end) => epochOfInstant(end) - epochOfInstant(start),\n compareSpans: (a, b) => a - b,\n resolve: (rule, context) => {\n const { start, end } = resolveDateRule(rule, context);\n return {\n start: start === null ? null : startOfDayIn(start, context.timeZone),\n end: end === null ? null : startOfDayIn(end, context.timeZone),\n };\n },\n sameRule,\n};\n\n/**\n * The days a date range input's value stands for now: its ends, or its\n * rule resolved against `context.today()`. For code that needs the days\n * outside an event (a grid filter at filter time), and to turn a rule\n * into fixed dates: `setValue(resolveDateRange(value, context))`.\n */\nexport function resolveDateRange(\n value: RangeValue<PlainDate, NoFlags, RelativeDateRule>,\n context: DateRuleContext,\n): DateRange {\n return resolveRange(dateRangeKind, value, context);\n}\n\n/** The times days picked in a calendar get: the start of the first day and the start of the day after the last, by default. */\nexport interface DefaultTimes {\n readonly start: PlainTime;\n readonly end: PlainTime;\n}\n\nconst MIDNIGHTS: DefaultTimes = { start: \"00:00\", end: \"00:00\" };\n\n/**\n * Days picked as a wall-clock range: the first day at `times.start`, the\n * stored end (the day after the last) at `times.end`. 29 March picked\n * alone is 29 March 00:00 to 30 March 00:00.\n */\nexport function daysToDateTimeRange(\n days: DateRange,\n times: DefaultTimes = MIDNIGHTS,\n): Range<PlainDateTime> {\n return {\n start: days.start === null ? null : plainDateTime(days.start, times.start),\n end: days.end === null ? null : plainDateTime(days.end, times.end),\n };\n}\n\n/** Days picked as a range of moments in `timeZone`, as `daysToDateTimeRange` picks the wall clocks. */\nexport function daysToInstantRange(\n days: DateRange,\n timeZone: string,\n times: DefaultTimes = MIDNIGHTS,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): Range<Instant> {\n const { start, end } = daysToDateTimeRange(days, times);\n return {\n start:\n start === null ? null : exactInstantOf(start, timeZone, disambiguation),\n end: end === null ? null : exactInstantOf(end, timeZone, disambiguation),\n };\n}\n\n/** How a range writes its display text. */\nexport interface RangeTextOptions {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n readonly displayFormat?: Intl.DateTimeFormatOptions | undefined;\n}\n\n/**\n * A date range as display mode writes it, inclusive: `formatRange` of the\n * start and the end shown (\"Mar 1 – 31, 2026\"), one day once (\"Mar 14,\n * 2026\"), and an open end as `messages.rangeFrom` or `rangeUpTo`.\n */\nexport function formatDateRange(\n range: DateRange,\n options: RangeTextOptions & { readonly bounds?: RangeBounds | undefined },\n): string {\n const { locale, messages, displayFormat } = options;\n const write = (date: PlainDate) => formatDate(date, locale, displayFormat);\n const { start } = range;\n const end =\n range.end !== null && (options.bounds ?? \"[)\") === \"[)\"\n ? addDays(range.end, -1)\n : range.end;\n if (start === null || end === null) {\n if (start !== null) {\n return messages.rangeFrom(write(start));\n }\n return end === null ? \"\" : messages.rangeUpTo(write(end));\n }\n if (compareDates(start, end) === 0) {\n return write(start);\n }\n const at = (date: PlainDate) =>\n epochOfWallClock(plainDateTime(date, \"00:00\"));\n return dateTimeFormat(locale, {\n ...(displayFormat ?? { dateStyle: \"medium\" }),\n timeZone: \"UTC\",\n }).formatRange(at(start), at(end));\n}\n\n/**\n * A time range as display mode writes it: the two times joined by\n * `messages.rangeSeparator`, with `messages.rangeNextDay` after an\n * overnight end (\"22:00 – 06:00 +1\"); an open end as `rangeFrom` or\n * `rangeUpTo`. `formatRange` is not used: for times on two days it writes\n * the dates too.\n */\nexport function formatTimeRange(\n range: TimeRange,\n options: RangeTextOptions,\n): string {\n const { locale, messages, displayFormat } = options;\n const write = (time: PlainTime) => formatTime(time, locale, displayFormat);\n const { start, end } = range;\n if (start === null || end === null) {\n if (start !== null) {\n return messages.rangeFrom(write(start));\n }\n return end === null ? \"\" : messages.rangeUpTo(write(end));\n }\n const text = `${write(start)} ${messages.rangeSeparator} ${write(end)}`;\n return range.overnight ? `${text} ${messages.rangeNextDay}` : text;\n}\n\n/** A length of time for span limits, a day being 24 hours: `{ days: 31 }`, `{ hours: 1 }`. */\nexport interface DurationLike {\n readonly weeks?: number | undefined;\n readonly days?: number | undefined;\n readonly hours?: number | undefined;\n readonly minutes?: number | undefined;\n}\n\n/** `duration` in minutes. */\nfunction minutesIn(duration: DurationLike): number {\n return (\n (duration.weeks ?? 0) * 7 * 24 * 60 +\n (duration.days ?? 0) * 24 * 60 +\n (duration.hours ?? 0) * 60 +\n (duration.minutes ?? 0)\n );\n}\n\n/**\n * `duration` in the span unit of a range kind, for `minSpan` and\n * `maxSpan`: days for a date range, minutes for a time range,\n * milliseconds for a date-time or instant range.\n */\nexport function spanOf(\n duration: DurationLike,\n unit: \"day\" | \"minute\" | \"millisecond\",\n): number {\n const minutes = minutesIn(duration);\n switch (unit) {\n case \"day\":\n return minutes / (24 * 60);\n case \"minute\":\n return minutes;\n case \"millisecond\":\n return minutes * 60_000;\n }\n}\n\n/** A number of days as words in the validator's locale: \"31 days\", \"31 Tage\". A `SpanFormatter` for date ranges. */\nexport const formatDaySpan: SpanFormatter<number> = (days, { locale }) =>\n new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit: \"day\",\n unitDisplay: \"long\",\n }).format(days);\n\n/**\n * A length of time in milliseconds as words, through `Intl.DurationFormat`\n * with `style: \"short\"`: hours and minutes under 48 hours (\"8 hr\", \"1 hr,\n * 30 min\"), days and hours from 48 (\"3 days, 2 hr\"). A `SpanFormatter`\n * for date-time and instant ranges; a time range's minutes times 60,000.\n */\nexport const formatTimeSpan: SpanFormatter<number> = (\n milliseconds,\n { locale },\n) => {\n const minutes = Math.round(Math.abs(milliseconds) / 60_000);\n const hours = Math.floor(minutes / 60);\n const parts =\n hours >= 48\n ? { days: Math.floor(hours / 24), hours: hours % 24 }\n : { hours, minutes: minutes % 60 };\n return new Intl.DurationFormat(locale, { style: \"short\" }).format(\n minutes === 0 ? { minutes: 0 } : parts,\n );\n};\n","import type { FieldState } from \"../field/state\";\nimport { localeKey } from \"../localeKey\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport type { Validator } from \"../validation/validators\";\nimport { cleanDateText, foldWord } from \"./text\";\n\n/** The unit a duration's value is held in. */\nexport type DurationUnit = \"millisecond\" | \"second\" | \"minute\" | \"hour\";\n\n/** How a duration is written: `\"units\"` (\"1h 30m\"), `\"clock\"` (\"1:30\") or `\"decimal\"` hours (\"1.5\"). */\nexport type DurationNotation = \"units\" | \"clock\" | \"decimal\";\n\n/** How a duration field reads and writes. */\nexport interface DurationOptions {\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n /** The unit the value is held in; `\"minute\"` by default, so timesheet values stay whole. */\n readonly valueUnit?: DurationUnit | undefined;\n /** What a bare number means: `\"hour\"` by default, so \"1.5\" is an hour and a half. */\n readonly inputUnit?: \"minute\" | \"hour\" | undefined;\n /** The smallest part that can be typed; finer parts round half up to it. `\"minute\"` by default. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n /** How the value is written; `\"units\"` by default. */\n readonly notation?: DurationNotation | undefined;\n /** How many hours a day (`d`) is: 24 by default, 8 for a working day. */\n readonly hoursPerDay?: number | undefined;\n /** Whether a duration may be negative. */\n readonly allowNegative?: boolean | undefined;\n}\n\n/** What a duration text reads as: nothing, a value in the value unit, or why it cannot be read. */\nexport type DurationReading =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"duration\"; readonly value: number }\n | { readonly kind: \"unreadable\"; readonly reason: \"negative\" | \"unreadable\" };\n\nconst MS: Readonly<Record<DurationUnit | \"day\", number>> = {\n millisecond: 1,\n second: 1000,\n minute: 60_000,\n hour: 3_600_000,\n day: 86_400_000,\n};\n\ntype PartUnit = \"day\" | \"hour\" | \"minute\" | \"second\";\n\n/** The unit a bare number after a part with `unit` means: minutes after hours (\"1h30\"). */\nconst NEXT_UNIT: Readonly<Record<PartUnit, PartUnit | null>> = {\n day: \"hour\",\n hour: \"minute\",\n minute: \"second\",\n second: null,\n};\n\nconst ENGLISH_UNITS: Readonly<Record<string, PartUnit>> = {\n d: \"day\",\n day: \"day\",\n days: \"day\",\n h: \"hour\",\n hr: \"hour\",\n hrs: \"hour\",\n hour: \"hour\",\n hours: \"hour\",\n m: \"minute\",\n min: \"minute\",\n mins: \"minute\",\n minute: \"minute\",\n minutes: \"minute\",\n s: \"second\",\n sec: \"second\",\n secs: \"second\",\n second: \"second\",\n seconds: \"second\",\n};\n\n/** The words a locale writes for each unit, and between parts. */\ninterface DurationWords {\n readonly units: ReadonlyMap<string, PartUnit>;\n /** Words that join parts (\"and\", \"و\"), passed over. */\n readonly joiners: ReadonlySet<string>;\n readonly decimal: string;\n}\n\nconst wordsByLocale = new Map<string, DurationWords>();\n\n/** Unit words from `Intl.NumberFormat`'s unit style, narrow to long, singular and plural; joiners from `Intl.ListFormat`. */\nfunction wordsOf(locale: Intl.LocalesArgument): DurationWords {\n const key = localeKey(locale);\n const known = wordsByLocale.get(key);\n if (known !== undefined) {\n return known;\n }\n const units = new Map<string, PartUnit>(Object.entries(ENGLISH_UNITS));\n for (const unit of [\"day\", \"hour\", \"minute\", \"second\"] as const) {\n for (const unitDisplay of [\"narrow\", \"short\", \"long\"] as const) {\n const format = new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit,\n unitDisplay,\n });\n for (const count of [1, 2, 5]) {\n for (const part of format.formatToParts(count)) {\n if (part.type === \"unit\") {\n units.set(foldWord(part.value.trim()), unit);\n }\n }\n }\n }\n }\n const joiners = new Set<string>();\n for (const style of [\"narrow\", \"short\", \"long\"] as const) {\n const parts = new Intl.ListFormat(locale, { type: \"unit\", style })\n .formatToParts([\"1\", \"2\", \"3\"])\n .concat(\n new Intl.ListFormat(locale, {\n type: \"conjunction\",\n style,\n }).formatToParts([\"1\", \"2\"]),\n );\n for (const part of parts) {\n for (const word of part.value.match(/\\p{L}+/gu) ?? []) {\n joiners.add(foldWord(word));\n }\n }\n }\n const decimal =\n new Intl.NumberFormat(locale)\n .formatToParts(1.5)\n .find((part) => part.type === \"decimal\")?.value ?? \".\";\n const words = { units, joiners, decimal };\n wordsByLocale.set(key, words);\n return words;\n}\n\nconst CLOCK = /^(\\d+):(\\d{2})(?::(\\d{2}))?$/;\nconst BARE = /^\\d+(?:\\.\\d+)?$/;\nconst PART = /(\\d+(?:\\.\\d+)?)|(\\p{L}[\\p{L}\\p{M}]*\\.?)/gu;\n\n/** Milliseconds a units text (\"1h 30m\", \"2d 4h\", \"1h30\") stands for; `null` for text that is not one. */\nfunction unitsMilliseconds(\n text: string,\n words: DurationWords,\n hoursPerDay: number,\n): number | null {\n const tokens = [...text.matchAll(PART)];\n if (tokens.length === 0) {\n return null;\n }\n // Only spaces and commas may sit between the numbers and words.\n if (text.replace(PART, \"\").replace(/[\\s,]/g, \"\") !== \"\") {\n return null;\n }\n const size = (unit: PartUnit) =>\n unit === \"day\" ? hoursPerDay * MS.hour : MS[unit];\n let total = 0;\n let pending: number | null = null;\n let last: PartUnit | null = null;\n for (const [, number, word] of tokens) {\n if (number !== undefined) {\n if (pending !== null) {\n return null;\n }\n pending = Number(number);\n continue;\n }\n const folded = foldWord(word ?? \"\");\n const unit = words.units.get(folded);\n if (unit !== undefined && pending !== null) {\n total += pending * size(unit);\n pending = null;\n last = unit;\n } else if (pending !== null || !words.joiners.has(folded)) {\n return null;\n }\n }\n if (pending !== null) {\n const next = last === null ? null : NEXT_UNIT[last];\n if (next === null) {\n return null;\n }\n total += pending * size(next);\n }\n return last === null ? null : total;\n}\n\n/** `ms` rounded half up to the precision, then held in the value unit. */\nfunction toValue(ms: number, options: DurationOptions): number {\n const step = options.precision === \"second\" ? MS.second : MS.minute;\n const rounded = Math.sign(ms) * Math.round(Math.abs(ms) / step) * step;\n return rounded / MS[options.valueUnit ?? \"minute\"] + 0;\n}\n\n/**\n * Reads a duration: `units` (\"1h 30m\", \"1h30m\", \"90m\", \"2d 4h\", and \"1h30\",\n * a bare number after an hour being minutes; unit words in the locale or\n * English, any case; minutes over 59 allowed), `clock` (\"1:30\", \"26:15\",\n * seconds optional; minutes and seconds up to 59), or a bare number in\n * `inputUnit` (hours by default: \"1.5\" is 90 minutes). Digits in any\n * script; the locale's decimal separator or \".\"; `d` is `hoursPerDay`\n * hours. A sign only with `allowNegative`. The value is rounded half up to\n * the precision and held in `valueUnit`.\n */\nexport function parseDuration(\n text: string,\n options: DurationOptions = {},\n): DurationReading {\n const words = wordsOf(options.locale);\n let clean = cleanDateText(text).replace(/\\u{2212}/gu, \"-\");\n if (words.decimal !== \".\") {\n clean = clean.replaceAll(\n new RegExp(\n `(\\\\d)${words.decimal.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}(\\\\d)`,\n \"gu\",\n ),\n \"$1.$2\",\n );\n }\n if (clean === \"\") {\n return { kind: \"empty\" };\n }\n const negative = clean.startsWith(\"-\");\n const body = negative ? clean.slice(1).trim() : clean;\n if (negative && options.allowNegative !== true) {\n return { kind: \"unreadable\", reason: \"negative\" };\n }\n const ms = millisecondsOf(body, words, options);\n if (ms === null || !Number.isFinite(ms) || ms > Number.MAX_SAFE_INTEGER) {\n return { kind: \"unreadable\", reason: \"unreadable\" };\n }\n return { kind: \"duration\", value: toValue(negative ? -ms : ms, options) };\n}\n\n/** Milliseconds an unsigned duration text stands for, as a clock, a bare number or units; `null` for none. */\nfunction millisecondsOf(\n text: string,\n words: DurationWords,\n options: DurationOptions,\n): number | null {\n const clock = CLOCK.exec(text);\n if (clock !== null) {\n const [, hours = \"0\", minutes = \"0\", seconds = \"0\"] = clock;\n return Number(minutes) > 59 || Number(seconds) > 59\n ? null\n : Number(hours) * MS.hour +\n Number(minutes) * MS.minute +\n Number(seconds) * MS.second;\n }\n if (BARE.test(text)) {\n return Number(text) * MS[options.inputUnit ?? \"hour\"];\n }\n return unitsMilliseconds(text, words, options.hoursPerDay ?? 24);\n}\n\n/**\n * Writes a duration held in `valueUnit`, rounded to the precision:\n * `\"units\"` through `Intl.DurationFormat` with `style: \"narrow\"` (\"1h\n * 30m\" in `en-US`; hours are not gathered into days), `\"clock\"` as hours\n * and minutes (\"1:30\", \"26:15\", seconds with `precision: \"second\"`), or\n * `\"decimal\"` hours with up to two fraction digits (\"1.5\", \"1,5\").\n */\nexport function formatDuration(\n value: number,\n options: DurationOptions = {},\n): string {\n const { locale } = options;\n const step = options.precision === \"second\" ? MS.second : MS.minute;\n const ms = value * MS[options.valueUnit ?? \"minute\"];\n const size = Math.round(Math.abs(ms) / step) * step;\n const sign = ms < 0 && size > 0 ? -1 : 1;\n const hours = Math.floor(size / MS.hour);\n const minutes = Math.floor((size % MS.hour) / MS.minute);\n const seconds = Math.floor((size % MS.minute) / MS.second);\n switch (options.notation ?? \"units\") {\n case \"units\": {\n const parts =\n options.precision === \"second\" && seconds > 0\n ? { hours, minutes, seconds }\n : { hours, minutes };\n return new Intl.DurationFormat(locale, {\n style: \"narrow\",\n ...(size === 0 ? { minutesDisplay: \"always\" } : {}),\n }).format(\n Object.fromEntries(\n Object.entries(parts).map(([unit, count]) => [unit, sign * count]),\n ),\n );\n }\n case \"clock\": {\n const two = new Intl.NumberFormat(locale, {\n minimumIntegerDigits: 2,\n useGrouping: false,\n });\n const hour = new Intl.NumberFormat(locale, { useGrouping: false });\n const clock = `${hour.format(hours)}:${two.format(minutes)}${\n options.precision === \"second\" ? `:${two.format(seconds)}` : \"\"\n }`;\n return sign < 0 ? `-${clock}` : clock;\n }\n case \"decimal\":\n return new Intl.NumberFormat(locale, {\n maximumFractionDigits: 2,\n useGrouping: false,\n }).format((sign * size) / MS.hour);\n }\n}\n\n/** The example an unreadable duration's message gives: 90 minutes as the field writes them. */\nfunction example(options: DurationOptions): string {\n return formatDuration(\n 90 / (MS[options.valueUnit ?? \"minute\"] / MS.minute),\n options,\n );\n}\n\n/**\n * A duration field's own reading, `parseDuration` in the field's locale:\n * empty as `null`; \"Enter a duration of zero or more\" for a sign the\n * field takes none of; \"Enter a duration such as 1h 30m\" otherwise.\n */\nexport function durationParser(\n options: DurationOptions = {},\n): (text: string, context: ParseContext<number>) => ParseResult<number> {\n return (text, { locale, messages }) => {\n const own = { ...options, locale: options.locale ?? locale };\n const reading = parseDuration(text, own);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"duration\":\n return parsed(reading.value);\n case \"unreadable\":\n return unreadable(\n reading.reason === \"negative\"\n ? messages.durationNegative\n : messages.durationUnreadable(example(own)),\n );\n }\n };\n}\n\n/** A duration field's own writing, the same whatever the purpose: `formatDuration` in the field's locale; `\"\"` for `null`. */\nexport function durationFormatter(\n options: DurationOptions = {},\n): (value: number | null, context: FormatContext<number>) => string {\n return (value, { locale }) =>\n value === null\n ? \"\"\n : formatDuration(value, { ...options, locale: options.locale ?? locale });\n}\n\n/** `value` held in `from`, held in `to` instead: 90 minutes is 1.5 hours. */\nexport function convertDuration(\n value: number,\n from: DurationUnit,\n to: DurationUnit,\n): number {\n return (value * MS[from]) / MS[to];\n}\n\n/** A duration past `limit` on `side`, the limit written as the field writes durations, in the validator's locale. */\nfunction durationLimitRule(\n limit: number,\n side: \"min\" | \"max\",\n options: DurationOptions,\n): Validator<number> {\n return (value, { locale, messages }) => {\n if (value === null || (side === \"min\" ? value >= limit : value <= limit)) {\n return null;\n }\n const written = formatDuration(limit, {\n ...options,\n locale: options.locale ?? locale,\n });\n return side === \"min\"\n ? { text: messages.rangeUnderflow(written), code: \"rangeUnderflow\" }\n : { text: messages.rangeOverflow(written), code: \"rangeOverflow\" };\n };\n}\n\n/**\n * A duration under `min`, held in `options.valueUnit`, is\n * `messages.rangeUnderflow`, \"Enter 15m or more\", the limit written as\n * the field writes durations. Inclusive; `null` passes.\n */\nexport function minDurationRule(\n min: number,\n options: DurationOptions = {},\n): Validator<number> {\n return durationLimitRule(min, \"min\", options);\n}\n\n/** A duration over `max` is `messages.rangeOverflow`, \"Enter 8h or less\"; otherwise as `minDurationRule`. */\nexport function maxDurationRule(\n max: number,\n options: DurationOptions = {},\n): Validator<number> {\n return durationLimitRule(max, \"max\", options);\n}\n\n/** What a duration input adds to every event. */\nexport interface DurationDetails {\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The value in minutes, whatever `valueUnit` is; `null` when empty. */\n readonly minutes: number | null;\n}\n\n/** What a duration field's events carry. `options` holds the field's locale. */\nexport function durationDetails(\n state: FieldState<number>,\n options: DurationOptions,\n): DurationDetails {\n const { value } = state;\n return {\n formatted: value === null ? \"\" : formatDuration(value, options),\n minutes:\n value === null\n ? null\n : convertDuration(value, options.valueUnit ?? \"minute\", \"minute\"),\n };\n}\n","import type { ChangeCause } from \"../field/plan\";\nimport type { FieldState } from \"../field/state\";\nimport { localeKey } from \"../localeKey\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport type { Range } from \"../range/range\";\nimport { dateTimeFormat } from \"./format\";\nimport {\n dateLayout,\n formatSegments,\n layoutOf,\n segmentIndex,\n segmentSpans,\n segmentValue,\n splitSegments,\n type DateLayout,\n type LayoutShape,\n type SegmentType,\n} from \"./layout\";\nimport { monthOfName, pivotYear } from \"./reading\";\nimport { cleanDateText } from \"./text\";\nimport {\n addMonths,\n dateParts,\n epochOfWallClock,\n plainDate,\n plainDateTime,\n type PlainDate,\n} from \"./values\";\n\n/** A month: \"2026-11\". */\nexport type MonthPeriod = `${number}-${number}`;\n/** A calendar quarter: \"2026-Q3\". */\nexport type QuarterPeriod = `${number}-Q${number}`;\n/** A calendar year: \"2026\". */\nexport type YearPeriod = `${number}`;\n/** A fiscal year, named by the year it ends in unless told otherwise: \"FY2026\". */\nexport type FiscalYearPeriod = `FY${number}`;\n/** A quarter of a fiscal year: \"FY2026-Q1\". */\nexport type FiscalQuarterPeriod = `FY${number}-Q${number}`;\n/** A month of a fiscal year, P01 to P12: \"FY2026-P04\". */\nexport type FiscalMonthPeriod = `FY${number}-P${number}`;\n\n/** How long a period is. */\nexport type PeriodGranularity =\n \"month\" | \"quarter\" | \"year\" | \"fiscalMonth\" | \"fiscalQuarter\" | \"fiscalYear\";\n\n/** The value type of each granularity. */\nexport interface PeriodValues {\n readonly month: MonthPeriod;\n readonly quarter: QuarterPeriod;\n readonly year: YearPeriod;\n readonly fiscalMonth: FiscalMonthPeriod;\n readonly fiscalQuarter: FiscalQuarterPeriod;\n readonly fiscalYear: FiscalYearPeriod;\n}\n\n/** An accounting or reporting period, as a string: one of `PeriodValues`. */\nexport type Period<G extends PeriodGranularity = PeriodGranularity> =\n PeriodValues[G];\n\n/** Where a fiscal year starts and how it is named. */\nexport interface FiscalYear {\n /** The month it starts in, 1 to 12. */\n readonly start: number;\n /** Whether \"FY2026\" names the year it starts in or the year it ends in. */\n readonly namedBy: \"start\" | \"end\";\n}\n\n/** The calendar year as a fiscal year: from January, so both namings agree. */\nexport const CALENDAR_FISCAL_YEAR: FiscalYear = { start: 1, namedBy: \"end\" };\n\n/** A period's numbers: its year (the fiscal year's name for a fiscal period) and its place in it, from 1. */\nexport interface PeriodParts {\n readonly granularity: PeriodGranularity;\n readonly year: number;\n readonly index: number;\n}\n\nconst PATTERNS: Readonly<Record<PeriodGranularity, RegExp>> = {\n month: /^(\\d{4})-(\\d{2})$/,\n quarter: /^(\\d{4})-Q([1-4])$/,\n year: /^(\\d{4})$/,\n fiscalMonth: /^FY(\\d{4})-P(\\d{2})$/,\n fiscalQuarter: /^FY(\\d{4})-Q([1-4])$/,\n fiscalYear: /^FY(\\d{4})$/,\n};\n\n/** How many periods of a granularity a year holds. */\nconst PER_YEAR: Readonly<Record<PeriodGranularity, number>> = {\n month: 12,\n quarter: 4,\n year: 1,\n fiscalMonth: 12,\n fiscalQuarter: 4,\n fiscalYear: 1,\n};\n\nconst GRANULARITIES = Object.keys(PATTERNS) as PeriodGranularity[];\n\nfunction partsOf(text: string): PeriodParts | null {\n for (const granularity of GRANULARITIES) {\n const match = PATTERNS[granularity].exec(text);\n if (match !== null) {\n const year = Number(match[1]);\n const index = Number(match[2] ?? 1);\n return year >= 1 && index >= 1 && index <= PER_YEAR[granularity]\n ? { granularity, year, index }\n : null;\n }\n }\n return null;\n}\n\n/**\n * A period's granularity, year and place in that year, from 1: `2026-Q3`\n * is 2026 and 3, `FY2026-P04` fiscal year 2026 and 4. Throws a\n * `RangeError` for text that is not a period.\n */\nexport function periodParts(period: Period): PeriodParts {\n const parts = partsOf(period);\n if (parts === null) {\n throw new RangeError(`${period} is not a period`);\n }\n return parts;\n}\n\n/** The period with these numbers. Throws a `RangeError` for a year outside 1 to 9999. */\nfunction periodFrom<G extends PeriodGranularity>(\n granularity: G,\n year: number,\n index: number,\n): Period<G> {\n if (!(year >= 1 && year <= 9999)) {\n throw new RangeError(`${String(year)} is outside the years 1 to 9999`);\n }\n const y = String(year).padStart(4, \"0\");\n const texts: Record<PeriodGranularity, string> = {\n month: `${y}-${String(index).padStart(2, \"0\")}`,\n quarter: `${y}-Q${String(index)}`,\n year: y,\n fiscalMonth: `FY${y}-P${String(index).padStart(2, \"0\")}`,\n fiscalQuarter: `FY${y}-Q${String(index)}`,\n fiscalYear: `FY${y}`,\n };\n return texts[granularity] as Period<G>;\n}\n\n/** `text` as a period of `granularity` when it is one in canonical form (\"2026-11\", \"FY2026-P04\"); `null` otherwise. */\nexport function toPeriod<G extends PeriodGranularity>(\n text: string,\n granularity: G,\n): Period<G> | null {\n const parts = partsOf(text);\n return parts?.granularity === granularity ? (text as Period<G>) : null;\n}\n\n/** Whether `value` is a period in canonical form, of `granularity` when given. */\nexport function isPeriod(\n value: unknown,\n granularity?: PeriodGranularity,\n): value is Period {\n if (typeof value !== \"string\") {\n return false;\n }\n const parts = partsOf(value);\n return (\n parts !== null &&\n (granularity === undefined || parts.granularity === granularity)\n );\n}\n\n/** A period's granularity. Throws a `RangeError` for text that is not a period. */\nexport function periodGranularity(period: Period): PeriodGranularity {\n return periodParts(period).granularity;\n}\n\n/**\n * Negative when `a` comes first, 0 for the same period, positive after,\n * for two periods of one granularity; periods of different granularities\n * are ordered by their text.\n */\nexport function comparePeriods(a: Period, b: Period): number {\n const left = periodParts(a);\n const right = periodParts(b);\n if (left.granularity !== right.granularity) {\n return a < b ? -1 : 1;\n }\n return left.year - right.year || left.index - right.index;\n}\n\n/** The period `count` periods after `period` (before, when negative). */\nexport function addPeriods<G extends PeriodGranularity>(\n period: Period<G>,\n count: number,\n): Period<G> {\n const { granularity, year, index } = periodParts(period);\n const size = PER_YEAR[granularity];\n const place = year * size + index - 1 + count;\n return periodFrom(\n granularity as G,\n Math.floor(place / size),\n (place % size) + 1,\n );\n}\n\n/** The first day of the fiscal year named `name`. */\nfunction fiscalStart(name: number, fiscal: FiscalYear): PlainDate {\n const year = fiscal.namedBy === \"end\" && fiscal.start > 1 ? name - 1 : name;\n return plainDate(year, fiscal.start, 1);\n}\n\n/**\n * The days a period covers, half-open: `2026-11` is [2026-11-01,\n * 2026-12-01). A fiscal period counts from `fiscal`'s start month: with an\n * April start named by the year it ends in, `FY2026` is [2025-04-01,\n * 2026-04-01) and `FY2026-P04` is July 2025.\n */\nexport function periodRange(\n period: Period,\n fiscal: FiscalYear = CALENDAR_FISCAL_YEAR,\n): Range<PlainDate> {\n const { granularity, year, index } = periodParts(period);\n const months = (start: PlainDate, count: number) => ({\n start,\n end: addMonths(start, count),\n });\n switch (granularity) {\n case \"month\":\n return months(plainDate(year, index, 1), 1);\n case \"quarter\":\n return months(plainDate(year, (index - 1) * 3 + 1, 1), 3);\n case \"year\":\n return months(plainDate(year, 1, 1), 12);\n case \"fiscalMonth\":\n return months(addMonths(fiscalStart(year, fiscal), index - 1), 1);\n case \"fiscalQuarter\":\n return months(addMonths(fiscalStart(year, fiscal), (index - 1) * 3), 3);\n case \"fiscalYear\":\n return months(fiscalStart(year, fiscal), 12);\n }\n}\n\n/** The period of `granularity` that `date` falls in. */\nexport function periodOf<G extends PeriodGranularity>(\n date: PlainDate,\n granularity: G,\n fiscal: FiscalYear = CALENDAR_FISCAL_YEAR,\n): Period<G> {\n const { year, month } = dateParts(date);\n const intoYear = (month - fiscal.start + 12) % 12;\n const startYear = month >= fiscal.start ? year : year - 1;\n const name =\n fiscal.namedBy === \"end\" && fiscal.start > 1 ? startYear + 1 : startYear;\n switch (granularity) {\n case \"month\":\n return periodFrom(granularity, year, month);\n case \"quarter\":\n return periodFrom(granularity, year, Math.floor((month - 1) / 3) + 1);\n case \"year\":\n return periodFrom(granularity, year, 1);\n case \"fiscalMonth\":\n return periodFrom(granularity, name, intoYear + 1);\n case \"fiscalQuarter\":\n return periodFrom(granularity, name, Math.floor(intoYear / 3) + 1);\n default:\n return periodFrom(granularity, name, 1);\n }\n}\n\n/** The segment holding a granularity's place in its year. */\nconst PLACE_SEGMENT: Readonly<Record<PeriodGranularity, SegmentType | null>> = {\n month: \"month\",\n quarter: \"quarter\",\n year: null,\n fiscalMonth: \"period\",\n fiscalQuarter: \"quarter\",\n fiscalYear: null,\n};\n\n/** How a period field lays out its segments. */\nexport interface PeriodLayoutOptions {\n readonly locale: Intl.LocalesArgument;\n readonly granularity: PeriodGranularity;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n}\n\nconst periodLayouts = new WeakMap<FormsMessages, Map<string, DateLayout>>();\n\n/**\n * How a period field lays out its segments: a month as the locale writes\n * a month and year (`11/2026`, `2026/11`), a year alone, and the others\n * with the messages' prefixes as literals: `Q3 2026`, `FY2026`,\n * `FY2026 Q1`, `FY2026 P04`.\n */\nexport function periodLayout(\n options: PeriodLayoutOptions,\n messages: FormsMessages,\n): DateLayout {\n const { granularity, locale, numberingSystem } = options;\n if (granularity === \"month\" || granularity === \"year\") {\n return dateLayout(\n { locale, fields: granularity, numberingSystem },\n messages,\n );\n }\n const key = [localeKey(locale), granularity, numberingSystem ?? \"\"].join(\"|\");\n let named = periodLayouts.get(messages);\n if (named === undefined) {\n named = new Map();\n periodLayouts.set(messages, named);\n }\n let layout = named.get(key);\n if (layout === undefined) {\n const years = dateLayout(\n { locale, fields: \"year\", numberingSystem },\n messages,\n );\n const literal = (text: string) => ({ kind: \"literal\", text }) as const;\n const segment = (type: SegmentType) => ({ kind: \"segment\", type }) as const;\n const fiscalYear = [literal(messages.fiscalYearPrefix), segment(\"year\")];\n const parts: LayoutShape[\"parts\"] =\n granularity === \"quarter\"\n ? [\n literal(messages.periodQuarterPrefix),\n segment(\"quarter\"),\n literal(\" \"),\n segment(\"year\"),\n ]\n : granularity === \"fiscalYear\"\n ? fiscalYear\n : granularity === \"fiscalQuarter\"\n ? [\n ...fiscalYear,\n literal(` ${messages.periodQuarterPrefix}`),\n segment(\"quarter\"),\n ]\n : [\n ...fiscalYear,\n literal(` ${messages.fiscalPeriodPrefix}`),\n segment(\"period\"),\n ];\n layout = layoutOf(\n {\n parts,\n widths: { quarter: 1, period: 2 },\n hourCycle: null,\n dayPeriods: years.dayPeriods,\n digits: years.digits,\n },\n messages,\n );\n named.set(key, layout);\n }\n return layout;\n}\n\n/** A period written in its layout's segments: \"11/2026\", \"Q3 2026\", \"FY2026 P04\". */\nexport function formatPeriodSegments(\n layout: DateLayout,\n period: Period,\n): string {\n const { granularity, year, index } = periodParts(period);\n const place = PLACE_SEGMENT[granularity];\n return formatSegments(\n layout,\n place === null ? { year } : { year, [place]: index },\n );\n}\n\n/**\n * A period as display mode writes it: a month by `Intl` (\"November\n * 2026\"), a year by `Intl`, the others with the messages' prefixes and the\n * locale's digits (\"Q3 2026\", \"FY2026\", \"FY2026 Q1\", \"FY2026 P04\").\n */\nexport function formatPeriod(\n period: Period,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const { granularity, year, index } = periodParts(period);\n const at = epochOfWallClock(\n plainDateTime(\n plainDate(year, granularity === \"month\" ? index : 1, 1),\n \"00:00\",\n ),\n );\n if (granularity === \"month\" || granularity === \"year\") {\n return dateTimeFormat(locale, {\n ...(granularity === \"month\" ? { month: \"long\" } : {}),\n year: \"numeric\",\n timeZone: \"UTC\",\n }).format(at);\n }\n const digits = new Intl.NumberFormat(locale, { useGrouping: false });\n const number = (value: number, width = 1) =>\n digits.format(value).padStart(width, digits.format(0));\n const fiscalYear = `${messages.fiscalYearPrefix}${number(year, 4)}`;\n switch (granularity) {\n case \"quarter\":\n return `${messages.periodQuarterPrefix}${number(index)} ${number(year, 4)}`;\n case \"fiscalYear\":\n return fiscalYear;\n case \"fiscalQuarter\":\n return `${fiscalYear} ${messages.periodQuarterPrefix}${number(index)}`;\n default:\n return `${fiscalYear} ${messages.fiscalPeriodPrefix}${number(index, 2)}`;\n }\n}\n\n/** Whether a granularity's periods are whole years, which a picker shows twelve at a time. */\nfunction isYearly(granularity: PeriodGranularity): boolean {\n return PER_YEAR[granularity] === 1;\n}\n\n/** How many years a period picker's previous and next buttons move: 1, or 12 for years. */\nexport function periodPageYears(granularity: PeriodGranularity): number {\n return isYearly(granularity) ? 12 : 1;\n}\n\n/**\n * The periods a picker shows together on the page that holds `year`: that\n * year's months, quarters or fiscal periods, or for a year granularity the\n * twelve years around it (2017 to 2028 for 2026), within 1 to 9999.\n */\nexport function periodPage<G extends PeriodGranularity>(\n granularity: G,\n year: number,\n): readonly Period<G>[] {\n if (isYearly(granularity)) {\n const first = year - ((year - 1) % 12);\n return Array.from({ length: 12 }, (_, offset) => first + offset)\n .filter((listed) => listed <= 9999)\n .map((listed) => periodFrom(granularity, listed, 1));\n }\n return Array.from({ length: PER_YEAR[granularity] }, (_, offset) =>\n periodFrom(granularity, year, offset + 1),\n );\n}\n\n/**\n * A period as a picker's button writes it, without the year its page\n * names: a month's short name by `Intl` (\"Nov\"), \"Q3\", \"P04\", or a year\n * (\"2026\", \"FY2026\"), in the locale's digits.\n */\nexport function formatPeriodPlace(\n period: Period,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const { granularity, index } = periodParts(period);\n const number = (value: number, width: number) =>\n new Intl.NumberFormat(locale, {\n useGrouping: false,\n minimumIntegerDigits: width,\n }).format(value);\n switch (granularity) {\n case \"month\":\n return dateTimeFormat(locale, { month: \"short\", timeZone: \"UTC\" }).format(\n epochOfWallClock(plainDateTime(plainDate(2026, index, 1), \"00:00\")),\n );\n case \"quarter\":\n case \"fiscalQuarter\":\n return `${messages.periodQuarterPrefix}${number(index, 1)}`;\n case \"fiscalMonth\":\n return `${messages.fiscalPeriodPrefix}${number(index, 2)}`;\n default:\n return formatPeriod(period, locale, messages);\n }\n}\n\n/**\n * The title of a period picker's page that holds `year`: the year\n * (\"2026\", \"FY2026\"), or for a year granularity its first and last years\n * (\"2017 – 2028\").\n */\nexport function formatPeriodPage(\n granularity: PeriodGranularity,\n year: number,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const page = periodPage(granularity, year);\n const first = page[0];\n const last = page.at(-1);\n if (first === undefined || last === undefined) {\n return \"\";\n }\n if (isYearly(granularity)) {\n return `${formatPeriod(first, locale, messages)} – ${formatPeriod(last, locale, messages)}`;\n }\n const fiscal = granularity.startsWith(\"fiscal\");\n return formatPeriod(\n periodFrom(fiscal ? \"fiscalYear\" : \"year\", year, 1),\n locale,\n messages,\n );\n}\n\n/** How a period field reads and writes. */\nexport interface PeriodFieldOptions<G extends PeriodGranularity = \"month\"> {\n readonly granularity: G;\n /** The fiscal year's start and naming; the calendar year by default. */\n readonly fiscalYear?: FiscalYear | undefined;\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n readonly numberingSystem?: string | undefined;\n /** Today in the field's zone: `t`, `+1` and `-1` count from its period, and the year pivot. */\n readonly today: () => PlainDate;\n /** `t`, `+1` and `-1` for this, next and previous period; on by default. */\n readonly shortcuts?: boolean | undefined;\n /** The segment the user is typing in, if any: a short year there is not pivoted yet. */\n readonly activeSegment?: (() => number | null) | undefined;\n}\n\n/** What a period text reads as. */\ntype PeriodReading<G extends PeriodGranularity> =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"period\"; readonly period: Period<G> }\n | {\n readonly kind: \"unreadable\";\n readonly reason: \"incomplete\" | \"yearDigits\" | \"unreadable\";\n };\n\nconst UNREADABLE = { kind: \"unreadable\", reason: \"unreadable\" } as const;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** A year typed with one, two or four digits; `null` otherwise. */\nfunction yearOf(text: string, today: PlainDate): number | null {\n if (text.length === 4) {\n return Number(text);\n }\n return text.length === 1 || text.length === 2\n ? pivotYear(Number(text), { today })\n : null;\n}\n\n/** A period from a typed year and place, or unreadable when either is wrong. */\nfunction readingOf<G extends PeriodGranularity>(\n granularity: G,\n yearText: string,\n place: number,\n today: PlainDate,\n): PeriodReading<G> {\n const year = yearOf(yearText, today);\n if (year === null || place < 1 || place > PER_YEAR[granularity]) {\n return yearText.length === 3\n ? { kind: \"unreadable\", reason: \"yearDigits\" }\n : UNREADABLE;\n }\n return { kind: \"period\", period: periodFrom(granularity, year, place) };\n}\n\n/**\n * The patterns a pasted period reads by, each giving the year and the\n * place in that order of groups, or the reverse (`placeFirst`).\n */\nfunction pastePatterns(\n granularity: PeriodGranularity,\n messages: FormsMessages,\n): readonly { readonly pattern: RegExp; readonly placeFirst: boolean }[] {\n const prefix = (ascii: string, own: string) =>\n `(?:${escapeRegExp(ascii)}|${escapeRegExp(own.toUpperCase())})`;\n const q = prefix(\"Q\", messages.periodQuarterPrefix);\n const fy = prefix(\"FY\", messages.fiscalYearPrefix);\n const p = prefix(\"P\", messages.fiscalPeriodPrefix);\n const year = String.raw`(\\d{4}|\\d{1,2})`;\n const gap = String.raw`\\s*[-/ ]?\\s*`;\n const rule = (text: string, placeFirst = false) => ({\n pattern: new RegExp(`^${text}$`, \"u\"),\n placeFirst,\n });\n switch (granularity) {\n case \"quarter\":\n return [\n rule(`${year}${gap}${q}\\\\s*([1-4])`),\n rule(`${q}\\\\s*([1-4])${gap}${year}`, true),\n rule(`([1-4])\\\\s*${q}${gap}${year}`, true),\n ];\n case \"fiscalYear\":\n return [rule(`${fy}\\\\s*${year}`)];\n case \"fiscalQuarter\":\n return [\n rule(`${fy}\\\\s*${year}${gap}${q}\\\\s*([1-4])`),\n rule(`${q}\\\\s*([1-4])${gap}${fy}\\\\s*${year}`, true),\n ];\n case \"fiscalMonth\":\n return [\n rule(`${fy}\\\\s*${year}${gap}${p}\\\\s*(\\\\d{1,2})`),\n rule(`${p}\\\\s*(\\\\d{1,2})${gap}${fy}\\\\s*${year}`, true),\n ];\n default:\n return [];\n }\n}\n\n/** A month and year pasted: \"2026-11\", \"11/2026\", \"11/26\", \"Nov 2026\", \"November 2026\". */\nfunction readMonth(\n text: string,\n layout: DateLayout,\n locale: Intl.LocalesArgument,\n today: PlainDate,\n): PeriodReading<\"month\"> {\n const numbers = /^(\\d{1,4})\\s*[-/. ]\\s*(\\d{1,4})$/u.exec(text);\n if (numbers !== null) {\n const [, first = \"\", second = \"\"] = numbers;\n const yearFirst =\n first.length === 4 ||\n (second.length !== 4 &&\n segmentIndex(layout, \"year\") < segmentIndex(layout, \"month\"));\n return yearFirst\n ? readingOf(\"month\", first, Number(second), today)\n : readingOf(\"month\", second, Number(first), today);\n }\n const named = /^(\\p{L}[\\p{L}\\p{M}]*\\.?)\\s*,?\\s*(\\d{1,4})$/u.exec(text);\n const month = named?.[1] === undefined ? null : monthOfName(named[1], locale);\n return month === null\n ? UNREADABLE\n : readingOf(\"month\", named?.[2] ?? \"\", month, today);\n}\n\n/**\n * Pasted or free period text read whole: the shortcuts (`t` this period,\n * `+1` the next, `-1` the previous), the canonical form, and the common\n * ways to write each granularity (`Q3 2026`, `3Q2026`, `FY26 P4`,\n * `Nov 2026`); one- and two-digit years pivot.\n */\nfunction readPeriodText<G extends PeriodGranularity>(\n text: string,\n options: PeriodFieldOptions<G>,\n layout: DateLayout,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): PeriodReading<G> {\n const { granularity } = options;\n const today = options.today();\n const clean = cleanDateText(text).toUpperCase();\n if (clean === \"\") {\n return { kind: \"empty\" };\n }\n const current = periodOf(today, granularity, options.fiscalYear);\n if (options.shortcuts !== false) {\n const shortcut = /^(?:(T)|([+\\-\\u{2212}])(\\d+))$/u.exec(clean);\n if (shortcut !== null) {\n const [, , sign, count = \"0\"] = shortcut;\n return {\n kind: \"period\",\n period: addPeriods(current, Number(count) * (sign === \"+\" ? 1 : -1)),\n };\n }\n }\n const canonical = toPeriod(clean, granularity);\n if (canonical !== null) {\n return { kind: \"period\", period: canonical };\n }\n if (granularity === \"year\") {\n return /^\\d{1,4}$/.test(clean)\n ? readingOf(granularity, clean, 1, today)\n : UNREADABLE;\n }\n if (granularity === \"month\") {\n return readMonth(clean, layout, locale, today) as PeriodReading<G>;\n }\n for (const { pattern, placeFirst } of pastePatterns(granularity, messages)) {\n const match = pattern.exec(clean);\n if (match !== null) {\n const [, first = \"\", second = \"\"] = match;\n const [yearText, place] = placeFirst ? [second, first] : [first, second];\n return readingOf(granularity, yearText, Number(place || 1), today);\n }\n }\n return UNREADABLE;\n}\n\n/** Segment texts read strictly: empty, incomplete while a segment is empty or the year is being typed, or the period. */\nfunction readPeriodSegments<G extends PeriodGranularity>(\n texts: readonly string[],\n options: PeriodFieldOptions<G>,\n layout: DateLayout,\n): PeriodReading<G> {\n if (texts.every((text) => text === \"\")) {\n return { kind: \"empty\" };\n }\n const yearIndex = segmentIndex(layout, \"year\");\n const yearText = texts[yearIndex] ?? \"\";\n if (\n texts.some((text) => text === \"\") ||\n (options.activeSegment?.() === yearIndex && yearText.length < 4)\n ) {\n return { kind: \"unreadable\", reason: \"incomplete\" };\n }\n const place = PLACE_SEGMENT[options.granularity];\n const placeIndex = place === null ? -1 : segmentIndex(layout, place);\n const year = String(segmentValue(layout, yearIndex, yearText) ?? \"\").padStart(\n yearText.length,\n \"0\",\n );\n return readingOf(\n options.granularity,\n year,\n placeIndex < 0\n ? 1\n : (segmentValue(layout, placeIndex, texts[placeIndex] ?? \"\") ?? 0),\n options.today(),\n );\n}\n\nfunction layoutFor<G extends PeriodGranularity>(\n options: PeriodFieldOptions<G>,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): DateLayout {\n return periodLayout(\n {\n locale: options.locale ?? locale,\n granularity: options.granularity,\n numberingSystem: options.numberingSystem,\n },\n messages,\n );\n}\n\nfunction readPeriod<G extends PeriodGranularity>(\n text: string,\n options: PeriodFieldOptions<G>,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): PeriodReading<G> {\n const layout = layoutFor(options, locale, messages);\n const texts = splitSegments(layout, text);\n if (texts !== null) {\n const strict = readPeriodSegments(texts, options, layout);\n if (strict.kind !== \"unreadable\" || strict.reason !== \"unreadable\") {\n return strict;\n }\n }\n return readPeriodText(\n text,\n options,\n layout,\n options.locale ?? locale,\n messages,\n );\n}\n\n/**\n * A period field's own reading: its segments strictly, pasted and free\n * text leniently (shortcuts, the canonical form, `Q3 2026`, `FY26 P4`,\n * `Nov 2026`); empty as `null`. Text that is no period says \"Enter a\n * period such as Q4 2026\", the current period in the field's segments.\n */\nexport function periodParser<G extends PeriodGranularity>(\n options: PeriodFieldOptions<G>,\n): (text: string, context: ParseContext<Period<G>>) => ParseResult<Period<G>> {\n return (text, { locale, messages }) => {\n const reading = readPeriod(text, options, locale, messages);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"period\":\n return parsed(reading.period);\n case \"unreadable\": {\n if (reading.reason === \"incomplete\") {\n return unreadable(messages.dateIncomplete);\n }\n if (reading.reason === \"yearDigits\") {\n return unreadable(messages.dateYearDigits);\n }\n const example = formatPeriodSegments(\n layoutFor(options, locale, messages),\n periodOf(options.today(), options.granularity, options.fiscalYear),\n );\n return unreadable(messages.periodUnreadable(example));\n }\n }\n };\n}\n\n/** A period field's own writing: the period in its segments, whatever the purpose; `\"\"` for `null`. */\nexport function periodFormatter<G extends PeriodGranularity>(\n options: Pick<\n PeriodFieldOptions<G>,\n \"granularity\" | \"locale\" | \"numberingSystem\"\n >,\n): (value: Period<G> | null, context: FormatContext<Period<G>>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatPeriodSegments(\n periodLayout(\n {\n locale: options.locale ?? locale,\n granularity: options.granularity,\n numberingSystem: options.numberingSystem,\n },\n messages,\n ),\n value,\n );\n}\n\n/** What a period input adds to every event. */\nexport interface PeriodDetails {\n /** The days the period covers, half-open. `null` when empty. */\n readonly range: Range<PlainDate> | null;\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The segment the edit was in; `null` for a paste, a pick or a change from code. */\n readonly segment: \"year\" | \"month\" | \"quarter\" | \"period\" | null;\n}\n\n/** What a period field's events carry, for its state and the event's cause. */\nexport function periodDetails<G extends PeriodGranularity>(\n state: FieldState<Period<G>>,\n cause: ChangeCause<unknown> | null,\n options: PeriodFieldOptions<G> & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): PeriodDetails {\n const { value } = state;\n const { locale, messages } = options;\n const layout = layoutFor(options, locale, messages);\n const text =\n state.draft.kind === \"text\"\n ? state.draft.text\n : value === null\n ? \"\"\n : formatPeriodSegments(layout, value);\n const at = cause?.input?.selectionStart ?? null;\n const spans =\n at === null || cause?.source === \"paste\" || cause?.source === \"drop\"\n ? null\n : segmentSpans(layout, text);\n const index =\n spans === null || at === null\n ? -1\n : spans.findIndex(([start, end]) => start <= at && at <= end);\n const type = layout.segments[index]?.type;\n return {\n range: value === null ? null : periodRange(value, options.fiscalYear),\n formatted: value === null ? \"\" : formatPeriod(value, locale, messages),\n segment:\n type === \"year\" ||\n type === \"month\" ||\n type === \"quarter\" ||\n type === \"period\"\n ? type\n : null,\n };\n}\n","import type { Validator, ValidatorContext } from \"../validation/validators\";\nimport {\n formatDate,\n formatDateTime,\n formatInstant,\n formatTime,\n} from \"./format\";\nimport {\n comparePeriods,\n formatPeriod,\n type Period,\n type PeriodGranularity,\n} from \"./period\";\nimport {\n compareDates,\n compareDateTimes,\n compareInstants,\n compareTimes,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\n\n/** How one value type orders and writes its limits. */\ninterface LimitType<V> {\n readonly compare: (a: V, b: V) => number;\n readonly write: (limit: V, context: ValidatorContext) => string;\n}\n\n/** A value before `min` is `messages.tooEarly`, after `max` `messages.tooLate`, the limit written by `type`. */\nfunction limitRule<V>(\n type: LimitType<V>,\n limit: V,\n side: \"min\" | \"max\",\n): Validator<V> {\n return (value, context) => {\n if (value === null) {\n return null;\n }\n const order = type.compare(value, limit);\n if (side === \"min\" && order < 0) {\n return {\n text: context.messages.tooEarly(type.write(limit, context)),\n code: \"tooEarly\",\n };\n }\n if (side === \"max\" && order > 0) {\n return {\n text: context.messages.tooLate(type.write(limit, context)),\n code: \"tooLate\",\n };\n }\n return null;\n };\n}\n\nconst dates = (options?: Intl.DateTimeFormatOptions): LimitType<PlainDate> => ({\n compare: compareDates,\n write: (limit, { locale }) => formatDate(limit, locale, options),\n});\n\nconst times = (options?: Intl.DateTimeFormatOptions): LimitType<PlainTime> => ({\n compare: compareTimes,\n write: (limit, { locale }) => formatTime(limit, locale, options),\n});\n\nconst dateTimes = (\n options?: Intl.DateTimeFormatOptions,\n): LimitType<PlainDateTime> => ({\n compare: compareDateTimes,\n write: (limit, { locale }) => formatDateTime(limit, locale, options),\n});\n\nconst instants = (\n timeZone: string,\n options?: Intl.DateTimeFormatOptions,\n): LimitType<Instant> => ({\n compare: compareInstants,\n write: (limit, { locale }) => formatInstant(limit, timeZone, locale, options),\n});\n\n/**\n * A day before `min` is `messages.tooEarly`, \"Enter Mar 1, 2026 or later\",\n * the limit in display form (`displayFormat`, the field's, else\n * `dateStyle: \"medium\"`) in the validator's locale. Inclusive; `null`\n * passes.\n */\nexport function minDateRule(\n min: PlainDate,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDate> {\n return limitRule(dates(displayFormat), min, \"min\");\n}\n\n/** A day after `max` is `messages.tooLate`, \"Enter Mar 31, 2026 or earlier\"; otherwise as `minDateRule`. */\nexport function maxDateRule(\n max: PlainDate,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDate> {\n return limitRule(dates(displayFormat), max, \"max\");\n}\n\n/** A time of day before `min` is `messages.tooEarly`; as `minDateRule`. */\nexport function minTimeRule(\n min: PlainTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainTime> {\n return limitRule(times(displayFormat), min, \"min\");\n}\n\n/** A time of day after `max` is `messages.tooLate`; as `maxDateRule`. */\nexport function maxTimeRule(\n max: PlainTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainTime> {\n return limitRule(times(displayFormat), max, \"max\");\n}\n\n/** A wall clock before `min` is `messages.tooEarly`; as `minDateRule`. */\nexport function minDateTimeRule(\n min: PlainDateTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDateTime> {\n return limitRule(dateTimes(displayFormat), min, \"min\");\n}\n\n/** A wall clock after `max` is `messages.tooLate`; as `maxDateRule`. */\nexport function maxDateTimeRule(\n max: PlainDateTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDateTime> {\n return limitRule(dateTimes(displayFormat), max, \"max\");\n}\n\n/** A moment before `min` is `messages.tooEarly`, the limit written in `timeZone`; as `minDateRule`. */\nexport function minInstantRule(\n min: Instant,\n timeZone: string,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<Instant> {\n return limitRule(instants(timeZone, displayFormat), min, \"min\");\n}\n\n/** A moment after `max` is `messages.tooLate`, the limit written in `timeZone`; as `maxDateRule`. */\nexport function maxInstantRule(\n max: Instant,\n timeZone: string,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<Instant> {\n return limitRule(instants(timeZone, displayFormat), max, \"max\");\n}\n\nconst periods = <G extends PeriodGranularity>(): LimitType<Period<G>> => ({\n compare: comparePeriods,\n write: (limit, { locale, messages }) => formatPeriod(limit, locale, messages),\n});\n\n/**\n * A period before `min` is `messages.tooEarly`, \"Enter Q2 2026 or later\",\n * the limit as display mode writes it, in the validator's locale.\n * Inclusive; `null` passes.\n */\nexport function minPeriodRule<G extends PeriodGranularity>(\n min: Period<G>,\n): Validator<Period<G>> {\n return limitRule(periods<G>(), min, \"min\");\n}\n\n/** A period after `max` is `messages.tooLate`; as `minPeriodRule`. */\nexport function maxPeriodRule<G extends PeriodGranularity>(\n max: Period<G>,\n): Validator<Period<G>> {\n return limitRule(periods<G>(), max, \"max\");\n}\n\n/**\n * A day `isDateDisabled` marks is `messages.dateUnavailable`, \"This date\n * isn't available\". For a wall clock, its day is checked. `null` passes.\n */\nexport function availableDateRule<V extends PlainDate | PlainDateTime>(\n isDateDisabled: (date: PlainDate) => boolean,\n): Validator<V> {\n return (value, { messages }) =>\n value !== null && isDateDisabled(value.slice(0, 10) as PlainDate)\n ? { text: messages.dateUnavailable, code: \"dateUnavailable\" }\n : null;\n}\n","import { compareDates, type PlainDate } from \"./values\";\n\n/**\n * Where picking a range of days in a calendar stands: nothing picked yet;\n * a first day chosen (the anchor), waiting for the other end while\n * `target`, the day under the pointer or focus, previews it; or a mouse or\n * pen pressed on a day and dragged to `target`. `fromAnchor` marks a press\n * made while an anchor was already set, which picks the other end even\n * when it lets go on the anchor itself.\n */\nexport type RangePick =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"anchored\";\n readonly anchor: PlainDate;\n readonly target: PlainDate;\n }\n | {\n readonly kind: \"dragging\";\n readonly anchor: PlainDate;\n readonly target: PlainDate;\n readonly fromAnchor: boolean;\n };\n\n/** The days a range covers, both ends included and in order. */\nexport interface PickedDays {\n readonly first: PlainDate;\n readonly last: PlainDate;\n}\n\n/** What can happen while a range is picked. */\nexport type RangePickAction =\n /** A day clicked, tapped, or chosen with Enter or Space. */\n | { readonly type: \"choose\"; readonly date: PlainDate }\n /** The pointer moved over a day, or focus moved to one. */\n | { readonly type: \"preview\"; readonly date: PlainDate }\n /** A mouse or pen pressed on a day. */\n | { readonly type: \"press\"; readonly date: PlainDate }\n /** That press let go. */\n | { readonly type: \"release\" }\n /** That press lost its pointer: cancelled, or its capture taken. */\n | { readonly type: \"lose\" }\n /** Escape: a range in progress is dropped. */\n | { readonly type: \"cancel\" };\n\n/** The picking state after an action, and the days it picked, if it finished a range. */\nexport interface RangePickStep {\n readonly state: RangePick;\n readonly picked: PickedDays | null;\n}\n\nconst IDLE: RangePick = { kind: \"idle\" };\n\n/** `a` and `b` as a range's first and last days, whichever comes first. */\nexport function pickedDays(a: PlainDate, b: PlainDate): PickedDays {\n return compareDates(a, b) <= 0\n ? { first: a, last: b }\n : { first: b, last: a };\n}\n\n/** The days a range in progress would cover now: anchor to target. `null` while nothing is anchored. */\nexport function rangePickPreview(state: RangePick): PickedDays | null {\n return state.kind === \"idle\" ? null : pickedDays(state.anchor, state.target);\n}\n\n/**\n * Picking a range of days after `action`. A choice sets the anchor, then\n * the other end, which finishes the range; a press and a release on\n * another day finish it in one gesture, while a release where the press\n * began leaves that day anchored, as a click would. A day `selectable`\n * refuses cannot be an end: choosing one does nothing, and a drag let go\n * over one keeps its anchor. Escape drops the range in progress.\n */\nexport function rangePickReducer(\n state: RangePick,\n action: RangePickAction,\n selectable: (date: PlainDate) => boolean,\n): RangePickStep {\n const stay: RangePickStep = { state, picked: null };\n switch (action.type) {\n case \"choose\": {\n if (state.kind === \"dragging\" || !selectable(action.date)) {\n return stay;\n }\n if (state.kind === \"idle\") {\n return {\n state: { kind: \"anchored\", anchor: action.date, target: action.date },\n picked: null,\n };\n }\n return { state: IDLE, picked: pickedDays(state.anchor, action.date) };\n }\n case \"preview\":\n return state.kind === \"idle\" || state.target === action.date\n ? stay\n : { state: { ...state, target: action.date }, picked: null };\n case \"press\":\n if (state.kind === \"anchored\") {\n return {\n state: {\n kind: \"dragging\",\n anchor: state.anchor,\n target: action.date,\n fromAnchor: true,\n },\n picked: null,\n };\n }\n return state.kind === \"idle\" && selectable(action.date)\n ? {\n state: {\n kind: \"dragging\",\n anchor: action.date,\n target: action.date,\n fromAnchor: false,\n },\n picked: null,\n }\n : stay;\n case \"release\": {\n if (state.kind !== \"dragging\") {\n return stay;\n }\n const { anchor, target, fromAnchor } = state;\n const anchored: RangePick = { kind: \"anchored\", anchor, target };\n if (!selectable(target) || (!fromAnchor && target === anchor)) {\n return { state: anchored, picked: null };\n }\n return { state: IDLE, picked: pickedDays(anchor, target) };\n }\n case \"lose\":\n if (state.kind !== \"dragging\") {\n return stay;\n }\n return {\n state: state.fromAnchor\n ? { kind: \"anchored\", anchor: state.anchor, target: state.anchor }\n : IDLE,\n picked: null,\n };\n case \"cancel\":\n return state.kind === \"idle\" ? stay : { state: IDLE, picked: null };\n }\n}\n","import type { ChangeSource } from \"../field/events\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { digitValue, isDigit } from \"../number/digits\";\nimport type { StepDirection, StepSize } from \"../number/stepNumber\";\nimport {\n joinSegments,\n maxDigits,\n segmentIndex,\n segmentValue,\n shownHour,\n splitSegments,\n writeSegment,\n type DateLayout,\n type SegmentType,\n} from \"./layout\";\nimport { dateTimeFormat } from \"./format\";\nimport { cleanDateText, foldWord } from \"./text\";\nimport { daysInMonth } from \"./values\";\n\n/**\n * Where typing in a segmented field stands:\n *\n * - `idle`: focus is elsewhere.\n * - `active`: a segment has focus and nothing is typed into it yet; a\n * digit replaces what it holds. `advanced`: typing or a separator moved\n * focus here, so a separator typed now does nothing (`3/14` and `314`\n * both work).\n * - `typing`: digits typed into a segment that can take more.\n * - `composing`: an input method owns a segment's text until it ends.\n * - `text`: the free-text box shows, for a shortcut; `before` is the\n * segments' text to go back to.\n */\nexport type SegmentEntry =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"active\";\n readonly segment: number;\n readonly advanced: boolean;\n }\n | {\n readonly kind: \"typing\";\n readonly segment: number;\n readonly digits: string;\n }\n | { readonly kind: \"composing\"; readonly segment: number }\n | { readonly kind: \"text\"; readonly before: string };\n\n/** What happened in a segmented field, as forms-dom reports it. */\nexport type SegmentAction =\n | { readonly type: \"focus\"; readonly segment: number }\n /** Characters typed into the active segment. */\n | { readonly type: \"key\"; readonly text: string }\n | { readonly type: \"backspace\" }\n | { readonly type: \"delete\" }\n /** ArrowUp and ArrowDown (`step`), PageUp and PageDown (`large`), Home and End (`edge`). */\n | {\n readonly type: \"step\";\n readonly direction: StepDirection;\n readonly size: StepSize;\n }\n | { readonly type: \"move\"; readonly to: \"next\" | \"previous\" }\n | { readonly type: \"paste\"; readonly text: string }\n | { readonly type: \"compositionStart\" }\n | { readonly type: \"compositionEnd\"; readonly text: string }\n /** The free-text box's text changed; `source` is `\"typing\"` unless given. */\n | {\n readonly type: \"textEdit\";\n readonly text: string;\n readonly source?: ChangeSource | undefined;\n }\n /** Enter: the active segment is finished before the field commits. */\n | { readonly type: \"finish\" }\n /** Focus left the field. */\n | { readonly type: \"leave\" }\n /** The field's text changed from outside: a controlled value, a revert, a clear, a commit. */\n | { readonly type: \"outside\"; readonly text: string };\n\nexport interface SegmentState {\n readonly entry: SegmentEntry;\n /** The field's text: the segments joined by the layout's literals, or the free text. */\n readonly text: string;\n}\n\n/** What the reducer needs to know about the field. */\nexport interface SegmentContext {\n readonly layout: DateLayout;\n /**\n * Where an empty segment steps from: today's year, month or day, 0 for\n * a time. An hour is given 0 to 23 and shown in the layout's cycle; the\n * day period 0 for the morning, 1 for the afternoon.\n */\n readonly reference: (segment: SegmentType) => number;\n /** The year a one- or two-digit year left in a segment means. */\n readonly pivotYear: (digits: number) => number;\n /** Whether letters and signs in a date segment open the free-text box. */\n readonly shortcuts: boolean;\n /** The field's text for a pasted or one-letter text that reads as a value, else `null`. */\n readonly readWhole: (text: string) => string | null;\n /** What ArrowUp and ArrowDown add to the minutes, snapping to it; 1 by default. */\n readonly minuteStep?: number | undefined;\n /**\n * Whether a step may leave the segments as `texts`: the renderer checks\n * them against `min` and `max`, so stepping never leaves the limits.\n * Every step is allowed without it.\n */\n readonly allows?: ((texts: readonly string[]) => boolean) | undefined;\n}\n\n/** What one action did. */\nexport interface SegmentStep {\n readonly state: SegmentState;\n /** What has focus afterwards: a segment, the free-text box, or nothing (idle). */\n readonly focus: number | \"text\" | null;\n /** What the change was, for the event; `null` when the text did not change. */\n readonly source: ChangeSource | null;\n /**\n * A one-letter free text applied at once (`t`): forms-dom reports it as\n * typed before the segments it gave, so the events name the shortcut.\n * Absent otherwise.\n */\n readonly applied?: string;\n}\n\nconst IDLE: SegmentEntry = { kind: \"idle\" };\n\nconst DATE_TYPES: ReadonlySet<SegmentType> = new Set<SegmentType>([\n \"year\",\n \"month\",\n \"day\",\n \"quarter\",\n \"period\",\n]);\n\n/** How far PageUp and PageDown step each segment. */\nconst LARGE_STEPS: Readonly<Record<SegmentType, number>> = {\n year: 10,\n month: 3,\n day: 7,\n hour: 10,\n minute: 10,\n second: 10,\n dayPeriod: 1,\n quarter: 1,\n period: 3,\n};\n\n/** Separators typed between segments, beside the layout's own literals. */\nconst SEPARATORS = \"/.-,:\";\n/** The signs that open a shortcut: plus, hyphen-minus and the minus sign. */\nconst SIGNS = \"+-\\u{2212}\";\n\nfunction focusOf(entry: SegmentEntry): number | \"text\" | null {\n switch (entry.kind) {\n case \"idle\":\n return null;\n case \"text\":\n return \"text\";\n default:\n return entry.segment;\n }\n}\n\n/** The segment typing is in, or `null`. */\nfunction segmentOf(entry: SegmentEntry): number | null {\n return entry.kind === \"active\" ||\n entry.kind === \"typing\" ||\n entry.kind === \"composing\"\n ? entry.segment\n : null;\n}\n\n/** The last date segment in typing order, where a shortcut leaves focus. */\nfunction lastDateSegment(layout: DateLayout): number {\n const last = layout.segments.findLastIndex((segment) =>\n DATE_TYPES.has(segment.type),\n );\n return Math.max(last, 0);\n}\n\n/** The field's state as it is worked on within one action. */\ninterface Draft {\n entry: SegmentEntry;\n texts: string[];\n /** The free text, while the entry is `text`. */\n free: string;\n /** A one-letter free text applied at once, if any. */\n applied: string | null;\n}\n\nfunction draftOf(state: SegmentState, layout: DateLayout): Draft {\n const texts =\n state.entry.kind === \"text\"\n ? splitSegments(layout, state.entry.before)\n : splitSegments(layout, state.text);\n return {\n entry: state.entry,\n texts: [...(texts ?? layout.segments.map(() => \"\"))],\n free: state.entry.kind === \"text\" ? state.text : \"\",\n applied: null,\n };\n}\n\nfunction textOf(draft: Draft, layout: DateLayout): string {\n return draft.entry.kind === \"text\"\n ? draft.free\n : joinSegments(layout, draft.texts);\n}\n\nfunction stepOf(\n before: SegmentState,\n draft: Draft,\n context: SegmentContext,\n source: ChangeSource,\n): SegmentStep {\n const text = textOf(draft, context.layout);\n return {\n state:\n text === before.text && draft.entry === before.entry\n ? before\n : { entry: draft.entry, text },\n focus: focusOf(draft.entry),\n source: text === before.text ? null : source,\n ...(draft.applied === null ? {} : { applied: draft.applied }),\n };\n}\n\n/** `digits` (ASCII) written in the layout's digits, leading zeros kept. */\nfunction localDigits(layout: DateLayout, digits: string): string {\n return digits.replace(\n /\\d/g,\n (digit) => layout.digits[Number(digit)] ?? digit,\n );\n}\n\n/**\n * Pads segment `index` to its width, a one- or two-digit year pivoted;\n * an empty segment, a day period and a three-digit year stay as they are.\n */\nfunction finish(draft: Draft, index: number, context: SegmentContext): void {\n const { layout } = context;\n const segment = layout.segments[index];\n const text = draft.texts[index] ?? \"\";\n const value = segmentValue(layout, index, text);\n if (segment === undefined || value === null || segment.type === \"dayPeriod\") {\n return;\n }\n if (segment.type === \"year\") {\n if (text.length <= 2) {\n draft.texts[index] = writeSegment(\n layout,\n index,\n context.pivotYear(value),\n );\n }\n return;\n }\n draft.texts[index] = writeSegment(layout, index, value);\n}\n\n/** The segment after `index` in typing order, or `index` itself at the end. */\nfunction next(layout: DateLayout, index: number): number {\n return Math.min(index + 1, layout.segments.length - 1);\n}\n\nfunction isSeparator(layout: DateLayout, char: string): boolean {\n if (/\\s/.test(char) || SEPARATORS.includes(char)) {\n return true;\n }\n return layout.parts.some(\n (part) =>\n part.kind === \"literal\" && !isDigit(char) && part.text.includes(char),\n );\n}\n\n/** Types digit `digit` (0 to 9) into the active segment. */\nfunction typeDigit(draft: Draft, digit: number, context: SegmentContext): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined || segment.type === \"dayPeriod\") {\n return;\n }\n const most = maxDigits(layout, index);\n const fits = (digits: string) => {\n const value = Number(digits);\n return (\n value <= segment.max && (digits.length < most || value >= segment.min)\n );\n };\n const buffer = draft.entry.kind === \"typing\" ? draft.entry.digits : \"\";\n let digits = `${buffer}${String(digit)}`;\n if (!fits(digits)) {\n digits = String(digit);\n if (!fits(digits)) {\n return;\n }\n }\n const complete = digits.length === most || Number(digits) * 10 > segment.max;\n if (complete) {\n draft.texts[index] = writeSegment(layout, index, Number(digits));\n const after = next(layout, index);\n draft.entry = { kind: \"active\", segment: after, advanced: after !== index };\n } else {\n draft.texts[index] = localDigits(layout, digits);\n draft.entry = { kind: \"typing\", segment: index, digits };\n }\n}\n\n/** Sets the day period from a letter: the first letter of one of the locale's, or `a` and `p`. */\nfunction typeDayPeriod(\n draft: Draft,\n char: string,\n context: SegmentContext,\n): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n if (index === null) {\n return;\n }\n const letter = foldWord(char);\n const english: readonly string[] = [\"a\", \"p\"];\n const matches = ([0, 1] as const).filter(\n (period) =>\n foldWord(layout.dayPeriods[period]).startsWith(letter) ||\n english[period] === letter,\n );\n const [only] = matches;\n if (only === undefined || matches.length > 1) {\n return;\n }\n draft.texts[index] = writeSegment(layout, index, only);\n const after = next(layout, index);\n draft.entry = { kind: \"active\", segment: after, advanced: after !== index };\n}\n\n/** Opens the free-text box with `char`, applying it at once when one letter reads as a value. */\nfunction openText(draft: Draft, char: string, context: SegmentContext): void {\n const { layout } = context;\n draft.entry = { kind: \"text\", before: joinSegments(layout, draft.texts) };\n draft.free = char;\n applyOneLetter(draft, context);\n}\n\n/** A one-letter free text that reads (`t`, `s`, `e`, an app's own word) is applied and the segments return. */\nfunction applyOneLetter(draft: Draft, context: SegmentContext): void {\n if (Array.from(draft.free).length !== 1) {\n return;\n }\n const whole = context.readWhole(draft.free);\n const texts = whole === null ? null : splitSegments(context.layout, whole);\n if (texts === null) {\n return;\n }\n draft.applied = draft.free;\n draft.texts = [...texts];\n draft.entry = {\n kind: \"active\",\n segment: lastDateSegment(context.layout),\n advanced: false,\n };\n}\n\n/** One character typed while a segment has focus. */\nfunction typeChar(draft: Draft, char: string, context: SegmentContext): void {\n const { layout } = context;\n if (draft.entry.kind === \"text\") {\n draft.free += char;\n return;\n }\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined) {\n return;\n }\n if (isDigit(char)) {\n typeDigit(draft, digitValue(char), context);\n return;\n }\n if (segment.type === \"dayPeriod\" && /\\p{L}/u.test(char)) {\n typeDayPeriod(draft, char, context);\n return;\n }\n const filled = (draft.texts[index] ?? \"\") !== \"\";\n const advanced = draft.entry.kind === \"active\" && draft.entry.advanced;\n const opensText =\n context.shortcuts &&\n DATE_TYPES.has(segment.type) &&\n (/\\p{L}/u.test(char) || SIGNS.includes(char));\n if (isSeparator(layout, char) && (!opensText || filled || advanced)) {\n if (advanced) {\n draft.entry = { kind: \"active\", segment: index, advanced: false };\n } else if (filled) {\n finish(draft, index, context);\n const after = next(layout, index);\n draft.entry = {\n kind: \"active\",\n segment: after,\n advanced: after !== index,\n };\n }\n return;\n }\n if (opensText) {\n openText(draft, char, context);\n }\n}\n\nfunction typeText(draft: Draft, text: string, context: SegmentContext): void {\n for (const char of text) {\n typeChar(draft, char, context);\n }\n}\n\n/** The days segment `day` steps within: its month's, once the month (and year) are set. */\nfunction dayLimit(texts: readonly string[], layout: DateLayout): number {\n const value = (type: SegmentType) => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const month = value(\"month\");\n if (month === null || month < 1 || month > 12) {\n return 31;\n }\n // Without a year, February may have 29 days.\n return daysInMonth(value(\"year\") ?? 2000, month);\n}\n\n/** Where a step takes segment `index` from `value`, wrapping within `low` to `high`. */\nfunction stepped(\n type: SegmentType,\n value: number,\n direction: StepDirection,\n size: StepSize,\n [low, high]: readonly [number, number],\n minuteStep: number,\n): number {\n if (size === \"edge\") {\n return direction === \"up\" ? high : low;\n }\n const count = high - low + 1;\n const wrap = (to: number) => low + ((((to - low) % count) + count) % count);\n const from = Math.min(value, high);\n if (type === \"minute\" && size === \"step\" && minuteStep > 1) {\n const snapped =\n direction === \"up\"\n ? Math.floor(from / minuteStep) * minuteStep + minuteStep\n : Math.ceil(from / minuteStep) * minuteStep - minuteStep;\n return wrap(snapped);\n }\n const amount = size === \"large\" ? LARGE_STEPS[type] : 1;\n return wrap(from + (direction === \"up\" ? amount : -amount));\n}\n\n/** The day clamped to its month's last day after the month or year changed: 31 January, month up, is 28 February. */\nfunction clampDay(draft: Draft, layout: DateLayout): void {\n const day = segmentIndex(layout, \"day\");\n const value =\n day < 0 ? null : segmentValue(layout, day, draft.texts[day] ?? \"\");\n const limit = dayLimit(draft.texts, layout);\n if (value !== null && value > limit) {\n draft.texts[day] = writeSegment(layout, day, limit);\n }\n}\n\n/** ArrowUp, ArrowDown, PageUp, PageDown, Home and End on the active segment. */\nfunction step(\n draft: Draft,\n direction: StepDirection,\n size: StepSize,\n context: SegmentContext,\n): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined) {\n return;\n }\n const { type } = segment;\n const current = segmentValue(layout, index, draft.texts[index] ?? \"\");\n const range: readonly [number, number] = [\n segment.min,\n type === \"day\" ? dayLimit(draft.texts, layout) : segment.max,\n ];\n const candidates = (): number[] => {\n if (type === \"dayPeriod\") {\n if (size === \"edge\") {\n return [direction === \"up\" ? 1 : 0];\n }\n return [current === null ? context.reference(type) : 1 - current];\n }\n if (current === null && size !== \"edge\") {\n const reference = context.reference(type);\n return [\n type === \"hour\" ? shownHour(reference, layout.hourCycle) : reference,\n ];\n }\n if (size === \"edge\") {\n // Home and End go to the limit the field allows nearest the segment's own.\n const all = Array.from(\n { length: range[1] - range[0] + 1 },\n (_, offset) => range[0] + offset,\n );\n return direction === \"up\" ? all.reverse() : all;\n }\n return [\n stepped(\n type,\n current ?? range[0],\n direction,\n size,\n range,\n context.minuteStep ?? 1,\n ),\n ];\n };\n for (const value of candidates()) {\n const texts = [...draft.texts];\n texts[index] = writeSegment(layout, index, value);\n const trial: Draft = { ...draft, texts };\n if (type === \"month\" || type === \"year\") {\n clampDay(trial, layout);\n }\n if (context.allows === undefined || context.allows(trial.texts)) {\n draft.texts = trial.texts;\n break;\n }\n }\n draft.entry = { kind: \"active\", segment: index, advanced: false };\n}\n\n/** Moves from the active segment to `to`, finishing it. */\nfunction moveTo(draft: Draft, to: number, context: SegmentContext): void {\n const index = segmentOf(draft.entry);\n if (index !== null && draft.entry.kind !== \"composing\") {\n finish(draft, index, context);\n }\n draft.entry = { kind: \"active\", segment: to, advanced: false };\n}\n\n/** Whether `text` is digits that fit segment `index` whole, as a paste typed into it. */\nfunction fitsSegment(\n text: string,\n index: number,\n context: SegmentContext,\n): boolean {\n const { layout } = context;\n const segment = layout.segments[index];\n const digits = cleanDateText(text);\n return (\n segment !== undefined &&\n segment.type !== \"dayPeriod\" &&\n /^\\d+$/.test(digits) &&\n digits.length <= maxDigits(layout, index) &&\n Number(digits) <= segment.max\n );\n}\n\n/**\n * Every transition of a segmented field's typing, pure: forms-dom splits\n * the controller's text into segments before each action and reports\n * what comes back. Typing moves on once a segment is complete (a digit\n * that cannot start a longer number, or the segment's width reached); a\n * digit that would leave the segment's range starts it again (1 then 3 in\n * a month gives 03). Separators finish a segment; Backspace in an empty\n * one goes back. Steps wrap, a day within its month, and clamp the day\n * when the month or year changes; a step the field does not allow\n * (`allows`) is not taken. Leaving a segment pads it and pivots a short\n * year. In a date segment with shortcuts on, a letter or a sign opens the\n * free-text box; a one-letter text that reads is applied at once.\n */\nexport function segmentReducer(\n state: SegmentState,\n action: SegmentAction,\n context: SegmentContext,\n): SegmentStep {\n const { layout } = context;\n const draft = draftOf(state, layout);\n const active = segmentOf(draft.entry);\n const unchanged: SegmentStep = {\n state,\n focus: focusOf(state.entry),\n source: null,\n };\n switch (action.type) {\n case \"focus\": {\n if (draft.entry.kind === \"text\" || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n if (splitSegments(layout, state.text) === null) {\n // Free text left in the field, a shortcut that did not read, goes on in the free-text box.\n const entry: SegmentEntry = { kind: \"text\", before: \"\" };\n return {\n state: { entry, text: state.text },\n focus: \"text\",\n source: null,\n };\n }\n moveTo(draft, action.segment, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"key\": {\n if (draft.entry.kind === \"idle\" || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n typeText(draft, action.text, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"backspace\": {\n if (active === null) {\n return unchanged;\n }\n const text = draft.texts[active] ?? \"\";\n if (text === \"\") {\n draft.entry = {\n kind: \"active\",\n segment: Math.max(active - 1, 0),\n advanced: false,\n };\n return stepOf(state, draft, context, \"typing\");\n }\n const isPeriod = layout.segments[active]?.type === \"dayPeriod\";\n const rest = isPeriod ? \"\" : Array.from(text).slice(0, -1).join(\"\");\n draft.texts[active] = rest;\n draft.entry =\n rest === \"\"\n ? { kind: \"active\", segment: active, advanced: false }\n : { kind: \"typing\", segment: active, digits: cleanDateText(rest) };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"delete\": {\n if (active === null) {\n return unchanged;\n }\n draft.texts[active] = \"\";\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"step\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n step(draft, action.direction, action.size, context);\n return stepOf(state, draft, context, \"step\");\n }\n case \"move\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n const to =\n action.to === \"next\" ? next(layout, active) : Math.max(active - 1, 0);\n moveTo(draft, to, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"paste\": {\n const whole = context.readWhole(action.text);\n const texts = whole === null ? null : splitSegments(layout, whole);\n if (texts !== null) {\n draft.texts = [...texts];\n draft.entry = { kind: \"active\", segment: active ?? 0, advanced: false };\n return stepOf(state, draft, context, \"paste\");\n }\n if (active !== null && fitsSegment(action.text, active, context)) {\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n typeText(draft, cleanDateText(action.text), context);\n return stepOf(state, draft, context, \"paste\");\n }\n return unchanged;\n }\n case \"compositionStart\": {\n if (active === null) {\n return unchanged;\n }\n draft.entry = { kind: \"composing\", segment: active };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"compositionEnd\": {\n if (active === null) {\n return unchanged;\n }\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n typeText(draft, action.text, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"textEdit\": {\n if (draft.entry.kind !== \"text\") {\n return unchanged;\n }\n if (action.text === \"\") {\n draft.entry = { kind: \"active\", segment: 0, advanced: false };\n return stepOf(state, draft, context, \"typing\");\n }\n draft.free = action.text;\n applyOneLetter(draft, context);\n return stepOf(state, draft, context, action.source ?? \"typing\");\n }\n case \"finish\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n moveTo(draft, active, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"leave\": {\n if (active !== null && draft.entry.kind !== \"composing\") {\n finish(draft, active, context);\n }\n const text = textOf(draft, layout);\n return {\n state: { entry: IDLE, text },\n focus: null,\n source: text === state.text ? null : \"typing\",\n };\n }\n case \"outside\": {\n const texts = splitSegments(layout, action.text);\n let entry = state.entry;\n if (texts === null && entry.kind !== \"idle\" && entry.kind !== \"text\") {\n entry = { kind: \"text\", before: \"\" };\n } else if (entry.kind === \"typing\") {\n entry = { kind: \"active\", segment: entry.segment, advanced: false };\n } else if (entry.kind === \"text\" && texts !== null) {\n entry = {\n kind: \"active\",\n segment: lastDateSegment(layout),\n advanced: false,\n };\n }\n return {\n state: { entry, text: action.text },\n focus: focusOf(entry),\n source: null,\n };\n }\n }\n}\n\n/** A state in which no segment has focus, showing `text`. */\nexport function idleSegments(text: string): SegmentState {\n return { entry: IDLE, text };\n}\n\n/** What a segment's spinbutton tells assistive technology. */\nexport interface SegmentAria {\n /** The number it holds; `null` while empty. A day period is 0 or 1. */\n readonly valueNow: number | null;\n readonly valueMin: number;\n /** The segment's highest value; a day's follows its month once the month is set. */\n readonly valueMax: number;\n /** The month's name, the day period's text, the digits; `messages.segmentEmpty` while empty. */\n readonly valueText: string;\n}\n\n/**\n * The value, range and value text of segment `index` among the field's\n * segment `texts`, for its `aria-valuenow`, `aria-valuemin`,\n * `aria-valuemax` and `aria-valuetext`: a month reads as its name in\n * `locale` (\"March\"), a day period as its text, anything else as its\n * digits, and an empty segment as \"Empty\".\n */\nexport function segmentAria(\n layout: DateLayout,\n index: number,\n texts: readonly string[],\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): SegmentAria {\n const segment = layout.segments[index];\n const text = texts[index] ?? \"\";\n const valueNow = segmentValue(layout, index, text);\n const valueMin = segment?.min ?? 0;\n const valueMax =\n segment?.type === \"day\" ? dayLimit(texts, layout) : (segment?.max ?? 0);\n if (valueNow === null) {\n return { valueNow, valueMin, valueMax, valueText: messages.segmentEmpty };\n }\n const valueText =\n segment?.type === \"month\" && valueNow >= 1 && valueNow <= 12\n ? dateTimeFormat(locale, { month: \"long\", timeZone: \"UTC\" }).format(\n Date.UTC(2026, valueNow - 1, 1),\n )\n : text;\n return { valueNow, valueMin, valueMax, valueText };\n}\n","import { shownHour, writeSegment, type DateLayout } from \"./layout\";\nimport {\n compareDates,\n plainTime,\n splitDateTime,\n timeParts,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n type TimeParts,\n} from \"./values\";\n\n/** A column of a time picker: one per time segment of the field's layout. */\nexport type TimeColumnType = \"hour\" | \"minute\" | \"second\" | \"dayPeriod\";\n\n/** One choice in a time picker's column. */\nexport interface TimeColumnOption {\n /**\n * What the column sets: the hour of the day (0 to 23), or of the half\n * day (0 to 11) in a 12-hour cycle; the minute; the second; 0 for the\n * morning and 1 for the afternoon.\n */\n readonly value: number;\n /** As the field's segment writes it: \"12\", \"03\", \"PM\", in the locale's digits. */\n readonly text: string;\n /** No time it would give is within the limits. */\n readonly disabled: boolean;\n}\n\n/** A time picker's column, in the order the field's segments are. */\nexport interface TimeColumn {\n readonly type: TimeColumnType;\n /** The segment's name, which names the column: \"hour\". */\n readonly label: string;\n readonly options: readonly TimeColumnOption[];\n /** The value of the option the time holds; `null` while there is no time, or for minutes off the step. */\n readonly selected: number | null;\n}\n\n/**\n * The first and last time allowed, inclusive; `null` for no limit. With\n * `min` after `max` no time of day is allowed.\n */\nexport interface TimeLimits {\n readonly min: PlainTime | null;\n readonly max: PlainTime | null;\n}\n\n/** What a time picker's columns are drawn from. */\nexport interface TimeColumnsOptions extends TimeLimits {\n /** The field's layout: which columns, the hour cycle, the texts and digits. */\n readonly layout: DateLayout;\n /** The minutes offered, every `minuteStep` from 0; 1 by default. */\n readonly minuteStep?: number | undefined;\n}\n\n/** No limits: every time of day. */\nexport const ALL_DAY: TimeLimits = { min: null, max: null };\n\n/** Limits no time of day meets, for a day outside a date-time field's limits. */\nexport const NO_TIME: TimeLimits = { min: \"23:59:59.999\", max: \"00:00\" };\n\nconst SECOND_MS = 1000;\nconst DAY_MS = 86_400_000;\nconst COLUMN_TYPES: ReadonlySet<string> = new Set<TimeColumnType>([\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\n/** A whole minute step from 1 to 59; anything else is 1. */\nfunction stepOf(minuteStep: number | undefined): number {\n return minuteStep !== undefined &&\n Number.isInteger(minuteStep) &&\n minuteStep >= 1 &&\n minuteStep < 60\n ? minuteStep\n : 1;\n}\n\nfunction msOf({ hour, minute, second, millisecond }: TimeParts): number {\n return ((hour * 60 + minute) * 60 + second) * SECOND_MS + millisecond;\n}\n\n/** The limits in milliseconds into the day; `null` when no time is allowed. */\nfunction windowOf({\n min,\n max,\n}: TimeLimits): { readonly low: number; readonly high: number } | null {\n const low = min === null ? 0 : msOf(timeParts(min));\n const high = max === null ? DAY_MS - 1 : msOf(timeParts(max));\n return low <= high ? { low, high } : null;\n}\n\nfunction isTwelveHour(layout: DateLayout): boolean {\n return layout.hourCycle === \"h11\" || layout.hourCycle === \"h12\";\n}\n\nfunction hasSeconds(layout: DateLayout): boolean {\n return layout.segments.some((segment) => segment.type === \"second\");\n}\n\n/** Where a picker starts from while the field is empty: `min`, else midnight. */\nfunction startOf(limits: TimeLimits): TimeParts {\n return timeParts(limits.min ?? \"00:00\");\n}\n\n/** `count / every` values from 0, `every` apart. */\nfunction values(count: number, every = 1): number[] {\n return Array.from(\n { length: Math.ceil(count / every) },\n (_, index) => index * every,\n );\n}\n\n/**\n * A time picker's columns for `time`: hours, minutes every `minuteStep`,\n * seconds when the layout has them, and the day period in a 12-hour cycle,\n * in the layout's order, each option written as its segment writes it.\n * An option is disabled when every time it would give, at the other\n * columns' values (`min`, else midnight, while `time` is `null`), falls\n * outside `min` and `max`.\n */\nexport function timeColumns(\n time: PlainTime | null,\n options: TimeColumnsOptions,\n): readonly TimeColumn[] {\n const { layout } = options;\n const step = stepOf(options.minuteStep);\n const twelve = isTwelveHour(layout);\n const limits = windowOf(options);\n const current = time === null ? startOf(options) : timeParts(time);\n const held = time === null ? null : current;\n const afternoon = current.hour >= 12 ? 12 : 0;\n const lastMinute = 60 - step;\n const lastSecond = hasSeconds(layout) ? 59 : 0;\n const at = (hour: number, minute: number, second: number) =>\n msOf({ hour, minute, second, millisecond: 0 });\n\n const columns: TimeColumn[] = [];\n layout.segments.forEach((segment, index) => {\n if (!COLUMN_TYPES.has(segment.type)) {\n return;\n }\n const type = segment.type as TimeColumnType;\n // An option stands for the times from `start` to `end` the columns can give.\n const option = (\n value: number,\n shown: number,\n start: number,\n end: number,\n ): TimeColumnOption => ({\n value,\n text: writeSegment(layout, index, shown),\n disabled: limits === null || start > limits.high || end < limits.low,\n });\n let list: TimeColumnOption[];\n let selected: number | null;\n switch (type) {\n case \"hour\":\n list = values(twelve ? 12 : 24).map((value) => {\n const hour = twelve ? value + afternoon : value;\n return option(\n value,\n shownHour(hour, layout.hourCycle),\n at(hour, 0, 0),\n at(hour, lastMinute, lastSecond),\n );\n });\n selected = held === null ? null : held.hour - (twelve ? afternoon : 0);\n break;\n case \"minute\":\n list = values(60, step).map((minute) =>\n option(\n minute,\n minute,\n at(current.hour, minute, 0),\n at(current.hour, minute, lastSecond),\n ),\n );\n selected =\n held !== null && held.minute % step === 0 ? held.minute : null;\n break;\n case \"second\":\n list = values(60).map((second) => {\n const start = at(current.hour, current.minute, second);\n return option(second, second, start, start);\n });\n selected = held?.second ?? null;\n break;\n case \"dayPeriod\":\n list = [0, 1].map((period) =>\n option(\n period,\n period,\n at(period * 12, 0, 0),\n at(period * 12 + 11, lastMinute, lastSecond),\n ),\n );\n selected = held === null ? null : held.hour >= 12 ? 1 : 0;\n break;\n }\n columns.push({ type, label: segment.label, options: list, selected });\n });\n return columns;\n}\n\n/**\n * `time` within `limits`: the nearer limit when it is outside them, and\n * `time` itself when no time of day is allowed.\n */\nexport function clampTime(time: PlainTime, limits: TimeLimits): PlainTime {\n const window = windowOf(limits);\n if (window === null) {\n return time;\n }\n const ms = msOf(timeParts(time));\n if (limits.min !== null && ms < window.low) {\n return limits.min;\n }\n if (limits.max !== null && ms > window.high) {\n return limits.max;\n }\n return time;\n}\n\n/**\n * The time choosing `value` in the column `type` gives: `time` (`min`,\n * else midnight, while it is `null`) with that part set, then brought\n * within the limits. An hour keeps the half of the day in a 12-hour\n * cycle; a day period keeps the hour shown (3 AM becomes 3 PM).\n */\nexport function setTimeColumn(\n time: PlainTime | null,\n type: TimeColumnType,\n value: number,\n options: TimeColumnsOptions,\n): PlainTime {\n const current = time === null ? startOf(options) : timeParts(time);\n let { hour, minute, second } = current;\n switch (type) {\n case \"hour\":\n hour = isTwelveHour(options.layout)\n ? (value % 12) + (current.hour >= 12 ? 12 : 0)\n : value;\n break;\n case \"minute\":\n minute = value;\n break;\n case \"second\":\n second = value;\n break;\n case \"dayPeriod\":\n hour = (current.hour % 12) + (value === 0 ? 0 : 12);\n break;\n }\n return clampTime(\n plainTime(hour, minute, second, current.millisecond),\n options,\n );\n}\n\n/**\n * `time` as the columns can show it, for a \"Now\" button: the minutes down\n * to the step, no seconds unless the layout has them, no milliseconds,\n * within the limits.\n */\nexport function snapTime(\n time: PlainTime,\n options: TimeColumnsOptions,\n): PlainTime {\n const step = stepOf(options.minuteStep);\n const { hour, minute, second } = timeParts(time);\n return clampTime(\n plainTime(\n hour,\n Math.floor(minute / step) * step,\n hasSeconds(options.layout) ? second : 0,\n ),\n options,\n );\n}\n\n/**\n * The times a date-time field allows on `day`, for its time columns: from\n * `min`'s time on `min`'s day, to `max`'s time on `max`'s day, all day in\n * between, and none (`NO_TIME`) on a day before `min`'s or after `max`'s.\n */\nexport function dayTimeLimits(\n day: PlainDate,\n min: PlainDateTime | null,\n max: PlainDateTime | null,\n): TimeLimits {\n const first = min === null ? null : splitDateTime(min);\n const last = max === null ? null : splitDateTime(max);\n const fromFirst = first === null ? 1 : compareDates(day, first.date);\n const toLast = last === null ? -1 : compareDates(day, last.date);\n if (fromFirst < 0 || toLast > 0) {\n return NO_TIME;\n }\n return {\n min: fromFirst === 0 && first !== null ? first.time : null,\n max: toLast === 0 && last !== null ? last.time : null,\n };\n}\n","/**\n * The way a line runs: left to right, or right to left as in Arabic and\n * Hebrew. A grid's rows and toolbars and a form's controls run this way, so\n * in `\"rtl\"` the first column sits at the right edge.\n */\nexport type WritingDirection = \"ltr\" | \"rtl\";\n\n/**\n * Which way a horizontal arrow key moves along a line in `direction`: `1`\n * to the next column, chip or control, `-1` to the previous one, or\n * `null` for any other key. The arrows point the way they move, so in\n * `\"rtl\"`, where the next one is to the left, `ArrowLeft` moves forward.\n */\nexport function inlineStep(\n key: string,\n direction: WritingDirection = \"ltr\",\n): 1 | -1 | null {\n const forward = direction === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\";\n const backward = direction === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\";\n if (key === forward) {\n return 1;\n }\n if (key === backward) {\n return -1;\n }\n return null;\n}\n","/**\n * How serious a field's message is. Only `\"error\"` blocks a commit or a\n * submit; the others are shown and never stop the user. Growable: a later\n * release may add a severity.\n */\nexport type Severity = \"error\" | \"warning\" | \"info\" | \"success\";\n\n/** Every severity, most serious first: the order messages are shown in. */\nconst BY_SERIOUSNESS: readonly Severity[] = [\n \"error\",\n \"warning\",\n \"info\",\n \"success\",\n];\n\n/** Where `severity` sorts among messages: 0 for an error, higher for less serious. */\nexport function severityRank(severity: Severity): number {\n return BY_SERIOUSNESS.indexOf(severity);\n}\n\n/**\n * The most serious of `severities`, or `null` when there are none. A field\n * showing several messages takes the state of the most serious one.\n */\nexport function mostSevere(severities: Iterable<Severity>): Severity | null {\n const present = new Set(severities);\n return BY_SERIOUSNESS.find((severity) => present.has(severity)) ?? null;\n}\n","import { severityRank, type Severity } from \"./severity\";\n\n/** One message a field holds, ready to show. */\nexport interface FieldMessage {\n readonly severity: Severity;\n /** The text shown, already localized. */\n readonly text: string;\n /**\n * A stable id for the kind of message: `\"unreadable\"`, `\"required\"`,\n * `\"tooShort\"`, `\"tooLong\"`, `\"pattern\"`, `\"refused\"`, or the app's own;\n * `null` when it has none.\n */\n readonly code: string | null;\n /**\n * Where it came from: reading the text (`\"parse\"`), a validator\n * (`\"validate\"`), a refused commit (`\"commit\"`) or the app (`\"app\"`).\n * Growable: a later release may add a source.\n */\n readonly source: \"parse\" | \"validate\" | \"commit\" | \"app\";\n}\n\n/** A message as an app writes it: a string is an error. */\nexport type FieldMessageInput =\n | string\n | {\n readonly text: string;\n readonly severity?: Severity | undefined;\n readonly code?: string | undefined;\n };\n\n/** The display order of sources, among messages of one severity. */\nconst SOURCE_ORDER: readonly FieldMessage[\"source\"][] = [\n \"parse\",\n \"commit\",\n \"validate\",\n \"app\",\n];\n\n/**\n * `input` as a message from `source`; `code` stands in when the input names\n * none.\n */\nexport function toFieldMessage(\n input: FieldMessageInput,\n source: FieldMessage[\"source\"],\n code: string | null = null,\n): FieldMessage {\n return typeof input === \"string\"\n ? { severity: \"error\", text: input, code, source }\n : {\n severity: input.severity ?? \"error\",\n text: input.text,\n code: input.code ?? code,\n source,\n };\n}\n\n/**\n * Whatever an app or a validator returned, as a list of messages from\n * `source`: one input or several, `null` and `undefined` for none.\n */\nexport function toFieldMessages(\n input: FieldMessageInput | readonly FieldMessageInput[] | null | undefined,\n source: FieldMessage[\"source\"],\n): FieldMessage[] {\n if (input === null || input === undefined) {\n return [];\n }\n return isList(input)\n ? input.map((entry) => toFieldMessage(entry, source))\n : [toFieldMessage(input, source)];\n}\n\n// `Array.isArray` does not narrow a readonly array, hence the guard.\nfunction isList(\n input: FieldMessageInput | readonly FieldMessageInput[],\n): input is readonly FieldMessageInput[] {\n return Array.isArray(input);\n}\n\n/**\n * `messages` in the order a field shows them: the most serious first, and\n * within a severity what the text could not say (parse), then a refused\n * commit, then validators, then the app's own. Equal messages keep their\n * order.\n */\nexport function sortFieldMessages(\n messages: readonly FieldMessage[],\n): FieldMessage[] {\n return messages.toSorted(\n (a, b) =>\n severityRank(a.severity) - severityRank(b.severity) ||\n SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source),\n );\n}\n\n/** Whether any of `messages` is an error: the only severity that blocks. */\nexport function hasError(messages: readonly FieldMessage[]): boolean {\n return messages.some((message) => message.severity === \"error\");\n}\n","import type { FormsMessages } from \"./messages/formsMessages\";\nimport { parsed, type ParseContext, type ParseResult } from \"./parse\";\n\n/** How a text input reads its text. */\nexport interface TextParseOptions {\n /** Drops leading and trailing whitespace from the value. */\n readonly trim?: boolean | undefined;\n /** Upper-cases the value in the context's locale. */\n readonly uppercase?: boolean | undefined;\n}\n\n/**\n * A text input's own reading: the text as it is, trimmed or upper-cased\n * when asked, and `null` when that leaves it empty. Whitespace is kept\n * unless `trim` is set, so `requiredRule` is what refuses a blank value.\n * Text always reads, so it never returns `unreadable`.\n */\nexport function textParser(\n options: TextParseOptions = {},\n): (text: string, context: ParseContext<string>) => ParseResult<string> {\n const { trim = false, uppercase = false } = options;\n return (text, { locale }) => {\n const trimmed = trim ? text.trim() : text;\n const value = uppercase ? trimmed.toLocaleUpperCase(locale) : trimmed;\n return parsed(value === \"\" ? null : value);\n };\n}\n\n/** A text input's own formatting: the value as it is, `\"\"` for `null`. */\nexport function formatText(value: string | null): string {\n return value ?? \"\";\n}\n\n/**\n * The characters in `text` as a `maxLength` counts them: code points,\n * closer to \"characters\" than UTF-16 units, and how databases count a\n * `VARCHAR`. A simple emoji is one; a composed one (a family, a flag) is\n * several, as a database would count it.\n */\nexport function countCharacters(text: string): number {\n return Array.from(text).length;\n}\n\n/**\n * What a character counter announces when typing pauses: the characters\n * left once 10% of `max` or fewer remain, the characters too many once\n * over it, else nothing.\n */\nexport function counterAnnouncement(\n count: number,\n max: number,\n messages: FormsMessages,\n): string | null {\n const left = max - count;\n if (left < 0) {\n return messages.charactersOver(-left);\n }\n return left <= max / 10 ? messages.charactersLeft(left) : null;\n}\n","import {\n toFieldMessages,\n type FieldMessage,\n type FieldMessageInput,\n} from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { countCharacters } from \"../text\";\n\n/** What a validator knows beside the value. */\nexport interface ValidatorContext {\n /** The text the field shows. */\n readonly text: string;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/** What a validator returns: one message or several, `null` or nothing when the value is fine. */\nexport type ValidationResult =\n FieldMessageInput | readonly FieldMessageInput[] | null | undefined;\n\n/**\n * Checks a value. Called with every value, `null` included, after each\n * change, so it must be synchronous and cheap: anything slow or remote\n * belongs in `onBeforeCommit`. A string it returns is an error; a message\n * with another severity is shown and never blocks.\n */\nexport type Validator<V> = (\n value: V | null,\n context: ValidatorContext,\n) => ValidationResult;\n\n/** `null`, or a string of only whitespace, is `messages.required`. */\nexport function requiredRule<V>(): Validator<V> {\n return (value, { messages }) =>\n value === null || (typeof value === \"string\" && value.trim() === \"\")\n ? { text: messages.required, code: \"required\" }\n : null;\n}\n\n/** Fewer than `min` code points is `messages.tooShort`. `null` passes. */\nexport function minLengthRule(min: number): Validator<string> {\n return (value, { messages }) =>\n value !== null && countCharacters(value) < min\n ? { text: messages.tooShort(min), code: \"tooShort\" }\n : null;\n}\n\n/** More than `max` code points is `messages.tooLong`. `null` passes. */\nexport function maxLengthRule(max: number): Validator<string> {\n return (value, { messages }) =>\n value !== null && countCharacters(value) > max\n ? { text: messages.tooLong(max), code: \"tooLong\" }\n : null;\n}\n\n/**\n * The whole value must match `pattern`, as the HTML `pattern` attribute\n * reads it; `message` replaces `messages.patternMismatch`. `null` passes.\n */\nexport function patternRule(\n pattern: RegExp,\n message?: string,\n): Validator<string> {\n // `g` and `y` make `test` remember where it stopped, so they are dropped.\n const whole = new RegExp(\n `^(?:${pattern.source})$`,\n pattern.flags.replace(/[gy]/g, \"\"),\n );\n return (value, { messages }) =>\n value !== null && !whole.test(value)\n ? { text: message ?? messages.patternMismatch, code: \"pattern\" }\n : null;\n}\n\n/**\n * Anything but `true` is the message `message` picks from the catalogue:\n * a required checkbox (`requiredChecked`) or switch (`requiredOn`).\n */\nexport function checkedRule(\n message: (messages: FormsMessages) => string,\n): Validator<boolean> {\n return (value, context) =>\n value === true\n ? null\n : { text: message(context.messages), code: \"required\" };\n}\n\n/** Every message `validators` return for `value`, in their order. */\nexport function runValidators<V>(\n validators: readonly Validator<V>[],\n value: V | null,\n context: ValidatorContext,\n): FieldMessage[] {\n return validators.flatMap((validator) =>\n toFieldMessages(validator(value, context), \"validate\"),\n );\n}\n","import { sortFieldMessages, type FieldMessage } from \"../messages/fieldMessage\";\nimport type { FormatPurpose, ParseResult } from \"../parse\";\nimport type { CommitTrigger } from \"./events\";\n\n/**\n * The reading of a draft's text: `pending` while it has not been read yet\n * (an input method is composing, or a change delay is running), else the\n * parse result. A minor release may add a member.\n */\nexport type TextReading<V> = { readonly kind: \"pending\" } | ParseResult<V>;\n\n/**\n * What a field shows. `current` is its value, formatted, and follows the\n * value when the value changes (an untouched field follows a controlled\n * value); `text` is text the user typed, with how it reads. A minor release\n * may add a member.\n */\nexport type FieldDraft<V> =\n | { readonly kind: \"current\" }\n | {\n readonly kind: \"text\";\n readonly text: string;\n readonly reading: TextReading<V>;\n };\n\n/**\n * Where the field is in an edit. A minor release may add a member, so a\n * `switch` over `kind` needs a `default`.\n *\n * - `idle`: not being edited.\n * - `editing`: focused. `initialValue` is the value when it gained focus;\n * `committedValue` the value at its last commit since then (or at focus).\n * - `checking`: an asynchronous `onBeforeCommit` is deciding. `attempt`\n * identifies it, so a superseded check's answer is ignored; `leaving` is\n * true once focus has gone (its `onBlur` waits for the answer).\n * - `leaving`: Tab committed and focus is about to move; the blur that\n * follows commits nothing more.\n */\nexport type FieldPhase<V> =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"editing\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n }\n | {\n readonly kind: \"checking\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n readonly trigger: CommitTrigger;\n readonly attempt: number;\n readonly leaving: boolean;\n }\n | {\n readonly kind: \"leaving\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n };\n\n/** One field, whole. */\nexport interface FieldState<V> {\n /** The last valid value; `null` is empty. */\n readonly value: V | null;\n readonly draft: FieldDraft<V>;\n /** What the validators said about `value`. */\n readonly validation: readonly FieldMessage[];\n /** Why the last commit was refused, until the text or value changes again. */\n readonly refusal: FieldMessage | null;\n /** Whether messages are shown yet: false until the first commit attempt or `reveal`. */\n readonly revealed: boolean;\n readonly phase: FieldPhase<V>;\n}\n\nexport const CURRENT_DRAFT: FieldDraft<never> = { kind: \"current\" };\nexport const IDLE_PHASE: FieldPhase<never> = { kind: \"idle\" };\n\n/** A field holding `value`, untouched, with what its validators said. */\nexport function createFieldState<V>(\n value: V | null,\n validation: readonly FieldMessage[],\n): FieldState<V> {\n return {\n value,\n draft: CURRENT_DRAFT,\n validation,\n refusal: null,\n revealed: false,\n phase: IDLE_PHASE,\n };\n}\n\n/** The text on screen: `format(value)` for a `current` draft, else the typed text. */\nexport function fieldText<V>(\n state: FieldState<V>,\n format: (value: V | null) => string,\n): string {\n return state.draft.kind === \"current\"\n ? format(state.value)\n : state.draft.text;\n}\n\n/**\n * What the field's text is written for in `phase`: `edit` while the field\n * has focus (editing, leaving after Tab, or checking before focus went),\n * else `display`.\n */\nexport function formatPurpose<V>(phase: FieldPhase<V>): FormatPurpose {\n switch (phase.kind) {\n case \"idle\":\n return \"display\";\n case \"checking\":\n return phase.leaving ? \"display\" : \"edit\";\n case \"editing\":\n case \"leaving\":\n return \"edit\";\n }\n}\n\n/** Why `draft`'s text cannot be read, or `null` when it can (or has not been read yet). */\nexport function unreadableMessage<V>(draft: FieldDraft<V>): string | null {\n return draft.kind === \"text\" && draft.reading.kind === \"unreadable\"\n ? draft.reading.message\n : null;\n}\n\n/**\n * Every message the field holds, in display order, shown or not yet. Text\n * that cannot be read shows only why (and a refusal), not what the\n * validators said about the value it no longer shows.\n */\nexport function fieldMessages<V>(state: FieldState<V>): FieldMessage[] {\n const refusal = state.refusal === null ? [] : [state.refusal];\n const unreadable = unreadableMessage(state.draft);\n if (unreadable !== null) {\n return sortFieldMessages([\n {\n severity: \"error\",\n text: unreadable,\n code: \"unreadable\",\n source: \"parse\",\n },\n ...refusal,\n ]);\n }\n return sortFieldMessages([...refusal, ...state.validation]);\n}\n\n/** The messages the field shows now: all of them once `revealed`, else none. */\nexport function shownMessages<V>(state: FieldState<V>): FieldMessage[] {\n return state.revealed ? fieldMessages(state) : [];\n}\n","import type { FieldMessage } from \"../messages/fieldMessage\";\nimport type { ParseResult } from \"../parse\";\nimport type { CommitTrigger } from \"./events\";\nimport {\n CURRENT_DRAFT,\n IDLE_PHASE,\n unreadableMessage,\n type FieldDraft,\n type FieldPhase,\n type FieldState,\n} from \"./state\";\n\n/**\n * A step of a field's edit, as its controller asks for it. Parsing, the\n * app's hooks and value equality are the controller's, which passes their\n * results in (`read.reading`, `sync.equal`).\n *\n * - `focus`: the field gained focus.\n * - `edit`: the user changed the text; it is not read yet.\n * - `read`: how the typed text reads.\n * - `change`: the value changes; `text` is typed text that reads as it, or\n * `null` to show the value formatted.\n * - `revert`: the draft is put back (a refused change, Escape).\n * - `validated`: what the validators say about the value now.\n * - `check`: an asynchronous `onBeforeCommit` starts deciding.\n * - `accept`, `refuse`: a commit is allowed or refused; `next` is the phase\n * it leaves the field in.\n * - `blur`: the field lost focus.\n * - `sync`: a controlled value arrived; `equal` says whether it equals the\n * field's value.\n * - `reveal`: messages show from now on.\n */\nexport type FieldAction<V> =\n | { readonly type: \"focus\" }\n | { readonly type: \"edit\"; readonly text: string }\n | { readonly type: \"read\"; readonly reading: ParseResult<V> }\n | {\n readonly type: \"change\";\n readonly value: V | null;\n readonly text: string | null;\n }\n | { readonly type: \"revert\"; readonly draft: FieldDraft<V> }\n | { readonly type: \"validated\"; readonly messages: readonly FieldMessage[] }\n | {\n readonly type: \"check\";\n readonly trigger: CommitTrigger;\n readonly attempt: number;\n readonly leaving: boolean;\n }\n | { readonly type: \"accept\"; readonly next: \"editing\" | \"leaving\" | \"idle\" }\n | {\n readonly type: \"refuse\";\n readonly message: FieldMessage;\n readonly next: \"editing\" | \"idle\";\n }\n | { readonly type: \"blur\" }\n | { readonly type: \"sync\"; readonly value: V | null; readonly equal: boolean }\n | { readonly type: \"reveal\" };\n\ntype EditPhase<V> = Exclude<FieldPhase<V>, { kind: \"idle\" }>;\n\n/** `phase` as plain editing, keeping its two values. */\nfunction editing<V>(phase: EditPhase<V>): FieldPhase<V> {\n return phase.kind === \"editing\"\n ? phase\n : {\n kind: \"editing\",\n initialValue: phase.initialValue,\n committedValue: phase.committedValue,\n };\n}\n\n/**\n * Every transition of a field. Pure: no parsing, no callbacks, no equality\n * of its own. An action that means nothing in the field's phase returns the\n * state unchanged.\n */\nexport function fieldReducer<V>(\n state: FieldState<V>,\n action: FieldAction<V>,\n): FieldState<V> {\n const { phase } = state;\n switch (action.type) {\n case \"focus\":\n if (phase.kind === \"idle\") {\n return {\n ...state,\n phase: {\n kind: \"editing\",\n initialValue: state.value,\n committedValue: state.value,\n },\n };\n }\n return phase.kind === \"leaving\"\n ? { ...state, phase: editing(phase) }\n : state;\n\n case \"edit\":\n // An idle field takes no typing: autofill reaches it through a focus.\n return phase.kind === \"idle\"\n ? state\n : {\n ...state,\n draft: { kind: \"text\", text: action.text, reading: PENDING },\n refusal: null,\n phase: editing(phase),\n };\n\n case \"read\":\n return state.draft.kind === \"text\"\n ? { ...state, draft: { ...state.draft, reading: action.reading } }\n : state;\n\n case \"change\":\n return {\n ...state,\n value: action.value,\n draft:\n action.text === null\n ? CURRENT_DRAFT\n : {\n kind: \"text\",\n text: action.text,\n reading: { kind: \"value\", value: action.value },\n },\n refusal: null,\n // A change supersedes a pending check.\n phase: phase.kind === \"checking\" ? editing(phase) : phase,\n };\n\n case \"revert\":\n return phase.kind === \"checking\"\n ? state\n : { ...state, draft: action.draft };\n\n case \"validated\":\n return { ...state, validation: action.messages };\n\n case \"check\":\n return phase.kind === \"editing\"\n ? {\n ...state,\n phase: {\n kind: \"checking\",\n initialValue: phase.initialValue,\n committedValue: phase.committedValue,\n trigger: action.trigger,\n attempt: action.attempt,\n leaving: action.leaving,\n },\n }\n : state;\n\n case \"accept\":\n if (phase.kind !== \"editing\" && phase.kind !== \"checking\") {\n return state;\n }\n return {\n ...state,\n draft:\n unreadableMessage(state.draft) === null ? CURRENT_DRAFT : state.draft,\n refusal: null,\n revealed: true,\n phase:\n action.next === \"idle\"\n ? IDLE_PHASE\n : {\n kind: action.next,\n initialValue: phase.initialValue,\n committedValue: state.value,\n },\n };\n\n case \"refuse\":\n if (phase.kind !== \"editing\" && phase.kind !== \"checking\") {\n return state;\n }\n return {\n ...state,\n refusal: action.message,\n revealed: true,\n phase: action.next === \"idle\" ? IDLE_PHASE : editing(phase),\n };\n\n case \"blur\":\n return blur(state);\n\n case \"sync\":\n return sync(state, action.value, action.equal);\n\n case \"reveal\":\n return state.revealed ? state : { ...state, revealed: true };\n }\n}\n\nconst PENDING = { kind: \"pending\" } as const;\n\n/**\n * Focus went. A focused field goes idle and shows its messages; this is\n * reached only when leaving commits nothing (unreadable text, a toggle).\n * A pending check notes it, so its answer ends the edit.\n */\nfunction blur<V>(state: FieldState<V>): FieldState<V> {\n const { phase } = state;\n switch (phase.kind) {\n case \"idle\":\n return state;\n case \"editing\":\n return { ...state, phase: IDLE_PHASE, revealed: true };\n case \"checking\":\n return { ...state, phase: { ...phase, leaving: true } };\n case \"leaving\":\n return { ...state, phase: IDLE_PHASE };\n }\n}\n\n/**\n * A controlled value is adopted whenever the user is not typing: always in\n * an idle field, and in a focused one while its draft shows the value. A\n * pending check holds it off; the next `sync` after the edit ends adopts it.\n */\nfunction sync<V>(\n state: FieldState<V>,\n value: V | null,\n equal: boolean,\n): FieldState<V> {\n const { phase } = state;\n if (equal || phase.kind === \"checking\") {\n return state;\n }\n if (phase.kind === \"idle\") {\n return { ...state, value, draft: CURRENT_DRAFT, refusal: null };\n }\n return state.draft.kind === \"current\"\n ? {\n ...state,\n value,\n refusal: null,\n phase: { ...phase, committedValue: value },\n }\n : state;\n}\n","import {\n hasError,\n toFieldMessage,\n type FieldMessage,\n type FieldMessageInput,\n} from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { parsed, type ParseResult } from \"../parse\";\nimport type {\n ChangeSource,\n CommitTrigger,\n FieldEventBase,\n FieldHandlers,\n TextInputDetails,\n} from \"./events\";\nimport type { FieldAction } from \"./fieldReducer\";\nimport {\n CURRENT_DRAFT,\n fieldMessages,\n fieldText,\n unreadableMessage,\n type FieldDraft,\n type FieldState,\n} from \"./state\";\n\n// The event plans: one function per kind of request, calling the app's\n// handlers in the documented order and dispatching reducer actions between\n// them. They touch nothing but `env`, so a test drives them with handlers\n// that record their calls. Timers, the request queue and the pending check's\n// promise are the controller's.\n\n/** Where a change came from, and the browser's report of it. */\nexport interface ChangeCause<N> {\n readonly source: ChangeSource;\n readonly nativeEvent: N | null;\n readonly input: TextInputDetails | null;\n}\n\n/** A text edit, as forms-dom reports it. */\nexport interface TextEdit<N> extends ChangeCause<N> {\n /** The text after the edit; for `beforeInput`, the proposed text. */\n readonly text: string;\n}\n\n/** What forms-dom does with a text edit `onBeforeInput` saw. */\nexport type BeforeInputDecision =\n | { readonly kind: \"allow\" }\n | { readonly kind: \"prevent\" }\n | { readonly kind: \"rewrite\"; readonly data: string };\n\n/**\n * What an input's own filter does with an edit: one of `onBeforeInput`'s\n * decisions, or `replace`, where the whole text becomes `text` with the\n * caret at `caret` (a mask laying its characters out again).\n */\nexport type InputFilterDecision =\n | BeforeInputDecision\n | { readonly kind: \"replace\"; readonly text: string; readonly caret: number };\n\n/**\n * An input's own judgement of an edit, after the app's `onBeforeInput` let\n * it through: `edit` is the edit as the app left it (its `text` the text it\n * would leave), `before` the text before it.\n */\nexport type InputFilter<N> = (\n edit: TextEdit<N>,\n before: string,\n) => InputFilterDecision;\n\n/**\n * How a commit request ended:\n *\n * - `accepted`: committed (`onCommit` has fired).\n * - `refused`: `onBeforeCommit` refused it; its message shows.\n * - `unreadable`: the text cannot be read, so nothing was committed; the\n * message shows.\n * - `checking`: not decided yet. An asynchronous `onBeforeCommit` is\n * deciding, or the request was made from inside a handler and runs once\n * the current sequence ends.\n */\nexport type CommitOutcome =\n | { readonly kind: \"accepted\" }\n | { readonly kind: \"refused\" }\n | { readonly kind: \"unreadable\" }\n | { readonly kind: \"checking\" };\n\n/** Everything a sequence needs: the field's state and its options, resolved. */\nexport interface FieldEnv<V, D extends object, N> {\n /** The state as the sequence runs, which a handler reading the field sees too. */\n readonly get: () => FieldState<V>;\n readonly dispatch: (action: FieldAction<V>) => FieldState<V>;\n readonly handlers: FieldHandlers<V, D, N>;\n /** The input's own judgement of an edit, after `onBeforeInput`. */\n readonly filterInput: InputFilter<N> | undefined;\n readonly parse: (text: string) => ParseResult<V>;\n readonly format: (value: V | null) => string;\n /** Whether two values are one; `null` equals only itself. */\n readonly same: (a: V | null, b: V | null) => boolean;\n readonly validate: (value: V | null, text: string) => readonly FieldMessage[];\n readonly details: (\n current: FieldState<V>,\n previous: FieldState<V>,\n cause: ChangeCause<N>,\n ) => D;\n readonly messages: FormsMessages;\n readonly commitOnLeave: boolean;\n}\n\n/** A commit as the controller asks for it. */\nexport interface CommitRequest<N> {\n readonly trigger: CommitTrigger;\n readonly source: ChangeSource;\n readonly nativeEvent: N | null;\n /** Identifies this commit, should `onBeforeCommit` answer later. */\n readonly attempt: number;\n}\n\n/** A commit an asynchronous `onBeforeCommit` is deciding. */\nexport interface PendingCheck<N> extends CommitRequest<N> {\n /** Started while the field was idle: it ends idle, with no `onBlur`. */\n readonly quiet: boolean;\n /** Settles with the refusal, or `null` when allowed. Never rejects. */\n readonly answer: Promise<FieldMessage | null>;\n}\n\nexport interface CommitStep<N> {\n readonly outcome: CommitOutcome;\n /** The check to wait for, when the outcome is `checking`. */\n readonly check: PendingCheck<N> | null;\n}\n\nconst ALLOW = { kind: \"allow\" } as const;\nconst PREVENT = { kind: \"prevent\" } as const;\nconst ACCEPTED = { kind: \"accepted\" } as const;\nconst REFUSED = { kind: \"refused\" } as const;\nconst UNREADABLE = { kind: \"unreadable\" } as const;\nexport const CHECKING = { kind: \"checking\" } as const;\n\ninterface EventValues<V> {\n readonly value: V | null;\n readonly previousValue: V | null;\n readonly text: string;\n readonly previousText: string;\n}\n\n/**\n * An event's shared fields, with the input's details computed from the\n * state now, the state the request started from and the change's cause.\n * The base fields go last, so a details key can never hide one.\n */\nfunction eventBase<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n values: EventValues<V>,\n cause: ChangeCause<N>,\n): FieldEventBase<V, N> & D {\n return {\n ...env.details(env.get(), start, cause),\n ...values,\n source: cause.source,\n nativeEvent: cause.nativeEvent,\n input: cause.input,\n };\n}\n\n/** The text `draft` shows over the field's current value. */\nfunction draftText<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n draft: FieldDraft<V>,\n): string {\n return draft.kind === \"current\" ? env.format(env.get().value) : draft.text;\n}\n\nfunction emitValidate<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n values: EventValues<V>,\n cause: ChangeCause<N>,\n): void {\n const messages = fieldMessages(env.get());\n env.handlers.onValidate?.({\n ...eventBase(env, start, values, cause),\n messages,\n valid: !hasError(messages),\n });\n}\n\nfunction emitBlur<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): void {\n const state = env.get();\n env.handlers.onBlur?.({\n value: state.value,\n text: fieldText(state, env.format),\n nativeEvent,\n });\n}\n\n/**\n * `onBeforeInput` for an edit about to happen, then the input's own filter\n * for an edit the app let through (outside a composition, which cannot be\n * refused), and what forms-dom should do with it. Changes no state: the\n * edit arrives through `runEdit`.\n */\nexport function runBeforeInput<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N> & { readonly cancelable: boolean },\n): InputFilterDecision {\n const before = fieldText(env.get(), env.format);\n const decision = appDecision(env, edit, before);\n const { filterInput } = env;\n if (\n filterInput === undefined ||\n !edit.cancelable ||\n decision.kind === \"prevent\"\n ) {\n return decision;\n }\n const judged = filterInput(\n decision.kind === \"rewrite\"\n ? rewrittenEdit(edit, before, decision.data)\n : edit,\n before,\n );\n return judged.kind === \"allow\" ? decision : judged;\n}\n\n/** `edit` with `data` in place of the selection, as forms-dom inserts a rewrite. */\nfunction rewrittenEdit<N>(\n edit: TextEdit<N>,\n before: string,\n data: string,\n): TextEdit<N> {\n const { input } = edit;\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n return {\n ...edit,\n text: before.slice(0, start) + data + before.slice(end),\n input: input && { ...input, data },\n };\n}\n\n/** What the app's `onBeforeInput` decides about `edit`; `before` is the text before it. */\nfunction appDecision<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N> & { readonly cancelable: boolean },\n before: string,\n): BeforeInputDecision {\n const handler = env.handlers.onBeforeInput;\n if (handler === undefined) {\n return ALLOW;\n }\n const state = env.get();\n const decided: { decision: BeforeInputDecision } = { decision: ALLOW };\n handler({\n ...eventBase(\n env,\n state,\n {\n value: state.value,\n previousValue: state.value,\n text: edit.text,\n previousText: before,\n },\n edit,\n ),\n cancelable: edit.cancelable,\n get defaultPrevented() {\n return decided.decision.kind === \"prevent\";\n },\n preventDefault() {\n if (edit.cancelable) {\n decided.decision = PREVENT;\n }\n },\n setData(data) {\n if (edit.cancelable && decided.decision.kind !== \"prevent\") {\n decided.decision = { kind: \"rewrite\", data };\n }\n },\n });\n return decided.decision;\n}\n\n/**\n * The text changed: the draft takes it, unread, then `onInput`. False when\n * nothing happened: the text is the same, or the field is idle (autofill\n * goes through `runAutofill`).\n */\nexport function runEdit<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N>,\n): boolean {\n const start = env.get();\n const previousText = fieldText(start, env.format);\n if (start.phase.kind === \"idle\" || edit.text === previousText) {\n return false;\n }\n env.dispatch({ type: \"edit\", text: edit.text });\n env.handlers.onInput?.(\n eventBase(\n env,\n start,\n {\n value: start.value,\n previousValue: start.value,\n text: edit.text,\n previousText,\n },\n edit,\n ),\n );\n return true;\n}\n\n/**\n * Reads the draft's unread text: parse, then the change chain when it reads\n * as another value, else `onValidate` when whether (or why) it cannot be\n * read changed. `before` is the draft before the edits being read, which a\n * refused change puts back.\n */\nexport function runRead<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n const { draft } = start;\n if (draft.kind !== \"text\" || draft.reading.kind !== \"pending\") {\n return;\n }\n const reading = env.parse(draft.text);\n env.dispatch({ type: \"read\", reading });\n if (\n reading.kind === \"unreadable\" ||\n runChange(env, start, reading.value, draft.text, before, cause) ===\n \"unchanged\"\n ) {\n validateIfReadingChanged(env, start, before, cause);\n }\n}\n\ntype ChangeResult = \"changed\" | \"unchanged\" | \"prevented\";\n\n/**\n * The change chain: `onBeforeChange`, the change, `onChange`, validation and\n * `onValidate`, skipped when `target` is the value held. `typedText` is text\n * that reads as `target`, kept on screen; `null` shows the value formatted.\n */\nfunction runChange<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n target: V | null,\n typedText: string | null,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): ChangeResult {\n const previousValue = env.get().value;\n if (env.same(target, previousValue)) {\n if (typedText === null) {\n env.dispatch({ type: \"revert\", draft: CURRENT_DRAFT });\n }\n return \"unchanged\";\n }\n const previousText = draftText(env, before);\n const decided: {\n decision:\n typeof ALLOW | typeof PREVENT | { kind: \"replace\"; value: V | null };\n } = { decision: ALLOW };\n env.handlers.onBeforeChange?.({\n ...eventBase(\n env,\n start,\n {\n value: target,\n previousValue,\n text: typedText ?? env.format(target),\n previousText,\n },\n cause,\n ),\n get defaultPrevented() {\n return decided.decision.kind === \"prevent\";\n },\n preventDefault() {\n decided.decision = PREVENT;\n },\n setValue(value) {\n if (decided.decision.kind !== \"prevent\") {\n decided.decision = { kind: \"replace\", value };\n }\n },\n });\n const { decision } = decided;\n if (decision.kind === \"prevent\") {\n env.dispatch({ type: \"revert\", draft: before });\n return \"prevented\";\n }\n const value = decision.kind === \"replace\" ? decision.value : target;\n if (env.same(value, previousValue)) {\n // `setValue` chose the value already held: only the text changes back.\n env.dispatch({ type: \"revert\", draft: CURRENT_DRAFT });\n return \"unchanged\";\n }\n const text = typedText !== null && env.same(value, target) ? typedText : null;\n const changed = env.dispatch({ type: \"change\", value, text });\n const values = {\n value,\n previousValue,\n text: fieldText(changed, env.format),\n previousText,\n };\n env.handlers.onChange?.(eventBase(env, start, values, cause));\n env.dispatch({\n type: \"validated\",\n messages: env.validate(value, values.text),\n });\n emitValidate(env, start, values, cause);\n return \"changed\";\n}\n\n/** `onValidate` when the value stayed but whether, or why, the text cannot be read changed. */\nfunction validateIfReadingChanged<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): void {\n const state = env.get();\n if (unreadableMessage(before) === unreadableMessage(state.draft)) {\n return;\n }\n emitValidate(\n env,\n start,\n {\n value: state.value,\n previousValue: state.value,\n text: fieldText(state, env.format),\n previousText: draftText(env, before),\n },\n cause,\n );\n}\n\n/**\n * Puts the text `target` formats to on screen as if typed (`onInput`), then\n * runs the change chain to `target`: Escape's revert and the clear button.\n */\nfunction replaceText<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n target: V | null,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n const before = start.draft;\n const previousText = fieldText(start, env.format);\n const text = env.format(target);\n if (text !== previousText) {\n env.dispatch({ type: \"edit\", text });\n env.dispatch({ type: \"read\", reading: parsed(target) });\n env.handlers.onInput?.(\n eventBase(\n env,\n start,\n { value: start.value, previousValue: start.value, text, previousText },\n cause,\n ),\n );\n }\n if (runChange(env, start, target, null, before, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, before, cause);\n }\n}\n\n/**\n * Focuses an idle field without an `onFocus`, for a change made while it had\n * no focus (autofill, a toggle clicked in a browser that does not focus it).\n * True when it did; the commit that follows then ends the edit.\n */\nfunction enterQuietly<V, D extends object, N>(env: FieldEnv<V, D, N>): boolean {\n if (env.get().phase.kind !== \"idle\") {\n return false;\n }\n env.dispatch({ type: \"focus\" });\n return true;\n}\n\n/** `message` as a refusal, `messages.checkFailed` when none is given. */\nfunction refusalOf(\n message: FieldMessageInput | undefined,\n messages: FormsMessages,\n): FieldMessage {\n return toFieldMessage(message ?? messages.checkFailed, \"commit\", \"refused\");\n}\n\n/** What a commit event reports, read from the state before the commit. */\ninterface Committing<V> {\n readonly value: V | null;\n readonly committedValue: V | null;\n readonly initialValue: V | null;\n readonly previousText: string;\n}\n\nfunction commitEvent<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n request: CommitRequest<N>,\n committing: Committing<V>,\n) {\n return {\n ...eventBase(\n env,\n start,\n {\n value: committing.value,\n previousValue: committing.committedValue,\n text: env.format(committing.value),\n previousText: committing.previousText,\n },\n {\n source: request.source,\n nativeEvent: request.nativeEvent,\n input: null,\n },\n ),\n trigger: request.trigger,\n changed: !env.same(committing.value, committing.committedValue),\n initialValue: committing.initialValue,\n };\n}\n\n/** What `state`, in an edit, would commit. */\nfunction committingOf<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n state: FieldState<V>,\n): Committing<V> | null {\n const { phase } = state;\n return phase.kind === \"editing\" || phase.kind === \"checking\"\n ? {\n value: state.value,\n committedValue: phase.committedValue,\n initialValue: phase.initialValue,\n previousText: fieldText(state, env.format),\n }\n : null;\n}\n\n/** The commit is allowed: accept, then `onCommit`. */\nfunction accept<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n request: CommitRequest<N>,\n committing: Committing<V>,\n next: \"editing\" | \"leaving\" | \"idle\",\n): void {\n env.dispatch({ type: \"accept\", next });\n env.handlers.onCommit?.(commitEvent(env, start, request, committing));\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\n/**\n * A commit: `onBeforeCommit`, then `onCommit` once allowed. Text that\n * cannot be read commits nothing and shows why. Tab leaves the field\n * `leaving`, so the blur that follows commits nothing more; a blur ends the\n * edit. A field that was idle (`quiet`) returns to idle.\n */\nfunction commitFrom<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n request: CommitRequest<N>,\n quiet: boolean,\n): CommitStep<N> {\n const start = env.get();\n if (start.phase.kind === \"checking\") {\n // The pending check is about this same value: any change supersedes it.\n return { outcome: CHECKING, check: null };\n }\n const committing = committingOf(env, start);\n if (committing === null) {\n // Leaving: Tab has committed already.\n return { outcome: ACCEPTED, check: null };\n }\n if (unreadableMessage(start.draft) !== null) {\n env.dispatch({ type: \"reveal\" });\n if (quiet) {\n env.dispatch({ type: \"blur\" });\n }\n return { outcome: UNREADABLE, check: null };\n }\n const ends = quiet || request.trigger === \"blur\";\n const decided: { open: boolean; refusal: FieldMessage | null } = {\n open: true,\n refusal: null,\n };\n const answer: unknown = env.handlers.onBeforeCommit?.({\n ...commitEvent(env, start, request, committing),\n get defaultPrevented() {\n return decided.refusal !== null;\n },\n preventDefault(message) {\n if (decided.open && decided.refusal === null) {\n decided.refusal = refusalOf(message, env.messages);\n }\n },\n });\n if (isPromiseLike(answer)) {\n env.dispatch({\n type: \"check\",\n trigger: request.trigger,\n attempt: request.attempt,\n leaving: ends || request.trigger === \"tab\",\n });\n const close = (failed: boolean): FieldMessage | null => {\n decided.open = false;\n return (\n decided.refusal ?? (failed ? refusalOf(undefined, env.messages) : null)\n );\n };\n return {\n outcome: CHECKING,\n check: {\n ...request,\n quiet,\n answer: Promise.resolve(answer).then(\n () => close(false),\n () => close(true),\n ),\n },\n };\n }\n decided.open = false;\n if (decided.refusal !== null) {\n env.dispatch({\n type: \"refuse\",\n message: decided.refusal,\n next: ends ? \"idle\" : \"editing\",\n });\n return { outcome: REFUSED, check: null };\n }\n const next = ends\n ? \"idle\"\n : request.trigger === \"tab\"\n ? \"leaving\"\n : \"editing\";\n accept(env, start, request, committing, next);\n return { outcome: ACCEPTED, check: null };\n}\n\n/** A commit by Enter or Tab, or one an app or input asks for. */\nexport function runCommit<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n request: CommitRequest<N>,\n): CommitStep<N> {\n return commitFrom(env, request, enterQuietly(env));\n}\n\n/**\n * A pending check answered. Ignored unless it is still the field's check:\n * a change since then, or a newer commit, superseded it. A field focus has\n * left gets its `onBlur` now.\n */\nexport function runSettle<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n check: PendingCheck<N>,\n refusal: FieldMessage | null,\n blurEvent: N | null,\n): void {\n const start = env.get();\n const { phase } = start;\n const committing = committingOf(env, start);\n if (\n phase.kind !== \"checking\" ||\n phase.attempt !== check.attempt ||\n committing === null\n ) {\n return;\n }\n const next = phase.leaving ? \"idle\" : \"editing\";\n if (refusal === null) {\n accept(env, start, check, committing, next);\n } else {\n env.dispatch({ type: \"refuse\", message: refusal, next });\n }\n if (phase.leaving && !check.quiet) {\n emitBlur(env, blurEvent);\n }\n}\n\n/** The field gained focus: `onFocus`, unless it never lost it. */\nexport function runFocus<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): void {\n const { phase } = env.get();\n if (phase.kind === \"leaving\") {\n // Tab committed but focus stayed: the edit goes on, unannounced.\n env.dispatch({ type: \"focus\" });\n return;\n }\n if (phase.kind !== \"idle\") {\n return;\n }\n const state = env.dispatch({ type: \"focus\" });\n env.handlers.onFocus?.({\n value: state.value,\n text: fieldText(state, env.format),\n nativeEvent,\n });\n}\n\n/**\n * The field lost focus. An edit commits (`trigger: \"blur\"`) unless Tab\n * already did or the field commits as it changes (`commitOnLeave: false`),\n * then `onBlur`; a pending check holds `onBlur` until it answers, and the\n * check this blur starts, if any, is returned.\n */\nexport function runBlur<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n attempt: number,\n): PendingCheck<N> | null {\n const { phase } = env.get();\n switch (phase.kind) {\n case \"idle\":\n return null;\n case \"checking\":\n env.dispatch({ type: \"blur\" });\n return null;\n case \"leaving\":\n env.dispatch({ type: \"blur\" });\n emitBlur(env, nativeEvent);\n return null;\n case \"editing\": {\n if (env.commitOnLeave) {\n const { check } = commitFrom(\n env,\n { trigger: \"blur\", source: \"typing\", nativeEvent, attempt },\n false,\n );\n if (check !== null) {\n return check;\n }\n }\n // A commit leaves the field idle; anything else still needs to end.\n env.dispatch({ type: \"blur\" });\n emitBlur(env, nativeEvent);\n return null;\n }\n }\n}\n\n/**\n * Escape: the text and value go back to the last commit (`source:\n * \"revert\"`). False when they are already there, or the field is not\n * being edited.\n */\nexport function runRevert<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): boolean {\n const state = env.get();\n const { phase } = state;\n if (phase.kind !== \"editing\") {\n return false;\n }\n const target = phase.committedValue;\n if (\n env.same(state.value, target) &&\n fieldText(state, env.format) === env.format(target)\n ) {\n return false;\n }\n replaceText(env, target, { source: \"revert\", nativeEvent, input: null });\n return true;\n}\n\n/** The clear button: empty text, the value `null`, then a commit. */\nexport function runClear<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n attempt: number,\n): CommitStep<N> {\n const quiet = enterQuietly(env);\n replaceText(env, null, { source: \"clear\", nativeEvent, input: null });\n return commitFrom(\n env,\n { trigger: \"clear\", source: \"clear\", nativeEvent, attempt },\n quiet,\n );\n}\n\n/** A value chosen whole (a toggle, an option, a preset): the change chain, then a commit. */\nexport function runPick<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n request: CommitRequest<N>,\n): CommitStep<N> {\n const quiet = enterQuietly(env);\n const start = env.get();\n const cause = {\n source: request.source,\n nativeEvent: request.nativeEvent,\n input: null,\n };\n if (runChange(env, start, value, null, start.draft, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, start.draft, cause);\n }\n return commitFrom(env, request, quiet);\n}\n\n/**\n * Text that changed while the field had no focus (browser autofill): read\n * at once and committed (`trigger: \"autofill\"`), with no `onFocus` or\n * `onBlur`. Returns the check a slow `onBeforeCommit` starts, if any.\n */\nexport function runAutofill<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N>,\n attempt: number,\n): PendingCheck<N> | null {\n if (edit.text === fieldText(env.get(), env.format)) {\n return null;\n }\n const quiet = enterQuietly(env);\n const before = env.get().draft;\n runEdit(env, edit);\n runRead(env, before, edit);\n return commitFrom(\n env,\n {\n trigger: \"autofill\",\n source: edit.source,\n nativeEvent: edit.nativeEvent,\n attempt,\n },\n quiet,\n ).check;\n}\n\n/**\n * A value set whole without a commit: a step, `setValue` and `reset`. The\n * change chain, with `cause`'s source and native event; typed text is\n * replaced by the value formatted, even when the value stays.\n */\nexport function runValueChange<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n if (runChange(env, start, value, null, start.draft, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, start.draft, cause);\n }\n}\n\n/**\n * A controlled value arrived: adopted, silently, whenever the user is not\n * typing, and validated when it changes the value.\n */\nexport function runSync<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n): void {\n const start = env.get();\n const next = env.dispatch({\n type: \"sync\",\n value,\n equal: env.same(value, start.value),\n });\n if (next !== start) {\n env.dispatch({\n type: \"validated\",\n messages: env.validate(next.value, fieldText(next, env.format)),\n });\n }\n}\n\nfunction sameMessages(\n a: readonly FieldMessage[],\n b: readonly FieldMessage[],\n): boolean {\n return (\n a.length === b.length &&\n a.every((message, index) => {\n const other = b[index];\n return (\n other !== undefined &&\n message.severity === other.severity &&\n message.text === other.text &&\n message.code === other.code &&\n message.source === other.source\n );\n })\n );\n}\n\n/** Messages show from now on, the validators asked again. */\nexport function runReveal<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n): void {\n const state = env.dispatch({ type: \"reveal\" });\n const messages = env.validate(state.value, fieldText(state, env.format));\n if (!sameMessages(messages, state.validation)) {\n env.dispatch({ type: \"validated\", messages });\n }\n}\n","import type { FieldMessage } from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport type {\n FormatContext,\n FormatPurpose,\n Formatter,\n ParseContext,\n ParseResult,\n Parser,\n} from \"../parse\";\nimport type { Schedule } from \"../schedule\";\nimport { runValidators, type Validator } from \"../validation/validators\";\nimport type {\n ChangeSource,\n CommitTrigger,\n FieldHandlers,\n NoDetails,\n} from \"./events\";\nimport { fieldReducer } from \"./fieldReducer\";\nimport {\n CHECKING,\n runAutofill,\n runBeforeInput,\n runBlur,\n runClear,\n runCommit,\n runEdit,\n runFocus,\n runPick,\n runRead,\n runReveal,\n runRevert,\n runSettle,\n runSync,\n runValueChange,\n type ChangeCause,\n type CommitOutcome,\n type CommitStep,\n type FieldEnv,\n type InputFilter,\n type InputFilterDecision,\n type PendingCheck,\n type TextEdit,\n} from \"./plan\";\nimport {\n createFieldState,\n fieldMessages,\n fieldText,\n formatPurpose,\n type FieldDraft,\n type FieldState,\n} from \"./state\";\n\n/**\n * What a field is given: its value, how it reads and writes text, how it\n * validates, and the app's handlers. A renderer passes the latest on every\n * update through `setOptions`.\n */\nexport interface FieldOptions<\n V,\n D extends object = NoDetails,\n N = unknown,\n> extends FieldHandlers<V, D, N> {\n /** Present (`null` included) means controlled: see `FieldController.sync`. */\n readonly value?: V | null | undefined;\n /** The value of an uncontrolled field at first, and what `reset` returns to. */\n readonly defaultValue?: V | null | undefined;\n /** The app's reading of typed text; its context holds `defaultParse`. */\n readonly parse?: Parser<V> | undefined;\n /** The app's writing of the value; its context holds `defaultFormat`. */\n readonly format?: Formatter<V> | undefined;\n /** The input's own reading. */\n readonly defaultParse: (\n text: string,\n context: ParseContext<V>,\n ) => ParseResult<V>;\n /** The input's own writing. */\n readonly defaultFormat: (\n value: V | null,\n context: FormatContext<V>,\n ) => string;\n /** Whether two values are one; `Object.is` by default. Never called with `null`. */\n readonly equals?: ((a: V, b: V) => boolean) | undefined;\n /**\n * The input's own judgement of each edit the app's `onBeforeInput` lets\n * through, outside a composition: a number input refusing letters, or\n * cleaning a paste.\n */\n readonly filterInput?: InputFilter<N> | undefined;\n readonly validators?: readonly Validator<V>[] | undefined;\n /**\n * The input's own details, added to every event it fires. `cause` is\n * the change the event is about: its source and, for a text edit, where\n * in the text it happened (a date field names the segment from it).\n */\n readonly details?:\n | ((\n current: FieldState<V>,\n previous: FieldState<V>,\n cause: ChangeCause<N>,\n ) => D)\n | undefined;\n /**\n * Milliseconds typing must pause before the text is read (`onChange`),\n * for a search box. `onInput` fires at once, and a commit reads at once.\n * Needs `schedule`; 0, the default, reads at once.\n */\n readonly changeDelay?: number | undefined;\n /** Whether leaving the field commits it: true by default, false for a toggle, which commits as it flips. */\n readonly commitOnLeave?: boolean | undefined;\n /** The timer `changeDelay` runs on. */\n readonly schedule?: Schedule | undefined;\n readonly locale?: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/**\n * One field's state and every request that moves it, for a renderer to\n * drive: forms-dom calls the text and focus requests from the browser's\n * events, the app the value requests. Each request runs its sequence of\n * handlers to the end before the next starts: one made from inside a\n * handler is queued behind it.\n */\nexport interface FieldController<V, D extends object = NoDetails, N = unknown> {\n readonly getState: () => FieldState<V>;\n /** The text on screen. */\n readonly getText: () => string;\n /** Every message the field holds, in display order; the same array until the state changes. */\n readonly getMessages: () => readonly FieldMessage[];\n /** Calls `listener` once after each request that changed the state. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Replaces the options, silently: no listener is called. */\n readonly setOptions: (options: FieldOptions<V, D, N>) => void;\n /**\n * `onBeforeInput` for an edit about to happen, then the input's\n * `filterInput`, and what to do with it.\n */\n readonly beforeInput: (\n edit: TextEdit<N> & { readonly cancelable: boolean },\n ) => InputFilterDecision;\n /**\n * The text changed. Read at once, after `changeDelay`, or, while an input\n * method composes (`input.isComposing`), once composition ends. While the\n * field is idle the change is autofill: read and committed at once.\n */\n readonly input: (edit: TextEdit<N>) => void;\n /** An input method finished composing: the text is read. */\n readonly endComposition: (nativeEvent: N | null) => void;\n /**\n * The input's own `filterInput` alone, for the text an input method\n * composed, judged as one insert over the range the composition\n * replaced once it has ended: `before` is the text from before it began.\n * The app's `onBeforeInput` saw the composition as it happened. `allow`\n * for an input with no filter.\n */\n readonly filterComposition: (\n edit: TextEdit<N>,\n before: string,\n ) => InputFilterDecision;\n /**\n * How `text` reads with the field's parser (the app's `parse` around the\n * input's own), changing nothing: a segmented date field checks a paste\n * with it before taking it.\n */\n readonly read: (text: string) => ParseResult<V>;\n readonly focus: (nativeEvent: N | null) => void;\n /** Reads any unread text, then commits it. */\n readonly commit: (\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ) => CommitOutcome;\n /** Focus went: the edit commits, unless Tab did already. */\n readonly blur: (nativeEvent: N | null) => void;\n /** Escape: back to the last commit. False when there is nothing to put back. */\n readonly revert: (nativeEvent: N | null) => boolean;\n /** The clear button: `null`, then a commit. */\n readonly clear: (nativeEvent: N | null) => CommitOutcome;\n /** A value chosen whole (a toggle, an option, a preset), then a commit. */\n readonly pick: (\n value: V | null,\n source: ChangeSource,\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ) => CommitOutcome;\n /**\n * A value set whole without a commit (a step, a part of a composite\n * input): the change chain to `value`, with `cause`'s source and native\n * event. Typed text gives way to the value formatted, even when the value\n * stays.\n */\n readonly change: (value: V | null, cause: ChangeCause<N>) => void;\n /** `change` to `value` with `source: \"api\"`. */\n readonly setValue: (value: V | null) => void;\n /** The change chain back to `defaultValue` (or `null`), with `source: \"api\"`. */\n readonly reset: () => void;\n /**\n * The controlled value, which a renderer passes on every update. Adopted\n * whenever the user is not typing, with no event; while they type it is\n * held, and the first `sync` after the edit ends adopts it.\n */\n readonly sync: (value: V | null) => void;\n /** Messages show from now on: a form's submit reveals every field. */\n readonly reveal: () => void;\n /** Cancels a scheduled reading and ignores a pending check's answer. */\n readonly destroy: () => void;\n}\n\n/** What waits to read the draft's text. Each wait holds what reading it needs. */\ntype ReadWait<V, N> =\n | { readonly kind: \"none\" }\n | {\n readonly kind: \"composing\";\n /** The draft before the edits being read, which a refused change puts back. */\n readonly before: FieldDraft<V>;\n readonly cause: ChangeCause<N>;\n }\n | {\n readonly kind: \"delayed\";\n readonly before: FieldDraft<V>;\n readonly cause: ChangeCause<N>;\n readonly cancel: () => void;\n };\n\n/** A pending check, with the blur its `onBlur` reports once it answers. */\ninterface CheckWait<N> {\n readonly check: PendingCheck<N>;\n readonly blurEvent: N | null;\n}\n\nconst NO_READ = { kind: \"none\" } as const;\n\n/** A change made from code: `setValue` and `reset`. */\nconst API: ChangeCause<never> = {\n source: \"api\",\n nativeEvent: null,\n input: null,\n};\n\n/** The source a commit reports, by what triggered it. */\nconst COMMIT_SOURCES: Readonly<Record<CommitTrigger, ChangeSource>> = {\n enter: \"typing\",\n tab: \"typing\",\n blur: \"typing\",\n picker: \"picker\",\n preset: \"preset\",\n clear: \"clear\",\n toggle: \"toggle\",\n autofill: \"autofill\",\n};\n\n/** Writes a value for what `purpose` says the text is for when it is called. */\nfunction formatterOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n purpose: () => FormatPurpose,\n): (value: V | null) => string {\n const format = options.format ?? options.defaultFormat;\n return (value) => {\n const context: FormatContext<V> = {\n defaultFormat: (shown) => options.defaultFormat(shown, context),\n locale: options.locale,\n messages: options.messages,\n purpose: purpose(),\n };\n return format(value, context);\n };\n}\n\nfunction parserOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n): (text: string) => ParseResult<V> {\n const parse = options.parse ?? options.defaultParse;\n const context: ParseContext<V> = {\n defaultParse: (text) => options.defaultParse(text, context),\n locale: options.locale,\n messages: options.messages,\n };\n return (text) => parse(text, context);\n}\n\nfunction validatorOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n): (value: V | null, text: string) => FieldMessage[] {\n const validators = options.validators ?? [];\n return (value, text) =>\n runValidators(validators, value, {\n text,\n locale: options.locale,\n messages: options.messages,\n });\n}\n\n/**\n * A controller for one field. The field starts idle with `value` when\n * given (controlled), else `defaultValue`, else `null`, validated but with\n * no message shown.\n */\nexport function createFieldController<\n V,\n D extends object = NoDetails,\n N = unknown,\n>(initialOptions: FieldOptions<V, D, N>): FieldController<V, D, N> {\n let options = initialOptions;\n const startValue =\n options.value === undefined\n ? (options.defaultValue ?? null)\n : options.value;\n let state = createFieldState<V>(\n startValue,\n validatorOf(options)(\n startValue,\n formatterOf(options, () => \"display\")(startValue),\n ),\n );\n const listeners = new Set<() => void>();\n let read: ReadWait<V, N> = NO_READ;\n let waiting: CheckWait<N> | null = null;\n let attempts = 0;\n let running = false;\n const queue: (() => void)[] = [];\n let shown: { state: FieldState<V>; messages: FieldMessage[] } | null = null;\n // An input that declares details passes `details`; without it, `D` is\n // `NoDetails` and an empty object is all of them.\n const noDetails = (): D => ({}) as D;\n const purposeNow = (): FormatPurpose => formatPurpose(state.phase);\n\n function env(): FieldEnv<V, D, N> {\n return {\n get: () => state,\n dispatch: (action) => (state = fieldReducer(state, action)),\n handlers: options,\n filterInput: options.filterInput,\n parse: parserOf(options),\n format: formatterOf(options, purposeNow),\n same: (a, b) =>\n a === null || b === null\n ? a === b\n : (options.equals ?? Object.is)(a, b),\n validate: validatorOf(options),\n details: options.details ?? noDetails,\n messages: options.messages,\n commitOnLeave: options.commitOnLeave ?? true,\n };\n }\n\n function setRead(next: ReadWait<V, N>): void {\n if (read.kind === \"delayed\" && read !== next) {\n read.cancel();\n }\n read = next;\n }\n\n /**\n * Lets go of what the state no longer needs: a wait to read text that is\n * no longer unread, a check the field is no longer waiting for.\n */\n function release(): void {\n const { draft, phase } = state;\n if (draft.kind !== \"text\" || draft.reading.kind !== \"pending\") {\n setRead(NO_READ);\n }\n if (phase.kind !== \"checking\") {\n waiting = null;\n }\n }\n\n /**\n * Runs `request` to the end, then whatever its handlers asked for in the\n * meantime, then tells listeners once if the state changed. A request made\n * while one runs is queued and answers `queued` at once.\n */\n function run<T>(request: () => T, queued: T): T {\n if (running) {\n queue.push(() => {\n request();\n });\n return queued;\n }\n running = true;\n const before = state;\n try {\n const result = request();\n release();\n for (let next = queue.shift(); next !== undefined; next = queue.shift()) {\n next();\n release();\n }\n return result;\n } finally {\n running = false;\n queue.length = 0;\n if (state !== before) {\n for (const listener of [...listeners]) {\n listener();\n }\n }\n }\n }\n\n function perform(request: () => void): void {\n run(request, undefined);\n }\n\n /** Reads the draft's text now, or once `changeDelay` has passed. */\n function readSoon(before: FieldDraft<V>, cause: ChangeCause<N>): void {\n const delay = options.changeDelay ?? 0;\n const { schedule } = options;\n if (delay > 0 && schedule !== undefined) {\n setRead({\n kind: \"delayed\",\n before,\n cause,\n cancel: schedule(() => {\n perform(flushRead);\n }, delay),\n });\n return;\n }\n setRead(NO_READ);\n runRead(env(), before, cause);\n }\n\n /** Reads text still waiting to be read, at once: a commit needs its value. */\n function flushRead(): void {\n if (read.kind === \"none\") {\n return;\n }\n const { before, cause } = read;\n setRead(NO_READ);\n runRead(env(), before, cause);\n }\n\n function awaitCheck(check: PendingCheck<N>, blurEvent: N | null): void {\n waiting = { check, blurEvent };\n void check.answer.then((refusal) => {\n perform(() => {\n if (waiting?.check !== check) {\n return;\n }\n const settled = waiting;\n waiting = null;\n runSettle(env(), check, refusal, settled.blurEvent);\n });\n });\n }\n\n function track(step: CommitStep<N>, blurEvent: N | null): CommitOutcome {\n if (step.check !== null) {\n awaitCheck(step.check, blurEvent);\n }\n return step.outcome;\n }\n\n function input(edit: TextEdit<N>): void {\n if (state.phase.kind === \"idle\") {\n const check = runAutofill(env(), edit, ++attempts);\n if (check !== null) {\n awaitCheck(check, null);\n }\n return;\n }\n const before = read.kind === \"none\" ? state.draft : read.before;\n const edited = runEdit(env(), edit);\n if (edit.input?.isComposing === true) {\n if (edited) {\n setRead({ kind: \"composing\", before, cause: edit });\n }\n return;\n }\n // A plain input also ends a composition whose end was not reported.\n if (edited || read.kind === \"composing\") {\n readSoon(before, edit);\n }\n }\n\n return {\n getState: () => state,\n getText: () => fieldText(state, formatterOf(options, purposeNow)),\n getMessages: () => {\n if (shown?.state !== state) {\n shown = { state, messages: fieldMessages(state) };\n }\n return shown.messages;\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setOptions: (next) => {\n options = next;\n },\n // Changes no state, so it runs even inside another request: the browser\n // needs its answer before the edit happens.\n beforeInput: (edit) => runBeforeInput(env(), edit),\n input: (edit) => {\n perform(() => {\n input(edit);\n });\n },\n endComposition: (nativeEvent) => {\n perform(() => {\n if (read.kind !== \"composing\") {\n return;\n }\n const { before, cause } = read;\n readSoon(before, {\n ...cause,\n nativeEvent,\n input: cause.input && { ...cause.input, isComposing: false },\n });\n });\n },\n filterComposition: (edit, before) =>\n options.filterInput?.(edit, before) ?? { kind: \"allow\" },\n read: (text) => parserOf(options)(text),\n focus: (nativeEvent) => {\n perform(() => {\n runFocus(env(), nativeEvent);\n });\n },\n commit: (trigger, nativeEvent) =>\n run(() => {\n flushRead();\n return track(\n runCommit(env(), {\n trigger,\n source: COMMIT_SOURCES[trigger],\n nativeEvent,\n attempt: ++attempts,\n }),\n trigger === \"blur\" ? nativeEvent : null,\n );\n }, CHECKING),\n blur: (nativeEvent) => {\n perform(() => {\n flushRead();\n if (waiting !== null) {\n waiting = { ...waiting, blurEvent: nativeEvent };\n }\n const check = runBlur(env(), nativeEvent, ++attempts);\n if (check !== null) {\n awaitCheck(check, nativeEvent);\n }\n });\n },\n revert: (nativeEvent) => run(() => runRevert(env(), nativeEvent), false),\n clear: (nativeEvent) =>\n run(\n () => track(runClear(env(), nativeEvent, ++attempts), null),\n CHECKING,\n ),\n pick: (value, source, trigger, nativeEvent) =>\n run(\n () =>\n track(\n runPick(env(), value, {\n trigger,\n source,\n nativeEvent,\n attempt: ++attempts,\n }),\n null,\n ),\n CHECKING,\n ),\n change: (value, cause) => {\n perform(() => {\n runValueChange(env(), value, cause);\n });\n },\n setValue: (value) => {\n perform(() => {\n runValueChange(env(), value, API);\n });\n },\n reset: () => {\n perform(() => {\n runValueChange(env(), options.defaultValue ?? null, API);\n });\n },\n sync: (value) => {\n perform(() => {\n runSync(env(), value);\n });\n },\n reveal: () => {\n perform(() => {\n runReveal(env());\n });\n },\n destroy: () => {\n setRead(NO_READ);\n waiting = null;\n },\n };\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n unreadable,\n type FormatContext,\n type FormatPurpose,\n type ParseResult,\n} from \"../parse\";\nimport {\n createFieldController,\n type FieldController,\n type FieldOptions,\n} from \"./createFieldController\";\nimport type { CommitTrigger, FieldBeforeInputEvent, NoDetails } from \"./events\";\nimport type { ChangeCause, CommitOutcome } from \"./plan\";\nimport { unreadableMessage, type FieldState } from \"./state\";\n\n/** Each part's value, by part name; `null` for an empty part. */\nexport type PartValues<P extends Record<string, unknown>> = {\n readonly [K in keyof P]: P[K] | null;\n};\n\n/** Each part's text, by part name. */\nexport type PartTexts<P extends Record<string, unknown>> = {\n readonly [K in keyof P]: string;\n};\n\n/**\n * Which part an event is about: the part whose edit it is, `\"all\"` for a\n * value set whole (`setValue`, a controlled value, a revert or clear), and\n * on a commit the part that differs from the last commit (`\"all\"` when\n * several do, `null` when none does).\n */\nexport type PartChange<P extends Record<string, unknown>> =\n keyof P | \"all\" | null;\n\n/** How one part reads and writes its text. The composite owns its value and events. */\nexport type PartOptions<T, N = unknown> = Pick<\n FieldOptions<T, NoDetails, N>,\n | \"parse\"\n | \"format\"\n | \"defaultParse\"\n | \"defaultFormat\"\n | \"equals\"\n | \"filterInput\"\n | \"locale\"\n>;\n\n/** What `assemble` knows beside the parts' values. */\nexport interface AssembleContext {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/** What a composite input's `details` is told beside the field's state. */\nexport interface CompositeDetailsContext<\n P extends Record<string, unknown>,\n N = unknown,\n> {\n readonly changed: PartChange<P>;\n readonly parts: { readonly [K in keyof P]: FieldState<P[K]> };\n readonly texts: PartTexts<P>;\n /** The change the event is about, as `FieldOptions.details` receives it. */\n readonly cause: ChangeCause<N>;\n}\n\n/**\n * What a composite input is given: the field's options, as for one input,\n * with how each part reads and writes, and how the parts' values make the\n * one value the app sees and back. The renderer passes the latest on every\n * update through `setOptions`.\n */\nexport interface CompositeFieldOptions<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n> extends Omit<\n FieldOptions<V, D, N>,\n | \"parse\"\n | \"format\"\n | \"defaultParse\"\n | \"defaultFormat\"\n | \"details\"\n | \"filterInput\"\n | \"changeDelay\"\n | \"schedule\"\n | \"commitOnLeave\"\n> {\n /** Each part, in the order the parts are read: a part's unreadable text is reported first. */\n readonly parts: { readonly [K in keyof P]: PartOptions<P[K], N> };\n /** The value the parts make, or why they make none (an end before its start). */\n readonly assemble: (\n parts: PartValues<P>,\n context: AssembleContext,\n ) => ParseResult<V>;\n /** Each part's value within `value`. */\n readonly split: (value: V | null) => PartValues<P>;\n /** The field's text, which events carry: the parts' texts, joined. */\n readonly join: (texts: PartTexts<P>) => string;\n /** The input's own details, added to every event the field fires. */\n readonly details?:\n | ((\n current: FieldState<V>,\n previous: FieldState<V>,\n context: CompositeDetailsContext<P, N>,\n ) => D)\n | undefined;\n}\n\n/**\n * One part's controller, for a renderer to attach a control to as it\n * would a field's: its text and state are the part's own; its edits,\n * Enter, Escape and the clear button act on the whole field.\n */\nexport type PartController<T, N = unknown> = Pick<\n FieldController<T, NoDetails, N>,\n | \"getState\"\n | \"getText\"\n | \"getMessages\"\n | \"subscribe\"\n | \"beforeInput\"\n | \"input\"\n | \"endComposition\"\n | \"filterComposition\"\n | \"read\"\n | \"focus\"\n | \"commit\"\n | \"blur\"\n | \"revert\"\n | \"clear\"\n | \"reset\"\n | \"change\"\n>;\n\n/** The field and its parts, whole: one object until any of them changes. */\nexport interface CompositeState<V, P extends Record<string, unknown>> {\n readonly field: FieldState<V>;\n readonly parts: { readonly [K in keyof P]: FieldState<P[K]> };\n}\n\n/**\n * An input made of parts (both ends of a range, an amount and its\n * currency) driven as one field. Expect this API to change while its first\n * users settle it.\n */\nexport interface CompositeController<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n> {\n /** The field the app sees: its events, value and messages. */\n readonly field: Omit<FieldController<V, D, N>, \"setOptions\">;\n /** One controller per part, for a renderer to attach a control to. */\n readonly parts: { readonly [K in keyof P]: PartController<P[K], N> };\n readonly getState: () => CompositeState<V, P>;\n /** Calls `listener` after each request that changed the field or a part. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Replaces the options, silently. */\n readonly setOptions: (options: CompositeFieldOptions<V, P, D, N>) => void;\n /**\n * Focus left the whole input (a part's own blur cannot tell): the field\n * commits with `trigger` `\"tab\"` or `\"blur\"`, then `onBlur`.\n */\n readonly leave: (by: \"tab\" | \"blur\", nativeEvent: N | null) => void;\n /** Cancels what the field and its parts wait for. */\n readonly destroy: () => void;\n}\n\n/** What the field is doing, which its events' `PartChange` reports. */\ntype Activity<P> =\n | { readonly kind: \"whole\" }\n | { readonly kind: \"part\"; readonly part: keyof P }\n | { readonly kind: \"commit\" };\n\nconst WHOLE = { kind: \"whole\" } as const;\nconst COMMITTING = { kind: \"commit\" } as const;\n\n/** A value the composite pushes into a part. */\nconst API: ChangeCause<never> = {\n source: \"api\",\n nativeEvent: null,\n input: null,\n};\n\n/**\n * A controller for an input made of parts. Each part is a field of its\n * own with no app handlers: it reads, filters and writes its text as a\n * lone input does. The composite relays every part edit to the field the\n * app sees as an edit of the joined text, so `onBeforeInput` and `onInput`\n * fire with the part's edit, and the field reads its value from the parts\n * (`assemble`), then runs the change chain. A value the field takes whole\n * (`setValue` in `onBeforeChange`, a controlled value, a revert, a clear)\n * is pushed into the parts by `split`; a part whose text already reads as\n * its value keeps it while the user types, and every part shows its value\n * formatted once the field commits.\n *\n * Tab from part to part commits only the part, normalizing its text.\n * Enter in a part commits the field; Escape reverts it. Focus entering a\n * part of an idle field fires `onFocus`; focus leaving the whole input is\n * the renderer's to report through `leave`. Parts read at once: they take\n * no `changeDelay`.\n */\nexport function createCompositeController<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n>(\n initialOptions: CompositeFieldOptions<V, P, D, N>,\n): CompositeController<V, P, D, N> {\n let options = initialOptions;\n let activity: Activity<P> = WHOLE;\n // The part names, in the order the options list them. `keyof P` holds\n // exactly these keys, which `Object.keys` cannot say.\n const names = Object.keys(options.parts) as (keyof P)[];\n\n /** One entry per part, made by `make`. */\n function eachPart<R>(make: (name: keyof P) => R): Record<keyof P, R> {\n // `fromEntries` loses the keys' type; there is one entry per name.\n return Object.fromEntries(\n names.map((name) => [name, make(name)]),\n ) as Record<keyof P, R>;\n }\n\n function during<R>(next: Activity<P>, request: () => R): R {\n const before = activity;\n activity = next;\n try {\n return request();\n } finally {\n activity = before;\n }\n }\n\n function same(a: V | null, b: V | null): boolean {\n return a === null || b === null\n ? a === b\n : (options.equals ?? Object.is)(a, b);\n }\n\n function samePart<K extends keyof P>(\n name: K,\n a: P[K] | null,\n b: P[K] | null,\n ): boolean {\n return a === null || b === null\n ? a === b\n : (options.parts[name].equals ?? Object.is)(a, b);\n }\n\n function formatPart<K extends keyof P>(\n name: K,\n value: P[K] | null,\n purpose: FormatPurpose,\n ): string {\n const own = options.parts[name];\n const context: FormatContext<P[K]> = {\n defaultFormat: (shown) => own.defaultFormat(shown, context),\n locale: own.locale ?? options.locale,\n messages: options.messages,\n purpose,\n };\n return (own.format ?? own.defaultFormat)(value, context);\n }\n\n function partOptions<K extends keyof P>(\n name: K,\n value: P[K] | null,\n ): FieldOptions<P[K], NoDetails, N> {\n const own = options.parts[name];\n return {\n ...own,\n defaultValue: value,\n locale: own.locale ?? options.locale,\n messages: options.messages,\n onBeforeInput: (event) => {\n relayBeforeInput(name, event);\n },\n };\n }\n\n const startValue =\n options.value === undefined\n ? (options.defaultValue ?? null)\n : options.value;\n const startParts = options.split(startValue);\n // One controller per part; `eachPart` keys them by name.\n const parts = eachPart((name) =>\n createFieldController(partOptions(name, startParts[name])),\n ) as unknown as {\n readonly [K in keyof P]: FieldController<P[K], NoDetails, N>;\n };\n\n function texts(): PartTexts<P> {\n return eachPart((name) => parts[name].getText());\n }\n\n /** What the parts make now: the first unreadable part's message, or `assemble`'s reading. */\n function readParts(): ParseResult<V> {\n for (const name of names) {\n const message = unreadableMessage(parts[name].getState().draft);\n if (message !== null) {\n return unreadable(message);\n }\n }\n // Each entry is its part's value.\n const values = eachPart(\n (name) => parts[name].getState().value,\n ) as PartValues<P>;\n return options.assemble(values, {\n locale: options.locale,\n messages: options.messages,\n });\n }\n\n function changedNow(previous: FieldState<V>): PartChange<P> {\n switch (activity.kind) {\n case \"part\":\n return activity.part;\n case \"whole\":\n return \"all\";\n case \"commit\": {\n const { phase } = previous;\n if (phase.kind === \"idle\") {\n return \"all\";\n }\n const now = options.split(previous.value);\n const committed = options.split(phase.committedValue);\n const differ = names.filter(\n (name) => !samePart(name, now[name], committed[name]),\n );\n const [only] = differ;\n if (differ.length === 0 || only === undefined) {\n return null;\n }\n return differ.length === 1 ? only : \"all\";\n }\n }\n }\n\n function fieldOptions(): FieldOptions<V, D, N> {\n const { details } = options;\n return {\n ...options,\n defaultParse: () => readParts(),\n defaultFormat: (value, context) => {\n const values = options.split(value);\n return options.join(\n eachPart((name) => formatPart(name, values[name], context.purpose)),\n );\n },\n details:\n details &&\n ((current, previous, cause) =>\n details(current, previous, {\n changed: changedNow(previous),\n // Each entry is its part's state.\n parts: eachPart((name) => parts[name].getState()) as {\n readonly [K in keyof P]: FieldState<P[K]>;\n },\n texts: texts(),\n cause,\n })),\n };\n }\n\n const field = createFieldController(fieldOptions());\n\n /** The app's `onBeforeInput` for a part's edit, as an edit of the joined text. */\n function relayBeforeInput<K extends keyof P>(\n name: K,\n event: FieldBeforeInputEvent<P[K], NoDetails, N>,\n ): void {\n const decision = during({ kind: \"part\", part: name }, () =>\n field.beforeInput({\n text: options.join({ ...texts(), [name]: event.text }),\n source: event.source,\n nativeEvent: event.nativeEvent,\n input: event.input,\n cancelable: event.cancelable,\n }),\n );\n if (decision.kind === \"prevent\") {\n event.preventDefault();\n } else if (decision.kind === \"rewrite\") {\n event.setData(decision.data);\n }\n }\n\n /** A part's text changed: the field sees an edit of the joined text. */\n function relayEdit(name: keyof P, cause: ChangeCause<N>): void {\n during({ kind: \"part\", part: name }, () => {\n field.input({ ...cause, text: options.join(texts()) });\n });\n }\n\n /**\n * Shows the field's value in the parts. A part keeps its text when it\n * already holds its value and, unless `exact`, while that text reads as\n * it (typed digits not yet normalized). A part being composed is left to\n * the input method.\n */\n function showValue(exact: boolean): void {\n const target = options.split(field.getState().value);\n for (const name of names) {\n const part = parts[name];\n const { draft, value } = part.getState();\n if (draft.kind === \"text\" && draft.reading.kind === \"pending\") {\n continue;\n }\n const reads = draft.kind === \"current\" || draft.reading.kind === \"value\";\n if (\n samePart(name, value, target[name]) &&\n (draft.kind === \"current\" || (!exact && reads))\n ) {\n continue;\n }\n part.change(target[name], API);\n }\n }\n\n /**\n * After each request that changed the field: an idle field shows its\n * value in every part exactly (a swapped range's texts change places);\n * otherwise a value the parts do not make came from elsewhere, and is\n * pushed into them. Text that cannot be read is the user's, left alone.\n */\n function followField(): void {\n const state = field.getState();\n if (state.draft.kind === \"current\" && state.phase.kind === \"idle\") {\n showValue(true);\n return;\n }\n if (state.draft.kind === \"text\" && state.draft.reading.kind !== \"value\") {\n return;\n }\n const made = readParts();\n if (made.kind === \"value\" && same(made.value, state.value)) {\n return;\n }\n showValue(false);\n }\n field.subscribe(followField);\n\n function commitWhole(\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ): CommitOutcome {\n return during(COMMITTING, () => {\n const outcome = field.commit(trigger, nativeEvent);\n if (outcome.kind === \"accepted\") {\n showValue(true);\n }\n return outcome;\n });\n }\n\n function facade<K extends keyof P>(name: K): PartController<P[K], N> {\n const part = parts[name];\n return {\n getState: part.getState,\n getText: part.getText,\n getMessages: part.getMessages,\n subscribe: part.subscribe,\n beforeInput: part.beforeInput,\n input: (edit) => {\n part.input(edit);\n relayEdit(name, edit);\n },\n endComposition: (nativeEvent) => {\n part.endComposition(nativeEvent);\n during({ kind: \"part\", part: name }, () => {\n field.endComposition(nativeEvent);\n });\n },\n filterComposition: part.filterComposition,\n read: part.read,\n focus: (nativeEvent) => {\n part.focus(nativeEvent);\n field.focus(nativeEvent);\n },\n commit: (trigger, nativeEvent) =>\n trigger === \"tab\"\n ? part.commit(trigger, nativeEvent)\n : commitWhole(trigger, nativeEvent),\n blur: part.blur,\n revert: (nativeEvent) => {\n const reverted = field.revert(nativeEvent);\n if (reverted) {\n showValue(true);\n }\n return reverted;\n },\n clear: field.clear,\n reset: field.reset,\n change: (value, cause) => {\n part.change(value, cause);\n relayEdit(name, cause);\n },\n };\n }\n\n // One facade per part; `eachPart` keys them by name.\n const facades = eachPart(facade) as unknown as {\n readonly [K in keyof P]: PartController<P[K], N>;\n };\n\n let snapshot: CompositeState<V, P> | null = null;\n\n return {\n field,\n parts: facades,\n getState: () => {\n const fieldState = field.getState();\n if (\n snapshot?.field !== fieldState ||\n names.some((name) => snapshot?.parts[name] !== parts[name].getState())\n ) {\n snapshot = {\n field: fieldState,\n // Each entry is its part's state.\n parts: eachPart((name) => parts[name].getState()) as {\n readonly [K in keyof P]: FieldState<P[K]>;\n },\n };\n }\n return snapshot;\n },\n subscribe: (listener) => {\n const unsubscribes = [\n field.subscribe(listener),\n ...names.map((name) => parts[name].subscribe(listener)),\n ];\n return () => {\n for (const unsubscribe of unsubscribes) {\n unsubscribe();\n }\n };\n },\n setOptions: (next) => {\n options = next;\n field.setOptions(fieldOptions());\n for (const name of names) {\n parts[name].setOptions(partOptions(name, parts[name].getState().value));\n }\n },\n leave: (by, nativeEvent) => {\n during(COMMITTING, () => {\n if (field.getState().phase.kind === \"idle\") {\n return;\n }\n if (by === \"tab\") {\n field.commit(\"tab\", nativeEvent);\n }\n field.blur(nativeEvent);\n });\n },\n destroy: () => {\n field.destroy();\n for (const name of names) {\n parts[name].destroy();\n }\n },\n };\n}\n","/** A token of an app's own: one character it accepts, and how it is written. */\nexport interface MaskTokenDefinition {\n /** Tested against one character, after its digits and full-width forms become ASCII. */\n readonly accept: RegExp;\n /** Whether the slot may stay empty. False by default. */\n readonly optional?: boolean | undefined;\n /** Applied to the character before it is kept; the case tokens still apply after. */\n readonly transform?: ((character: string) => string) | undefined;\n}\n\n/** One-character token names, beside the built-in tokens, which they may replace. */\nexport type MaskTokens = Readonly<Record<string, RegExp | MaskTokenDefinition>>;\n\n/** How letters typed into a slot are written, as `>`, `<` and `|` set it. */\nexport type MaskLetterCase = \"upper\" | \"lower\" | \"keep\";\n\n/**\n * One place in a compiled pattern: a slot that takes a character, or a\n * literal printed as it is. `section` numbers the optional section (`[ ]`)\n * it sits in, `null` outside one.\n */\nexport type MaskSlot =\n | {\n readonly kind: \"input\";\n /** The token that made it: `\"0\"`, `\"L\"`, an app's own. */\n readonly token: string;\n readonly accepts: (character: string) => boolean;\n readonly optional: boolean;\n readonly transform: ((character: string) => string) | null;\n readonly letterCase: MaskLetterCase;\n readonly section: number | null;\n }\n | {\n readonly kind: \"literal\";\n readonly character: string;\n readonly section: number | null;\n };\n\n/** A pattern compiled into its slots. */\nexport interface CompiledMask {\n readonly pattern: string;\n readonly slots: readonly MaskSlot[];\n}\n\n/**\n * A compiled pattern, or why it could not be compiled. `position` is the\n * index in the pattern where the problem starts, `null` for a problem in\n * the custom tokens.\n */\nexport type MaskCompileResult =\n | { readonly kind: \"compiled\"; readonly mask: CompiledMask }\n | {\n readonly kind: \"error\";\n readonly message: string;\n readonly position: number | null;\n };\n\ninterface Token {\n readonly accepts: (character: string) => boolean;\n readonly optional: boolean;\n readonly transform: ((character: string) => string) | null;\n}\n\nconst DIGIT = /^[0-9]$/;\nconst LETTER = /^\\p{L}$/u;\nconst LETTER_OR_DIGIT = /^[\\p{L}0-9]$/u;\n\nfunction digit(character: string): boolean {\n return DIGIT.test(character);\n}\n\nfunction letter(character: string): boolean {\n return LETTER.test(character);\n}\n\nfunction letterOrDigit(character: string): boolean {\n return LETTER_OR_DIGIT.test(character);\n}\n\nconst BUILT_IN_TOKENS: Readonly<Record<string, Token>> = {\n \"0\": { accepts: digit, optional: false, transform: null },\n \"9\": { accepts: digit, optional: true, transform: null },\n \"#\": {\n accepts: (character) =>\n digit(character) || character === \"+\" || character === \"-\",\n optional: true,\n transform: null,\n },\n L: { accepts: letter, optional: false, transform: null },\n \"?\": { accepts: letter, optional: true, transform: null },\n \"&\": {\n accepts: (character) => !/^\\s$/u.test(character),\n optional: false,\n transform: null,\n },\n C: { accepts: () => true, optional: true, transform: null },\n A: { accepts: letterOrDigit, optional: false, transform: null },\n a: { accepts: letterOrDigit, optional: true, transform: null },\n};\n\n/** Characters the grammar itself uses, which no token may be named. */\nconst GRAMMAR = new Set([\"\\\\\", \"[\", \"]\", \">\", \"<\", \"|\"]);\n\nconst CASES: Readonly<Record<string, MaskLetterCase>> = {\n \">\": \"upper\",\n \"<\": \"lower\",\n \"|\": \"keep\",\n};\n\n/** `pattern` tested against a whole character: `g` and `y` make `test` remember where it stopped, so they are dropped. */\nfunction characterTest(pattern: RegExp): (character: string) => boolean {\n const whole = new RegExp(\n `^(?:${pattern.source})$`,\n pattern.flags.replace(/[gy]/g, \"\"),\n );\n return (character) => whole.test(character);\n}\n\nfunction customToken(definition: RegExp | MaskTokenDefinition): Token {\n if (definition instanceof RegExp) {\n return {\n accepts: characterTest(definition),\n optional: false,\n transform: null,\n };\n }\n return {\n accepts: characterTest(definition.accept),\n optional: definition.optional ?? false,\n transform: definition.transform ?? null,\n };\n}\n\nfunction compileError(\n message: string,\n position: number | null,\n): MaskCompileResult {\n return { kind: \"error\", message, position };\n}\n\n/** The built-in tokens with `tokens` laid over them, or why `tokens` cannot be used. */\nfunction tokenTable(\n tokens: MaskTokens | undefined,\n): Readonly<Record<string, Token>> | string {\n if (tokens === undefined) {\n return BUILT_IN_TOKENS;\n }\n const table: Record<string, Token> = { ...BUILT_IN_TOKENS };\n for (const [name, definition] of Object.entries(tokens)) {\n if (Array.from(name).length !== 1) {\n return `A token's name is one character, not \"${name}\"`;\n }\n if (GRAMMAR.has(name)) {\n return `\"${name}\" is part of the mask grammar and cannot name a token`;\n }\n table[name] = customToken(definition);\n }\n return table;\n}\n\n/**\n * Compiles `pattern` on the .NET-style grammar: `0` a digit, `9` an\n * optional digit, `#` an optional digit, `+` or `-`, `L` a letter, `?` an\n * optional letter, `&` any character but a space, `C` any optional\n * character, `A` a letter or digit, `a` an optional one; `>`, `<` and `|`\n * upper-case, lower-case or keep the letters after them; `\\` makes the next\n * character a literal; `[ ]` holds an optional section, which appears once\n * one of its slots is filled; anything else is a literal. `tokens` adds\n * one-character tokens of an app's own, or replaces built-in ones.\n *\n * A malformed pattern (an unclosed, nested or stray bracket, an empty\n * section, a trailing `\\`, no slot at all) is an error with its position.\n */\nexport function compileMask(\n pattern: string,\n tokens?: MaskTokens,\n): MaskCompileResult {\n const table = tokenTable(tokens);\n if (typeof table === \"string\") {\n return compileError(table, null);\n }\n const slots: MaskSlot[] = [];\n let letterCase: MaskLetterCase = \"keep\";\n let section: { readonly id: number; readonly start: number } | null = null;\n let sections = 0;\n let sectionHasInput = false;\n let escaped = false;\n let index = 0;\n for (const character of pattern) {\n const position = index;\n index += character.length;\n if (escaped) {\n slots.push({ kind: \"literal\", character, section: section?.id ?? null });\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (character === \"[\") {\n if (section !== null) {\n return compileError(\"Optional sections cannot nest\", position);\n }\n section = { id: sections, start: position };\n sections += 1;\n sectionHasInput = false;\n continue;\n }\n if (character === \"]\") {\n if (section === null) {\n return compileError(\n 'A \"]\" closes no section; write \"\\\\]\" for the character',\n position,\n );\n }\n if (!sectionHasInput) {\n return compileError(\n \"An optional section needs at least one slot\",\n section.start,\n );\n }\n section = null;\n continue;\n }\n const nextCase = CASES[character];\n if (nextCase !== undefined) {\n letterCase = nextCase;\n continue;\n }\n const token = table[character];\n if (token === undefined) {\n slots.push({ kind: \"literal\", character, section: section?.id ?? null });\n continue;\n }\n slots.push({\n kind: \"input\",\n token: character,\n accepts: token.accepts,\n optional: token.optional,\n transform: token.transform,\n letterCase,\n section: section?.id ?? null,\n });\n sectionHasInput = true;\n }\n if (escaped) {\n return compileError(\n 'A \"\\\\\" at the end escapes nothing',\n pattern.length - 1,\n );\n }\n if (section !== null) {\n return compileError(\"This optional section is not closed\", section.start);\n }\n if (!slots.some((slot) => slot.kind === \"input\")) {\n return compileError(\"A mask needs at least one slot\", 0);\n }\n return { kind: \"compiled\", mask: { pattern, slots } };\n}\n\n/** Patterns compiled so far, per token set: a mask compiles on every edit. */\nconst compiledByTokens = new WeakMap<MaskTokens, Map<string, CompiledMask>>();\nconst compiledBuiltIn = new Map<string, CompiledMask>();\n\n/**\n * `pattern` compiled with `tokens`, from the cache when it has been before.\n * Throws on a malformed pattern: an input checks its patterns with\n * `compileMask` before it relies on them.\n */\nexport function compiledPattern(\n pattern: string,\n tokens: MaskTokens | undefined,\n): CompiledMask {\n let cache = compiledBuiltIn;\n if (tokens !== undefined) {\n cache = compiledByTokens.get(tokens) ?? new Map<string, CompiledMask>();\n compiledByTokens.set(tokens, cache);\n }\n const cached = cache.get(pattern);\n if (cached !== undefined) {\n return cached;\n }\n const result = compileMask(pattern, tokens);\n if (result.kind === \"error\") {\n throw new SyntaxError(\n `Mask \"${pattern}\": ${result.message}${\n result.position === null ? \"\" : ` (at ${String(result.position)})`\n }`,\n );\n }\n cache.set(pattern, result.mask);\n return result.mask;\n}\n","import { digitValue, isDigit } from \"../number/digits\";\nimport type { CompiledMask, MaskSlot } from \"./grammar\";\n\n// The mask's model: a compiled pattern's slots, each input slot filled,\n// empty or skipped (an optional slot typed past). An edit works on items,\n// the characters typed and the steps past literals that skipped slots,\n// laid into the slots in order with no holes. The engine keeps nothing\n// between edits: it reads the text on screen back into cells, edits the\n// items, lays them out again and writes the text.\n\n/** What one input slot holds. Entries for literals stay empty. */\nexport type MaskCell =\n | { readonly kind: \"filled\"; readonly character: string }\n | { readonly kind: \"skipped\" }\n | { readonly kind: \"empty\" };\n\n/**\n * What an edit moves around: a character for an input slot, or a step past\n * the literal `literal`, leaving the optional slots before it skipped\n * (typing \".\" after \"19\" in an IPv4 mask).\n */\nexport type MaskItem =\n | { readonly kind: \"character\"; readonly character: string }\n | { readonly kind: \"jump\"; readonly literal: string };\n\n/** An item, and the index in the text where it was read. */\nexport interface PlacedItem {\n readonly item: MaskItem;\n readonly at: number;\n}\n\n/**\n * What laying out does with an item no slot takes: `truncate` drops it\n * with every item after it, `lenient` (a paste) drops it alone.\n */\nexport type LayoutMode = \"truncate\" | \"lenient\";\n\n/** Items laid into a pattern. */\nexport interface MaskLayout {\n readonly mask: CompiledMask;\n readonly cells: readonly MaskCell[];\n /** For each item, the slot it filled or the literal it stepped past; `null` when dropped. */\n readonly landed: readonly (number | null)[];\n /** How many characters found a slot. */\n readonly kept: number;\n}\n\nconst EMPTY: MaskCell = { kind: \"empty\" };\nconst SKIPPED: MaskCell = { kind: \"skipped\" };\n\n/**\n * `character` as a mask keeps it: a decimal digit of any script as its\n * ASCII digit, a full-width form (from an input method) as its ASCII.\n */\nexport function maskCharacter(character: string): string {\n if (isDigit(character)) {\n return String(digitValue(character));\n }\n const code = character.codePointAt(0) ?? 0;\n if (code >= 0xff01 && code <= 0xff5e) {\n return String.fromCodePoint(code - 0xfee0);\n }\n return code === 0x3000 ? \" \" : character;\n}\n\n/** `character` as `slot` keeps it, after its transform and case; `null` when the slot refuses it. */\nfunction accepted(\n slot: Extract<MaskSlot, { kind: \"input\" }>,\n character: string,\n locale: Intl.LocalesArgument,\n): string | null {\n if (!slot.accepts(character)) {\n return null;\n }\n const kept = slot.transform === null ? character : slot.transform(character);\n switch (slot.letterCase) {\n case \"upper\":\n return kept.toLocaleUpperCase(locale);\n case \"lower\":\n return kept.toLocaleLowerCase(locale);\n case \"keep\":\n return kept;\n }\n}\n\n/**\n * Places `item` in the first slot from `from` that takes it, into `cells`.\n * A character fills the next input slot that accepts it, crossing\n * literals; one equal to a literal it reaches steps past it. Either may\n * skip optional slots that refuse it on the way, which are then marked\n * skipped; a required slot that refuses it stops it. A slot that accepts\n * the character wins over a literal after it.\n */\nfunction place(\n slots: readonly MaskSlot[],\n cells: MaskCell[],\n from: number,\n item: MaskItem,\n locale: Intl.LocalesArgument,\n): number | null {\n const skipped: number[] = [];\n const settle = (slot: number, cell: MaskCell | null) => {\n for (const index of skipped) {\n cells[index] = SKIPPED;\n }\n if (cell !== null) {\n cells[slot] = cell;\n }\n return slot;\n };\n const character = item.kind === \"jump\" ? item.literal : item.character;\n for (let index = from; index < slots.length; index += 1) {\n const slot = slots[index];\n if (slot === undefined) {\n break;\n }\n if (slot.kind === \"literal\") {\n if (slot.character === character) {\n return settle(index, null);\n }\n continue;\n }\n if (item.kind === \"character\") {\n const kept = accepted(slot, character, locale);\n if (kept !== null) {\n return settle(index, { kind: \"filled\", character: kept });\n }\n }\n if (!slot.optional) {\n return null;\n }\n skipped.push(index);\n }\n return null;\n}\n\n/** `items` laid into `mask` from its start. */\nexport function layOut(\n mask: CompiledMask,\n items: readonly MaskItem[],\n mode: LayoutMode,\n locale: Intl.LocalesArgument,\n): MaskLayout {\n const cells: MaskCell[] = mask.slots.map(() => EMPTY);\n const landed: (number | null)[] = [];\n let next = 0;\n let kept = 0;\n let stopped = false;\n for (const item of items) {\n const slot = stopped ? null : place(mask.slots, cells, next, item, locale);\n if (slot === null) {\n stopped = mode === \"truncate\";\n landed.push(null);\n continue;\n }\n landed.push(slot);\n next = slot + 1;\n if (item.kind === \"character\") {\n kept += 1;\n }\n }\n return { mask, cells, landed, kept };\n}\n\n/** Whether every item found a place. */\nexport function fits(layout: MaskLayout): boolean {\n return layout.landed.every((slot) => slot !== null);\n}\n\n/**\n * The items a layout holds, each at the text index `at` gives its slot: a\n * character per filled slot, and a jump at each literal that follows\n * skipped slots.\n */\nexport function itemsOf(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n at: readonly number[],\n): PlacedItem[] {\n const items: PlacedItem[] = [];\n let skipping = false;\n mask.slots.forEach((slot, index) => {\n const cell = cells[index] ?? EMPTY;\n if (slot.kind === \"literal\") {\n if (skipping) {\n items.push({\n item: { kind: \"jump\", literal: slot.character },\n at: at[index] ?? 0,\n });\n skipping = false;\n }\n } else if (cell.kind === \"filled\") {\n items.push({\n item: { kind: \"character\", character: cell.character },\n at: at[index] ?? 0,\n });\n skipping = false;\n } else if (cell.kind === \"skipped\") {\n skipping = true;\n }\n });\n return items;\n}\n\n/** Cells read from text, with the text index of each slot (where it would be, when not printed). */\nexport interface MaskReading {\n readonly cells: readonly MaskCell[];\n readonly at: readonly number[];\n}\n\n/**\n * Reads `text` as `mask` writes it, focused or not: a prompt character is\n * an empty slot, an optional slot facing a character it refuses is\n * skipped, and a literal that is not there was not printed. `null` when the\n * text is not this pattern's: a required slot refuses its character, a\n * required slot is empty before a filled one, or text is left over.\n */\nexport function readExact(\n mask: CompiledMask,\n text: string,\n prompt: string,\n locale: Intl.LocalesArgument,\n): MaskReading | null {\n const characters = Array.from(text);\n const cells: MaskCell[] = [];\n const at: number[] = [];\n let next = 0;\n let index = 0;\n for (const slot of mask.slots) {\n at.push(index);\n const typed = characters[next];\n if (slot.kind === \"literal\") {\n cells.push(EMPTY);\n if (typed === slot.character) {\n next += 1;\n index += typed.length;\n }\n continue;\n }\n if (typed === undefined || (prompt !== \"\" && typed === prompt)) {\n cells.push(EMPTY);\n } else {\n const kept = accepted(slot, maskCharacter(typed), locale);\n if (kept !== null) {\n cells.push({ kind: \"filled\", character: kept });\n } else if (slot.optional) {\n cells.push(SKIPPED);\n continue;\n } else {\n return null;\n }\n }\n if (typed !== undefined) {\n next += 1;\n index += typed.length;\n }\n }\n if (next < characters.length) {\n return null;\n }\n const last = cells.findLastIndex((cell) => cell.kind === \"filled\");\n for (let slot = 0; slot < last; slot += 1) {\n const definition = mask.slots[slot];\n if (definition?.kind === \"input\" && cells[slot]?.kind === \"empty\") {\n if (!definition.optional) {\n return null;\n }\n cells[slot] = SKIPPED;\n }\n }\n return { cells, at };\n}\n\n/** The sections with a filled slot: only they print. */\nfunction filledSections(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): ReadonlySet<number> {\n const sections = new Set<number>();\n mask.slots.forEach((slot, index) => {\n if (slot.section !== null && cells[index]?.kind === \"filled\") {\n sections.add(slot.section);\n }\n });\n return sections;\n}\n\n/** Text written from cells, with where each slot starts in it (`offsets[slots.length]` is the end). */\nexport interface MaskWriting {\n readonly text: string;\n readonly offsets: readonly number[];\n}\n\n/**\n * The text cells show. While focused: literals, filled characters, the\n * prompt in each empty slot, nothing for skipped slots, and nothing of an\n * optional section with no slot filled; with no prompt character, the text\n * ends at the first empty slot. Otherwise (display, and the formatted\n * value): literals and filled characters up to the last filled slot.\n */\nexport function writeCells(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n focused: boolean,\n prompt: string,\n): MaskWriting {\n const sections = filledSections(mask, cells);\n const last = cells.findLastIndex((cell) => cell.kind === \"filled\");\n const offsets: number[] = [];\n let text = \"\";\n let ended = false;\n mask.slots.forEach((slot, index) => {\n offsets.push(text.length);\n const hidden =\n ended ||\n (slot.section !== null && !sections.has(slot.section)) ||\n (!focused && index > last);\n if (hidden) {\n return;\n }\n if (slot.kind === \"literal\") {\n text += slot.character;\n return;\n }\n const cell = cells[index] ?? EMPTY;\n if (cell.kind === \"filled\") {\n text += cell.character;\n } else if (cell.kind === \"empty\") {\n if (prompt === \"\") {\n ended = true;\n } else {\n text += prompt;\n }\n }\n });\n offsets.push(text.length);\n return { text, offsets };\n}\n\n/**\n * Where the caret goes after the slot `slot` (`null` for the start of the\n * text): after what it prints, then past the literals and skipped slots\n * that follow, so typing goes on at the next input slot.\n */\nexport function caretAfter(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n { offsets }: MaskWriting,\n slot: number | null,\n): number {\n let caret = slot === null ? 0 : (offsets[slot + 1] ?? 0);\n for (\n let index = slot === null ? 0 : slot + 1;\n index < mask.slots.length;\n index += 1\n ) {\n const definition = mask.slots[index];\n if (definition?.kind === \"input\" && cells[index]?.kind !== \"skipped\") {\n break;\n }\n caret = offsets[index + 1] ?? caret;\n }\n return caret;\n}\n\n/** The filled characters alone. */\nexport function rawOf(cells: readonly MaskCell[]): string {\n return cells\n .map((cell) => (cell.kind === \"filled\" ? cell.character : \"\"))\n .join(\"\");\n}\n\n/** Every required slot is filled: those outside sections, and those of each section begun. */\nexport function isComplete(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): boolean {\n const sections = filledSections(mask, cells);\n return mask.slots.every(\n (slot, index) =>\n slot.kind === \"literal\" ||\n slot.optional ||\n (slot.section !== null && !sections.has(slot.section)) ||\n cells[index]?.kind === \"filled\",\n );\n}\n","import { compiledPattern, type CompiledMask, type MaskTokens } from \"./grammar\";\nimport {\n caretAfter,\n fits,\n isComplete,\n itemsOf,\n layOut,\n maskCharacter,\n rawOf,\n readExact,\n writeCells,\n type LayoutMode,\n type MaskCell,\n type MaskItem,\n type MaskLayout,\n type MaskWriting,\n type PlacedItem,\n} from \"./layout\";\n\n/** A pattern, several tried in order as the text grows, or a function choosing one from the raw text. */\nexport type MaskSource = string | readonly string[] | ((raw: string) => string);\n\n/** A mask: its pattern, its own tokens and how it prints. */\nexport interface MaskOptions {\n readonly mask: MaskSource;\n /** One-character names, beside the built-in tokens, which they may replace. */\n readonly tokens?: MaskTokens | undefined;\n /** One character, shown in empty slots while focused; `\"_\"` by default, `\"\"` for none. */\n readonly promptCharacter?: string | undefined;\n /** Whose rules `>` and `<` change case by; the runtime's by default. */\n readonly locale?: Intl.LocalesArgument;\n}\n\n/** Text in a masked control, with the selection. */\nexport interface MaskedText {\n readonly text: string;\n readonly selectionStart: number;\n readonly selectionEnd: number;\n}\n\n/** A browser edit, as `beforeinput` reports it. */\nexport interface MaskEdit {\n readonly inputType: string;\n /** The text inserted; `null` for a deletion. */\n readonly data: string | null;\n}\n\n/** What a mask makes of some text. */\nexport interface MaskDetails {\n /** Only the characters typed into input slots. */\n readonly raw: string;\n /** With literals, without prompt characters, cut after the last character typed. */\n readonly formatted: string;\n /** Every required slot (of the pattern in use, and of each optional section begun) is filled. */\n readonly complete: boolean;\n /** The pattern in use. */\n readonly pattern: string;\n}\n\n/** What an edit leaves. */\nexport interface MaskResult extends MaskDetails {\n /** The text to show, prompt characters included while focused. */\n readonly text: string;\n readonly caret: number;\n /** False when the edit changed nothing the mask accepts (a letter in a digit slot): the input refuses it. */\n readonly accepted: boolean;\n}\n\n/** Whether a mask's value is only the characters typed, or the text with its literals. */\nexport type MaskValueFormat = \"raw\" | \"formatted\";\n\n/** A pattern's text read into cells, and the items an edit works on. */\ninterface TextReading {\n readonly layout: Pick<MaskLayout, \"mask\" | \"cells\">;\n readonly items: readonly PlacedItem[];\n /** Whether characters other than prompt characters had to be dropped to read the text. */\n readonly dropped: boolean;\n}\n\n/**\n * Edits that cannot be refused or come whole from elsewhere: a paste, a\n * drop, autofill or a correction, and the text an input method composed.\n * Their characters that fit nowhere are dropped and the rest go in.\n */\nconst LENIENT_INPUT = new Set([\n \"insertFromPaste\",\n \"insertFromPasteAsQuotation\",\n \"insertFromDrop\",\n \"insertFromYank\",\n \"insertReplacementText\",\n \"insertCompositionText\",\n \"insertFromComposition\",\n]);\n\nfunction promptOf(options: MaskOptions): string {\n return options.promptCharacter ?? \"_\";\n}\n\nfunction compiled(options: MaskOptions, pattern: string): CompiledMask {\n return compiledPattern(pattern, options.tokens);\n}\n\nfunction characterItems(text: string): MaskItem[] {\n return Array.from(text, (character) => ({\n kind: \"character\",\n character: maskCharacter(character),\n }));\n}\n\n/**\n * The patterns `items` may be laid into: the one pattern, every one of\n * several in order, or the one a function picks for the raw text the items\n * make when laid leniently into `current` (the pattern before the edit).\n */\nfunction candidates(\n options: MaskOptions,\n items: readonly MaskItem[],\n current: CompiledMask | null,\n): readonly [CompiledMask, ...CompiledMask[]] {\n const { mask } = options;\n if (typeof mask === \"string\") {\n return [compiled(options, mask)];\n }\n if (typeof mask !== \"function\") {\n const [first, ...rest] = mask;\n if (first === undefined) {\n throw new TypeError(\"A mask needs at least one pattern\");\n }\n return [\n compiled(options, first),\n ...rest.map((pattern) => compiled(options, pattern)),\n ];\n }\n const start = current ?? compiled(options, mask(\"\"));\n const provisional = layOut(start, items, \"lenient\", options.locale);\n return [compiled(options, mask(rawOf(provisional.cells)))];\n}\n\n/** `items` laid into the first pattern that holds every one of them, in order; `null` when none does. */\nfunction fittingLayout(\n options: MaskOptions,\n items: readonly MaskItem[],\n current: CompiledMask | null,\n): MaskLayout | null {\n for (const mask of candidates(options, items, current)) {\n const layout = layOut(mask, items, \"truncate\", options.locale);\n if (fits(layout)) {\n return layout;\n }\n }\n return null;\n}\n\n/** `items` laid into the pattern that keeps most of their characters, the first of equals. */\nfunction bestLayout(\n options: MaskOptions,\n items: readonly MaskItem[],\n mode: LayoutMode,\n current: CompiledMask | null,\n): MaskLayout {\n const [first, ...rest] = candidates(options, items, current);\n let best = layOut(first, items, mode, options.locale);\n for (const mask of rest) {\n const layout = layOut(mask, items, mode, options.locale);\n if (layout.kept > best.kept) {\n best = layout;\n }\n }\n return best;\n}\n\n/** `text` laid in as a paste would be, prompt characters left out. */\nfunction readLeniently(\n options: MaskOptions,\n text: string,\n current: CompiledMask | null,\n): TextReading {\n const prompt = promptOf(options);\n const typed: { readonly character: string; readonly at: number }[] = [];\n let index = 0;\n for (const character of text) {\n if (character !== prompt) {\n typed.push({ character: maskCharacter(character), at: index });\n }\n index += character.length;\n }\n const layout = bestLayout(\n options,\n typed.map(({ character }) => ({ kind: \"character\", character })),\n \"lenient\",\n current,\n );\n const at = layout.mask.slots.map(() => text.length);\n layout.landed.forEach((slot, item) => {\n if (slot !== null) {\n at[slot] = typed[item]?.at ?? text.length;\n }\n });\n return {\n layout,\n items: itemsOf(layout.mask, layout.cells, at),\n dropped: layout.landed.some((slot) => slot === null),\n };\n}\n\nfunction readIn(\n options: MaskOptions,\n mask: CompiledMask,\n text: string,\n): TextReading | null {\n const reading = readExact(mask, text, promptOf(options), options.locale);\n return (\n reading && {\n layout: { mask, cells: reading.cells },\n items: itemsOf(mask, reading.cells, reading.at),\n dropped: false,\n }\n );\n}\n\n/**\n * Reads the text on screen back into the mask: as the first pattern that\n * wrote it, or, for text no pattern wrote (after an undo), laid in as a\n * paste. A function mask is read with the pattern it picks for the text's\n * raw characters.\n */\nfunction readText(options: MaskOptions, text: string): TextReading {\n const { mask } = options;\n if (typeof mask !== \"function\") {\n for (const pattern of typeof mask === \"string\" ? [mask] : mask) {\n const reading = readIn(options, compiled(options, pattern), text);\n if (reading !== null) {\n return reading;\n }\n }\n return readLeniently(options, text, null);\n }\n const start = compiled(options, mask(\"\"));\n const first =\n readIn(options, start, text) ?? readLeniently(options, text, start);\n const picked = compiled(options, mask(rawOf(first.layout.cells)));\n if (picked === start) {\n return first;\n }\n return readIn(options, picked, text) ?? readLeniently(options, text, picked);\n}\n\nfunction resultOf(\n options: MaskOptions,\n { mask, cells }: Pick<MaskLayout, \"mask\" | \"cells\">,\n focused: boolean,\n caretSlot: (writing: MaskWriting) => number,\n accepted: boolean,\n): MaskResult {\n const writing = writeCells(mask, cells, focused, promptOf(options));\n return {\n ...detailsOf(options, mask, cells),\n text: writing.text,\n caret: caretSlot(writing),\n accepted,\n };\n}\n\n/** The slot item `index` landed in, or the last one before it that landed. */\nfunction slotBefore(\n landed: readonly (number | null)[],\n index: number,\n): number | null {\n for (let item = Math.min(index, landed.length) - 1; item >= 0; item -= 1) {\n const slot = landed[item];\n if (slot !== undefined && slot !== null) {\n return slot;\n }\n }\n return null;\n}\n\n/** Whether items `a` and `b` (in that order) are characters next to each other in the text: one group. */\nfunction sameGroup(a: PlacedItem | undefined, b: PlacedItem | undefined) {\n return (\n a !== undefined &&\n b !== undefined &&\n a.item.kind === \"character\" &&\n b.item.kind === \"character\" &&\n b.at - a.at === a.item.character.length\n );\n}\n\n/**\n * The items a deletion with nothing selected removes, as `[from, to)`:\n * the item before the caret (or after it, forward), stepping over\n * literals; a word removes the group of characters around it, between\n * literals; a line, every item on that side. `null` when there is none.\n */\nfunction deletedItems(\n items: readonly PlacedItem[],\n caret: number,\n inputType: string,\n): readonly [from: number, to: number] | null {\n const before = items.filter(({ at }) => at < caret).length;\n const forward = inputType.endsWith(\"Forward\");\n if (forward ? before >= items.length : before === 0) {\n return null;\n }\n if (inputType.includes(\"Line\")) {\n return forward ? [before, items.length] : [0, before];\n }\n let from = forward ? before : before - 1;\n let to = from + 1;\n if (inputType.includes(\"Word\")) {\n while (forward && sameGroup(items[to - 1], items[to])) {\n to += 1;\n }\n while (!forward && sameGroup(items[from - 1], items[from])) {\n from -= 1;\n }\n }\n return [from, to];\n}\n\n/**\n * What `edit` does to `current` under the mask. A selection removes the\n * characters in it; Backspace removes the character before the caret and\n * Delete the one after it, stepping over literals; the characters after\n * move back, and one that no longer fits is dropped with the rest. An\n * insert fills the slots from the caret, each character the next slot that\n * accepts it, and a character equal to the next literal steps past it\n * (skipping optional slots before it). Typing is strict: a character no\n * slot takes, or one that would push another out, refuses the whole edit.\n * A paste, a drop, autofill or composed text is lenient: what fits nowhere\n * is dropped. The pattern is chosen again for what the edit leaves.\n *\n * The caret goes after the last character inserted and past the literals\n * after it; after a deletion, to where the first removed character was.\n * Undo, redo and other edits the mask cannot place leave `accepted` false.\n */\nexport function applyMaskEdit(\n options: MaskOptions,\n current: MaskedText,\n edit: MaskEdit,\n focused: boolean,\n): MaskResult {\n const reading = readText(options, current.text);\n const start = Math.min(current.selectionStart, current.selectionEnd);\n const end = Math.max(current.selectionStart, current.selectionEnd);\n const refused = () =>\n resultOf(\n options,\n reading.layout,\n focused,\n () => Math.min(start, current.text.length),\n false,\n );\n const inserting = edit.inputType.startsWith(\"insert\");\n if (!inserting && !edit.inputType.startsWith(\"delete\")) {\n return refused();\n }\n let items = reading.items;\n if (start < end) {\n items = items.filter(({ at }) => at < start || at >= end);\n } else if (!inserting) {\n const range = deletedItems(items, start, edit.inputType);\n if (range === null) {\n return refused();\n }\n items = [...items.slice(0, range[0]), ...items.slice(range[1])];\n }\n const position = items.filter(({ at }) => at < start).length;\n const inserted = inserting ? characterItems(edit.data ?? \"\") : [];\n const next = [\n ...items.slice(0, position).map(({ item }) => item),\n ...inserted,\n ...items.slice(position).map(({ item }) => item),\n ];\n const shownMask = reading.layout.mask;\n const layout =\n inserting && !LENIENT_INPUT.has(edit.inputType)\n ? fittingLayout(options, next, shownMask)\n : bestLayout(\n options,\n next,\n inserting ? \"lenient\" : \"truncate\",\n shownMask,\n );\n if (layout === null) {\n return refused();\n }\n const insertedLanded = layout.landed.slice(\n position,\n position + inserted.length,\n );\n if (inserted.length > 0 && insertedLanded.every((slot) => slot === null)) {\n return refused();\n }\n const result = resultOf(\n options,\n layout,\n focused,\n (writing) =>\n caretAfter(\n layout.mask,\n layout.cells,\n writing,\n slotBefore(layout.landed, position + inserted.length),\n ),\n true,\n );\n return result.text === current.text ? refused() : result;\n}\n\n/**\n * `raw` laid into the mask, as a value from the app or a commit shows it,\n * with the caret at the first empty slot. Laid in leniently, so a\n * formatted value (with its literals) reads too.\n */\nexport function formatMasked(\n options: MaskOptions,\n raw: string,\n focused: boolean,\n): MaskResult {\n const items = characterItems(raw);\n const layout = bestLayout(options, items, \"lenient\", null);\n return resultOf(\n options,\n layout,\n focused,\n (writing) =>\n caretAfter(\n layout.mask,\n layout.cells,\n writing,\n slotBefore(layout.landed, items.length),\n ),\n true,\n );\n}\n\n/** Whether `raw` can still become complete by typing more: some pattern takes every character of it, in order. */\nexport function isValidMaskStart(options: MaskOptions, raw: string): boolean {\n return fittingLayout(options, characterItems(raw), null) !== null;\n}\n\n/** What the mask makes of `text`, focused or display text alike. */\nexport function maskDetails(options: MaskOptions, text: string): MaskDetails {\n const { layout } = readText(options, text);\n return detailsOf(options, layout.mask, layout.cells);\n}\n\nfunction detailsOf(\n options: MaskOptions,\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): MaskDetails {\n return {\n raw: rawOf(cells),\n formatted: writeCells(mask, cells, false, promptOf(options)).text,\n complete: isComplete(mask, cells),\n pattern: mask.pattern,\n };\n}\n\n/** `text` read by the mask, and whether reading it had to drop characters. */\nexport function readMasked(\n options: MaskOptions,\n text: string,\n): MaskDetails & { readonly dropped: boolean } {\n const { layout, dropped } = readText(options, text);\n return { ...detailsOf(options, layout.mask, layout.cells), dropped };\n}\n","import type { InputFilterDecision, TextEdit } from \"../field/plan\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n applyMaskEdit,\n formatMasked,\n readMasked,\n type MaskOptions,\n type MaskValueFormat,\n} from \"./applyMask\";\nimport { compiledPattern } from \"./grammar\";\n\n/** The options with the field's locale, unless they name one. */\nfunction inLocale(\n options: MaskOptions,\n locale: Intl.LocalesArgument,\n): MaskOptions {\n return options.locale === undefined ? { ...options, locale } : options;\n}\n\n/**\n * A masked field's own reading: no character typed is `null`; complete\n * text is its raw characters, or with `valueFormat: \"formatted\"` its\n * formatted text; incomplete text is unreadable with\n * `messages.maskIncomplete`, so the value stays the last complete one.\n * Text with characters no slot takes (after an undo) is unreadable with\n * `messages.patternMismatch`.\n */\nexport function maskParser(\n options: MaskOptions,\n valueFormat: MaskValueFormat = \"raw\",\n): (text: string, context: ParseContext<string>) => ParseResult<string> {\n return (text, { locale, messages }) => {\n const read = readMasked(inLocale(options, locale), text);\n if (read.dropped) {\n return unreadable(messages.patternMismatch);\n }\n if (read.raw === \"\") {\n return parsed(null);\n }\n if (!read.complete) {\n return unreadable(messages.maskIncomplete);\n }\n return parsed(valueFormat === \"raw\" ? read.raw : read.formatted);\n };\n}\n\n/**\n * A masked field's own writing: the value laid into the mask, with the\n * prompt in empty slots while the field has focus (`purpose: \"edit\"`, so\n * an empty field shows the template), and the formatted text otherwise.\n */\nexport function maskFormatter(\n options: MaskOptions,\n): (value: string | null, context: FormatContext<string>) => string {\n return (value, { locale, purpose }) =>\n formatMasked(inLocale(options, locale), value ?? \"\", purpose === \"edit\")\n .text;\n}\n\n/**\n * A masked field's judgement of an edit, its `filterInput`: the edit\n * worked out by `applyMaskEdit` on the text before it and the selection,\n * replacing the whole text and placing the caret, or refused. An edit with\n * no browser report (an app's change) and undo or redo stand as they are.\n * `options` hold the field's locale.\n */\nexport function filterMaskEdit<N>(\n edit: TextEdit<N>,\n before: string,\n options: MaskOptions,\n): InputFilterDecision {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (input === null || inputType === null || inputType.startsWith(\"history\")) {\n return { kind: \"allow\" };\n }\n const start = Math.min(input.selectionStart ?? before.length, before.length);\n const end = Math.min(input.selectionEnd ?? start, before.length);\n const result = applyMaskEdit(\n options,\n { text: before, selectionStart: start, selectionEnd: end },\n { inputType, data: input.data },\n true,\n );\n return result.accepted\n ? { kind: \"replace\", text: result.text, caret: result.caret }\n : { kind: \"prevent\" };\n}\n\n/** What a masked input tells the browser's keyboard. */\nexport interface MaskInputHints {\n /** `\"numeric\"` when every slot of every pattern is a built-in digit slot (`0`, `9`); a function mask is `\"text\"`. */\n readonly inputMode: \"numeric\" | \"text\";\n /** Whether a pattern upper-cases letters, for `autocapitalize=\"characters\"`. A function mask is judged by its first pattern. */\n readonly upperCase: boolean;\n}\n\n/** The keyboard a mask wants. Throws on a malformed pattern, as the engine does. */\nexport function maskInputHints(options: MaskOptions): MaskInputHints {\n const { mask, tokens } = options;\n const patterns =\n typeof mask === \"function\"\n ? [mask(\"\")]\n : typeof mask === \"string\"\n ? [mask]\n : mask;\n const slots = patterns.flatMap(\n (pattern) => compiledPattern(pattern, tokens).slots,\n );\n const inputs = slots.filter((slot) => slot.kind === \"input\");\n const digitsOnly = inputs.every(\n (slot) =>\n (slot.token === \"0\" || slot.token === \"9\") &&\n tokens?.[slot.token] === undefined,\n );\n return {\n inputMode: typeof mask !== \"function\" && digitsOnly ? \"numeric\" : \"text\",\n upperCase: inputs.some((slot) => slot.letterCase === \"upper\"),\n };\n}\n","import type { Validator } from \"../validation/validators\";\n\n/** IBAN lengths by country code, from the SWIFT IBAN registry. */\nexport const IBAN_LENGTHS: Readonly<Record<string, number>> = {\n AD: 24,\n AE: 23,\n AL: 28,\n AT: 20,\n AZ: 28,\n BA: 20,\n BE: 16,\n BG: 22,\n BH: 22,\n BI: 27,\n BR: 29,\n BY: 28,\n CH: 21,\n CR: 22,\n CY: 28,\n CZ: 24,\n DE: 22,\n DJ: 27,\n DK: 18,\n DO: 28,\n EE: 20,\n EG: 29,\n ES: 24,\n FI: 18,\n FK: 18,\n FO: 18,\n FR: 27,\n GB: 22,\n GE: 22,\n GI: 23,\n GL: 18,\n GR: 27,\n GT: 28,\n HN: 28,\n HR: 21,\n HU: 28,\n IE: 22,\n IL: 23,\n IQ: 23,\n IS: 26,\n IT: 27,\n JO: 30,\n KW: 30,\n KZ: 20,\n LB: 28,\n LC: 32,\n LI: 21,\n LT: 20,\n LU: 20,\n LV: 21,\n LY: 25,\n MC: 27,\n MD: 24,\n ME: 22,\n MK: 19,\n MN: 20,\n MR: 27,\n MT: 31,\n MU: 30,\n NI: 28,\n NL: 18,\n NO: 15,\n OM: 23,\n PK: 24,\n PL: 28,\n PS: 29,\n PT: 25,\n QA: 29,\n RO: 24,\n RS: 22,\n RU: 33,\n SA: 24,\n SC: 31,\n SD: 18,\n SE: 24,\n SI: 19,\n SK: 24,\n SM: 27,\n SO: 23,\n ST: 25,\n SV: 28,\n TL: 23,\n TN: 24,\n TR: 26,\n UA: 29,\n VA: 22,\n VG: 24,\n XK: 20,\n YE: 30,\n};\n\n/** Whether `value` is an IBAN of its country's length whose check digits hold (mod 97 is 1). */\nfunction isIban(value: string): boolean {\n const iban = value.replace(/\\s/g, \"\").toUpperCase();\n if (\n !/^[A-Z]{2}[0-9]{2}[A-Z0-9]+$/.test(iban) ||\n IBAN_LENGTHS[iban.slice(0, 2)] !== iban.length\n ) {\n return false;\n }\n let remainder = 0;\n for (const character of iban.slice(4) + iban.slice(0, 4)) {\n // Letters count as two digits, A = 10 to Z = 35.\n const digits = Number.parseInt(character, 36);\n remainder = (remainder * (digits < 10 ? 10 : 100) + digits) % 97;\n }\n return remainder === 1;\n}\n\n/** Whether the digits of `value` pass the Luhn check. */\nfunction passesLuhn(value: string): boolean {\n const digits = value.replace(/\\s/g, \"\");\n if (!/^[0-9]{2,}$/.test(digits)) {\n return false;\n }\n let sum = 0;\n Array.from(digits)\n .reverse()\n .forEach((character, index) => {\n const digit = Number(character);\n const doubled = index % 2 === 1 ? digit * 2 : digit;\n sum += doubled > 9 ? doubled - 9 : doubled;\n });\n return sum % 10 === 0;\n}\n\nconst IPV4_PART = /^(?:0|[1-9][0-9]{0,2})$/;\n\n/** Whether `value` is four dotted parts from 0 to 255, none with a leading zero. */\nfunction isIpv4(value: string): boolean {\n const parts = value.split(\".\");\n return (\n parts.length === 4 &&\n parts.every((part) => IPV4_PART.test(part) && Number(part) <= 255)\n );\n}\n\n/**\n * An IBAN with the wrong length for its country, or whose check digits\n * fail, is `messages.ibanInvalid`. Spaces are ignored. `null` passes.\n */\nexport function ibanRule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !isIban(value)\n ? { text: messages.ibanInvalid, code: \"iban\" }\n : null;\n}\n\n/** A card number whose check digit fails (Luhn) is `messages.cardNumberInvalid`. Spaces are ignored. `null` passes. */\nexport function luhnRule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !passesLuhn(value)\n ? { text: messages.cardNumberInvalid, code: \"cardNumber\" }\n : null;\n}\n\n/** An IPv4 address with a part above 255 or a leading zero is `messages.ipv4Invalid`. `null` passes. */\nexport function ipv4Rule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !isIpv4(value)\n ? { text: messages.ipv4Invalid, code: \"ipv4\" }\n : null;\n}\n","import type { Validator } from \"../validation/validators\";\nimport type { MaskOptions, MaskValueFormat } from \"./applyMask\";\nimport type { MaskTokens } from \"./grammar\";\nimport { IBAN_LENGTHS, ibanRule, ipv4Rule, luhnRule } from \"./rules\";\n\n/** A ready-made mask: its options, its check, the keyboard it wants and the value it keeps. */\nexport interface MaskPreset {\n readonly options: MaskOptions;\n /** Checks a complete value further: a checksum, a range. */\n readonly validate?: Validator<string> | undefined;\n readonly inputMode: \"numeric\" | \"decimal\" | \"text\";\n readonly autoComplete?: string | undefined;\n readonly valueFormat: MaskValueFormat;\n}\n\n/** Codes are ASCII: these tokens keep out the letters and digits of other scripts that the built-in ones accept. */\nconst ASCII_TOKENS: MaskTokens = {\n L: /[A-Za-z]/,\n A: /[A-Za-z0-9]/,\n a: { accept: /[A-Za-z0-9]/, optional: true },\n};\n\n/** Upper-casing codes the same in every locale (\"i\" is \"I\", not the Turkish \"İ\"). */\nconst CODE_LOCALE = \"en\";\n\n/** The longest IBAN, and the shortest, which an unknown country's pattern spans. */\nconst IBAN_MAX = 34;\nconst IBAN_MIN = 15;\n\n/**\n * An IBAN's pattern for the raw text typed: two letters, two check digits\n * and the rest, sized by the country the letters name and grouped in\n * fours; up to 34 characters (15 required) for a country it does not know.\n */\nfunction ibanPattern(raw: string): string {\n const length = IBAN_LENGTHS[raw.slice(0, 2).toUpperCase()];\n const tokens = Array.from({ length: length ?? IBAN_MAX }, (_, index) => {\n if (index < 2) {\n return \"L\";\n }\n if (index < 4) {\n return \"0\";\n }\n return length === undefined && index >= IBAN_MIN ? \"a\" : \"A\";\n });\n const groups: string[] = [];\n for (let start = 0; start < tokens.length; start += 4) {\n groups.push(tokens.slice(start, start + 4).join(\"\"));\n }\n return `>${groups.join(\" \")}`;\n}\n\n/** A card number's pattern: American Express (34, 37) groups 4-6-5; the rest 4-4-4-4, with up to three more digits. */\nfunction cardNumberPattern(raw: string): string {\n return /^3[47]/.test(raw) ? \"0000 000000 00000\" : \"0000 0000 0000 0000[ 000]\";\n}\n\nfunction postalCode(\n mask: MaskOptions[\"mask\"],\n inputMode: \"numeric\" | \"text\",\n): MaskPreset {\n return {\n options:\n inputMode === \"text\"\n ? { mask, tokens: ASCII_TOKENS, locale: CODE_LOCALE }\n : { mask },\n inputMode,\n autoComplete: \"postal-code\",\n valueFormat: \"formatted\",\n };\n}\n\n/** The presets `MaskedInput` takes by name. */\nexport interface MaskPresets {\n /** An IBAN, grouped in fours, sized by its country; raw value, checked by `ibanRule`. */\n readonly iban: MaskPreset;\n /** A card number, grouped by its length; raw digits, checked by `luhnRule`. */\n readonly cardNumber: MaskPreset;\n /** An IPv4 address, `.` moving to the next part; formatted value, checked by `ipv4Rule`. */\n readonly ipv4: MaskPreset;\n /** `12345` or `12345-6789`. */\n readonly postalCodeUS: MaskPreset;\n /** `K1A 0B1`. */\n readonly postalCodeCA: MaskPreset;\n /** `SW1A 1AA`, `M1 1AA` and the other UK shapes. */\n readonly postalCodeGB: MaskPreset;\n /** `10115`. */\n readonly postalCodeDE: MaskPreset;\n /** `1012 AB`. */\n readonly postalCodeNL: MaskPreset;\n /** `01310-100`. */\n readonly postalCodeBR: MaskPreset;\n /** `100-0001`. */\n readonly postalCodeJP: MaskPreset;\n}\n\n/**\n * Ready-made masks. Postal codes keep their separators, as addresses print\n * them; an IPv4 address keeps its dots, which its raw digits would lose.\n */\nexport const maskPresets: MaskPresets = {\n iban: {\n options: { mask: ibanPattern, tokens: ASCII_TOKENS, locale: CODE_LOCALE },\n validate: ibanRule(),\n inputMode: \"text\",\n valueFormat: \"raw\",\n },\n cardNumber: {\n options: { mask: cardNumberPattern },\n validate: luhnRule(),\n inputMode: \"numeric\",\n autoComplete: \"cc-number\",\n valueFormat: \"raw\",\n },\n ipv4: {\n options: { mask: \"099.099.099.099\" },\n validate: ipv4Rule(),\n // The decimal keypad has the dot.\n inputMode: \"decimal\",\n valueFormat: \"formatted\",\n },\n postalCodeUS: postalCode(\"00000[-0000]\", \"numeric\"),\n postalCodeCA: postalCode(\">L0L 0L0\", \"text\"),\n postalCodeGB: postalCode(\n [\">L0 0LL\", \">L00 0LL\", \">LL0 0LL\", \">LL00 0LL\", \">L0L 0LL\", \">LL0L 0LL\"],\n \"text\",\n ),\n postalCodeDE: postalCode(\"00000\", \"numeric\"),\n postalCodeNL: postalCode(\"0000 >LL\", \"text\"),\n postalCodeBR: postalCode(\"00000-000\", \"numeric\"),\n postalCodeJP: postalCode(\"000-0000\", \"numeric\"),\n};\n","import type { SegmentType } from \"../date/layout\";\nimport type { RelativeDateRule } from \"../date/relative\";\nimport { localeKey } from \"../localeKey\";\nimport type { Severity } from \"./severity\";\n\n/**\n * Every string the forms show or announce of their own: validation\n * messages, button names, counters, display-mode text and the message\n * summary, so the forms can speak a language other than English. A message\n * that names something takes a function, so a translation can put it where\n * its own grammar wants it. Counts print in the locale's digits: \"1,000\"\n * under `\"en\"`, \"1.000\" under `\"de-DE\"`.\n *\n * A minor release may add keys. `resolveFormsMessages` lays a partial set\n * over the defaults, so a translation without a new key shows its English\n * default until it gains one.\n */\nexport interface FormsMessages {\n /** A required field is empty. */\n required: string;\n /** A required checkbox is not checked. */\n requiredChecked: string;\n /** A required switch is off. */\n requiredOn: string;\n /** The text is shorter than `minLength`. */\n tooShort: (min: number) => string;\n /** The text is longer than `maxLength`. */\n tooLong: (max: number) => string;\n /** The text does not match `pattern`. */\n patternMismatch: string;\n /** A custom parser's fallback when the text cannot be read. */\n unreadable: string;\n /** A number field's text is not a number. */\n notANumber: string;\n /** A number field's text groups digits where the field does not; names its separators. */\n numberGrouping: (decimal: string, group: string) => string;\n /** A number field holding JS numbers was given more digits than one keeps exactly. */\n numberTooPrecise: string;\n /** A number is below `min`, written as the field writes numbers. */\n rangeUnderflow: (min: string) => string;\n /** A number is above `max`, written as the field writes numbers. */\n rangeOverflow: (max: string) => string;\n /** A number is off its step, written as the field writes numbers. */\n stepMismatch: (step: string) => string;\n /** A date or time is before `min`, written as display mode writes it. */\n tooEarly: (limit: string) => string;\n /** A date or time is after `max`, written as display mode writes it. */\n tooLate: (limit: string) => string;\n /** A day `isDateDisabled` marks unavailable. */\n dateUnavailable: string;\n /** A date's segments are partly filled. */\n dateIncomplete: string;\n /** A time's segments are partly filled, or a 12-hour time has no AM or PM. */\n timeIncomplete: string;\n /** A date's month has no such day: 31 February. */\n dateNonexistent: string;\n /** Text that is not a date; `example` is today as the field writes it. */\n dateUnreadable: (example: string) => string;\n /** Text that is not a time; `example` is a time as the field writes it. */\n timeUnreadable: (example: string) => string;\n /** A year typed with three digits. */\n dateYearDigits: string;\n /** A wall clock in an hour the clocks skipped, read as the hour after: `typed` and `read` as the field writes times. */\n timeSkipped: (typed: string, read: string) => string;\n /** A wall clock in an hour that happens twice, read with `offset` (\"GMT+02:00\"). */\n timeRepeated: (time: string, offset: string) => string;\n /** A wall clock in an hour the clocks skipped, refused. */\n timeNonexistent: (typed: string) => string;\n /** A wall clock in an hour that happens twice, refused. */\n timeAmbiguous: (typed: string) => string;\n /** A segment's name, read with the field's label: \"month\". */\n dateSegmentName: (type: SegmentType) => string;\n /** What an empty segment shows: \"mm\". */\n dateSegmentPlaceholder: (type: SegmentType) => string;\n /** An empty segment's value, as a screen reader reads it. */\n segmentEmpty: string;\n /** The button that opens a date input's calendar, and the calendar popup itself. */\n chooseDate: string;\n /** The button that opens a time input's time columns, and their popup. */\n chooseTime: string;\n /** The button that opens a date-time input's calendar and time columns, and their popup. */\n chooseDateTime: string;\n /** A time picker's button that chooses the time it is now. */\n pickerNow: string;\n /** A date-time picker's button that closes it. */\n pickerDone: string;\n /** The button that opens a period input's picker, and the picker popup itself. */\n choosePeriod: string;\n /** A period picker's button to the year before. */\n previousYear: string;\n /** A period picker's button to the year after. */\n nextYear: string;\n /** A year picker's button to the twelve years before. */\n previousYears: string;\n /** A year picker's button to the twelve years after. */\n nextYears: string;\n /** A calendar's button to the month before. */\n previousMonth: string;\n /** A calendar's button to the month after. */\n nextMonth: string;\n /** A calendar's view of months and years, which its title opens. */\n chooseMonthYear: string;\n /** The list of years in a calendar's month and year view. */\n calendarYears: string;\n /** The heading of a calendar's column of week numbers, as a screen reader reads it. */\n weekColumn: string;\n /** A week number in a calendar, as a screen reader reads it. */\n weekLabel: (week: number) => string;\n /** Read after the first day of a range in a calendar. */\n calendarRangeStart: string;\n /** Read after the last day of a range in a calendar. */\n calendarRangeEnd: string;\n /** A relative rule's name, for a preset or a rule held as the value: \"Last 7 days\", \"This month\". */\n relativeRangeLabel: (rule: RelativeDateRule) => string;\n /** Written after a time range's end on the day after its start: \"22:00 – 06:00 +1\". */\n rangeNextDay: string;\n /** Written before a quarter: \"Q3 2026\". */\n periodQuarterPrefix: string;\n /** Written before a fiscal year: \"FY2026\". */\n fiscalYearPrefix: string;\n /** Written before a fiscal period: \"FY2026 P04\". */\n fiscalPeriodPrefix: string;\n /** Text that is not a period; `example` is the current period as the field writes it. */\n periodUnreadable: (example: string) => string;\n /** Text that is not a duration; `example` is 90 minutes as the field writes them. */\n durationUnreadable: (example: string) => string;\n /** A negative duration where the field takes none. */\n durationNegative: string;\n /** A commit refused without a message, or a check that failed. */\n checkFailed: string;\n /** The clear button's accessible name. */\n clear: string;\n /** The password reveal button's accessible name. */\n showPassword: string;\n /** A number input's stepper button that steps up. */\n increase: string;\n /** A number input's stepper button that steps down. */\n decrease: string;\n /** A range input's first end, read with the field's label. */\n rangeStart: string;\n /** A range input's second end, read with the field's label. */\n rangeEnd: string;\n /** Drawn between a range input's two ends. */\n rangeSeparator: string;\n /** A range with only a start, in display mode; `start` as the input writes it. */\n rangeFrom: (start: string) => string;\n /** A range with only an end, in display mode; `end` as the input writes it. */\n rangeUpTo: (end: string) => string;\n /** A range's end comes before its start, and the input does not swap them. */\n rangeReversed: string;\n /** A half-open range's start is its end, so it holds nothing. */\n rangeEmpty: string;\n /** A range spans less than its minimum, written as the input writes spans. */\n rangeTooShort: (span: string) => string;\n /** A range spans more than its maximum, written as the input writes spans. */\n rangeTooLong: (span: string) => string;\n /** A range input's span, shown after its end. */\n rangeSpanLabel: (span: string) => string;\n /** A masked field's text leaves required slots empty. */\n maskIncomplete: string;\n /** An IBAN has the wrong length for its country, or fails its check digits. */\n ibanInvalid: string;\n /** A card number fails its check digit. */\n cardNumberInvalid: string;\n /** An IPv4 address has a part above 255, or one with a leading zero. */\n ipv4Invalid: string;\n /** The visible character counter. */\n counter: (count: number, max: number) => string;\n /** The counter's description, read with the control. */\n counterLabel: (max: number) => string;\n /** Announced as typing pauses near the limit. */\n charactersLeft: (left: number) => string;\n /** Announced as typing pauses over the limit. */\n charactersOver: (over: number) => string;\n /** Announced while an input loads. */\n loading: string;\n /** Read beside the dash an empty field shows in display mode. */\n emptyValue: string;\n /** A checked checkbox in display mode, and its event text. */\n displayChecked: string;\n /** An unchecked checkbox in display mode, and its event text. */\n displayUnchecked: string;\n /** A switch that is on, in display mode. */\n displayOn: string;\n /** A switch that is off, in display mode. */\n displayOff: string;\n /** The marker on an optional field's label. */\n optional: string;\n /** The help button's accessible name. */\n fieldHelp: string;\n /** A search input's placeholder. */\n searchPlaceholder: string;\n /** Read before a message, naming its severity. */\n severityLabel: (severity: Severity) => string;\n /** How many messages of one severity a summary holds. */\n severityCount: (severity: Severity, count: number) => string;\n /** The message summary's title. */\n messageSummaryTitle: (count: number) => string;\n}\n\ntype CountFormat = (count: number) => string;\n\n/**\n * Count formats already built, one per locale: building an\n * `Intl.NumberFormat` costs far more than using one.\n */\nconst countFormats = new Map<string, CountFormat>();\n\n/** A count in `locale`'s digits and separators, whole. */\nfunction countFormat(locale: Intl.LocalesArgument): CountFormat {\n const key = localeKey(locale);\n let format = countFormats.get(key);\n if (format === undefined) {\n const numberFormat = new Intl.NumberFormat(locale, {\n maximumFractionDigits: 0,\n });\n format = (count) => numberFormat.format(count);\n countFormats.set(key, format);\n }\n return format;\n}\n\nconst SEVERITY_LABELS: Readonly<Record<Severity, string>> = {\n error: \"Error\",\n warning: \"Warning\",\n info: \"Information\",\n success: \"Success\",\n};\n\nconst SEGMENT_NAMES: Readonly<Record<SegmentType, string>> = {\n year: \"year\",\n month: \"month\",\n day: \"day\",\n hour: \"hour\",\n minute: \"minute\",\n second: \"second\",\n dayPeriod: \"AM/PM\",\n quarter: \"quarter\",\n period: \"period\",\n};\n\nconst SEGMENT_PLACEHOLDERS: Readonly<Record<SegmentType, string>> = {\n year: \"yyyy\",\n month: \"mm\",\n day: \"dd\",\n hour: \"--\",\n minute: \"--\",\n second: \"--\",\n dayPeriod: \"--\",\n quarter: \"-\",\n period: \"--\",\n};\n\n/** \"day\", \"fiscal quarter\": a rule's unit as words. */\nfunction unitWords(unit: string, fiscal: boolean | undefined): string {\n return fiscal === true && (unit === \"quarter\" || unit === \"year\")\n ? `fiscal ${unit}`\n : unit;\n}\n\n/** A rule's English name: \"Today\", \"Last month\", \"Last 7 days\", \"Year to date\". */\nfunction relativeLabel(rule: RelativeDateRule, n: CountFormat): string {\n switch (rule.kind) {\n case \"period\": {\n const { offset } = rule;\n const unit = unitWords(rule.unit, rule.fiscal);\n const units = counted(n, Math.abs(offset), [unit, `${unit}s`]);\n const days = rule.unit === \"day\";\n if (offset === 0) {\n return days ? \"Today\" : `This ${unit}`;\n }\n if (offset === -1) {\n return days ? \"Yesterday\" : `Last ${unit}`;\n }\n if (offset === 1) {\n return days ? \"Tomorrow\" : `Next ${unit}`;\n }\n return offset < 0 ? `${units} ago` : `In ${units}`;\n }\n case \"last\":\n case \"next\": {\n const units = counted(n, rule.count, [rule.unit, `${rule.unit}s`]);\n if (rule.kind === \"last\") {\n return rule.includeToday\n ? `Last ${units}`\n : `Last ${units} before today`;\n }\n return rule.includeToday ? `Next ${units} from today` : `Next ${units}`;\n }\n case \"toDate\": {\n const unit = unitWords(rule.unit, rule.fiscal);\n return `${unit.charAt(0).toUpperCase()}${unit.slice(1)} to date`;\n }\n }\n}\n\n/** The singular and plural noun a count of each severity takes. */\nconst SEVERITY_NOUNS: Readonly<Record<Severity, readonly [string, string]>> = {\n error: [\"error\", \"errors\"],\n warning: [\"warning\", \"warnings\"],\n info: [\"note\", \"notes\"],\n success: [\"confirmation\", \"confirmations\"],\n};\n\n/** \"1 character\", \"3 characters\": `count` with the noun in its number. */\nfunction counted(\n n: CountFormat,\n count: number,\n [one, many]: readonly [string, string],\n): string {\n return count === 1 ? `1 ${one}` : `${n(count)} ${many}`;\n}\n\n/**\n * The forms' own English, counts printed in `locale`'s digits. Without a\n * locale, the runtime's own; that one is `defaultFormsMessages`.\n */\nexport function createDefaultFormsMessages(\n locale?: Intl.LocalesArgument,\n): FormsMessages {\n const n = countFormat(locale);\n const characters = [\"character\", \"characters\"] as const;\n return {\n required: \"Enter a value\",\n requiredChecked: \"Check this box to continue\",\n requiredOn: \"Turn this on to continue\",\n tooShort: (min) => `Enter at least ${counted(n, min, characters)}`,\n tooLong: (max) => `Enter no more than ${counted(n, max, characters)}`,\n patternMismatch: \"Enter a value in the expected format\",\n unreadable: \"This value can't be read\",\n notANumber: \"Enter a number\",\n numberGrouping: (decimal, group) =>\n `Use “${decimal}” for decimals and “${group}” between thousands`,\n numberTooPrecise: \"This number has more digits than can be kept exactly\",\n rangeUnderflow: (min) => `Enter ${min} or more`,\n rangeOverflow: (max) => `Enter ${max} or less`,\n stepMismatch: (step) => `Enter a multiple of ${step}`,\n tooEarly: (limit) => `Enter ${limit} or later`,\n tooLate: (limit) => `Enter ${limit} or earlier`,\n dateUnavailable: \"This date isn't available\",\n dateIncomplete: \"Complete the date\",\n timeIncomplete: \"Complete the time\",\n dateNonexistent: \"This date doesn't exist\",\n dateUnreadable: (example) => `Enter a date such as ${example}`,\n timeUnreadable: (example) => `Enter a time such as ${example}`,\n dateYearDigits: \"Enter the year with 2 or 4 digits\",\n timeSkipped: (typed, read) =>\n `Clocks go forward here: ${typed} is read as ${read}`,\n timeRepeated: (time, offset) => `${time} happens twice; read as ${offset}`,\n timeNonexistent: (typed) =>\n `${typed} doesn't exist here: clocks go forward`,\n timeAmbiguous: (typed) => `${typed} happens twice here: clocks go back`,\n dateSegmentName: (type) => SEGMENT_NAMES[type],\n dateSegmentPlaceholder: (type) => SEGMENT_PLACEHOLDERS[type],\n segmentEmpty: \"Empty\",\n chooseDate: \"Choose date\",\n chooseTime: \"Choose time\",\n chooseDateTime: \"Choose date and time\",\n pickerNow: \"Now\",\n pickerDone: \"Done\",\n choosePeriod: \"Choose period\",\n previousYear: \"Previous year\",\n nextYear: \"Next year\",\n previousYears: \"Previous years\",\n nextYears: \"Next years\",\n previousMonth: \"Previous month\",\n nextMonth: \"Next month\",\n chooseMonthYear: \"Choose month and year\",\n calendarYears: \"Years\",\n weekColumn: \"Week\",\n weekLabel: (week) => `Week ${n(week)}`,\n calendarRangeStart: \"start of range\",\n calendarRangeEnd: \"end of range\",\n relativeRangeLabel: (rule) => relativeLabel(rule, n),\n rangeNextDay: \"+1\",\n periodQuarterPrefix: \"Q\",\n fiscalYearPrefix: \"FY\",\n fiscalPeriodPrefix: \"P\",\n periodUnreadable: (example) => `Enter a period such as ${example}`,\n durationUnreadable: (example) => `Enter a duration such as ${example}`,\n durationNegative: \"Enter a duration of zero or more\",\n checkFailed: \"This value could not be checked\",\n clear: \"Clear\",\n showPassword: \"Show password\",\n increase: \"Increase\",\n decrease: \"Decrease\",\n rangeStart: \"From\",\n rangeEnd: \"To\",\n rangeSeparator: \"–\",\n rangeFrom: (start) => `from ${start}`,\n rangeUpTo: (end) => `up to ${end}`,\n rangeReversed: \"The end comes before the start\",\n rangeEmpty: \"The range is empty\",\n rangeTooShort: (span) => `The range must span at least ${span}`,\n rangeTooLong: (span) => `The range must span no more than ${span}`,\n rangeSpanLabel: (span) => `Span: ${span}`,\n maskIncomplete: \"Complete this field\",\n ibanInvalid: \"Enter a valid IBAN\",\n cardNumberInvalid: \"Enter a valid card number\",\n ipv4Invalid: \"Enter a valid IPv4 address\",\n counter: (count, max) => `${n(count)}/${n(max)}`,\n counterLabel: (max) => `Up to ${counted(n, max, characters)}`,\n charactersLeft: (left) => `${counted(n, left, characters)} left`,\n charactersOver: (over) => `${counted(n, over, characters)} too many`,\n loading: \"Loading\",\n emptyValue: \"No value\",\n displayChecked: \"Yes\",\n displayUnchecked: \"No\",\n displayOn: \"On\",\n displayOff: \"Off\",\n optional: \"optional\",\n fieldHelp: \"More information\",\n searchPlaceholder: \"Search\",\n severityLabel: (severity) => SEVERITY_LABELS[severity],\n severityCount: (severity, count) =>\n counted(n, count, SEVERITY_NOUNS[severity]),\n messageSummaryTitle: (count) =>\n count === 1\n ? \"There is 1 problem with this form\"\n : `There are ${n(count)} problems with this form`,\n };\n}\n\n/** The forms' own English, which an app's messages replace key by key. */\nexport const defaultFormsMessages: FormsMessages = createDefaultFormsMessages();\n\n/** The defaults made for each locale so far, one object per locale. */\nconst localeDefaults = new Map<string, FormsMessages>();\n\nfunction defaultsFor(locale: Intl.LocalesArgument): FormsMessages {\n if (locale === undefined) {\n return defaultFormsMessages;\n }\n const key = localeKey(locale);\n let defaults = localeDefaults.get(key);\n if (defaults === undefined) {\n defaults = createDefaultFormsMessages(locale);\n localeDefaults.set(key, defaults);\n }\n return defaults;\n}\n\n/**\n * `messages` over the defaults for `locale`: every key the forms need,\n * whichever the caller gave. The defaults themselves, the same object for\n * the same locale, when it gave none, so a renderer memoizing on the result\n * sees no change that is not one.\n */\nexport function resolveFormsMessages(\n messages: Partial<FormsMessages> | undefined,\n locale?: Intl.LocalesArgument,\n): FormsMessages {\n const defaults = defaultsFor(locale);\n return messages === undefined ? defaults : { ...defaults, ...messages };\n}\n","/**\n * An exact decimal number as text: an optional `-`, digits, and a point\n * before any fraction digits, as in `\"-1234.5\"`. A number field holds one\n * with `valueType: \"decimal\"`, and every value goes through one to be\n * stepped, rounded and compared without binary rounding.\n */\nexport type DecimalString = string;\n\n/** A value as a number field holds it: a JS number, or an exact decimal string. */\nexport type NumberLike = number | string;\n\n/**\n * Intl's rounding modes, with Intl's meanings. Spelled out rather than read\n * from `Intl.NumberFormatOptions`, which has them only from TypeScript's\n * ES2023 lib, so an app type-checking against ES2022 can still read them.\n */\nexport type RoundingMode =\n | \"ceil\"\n | \"floor\"\n | \"expand\"\n | \"trunc\"\n | \"halfCeil\"\n | \"halfFloor\"\n | \"halfExpand\"\n | \"halfTrunc\"\n | \"halfEven\";\n\n/** A decimal as `coefficient × 10^-scale`. */\ninterface Decimal {\n readonly coefficient: bigint;\n readonly scale: number;\n}\n\nconst DECIMAL_TEXT = /^([+-]?)(?:(\\d+)(?:\\.(\\d+))?|\\.(\\d+))$/;\n\nfunction readDecimal(text: string): Decimal | null {\n const match = DECIMAL_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const fraction = match[3] ?? match[4] ?? \"\";\n const magnitude = BigInt((match[2] ?? \"\") + fraction);\n return {\n coefficient: match[1] === \"-\" ? -magnitude : magnitude,\n scale: fraction.length,\n };\n}\n\nfunction toDecimal(text: DecimalString): Decimal {\n const decimal = readDecimal(text);\n if (decimal === null) {\n throw new RangeError(`\"${text}\" is not a decimal string`);\n }\n return decimal;\n}\n\n/** `decimal` in normal form, its fraction padded to `minimumFractionDigits`. */\nfunction writeDecimal(\n { coefficient, scale }: Decimal,\n minimumFractionDigits = 0,\n): DecimalString {\n const negative = coefficient < 0n;\n const digits = (negative ? -coefficient : coefficient)\n .toString()\n .padStart(scale + 1, \"0\");\n const point = digits.length - scale;\n const fraction = digits\n .slice(point)\n .replace(/0+$/, \"\")\n .padEnd(minimumFractionDigits, \"0\");\n return (\n (negative ? \"-\" : \"\") +\n digits.slice(0, point) +\n (fraction === \"\" ? \"\" : `.${fraction}`)\n );\n}\n\nfunction pow10(exponent: number): bigint {\n return 10n ** BigInt(exponent);\n}\n\n/** The coefficients of `a` and `b` at one scale, and that scale. */\nfunction aligned(\n a: Decimal,\n b: Decimal,\n): readonly [a: bigint, b: bigint, scale: number] {\n const scale = Math.max(a.scale, b.scale);\n return [\n a.coefficient * pow10(scale - a.scale),\n b.coefficient * pow10(scale - b.scale),\n scale,\n ];\n}\n\n/** Whether `text` is a decimal string: `[+-]digits[.digits]` or `[+-].digits`. */\nexport function isDecimalString(text: string): boolean {\n return DECIMAL_TEXT.test(text);\n}\n\n/**\n * `text` in normal form: a `-` only when it is not zero, no leading zeros\n * (one `0` before the point), and no trailing fraction zeros beyond\n * `minimumFractionDigits`. `null` when `text` is not a decimal string.\n */\nexport function normalizeDecimal(\n text: string,\n minimumFractionDigits = 0,\n): DecimalString | null {\n const decimal = readDecimal(text);\n return decimal === null ? null : writeDecimal(decimal, minimumFractionDigits);\n}\n\n/**\n * Orders two decimals by value: `\"12.5\"` and `\"12.50\"` are equal. Throws a\n * `RangeError` for text that is not a decimal string, as every function\n * here does.\n */\nexport function compareDecimals(\n a: DecimalString,\n b: DecimalString,\n): -1 | 0 | 1 {\n const [x, y] = aligned(toDecimal(a), toDecimal(b));\n return x < y ? -1 : x > y ? 1 : 0;\n}\n\n/** `a + b`, exactly. */\nexport function addDecimals(a: DecimalString, b: DecimalString): DecimalString {\n const [x, y, scale] = aligned(toDecimal(a), toDecimal(b));\n return writeDecimal({ coefficient: x + y, scale });\n}\n\n/** `a - b`, exactly. */\nexport function subtractDecimals(\n a: DecimalString,\n b: DecimalString,\n): DecimalString {\n const [x, y, scale] = aligned(toDecimal(a), toDecimal(b));\n return writeDecimal({ coefficient: x - y, scale });\n}\n\n/** Whether a dropped remainder takes the kept digits one further from zero. */\nfunction roundsAway(\n mode: RoundingMode,\n negative: boolean,\n twiceRemainder: bigint,\n divisor: bigint,\n quotient: bigint,\n): boolean {\n const above = twiceRemainder > divisor;\n const tie = twiceRemainder === divisor;\n switch (mode) {\n case \"trunc\":\n return false;\n case \"expand\":\n return true;\n case \"ceil\":\n return !negative;\n case \"floor\":\n return negative;\n case \"halfTrunc\":\n return above;\n case \"halfExpand\":\n return above || tie;\n case \"halfCeil\":\n return above || (tie && !negative);\n case \"halfFloor\":\n return above || (tie && negative);\n case \"halfEven\":\n return above || (tie && quotient % 2n !== 0n);\n }\n}\n\n/**\n * `value` rounded to `fractionDigits` digits after the point by `mode`,\n * exactly as Intl rounds the same text: `\"2.345\"` is `\"2.35\"` with\n * `halfExpand` and `\"2.34\"` with `halfEven`. A value that rounds to zero\n * is `\"0\"`, never `\"-0\"`.\n */\nexport function roundDecimal(\n value: DecimalString,\n fractionDigits: number,\n mode: RoundingMode,\n): DecimalString {\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0) {\n throw new RangeError(`${String(fractionDigits)} is not a digit count`);\n }\n const { coefficient, scale } = toDecimal(value);\n if (scale <= fractionDigits) {\n return writeDecimal({ coefficient, scale });\n }\n const divisor = pow10(scale - fractionDigits);\n const quotient = coefficient / divisor;\n const remainder = coefficient % divisor;\n const negative = coefficient < 0n;\n const away =\n remainder !== 0n &&\n roundsAway(\n mode,\n negative,\n (negative ? -remainder : remainder) * 2n,\n divisor,\n quotient,\n );\n return writeDecimal({\n coefficient: away ? quotient + (negative ? -1n : 1n) : quotient,\n scale: fractionDigits,\n });\n}\n\n/** `value` times 10 to the `places`, exactly: `shiftDecimal(\"0.125\", 2)` is `\"12.5\"`. */\nexport function shiftDecimal(\n value: DecimalString,\n places: number,\n): DecimalString {\n if (!Number.isInteger(places)) {\n throw new RangeError(`${String(places)} is not a whole number of places`);\n }\n const { coefficient, scale } = toDecimal(value);\n const shifted = scale - places;\n return shifted >= 0\n ? writeDecimal({ coefficient, scale: shifted })\n : writeDecimal({ coefficient: coefficient * pow10(-shifted), scale: 0 });\n}\n\n/**\n * The multiple of `step` counted from `base` that is nearest `value` on\n * its `side`: the greatest not above it (`\"below\"`) or the least not below\n * it (`\"above\"`); `value` itself when it is one.\n */\nexport function snapDecimal(\n value: DecimalString,\n base: DecimalString,\n step: DecimalString,\n side: \"below\" | \"above\",\n): DecimalString {\n const target = toDecimal(value);\n const origin = toDecimal(base);\n const size = toDecimal(step);\n const scale = Math.max(target.scale, origin.scale, size.scale);\n const scaled = (decimal: Decimal) =>\n decimal.coefficient * pow10(scale - decimal.scale);\n const unit = scaled(size);\n if (unit <= 0n) {\n throw new RangeError(`The step \"${step}\" is not above zero`);\n }\n const offset = scaled(target) - scaled(origin);\n let steps = offset / unit;\n const remainder = offset % unit;\n if (remainder < 0n && side === \"below\") {\n steps -= 1n;\n } else if (remainder > 0n && side === \"above\") {\n steps += 1n;\n }\n return writeDecimal({ coefficient: scaled(origin) + steps * unit, scale });\n}\n\n/**\n * The shortest decimal that reads back as `value`, with no exponent:\n * `1e21` is `\"1000000000000000000000\"`, `-0` is `\"0\"`. Throws a\n * `RangeError` for `NaN` and the infinities.\n */\nexport function numberToDecimal(value: number): DecimalString {\n const match = /^(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/.exec(\n String(Math.abs(value)),\n );\n if (match === null) {\n throw new RangeError(`${String(value)} has no decimal form`);\n }\n const integer = match[1] ?? \"\";\n const fraction = match[2] ?? \"\";\n const scale = fraction.length - Number(match[3] ?? 0);\n const magnitude = BigInt(integer + fraction);\n const coefficient = scale < 0 ? magnitude * pow10(-scale) : magnitude;\n return writeDecimal({\n coefficient: value < 0 ? -coefficient : coefficient,\n scale: Math.max(scale, 0),\n });\n}\n\n/**\n * `value` as a JS number, and whether that number writes back as exactly\n * this decimal: `\"0.1\"` is exact, `\"9007199254740993\"` is not (it becomes\n * …992), and neither is a decimal beyond the number range.\n */\nexport function decimalToNumber(value: DecimalString): {\n readonly number: number;\n readonly exact: boolean;\n} {\n const decimal = writeDecimal(toDecimal(value));\n const number = Number(decimal);\n return {\n number,\n exact:\n Number.isFinite(number) &&\n compareDecimals(numberToDecimal(number), decimal) === 0,\n };\n}\n\n/**\n * `value` as a decimal in normal form, whichever value type it is, its\n * fraction padded to `minimumFractionDigits`.\n */\nexport function decimalOf(\n value: NumberLike,\n minimumFractionDigits = 0,\n): DecimalString {\n return writeDecimal(\n toDecimal(typeof value === \"number\" ? numberToDecimal(value) : value),\n minimumFractionDigits,\n );\n}\n\n/** How many digits `value` has after the point, trailing zeros not counted. */\nexport function fractionDigitsOf(value: DecimalString): number {\n const normal = writeDecimal(toDecimal(value));\n const point = normal.indexOf(\".\");\n return point === -1 ? 0 : normal.length - point - 1;\n}\n","import type { RoundingMode } from \"./decimal\";\nimport type { NumberSymbolOverrides } from \"./symbols\";\n\nexport type NumberStyle = \"decimal\" | \"percent\" | \"currency\" | \"unit\";\n\n/** How a negative number is written: `-12`, `(12)` or `12-`. Each is read in every field. */\nexport type NegativeStyle = \"minus\" | \"parentheses\" | \"trailingMinus\";\n\n/** Whether 12 % is stored as 0.12 (`\"fraction\"`, Intl's reading) or as 12 (`\"percent\"`). */\nexport type PercentScale = \"fraction\" | \"percent\";\n\n/** What a number field holds: a JS `number`, or an exact decimal string. */\nexport type NumberValueType = \"number\" | \"decimal\";\n\n/** The value type `T` names. */\nexport type NumberValue<T extends NumberValueType> = T extends \"decimal\"\n ? string\n : number;\n\n/**\n * How numbers read and write. Every name `Intl.NumberFormatOptions` also\n * has means what it means there, so a grid column's `format` can be passed\n * on. As in Intl, `currency` and `unit` take effect with their `style`, and\n * an unknown currency code or unit throws Intl's `RangeError`.\n */\nexport interface NumberOptions extends NumberSymbolOverrides {\n readonly locale?: Intl.LocalesArgument;\n /** `\"decimal\"` by default. */\n readonly style?: NumberStyle | undefined;\n /** ISO 4217 code; with `style: \"currency\"`. */\n readonly currency?: string | undefined;\n /** `\"symbol\"` by default. */\n readonly currencyDisplay?:\n \"symbol\" | \"narrowSymbol\" | \"code\" | \"name\" | undefined;\n /** An Intl unit identifier (`\"kilogram\"`, `\"kilometer-per-hour\"`); with `style: \"unit\"`. */\n readonly unit?: string | undefined;\n /** `\"short\"` by default. */\n readonly unitDisplay?: \"short\" | \"narrow\" | \"long\" | undefined;\n /** 0 by default; a currency's minor units. For a percent, of the number shown. */\n readonly minimumFractionDigits?: number | undefined;\n /** Unset: no rounding, every digit typed is kept (a currency: its minor units). */\n readonly maximumFractionDigits?: number | undefined;\n /** `\"halfExpand\"` (ties away from zero) by default. */\n readonly roundingMode?: RoundingMode | undefined;\n /** Group the integer digits when the value is shown formatted. On by default. */\n readonly useGrouping?: boolean | undefined;\n /** `\"minus\"` by default. */\n readonly negative?: NegativeStyle | undefined;\n /** `\"fraction\"` by default. */\n readonly percentScale?: PercentScale | undefined;\n}\n\n/** The fraction digits a field writes, and rounds its value to. */\nexport interface FractionDigits {\n readonly minimum: number;\n /** `null`: no rounding, every digit is kept. */\n readonly maximum: number | null;\n}\n\n/** Minor units per currency code, read from Intl once. */\nconst currencyDigits = new Map<string, number>();\n\n/** The digits ISO 4217 gives `currency`: 2 for EUR, 0 for JPY, 3 for KWD. */\nfunction minorUnits(currency: string): number {\n let digits = currencyDigits.get(currency);\n if (digits === undefined) {\n digits =\n new Intl.NumberFormat(\"en\", {\n style: \"currency\",\n currency,\n }).resolvedOptions().maximumFractionDigits ?? 2;\n currencyDigits.set(currency, digits);\n }\n return digits;\n}\n\n/**\n * The fraction digits `options` ask for: the minimum written and the\n * maximum kept. A currency defaults both to its minor units; otherwise the\n * minimum is 0 and there is no maximum. A maximum below the minimum is\n * raised to it. A field has fixed decimals when the two are equal.\n */\nexport function numberFractionDigits(\n options: NumberOptions = {},\n): FractionDigits {\n const own =\n options.style === \"currency\" && options.currency !== undefined\n ? minorUnits(options.currency)\n : null;\n const maximum = options.maximumFractionDigits ?? own;\n const minimum =\n options.minimumFractionDigits ??\n (own === null ? 0 : Math.min(own, maximum ?? own));\n return {\n minimum,\n maximum: maximum === null ? null : Math.max(maximum, minimum),\n };\n}\n","import { localeKey } from \"../localeKey\";\n\n/** How a locale writes numbers, read from `Intl.NumberFormat#formatToParts`. */\nexport interface NumberSymbols {\n /** The numbering system the field writes in: `\"latn\"`, `\"arab\"`, `\"deva\"`, ... */\n readonly numberingSystem: string;\n /** Its ten digits, zero first. */\n readonly digits: string;\n readonly decimal: string;\n /** `\"\"` when the field writes no grouping. */\n readonly group: string;\n /** Digits in the last group, then in every group before it: `[3, 3]`, or `[3, 2]` for lakh grouping. */\n readonly groupSizes: readonly [primary: number, secondary: number];\n /** 2 where a four-digit number is written ungrouped (\"1234\" in `es-ES`), else 1. */\n readonly minimumGroupingDigits: 1 | 2;\n /** Without the direction marks Intl puts around it. */\n readonly minus: string;\n readonly percent: string;\n /** Whether the locale writes numbers left to right inside right-to-left text. */\n readonly numbersLeftToRight: boolean;\n}\n\n/** What a field may set over its locale's symbols. */\nexport interface NumberSymbolOverrides {\n /** Replaces the locale's decimal separator; it must differ from the group separator. */\n readonly decimalSeparator?: string | undefined;\n /** Replaces the locale's group separator; `\"\"` writes no grouping. */\n readonly groupSeparator?: string | undefined;\n readonly groupSizes?:\n readonly [primary: number, secondary: number] | undefined;\n /** The digits the field writes: `\"latn\"` keeps Latin digits in `ar-EG`. */\n readonly numberingSystem?: string | undefined;\n}\n\n/** Marks Intl puts around a sign to keep it in place in right-to-left text. */\nexport const DIRECTION_MARKS =\n /[\\u200E\\u200F\\u061C\\u202A-\\u202E\\u2066-\\u2069]/g;\n\nconst RIGHT_TO_LEFT_MARK = /[\\u061C\\u200F]/;\n\n/**\n * Symbols already read, one per locale and overrides: building an\n * `Intl.NumberFormat` costs far more than using one, and a page has few.\n */\nconst cache = new Map<string, NumberSymbols>();\n\n/** The symbols `locale` writes with, in `numberingSystem` when given. */\nfunction localeSymbols(\n locale: Intl.LocalesArgument,\n numberingSystem: string | undefined,\n): NumberSymbols {\n const options = numberingSystem === undefined ? {} : { numberingSystem };\n const format = new Intl.NumberFormat(locale, options);\n const parts = format.formatToParts(-1234567.891);\n const part = (type: Intl.NumberFormatPartTypes) =>\n parts.find((found) => found.type === type)?.value;\n const groups = parts\n .filter((found) => found.type === \"integer\")\n .map((found) => found.value.length);\n const primary = groups.at(-1) ?? 3;\n const secondary = groups.length > 2 ? (groups.at(-2) ?? primary) : primary;\n const group = part(\"group\") ?? \"\";\n const percent = new Intl.NumberFormat(locale, {\n ...options,\n style: \"percent\",\n })\n .formatToParts(0.5)\n .find((found) => found.type === \"percentSign\")?.value;\n return {\n numberingSystem: format.resolvedOptions().numberingSystem,\n digits: Array.from({ length: 10 }, (_, digit) => format.format(digit)).join(\n \"\",\n ),\n decimal: part(\"decimal\") ?? \".\",\n group,\n groupSizes: [primary, secondary],\n minimumGroupingDigits:\n group !== \"\" &&\n !format.formatToParts(1234).some((found) => found.type === \"group\")\n ? 2\n : 1,\n minus: (part(\"minusSign\") ?? \"-\").replace(DIRECTION_MARKS, \"\"),\n percent: percent ?? \"%\",\n numbersLeftToRight: !RIGHT_TO_LEFT_MARK.test(format.format(-1)),\n };\n}\n\nfunction isGroupSize(size: number): boolean {\n return Number.isInteger(size) && size > 0;\n}\n\n/**\n * How `locale` writes numbers: its separators, group sizes, digits, minus\n * and percent signs, read from Intl at run time (they differ between ICU\n * versions), with the field's overrides laid over them. Separators that\n * would clash (an empty decimal separator, or both the same) and group\n * sizes that are not positive whole numbers are ignored, leaving the\n * locale's own. Cached per locale and overrides.\n */\nexport function numberSymbols(\n locale: Intl.LocalesArgument,\n overrides: NumberSymbolOverrides = {},\n): NumberSymbols {\n const { decimalSeparator, groupSeparator, groupSizes, numberingSystem } =\n overrides;\n const key = JSON.stringify([\n localeKey(locale),\n decimalSeparator,\n groupSeparator,\n groupSizes,\n numberingSystem,\n ]);\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const own = localeSymbols(locale, numberingSystem);\n const decimal = decimalSeparator ?? own.decimal;\n const group = groupSeparator ?? own.group;\n const separators =\n decimal === \"\" || decimal === group\n ? { decimal: own.decimal, group: own.group }\n : { decimal, group };\n const symbols: NumberSymbols = {\n ...own,\n ...separators,\n groupSizes:\n groupSizes !== undefined && groupSizes.every(isGroupSize)\n ? groupSizes\n : own.groupSizes,\n };\n cache.set(key, symbols);\n return symbols;\n}\n","import { localeKey } from \"../localeKey\";\nimport {\n decimalOf,\n fractionDigitsOf,\n shiftDecimal,\n type DecimalString,\n type NumberLike,\n} from \"./decimal\";\nimport {\n numberFractionDigits,\n type FractionDigits,\n type NumberOptions,\n} from \"./options\";\nimport { DIRECTION_MARKS, numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/**\n * Which text `formatNumber` writes:\n *\n * - `display`: what a field shows when it does not have focus: grouped,\n * fraction digits padded, the negative style; no currency, percent sign\n * or unit.\n * - `edit`: what a focused field shows: no grouping, a leading minus, the\n * digits the value has, padded to the minimum.\n * - `full`: Intl's whole text, with the currency, percent sign or unit, as\n * display mode, the `formatted` event detail and a grid cell show it.\n */\nexport type NumberTextForm = \"display\" | \"edit\" | \"full\";\n\n/** Where the currency, percent sign or unit sits around the number, for an input's adornments. */\nexport interface NumberAffixes {\n readonly prefix: string;\n readonly suffix: string;\n}\n\nconst NO_AFFIXES: NumberAffixes = { prefix: \"\", suffix: \"\" };\n\n/** Intl allows no more fraction digits than this. */\nconst MAX_FRACTION_DIGITS = 100;\n\nconst EDGE_SPACING = /^[\\s\\u200E\\u200F\\u061C]+|[\\s\\u200E\\u200F\\u061C]+$/g;\n\ninterface Part {\n readonly type: string;\n readonly value: string;\n}\n\n/** Formats already built, by locale and options. */\nconst formats = new Map<string, Intl.NumberFormat>();\n\nfunction intlFormat(\n locale: Intl.LocalesArgument,\n options: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n const key = JSON.stringify([localeKey(locale), options]);\n let format = formats.get(key);\n if (format === undefined) {\n format = new Intl.NumberFormat(locale, options);\n formats.set(key, format);\n }\n return format;\n}\n\nfunction isPercent(options: NumberOptions): boolean {\n return options.style === \"percent\";\n}\n\n/** The number a field shows for `value`: for a percent, the percent number (12.5 for 0.125). */\nfunction shownDecimal(\n value: NumberLike,\n options: NumberOptions,\n): DecimalString {\n const decimal = decimalOf(value);\n return isPercent(options) && options.percentScale !== \"percent\"\n ? shiftDecimal(decimal, 2)\n : decimal;\n}\n\n/** What Intl formats for `value`: for a percent, the fraction it multiplies by 100. */\nfunction intlValue(\n value: NumberLike,\n options: NumberOptions,\n): Intl.StringNumericLiteral {\n const decimal = decimalOf(value);\n const scaled =\n isPercent(options) && options.percentScale === \"percent\"\n ? shiftDecimal(decimal, -2)\n : decimal;\n // A decimal string is a numeric string, which Intl formats exactly.\n return scaled as Intl.StringNumericLiteral;\n}\n\n/** The fraction digits to write `shown` with: with no maximum, every digit it has. */\nfunction digitsFor(\n options: NumberOptions,\n shown: readonly DecimalString[],\n): FractionDigits & { readonly maximum: number } {\n const { minimum, maximum } = numberFractionDigits(options);\n const kept =\n maximum ??\n Math.max(minimum, ...shown.map((value) => fractionDigitsOf(value)));\n return { minimum, maximum: Math.min(kept, MAX_FRACTION_DIGITS) };\n}\n\nfunction intlOptions(\n options: NumberOptions,\n form: NumberTextForm,\n digits: FractionDigits & { readonly maximum: number },\n grouping: boolean,\n): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = {\n minimumFractionDigits: digits.minimum,\n maximumFractionDigits: digits.maximum,\n roundingMode: options.roundingMode ?? \"halfExpand\",\n // `true` would group four-digit numbers in locales that do not.\n useGrouping: grouping ? \"auto\" : false,\n // Intl writes \"-0\" for a negative value that rounds to zero otherwise.\n signDisplay: \"negative\",\n numberingSystem: options.numberingSystem,\n };\n if (form !== \"full\") {\n return { ...base, style: \"decimal\" };\n }\n switch (options.style ?? \"decimal\") {\n case \"decimal\":\n return { ...base, style: \"decimal\" };\n case \"percent\":\n return { ...base, style: \"percent\" };\n case \"currency\":\n return {\n ...base,\n style: \"currency\",\n currency: options.currency,\n currencyDisplay: options.currencyDisplay ?? \"symbol\",\n };\n case \"unit\":\n return {\n ...base,\n style: \"unit\",\n unit: options.unit,\n unitDisplay: options.unitDisplay ?? \"short\",\n };\n }\n}\n\n/** Whether `form` groups the integer digits. */\nfunction groups(\n options: NumberOptions,\n symbols: NumberSymbols,\n form: NumberTextForm,\n): boolean {\n return (\n form !== \"edit\" && options.useGrouping !== false && symbols.group !== \"\"\n );\n}\n\n/** `digits` grouped by the field's sizes and separator. */\nfunction regroup(digits: string, symbols: NumberSymbols): string {\n const characters = Array.from(digits);\n const [primary, secondary] = symbols.groupSizes;\n if (characters.length < primary + symbols.minimumGroupingDigits) {\n return digits;\n }\n let end = characters.length - primary;\n const grouped = [characters.slice(end).join(\"\")];\n while (end > 0) {\n const start = Math.max(0, end - secondary);\n grouped.unshift(characters.slice(start, end).join(\"\"));\n end = start;\n }\n return grouped.join(symbols.group);\n}\n\n/**\n * Intl's parts with the field's own separators and group sizes where it\n * overrides the locale's (an override `numberSymbols` ignored is not in\n * them): the integer digits of each number are grouped again when the\n * text is grouped and the sizes are the field's own.\n */\nfunction withFieldSymbols(\n parts: readonly Part[],\n options: NumberOptions,\n symbols: NumberSymbols,\n grouping: boolean,\n): Part[] {\n const decimal =\n options.decimalSeparator === symbols.decimal ? symbols.decimal : null;\n const group = options.groupSeparator === symbols.group ? symbols.group : null;\n const sizes = options.groupSizes;\n const ownSizes =\n grouping &&\n sizes !== undefined &&\n sizes.every((size, index) => size === symbols.groupSizes[index]);\n const written: Part[] = [];\n for (const part of parts) {\n if (ownSizes && (part.type === \"integer\" || part.type === \"group\")) {\n const previous = written.at(-1);\n const digits = part.type === \"integer\" ? part.value : \"\";\n if (previous?.type === \"integer\") {\n written[written.length - 1] = {\n type: \"integer\",\n value: previous.value + digits,\n };\n } else {\n written.push({ type: \"integer\", value: digits });\n }\n } else if (part.type === \"decimal\" && decimal !== null) {\n written.push({ type: \"decimal\", value: decimal });\n } else if (part.type === \"group\" && group !== null) {\n written.push({ type: \"group\", value: group });\n } else {\n written.push(part);\n }\n }\n return ownSizes\n ? written.map((part) =>\n part.type === \"integer\"\n ? { type: \"integer\", value: regroup(part.value, symbols) }\n : part,\n )\n : written;\n}\n\nconst NUMERIC_PARTS = new Set([\"integer\", \"group\", \"decimal\", \"fraction\"]);\n\n/** The text of `parts`, its minus written in the `negative` style. */\nfunction joinWithSign(\n parts: readonly Part[],\n negative: NumberOptions[\"negative\"],\n): string {\n const minusAt = parts.findIndex((part) => part.type === \"minusSign\");\n const minus = parts[minusAt];\n if (minus === undefined || negative === undefined || negative === \"minus\") {\n return parts.map((part) => part.value).join(\"\");\n }\n const rest = parts.filter((_, index) => index !== minusAt);\n const text = (list: readonly Part[]) =>\n list.map((part) => part.value).join(\"\");\n if (negative === \"parentheses\") {\n return `(${text(rest)})`;\n }\n const lastDigit = rest.findLastIndex(\n (part) => part.type === \"integer\" || part.type === \"fraction\",\n );\n return (\n text(rest.slice(0, lastDigit + 1)) +\n minus.value.replace(DIRECTION_MARKS, \"\") +\n text(rest.slice(lastDigit + 1))\n );\n}\n\n/**\n * `value` as text, in one of three forms (`display` by default; see\n * `NumberTextForm`). A decimal string is formatted without passing through\n * a JS number, so every digit of a 20-digit amount is written. With no\n * maximum, every fraction digit of the value is written; with one, the\n * value is rounded to it by `roundingMode`. Nothing is written as \"-0\".\n * Throws a `RangeError` for a string that is not a decimal, or a number\n * that is not finite.\n */\nexport function formatNumber(\n value: NumberLike,\n options: NumberOptions = {},\n form: NumberTextForm = \"display\",\n): string {\n const symbols = numberSymbols(options.locale, options);\n const shown = shownDecimal(value, options);\n const grouping = groups(options, symbols, form);\n const format = intlFormat(\n options.locale,\n intlOptions(options, form, digitsFor(options, [shown]), grouping),\n );\n const parts = withFieldSymbols(\n format.formatToParts(\n form === \"full\"\n ? intlValue(value, options)\n : (shown as Intl.StringNumericLiteral),\n ),\n options,\n symbols,\n grouping,\n );\n const text = joinWithSign(\n parts,\n form === \"edit\" ? \"minus\" : options.negative,\n );\n return form === \"full\" ? text : text.replace(DIRECTION_MARKS, \"\");\n}\n\n/**\n * The currency, percent sign or unit written before and after the number\n * in `full` text, trimmed of spacing, for an input to draw beside its\n * text: `$` before in `en-US`, `€` after in `de-DE`, `%` before in\n * `tr-TR`. A spelled-out name agrees with `value` (\"1 euro\", \"2 euros\");\n * without one it is written for 0. Both are `\"\"` for a plain decimal.\n */\nexport function numberAffixes(\n options: NumberOptions = {},\n value: NumberLike = 0,\n): NumberAffixes {\n if ((options.style ?? \"decimal\") === \"decimal\") {\n return NO_AFFIXES;\n }\n const positive = decimalOf(value).replace(/^-/, \"\");\n const format = intlFormat(\n options.locale,\n intlOptions(\n options,\n \"full\",\n digitsFor(options, [shownDecimal(positive, options)]),\n false,\n ),\n );\n const parts = format.formatToParts(intlValue(positive, options));\n const first = parts.findIndex((part) => NUMERIC_PARTS.has(part.type));\n const last = parts.findLastIndex((part) => NUMERIC_PARTS.has(part.type));\n const text = (list: readonly Part[]) =>\n list\n .map((part) => part.value)\n .join(\"\")\n .replace(EDGE_SPACING, \"\");\n return {\n prefix: text(parts.slice(0, first)),\n suffix: text(parts.slice(last + 1)),\n };\n}\n\n/**\n * Intl's text for the range from `start` to `end`, in the `full` form:\n * \"10–20\", \"10,00–20,00 €\". Ends that write the same are written once\n * (\"10\", where Intl writes \"~10\"). A negative end in another `negative`\n * style than the minus writes each end whole around the locale's range\n * separator: \"(10)–20\".\n */\nexport function formatNumberRange(\n start: NumberLike,\n end: NumberLike,\n options: NumberOptions = {},\n): string {\n const symbols = numberSymbols(options.locale, options);\n const grouping = groups(options, symbols, \"full\");\n const format = intlFormat(\n options.locale,\n intlOptions(\n options,\n \"full\",\n digitsFor(options, [\n shownDecimal(start, options),\n shownDecimal(end, options),\n ]),\n grouping,\n ),\n );\n const parts = format.formatRangeToParts(\n intlValue(start, options),\n intlValue(end, options),\n );\n if (!parts.some((part) => part.source === \"endRange\")) {\n return formatNumber(start, options, \"full\");\n }\n if (\n (options.negative ?? \"minus\") !== \"minus\" &&\n parts.some((part) => part.type === \"minusSign\")\n ) {\n const lastStart = parts.findLastIndex(\n (part) => part.source === \"startRange\",\n );\n const firstEnd = parts.findIndex((part) => part.source === \"endRange\");\n const separator = parts\n .slice(lastStart + 1, firstEnd)\n .filter((part) => part.type === \"literal\")\n .map((part) => part.value)\n .join(\"\");\n return (\n formatNumber(start, options, \"full\") +\n separator +\n formatNumber(end, options, \"full\")\n );\n }\n return withFieldSymbols(parts, options, symbols, grouping)\n .map((part) => part.value)\n .join(\"\");\n}\n","import { isDigit, numberingSystemOf } from \"./digits\";\nimport { numberAffixes } from \"./formatNumber\";\nimport type { NegativeStyle, NumberOptions } from \"./options\";\nimport { DIRECTION_MARKS, type NumberSymbols } from \"./symbols\";\n\n/** How a text was read. */\nexport interface NumberReadingInfo {\n /** The character taken as the decimal point, as typed; `null` when there was none. */\n readonly decimalSeparator: string | null;\n /** Whether the integer digits were grouped. */\n readonly grouped: boolean;\n /** How a negative number was written; `null` for one that is not negative. */\n readonly negative: NegativeStyle | null;\n /** The numbering systems of the digits typed, in the order met: `[\"latn\"]`, `[\"arab\"]`, `[\"latn\", \"fullwide\"]`. */\n readonly digits: readonly string[];\n /** The text was a paste or drop that clean-up rewrote. */\n readonly cleaned: boolean;\n}\n\nconst FULL_WIDTH = /[\\uFF01-\\uFF5E]/g;\nconst MINUS_SIGNS = /[\\u2212\\uFE63]/g;\n\n/**\n * `text` with the noise of where it came from removed: direction marks\n * dropped, full-width forms (which a Chinese or Japanese input method\n * types) turned into ASCII, every minus sign into `-`, and trimmed.\n */\nexport function plainNumberText(text: string): string {\n return text\n .replace(DIRECTION_MARKS, \"\")\n .replace(FULL_WIDTH, (char) =>\n String.fromCharCode(char.charCodeAt(0) - 0xfee0),\n )\n .replace(MINUS_SIGNS, \"-\")\n .trim();\n}\n\n/** The numbering systems of the digits in `text`, in the order met. */\nexport function digitSystems(text: string): string[] {\n const systems = new Set<string>();\n for (const char of text) {\n if (isDigit(char)) {\n systems.add(numberingSystemOf(char));\n }\n }\n return [...systems];\n}\n\nconst SPACES = [\" \", \"\\u00A0\", \"\\u202F\", \"\\u2009\"];\n/** The apostrophes typed for an apostrophe group separator, as in `de-CH`. */\nexport const APOSTROPHES: readonly string[] = [\"'\", \"\\u2019\", \"\\u02BC\"];\nconst ARABIC_GROUP = \"\\u066C\";\nconst ARABIC_DECIMAL = \"\\u066B\";\n\n/** `separator` and the characters typed for it: any space for a space, any apostrophe for an apostrophe. */\nfunction lookalikes(separator: string): readonly string[] {\n if (SPACES.includes(separator)) {\n return SPACES;\n }\n if (APOSTROPHES.includes(separator)) {\n return APOSTROPHES;\n }\n if (separator === ARABIC_GROUP) {\n return [ARABIC_GROUP, \",\", \"\\u060C\"];\n }\n if (separator === ARABIC_DECIMAL) {\n return [ARABIC_DECIMAL, \".\"];\n }\n return separator === \"\" ? [] : [separator];\n}\n\n/** The characters a field reads as its decimal point and as its group separator. */\nexport interface FieldSeparators {\n readonly decimal: ReadonlySet<string>;\n readonly group: ReadonlySet<string>;\n}\n\n/** The field's separators and their lookalikes; the decimal's own character wins a clash. */\nexport function fieldSeparators(symbols: NumberSymbols): FieldSeparators {\n const decimal = new Set(\n lookalikes(symbols.decimal).filter((char) => char !== symbols.group),\n );\n const group = new Set(\n lookalikes(symbols.group).filter((char) => !decimal.has(char)),\n );\n return { decimal, group };\n}\n\n/**\n * Whether integer digit groups (as split by group separators) are grouped\n * the way the field groups: the first group 1 to the larger size long, the\n * last exactly the primary size, every one between either size. So `en-IN`\n * reads both \"12,34,567\" and \"1,234,567\", and `en-US` neither \"12,34,567\"\n * nor \"1,5\".\n */\nexport function groupingFits(\n groups: readonly string[],\n [primary, secondary]: NumberSymbols[\"groupSizes\"],\n): boolean {\n const [first = \"\", ...rest] = groups;\n const last = rest.at(-1);\n return (\n first.length >= 1 &&\n first.length <= Math.max(primary, secondary) &&\n last?.length === primary &&\n rest\n .slice(0, -1)\n .every((group) => group.length === secondary || group.length === primary)\n );\n}\n\n/** The currency, percent and unit texts a field accepts around its number, longest first. */\nfunction affixTokens(options: NumberOptions, symbols: NumberSymbols): string[] {\n const style = options.style ?? \"decimal\";\n if (style === \"decimal\") {\n return [];\n }\n const { prefix, suffix } = numberAffixes(options);\n const tokens = [prefix, suffix];\n if (style === \"currency\" && options.currency !== undefined) {\n tokens.push(options.currency.toUpperCase());\n }\n if (style === \"percent\") {\n tokens.push(\"%\", symbols.percent);\n }\n return [...new Set(tokens.map(plainNumberText))]\n .filter((token) => token !== \"\")\n .sort((a, b) => b.length - a.length);\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * `text` with the field's own currency sign or code, percent sign or unit\n * removed from either end, inside or outside a sign: \"-$1,234.50\",\n * \"1.234,50- €\" and \"(1.234,50 €)\" keep their signs.\n */\nexport function withoutAffixes(\n text: string,\n options: NumberOptions,\n symbols: NumberSymbols,\n): string {\n let rest = text;\n for (const token of affixTokens(options, symbols)) {\n const escaped = escapeRegExp(token);\n rest = rest\n .replace(new RegExp(`^([-+(]?)\\\\s*${escaped}\\\\s*`, \"u\"), \"$1\")\n .replace(new RegExp(`\\\\s*${escaped}\\\\s*([-)]?)$`, \"u\"), \"$1\");\n }\n return rest.trim();\n}\n\n/** The sign of a number's text, and the text inside it. */\nexport interface SignedText {\n readonly body: string;\n readonly negative: NegativeStyle | null;\n /** False for an opening parenthesis with no closing one yet. */\n readonly closed: boolean;\n}\n\n/** Reads a leading `-` or `+`, a trailing `-`, or parentheses around the whole text. */\nexport function readSign(text: string): SignedText {\n if (text.startsWith(\"(\")) {\n const closed = text.endsWith(\")\") && text.length > 1;\n return {\n body: text.slice(1, closed ? -1 : undefined).trim(),\n negative: \"parentheses\",\n closed,\n };\n }\n if (text.startsWith(\"-\") || text.startsWith(\"+\")) {\n return {\n body: text.slice(1).trim(),\n negative: text.startsWith(\"-\") ? \"minus\" : null,\n closed: true,\n };\n }\n if (text.endsWith(\"-\")) {\n return {\n body: text.slice(0, -1).trim(),\n negative: \"trailingMinus\",\n closed: true,\n };\n }\n return { body: text, negative: null, closed: true };\n}\n","import { digitValue, isDigit } from \"./digits\";\nimport type { NumberOptions } from \"./options\";\nimport {\n APOSTROPHES,\n digitSystems,\n fieldSeparators,\n groupingFits,\n plainNumberText,\n readSign,\n withoutAffixes,\n type NumberReadingInfo,\n} from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/** A paste turned into the field's own text, and how it was read. */\nexport interface CleanedNumber {\n /** The field's edit text: its digits and decimal separator, a leading minus, no grouping, every digit kept. */\n readonly text: string;\n /** How the pasted text was read; `cleaned` is true. */\n readonly info: NumberReadingInfo;\n}\n\nconst CURRENCY_SIGN = /\\p{Sc}/gu;\nconst PERCENT_SIGNS = /[%\\u066A\\uFE6A]/g;\nconst UPPER_WORD = /(?<![A-Za-z])[A-Z]{3}(?![A-Za-z])/g;\n/** The Arabic group separator and comma, which never mark a decimal point. */\nconst ARABIC_GROUPS = new Set([\"\\u066C\", \"\\u060C\"]);\nconst ARABIC_DECIMAL = \"\\u066B\";\n\n/** ISO 4217 codes Intl knows, read once. */\nlet currencyCodes: ReadonlySet<string> | undefined;\n\nfunction isCurrencyCode(word: string): boolean {\n currencyCodes ??= new Set(Intl.supportedValuesOf(\"currency\"));\n return currencyCodes.has(word);\n}\n\n/** `text` without currency signs and codes or percent signs; other letters stay, to refuse the paste. */\nfunction withoutSymbols(text: string, symbols: NumberSymbols): string {\n return text\n .replace(UPPER_WORD, (word) => (isCurrencyCode(word) ? \" \" : word))\n .replace(CURRENCY_SIGN, \"\")\n .replace(PERCENT_SIGNS, \"\")\n .replaceAll(symbols.percent, \"\")\n .trim();\n}\n\ntype Character =\n | { readonly kind: \"digit\"; readonly value: number }\n | { readonly kind: \"group\" }\n | { readonly kind: \"decimal\" }\n | { readonly kind: \"mark\"; readonly char: string };\n\n/**\n * What one pasted character can be: spaces and apostrophes always group,\n * as do the Arabic group separator and comma; the Arabic decimal separator\n * is always the point; `.`, `,` and the field's own separators are marks\n * whose role depends on the rest. `null` for anything else.\n */\nfunction characterOf(char: string, symbols: NumberSymbols): Character | null {\n if (isDigit(char)) {\n return { kind: \"digit\", value: digitValue(char) };\n }\n if (\n /\\s/u.test(char) ||\n APOSTROPHES.includes(char) ||\n ARABIC_GROUPS.has(char)\n ) {\n return { kind: \"group\" };\n }\n if (char === ARABIC_DECIMAL) {\n return { kind: \"decimal\" };\n }\n return char === \".\" ||\n char === \",\" ||\n char === symbols.decimal ||\n char === symbols.group\n ? { kind: \"mark\", char }\n : null;\n}\n\n/**\n * Which mark is the decimal point, or `null` for none:\n *\n * - two different marks: the one that comes last;\n * - one mark, more than once: none, it groups;\n * - one mark, once: the field's decimal separator (or a lookalike) is the\n * point; any other mark groups when the field's grouping fits it and is\n * the point when it does not (\"1,5\" is 1.5 in `en-US`, \"1.234\" 1234 in\n * `de-DE`).\n */\nfunction decimalMark(\n characters: readonly Character[],\n symbols: NumberSymbols,\n): string | null {\n const marks = characters.flatMap((character) =>\n character.kind === \"mark\" ? [character.char] : [],\n );\n const distinct = new Set(marks);\n const [only] = distinct;\n if (distinct.size > 1) {\n return marks.at(-1) ?? null;\n }\n if (only === undefined || marks.length > 1) {\n return null;\n }\n if (fieldSeparators(symbols).decimal.has(only)) {\n return only;\n }\n const groups: string[] = [];\n let group = \"\";\n for (const character of characters) {\n if (character.kind === \"digit\") {\n group += String(character.value);\n } else {\n groups.push(group);\n group = \"\";\n }\n }\n groups.push(group);\n return groupingFits(groups, symbols.groupSizes) ? null : only;\n}\n\n/**\n * Turns pasted or dropped text, copied from a web page, a PDF or a\n * spreadsheet in another locale, into the field's own edit text, or\n * returns `null` to refuse it. Currency signs and codes, percent signs and\n * the field's unit are dropped; parentheses or a leading or trailing minus\n * give the sign; any other letter refuses the paste, since dropping it\n * could change the number (\"12abc\", \"1e5\"). When both `.` and `,` appear,\n * the last is the decimal point (\"$1,234.50\" becomes \"1234,50\" in\n * `de-DE`); a lone mark is decided by the field's locale, so \"1.234\"\n * pasted into `de-DE` is 1234.\n */\nexport function cleanPastedNumber(\n text: string,\n options: NumberOptions = {},\n): CleanedNumber | null {\n const symbols = numberSymbols(options.locale, options);\n const rest = withoutSymbols(\n withoutAffixes(plainNumberText(text), options, symbols),\n symbols,\n );\n const sign = readSign(rest);\n if (!sign.closed) {\n return null;\n }\n const characters: Character[] = [];\n for (const char of sign.body) {\n const character = characterOf(char, symbols);\n if (character === null) {\n return null;\n }\n characters.push(character);\n }\n const point = characters.some((character) => character.kind === \"decimal\")\n ? ARABIC_DECIMAL\n : decimalMark(characters, symbols);\n const fieldDigits = Array.from(symbols.digits);\n let integer = \"\";\n let fraction: string | null = null;\n let grouped = false;\n for (const character of characters) {\n const isPoint =\n character.kind === \"decimal\" ||\n (character.kind === \"mark\" && character.char === point);\n if (isPoint) {\n if (fraction !== null) {\n return null;\n }\n fraction = \"\";\n } else if (character.kind === \"digit\") {\n const digit = fieldDigits[character.value] ?? String(character.value);\n if (fraction === null) {\n integer += digit;\n } else {\n fraction += digit;\n }\n } else if (fraction === null) {\n grouped = true;\n } else {\n return null;\n }\n }\n const digits = integer + (fraction ?? \"\");\n if (digits === \"\") {\n return null;\n }\n const negative =\n sign.negative !== null &&\n characters.some(\n (character) => character.kind === \"digit\" && character.value > 0,\n )\n ? sign.negative\n : null;\n return {\n text: `${negative === null ? \"\" : symbols.minus}${integer}${fraction === null ? \"\" : symbols.decimal + fraction}`,\n info: {\n decimalSeparator: fraction === null ? null : point,\n grouped,\n negative,\n digits: digitSystems(text),\n cleaned: true,\n },\n };\n}\n","import type { DecimalString } from \"./decimal\";\nimport { digitValue, isDigit } from \"./digits\";\nimport type { NumberOptions } from \"./options\";\nimport {\n digitSystems,\n fieldSeparators,\n groupingFits,\n plainNumberText,\n readSign,\n withoutAffixes,\n type FieldSeparators,\n type NumberReadingInfo,\n} from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/**\n * Why a text is not a number:\n *\n * - `notANumber`: a letter, a second decimal separator, a group separator\n * after it, an exponent.\n * - `incomplete`: a sign or separator with no digit yet (\"-\", \",\"), or an\n * opening parenthesis with no closing one.\n * - `grouping`: group separators where the field does not group (\"1,5\" in\n * `en-US`).\n * - `tooPrecise`: more digits than a JS number keeps exactly, for a field\n * holding numbers (`numberParser`).\n *\n * A minor release may add a member.\n */\nexport type NumberUnreadableReason =\n \"notANumber\" | \"incomplete\" | \"grouping\" | \"tooPrecise\";\n\n/** What a text reads as: nothing, an exact number, or why it is not one. */\nexport type NumberReading =\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"number\";\n /** Exact, as typed: point decimal, no grouping, no trailing fraction zeros. */\n readonly decimal: DecimalString;\n readonly info: NumberReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: NumberUnreadableReason };\n\nconst EMPTY = { kind: \"empty\" } as const;\n\nfunction unreadableBecause(reason: NumberUnreadableReason): NumberReading {\n return { kind: \"unreadable\", reason };\n}\n\n/** The digits of a number's text, in ASCII, and how it was written. */\ninterface NumberBody {\n readonly integer: string;\n readonly fraction: string;\n readonly decimalSeparator: string | null;\n readonly grouped: boolean;\n}\n\n/** Reads digits and separators: any decimal digits, the field's separators and their lookalikes. */\nfunction readBody(\n body: string,\n separators: FieldSeparators,\n groupSizes: NumberSymbols[\"groupSizes\"],\n): NumberBody | NumberUnreadableReason {\n const groups: string[] = [];\n let group = \"\";\n let fraction = \"\";\n let decimalSeparator: string | null = null;\n for (const char of body) {\n if (isDigit(char)) {\n const digit = String(digitValue(char));\n if (decimalSeparator === null) {\n group += digit;\n } else {\n fraction += digit;\n }\n } else if (decimalSeparator === null && separators.decimal.has(char)) {\n decimalSeparator = char;\n } else if (decimalSeparator === null && separators.group.has(char)) {\n groups.push(group);\n group = \"\";\n } else {\n return \"notANumber\";\n }\n }\n groups.push(group);\n const integer = groups.join(\"\");\n if (integer === \"\" && fraction === \"\") {\n return \"incomplete\";\n }\n const grouped = groups.length > 1;\n if (grouped && !groupingFits(groups, groupSizes)) {\n return \"grouping\";\n }\n return { integer, fraction, decimalSeparator, grouped };\n}\n\n/**\n * Reads text a user typed, strictly by the field's symbols, as an exact\n * decimal; it never rounds or guesses. It takes:\n *\n * - any Unicode decimal digits (`١٢٣` reads as 123 in `en-US`), and\n * full-width forms from an input method;\n * - the field's decimal separator once, and its group separator between\n * integer digits where its grouping allows (\"1,5\" is `grouping` in\n * `en-US`), each with its lookalikes (any space for a space);\n * - a leading `-` or `+`, a trailing `-`, or parentheses;\n * - the field's own currency sign or code, percent sign or unit at either\n * end, so its `full` text reads back.\n *\n * \"12,\" reads as 12, \",5\" as 0.5, \"007\" as 7, and \"-0\" as 0.\n */\nexport function parseNumber(\n text: string,\n options: NumberOptions = {},\n): NumberReading {\n const plain = plainNumberText(text);\n if (plain === \"\") {\n return EMPTY;\n }\n const symbols = numberSymbols(options.locale, options);\n const sign = readSign(withoutAffixes(plain, options, symbols));\n const body = readBody(\n sign.body,\n fieldSeparators(symbols),\n symbols.groupSizes,\n );\n if (typeof body === \"string\") {\n return unreadableBecause(body);\n }\n if (!sign.closed) {\n return unreadableBecause(\"incomplete\");\n }\n const integer = body.integer.replace(/^0+(?=\\d)/, \"\") || \"0\";\n const fraction = body.fraction.replace(/0+$/, \"\");\n const negative =\n sign.negative !== null && /[1-9]/.test(integer + fraction)\n ? sign.negative\n : null;\n return {\n kind: \"number\",\n decimal: `${negative === null ? \"\" : \"-\"}${integer}${fraction === \"\" ? \"\" : `.${fraction}`}`,\n info: {\n decimalSeparator: body.decimalSeparator,\n grouped: body.grouped,\n negative,\n digits: digitSystems(text),\n cleaned: false,\n },\n };\n}\n","import type { InputFilterDecision, TextEdit } from \"../field/plan\";\nimport { cleanPastedNumber } from \"./cleanPastedNumber\";\nimport { roundDecimal, type DecimalString } from \"./decimal\";\nimport { digitValue, isDigit } from \"./digits\";\nimport { formatNumber } from \"./formatNumber\";\nimport { numberFractionDigits, type NumberOptions } from \"./options\";\nimport { parseNumber } from \"./parseNumber\";\nimport { fieldSeparators, type NumberReadingInfo } from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/** How a number field takes what is typed, pasted and dropped into it. */\nexport interface NumberEntryOptions extends NumberOptions {\n /** Whether a minus or parentheses may be typed; false for a field whose `min` is 0 or above. True by default. */\n readonly negatives?: boolean | undefined;\n /** Refuses a digit that would type more fraction digits than the maximum, instead of rounding them. */\n readonly limitFractionDigits?: boolean | undefined;\n /**\n * `\"fixed\"` (default): a field with fixed decimals shows them all while\n * it has a value, the decimal separator jumps into them and they are\n * typed over. `\"free\"`: digits and one separator, typed as anywhere else.\n */\n readonly decimalEntry?: \"fixed\" | \"free\" | undefined;\n}\n\n/** What a number field does with an edit, and how clean-up read a paste. */\nexport interface NumberEntry {\n readonly decision: InputFilterDecision;\n /** How clean-up read the paste or drop the decision inserts; `null` for any other edit. */\n readonly pasted: NumberReadingInfo | null;\n}\n\nconst ALLOW = { kind: \"allow\" } as const;\nconst PREVENT = { kind: \"prevent\" } as const;\nconst SIGNS = new Set([\"-\", \"\\u2212\", \"+\", \"(\", \")\"]);\nconst MINUS_SIGNS = new Set([\"-\", \"\\u2212\", \"\\uFE63\"]);\n\nfunction entry(\n decision: InputFilterDecision,\n pasted: NumberReadingInfo | null = null,\n): NumberEntry {\n return { decision, pasted };\n}\n\n/**\n * The fraction digits a field types in place, or `null` when it types\n * them freely: with fixed-decimal entry, a minimum equal to a maximum\n * above zero.\n */\nexport function fixedFractionDigits(\n options: NumberEntryOptions,\n): number | null {\n const { minimum, maximum } = numberFractionDigits(options);\n return options.decimalEntry !== \"free\" && maximum === minimum && minimum > 0\n ? minimum\n : null;\n}\n\nfunction isPaste(edit: TextEdit<unknown>): boolean {\n return edit.source === \"paste\" || edit.source === \"drop\";\n}\n\n/** What an edit inserted, from the text before and after it: the middle that differs. */\nfunction insertedText(before: string, after: string): string {\n let start = 0;\n while (\n start < before.length &&\n start < after.length &&\n before[start] === after[start]\n ) {\n start += 1;\n }\n let end = 0;\n while (\n end < before.length - start &&\n end < after.length - start &&\n before[before.length - 1 - end] === after[after.length - 1 - end]\n ) {\n end += 1;\n }\n return after.slice(start, after.length - end);\n}\n\n/** The stretch of `before` an edit removed, from the text after it. */\nfunction removedRange(\n before: string,\n after: string,\n): readonly [start: number, end: number] {\n let start = 0;\n while (\n start < before.length &&\n start < after.length &&\n before[start] === after[start]\n ) {\n start += 1;\n }\n let end = before.length;\n while (\n end > start &&\n end - start > before.length - after.length &&\n before[end - 1] === after[after.length - (before.length - end) - 1]\n ) {\n end -= 1;\n }\n return [start, end];\n}\n\n/** The characters typed for the decimal point: the field's separator and its lookalikes. */\nfunction decimalChars(symbols: NumberSymbols): ReadonlySet<string> {\n return fieldSeparators(symbols).decimal;\n}\n\n/**\n * Whether the groups typed so far fit the field's grouping, the last one\n * still being typed: the first 1 to the larger size long, the ones after\n * either size, the last no longer than the primary size.\n */\nfunction groupsSoFarFit(integer: string, symbols: NumberSymbols): boolean {\n const separators = fieldSeparators(symbols).group;\n const groups: string[] = [];\n let group = \"\";\n for (const char of integer) {\n if (separators.has(char)) {\n groups.push(group);\n group = \"\";\n } else {\n group += char;\n }\n }\n groups.push(group);\n const [primary, secondary] = symbols.groupSizes;\n const [first = \"\", ...rest] = groups;\n const last = rest.pop();\n return (\n first.length >= 1 &&\n first.length <= Math.max(primary, secondary) &&\n rest.every(\n (group) => group.length === primary || group.length === secondary,\n ) &&\n (last === undefined || last.length <= primary)\n );\n}\n\n/** The integer part of typed text: its characters before the decimal separator, signs left out. */\nfunction integerText(text: string, decimals: ReadonlySet<string>): string {\n let integer = \"\";\n for (const char of text) {\n if (decimals.has(char)) {\n break;\n }\n if (!SIGNS.has(char)) {\n integer += char;\n }\n }\n return integer;\n}\n\n/** The text a number field could still become a number from: anything but `notANumber`. */\nfunction isValidStart(text: string, options: NumberOptions): boolean {\n const reading = parseNumber(text, options);\n return reading.kind !== \"unreadable\" || reading.reason !== \"notANumber\";\n}\n\n/** The digits typed after the decimal separator of `text`. */\nfunction fractionDigitsTyped(text: string, symbols: NumberSymbols): number {\n const decimals = decimalChars(symbols);\n const point = Array.from(text).findIndex((char) => decimals.has(char));\n if (point === -1) {\n return 0;\n }\n return Array.from(text)\n .slice(point + 1)\n .filter(isDigit).length;\n}\n\n/** Free entry: the edit stands when it leaves text that can still become a number. */\nfunction filterFree<N>(\n edit: TextEdit<N>,\n before: string,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (\n inputType === null ||\n inputType.startsWith(\"delete\") ||\n inputType.startsWith(\"history\")\n ) {\n return entry(ALLOW);\n }\n if (isPaste(edit)) {\n const pasted = input?.data ?? insertedText(before, edit.text);\n const cleaned = cleanPastedNumber(pasted, options);\n if (cleaned === null) {\n return entry(PREVENT);\n }\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n const text = before.slice(0, start) + cleaned.text + before.slice(end);\n return isValidStart(text, options)\n ? entry({ kind: \"rewrite\", data: cleaned.text }, cleaned.info)\n : entry(PREVENT);\n }\n const data = input?.data ?? insertedText(before, edit.text);\n const separators = fieldSeparators(symbols);\n const fractions = numberFractionDigits(options).maximum !== 0;\n const negatives = options.negatives !== false;\n for (const char of data) {\n const allowed =\n isDigit(char) ||\n (fractions && separators.decimal.has(char)) ||\n separators.group.has(char) ||\n (SIGNS.has(char) && (negatives || char === \"+\"));\n if (!allowed) {\n return entry(PREVENT);\n }\n }\n const text = edit.text;\n if (!isValidStart(text, options)) {\n return entry(PREVENT);\n }\n if (\n Array.from(data).some((char) => separators.group.has(char)) &&\n !groupsSoFarFit(integerText(text, separators.decimal), symbols)\n ) {\n return entry(PREVENT);\n }\n const { maximum } = numberFractionDigits(options);\n if (\n options.limitFractionDigits === true &&\n maximum !== null &&\n fractionDigitsTyped(text, symbols) > maximum\n ) {\n return entry(PREVENT);\n }\n return entry(ALLOW);\n}\n\n/**\n * A fixed-decimal text, read into its parts: an optional sign, the integer\n * digits and the fraction digits, with where each starts in the text.\n */\ninterface FixedText {\n readonly negative: boolean;\n readonly integer: string;\n readonly fraction: string;\n /** Where the integer digits start: after the sign. */\n readonly integerStart: number;\n /** Where the integer digits end: at the separator, or the end of the text. */\n readonly integerEnd: number;\n /** Where the fraction digits start: after the separator. */\n readonly fractionStart: number;\n}\n\n/** Where an edit is, in the parts of a fixed-decimal text. */\ntype FixedCaret =\n | { readonly part: \"integer\"; readonly index: number }\n | { readonly part: \"fraction\"; readonly index: number };\n\n/** A fixed-decimal number being edited: its digits as arrays, and the caret. */\ninterface FixedDraft {\n negative: boolean;\n integer: string[];\n fraction: string[];\n caret: FixedCaret;\n}\n\n/** Reads `text` as a fixed-decimal text, or `null` when it holds anything else. */\nfunction readFixed(text: string, symbols: NumberSymbols): FixedText | null {\n const decimals = decimalChars(symbols);\n const at = (offset: number) => text[offset] ?? \"\";\n let index = 0;\n let negative = false;\n if (MINUS_SIGNS.has(at(0)) || (text !== \"\" && at(0) === symbols.minus)) {\n negative = true;\n index = 1;\n }\n const integerStart = index;\n let integer = \"\";\n while (index < text.length && isDigit(at(index))) {\n integer += at(index);\n index += 1;\n }\n const integerEnd = index;\n let fraction = \"\";\n let fractionStart = index;\n if (index < text.length && decimals.has(at(index))) {\n index += 1;\n fractionStart = index;\n while (index < text.length && isDigit(at(index))) {\n fraction += at(index);\n index += 1;\n }\n }\n return index === text.length\n ? { negative, integer, fraction, integerStart, integerEnd, fractionStart }\n : null;\n}\n\n/** Where `offset` in the text falls among a fixed-decimal text's parts. */\nfunction caretAt(text: FixedText, offset: number): FixedCaret {\n if (offset <= text.integerEnd) {\n return {\n part: \"integer\",\n index: Math.max(0, offset - text.integerStart),\n };\n }\n return {\n part: \"fraction\",\n index: Math.min(\n text.fraction.length,\n Math.max(0, offset - text.fractionStart),\n ),\n };\n}\n\n/** The field's own digit for a typed one in any script. */\nfunction fieldDigit(char: string, symbols: NumberSymbols): string {\n return Array.from(symbols.digits)[digitValue(char)] ?? char;\n}\n\nfunction zeroOf(symbols: NumberSymbols): string {\n return Array.from(symbols.digits)[0] ?? \"0\";\n}\n\n/** `fraction` padded or cut to `digits`, with the field's zero. */\nfunction fitFraction(\n fraction: readonly string[],\n digits: number,\n zero: string,\n): string[] {\n const fitted = fraction.slice(0, digits);\n while (fitted.length < digits) {\n fitted.push(zero);\n }\n return fitted;\n}\n\n/**\n * Removes `start` to `end` of the text: integer digits go, fraction digits\n * turn to zero in place (so the decimals never shift), a sign inside it\n * goes, the separator stays. The caret lands at `start`.\n */\nfunction removeFixed(\n draft: FixedDraft,\n text: FixedText,\n start: number,\n end: number,\n zero: string,\n): void {\n if (start < text.integerStart && end > 0) {\n draft.negative = false;\n }\n const integerFrom = Math.max(start, text.integerStart) - text.integerStart;\n const integerTo = Math.min(end, text.integerEnd) - text.integerStart;\n if (integerTo > integerFrom) {\n draft.integer.splice(integerFrom, integerTo - integerFrom);\n }\n const fractionFrom = Math.max(start, text.fractionStart) - text.fractionStart;\n const fractionTo =\n Math.min(end, text.fractionStart + draft.fraction.length) -\n text.fractionStart;\n for (let index = fractionFrom; index < fractionTo; index += 1) {\n draft.fraction[index] = zero;\n }\n draft.caret =\n start <= text.integerEnd\n ? { part: \"integer\", index: integerFrom }\n : { part: \"fraction\", index: Math.max(0, fractionFrom) };\n}\n\n/**\n * Backspace or Delete with nothing selected, keeping the decimals' shape:\n * in the decimals one turns to zero and the caret moves past it; from the\n * first decimal Backspace deletes the last integer digit, and Delete from\n * the end of the integer part zeroes the first decimal. `beforeSign`: the\n * caret is in front of the minus. False when there is nothing to delete.\n */\nfunction deleteFixed(\n draft: FixedDraft,\n backward: boolean,\n beforeSign: boolean,\n zero: string,\n): boolean {\n const { caret } = draft;\n if (backward) {\n if (caret.part === \"fraction\" && caret.index > 0) {\n draft.fraction[caret.index - 1] = zero;\n draft.caret = { part: \"fraction\", index: caret.index - 1 };\n return true;\n }\n const index =\n caret.part === \"fraction\" ? draft.integer.length : caret.index;\n if (index > 0) {\n draft.integer.splice(index - 1, 1);\n draft.caret = { part: \"integer\", index: index - 1 };\n return true;\n }\n if (draft.negative && !beforeSign) {\n draft.negative = false;\n return true;\n }\n return false;\n }\n if (beforeSign) {\n draft.negative = false;\n return true;\n }\n if (caret.part === \"integer\" && caret.index < draft.integer.length) {\n draft.integer.splice(caret.index, 1);\n return true;\n }\n const index = caret.part === \"fraction\" ? caret.index : 0;\n if (index < draft.fraction.length) {\n draft.fraction[index] = zero;\n draft.caret = { part: \"fraction\", index: index + 1 };\n return true;\n }\n return false;\n}\n\n/**\n * Types one character into a fixed-decimal draft: a digit goes into the\n * integer part or over the next decimal, the decimal separator (or `.`\n * or `,`) moves into the decimals, a minus at the start makes it negative. False\n * when the character is refused.\n */\nfunction typeFixed(\n draft: FixedDraft,\n char: string,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): boolean {\n const { caret } = draft;\n if (isDigit(char)) {\n const digit = fieldDigit(char, symbols);\n if (caret.part === \"integer\") {\n // A lone zero holds the place of the integer part, so a digit typed\n // beside it takes its place.\n if (draft.integer.length === 1 && draft.integer[0] === zeroOf(symbols)) {\n draft.integer = [digit];\n draft.caret = { part: \"integer\", index: 1 };\n return true;\n }\n draft.integer.splice(caret.index, 0, digit);\n draft.caret = { part: \"integer\", index: caret.index + 1 };\n return true;\n }\n if (caret.index >= draft.fraction.length) {\n return false;\n }\n draft.fraction[caret.index] = digit;\n draft.caret = { part: \"fraction\", index: caret.index + 1 };\n return true;\n }\n // Both marks jump, whichever the locale groups with: a phone's decimal\n // key types the device's separator, which need not be the field's.\n if (char === \".\" || char === \",\" || decimalChars(symbols).has(char)) {\n if (caret.part === \"integer\") {\n if (draft.integer.length === 0) {\n draft.integer = [zeroOf(symbols)];\n }\n draft.caret = { part: \"fraction\", index: 0 };\n }\n return true;\n }\n if (\n (MINUS_SIGNS.has(char) || char === symbols.minus) &&\n options.negatives !== false &&\n !draft.negative &&\n caret.part === \"integer\" &&\n caret.index === 0\n ) {\n draft.negative = true;\n return true;\n }\n return false;\n}\n\n/**\n * A fixed-decimal draft as the field's edit text, and where the caret goes\n * in it. Leading zeros go; an integer part with no digits shows \"0\" while\n * a decimal is not zero; with no digit that counts left, the text is\n * empty (or the lone minus just typed).\n */\nfunction writeFixed(\n draft: FixedDraft,\n digits: number,\n symbols: NumberSymbols,\n): { readonly text: string; readonly caret: number } {\n const zero = zeroOf(symbols);\n let integer = [...draft.integer];\n let { caret } = draft;\n while (integer.length > 1 && integer[0] === zero) {\n integer = integer.slice(1);\n if (caret.part === \"integer\") {\n caret = { part: \"integer\", index: Math.max(0, caret.index - 1) };\n }\n }\n const fraction = fitFraction(draft.fraction, digits, zero);\n const typedFraction = draft.fraction.some((digit) => digit !== zero);\n if (integer.length === 0) {\n if (!typedFraction && draft.fraction.length > 0) {\n return { text: \"\", caret: 0 };\n }\n if (!typedFraction) {\n const sign = draft.negative ? symbols.minus : \"\";\n return { text: sign, caret: sign.length };\n }\n integer = [zero];\n if (caret.part === \"integer\") {\n caret = { part: \"integer\", index: 1 };\n }\n }\n const sign = draft.negative ? symbols.minus : \"\";\n const integerText = integer.join(\"\");\n const text = sign + integerText + symbols.decimal + fraction.join(\"\");\n const fractionStart =\n sign.length + integerText.length + symbols.decimal.length;\n return {\n text,\n caret:\n caret.part === \"integer\"\n ? sign.length + Math.min(caret.index, integerText.length)\n : fractionStart + Math.min(caret.index, digits),\n };\n}\n\n/** A pasted number as the field's fixed-decimal edit text, rounded, with the caret at the end of its integer part. */\nfunction pastedFixed(\n decimal: DecimalString,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): InputFilterDecision {\n const rounded = roundDecimal(\n decimal,\n digits,\n options.roundingMode ?? \"halfExpand\",\n );\n const text = formatNumber(\n rounded,\n {\n ...options,\n style: \"decimal\",\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n },\n \"edit\",\n );\n const point = text.lastIndexOf(symbols.decimal);\n return { kind: \"replace\", text, caret: point === -1 ? text.length : point };\n}\n\n/** Fixed-decimal entry for a paste or drop. */\nfunction pasteFixed<N>(\n edit: TextEdit<N>,\n before: string,\n current: FixedText,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry {\n const input = edit.input;\n const pasted = input?.data ?? insertedText(before, edit.text);\n const cleaned = cleanPastedNumber(pasted, options);\n if (cleaned === null) {\n return entry(PREVENT);\n }\n const reading = parseNumber(cleaned.text, { ...options, style: \"decimal\" });\n if (reading.kind !== \"number\") {\n return entry(PREVENT);\n }\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n const whole = start === 0 && end === before.length;\n const intoInteger =\n !whole &&\n before !== \"\" &&\n cleaned.info.decimalSeparator === null &&\n cleaned.info.negative === null &&\n end <= current.integerEnd &&\n start >= current.integerStart;\n if (!intoInteger) {\n return entry(\n pastedFixed(reading.decimal, digits, options, symbols),\n cleaned.info,\n );\n }\n const draft: FixedDraft = {\n negative: current.negative,\n integer: Array.from(current.integer),\n fraction: Array.from(current.fraction),\n caret: caretAt(current, start),\n };\n removeFixed(draft, current, start, end, zeroOf(symbols));\n for (const char of cleaned.text) {\n typeFixed(draft, char, options, symbols);\n }\n const written = writeFixed(draft, digits, symbols);\n return entry(\n { kind: \"replace\", text: written.text, caret: written.caret },\n cleaned.info,\n );\n}\n\n/**\n * Fixed-decimal entry: every edit is worked out on the text's parts and\n * the whole text replaced, so the decimals keep their count and place.\n */\nfunction filterFixed<N>(\n edit: TextEdit<N>,\n before: string,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry | null {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (input === null || inputType === null || inputType.startsWith(\"history\")) {\n return entry(ALLOW);\n }\n const current = readFixed(before, symbols);\n if (current === null) {\n return null;\n }\n if (isPaste(edit)) {\n return pasteFixed(edit, before, current, digits, options, symbols);\n }\n const zero = zeroOf(symbols);\n const start = Math.min(input.selectionStart ?? before.length, before.length);\n const end = Math.min(input.selectionEnd ?? start, before.length);\n const whole = before !== \"\" && start === 0 && end === before.length;\n const draft: FixedDraft = whole\n ? {\n negative: false,\n integer: [],\n fraction: [],\n caret: { part: \"integer\", index: 0 },\n }\n : {\n negative: current.negative,\n integer: Array.from(current.integer),\n fraction: Array.from(current.fraction),\n caret: caretAt(current, start),\n };\n const deleting = inputType.startsWith(\"delete\");\n if (whole && deleting) {\n return entry({ kind: \"replace\", text: \"\", caret: 0 });\n }\n if (!whole && start < end) {\n removeFixed(draft, current, start, end, zero);\n } else if (!whole && deleting) {\n if (\n inputType === \"deleteContentBackward\" ||\n inputType === \"deleteContentForward\"\n ) {\n if (\n !deleteFixed(\n draft,\n inputType === \"deleteContentBackward\",\n start < current.integerStart,\n zero,\n )\n ) {\n return entry(PREVENT);\n }\n } else {\n const [from, to] = removedRange(before, edit.text);\n if (from === to) {\n return entry(PREVENT);\n }\n removeFixed(draft, current, from, to, zero);\n }\n }\n if (!deleting) {\n const data = input.data ?? insertedText(before, edit.text);\n for (const char of data) {\n if (!typeFixed(draft, char, options, symbols)) {\n return entry(PREVENT);\n }\n }\n }\n const written = writeFixed(draft, digits, symbols);\n if (written.text === before && start === end && written.caret === start) {\n return entry(PREVENT);\n }\n return entry({ kind: \"replace\", text: written.text, caret: written.caret });\n}\n\n/**\n * A number field's judgement of an edit, its `filterInput`: `edit` is the\n * edit as the app's `onBeforeInput` left it, `before` the text before it.\n *\n * Free entry keeps what can still become a number: digits, the decimal\n * separator once (none in a field with no fraction digits), group\n * separators where the grouping allows, a sign (none when `negatives` is\n * false). Letters, currency signs and the rest are refused, deletions and\n * undo always stand, and a paste or drop is cleaned by `cleanPastedNumber`\n * and inserted in its place, or refused.\n *\n * A field with fixed decimals (`fixedFractionDigits`) replaces the whole\n * text on every edit instead: the decimals always show once it has a\n * value, digits go before them, the decimal separator (or `.` or `,`)\n * moves the caret into them, they are typed over and never grow, and deleting turns\n * one to zero. A paste is rounded to them. Text that is not a\n * fixed-decimal text (after an undo) is edited freely until it is again.\n */\nexport function filterNumberEdit<N>(\n edit: TextEdit<N>,\n before: string,\n options: NumberEntryOptions = {},\n): NumberEntry {\n const symbols = numberSymbols(options.locale, options);\n const digits = fixedFractionDigits(options);\n if (digits !== null) {\n const fixed = filterFixed(edit, before, digits, options, symbols);\n if (fixed !== null) {\n return fixed;\n }\n }\n return filterFree(edit, before, options, symbols);\n}\n\n/**\n * Where the caret goes when a number field's text is written again (the\n * edit form on focus, the padded text on commit): after as many digits,\n * decimal separators and signs as it had before it, so group separators\n * added or removed around it do not move it. A caret at the end stays at\n * the end.\n */\nexport function numberCaret(\n options: NumberOptions = {},\n): (previousText: string, caret: number, nextText: string) => number {\n const symbols = numberSymbols(options.locale, options);\n const decimals = decimalChars(symbols);\n const significant = (char: string) =>\n isDigit(char) ||\n decimals.has(char) ||\n SIGNS.has(char) ||\n char === symbols.minus;\n return (previousText, caret, nextText) => {\n if (caret >= previousText.length) {\n return nextText.length;\n }\n let count = 0;\n for (let index = 0; index < caret; index += 1) {\n if (significant(previousText[index] ?? \"\")) {\n count += 1;\n }\n }\n if (count === 0) {\n return 0;\n }\n for (let index = 0; index < nextText.length; index += 1) {\n if (significant(nextText[index] ?? \"\")) {\n count -= 1;\n if (count === 0) {\n return index + 1;\n }\n }\n }\n return nextText.length;\n };\n}\n","import {\n addDecimals,\n compareDecimals,\n decimalOf,\n snapDecimal,\n subtractDecimals,\n type DecimalString,\n} from \"./decimal\";\n\nexport type StepDirection = \"up\" | \"down\";\n\n/** One `step`, one `largeStep`, or all the way to the limit (`edge`). */\nexport type StepSize = \"step\" | \"large\" | \"edge\";\n\n/** A step to take, every number an exact decimal. */\nexport interface StepRequest {\n /** The value to step from; `null` for an empty field. */\n readonly value: DecimalString | null;\n readonly direction: StepDirection;\n readonly size: StepSize;\n /** Above zero. */\n readonly step: DecimalString;\n readonly largeStep: DecimalString;\n readonly min: DecimalString | null;\n readonly max: DecimalString | null;\n}\n\n/** `value` within `min` and `max`. */\nfunction clamp(\n value: DecimalString,\n min: DecimalString | null,\n max: DecimalString | null,\n): DecimalString {\n if (min !== null && compareDecimals(value, min) < 0) {\n return decimalOf(min);\n }\n if (max !== null && compareDecimals(value, max) > 0) {\n return decimalOf(max);\n }\n return value;\n}\n\n/**\n * The value one step on, in normal form:\n *\n * - From empty, the starting point: 0, or `min` when it is above 0, or\n * `max` when it is below 0.\n * - On the step grid (multiples of `step` from `min`, or from 0 without\n * one), one step or one large step; off it, to the grid value that way\n * first, as native number inputs do (1.37 with step 0.5: up to 1.5, down\n * to 1).\n * - `edge`: to `max` going up and `min` going down; the value unchanged\n * when that limit is not set.\n * - Never past `min` or `max`: a step from a limit returns that limit,\n * which `compareDecimals` tells the caller is the value it had.\n *\n * The result can have more fraction digits than the field keeps; the\n * caller rounds it. Throws a `RangeError` for a step that is not above\n * zero.\n */\nexport function stepNumber(request: StepRequest): DecimalString | null {\n const { value, direction, size, step, largeStep, min, max } = request;\n if (size === \"edge\") {\n const edge = direction === \"up\" ? max : min;\n return edge === null ? value : decimalOf(edge);\n }\n if (value === null) {\n if (min !== null && compareDecimals(min, \"0\") > 0) {\n return decimalOf(min);\n }\n return max !== null && compareDecimals(max, \"0\") < 0 ? decimalOf(max) : \"0\";\n }\n const amount = size === \"large\" ? largeStep : step;\n const base = min ?? \"0\";\n // The farthest grid value no more than one step away, so an off-grid\n // value lands on the grid and an on-grid one moves a whole step.\n const target =\n direction === \"up\"\n ? snapDecimal(addDecimals(value, amount), base, step, \"below\")\n : snapDecimal(subtractDecimals(value, amount), base, step, \"above\");\n return clamp(target, min, max);\n}\n","import type { FieldState } from \"../field/state\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n decimalOf,\n decimalToNumber,\n roundDecimal,\n shiftDecimal,\n type DecimalString,\n type NumberLike,\n} from \"./decimal\";\nimport { formatNumber } from \"./formatNumber\";\nimport {\n numberFractionDigits,\n type NumberOptions,\n type NumberValue,\n type NumberValueType,\n} from \"./options\";\nimport { parseNumber, type NumberUnreadableReason } from \"./parseNumber\";\nimport type { NumberReadingInfo } from \"./reading\";\nimport { numberSymbols } from \"./symbols\";\nimport { stepNumber, type StepDirection, type StepSize } from \"./stepNumber\";\n\n/** How a number field reads and writes, and the value type it holds. */\nexport interface NumberFieldOptions<\n T extends NumberValueType = NumberValueType,\n> extends NumberOptions {\n /** `\"number\"` (default): a JS number. `\"decimal\"`: an exact decimal string (`\"1234.50\"`). */\n readonly valueType?: T | undefined;\n}\n\n/** What a number field adds to every event it fires. */\nexport interface NumberDetails {\n /** The value as an exact decimal string, whatever the value type; `null` when empty. */\n readonly decimal: DecimalString | null;\n /** The value as display mode writes it, currency, percent sign or unit included; `\"\"` when empty. */\n readonly formatted: string;\n /** How the text on screen reads; `null` while it shows the value formatted, or cannot be read. */\n readonly reading: NumberReadingInfo | null;\n}\n\n/** Places a percent's stored value sits below the number shown: 2 for a fraction (0.125 for 12.5). */\nfunction percentShift(options: NumberOptions): number {\n return options.style === \"percent\" && options.percentScale !== \"percent\"\n ? 2\n : 0;\n}\n\n/**\n * The value a field stores for a number shown as `typed`: rounded to the\n * maximum fraction digits, scaled back for a percent, in normal form with\n * the minimum digits.\n */\nfunction storedDecimal(\n typed: DecimalString,\n options: NumberOptions,\n): DecimalString {\n const { minimum, maximum } = numberFractionDigits(options);\n const rounded =\n maximum === null\n ? typed\n : roundDecimal(typed, maximum, options.roundingMode ?? \"halfExpand\");\n const shift = percentShift(options);\n return decimalOf(shiftDecimal(rounded, -shift), minimum + shift);\n}\n\n/** The message a field shows for text it cannot read. */\nfunction unreadableMessage(\n reason: NumberUnreadableReason,\n options: NumberOptions,\n messages: FormsMessages,\n): string {\n switch (reason) {\n case \"notANumber\":\n case \"incomplete\":\n return messages.notANumber;\n case \"grouping\": {\n const { decimal, group } = numberSymbols(options.locale, options);\n return messages.numberGrouping(decimal, group);\n }\n case \"tooPrecise\":\n return messages.numberTooPrecise;\n }\n}\n\n/**\n * A number field's own reading: `parseNumber`, then the value rounded to\n * the maximum fraction digits by `roundingMode` (so `onChange` carries the\n * value that will be stored), scaled for a percent, and held as the value\n * type. As a JS number, text whose rounded digits a number cannot keep\n * exactly (\"9007199254740993\") is unreadable rather than silently changed.\n * The locale is the field's unless `options` names one.\n */\nexport function numberParser<T extends NumberValueType = \"number\">(\n options: NumberFieldOptions<T> = {},\n): (\n text: string,\n context: ParseContext<NumberValue<T>>,\n) => ParseResult<NumberValue<T>> {\n return (text, context) => {\n const field = { ...options, locale: options.locale ?? context.locale };\n const reading = parseNumber(text, field);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"unreadable\":\n return unreadable(\n unreadableMessage(reading.reason, field, context.messages),\n );\n case \"number\": {\n const decimal = storedDecimal(reading.decimal, field);\n if (options.valueType === \"decimal\") {\n return parsed(decimal as NumberValue<T>);\n }\n const { number, exact } = decimalToNumber(decimal);\n return exact\n ? parsed(number as NumberValue<T>)\n : unreadable(\n unreadableMessage(\"tooPrecise\", field, context.messages),\n );\n }\n }\n };\n}\n\n/**\n * A number field's own writing: the `edit` form while it has focus and the\n * `display` form otherwise (`FormatContext.purpose`), `\"\"` for `null`. The\n * locale is the field's unless `options` names one.\n */\nexport function numberFormatter<V extends NumberLike>(\n options: NumberOptions = {},\n): (value: V | null, context: FormatContext<V>) => string {\n return (value, { locale, purpose }) =>\n value === null\n ? \"\"\n : formatNumber(\n value,\n { ...options, locale: options.locale ?? locale },\n purpose,\n );\n}\n\n/**\n * A number field's details for `state`, what its `FieldOptions.details`\n * returns. `pasted` is how clean-up read the paste the text on screen came\n * from, which the input remembers until the next edit (`cleanPastedNumber`);\n * without it, `reading` describes the text as typed. `options` holds the\n * field's locale.\n */\nexport function numberDetails<V extends NumberLike>(\n state: FieldState<V>,\n options: NumberOptions,\n pasted: NumberReadingInfo | null = null,\n): NumberDetails {\n const { value, draft } = state;\n return {\n decimal:\n value === null\n ? null\n : decimalOf(\n value,\n numberFractionDigits(options).minimum + percentShift(options),\n ),\n formatted: value === null ? \"\" : formatNumber(value, options, \"full\"),\n reading:\n draft.kind === \"text\" ? (pasted ?? readingOf(draft.text, options)) : null,\n };\n}\n\n/** A step a number field takes, its numbers in the field's value units. */\nexport interface NumberStep {\n readonly direction: StepDirection;\n readonly size: StepSize;\n /** Above zero. */\n readonly step: NumberLike;\n readonly largeStep: NumberLike;\n readonly min: NumberLike | null;\n readonly max: NumberLike | null;\n}\n\n/**\n * The value a step takes a number field to, as `stepNumber` works it out\n * exactly, rounded to the field's maximum fraction digits (of the number\n * shown, for a percent) and held as its value type. At a limit it is the\n * value the field has; from empty, the starting point.\n */\nexport function stepNumberValue<T extends NumberValueType = \"number\">(\n value: NumberValue<T> | null,\n step: NumberStep,\n options: NumberFieldOptions<T> = {},\n): NumberValue<T> | null {\n const limit = (bound: NumberLike | null) =>\n bound === null ? null : decimalOf(bound);\n const next = stepNumber({\n value: value === null ? null : decimalOf(value),\n direction: step.direction,\n size: step.size,\n step: decimalOf(step.step),\n largeStep: decimalOf(step.largeStep),\n min: limit(step.min),\n max: limit(step.max),\n });\n if (next === null) {\n return null;\n }\n const { minimum, maximum } = numberFractionDigits(options);\n const shift = percentShift(options);\n const rounded =\n maximum === null\n ? next\n : roundDecimal(\n next,\n maximum + shift,\n options.roundingMode ?? \"halfExpand\",\n );\n if (options.valueType === \"decimal\") {\n return decimalOf(rounded, minimum + shift) as NumberValue<T>;\n }\n return decimalToNumber(rounded).number as NumberValue<T>;\n}\n\nfunction readingOf(\n text: string,\n options: NumberOptions,\n): NumberReadingInfo | null {\n const reading = parseNumber(text, options);\n return reading.kind === \"number\" ? reading.info : null;\n}\n","import type { NoFlags, RangeKind } from \"../range/range\";\nimport {\n compareDecimals,\n decimalOf,\n decimalToNumber,\n subtractDecimals,\n type DecimalString,\n} from \"./decimal\";\nimport type { NumberValue, NumberValueType } from \"./options\";\n\n/** Orders two ends: an end before its start is reversed. */\nfunction orient(order: number) {\n return order >= 0\n ? ({ kind: \"ordered\", flags: {} } as const)\n : ({ kind: \"reversed\" } as const);\n}\n\n/**\n * The range kind of JS numbers. The span is `end - start`, worked out\n * exactly (0.3 to 0.1 spans 0.2, never 0.19999999999999998), the same\n * whatever the bounds. Numbers show the end they store, so it has no\n * shown-versus-stored conversion.\n */\nexport const numberRangeKind: RangeKind<number> = {\n compare: (a, b) => compareDecimals(decimalOf(a), decimalOf(b)),\n orient: (start, end) =>\n orient(compareDecimals(decimalOf(end), decimalOf(start))),\n openFlags: {},\n span: (start, end) =>\n decimalToNumber(subtractDecimals(decimalOf(end), decimalOf(start))).number,\n compareSpans: (a, b) => compareDecimals(decimalOf(a), decimalOf(b)),\n};\n\n/** The range kind of exact decimal strings: as `numberRangeKind`, the span a decimal string too. */\nexport const decimalRangeKind: RangeKind<\n DecimalString,\n NoFlags,\n DecimalString\n> = {\n compare: compareDecimals,\n orient: (start, end) => orient(compareDecimals(end, start)),\n openFlags: {},\n span: (start, end) => subtractDecimals(end, start),\n compareSpans: compareDecimals,\n};\n\n/** The range kind of a number field's value type: `numberRangeKind`, or `decimalRangeKind` for `\"decimal\"`. */\nexport function numberRangeKindOf<T extends NumberValueType = \"number\">(\n valueType: T | undefined,\n): RangeKind<NumberValue<T>, NoFlags, NumberValue<T>> {\n // `NumberValue<T>` is a string exactly when `T` is \"decimal\".\n return (valueType === \"decimal\"\n ? decimalRangeKind\n : numberRangeKind) as unknown as RangeKind<\n NumberValue<T>,\n NoFlags,\n NumberValue<T>\n >;\n}\n","import type { Validator } from \"../validation/validators\";\nimport {\n compareDecimals,\n decimalOf,\n snapDecimal,\n type NumberLike,\n} from \"./decimal\";\nimport { formatNumber } from \"./formatNumber\";\nimport type { NumberOptions } from \"./options\";\n\n/** `limit` as the field writes numbers in its messages: the `full` form, in its locale unless `options` names one. */\nfunction written(\n limit: NumberLike,\n options: NumberOptions,\n locale: Intl.LocalesArgument,\n): string {\n return formatNumber(\n limit,\n { ...options, locale: options.locale ?? locale },\n \"full\",\n );\n}\n\n/**\n * A number below `min` is `messages.rangeUnderflow`, \"Enter 10 or more\".\n * Compared as exact decimals, so either value type works and a decimal\n * limit keeps every digit. `options` are the field's, to write `min` the\n * way it writes numbers. `null` passes.\n */\nexport function minRule<V extends NumberLike>(\n min: NumberLike,\n options: NumberOptions = {},\n): Validator<V> {\n const limit = decimalOf(min);\n return (value, { locale, messages }) =>\n value !== null && compareDecimals(decimalOf(value), limit) < 0\n ? {\n text: messages.rangeUnderflow(written(min, options, locale)),\n code: \"rangeUnderflow\",\n }\n : null;\n}\n\n/** A number above `max` is `messages.rangeOverflow`, \"Enter 100 or less\"; otherwise as `minRule`. */\nexport function maxRule<V extends NumberLike>(\n max: NumberLike,\n options: NumberOptions = {},\n): Validator<V> {\n const limit = decimalOf(max);\n return (value, { locale, messages }) =>\n value !== null && compareDecimals(decimalOf(value), limit) > 0\n ? {\n text: messages.rangeOverflow(written(max, options, locale)),\n code: \"rangeOverflow\",\n }\n : null;\n}\n\n/**\n * A number that is not a whole number of `step`s from `base` is\n * `messages.stepMismatch`, \"Enter a multiple of 0.05\". Exact, so 0.15 is\n * three steps of 0.05. A number input's `step` only drives stepping; this\n * rule is for a field whose values must sit on it. Throws a `RangeError`\n * for a step that is not above zero. `null` passes.\n */\nexport function stepRule<V extends NumberLike>(\n step: NumberLike,\n base: NumberLike = 0,\n options: NumberOptions = {},\n): Validator<V> {\n const size = decimalOf(step);\n const origin = decimalOf(base);\n if (compareDecimals(size, \"0\") <= 0) {\n throw new RangeError(`The step ${size} is not above zero`);\n }\n return (value, { locale, messages }) => {\n if (value === null) {\n return null;\n }\n const decimal = decimalOf(value);\n return compareDecimals(\n snapDecimal(decimal, origin, size, \"below\"),\n decimal,\n ) === 0\n ? null\n : {\n text: messages.stepMismatch(written(step, options, locale)),\n code: \"stepMismatch\",\n };\n };\n}\n","/** What opened a popup: its button, or a key in the field (F4, Alt+ArrowDown). */\nexport type PopupOpenReason = \"button\" | \"keyboard\";\n\n/**\n * What closed a popup: Escape; a press outside it; a scroll outside it or\n * the window resizing, which would leave it behind its field; focus or\n * the window leaving it; the overlay it was opened above closing\n * (`\"parent\"`); its button pressed again; a value chosen in it\n * (`\"picker\"`); or the field turning disabled, read-only or display-only.\n */\nexport type PopupCloseReason =\n | \"escape\"\n | \"outside\"\n | \"scroll\"\n | \"resize\"\n | \"blur\"\n | \"parent\"\n | \"button\"\n | \"picker\"\n | \"disabled\";\n\n/** What `onOpenChange` is told as a popup opens or closes. */\nexport type PopupOpenChange =\n | { readonly open: true; readonly reason: PopupOpenReason }\n | { readonly open: false; readonly reason: PopupCloseReason };\n\n/** Whether a popup is open, and what opened it. */\nexport type PopupState =\n | { readonly kind: \"closed\" }\n | { readonly kind: \"open\"; readonly openedBy: PopupOpenReason };\n\n/** What can happen to a popup. */\nexport type PopupAction =\n | { readonly type: \"open\"; readonly reason: PopupOpenReason }\n | { readonly type: \"close\"; readonly reason: PopupCloseReason }\n /** Its button: opens a closed popup, closes an open one. */\n | { readonly type: \"toggle\" };\n\n/** The popup after an action, and what `onOpenChange` is told: `null` when nothing changed. */\nexport interface PopupStep {\n readonly state: PopupState;\n readonly change: PopupOpenChange | null;\n}\n\nexport const POPUP_CLOSED: PopupState = { kind: \"closed\" };\n\n/**\n * A popup's open state after `action`. Opening an open popup and closing\n * a closed one change nothing, so `onOpenChange` hears each change once.\n */\nexport function popupReducer(\n state: PopupState,\n action: PopupAction,\n): PopupStep {\n switch (action.type) {\n case \"open\":\n return state.kind === \"open\"\n ? { state, change: null }\n : {\n state: { kind: \"open\", openedBy: action.reason },\n change: { open: true, reason: action.reason },\n };\n case \"close\":\n return state.kind === \"closed\"\n ? { state, change: null }\n : {\n state: POPUP_CLOSED,\n change: { open: false, reason: action.reason },\n };\n case \"toggle\":\n return popupReducer(\n state,\n state.kind === \"open\"\n ? { type: \"close\", reason: \"button\" }\n : { type: \"open\", reason: \"button\" },\n );\n }\n}\n","import type {\n AssembleContext,\n PartChange,\n PartTexts,\n PartValues,\n} from \"../field/createCompositeController\";\nimport { parsed, unreadable, type ParseResult } from \"../parse\";\nimport {\n orderRange,\n rangeSpan,\n shownEnd,\n type NoFlags,\n type Range,\n type RangeBounds,\n type RangeEnd,\n type RangeKind,\n type RangeOptions,\n} from \"./range\";\n\n/** The parts of a range input: its two ends, each a value of `T`. */\nexport type RangeEnds<T> = { start: T; end: T };\n\n/** What every range input adds to its events. */\nexport interface RangeDetails<\n T,\n F extends object = NoFlags,\n S = number,\n R = never,\n> {\n /**\n * The end this event is about: the end typed in; `\"both\"` for a value\n * set whole (`setValue`, a controlled value, a revert or clear); on a\n * commit, the end that differs from the last commit (`\"both\"` when both\n * do, `null` when neither does).\n */\n readonly changedEnd: RangeEnd | \"both\" | null;\n /** The ends the value stands for now: the value itself, or its rule resolved. `null` when empty. */\n readonly resolved: Range<T, F> | null;\n /** From start to end; `null` while an end is open or the field is empty. */\n readonly span: S | null;\n readonly bounds: RangeBounds;\n /** Each end's text as shown. */\n readonly startText: string;\n readonly endText: string;\n /** The rule, when the value is one. */\n readonly rule: R | null;\n}\n\n/**\n * The range two ends as shown make, for a range input's `assemble`:\n * `orderRange` with its refusals as `messages.rangeReversed` and\n * `messages.rangeEmpty`, and both ends empty as `null`.\n */\nexport function readRangeEnds<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n ends: PartValues<RangeEnds<T>>,\n options: RangeOptions<S>,\n context: C,\n { messages }: AssembleContext,\n): ParseResult<Range<T, F>> {\n const reading = orderRange(kind, ends.start, ends.end, options, context);\n switch (reading.kind) {\n case \"none\":\n return parsed(null);\n case \"range\":\n return parsed(reading.range);\n case \"unreadable\":\n return unreadable(\n reading.reason === \"reversed\"\n ? messages.rangeReversed\n : messages.rangeEmpty,\n );\n }\n}\n\n/** The ends a range input shows for `range`, for its `split`: the end through `toShownEnd` when half-open. */\nexport function rangeEnds<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F> | null,\n bounds: RangeBounds,\n context: C,\n): PartValues<RangeEnds<T>> {\n return range === null\n ? { start: null, end: null }\n : { start: range.start, end: shownEnd(kind, range, bounds, context) };\n}\n\n/** What a range input's events carry, from its value and its ends' texts. */\nexport function rangeDetails<T, F extends object, S, C, R = never>(\n kind: RangeKind<T, F, S, C, R>,\n resolved: Range<T, F> | null,\n changed: PartChange<RangeEnds<T>>,\n texts: PartTexts<RangeEnds<T>>,\n bounds: RangeBounds,\n context: C,\n rule: R | null = null,\n): RangeDetails<T, F, S, R> {\n return {\n changedEnd: changed === \"all\" ? \"both\" : changed,\n resolved,\n span: resolved === null ? null : rangeSpan(kind, resolved, context),\n bounds,\n startText: texts.start,\n endText: texts.end,\n rule,\n };\n}\n","import type { FieldMessageInput } from \"../messages/fieldMessage\";\nimport type {\n ValidationResult,\n Validator,\n ValidatorContext,\n} from \"../validation/validators\";\nimport { rangeSpan, type Range, type RangeKind } from \"./range\";\n\n/** Writes a span for a message: \"10\", \"14 days\". */\nexport type SpanFormatter<S> = (span: S, context: ValidatorContext) => string;\n\n/**\n * A range shorter than `minSpan`, measured by the kind, is\n * `messages.rangeTooShort`, with `minSpan` written by `formatSpan`.\n * `context` gives the kind's context when the rule runs. A range with an\n * open end, and `null`, pass.\n */\nexport function minSpanRule<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n minSpan: S,\n context: () => C,\n formatSpan: SpanFormatter<S>,\n): Validator<Range<T, F>> {\n return (range, validator) => {\n const span = range === null ? null : rangeSpan(kind, range, context());\n return span !== null && kind.compareSpans(span, minSpan) < 0\n ? {\n text: validator.messages.rangeTooShort(\n formatSpan(minSpan, validator),\n ),\n code: \"rangeTooShort\",\n }\n : null;\n };\n}\n\n/** A range longer than `maxSpan` is `messages.rangeTooLong`; otherwise as `minSpanRule`. */\nexport function maxSpanRule<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n maxSpan: S,\n context: () => C,\n formatSpan: SpanFormatter<S>,\n): Validator<Range<T, F>> {\n return (range, validator) => {\n const span = range === null ? null : rangeSpan(kind, range, context());\n return span !== null && kind.compareSpans(span, maxSpan) > 0\n ? {\n text: validator.messages.rangeTooLong(formatSpan(maxSpan, validator)),\n code: \"rangeTooLong\",\n }\n : null;\n };\n}\n\n// `Array.isArray` does not narrow a readonly array, hence the guard.\nfunction isList(\n result: FieldMessageInput | readonly FieldMessageInput[],\n): result is readonly FieldMessageInput[] {\n return Array.isArray(result);\n}\n\nfunction asList(result: ValidationResult): readonly FieldMessageInput[] {\n if (result === null || result === undefined) {\n return [];\n }\n return isList(result) ? result : [result];\n}\n\nfunction textOf(message: FieldMessageInput): string {\n return typeof message === \"string\" ? message : message.text;\n}\n\n/**\n * Runs `rule`, a check of one value, on each present end of a range: a\n * number range's `min` and `max` bound both ends. A message both ends\n * earn is given once. Open ends and `null` pass.\n */\nexport function endsRule<T, F extends object>(\n rule: Validator<T>,\n): Validator<Range<T, F>> {\n return (range, context) => {\n if (range === null) {\n return null;\n }\n const messages: FieldMessageInput[] = [];\n for (const end of [range.start, range.end]) {\n if (end === null) {\n continue;\n }\n for (const message of asList(rule(end, context))) {\n if (!messages.some((held) => textOf(held) === textOf(message))) {\n messages.push(message);\n }\n }\n }\n return messages;\n };\n}\n","import { sortFieldMessages, type FieldMessage } from \"./messages/fieldMessage\";\nimport { severityRank, type Severity } from \"./messages/severity\";\n\n/** What a form knows of one of its fields: enough to list its messages. */\nexport interface RegisteredField {\n /** Unique in the form: the id of the element a message links to. */\n readonly id: string;\n /** The messages the field shows, in its own order. */\n readonly messages: readonly FieldMessage[];\n}\n\n/**\n * The fields of one form, for a summary of their messages, and the fields'\n * ways to reveal their messages, for a submit attempt. A renderer creates\n * one per form; fields register and unregister themselves.\n */\nexport interface FieldRegistry<F extends RegisteredField> {\n /**\n * Adds `field`, in place of a field registered under the same id, and\n * returns what removes it again.\n */\n readonly register: (field: F) => () => void;\n /**\n * Adds what shows one field's messages, as a commit attempt would, and\n * returns what removes it again.\n */\n readonly addRevealer: (reveal: () => void) => () => void;\n /** Shows every field's messages, as a submit attempt does. */\n readonly revealAll: () => void;\n /**\n * Every registered field, in the order the registry was created with.\n * The same array until a field registers or unregisters.\n */\n readonly getFields: () => readonly F[];\n /** Calls `listener` whenever the fields change, and returns what stops it. */\n readonly subscribe: (listener: () => void) => () => void;\n}\n\n/**\n * A registry of a form's fields, listed in `order`, or in the order they\n * registered without one. A renderer passes its fields' place in the page,\n * which forms-core cannot see.\n */\nexport function createFieldRegistry<F extends RegisteredField>(\n order?: (a: F, b: F) => number,\n): FieldRegistry<F> {\n const fields = new Map<string, F>();\n const revealers = new Set<() => void>();\n const listeners = new Set<() => void>();\n let listed: readonly F[] | null = null;\n\n function changed(): void {\n listed = null;\n for (const listener of [...listeners]) {\n listener();\n }\n }\n\n return {\n register(field) {\n fields.set(field.id, field);\n changed();\n return () => {\n if (fields.get(field.id) === field) {\n fields.delete(field.id);\n changed();\n }\n };\n },\n addRevealer(reveal) {\n revealers.add(reveal);\n return () => {\n revealers.delete(reveal);\n };\n },\n revealAll() {\n for (const reveal of [...revealers]) {\n reveal();\n }\n },\n getFields() {\n if (listed === null) {\n const all = [...fields.values()];\n listed = order === undefined ? all : all.sort(order);\n }\n return listed;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/** One line of a message summary: a message and the field showing it. */\nexport interface SummaryItem<F extends RegisteredField> {\n readonly field: F;\n readonly message: FieldMessage;\n}\n\n/** How many messages of one severity a summary lists. */\nexport interface SeverityCount {\n readonly severity: Severity;\n readonly count: number;\n}\n\n/** What a message summary lists. */\nexport interface MessageSummary<F extends RegisteredField> {\n /** Field by field in their order, each field's most serious first. */\n readonly items: readonly SummaryItem<F>[];\n /** Most serious first, leaving out a severity with none. */\n readonly counts: readonly SeverityCount[];\n}\n\n/** The messages of `fields` whose severity is one of `severities`, with their counts. */\nexport function summarizeMessages<F extends RegisteredField>(\n fields: readonly F[],\n severities: readonly Severity[],\n): MessageSummary<F> {\n const wanted = new Set(severities);\n const items = fields.flatMap((field) =>\n sortFieldMessages(field.messages)\n .filter((message) => wanted.has(message.severity))\n .map((message) => ({ field, message })),\n );\n const counts = new Map<Severity, number>();\n for (const { message } of items) {\n counts.set(message.severity, (counts.get(message.severity) ?? 0) + 1);\n }\n return {\n items,\n counts: [...counts]\n .map(([severity, count]) => ({ severity, count }))\n .sort((a, b) => severityRank(a.severity) - severityRank(b.severity)),\n };\n}\n","/**\n * The index of the item `query` — what was typed, buffered for a moment —\n * picks, matched case-insensitively against the start of each label and\n * wrapping round the end; `-1` when none matches.\n *\n * `from` is the item focused now. A single letter, or the same letter\n * typed again and again, searches from the item after it, so repeating a\n * letter steps through every item it starts. A longer query searches from\n * `from` itself, so the item already found stays put while what is typed\n * still matches it.\n */\nexport function typeaheadIndex(\n labels: readonly string[],\n from: number,\n query: string,\n): number {\n const typed = query.toLowerCase();\n const firstCodePoint = typed.codePointAt(0);\n if (firstCodePoint === undefined) {\n return -1;\n }\n const first = String.fromCodePoint(firstCodePoint);\n const repeated = typed.replaceAll(first, \"\") === \"\";\n const prefix = repeated ? first : typed;\n const start = repeated ? from + 1 : Math.max(from, 0);\n for (let offset = 0; offset < labels.length; offset++) {\n const index = (start + offset) % labels.length;\n if (labels[index]?.toLowerCase().startsWith(prefix) === true) {\n return index;\n }\n }\n return -1;\n}\n","/**\n * One entry per row: its measured height once known, `undefined` until then.\n * A row never yet rendered (or rendered but not yet observed) falls back to\n * `visibleRange`'s own `estimatedHeight` argument.\n */\nexport type RowHeights = readonly (number | undefined)[];\n\nexport interface VisibleRange {\n readonly startIndex: number;\n readonly endIndex: number; // inclusive\n /** Total height of every row before `startIndex` — the leading spacer's height. */\n readonly offsetBefore: number;\n /** Total height of every row after `endIndex` — the trailing spacer's height. */\n readonly offsetAfter: number;\n}\n\n/**\n * Which rows of a dynamic-height, virtualized list fall within\n * `[scrollTop, scrollTop + viewportHeight)`, padded by `overscan` rows on\n * each side and clamped to the array's own bounds.\n *\n * Walks a cumulative-offset prefix sum built from `heights` (measured height\n * where known, `estimatedHeight` otherwise) rather than assuming a uniform\n * row height — a grid's rows are not uniform (`.is-wrapped` cells, group\n * header/summary rows), so a fixed-height virtualizer would either break\n * wrapping or force it out of scope.\n *\n * `O(n)` in `heights.length`. Deliberately not a Fenwick tree or a\n * binary-searchable prefix-sum structure — that optimization belongs in the\n * mutable height cache that already owns mutability (`createRowVirtualizer`\n * in `@gridkitjs/forms-dom`), not in this pure function's contract, and is not\n * worth taking on until a profiled scenario actually shows it matters at\n * realistic row counts.\n */\nexport function visibleRange(\n heights: RowHeights,\n estimatedHeight: number,\n scrollTop: number,\n viewportHeight: number,\n overscan: number,\n): VisibleRange {\n const rowCount = heights.length;\n if (rowCount === 0) {\n return { startIndex: 0, endIndex: -1, offsetBefore: 0, offsetAfter: 0 };\n }\n\n function heightAt(index: number): number {\n return heights[index] ?? estimatedHeight;\n }\n\n const viewportBottom = scrollTop + viewportHeight;\n\n // The first row whose bottom edge crosses `scrollTop` — everything before\n // it is fully scrolled past. `top` tracks that row's own top edge (the\n // cumulative height of every row before it) as the walk advances. Stops at\n // the last row rather than walking off the end when `scrollTop` reaches or\n // exceeds the total height.\n let start = 0;\n let top = 0;\n while (start < rowCount - 1 && top + heightAt(start) <= scrollTop) {\n top += heightAt(start);\n start += 1;\n }\n const startTop = top;\n\n // From `start`, the last row whose top edge is still above `viewportBottom`\n // — the first row no longer even partially visible ends the walk one row\n // earlier than it, or the array itself runs out first. `bottom` tracks the\n // current row's own bottom edge.\n let end = start;\n let bottom = startTop + heightAt(start);\n while (end < rowCount - 1 && bottom < viewportBottom) {\n end += 1;\n bottom += heightAt(end);\n }\n\n const overscanStart = Math.max(0, start - overscan);\n const overscanEnd = Math.min(rowCount - 1, end + overscan);\n\n let offsetBefore = 0;\n for (let index = 0; index < overscanStart; index++) {\n offsetBefore += heightAt(index);\n }\n let offsetAfter = 0;\n for (let index = overscanEnd + 1; index < rowCount; index++) {\n offsetAfter += heightAt(index);\n }\n\n return {\n startIndex: overscanStart,\n endIndex: overscanEnd,\n offsetBefore,\n offsetAfter,\n };\n}\n"],"mappings":";AAoDO,SAAS,OAAU,OAAiC;AACzD,SAAO,EAAE,MAAM,SAAS,MAAM;AAChC;AAGO,SAAS,WAAc,SAAiC;AAC7D,SAAO,EAAE,MAAM,cAAc,QAAQ;AACvC;;;AC7CO,SAAS,iBACd,OACA,YACgB;AAChB,MAAI,UAAU,MAAM;AAClB,WAAO,aAAa,OAAO;AAAA,EAC7B;AACA,SAAO,UAAU,QAAQ,aAAa,QAAQ;AAChD;AASO,IAAM,iBAA+B;AAAA,EAC1C,IAAI,CAAC,aAAa,SAAS;AAAA,EAC3B,KAAK,CAAC,aAAa,SAAS;AAC9B;AAGO,IAAM,eAA6B;AAAA,EACxC,IAAI,CAAC,aAAa,SAAS;AAAA,EAC3B,KAAK,CAAC,aAAa,SAAS;AAC9B;AAMO,SAAS,iBACd,OACoE;AACpE,SAAO,CAAC,OAAO,EAAE,SAAS,MAAM;AAC9B,QAAI,UAAU,MAAM;AAClB,aAAO;AAAA,IACT;AACA,WAAO,QAAQ,MAAM,GAAG,QAAQ,IAAI,MAAM,IAAI,QAAQ;AAAA,EACxD;AACF;AAGO,SAAS,cACd,OACwE;AACxE,SAAO,CAAC,MAAM,EAAE,SAAS,MAAM;AAC7B,QAAI,SAAS,MAAM,GAAG,QAAQ,GAAG;AAC/B,aAAO,OAAO,IAAI;AAAA,IACpB;AACA,WAAO,OAAO,SAAS,MAAM,IAAI,QAAQ,IAAI,QAAQ,IAAI;AAAA,EAC3D;AACF;;;AClEO,SAAS,UAAU,QAAsC;AAC9D,MAAI,WAAW,QAAW;AACxB,WAAO;AAAA,EACT;AACA,SAAO,OAAO,WAAW,YAAY,kBAAkB,KAAK,S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cAAc,GAAG,aAAa,EAAE;AAAA,EACxE;AAEA,WAAS,SAAS,OAAuB;AACvC,WAAO,QAAQ,KAAK,KAAK;AAAA,EAC3B;AAEA,QAAM,iBAAiB,YAAY;AAOnC,MAAI,QAAQ;AACZ,MAAI,MAAM;AACV,SAAO,QAAQ,WAAW,KAAK,MAAM,SAAS,KAAK,KAAK,WAAW;AACjE,WAAO,SAAS,KAAK;AACrB,aAAS;AAAA,EACX;AACA,QAAM,WAAW;AAMjB,MAAI,MAAM;AACV,MAAI,SAAS,WAAW,SAAS,KAAK;AACtC,SAAO,MAAM,WAAW,KAAK,SAAS,gBAAgB;AACpD,WAAO;AACP,cAAU,SAAS,GAAG;AAAA,EACxB;AAEA,QAAM,gBAAgB,KAAK,IAAI,GAAG,QAAQ,QAAQ;AAClD,QAAM,cAAc,KAAK,IAAI,WAAW,GAAG,MAAM,QAAQ;AAEzD,MAAI,eAAe;AACnB,WAAS,QAAQ,GAAG,QAAQ,eAAe,SAAS;AAClD,oBAAgB,SAAS,KAAK;AAAA,EAChC;AACA,MAAI,cAAc;AAClB,WAAS,QAAQ,cAAc,GAAG,QAAQ,UAAU,SAAS;AAC3D,mBAAe,SAAS,KAAK;AAAA,EAC/B;AAEA,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["monthIndex","offset","dayNumber","year","_","dayNumber","offset","chosen","digit","values","index","next","offset","groups","word","DAY_MS","offset","pad","candidates","example","offset","rangeOf","times","next","step","written","place","offset","yearOf","layoutFor","example","anchored","IDLE","entry","segmentOf","digit","fits","digits","letter","candidates","offset","isPeriod","DAY_MS","stepOf","step","entry","unreadable","UNREADABLE","values","value","next","read","next","step","API","next","values","DIGIT","cache","EMPTY","next","accepted","next","read","digit","groups","offset","step","example","read","step","offset","groups","digit","formats","intlOptions","written","FULL_WIDTH","SPACES","groups","escapeRegExp","ARABIC_DECIMAL","groups","digit","EMPTY","unreadableBecause","groups","digit","ALLOW","PREVENT","SIGNS","MINUS_SIGNS","groups","group","text","offset","index","digit","sign","integerText","written","clamp","step","unreadableMessage","readingOf","step","next","step","isList","textOf","reveal","offset"]}
|
|
1
|
+
{"version":3,"sources":["../src/parse.ts","../src/boolean.ts","../src/choice/multi.ts","../src/choice/options.ts","../src/choice/details.ts","../src/localeKey.ts","../src/choice/match.ts","../src/typeahead.ts","../src/choice/moveActive.ts","../src/choice/source.ts","../src/choice/optionCache.ts","../src/choice/sourceController.ts","../src/choice/tree.ts","../src/date/values.ts","../src/date/format.ts","../src/date/week.ts","../src/date/calendar.ts","../src/number/digits.ts","../src/date/text.ts","../src/date/layout.ts","../src/date/shortcuts.ts","../src/date/reading.ts","../src/date/zone.ts","../src/date/dateField.ts","../src/range/range.ts","../src/date/relative.ts","../src/date/dateRange.ts","../src/date/duration.ts","../src/date/period.ts","../src/date/limits.ts","../src/date/rangePick.ts","../src/date/segments.ts","../src/date/timeColumns.ts","../src/direction.ts","../src/messages/severity.ts","../src/messages/fieldMessage.ts","../src/text.ts","../src/validation/validators.ts","../src/field/state.ts","../src/field/fieldReducer.ts","../src/field/plan.ts","../src/field/createFieldController.ts","../src/field/createCompositeController.ts","../src/mask/grammar.ts","../src/mask/layout.ts","../src/mask/applyMask.ts","../src/mask/maskField.ts","../src/mask/rules.ts","../src/mask/presets.ts","../src/messages/formsMessages.ts","../src/number/decimal.ts","../src/number/options.ts","../src/number/symbols.ts","../src/number/formatNumber.ts","../src/number/reading.ts","../src/number/cleanPastedNumber.ts","../src/number/parseNumber.ts","../src/number/numberEntry.ts","../src/number/stepNumber.ts","../src/number/numberField.ts","../src/number/numberRange.ts","../src/number/rules.ts","../src/popup.ts","../src/range/rangeField.ts","../src/range/rules.ts","../src/registry.ts","../src/virtualization.ts"],"sourcesContent":["import type { FormsMessages } from \"./messages/formsMessages\";\n\n/** How text reads: a value (`null` for empty), or why it cannot be read. */\nexport type ParseResult<V> =\n | { readonly kind: \"value\"; readonly value: V | null }\n | { readonly kind: \"unreadable\"; readonly message: string };\n\n/** What a parser knows beside the text. */\nexport interface ParseContext<V> {\n /** The input's own reading, to fall back on. */\n readonly defaultParse: (text: string) => ParseResult<V>;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/**\n * Reads typed text as a value. An app's parser receives the input's own in\n * its context, so it can change one case and leave the rest to it:\n *\n * ```ts\n * const parse: Parser<string> = (text, { defaultParse }) =>\n * text === \"n/a\" ? parsed(null) : defaultParse(text);\n * ```\n */\nexport type Parser<V> = (\n text: string,\n context: ParseContext<V>,\n) => ParseResult<V>;\n\n/**\n * What a value is written for: `edit` while the field has focus, `display`\n * otherwise and in display mode. A number input writes plain digits to\n * edit and grouped digits to display; a text input writes the same for both.\n */\nexport type FormatPurpose = \"display\" | \"edit\";\n\n/** What a formatter knows beside the value. */\nexport interface FormatContext<V> {\n /** The input's own formatting, to fall back on. */\n readonly defaultFormat: (value: V | null) => string;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n readonly purpose: FormatPurpose;\n}\n\n/** Writes a value as the text a field shows, `null` included. */\nexport type Formatter<V> = (\n value: V | null,\n context: FormatContext<V>,\n) => string;\n\n/** Text that reads as `value`; `null` for empty. */\nexport function parsed<V>(value: V | null): ParseResult<V> {\n return { kind: \"value\", value };\n}\n\n/** Text that cannot be read, and why, in words the user sees. */\nexport function unreadable<V>(message: string): ParseResult<V> {\n return { kind: \"unreadable\", message };\n}\n","import type { FormsMessages } from \"./messages/formsMessages\";\nimport {\n parsed,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"./parse\";\n\n/**\n * The value a checkbox takes when it is flipped. Without `threeState`,\n * `false` and `null` go to `true` and `true` to `false`, so an app's\n * `null` (a \"select all\" over a partial selection) checks on the first\n * flip. With it, `false` → `true` → `null` → `false`.\n */\nexport function nextCheckedValue(\n value: boolean | null,\n threeState: boolean,\n): boolean | null {\n if (value === true) {\n return threeState ? null : false;\n }\n return value === null && threeState ? false : true;\n}\n\n/** The words a toggle reads as: one for `true`, one for `false`. */\nexport interface BooleanWords {\n readonly on: (messages: FormsMessages) => string;\n readonly off: (messages: FormsMessages) => string;\n}\n\n/** A checkbox reads \"Yes\" or \"No\" (`displayChecked`, `displayUnchecked`). */\nexport const CHECKBOX_WORDS: BooleanWords = {\n on: (messages) => messages.displayChecked,\n off: (messages) => messages.displayUnchecked,\n};\n\n/** A switch reads \"On\" or \"Off\" (`displayOn`, `displayOff`). */\nexport const SWITCH_WORDS: BooleanWords = {\n on: (messages) => messages.displayOn,\n off: (messages) => messages.displayOff,\n};\n\n/**\n * A toggle's value as text: its words for `true` and `false`, `\"\"` for\n * `null`. The text a toggle's events carry and display mode shows.\n */\nexport function booleanFormatter(\n words: BooleanWords,\n): (value: boolean | null, context: FormatContext<boolean>) => string {\n return (value, { messages }) => {\n if (value === null) {\n return \"\";\n }\n return value ? words.on(messages) : words.off(messages);\n };\n}\n\n/** Reads a toggle's words back as its value; anything else is `null`. */\nexport function booleanParser(\n words: BooleanWords,\n): (text: string, context: ParseContext<boolean>) => ParseResult<boolean> {\n return (text, { messages }) => {\n if (text === words.on(messages)) {\n return parsed(true);\n }\n return parsed(text === words.off(messages) ? false : null);\n };\n}\n","import type { ChoiceOption, OptionKey, OptionRow } from \"./options\";\n\n/**\n * Several chosen keys in the order they were chosen; `null` when none is,\n * never `[]`.\n */\nexport type KeyList<K extends OptionKey> = readonly K[] | null;\n\n/** The keys of a value, `[]` for `null`. */\nexport function valueKeys<K extends OptionKey>(\n value: KeyList<K>,\n): readonly K[] {\n return value ?? [];\n}\n\n/** Keys as a value: `null` for none. */\nexport function toKeyList<K extends OptionKey>(keys: readonly K[]): KeyList<K> {\n return keys.length === 0 ? null : keys;\n}\n\n/** Whether `value` holds `key`. */\nexport function hasKey<K extends OptionKey>(\n value: KeyList<K>,\n key: K,\n): boolean {\n return valueKeys(value).some((held) => Object.is(held, key));\n}\n\n/** Whether two values hold the same keys in the same order: a reorder is a change. */\nexport function sameKeys<K extends OptionKey>(\n a: KeyList<K>,\n b: KeyList<K>,\n): boolean {\n const left = valueKeys(a);\n const right = valueKeys(b);\n return (\n left.length === right.length &&\n left.every((key, index) => Object.is(key, right[index]))\n );\n}\n\n/** Whether another key may join `value` under `maxCount` (`null`: no limit). */\nexport function canAddKey<K extends OptionKey>(\n value: KeyList<K>,\n maxCount: number | null,\n): boolean {\n return maxCount === null || valueKeys(value).length < maxCount;\n}\n\n/**\n * `value` with `keys` appended in their order, skipping keys it holds, and\n * stopping once it holds `maxCount`. A value already at or over the limit\n * gains nothing. Returns `value` itself when nothing was added.\n */\nexport function addKeys<K extends OptionKey>(\n value: KeyList<K>,\n keys: readonly K[],\n maxCount: number | null = null,\n): KeyList<K> {\n const next = [...valueKeys(value)];\n for (const key of keys) {\n if (!canAddKey(next, maxCount)) {\n break;\n }\n if (!next.some((held) => Object.is(held, key))) {\n next.push(key);\n }\n }\n return next.length === valueKeys(value).length ? value : next;\n}\n\n/** `value` without `keys`, the rest in order. Returns `value` itself when it held none of them. */\nexport function removeKeys<K extends OptionKey>(\n value: KeyList<K>,\n keys: readonly K[],\n): KeyList<K> {\n const held = valueKeys(value);\n const next = held.filter((key) => !keys.some((gone) => Object.is(gone, key)));\n return next.length === held.length ? value : toKeyList(next);\n}\n\n/**\n * `key` removed when `value` holds it, else appended unless `value` holds\n * `maxCount` keys already, when `value` itself is returned.\n */\nexport function toggleKey<K extends OptionKey>(\n value: KeyList<K>,\n key: K,\n maxCount: number | null = null,\n): KeyList<K> {\n return hasKey(value, key)\n ? removeKeys(value, [key])\n : addKeys(value, [key], maxCount);\n}\n\n/**\n * The keys of the options from row `from` to row `to`, both included, in\n * list order whichever way the range runs: what Shift with a click or an\n * arrow chooses. Headers, actions and disabled options are skipped.\n */\nexport function rangeKeys<O extends ChoiceOption>(\n rows: readonly OptionRow<O>[],\n from: number,\n to: number,\n): readonly O[\"value\"][] {\n const keys: O[\"value\"][] = [];\n for (let index = Math.min(from, to); index <= Math.max(from, to); index++) {\n const row = rows[index];\n if (row?.kind === \"option\" && row.option.disabled !== true) {\n keys.push(row.option.value);\n }\n }\n return keys;\n}\n\n/** How much of a scope is chosen: every enabled option, none, or some. */\nexport type ScopeState = \"all\" | \"none\" | \"some\";\n\nfunction enabledKeys<O extends ChoiceOption>(\n scope: readonly O[],\n): readonly O[\"value\"][] {\n return scope\n .filter((option) => option.disabled !== true)\n .map((option) => option.value);\n}\n\n/**\n * How much of `scope` (the options matching the query, the loaded ones, or\n * stand-ins for every key a source has) `value` holds, counting enabled\n * options only: the tri-state of a \"Select all\" row.\n */\nexport function scopeState<O extends ChoiceOption>(\n value: KeyList<O[\"value\"]>,\n scope: readonly O[],\n): ScopeState {\n const keys = enabledKeys(scope);\n const chosen = keys.filter((key) => hasKey(value, key)).length;\n if (chosen === 0) {\n return \"none\";\n }\n return chosen === keys.length ? \"all\" : \"some\";\n}\n\n/**\n * Whether \"Select all\" over `scope` stays within `maxCount`: false when\n * adding its unchosen enabled options would go past the limit.\n */\nexport function canSelectAll<O extends ChoiceOption>(\n value: KeyList<O[\"value\"]>,\n scope: readonly O[],\n maxCount: number | null,\n): boolean {\n if (maxCount === null) {\n return true;\n }\n const missing = enabledKeys(scope).filter((key) => !hasKey(value, key));\n return valueKeys(value).length + missing.length <= maxCount;\n}\n\n/**\n * A \"Select all\" row chosen over `scope`. With every enabled option of the\n * scope chosen, it removes them (the scope's only); otherwise it appends\n * the unchosen enabled ones in scope order, the chosen keeping their\n * place. Disabled options are never added or removed. Past `maxCount` it\n * changes nothing and returns `value`.\n */\nexport function selectAll<O extends ChoiceOption>(\n value: KeyList<O[\"value\"]>,\n scope: readonly O[],\n maxCount: number | null = null,\n): KeyList<O[\"value\"]> {\n const keys = enabledKeys(scope);\n if (scopeState(value, scope) === \"all\") {\n return removeKeys(value, keys);\n }\n return canSelectAll(value, scope, maxCount) ? addKeys(value, keys) : value;\n}\n\n/**\n * The clear button: `value` without every key the user may remove. A\n * `locked` key (a chosen disabled option) stays.\n */\nexport function clearKeys<K extends OptionKey>(\n value: KeyList<K>,\n locked: (key: K) => boolean,\n): KeyList<K> {\n return removeKeys(\n value,\n valueKeys(value).filter((key) => !locked(key)),\n );\n}\n\n/** What a change did to a value: each list in the order of the value it is found in. */\nexport interface KeyChanges<K extends OptionKey> {\n /** In `next` and not in `previous`, in `next`'s order. */\n readonly added: readonly K[];\n /** In `previous` and not in `next`, in `previous`'s order. */\n readonly removed: readonly K[];\n}\n\n/** The keys a change added and removed. */\nexport function keyChanges<K extends OptionKey>(\n previous: KeyList<K>,\n next: KeyList<K>,\n): KeyChanges<K> {\n return {\n added: valueKeys(next).filter((key) => !hasKey(previous, key)),\n removed: valueKeys(previous).filter((key) => !hasKey(next, key)),\n };\n}\n","/** What identifies an option, and what a choice input's value holds. */\nexport type OptionKey = string | number | bigint | boolean;\n\n/** One choice. A minor release may add optional members. */\nexport interface ChoiceOption<K extends OptionKey = OptionKey, T = unknown> {\n /** The key the value holds; unique within its list. */\n readonly value: K;\n /** Plain text: shown, matched, typed ahead to, announced, written in display mode. */\n readonly label: string;\n /** A second line under the label; matched only when the match fields name it. */\n readonly description?: string | undefined;\n /**\n * Never chosen by the user. The keys skip it unless the list makes\n * disabled options reachable (`DisabledOptions`).\n */\n readonly disabled?: boolean | undefined;\n /** The group's label: options sharing it are drawn under one header. */\n readonly group?: string | undefined;\n /** Text of extra columns, by column id. */\n readonly columns?: Readonly<Record<string, string>> | undefined;\n /** More text to match on, never shown: a code, synonyms. */\n readonly keywords?: readonly string[] | undefined;\n /** The app's own record, handed back in events and templates. */\n readonly data?: T | undefined;\n}\n\n/** The key type of an option type. */\nexport type KeyOf<O extends ChoiceOption> = O[\"value\"];\n\n/** A tree node: an option with children, given or loaded on demand. */\nexport interface TreeOption<\n K extends OptionKey = OptionKey,\n T = unknown,\n> extends ChoiceOption<K, T> {\n readonly children?: readonly TreeOption<K, T>[] | undefined;\n /** Children exist but are not given: the source's `children` loads them. */\n readonly hasChildren?: boolean | undefined;\n}\n\n/**\n * Whether two keys are one: `Object.is`, so `NaN` equals itself and `0`\n * and `-0` differ.\n */\nexport function sameKey(a: OptionKey, b: OptionKey): boolean {\n return Object.is(a, b);\n}\n\n/**\n * A key as text: what a hidden input submits, and what duplicate checks\n * compare, since a form submission cannot tell `1` from `\"1\"`.\n */\nexport function keyText(key: OptionKey): string {\n return String(key);\n}\n\n/**\n * The option a renderer shows for a key whose option is not known: its\n * text as the label.\n */\nexport function standInOption<K extends OptionKey, T = unknown>(\n key: K,\n): ChoiceOption<K, T> {\n return { value: key, label: keyText(key) };\n}\n\n/**\n * The text of every key that more than one option in `options` holds, by\n * `keyText`, each once, in the order of the second occurrence. A renderer\n * draws every row and warns about these; the first option gives the label.\n */\nexport function findDuplicateKeys(\n options: readonly ChoiceOption[],\n): readonly string[] {\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const option of options) {\n const text = keyText(option.value);\n if (seen.has(text)) {\n duplicates.add(text);\n } else {\n seen.add(text);\n }\n }\n return [...duplicates];\n}\n\n/** A row that does something rather than being a value. */\nexport type OptionAction =\n | {\n readonly kind: \"selectAll\";\n readonly scope: \"matching\" | \"loaded\" | \"all\";\n }\n | { readonly kind: \"create\"; readonly text: string }\n | { readonly kind: \"retry\" };\n\n/** One row of an option list as a renderer draws it and a listbox moves over it. */\nexport type OptionRow<O extends ChoiceOption> =\n | {\n readonly kind: \"header\";\n readonly label: string;\n /** How many options the group shows. */\n readonly size: number;\n }\n | {\n readonly kind: \"option\";\n readonly option: O;\n /** Its group's label; `null` for an option with none. */\n readonly group: string | null;\n /** Its place among the options, from 0: `aria-posinset` is one more. */\n readonly position: number;\n }\n | { readonly kind: \"action\"; readonly action: OptionAction };\n\n/** Action rows around the options: \"Select all\" first, \"Create\" or \"Try again\" last. */\nexport interface OptionRowActions {\n readonly start?: readonly OptionAction[] | undefined;\n readonly end?: readonly OptionAction[] | undefined;\n}\n\n/**\n * The rows an option list draws. Groups appear in the order of their first\n * option, each keeping its options' order, under a header; options with no\n * group form a group with no header, placed the same way. A group with no\n * option to show has no header either, so a search that filters out a\n * group's options removes the group.\n */\nexport function flattenOptions<O extends ChoiceOption>(\n options: readonly O[],\n actions: OptionRowActions = {},\n): readonly OptionRow<O>[] {\n const groups = new Map<string | null, O[]>();\n for (const option of options) {\n const group = option.group ?? null;\n const members = groups.get(group);\n if (members === undefined) {\n groups.set(group, [option]);\n } else {\n members.push(option);\n }\n }\n const rows: OptionRow<O>[] = (actions.start ?? []).map(actionRow<O>);\n let position = 0;\n for (const [group, members] of groups) {\n if (group !== null) {\n rows.push({ kind: \"header\", label: group, size: members.length });\n }\n for (const option of members) {\n rows.push({ kind: \"option\", option, group, position });\n position += 1;\n }\n }\n rows.push(...(actions.end ?? []).map(actionRow<O>));\n return rows;\n}\n\nfunction actionRow<O extends ChoiceOption>(action: OptionAction): OptionRow<O> {\n return { kind: \"action\", action };\n}\n","import type { ChangeSource } from \"../field/events\";\nimport { keyChanges, valueKeys, type KeyList } from \"./multi\";\nimport {\n standInOption,\n type ChoiceOption,\n type KeyOf,\n type OptionKey,\n} from \"./options\";\nimport type { OptionQuery } from \"./source\";\n\n/**\n * What a choice input adds to every event it fires. Each list holds full\n * options, in the order of the value it is found in; a key whose option\n * is not known yet is a stand-in `{ value, label: keyText(value) }`.\n */\nexport interface ChoiceDetails<O extends ChoiceOption> {\n /** The options of the value, in its order. */\n readonly options: readonly O[];\n readonly previousOptions: readonly O[];\n /** In the value now and not before, in the value's order. */\n readonly added: readonly O[];\n /** In the value before and not now, in the previous value's order. */\n readonly removed: readonly O[];\n /** Keys of the value whose options are stand-ins: still resolving, missing or unresolved. */\n readonly unknownKeys: readonly KeyOf<O>[];\n /** The search text when it happened; `\"\"` for a list without a search box. */\n readonly query: string;\n}\n\n/** With one value, the same plus the option itself. */\nexport interface SingleChoiceDetails<\n O extends ChoiceOption,\n> extends ChoiceDetails<O> {\n readonly option: O | null;\n readonly previousOption: O | null;\n}\n\n/** The search text changed (`onQueryChange`). */\nexport interface QueryChangeEvent<N = unknown> {\n readonly query: string;\n readonly previousQuery: string;\n /**\n * `typing`, `paste`, `drop`; `clear`; `revert` when the query is dropped\n * as the popup closes; `picker` when a pick ends it; `api`.\n */\n readonly source: ChangeSource;\n readonly nativeEvent: N | null;\n}\n\n/** The highlighted option changed (`onHighlightChange`). */\nexport interface HighlightChangeEvent<O, N = unknown> {\n /** `null`: no option highlighted (the caret is back in the text). */\n readonly option: O | null;\n readonly previousOption: O | null;\n readonly by: \"keyboard\" | \"pointer\" | \"typing\" | \"open\";\n readonly nativeEvent: N | null;\n}\n\n/** The user asked to create an option from what they typed (`onCreate`). */\nexport interface CreateEvent<N = unknown> {\n /** The typed text, trimmed. */\n readonly text: string;\n readonly nativeEvent: N | null;\n}\n\n/** A source's request failed (`onLoadError`). */\nexport interface LoadErrorEvent<F> {\n readonly error: unknown;\n readonly query: OptionQuery<F>;\n}\n\n/** The option a key stands for: known, or a stand-in. */\ntype OptionFinder<K extends OptionKey, T> = (\n key: K,\n) => ChoiceOption<K, T> | null;\n\n/**\n * The details of a change between two values of a choice input with\n * several values. `optionOf` returns a key's option, or `null` when it is\n * not known (an option source controller's `lookup`, a local list).\n */\nexport function choiceDetails<K extends OptionKey, T>(\n value: KeyList<K>,\n previous: KeyList<K>,\n optionOf: OptionFinder<K, T>,\n query: string,\n): ChoiceDetails<ChoiceOption<K, T>> {\n const known = (key: K): ChoiceOption<K, T> =>\n optionOf(key) ?? standInOption(key);\n const { added, removed } = keyChanges(previous, value);\n return {\n options: valueKeys(value).map(known),\n previousOptions: valueKeys(previous).map(known),\n added: added.map(known),\n removed: removed.map(known),\n unknownKeys: valueKeys(value).filter((key) => optionOf(key) === null),\n query,\n };\n}\n\n/** The details of a change between two values of a choice input with one value. */\nexport function singleChoiceDetails<K extends OptionKey, T>(\n value: K | null,\n previous: K | null,\n optionOf: OptionFinder<K, T>,\n query: string,\n): SingleChoiceDetails<ChoiceOption<K, T>> {\n const details = choiceDetails(\n value === null ? null : [value],\n previous === null ? null : [previous],\n optionOf,\n query,\n );\n return {\n ...details,\n option: details.options[0] ?? null,\n previousOption: details.previousOptions[0] ?? null,\n };\n}\n","/** `locale` as a cache key: the same text for the same locales. */\nexport function localeKey(locale: Intl.LocalesArgument): string {\n if (locale === undefined) {\n return \"\";\n }\n return typeof locale === \"string\" || locale instanceof Intl.Locale\n ? String(locale)\n : locale.map(String).join(\",\");\n}\n","import { localeKey } from \"../localeKey\";\nimport type { ChoiceOption } from \"./options\";\n\n/**\n * How a query matches: anywhere in a field, at its start, or every query\n * word at the start of a word of some field, in any order.\n */\nexport type MatchMode = \"contains\" | \"startsWith\" | \"words\";\n\n/** `[start, end)` in UTF-16 units of the original text, always whole graphemes. */\nexport type TextRange = readonly [start: number, end: number];\n\n/**\n * Where an option matched: ranges by field id (`\"label\"`, `\"description\"`,\n * `\"keywords\"`, a column id). A field that matched with nothing to\n * highlight, such as `\"keywords\"`, holds no ranges.\n */\nexport interface OptionMatch {\n readonly fields: Readonly<Record<string, readonly TextRange[]>>;\n}\n\n/**\n * Text folded for matching, with the original range each folded UTF-16\n * unit came from: `starts[i]` and `ends[i]` bound the grapheme of unit `i`.\n */\nexport interface FoldedText {\n readonly text: string;\n readonly starts: readonly number[];\n readonly ends: readonly number[];\n}\n\n/** What a matcher is told besides the option and the query. */\nexport interface MatchContext<O> {\n readonly mode: MatchMode;\n readonly locale: Intl.LocalesArgument;\n /** Field ids to search. */\n readonly fields: readonly string[];\n /** The built-in matcher, to fall back on or wrap. */\n readonly defaultMatch: (option: O, query: string) => OptionMatch | null;\n}\n\n/**\n * An app's matcher. `true` is a match with nothing highlighted; `false` or\n * `null` is no match.\n */\nexport type OptionMatcher<O> = (\n option: O,\n query: string,\n context: MatchContext<O>,\n) => OptionMatch | boolean | null;\n\n/** The fields matched when an input names none. */\nexport const DEFAULT_MATCH_FIELDS: readonly string[] = [\"label\", \"keywords\"];\n\nconst MARKS = /\\p{Mn}/gu;\n// Scripts whose nonspacing marks are accents or optional vowel points;\n// elsewhere (Devanagari, Thai, the Japanese voiced mark) a mark is part of\n// the letter and stays.\nconst FOLDED_MARK_BASE =\n /^[\\p{Script=Latin}\\p{Script=Greek}\\p{Script=Cyrillic}\\p{Script=Hebrew}\\p{Script=Arabic}]/u;\nconst WHITESPACE = /\\s+/u;\n\nconst segmenters = new Map<string, Intl.Segmenter>();\n\nfunction segmenter(\n locale: Intl.LocalesArgument,\n granularity: \"grapheme\" | \"word\",\n): Intl.Segmenter {\n const key = `${granularity}|${localeKey(locale)}`;\n let found = segmenters.get(key);\n if (found === undefined) {\n found = new Intl.Segmenter(locale, { granularity });\n segmenters.set(key, found);\n }\n return found;\n}\n\nconst dotlessILocales = new Map<string, boolean>();\n\n/** Whether the locale lowers \"I\" to dotless \"ı\", so \"ı\" must not fold to \"i\". */\nfunction keepsDotlessI(locale: Intl.LocalesArgument): boolean {\n const key = localeKey(locale);\n let keeps = dotlessILocales.get(key);\n if (keeps === undefined) {\n const language = segmenter(locale, \"grapheme\")\n .resolvedOptions()\n .locale.split(\"-\")[0];\n keeps = language === \"tr\" || language === \"az\";\n dotlessILocales.set(key, keeps);\n }\n return keeps;\n}\n\n// Printable ASCII folds to its lower case one unit for one, which spares\n// most labels the per-grapheme work.\nconst PLAIN_ASCII = /^[\\x20-\\x7e]*$/;\n\n// Below U+0300 (where combining marks start) every unit but CR and LF is a\n// grapheme of its own, so Latin-1 and Latin Extended text needs no segmenter.\nconst SINGLE_UNIT_GRAPHEMES = /^[\\x20-\\x7e\\xa0-\\u02ff]*$/;\n\nfunction graphemes(\n text: string,\n locale: Intl.LocalesArgument,\n): Iterable<{ readonly segment: string; readonly index: number }> {\n return SINGLE_UNIT_GRAPHEMES.test(text)\n ? Array.from(text, (segment, index) => ({ segment, index }))\n : segmenter(locale, \"grapheme\").segment(text);\n}\n\nfunction lowerAscii(text: string, dotlessI: boolean): string {\n return (dotlessI ? text.replaceAll(\"I\", \"ı\") : text).toLowerCase();\n}\n\nfunction foldGrapheme(\n grapheme: string,\n locale: Intl.LocalesArgument,\n dotlessI: boolean,\n): string {\n if (PLAIN_ASCII.test(grapheme)) {\n return lowerAscii(grapheme, dotlessI);\n }\n // Lowered before decomposing, so the Turkish \"İ\" lowers to \"i\".\n let folded = grapheme\n .normalize(\"NFC\")\n .toLocaleLowerCase(locale)\n .normalize(\"NFKD\");\n if (FOLDED_MARK_BASE.test(folded)) {\n folded = folded.replace(MARKS, \"\");\n }\n if (!dotlessI) {\n folded = folded.replaceAll(\"ı\", \"i\");\n }\n return folded.replaceAll(\"ς\", \"σ\");\n}\n\n/**\n * `text` folded for matching, one grapheme at a time: lower case in the\n * locale, compatibility forms decomposed (full width, ligatures), accents\n * dropped from Latin, Greek, Cyrillic, Hebrew and Arabic letters, dotless\n * \"ı\" as \"i\" outside Turkish and Azerbaijani, and a final sigma as \"σ\".\n * Nothing expands: \"ß\" stays \"ß\".\n */\nexport function foldText(\n text: string,\n locale: Intl.LocalesArgument,\n): FoldedText {\n const folded = fold(text, locale);\n if (folded.starts !== null) {\n return folded;\n }\n const starts = Array.from({ length: text.length }, (_, unit) => unit);\n return {\n text: folded.text,\n starts,\n ends: starts.map((unit) => unit + 1),\n };\n}\n\n/** `FoldedText` whose `starts` and `ends` are `null` when every unit maps to itself. */\ntype Folding =\n | FoldedText\n | { readonly text: string; readonly starts: null; readonly ends: null };\n\nfunction fold(text: string, locale: Intl.LocalesArgument): Folding {\n const dotlessI = keepsDotlessI(locale);\n if (PLAIN_ASCII.test(text)) {\n return { text: lowerAscii(text, dotlessI), starts: null, ends: null };\n }\n let folded = \"\";\n const starts: number[] = [];\n const ends: number[] = [];\n for (const { segment, index } of graphemes(text, locale)) {\n const part = foldGrapheme(segment, locale, dotlessI);\n folded += part;\n const end = index + segment.length;\n for (let unit = 0; unit < part.length; unit++) {\n starts.push(index);\n ends.push(end);\n }\n }\n return { text: folded, starts, ends };\n}\n\n/** A field's folded text, with where its words start once asked. */\ninterface FoldedField {\n readonly original: string;\n readonly folded: Folding;\n wordStarts: readonly number[] | null;\n}\n\nfunction foldField(text: string, locale: Intl.LocalesArgument): FoldedField {\n return { original: text, folded: fold(text, locale), wordStarts: null };\n}\n\n/** Where folded unit `unit` comes from in the original text. */\nfunction startOf(folded: Folding, unit: number): number {\n return folded.starts === null ? unit : (folded.starts[unit] ?? 0);\n}\n\nfunction endOf(folded: Folding, unit: number): number {\n return folded.ends === null ? unit + 1 : (folded.ends[unit] ?? 0);\n}\n\n/** Where each word of the original text starts in the folded text. */\nfunction wordStartsOf(\n field: FoldedField,\n locale: Intl.LocalesArgument,\n): readonly number[] {\n if (field.wordStarts !== null) {\n return field.wordStarts;\n }\n const { folded } = field;\n const length = folded.text.length;\n const found: number[] = [];\n let unit = 0;\n for (const { index, isWordLike } of segmenter(locale, \"word\").segment(\n field.original,\n )) {\n while (unit < length && startOf(folded, unit) < index) {\n unit += 1;\n }\n if (isWordLike === true && unit < length) {\n found.push(unit);\n }\n }\n field.wordStarts = found;\n return found;\n}\n\nfunction originalRange(\n folded: Folding,\n start: number,\n length: number,\n): TextRange {\n return [startOf(folded, start), endOf(folded, start + length - 1)];\n}\n\n/** Where `query` (folded, one word in `words` mode) first matches in `field`; `null` for nowhere. */\nfunction findIn(\n field: FoldedField,\n query: string,\n mode: MatchMode,\n locale: Intl.LocalesArgument,\n): TextRange | null {\n const { folded } = field;\n let start: number;\n switch (mode) {\n case \"contains\":\n start = folded.text.indexOf(query);\n break;\n case \"startsWith\":\n start = folded.text.startsWith(query) ? 0 : -1;\n break;\n case \"words\":\n start =\n wordStartsOf(field, locale).find((at) =>\n folded.text.startsWith(query, at),\n ) ?? -1;\n break;\n }\n return start === -1 ? null : originalRange(folded, start, query.length);\n}\n\n/** Sorted, with overlapping and touching ranges joined. */\nfunction joinRanges(ranges: readonly TextRange[]): readonly TextRange[] {\n const sorted = [...ranges].sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n const joined: [number, number][] = [];\n for (const [start, end] of sorted) {\n const last = joined.at(-1);\n if (last !== undefined && start <= last[1]) {\n last[1] = Math.max(last[1], end);\n } else {\n joined.push([start, end]);\n }\n }\n return joined;\n}\n\n/** The query folded and split as `mode` searches for it; `[]` for an empty query. */\nfunction queryParts(\n query: string,\n mode: MatchMode,\n locale: Intl.LocalesArgument,\n): readonly string[] {\n const folded = foldText(query.trim(), locale).text;\n if (folded === \"\") {\n return [];\n }\n return mode === \"words\"\n ? folded.split(WHITESPACE).filter((word) => word !== \"\")\n : [folded];\n}\n\n/** Ranges of every part in `field`, or `null` when one part is missing. */\nfunction matchParts(\n field: FoldedField,\n parts: readonly string[],\n mode: MatchMode,\n locale: Intl.LocalesArgument,\n): readonly TextRange[] | null {\n const ranges: TextRange[] = [];\n for (const part of parts) {\n const range = findIn(field, part, mode, locale);\n if (range === null) {\n return null;\n }\n ranges.push(range);\n }\n return joinRanges(ranges);\n}\n\n/**\n * The ranges of `query` in `text`, on the original text: `[]` for an empty\n * query (it matches everything), `null` for no match. In `words` mode every\n * query word must start a word of `text`.\n */\nexport function matchText(\n text: string,\n query: string,\n mode: MatchMode,\n locale: Intl.LocalesArgument,\n): readonly TextRange[] | null {\n const parts = queryParts(query, mode, locale);\n if (parts.length === 0) {\n return [];\n }\n return matchParts(foldField(text, locale), parts, mode, locale);\n}\n\n/** The texts of one field of an option: `[]` when it has none. */\nfunction fieldTexts(option: ChoiceOption, field: string): readonly string[] {\n switch (field) {\n case \"label\":\n return [option.label];\n case \"description\":\n return option.description === undefined ? [] : [option.description];\n case \"keywords\":\n return option.keywords ?? [];\n default: {\n const text = option.columns?.[field];\n return text === undefined ? [] : [text];\n }\n }\n}\n\n/** One option's fields, folded. */\ntype FoldedOption = readonly {\n readonly field: string;\n readonly texts: readonly FoldedField[];\n}[];\n\nfunction foldOption(\n option: ChoiceOption,\n fields: readonly string[],\n locale: Intl.LocalesArgument,\n): FoldedOption {\n return fields.map((field) => ({\n field,\n texts: fieldTexts(option, field).map((text) => foldField(text, locale)),\n }));\n}\n\n// Keywords are never shown, so a keyword match holds no ranges; every other\n// field holds the ranges of its one text.\nfunction rangesFor(\n field: string,\n ranges: readonly TextRange[],\n): readonly TextRange[] {\n return field === \"keywords\" ? [] : ranges;\n}\n\nfunction matchFolded(\n option: FoldedOption,\n parts: readonly string[],\n mode: MatchMode,\n locale: Intl.LocalesArgument,\n): OptionMatch | null {\n if (parts.length === 0) {\n return { fields: {} };\n }\n if (mode !== \"words\") {\n const fields: Record<string, readonly TextRange[]> = {};\n for (const { field, texts } of option) {\n for (const text of texts) {\n const ranges = matchParts(text, parts, mode, locale);\n if (ranges !== null) {\n fields[field] = rangesFor(field, ranges);\n break;\n }\n }\n }\n return Object.keys(fields).length === 0 ? null : { fields };\n }\n // Each query word may match a different field.\n const found = new Map<string, TextRange[]>();\n for (const part of parts) {\n let matched = false;\n for (const { field, texts } of option) {\n for (const text of texts) {\n const range = findIn(text, part, mode, locale);\n if (range !== null) {\n const ranges = found.get(field) ?? [];\n ranges.push(range);\n found.set(field, ranges);\n matched = true;\n }\n }\n }\n if (!matched) {\n return null;\n }\n }\n const fields: Record<string, readonly TextRange[]> = {};\n for (const [field, ranges] of found) {\n fields[field] = rangesFor(field, joinRanges(ranges));\n }\n return { fields };\n}\n\n/**\n * Where `query` matches `option` in the context's fields, or `null`. An\n * empty query matches with nothing highlighted.\n */\nexport function matchOption<O extends ChoiceOption>(\n option: O,\n query: string,\n context: Omit<MatchContext<O>, \"defaultMatch\">,\n): OptionMatch | null {\n const { mode, locale, fields } = context;\n return matchFolded(\n foldOption(option, fields, locale),\n queryParts(query, mode, locale),\n mode,\n locale,\n );\n}\n\n/** An option a search kept, with its place in the list and where it matched. */\nexport interface OptionHit<O> {\n readonly option: O;\n readonly index: number;\n readonly match: OptionMatch;\n}\n\n/**\n * A list's options folded once for one set of fields and one locale, so\n * a keystroke folds only the query.\n */\nexport interface OptionIndex<O extends ChoiceOption> {\n readonly options: readonly O[];\n /** Where `query` matches the option at `index`, or `null`. */\n readonly matchAt: (\n index: number,\n query: string,\n mode: MatchMode,\n ) => OptionMatch | null;\n /**\n * Every option `query` matches, in list order. An app's `matcher`\n * decides in place of the built-in one, which it receives as\n * `defaultMatch`.\n */\n readonly search: (\n query: string,\n mode: MatchMode,\n matcher?: OptionMatcher<O>,\n ) => readonly OptionHit<O>[];\n}\n\n/** `options` folded once, for matching on `fields` in `locale`. */\nexport function createOptionIndex<O extends ChoiceOption>(\n options: readonly O[],\n fields: readonly string[],\n locale: Intl.LocalesArgument,\n): OptionIndex<O> {\n const folded = new Map<number, FoldedOption>();\n const indexOf = new Map<O, number>();\n options.forEach((option, index) => {\n if (!indexOf.has(option)) {\n indexOf.set(option, index);\n }\n });\n\n const foldedAt = (index: number, option: O): FoldedOption => {\n let found = folded.get(index);\n if (found === undefined) {\n found = foldOption(option, fields, locale);\n folded.set(index, found);\n }\n return found;\n };\n\n const matchAt = (\n index: number,\n query: string,\n mode: MatchMode,\n ): OptionMatch | null => {\n const option = options[index];\n return option === undefined\n ? null\n : matchFolded(\n foldedAt(index, option),\n queryParts(query, mode, locale),\n mode,\n locale,\n );\n };\n\n const search = (\n query: string,\n mode: MatchMode,\n matcher?: OptionMatcher<O>,\n ): readonly OptionHit<O>[] => {\n const parts = queryParts(query, mode, locale);\n const defaultMatch = (option: O, asked: string): OptionMatch | null => {\n const index = indexOf.get(option);\n if (index === undefined) {\n return matchOption(option, asked, { mode, locale, fields });\n }\n return asked === query\n ? matchFolded(foldedAt(index, option), parts, mode, locale)\n : matchAt(index, asked, mode);\n };\n const context: MatchContext<O> = { mode, locale, fields, defaultMatch };\n const hits: OptionHit<O>[] = [];\n options.forEach((option, index) => {\n const match =\n matcher === undefined\n ? matchFolded(foldedAt(index, option), parts, mode, locale)\n : matcherResult(matcher(option, query, context));\n if (match !== null) {\n hits.push({ option, index, match });\n }\n });\n return hits;\n };\n\n return { options, matchAt, search };\n}\n\nfunction matcherResult(\n result: OptionMatch | boolean | null,\n): OptionMatch | null {\n if (result === true) {\n return { fields: {} };\n }\n return result === false ? null : result;\n}\n","/**\n * The index of the item `query` — what was typed, buffered for a moment —\n * picks, matched case-insensitively against the start of each label and\n * wrapping round the end; `-1` when none matches.\n *\n * `from` is the item focused now. A single letter, or the same letter\n * typed again and again, searches from the item after it, so repeating a\n * letter steps through every item it starts. A longer query searches from\n * `from` itself, so the item already found stays put while what is typed\n * still matches it.\n */\nexport function typeaheadIndex(\n labels: readonly string[],\n from: number,\n query: string,\n): number {\n const typed = query.toLowerCase();\n const firstCodePoint = typed.codePointAt(0);\n if (firstCodePoint === undefined) {\n return -1;\n }\n const first = String.fromCodePoint(firstCodePoint);\n const repeated = typed.replaceAll(first, \"\") === \"\";\n const prefix = repeated ? first : typed;\n const start = repeated ? from + 1 : Math.max(from, 0);\n for (let offset = 0; offset < labels.length; offset++) {\n const index = (start + offset) % labels.length;\n if (labels[index]?.toLowerCase().startsWith(prefix) === true) {\n return index;\n }\n }\n return -1;\n}\n","import { typeaheadIndex } from \"../typeahead\";\nimport { foldText } from \"./match\";\n\n/**\n * Whether the keys reach disabled options: `\"skip\"` (the default, as a\n * native `<select>` does) or `\"focus\"`, which makes them reachable, to be\n * announced as unavailable and never chosen.\n */\nexport type DisabledOptions = \"skip\" | \"focus\";\n\n/** What a listbox needs to know of a row to move over it. */\nexport interface NavigableRow {\n readonly kind: \"header\" | \"option\" | \"action\";\n readonly disabled: boolean;\n}\n\n/** A move of the active row. `rows` is how many rows a page holds. */\nexport type ActiveMove =\n | { readonly kind: \"next\" }\n | { readonly kind: \"previous\" }\n | { readonly kind: \"first\" }\n | { readonly kind: \"last\" }\n | { readonly kind: \"pageDown\"; readonly rows: number }\n | { readonly kind: \"pageUp\"; readonly rows: number };\n\n/**\n * Whether the active row can land on `row`: never a header, a disabled\n * row only when `disabledOptions` is `\"focus\"`.\n */\nexport function isLandingRow(\n row: NavigableRow,\n disabledOptions: DisabledOptions,\n): boolean {\n return (\n row.kind !== \"header\" && (!row.disabled || disabledOptions === \"focus\")\n );\n}\n\n/** The first landing row from `start` stepping by `step`, before `stop`; `null` for none. */\nfunction findLanding(\n rows: readonly NavigableRow[],\n start: number,\n step: 1 | -1,\n stop: number,\n disabledOptions: DisabledOptions,\n): number | null {\n for (let index = start; index !== stop; index += step) {\n const row = rows[index];\n if (row !== undefined && isLandingRow(row, disabledOptions)) {\n return index;\n }\n }\n return null;\n}\n\n/**\n * The row the active row moves to, or `null` when no row can be landed\n * on. Moves stop at the ends rather than wrapping, so a long list never\n * jumps end to end; a move with nowhere to go keeps `from`. With no active\n * row, \"next\" lands on the first row and \"previous\" on the last. A page\n * move lands on the row a page away, or the nearest landing row past it,\n * else the nearest before it.\n */\nexport function moveActive(\n rows: readonly NavigableRow[],\n from: number | null,\n move: ActiveMove,\n disabledOptions: DisabledOptions = \"skip\",\n): number | null {\n const count = rows.length;\n const first = findLanding(rows, 0, 1, count, disabledOptions);\n if (first === null) {\n return null;\n }\n const last = findLanding(rows, count - 1, -1, -1, disabledOptions) ?? first;\n if (from === null || from < 0 || from >= count) {\n return move.kind === \"previous\" || move.kind === \"last\" ? last : first;\n }\n switch (move.kind) {\n case \"first\":\n return first;\n case \"last\":\n return last;\n case \"next\":\n return findLanding(rows, from + 1, 1, count, disabledOptions) ?? from;\n case \"previous\":\n return findLanding(rows, from - 1, -1, -1, disabledOptions) ?? from;\n case \"pageDown\": {\n const target = Math.min(from + Math.max(move.rows, 1), count - 1);\n return (\n findLanding(rows, target, 1, count, disabledOptions) ??\n findLanding(rows, target - 1, -1, from, disabledOptions) ??\n from\n );\n }\n case \"pageUp\": {\n const target = Math.max(from - Math.max(move.rows, 1), 0);\n return (\n findLanding(rows, target, -1, -1, disabledOptions) ??\n findLanding(rows, target + 1, 1, from, disabledOptions) ??\n from\n );\n }\n }\n}\n\n/** A row type-ahead can find: `typeahead` is its label folded with `foldText`. */\nexport interface TypeaheadRow extends NavigableRow {\n readonly typeahead: string;\n}\n\n/**\n * The row the typed `buffer` finds, folded as labels are, among the rows\n * the active row can land on; `null` when none starts with it. Repeating\n * one letter steps through the rows it starts, from the one after `from`.\n */\nexport function typeaheadRow(\n rows: readonly TypeaheadRow[],\n from: number | null,\n buffer: string,\n locale: Intl.LocalesArgument,\n disabledOptions: DisabledOptions = \"skip\",\n): number | null {\n const labels = rows.map((row) =>\n isLandingRow(row, disabledOptions) ? row.typeahead : \"\",\n );\n const index = typeaheadIndex(\n labels,\n from ?? -1,\n foldText(buffer, locale).text,\n );\n return index === -1 ? null : index;\n}\n","import type { ChoiceOption, KeyOf, TreeOption } from \"./options\";\n\n/** Where the next page starts, as the source wrote it. */\nexport type OptionCursor = string | number;\n\n/** What a query asks for, apart from its page. */\nexport interface OptionQuery<F> {\n /** The search text as typed; `\"\"` when the list opens. */\n readonly text: string;\n /** The app's dependent filter values (a city list's country), compared by value. */\n readonly filters: F;\n}\n\n/** One request a source answers. `S` is the signal type: `AbortSignal` in a browser. */\nexport interface OptionSearch<F, S> extends OptionQuery<F> {\n /** `null` for the first page, else the previous page's `next`. */\n readonly cursor: OptionCursor | null;\n readonly pageSize: number;\n /** Aborted as soon as this request is superseded or the input goes away. */\n readonly signal: S;\n}\n\n/** One page of a query's options. */\nexport interface OptionPage<O> {\n readonly options: readonly O[];\n /** Passed back as `cursor` for more; absent or `null` on the last page. */\n readonly next?: OptionCursor | null | undefined;\n /** How many options match in all, when the server knows. */\n readonly total?: number | undefined;\n}\n\n/**\n * Where a choice input's options come from when they are not a local\n * list: a server, usually. The input never fetches by itself; it calls\n * these and shows their states. `F` is the dependent filters' type and\n * `S` the signal type.\n */\nexport interface OptionSource<\n O extends ChoiceOption,\n F = undefined,\n S = unknown,\n> {\n /** One page for a query. A bare array is a single, last page. */\n readonly search: (\n request: OptionSearch<F, S>,\n ) => Promise<OptionPage<O> | readonly O[]>;\n /**\n * The options of keys not loaded: the labels of a value the form opened\n * with. A key missing from the answer no longer exists.\n */\n readonly resolve?:\n | ((\n keys: readonly KeyOf<O>[],\n context: { readonly filters: F; readonly signal: S },\n ) => Promise<readonly O[]>)\n | undefined;\n /** Every key matching a query, for \"select all\" past the loaded pages. */\n readonly allKeys?:\n | ((query: OptionQuery<F>, signal: S) => Promise<readonly KeyOf<O>[]>)\n | undefined;\n /**\n * `\"source\"` (the default): `search` filters by `text` itself.\n * `\"local\"`: it returns the whole list once per filters value, and the\n * input matches locally.\n */\n readonly filtering?: \"source\" | \"local\" | undefined;\n /** Milliseconds typing must pause before `search`. Default 250. */\n readonly debounce?: number | undefined;\n /** Default 50. */\n readonly pageSize?: number | undefined;\n /** The shortest text that searches; shorter asks nothing. Default 0. */\n readonly minQueryLength?: number | undefined;\n}\n\n/** A tree's source: a source that also loads a node's children. */\nexport interface TreeSource<\n O extends TreeOption,\n F = undefined,\n S = unknown,\n> extends OptionSource<O, F, S> {\n readonly children: (\n parent: KeyOf<O>,\n context: {\n readonly filters: F;\n readonly signal: S;\n readonly cursor: OptionCursor | null;\n },\n ) => Promise<OptionPage<O> | readonly O[]>;\n}\n\n/**\n * A fresh signal and the means to abort it. forms-core has no\n * `AbortSignal`, so whoever drives a source hands it one of these:\n * forms-dom's `abortSignals` makes `AbortController`s.\n */\nexport type AbortFactory<S> = () => {\n readonly signal: S;\n readonly abort: () => void;\n};\n\nexport const DEFAULT_SOURCE_DEBOUNCE = 250;\nexport const DEFAULT_SOURCE_PAGE_SIZE = 50;\n\n/** A source's answer as a page. */\nexport function toOptionPage<O>(\n answer: OptionPage<O> | readonly O[],\n): OptionPage<O> {\n return \"options\" in answer ? answer : { options: answer };\n}\n\nfunction canonical(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return JSON.stringify(value);\n case \"number\":\n case \"boolean\":\n case \"undefined\":\n return String(value);\n case \"bigint\":\n return `${String(value)}n`;\n case \"symbol\":\n case \"function\":\n return `<${typeof value}>`;\n case \"object\":\n if (value === null) {\n return \"null\";\n }\n if (value instanceof Date) {\n return `Date(${String(value.getTime())})`;\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonical).join(\",\")}]`;\n }\n return `{${Object.entries(value)\n .filter(([, member]) => member !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([key, member]) => `${JSON.stringify(key)}:${canonical(member)}`)\n .join(\",\")}}`;\n }\n}\n\n/**\n * Filter values as text, the same for the same values: object keys in any\n * order, members holding `undefined` left out, `bigint` and `Date` by\n * value. Filters are plain data; a function or symbol counts only as one.\n */\nexport function filtersKey(filters: unknown): string {\n return canonical(filters);\n}\n\n/** Whether two filter values are the same by value, so an inline `{ country }` object is fine. */\nexport function sameFilters(a: unknown, b: unknown): boolean {\n return filtersKey(a) === filtersKey(b);\n}\n\n/** What a list shows from a query: every page so far, in order. */\nexport interface LoadedOptions<O> {\n readonly options: readonly O[];\n readonly next: OptionCursor | null;\n readonly total: number | null;\n}\n\n/** `page` after the pages in `shown`, or alone when `shown` is `null`. */\nexport function appendPage<O>(\n shown: LoadedOptions<O> | null,\n page: OptionPage<O>,\n): LoadedOptions<O> {\n return {\n options:\n shown === null ? page.options : [...shown.options, ...page.options],\n next: page.next ?? null,\n total: page.total ?? shown?.total ?? null,\n };\n}\n\n/**\n * A query's lifecycle. `shown` is what the list keeps showing meanwhile,\n * drawn dimmed: the last result for the same filters, never another\n * filter's. `request` numbers a request, so an answer to an earlier one\n * is ignored; `more` marks a next page rather than a new query.\n */\nexport type SourceState<O, F> =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"waiting\";\n readonly query: OptionQuery<F>;\n readonly shown: LoadedOptions<O> | null;\n }\n | {\n readonly kind: \"loading\";\n readonly query: OptionQuery<F>;\n readonly request: number;\n readonly shown: LoadedOptions<O> | null;\n readonly more: boolean;\n }\n | {\n readonly kind: \"loaded\";\n readonly query: OptionQuery<F>;\n readonly result: LoadedOptions<O>;\n }\n | {\n readonly kind: \"failed\";\n readonly query: OptionQuery<F>;\n readonly request: number;\n readonly error: unknown;\n readonly shown: LoadedOptions<O> | null;\n readonly more: boolean;\n };\n\n/** What can happen to a query. */\nexport type SourceAction<O, F> =\n /** Typing: the query waits for the debounce. */\n | { readonly type: \"wait\"; readonly query: OptionQuery<F> }\n /** A request starts: a new query, or its next page with `more`. */\n | {\n readonly type: \"start\";\n readonly query: OptionQuery<F>;\n readonly request: number;\n readonly more: boolean;\n }\n | {\n readonly type: \"page\";\n readonly request: number;\n readonly page: OptionPage<O>;\n }\n | { readonly type: \"fail\"; readonly request: number; readonly error: unknown }\n /** A result known without a request: a cached page, or a local list matched. */\n | {\n readonly type: \"show\";\n readonly query: OptionQuery<F>;\n readonly result: LoadedOptions<O>;\n }\n /** The query is dropped, and what it showed with it: the filters changed or the list closed. */\n | { readonly type: \"reset\" };\n\nexport const SOURCE_IDLE: SourceState<never, never> = { kind: \"idle\" };\n\nfunction shownOf<O, F>(state: SourceState<O, F>): LoadedOptions<O> | null {\n switch (state.kind) {\n case \"idle\":\n return null;\n case \"loaded\":\n return state.result;\n case \"waiting\":\n case \"loading\":\n case \"failed\":\n return state.shown;\n }\n}\n\n/**\n * A query's state after `action`. Pure. A `page` or `fail` whose `request`\n * is not the one loading is ignored, so a superseded answer never replaces\n * a newer one, even from a source that ignores its signal.\n */\nexport function sourceReducer<O, F>(\n state: SourceState<O, F>,\n action: SourceAction<O, F>,\n): SourceState<O, F> {\n switch (action.type) {\n case \"wait\":\n return { kind: \"waiting\", query: action.query, shown: shownOf(state) };\n case \"start\":\n return {\n kind: \"loading\",\n query: action.query,\n request: action.request,\n shown: shownOf(state),\n more: action.more,\n };\n case \"page\":\n if (state.kind !== \"loading\" || state.request !== action.request) {\n return state;\n }\n return {\n kind: \"loaded\",\n query: state.query,\n result: appendPage(state.more ? state.shown : null, action.page),\n };\n case \"fail\":\n if (state.kind !== \"loading\" || state.request !== action.request) {\n return state;\n }\n return {\n kind: \"failed\",\n query: state.query,\n request: state.request,\n error: action.error,\n shown: state.shown,\n more: state.more,\n };\n case \"show\":\n return { kind: \"loaded\", query: action.query, result: action.result };\n case \"reset\":\n return state.kind === \"idle\" ? state : SOURCE_IDLE;\n }\n}\n","import type { ChoiceOption, KeyOf, OptionKey } from \"./options\";\nimport type {\n AbortFactory,\n OptionCursor,\n OptionPage,\n OptionSource,\n} from \"./source\";\nimport { filtersKey } from \"./source\";\n\n/** What is known of a key's option now. */\nexport type KeyLookup<O> =\n | { readonly kind: \"known\"; readonly option: O }\n /** Asked of the source's `resolve`, not answered yet. */\n | { readonly kind: \"resolving\" }\n /** `resolve` answered without it: the option no longer exists. */\n | { readonly kind: \"missing\" }\n /** Not known and not asked: no `resolve`, it failed, or nothing asked yet. */\n | { readonly kind: \"unresolved\" };\n\n/** Where a page is kept: its text, its filters as `filtersKey` wrote them, and its cursor. */\nexport interface PageKey {\n readonly text: string;\n readonly filters: string;\n readonly cursor: OptionCursor | null;\n}\n\n/** What a cache needs to ask a source for labels. */\nexport interface ResolveRequest<O extends ChoiceOption, F, S> {\n readonly resolve: NonNullable<OptionSource<O, F, S>[\"resolve\"]>;\n readonly filters: F;\n readonly abort: AbortFactory<S>;\n}\n\nexport interface OptionCacheOptions {\n /** How many queries' pages it keeps, least recently used out first. Default 50. */\n readonly maxQueries?: number | undefined;\n /** How long a page stays fresh, in milliseconds; a stale page is asked again. Default 300 000. */\n readonly maxAge?: number | undefined;\n /** The clock, for tests. */\n readonly now?: (() => number) | undefined;\n}\n\n/**\n * One source's pages and options, shared by every input on the source\n * that is handed it. Pages are kept by query and filters, so one filter\n * value never reads another's; options are kept by key for every label\n * an input shows. A renderer drives it through an option source\n * controller.\n */\nexport interface OptionCache<O extends ChoiceOption> {\n /** A fresh page, or `null`. */\n readonly readPage: (key: PageKey) => OptionPage<O> | null;\n /** Keeps a page (a first page replaces the query's others) and its options by key. */\n readonly storePage: (key: PageKey, page: OptionPage<O>) => void;\n /** Options known without a request: an input's `options` and `valueOptions`, a created option. Silent. */\n readonly addOptions: (options: readonly O[]) => void;\n readonly lookup: (key: KeyOf<O>) => KeyLookup<O>;\n /**\n * Asks for the options of `keys` not known, missing or already asked.\n * Keys asked in one microtask, by any input, go into one `resolve`\n * call per filters value. Its signal is never aborted: other inputs\n * may wait on the same call.\n */\n readonly resolve: <F, S>(\n keys: readonly KeyOf<O>[],\n request: ResolveRequest<O, F, S>,\n ) => void;\n /** Forgets every page and every missing key; options by key stay. */\n readonly invalidate: () => void;\n /** Called when an answer makes a key's lookup change. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Grows each time listeners are called. */\n readonly getVersion: () => number;\n}\n\ninterface QueryEntry<O> {\n readonly at: number;\n readonly pages: Map<string, OptionPage<O>>;\n}\n\ninterface Batch<O extends ChoiceOption> {\n readonly keys: KeyOf<O>[];\n // Each batch calls the first request's `resolve`: one cache serves one\n // source, so every input on it hands the same function.\n readonly request: ResolveRequest<O, unknown, unknown>;\n}\n\n/**\n * A cache for one source. One per input by default; share one across\n * every input on a source (created once, at module level) so a form with\n * ten fields on it calls `resolve` once.\n */\nexport function createOptionCache<O extends ChoiceOption>(\n options: OptionCacheOptions = {},\n): OptionCache<O> {\n const maxQueries = options.maxQueries ?? 50;\n const maxAge = options.maxAge ?? 300_000;\n const now = options.now ?? Date.now;\n const queries = new Map<string, QueryEntry<O>>();\n const byKey = new Map<OptionKey, O>();\n const resolving = new Set<OptionKey>();\n const missing = new Set<OptionKey>();\n const pending = new Map<string, Batch<O>>();\n const listeners = new Set<() => void>();\n let version = 0;\n\n const notify = (): void => {\n version += 1;\n for (const listener of [...listeners]) {\n listener();\n }\n };\n\n const queryKey = (key: PageKey): string =>\n JSON.stringify([key.filters, key.text]);\n\n /** Adds options by key; true when one was not known before. */\n const learn = (found: readonly O[]): boolean => {\n let learned = false;\n for (const option of found) {\n learned ||= !byKey.has(option.value);\n byKey.set(option.value, option);\n }\n return learned;\n };\n\n const flush = (): void => {\n const batches = [...pending.values()];\n pending.clear();\n for (const { keys, request } of batches) {\n const { signal } = request.abort();\n Promise.resolve()\n .then(() => request.resolve(keys, { filters: request.filters, signal }))\n .then(\n (found) => {\n learn(found);\n for (const key of keys) {\n resolving.delete(key);\n if (!byKey.has(key)) {\n missing.add(key);\n }\n }\n notify();\n },\n () => {\n for (const key of keys) {\n resolving.delete(key);\n }\n notify();\n },\n );\n }\n };\n\n return {\n readPage: (key) => {\n const id = queryKey(key);\n const entry = queries.get(id);\n if (entry === undefined) {\n return null;\n }\n if (now() - entry.at > maxAge) {\n queries.delete(id);\n return null;\n }\n queries.delete(id);\n queries.set(id, entry);\n return entry.pages.get(JSON.stringify(key.cursor)) ?? null;\n },\n storePage: (key, page) => {\n const id = queryKey(key);\n const existing = queries.get(id);\n const entry =\n key.cursor === null || existing === undefined\n ? { at: now(), pages: new Map<string, OptionPage<O>>() }\n : existing;\n entry.pages.set(JSON.stringify(key.cursor), page);\n queries.delete(id);\n queries.set(id, entry);\n for (const oldest of queries.keys()) {\n if (queries.size <= maxQueries) {\n break;\n }\n queries.delete(oldest);\n }\n if (learn(page.options)) {\n notify();\n }\n },\n addOptions: (found) => {\n learn(found);\n },\n lookup: (key) => {\n const option = byKey.get(key);\n if (option !== undefined) {\n return { kind: \"known\", option };\n }\n if (resolving.has(key)) {\n return { kind: \"resolving\" };\n }\n return missing.has(key) ? { kind: \"missing\" } : { kind: \"unresolved\" };\n },\n resolve: (keys, request) => {\n const asked = [...new Set(keys)].filter(\n (key) => !byKey.has(key) && !resolving.has(key) && !missing.has(key),\n );\n if (asked.length === 0) {\n return;\n }\n const id = filtersKey(request.filters);\n const batch = pending.get(id);\n if (batch === undefined) {\n if (pending.size === 0) {\n void Promise.resolve().then(flush);\n }\n pending.set(id, {\n keys: asked,\n request: request as ResolveRequest<O, unknown, unknown>,\n });\n } else {\n batch.keys.push(...asked.filter((key) => !batch.keys.includes(key)));\n }\n for (const key of asked) {\n resolving.add(key);\n }\n },\n invalidate: () => {\n queries.clear();\n missing.clear();\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getVersion: () => version,\n };\n}\n","import type { Schedule } from \"../schedule\";\nimport {\n createOptionCache,\n type KeyLookup,\n type OptionCache,\n type PageKey,\n} from \"./optionCache\";\nimport type { ChoiceOption, KeyOf } from \"./options\";\nimport {\n appendPage,\n DEFAULT_SOURCE_DEBOUNCE,\n DEFAULT_SOURCE_PAGE_SIZE,\n filtersKey,\n sameFilters,\n SOURCE_IDLE,\n sourceReducer,\n toOptionPage,\n type AbortFactory,\n type LoadedOptions,\n type OptionCursor,\n type OptionPage,\n type OptionQuery,\n type OptionSource,\n type SourceAction,\n type SourceState,\n} from \"./source\";\n\n/** What drives an option source controller; a renderer passes the latest on every update. */\nexport interface OptionSourceOptions<O extends ChoiceOption, F, S> {\n /** A new object is not a reset: the latest functions serve the next request. */\n readonly source: OptionSource<O, F, S>;\n readonly filters: F;\n readonly abort: AbortFactory<S>;\n /** The debounce's timer. */\n readonly schedule: Schedule;\n /** One per controller by default; share one per source with `createOptionCache`. */\n readonly cache?: OptionCache<O> | undefined;\n /** The input's matcher, used when the source's `filtering` is `\"local\"`. */\n readonly match: (option: O, text: string) => boolean;\n /** A request failed (the input's `onLoadError`). */\n readonly onError?:\n ((error: unknown, query: OptionQuery<F>) => void) | undefined;\n}\n\n/**\n * One input's queries to a source: what the list shows, the debounce,\n * the request in flight and its signal, paging, and labels through the\n * cache. Listeners hear every change of the state and every label that\n * arrives (the cache's version grows then).\n */\nexport interface OptionSourceController<O extends ChoiceOption, F, S> {\n readonly getState: () => SourceState<O, F>;\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Silent. Filters that differ by value drop the query and what it\n * showed; if a list shows, the same text is asked again at once.\n */\n readonly setOptions: (options: OptionSourceOptions<O, F, S>) => void;\n /** Typing: the query is `text` now, asked after the debounce unless a fresh cached page answers at once. */\n readonly query: (text: string) => void;\n /** Opening, Enter, a retry: asked now, or answered at once from a fresh cached page. */\n readonly queryNow: (text: string) => void;\n /** The next page, when the loaded result has `next`. */\n readonly loadMore: () => void;\n /** Asks the failed request again. */\n readonly retry: () => void;\n /** Forgets the cache's pages and, if a list shows, asks again. */\n readonly invalidate: () => void;\n /** The list closed: aborts what is in flight, cancels the debounce and drops the query. */\n readonly close: () => void;\n /** Labels for `keys`, through the cache's batched `resolve`. */\n readonly resolve: (keys: readonly KeyOf<O>[]) => void;\n /** What is known of a key now. */\n readonly lookup: (key: KeyOf<O>) => KeyLookup<O>;\n readonly getCache: () => OptionCache<O>;\n /**\n * Aborts what is in flight, cancels the debounce and ignores every\n * later answer. Silent, and the controller stays usable, so a second\n * mount can use it again.\n */\n readonly destroy: () => void;\n}\n\n/**\n * The controller between a choice input and its source. Each request\n * gets its own signal and number: a newer query aborts the older one at\n * once, and an older answer that arrives anyway is ignored.\n */\nexport function createOptionSourceController<O extends ChoiceOption, F, S>(\n initial: OptionSourceOptions<O, F, S>,\n): OptionSourceController<O, F, S> {\n let options = initial;\n const ownCache = createOptionCache<O>();\n let state: SourceState<O, F> = SOURCE_IDLE;\n let lastRequest = 0;\n let inFlight: {\n readonly request: number;\n readonly abort: () => void;\n } | null = null;\n let cancelWait: (() => void) | null = null;\n const listeners = new Set<() => void>();\n let cacheSubscription: (() => void) | null = null;\n\n const cache = (): OptionCache<O> => options.cache ?? ownCache;\n\n const emit = (): void => {\n for (const listener of [...listeners]) {\n listener();\n }\n };\n\n const apply = (action: SourceAction<O, F>): void => {\n state = sourceReducer(state, action);\n };\n\n /** Runs `change`, then tells the listeners if the state moved. */\n const transition = (change: () => void): void => {\n const before = state;\n change();\n if (state !== before) {\n emit();\n }\n };\n\n const release = (): void => {\n cancelWait?.();\n cancelWait = null;\n inFlight?.abort();\n inFlight = null;\n };\n\n const isLocal = (): boolean => options.source.filtering === \"local\";\n\n const tooShort = (text: string): boolean =>\n text.trim().length < (options.source.minQueryLength ?? 0);\n\n const queryOf = (text: string): OptionQuery<F> => ({\n text,\n filters: options.filters,\n });\n\n // A local source answers once per filters value with its whole list.\n const pageKey = (\n query: OptionQuery<F>,\n cursor: OptionCursor | null,\n ): PageKey => ({\n text: isLocal() ? \"\" : query.text,\n filters: filtersKey(query.filters),\n cursor,\n });\n\n const matches = (option: O, text: string): boolean =>\n text.trim() === \"\" || options.match(option, text);\n\n /** What a page shows: after the result it follows, or, from a local source, the whole list matched. */\n const shownResult = (\n query: OptionQuery<F>,\n page: OptionPage<O>,\n more: LoadedOptions<O> | null,\n ): LoadedOptions<O> => {\n if (!isLocal()) {\n return appendPage(more, page);\n }\n const kept = page.options.filter((option) => matches(option, query.text));\n return { options: kept, next: null, total: kept.length };\n };\n\n /** Asks for a page, or shows a fresh cached one; `more` is the result it follows. */\n const fetch = (\n query: OptionQuery<F>,\n cursor: OptionCursor | null,\n more: LoadedOptions<O> | null,\n ): void => {\n const key = pageKey(query, cursor);\n const cached = cache().readPage(key);\n if (cached !== null) {\n apply({ type: \"show\", query, result: shownResult(query, cached, more) });\n return;\n }\n lastRequest += 1;\n const request = lastRequest;\n const { signal, abort } = options.abort();\n inFlight = { request, abort };\n apply({ type: \"start\", query, request, more: more !== null });\n const { source } = options;\n Promise.resolve()\n .then(() =>\n source.search({\n text: key.text,\n filters: query.filters,\n cursor,\n pageSize: source.pageSize ?? DEFAULT_SOURCE_PAGE_SIZE,\n signal,\n }),\n )\n .then(\n (answer) => {\n if (inFlight?.request !== request) {\n return;\n }\n inFlight = null;\n const page = toOptionPage(answer);\n cache().storePage(key, page);\n transition(() => {\n if (isLocal()) {\n apply({\n type: \"show\",\n query,\n result: shownResult(query, page, null),\n });\n } else {\n apply({ type: \"page\", request, page });\n }\n });\n },\n (error: unknown) => {\n if (inFlight?.request !== request) {\n return;\n }\n inFlight = null;\n transition(() => {\n apply({ type: \"fail\", request, error });\n });\n options.onError?.(error, query);\n },\n );\n };\n\n const ask = (text: string): void => {\n release();\n if (tooShort(text)) {\n apply({ type: \"reset\" });\n } else {\n fetch(queryOf(text), null, null);\n }\n };\n\n const subscribeCache = (): void => {\n cacheSubscription = cache().subscribe(emit);\n };\n\n return {\n getState: () => state,\n subscribe: (listener) => {\n listeners.add(listener);\n if (cacheSubscription === null) {\n subscribeCache();\n }\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n cacheSubscription?.();\n cacheSubscription = null;\n }\n };\n },\n setOptions: (next) => {\n const previous = options;\n options = next;\n if (\n (previous.cache ?? ownCache) !== cache() &&\n cacheSubscription !== null\n ) {\n cacheSubscription();\n subscribeCache();\n }\n if (sameFilters(previous.filters, next.filters)) {\n return;\n }\n const shown = state.kind === \"idle\" ? null : state.query.text;\n release();\n apply({ type: \"reset\" });\n if (shown !== null) {\n ask(shown);\n }\n },\n query: (text) => {\n transition(() => {\n release();\n const query = queryOf(text);\n const delay = options.source.debounce ?? DEFAULT_SOURCE_DEBOUNCE;\n if (\n tooShort(text) ||\n isLocal() ||\n delay <= 0 ||\n cache().readPage(pageKey(query, null)) !== null\n ) {\n ask(text);\n return;\n }\n apply({ type: \"wait\", query });\n cancelWait = options.schedule(() => {\n cancelWait = null;\n transition(() => {\n fetch(query, null, null);\n });\n }, delay);\n });\n },\n queryNow: (text) => {\n transition(() => {\n ask(text);\n });\n },\n loadMore: () => {\n if (state.kind !== \"loaded\" || state.result.next === null || isLocal()) {\n return;\n }\n const { query, result } = state;\n transition(() => {\n fetch(query, result.next, result);\n });\n },\n retry: () => {\n if (state.kind !== \"failed\") {\n return;\n }\n const { query, more, shown } = state;\n transition(() => {\n release();\n if (more && shown !== null && shown.next !== null) {\n fetch(query, shown.next, shown);\n } else {\n fetch(query, null, null);\n }\n });\n },\n invalidate: () => {\n cache().invalidate();\n if (state.kind !== \"idle\") {\n const { text } = state.query;\n transition(() => {\n ask(text);\n });\n }\n },\n close: () => {\n transition(() => {\n release();\n apply({ type: \"reset\" });\n });\n },\n resolve: (keys) => {\n const { resolve } = options.source;\n if (resolve !== undefined) {\n cache().resolve(keys, {\n resolve,\n filters: options.filters,\n abort: options.abort,\n });\n }\n },\n lookup: (key) => cache().lookup(key),\n getCache: cache,\n destroy: () => {\n release();\n apply({ type: \"reset\" });\n },\n };\n}\n","import { matchOption, type MatchContext, type OptionMatch } from \"./match\";\nimport type { KeyOf, OptionKey, TreeOption } from \"./options\";\n\n/**\n * What a tree's value holds with several values: every ticked node\n * (`\"all\"`), ticked nodes with no children (`\"leaves\"`), or each ticked\n * node whose parent is not ticked, a whole parent standing for its\n * children (`\"parent\"`).\n */\nexport type TreeValueMode = \"all\" | \"leaves\" | \"parent\";\n\n/** A node's tick: a parent with some of its enabled children ticked is `\"mixed\"`. */\nexport type TickState = \"ticked\" | \"unticked\" | \"mixed\";\n\n/** A tree's shape by key, built once per tree by `createTreeIndex`. */\nexport interface TreeIndex<K extends OptionKey> {\n /** The top-level keys, in order. */\n readonly roots: readonly K[];\n /** Every key, parents before their children, in order. */\n readonly keys: readonly K[];\n /** Whether the tree holds `key`. */\n readonly has: (key: K) => boolean;\n /** The parent's key; `null` for a top-level or unknown key. */\n readonly parentOf: (key: K) => K | null;\n /** The children's keys; `null` for a leaf, an unknown key or children not loaded yet. */\n readonly childrenOf: (key: K) => readonly K[] | null;\n readonly isDisabled: (key: K) => boolean;\n /** Keys listed again under their own descendant, or twice in the tree: left out, for a development warning. */\n readonly cycles: readonly K[];\n}\n\ninterface IndexedNode<K> {\n readonly parent: K | null;\n readonly children: readonly K[] | null;\n readonly disabled: boolean;\n}\n\n/** The shape of `nodes`, by key. A key met a second time is left out and listed in `cycles`. */\nexport function createTreeIndex<O extends TreeOption>(\n nodes: readonly O[],\n): TreeIndex<KeyOf<O>> {\n type K = KeyOf<O>;\n const byKey = new Map<K, IndexedNode<K>>();\n const keys: K[] = [];\n const cycles: K[] = [];\n\n const visit = (siblings: readonly TreeOption[], parent: K | null): K[] => {\n const placed: K[] = [];\n for (const node of siblings) {\n const key = node.value as K;\n if (byKey.has(key)) {\n cycles.push(key);\n continue;\n }\n // Held before the children are visited, so a node listed under its\n // own descendant is met as a repeat.\n byKey.set(key, { parent, children: null, disabled: false });\n keys.push(key);\n placed.push(key);\n const children =\n node.children === undefined ? null : visit(node.children, key);\n byKey.set(key, {\n parent,\n children: children?.length === 0 ? null : children,\n disabled: node.disabled === true,\n });\n }\n return placed;\n };\n const roots = visit(nodes, null);\n\n return {\n roots,\n keys,\n has: (key) => byKey.has(key),\n parentOf: (key) => byKey.get(key)?.parent ?? null,\n childrenOf: (key) => byKey.get(key)?.children ?? null,\n isDisabled: (key) => byKey.get(key)?.disabled === true,\n cycles,\n };\n}\n\n/** Every enabled descendant of `key`, parents first; a disabled node's subtree keeps its ticks. */\nfunction enabledDescendants<K extends OptionKey>(\n tree: TreeIndex<K>,\n key: K,\n): K[] {\n const found: K[] = [];\n for (const child of tree.childrenOf(key) ?? []) {\n if (!tree.isDisabled(child)) {\n found.push(child, ...enabledDescendants(tree, child));\n }\n }\n return found;\n}\n\n/** Parents ticked when every enabled child is, unticked otherwise, from `key`'s parent up. */\nfunction settleAncestors<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: Set<K>,\n key: K,\n): void {\n for (\n let parent = tree.parentOf(key);\n parent !== null;\n parent = tree.parentOf(parent)\n ) {\n if (tree.isDisabled(parent)) {\n continue;\n }\n const enabled = (tree.childrenOf(parent) ?? []).filter(\n (child) => !tree.isDisabled(child),\n );\n if (enabled.length > 0 && enabled.every((child) => ticked.has(child))) {\n ticked.add(parent);\n } else {\n ticked.delete(parent);\n }\n }\n}\n\n/**\n * The ticked set after ticking (`tick` true) or unticking `key`. With\n * `cascade`, the tick carries down to every enabled descendant (a\n * disabled node and its subtree keep their state) and up: a parent is\n * ticked exactly when every enabled child is. Without it, the node ticks\n * alone. A disabled node changes nothing.\n *\n * The set keeps the order nodes were ticked in: the node, its\n * descendants, then the parents it completed, bottom up. `treeValue`\n * appends in that order.\n */\nexport function tickNode<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: ReadonlySet<K>,\n key: K,\n tick: boolean,\n cascade: boolean,\n): ReadonlySet<K> {\n if (tree.isDisabled(key)) {\n return ticked;\n }\n return setTick(tree, ticked, key, tick, cascade);\n}\n\nfunction setTick<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: ReadonlySet<K>,\n key: K,\n tick: boolean,\n cascade: boolean,\n): ReadonlySet<K> {\n const next = new Set(ticked);\n const changed = cascade ? [key, ...enabledDescendants(tree, key)] : [key];\n for (const node of changed) {\n if (tick) {\n next.add(node);\n } else {\n next.delete(node);\n }\n }\n if (cascade) {\n settleAncestors(tree, next, key);\n }\n return next;\n}\n\n/**\n * A node's tick as a ticked set shows it, for a cascading tree: a node\n * with enabled children is ticked when they all are, unticked when none\n * is (and it is not ticked itself), and mixed otherwise; a leaf, or a\n * node whose children are not loaded, is ticked when the set holds it.\n */\nexport function tickState<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: ReadonlySet<K>,\n key: K,\n): TickState {\n const enabled = (tree.childrenOf(key) ?? []).filter(\n (child) => !tree.isDisabled(child),\n );\n if (enabled.length === 0) {\n return ticked.has(key) ? \"ticked\" : \"unticked\";\n }\n const states = new Set(\n enabled.map((child) => tickState(tree, ticked, child)),\n );\n if (states.size === 1 && states.has(\"ticked\")) {\n return \"ticked\";\n }\n return states.size === 1 && states.has(\"unticked\") && !ticked.has(key)\n ? \"unticked\"\n : \"mixed\";\n}\n\nfunction inValue<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: ReadonlySet<K>,\n key: K,\n mode: TreeValueMode,\n): boolean {\n switch (mode) {\n case \"all\":\n return true;\n case \"leaves\":\n return tree.childrenOf(key) === null;\n case \"parent\": {\n const parent = tree.parentOf(key);\n return parent === null || !ticked.has(parent);\n }\n }\n}\n\n/**\n * The value a ticked set means in `mode`: the keys of `previous` it still\n * holds, in their order, then the rest in the order they were ticked.\n * Keys the tree does not hold stay. `null` when nothing is ticked.\n */\nexport function treeValue<K extends OptionKey>(\n tree: TreeIndex<K>,\n ticked: ReadonlySet<K>,\n mode: TreeValueMode,\n previous: readonly K[] | null,\n): readonly K[] | null {\n const shown = [...ticked].filter((key) => inValue(tree, ticked, key, mode));\n const kept = (previous ?? []).filter((key) => shown.includes(key));\n const value = [...kept, ...shown.filter((key) => !kept.includes(key))];\n return value.length === 0 ? null : value;\n}\n\n/**\n * The ticked set a value means, in any `TreeValueMode`: each key ticks its\n * node and, with `cascade` (the default), its enabled descendants, and\n * the parents follow. A disabled node in the value is ticked too. Keys\n * the tree does not hold stay in the set.\n */\nexport function tickedFromValue<K extends OptionKey>(\n tree: TreeIndex<K>,\n value: readonly K[] | null,\n cascade = true,\n): ReadonlySet<K> {\n let ticked: ReadonlySet<K> = new Set();\n for (const key of value ?? []) {\n ticked = setTick(tree, ticked, key, true, cascade);\n }\n return ticked;\n}\n\n/** A visible row of a tree. */\nexport interface TreeRow<O extends TreeOption> {\n readonly option: O;\n /** Depth from 1: `aria-level`. */\n readonly level: number;\n /** Open, closed, or `null` for a leaf (no children, given or to load). */\n readonly expanded: boolean | null;\n /** The parent's row; `null` at the top. */\n readonly parent: number | null;\n /** How many siblings it has, itself included, and its place among them from 1: `aria-setsize`, `aria-posinset`. */\n readonly size: number;\n readonly position: number;\n}\n\nfunction hasChildNodes(node: TreeOption): boolean {\n return (node.children?.length ?? 0) > 0 || node.hasChildren === true;\n}\n\n/**\n * The rows a tree shows: every top-level node, and the children of every\n * open node. A node listed under its own descendant is left out.\n */\nexport function flattenTree<O extends TreeOption>(\n nodes: readonly O[],\n open: ReadonlySet<KeyOf<O>>,\n): readonly TreeRow<O>[] {\n const rows: TreeRow<O>[] = [];\n const path = new Set<KeyOf<O>>();\n const visit = (\n siblings: readonly O[],\n level: number,\n parent: number | null,\n ): void => {\n const shown = siblings.filter((node) => !path.has(node.value));\n shown.forEach((node, index) => {\n const branch = hasChildNodes(node);\n const expanded = branch ? open.has(node.value) : null;\n rows.push({\n option: node,\n level,\n expanded,\n parent,\n size: shown.length,\n position: index + 1,\n });\n if (expanded === true && node.children !== undefined) {\n path.add(node.value);\n visit(node.children as readonly O[], level + 1, rows.length - 1);\n path.delete(node.value);\n }\n });\n };\n visit(nodes, 1, null);\n return rows;\n}\n\n/** What a search keeps of a tree. */\nexport interface TreeSearch<O extends TreeOption> {\n /** Every match and its ancestors; a match keeps all its children. */\n readonly nodes: readonly O[];\n /** The ancestors of the matches, to show open while searching. */\n readonly open: ReadonlySet<KeyOf<O>>;\n /** Where each matching node matched. */\n readonly matches: ReadonlyMap<KeyOf<O>, OptionMatch>;\n}\n\n/**\n * The nodes a search keeps: every node `query` matches, with its whole\n * subtree (closed unless a descendant matches too), and the ancestors of\n * every match, open. An empty query keeps the tree as it is.\n */\nexport function searchTree<O extends TreeOption>(\n nodes: readonly O[],\n query: string,\n context: Omit<MatchContext<O>, \"defaultMatch\">,\n): TreeSearch<O> {\n const open = new Set<KeyOf<O>>();\n const matches = new Map<KeyOf<O>, OptionMatch>();\n if (query.trim() === \"\") {\n return { nodes, open, matches };\n }\n const path = new Set<KeyOf<O>>();\n const prune = (siblings: readonly O[]): O[] => {\n const kept: O[] = [];\n for (const node of siblings) {\n if (path.has(node.value)) {\n continue;\n }\n path.add(node.value);\n const match = matchOption(node, query, context);\n const children = prune((node.children ?? []) as readonly O[]);\n path.delete(node.value);\n if (match !== null) {\n matches.set(node.value, match);\n }\n if (children.length > 0) {\n open.add(node.value);\n }\n if (match !== null) {\n kept.push(node);\n } else if (children.length > 0) {\n kept.push({ ...node, children });\n }\n }\n return kept;\n };\n return { nodes: prune(nodes), open, matches };\n}\n\n/**\n * A node's children loading on demand. `request` numbers the load, so an\n * answer to an earlier one is ignored.\n */\nexport type ChildrenLoad =\n | { readonly kind: \"unloaded\" }\n | { readonly kind: \"loading\"; readonly request: number }\n | { readonly kind: \"loaded\" }\n | { readonly kind: \"failed\"; readonly error: unknown };\n\n/** What can happen to a node's children load. */\nexport type ChildrenLoadAction =\n | { readonly type: \"start\"; readonly request: number }\n | { readonly type: \"loaded\"; readonly request: number }\n | { readonly type: \"fail\"; readonly request: number; readonly error: unknown }\n /** Forget the children: the tree was reloaded. */\n | { readonly type: \"reset\" };\n\nexport const CHILDREN_UNLOADED: ChildrenLoad = { kind: \"unloaded\" };\n\n/**\n * A children load after `action`. An answer whose `request` is not the\n * one loading is ignored; a load starts again from any state, a retry\n * after a failure among them.\n */\nexport function childrenLoadReducer(\n state: ChildrenLoad,\n action: ChildrenLoadAction,\n): ChildrenLoad {\n switch (action.type) {\n case \"start\":\n return { kind: \"loading\", request: action.request };\n case \"loaded\":\n return state.kind === \"loading\" && state.request === action.request\n ? { kind: \"loaded\" }\n : state;\n case \"fail\":\n return state.kind === \"loading\" && state.request === action.request\n ? { kind: \"failed\", error: action.error }\n : state;\n case \"reset\":\n return CHILDREN_UNLOADED;\n }\n}\n","// Calendar arithmetic runs on a `Date`'s UTC fields only, so the process\n// zone never enters it. Days become day numbers through `setUTCFullYear`,\n// never `Date.UTC`, which reads the years 0 to 99 as 1900 to 1999.\n\n/** A calendar day, no time, no zone: \"2026-03-14\". */\nexport type PlainDate = `${number}-${number}-${number}`;\n/** A time of day, no date, no zone: \"15:05\", \"15:05:09\", \"15:05:09.250\". */\nexport type PlainTime = `${number}:${number}` | `${number}:${number}:${number}`;\n/** A wall-clock date and time, no zone: \"2026-03-14T15:05\". */\nexport type PlainDateTime = `${PlainDate}T${PlainTime}`;\n/** An exact moment, always written in UTC: \"2026-03-14T14:05:00.000Z\". */\nexport type Instant = `${PlainDate}T${PlainTime}Z`;\n/** ISO weekday: 1 is Monday, 7 Sunday, as `Intl.Locale#getWeekInfo` numbers them. */\nexport type Weekday = 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\n/** A day's fields: month 1 to 12, day 1 to 31. */\nexport interface DateParts {\n readonly year: number;\n readonly month: number;\n readonly day: number;\n}\n\n/** A time's fields: hour 0 to 23. */\nexport interface TimeParts {\n readonly hour: number;\n readonly minute: number;\n readonly second: number;\n readonly millisecond: number;\n}\n\nconst DAY_MS = 86_400_000;\nexport const MIN_YEAR = 1;\nexport const MAX_YEAR = 9999;\n\nconst DATE_TEXT = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst TIME_TEXT = /^(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{1,9}))?)?$/;\nconst OFFSET_TEXT = /^(?:Z|([+-])(\\d{2}):?(\\d{2}))$/i;\n\nfunction pad(value: number, width: number): string {\n return String(value).padStart(width, \"0\");\n}\n\n/** Whether `year` has a 29 February in the proleptic Gregorian calendar. */\nexport function isLeapYear(year: number): boolean {\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\nconst MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n/** The days in `month` of `year`: 28 to 31. A month outside 1 to 12 counts on into the years either side. */\nexport function daysInMonth(year: number, month: number): number {\n const index = year * 12 + month - 1;\n const fullYear = Math.floor(index / 12);\n const monthIndex = index - fullYear * 12;\n const length = MONTH_LENGTHS[monthIndex] ?? 31;\n return monthIndex === 1 && isLeapYear(fullYear) ? length + 1 : length;\n}\n\nfunction isDay(year: number, month: number, day: number): boolean {\n return (\n Number.isInteger(year) &&\n Number.isInteger(month) &&\n Number.isInteger(day) &&\n year >= MIN_YEAR &&\n year <= MAX_YEAR &&\n month >= 1 &&\n month <= 12 &&\n day >= 1 &&\n day <= daysInMonth(year, month)\n );\n}\n\nfunction isTime(parts: TimeParts): boolean {\n const { hour, minute, second, millisecond } = parts;\n return (\n [hour, minute, second, millisecond].every(Number.isInteger) &&\n hour >= 0 &&\n hour <= 23 &&\n minute >= 0 &&\n minute <= 59 &&\n second >= 0 &&\n second <= 59 &&\n millisecond >= 0 &&\n millisecond <= 999\n );\n}\n\n/** The day `year-month-day`. Throws a `RangeError` for a day that does not exist or a year outside 1 to 9999. */\nexport function plainDate(year: number, month: number, day: number): PlainDate {\n if (!isDay(year, month, day)) {\n throw new RangeError(`${[year, month, day].join(\"-\")} is not a day`);\n }\n return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}` as PlainDate;\n}\n\n/**\n * The time `hour:minute`, with seconds when they or the milliseconds are\n * set, and milliseconds when set: \"15:05\", \"15:05:09\", \"15:05:09.250\".\n * Throws a `RangeError` for a time that does not exist (24:00 included).\n */\nexport function plainTime(\n hour: number,\n minute: number,\n second = 0,\n millisecond = 0,\n): PlainTime {\n if (!isTime({ hour, minute, second, millisecond })) {\n throw new RangeError(\n `${[hour, minute, second].join(\":\")} is not a time of day`,\n );\n }\n const base = `${pad(hour, 2)}:${pad(minute, 2)}`;\n if (second === 0 && millisecond === 0) {\n return base as PlainTime;\n }\n const seconds = `${base}:${pad(second, 2)}`;\n return (\n millisecond === 0 ? seconds : `${seconds}.${pad(millisecond, 3)}`\n ) as PlainTime;\n}\n\n/** `date` at `time`. */\nexport function plainDateTime(date: PlainDate, time: PlainTime): PlainDateTime {\n return `${date}T${time}`;\n}\n\nfunction datePartsOf(text: string): DateParts | null {\n const match = DATE_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const parts = {\n year: Number(match[1]),\n month: Number(match[2]),\n day: Number(match[3]),\n };\n return isDay(parts.year, parts.month, parts.day) ? parts : null;\n}\n\nfunction timePartsOf(text: string): TimeParts | null {\n const match = TIME_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const parts = {\n hour: Number(match[1]),\n minute: Number(match[2]),\n second: Number(match[3] ?? 0),\n millisecond: Number((match[4] ?? \"\").padEnd(3, \"0\").slice(0, 3)),\n };\n return isTime(parts) ? parts : null;\n}\n\n/** `text` as a day when it is one in ISO form (\"2026-03-14\"); `null` otherwise. */\nexport function toPlainDate(text: string): PlainDate | null {\n const parts = datePartsOf(text);\n return parts === null ? null : plainDate(parts.year, parts.month, parts.day);\n}\n\n/**\n * `text` as a time of day when it is one in ISO form, in its shortest\n * form (\"15:05:00\" is \"15:05\"; digits past milliseconds are dropped);\n * `null` otherwise.\n */\nexport function toPlainTime(text: string): PlainTime | null {\n const parts = timePartsOf(text);\n return parts === null\n ? null\n : plainTime(parts.hour, parts.minute, parts.second, parts.millisecond);\n}\n\n/** `text` as a wall clock when it is one in ISO form (\"2026-03-14T15:05\"), its time shortest; `null` otherwise. */\nexport function toPlainDateTime(text: string): PlainDateTime | null {\n const [date = \"\", time = \"\", ...rest] = text.split(\"T\");\n if (rest.length > 0) {\n return null;\n }\n const day = toPlainDate(date);\n const clock = toPlainTime(time);\n return day === null || clock === null ? null : plainDateTime(day, clock);\n}\n\n/**\n * `text` as an exact moment when it is an ISO date and time with `Z` or\n * an offset (`+01:00`), written as `Date#toISOString` writes it; `null`\n * otherwise.\n */\nexport function toInstant(text: string): Instant | null {\n const match = /^(.+T[\\d:.]+)(Z|[+-]\\d{2}:?\\d{2})$/i.exec(text);\n const local = match?.[1] === undefined ? null : toPlainDateTime(match[1]);\n const offset = OFFSET_TEXT.exec(match?.[2] ?? \"\");\n if (local === null || offset === null) {\n return null;\n }\n const [, sign, hours = \"0\", minutes = \"0\"] = offset;\n const offsetMs =\n (sign === \"-\" ? -1 : 1) * (Number(hours) * 60 + Number(minutes)) * 60_000;\n const epoch = epochOfWallClock(local) - offsetMs;\n return inYears(epoch) ? instantFromEpoch(epoch) : null;\n}\n\n/** Whether the moment `epoch` falls in the years 1 to 9999, in UTC. */\nfunction inYears(epoch: number): boolean {\n const year = new Date(epoch).getUTCFullYear();\n return year >= MIN_YEAR && year <= MAX_YEAR;\n}\n\n/** Whether `value` is a day in canonical form. */\nexport function isPlainDate(value: unknown): value is PlainDate {\n return typeof value === \"string\" && toPlainDate(value) === value;\n}\n\n/** Whether `value` is a time of day in canonical (shortest) form. */\nexport function isPlainTime(value: unknown): value is PlainTime {\n return typeof value === \"string\" && toPlainTime(value) === value;\n}\n\n/** Whether `value` is a wall clock in canonical form. */\nexport function isPlainDateTime(value: unknown): value is PlainDateTime {\n return typeof value === \"string\" && toPlainDateTime(value) === value;\n}\n\n/** Whether `value` is an exact moment in canonical form. */\nexport function isInstant(value: unknown): value is Instant {\n return typeof value === \"string\" && toInstant(value) === value;\n}\n\n/** A day's fields. Throws a `RangeError` for text that is not a day. */\nexport function dateParts(date: PlainDate): DateParts {\n const parts = datePartsOf(date);\n if (parts === null) {\n throw new RangeError(`${date} is not a day`);\n }\n return parts;\n}\n\n/** A time's fields. Throws a `RangeError` for text that is not a time of day. */\nexport function timeParts(time: PlainTime): TimeParts {\n const parts = timePartsOf(time);\n if (parts === null) {\n throw new RangeError(`${time} is not a time of day`);\n }\n return parts;\n}\n\n/** A wall clock's day and time. */\nexport function splitDateTime(dateTime: PlainDateTime): {\n readonly date: PlainDate;\n readonly time: PlainTime;\n} {\n const [date = \"\", time = \"\"] = dateTime.split(\"T\");\n return { date: date as PlainDate, time: time as PlainTime };\n}\n\n// Day numbers use Howard Hinnant's `days_from_civil` and `civil_from_days`\n// (public domain, \"chrono-Compatible Low-Level Date Algorithms\", the\n// algorithms behind C++20 <chrono>): whole numbers only, exact in the\n// proleptic Gregorian calendar, counted in 400-year eras of 146 097 days\n// that start on 1 March, with 719 468 the day number of 0000-03-01 from\n// 1970-01-01. `Math.floor` keeps the division right for negative eras.\nconst DAYS_PER_ERA = 146_097;\nconst EPOCH_SHIFT = 719_468;\n\n/**\n * Days since 1970-01-01 for a day's fields, any year. A month outside 1\n * to 12 counts on into the years either side, and a day outside the\n * month into the months either side, as `Date` would.\n */\nexport function dayNumberOf(year: number, month: number, day: number): number {\n const index = year * 12 + month - 1;\n const monthIndex = index - Math.floor(index / 12) * 12;\n // The year from 1 March, so 29 February ends it.\n const marchYear = Math.floor(index / 12) - (monthIndex < 2 ? 1 : 0);\n const era = Math.floor(marchYear / 400);\n const yearOfEra = marchYear - era * 400;\n const marchMonth = monthIndex < 2 ? monthIndex + 10 : monthIndex - 2;\n const dayOfYear = Math.floor((153 * marchMonth + 2) / 5) + day - 1;\n const dayOfEra =\n yearOfEra * 365 +\n Math.floor(yearOfEra / 4) -\n Math.floor(yearOfEra / 100) +\n dayOfYear;\n return era * DAYS_PER_ERA + dayOfEra - EPOCH_SHIFT;\n}\n\n/** A day's fields for `dayNumber` days after 1970-01-01, any year. */\nfunction fieldsOfDayNumber(dayNumber: number): DateParts {\n const shifted = Math.floor(dayNumber) + EPOCH_SHIFT;\n const era = Math.floor(shifted / DAYS_PER_ERA);\n const dayOfEra = shifted - era * DAYS_PER_ERA;\n const yearOfEra = Math.floor(\n (dayOfEra -\n Math.floor(dayOfEra / 1460) +\n Math.floor(dayOfEra / 36_524) -\n Math.floor(dayOfEra / 146_096)) /\n 365,\n );\n const dayOfYear =\n dayOfEra -\n (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));\n const marchMonth = Math.floor((5 * dayOfYear + 2) / 153);\n const month = marchMonth < 10 ? marchMonth + 3 : marchMonth - 9;\n return {\n year: yearOfEra + era * 400 + (month <= 2 ? 1 : 0),\n month,\n day: dayOfYear - Math.floor((153 * marchMonth + 2) / 5) + 1,\n };\n}\n\n/** The day `dayNumber` days after 1970-01-01. Throws a `RangeError` outside the years 1 to 9999. */\nexport function dateOfDayNumber(dayNumber: number): PlainDate {\n const { year, month, day } = fieldsOfDayNumber(dayNumber);\n return plainDate(year, month, day);\n}\n\nfunction dayNumber(date: PlainDate): number {\n const { year, month, day } = dateParts(date);\n return dayNumberOf(year, month, day);\n}\n\n/** `days` days after `date` (before, when negative). */\nexport function addDays(date: PlainDate, days: number): PlainDate {\n return dateOfDayNumber(dayNumber(date) + days);\n}\n\n/** `months` months after `date`, the day clamped to the month's length: 31 January plus a month is the last day of February. */\nexport function addMonths(date: PlainDate, months: number): PlainDate {\n const { year, month, day } = dateParts(date);\n const index = year * 12 + (month - 1) + months;\n const nextYear = Math.floor(index / 12);\n const nextMonth = index - nextYear * 12 + 1;\n return plainDate(\n nextYear,\n nextMonth,\n Math.min(day, daysInMonth(nextYear, nextMonth)),\n );\n}\n\n/** `years` years after `date`; 29 February becomes 28 February in a year that has none. */\nexport function addYears(date: PlainDate, years: number): PlainDate {\n return addMonths(date, years * 12);\n}\n\n/** Days from `start` to `end`: negative when `end` comes first. */\nexport function daysBetween(start: PlainDate, end: PlainDate): number {\n return dayNumber(end) - dayNumber(start);\n}\n\n/** The ISO weekday of `date`: 1 for Monday to 7 for Sunday. */\nexport function dayOfWeek(date: PlainDate): Weekday {\n // Day 0, 1970-01-01, was a Thursday (4). Adding 10 (3, then a week)\n // keeps the remainder of a day before 1970 from going negative.\n return ((((dayNumber(date) % 7) + 10) % 7) + 1) as Weekday;\n}\n\n/** The first day of `date`'s month. */\nexport function startOfMonth(date: PlainDate): PlainDate {\n const { year, month } = dateParts(date);\n return plainDate(year, month, 1);\n}\n\n/** The last day of `date`'s month. */\nexport function endOfMonth(date: PlainDate): PlainDate {\n const { year, month } = dateParts(date);\n return plainDate(year, month, daysInMonth(year, month));\n}\n\n/** Negative when `a` comes first, 0 for the same day, positive after. */\nexport function compareDates(a: PlainDate, b: PlainDate): number {\n return dayNumber(a) - dayNumber(b);\n}\n\n/** Milliseconds into the day. */\nfunction millisecondsOfDay(time: PlainTime): number {\n const { hour, minute, second, millisecond } = timeParts(time);\n return ((hour * 60 + minute) * 60 + second) * 1000 + millisecond;\n}\n\n/** Minutes into the day, seconds as a fraction: \"01:30\" is 90. */\nexport function minutesOfDay(time: PlainTime): number {\n return millisecondsOfDay(time) / 60_000;\n}\n\n/** Negative when `a` comes first in the day, 0 for the same time, positive after. */\nexport function compareTimes(a: PlainTime, b: PlainTime): number {\n return millisecondsOfDay(a) - millisecondsOfDay(b);\n}\n\n/** Milliseconds since the epoch of `dateTime` read as if it were UTC. */\nexport function epochOfWallClock(dateTime: PlainDateTime): number {\n const { date, time } = splitDateTime(dateTime);\n return dayNumber(date) * DAY_MS + millisecondsOfDay(time);\n}\n\n/** The wall clock `epoch` milliseconds since the epoch shows in UTC. */\nexport function wallClockOfEpoch(epoch: number): PlainDateTime {\n const date = new Date(epoch);\n return plainDateTime(\n plainDate(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()),\n plainTime(\n date.getUTCHours(),\n date.getUTCMinutes(),\n date.getUTCSeconds(),\n date.getUTCMilliseconds(),\n ),\n );\n}\n\n/** Negative when `a` comes first, 0 for the same wall clock, positive after. */\nexport function compareDateTimes(a: PlainDateTime, b: PlainDateTime): number {\n return epochOfWallClock(a) - epochOfWallClock(b);\n}\n\n/** Milliseconds since the epoch. */\nexport function epochOfInstant(instant: Instant): number {\n return Date.parse(instant);\n}\n\n/** The moment `epoch` milliseconds since the epoch. Throws a `RangeError` outside the years 1 to 9999. */\nexport function instantFromEpoch(epoch: number): Instant {\n if (!inYears(epoch)) {\n throw new RangeError(`${String(epoch)} is outside the years 1 to 9999`);\n }\n return new Date(epoch).toISOString() as Instant;\n}\n\n/** Negative when `a` comes first, 0 for the same moment, positive after. */\nexport function compareInstants(a: Instant, b: Instant): number {\n return epochOfInstant(a) - epochOfInstant(b);\n}\n\n/**\n * `date` as a `Date` at local midnight, as the grid reads a `yyyy-mm-dd`\n * cell, where `new Date(\"2026-03-01\")` would be midnight in UTC: the day\n * before west of UTC.\n */\nexport function dateFromPlainDate(date: PlainDate): Date {\n const { year, month, day } = dateParts(date);\n const local = new Date(0);\n local.setFullYear(year, month - 1, day);\n local.setHours(0, 0, 0, 0);\n return local;\n}\n\n/** `dateTime` as a `Date` at that local wall clock. */\nexport function dateFromPlainDateTime(dateTime: PlainDateTime): Date {\n const { date, time } = splitDateTime(dateTime);\n const local = dateFromPlainDate(date);\n const { hour, minute, second, millisecond } = timeParts(time);\n local.setHours(hour, minute, second, millisecond);\n return local;\n}\n\n/** The local day of a `Date`, as the grid writes a date cell. */\nexport function plainDateFromDate(date: Date): PlainDate {\n return plainDate(date.getFullYear(), date.getMonth() + 1, date.getDate());\n}\n\n/** `instant` as a `Date`: exact. */\nexport function dateFromInstant(instant: Instant): Date {\n return new Date(epochOfInstant(instant));\n}\n\n/** A `Date` as an exact moment. */\nexport function instantFromDate(date: Date): Instant {\n return instantFromEpoch(date.getTime());\n}\n","import { localeKey } from \"../localeKey\";\nimport {\n epochOfInstant,\n epochOfWallClock,\n plainDateTime,\n timeParts,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\n\n// Wall clocks are formatted as the UTC moment of the same wall clock, with\n// `timeZone: \"UTC\"`, so the process zone never shifts the text; an instant\n// is formatted in the zone its input names. Every format passes\n// `calendar: \"gregory\"`: the forms read the Gregorian calendar only.\n\n/** Formatters already built, by locale and options. */\nconst formats = new Map<string, Intl.DateTimeFormat>();\n\n/** A Gregorian `Intl.DateTimeFormat` for `locale` and `options`, cached. */\nexport function dateTimeFormat(\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormat {\n const key = `${localeKey(locale)}|${JSON.stringify(options)}`;\n let format = formats.get(key);\n if (format === undefined) {\n format = new Intl.DateTimeFormat(locale, {\n ...options,\n calendar: \"gregory\",\n });\n formats.set(key, format);\n }\n return format;\n}\n\nconst DATE_STYLE: Intl.DateTimeFormatOptions = { dateStyle: \"medium\" };\n\n/** `timeStyle: \"short\"`, or `\"medium\"` when `time` has seconds. */\nfunction timeStyleFor(time: PlainTime): Intl.DateTimeFormatOptions {\n const { second, millisecond } = timeParts(time);\n return { timeStyle: second === 0 && millisecond === 0 ? \"short\" : \"medium\" };\n}\n\n/** `options` for a wall clock: the caller's, written in UTC. */\nfunction inUtc(\n options: Intl.DateTimeFormatOptions,\n): Intl.DateTimeFormatOptions {\n return { ...options, timeZone: \"UTC\" };\n}\n\n/** A day as display mode writes it: `dateStyle: \"medium\"` unless `options` say otherwise (\"Mar 14, 2026\", \"14.03.2026\"). */\nexport function formatDate(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions = DATE_STYLE,\n): string {\n return dateTimeFormat(locale, inUtc(options)).format(\n epochOfWallClock(plainDateTime(date, \"00:00\")),\n );\n}\n\n/** A time of day as display mode writes it: `timeStyle: \"short\"`, `\"medium\"` with seconds, unless `options` say otherwise. */\nexport function formatTime(\n time: PlainTime,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions = timeStyleFor(time),\n): string {\n return dateTimeFormat(locale, inUtc(options)).format(\n epochOfWallClock(plainDateTime(\"1970-01-01\", time)),\n );\n}\n\n/** A wall clock as display mode writes it: the date and time styles together unless `options` say otherwise. */\nexport function formatDateTime(\n dateTime: PlainDateTime,\n locale: Intl.LocalesArgument,\n options?: Intl.DateTimeFormatOptions,\n): string {\n const time = dateTime.slice(11) as PlainTime;\n return dateTimeFormat(\n locale,\n inUtc(options ?? { ...DATE_STYLE, ...timeStyleFor(time) }),\n ).format(epochOfWallClock(dateTime));\n}\n\n/** A moment as display mode writes it in `timeZone`, as `formatDateTime` writes its wall clock. */\nexport function formatInstant(\n instant: Instant,\n timeZone: string,\n locale: Intl.LocalesArgument,\n options?: Intl.DateTimeFormatOptions,\n): string {\n const time = instant.slice(11, -1) as PlainTime;\n return dateTimeFormat(locale, {\n ...(options ?? { ...DATE_STYLE, ...timeStyleFor(time) }),\n timeZone,\n }).format(epochOfInstant(instant));\n}\n","import {\n addDays,\n dateParts,\n dayOfWeek,\n daysBetween,\n plainDate,\n type PlainDate,\n type Weekday,\n} from \"./values\";\n\n/** The day a week starts on in a locale, and its weekend days. */\nexport interface WeekInfo {\n readonly firstDay: Weekday;\n readonly weekend: readonly Weekday[];\n}\n\n/**\n * How weeks are numbered: `\"iso\"`, weeks from Monday with week 1 holding\n * the year's first Thursday (ISO 8601); `\"simple\"`, weeks from the first\n * day of week with week 1 holding 1 January (US practice).\n */\nexport type WeekNumbering = \"iso\" | \"simple\";\n\n/** A week of a year: `{ year: 2026, week: 11 }` is 2026-W11. */\nexport interface WeekOfYear {\n readonly year: number;\n readonly week: number;\n}\n\n/** What weekInfo reads from an `Intl.Locale`: the method, the getter some engines shipped before it, or the region. */\nexport interface WeekInfoSource {\n readonly getWeekInfo?: (() => Partial<WeekInfo>) | undefined;\n readonly weekInfo?: Partial<WeekInfo> | undefined;\n readonly maximize: () => { readonly region?: string | undefined };\n}\n\n// CLDR's first day of week by region, for an engine without week info.\nconst SUNDAY_FIRST = new Set(\n \"AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN JM JP KE KH KR LA MH MM MO MT MX MZ NI NP PA PE PH PK PR PT PY SA SG SV TH TT TW UM US VE VI WS YE ZA ZW\".split(\n \" \",\n ),\n);\nconst SATURDAY_FIRST = new Set(\n \"AE AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY\".split(\" \"),\n);\n// CLDR's weekends that are not Saturday and Sunday.\nconst FRIDAY_SATURDAY = new Set(\n \"AE BH DZ EG IL IQ JO KW LY OM QA SA SD SY YE\".split(\" \"),\n);\nconst OTHER_WEEKENDS: Readonly<Record<string, readonly Weekday[]>> = {\n AF: [4, 5],\n IR: [5],\n IN: [7],\n UG: [7],\n};\n\nfunction isWeekday(day: unknown): day is Weekday {\n return (\n typeof day === \"number\" && Number.isInteger(day) && day >= 1 && day <= 7\n );\n}\n\n/** Week info from the region alone, CLDR's data for an engine that has none. */\nfunction regionWeekInfo(region: string | undefined): WeekInfo {\n const code = region ?? \"\";\n const firstDay: Weekday = SUNDAY_FIRST.has(code)\n ? 7\n : SATURDAY_FIRST.has(code)\n ? 6\n : 1;\n const weekend: readonly Weekday[] =\n OTHER_WEEKENDS[code] ?? (FRIDAY_SATURDAY.has(code) ? [5, 6] : [6, 7]);\n return { firstDay, weekend };\n}\n\n/**\n * Week info from `source`: `getWeekInfo()`, else the `weekInfo` getter,\n * else the table by region (`maximize().region`).\n */\nexport function weekInfoOf(source: WeekInfoSource): WeekInfo {\n const info = source.getWeekInfo?.() ?? source.weekInfo;\n if (info !== undefined && isWeekday(info.firstDay)) {\n const weekend = (info.weekend ?? []).filter(isWeekday);\n return { firstDay: info.firstDay, weekend };\n }\n return regionWeekInfo(source.maximize().region);\n}\n\n/** Week info already read, by locale. */\nconst weekInfos = new Map<string, WeekInfo>();\n\n/**\n * The first day of week and the weekend in `locale`: Sunday in `en-US`,\n * Monday in `de-DE`, Saturday in `ar-EG`. Read from\n * `Intl.Locale#getWeekInfo`, else the getter some engines shipped before\n * it, else CLDR's table by region. A field's `firstDayOfWeek` overrides\n * it.\n */\nexport function weekInfo(locale: Intl.LocalesArgument): WeekInfo {\n const tag = new Intl.DateTimeFormat(locale).resolvedOptions().locale;\n let info = weekInfos.get(tag);\n if (info === undefined) {\n info = weekInfoOf(new Intl.Locale(tag));\n weekInfos.set(tag, info);\n }\n return info;\n}\n\n/**\n * The numbering a field uses unless told: `\"iso\"` when weeks start on\n * Monday, `\"simple\"` otherwise. `Intl` no longer reports a locale's\n * minimal days in the first week, so the numbering cannot come from it.\n */\nexport function defaultWeekNumbering(firstDay: Weekday): WeekNumbering {\n return firstDay === 1 ? \"iso\" : \"simple\";\n}\n\n/** The first day of the week `date` falls in, weeks starting on `firstDay`. */\nexport function startOfWeek(date: PlainDate, firstDay: Weekday): PlainDate {\n return addDays(date, -((dayOfWeek(date) - firstDay + 7) % 7));\n}\n\n/**\n * The week `date` falls in. ISO: weeks from Monday, the week belonging to\n * the year of its Thursday (`firstDay` is ignored). Simple: weeks from\n * `firstDay`, the week belonging to the year of its last day, week 1\n * holding 1 January. Days in the first or last week of the years 1 and\n * 9999 may have no week to count from and throw a `RangeError`.\n */\nexport function weekOf(\n date: PlainDate,\n numbering: WeekNumbering,\n firstDay: Weekday,\n): WeekOfYear {\n if (numbering === \"iso\") {\n const thursday = addDays(date, 4 - dayOfWeek(date));\n const { year } = dateParts(thursday);\n const week =\n Math.floor(daysBetween(plainDate(year, 1, 1), thursday) / 7) + 1;\n return { year, week };\n }\n const start = startOfWeek(date, firstDay);\n const { year } = dateParts(addDays(start, 6));\n const first = startOfWeek(plainDate(year, 1, 1), firstDay);\n return { year, week: daysBetween(first, start) / 7 + 1 };\n}\n","import { dateTimeFormat } from \"./format\";\nimport {\n defaultWeekNumbering,\n startOfWeek,\n weekOf,\n type WeekNumbering,\n type WeekOfYear,\n} from \"./week\";\nimport {\n addDays,\n compareDates,\n dateOfDayNumber,\n dateParts,\n dayNumberOf,\n dayOfWeek,\n daysInMonth,\n epochOfWallClock,\n MAX_YEAR,\n MIN_YEAR,\n plainDate,\n plainDateTime,\n type PlainDate,\n type Weekday,\n} from \"./values\";\n\n/** One day in a month grid. */\nexport interface CalendarDay {\n readonly date: PlainDate;\n readonly weekday: Weekday;\n /** False for the days of the months before and after that fill the first and last weeks. */\n readonly inMonth: boolean;\n}\n\n/** One row of a month grid: seven days and the week they make. */\nexport interface CalendarWeek {\n readonly week: WeekOfYear;\n readonly days: readonly CalendarDay[];\n}\n\n/** A month laid out for a calendar. */\nexport interface MonthGrid {\n readonly year: number;\n readonly month: number;\n /** The weekdays in column order, `firstDayOfWeek` first. */\n readonly weekdays: readonly Weekday[];\n /** Always six, so a calendar's height never changes from month to month. */\n readonly weeks: readonly CalendarWeek[];\n}\n\nexport interface MonthGridOptions {\n readonly firstDayOfWeek: Weekday;\n /** By default `\"iso\"` when weeks start on Monday, `\"simple\"` otherwise. */\n readonly weekNumbering?: WeekNumbering | undefined;\n}\n\n/**\n * `month` of `year` as six weeks of days from `firstDayOfWeek`, with the\n * days of the months either side filling the first and last weeks, and\n * each week's number. A row's number is its fourth day's week, which is\n * the week most of its days belong to even when the numbering's weeks\n * start on another day (ISO weeks in a Sunday-first grid). Throws a\n * `RangeError` for a month whose six weeks reach before 0001-01-01 or\n * after 9999-12-31.\n */\nexport function monthGrid(\n year: number,\n month: number,\n options: MonthGridOptions,\n): MonthGrid {\n const { firstDayOfWeek } = options;\n const numbering =\n options.weekNumbering ?? defaultWeekNumbering(firstDayOfWeek);\n const first = startOfWeek(plainDate(year, month, 1), firstDayOfWeek);\n const weeks = Array.from({ length: 6 }, (_, row): CalendarWeek => {\n const days = Array.from({ length: 7 }, (_, column): CalendarDay => {\n const date = addDays(first, row * 7 + column);\n const parts = dateParts(date);\n return {\n date,\n weekday: dayOfWeek(date),\n inMonth: parts.year === year && parts.month === month,\n };\n });\n const middle = days[3]?.date ?? first;\n return { week: weekOf(middle, numbering, firstDayOfWeek), days };\n });\n const weekdays = Array.from(\n { length: 7 },\n (_, column) => (((firstDayOfWeek - 1 + column) % 7) + 1) as Weekday,\n );\n return { year, month, weekdays, weeks };\n}\n\n/** A month a calendar shows, as `yyyy-mm`: \"2026-03\". */\nexport type CalendarMonth = `${number}-${number}`;\n\nconst MONTH_TEXT = /^(\\d{4})-(\\d{2})$/;\n\n// A month's six weeks reach into the months either side, so a calendar\n// shows no month before February of the year 1 or after November of 9999:\n// its grid never leaves the days a PlainDate holds.\nconst FIRST_MONTH = monthIndexOf(MIN_YEAR, 2);\nconst LAST_MONTH = monthIndexOf(MAX_YEAR, 11);\nconst FIRST_DAY = dayNumberOf(MIN_YEAR, 2, 1);\nconst LAST_DAY = dayNumberOf(MAX_YEAR, 11, 30);\n\n/** Months since the start of the year 0, so months add as numbers. */\nfunction monthIndexOf(year: number, month: number): number {\n return year * 12 + month - 1;\n}\n\nfunction monthIndex(month: CalendarMonth): number {\n const parts = calendarMonthParts(month);\n return monthIndexOf(parts.year, parts.month);\n}\n\nfunction monthAt(index: number): CalendarMonth {\n const year = Math.floor(index / 12);\n return calendarMonth(year, index - year * 12 + 1);\n}\n\nfunction dayNumber(date: PlainDate): number {\n const { year, month, day } = dateParts(date);\n return dayNumberOf(year, month, day);\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(Math.max(value, low), high);\n}\n\n/** Whether `value` is a month as a calendar holds one: \"2026-03\", years 1 to 9999. */\nexport function isCalendarMonth(value: unknown): value is CalendarMonth {\n if (typeof value !== \"string\") {\n return false;\n }\n const match = MONTH_TEXT.exec(value);\n const year = Number(match?.[1]);\n const month = Number(match?.[2]);\n return year >= MIN_YEAR && year <= MAX_YEAR && month >= 1 && month <= 12;\n}\n\n/** The month `month` (1 to 12) of `year`. Throws a `RangeError` for a month that does not exist. */\nexport function calendarMonth(year: number, month: number): CalendarMonth {\n const text = `${String(year).padStart(4, \"0\")}-${String(month).padStart(2, \"0\")}`;\n if (!Number.isInteger(year) || !isCalendarMonth(text)) {\n throw new RangeError(`${String(year)}-${String(month)} is not a month`);\n }\n return text;\n}\n\n/** A month's year and its number, 1 to 12. */\nexport function calendarMonthParts(month: CalendarMonth): {\n readonly year: number;\n readonly month: number;\n} {\n return { year: Number(month.slice(0, -3)), month: Number(month.slice(-2)) };\n}\n\n/** The month `date` falls in. */\nexport function monthOfDate(date: PlainDate): CalendarMonth {\n return date.slice(0, 7) as CalendarMonth;\n}\n\n/** Negative when `a` comes first, 0 for the same month, positive after. */\nexport function compareCalendarMonths(\n a: CalendarMonth,\n b: CalendarMonth,\n): number {\n return monthIndex(a) - monthIndex(b);\n}\n\n/** The days a calendar lets a user reach and choose. */\nexport interface CalendarLimits {\n /** The first day that can be chosen, inclusive. */\n readonly min?: PlainDate | undefined;\n /** The last day that can be chosen, inclusive. */\n readonly max?: PlainDate | undefined;\n /** Days that show but cannot be chosen. */\n readonly isDateDisabled?: ((date: PlainDate) => boolean) | undefined;\n}\n\n/** The first and last days focus can reach, as day numbers: the calendar's reach within `min` and `max`. */\nfunction dayReach(limits: CalendarLimits): {\n readonly first: number;\n readonly last: number;\n} {\n const first = Math.max(\n FIRST_DAY,\n limits.min === undefined ? FIRST_DAY : dayNumber(limits.min),\n );\n const last = Math.min(\n LAST_DAY,\n limits.max === undefined ? LAST_DAY : dayNumber(limits.max),\n );\n return { first: Math.min(first, LAST_DAY), last: Math.max(first, last) };\n}\n\n/** The first and last months that hold a day focus can reach, as month indexes. */\nfunction monthReach(limits: CalendarLimits): {\n readonly first: number;\n readonly last: number;\n} {\n const { first, last } = dayReach(limits);\n return {\n first: monthIndex(monthOfDate(dateOfDayNumber(first))),\n last: monthIndex(monthOfDate(dateOfDayNumber(last))),\n };\n}\n\n/**\n * Whether a calendar shows `date` as one that cannot be chosen: before\n * `min`, after `max`, marked by `isDateDisabled`, or outside the months a\n * calendar shows (before February of the year 1, after November of 9999).\n */\nexport function isCalendarDayDisabled(\n date: PlainDate,\n limits: CalendarLimits,\n): boolean {\n const day = dayNumber(date);\n return (\n day < FIRST_DAY ||\n day > LAST_DAY ||\n (limits.min !== undefined && compareDates(date, limits.min) < 0) ||\n (limits.max !== undefined && compareDates(date, limits.max) > 0) ||\n limits.isDateDisabled?.(date) === true\n );\n}\n\n/** Whether month `month` of `year` holds no day within the calendar's limits, so its month view disables it. */\nexport function isCalendarMonthDisabled(\n year: number,\n month: number,\n limits: CalendarLimits,\n): boolean {\n const { first, last } = monthReach(limits);\n const index = monthIndexOf(year, month);\n return index < first || index > last;\n}\n\n/**\n * `month` moved where a calendar showing `visibleMonths` months from it\n * can be: no earlier than the month of `min`, and its last month no later\n * than the month of `max`, nor than November of 9999.\n */\nexport function clampCalendarMonth(\n month: CalendarMonth,\n limits: CalendarLimits,\n visibleMonths = 1,\n): CalendarMonth {\n return clampMonthIndex(monthIndex(month), limits, visibleMonths);\n}\n\n/** `clampCalendarMonth` for a month index, which may lie outside the years a month holds. */\nfunction clampMonthIndex(\n index: number,\n limits: CalendarLimits,\n visibleMonths: number,\n): CalendarMonth {\n const { first, last } = monthReach(limits);\n const lastStart = Math.min(\n Math.max(first, last - (visibleMonths - 1)),\n LAST_MONTH - (visibleMonths - 1),\n );\n return monthAt(clamp(index, Math.min(first, lastStart), lastStart));\n}\n\n/** `date` moved into the days focus can reach. */\nexport function clampCalendarDate(\n date: PlainDate,\n limits: CalendarLimits,\n): PlainDate {\n const { first, last } = dayReach(limits);\n return dateOfDayNumber(clamp(dayNumber(date), first, last));\n}\n\n/** `date`'s day of the month in `month`, clamped to the month's length: the 31st in February is the 28th or 29th. */\nexport function sameDayIn(month: CalendarMonth, date: PlainDate): PlainDate {\n const parts = calendarMonthParts(month);\n const { day } = dateParts(date);\n return plainDate(\n parts.year,\n parts.month,\n Math.min(day, daysInMonth(parts.year, parts.month)),\n );\n}\n\n/** The years a calendar's month view lists: from `min` to `max`, else 100 either side of `year`. */\nexport function calendarYears(\n year: number,\n limits: CalendarLimits,\n): { readonly first: number; readonly last: number } {\n const { first, last } = monthReach(limits);\n const firstYear = Math.floor(first / 12);\n const lastYear = Math.floor(last / 12);\n return {\n first:\n limits.min === undefined ? Math.max(firstYear, year - 100) : firstYear,\n last: limits.max === undefined ? Math.min(lastYear, year + 100) : lastYear,\n };\n}\n\n/** Where a key moves focus in a calendar's grid. */\nexport type CalendarMove =\n | \"previousDay\"\n | \"nextDay\"\n | \"previousWeek\"\n | \"nextWeek\"\n | \"startOfWeek\"\n | \"endOfWeek\"\n | \"previousMonth\"\n | \"nextMonth\"\n | \"previousYear\"\n | \"nextYear\";\n\n/**\n * The day `move` takes focus to from `date`, weeks starting on\n * `firstDayOfWeek`: a day or a week on, the week's first or last day, or\n * the same day of the month or year before or after (clamped to the\n * month's length). Clamped to the days focus can reach, so at the edge a\n * key does nothing.\n */\nexport function moveCalendarDate(\n date: PlainDate,\n move: CalendarMove,\n firstDayOfWeek: Weekday,\n limits: CalendarLimits,\n): PlainDate {\n const day = dayNumber(date);\n const { year, month, day: dayOfMonth } = dateParts(date);\n const sameDayMonthsOn = (months: number): number => {\n const index = monthIndexOf(year, month) + months;\n const nextYear = Math.floor(index / 12);\n const nextMonth = index - nextYear * 12 + 1;\n return dayNumberOf(\n nextYear,\n nextMonth,\n Math.min(dayOfMonth, daysInMonth(nextYear, nextMonth)),\n );\n };\n const intoWeek = (dayOfWeek(date) - firstDayOfWeek + 7) % 7;\n const targets: Readonly<Record<CalendarMove, () => number>> = {\n previousDay: () => day - 1,\n nextDay: () => day + 1,\n previousWeek: () => day - 7,\n nextWeek: () => day + 7,\n startOfWeek: () => day - intoWeek,\n endOfWeek: () => day + 6 - intoWeek,\n previousMonth: () => sameDayMonthsOn(-1),\n nextMonth: () => sameDayMonthsOn(1),\n previousYear: () => sameDayMonthsOn(-12),\n nextYear: () => sameDayMonthsOn(12),\n };\n const { first, last } = dayReach(limits);\n return dateOfDayNumber(clamp(targets[move](), first, last));\n}\n\n/** What a calendar's panel shows: the days of its months, or its months and years to jump to. */\nexport type CalendarView =\n | { readonly kind: \"days\" }\n | {\n readonly kind: \"months\";\n /** The year whose months show. */\n readonly year: number;\n /** Which of the months shown the jump replaces, 0 for the first. */\n readonly panel: number;\n };\n\n/** Where a calendar is: the months it shows, the day focus is on, its view. */\nexport interface CalendarState {\n /** The first month shown. */\n readonly month: CalendarMonth;\n /** The day that takes focus in the grid: always in a month shown. */\n readonly focused: PlainDate;\n readonly view: CalendarView;\n}\n\n/** What the calendar reducer is told. */\nexport interface CalendarContext {\n readonly firstDayOfWeek: Weekday;\n /** How many months show side by side. */\n readonly visibleMonths: number;\n readonly limits: CalendarLimits;\n}\n\n/** What can happen to a calendar. */\nexport type CalendarAction =\n /** A key moved focus in the grid. */\n | { readonly type: \"move\"; readonly move: CalendarMove }\n /** A day took focus: a click, or a day of another month chosen. */\n | { readonly type: \"focus\"; readonly date: PlainDate }\n /** The previous or next month button: the months shown move by `months`. */\n | { readonly type: \"page\"; readonly months: number }\n /** The app's `month`: shown first. */\n | { readonly type: \"show\"; readonly month: CalendarMonth }\n /** A month's title: the month view opens in its place. */\n | { readonly type: \"openMonths\"; readonly panel: number }\n /** A year chosen in the month view. */\n | { readonly type: \"showYear\"; readonly year: number }\n /** A month (1 to 12) of the view's year chosen: the days show again, from it. */\n | { readonly type: \"chooseMonth\"; readonly month: number }\n /** Escape in the month view: the days show again, unchanged. */\n | { readonly type: \"closeMonths\" };\n\nconst DAYS: CalendarView = { kind: \"days\" };\n\n/** `focused` with the first month moved, as little as it takes, for `focused` to be shown. */\nfunction reveal(\n month: CalendarMonth,\n focused: PlainDate,\n context: CalendarContext,\n): Pick<CalendarState, \"month\" | \"focused\"> {\n const start = monthIndex(month);\n const index = monthIndex(monthOfDate(focused));\n const visible = context.visibleMonths;\n const first =\n index < start\n ? index\n : index > start + visible - 1\n ? index - visible + 1\n : start;\n return {\n month: clampMonthIndex(first, context.limits, visible),\n focused,\n };\n}\n\n/** Whether `date` falls in one of the months shown from `month`. */\nfunction isShown(\n date: PlainDate,\n month: CalendarMonth,\n visibleMonths: number,\n): boolean {\n const offset = monthIndex(monthOfDate(date)) - monthIndex(month);\n return offset >= 0 && offset < visibleMonths;\n}\n\n/**\n * Where a calendar starts: showing `month` (the app's), else the month of\n * `focus`, with focus on `focus` when it is shown, else on its day of the\n * month in the first month shown.\n */\nexport function calendarStart(\n focus: PlainDate,\n month: CalendarMonth | undefined,\n context: CalendarContext,\n): CalendarState {\n const { limits, visibleMonths } = context;\n const target = clampCalendarDate(focus, limits);\n const first = clampCalendarMonth(\n month ?? monthOfDate(target),\n limits,\n visibleMonths,\n );\n const focused = isShown(target, first, visibleMonths)\n ? target\n : clampCalendarDate(sameDayIn(first, target), limits);\n return { ...reveal(first, focused, context), view: DAYS };\n}\n\n/**\n * The calendar after `action`: every way focus moves between days and\n * months, and the month view opens and closes. Focus stays on a day in a\n * month shown and within the limits; the months shown move as little as\n * it takes.\n */\nexport function calendarReducer(\n state: CalendarState,\n action: CalendarAction,\n context: CalendarContext,\n): CalendarState {\n const { limits, firstDayOfWeek, visibleMonths } = context;\n switch (action.type) {\n case \"move\": {\n const focused = moveCalendarDate(\n state.focused,\n action.move,\n firstDayOfWeek,\n limits,\n );\n return { ...state, ...reveal(state.month, focused, context) };\n }\n case \"focus\":\n return {\n ...state,\n ...reveal(state.month, clampCalendarDate(action.date, limits), context),\n };\n case \"page\": {\n const month = clampMonthIndex(\n monthIndex(state.month) + action.months,\n limits,\n visibleMonths,\n );\n const panel =\n monthIndex(monthOfDate(state.focused)) - monthIndex(state.month);\n const focused = clampCalendarDate(\n sameDayIn(monthAt(monthIndex(month) + panel), state.focused),\n limits,\n );\n return { ...state, ...reveal(month, focused, context) };\n }\n case \"show\": {\n const month = clampCalendarMonth(action.month, limits, visibleMonths);\n const focused = isShown(state.focused, month, visibleMonths)\n ? state.focused\n : clampCalendarDate(sameDayIn(month, state.focused), limits);\n return { ...state, ...reveal(month, focused, context) };\n }\n case \"openMonths\": {\n const panel = clamp(action.panel, 0, visibleMonths - 1);\n const { year } = calendarMonthParts(\n monthAt(monthIndex(state.month) + panel),\n );\n return { ...state, view: { kind: \"months\", year, panel } };\n }\n case \"showYear\":\n return state.view.kind === \"months\"\n ? {\n ...state,\n view: {\n ...state.view,\n year: clamp(action.year, MIN_YEAR, MAX_YEAR),\n },\n }\n : state;\n case \"chooseMonth\": {\n if (state.view.kind !== \"months\") {\n return state;\n }\n const { year, panel } = state.view;\n const chosen = monthAt(\n clamp(monthIndexOf(year, action.month), FIRST_MONTH, LAST_MONTH),\n );\n const month = clampMonthIndex(\n monthIndex(chosen) - panel,\n limits,\n visibleMonths,\n );\n const focused = clampCalendarDate(\n sameDayIn(chosen, state.focused),\n limits,\n );\n return { ...reveal(month, focused, context), view: DAYS };\n }\n case \"closeMonths\":\n return state.view.kind === \"days\" ? state : { ...state, view: DAYS };\n }\n}\n\n/** A wall clock's day at midnight, as `Intl` formats it in UTC. */\nfunction formatDay(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n options: Intl.DateTimeFormatOptions,\n): string {\n return dateTimeFormat(locale, { ...options, timeZone: \"UTC\" }).format(\n epochOfWallClock(plainDateTime(date, \"00:00\")),\n );\n}\n\n// A Monday, so weekday `n` is `n - 1` days after it.\nconst A_MONDAY: PlainDate = \"2026-03-09\";\n\n/** A month as a calendar's title writes it: \"March 2026\", \"März 2026\". */\nexport function formatCalendarMonth(\n month: CalendarMonth,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(sameDayIn(month, \"2026-01-01\"), locale, {\n month: \"long\",\n year: \"numeric\",\n });\n}\n\n/** A month's name alone: \"Mar\", \"March\". */\nexport function formatMonthName(\n month: number,\n locale: Intl.LocalesArgument,\n width: \"short\" | \"long\",\n): string {\n return formatDay(plainDate(2026, month, 1), locale, { month: width });\n}\n\n/** A weekday's name: \"M\", \"Mon\", \"Monday\". */\nexport function formatWeekday(\n weekday: Weekday,\n locale: Intl.LocalesArgument,\n width: \"narrow\" | \"short\" | \"long\",\n): string {\n return formatDay(addDays(A_MONDAY, weekday - 1), locale, {\n weekday: width,\n });\n}\n\n/** A day of the month as a calendar's cell writes it, in the locale's digits: \"14\". */\nexport function formatDayOfMonth(\n date: PlainDate,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(date, locale, { day: \"numeric\" });\n}\n\n/** A year as a calendar's year list writes it, in the locale's digits. */\nexport function formatCalendarYear(\n year: number,\n locale: Intl.LocalesArgument,\n): string {\n return formatDay(plainDate(year, 6, 1), locale, { year: \"numeric\" });\n}\n","const DIGIT = /^\\p{Nd}$/u;\n\n/** Whether `char` is one Unicode decimal digit, in any script. */\nexport function isDigit(char: string): boolean {\n return DIGIT.test(char);\n}\n\nfunction isDigitCode(code: number): boolean {\n return code >= 0 && isDigit(String.fromCodePoint(code));\n}\n\n/**\n * The value of the decimal digit `char`. Unicode keeps every decimal digit\n * in a run of ten from zero to nine, and runs that touch (the mathematical\n * digits) follow on from each other, so the value is the digit's distance\n * from the start of its run, modulo 10: no table needed.\n */\nexport function digitValue(char: string): number {\n const code = char.codePointAt(0) ?? 0;\n let start = code;\n while (isDigitCode(start - 1)) {\n start -= 1;\n }\n return (code - start) % 10;\n}\n\n/** Intl's numbering systems by the code point of their zero, built on first use. */\nlet systemsByZero: ReadonlyMap<number, string> | undefined;\n\nfunction numberingSystems(): ReadonlyMap<number, string> {\n if (systemsByZero === undefined) {\n const systems = new Map<number, string>();\n for (const system of Intl.supportedValuesOf(\"numberingSystem\")) {\n const format = new Intl.NumberFormat(\"en\", { numberingSystem: system });\n const zero = format.format(0);\n // An engine without the system falls back to Latin digits.\n if (\n format.resolvedOptions().numberingSystem === system &&\n isDigit(zero)\n ) {\n systems.set(zero.codePointAt(0) ?? 0, system);\n }\n }\n systemsByZero = systems;\n }\n return systemsByZero;\n}\n\n/** The Intl numbering system of the digit `char` (`\"latn\"`, `\"arab\"`, `\"fullwide\"`), or `\"unknown\"`. */\nexport function numberingSystemOf(char: string): string {\n const zero = (char.codePointAt(0) ?? 0) - digitValue(char);\n return numberingSystems().get(zero) ?? \"unknown\";\n}\n","import { digitValue, isDigit } from \"../number/digits\";\n\nconst BIDI_MARKS = /[\\u{200E}\\u{200F}\\u{061C}\\u{2066}-\\u{2069}]/gu;\nconst SPACES = /[\\u{00A0}\\u{2007}\\u{2009}\\u{202F}\\u{3000}]/gu;\nconst FULL_WIDTH = /[\\u{FF01}-\\u{FF5E}]/gu;\n\n/** `text` with every decimal digit, in any script, written as ASCII. */\nexport function asciiDigits(text: string): string {\n let result = \"\";\n for (const char of text) {\n result += isDigit(char) ? String(digitValue(char)) : char;\n }\n return result;\n}\n\n/**\n * `text` as the date readers take it: trimmed, direction marks dropped,\n * no-break, narrow and thin spaces as plain spaces, full-width forms\n * (which Chinese and Japanese input methods type) as ASCII, and every\n * digit as ASCII.\n */\nexport function cleanDateText(text: string): string {\n return asciiDigits(\n text\n .replace(BIDI_MARKS, \"\")\n .replace(SPACES, \" \")\n .replace(FULL_WIDTH, (char) =>\n String.fromCharCode(char.charCodeAt(0) - 0xfee0),\n ),\n ).trim();\n}\n\n/** `text` lower-cased with its accents removed and a trailing dot dropped, for matching words. */\nexport function foldWord(text: string): string {\n return text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .toLocaleLowerCase(\"en\")\n .replace(/\\.$/, \"\");\n}\n","import { localeKey } from \"../localeKey\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { digitValue, isDigit } from \"../number/digits\";\nimport { dateTimeFormat } from \"./format\";\nimport { foldWord } from \"./text\";\n\n/** A segment of a date, time or date-time field. */\nexport type DateSegmentType =\n \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"dayPeriod\";\n\n/** Any segment a field types in: a date's, or a period's quarter or fiscal period. */\nexport type SegmentType = DateSegmentType | \"quarter\" | \"period\";\n\n/** One segment of a layout. */\nexport interface DateSegment {\n readonly type: SegmentType;\n /** The lowest and highest value it takes: month 1 to 12, hour 1 to 12 in a 12-hour cycle, 0 and 1 for the day period. */\n readonly min: number;\n readonly max: number;\n /** Characters it is shown with once left: 2 for \"03\", 1 for \"3\", 4 for a year. */\n readonly width: number;\n /** Shown while empty: \"mm\", \"dd\", \"yyyy\", \"--\" (messages). */\n readonly placeholder: string;\n /** Read with the field's label: \"month\" (messages). */\n readonly label: string;\n}\n\n/** One part of a layout: a segment (by its index in `segments`), or text drawn between them. */\nexport type DateLayoutPart =\n | { readonly kind: \"segment\"; readonly index: number }\n | { readonly kind: \"literal\"; readonly text: string };\n\n/** How a field lays out its segments in a locale. */\nexport interface DateLayout {\n /** In the order `Intl.DateTimeFormat#formatToParts` gives them. */\n readonly parts: readonly DateLayoutPart[];\n /** The segments alone, in typing order. */\n readonly segments: readonly DateSegment[];\n readonly hourCycle: \"h11\" | \"h12\" | \"h23\" | \"h24\" | null;\n /** The locale's two day-period texts, morning first (\"AM\", \"PM\"). */\n readonly dayPeriods: readonly [string, string];\n /** The ten digits the locale writes, \"0\" to \"9\" first. */\n readonly digits: string;\n}\n\n/** What a field's layout is made for. */\nexport type DateLayoutFields = \"date\" | \"time\" | \"dateTime\" | \"month\" | \"year\";\n\nexport interface DateLayoutOptions {\n readonly locale: Intl.LocalesArgument;\n readonly fields: DateLayoutFields;\n /** The locale's hour cycle unless given. */\n readonly hourCycle?: \"h12\" | \"h23\" | undefined;\n /** `\"minute\"` by default; `\"second\"` adds a seconds segment. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n}\n\n/** A layout before its segments are named by the messages. */\nexport interface LayoutShape {\n readonly parts: readonly (\n | { readonly kind: \"segment\"; readonly type: SegmentType }\n | { readonly kind: \"literal\"; readonly text: string }\n )[];\n readonly widths: Partial<Record<SegmentType, number>>;\n readonly hourCycle: DateLayout[\"hourCycle\"];\n readonly dayPeriods: readonly [string, string];\n readonly digits: string;\n}\n\nconst SEGMENT_TYPES: ReadonlySet<string> = new Set<SegmentType>([\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\nfunction isSegmentType(type: string): type is DateSegmentType {\n return SEGMENT_TYPES.has(type);\n}\n\n/** 14 March 2026, 15:05:09, the moment a layout is read from. */\nconst SAMPLE = Date.UTC(2026, 2, 14, 15, 5, 9);\n/** 2 January 2026, 03:04:05: one-digit values, to see which segments pad. */\nconst SHORT_SAMPLE = Date.UTC(2026, 0, 2, 3, 4, 5);\nconst MORNING = Date.UTC(2026, 0, 2, 3);\n\nfunction intlOptions(options: DateLayoutOptions): Intl.DateTimeFormatOptions {\n const date: Intl.DateTimeFormatOptions = {\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n };\n const time: Intl.DateTimeFormatOptions = {\n hour: \"numeric\",\n minute: \"2-digit\",\n ...(options.precision === \"second\" ? { second: \"2-digit\" } : {}),\n ...(options.hourCycle === undefined\n ? {}\n : { hourCycle: options.hourCycle }),\n };\n const fields: Record<DateLayoutFields, Intl.DateTimeFormatOptions> = {\n date,\n time,\n dateTime: { ...date, ...time },\n month: { year: \"numeric\", month: \"2-digit\" },\n year: { year: \"numeric\" },\n };\n return {\n ...fields[options.fields],\n timeZone: \"UTC\",\n ...(options.numberingSystem === undefined\n ? {}\n : { numberingSystem: options.numberingSystem }),\n };\n}\n\n/** The ten digits of `numberingSystem`, \"0\" to \"9\". */\nfunction digitsOf(numberingSystem: string): string {\n const format = new Intl.NumberFormat(\"en\", {\n numberingSystem,\n useGrouping: false,\n });\n return Array.from({ length: 10 }, (_, digit) => format.format(digit)).join(\n \"\",\n );\n}\n\n/** The day-period texts `locale` writes beside a 12-hour hour. */\nfunction dayPeriodsOf(\n locale: Intl.LocalesArgument,\n numberingSystem: string,\n): readonly [string, string] {\n const format = dateTimeFormat(locale, {\n hour: \"numeric\",\n hourCycle: \"h12\",\n timeZone: \"UTC\",\n numberingSystem,\n });\n const text = (moment: number) =>\n format.formatToParts(moment).find((part) => part.type === \"dayPeriod\")\n ?.value ?? \"\";\n return [text(MORNING) || \"AM\", text(SAMPLE) || \"PM\"];\n}\n\nfunction readShape(options: DateLayoutOptions): LayoutShape {\n const format = dateTimeFormat(options.locale, intlOptions(options));\n const resolved = format.resolvedOptions();\n const parts: LayoutShape[\"parts\"][number][] = [];\n for (const part of format.formatToParts(SAMPLE)) {\n if (part.type === \"literal\") {\n const last = parts.at(-1);\n if (last?.kind === \"literal\") {\n parts[parts.length - 1] = {\n kind: \"literal\",\n text: last.text + part.value,\n };\n } else {\n parts.push({ kind: \"literal\", text: part.value });\n }\n } else if (isSegmentType(part.type)) {\n parts.push({ kind: \"segment\", type: part.type });\n }\n }\n const widths: Partial<Record<SegmentType, number>> = {};\n for (const part of format.formatToParts(SHORT_SAMPLE)) {\n if (isSegmentType(part.type)) {\n widths[part.type] = part.value.length;\n }\n }\n return {\n parts,\n widths,\n hourCycle: resolved.hourCycle ?? null,\n dayPeriods: dayPeriodsOf(options.locale, resolved.numberingSystem),\n digits: digitsOf(resolved.numberingSystem),\n };\n}\n\n/** The range a segment of `type` takes in a layout with `hourCycle`. */\nfunction rangeOf(\n type: SegmentType,\n hourCycle: DateLayout[\"hourCycle\"],\n): readonly [number, number] {\n switch (type) {\n case \"year\":\n return [1, 9999];\n case \"month\":\n case \"period\":\n return [1, 12];\n case \"day\":\n return [1, 31];\n case \"quarter\":\n return [1, 4];\n case \"dayPeriod\":\n return [0, 1];\n case \"minute\":\n case \"second\":\n return [0, 59];\n case \"hour\":\n switch (hourCycle) {\n case \"h11\":\n return [0, 11];\n case \"h12\":\n return [1, 12];\n case \"h24\":\n return [1, 24];\n default:\n return [0, 23];\n }\n }\n}\n\n/** Names a shape's segments from `messages`, making the layout. */\nexport function layoutOf(\n shape: LayoutShape,\n messages: FormsMessages,\n): DateLayout {\n const segments: DateSegment[] = [];\n const parts = shape.parts.map((part): DateLayoutPart => {\n if (part.kind === \"literal\") {\n return part;\n }\n const [min, max] = rangeOf(part.type, shape.hourCycle);\n const width =\n part.type === \"year\"\n ? 4\n : part.type === \"dayPeriod\"\n ? Math.max(...shape.dayPeriods.map((text) => text.length))\n : Math.max(shape.widths[part.type] ?? 2, 1);\n segments.push({\n type: part.type,\n min,\n max,\n width,\n placeholder: messages.dateSegmentPlaceholder(part.type),\n label: messages.dateSegmentName(part.type),\n });\n return { kind: \"segment\", index: segments.length - 1 };\n });\n return {\n parts,\n segments,\n hourCycle: shape.hourCycle,\n dayPeriods: shape.dayPeriods,\n digits: shape.digits,\n };\n}\n\n/** Shapes already read, by locale and options: reading one builds several formatters. */\nconst shapes = new Map<string, LayoutShape>();\n/** Layouts already named, per messages object. */\nconst layouts = new WeakMap<FormsMessages, Map<string, DateLayout>>();\n\n/**\n * How a field lays out its segments in a locale, read from\n * `Intl.DateTimeFormat#formatToParts` for a sample moment (14 March 2026,\n * 15:05:09): each year, month, day, hour, minute, second or day-period\n * part becomes a segment, each literal the text drawn between them, in\n * the order the engine gives. Whether a segment pads is read from a second\n * sample with one-digit values, so `en-US` hours stay unpadded (\"3:05 PM\").\n * Nothing is written per locale: each engine shows its own. Gregorian\n * only. Cached per locale, options and messages.\n */\nexport function dateLayout(\n options: DateLayoutOptions,\n messages: FormsMessages,\n): DateLayout {\n const key = [\n localeKey(options.locale),\n options.fields,\n options.hourCycle ?? \"\",\n options.precision ?? \"\",\n options.numberingSystem ?? \"\",\n ].join(\"|\");\n let named = layouts.get(messages);\n if (named === undefined) {\n named = new Map();\n layouts.set(messages, named);\n }\n let layout = named.get(key);\n if (layout === undefined) {\n let shape = shapes.get(key);\n if (shape === undefined) {\n shape = readShape(options);\n shapes.set(key, shape);\n }\n layout = layoutOf(shape, messages);\n named.set(key, layout);\n }\n return layout;\n}\n\n/** The index of the first segment of `type`, or -1. */\nexport function segmentIndex(layout: DateLayout, type: SegmentType): number {\n return layout.segments.findIndex((segment) => segment.type === type);\n}\n\n/** `value` written in the layout's digits, padded to `width`. */\nexport function writeDigits(\n layout: DateLayout,\n value: number,\n width: number,\n): string {\n return String(value)\n .padStart(width, \"0\")\n .replace(/\\d/g, (digit) => layout.digits[Number(digit)] ?? digit);\n}\n\n/**\n * Segment `index` written for `value`: digits in the layout's digits,\n * padded to the segment's width; a day period's text for 0 or 1.\n */\nexport function writeSegment(\n layout: DateLayout,\n index: number,\n value: number,\n): string {\n const segment = layout.segments[index];\n if (segment === undefined) {\n return \"\";\n }\n return segment.type === \"dayPeriod\"\n ? layout.dayPeriods[value === 0 ? 0 : 1]\n : writeDigits(layout, value, segment.width);\n}\n\n/** The day period `text` names: 0 for the morning, 1 for the afternoon; the locale's texts or `a`, `am`, `p`, `pm`. */\nexport function dayPeriodOf(layout: DateLayout, text: string): 0 | 1 | null {\n const folded = foldWord(text).replace(/\\./g, \"\");\n const [morning, afternoon] = layout.dayPeriods.map((period) =>\n foldWord(period).replace(/\\./g, \"\"),\n );\n if (folded === \"\") {\n return null;\n }\n if (folded === morning || folded === \"am\" || folded === \"a\") {\n return 0;\n }\n if (folded === afternoon || folded === \"pm\" || folded === \"p\") {\n return 1;\n }\n return null;\n}\n\n/** The number segment `index`'s text holds, digits in any script; `null` while empty or for text that is not its value. */\nexport function segmentValue(\n layout: DateLayout,\n index: number,\n text: string,\n): number | null {\n const segment = layout.segments[index];\n if (segment === undefined || text === \"\") {\n return null;\n }\n if (segment.type === \"dayPeriod\") {\n return dayPeriodOf(layout, text);\n }\n let value = 0;\n for (const char of text) {\n if (!isDigit(char)) {\n return null;\n }\n value = value * 10 + digitValue(char);\n }\n return value;\n}\n\n/** How many digits segment `index` takes at most: 4 for a year, 2 for a month. */\nexport function maxDigits(layout: DateLayout, index: number): number {\n const segment = layout.segments[index];\n return segment === undefined ? 0 : String(segment.max).length;\n}\n\n/**\n * The field's text for these segment texts: joined by the layout's\n * literals, an empty segment written as nothing (\"03//2026\"), and `\"\"`\n * when every segment is empty.\n */\nexport function joinSegments(\n layout: DateLayout,\n texts: readonly string[],\n): string {\n if (texts.every((text) => text === \"\")) {\n return \"\";\n }\n return layout.parts\n .map((part) =>\n part.kind === \"literal\" ? part.text : (texts[part.index] ?? \"\"),\n )\n .join(\"\");\n}\n\n/** An hour of the day (0 to 23) as an hour segment in `hourCycle` shows it: 15 is 3 in a 12-hour cycle. */\nexport function shownHour(\n hour: number,\n hourCycle: DateLayout[\"hourCycle\"],\n): number {\n switch (hourCycle) {\n case \"h12\":\n return hour % 12 === 0 ? 12 : hour % 12;\n case \"h11\":\n return hour % 12;\n case \"h24\":\n return hour === 0 ? 24 : hour;\n default:\n return hour;\n }\n}\n\n/** The field's text for each segment type's number: written and joined; a segment with no number stays empty. */\nexport function formatSegments(\n layout: DateLayout,\n values: Partial<Record<SegmentType, number>>,\n): string {\n return joinSegments(\n layout,\n layout.segments.map((segment, index) => {\n const value = values[segment.type];\n return value === undefined ? \"\" : writeSegment(layout, index, value);\n }),\n );\n}\n\n/** The length of the segment text at `position` in `text`, or -1 when none fits. */\nfunction segmentLength(\n layout: DateLayout,\n index: number,\n text: string,\n position: number,\n): number {\n const segment = layout.segments[index];\n if (segment?.type === \"dayPeriod\") {\n const match = layout.dayPeriods\n .filter(\n (period) =>\n foldWord(text.slice(position, position + period.length)) ===\n foldWord(period),\n )\n .sort((a, b) => b.length - a.length)[0];\n return match?.length ?? 0;\n }\n let length = 0;\n for (const char of text.slice(position)) {\n if (!isDigit(char)) {\n break;\n }\n length += char.length;\n }\n return length <= maxDigits(layout, index) ? length : -1;\n}\n\n/**\n * Each segment's text in the field's text, or `null` for text that is\n * not segments (free text: a shortcut, a pasted date in another form).\n * `\"\"` is every segment empty.\n */\nexport function splitSegments(\n layout: DateLayout,\n text: string,\n): readonly string[] | null {\n const texts = layout.segments.map(() => \"\");\n if (text === \"\") {\n return texts;\n }\n let position = 0;\n for (const part of layout.parts) {\n if (part.kind === \"literal\") {\n if (!text.startsWith(part.text, position)) {\n return null;\n }\n position += part.text.length;\n continue;\n }\n const length = segmentLength(layout, part.index, text, position);\n if (length < 0) {\n return null;\n }\n texts[part.index] = text.slice(position, position + length);\n position += length;\n }\n return position === text.length ? texts : null;\n}\n\n/** Where each segment's text sits in the field's text, as `[start, end)`; `null` for text that is not segments. */\nexport function segmentSpans(\n layout: DateLayout,\n text: string,\n): readonly (readonly [number, number])[] | null {\n const texts = splitSegments(layout, text);\n if (texts === null) {\n return null;\n }\n const spans: (readonly [number, number])[] = [];\n let position = 0;\n for (const part of layout.parts) {\n if (part.kind === \"literal\") {\n position += text === \"\" ? 0 : part.text.length;\n } else {\n const length = texts[part.index]?.length ?? 0;\n spans[part.index] = [position, position + length];\n position += length;\n }\n }\n return spans;\n}\n\n/** A stretch of a layout's parts drawn together. */\nexport interface SegmentRun {\n /** Indexes into the layout's `parts`, in order. */\n readonly parts: readonly number[];\n /** Whether the renderer wraps it in `dir=\"ltr\"`: a run of several number segments in a right-to-left field. */\n readonly leftToRight: boolean;\n}\n\nconst RIGHT_TO_LEFT =\n /[\\u{0590}-\\u{08FF}\\u{FB1D}-\\u{FDFF}\\u{FE70}-\\u{FEFF}\\u{200F}\\u{061C}]/u;\n\n/**\n * The layout's parts grouped into runs for a field written in\n * `direction`. A right-to-left field cannot simply reverse its segments:\n * `he-IL` and `fa-IR` write a date left to right even in right-to-left\n * text (digits and `.` or `/` form one number run under the Unicode bidi\n * rules), while `ar-EG` leads each `/` with a right-to-left mark, so its\n * date runs right to left. So consecutive number segments joined by\n * literals with no right-to-left character or mark form one run, read\n * left to right; a literal with one, or a right-to-left day period,\n * breaks it. Every other part is a run of its own. A left-to-right field\n * is one run.\n */\nexport function segmentRuns(\n layout: DateLayout,\n direction: \"ltr\" | \"rtl\",\n): readonly SegmentRun[] {\n const all = layout.parts.map((_, index) => index);\n if (direction === \"ltr\") {\n return [{ parts: all, leftToRight: false }];\n }\n const joins = (index: number): boolean => {\n const part = layout.parts[index];\n if (part === undefined) {\n return false;\n }\n if (part.kind === \"literal\") {\n return !RIGHT_TO_LEFT.test(part.text);\n }\n return (\n layout.segments[part.index]?.type !== \"dayPeriod\" ||\n !layout.dayPeriods.some((period) => RIGHT_TO_LEFT.test(period))\n );\n };\n const isSegment = (index: number) => layout.parts[index]?.kind === \"segment\";\n const runs: SegmentRun[] = [];\n let index = 0;\n while (index < all.length) {\n if (!isSegment(index) || !joins(index)) {\n runs.push({ parts: [index], leftToRight: false });\n index += 1;\n continue;\n }\n // Extend over joining parts, ending on the last joining segment.\n let end = index;\n for (let next = index + 1; next < all.length && joins(next); next += 1) {\n if (isSegment(next)) {\n end = next;\n }\n }\n const parts = all.slice(index, end + 1);\n runs.push({\n parts,\n leftToRight: parts.filter(isSegment).length > 1,\n });\n index = end + 1;\n }\n return runs;\n}\n","import { cleanDateText } from \"./text\";\nimport {\n addDays,\n addMonths,\n addYears,\n endOfMonth,\n startOfMonth,\n type PlainDate,\n} from \"./values\";\n\n// shortcut := \"t\" | anchor | offset [anchor]\n// offset := sign digits [unit] sign: +, - or U+2212; unit: d (default) w m y\n// anchor := \"s\" | \"e\" start or end of the month\nconst SHORTCUT = /^(?:(t)|([se])|([+\\-\\u{2212}])(\\d+)([dwmy])?([se])?)$/iu;\n\n/** `date` moved `count` units (`d`, `w`, `m` or `y`) on, back when `count` is negative. */\nfunction offset(date: PlainDate, count: number, unit: string): PlainDate {\n switch (unit) {\n case \"w\":\n return addDays(date, count * 7);\n case \"m\":\n return addMonths(date, count);\n case \"y\":\n return addYears(date, count);\n default:\n return addDays(date, count);\n }\n}\n\nfunction anchored(date: PlainDate, anchor: string | undefined): PlainDate {\n if (anchor === undefined) {\n return date;\n }\n return anchor === \"s\" ? startOfMonth(date) : endOfMonth(date);\n}\n\n/**\n * The day a typed shortcut names, always counted from `today`, never from\n * the field's value: `t` today; `+3` or `+3d` three days on, `-1w` a week\n * back, `+2m` and `-1y` months and years (clamped to the month's length);\n * `s` and `e` the start and end of this month; an offset then an anchor,\n * `+1ms` the start of next month, `-1me` the end of last. Case-insensitive,\n * digits in any script. `null` for anything else, or a day past the years\n * 1 to 9999.\n */\nexport function readDateShortcut(\n text: string,\n today: PlainDate,\n): PlainDate | null {\n const match = SHORTCUT.exec(cleanDateText(text).toLowerCase());\n if (match === null) {\n return null;\n }\n const [, todayKey, anchor, sign, digits, unit = \"d\", offsetAnchor] = match;\n if (todayKey !== undefined) {\n return today;\n }\n if (anchor !== undefined) {\n return anchored(today, anchor);\n }\n const count = Number(digits) * (sign === \"+\" ? 1 : -1);\n try {\n return anchored(offset(today, count, unit), offsetAnchor);\n } catch {\n return null;\n }\n}\n","import { localeKey } from \"../localeKey\";\nimport { dateTimeFormat } from \"./format\";\nimport {\n dayPeriodOf,\n segmentIndex,\n segmentValue,\n splitSegments,\n type DateLayout,\n type SegmentType,\n} from \"./layout\";\nimport { readDateShortcut } from \"./shortcuts\";\nimport { cleanDateText, foldWord } from \"./text\";\nimport {\n dateParts,\n daysInMonth,\n plainDate,\n plainTime,\n type PlainDate,\n type PlainTime,\n} from \"./values\";\n\n/** How a text was read as a date or time. */\nexport type DateReadingInfo =\n | { readonly kind: \"segments\" }\n | { readonly kind: \"iso\" }\n | {\n readonly kind: \"numeric\";\n /** The order the numbers were read in: `\"mdy\"`, `\"dmy\"`, `\"ymd\"`. */\n readonly order: string;\n /** A one- or two-digit year took its century from the pivot. */\n readonly pivotedYear: boolean;\n }\n | { readonly kind: \"monthName\"; readonly pivotedYear: boolean }\n | { readonly kind: \"shortcut\"; readonly shortcut: string }\n /** A time of day from pasted or free text: \"3:05 PM\", \"1505\". */\n | { readonly kind: \"time\" };\n\n/** Why a text cannot be read as a date or time. */\nexport type DateUnreadableReason =\n | \"dateIncomplete\"\n | \"timeIncomplete\"\n | \"nonexistent\"\n | \"yearDigits\"\n | \"unreadable\";\n\n/**\n * What a text reads as, before a field makes its value from it: nothing;\n * a day and a time of day (either may be absent), with the offset a\n * pasted ISO text named; or why it cannot be read.\n */\nexport type DateTextReading =\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"read\";\n readonly date: PlainDate | null;\n readonly time: PlainTime | null;\n /** Minutes east of UTC a pasted text gave (\"Z\", \"+01:00\"); `null` without one. */\n readonly offset: number | null;\n readonly info: DateReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: DateUnreadableReason };\n\n/** What the two-digit year pivot is told. */\nexport interface PivotOptions {\n /** Its year is the current year. */\n readonly today: PlainDate;\n /** A year after `max`'s takes the century before. */\n readonly max?: PlainDate | null | undefined;\n /** A year before `min`'s takes the century after. */\n readonly min?: PlainDate | null | undefined;\n}\n\n/** What the readers need to know about the field. */\nexport interface DateReadOptions extends PivotOptions {\n /** What the field holds: a day, a time of day, or both. */\n readonly fields: \"date\" | \"time\" | \"dateTime\";\n /** The field's layout: its order and day periods. */\n readonly layout: DateLayout;\n /** For month and weekday names; English names are read too. */\n readonly locale: Intl.LocalesArgument;\n /** Whether `t`, `+3` and the rest read. */\n readonly shortcuts: boolean;\n /**\n * The segment the user is typing in, if any: a short year there is\n * still being typed, so it reads as incomplete rather than pivoted.\n */\n readonly activeSegment?: number | null | undefined;\n}\n\nconst EMPTY: DateTextReading = { kind: \"empty\" };\n\nfunction unreadableBecause(reason: DateUnreadableReason): DateTextReading {\n return { kind: \"unreadable\", reason };\n}\n\nfunction read(\n date: PlainDate | null,\n time: PlainTime | null,\n info: DateReadingInfo,\n offset: number | null = null,\n): DateTextReading {\n return { kind: \"read\", date, time, offset, info };\n}\n\n/**\n * The year ending in `digits` (one or two digits) within the hundred\n * years from 80 before the current year (ICU's rule): in 2026, 26 is 2026,\n * 45 is 2045, 46 is 1946. A year after `max`'s takes the century before,\n * one before `min`'s the century after, so a birthday field whose `max`\n * is today reads 36 as 1936.\n */\nexport function pivotYear(digits: number, options: PivotOptions): number {\n const current = dateParts(options.today).year;\n const start = current - 80;\n let year = start + ((((digits - start) % 100) + 100) % 100);\n if (options.max != null && year > dateParts(options.max).year) {\n year -= 100;\n } else if (options.min != null && year < dateParts(options.min).year) {\n year += 100;\n }\n return year;\n}\n\n/** A year typed with `length` digits: four as written, one or two pivoted; `null` for three or more than four. */\nfunction yearOf(\n value: number,\n length: number,\n options: PivotOptions,\n): { readonly year: number; readonly pivoted: boolean } | null {\n if (length === 4) {\n return { year: value, pivoted: false };\n }\n return length === 1 || length === 2\n ? { year: pivotYear(value, options), pivoted: true }\n : null;\n}\n\n/** A day from its numbers: the day, or why there is none. */\nfunction dayReading(\n year: number,\n month: number,\n day: number,\n info: DateReadingInfo,\n): DateTextReading {\n if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) {\n return unreadableBecause(\"unreadable\");\n }\n return day > daysInMonth(year, month)\n ? unreadableBecause(\"nonexistent\")\n : read(plainDate(year, month, day), null, info);\n}\n\n/** The hour of the day for a 12-hour cycle's hour and its day period, or another cycle's hour; `null` out of range. */\nfunction hourOfDay(\n hour: number,\n dayPeriod: 0 | 1 | null,\n hourCycle: DateLayout[\"hourCycle\"],\n): number | null {\n if (dayPeriod !== null) {\n const twelve = hourCycle === \"h11\" ? hour : hour === 12 ? 0 : hour;\n return twelve >= 0 && twelve <= 11 ? twelve + dayPeriod * 12 : null;\n }\n if (hourCycle === \"h24\") {\n return hour >= 1 && hour <= 24 ? hour % 24 : null;\n }\n return hour >= 0 && hour <= 23 ? hour : null;\n}\n\nconst TIME_TYPES: ReadonlySet<SegmentType> = new Set<SegmentType>([\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\n/** The order of the layout's date segments, as `\"mdy\"`; `\"ymd\"` without them. */\nexport function dateOrder(layout: DateLayout): string {\n const order = layout.segments\n .map((segment) => segment.type)\n .filter((type) => type === \"year\" || type === \"month\" || type === \"day\")\n .map((type) => type.charAt(0))\n .join(\"\");\n return order.length === 3 ? order : \"ymd\";\n}\n\n/**\n * Segment texts read strictly, as the field holds them while typed:\n * every segment empty is nothing; a date with an empty segment, or a year\n * still being typed (`activeSegment`), is incomplete; a year left with one\n * or two digits is pivoted, with three it is refused; a day the month does\n * not have does not exist; a 12-hour time without its day period is\n * incomplete. A date-time whose time segments are all empty reads with no\n * time, which the field fills with its default.\n */\nexport function readDateSegments(\n texts: readonly string[],\n options: DateReadOptions,\n): DateTextReading {\n const { layout } = options;\n if (texts.every((text) => text === \"\")) {\n return EMPTY;\n }\n const value = (type: SegmentType): number | null => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const filled = (index: number) => (texts[index] ?? \"\") !== \"\";\n const indexes = layout.segments.map((_, index) => index);\n const dateIndexes = indexes.filter(\n (index) => !TIME_TYPES.has(layout.segments[index]?.type ?? \"hour\"),\n );\n const timeIndexes = indexes.filter((index) => !dateIndexes.includes(index));\n\n let date: PlainDate | null = null;\n let info: DateReadingInfo = { kind: \"segments\" };\n if (dateIndexes.length > 0) {\n const yearIndex = segmentIndex(layout, \"year\");\n const yearLength = (texts[yearIndex] ?? \"\").length;\n if (\n !dateIndexes.every(filled) ||\n (options.activeSegment === yearIndex && yearLength < 4)\n ) {\n return unreadableBecause(\"dateIncomplete\");\n }\n const year = yearOf(value(\"year\") ?? 0, yearLength, options);\n if (year === null) {\n return unreadableBecause(\"yearDigits\");\n }\n if (year.pivoted) {\n info = { kind: \"numeric\", order: dateOrder(layout), pivotedYear: true };\n }\n const day = dayReading(\n year.year,\n value(\"month\") ?? 0,\n value(\"day\") ?? 0,\n info,\n );\n if (day.kind !== \"read\") {\n return day;\n }\n date = day.date;\n }\n if (timeIndexes.length === 0) {\n return read(date, null, info);\n }\n const filledTimes = timeIndexes.filter(filled).length;\n if (filledTimes === 0 && options.fields === \"dateTime\") {\n return read(date, null, info);\n }\n if (filledTimes < timeIndexes.length) {\n return unreadableBecause(\"timeIncomplete\");\n }\n const time = timeOfSegments(texts, layout);\n return time === null\n ? unreadableBecause(\"unreadable\")\n : read(date, time, info);\n}\n\n/** The time of day filled time segments hold; `null` for an hour outside the cycle or minutes past 59. */\nfunction timeOfSegments(\n texts: readonly string[],\n layout: DateLayout,\n): PlainTime | null {\n const value = (type: SegmentType): number | null => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const dayPeriod = value(\"dayPeriod\");\n const hour = hourOfDay(\n value(\"hour\") ?? -1,\n dayPeriod === null ? null : dayPeriod === 0 ? 0 : 1,\n layout.hourCycle,\n );\n const minute = value(\"minute\") ?? 0;\n const second = value(\"second\") ?? 0;\n return hour === null || minute > 59 || second > 59\n ? null\n : plainTime(hour, minute, second);\n}\n\n/**\n * The time of day a field's segments hold once every time segment is\n * filled, whatever its date segments hold: a date-time field keeps it when\n * a shortcut sets the date. `null` for text that is not segments, a layout\n * without time segments, or a time not yet complete.\n */\nexport function segmentsTime(\n layout: DateLayout,\n text: string,\n): PlainTime | null {\n const texts = splitSegments(layout, text);\n const timeIndexes = layout.segments\n .map((segment, index) => (TIME_TYPES.has(segment.type) ? index : -1))\n .filter((index) => index >= 0);\n if (\n texts === null ||\n timeIndexes.length === 0 ||\n timeIndexes.some((index) => (texts[index] ?? \"\") === \"\")\n ) {\n return null;\n }\n return timeOfSegments(texts, layout);\n}\n\nconst ISO =\n /^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:[.,](\\d{1,9}))?)?)?\\s*(Z|[+-]\\d{2}(?::?\\d{2})?)?$/i;\n\n/** Minutes east of UTC for an ISO offset: `Z`, `+01:00`, `-0800`, `+05`. */\nfunction offsetMinutes(text: string): number {\n if (text.toUpperCase() === \"Z\") {\n return 0;\n }\n const sign = text.startsWith(\"-\") ? -1 : 1;\n const digits = text.slice(1).replace(\":\", \"\");\n return (\n sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2) || 0))\n );\n}\n\n/** An ISO date or date-time, or `null` for text in another form. */\nfunction readIso(text: string): DateTextReading | null {\n const match = ISO.exec(text);\n if (match === null) {\n return null;\n }\n const [, year, month, day, hour, minute, second, fraction, offset] = match;\n const iso: DateReadingInfo = { kind: \"iso\" };\n const date = dayReading(Number(year), Number(month), Number(day), iso);\n if (date.kind !== \"read\") {\n return date;\n }\n if (hour === undefined || minute === undefined) {\n return date;\n }\n const clock = [Number(hour), Number(minute), Number(second ?? 0)] as const;\n if (clock[0] > 23 || clock[1] > 59 || clock[2] > 59) {\n return unreadableBecause(\"unreadable\");\n }\n const time = plainTime(\n ...clock,\n Number((fraction ?? \"\").padEnd(3, \"0\").slice(0, 3)),\n );\n return read(\n date.date,\n time,\n iso,\n offset === undefined ? null : offsetMinutes(offset),\n );\n}\n\n/** Three numbers in `order` (\"mdy\") as a day; the year one, two or four digits. */\nfunction readNumbers(\n numbers: readonly string[],\n order: string,\n options: PivotOptions,\n): DateTextReading {\n const byType = new Map(\n Array.from(order, (type, index) => [type, numbers[index] ?? \"\"]),\n );\n const yearText = byType.get(\"y\") ?? \"\";\n const monthText = byType.get(\"m\") ?? \"\";\n const dayText = byType.get(\"d\") ?? \"\";\n if (monthText.length > 2 || dayText.length > 2) {\n return unreadableBecause(\"unreadable\");\n }\n const year = yearOf(Number(yearText), yearText.length, options);\n if (year === null) {\n return unreadableBecause(\n yearText.length === 3 ? \"yearDigits\" : \"unreadable\",\n );\n }\n return dayReading(year.year, Number(monthText), Number(dayText), {\n kind: \"numeric\",\n order,\n pivotedYear: year.pivoted,\n });\n}\n\n/** Month and weekday names a locale writes, folded, with English beside them. */\ninterface Names {\n readonly months: ReadonlyMap<string, number>;\n readonly weekdays: ReadonlySet<string>;\n}\n\nconst namesByLocale = new Map<string, Names>();\n\n/** The letters glued to a literal's end or start next to a name: Hebrew writes \"במרץ\" in \"14 במרץ\". */\nfunction glued(text: string | undefined, end: \"start\" | \"end\"): string {\n const match = (end === \"end\" ? /\\p{L}+$/u : /^\\p{L}+/u).exec(text ?? \"\");\n return match?.[0] ?? \"\";\n}\n\n/**\n * Month names alone and inside a date, where some languages change the\n * word (Russian writes the genitive \"марта\"), long and short; weekday\n * names long and short; in `locale` and in English.\n */\nfunction namesOf(locale: Intl.LocalesArgument): Names {\n const key = localeKey(locale);\n const known = namesByLocale.get(key);\n if (known !== undefined) {\n return known;\n }\n const months = new Map<string, number>();\n const weekdays = new Set<string>();\n for (const language of [locale, \"en\"]) {\n for (const width of [\"long\", \"short\"] as const) {\n const alone = dateTimeFormat(language, { month: width, timeZone: \"UTC\" });\n const inDate = dateTimeFormat(language, {\n day: \"numeric\",\n month: width,\n timeZone: \"UTC\",\n });\n const weekday = dateTimeFormat(language, {\n weekday: width,\n timeZone: \"UTC\",\n });\n for (let month = 1; month <= 12; month += 1) {\n const moment = Date.UTC(2026, month - 1, 15);\n months.set(foldWord(alone.format(moment)), month);\n const parts = inDate.formatToParts(moment);\n const at = parts.findIndex((part) => part.type === \"month\");\n const name = parts[at]?.value ?? \"\";\n months.set(foldWord(name), month);\n months.set(\n foldWord(\n glued(parts[at - 1]?.value, \"end\") +\n name +\n glued(parts[at + 1]?.value, \"start\"),\n ),\n month,\n );\n }\n // 9 to 15 March 2026 run from Monday to Sunday.\n for (let day = 9; day <= 15; day += 1) {\n weekdays.add(foldWord(weekday.format(Date.UTC(2026, 2, day))));\n }\n }\n }\n months.delete(\"\");\n const names = { months, weekdays };\n namesByLocale.set(key, names);\n return names;\n}\n\n/** The month a word names in `locale` or in English, long or short, without case, accents or a trailing dot; `null` for none. */\nexport function monthOfName(\n word: string,\n locale: Intl.LocalesArgument,\n): number | null {\n return namesOf(locale).months.get(foldWord(word)) ?? null;\n}\n\nconst TOKENS = /\\p{L}[\\p{L}\\p{M}]*\\.?|\\d+/gu;\n\n/**\n * A date written with numbers and words: a month name (long or short, in\n * the locale or in English, without case, accents or a trailing dot),\n * four digits for the year, and the day; of two short numbers, the\n * locale's order decides which is the day. Weekday names and words of one\n * or two letters (\"de\", \"of\", a CJK \"年\") are passed over, so\n * \"2026年3月14日\" is three numbers. `null` when a longer word is no name,\n * or there is no month name and not three numbers either.\n */\nfunction readWords(\n text: string,\n options: DateReadOptions,\n): DateTextReading | null {\n const { months, weekdays } = namesOf(options.locale);\n const numbers: string[] = [];\n let month: number | null = null;\n for (const token of text.match(TOKENS) ?? []) {\n if (/^\\d/.test(token)) {\n numbers.push(token);\n continue;\n }\n const word = foldWord(token);\n const named = months.get(word);\n if (named !== undefined) {\n if (month !== null && month !== named) {\n return unreadableBecause(\"unreadable\");\n }\n month = named;\n } else if (!weekdays.has(word) && Array.from(word).length > 2) {\n return null;\n }\n }\n const order = dateOrder(options.layout);\n if (month === null) {\n return numbers.length === 3 ? readNumbers(numbers, order, options) : null;\n }\n const long = numbers.filter((number) => number.length === 4);\n const short = numbers.filter((number) => number.length <= 2);\n if (long.length + short.length !== numbers.length) {\n return unreadableBecause(\n numbers.some((number) => number.length === 3)\n ? \"yearDigits\"\n : \"unreadable\",\n );\n }\n const dayFirst = order.indexOf(\"d\") < order.indexOf(\"y\");\n const [dayText, yearText] =\n long.length === 1 && short.length === 1\n ? [short[0], long[0]]\n : long.length === 0 && short.length === 2\n ? dayFirst\n ? [short[0], short[1]]\n : [short[1], short[0]]\n : [undefined, undefined];\n if (dayText === undefined || yearText === undefined) {\n return unreadableBecause(\"unreadable\");\n }\n const year = yearOf(Number(yearText), yearText.length, options);\n return year === null\n ? unreadableBecause(\"unreadable\")\n : dayReading(year.year, month, Number(dayText), {\n kind: \"monthName\",\n pivotedYear: year.pivoted,\n });\n}\n\n/** `text` cut into numbers of the given widths. */\nfunction cut(text: string, widths: readonly number[]): string[] {\n let at = 0;\n return widths.map((width) => {\n const piece = text.slice(at, at + width);\n at += width;\n return piece;\n });\n}\n\n/** A day alone, read leniently: ISO, eight digits, three numbers, or a month name. */\nfunction readDay(text: string, options: DateReadOptions): DateTextReading {\n const iso = readIso(text);\n if (iso !== null) {\n return iso.kind === \"read\" ? read(iso.date, null, iso.info) : iso;\n }\n const order = dateOrder(options.layout);\n if (/^\\d{8}$/.test(text)) {\n const compact = readNumbers(cut(text, [4, 2, 2]), \"ymd\", options);\n if (compact.kind === \"read\" || order === \"ymd\") {\n return compact;\n }\n const widths = Array.from(order, (type) => (type === \"y\" ? 4 : 2));\n return readNumbers(cut(text, widths), order, options);\n }\n if (/^\\d+(?:\\D+\\d+){2}$/u.test(text) && !/\\p{L}/u.test(text)) {\n const numbers = text.split(/\\D+/u);\n return readNumbers(\n numbers,\n numbers[0]?.length === 4 ? \"ymd\" : order,\n options,\n );\n }\n return readWords(text, options) ?? unreadableBecause(\"unreadable\");\n}\n\nconst TIME_CORE = /^(\\D*?)\\s*(\\d(?:[\\d\\s:.,hH]*\\d)?)\\s*(\\D*)$/u;\nconst TIME_SEPARATOR = /^\\s*(?:[:.,hH]|\\s)\\s*$/;\n\n/** The numbers of a time's core: \"1505\" is 15 and 05, \"15:05:09.250\" four numbers. */\nfunction clockNumbers(core: string, hasDayPeriod: boolean): string[] | null {\n const separators = core.split(/\\d+/).slice(1, -1);\n if (separators.some((separator) => !TIME_SEPARATOR.test(separator))) {\n return null;\n }\n const groups = core.split(/\\D+/);\n const [only = \"\"] = groups;\n if (groups.length > 1) {\n return groups.length <= 4 ? groups : null;\n }\n if (only.length === 3 || only.length === 4) {\n return cut(only, [only.length - 2, 2]);\n }\n if (only.length === 6) {\n return cut(only, [2, 2, 2]);\n }\n return hasDayPeriod && only.length <= 2 ? [only] : null;\n}\n\n/**\n * A time of day read leniently: \"15:05\", \"15.05\", \"1505\", \"15 h 05\",\n * \"3:05 PM\", \"3:05pm\", \"3 pm\", \"15:05:09.250\", the locale's day-period\n * texts before or after it (\"오후 3:05\") or English `am`, `pm`, `a`, `p`.\n * An hour alone needs its day period. `null` for anything else.\n */\nexport function readTimeText(\n text: string,\n layout: DateLayout,\n): PlainTime | null {\n const match = TIME_CORE.exec(cleanDateText(text));\n if (match === null) {\n return null;\n }\n const [, before = \"\", core = \"\", after = \"\"] = match;\n const words = [before.trim(), after.trim()].filter((word) => word !== \"\");\n const [word] = words;\n const dayPeriod = word === undefined ? null : dayPeriodOf(layout, word);\n if (words.length > 1 || (word !== undefined && dayPeriod === null)) {\n return null;\n }\n const numbers = clockNumbers(core, dayPeriod !== null);\n if (numbers === null) {\n return null;\n }\n const [hour = \"\", minute = \"\", second = \"\", fraction = \"\"] = numbers;\n if (\n hour.length > 2 ||\n (minute !== \"\" && minute.length !== 2) ||\n (second !== \"\" && second.length !== 2)\n ) {\n return null;\n }\n const hours = hourOfDay(\n Number(hour),\n dayPeriod,\n dayPeriod === null ? \"h23\" : layout.hourCycle === \"h11\" ? \"h11\" : \"h12\",\n );\n const minutes = Number(minute || 0);\n const seconds = Number(second || 0);\n if (hours === null || minutes > 59 || seconds > 59) {\n return null;\n }\n return plainTime(\n hours,\n minutes,\n seconds,\n Number(fraction.padEnd(3, \"0\").slice(0, 3)),\n );\n}\n\n/** Where a date-time text may split into its date and its time: at each space, comma or `T`. */\nfunction splitPoints(text: string): number[] {\n const points: number[] = [];\n for (let index = 1; index < text.length; index += 1) {\n if (/[\\s,T]/.test(text.charAt(index))) {\n points.push(index);\n }\n }\n return points;\n}\n\n/**\n * A pasted or free text read whole, leniently:\n *\n * 1. Cleaned: trimmed, digits in any script as ASCII, direction marks\n * dropped, every kind of space a space.\n * 2. With shortcuts on, the shortcut grammar (`t`, `+3`, `-1me`).\n * 3. ISO: `2026-03-14`, `2026-03-14T15:05`, seconds and fractions\n * optional, a trailing `Z` or offset. A date field takes the day, a\n * time field the time.\n * 4. Eight digits: `YYYYMMDD` when that is a real day, else the locale's\n * order as 2-2-4.\n * 5. Three numbers with anything between: in the locale's order, except\n * that four digits first always means year, month, day.\n * 6. A month name with the day and year, weekday names passed over.\n * 7. A time after the date (or alone, in a time field): \"15:05\",\n * \"3:05 PM\", \"3 pm\", the locale's day periods or English ones.\n *\n * One- and two-digit years pivot (`pivotYear`). Anything else is\n * unreadable.\n */\nexport function readDateText(\n text: string,\n options: DateReadOptions,\n): DateTextReading {\n const clean = cleanDateText(text);\n if (clean === \"\") {\n return EMPTY;\n }\n const iso = readIso(clean);\n if (options.fields === \"time\") {\n if (iso?.kind === \"read\" && iso.time !== null) {\n return read(null, iso.time, iso.info);\n }\n const time = readTimeText(clean, options.layout);\n return time === null\n ? unreadableBecause(\"unreadable\")\n : read(null, time, { kind: \"time\" });\n }\n if (options.shortcuts) {\n const shortcut = readDateShortcut(clean, options.today);\n if (shortcut !== null) {\n return read(shortcut, null, { kind: \"shortcut\", shortcut: clean });\n }\n }\n if (iso !== null) {\n return options.fields === \"date\" && iso.kind === \"read\"\n ? read(iso.date, null, iso.info)\n : iso;\n }\n const whole = readDay(clean, options);\n if (whole.kind === \"read\") {\n return whole;\n }\n for (const point of splitPoints(clean)) {\n const day = readDay(clean.slice(0, point).replace(/[\\s,]+$/, \"\"), options);\n const time = readTimeText(clean.slice(point + 1), options.layout);\n if (day.kind === \"read\" && time !== null) {\n return read(day.date, options.fields === \"date\" ? null : time, day.info);\n }\n }\n return whole;\n}\n\n/**\n * The field's text read as the field reads it: its segments (`texts`,\n * `null` for text that is not segments) strictly, so a date still being\n * typed is incomplete; anything else, or segments that make no date but\n * a lenient reading does, by `readDateText`.\n */\nexport function readDateField(\n text: string,\n texts: readonly string[] | null,\n options: DateReadOptions,\n): DateTextReading {\n if (texts === null) {\n return readDateText(text, options);\n }\n const strict = readDateSegments(texts, options);\n if (\n strict.kind !== \"unreadable\" ||\n strict.reason === \"dateIncomplete\" ||\n strict.reason === \"timeIncomplete\" ||\n strict.reason === \"yearDigits\"\n ) {\n return strict;\n }\n const lenient = readDateText(text, options);\n return lenient.kind === \"read\" ? lenient : strict;\n}\n","import {\n epochOfInstant,\n epochOfWallClock,\n instantFromEpoch,\n plainDateTime,\n splitDateTime,\n wallClockOfEpoch,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n} from \"./values\";\n\n/** Which moment a wall clock in a skipped or repeated hour means: Temporal's four answers. */\nexport type TimeZoneDisambiguation =\n \"compatible\" | \"earlier\" | \"later\" | \"reject\";\n\n/**\n * How a wall clock met a zone: as typed (`exact`); in an hour the clocks\n * skipped, read as `wallClock` (`skipped`); in an hour that happens twice,\n * read as one moment with the `other` beside it (`repeated`); or, with\n * `\"reject\"`, refused, with why.\n */\nexport type ZonedReading =\n | { readonly kind: \"exact\"; readonly instant: Instant }\n | {\n readonly kind: \"skipped\";\n readonly instant: Instant;\n readonly wallClock: PlainDateTime;\n }\n | {\n readonly kind: \"repeated\";\n readonly instant: Instant;\n readonly other: Instant;\n }\n | { readonly kind: \"rejected\"; readonly reason: \"skipped\" | \"repeated\" };\n\nconst DAY_MS = 86_400_000;\n\n/** Formatters per zone: building an `Intl.DateTimeFormat` costs far more than using one. */\nconst zoneFormats = new Map<string, Intl.DateTimeFormat>();\n\nfunction zoneFormat(timeZone: string): Intl.DateTimeFormat {\n let format = zoneFormats.get(timeZone);\n if (format === undefined) {\n format = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n calendar: \"gregory\",\n numberingSystem: \"latn\",\n hourCycle: \"h23\",\n year: \"numeric\",\n month: \"numeric\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"numeric\",\n second: \"numeric\",\n });\n zoneFormats.set(timeZone, format);\n }\n return format;\n}\n\n/** The wall clock `timeZone` shows at `epoch`, as the epoch of that wall clock read as UTC. */\nfunction wallEpochAt(epoch: number, timeZone: string): number {\n const whole = Math.floor(epoch / 1000) * 1000;\n const fields: Partial<Record<Intl.DateTimeFormatPartTypes, number>> = {};\n for (const part of zoneFormat(timeZone).formatToParts(whole)) {\n fields[part.type] = Number(part.value);\n }\n const wall = new Date(0);\n wall.setUTCFullYear(\n fields.year ?? 1970,\n (fields.month ?? 1) - 1,\n fields.day ?? 1,\n );\n wall.setUTCHours(fields.hour ?? 0, fields.minute ?? 0, fields.second ?? 0);\n return wall.getTime() + (epoch - whole);\n}\n\n/** Milliseconds `timeZone`'s clocks are ahead of UTC at `epoch`. */\nfunction offsetAt(epoch: number, timeZone: string): number {\n return wallEpochAt(epoch, timeZone) - epoch;\n}\n\n/**\n * The zone the runtime runs in. The one place forms-core reads it: only\n * an input whose prop says it defaults to the runtime's zone asks.\n */\nexport function runtimeTimeZone(): string {\n return new Intl.DateTimeFormat().resolvedOptions().timeZone;\n}\n\n/** Whether `name` is a time zone `Intl` knows (\"Europe/Berlin\", \"UTC\"). */\nexport function isTimeZone(name: string): boolean {\n try {\n zoneFormat(name);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The day it is in `timeZone` at `now` (milliseconds since the epoch). */\nexport function todayIn(timeZone: string, now: number): PlainDate {\n return splitDateTime(nowIn(timeZone, now)).date;\n}\n\n/** The wall clock in `timeZone` at `now` (milliseconds since the epoch). */\nexport function nowIn(timeZone: string, now: number): PlainDateTime {\n return wallClockOfEpoch(wallEpochAt(now, timeZone));\n}\n\n/** The wall clock `timeZone` shows at `instant`. */\nexport function wallClockOf(instant: Instant, timeZone: string): PlainDateTime {\n return nowIn(timeZone, epochOfInstant(instant));\n}\n\n/** How far `timeZone` is from UTC at `instant`: \"+01:00\", \"-08:00\", \"+05:30\" (with seconds when it has them). */\nexport function offsetOf(instant: Instant, timeZone: string): string {\n const offset = offsetAt(epochOfInstant(instant), timeZone) / 1000;\n const size = Math.abs(offset);\n const pad = (value: number) => String(value).padStart(2, \"0\");\n const hours = pad(Math.floor(size / 3600));\n const minutes = pad(Math.floor(size / 60) % 60);\n const seconds = size % 60;\n return `${offset < 0 ? \"-\" : \"+\"}${hours}:${minutes}${\n seconds === 0 ? \"\" : `:${pad(seconds)}`\n }`;\n}\n\n/**\n * The moment `dateTime` is in `timeZone`. A candidate is the wall clock\n * less an offset the zone has on the day before or the day after it, kept\n * when the zone really has that offset at the candidate: two candidates\n * are a repeated hour, none a skipped one. `disambiguation` picks as\n * Temporal does: `\"compatible\"` (the default) takes the earlier of a\n * repeated hour and reads a skipped one with the offset from before the\n * change, so 02:30 on the night clocks go from 02:00 to 03:00 is 03:30;\n * `\"earlier\"` reads it with the offset after (01:30); `\"later\"` takes the\n * later of a repeated hour; `\"reject\"` refuses both. Throws a\n * `RangeError` for a moment outside the years 1 to 9999.\n */\nexport function instantOf(\n dateTime: PlainDateTime,\n timeZone: string,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): ZonedReading {\n const meeting = meet(dateTime, timeZone);\n const { candidates } = meeting;\n const [first, second] = candidates;\n if (first !== undefined && second === undefined) {\n return { kind: \"exact\", instant: instantFromEpoch(first) };\n }\n if (disambiguation === \"reject\") {\n return {\n kind: \"rejected\",\n reason: first === undefined ? \"skipped\" : \"repeated\",\n };\n }\n const epoch = chosen(meeting, disambiguation);\n if (first !== undefined && second !== undefined) {\n return {\n kind: \"repeated\",\n instant: instantFromEpoch(epoch),\n other: instantFromEpoch(epoch === first ? second : first),\n };\n }\n return {\n kind: \"skipped\",\n instant: instantFromEpoch(epoch),\n wallClock: wallClockOfEpoch(wallEpochAt(epoch, timeZone)),\n };\n}\n\n/** A wall clock met with a zone: the offsets either side of it, and the moments it can be. */\ninterface Meeting {\n readonly local: number;\n readonly before: number;\n readonly after: number;\n /** Earliest first: one when the wall clock is plain, two when repeated, none when skipped. */\n readonly candidates: readonly number[];\n}\n\nfunction meet(dateTime: PlainDateTime, timeZone: string): Meeting {\n const local = epochOfWallClock(dateTime);\n const before = offsetAt(local - DAY_MS, timeZone);\n const after = offsetAt(local + DAY_MS, timeZone);\n const candidates = [...new Set([before, after])]\n .map((offset) => local - offset)\n .filter((epoch) => offsetAt(epoch, timeZone) === local - epoch)\n .sort((a, b) => a - b);\n return { local, before, after, candidates };\n}\n\n/** The moment a disambiguation that does not refuse picks, as epoch milliseconds. */\nfunction chosen(\n { local, before, after, candidates }: Meeting,\n disambiguation: Exclude<TimeZoneDisambiguation, \"reject\">,\n): number {\n const [first, second] = candidates;\n if (first !== undefined) {\n return disambiguation === \"later\" ? (second ?? first) : first;\n }\n return local - (disambiguation === \"earlier\" ? after : before);\n}\n\n/**\n * The moment `dateTime` is in `timeZone`, by `disambiguation`; where it\n * would refuse (`\"reject\"`), as `\"compatible\"` reads it. For measuring a\n * span between wall clocks, which needs a moment either way.\n */\nexport function exactInstantOf(\n dateTime: PlainDateTime,\n timeZone: string,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): Instant {\n return instantFromEpoch(\n chosen(\n meet(dateTime, timeZone),\n disambiguation === \"reject\" ? \"compatible\" : disambiguation,\n ),\n );\n}\n\n/**\n * The moment `date` starts in `timeZone`: its midnight, or the first\n * moment after it when the clocks skipped midnight (01:00 that day).\n */\nexport function startOfDayIn(date: PlainDate, timeZone: string): Instant {\n return exactInstantOf(plainDateTime(date, \"00:00\"), timeZone);\n}\n","import type { ChangeCause } from \"../field/plan\";\nimport type { FieldState } from \"../field/state\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n dateTimeFormat,\n formatDate,\n formatDateTime,\n formatInstant,\n formatTime,\n} from \"./format\";\nimport {\n dateLayout,\n formatSegments,\n segmentSpans,\n shownHour,\n splitSegments,\n type DateLayout,\n type DateLayoutFields,\n type DateSegmentType,\n type SegmentType,\n} from \"./layout\";\nimport {\n readDateField,\n type DateReadingInfo,\n type DateTextReading,\n type DateUnreadableReason,\n} from \"./reading\";\nimport {\n dateFromInstant,\n dateFromPlainDate,\n dateFromPlainDateTime,\n dateParts,\n epochOfInstant,\n epochOfWallClock,\n instantFromEpoch,\n plainDateTime,\n plainTime,\n splitDateTime,\n timeParts,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\nimport {\n instantOf,\n offsetOf,\n wallClockOf,\n type TimeZoneDisambiguation,\n} from \"./zone\";\n\n/** What a date input adds to every event it fires. */\nexport interface DateDetails {\n /** The day as a JS `Date` at local midnight, as the grid reads a day; `null` when empty. */\n readonly date: Date | null;\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The segment the edit was in; `null` for a paste, a pick or a change from code. */\n readonly segment: DateSegmentType | null;\n /** The shortcut typed (\"t\", \"+3\", \"-1me\"); `null` otherwise. */\n readonly shortcut: string | null;\n /** How the text on screen reads; `null` while it shows the value. */\n readonly reading: DateReadingInfo | null;\n}\n\n/** What a time input adds to every event. */\nexport type TimeDetails = Omit<DateDetails, \"date\" | \"shortcut\">;\n\n/** What a date-time input adds to every event. */\nexport interface DateTimeDetails extends DateDetails {\n /** For an instant: how the wall clock was read in the zone; `null` for a local date-time. */\n readonly zone: {\n readonly reading: \"exact\" | \"skipped\" | \"repeated\";\n readonly offset: string;\n } | null;\n}\n\n/** What every date, time and date-time field is told. */\ninterface SegmentedFieldOptions {\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n /** How display mode writes the value; `Intl` styles by default. */\n readonly displayFormat?: Intl.DateTimeFormatOptions | undefined;\n /** The segment the user is typing in, if any, which a renderer knows: a short year there is not pivoted yet. */\n readonly activeSegment?: (() => number | null) | undefined;\n}\n\n/** How a date field reads and writes. */\nexport interface DateFieldOptions extends SegmentedFieldOptions {\n /** Today in the field's zone: shortcuts count from it, and the year pivot. */\n readonly today: () => PlainDate;\n /** Typing \"t\", \"+3\", \"-1w\", \"s\", \"e\"; on by default. */\n readonly shortcuts?: boolean | undefined;\n /** The limits, which the two-digit year pivot respects. */\n readonly min?: PlainDate | null | undefined;\n readonly max?: PlainDate | null | undefined;\n}\n\n/** How a time field reads and writes. */\nexport interface TimeFieldOptions extends SegmentedFieldOptions {\n /** The locale's hour cycle unless given. */\n readonly hourCycle?: \"h12\" | \"h23\" | undefined;\n /** `\"minute\"` by default; `\"second\"` keeps seconds. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n}\n\n/** How a local date-time field reads and writes. */\nexport interface DateTimeFieldOptions\n extends\n Omit<DateFieldOptions, \"min\" | \"max\">,\n Omit<TimeFieldOptions, keyof SegmentedFieldOptions> {\n /** The time a date gets when its time is left empty; \"00:00\" by default. */\n readonly defaultTime?: PlainTime | undefined;\n readonly min?: PlainDateTime | null | undefined;\n readonly max?: PlainDateTime | null | undefined;\n}\n\n/** How an instant field reads and writes: wall clocks in `timeZone`. */\nexport interface InstantFieldOptions extends Omit<\n DateTimeFieldOptions,\n \"min\" | \"max\"\n> {\n readonly timeZone: string;\n /** Which moment a wall clock in a skipped or repeated hour means; `\"compatible\"` by default. */\n readonly disambiguation?: TimeZoneDisambiguation | undefined;\n readonly min?: Instant | null | undefined;\n readonly max?: Instant | null | undefined;\n}\n\ntype AnyFieldOptions = SegmentedFieldOptions &\n Partial<Pick<DateFieldOptions, \"today\" | \"shortcuts\">> &\n Partial<Pick<TimeFieldOptions, \"hourCycle\" | \"precision\">>;\n\n/** The layout a field of `fields` uses, in the field's locale unless its options name one. */\nfunction layoutFor(\n fields: DateLayoutFields,\n options: AnyFieldOptions,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): DateLayout {\n return dateLayout(\n {\n locale: options.locale ?? locale,\n fields,\n hourCycle: options.hourCycle,\n precision: options.precision,\n numberingSystem: options.numberingSystem,\n },\n messages,\n );\n}\n\n/** The hours, minutes and seconds each segment type shows for a time of day. */\nfunction timeValues(\n time: PlainTime,\n hourCycle: DateLayout[\"hourCycle\"],\n): Partial<Record<SegmentType, number>> {\n const { hour, minute, second } = timeParts(time);\n return {\n hour: shownHour(hour, hourCycle),\n minute,\n second,\n dayPeriod: hour >= 12 ? 1 : 0,\n };\n}\n\n/** A day written in a date layout's segments: \"03/14/2026\", \"14.03.2026\". */\nexport function formatDateSegments(\n layout: DateLayout,\n date: PlainDate,\n): string {\n return formatSegments(layout, dateParts(date));\n}\n\n/** A time of day written in a time layout's segments: \"3:05 PM\", \"15:05\". */\nexport function formatTimeSegments(\n layout: DateLayout,\n time: PlainTime,\n): string {\n return formatSegments(layout, timeValues(time, layout.hourCycle));\n}\n\n/** A wall clock written in a date-time layout's segments: \"03/14/2026, 3:05 PM\". */\nexport function formatDateTimeSegments(\n layout: DateLayout,\n dateTime: PlainDateTime,\n): string {\n const { date, time } = splitDateTime(dateTime);\n return formatSegments(layout, {\n ...dateParts(date),\n ...timeValues(time, layout.hourCycle),\n });\n}\n\n/** `time` at the field's precision: seconds dropped unless it keeps them, milliseconds always. */\nfunction atPrecision(\n time: PlainTime,\n precision: TimeFieldOptions[\"precision\"],\n): PlainTime {\n const { hour, minute, second } = timeParts(time);\n return plainTime(hour, minute, precision === \"second\" ? second : 0);\n}\n\n/** The message for text a field cannot read; `example` writes the example the field gives. */\nfunction messageFor(\n reason: DateUnreadableReason,\n messages: FormsMessages,\n example: () => string,\n fields: \"date\" | \"time\" | \"dateTime\",\n): string {\n switch (reason) {\n case \"dateIncomplete\":\n return messages.dateIncomplete;\n case \"timeIncomplete\":\n return messages.timeIncomplete;\n case \"nonexistent\":\n return messages.dateNonexistent;\n case \"yearDigits\":\n return messages.dateYearDigits;\n case \"unreadable\":\n return fields === \"time\"\n ? messages.timeUnreadable(example())\n : messages.dateUnreadable(example());\n }\n}\n\n/** How a state's typed text reads; `null` while it shows its value or cannot be read. */\nfunction readState<V>(\n state: FieldState<V>,\n reader: (text: string) => DateTextReading,\n): DateReadingInfo | null {\n if (state.draft.kind !== \"text\") {\n return null;\n }\n const reading = reader(state.draft.text);\n return reading.kind === \"read\" ? reading.info : null;\n}\n\n/**\n * The segment an edit was in, from where the cause says it happened in\n * the field's text; `null` for a paste or drop, a change from code, or\n * text that is not segments.\n */\nfunction segmentOf(\n layout: DateLayout,\n text: string,\n cause: ChangeCause<unknown> | null,\n): DateSegmentType | null {\n const at = cause?.input?.selectionStart ?? null;\n if (\n cause === null ||\n at === null ||\n cause.source === \"paste\" ||\n cause.source === \"drop\"\n ) {\n return null;\n }\n const spans = segmentSpans(layout, text);\n if (spans === null) {\n return null;\n }\n const starting = spans.findIndex(([start]) => start === at);\n const index =\n starting >= 0\n ? starting\n : spans.findIndex(([start, end]) => start <= at && at <= end);\n const type = layout.segments[index]?.type;\n return type === undefined || type === \"quarter\" || type === \"period\"\n ? null\n : type;\n}\n\n/** The text a state shows: its draft, or its value written by `write`. */\nfunction shownText<V>(\n state: FieldState<V>,\n write: (value: V) => string,\n): string {\n if (state.draft.kind === \"text\") {\n return state.draft.text;\n }\n return state.value === null ? \"\" : write(state.value);\n}\n\n/**\n * A date field's own reading: its segments strictly, pasted and free text\n * leniently (shortcuts, ISO, numbers in the locale's order, month names),\n * empty as `null`, with the messages for text that is incomplete, a day\n * that does not exist, a three-digit year, or text that is no date (\"Enter\n * a date such as 03/14/2026\", today in the field's segments).\n */\nexport function dateParser(\n options: DateFieldOptions,\n): (text: string, context: ParseContext<PlainDate>) => ParseResult<PlainDate> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"date\", options, locale, messages);\n const reading = readDate(text, \"date\", layout, options, locale);\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => formatDateSegments(layout, options.today()),\n \"date\",\n ),\n );\n }\n return parsed(reading.kind === \"empty\" ? null : reading.date);\n };\n}\n\nfunction readDate(\n text: string,\n fields: \"date\" | \"time\" | \"dateTime\",\n layout: DateLayout,\n options: AnyFieldOptions & {\n readonly min?: PlainDate | null | undefined;\n readonly max?: PlainDate | null | undefined;\n },\n locale: Intl.LocalesArgument,\n): DateTextReading {\n return readDateField(text, splitSegments(layout, text), {\n fields,\n layout,\n locale: options.locale ?? locale,\n shortcuts: fields !== \"time\" && options.shortcuts !== false,\n // A time field reads no day, so it has no today to pass.\n today: options.today?.() ?? \"2000-01-01\",\n min: options.min,\n max: options.max,\n activeSegment: options.activeSegment?.(),\n });\n}\n\n/** A date field's own writing: the day in its segments, whatever the purpose; `\"\"` for `null`. */\nexport function dateFormatter(\n options: Pick<DateFieldOptions, \"locale\" | \"numberingSystem\"> = {},\n): (value: PlainDate | null, context: FormatContext<PlainDate>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateSegments(layoutFor(\"date\", options, locale, messages), value);\n}\n\n/** What a date field's events carry, for its state and the event's cause. */\nexport function dateDetails(\n state: FieldState<PlainDate>,\n cause: ChangeCause<unknown> | null,\n options: DateFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"date\", options, locale, messages);\n const reading = readState(state, (text) =>\n readDate(text, \"date\", layout, options, locale),\n );\n const { value } = state;\n return {\n date: value === null ? null : dateFromPlainDate(value),\n formatted:\n value === null ? \"\" : formatDate(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (date) => formatDateSegments(layout, date)),\n cause,\n ),\n shortcut: reading?.kind === \"shortcut\" ? reading.shortcut : null,\n reading,\n };\n}\n\n/** A sample time an unreadable time's message gives: 15:05 in the field's segments. */\nconst EXAMPLE_TIME: PlainTime = \"15:05\";\n\n/**\n * A time field's own reading: its segments strictly, pasted and free text\n * leniently (\"15:05\", \"3:05 PM\", \"1505\", an ISO date-time's time), at the\n * field's precision; empty as `null`.\n */\nexport function timeParser(\n options: TimeFieldOptions = {},\n): (text: string, context: ParseContext<PlainTime>) => ParseResult<PlainTime> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"time\", options, locale, messages);\n const reading = readDate(text, \"time\", layout, options, locale);\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => formatTimeSegments(layout, EXAMPLE_TIME),\n \"time\",\n ),\n );\n }\n return parsed(\n reading.kind === \"empty\" || reading.time === null\n ? null\n : atPrecision(reading.time, options.precision),\n );\n };\n}\n\n/** A time field's own writing: the time in its segments; `\"\"` for `null`. */\nexport function timeFormatter(\n options: TimeFieldOptions = {},\n): (value: PlainTime | null, context: FormatContext<PlainTime>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatTimeSegments(layoutFor(\"time\", options, locale, messages), value);\n}\n\n/** What a time field's events carry. */\nexport function timeDetails(\n state: FieldState<PlainTime>,\n cause: ChangeCause<unknown> | null,\n options: TimeFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): TimeDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"time\", options, locale, messages);\n const { value } = state;\n return {\n formatted:\n value === null ? \"\" : formatTime(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (time) => formatTimeSegments(layout, time)),\n cause,\n ),\n reading: readState(state, (text) =>\n readDate(text, \"time\", layout, options, locale),\n ),\n };\n}\n\n/** The date part of a wall-clock limit, for the year pivot. */\nfunction dayOf(limit: string | null | undefined): PlainDate | null {\n return limit == null ? null : (limit.slice(0, 10) as PlainDate);\n}\n\n/** A date-time text read as a wall clock: a date without a time takes `defaultTime`. */\nfunction readWallClock(\n text: string,\n layout: DateLayout,\n options: DateTimeFieldOptions | InstantFieldOptions,\n locale: Intl.LocalesArgument,\n limits: { readonly min: PlainDate | null; readonly max: PlainDate | null },\n):\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"read\";\n readonly dateTime: PlainDateTime;\n readonly offset: number | null;\n readonly info: DateReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: DateUnreadableReason } {\n const reading = readDate(\n text,\n \"dateTime\",\n layout,\n { ...options, ...limits },\n locale,\n );\n if (reading.kind !== \"read\") {\n return reading;\n }\n if (reading.date === null) {\n return { kind: \"unreadable\", reason: \"dateIncomplete\" };\n }\n const time = atPrecision(\n reading.time ?? options.defaultTime ?? \"00:00\",\n options.precision,\n );\n return {\n kind: \"read\",\n dateTime: plainDateTime(reading.date, time),\n offset: reading.offset,\n info: reading.info,\n };\n}\n\n/** The example an unreadable date-time's message gives: today at the default time, in the field's segments. */\nfunction dateTimeExample(\n layout: DateLayout,\n options: DateTimeFieldOptions | InstantFieldOptions,\n): string {\n return formatDateTimeSegments(\n layout,\n plainDateTime(options.today(), options.defaultTime ?? \"00:00\"),\n );\n}\n\n/**\n * A local date-time field's own reading: as `dateParser` reads the date\n * and `timeParser` the time; a date whose time is left empty takes\n * `defaultTime`; a pasted offset is dropped, the wall clock kept.\n */\nexport function dateTimeParser(\n options: DateTimeFieldOptions,\n): (\n text: string,\n context: ParseContext<PlainDateTime>,\n) => ParseResult<PlainDateTime> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const reading = readWallClock(text, layout, options, locale, {\n min: dayOf(options.min),\n max: dayOf(options.max),\n });\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => dateTimeExample(layout, options),\n \"dateTime\",\n ),\n );\n }\n return parsed(reading.kind === \"empty\" ? null : reading.dateTime);\n };\n}\n\n/** A local date-time field's own writing: the wall clock in its segments; `\"\"` for `null`. */\nexport function dateTimeFormatter(\n options: Omit<TimeFieldOptions, \"displayFormat\"> = {},\n): (\n value: PlainDateTime | null,\n context: FormatContext<PlainDateTime>,\n) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateTimeSegments(\n layoutFor(\"dateTime\", options, locale, messages),\n value,\n );\n}\n\n/** What a local date-time field's events carry; `date` is the wall clock as a local `Date`. */\nexport function dateTimeDetails(\n state: FieldState<PlainDateTime>,\n cause: ChangeCause<unknown> | null,\n options: DateTimeFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateTimeDetails {\n const { locale, messages } = options;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const limits = { min: dayOf(options.min), max: dayOf(options.max) };\n const reading = readState(state, (text) =>\n readDate(text, \"dateTime\", layout, { ...options, ...limits }, locale),\n );\n const { value } = state;\n return {\n date: value === null ? null : dateFromPlainDateTime(value),\n formatted:\n value === null\n ? \"\"\n : formatDateTime(value, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (dateTime) => formatDateTimeSegments(layout, dateTime)),\n cause,\n ),\n shortcut: reading?.kind === \"shortcut\" ? reading.shortcut : null,\n reading,\n zone: null,\n };\n}\n\n/**\n * An instant field's own reading: the wall clock as a local date-time\n * field reads it, then the moment it is in `timeZone` by\n * `disambiguation`; a pasted text with an offset is that moment exactly.\n * A wall clock `\"reject\"` refuses is unreadable (\"02:30 doesn't exist\n * here: clocks go forward\").\n */\nexport function instantParser(\n options: InstantFieldOptions,\n): (text: string, context: ParseContext<Instant>) => ParseResult<Instant> {\n return (text, { locale, messages }) => {\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const { timeZone } = options;\n const reading = readWallClock(text, layout, options, locale, {\n min:\n options.min == null ? null : dayOf(wallClockOf(options.min, timeZone)),\n max:\n options.max == null ? null : dayOf(wallClockOf(options.max, timeZone)),\n });\n if (reading.kind === \"unreadable\") {\n return unreadable(\n messageFor(\n reading.reason,\n messages,\n () => dateTimeExample(layout, options),\n \"dateTime\",\n ),\n );\n }\n if (reading.kind === \"empty\") {\n return parsed(null);\n }\n const { dateTime, offset } = reading;\n if (offset !== null) {\n return parsed(\n instantFromEpoch(epochOfWallClock(dateTime) - offset * 60_000),\n );\n }\n const zoned = instantOf(dateTime, timeZone, options.disambiguation);\n if (zoned.kind !== \"rejected\") {\n return parsed(zoned.instant);\n }\n const typed = formatTime(\n splitDateTime(dateTime).time,\n options.locale ?? locale,\n );\n return unreadable(\n zoned.reason === \"skipped\"\n ? messages.timeNonexistent(typed)\n : messages.timeAmbiguous(typed),\n );\n };\n}\n\n/** An instant field's own writing: its wall clock in `timeZone`, in the field's segments; `\"\"` for `null`. */\nexport function instantFormatter(\n options: Pick<InstantFieldOptions, \"timeZone\"> &\n Omit<TimeFieldOptions, \"displayFormat\">,\n): (value: Instant | null, context: FormatContext<Instant>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatDateTimeSegments(\n layoutFor(\"dateTime\", options, locale, messages),\n wallClockOf(value, options.timeZone),\n );\n}\n\n/**\n * What an instant field's events carry: `date` is the exact `Date`;\n * `zone` says how the wall clock shown was read in the zone (a skipped\n * hour read as the hour after, a repeated one) and the offset it has.\n */\nexport function instantDetails(\n state: FieldState<Instant>,\n cause: ChangeCause<unknown> | null,\n options: InstantFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): DateTimeDetails {\n const { locale, messages, timeZone } = options;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const typed =\n state.draft.kind === \"text\"\n ? readWallClock(state.draft.text, layout, options, locale, {\n min: null,\n max: null,\n })\n : null;\n const { value } = state;\n const wallClock =\n typed?.kind === \"read\" && typed.offset === null\n ? typed.dateTime\n : value === null\n ? null\n : wallClockOf(value, timeZone);\n const zoned =\n wallClock === null\n ? null\n : instantOf(wallClock, timeZone, options.disambiguation);\n return {\n date: value === null ? null : dateFromInstant(value),\n formatted:\n value === null\n ? \"\"\n : formatInstant(value, timeZone, locale, options.displayFormat),\n segment: segmentOf(\n layout,\n shownText(state, (instant) =>\n formatDateTimeSegments(layout, wallClockOf(instant, timeZone)),\n ),\n cause,\n ),\n shortcut:\n typed?.kind === \"read\" && typed.info.kind === \"shortcut\"\n ? typed.info.shortcut\n : null,\n reading: typed?.kind === \"read\" ? typed.info : null,\n zone:\n value === null || zoned === null || zoned.kind === \"rejected\"\n ? null\n : { reading: zoned.kind, offset: offsetOf(value, timeZone) },\n };\n}\n\n/** The zone's offset at `instant` as `locale` names it: \"GMT+02:00\". */\nfunction offsetName(\n instant: Instant,\n timeZone: string,\n locale: Intl.LocalesArgument,\n): string {\n return (\n dateTimeFormat(locale, { timeZone, timeZoneName: \"longOffset\" })\n .formatToParts(epochOfInstant(instant))\n .find((part) => part.type === \"timeZoneName\")?.value ??\n offsetOf(instant, timeZone)\n );\n}\n\n/**\n * The info message an instant field shows while the wall clock in `text`\n * falls in an hour its zone skips (\"Clocks go forward here: 02:30 is read\n * as 03:30\") or repeats (\"02:30 happens twice; read as GMT+02:00\"), times\n * as display mode writes them; `null` for any other text, a text with an\n * offset of its own included.\n */\nexport function instantZoneMessage(\n text: string,\n options: InstantFieldOptions & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): string | null {\n const { messages, timeZone } = options;\n const locale = options.locale;\n const layout = layoutFor(\"dateTime\", options, locale, messages);\n const typed = readWallClock(text, layout, options, locale, {\n min: null,\n max: null,\n });\n if (typed.kind !== \"read\" || typed.offset !== null) {\n return null;\n }\n const timeOf = (dateTime: PlainDateTime) =>\n formatTime(splitDateTime(dateTime).time, locale);\n const zoned = instantOf(typed.dateTime, timeZone, options.disambiguation);\n switch (zoned.kind) {\n case \"skipped\":\n return messages.timeSkipped(\n timeOf(typed.dateTime),\n timeOf(zoned.wallClock),\n );\n case \"repeated\":\n return messages.timeRepeated(\n timeOf(typed.dateTime),\n offsetName(zoned.instant, timeZone, locale),\n );\n default:\n return null;\n }\n}\n","/** No per-type flags. */\nexport type NoFlags = Record<never, never>;\n\n/**\n * A stretch of values of one type. Either end may be `null` (open). `F` is\n * the type's own flags, carried in the value beside the ends (a time range\n * over midnight carries `overnight`); a flag is never named `start`,\n * `end` or `rule` (which marks a `RelativeRange`).\n * A range with both ends open is no range: an input holding one holds\n * `null`.\n */\nexport type Range<T, F extends object = NoFlags> = {\n readonly start: T | null;\n readonly end: T | null;\n} & Readonly<F>;\n\n/**\n * Whether `end` belongs to the range: `\"[)\"`, half-open (`end` is the first\n * value after it, as a date range stores the day after its last day), or\n * `\"[]\"`, closed.\n */\nexport type RangeBounds = \"[)\" | \"[]\";\n\n/** One end of a range. */\nexport type RangeEnd = \"start\" | \"end\";\n\n/** A range kept as a rule (\"the last 7 days\"), resolved to ends on demand. */\nexport interface RelativeRange<R> {\n readonly kind: \"relative\";\n readonly rule: R;\n}\n\n/** What a range input holds: fixed ends, or (for a type with rules) a rule. */\nexport type RangeValue<T, F extends object = NoFlags, R = never> = [R] extends [\n never,\n]\n ? Range<T, F>\n : Range<T, F> | RelativeRange<R>;\n\n/** How two present ends stand: in order, with the flags that makes, or reversed. */\nexport type RangeOrientation<F extends object> =\n | { readonly kind: \"ordered\"; readonly flags: F }\n | { readonly kind: \"reversed\" };\n\n/**\n * Everything the range model needs to know about one value type, which the\n * type supplies. `S` is its span (a number for numbers, a duration for\n * dates); `C` the context its functions need (a time zone, whether\n * `overnight` is allowed); `R` its relative rule, `never` when it has none.\n * The model orders, checks and measures only through these functions.\n */\nexport interface RangeKind<\n T,\n F extends object = NoFlags,\n S = number,\n C = undefined,\n R = never,\n> {\n /** Negative when `a` comes before `b`, 0 when they are one, positive after. */\n readonly compare: (a: T, b: T) => number;\n /** How `end` stands to `start`: a time range may call an earlier end \"ordered, overnight\". */\n readonly orient: (start: T, end: T, context: C) => RangeOrientation<F>;\n /** The flags of a range with an open end. */\n readonly openFlags: F;\n /** The length from `start` to `end`, both present, as stored. */\n readonly span: (start: T, end: T, flags: F, context: C) => S;\n readonly compareSpans: (a: S, b: S) => number;\n /**\n * The stored end of a half-open range for an end shown inclusive (a date:\n * the next day). Without it, the end shown is the end stored.\n */\n readonly toStoredEnd?: ((shown: T, context: C) => T) | undefined;\n /** The end shown inclusive for a half-open range's stored end; the inverse of `toStoredEnd`. */\n readonly toShownEnd?: ((stored: T, context: C) => T) | undefined;\n /** The ends a rule stands for, now. Required when `R` is not `never`. */\n readonly resolve?: ((rule: R, context: C) => Range<T, F>) | undefined;\n /**\n * Whether two rules are one. Without it, rules are compared as plain\n * data: the same keys holding the same values, deeply.\n */\n readonly sameRule?: ((a: R, b: R) => boolean) | undefined;\n}\n\n/** How a range input reads two ends. */\nexport interface RangeOptions<S> {\n /** `\"[)\"` by default: whether the stored `end` belongs to the range. */\n readonly bounds?: RangeBounds | undefined;\n /** What an end before its start does: swapped (default) or an error. */\n readonly reversed?: \"swap\" | \"error\" | undefined;\n /** Whether a start equal to its end is allowed when that holds nothing (half-open). */\n readonly allowEmpty?: boolean | undefined;\n readonly minSpan?: S | undefined;\n readonly maxSpan?: S | undefined;\n}\n\n/**\n * Two ends as typed, made into a range: no range (both open), an ordered\n * range (`swapped` when the ends changed places), or refused with why.\n */\nexport type RangeReading<T, F extends object> =\n | { readonly kind: \"none\" }\n | {\n readonly kind: \"range\";\n readonly range: Range<T, F>;\n readonly swapped: boolean;\n }\n | { readonly kind: \"unreadable\"; readonly reason: \"reversed\" | \"empty\" };\n\n/** A range from its parts. The one place a `Range` is built, so its flags sit beside the ends. */\nfunction rangeOf<T, F extends object>(\n start: T | null,\n end: T | null,\n flags: F,\n): Range<T, F> {\n return { ...flags, start, end };\n}\n\n/** `range`'s own flags, without its ends. */\nexport function rangeFlags<T, F extends object>(range: Range<T, F>): F {\n const flags: Record<string, unknown> = { ...range };\n delete flags.start;\n delete flags.end;\n // What is left of a `Range<T, F>` without its ends is its `F`.\n return flags as F;\n}\n\n/** `end` as stored, for a range with `bounds`: the kind's `toStoredEnd` for a half-open one. */\nfunction storedEnd<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n end: T,\n bounds: RangeBounds,\n context: C,\n): T {\n return bounds === \"[)\" && kind.toStoredEnd !== undefined\n ? kind.toStoredEnd(end, context)\n : end;\n}\n\n/**\n * Makes two ends as shown into the stored range. Both open is no range; one\n * open end keeps the kind's `openFlags`. Two present ends are oriented by\n * the kind: reversed ends are swapped (the default) or refused with\n * `\"reversed\"`. The end is then stored through `toStoredEnd` for a\n * half-open range, and a half-open range whose start is its stored end\n * holds nothing, so it is refused with `\"empty\"` unless `allowEmpty`.\n */\nexport function orderRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n start: T | null,\n end: T | null,\n options: RangeOptions<S>,\n context: C,\n): RangeReading<T, F> {\n const bounds = options.bounds ?? \"[)\";\n if (start === null && end === null) {\n return { kind: \"none\" };\n }\n if (start === null || end === null) {\n return {\n kind: \"range\",\n range: rangeOf(\n start,\n end === null ? null : storedEnd(kind, end, bounds, context),\n kind.openFlags,\n ),\n swapped: false,\n };\n }\n let first = start;\n let last = end;\n let orientation = kind.orient(first, last, context);\n const swapped = orientation.kind === \"reversed\";\n if (swapped) {\n if (options.reversed === \"error\") {\n return { kind: \"unreadable\", reason: \"reversed\" };\n }\n [first, last] = [end, start];\n orientation = kind.orient(first, last, context);\n }\n if (orientation.kind === \"reversed\") {\n return { kind: \"unreadable\", reason: \"reversed\" };\n }\n const stored = storedEnd(kind, last, bounds, context);\n if (\n bounds === \"[)\" &&\n options.allowEmpty !== true &&\n kind.compare(first, stored) === 0\n ) {\n return { kind: \"unreadable\", reason: \"empty\" };\n }\n return {\n kind: \"range\",\n range: rangeOf(first, stored, orientation.flags),\n swapped,\n };\n}\n\n/** The end a stored range shows: the kind's `toShownEnd` for a half-open one. */\nexport function shownEnd<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n bounds: RangeBounds,\n context: C,\n): T | null {\n const { end } = range;\n return end !== null && bounds === \"[)\" && kind.toShownEnd !== undefined\n ? kind.toShownEnd(end, context)\n : end;\n}\n\n/** From `range`'s start to its stored end, by the kind; `null` while an end is open. */\nexport function rangeSpan<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n context: C,\n): S | null {\n const { start, end } = range;\n return start === null || end === null\n ? null\n : kind.span(start, end, rangeFlags(range), context);\n}\n\n/**\n * Whether `value` lies in `range`. An open end reaches as far as values go.\n * A range whose stored end comes before its start (a time range over\n * midnight) wraps: it holds what comes from its start on, and what comes\n * before its end.\n */\nexport function rangeIncludes<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F>,\n value: T,\n bounds: RangeBounds,\n): boolean {\n const { start, end } = range;\n const fromStart = start === null || kind.compare(value, start) >= 0;\n const toEnd =\n end === null ||\n (bounds === \"[)\"\n ? kind.compare(value, end) < 0\n : kind.compare(value, end) <= 0);\n const wraps = start !== null && end !== null && kind.compare(end, start) < 0;\n return wraps ? fromStart || toEnd : fromStart && toEnd;\n}\n\n/** Whether `value` is a rule rather than fixed ends. */\nexport function isRelativeRange<T, F extends object, R>(\n value: Range<T, F> | RelativeRange<R>,\n): value is RelativeRange<R> {\n return \"rule\" in value;\n}\n\n/**\n * The ends `value` stands for now: itself, or its rule resolved by the\n * kind. Throws a `TypeError` for a rule when the kind has no `resolve`.\n */\nexport function resolveRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n value: RangeValue<T, F, R>,\n context: C,\n): Range<T, F> {\n // `RangeValue` is one of the two members, whatever `R` is.\n const either = value as Range<T, F> | RelativeRange<R>;\n if (!isRelativeRange(either)) {\n return either;\n }\n if (kind.resolve === undefined) {\n throw new TypeError(\"This range kind has no rules to resolve.\");\n }\n return kind.resolve(either.rule, context);\n}\n\n/** Whether `a` and `b` are the same plain data: primitives by `Object.is`, arrays and objects key by key. */\nfunction samePlainData(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null ||\n Array.isArray(a) !== Array.isArray(b)\n ) {\n return false;\n }\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => key in right && samePlainData(left[key], right[key]))\n );\n}\n\n/**\n * Whether two ranges are one: the same ends by the kind's `compare`, and\n * the same flags; or two rules the kind's `sameRule` calls one (equal plain\n * data without it), so a rule written inline, a new object each render,\n * is still the value held.\n */\nexport function sameRange<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n a: RangeValue<T, F, R>,\n b: RangeValue<T, F, R>,\n): boolean {\n const left = a as Range<T, F> | RelativeRange<R>;\n const right = b as Range<T, F> | RelativeRange<R>;\n if (isRelativeRange(left) || isRelativeRange(right)) {\n return (\n isRelativeRange(left) &&\n isRelativeRange(right) &&\n (kind.sameRule ?? samePlainData)(left.rule, right.rule)\n );\n }\n const sameEnd = (x: T | null, y: T | null) =>\n x === null || y === null ? x === y : kind.compare(x, y) === 0;\n const leftFlags = rangeFlags(left) as Record<string, unknown>;\n const rightFlags = rangeFlags(right) as Record<string, unknown>;\n const keys = Object.keys(leftFlags);\n return (\n sameEnd(left.start, right.start) &&\n sameEnd(left.end, right.end) &&\n keys.length === Object.keys(rightFlags).length &&\n keys.every((key) => Object.is(leftFlags[key], rightFlags[key]))\n );\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport type { Range, RelativeRange } from \"../range/range\";\nimport {\n addDays,\n addMonths,\n dateParts,\n startOfMonth,\n type PlainDate,\n type Weekday,\n} from \"./values\";\nimport { startOfWeek } from \"./week\";\n\n/** A unit of the calendar a rule counts in. */\nexport type CalendarUnit = \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\n/**\n * A date range kept as a rule, resolved against today in a zone whenever\n * it is shown or read. Plain data: it serializes as JSON, so a saved\n * filter still means \"the last 7 days\" next month.\n */\nexport type RelativeDateRule =\n | {\n /** The unit `offset` units from the one today is in: this month (0), last month (-1). */\n readonly kind: \"period\";\n readonly unit: CalendarUnit;\n readonly offset: number;\n /** Quarters and years counted from the fiscal year's start. */\n readonly fiscal?: boolean | undefined;\n }\n | {\n /** The `count` units up to today (`includeToday`) or up to yesterday; \"next\" looks ahead from tomorrow, or from today. */\n readonly kind: \"last\" | \"next\";\n readonly unit: \"day\" | \"week\" | \"month\" | \"year\";\n readonly count: number;\n readonly includeToday: boolean;\n }\n | {\n /** From the start of the unit today is in, through today. */\n readonly kind: \"toDate\";\n readonly unit: \"week\" | \"month\" | \"quarter\" | \"year\";\n readonly fiscal?: boolean | undefined;\n };\n\n/** What a rule is resolved against. */\nexport interface DateRuleContext {\n /** Today in the input's zone. */\n readonly today: () => PlainDate;\n readonly firstDayOfWeek: Weekday;\n /** The month the fiscal year starts in, 1 to 12. */\n readonly fiscalYearStart: number;\n}\n\n/** `date` moved `count` units on (back when negative); months clamp to the month's length. */\nfunction addUnits(\n date: PlainDate,\n unit: CalendarUnit,\n count: number,\n): PlainDate {\n switch (unit) {\n case \"day\":\n return addDays(date, count);\n case \"week\":\n return addDays(date, count * 7);\n case \"month\":\n return addMonths(date, count);\n case \"quarter\":\n return addMonths(date, count * 3);\n case \"year\":\n return addMonths(date, count * 12);\n }\n}\n\n/** The first day of the `unit` `date` is in; quarters and years from the fiscal start when `fiscal`. */\nfunction startOfUnit(\n date: PlainDate,\n unit: CalendarUnit,\n context: DateRuleContext,\n fiscal: boolean,\n): PlainDate {\n if (unit === \"day\") {\n return date;\n }\n if (unit === \"week\") {\n return startOfWeek(date, context.firstDayOfWeek);\n }\n const month = startOfMonth(date);\n const first = fiscal ? context.fiscalYearStart : 1;\n const intoYear = (dateParts(date).month - first + 12) % 12;\n switch (unit) {\n case \"month\":\n return month;\n case \"quarter\":\n return addMonths(month, -(intoYear % 3));\n case \"year\":\n return addMonths(month, -intoYear);\n }\n}\n\n/**\n * The days a rule stands for at `context.today()`, half-open:\n *\n * - `period`: the unit `offset` units from the one today is in (a week by\n * `firstDayOfWeek`; a quarter or year from `fiscalYearStart` when\n * `fiscal`).\n * - `last`: the `count` units up to tomorrow with `includeToday`, else up\n * to today; `next`: the `count` units from tomorrow, or from today with\n * `includeToday`. Months clamp to the month's length.\n * - `toDate`: from the start of the unit today is in through today.\n */\nexport function resolveDateRule(\n rule: RelativeDateRule,\n context: DateRuleContext,\n): Range<PlainDate> {\n const today = context.today();\n const tomorrow = addDays(today, 1);\n switch (rule.kind) {\n case \"period\": {\n const start = addUnits(\n startOfUnit(today, rule.unit, context, rule.fiscal === true),\n rule.unit,\n rule.offset,\n );\n return { start, end: addUnits(start, rule.unit, 1) };\n }\n case \"last\": {\n const end = rule.includeToday ? tomorrow : today;\n return { start: addUnits(end, rule.unit, -rule.count), end };\n }\n case \"next\": {\n const start = rule.includeToday ? today : tomorrow;\n return { start, end: addUnits(start, rule.unit, rule.count) };\n }\n case \"toDate\":\n return {\n start: startOfUnit(today, rule.unit, context, rule.fiscal === true),\n end: tomorrow,\n };\n }\n}\n\n/** Whether two rules stand for the same days, compared by value; `fiscal` absent is false. */\nexport function sameRule(a: RelativeDateRule, b: RelativeDateRule): boolean {\n switch (a.kind) {\n case \"period\":\n return (\n b.kind === \"period\" &&\n a.unit === b.unit &&\n a.offset === b.offset &&\n (a.fiscal === true) === (b.fiscal === true)\n );\n case \"last\":\n case \"next\":\n return (\n b.kind === a.kind &&\n a.unit === b.unit &&\n a.count === b.count &&\n a.includeToday === b.includeToday\n );\n case \"toDate\":\n return (\n b.kind === \"toDate\" &&\n a.unit === b.unit &&\n (a.fiscal === true) === (b.fiscal === true)\n );\n }\n}\n\nconst UNITS: readonly string[] = [\"day\", \"week\", \"month\", \"quarter\", \"year\"];\n\nfunction isInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value);\n}\n\n/**\n * Whether `value` is a rule, as read back from JSON: the right kind, a\n * unit that kind takes, whole numbers, `count` not negative. For checking\n * a stored filter before using it.\n */\nexport function isRelativeDateRule(value: unknown): value is RelativeDateRule {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const rule = value as Record<string, unknown>;\n const fiscal = rule.fiscal === undefined || typeof rule.fiscal === \"boolean\";\n const unit = typeof rule.unit === \"string\" ? rule.unit : \"\";\n switch (rule.kind) {\n case \"period\":\n return UNITS.includes(unit) && isInteger(rule.offset) && fiscal;\n case \"last\":\n case \"next\":\n return (\n unit !== \"quarter\" &&\n UNITS.includes(unit) &&\n isInteger(rule.count) &&\n rule.count >= 0 &&\n typeof rule.includeToday === \"boolean\"\n );\n case \"toDate\":\n return unit !== \"day\" && UNITS.includes(unit) && fiscal;\n default:\n return false;\n }\n}\n\n/** A preset: a rule (kept as the rule) or fixed ends; a rule's label comes from the messages when absent. */\nexport interface DatePreset<V> {\n readonly id: string;\n readonly label?: string | undefined;\n readonly value: V;\n}\n\n/** A preset that stores `rule` as the value, named by `label` or `messages.relativeRangeLabel`. */\nexport function relativePreset(\n id: string,\n rule: RelativeDateRule,\n label?: string,\n): DatePreset<RelativeRange<RelativeDateRule>> {\n return {\n id,\n ...(label === undefined ? {} : { label }),\n value: { kind: \"relative\", rule },\n };\n}\n\n/**\n * The presets most date range inputs want, each a rule: today, yesterday,\n * this week, the last 7 days (today included), this month, last month,\n * this quarter and year to date. A range input shows none unless it is\n * given a list.\n */\nexport const commonDatePresets: readonly DatePreset<\n RelativeRange<RelativeDateRule>\n>[] = [\n relativePreset(\"today\", { kind: \"period\", unit: \"day\", offset: 0 }),\n relativePreset(\"yesterday\", { kind: \"period\", unit: \"day\", offset: -1 }),\n relativePreset(\"thisWeek\", { kind: \"period\", unit: \"week\", offset: 0 }),\n relativePreset(\"last7Days\", {\n kind: \"last\",\n unit: \"day\",\n count: 7,\n includeToday: true,\n }),\n relativePreset(\"thisMonth\", { kind: \"period\", unit: \"month\", offset: 0 }),\n relativePreset(\"lastMonth\", { kind: \"period\", unit: \"month\", offset: -1 }),\n relativePreset(\"thisQuarter\", { kind: \"period\", unit: \"quarter\", offset: 0 }),\n relativePreset(\"yearToDate\", { kind: \"toDate\", unit: \"year\" }),\n];\n\n/** What a preset is called: its own label, a rule's from the messages, else its id. */\nexport function datePresetLabel<V>(\n preset: DatePreset<V>,\n messages: FormsMessages,\n): string {\n if (preset.label !== undefined) {\n return preset.label;\n }\n const { value } = preset;\n return typeof value === \"object\" &&\n value !== null &&\n \"rule\" in value &&\n isRelativeDateRule(value.rule)\n ? messages.relativeRangeLabel(value.rule)\n : preset.id;\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n resolveRange,\n type NoFlags,\n type Range,\n type RangeBounds,\n type RangeKind,\n type RangeValue,\n} from \"../range/range\";\nimport type { SpanFormatter } from \"../range/rules\";\nimport { dateTimeFormat, formatDate, formatTime } from \"./format\";\nimport {\n resolveDateRule,\n sameRule,\n type DateRuleContext,\n type RelativeDateRule,\n} from \"./relative\";\nimport {\n addDays,\n compareDates,\n compareDateTimes,\n compareInstants,\n compareTimes,\n daysBetween,\n epochOfInstant,\n epochOfWallClock,\n minutesOfDay,\n plainDateTime,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\nimport {\n exactInstantOf,\n startOfDayIn,\n type TimeZoneDisambiguation,\n} from \"./zone\";\n\n/** A range of days, stored half-open: `end` is the day after the last. */\nexport type DateRange = Range<PlainDate>;\n\n/** A time range's flag: its end is on the day after its start (22:00 to 06:00). */\nexport interface OvernightFlags {\n readonly overnight: boolean;\n}\n\n/** A range of times of day, which may cross midnight. */\nexport type TimeRange = Range<PlainTime, OvernightFlags>;\n\n/** What a time range kind is told: whether an end before its start means the next day. */\nexport interface TimeRangeContext {\n readonly overnight: boolean;\n}\n\n/** A date-time range's one zone, with what its rules need. */\nexport interface ZonedRangeContext extends DateRuleContext {\n readonly timeZone: string;\n readonly disambiguation: TimeZoneDisambiguation;\n}\n\n/**\n * Days, stored half-open: the end shown is the last day, the end stored\n * the day after, so 1 to 31 March stores `end: \"2026-04-01\"` and one day\n * shown is not an empty range. Span in days. Its rules resolve against\n * today; two rules are one when they are equal by value.\n */\nexport const dateRangeKind: RangeKind<\n PlainDate,\n NoFlags,\n number,\n DateRuleContext,\n RelativeDateRule\n> = {\n compare: compareDates,\n orient: (start, end) =>\n compareDates(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end) => daysBetween(start, end),\n compareSpans: (a, b) => a - b,\n toStoredEnd: (shown) => addDays(shown, 1),\n toShownEnd: (stored) => addDays(stored, -1),\n resolve: resolveDateRule,\n sameRule,\n};\n\n/**\n * Times of day. An end before its start is the next day (\"overnight\")\n * when the context allows it, else reversed; a range ending at midnight\n * crosses into the next day too. The end shown is the end stored\n * (09:00 to 17:00 stores `end: \"17:00\"`). Span in wall-clock minutes.\n */\nexport const timeRangeKind: RangeKind<\n PlainTime,\n OvernightFlags,\n number,\n TimeRangeContext\n> = {\n compare: compareTimes,\n orient: (start, end, { overnight }) => {\n if (compareTimes(end, start) >= 0) {\n return { kind: \"ordered\", flags: { overnight: false } };\n }\n return overnight\n ? { kind: \"ordered\", flags: { overnight: true } }\n : { kind: \"reversed\" };\n },\n openFlags: { overnight: false },\n span: (start, end, { overnight }) =>\n minutesOfDay(end) - minutesOfDay(start) + (overnight ? 24 * 60 : 0),\n compareSpans: (a, b) => a - b,\n};\n\n/** Milliseconds between two wall clocks in a zone: 23 hours across the night clocks go forward. */\nfunction zonedSpan(\n start: PlainDateTime,\n end: PlainDateTime,\n { timeZone, disambiguation }: ZonedRangeContext,\n): number {\n return (\n epochOfInstant(exactInstantOf(end, timeZone, disambiguation)) -\n epochOfInstant(exactInstantOf(start, timeZone, disambiguation))\n );\n}\n\n/**\n * Wall clocks, measured in the range's one zone: 29 March 2026 in Berlin,\n * midnight to midnight, is 23 hours. The end shown is the end stored. A\n * rule resolves to the start of its days. Span in milliseconds.\n */\nexport const dateTimeRangeKind: RangeKind<\n PlainDateTime,\n NoFlags,\n number,\n ZonedRangeContext,\n RelativeDateRule\n> = {\n compare: compareDateTimes,\n orient: (start, end) =>\n compareDateTimes(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end, _flags, context) => zonedSpan(start, end, context),\n compareSpans: (a, b) => a - b,\n resolve: (rule, context) => {\n const { start, end } = resolveDateRule(rule, context);\n return {\n start: start === null ? null : plainDateTime(start, \"00:00\"),\n end: end === null ? null : plainDateTime(end, \"00:00\"),\n };\n },\n sameRule,\n};\n\n/**\n * Exact moments; the zone is the one they are typed in, and where a\n * rule's days start. Span in milliseconds.\n */\nexport const instantRangeKind: RangeKind<\n Instant,\n NoFlags,\n number,\n ZonedRangeContext,\n RelativeDateRule\n> = {\n compare: compareInstants,\n orient: (start, end) =>\n compareInstants(end, start) >= 0\n ? { kind: \"ordered\", flags: {} }\n : { kind: \"reversed\" },\n openFlags: {},\n span: (start, end) => epochOfInstant(end) - epochOfInstant(start),\n compareSpans: (a, b) => a - b,\n resolve: (rule, context) => {\n const { start, end } = resolveDateRule(rule, context);\n return {\n start: start === null ? null : startOfDayIn(start, context.timeZone),\n end: end === null ? null : startOfDayIn(end, context.timeZone),\n };\n },\n sameRule,\n};\n\n/**\n * The days a date range input's value stands for now: its ends, or its\n * rule resolved against `context.today()`. For code that needs the days\n * outside an event (a grid filter at filter time), and to turn a rule\n * into fixed dates: `setValue(resolveDateRange(value, context))`.\n */\nexport function resolveDateRange(\n value: RangeValue<PlainDate, NoFlags, RelativeDateRule>,\n context: DateRuleContext,\n): DateRange {\n return resolveRange(dateRangeKind, value, context);\n}\n\n/** The times days picked in a calendar get: the start of the first day and the start of the day after the last, by default. */\nexport interface DefaultTimes {\n readonly start: PlainTime;\n readonly end: PlainTime;\n}\n\nconst MIDNIGHTS: DefaultTimes = { start: \"00:00\", end: \"00:00\" };\n\n/**\n * Days picked as a wall-clock range: the first day at `times.start`, the\n * stored end (the day after the last) at `times.end`. 29 March picked\n * alone is 29 March 00:00 to 30 March 00:00.\n */\nexport function daysToDateTimeRange(\n days: DateRange,\n times: DefaultTimes = MIDNIGHTS,\n): Range<PlainDateTime> {\n return {\n start: days.start === null ? null : plainDateTime(days.start, times.start),\n end: days.end === null ? null : plainDateTime(days.end, times.end),\n };\n}\n\n/** Days picked as a range of moments in `timeZone`, as `daysToDateTimeRange` picks the wall clocks. */\nexport function daysToInstantRange(\n days: DateRange,\n timeZone: string,\n times: DefaultTimes = MIDNIGHTS,\n disambiguation: TimeZoneDisambiguation = \"compatible\",\n): Range<Instant> {\n const { start, end } = daysToDateTimeRange(days, times);\n return {\n start:\n start === null ? null : exactInstantOf(start, timeZone, disambiguation),\n end: end === null ? null : exactInstantOf(end, timeZone, disambiguation),\n };\n}\n\n/** How a range writes its display text. */\nexport interface RangeTextOptions {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n readonly displayFormat?: Intl.DateTimeFormatOptions | undefined;\n}\n\n/**\n * A date range as display mode writes it, inclusive: `formatRange` of the\n * start and the end shown (\"Mar 1 – 31, 2026\"), one day once (\"Mar 14,\n * 2026\"), and an open end as `messages.rangeFrom` or `rangeUpTo`.\n */\nexport function formatDateRange(\n range: DateRange,\n options: RangeTextOptions & { readonly bounds?: RangeBounds | undefined },\n): string {\n const { locale, messages, displayFormat } = options;\n const write = (date: PlainDate) => formatDate(date, locale, displayFormat);\n const { start } = range;\n const end =\n range.end !== null && (options.bounds ?? \"[)\") === \"[)\"\n ? addDays(range.end, -1)\n : range.end;\n if (start === null || end === null) {\n if (start !== null) {\n return messages.rangeFrom(write(start));\n }\n return end === null ? \"\" : messages.rangeUpTo(write(end));\n }\n if (compareDates(start, end) === 0) {\n return write(start);\n }\n const at = (date: PlainDate) =>\n epochOfWallClock(plainDateTime(date, \"00:00\"));\n return dateTimeFormat(locale, {\n ...(displayFormat ?? { dateStyle: \"medium\" }),\n timeZone: \"UTC\",\n }).formatRange(at(start), at(end));\n}\n\n/**\n * A time range as display mode writes it: the two times joined by\n * `messages.rangeSeparator`, with `messages.rangeNextDay` after an\n * overnight end (\"22:00 – 06:00 +1\"); an open end as `rangeFrom` or\n * `rangeUpTo`. `formatRange` is not used: for times on two days it writes\n * the dates too.\n */\nexport function formatTimeRange(\n range: TimeRange,\n options: RangeTextOptions,\n): string {\n const { locale, messages, displayFormat } = options;\n const write = (time: PlainTime) => formatTime(time, locale, displayFormat);\n const { start, end } = range;\n if (start === null || end === null) {\n if (start !== null) {\n return messages.rangeFrom(write(start));\n }\n return end === null ? \"\" : messages.rangeUpTo(write(end));\n }\n const text = `${write(start)} ${messages.rangeSeparator} ${write(end)}`;\n return range.overnight ? `${text} ${messages.rangeNextDay}` : text;\n}\n\n/** A length of time for span limits, a day being 24 hours: `{ days: 31 }`, `{ hours: 1 }`. */\nexport interface DurationLike {\n readonly weeks?: number | undefined;\n readonly days?: number | undefined;\n readonly hours?: number | undefined;\n readonly minutes?: number | undefined;\n}\n\n/** `duration` in minutes. */\nfunction minutesIn(duration: DurationLike): number {\n return (\n (duration.weeks ?? 0) * 7 * 24 * 60 +\n (duration.days ?? 0) * 24 * 60 +\n (duration.hours ?? 0) * 60 +\n (duration.minutes ?? 0)\n );\n}\n\n/**\n * `duration` in the span unit of a range kind, for `minSpan` and\n * `maxSpan`: days for a date range, minutes for a time range,\n * milliseconds for a date-time or instant range.\n */\nexport function spanOf(\n duration: DurationLike,\n unit: \"day\" | \"minute\" | \"millisecond\",\n): number {\n const minutes = minutesIn(duration);\n switch (unit) {\n case \"day\":\n return minutes / (24 * 60);\n case \"minute\":\n return minutes;\n case \"millisecond\":\n return minutes * 60_000;\n }\n}\n\n/** A number of days as words in the validator's locale: \"31 days\", \"31 Tage\". A `SpanFormatter` for date ranges. */\nexport const formatDaySpan: SpanFormatter<number> = (days, { locale }) =>\n new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit: \"day\",\n unitDisplay: \"long\",\n }).format(days);\n\n/**\n * A length of time in milliseconds as words, through `Intl.DurationFormat`\n * with `style: \"short\"`: hours and minutes under 48 hours (\"8 hr\", \"1 hr,\n * 30 min\"), days and hours from 48 (\"3 days, 2 hr\"). A `SpanFormatter`\n * for date-time and instant ranges; a time range's minutes times 60,000.\n */\nexport const formatTimeSpan: SpanFormatter<number> = (\n milliseconds,\n { locale },\n) => {\n const minutes = Math.round(Math.abs(milliseconds) / 60_000);\n const hours = Math.floor(minutes / 60);\n const parts =\n hours >= 48\n ? { days: Math.floor(hours / 24), hours: hours % 24 }\n : { hours, minutes: minutes % 60 };\n return new Intl.DurationFormat(locale, { style: \"short\" }).format(\n minutes === 0 ? { minutes: 0 } : parts,\n );\n};\n","import type { FieldState } from \"../field/state\";\nimport { localeKey } from \"../localeKey\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport type { Validator } from \"../validation/validators\";\nimport { cleanDateText, foldWord } from \"./text\";\n\n/** The unit a duration's value is held in. */\nexport type DurationUnit = \"millisecond\" | \"second\" | \"minute\" | \"hour\";\n\n/** How a duration is written: `\"units\"` (\"1h 30m\"), `\"clock\"` (\"1:30\") or `\"decimal\"` hours (\"1.5\"). */\nexport type DurationNotation = \"units\" | \"clock\" | \"decimal\";\n\n/** How a duration field reads and writes. */\nexport interface DurationOptions {\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n /** The unit the value is held in; `\"minute\"` by default, so timesheet values stay whole. */\n readonly valueUnit?: DurationUnit | undefined;\n /** What a bare number means: `\"hour\"` by default, so \"1.5\" is an hour and a half. */\n readonly inputUnit?: \"minute\" | \"hour\" | undefined;\n /** The smallest part that can be typed; finer parts round half up to it. `\"minute\"` by default. */\n readonly precision?: \"minute\" | \"second\" | undefined;\n /** How the value is written; `\"units\"` by default. */\n readonly notation?: DurationNotation | undefined;\n /** How many hours a day (`d`) is: 24 by default, 8 for a working day. */\n readonly hoursPerDay?: number | undefined;\n /** Whether a duration may be negative. */\n readonly allowNegative?: boolean | undefined;\n}\n\n/** What a duration text reads as: nothing, a value in the value unit, or why it cannot be read. */\nexport type DurationReading =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"duration\"; readonly value: number }\n | { readonly kind: \"unreadable\"; readonly reason: \"negative\" | \"unreadable\" };\n\nconst MS: Readonly<Record<DurationUnit | \"day\", number>> = {\n millisecond: 1,\n second: 1000,\n minute: 60_000,\n hour: 3_600_000,\n day: 86_400_000,\n};\n\ntype PartUnit = \"day\" | \"hour\" | \"minute\" | \"second\";\n\n/** The unit a bare number after a part with `unit` means: minutes after hours (\"1h30\"). */\nconst NEXT_UNIT: Readonly<Record<PartUnit, PartUnit | null>> = {\n day: \"hour\",\n hour: \"minute\",\n minute: \"second\",\n second: null,\n};\n\nconst ENGLISH_UNITS: Readonly<Record<string, PartUnit>> = {\n d: \"day\",\n day: \"day\",\n days: \"day\",\n h: \"hour\",\n hr: \"hour\",\n hrs: \"hour\",\n hour: \"hour\",\n hours: \"hour\",\n m: \"minute\",\n min: \"minute\",\n mins: \"minute\",\n minute: \"minute\",\n minutes: \"minute\",\n s: \"second\",\n sec: \"second\",\n secs: \"second\",\n second: \"second\",\n seconds: \"second\",\n};\n\n/** The words a locale writes for each unit, and between parts. */\ninterface DurationWords {\n readonly units: ReadonlyMap<string, PartUnit>;\n /** Words that join parts (\"and\", \"و\"), passed over. */\n readonly joiners: ReadonlySet<string>;\n readonly decimal: string;\n}\n\nconst wordsByLocale = new Map<string, DurationWords>();\n\n/** Unit words from `Intl.NumberFormat`'s unit style, narrow to long, singular and plural; joiners from `Intl.ListFormat`. */\nfunction wordsOf(locale: Intl.LocalesArgument): DurationWords {\n const key = localeKey(locale);\n const known = wordsByLocale.get(key);\n if (known !== undefined) {\n return known;\n }\n const units = new Map<string, PartUnit>(Object.entries(ENGLISH_UNITS));\n for (const unit of [\"day\", \"hour\", \"minute\", \"second\"] as const) {\n for (const unitDisplay of [\"narrow\", \"short\", \"long\"] as const) {\n const format = new Intl.NumberFormat(locale, {\n style: \"unit\",\n unit,\n unitDisplay,\n });\n for (const count of [1, 2, 5]) {\n for (const part of format.formatToParts(count)) {\n if (part.type === \"unit\") {\n units.set(foldWord(part.value.trim()), unit);\n }\n }\n }\n }\n }\n const joiners = new Set<string>();\n for (const style of [\"narrow\", \"short\", \"long\"] as const) {\n const parts = new Intl.ListFormat(locale, { type: \"unit\", style })\n .formatToParts([\"1\", \"2\", \"3\"])\n .concat(\n new Intl.ListFormat(locale, {\n type: \"conjunction\",\n style,\n }).formatToParts([\"1\", \"2\"]),\n );\n for (const part of parts) {\n for (const word of part.value.match(/\\p{L}+/gu) ?? []) {\n joiners.add(foldWord(word));\n }\n }\n }\n const decimal =\n new Intl.NumberFormat(locale)\n .formatToParts(1.5)\n .find((part) => part.type === \"decimal\")?.value ?? \".\";\n const words = { units, joiners, decimal };\n wordsByLocale.set(key, words);\n return words;\n}\n\nconst CLOCK = /^(\\d+):(\\d{2})(?::(\\d{2}))?$/;\nconst BARE = /^\\d+(?:\\.\\d+)?$/;\nconst PART = /(\\d+(?:\\.\\d+)?)|(\\p{L}[\\p{L}\\p{M}]*\\.?)/gu;\n\n/** Milliseconds a units text (\"1h 30m\", \"2d 4h\", \"1h30\") stands for; `null` for text that is not one. */\nfunction unitsMilliseconds(\n text: string,\n words: DurationWords,\n hoursPerDay: number,\n): number | null {\n const tokens = [...text.matchAll(PART)];\n if (tokens.length === 0) {\n return null;\n }\n // Only spaces and commas may sit between the numbers and words.\n if (text.replace(PART, \"\").replace(/[\\s,]/g, \"\") !== \"\") {\n return null;\n }\n const size = (unit: PartUnit) =>\n unit === \"day\" ? hoursPerDay * MS.hour : MS[unit];\n let total = 0;\n let pending: number | null = null;\n let last: PartUnit | null = null;\n for (const [, number, word] of tokens) {\n if (number !== undefined) {\n if (pending !== null) {\n return null;\n }\n pending = Number(number);\n continue;\n }\n const folded = foldWord(word ?? \"\");\n const unit = words.units.get(folded);\n if (unit !== undefined && pending !== null) {\n total += pending * size(unit);\n pending = null;\n last = unit;\n } else if (pending !== null || !words.joiners.has(folded)) {\n return null;\n }\n }\n if (pending !== null) {\n const next = last === null ? null : NEXT_UNIT[last];\n if (next === null) {\n return null;\n }\n total += pending * size(next);\n }\n return last === null ? null : total;\n}\n\n/** `ms` rounded half up to the precision, then held in the value unit. */\nfunction toValue(ms: number, options: DurationOptions): number {\n const step = options.precision === \"second\" ? MS.second : MS.minute;\n const rounded = Math.sign(ms) * Math.round(Math.abs(ms) / step) * step;\n return rounded / MS[options.valueUnit ?? \"minute\"] + 0;\n}\n\n/**\n * Reads a duration: `units` (\"1h 30m\", \"1h30m\", \"90m\", \"2d 4h\", and \"1h30\",\n * a bare number after an hour being minutes; unit words in the locale or\n * English, any case; minutes over 59 allowed), `clock` (\"1:30\", \"26:15\",\n * seconds optional; minutes and seconds up to 59), or a bare number in\n * `inputUnit` (hours by default: \"1.5\" is 90 minutes). Digits in any\n * script; the locale's decimal separator or \".\"; `d` is `hoursPerDay`\n * hours. A sign only with `allowNegative`. The value is rounded half up to\n * the precision and held in `valueUnit`.\n */\nexport function parseDuration(\n text: string,\n options: DurationOptions = {},\n): DurationReading {\n const words = wordsOf(options.locale);\n let clean = cleanDateText(text).replace(/\\u{2212}/gu, \"-\");\n if (words.decimal !== \".\") {\n clean = clean.replaceAll(\n new RegExp(\n `(\\\\d)${words.decimal.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}(\\\\d)`,\n \"gu\",\n ),\n \"$1.$2\",\n );\n }\n if (clean === \"\") {\n return { kind: \"empty\" };\n }\n const negative = clean.startsWith(\"-\");\n const body = negative ? clean.slice(1).trim() : clean;\n if (negative && options.allowNegative !== true) {\n return { kind: \"unreadable\", reason: \"negative\" };\n }\n const ms = millisecondsOf(body, words, options);\n if (ms === null || !Number.isFinite(ms) || ms > Number.MAX_SAFE_INTEGER) {\n return { kind: \"unreadable\", reason: \"unreadable\" };\n }\n return { kind: \"duration\", value: toValue(negative ? -ms : ms, options) };\n}\n\n/** Milliseconds an unsigned duration text stands for, as a clock, a bare number or units; `null` for none. */\nfunction millisecondsOf(\n text: string,\n words: DurationWords,\n options: DurationOptions,\n): number | null {\n const clock = CLOCK.exec(text);\n if (clock !== null) {\n const [, hours = \"0\", minutes = \"0\", seconds = \"0\"] = clock;\n return Number(minutes) > 59 || Number(seconds) > 59\n ? null\n : Number(hours) * MS.hour +\n Number(minutes) * MS.minute +\n Number(seconds) * MS.second;\n }\n if (BARE.test(text)) {\n return Number(text) * MS[options.inputUnit ?? \"hour\"];\n }\n return unitsMilliseconds(text, words, options.hoursPerDay ?? 24);\n}\n\n/**\n * Writes a duration held in `valueUnit`, rounded to the precision:\n * `\"units\"` through `Intl.DurationFormat` with `style: \"narrow\"` (\"1h\n * 30m\" in `en-US`; hours are not gathered into days), `\"clock\"` as hours\n * and minutes (\"1:30\", \"26:15\", seconds with `precision: \"second\"`), or\n * `\"decimal\"` hours with up to two fraction digits (\"1.5\", \"1,5\").\n */\nexport function formatDuration(\n value: number,\n options: DurationOptions = {},\n): string {\n const { locale } = options;\n const step = options.precision === \"second\" ? MS.second : MS.minute;\n const ms = value * MS[options.valueUnit ?? \"minute\"];\n const size = Math.round(Math.abs(ms) / step) * step;\n const sign = ms < 0 && size > 0 ? -1 : 1;\n const hours = Math.floor(size / MS.hour);\n const minutes = Math.floor((size % MS.hour) / MS.minute);\n const seconds = Math.floor((size % MS.minute) / MS.second);\n switch (options.notation ?? \"units\") {\n case \"units\": {\n const parts =\n options.precision === \"second\" && seconds > 0\n ? { hours, minutes, seconds }\n : { hours, minutes };\n return new Intl.DurationFormat(locale, {\n style: \"narrow\",\n ...(size === 0 ? { minutesDisplay: \"always\" } : {}),\n }).format(\n Object.fromEntries(\n Object.entries(parts).map(([unit, count]) => [unit, sign * count]),\n ),\n );\n }\n case \"clock\": {\n const two = new Intl.NumberFormat(locale, {\n minimumIntegerDigits: 2,\n useGrouping: false,\n });\n const hour = new Intl.NumberFormat(locale, { useGrouping: false });\n const clock = `${hour.format(hours)}:${two.format(minutes)}${\n options.precision === \"second\" ? `:${two.format(seconds)}` : \"\"\n }`;\n return sign < 0 ? `-${clock}` : clock;\n }\n case \"decimal\":\n return new Intl.NumberFormat(locale, {\n maximumFractionDigits: 2,\n useGrouping: false,\n }).format((sign * size) / MS.hour);\n }\n}\n\n/** The example an unreadable duration's message gives: 90 minutes as the field writes them. */\nfunction example(options: DurationOptions): string {\n return formatDuration(\n 90 / (MS[options.valueUnit ?? \"minute\"] / MS.minute),\n options,\n );\n}\n\n/**\n * A duration field's own reading, `parseDuration` in the field's locale:\n * empty as `null`; \"Enter a duration of zero or more\" for a sign the\n * field takes none of; \"Enter a duration such as 1h 30m\" otherwise.\n */\nexport function durationParser(\n options: DurationOptions = {},\n): (text: string, context: ParseContext<number>) => ParseResult<number> {\n return (text, { locale, messages }) => {\n const own = { ...options, locale: options.locale ?? locale };\n const reading = parseDuration(text, own);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"duration\":\n return parsed(reading.value);\n case \"unreadable\":\n return unreadable(\n reading.reason === \"negative\"\n ? messages.durationNegative\n : messages.durationUnreadable(example(own)),\n );\n }\n };\n}\n\n/** A duration field's own writing, the same whatever the purpose: `formatDuration` in the field's locale; `\"\"` for `null`. */\nexport function durationFormatter(\n options: DurationOptions = {},\n): (value: number | null, context: FormatContext<number>) => string {\n return (value, { locale }) =>\n value === null\n ? \"\"\n : formatDuration(value, { ...options, locale: options.locale ?? locale });\n}\n\n/** `value` held in `from`, held in `to` instead: 90 minutes is 1.5 hours. */\nexport function convertDuration(\n value: number,\n from: DurationUnit,\n to: DurationUnit,\n): number {\n return (value * MS[from]) / MS[to];\n}\n\n/** A duration past `limit` on `side`, the limit written as the field writes durations, in the validator's locale. */\nfunction durationLimitRule(\n limit: number,\n side: \"min\" | \"max\",\n options: DurationOptions,\n): Validator<number> {\n return (value, { locale, messages }) => {\n if (value === null || (side === \"min\" ? value >= limit : value <= limit)) {\n return null;\n }\n const written = formatDuration(limit, {\n ...options,\n locale: options.locale ?? locale,\n });\n return side === \"min\"\n ? { text: messages.rangeUnderflow(written), code: \"rangeUnderflow\" }\n : { text: messages.rangeOverflow(written), code: \"rangeOverflow\" };\n };\n}\n\n/**\n * A duration under `min`, held in `options.valueUnit`, is\n * `messages.rangeUnderflow`, \"Enter 15m or more\", the limit written as\n * the field writes durations. Inclusive; `null` passes.\n */\nexport function minDurationRule(\n min: number,\n options: DurationOptions = {},\n): Validator<number> {\n return durationLimitRule(min, \"min\", options);\n}\n\n/** A duration over `max` is `messages.rangeOverflow`, \"Enter 8h or less\"; otherwise as `minDurationRule`. */\nexport function maxDurationRule(\n max: number,\n options: DurationOptions = {},\n): Validator<number> {\n return durationLimitRule(max, \"max\", options);\n}\n\n/** What a duration input adds to every event. */\nexport interface DurationDetails {\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The value in minutes, whatever `valueUnit` is; `null` when empty. */\n readonly minutes: number | null;\n}\n\n/** What a duration field's events carry. `options` holds the field's locale. */\nexport function durationDetails(\n state: FieldState<number>,\n options: DurationOptions,\n): DurationDetails {\n const { value } = state;\n return {\n formatted: value === null ? \"\" : formatDuration(value, options),\n minutes:\n value === null\n ? null\n : convertDuration(value, options.valueUnit ?? \"minute\", \"minute\"),\n };\n}\n","import type { ChangeCause } from \"../field/plan\";\nimport type { FieldState } from \"../field/state\";\nimport { localeKey } from \"../localeKey\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport type { Range } from \"../range/range\";\nimport { dateTimeFormat } from \"./format\";\nimport {\n dateLayout,\n formatSegments,\n layoutOf,\n segmentIndex,\n segmentSpans,\n segmentValue,\n splitSegments,\n type DateLayout,\n type LayoutShape,\n type SegmentType,\n} from \"./layout\";\nimport { monthOfName, pivotYear } from \"./reading\";\nimport { cleanDateText } from \"./text\";\nimport {\n addMonths,\n dateParts,\n epochOfWallClock,\n plainDate,\n plainDateTime,\n type PlainDate,\n} from \"./values\";\n\n/** A month: \"2026-11\". */\nexport type MonthPeriod = `${number}-${number}`;\n/** A calendar quarter: \"2026-Q3\". */\nexport type QuarterPeriod = `${number}-Q${number}`;\n/** A calendar year: \"2026\". */\nexport type YearPeriod = `${number}`;\n/** A fiscal year, named by the year it ends in unless told otherwise: \"FY2026\". */\nexport type FiscalYearPeriod = `FY${number}`;\n/** A quarter of a fiscal year: \"FY2026-Q1\". */\nexport type FiscalQuarterPeriod = `FY${number}-Q${number}`;\n/** A month of a fiscal year, P01 to P12: \"FY2026-P04\". */\nexport type FiscalMonthPeriod = `FY${number}-P${number}`;\n\n/** How long a period is. */\nexport type PeriodGranularity =\n \"month\" | \"quarter\" | \"year\" | \"fiscalMonth\" | \"fiscalQuarter\" | \"fiscalYear\";\n\n/** The value type of each granularity. */\nexport interface PeriodValues {\n readonly month: MonthPeriod;\n readonly quarter: QuarterPeriod;\n readonly year: YearPeriod;\n readonly fiscalMonth: FiscalMonthPeriod;\n readonly fiscalQuarter: FiscalQuarterPeriod;\n readonly fiscalYear: FiscalYearPeriod;\n}\n\n/** An accounting or reporting period, as a string: one of `PeriodValues`. */\nexport type Period<G extends PeriodGranularity = PeriodGranularity> =\n PeriodValues[G];\n\n/** Where a fiscal year starts and how it is named. */\nexport interface FiscalYear {\n /** The month it starts in, 1 to 12. */\n readonly start: number;\n /** Whether \"FY2026\" names the year it starts in or the year it ends in. */\n readonly namedBy: \"start\" | \"end\";\n}\n\n/** The calendar year as a fiscal year: from January, so both namings agree. */\nexport const CALENDAR_FISCAL_YEAR: FiscalYear = { start: 1, namedBy: \"end\" };\n\n/** A period's numbers: its year (the fiscal year's name for a fiscal period) and its place in it, from 1. */\nexport interface PeriodParts {\n readonly granularity: PeriodGranularity;\n readonly year: number;\n readonly index: number;\n}\n\nconst PATTERNS: Readonly<Record<PeriodGranularity, RegExp>> = {\n month: /^(\\d{4})-(\\d{2})$/,\n quarter: /^(\\d{4})-Q([1-4])$/,\n year: /^(\\d{4})$/,\n fiscalMonth: /^FY(\\d{4})-P(\\d{2})$/,\n fiscalQuarter: /^FY(\\d{4})-Q([1-4])$/,\n fiscalYear: /^FY(\\d{4})$/,\n};\n\n/** How many periods of a granularity a year holds. */\nconst PER_YEAR: Readonly<Record<PeriodGranularity, number>> = {\n month: 12,\n quarter: 4,\n year: 1,\n fiscalMonth: 12,\n fiscalQuarter: 4,\n fiscalYear: 1,\n};\n\nconst GRANULARITIES = Object.keys(PATTERNS) as PeriodGranularity[];\n\nfunction partsOf(text: string): PeriodParts | null {\n for (const granularity of GRANULARITIES) {\n const match = PATTERNS[granularity].exec(text);\n if (match !== null) {\n const year = Number(match[1]);\n const index = Number(match[2] ?? 1);\n return year >= 1 && index >= 1 && index <= PER_YEAR[granularity]\n ? { granularity, year, index }\n : null;\n }\n }\n return null;\n}\n\n/**\n * A period's granularity, year and place in that year, from 1: `2026-Q3`\n * is 2026 and 3, `FY2026-P04` fiscal year 2026 and 4. Throws a\n * `RangeError` for text that is not a period.\n */\nexport function periodParts(period: Period): PeriodParts {\n const parts = partsOf(period);\n if (parts === null) {\n throw new RangeError(`${period} is not a period`);\n }\n return parts;\n}\n\n/** The period with these numbers. Throws a `RangeError` for a year outside 1 to 9999. */\nfunction periodFrom<G extends PeriodGranularity>(\n granularity: G,\n year: number,\n index: number,\n): Period<G> {\n if (!(year >= 1 && year <= 9999)) {\n throw new RangeError(`${String(year)} is outside the years 1 to 9999`);\n }\n const y = String(year).padStart(4, \"0\");\n const texts: Record<PeriodGranularity, string> = {\n month: `${y}-${String(index).padStart(2, \"0\")}`,\n quarter: `${y}-Q${String(index)}`,\n year: y,\n fiscalMonth: `FY${y}-P${String(index).padStart(2, \"0\")}`,\n fiscalQuarter: `FY${y}-Q${String(index)}`,\n fiscalYear: `FY${y}`,\n };\n return texts[granularity] as Period<G>;\n}\n\n/** `text` as a period of `granularity` when it is one in canonical form (\"2026-11\", \"FY2026-P04\"); `null` otherwise. */\nexport function toPeriod<G extends PeriodGranularity>(\n text: string,\n granularity: G,\n): Period<G> | null {\n const parts = partsOf(text);\n return parts?.granularity === granularity ? (text as Period<G>) : null;\n}\n\n/** Whether `value` is a period in canonical form, of `granularity` when given. */\nexport function isPeriod(\n value: unknown,\n granularity?: PeriodGranularity,\n): value is Period {\n if (typeof value !== \"string\") {\n return false;\n }\n const parts = partsOf(value);\n return (\n parts !== null &&\n (granularity === undefined || parts.granularity === granularity)\n );\n}\n\n/** A period's granularity. Throws a `RangeError` for text that is not a period. */\nexport function periodGranularity(period: Period): PeriodGranularity {\n return periodParts(period).granularity;\n}\n\n/**\n * Negative when `a` comes first, 0 for the same period, positive after,\n * for two periods of one granularity; periods of different granularities\n * are ordered by their text.\n */\nexport function comparePeriods(a: Period, b: Period): number {\n const left = periodParts(a);\n const right = periodParts(b);\n if (left.granularity !== right.granularity) {\n return a < b ? -1 : 1;\n }\n return left.year - right.year || left.index - right.index;\n}\n\n/** The period `count` periods after `period` (before, when negative). */\nexport function addPeriods<G extends PeriodGranularity>(\n period: Period<G>,\n count: number,\n): Period<G> {\n const { granularity, year, index } = periodParts(period);\n const size = PER_YEAR[granularity];\n const place = year * size + index - 1 + count;\n return periodFrom(\n granularity as G,\n Math.floor(place / size),\n (place % size) + 1,\n );\n}\n\n/** The first day of the fiscal year named `name`. */\nfunction fiscalStart(name: number, fiscal: FiscalYear): PlainDate {\n const year = fiscal.namedBy === \"end\" && fiscal.start > 1 ? name - 1 : name;\n return plainDate(year, fiscal.start, 1);\n}\n\n/**\n * The days a period covers, half-open: `2026-11` is [2026-11-01,\n * 2026-12-01). A fiscal period counts from `fiscal`'s start month: with an\n * April start named by the year it ends in, `FY2026` is [2025-04-01,\n * 2026-04-01) and `FY2026-P04` is July 2025.\n */\nexport function periodRange(\n period: Period,\n fiscal: FiscalYear = CALENDAR_FISCAL_YEAR,\n): Range<PlainDate> {\n const { granularity, year, index } = periodParts(period);\n const months = (start: PlainDate, count: number) => ({\n start,\n end: addMonths(start, count),\n });\n switch (granularity) {\n case \"month\":\n return months(plainDate(year, index, 1), 1);\n case \"quarter\":\n return months(plainDate(year, (index - 1) * 3 + 1, 1), 3);\n case \"year\":\n return months(plainDate(year, 1, 1), 12);\n case \"fiscalMonth\":\n return months(addMonths(fiscalStart(year, fiscal), index - 1), 1);\n case \"fiscalQuarter\":\n return months(addMonths(fiscalStart(year, fiscal), (index - 1) * 3), 3);\n case \"fiscalYear\":\n return months(fiscalStart(year, fiscal), 12);\n }\n}\n\n/** The period of `granularity` that `date` falls in. */\nexport function periodOf<G extends PeriodGranularity>(\n date: PlainDate,\n granularity: G,\n fiscal: FiscalYear = CALENDAR_FISCAL_YEAR,\n): Period<G> {\n const { year, month } = dateParts(date);\n const intoYear = (month - fiscal.start + 12) % 12;\n const startYear = month >= fiscal.start ? year : year - 1;\n const name =\n fiscal.namedBy === \"end\" && fiscal.start > 1 ? startYear + 1 : startYear;\n switch (granularity) {\n case \"month\":\n return periodFrom(granularity, year, month);\n case \"quarter\":\n return periodFrom(granularity, year, Math.floor((month - 1) / 3) + 1);\n case \"year\":\n return periodFrom(granularity, year, 1);\n case \"fiscalMonth\":\n return periodFrom(granularity, name, intoYear + 1);\n case \"fiscalQuarter\":\n return periodFrom(granularity, name, Math.floor(intoYear / 3) + 1);\n default:\n return periodFrom(granularity, name, 1);\n }\n}\n\n/** The segment holding a granularity's place in its year. */\nconst PLACE_SEGMENT: Readonly<Record<PeriodGranularity, SegmentType | null>> = {\n month: \"month\",\n quarter: \"quarter\",\n year: null,\n fiscalMonth: \"period\",\n fiscalQuarter: \"quarter\",\n fiscalYear: null,\n};\n\n/** How a period field lays out its segments. */\nexport interface PeriodLayoutOptions {\n readonly locale: Intl.LocalesArgument;\n readonly granularity: PeriodGranularity;\n /** The digits segments show; the locale's by default. */\n readonly numberingSystem?: string | undefined;\n}\n\nconst periodLayouts = new WeakMap<FormsMessages, Map<string, DateLayout>>();\n\n/**\n * How a period field lays out its segments: a month as the locale writes\n * a month and year (`11/2026`, `2026/11`), a year alone, and the others\n * with the messages' prefixes as literals: `Q3 2026`, `FY2026`,\n * `FY2026 Q1`, `FY2026 P04`.\n */\nexport function periodLayout(\n options: PeriodLayoutOptions,\n messages: FormsMessages,\n): DateLayout {\n const { granularity, locale, numberingSystem } = options;\n if (granularity === \"month\" || granularity === \"year\") {\n return dateLayout(\n { locale, fields: granularity, numberingSystem },\n messages,\n );\n }\n const key = [localeKey(locale), granularity, numberingSystem ?? \"\"].join(\"|\");\n let named = periodLayouts.get(messages);\n if (named === undefined) {\n named = new Map();\n periodLayouts.set(messages, named);\n }\n let layout = named.get(key);\n if (layout === undefined) {\n const years = dateLayout(\n { locale, fields: \"year\", numberingSystem },\n messages,\n );\n const literal = (text: string) => ({ kind: \"literal\", text }) as const;\n const segment = (type: SegmentType) => ({ kind: \"segment\", type }) as const;\n const fiscalYear = [literal(messages.fiscalYearPrefix), segment(\"year\")];\n const parts: LayoutShape[\"parts\"] =\n granularity === \"quarter\"\n ? [\n literal(messages.periodQuarterPrefix),\n segment(\"quarter\"),\n literal(\" \"),\n segment(\"year\"),\n ]\n : granularity === \"fiscalYear\"\n ? fiscalYear\n : granularity === \"fiscalQuarter\"\n ? [\n ...fiscalYear,\n literal(` ${messages.periodQuarterPrefix}`),\n segment(\"quarter\"),\n ]\n : [\n ...fiscalYear,\n literal(` ${messages.fiscalPeriodPrefix}`),\n segment(\"period\"),\n ];\n layout = layoutOf(\n {\n parts,\n widths: { quarter: 1, period: 2 },\n hourCycle: null,\n dayPeriods: years.dayPeriods,\n digits: years.digits,\n },\n messages,\n );\n named.set(key, layout);\n }\n return layout;\n}\n\n/** A period written in its layout's segments: \"11/2026\", \"Q3 2026\", \"FY2026 P04\". */\nexport function formatPeriodSegments(\n layout: DateLayout,\n period: Period,\n): string {\n const { granularity, year, index } = periodParts(period);\n const place = PLACE_SEGMENT[granularity];\n return formatSegments(\n layout,\n place === null ? { year } : { year, [place]: index },\n );\n}\n\n/**\n * A period as display mode writes it: a month by `Intl` (\"November\n * 2026\"), a year by `Intl`, the others with the messages' prefixes and the\n * locale's digits (\"Q3 2026\", \"FY2026\", \"FY2026 Q1\", \"FY2026 P04\").\n */\nexport function formatPeriod(\n period: Period,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const { granularity, year, index } = periodParts(period);\n const at = epochOfWallClock(\n plainDateTime(\n plainDate(year, granularity === \"month\" ? index : 1, 1),\n \"00:00\",\n ),\n );\n if (granularity === \"month\" || granularity === \"year\") {\n return dateTimeFormat(locale, {\n ...(granularity === \"month\" ? { month: \"long\" } : {}),\n year: \"numeric\",\n timeZone: \"UTC\",\n }).format(at);\n }\n const digits = new Intl.NumberFormat(locale, { useGrouping: false });\n const number = (value: number, width = 1) =>\n digits.format(value).padStart(width, digits.format(0));\n const fiscalYear = `${messages.fiscalYearPrefix}${number(year, 4)}`;\n switch (granularity) {\n case \"quarter\":\n return `${messages.periodQuarterPrefix}${number(index)} ${number(year, 4)}`;\n case \"fiscalYear\":\n return fiscalYear;\n case \"fiscalQuarter\":\n return `${fiscalYear} ${messages.periodQuarterPrefix}${number(index)}`;\n default:\n return `${fiscalYear} ${messages.fiscalPeriodPrefix}${number(index, 2)}`;\n }\n}\n\n/** Whether a granularity's periods are whole years, which a picker shows twelve at a time. */\nfunction isYearly(granularity: PeriodGranularity): boolean {\n return PER_YEAR[granularity] === 1;\n}\n\n/** How many years a period picker's previous and next buttons move: 1, or 12 for years. */\nexport function periodPageYears(granularity: PeriodGranularity): number {\n return isYearly(granularity) ? 12 : 1;\n}\n\n/**\n * The periods a picker shows together on the page that holds `year`: that\n * year's months, quarters or fiscal periods, or for a year granularity the\n * twelve years around it (2017 to 2028 for 2026), within 1 to 9999.\n */\nexport function periodPage<G extends PeriodGranularity>(\n granularity: G,\n year: number,\n): readonly Period<G>[] {\n if (isYearly(granularity)) {\n const first = year - ((year - 1) % 12);\n return Array.from({ length: 12 }, (_, offset) => first + offset)\n .filter((listed) => listed <= 9999)\n .map((listed) => periodFrom(granularity, listed, 1));\n }\n return Array.from({ length: PER_YEAR[granularity] }, (_, offset) =>\n periodFrom(granularity, year, offset + 1),\n );\n}\n\n/**\n * A period as a picker's button writes it, without the year its page\n * names: a month's short name by `Intl` (\"Nov\"), \"Q3\", \"P04\", or a year\n * (\"2026\", \"FY2026\"), in the locale's digits.\n */\nexport function formatPeriodPlace(\n period: Period,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const { granularity, index } = periodParts(period);\n const number = (value: number, width: number) =>\n new Intl.NumberFormat(locale, {\n useGrouping: false,\n minimumIntegerDigits: width,\n }).format(value);\n switch (granularity) {\n case \"month\":\n return dateTimeFormat(locale, { month: \"short\", timeZone: \"UTC\" }).format(\n epochOfWallClock(plainDateTime(plainDate(2026, index, 1), \"00:00\")),\n );\n case \"quarter\":\n case \"fiscalQuarter\":\n return `${messages.periodQuarterPrefix}${number(index, 1)}`;\n case \"fiscalMonth\":\n return `${messages.fiscalPeriodPrefix}${number(index, 2)}`;\n default:\n return formatPeriod(period, locale, messages);\n }\n}\n\n/**\n * The title of a period picker's page that holds `year`: the year\n * (\"2026\", \"FY2026\"), or for a year granularity its first and last years\n * (\"2017 – 2028\").\n */\nexport function formatPeriodPage(\n granularity: PeriodGranularity,\n year: number,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): string {\n const page = periodPage(granularity, year);\n const first = page[0];\n const last = page.at(-1);\n if (first === undefined || last === undefined) {\n return \"\";\n }\n if (isYearly(granularity)) {\n return `${formatPeriod(first, locale, messages)} – ${formatPeriod(last, locale, messages)}`;\n }\n const fiscal = granularity.startsWith(\"fiscal\");\n return formatPeriod(\n periodFrom(fiscal ? \"fiscalYear\" : \"year\", year, 1),\n locale,\n messages,\n );\n}\n\n/** How a period field reads and writes. */\nexport interface PeriodFieldOptions<G extends PeriodGranularity = \"month\"> {\n readonly granularity: G;\n /** The fiscal year's start and naming; the calendar year by default. */\n readonly fiscalYear?: FiscalYear | undefined;\n /** The field's locale unless given. */\n readonly locale?: Intl.LocalesArgument;\n readonly numberingSystem?: string | undefined;\n /** Today in the field's zone: `t`, `+1` and `-1` count from its period, and the year pivot. */\n readonly today: () => PlainDate;\n /** `t`, `+1` and `-1` for this, next and previous period; on by default. */\n readonly shortcuts?: boolean | undefined;\n /** The segment the user is typing in, if any: a short year there is not pivoted yet. */\n readonly activeSegment?: (() => number | null) | undefined;\n}\n\n/** What a period text reads as. */\ntype PeriodReading<G extends PeriodGranularity> =\n | { readonly kind: \"empty\" }\n | { readonly kind: \"period\"; readonly period: Period<G> }\n | {\n readonly kind: \"unreadable\";\n readonly reason: \"incomplete\" | \"yearDigits\" | \"unreadable\";\n };\n\nconst UNREADABLE = { kind: \"unreadable\", reason: \"unreadable\" } as const;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/** A year typed with one, two or four digits; `null` otherwise. */\nfunction yearOf(text: string, today: PlainDate): number | null {\n if (text.length === 4) {\n return Number(text);\n }\n return text.length === 1 || text.length === 2\n ? pivotYear(Number(text), { today })\n : null;\n}\n\n/** A period from a typed year and place, or unreadable when either is wrong. */\nfunction readingOf<G extends PeriodGranularity>(\n granularity: G,\n yearText: string,\n place: number,\n today: PlainDate,\n): PeriodReading<G> {\n const year = yearOf(yearText, today);\n if (year === null || place < 1 || place > PER_YEAR[granularity]) {\n return yearText.length === 3\n ? { kind: \"unreadable\", reason: \"yearDigits\" }\n : UNREADABLE;\n }\n return { kind: \"period\", period: periodFrom(granularity, year, place) };\n}\n\n/**\n * The patterns a pasted period reads by, each giving the year and the\n * place in that order of groups, or the reverse (`placeFirst`).\n */\nfunction pastePatterns(\n granularity: PeriodGranularity,\n messages: FormsMessages,\n): readonly { readonly pattern: RegExp; readonly placeFirst: boolean }[] {\n const prefix = (ascii: string, own: string) =>\n `(?:${escapeRegExp(ascii)}|${escapeRegExp(own.toUpperCase())})`;\n const q = prefix(\"Q\", messages.periodQuarterPrefix);\n const fy = prefix(\"FY\", messages.fiscalYearPrefix);\n const p = prefix(\"P\", messages.fiscalPeriodPrefix);\n const year = String.raw`(\\d{4}|\\d{1,2})`;\n const gap = String.raw`\\s*[-/ ]?\\s*`;\n const rule = (text: string, placeFirst = false) => ({\n pattern: new RegExp(`^${text}$`, \"u\"),\n placeFirst,\n });\n switch (granularity) {\n case \"quarter\":\n return [\n rule(`${year}${gap}${q}\\\\s*([1-4])`),\n rule(`${q}\\\\s*([1-4])${gap}${year}`, true),\n rule(`([1-4])\\\\s*${q}${gap}${year}`, true),\n ];\n case \"fiscalYear\":\n return [rule(`${fy}\\\\s*${year}`)];\n case \"fiscalQuarter\":\n return [\n rule(`${fy}\\\\s*${year}${gap}${q}\\\\s*([1-4])`),\n rule(`${q}\\\\s*([1-4])${gap}${fy}\\\\s*${year}`, true),\n ];\n case \"fiscalMonth\":\n return [\n rule(`${fy}\\\\s*${year}${gap}${p}\\\\s*(\\\\d{1,2})`),\n rule(`${p}\\\\s*(\\\\d{1,2})${gap}${fy}\\\\s*${year}`, true),\n ];\n default:\n return [];\n }\n}\n\n/** A month and year pasted: \"2026-11\", \"11/2026\", \"11/26\", \"Nov 2026\", \"November 2026\". */\nfunction readMonth(\n text: string,\n layout: DateLayout,\n locale: Intl.LocalesArgument,\n today: PlainDate,\n): PeriodReading<\"month\"> {\n const numbers = /^(\\d{1,4})\\s*[-/. ]\\s*(\\d{1,4})$/u.exec(text);\n if (numbers !== null) {\n const [, first = \"\", second = \"\"] = numbers;\n const yearFirst =\n first.length === 4 ||\n (second.length !== 4 &&\n segmentIndex(layout, \"year\") < segmentIndex(layout, \"month\"));\n return yearFirst\n ? readingOf(\"month\", first, Number(second), today)\n : readingOf(\"month\", second, Number(first), today);\n }\n const named = /^(\\p{L}[\\p{L}\\p{M}]*\\.?)\\s*,?\\s*(\\d{1,4})$/u.exec(text);\n const month = named?.[1] === undefined ? null : monthOfName(named[1], locale);\n return month === null\n ? UNREADABLE\n : readingOf(\"month\", named?.[2] ?? \"\", month, today);\n}\n\n/**\n * Pasted or free period text read whole: the shortcuts (`t` this period,\n * `+1` the next, `-1` the previous), the canonical form, and the common\n * ways to write each granularity (`Q3 2026`, `3Q2026`, `FY26 P4`,\n * `Nov 2026`); one- and two-digit years pivot.\n */\nfunction readPeriodText<G extends PeriodGranularity>(\n text: string,\n options: PeriodFieldOptions<G>,\n layout: DateLayout,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): PeriodReading<G> {\n const { granularity } = options;\n const today = options.today();\n const clean = cleanDateText(text).toUpperCase();\n if (clean === \"\") {\n return { kind: \"empty\" };\n }\n const current = periodOf(today, granularity, options.fiscalYear);\n if (options.shortcuts !== false) {\n const shortcut = /^(?:(T)|([+\\-\\u{2212}])(\\d+))$/u.exec(clean);\n if (shortcut !== null) {\n const [, , sign, count = \"0\"] = shortcut;\n return {\n kind: \"period\",\n period: addPeriods(current, Number(count) * (sign === \"+\" ? 1 : -1)),\n };\n }\n }\n const canonical = toPeriod(clean, granularity);\n if (canonical !== null) {\n return { kind: \"period\", period: canonical };\n }\n if (granularity === \"year\") {\n return /^\\d{1,4}$/.test(clean)\n ? readingOf(granularity, clean, 1, today)\n : UNREADABLE;\n }\n if (granularity === \"month\") {\n return readMonth(clean, layout, locale, today) as PeriodReading<G>;\n }\n for (const { pattern, placeFirst } of pastePatterns(granularity, messages)) {\n const match = pattern.exec(clean);\n if (match !== null) {\n const [, first = \"\", second = \"\"] = match;\n const [yearText, place] = placeFirst ? [second, first] : [first, second];\n return readingOf(granularity, yearText, Number(place || 1), today);\n }\n }\n return UNREADABLE;\n}\n\n/** Segment texts read strictly: empty, incomplete while a segment is empty or the year is being typed, or the period. */\nfunction readPeriodSegments<G extends PeriodGranularity>(\n texts: readonly string[],\n options: PeriodFieldOptions<G>,\n layout: DateLayout,\n): PeriodReading<G> {\n if (texts.every((text) => text === \"\")) {\n return { kind: \"empty\" };\n }\n const yearIndex = segmentIndex(layout, \"year\");\n const yearText = texts[yearIndex] ?? \"\";\n if (\n texts.some((text) => text === \"\") ||\n (options.activeSegment?.() === yearIndex && yearText.length < 4)\n ) {\n return { kind: \"unreadable\", reason: \"incomplete\" };\n }\n const place = PLACE_SEGMENT[options.granularity];\n const placeIndex = place === null ? -1 : segmentIndex(layout, place);\n const year = String(segmentValue(layout, yearIndex, yearText) ?? \"\").padStart(\n yearText.length,\n \"0\",\n );\n return readingOf(\n options.granularity,\n year,\n placeIndex < 0\n ? 1\n : (segmentValue(layout, placeIndex, texts[placeIndex] ?? \"\") ?? 0),\n options.today(),\n );\n}\n\nfunction layoutFor<G extends PeriodGranularity>(\n options: PeriodFieldOptions<G>,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): DateLayout {\n return periodLayout(\n {\n locale: options.locale ?? locale,\n granularity: options.granularity,\n numberingSystem: options.numberingSystem,\n },\n messages,\n );\n}\n\nfunction readPeriod<G extends PeriodGranularity>(\n text: string,\n options: PeriodFieldOptions<G>,\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): PeriodReading<G> {\n const layout = layoutFor(options, locale, messages);\n const texts = splitSegments(layout, text);\n if (texts !== null) {\n const strict = readPeriodSegments(texts, options, layout);\n if (strict.kind !== \"unreadable\" || strict.reason !== \"unreadable\") {\n return strict;\n }\n }\n return readPeriodText(\n text,\n options,\n layout,\n options.locale ?? locale,\n messages,\n );\n}\n\n/**\n * A period field's own reading: its segments strictly, pasted and free\n * text leniently (shortcuts, the canonical form, `Q3 2026`, `FY26 P4`,\n * `Nov 2026`); empty as `null`. Text that is no period says \"Enter a\n * period such as Q4 2026\", the current period in the field's segments.\n */\nexport function periodParser<G extends PeriodGranularity>(\n options: PeriodFieldOptions<G>,\n): (text: string, context: ParseContext<Period<G>>) => ParseResult<Period<G>> {\n return (text, { locale, messages }) => {\n const reading = readPeriod(text, options, locale, messages);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"period\":\n return parsed(reading.period);\n case \"unreadable\": {\n if (reading.reason === \"incomplete\") {\n return unreadable(messages.dateIncomplete);\n }\n if (reading.reason === \"yearDigits\") {\n return unreadable(messages.dateYearDigits);\n }\n const example = formatPeriodSegments(\n layoutFor(options, locale, messages),\n periodOf(options.today(), options.granularity, options.fiscalYear),\n );\n return unreadable(messages.periodUnreadable(example));\n }\n }\n };\n}\n\n/** A period field's own writing: the period in its segments, whatever the purpose; `\"\"` for `null`. */\nexport function periodFormatter<G extends PeriodGranularity>(\n options: Pick<\n PeriodFieldOptions<G>,\n \"granularity\" | \"locale\" | \"numberingSystem\"\n >,\n): (value: Period<G> | null, context: FormatContext<Period<G>>) => string {\n return (value, { locale, messages }) =>\n value === null\n ? \"\"\n : formatPeriodSegments(\n periodLayout(\n {\n locale: options.locale ?? locale,\n granularity: options.granularity,\n numberingSystem: options.numberingSystem,\n },\n messages,\n ),\n value,\n );\n}\n\n/** What a period input adds to every event. */\nexport interface PeriodDetails {\n /** The days the period covers, half-open. `null` when empty. */\n readonly range: Range<PlainDate> | null;\n /** The value as display mode writes it; `\"\"` when empty. */\n readonly formatted: string;\n /** The segment the edit was in; `null` for a paste, a pick or a change from code. */\n readonly segment: \"year\" | \"month\" | \"quarter\" | \"period\" | null;\n}\n\n/** What a period field's events carry, for its state and the event's cause. */\nexport function periodDetails<G extends PeriodGranularity>(\n state: FieldState<Period<G>>,\n cause: ChangeCause<unknown> | null,\n options: PeriodFieldOptions<G> & {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n },\n): PeriodDetails {\n const { value } = state;\n const { locale, messages } = options;\n const layout = layoutFor(options, locale, messages);\n const text =\n state.draft.kind === \"text\"\n ? state.draft.text\n : value === null\n ? \"\"\n : formatPeriodSegments(layout, value);\n const at = cause?.input?.selectionStart ?? null;\n const spans =\n at === null || cause?.source === \"paste\" || cause?.source === \"drop\"\n ? null\n : segmentSpans(layout, text);\n const index =\n spans === null || at === null\n ? -1\n : spans.findIndex(([start, end]) => start <= at && at <= end);\n const type = layout.segments[index]?.type;\n return {\n range: value === null ? null : periodRange(value, options.fiscalYear),\n formatted: value === null ? \"\" : formatPeriod(value, locale, messages),\n segment:\n type === \"year\" ||\n type === \"month\" ||\n type === \"quarter\" ||\n type === \"period\"\n ? type\n : null,\n };\n}\n","import type { Validator, ValidatorContext } from \"../validation/validators\";\nimport {\n formatDate,\n formatDateTime,\n formatInstant,\n formatTime,\n} from \"./format\";\nimport {\n comparePeriods,\n formatPeriod,\n type Period,\n type PeriodGranularity,\n} from \"./period\";\nimport {\n compareDates,\n compareDateTimes,\n compareInstants,\n compareTimes,\n type Instant,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n} from \"./values\";\n\n/** How one value type orders and writes its limits. */\ninterface LimitType<V> {\n readonly compare: (a: V, b: V) => number;\n readonly write: (limit: V, context: ValidatorContext) => string;\n}\n\n/** A value before `min` is `messages.tooEarly`, after `max` `messages.tooLate`, the limit written by `type`. */\nfunction limitRule<V>(\n type: LimitType<V>,\n limit: V,\n side: \"min\" | \"max\",\n): Validator<V> {\n return (value, context) => {\n if (value === null) {\n return null;\n }\n const order = type.compare(value, limit);\n if (side === \"min\" && order < 0) {\n return {\n text: context.messages.tooEarly(type.write(limit, context)),\n code: \"tooEarly\",\n };\n }\n if (side === \"max\" && order > 0) {\n return {\n text: context.messages.tooLate(type.write(limit, context)),\n code: \"tooLate\",\n };\n }\n return null;\n };\n}\n\nconst dates = (options?: Intl.DateTimeFormatOptions): LimitType<PlainDate> => ({\n compare: compareDates,\n write: (limit, { locale }) => formatDate(limit, locale, options),\n});\n\nconst times = (options?: Intl.DateTimeFormatOptions): LimitType<PlainTime> => ({\n compare: compareTimes,\n write: (limit, { locale }) => formatTime(limit, locale, options),\n});\n\nconst dateTimes = (\n options?: Intl.DateTimeFormatOptions,\n): LimitType<PlainDateTime> => ({\n compare: compareDateTimes,\n write: (limit, { locale }) => formatDateTime(limit, locale, options),\n});\n\nconst instants = (\n timeZone: string,\n options?: Intl.DateTimeFormatOptions,\n): LimitType<Instant> => ({\n compare: compareInstants,\n write: (limit, { locale }) => formatInstant(limit, timeZone, locale, options),\n});\n\n/**\n * A day before `min` is `messages.tooEarly`, \"Enter Mar 1, 2026 or later\",\n * the limit in display form (`displayFormat`, the field's, else\n * `dateStyle: \"medium\"`) in the validator's locale. Inclusive; `null`\n * passes.\n */\nexport function minDateRule(\n min: PlainDate,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDate> {\n return limitRule(dates(displayFormat), min, \"min\");\n}\n\n/** A day after `max` is `messages.tooLate`, \"Enter Mar 31, 2026 or earlier\"; otherwise as `minDateRule`. */\nexport function maxDateRule(\n max: PlainDate,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDate> {\n return limitRule(dates(displayFormat), max, \"max\");\n}\n\n/** A time of day before `min` is `messages.tooEarly`; as `minDateRule`. */\nexport function minTimeRule(\n min: PlainTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainTime> {\n return limitRule(times(displayFormat), min, \"min\");\n}\n\n/** A time of day after `max` is `messages.tooLate`; as `maxDateRule`. */\nexport function maxTimeRule(\n max: PlainTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainTime> {\n return limitRule(times(displayFormat), max, \"max\");\n}\n\n/** A wall clock before `min` is `messages.tooEarly`; as `minDateRule`. */\nexport function minDateTimeRule(\n min: PlainDateTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDateTime> {\n return limitRule(dateTimes(displayFormat), min, \"min\");\n}\n\n/** A wall clock after `max` is `messages.tooLate`; as `maxDateRule`. */\nexport function maxDateTimeRule(\n max: PlainDateTime,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<PlainDateTime> {\n return limitRule(dateTimes(displayFormat), max, \"max\");\n}\n\n/** A moment before `min` is `messages.tooEarly`, the limit written in `timeZone`; as `minDateRule`. */\nexport function minInstantRule(\n min: Instant,\n timeZone: string,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<Instant> {\n return limitRule(instants(timeZone, displayFormat), min, \"min\");\n}\n\n/** A moment after `max` is `messages.tooLate`, the limit written in `timeZone`; as `maxDateRule`. */\nexport function maxInstantRule(\n max: Instant,\n timeZone: string,\n displayFormat?: Intl.DateTimeFormatOptions,\n): Validator<Instant> {\n return limitRule(instants(timeZone, displayFormat), max, \"max\");\n}\n\nconst periods = <G extends PeriodGranularity>(): LimitType<Period<G>> => ({\n compare: comparePeriods,\n write: (limit, { locale, messages }) => formatPeriod(limit, locale, messages),\n});\n\n/**\n * A period before `min` is `messages.tooEarly`, \"Enter Q2 2026 or later\",\n * the limit as display mode writes it, in the validator's locale.\n * Inclusive; `null` passes.\n */\nexport function minPeriodRule<G extends PeriodGranularity>(\n min: Period<G>,\n): Validator<Period<G>> {\n return limitRule(periods<G>(), min, \"min\");\n}\n\n/** A period after `max` is `messages.tooLate`; as `minPeriodRule`. */\nexport function maxPeriodRule<G extends PeriodGranularity>(\n max: Period<G>,\n): Validator<Period<G>> {\n return limitRule(periods<G>(), max, \"max\");\n}\n\n/**\n * A day `isDateDisabled` marks is `messages.dateUnavailable`, \"This date\n * isn't available\". For a wall clock, its day is checked. `null` passes.\n */\nexport function availableDateRule<V extends PlainDate | PlainDateTime>(\n isDateDisabled: (date: PlainDate) => boolean,\n): Validator<V> {\n return (value, { messages }) =>\n value !== null && isDateDisabled(value.slice(0, 10) as PlainDate)\n ? { text: messages.dateUnavailable, code: \"dateUnavailable\" }\n : null;\n}\n","import { compareDates, type PlainDate } from \"./values\";\n\n/**\n * Where picking a range of days in a calendar stands: nothing picked yet;\n * a first day chosen (the anchor), waiting for the other end while\n * `target`, the day under the pointer or focus, previews it; or a mouse or\n * pen pressed on a day and dragged to `target`. `fromAnchor` marks a press\n * made while an anchor was already set, which picks the other end even\n * when it lets go on the anchor itself.\n */\nexport type RangePick =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"anchored\";\n readonly anchor: PlainDate;\n readonly target: PlainDate;\n }\n | {\n readonly kind: \"dragging\";\n readonly anchor: PlainDate;\n readonly target: PlainDate;\n readonly fromAnchor: boolean;\n };\n\n/** The days a range covers, both ends included and in order. */\nexport interface PickedDays {\n readonly first: PlainDate;\n readonly last: PlainDate;\n}\n\n/** What can happen while a range is picked. */\nexport type RangePickAction =\n /** A day clicked, tapped, or chosen with Enter or Space. */\n | { readonly type: \"choose\"; readonly date: PlainDate }\n /** The pointer moved over a day, or focus moved to one. */\n | { readonly type: \"preview\"; readonly date: PlainDate }\n /** A mouse or pen pressed on a day. */\n | { readonly type: \"press\"; readonly date: PlainDate }\n /** That press let go. */\n | { readonly type: \"release\" }\n /** That press lost its pointer: cancelled, or its capture taken. */\n | { readonly type: \"lose\" }\n /** Escape: a range in progress is dropped. */\n | { readonly type: \"cancel\" };\n\n/** The picking state after an action, and the days it picked, if it finished a range. */\nexport interface RangePickStep {\n readonly state: RangePick;\n readonly picked: PickedDays | null;\n}\n\nconst IDLE: RangePick = { kind: \"idle\" };\n\n/** `a` and `b` as a range's first and last days, whichever comes first. */\nexport function pickedDays(a: PlainDate, b: PlainDate): PickedDays {\n return compareDates(a, b) <= 0\n ? { first: a, last: b }\n : { first: b, last: a };\n}\n\n/** The days a range in progress would cover now: anchor to target. `null` while nothing is anchored. */\nexport function rangePickPreview(state: RangePick): PickedDays | null {\n return state.kind === \"idle\" ? null : pickedDays(state.anchor, state.target);\n}\n\n/**\n * Picking a range of days after `action`. A choice sets the anchor, then\n * the other end, which finishes the range; a press and a release on\n * another day finish it in one gesture, while a release where the press\n * began leaves that day anchored, as a click would. A day `selectable`\n * refuses cannot be an end: choosing one does nothing, and a drag let go\n * over one keeps its anchor. Escape drops the range in progress.\n */\nexport function rangePickReducer(\n state: RangePick,\n action: RangePickAction,\n selectable: (date: PlainDate) => boolean,\n): RangePickStep {\n const stay: RangePickStep = { state, picked: null };\n switch (action.type) {\n case \"choose\": {\n if (state.kind === \"dragging\" || !selectable(action.date)) {\n return stay;\n }\n if (state.kind === \"idle\") {\n return {\n state: { kind: \"anchored\", anchor: action.date, target: action.date },\n picked: null,\n };\n }\n return { state: IDLE, picked: pickedDays(state.anchor, action.date) };\n }\n case \"preview\":\n return state.kind === \"idle\" || state.target === action.date\n ? stay\n : { state: { ...state, target: action.date }, picked: null };\n case \"press\":\n if (state.kind === \"anchored\") {\n return {\n state: {\n kind: \"dragging\",\n anchor: state.anchor,\n target: action.date,\n fromAnchor: true,\n },\n picked: null,\n };\n }\n return state.kind === \"idle\" && selectable(action.date)\n ? {\n state: {\n kind: \"dragging\",\n anchor: action.date,\n target: action.date,\n fromAnchor: false,\n },\n picked: null,\n }\n : stay;\n case \"release\": {\n if (state.kind !== \"dragging\") {\n return stay;\n }\n const { anchor, target, fromAnchor } = state;\n const anchored: RangePick = { kind: \"anchored\", anchor, target };\n if (!selectable(target) || (!fromAnchor && target === anchor)) {\n return { state: anchored, picked: null };\n }\n return { state: IDLE, picked: pickedDays(anchor, target) };\n }\n case \"lose\":\n if (state.kind !== \"dragging\") {\n return stay;\n }\n return {\n state: state.fromAnchor\n ? { kind: \"anchored\", anchor: state.anchor, target: state.anchor }\n : IDLE,\n picked: null,\n };\n case \"cancel\":\n return state.kind === \"idle\" ? stay : { state: IDLE, picked: null };\n }\n}\n","import type { ChangeSource } from \"../field/events\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { digitValue, isDigit } from \"../number/digits\";\nimport type { StepDirection, StepSize } from \"../number/stepNumber\";\nimport {\n joinSegments,\n maxDigits,\n segmentIndex,\n segmentValue,\n shownHour,\n splitSegments,\n writeSegment,\n type DateLayout,\n type SegmentType,\n} from \"./layout\";\nimport { dateTimeFormat } from \"./format\";\nimport { cleanDateText, foldWord } from \"./text\";\nimport { daysInMonth } from \"./values\";\n\n/**\n * Where typing in a segmented field stands:\n *\n * - `idle`: focus is elsewhere.\n * - `active`: a segment has focus and nothing is typed into it yet; a\n * digit replaces what it holds. `advanced`: typing or a separator moved\n * focus here, so a separator typed now does nothing (`3/14` and `314`\n * both work).\n * - `typing`: digits typed into a segment that can take more.\n * - `composing`: an input method owns a segment's text until it ends.\n * - `text`: the free-text box shows, for a shortcut; `before` is the\n * segments' text to go back to.\n */\nexport type SegmentEntry =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"active\";\n readonly segment: number;\n readonly advanced: boolean;\n }\n | {\n readonly kind: \"typing\";\n readonly segment: number;\n readonly digits: string;\n }\n | { readonly kind: \"composing\"; readonly segment: number }\n | { readonly kind: \"text\"; readonly before: string };\n\n/** What happened in a segmented field, as forms-dom reports it. */\nexport type SegmentAction =\n | { readonly type: \"focus\"; readonly segment: number }\n /** Characters typed into the active segment. */\n | { readonly type: \"key\"; readonly text: string }\n | { readonly type: \"backspace\" }\n | { readonly type: \"delete\" }\n /** ArrowUp and ArrowDown (`step`), PageUp and PageDown (`large`), Home and End (`edge`). */\n | {\n readonly type: \"step\";\n readonly direction: StepDirection;\n readonly size: StepSize;\n }\n | { readonly type: \"move\"; readonly to: \"next\" | \"previous\" }\n | { readonly type: \"paste\"; readonly text: string }\n | { readonly type: \"compositionStart\" }\n | { readonly type: \"compositionEnd\"; readonly text: string }\n /** The free-text box's text changed; `source` is `\"typing\"` unless given. */\n | {\n readonly type: \"textEdit\";\n readonly text: string;\n readonly source?: ChangeSource | undefined;\n }\n /** Enter: the active segment is finished before the field commits. */\n | { readonly type: \"finish\" }\n /** Focus left the field. */\n | { readonly type: \"leave\" }\n /** The field's text changed from outside: a controlled value, a revert, a clear, a commit. */\n | { readonly type: \"outside\"; readonly text: string };\n\nexport interface SegmentState {\n readonly entry: SegmentEntry;\n /** The field's text: the segments joined by the layout's literals, or the free text. */\n readonly text: string;\n}\n\n/** What the reducer needs to know about the field. */\nexport interface SegmentContext {\n readonly layout: DateLayout;\n /**\n * Where an empty segment steps from: today's year, month or day, 0 for\n * a time. An hour is given 0 to 23 and shown in the layout's cycle; the\n * day period 0 for the morning, 1 for the afternoon.\n */\n readonly reference: (segment: SegmentType) => number;\n /** The year a one- or two-digit year left in a segment means. */\n readonly pivotYear: (digits: number) => number;\n /** Whether letters and signs in a date segment open the free-text box. */\n readonly shortcuts: boolean;\n /** The field's text for a pasted or one-letter text that reads as a value, else `null`. */\n readonly readWhole: (text: string) => string | null;\n /** What ArrowUp and ArrowDown add to the minutes, snapping to it; 1 by default. */\n readonly minuteStep?: number | undefined;\n /**\n * Whether a step may leave the segments as `texts`: the renderer checks\n * them against `min` and `max`, so stepping never leaves the limits.\n * Every step is allowed without it.\n */\n readonly allows?: ((texts: readonly string[]) => boolean) | undefined;\n}\n\n/** What one action did. */\nexport interface SegmentStep {\n readonly state: SegmentState;\n /** What has focus afterwards: a segment, the free-text box, or nothing (idle). */\n readonly focus: number | \"text\" | null;\n /** What the change was, for the event; `null` when the text did not change. */\n readonly source: ChangeSource | null;\n /**\n * A one-letter free text applied at once (`t`): forms-dom reports it as\n * typed before the segments it gave, so the events name the shortcut.\n * Absent otherwise.\n */\n readonly applied?: string;\n}\n\nconst IDLE: SegmentEntry = { kind: \"idle\" };\n\nconst DATE_TYPES: ReadonlySet<SegmentType> = new Set<SegmentType>([\n \"year\",\n \"month\",\n \"day\",\n \"quarter\",\n \"period\",\n]);\n\n/** How far PageUp and PageDown step each segment. */\nconst LARGE_STEPS: Readonly<Record<SegmentType, number>> = {\n year: 10,\n month: 3,\n day: 7,\n hour: 10,\n minute: 10,\n second: 10,\n dayPeriod: 1,\n quarter: 1,\n period: 3,\n};\n\n/** Separators typed between segments, beside the layout's own literals. */\nconst SEPARATORS = \"/.-,:\";\n/** The signs that open a shortcut: plus, hyphen-minus and the minus sign. */\nconst SIGNS = \"+-\\u{2212}\";\n\nfunction focusOf(entry: SegmentEntry): number | \"text\" | null {\n switch (entry.kind) {\n case \"idle\":\n return null;\n case \"text\":\n return \"text\";\n default:\n return entry.segment;\n }\n}\n\n/** The segment typing is in, or `null`. */\nfunction segmentOf(entry: SegmentEntry): number | null {\n return entry.kind === \"active\" ||\n entry.kind === \"typing\" ||\n entry.kind === \"composing\"\n ? entry.segment\n : null;\n}\n\n/** The last date segment in typing order, where a shortcut leaves focus. */\nfunction lastDateSegment(layout: DateLayout): number {\n const last = layout.segments.findLastIndex((segment) =>\n DATE_TYPES.has(segment.type),\n );\n return Math.max(last, 0);\n}\n\n/** The field's state as it is worked on within one action. */\ninterface Draft {\n entry: SegmentEntry;\n texts: string[];\n /** The free text, while the entry is `text`. */\n free: string;\n /** A one-letter free text applied at once, if any. */\n applied: string | null;\n}\n\nfunction draftOf(state: SegmentState, layout: DateLayout): Draft {\n const texts =\n state.entry.kind === \"text\"\n ? splitSegments(layout, state.entry.before)\n : splitSegments(layout, state.text);\n return {\n entry: state.entry,\n texts: [...(texts ?? layout.segments.map(() => \"\"))],\n free: state.entry.kind === \"text\" ? state.text : \"\",\n applied: null,\n };\n}\n\nfunction textOf(draft: Draft, layout: DateLayout): string {\n return draft.entry.kind === \"text\"\n ? draft.free\n : joinSegments(layout, draft.texts);\n}\n\nfunction stepOf(\n before: SegmentState,\n draft: Draft,\n context: SegmentContext,\n source: ChangeSource,\n): SegmentStep {\n const text = textOf(draft, context.layout);\n return {\n state:\n text === before.text && draft.entry === before.entry\n ? before\n : { entry: draft.entry, text },\n focus: focusOf(draft.entry),\n source: text === before.text ? null : source,\n ...(draft.applied === null ? {} : { applied: draft.applied }),\n };\n}\n\n/** `digits` (ASCII) written in the layout's digits, leading zeros kept. */\nfunction localDigits(layout: DateLayout, digits: string): string {\n return digits.replace(\n /\\d/g,\n (digit) => layout.digits[Number(digit)] ?? digit,\n );\n}\n\n/**\n * Pads segment `index` to its width, a one- or two-digit year pivoted;\n * an empty segment, a day period and a three-digit year stay as they are.\n */\nfunction finish(draft: Draft, index: number, context: SegmentContext): void {\n const { layout } = context;\n const segment = layout.segments[index];\n const text = draft.texts[index] ?? \"\";\n const value = segmentValue(layout, index, text);\n if (segment === undefined || value === null || segment.type === \"dayPeriod\") {\n return;\n }\n if (segment.type === \"year\") {\n if (text.length <= 2) {\n draft.texts[index] = writeSegment(\n layout,\n index,\n context.pivotYear(value),\n );\n }\n return;\n }\n draft.texts[index] = writeSegment(layout, index, value);\n}\n\n/** The segment after `index` in typing order, or `index` itself at the end. */\nfunction next(layout: DateLayout, index: number): number {\n return Math.min(index + 1, layout.segments.length - 1);\n}\n\nfunction isSeparator(layout: DateLayout, char: string): boolean {\n if (/\\s/.test(char) || SEPARATORS.includes(char)) {\n return true;\n }\n return layout.parts.some(\n (part) =>\n part.kind === \"literal\" && !isDigit(char) && part.text.includes(char),\n );\n}\n\n/** Types digit `digit` (0 to 9) into the active segment. */\nfunction typeDigit(draft: Draft, digit: number, context: SegmentContext): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined || segment.type === \"dayPeriod\") {\n return;\n }\n const most = maxDigits(layout, index);\n const fits = (digits: string) => {\n const value = Number(digits);\n return (\n value <= segment.max && (digits.length < most || value >= segment.min)\n );\n };\n const buffer = draft.entry.kind === \"typing\" ? draft.entry.digits : \"\";\n let digits = `${buffer}${String(digit)}`;\n if (!fits(digits)) {\n digits = String(digit);\n if (!fits(digits)) {\n return;\n }\n }\n const complete = digits.length === most || Number(digits) * 10 > segment.max;\n if (complete) {\n draft.texts[index] = writeSegment(layout, index, Number(digits));\n const after = next(layout, index);\n draft.entry = { kind: \"active\", segment: after, advanced: after !== index };\n } else {\n draft.texts[index] = localDigits(layout, digits);\n draft.entry = { kind: \"typing\", segment: index, digits };\n }\n}\n\n/** Sets the day period from a letter: the first letter of one of the locale's, or `a` and `p`. */\nfunction typeDayPeriod(\n draft: Draft,\n char: string,\n context: SegmentContext,\n): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n if (index === null) {\n return;\n }\n const letter = foldWord(char);\n const english: readonly string[] = [\"a\", \"p\"];\n const matches = ([0, 1] as const).filter(\n (period) =>\n foldWord(layout.dayPeriods[period]).startsWith(letter) ||\n english[period] === letter,\n );\n const [only] = matches;\n if (only === undefined || matches.length > 1) {\n return;\n }\n draft.texts[index] = writeSegment(layout, index, only);\n const after = next(layout, index);\n draft.entry = { kind: \"active\", segment: after, advanced: after !== index };\n}\n\n/** Opens the free-text box with `char`, applying it at once when one letter reads as a value. */\nfunction openText(draft: Draft, char: string, context: SegmentContext): void {\n const { layout } = context;\n draft.entry = { kind: \"text\", before: joinSegments(layout, draft.texts) };\n draft.free = char;\n applyOneLetter(draft, context);\n}\n\n/** A one-letter free text that reads (`t`, `s`, `e`, an app's own word) is applied and the segments return. */\nfunction applyOneLetter(draft: Draft, context: SegmentContext): void {\n if (Array.from(draft.free).length !== 1) {\n return;\n }\n const whole = context.readWhole(draft.free);\n const texts = whole === null ? null : splitSegments(context.layout, whole);\n if (texts === null) {\n return;\n }\n draft.applied = draft.free;\n draft.texts = [...texts];\n draft.entry = {\n kind: \"active\",\n segment: lastDateSegment(context.layout),\n advanced: false,\n };\n}\n\n/** One character typed while a segment has focus. */\nfunction typeChar(draft: Draft, char: string, context: SegmentContext): void {\n const { layout } = context;\n if (draft.entry.kind === \"text\") {\n draft.free += char;\n return;\n }\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined) {\n return;\n }\n if (isDigit(char)) {\n typeDigit(draft, digitValue(char), context);\n return;\n }\n if (segment.type === \"dayPeriod\" && /\\p{L}/u.test(char)) {\n typeDayPeriod(draft, char, context);\n return;\n }\n const filled = (draft.texts[index] ?? \"\") !== \"\";\n const advanced = draft.entry.kind === \"active\" && draft.entry.advanced;\n const opensText =\n context.shortcuts &&\n DATE_TYPES.has(segment.type) &&\n (/\\p{L}/u.test(char) || SIGNS.includes(char));\n if (isSeparator(layout, char) && (!opensText || filled || advanced)) {\n if (advanced) {\n draft.entry = { kind: \"active\", segment: index, advanced: false };\n } else if (filled) {\n finish(draft, index, context);\n const after = next(layout, index);\n draft.entry = {\n kind: \"active\",\n segment: after,\n advanced: after !== index,\n };\n }\n return;\n }\n if (opensText) {\n openText(draft, char, context);\n }\n}\n\nfunction typeText(draft: Draft, text: string, context: SegmentContext): void {\n for (const char of text) {\n typeChar(draft, char, context);\n }\n}\n\n/** The days segment `day` steps within: its month's, once the month (and year) are set. */\nfunction dayLimit(texts: readonly string[], layout: DateLayout): number {\n const value = (type: SegmentType) => {\n const index = segmentIndex(layout, type);\n return index < 0 ? null : segmentValue(layout, index, texts[index] ?? \"\");\n };\n const month = value(\"month\");\n if (month === null || month < 1 || month > 12) {\n return 31;\n }\n // Without a year, February may have 29 days.\n return daysInMonth(value(\"year\") ?? 2000, month);\n}\n\n/** Where a step takes segment `index` from `value`, wrapping within `low` to `high`. */\nfunction stepped(\n type: SegmentType,\n value: number,\n direction: StepDirection,\n size: StepSize,\n [low, high]: readonly [number, number],\n minuteStep: number,\n): number {\n if (size === \"edge\") {\n return direction === \"up\" ? high : low;\n }\n const count = high - low + 1;\n const wrap = (to: number) => low + ((((to - low) % count) + count) % count);\n const from = Math.min(value, high);\n if (type === \"minute\" && size === \"step\" && minuteStep > 1) {\n const snapped =\n direction === \"up\"\n ? Math.floor(from / minuteStep) * minuteStep + minuteStep\n : Math.ceil(from / minuteStep) * minuteStep - minuteStep;\n return wrap(snapped);\n }\n const amount = size === \"large\" ? LARGE_STEPS[type] : 1;\n return wrap(from + (direction === \"up\" ? amount : -amount));\n}\n\n/** The day clamped to its month's last day after the month or year changed: 31 January, month up, is 28 February. */\nfunction clampDay(draft: Draft, layout: DateLayout): void {\n const day = segmentIndex(layout, \"day\");\n const value =\n day < 0 ? null : segmentValue(layout, day, draft.texts[day] ?? \"\");\n const limit = dayLimit(draft.texts, layout);\n if (value !== null && value > limit) {\n draft.texts[day] = writeSegment(layout, day, limit);\n }\n}\n\n/** ArrowUp, ArrowDown, PageUp, PageDown, Home and End on the active segment. */\nfunction step(\n draft: Draft,\n direction: StepDirection,\n size: StepSize,\n context: SegmentContext,\n): void {\n const { layout } = context;\n const index = segmentOf(draft.entry);\n const segment = index === null ? undefined : layout.segments[index];\n if (index === null || segment === undefined) {\n return;\n }\n const { type } = segment;\n const current = segmentValue(layout, index, draft.texts[index] ?? \"\");\n const range: readonly [number, number] = [\n segment.min,\n type === \"day\" ? dayLimit(draft.texts, layout) : segment.max,\n ];\n const candidates = (): number[] => {\n if (type === \"dayPeriod\") {\n if (size === \"edge\") {\n return [direction === \"up\" ? 1 : 0];\n }\n return [current === null ? context.reference(type) : 1 - current];\n }\n if (current === null && size !== \"edge\") {\n const reference = context.reference(type);\n return [\n type === \"hour\" ? shownHour(reference, layout.hourCycle) : reference,\n ];\n }\n if (size === \"edge\") {\n // Home and End go to the limit the field allows nearest the segment's own.\n const all = Array.from(\n { length: range[1] - range[0] + 1 },\n (_, offset) => range[0] + offset,\n );\n return direction === \"up\" ? all.reverse() : all;\n }\n return [\n stepped(\n type,\n current ?? range[0],\n direction,\n size,\n range,\n context.minuteStep ?? 1,\n ),\n ];\n };\n for (const value of candidates()) {\n const texts = [...draft.texts];\n texts[index] = writeSegment(layout, index, value);\n const trial: Draft = { ...draft, texts };\n if (type === \"month\" || type === \"year\") {\n clampDay(trial, layout);\n }\n if (context.allows === undefined || context.allows(trial.texts)) {\n draft.texts = trial.texts;\n break;\n }\n }\n draft.entry = { kind: \"active\", segment: index, advanced: false };\n}\n\n/** Moves from the active segment to `to`, finishing it. */\nfunction moveTo(draft: Draft, to: number, context: SegmentContext): void {\n const index = segmentOf(draft.entry);\n if (index !== null && draft.entry.kind !== \"composing\") {\n finish(draft, index, context);\n }\n draft.entry = { kind: \"active\", segment: to, advanced: false };\n}\n\n/** Whether `text` is digits that fit segment `index` whole, as a paste typed into it. */\nfunction fitsSegment(\n text: string,\n index: number,\n context: SegmentContext,\n): boolean {\n const { layout } = context;\n const segment = layout.segments[index];\n const digits = cleanDateText(text);\n return (\n segment !== undefined &&\n segment.type !== \"dayPeriod\" &&\n /^\\d+$/.test(digits) &&\n digits.length <= maxDigits(layout, index) &&\n Number(digits) <= segment.max\n );\n}\n\n/**\n * Every transition of a segmented field's typing, pure: forms-dom splits\n * the controller's text into segments before each action and reports\n * what comes back. Typing moves on once a segment is complete (a digit\n * that cannot start a longer number, or the segment's width reached); a\n * digit that would leave the segment's range starts it again (1 then 3 in\n * a month gives 03). Separators finish a segment; Backspace in an empty\n * one goes back. Steps wrap, a day within its month, and clamp the day\n * when the month or year changes; a step the field does not allow\n * (`allows`) is not taken. Leaving a segment pads it and pivots a short\n * year. In a date segment with shortcuts on, a letter or a sign opens the\n * free-text box; a one-letter text that reads is applied at once.\n */\nexport function segmentReducer(\n state: SegmentState,\n action: SegmentAction,\n context: SegmentContext,\n): SegmentStep {\n const { layout } = context;\n const draft = draftOf(state, layout);\n const active = segmentOf(draft.entry);\n const unchanged: SegmentStep = {\n state,\n focus: focusOf(state.entry),\n source: null,\n };\n switch (action.type) {\n case \"focus\": {\n if (draft.entry.kind === \"text\" || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n if (splitSegments(layout, state.text) === null) {\n // Free text left in the field, a shortcut that did not read, goes on in the free-text box.\n const entry: SegmentEntry = { kind: \"text\", before: \"\" };\n return {\n state: { entry, text: state.text },\n focus: \"text\",\n source: null,\n };\n }\n moveTo(draft, action.segment, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"key\": {\n if (draft.entry.kind === \"idle\" || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n typeText(draft, action.text, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"backspace\": {\n if (active === null) {\n return unchanged;\n }\n const text = draft.texts[active] ?? \"\";\n if (text === \"\") {\n draft.entry = {\n kind: \"active\",\n segment: Math.max(active - 1, 0),\n advanced: false,\n };\n return stepOf(state, draft, context, \"typing\");\n }\n const isPeriod = layout.segments[active]?.type === \"dayPeriod\";\n const rest = isPeriod ? \"\" : Array.from(text).slice(0, -1).join(\"\");\n draft.texts[active] = rest;\n draft.entry =\n rest === \"\"\n ? { kind: \"active\", segment: active, advanced: false }\n : { kind: \"typing\", segment: active, digits: cleanDateText(rest) };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"delete\": {\n if (active === null) {\n return unchanged;\n }\n draft.texts[active] = \"\";\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"step\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n step(draft, action.direction, action.size, context);\n return stepOf(state, draft, context, \"step\");\n }\n case \"move\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n const to =\n action.to === \"next\" ? next(layout, active) : Math.max(active - 1, 0);\n moveTo(draft, to, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"paste\": {\n const whole = context.readWhole(action.text);\n const texts = whole === null ? null : splitSegments(layout, whole);\n if (texts !== null) {\n draft.texts = [...texts];\n draft.entry = { kind: \"active\", segment: active ?? 0, advanced: false };\n return stepOf(state, draft, context, \"paste\");\n }\n if (active !== null && fitsSegment(action.text, active, context)) {\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n typeText(draft, cleanDateText(action.text), context);\n return stepOf(state, draft, context, \"paste\");\n }\n return unchanged;\n }\n case \"compositionStart\": {\n if (active === null) {\n return unchanged;\n }\n draft.entry = { kind: \"composing\", segment: active };\n return stepOf(state, draft, context, \"typing\");\n }\n case \"compositionEnd\": {\n if (active === null) {\n return unchanged;\n }\n draft.entry = { kind: \"active\", segment: active, advanced: false };\n typeText(draft, action.text, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"textEdit\": {\n if (draft.entry.kind !== \"text\") {\n return unchanged;\n }\n if (action.text === \"\") {\n draft.entry = { kind: \"active\", segment: 0, advanced: false };\n return stepOf(state, draft, context, \"typing\");\n }\n draft.free = action.text;\n applyOneLetter(draft, context);\n return stepOf(state, draft, context, action.source ?? \"typing\");\n }\n case \"finish\": {\n if (active === null || draft.entry.kind === \"composing\") {\n return unchanged;\n }\n moveTo(draft, active, context);\n return stepOf(state, draft, context, \"typing\");\n }\n case \"leave\": {\n if (active !== null && draft.entry.kind !== \"composing\") {\n finish(draft, active, context);\n }\n const text = textOf(draft, layout);\n return {\n state: { entry: IDLE, text },\n focus: null,\n source: text === state.text ? null : \"typing\",\n };\n }\n case \"outside\": {\n const texts = splitSegments(layout, action.text);\n let entry = state.entry;\n if (texts === null && entry.kind !== \"idle\" && entry.kind !== \"text\") {\n entry = { kind: \"text\", before: \"\" };\n } else if (entry.kind === \"typing\") {\n entry = { kind: \"active\", segment: entry.segment, advanced: false };\n } else if (entry.kind === \"text\" && texts !== null) {\n entry = {\n kind: \"active\",\n segment: lastDateSegment(layout),\n advanced: false,\n };\n }\n return {\n state: { entry, text: action.text },\n focus: focusOf(entry),\n source: null,\n };\n }\n }\n}\n\n/** A state in which no segment has focus, showing `text`. */\nexport function idleSegments(text: string): SegmentState {\n return { entry: IDLE, text };\n}\n\n/** What a segment's spinbutton tells assistive technology. */\nexport interface SegmentAria {\n /** The number it holds; `null` while empty. A day period is 0 or 1. */\n readonly valueNow: number | null;\n readonly valueMin: number;\n /** The segment's highest value; a day's follows its month once the month is set. */\n readonly valueMax: number;\n /** The month's name, the day period's text, the digits; `messages.segmentEmpty` while empty. */\n readonly valueText: string;\n}\n\n/**\n * The value, range and value text of segment `index` among the field's\n * segment `texts`, for its `aria-valuenow`, `aria-valuemin`,\n * `aria-valuemax` and `aria-valuetext`: a month reads as its name in\n * `locale` (\"March\"), a day period as its text, anything else as its\n * digits, and an empty segment as \"Empty\".\n */\nexport function segmentAria(\n layout: DateLayout,\n index: number,\n texts: readonly string[],\n locale: Intl.LocalesArgument,\n messages: FormsMessages,\n): SegmentAria {\n const segment = layout.segments[index];\n const text = texts[index] ?? \"\";\n const valueNow = segmentValue(layout, index, text);\n const valueMin = segment?.min ?? 0;\n const valueMax =\n segment?.type === \"day\" ? dayLimit(texts, layout) : (segment?.max ?? 0);\n if (valueNow === null) {\n return { valueNow, valueMin, valueMax, valueText: messages.segmentEmpty };\n }\n const valueText =\n segment?.type === \"month\" && valueNow >= 1 && valueNow <= 12\n ? dateTimeFormat(locale, { month: \"long\", timeZone: \"UTC\" }).format(\n Date.UTC(2026, valueNow - 1, 1),\n )\n : text;\n return { valueNow, valueMin, valueMax, valueText };\n}\n","import { shownHour, writeSegment, type DateLayout } from \"./layout\";\nimport {\n compareDates,\n plainTime,\n splitDateTime,\n timeParts,\n type PlainDate,\n type PlainDateTime,\n type PlainTime,\n type TimeParts,\n} from \"./values\";\n\n/** A column of a time picker: one per time segment of the field's layout. */\nexport type TimeColumnType = \"hour\" | \"minute\" | \"second\" | \"dayPeriod\";\n\n/** One choice in a time picker's column. */\nexport interface TimeColumnOption {\n /**\n * What the column sets: the hour of the day (0 to 23), or of the half\n * day (0 to 11) in a 12-hour cycle; the minute; the second; 0 for the\n * morning and 1 for the afternoon.\n */\n readonly value: number;\n /** As the field's segment writes it: \"12\", \"03\", \"PM\", in the locale's digits. */\n readonly text: string;\n /** No time it would give is within the limits. */\n readonly disabled: boolean;\n}\n\n/** A time picker's column, in the order the field's segments are. */\nexport interface TimeColumn {\n readonly type: TimeColumnType;\n /** The segment's name, which names the column: \"hour\". */\n readonly label: string;\n readonly options: readonly TimeColumnOption[];\n /** The value of the option the time holds; `null` while there is no time, or for minutes off the step. */\n readonly selected: number | null;\n}\n\n/**\n * The first and last time allowed, inclusive; `null` for no limit. With\n * `min` after `max` no time of day is allowed.\n */\nexport interface TimeLimits {\n readonly min: PlainTime | null;\n readonly max: PlainTime | null;\n}\n\n/** What a time picker's columns are drawn from. */\nexport interface TimeColumnsOptions extends TimeLimits {\n /** The field's layout: which columns, the hour cycle, the texts and digits. */\n readonly layout: DateLayout;\n /** The minutes offered, every `minuteStep` from 0; 1 by default. */\n readonly minuteStep?: number | undefined;\n}\n\n/** No limits: every time of day. */\nexport const ALL_DAY: TimeLimits = { min: null, max: null };\n\n/** Limits no time of day meets, for a day outside a date-time field's limits. */\nexport const NO_TIME: TimeLimits = { min: \"23:59:59.999\", max: \"00:00\" };\n\nconst SECOND_MS = 1000;\nconst DAY_MS = 86_400_000;\nconst COLUMN_TYPES: ReadonlySet<string> = new Set<TimeColumnType>([\n \"hour\",\n \"minute\",\n \"second\",\n \"dayPeriod\",\n]);\n\n/** A whole minute step from 1 to 59; anything else is 1. */\nfunction stepOf(minuteStep: number | undefined): number {\n return minuteStep !== undefined &&\n Number.isInteger(minuteStep) &&\n minuteStep >= 1 &&\n minuteStep < 60\n ? minuteStep\n : 1;\n}\n\nfunction msOf({ hour, minute, second, millisecond }: TimeParts): number {\n return ((hour * 60 + minute) * 60 + second) * SECOND_MS + millisecond;\n}\n\n/** The limits in milliseconds into the day; `null` when no time is allowed. */\nfunction windowOf({\n min,\n max,\n}: TimeLimits): { readonly low: number; readonly high: number } | null {\n const low = min === null ? 0 : msOf(timeParts(min));\n const high = max === null ? DAY_MS - 1 : msOf(timeParts(max));\n return low <= high ? { low, high } : null;\n}\n\nfunction isTwelveHour(layout: DateLayout): boolean {\n return layout.hourCycle === \"h11\" || layout.hourCycle === \"h12\";\n}\n\nfunction hasSeconds(layout: DateLayout): boolean {\n return layout.segments.some((segment) => segment.type === \"second\");\n}\n\n/** Where a picker starts from while the field is empty: `min`, else midnight. */\nfunction startOf(limits: TimeLimits): TimeParts {\n return timeParts(limits.min ?? \"00:00\");\n}\n\n/** `count / every` values from 0, `every` apart. */\nfunction values(count: number, every = 1): number[] {\n return Array.from(\n { length: Math.ceil(count / every) },\n (_, index) => index * every,\n );\n}\n\n/**\n * A time picker's columns for `time`: hours, minutes every `minuteStep`,\n * seconds when the layout has them, and the day period in a 12-hour cycle,\n * in the layout's order, each option written as its segment writes it.\n * An option is disabled when every time it would give, at the other\n * columns' values (`min`, else midnight, while `time` is `null`), falls\n * outside `min` and `max`.\n */\nexport function timeColumns(\n time: PlainTime | null,\n options: TimeColumnsOptions,\n): readonly TimeColumn[] {\n const { layout } = options;\n const step = stepOf(options.minuteStep);\n const twelve = isTwelveHour(layout);\n const limits = windowOf(options);\n const current = time === null ? startOf(options) : timeParts(time);\n const held = time === null ? null : current;\n const afternoon = current.hour >= 12 ? 12 : 0;\n const lastMinute = 60 - step;\n const lastSecond = hasSeconds(layout) ? 59 : 0;\n const at = (hour: number, minute: number, second: number) =>\n msOf({ hour, minute, second, millisecond: 0 });\n\n const columns: TimeColumn[] = [];\n layout.segments.forEach((segment, index) => {\n if (!COLUMN_TYPES.has(segment.type)) {\n return;\n }\n const type = segment.type as TimeColumnType;\n // An option stands for the times from `start` to `end` the columns can give.\n const option = (\n value: number,\n shown: number,\n start: number,\n end: number,\n ): TimeColumnOption => ({\n value,\n text: writeSegment(layout, index, shown),\n disabled: limits === null || start > limits.high || end < limits.low,\n });\n let list: TimeColumnOption[];\n let selected: number | null;\n switch (type) {\n case \"hour\":\n list = values(twelve ? 12 : 24).map((value) => {\n const hour = twelve ? value + afternoon : value;\n return option(\n value,\n shownHour(hour, layout.hourCycle),\n at(hour, 0, 0),\n at(hour, lastMinute, lastSecond),\n );\n });\n selected = held === null ? null : held.hour - (twelve ? afternoon : 0);\n break;\n case \"minute\":\n list = values(60, step).map((minute) =>\n option(\n minute,\n minute,\n at(current.hour, minute, 0),\n at(current.hour, minute, lastSecond),\n ),\n );\n selected =\n held !== null && held.minute % step === 0 ? held.minute : null;\n break;\n case \"second\":\n list = values(60).map((second) => {\n const start = at(current.hour, current.minute, second);\n return option(second, second, start, start);\n });\n selected = held?.second ?? null;\n break;\n case \"dayPeriod\":\n list = [0, 1].map((period) =>\n option(\n period,\n period,\n at(period * 12, 0, 0),\n at(period * 12 + 11, lastMinute, lastSecond),\n ),\n );\n selected = held === null ? null : held.hour >= 12 ? 1 : 0;\n break;\n }\n columns.push({ type, label: segment.label, options: list, selected });\n });\n return columns;\n}\n\n/**\n * `time` within `limits`: the nearer limit when it is outside them, and\n * `time` itself when no time of day is allowed.\n */\nexport function clampTime(time: PlainTime, limits: TimeLimits): PlainTime {\n const window = windowOf(limits);\n if (window === null) {\n return time;\n }\n const ms = msOf(timeParts(time));\n if (limits.min !== null && ms < window.low) {\n return limits.min;\n }\n if (limits.max !== null && ms > window.high) {\n return limits.max;\n }\n return time;\n}\n\n/**\n * The time choosing `value` in the column `type` gives: `time` (`min`,\n * else midnight, while it is `null`) with that part set, then brought\n * within the limits. An hour keeps the half of the day in a 12-hour\n * cycle; a day period keeps the hour shown (3 AM becomes 3 PM).\n */\nexport function setTimeColumn(\n time: PlainTime | null,\n type: TimeColumnType,\n value: number,\n options: TimeColumnsOptions,\n): PlainTime {\n const current = time === null ? startOf(options) : timeParts(time);\n let { hour, minute, second } = current;\n switch (type) {\n case \"hour\":\n hour = isTwelveHour(options.layout)\n ? (value % 12) + (current.hour >= 12 ? 12 : 0)\n : value;\n break;\n case \"minute\":\n minute = value;\n break;\n case \"second\":\n second = value;\n break;\n case \"dayPeriod\":\n hour = (current.hour % 12) + (value === 0 ? 0 : 12);\n break;\n }\n return clampTime(\n plainTime(hour, minute, second, current.millisecond),\n options,\n );\n}\n\n/**\n * `time` as the columns can show it, for a \"Now\" button: the minutes down\n * to the step, no seconds unless the layout has them, no milliseconds,\n * within the limits.\n */\nexport function snapTime(\n time: PlainTime,\n options: TimeColumnsOptions,\n): PlainTime {\n const step = stepOf(options.minuteStep);\n const { hour, minute, second } = timeParts(time);\n return clampTime(\n plainTime(\n hour,\n Math.floor(minute / step) * step,\n hasSeconds(options.layout) ? second : 0,\n ),\n options,\n );\n}\n\n/**\n * The times a date-time field allows on `day`, for its time columns: from\n * `min`'s time on `min`'s day, to `max`'s time on `max`'s day, all day in\n * between, and none (`NO_TIME`) on a day before `min`'s or after `max`'s.\n */\nexport function dayTimeLimits(\n day: PlainDate,\n min: PlainDateTime | null,\n max: PlainDateTime | null,\n): TimeLimits {\n const first = min === null ? null : splitDateTime(min);\n const last = max === null ? null : splitDateTime(max);\n const fromFirst = first === null ? 1 : compareDates(day, first.date);\n const toLast = last === null ? -1 : compareDates(day, last.date);\n if (fromFirst < 0 || toLast > 0) {\n return NO_TIME;\n }\n return {\n min: fromFirst === 0 && first !== null ? first.time : null,\n max: toLast === 0 && last !== null ? last.time : null,\n };\n}\n","/**\n * The way a line runs: left to right, or right to left as in Arabic and\n * Hebrew. A grid's rows and toolbars and a form's controls run this way, so\n * in `\"rtl\"` the first column sits at the right edge.\n */\nexport type WritingDirection = \"ltr\" | \"rtl\";\n\n/**\n * Which way a horizontal arrow key moves along a line in `direction`: `1`\n * to the next column, chip or control, `-1` to the previous one, or\n * `null` for any other key. The arrows point the way they move, so in\n * `\"rtl\"`, where the next one is to the left, `ArrowLeft` moves forward.\n */\nexport function inlineStep(\n key: string,\n direction: WritingDirection = \"ltr\",\n): 1 | -1 | null {\n const forward = direction === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\";\n const backward = direction === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\";\n if (key === forward) {\n return 1;\n }\n if (key === backward) {\n return -1;\n }\n return null;\n}\n","/**\n * How serious a field's message is. Only `\"error\"` blocks a commit or a\n * submit; the others are shown and never stop the user. Growable: a later\n * release may add a severity.\n */\nexport type Severity = \"error\" | \"warning\" | \"info\" | \"success\";\n\n/** Every severity, most serious first: the order messages are shown in. */\nconst BY_SERIOUSNESS: readonly Severity[] = [\n \"error\",\n \"warning\",\n \"info\",\n \"success\",\n];\n\n/** Where `severity` sorts among messages: 0 for an error, higher for less serious. */\nexport function severityRank(severity: Severity): number {\n return BY_SERIOUSNESS.indexOf(severity);\n}\n\n/**\n * The most serious of `severities`, or `null` when there are none. A field\n * showing several messages takes the state of the most serious one.\n */\nexport function mostSevere(severities: Iterable<Severity>): Severity | null {\n const present = new Set(severities);\n return BY_SERIOUSNESS.find((severity) => present.has(severity)) ?? null;\n}\n","import { severityRank, type Severity } from \"./severity\";\n\n/** One message a field holds, ready to show. */\nexport interface FieldMessage {\n readonly severity: Severity;\n /** The text shown, already localized. */\n readonly text: string;\n /**\n * A stable id for the kind of message: `\"unreadable\"`, `\"required\"`,\n * `\"tooShort\"`, `\"tooLong\"`, `\"pattern\"`, `\"refused\"`, or the app's own;\n * `null` when it has none.\n */\n readonly code: string | null;\n /**\n * Where it came from: reading the text (`\"parse\"`), a validator\n * (`\"validate\"`), a refused commit (`\"commit\"`) or the app (`\"app\"`).\n * Growable: a later release may add a source.\n */\n readonly source: \"parse\" | \"validate\" | \"commit\" | \"app\";\n}\n\n/** A message as an app writes it: a string is an error. */\nexport type FieldMessageInput =\n | string\n | {\n readonly text: string;\n readonly severity?: Severity | undefined;\n readonly code?: string | undefined;\n };\n\n/** The display order of sources, among messages of one severity. */\nconst SOURCE_ORDER: readonly FieldMessage[\"source\"][] = [\n \"parse\",\n \"commit\",\n \"validate\",\n \"app\",\n];\n\n/**\n * `input` as a message from `source`; `code` stands in when the input names\n * none.\n */\nexport function toFieldMessage(\n input: FieldMessageInput,\n source: FieldMessage[\"source\"],\n code: string | null = null,\n): FieldMessage {\n return typeof input === \"string\"\n ? { severity: \"error\", text: input, code, source }\n : {\n severity: input.severity ?? \"error\",\n text: input.text,\n code: input.code ?? code,\n source,\n };\n}\n\n/**\n * Whatever an app or a validator returned, as a list of messages from\n * `source`: one input or several, `null` and `undefined` for none.\n */\nexport function toFieldMessages(\n input: FieldMessageInput | readonly FieldMessageInput[] | null | undefined,\n source: FieldMessage[\"source\"],\n): FieldMessage[] {\n if (input === null || input === undefined) {\n return [];\n }\n return isList(input)\n ? input.map((entry) => toFieldMessage(entry, source))\n : [toFieldMessage(input, source)];\n}\n\n// `Array.isArray` does not narrow a readonly array, hence the guard.\nfunction isList(\n input: FieldMessageInput | readonly FieldMessageInput[],\n): input is readonly FieldMessageInput[] {\n return Array.isArray(input);\n}\n\n/**\n * `messages` in the order a field shows them: the most serious first, and\n * within a severity what the text could not say (parse), then a refused\n * commit, then validators, then the app's own. Equal messages keep their\n * order.\n */\nexport function sortFieldMessages(\n messages: readonly FieldMessage[],\n): FieldMessage[] {\n return messages.toSorted(\n (a, b) =>\n severityRank(a.severity) - severityRank(b.severity) ||\n SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source),\n );\n}\n\n/** Whether any of `messages` is an error: the only severity that blocks. */\nexport function hasError(messages: readonly FieldMessage[]): boolean {\n return messages.some((message) => message.severity === \"error\");\n}\n","import type { FormsMessages } from \"./messages/formsMessages\";\nimport { parsed, type ParseContext, type ParseResult } from \"./parse\";\n\n/** How a text input reads its text. */\nexport interface TextParseOptions {\n /** Drops leading and trailing whitespace from the value. */\n readonly trim?: boolean | undefined;\n /** Upper-cases the value in the context's locale. */\n readonly uppercase?: boolean | undefined;\n}\n\n/**\n * A text input's own reading: the text as it is, trimmed or upper-cased\n * when asked, and `null` when that leaves it empty. Whitespace is kept\n * unless `trim` is set, so `requiredRule` is what refuses a blank value.\n * Text always reads, so it never returns `unreadable`.\n */\nexport function textParser(\n options: TextParseOptions = {},\n): (text: string, context: ParseContext<string>) => ParseResult<string> {\n const { trim = false, uppercase = false } = options;\n return (text, { locale }) => {\n const trimmed = trim ? text.trim() : text;\n const value = uppercase ? trimmed.toLocaleUpperCase(locale) : trimmed;\n return parsed(value === \"\" ? null : value);\n };\n}\n\n/** A text input's own formatting: the value as it is, `\"\"` for `null`. */\nexport function formatText(value: string | null): string {\n return value ?? \"\";\n}\n\n/**\n * The characters in `text` as a `maxLength` counts them: code points,\n * closer to \"characters\" than UTF-16 units, and how databases count a\n * `VARCHAR`. A simple emoji is one; a composed one (a family, a flag) is\n * several, as a database would count it.\n */\nexport function countCharacters(text: string): number {\n return Array.from(text).length;\n}\n\n/**\n * What a character counter announces when typing pauses: the characters\n * left once 10% of `max` or fewer remain, the characters too many once\n * over it, else nothing.\n */\nexport function counterAnnouncement(\n count: number,\n max: number,\n messages: FormsMessages,\n): string | null {\n const left = max - count;\n if (left < 0) {\n return messages.charactersOver(-left);\n }\n return left <= max / 10 ? messages.charactersLeft(left) : null;\n}\n","import {\n toFieldMessages,\n type FieldMessage,\n type FieldMessageInput,\n} from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { countCharacters } from \"../text\";\n\n/** What a validator knows beside the value. */\nexport interface ValidatorContext {\n /** The text the field shows. */\n readonly text: string;\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/** What a validator returns: one message or several, `null` or nothing when the value is fine. */\nexport type ValidationResult =\n FieldMessageInput | readonly FieldMessageInput[] | null | undefined;\n\n/**\n * Checks a value. Called with every value, `null` included, after each\n * change, so it must be synchronous and cheap: anything slow or remote\n * belongs in `onBeforeCommit`. A string it returns is an error; a message\n * with another severity is shown and never blocks.\n */\nexport type Validator<V> = (\n value: V | null,\n context: ValidatorContext,\n) => ValidationResult;\n\n/** `null`, or a string of only whitespace, is `messages.required`. */\nexport function requiredRule<V>(): Validator<V> {\n return (value, { messages }) =>\n value === null || (typeof value === \"string\" && value.trim() === \"\")\n ? { text: messages.required, code: \"required\" }\n : null;\n}\n\n/**\n * `null` is `messages.requiredChoice`: a choice input with nothing\n * chosen. Its value holds keys, so an empty string is a key like any other.\n */\nexport function requiredChoiceRule<V>(): Validator<V> {\n return (value, { messages }) =>\n value === null ? { text: messages.requiredChoice, code: \"required\" } : null;\n}\n\n/**\n * More than `max` keys is `messages.tooManyChoices`: a choice input with\n * several values, given one over its limit. `null` passes.\n */\nexport function maxCountRule<K>(max: number): Validator<readonly K[]> {\n return (value, { messages }) =>\n value !== null && value.length > max\n ? { text: messages.tooManyChoices(max), code: \"tooManyChoices\" }\n : null;\n}\n\n/**\n * Fewer than `min` keys is `messages.tooFewChoices`. `null` passes, as an\n * empty text passes `minLengthRule`: `required` asks for a first choice.\n */\nexport function minCountRule<K>(min: number): Validator<readonly K[]> {\n return (value, { messages }) =>\n value !== null && value.length < min\n ? { text: messages.tooFewChoices(min), code: \"tooFewChoices\" }\n : null;\n}\n\n/** Fewer than `min` code points is `messages.tooShort`. `null` passes. */\nexport function minLengthRule(min: number): Validator<string> {\n return (value, { messages }) =>\n value !== null && countCharacters(value) < min\n ? { text: messages.tooShort(min), code: \"tooShort\" }\n : null;\n}\n\n/** More than `max` code points is `messages.tooLong`. `null` passes. */\nexport function maxLengthRule(max: number): Validator<string> {\n return (value, { messages }) =>\n value !== null && countCharacters(value) > max\n ? { text: messages.tooLong(max), code: \"tooLong\" }\n : null;\n}\n\n/**\n * The whole value must match `pattern`, as the HTML `pattern` attribute\n * reads it; `message` replaces `messages.patternMismatch`. `null` passes.\n */\nexport function patternRule(\n pattern: RegExp,\n message?: string,\n): Validator<string> {\n // `g` and `y` make `test` remember where it stopped, so they are dropped.\n const whole = new RegExp(\n `^(?:${pattern.source})$`,\n pattern.flags.replace(/[gy]/g, \"\"),\n );\n return (value, { messages }) =>\n value !== null && !whole.test(value)\n ? { text: message ?? messages.patternMismatch, code: \"pattern\" }\n : null;\n}\n\n/**\n * Anything but `true` is the message `message` picks from the catalogue:\n * a required checkbox (`requiredChecked`) or switch (`requiredOn`).\n */\nexport function checkedRule(\n message: (messages: FormsMessages) => string,\n): Validator<boolean> {\n return (value, context) =>\n value === true\n ? null\n : { text: message(context.messages), code: \"required\" };\n}\n\n/** Every message `validators` return for `value`, in their order. */\nexport function runValidators<V>(\n validators: readonly Validator<V>[],\n value: V | null,\n context: ValidatorContext,\n): FieldMessage[] {\n return validators.flatMap((validator) =>\n toFieldMessages(validator(value, context), \"validate\"),\n );\n}\n","import { sortFieldMessages, type FieldMessage } from \"../messages/fieldMessage\";\nimport type { FormatPurpose, ParseResult } from \"../parse\";\nimport type { CommitTrigger } from \"./events\";\n\n/**\n * The reading of a draft's text: `pending` while it has not been read yet\n * (an input method is composing, or a change delay is running), else the\n * parse result. A minor release may add a member.\n */\nexport type TextReading<V> = { readonly kind: \"pending\" } | ParseResult<V>;\n\n/**\n * What a field shows. `current` is its value, formatted, and follows the\n * value when the value changes (an untouched field follows a controlled\n * value); `text` is text the user typed, with how it reads. A minor release\n * may add a member.\n */\nexport type FieldDraft<V> =\n | { readonly kind: \"current\" }\n | {\n readonly kind: \"text\";\n readonly text: string;\n readonly reading: TextReading<V>;\n };\n\n/**\n * Where the field is in an edit. A minor release may add a member, so a\n * `switch` over `kind` needs a `default`.\n *\n * - `idle`: not being edited.\n * - `editing`: focused. `initialValue` is the value when it gained focus;\n * `committedValue` the value at its last commit since then (or at focus).\n * - `checking`: an asynchronous `onBeforeCommit` is deciding. `attempt`\n * identifies it, so a superseded check's answer is ignored; `leaving` is\n * true once focus has gone (its `onBlur` waits for the answer).\n * - `leaving`: Tab committed and focus is about to move; the blur that\n * follows commits nothing more.\n */\nexport type FieldPhase<V> =\n | { readonly kind: \"idle\" }\n | {\n readonly kind: \"editing\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n }\n | {\n readonly kind: \"checking\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n readonly trigger: CommitTrigger;\n readonly attempt: number;\n readonly leaving: boolean;\n }\n | {\n readonly kind: \"leaving\";\n readonly initialValue: V | null;\n readonly committedValue: V | null;\n };\n\n/** One field, whole. */\nexport interface FieldState<V> {\n /** The last valid value; `null` is empty. */\n readonly value: V | null;\n readonly draft: FieldDraft<V>;\n /** What the validators said about `value`. */\n readonly validation: readonly FieldMessage[];\n /** Why the last commit was refused, until the text or value changes again. */\n readonly refusal: FieldMessage | null;\n /** Whether messages are shown yet: false until the first commit attempt or `reveal`. */\n readonly revealed: boolean;\n readonly phase: FieldPhase<V>;\n}\n\nexport const CURRENT_DRAFT: FieldDraft<never> = { kind: \"current\" };\nexport const IDLE_PHASE: FieldPhase<never> = { kind: \"idle\" };\n\n/** A field holding `value`, untouched, with what its validators said. */\nexport function createFieldState<V>(\n value: V | null,\n validation: readonly FieldMessage[],\n): FieldState<V> {\n return {\n value,\n draft: CURRENT_DRAFT,\n validation,\n refusal: null,\n revealed: false,\n phase: IDLE_PHASE,\n };\n}\n\n/** The text on screen: `format(value)` for a `current` draft, else the typed text. */\nexport function fieldText<V>(\n state: FieldState<V>,\n format: (value: V | null) => string,\n): string {\n return state.draft.kind === \"current\"\n ? format(state.value)\n : state.draft.text;\n}\n\n/**\n * What the field's text is written for in `phase`: `edit` while the field\n * has focus (editing, leaving after Tab, or checking before focus went),\n * else `display`.\n */\nexport function formatPurpose<V>(phase: FieldPhase<V>): FormatPurpose {\n switch (phase.kind) {\n case \"idle\":\n return \"display\";\n case \"checking\":\n return phase.leaving ? \"display\" : \"edit\";\n case \"editing\":\n case \"leaving\":\n return \"edit\";\n }\n}\n\n/** Why `draft`'s text cannot be read, or `null` when it can (or has not been read yet). */\nexport function unreadableMessage<V>(draft: FieldDraft<V>): string | null {\n return draft.kind === \"text\" && draft.reading.kind === \"unreadable\"\n ? draft.reading.message\n : null;\n}\n\n/**\n * Every message the field holds, in display order, shown or not yet. Text\n * that cannot be read shows only why (and a refusal), not what the\n * validators said about the value it no longer shows.\n */\nexport function fieldMessages<V>(state: FieldState<V>): FieldMessage[] {\n const refusal = state.refusal === null ? [] : [state.refusal];\n const unreadable = unreadableMessage(state.draft);\n if (unreadable !== null) {\n return sortFieldMessages([\n {\n severity: \"error\",\n text: unreadable,\n code: \"unreadable\",\n source: \"parse\",\n },\n ...refusal,\n ]);\n }\n return sortFieldMessages([...refusal, ...state.validation]);\n}\n\n/** The messages the field shows now: all of them once `revealed`, else none. */\nexport function shownMessages<V>(state: FieldState<V>): FieldMessage[] {\n return state.revealed ? fieldMessages(state) : [];\n}\n","import type { FieldMessage } from \"../messages/fieldMessage\";\nimport type { ParseResult } from \"../parse\";\nimport type { CommitTrigger } from \"./events\";\nimport {\n CURRENT_DRAFT,\n IDLE_PHASE,\n unreadableMessage,\n type FieldDraft,\n type FieldPhase,\n type FieldState,\n} from \"./state\";\n\n/**\n * A step of a field's edit, as its controller asks for it. Parsing, the\n * app's hooks and value equality are the controller's, which passes their\n * results in (`read.reading`, `sync.equal`).\n *\n * - `focus`: the field gained focus.\n * - `edit`: the user changed the text; it is not read yet.\n * - `read`: how the typed text reads.\n * - `change`: the value changes; `text` is typed text that reads as it, or\n * `null` to show the value formatted.\n * - `revert`: the draft is put back (a refused change, Escape).\n * - `validated`: what the validators say about the value now.\n * - `check`: an asynchronous `onBeforeCommit` starts deciding.\n * - `accept`, `refuse`: a commit is allowed or refused; `next` is the phase\n * it leaves the field in.\n * - `blur`: the field lost focus.\n * - `sync`: a controlled value arrived; `equal` says whether it equals the\n * field's value.\n * - `reveal`: messages show from now on.\n */\nexport type FieldAction<V> =\n | { readonly type: \"focus\" }\n | { readonly type: \"edit\"; readonly text: string }\n | { readonly type: \"read\"; readonly reading: ParseResult<V> }\n | {\n readonly type: \"change\";\n readonly value: V | null;\n readonly text: string | null;\n }\n | { readonly type: \"revert\"; readonly draft: FieldDraft<V> }\n | { readonly type: \"validated\"; readonly messages: readonly FieldMessage[] }\n | {\n readonly type: \"check\";\n readonly trigger: CommitTrigger;\n readonly attempt: number;\n readonly leaving: boolean;\n }\n | { readonly type: \"accept\"; readonly next: \"editing\" | \"leaving\" | \"idle\" }\n | {\n readonly type: \"refuse\";\n readonly message: FieldMessage;\n readonly next: \"editing\" | \"idle\";\n }\n | { readonly type: \"blur\" }\n | { readonly type: \"sync\"; readonly value: V | null; readonly equal: boolean }\n | { readonly type: \"reveal\" };\n\ntype EditPhase<V> = Exclude<FieldPhase<V>, { kind: \"idle\" }>;\n\n/** `phase` as plain editing, keeping its two values. */\nfunction editing<V>(phase: EditPhase<V>): FieldPhase<V> {\n return phase.kind === \"editing\"\n ? phase\n : {\n kind: \"editing\",\n initialValue: phase.initialValue,\n committedValue: phase.committedValue,\n };\n}\n\n/**\n * Every transition of a field. Pure: no parsing, no callbacks, no equality\n * of its own. An action that means nothing in the field's phase returns the\n * state unchanged.\n */\nexport function fieldReducer<V>(\n state: FieldState<V>,\n action: FieldAction<V>,\n): FieldState<V> {\n const { phase } = state;\n switch (action.type) {\n case \"focus\":\n if (phase.kind === \"idle\") {\n return {\n ...state,\n phase: {\n kind: \"editing\",\n initialValue: state.value,\n committedValue: state.value,\n },\n };\n }\n return phase.kind === \"leaving\"\n ? { ...state, phase: editing(phase) }\n : state;\n\n case \"edit\":\n // An idle field takes no typing: autofill reaches it through a focus.\n return phase.kind === \"idle\"\n ? state\n : {\n ...state,\n draft: { kind: \"text\", text: action.text, reading: PENDING },\n refusal: null,\n phase: editing(phase),\n };\n\n case \"read\":\n return state.draft.kind === \"text\"\n ? { ...state, draft: { ...state.draft, reading: action.reading } }\n : state;\n\n case \"change\":\n return {\n ...state,\n value: action.value,\n draft:\n action.text === null\n ? CURRENT_DRAFT\n : {\n kind: \"text\",\n text: action.text,\n reading: { kind: \"value\", value: action.value },\n },\n refusal: null,\n // A change supersedes a pending check.\n phase: phase.kind === \"checking\" ? editing(phase) : phase,\n };\n\n case \"revert\":\n return phase.kind === \"checking\"\n ? state\n : { ...state, draft: action.draft };\n\n case \"validated\":\n return { ...state, validation: action.messages };\n\n case \"check\":\n return phase.kind === \"editing\"\n ? {\n ...state,\n phase: {\n kind: \"checking\",\n initialValue: phase.initialValue,\n committedValue: phase.committedValue,\n trigger: action.trigger,\n attempt: action.attempt,\n leaving: action.leaving,\n },\n }\n : state;\n\n case \"accept\":\n if (phase.kind !== \"editing\" && phase.kind !== \"checking\") {\n return state;\n }\n return {\n ...state,\n draft:\n unreadableMessage(state.draft) === null ? CURRENT_DRAFT : state.draft,\n refusal: null,\n revealed: true,\n phase:\n action.next === \"idle\"\n ? IDLE_PHASE\n : {\n kind: action.next,\n initialValue: phase.initialValue,\n committedValue: state.value,\n },\n };\n\n case \"refuse\":\n if (phase.kind !== \"editing\" && phase.kind !== \"checking\") {\n return state;\n }\n return {\n ...state,\n refusal: action.message,\n revealed: true,\n phase: action.next === \"idle\" ? IDLE_PHASE : editing(phase),\n };\n\n case \"blur\":\n return blur(state);\n\n case \"sync\":\n return sync(state, action.value, action.equal);\n\n case \"reveal\":\n return state.revealed ? state : { ...state, revealed: true };\n }\n}\n\nconst PENDING = { kind: \"pending\" } as const;\n\n/**\n * Focus went. A focused field goes idle and shows its messages; this is\n * reached only when leaving commits nothing (unreadable text, a toggle).\n * A pending check notes it, so its answer ends the edit.\n */\nfunction blur<V>(state: FieldState<V>): FieldState<V> {\n const { phase } = state;\n switch (phase.kind) {\n case \"idle\":\n return state;\n case \"editing\":\n return { ...state, phase: IDLE_PHASE, revealed: true };\n case \"checking\":\n return { ...state, phase: { ...phase, leaving: true } };\n case \"leaving\":\n return { ...state, phase: IDLE_PHASE };\n }\n}\n\n/**\n * A controlled value is adopted whenever the user is not typing: always in\n * an idle field, and in a focused one while its draft shows the value. A\n * pending check holds it off; the next `sync` after the edit ends adopts it.\n */\nfunction sync<V>(\n state: FieldState<V>,\n value: V | null,\n equal: boolean,\n): FieldState<V> {\n const { phase } = state;\n if (equal || phase.kind === \"checking\") {\n return state;\n }\n if (phase.kind === \"idle\") {\n return { ...state, value, draft: CURRENT_DRAFT, refusal: null };\n }\n return state.draft.kind === \"current\"\n ? {\n ...state,\n value,\n refusal: null,\n phase: { ...phase, committedValue: value },\n }\n : state;\n}\n","import {\n hasError,\n toFieldMessage,\n type FieldMessage,\n type FieldMessageInput,\n} from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport { parsed, type ParseResult } from \"../parse\";\nimport type {\n ChangeSource,\n CommitTrigger,\n FieldEventBase,\n FieldHandlers,\n TextInputDetails,\n} from \"./events\";\nimport type { FieldAction } from \"./fieldReducer\";\nimport {\n CURRENT_DRAFT,\n fieldMessages,\n fieldText,\n unreadableMessage,\n type FieldDraft,\n type FieldState,\n} from \"./state\";\n\n// The event plans: one function per kind of request, calling the app's\n// handlers in the documented order and dispatching reducer actions between\n// them. They touch nothing but `env`, so a test drives them with handlers\n// that record their calls. Timers, the request queue and the pending check's\n// promise are the controller's.\n\n/** Where a change came from, and the browser's report of it. */\nexport interface ChangeCause<N> {\n readonly source: ChangeSource;\n readonly nativeEvent: N | null;\n readonly input: TextInputDetails | null;\n}\n\n/** A text edit, as forms-dom reports it. */\nexport interface TextEdit<N> extends ChangeCause<N> {\n /** The text after the edit; for `beforeInput`, the proposed text. */\n readonly text: string;\n}\n\n/** What forms-dom does with a text edit `onBeforeInput` saw. */\nexport type BeforeInputDecision =\n | { readonly kind: \"allow\" }\n | { readonly kind: \"prevent\" }\n | { readonly kind: \"rewrite\"; readonly data: string };\n\n/**\n * What an input's own filter does with an edit: one of `onBeforeInput`'s\n * decisions, or `replace`, where the whole text becomes `text` with the\n * caret at `caret` (a mask laying its characters out again).\n */\nexport type InputFilterDecision =\n | BeforeInputDecision\n | { readonly kind: \"replace\"; readonly text: string; readonly caret: number };\n\n/**\n * An input's own judgement of an edit, after the app's `onBeforeInput` let\n * it through: `edit` is the edit as the app left it (its `text` the text it\n * would leave), `before` the text before it.\n */\nexport type InputFilter<N> = (\n edit: TextEdit<N>,\n before: string,\n) => InputFilterDecision;\n\n/**\n * How a commit request ended:\n *\n * - `accepted`: committed (`onCommit` has fired).\n * - `refused`: `onBeforeCommit` refused it; its message shows.\n * - `unreadable`: the text cannot be read, so nothing was committed; the\n * message shows.\n * - `checking`: not decided yet. An asynchronous `onBeforeCommit` is\n * deciding, or the request was made from inside a handler and runs once\n * the current sequence ends.\n */\nexport type CommitOutcome =\n | { readonly kind: \"accepted\" }\n | { readonly kind: \"refused\" }\n | { readonly kind: \"unreadable\" }\n | { readonly kind: \"checking\" };\n\n/** Everything a sequence needs: the field's state and its options, resolved. */\nexport interface FieldEnv<V, D extends object, N> {\n /** The state as the sequence runs, which a handler reading the field sees too. */\n readonly get: () => FieldState<V>;\n readonly dispatch: (action: FieldAction<V>) => FieldState<V>;\n readonly handlers: FieldHandlers<V, D, N>;\n /** The input's own judgement of an edit, after `onBeforeInput`. */\n readonly filterInput: InputFilter<N> | undefined;\n readonly parse: (text: string) => ParseResult<V>;\n readonly format: (value: V | null) => string;\n /** Whether two values are one; `null` equals only itself. */\n readonly same: (a: V | null, b: V | null) => boolean;\n readonly validate: (value: V | null, text: string) => readonly FieldMessage[];\n readonly details: (\n current: FieldState<V>,\n previous: FieldState<V>,\n cause: ChangeCause<N>,\n ) => D;\n readonly messages: FormsMessages;\n readonly commitOnLeave: boolean;\n}\n\n/** A commit as the controller asks for it. */\nexport interface CommitRequest<N> {\n readonly trigger: CommitTrigger;\n readonly source: ChangeSource;\n readonly nativeEvent: N | null;\n /** Identifies this commit, should `onBeforeCommit` answer later. */\n readonly attempt: number;\n}\n\n/** A commit an asynchronous `onBeforeCommit` is deciding. */\nexport interface PendingCheck<N> extends CommitRequest<N> {\n /** Started while the field was idle: it ends idle, with no `onBlur`. */\n readonly quiet: boolean;\n /** Settles with the refusal, or `null` when allowed. Never rejects. */\n readonly answer: Promise<FieldMessage | null>;\n}\n\nexport interface CommitStep<N> {\n readonly outcome: CommitOutcome;\n /** The check to wait for, when the outcome is `checking`. */\n readonly check: PendingCheck<N> | null;\n}\n\nconst ALLOW = { kind: \"allow\" } as const;\nconst PREVENT = { kind: \"prevent\" } as const;\nconst ACCEPTED = { kind: \"accepted\" } as const;\nconst REFUSED = { kind: \"refused\" } as const;\nconst UNREADABLE = { kind: \"unreadable\" } as const;\nexport const CHECKING = { kind: \"checking\" } as const;\n\ninterface EventValues<V> {\n readonly value: V | null;\n readonly previousValue: V | null;\n readonly text: string;\n readonly previousText: string;\n}\n\n/**\n * An event's shared fields, with the input's details computed from the\n * state now, the state the request started from and the change's cause.\n * The base fields go last, so a details key can never hide one.\n */\nfunction eventBase<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n values: EventValues<V>,\n cause: ChangeCause<N>,\n): FieldEventBase<V, N> & D {\n return {\n ...env.details(env.get(), start, cause),\n ...values,\n source: cause.source,\n nativeEvent: cause.nativeEvent,\n input: cause.input,\n };\n}\n\n/** The text `draft` shows over the field's current value. */\nfunction draftText<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n draft: FieldDraft<V>,\n): string {\n return draft.kind === \"current\" ? env.format(env.get().value) : draft.text;\n}\n\nfunction emitValidate<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n values: EventValues<V>,\n cause: ChangeCause<N>,\n): void {\n const messages = fieldMessages(env.get());\n env.handlers.onValidate?.({\n ...eventBase(env, start, values, cause),\n messages,\n valid: !hasError(messages),\n });\n}\n\nfunction emitBlur<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): void {\n const state = env.get();\n env.handlers.onBlur?.({\n value: state.value,\n text: fieldText(state, env.format),\n nativeEvent,\n });\n}\n\n/**\n * `onBeforeInput` for an edit about to happen, then the input's own filter\n * for an edit the app let through (outside a composition, which cannot be\n * refused), and what forms-dom should do with it. Changes no state: the\n * edit arrives through `runEdit`.\n */\nexport function runBeforeInput<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N> & { readonly cancelable: boolean },\n): InputFilterDecision {\n const before = fieldText(env.get(), env.format);\n const decision = appDecision(env, edit, before);\n const { filterInput } = env;\n if (\n filterInput === undefined ||\n !edit.cancelable ||\n decision.kind === \"prevent\"\n ) {\n return decision;\n }\n const judged = filterInput(\n decision.kind === \"rewrite\"\n ? rewrittenEdit(edit, before, decision.data)\n : edit,\n before,\n );\n return judged.kind === \"allow\" ? decision : judged;\n}\n\n/** `edit` with `data` in place of the selection, as forms-dom inserts a rewrite. */\nfunction rewrittenEdit<N>(\n edit: TextEdit<N>,\n before: string,\n data: string,\n): TextEdit<N> {\n const { input } = edit;\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n return {\n ...edit,\n text: before.slice(0, start) + data + before.slice(end),\n input: input && { ...input, data },\n };\n}\n\n/** What the app's `onBeforeInput` decides about `edit`; `before` is the text before it. */\nfunction appDecision<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N> & { readonly cancelable: boolean },\n before: string,\n): BeforeInputDecision {\n const handler = env.handlers.onBeforeInput;\n if (handler === undefined) {\n return ALLOW;\n }\n const state = env.get();\n const decided: { decision: BeforeInputDecision } = { decision: ALLOW };\n handler({\n ...eventBase(\n env,\n state,\n {\n value: state.value,\n previousValue: state.value,\n text: edit.text,\n previousText: before,\n },\n edit,\n ),\n cancelable: edit.cancelable,\n get defaultPrevented() {\n return decided.decision.kind === \"prevent\";\n },\n preventDefault() {\n if (edit.cancelable) {\n decided.decision = PREVENT;\n }\n },\n setData(data) {\n if (edit.cancelable && decided.decision.kind !== \"prevent\") {\n decided.decision = { kind: \"rewrite\", data };\n }\n },\n });\n return decided.decision;\n}\n\n/**\n * The text changed: the draft takes it, unread, then `onInput`. False when\n * nothing happened: the text is the same, or the field is idle (autofill\n * goes through `runAutofill`).\n */\nexport function runEdit<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N>,\n): boolean {\n const start = env.get();\n const previousText = fieldText(start, env.format);\n if (start.phase.kind === \"idle\" || edit.text === previousText) {\n return false;\n }\n env.dispatch({ type: \"edit\", text: edit.text });\n env.handlers.onInput?.(\n eventBase(\n env,\n start,\n {\n value: start.value,\n previousValue: start.value,\n text: edit.text,\n previousText,\n },\n edit,\n ),\n );\n return true;\n}\n\n/**\n * Reads the draft's unread text: parse, then the change chain when it reads\n * as another value, else `onValidate` when whether (or why) it cannot be\n * read changed. `before` is the draft before the edits being read, which a\n * refused change puts back.\n */\nexport function runRead<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n const { draft } = start;\n if (draft.kind !== \"text\" || draft.reading.kind !== \"pending\") {\n return;\n }\n const reading = env.parse(draft.text);\n env.dispatch({ type: \"read\", reading });\n if (\n reading.kind === \"unreadable\" ||\n runChange(env, start, reading.value, draft.text, before, cause) ===\n \"unchanged\"\n ) {\n validateIfReadingChanged(env, start, before, cause);\n }\n}\n\ntype ChangeResult = \"changed\" | \"unchanged\" | \"prevented\";\n\n/**\n * The change chain: `onBeforeChange`, the change, `onChange`, validation and\n * `onValidate`, skipped when `target` is the value held. `typedText` is text\n * that reads as `target`, kept on screen; `null` shows the value formatted.\n */\nfunction runChange<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n target: V | null,\n typedText: string | null,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): ChangeResult {\n const previousValue = env.get().value;\n if (env.same(target, previousValue)) {\n if (typedText === null) {\n env.dispatch({ type: \"revert\", draft: CURRENT_DRAFT });\n }\n return \"unchanged\";\n }\n const previousText = draftText(env, before);\n const decided: {\n decision:\n typeof ALLOW | typeof PREVENT | { kind: \"replace\"; value: V | null };\n } = { decision: ALLOW };\n env.handlers.onBeforeChange?.({\n ...eventBase(\n env,\n start,\n {\n value: target,\n previousValue,\n text: typedText ?? env.format(target),\n previousText,\n },\n cause,\n ),\n get defaultPrevented() {\n return decided.decision.kind === \"prevent\";\n },\n preventDefault() {\n decided.decision = PREVENT;\n },\n setValue(value) {\n if (decided.decision.kind !== \"prevent\") {\n decided.decision = { kind: \"replace\", value };\n }\n },\n });\n const { decision } = decided;\n if (decision.kind === \"prevent\") {\n env.dispatch({ type: \"revert\", draft: before });\n return \"prevented\";\n }\n const value = decision.kind === \"replace\" ? decision.value : target;\n if (env.same(value, previousValue)) {\n // `setValue` chose the value already held: only the text changes back.\n env.dispatch({ type: \"revert\", draft: CURRENT_DRAFT });\n return \"unchanged\";\n }\n const text = typedText !== null && env.same(value, target) ? typedText : null;\n const changed = env.dispatch({ type: \"change\", value, text });\n const values = {\n value,\n previousValue,\n text: fieldText(changed, env.format),\n previousText,\n };\n env.handlers.onChange?.(eventBase(env, start, values, cause));\n env.dispatch({\n type: \"validated\",\n messages: env.validate(value, values.text),\n });\n emitValidate(env, start, values, cause);\n return \"changed\";\n}\n\n/** `onValidate` when the value stayed but whether, or why, the text cannot be read changed. */\nfunction validateIfReadingChanged<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n before: FieldDraft<V>,\n cause: ChangeCause<N>,\n): void {\n const state = env.get();\n if (unreadableMessage(before) === unreadableMessage(state.draft)) {\n return;\n }\n emitValidate(\n env,\n start,\n {\n value: state.value,\n previousValue: state.value,\n text: fieldText(state, env.format),\n previousText: draftText(env, before),\n },\n cause,\n );\n}\n\n/**\n * Puts the text `target` formats to on screen as if typed (`onInput`), then\n * runs the change chain to `target`: Escape's revert and the clear button.\n */\nfunction replaceText<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n target: V | null,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n const before = start.draft;\n const previousText = fieldText(start, env.format);\n const text = env.format(target);\n if (text !== previousText) {\n env.dispatch({ type: \"edit\", text });\n env.dispatch({ type: \"read\", reading: parsed(target) });\n env.handlers.onInput?.(\n eventBase(\n env,\n start,\n { value: start.value, previousValue: start.value, text, previousText },\n cause,\n ),\n );\n }\n if (runChange(env, start, target, null, before, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, before, cause);\n }\n}\n\n/**\n * Focuses an idle field without an `onFocus`, for a change made while it had\n * no focus (autofill, a toggle clicked in a browser that does not focus it).\n * True when it did; the commit that follows then ends the edit.\n */\nfunction enterQuietly<V, D extends object, N>(env: FieldEnv<V, D, N>): boolean {\n if (env.get().phase.kind !== \"idle\") {\n return false;\n }\n env.dispatch({ type: \"focus\" });\n return true;\n}\n\n/** `message` as a refusal, `messages.checkFailed` when none is given. */\nfunction refusalOf(\n message: FieldMessageInput | undefined,\n messages: FormsMessages,\n): FieldMessage {\n return toFieldMessage(message ?? messages.checkFailed, \"commit\", \"refused\");\n}\n\n/** What a commit event reports, read from the state before the commit. */\ninterface Committing<V> {\n readonly value: V | null;\n readonly committedValue: V | null;\n readonly initialValue: V | null;\n readonly previousText: string;\n}\n\nfunction commitEvent<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n request: CommitRequest<N>,\n committing: Committing<V>,\n) {\n return {\n ...eventBase(\n env,\n start,\n {\n value: committing.value,\n previousValue: committing.committedValue,\n text: env.format(committing.value),\n previousText: committing.previousText,\n },\n {\n source: request.source,\n nativeEvent: request.nativeEvent,\n input: null,\n },\n ),\n trigger: request.trigger,\n changed: !env.same(committing.value, committing.committedValue),\n initialValue: committing.initialValue,\n };\n}\n\n/** What `state`, in an edit, would commit. */\nfunction committingOf<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n state: FieldState<V>,\n): Committing<V> | null {\n const { phase } = state;\n return phase.kind === \"editing\" || phase.kind === \"checking\"\n ? {\n value: state.value,\n committedValue: phase.committedValue,\n initialValue: phase.initialValue,\n previousText: fieldText(state, env.format),\n }\n : null;\n}\n\n/** The commit is allowed: accept, then `onCommit`. */\nfunction accept<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n start: FieldState<V>,\n request: CommitRequest<N>,\n committing: Committing<V>,\n next: \"editing\" | \"leaving\" | \"idle\",\n): void {\n env.dispatch({ type: \"accept\", next });\n env.handlers.onCommit?.(commitEvent(env, start, request, committing));\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\n/**\n * A commit: `onBeforeCommit`, then `onCommit` once allowed. Text that\n * cannot be read commits nothing and shows why. Tab leaves the field\n * `leaving`, so the blur that follows commits nothing more; a blur ends the\n * edit. A field that was idle (`quiet`) returns to idle.\n */\nfunction commitFrom<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n request: CommitRequest<N>,\n quiet: boolean,\n): CommitStep<N> {\n const start = env.get();\n if (start.phase.kind === \"checking\") {\n // The pending check is about this same value: any change supersedes it.\n return { outcome: CHECKING, check: null };\n }\n const committing = committingOf(env, start);\n if (committing === null) {\n // Leaving: Tab has committed already.\n return { outcome: ACCEPTED, check: null };\n }\n if (unreadableMessage(start.draft) !== null) {\n env.dispatch({ type: \"reveal\" });\n if (quiet) {\n env.dispatch({ type: \"blur\" });\n }\n return { outcome: UNREADABLE, check: null };\n }\n const ends = quiet || request.trigger === \"blur\";\n const decided: { open: boolean; refusal: FieldMessage | null } = {\n open: true,\n refusal: null,\n };\n const answer: unknown = env.handlers.onBeforeCommit?.({\n ...commitEvent(env, start, request, committing),\n get defaultPrevented() {\n return decided.refusal !== null;\n },\n preventDefault(message) {\n if (decided.open && decided.refusal === null) {\n decided.refusal = refusalOf(message, env.messages);\n }\n },\n });\n if (isPromiseLike(answer)) {\n env.dispatch({\n type: \"check\",\n trigger: request.trigger,\n attempt: request.attempt,\n leaving: ends || request.trigger === \"tab\",\n });\n const close = (failed: boolean): FieldMessage | null => {\n decided.open = false;\n return (\n decided.refusal ?? (failed ? refusalOf(undefined, env.messages) : null)\n );\n };\n return {\n outcome: CHECKING,\n check: {\n ...request,\n quiet,\n answer: Promise.resolve(answer).then(\n () => close(false),\n () => close(true),\n ),\n },\n };\n }\n decided.open = false;\n if (decided.refusal !== null) {\n env.dispatch({\n type: \"refuse\",\n message: decided.refusal,\n next: ends ? \"idle\" : \"editing\",\n });\n return { outcome: REFUSED, check: null };\n }\n const next = ends\n ? \"idle\"\n : request.trigger === \"tab\"\n ? \"leaving\"\n : \"editing\";\n accept(env, start, request, committing, next);\n return { outcome: ACCEPTED, check: null };\n}\n\n/** A commit by Enter or Tab, or one an app or input asks for. */\nexport function runCommit<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n request: CommitRequest<N>,\n): CommitStep<N> {\n return commitFrom(env, request, enterQuietly(env));\n}\n\n/**\n * A pending check answered. Ignored unless it is still the field's check:\n * a change since then, or a newer commit, superseded it. A field focus has\n * left gets its `onBlur` now.\n */\nexport function runSettle<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n check: PendingCheck<N>,\n refusal: FieldMessage | null,\n blurEvent: N | null,\n): void {\n const start = env.get();\n const { phase } = start;\n const committing = committingOf(env, start);\n if (\n phase.kind !== \"checking\" ||\n phase.attempt !== check.attempt ||\n committing === null\n ) {\n return;\n }\n const next = phase.leaving ? \"idle\" : \"editing\";\n if (refusal === null) {\n accept(env, start, check, committing, next);\n } else {\n env.dispatch({ type: \"refuse\", message: refusal, next });\n }\n if (phase.leaving && !check.quiet) {\n emitBlur(env, blurEvent);\n }\n}\n\n/** The field gained focus: `onFocus`, unless it never lost it. */\nexport function runFocus<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): void {\n const { phase } = env.get();\n if (phase.kind === \"leaving\") {\n // Tab committed but focus stayed: the edit goes on, unannounced.\n env.dispatch({ type: \"focus\" });\n return;\n }\n if (phase.kind !== \"idle\") {\n return;\n }\n const state = env.dispatch({ type: \"focus\" });\n env.handlers.onFocus?.({\n value: state.value,\n text: fieldText(state, env.format),\n nativeEvent,\n });\n}\n\n/**\n * The field lost focus. An edit commits (`trigger: \"blur\"`) unless Tab\n * already did or the field commits as it changes (`commitOnLeave: false`),\n * then `onBlur`; a pending check holds `onBlur` until it answers, and the\n * check this blur starts, if any, is returned.\n */\nexport function runBlur<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n attempt: number,\n): PendingCheck<N> | null {\n const { phase } = env.get();\n switch (phase.kind) {\n case \"idle\":\n return null;\n case \"checking\":\n env.dispatch({ type: \"blur\" });\n return null;\n case \"leaving\":\n env.dispatch({ type: \"blur\" });\n emitBlur(env, nativeEvent);\n return null;\n case \"editing\": {\n if (env.commitOnLeave) {\n const { check } = commitFrom(\n env,\n { trigger: \"blur\", source: \"typing\", nativeEvent, attempt },\n false,\n );\n if (check !== null) {\n return check;\n }\n }\n // A commit leaves the field idle; anything else still needs to end.\n env.dispatch({ type: \"blur\" });\n emitBlur(env, nativeEvent);\n return null;\n }\n }\n}\n\n/**\n * Escape: the text and value go back to the last commit (`source:\n * \"revert\"`). False when they are already there, or the field is not\n * being edited.\n */\nexport function runRevert<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n): boolean {\n const state = env.get();\n const { phase } = state;\n if (phase.kind !== \"editing\") {\n return false;\n }\n const target = phase.committedValue;\n if (\n env.same(state.value, target) &&\n fieldText(state, env.format) === env.format(target)\n ) {\n return false;\n }\n replaceText(env, target, { source: \"revert\", nativeEvent, input: null });\n return true;\n}\n\n/** The clear button: empty text, the value `null`, then a commit. */\nexport function runClear<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n nativeEvent: N | null,\n attempt: number,\n): CommitStep<N> {\n const quiet = enterQuietly(env);\n replaceText(env, null, { source: \"clear\", nativeEvent, input: null });\n return commitFrom(\n env,\n { trigger: \"clear\", source: \"clear\", nativeEvent, attempt },\n quiet,\n );\n}\n\n/** A value chosen whole (a toggle, an option, a preset): the change chain, then a commit. */\nexport function runPick<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n request: CommitRequest<N>,\n): CommitStep<N> {\n const quiet = enterQuietly(env);\n const start = env.get();\n const cause = {\n source: request.source,\n nativeEvent: request.nativeEvent,\n input: null,\n };\n if (runChange(env, start, value, null, start.draft, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, start.draft, cause);\n }\n return commitFrom(env, request, quiet);\n}\n\n/**\n * Text that changed while the field had no focus (browser autofill): read\n * at once and committed (`trigger: \"autofill\"`), with no `onFocus` or\n * `onBlur`. Returns the check a slow `onBeforeCommit` starts, if any.\n */\nexport function runAutofill<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n edit: TextEdit<N>,\n attempt: number,\n): PendingCheck<N> | null {\n if (edit.text === fieldText(env.get(), env.format)) {\n return null;\n }\n const quiet = enterQuietly(env);\n const before = env.get().draft;\n runEdit(env, edit);\n runRead(env, before, edit);\n return commitFrom(\n env,\n {\n trigger: \"autofill\",\n source: edit.source,\n nativeEvent: edit.nativeEvent,\n attempt,\n },\n quiet,\n ).check;\n}\n\n/**\n * A value set whole without a commit: a step, `setValue` and `reset`. The\n * change chain, with `cause`'s source and native event; typed text is\n * replaced by the value formatted, even when the value stays.\n */\nexport function runValueChange<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n cause: ChangeCause<N>,\n): void {\n const start = env.get();\n if (runChange(env, start, value, null, start.draft, cause) === \"unchanged\") {\n validateIfReadingChanged(env, start, start.draft, cause);\n }\n}\n\n/**\n * A controlled value arrived: adopted, silently, whenever the user is not\n * typing, and validated when it changes the value.\n */\nexport function runSync<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n value: V | null,\n): void {\n const start = env.get();\n const next = env.dispatch({\n type: \"sync\",\n value,\n equal: env.same(value, start.value),\n });\n if (next !== start) {\n env.dispatch({\n type: \"validated\",\n messages: env.validate(next.value, fieldText(next, env.format)),\n });\n }\n}\n\nfunction sameMessages(\n a: readonly FieldMessage[],\n b: readonly FieldMessage[],\n): boolean {\n return (\n a.length === b.length &&\n a.every((message, index) => {\n const other = b[index];\n return (\n other !== undefined &&\n message.severity === other.severity &&\n message.text === other.text &&\n message.code === other.code &&\n message.source === other.source\n );\n })\n );\n}\n\n/** Messages show from now on, the validators asked again. */\nexport function runReveal<V, D extends object, N>(\n env: FieldEnv<V, D, N>,\n): void {\n const state = env.dispatch({ type: \"reveal\" });\n const messages = env.validate(state.value, fieldText(state, env.format));\n if (!sameMessages(messages, state.validation)) {\n env.dispatch({ type: \"validated\", messages });\n }\n}\n","import type { FieldMessage } from \"../messages/fieldMessage\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport type {\n FormatContext,\n FormatPurpose,\n Formatter,\n ParseContext,\n ParseResult,\n Parser,\n} from \"../parse\";\nimport type { Schedule } from \"../schedule\";\nimport { runValidators, type Validator } from \"../validation/validators\";\nimport type {\n ChangeSource,\n CommitTrigger,\n FieldHandlers,\n NoDetails,\n} from \"./events\";\nimport { fieldReducer } from \"./fieldReducer\";\nimport {\n CHECKING,\n runAutofill,\n runBeforeInput,\n runBlur,\n runClear,\n runCommit,\n runEdit,\n runFocus,\n runPick,\n runRead,\n runReveal,\n runRevert,\n runSettle,\n runSync,\n runValueChange,\n type ChangeCause,\n type CommitOutcome,\n type CommitStep,\n type FieldEnv,\n type InputFilter,\n type InputFilterDecision,\n type PendingCheck,\n type TextEdit,\n} from \"./plan\";\nimport {\n createFieldState,\n fieldMessages,\n fieldText,\n formatPurpose,\n type FieldDraft,\n type FieldState,\n} from \"./state\";\n\n/**\n * What a field is given: its value, how it reads and writes text, how it\n * validates, and the app's handlers. A renderer passes the latest on every\n * update through `setOptions`.\n */\nexport interface FieldOptions<\n V,\n D extends object = NoDetails,\n N = unknown,\n> extends FieldHandlers<V, D, N> {\n /** Present (`null` included) means controlled: see `FieldController.sync`. */\n readonly value?: V | null | undefined;\n /** The value of an uncontrolled field at first, and what `reset` returns to. */\n readonly defaultValue?: V | null | undefined;\n /** The app's reading of typed text; its context holds `defaultParse`. */\n readonly parse?: Parser<V> | undefined;\n /** The app's writing of the value; its context holds `defaultFormat`. */\n readonly format?: Formatter<V> | undefined;\n /** The input's own reading. */\n readonly defaultParse: (\n text: string,\n context: ParseContext<V>,\n ) => ParseResult<V>;\n /** The input's own writing. */\n readonly defaultFormat: (\n value: V | null,\n context: FormatContext<V>,\n ) => string;\n /** Whether two values are one; `Object.is` by default. Never called with `null`. */\n readonly equals?: ((a: V, b: V) => boolean) | undefined;\n /**\n * The input's own judgement of each edit the app's `onBeforeInput` lets\n * through, outside a composition: a number input refusing letters, or\n * cleaning a paste.\n */\n readonly filterInput?: InputFilter<N> | undefined;\n readonly validators?: readonly Validator<V>[] | undefined;\n /**\n * The input's own details, added to every event it fires. `cause` is\n * the change the event is about: its source and, for a text edit, where\n * in the text it happened (a date field names the segment from it).\n */\n readonly details?:\n | ((\n current: FieldState<V>,\n previous: FieldState<V>,\n cause: ChangeCause<N>,\n ) => D)\n | undefined;\n /**\n * Milliseconds typing must pause before the text is read (`onChange`),\n * for a search box. `onInput` fires at once, and a commit reads at once.\n * Needs `schedule`; 0, the default, reads at once.\n */\n readonly changeDelay?: number | undefined;\n /** Whether leaving the field commits it: true by default, false for a toggle, which commits as it flips. */\n readonly commitOnLeave?: boolean | undefined;\n /** The timer `changeDelay` runs on. */\n readonly schedule?: Schedule | undefined;\n readonly locale?: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/**\n * One field's state and every request that moves it, for a renderer to\n * drive: forms-dom calls the text and focus requests from the browser's\n * events, the app the value requests. Each request runs its sequence of\n * handlers to the end before the next starts: one made from inside a\n * handler is queued behind it.\n */\nexport interface FieldController<V, D extends object = NoDetails, N = unknown> {\n readonly getState: () => FieldState<V>;\n /** The text on screen. */\n readonly getText: () => string;\n /** Every message the field holds, in display order; the same array until the state changes. */\n readonly getMessages: () => readonly FieldMessage[];\n /** Calls `listener` once after each request that changed the state. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Replaces the options, silently: no listener is called. */\n readonly setOptions: (options: FieldOptions<V, D, N>) => void;\n /**\n * `onBeforeInput` for an edit about to happen, then the input's\n * `filterInput`, and what to do with it.\n */\n readonly beforeInput: (\n edit: TextEdit<N> & { readonly cancelable: boolean },\n ) => InputFilterDecision;\n /**\n * The text changed. Read at once, after `changeDelay`, or, while an input\n * method composes (`input.isComposing`), once composition ends. While the\n * field is idle the change is autofill: read and committed at once.\n */\n readonly input: (edit: TextEdit<N>) => void;\n /** An input method finished composing: the text is read. */\n readonly endComposition: (nativeEvent: N | null) => void;\n /**\n * The input's own `filterInput` alone, for the text an input method\n * composed, judged as one insert over the range the composition\n * replaced once it has ended: `before` is the text from before it began.\n * The app's `onBeforeInput` saw the composition as it happened. `allow`\n * for an input with no filter.\n */\n readonly filterComposition: (\n edit: TextEdit<N>,\n before: string,\n ) => InputFilterDecision;\n /**\n * How `text` reads with the field's parser (the app's `parse` around the\n * input's own), changing nothing: a segmented date field checks a paste\n * with it before taking it.\n */\n readonly read: (text: string) => ParseResult<V>;\n readonly focus: (nativeEvent: N | null) => void;\n /** Reads any unread text, then commits it. */\n readonly commit: (\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ) => CommitOutcome;\n /** Focus went: the edit commits, unless Tab did already. */\n readonly blur: (nativeEvent: N | null) => void;\n /** Escape: back to the last commit. False when there is nothing to put back. */\n readonly revert: (nativeEvent: N | null) => boolean;\n /** The clear button: `null`, then a commit. */\n readonly clear: (nativeEvent: N | null) => CommitOutcome;\n /** A value chosen whole (a toggle, an option, a preset), then a commit. */\n readonly pick: (\n value: V | null,\n source: ChangeSource,\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ) => CommitOutcome;\n /**\n * A value set whole without a commit (a step, a part of a composite\n * input): the change chain to `value`, with `cause`'s source and native\n * event. Typed text gives way to the value formatted, even when the value\n * stays.\n */\n readonly change: (value: V | null, cause: ChangeCause<N>) => void;\n /** `change` to `value` with `source: \"api\"`. */\n readonly setValue: (value: V | null) => void;\n /** The change chain back to `defaultValue` (or `null`), with `source: \"api\"`. */\n readonly reset: () => void;\n /**\n * The controlled value, which a renderer passes on every update. Adopted\n * whenever the user is not typing, with no event; while they type it is\n * held, and the first `sync` after the edit ends adopts it.\n */\n readonly sync: (value: V | null) => void;\n /** Messages show from now on: a form's submit reveals every field. */\n readonly reveal: () => void;\n /** Cancels a scheduled reading and ignores a pending check's answer. */\n readonly destroy: () => void;\n}\n\n/** What waits to read the draft's text. Each wait holds what reading it needs. */\ntype ReadWait<V, N> =\n | { readonly kind: \"none\" }\n | {\n readonly kind: \"composing\";\n /** The draft before the edits being read, which a refused change puts back. */\n readonly before: FieldDraft<V>;\n readonly cause: ChangeCause<N>;\n }\n | {\n readonly kind: \"delayed\";\n readonly before: FieldDraft<V>;\n readonly cause: ChangeCause<N>;\n readonly cancel: () => void;\n };\n\n/** A pending check, with the blur its `onBlur` reports once it answers. */\ninterface CheckWait<N> {\n readonly check: PendingCheck<N>;\n readonly blurEvent: N | null;\n}\n\nconst NO_READ = { kind: \"none\" } as const;\n\n/** A change made from code: `setValue` and `reset`. */\nconst API: ChangeCause<never> = {\n source: \"api\",\n nativeEvent: null,\n input: null,\n};\n\n/** The source a commit reports, by what triggered it. */\nconst COMMIT_SOURCES: Readonly<Record<CommitTrigger, ChangeSource>> = {\n enter: \"typing\",\n tab: \"typing\",\n blur: \"typing\",\n picker: \"picker\",\n preset: \"preset\",\n clear: \"clear\",\n toggle: \"toggle\",\n autofill: \"autofill\",\n remove: \"remove\",\n drop: \"drop\",\n paste: \"paste\",\n};\n\n/** Writes a value for what `purpose` says the text is for when it is called. */\nfunction formatterOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n purpose: () => FormatPurpose,\n): (value: V | null) => string {\n const format = options.format ?? options.defaultFormat;\n return (value) => {\n const context: FormatContext<V> = {\n defaultFormat: (shown) => options.defaultFormat(shown, context),\n locale: options.locale,\n messages: options.messages,\n purpose: purpose(),\n };\n return format(value, context);\n };\n}\n\nfunction parserOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n): (text: string) => ParseResult<V> {\n const parse = options.parse ?? options.defaultParse;\n const context: ParseContext<V> = {\n defaultParse: (text) => options.defaultParse(text, context),\n locale: options.locale,\n messages: options.messages,\n };\n return (text) => parse(text, context);\n}\n\nfunction validatorOf<V, D extends object, N>(\n options: FieldOptions<V, D, N>,\n): (value: V | null, text: string) => FieldMessage[] {\n const validators = options.validators ?? [];\n return (value, text) =>\n runValidators(validators, value, {\n text,\n locale: options.locale,\n messages: options.messages,\n });\n}\n\n/**\n * A controller for one field. The field starts idle with `value` when\n * given (controlled), else `defaultValue`, else `null`, validated but with\n * no message shown.\n */\nexport function createFieldController<\n V,\n D extends object = NoDetails,\n N = unknown,\n>(initialOptions: FieldOptions<V, D, N>): FieldController<V, D, N> {\n let options = initialOptions;\n const startValue =\n options.value === undefined\n ? (options.defaultValue ?? null)\n : options.value;\n let state = createFieldState<V>(\n startValue,\n validatorOf(options)(\n startValue,\n formatterOf(options, () => \"display\")(startValue),\n ),\n );\n const listeners = new Set<() => void>();\n let read: ReadWait<V, N> = NO_READ;\n let waiting: CheckWait<N> | null = null;\n let attempts = 0;\n let running = false;\n const queue: (() => void)[] = [];\n let shown: { state: FieldState<V>; messages: FieldMessage[] } | null = null;\n // An input that declares details passes `details`; without it, `D` is\n // `NoDetails` and an empty object is all of them.\n const noDetails = (): D => ({}) as D;\n const purposeNow = (): FormatPurpose => formatPurpose(state.phase);\n\n function env(): FieldEnv<V, D, N> {\n return {\n get: () => state,\n dispatch: (action) => (state = fieldReducer(state, action)),\n handlers: options,\n filterInput: options.filterInput,\n parse: parserOf(options),\n format: formatterOf(options, purposeNow),\n same: (a, b) =>\n a === null || b === null\n ? a === b\n : (options.equals ?? Object.is)(a, b),\n validate: validatorOf(options),\n details: options.details ?? noDetails,\n messages: options.messages,\n commitOnLeave: options.commitOnLeave ?? true,\n };\n }\n\n function setRead(next: ReadWait<V, N>): void {\n if (read.kind === \"delayed\" && read !== next) {\n read.cancel();\n }\n read = next;\n }\n\n /**\n * Lets go of what the state no longer needs: a wait to read text that is\n * no longer unread, a check the field is no longer waiting for.\n */\n function release(): void {\n const { draft, phase } = state;\n if (draft.kind !== \"text\" || draft.reading.kind !== \"pending\") {\n setRead(NO_READ);\n }\n if (phase.kind !== \"checking\") {\n waiting = null;\n }\n }\n\n /**\n * Runs `request` to the end, then whatever its handlers asked for in the\n * meantime, then tells listeners once if the state changed. A request made\n * while one runs is queued and answers `queued` at once.\n */\n function run<T>(request: () => T, queued: T): T {\n if (running) {\n queue.push(() => {\n request();\n });\n return queued;\n }\n running = true;\n const before = state;\n try {\n const result = request();\n release();\n for (let next = queue.shift(); next !== undefined; next = queue.shift()) {\n next();\n release();\n }\n return result;\n } finally {\n running = false;\n queue.length = 0;\n if (state !== before) {\n for (const listener of [...listeners]) {\n listener();\n }\n }\n }\n }\n\n function perform(request: () => void): void {\n run(request, undefined);\n }\n\n /** Reads the draft's text now, or once `changeDelay` has passed. */\n function readSoon(before: FieldDraft<V>, cause: ChangeCause<N>): void {\n const delay = options.changeDelay ?? 0;\n const { schedule } = options;\n if (delay > 0 && schedule !== undefined) {\n setRead({\n kind: \"delayed\",\n before,\n cause,\n cancel: schedule(() => {\n perform(flushRead);\n }, delay),\n });\n return;\n }\n setRead(NO_READ);\n runRead(env(), before, cause);\n }\n\n /** Reads text still waiting to be read, at once: a commit needs its value. */\n function flushRead(): void {\n if (read.kind === \"none\") {\n return;\n }\n const { before, cause } = read;\n setRead(NO_READ);\n runRead(env(), before, cause);\n }\n\n function awaitCheck(check: PendingCheck<N>, blurEvent: N | null): void {\n waiting = { check, blurEvent };\n void check.answer.then((refusal) => {\n perform(() => {\n if (waiting?.check !== check) {\n return;\n }\n const settled = waiting;\n waiting = null;\n runSettle(env(), check, refusal, settled.blurEvent);\n });\n });\n }\n\n function track(step: CommitStep<N>, blurEvent: N | null): CommitOutcome {\n if (step.check !== null) {\n awaitCheck(step.check, blurEvent);\n }\n return step.outcome;\n }\n\n function input(edit: TextEdit<N>): void {\n if (state.phase.kind === \"idle\") {\n const check = runAutofill(env(), edit, ++attempts);\n if (check !== null) {\n awaitCheck(check, null);\n }\n return;\n }\n const before = read.kind === \"none\" ? state.draft : read.before;\n const edited = runEdit(env(), edit);\n if (edit.input?.isComposing === true) {\n if (edited) {\n setRead({ kind: \"composing\", before, cause: edit });\n }\n return;\n }\n // A plain input also ends a composition whose end was not reported.\n if (edited || read.kind === \"composing\") {\n readSoon(before, edit);\n }\n }\n\n return {\n getState: () => state,\n getText: () => fieldText(state, formatterOf(options, purposeNow)),\n getMessages: () => {\n if (shown?.state !== state) {\n shown = { state, messages: fieldMessages(state) };\n }\n return shown.messages;\n },\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setOptions: (next) => {\n options = next;\n },\n // Changes no state, so it runs even inside another request: the browser\n // needs its answer before the edit happens.\n beforeInput: (edit) => runBeforeInput(env(), edit),\n input: (edit) => {\n perform(() => {\n input(edit);\n });\n },\n endComposition: (nativeEvent) => {\n perform(() => {\n if (read.kind !== \"composing\") {\n return;\n }\n const { before, cause } = read;\n readSoon(before, {\n ...cause,\n nativeEvent,\n input: cause.input && { ...cause.input, isComposing: false },\n });\n });\n },\n filterComposition: (edit, before) =>\n options.filterInput?.(edit, before) ?? { kind: \"allow\" },\n read: (text) => parserOf(options)(text),\n focus: (nativeEvent) => {\n perform(() => {\n runFocus(env(), nativeEvent);\n });\n },\n commit: (trigger, nativeEvent) =>\n run(() => {\n flushRead();\n return track(\n runCommit(env(), {\n trigger,\n source: COMMIT_SOURCES[trigger],\n nativeEvent,\n attempt: ++attempts,\n }),\n trigger === \"blur\" ? nativeEvent : null,\n );\n }, CHECKING),\n blur: (nativeEvent) => {\n perform(() => {\n flushRead();\n if (waiting !== null) {\n waiting = { ...waiting, blurEvent: nativeEvent };\n }\n const check = runBlur(env(), nativeEvent, ++attempts);\n if (check !== null) {\n awaitCheck(check, nativeEvent);\n }\n });\n },\n revert: (nativeEvent) => run(() => runRevert(env(), nativeEvent), false),\n clear: (nativeEvent) =>\n run(\n () => track(runClear(env(), nativeEvent, ++attempts), null),\n CHECKING,\n ),\n pick: (value, source, trigger, nativeEvent) =>\n run(\n () =>\n track(\n runPick(env(), value, {\n trigger,\n source,\n nativeEvent,\n attempt: ++attempts,\n }),\n null,\n ),\n CHECKING,\n ),\n change: (value, cause) => {\n perform(() => {\n runValueChange(env(), value, cause);\n });\n },\n setValue: (value) => {\n perform(() => {\n runValueChange(env(), value, API);\n });\n },\n reset: () => {\n perform(() => {\n runValueChange(env(), options.defaultValue ?? null, API);\n });\n },\n sync: (value) => {\n perform(() => {\n runSync(env(), value);\n });\n },\n reveal: () => {\n perform(() => {\n runReveal(env());\n });\n },\n destroy: () => {\n setRead(NO_READ);\n waiting = null;\n },\n };\n}\n","import type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n unreadable,\n type FormatContext,\n type FormatPurpose,\n type ParseResult,\n} from \"../parse\";\nimport {\n createFieldController,\n type FieldController,\n type FieldOptions,\n} from \"./createFieldController\";\nimport type { CommitTrigger, FieldBeforeInputEvent, NoDetails } from \"./events\";\nimport type { ChangeCause, CommitOutcome } from \"./plan\";\nimport { unreadableMessage, type FieldState } from \"./state\";\n\n/** Each part's value, by part name; `null` for an empty part. */\nexport type PartValues<P extends Record<string, unknown>> = {\n readonly [K in keyof P]: P[K] | null;\n};\n\n/** Each part's text, by part name. */\nexport type PartTexts<P extends Record<string, unknown>> = {\n readonly [K in keyof P]: string;\n};\n\n/**\n * Which part an event is about: the part whose edit it is, `\"all\"` for a\n * value set whole (`setValue`, a controlled value, a revert or clear), and\n * on a commit the part that differs from the last commit (`\"all\"` when\n * several do, `null` when none does).\n */\nexport type PartChange<P extends Record<string, unknown>> =\n keyof P | \"all\" | null;\n\n/** How one part reads and writes its text. The composite owns its value and events. */\nexport type PartOptions<T, N = unknown> = Pick<\n FieldOptions<T, NoDetails, N>,\n | \"parse\"\n | \"format\"\n | \"defaultParse\"\n | \"defaultFormat\"\n | \"equals\"\n | \"filterInput\"\n | \"locale\"\n>;\n\n/** What `assemble` knows beside the parts' values. */\nexport interface AssembleContext {\n readonly locale: Intl.LocalesArgument;\n readonly messages: FormsMessages;\n}\n\n/** What a composite input's `details` is told beside the field's state. */\nexport interface CompositeDetailsContext<\n P extends Record<string, unknown>,\n N = unknown,\n> {\n readonly changed: PartChange<P>;\n readonly parts: { readonly [K in keyof P]: FieldState<P[K]> };\n readonly texts: PartTexts<P>;\n /** The change the event is about, as `FieldOptions.details` receives it. */\n readonly cause: ChangeCause<N>;\n}\n\n/**\n * What a composite input is given: the field's options, as for one input,\n * with how each part reads and writes, and how the parts' values make the\n * one value the app sees and back. The renderer passes the latest on every\n * update through `setOptions`.\n */\nexport interface CompositeFieldOptions<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n> extends Omit<\n FieldOptions<V, D, N>,\n | \"parse\"\n | \"format\"\n | \"defaultParse\"\n | \"defaultFormat\"\n | \"details\"\n | \"filterInput\"\n | \"changeDelay\"\n | \"schedule\"\n | \"commitOnLeave\"\n> {\n /** Each part, in the order the parts are read: a part's unreadable text is reported first. */\n readonly parts: { readonly [K in keyof P]: PartOptions<P[K], N> };\n /** The value the parts make, or why they make none (an end before its start). */\n readonly assemble: (\n parts: PartValues<P>,\n context: AssembleContext,\n ) => ParseResult<V>;\n /** Each part's value within `value`. */\n readonly split: (value: V | null) => PartValues<P>;\n /** The field's text, which events carry: the parts' texts, joined. */\n readonly join: (texts: PartTexts<P>) => string;\n /** The input's own details, added to every event the field fires. */\n readonly details?:\n | ((\n current: FieldState<V>,\n previous: FieldState<V>,\n context: CompositeDetailsContext<P, N>,\n ) => D)\n | undefined;\n}\n\n/**\n * One part's controller, for a renderer to attach a control to as it\n * would a field's: its text and state are the part's own; its edits,\n * Enter, Escape and the clear button act on the whole field.\n */\nexport type PartController<T, N = unknown> = Pick<\n FieldController<T, NoDetails, N>,\n | \"getState\"\n | \"getText\"\n | \"getMessages\"\n | \"subscribe\"\n | \"beforeInput\"\n | \"input\"\n | \"endComposition\"\n | \"filterComposition\"\n | \"read\"\n | \"focus\"\n | \"commit\"\n | \"blur\"\n | \"revert\"\n | \"clear\"\n | \"reset\"\n | \"change\"\n>;\n\n/** The field and its parts, whole: one object until any of them changes. */\nexport interface CompositeState<V, P extends Record<string, unknown>> {\n readonly field: FieldState<V>;\n readonly parts: { readonly [K in keyof P]: FieldState<P[K]> };\n}\n\n/**\n * An input made of parts (both ends of a range, an amount and its\n * currency) driven as one field. Expect this API to change while its first\n * users settle it.\n */\nexport interface CompositeController<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n> {\n /** The field the app sees: its events, value and messages. */\n readonly field: Omit<FieldController<V, D, N>, \"setOptions\">;\n /** One controller per part, for a renderer to attach a control to. */\n readonly parts: { readonly [K in keyof P]: PartController<P[K], N> };\n readonly getState: () => CompositeState<V, P>;\n /** Calls `listener` after each request that changed the field or a part. */\n readonly subscribe: (listener: () => void) => () => void;\n /** Replaces the options, silently. */\n readonly setOptions: (options: CompositeFieldOptions<V, P, D, N>) => void;\n /**\n * Focus left the whole input (a part's own blur cannot tell): the field\n * commits with `trigger` `\"tab\"` or `\"blur\"`, then `onBlur`.\n */\n readonly leave: (by: \"tab\" | \"blur\", nativeEvent: N | null) => void;\n /** Cancels what the field and its parts wait for. */\n readonly destroy: () => void;\n}\n\n/** What the field is doing, which its events' `PartChange` reports. */\ntype Activity<P> =\n | { readonly kind: \"whole\" }\n | { readonly kind: \"part\"; readonly part: keyof P }\n | { readonly kind: \"commit\" };\n\nconst WHOLE = { kind: \"whole\" } as const;\nconst COMMITTING = { kind: \"commit\" } as const;\n\n/** A value the composite pushes into a part. */\nconst API: ChangeCause<never> = {\n source: \"api\",\n nativeEvent: null,\n input: null,\n};\n\n/**\n * A controller for an input made of parts. Each part is a field of its\n * own with no app handlers: it reads, filters and writes its text as a\n * lone input does. The composite relays every part edit to the field the\n * app sees as an edit of the joined text, so `onBeforeInput` and `onInput`\n * fire with the part's edit, and the field reads its value from the parts\n * (`assemble`), then runs the change chain. A value the field takes whole\n * (`setValue` in `onBeforeChange`, a controlled value, a revert, a clear)\n * is pushed into the parts by `split`; a part whose text already reads as\n * its value keeps it while the user types, and every part shows its value\n * formatted once the field commits.\n *\n * Tab from part to part commits only the part, normalizing its text.\n * Enter in a part commits the field; Escape reverts it. Focus entering a\n * part of an idle field fires `onFocus`; focus leaving the whole input is\n * the renderer's to report through `leave`. Parts read at once: they take\n * no `changeDelay`.\n */\nexport function createCompositeController<\n V,\n P extends Record<string, unknown>,\n D extends object = NoDetails,\n N = unknown,\n>(\n initialOptions: CompositeFieldOptions<V, P, D, N>,\n): CompositeController<V, P, D, N> {\n let options = initialOptions;\n let activity: Activity<P> = WHOLE;\n // The part names, in the order the options list them. `keyof P` holds\n // exactly these keys, which `Object.keys` cannot say.\n const names = Object.keys(options.parts) as (keyof P)[];\n\n /** One entry per part, made by `make`. */\n function eachPart<R>(make: (name: keyof P) => R): Record<keyof P, R> {\n // `fromEntries` loses the keys' type; there is one entry per name.\n return Object.fromEntries(\n names.map((name) => [name, make(name)]),\n ) as Record<keyof P, R>;\n }\n\n function during<R>(next: Activity<P>, request: () => R): R {\n const before = activity;\n activity = next;\n try {\n return request();\n } finally {\n activity = before;\n }\n }\n\n function same(a: V | null, b: V | null): boolean {\n return a === null || b === null\n ? a === b\n : (options.equals ?? Object.is)(a, b);\n }\n\n function samePart<K extends keyof P>(\n name: K,\n a: P[K] | null,\n b: P[K] | null,\n ): boolean {\n return a === null || b === null\n ? a === b\n : (options.parts[name].equals ?? Object.is)(a, b);\n }\n\n function formatPart<K extends keyof P>(\n name: K,\n value: P[K] | null,\n purpose: FormatPurpose,\n ): string {\n const own = options.parts[name];\n const context: FormatContext<P[K]> = {\n defaultFormat: (shown) => own.defaultFormat(shown, context),\n locale: own.locale ?? options.locale,\n messages: options.messages,\n purpose,\n };\n return (own.format ?? own.defaultFormat)(value, context);\n }\n\n function partOptions<K extends keyof P>(\n name: K,\n value: P[K] | null,\n ): FieldOptions<P[K], NoDetails, N> {\n const own = options.parts[name];\n return {\n ...own,\n defaultValue: value,\n locale: own.locale ?? options.locale,\n messages: options.messages,\n onBeforeInput: (event) => {\n relayBeforeInput(name, event);\n },\n };\n }\n\n const startValue =\n options.value === undefined\n ? (options.defaultValue ?? null)\n : options.value;\n const startParts = options.split(startValue);\n // One controller per part; `eachPart` keys them by name.\n const parts = eachPart((name) =>\n createFieldController(partOptions(name, startParts[name])),\n ) as unknown as {\n readonly [K in keyof P]: FieldController<P[K], NoDetails, N>;\n };\n\n function texts(): PartTexts<P> {\n return eachPart((name) => parts[name].getText());\n }\n\n /** What the parts make now: the first unreadable part's message, or `assemble`'s reading. */\n function readParts(): ParseResult<V> {\n for (const name of names) {\n const message = unreadableMessage(parts[name].getState().draft);\n if (message !== null) {\n return unreadable(message);\n }\n }\n // Each entry is its part's value.\n const values = eachPart(\n (name) => parts[name].getState().value,\n ) as PartValues<P>;\n return options.assemble(values, {\n locale: options.locale,\n messages: options.messages,\n });\n }\n\n function changedNow(previous: FieldState<V>): PartChange<P> {\n switch (activity.kind) {\n case \"part\":\n return activity.part;\n case \"whole\":\n return \"all\";\n case \"commit\": {\n const { phase } = previous;\n if (phase.kind === \"idle\") {\n return \"all\";\n }\n const now = options.split(previous.value);\n const committed = options.split(phase.committedValue);\n const differ = names.filter(\n (name) => !samePart(name, now[name], committed[name]),\n );\n const [only] = differ;\n if (differ.length === 0 || only === undefined) {\n return null;\n }\n return differ.length === 1 ? only : \"all\";\n }\n }\n }\n\n function fieldOptions(): FieldOptions<V, D, N> {\n const { details } = options;\n return {\n ...options,\n defaultParse: () => readParts(),\n defaultFormat: (value, context) => {\n const values = options.split(value);\n return options.join(\n eachPart((name) => formatPart(name, values[name], context.purpose)),\n );\n },\n details:\n details &&\n ((current, previous, cause) =>\n details(current, previous, {\n changed: changedNow(previous),\n // Each entry is its part's state.\n parts: eachPart((name) => parts[name].getState()) as {\n readonly [K in keyof P]: FieldState<P[K]>;\n },\n texts: texts(),\n cause,\n })),\n };\n }\n\n const field = createFieldController(fieldOptions());\n\n /** The app's `onBeforeInput` for a part's edit, as an edit of the joined text. */\n function relayBeforeInput<K extends keyof P>(\n name: K,\n event: FieldBeforeInputEvent<P[K], NoDetails, N>,\n ): void {\n const decision = during({ kind: \"part\", part: name }, () =>\n field.beforeInput({\n text: options.join({ ...texts(), [name]: event.text }),\n source: event.source,\n nativeEvent: event.nativeEvent,\n input: event.input,\n cancelable: event.cancelable,\n }),\n );\n if (decision.kind === \"prevent\") {\n event.preventDefault();\n } else if (decision.kind === \"rewrite\") {\n event.setData(decision.data);\n }\n }\n\n /** A part's text changed: the field sees an edit of the joined text. */\n function relayEdit(name: keyof P, cause: ChangeCause<N>): void {\n during({ kind: \"part\", part: name }, () => {\n field.input({ ...cause, text: options.join(texts()) });\n });\n }\n\n /**\n * Shows the field's value in the parts. A part keeps its text when it\n * already holds its value and, unless `exact`, while that text reads as\n * it (typed digits not yet normalized). A part being composed is left to\n * the input method.\n */\n function showValue(exact: boolean): void {\n const target = options.split(field.getState().value);\n for (const name of names) {\n const part = parts[name];\n const { draft, value } = part.getState();\n if (draft.kind === \"text\" && draft.reading.kind === \"pending\") {\n continue;\n }\n const reads = draft.kind === \"current\" || draft.reading.kind === \"value\";\n if (\n samePart(name, value, target[name]) &&\n (draft.kind === \"current\" || (!exact && reads))\n ) {\n continue;\n }\n part.change(target[name], API);\n }\n }\n\n /**\n * After each request that changed the field: an idle field shows its\n * value in every part exactly (a swapped range's texts change places);\n * otherwise a value the parts do not make came from elsewhere, and is\n * pushed into them. Text that cannot be read is the user's, left alone.\n */\n function followField(): void {\n const state = field.getState();\n if (state.draft.kind === \"current\" && state.phase.kind === \"idle\") {\n showValue(true);\n return;\n }\n if (state.draft.kind === \"text\" && state.draft.reading.kind !== \"value\") {\n return;\n }\n const made = readParts();\n if (made.kind === \"value\" && same(made.value, state.value)) {\n return;\n }\n showValue(false);\n }\n field.subscribe(followField);\n\n function commitWhole(\n trigger: CommitTrigger,\n nativeEvent: N | null,\n ): CommitOutcome {\n return during(COMMITTING, () => {\n const outcome = field.commit(trigger, nativeEvent);\n if (outcome.kind === \"accepted\") {\n showValue(true);\n }\n return outcome;\n });\n }\n\n function facade<K extends keyof P>(name: K): PartController<P[K], N> {\n const part = parts[name];\n return {\n getState: part.getState,\n getText: part.getText,\n getMessages: part.getMessages,\n subscribe: part.subscribe,\n beforeInput: part.beforeInput,\n input: (edit) => {\n part.input(edit);\n relayEdit(name, edit);\n },\n endComposition: (nativeEvent) => {\n part.endComposition(nativeEvent);\n during({ kind: \"part\", part: name }, () => {\n field.endComposition(nativeEvent);\n });\n },\n filterComposition: part.filterComposition,\n read: part.read,\n focus: (nativeEvent) => {\n part.focus(nativeEvent);\n field.focus(nativeEvent);\n },\n commit: (trigger, nativeEvent) =>\n trigger === \"tab\"\n ? part.commit(trigger, nativeEvent)\n : commitWhole(trigger, nativeEvent),\n blur: part.blur,\n revert: (nativeEvent) => {\n const reverted = field.revert(nativeEvent);\n if (reverted) {\n showValue(true);\n }\n return reverted;\n },\n clear: field.clear,\n reset: field.reset,\n change: (value, cause) => {\n part.change(value, cause);\n relayEdit(name, cause);\n },\n };\n }\n\n // One facade per part; `eachPart` keys them by name.\n const facades = eachPart(facade) as unknown as {\n readonly [K in keyof P]: PartController<P[K], N>;\n };\n\n let snapshot: CompositeState<V, P> | null = null;\n\n return {\n field,\n parts: facades,\n getState: () => {\n const fieldState = field.getState();\n if (\n snapshot?.field !== fieldState ||\n names.some((name) => snapshot?.parts[name] !== parts[name].getState())\n ) {\n snapshot = {\n field: fieldState,\n // Each entry is its part's state.\n parts: eachPart((name) => parts[name].getState()) as {\n readonly [K in keyof P]: FieldState<P[K]>;\n },\n };\n }\n return snapshot;\n },\n subscribe: (listener) => {\n const unsubscribes = [\n field.subscribe(listener),\n ...names.map((name) => parts[name].subscribe(listener)),\n ];\n return () => {\n for (const unsubscribe of unsubscribes) {\n unsubscribe();\n }\n };\n },\n setOptions: (next) => {\n options = next;\n field.setOptions(fieldOptions());\n for (const name of names) {\n parts[name].setOptions(partOptions(name, parts[name].getState().value));\n }\n },\n leave: (by, nativeEvent) => {\n during(COMMITTING, () => {\n if (field.getState().phase.kind === \"idle\") {\n return;\n }\n if (by === \"tab\") {\n field.commit(\"tab\", nativeEvent);\n }\n field.blur(nativeEvent);\n });\n },\n destroy: () => {\n field.destroy();\n for (const name of names) {\n parts[name].destroy();\n }\n },\n };\n}\n","/** A token of an app's own: one character it accepts, and how it is written. */\nexport interface MaskTokenDefinition {\n /** Tested against one character, after its digits and full-width forms become ASCII. */\n readonly accept: RegExp;\n /** Whether the slot may stay empty. False by default. */\n readonly optional?: boolean | undefined;\n /** Applied to the character before it is kept; the case tokens still apply after. */\n readonly transform?: ((character: string) => string) | undefined;\n}\n\n/** One-character token names, beside the built-in tokens, which they may replace. */\nexport type MaskTokens = Readonly<Record<string, RegExp | MaskTokenDefinition>>;\n\n/** How letters typed into a slot are written, as `>`, `<` and `|` set it. */\nexport type MaskLetterCase = \"upper\" | \"lower\" | \"keep\";\n\n/**\n * One place in a compiled pattern: a slot that takes a character, or a\n * literal printed as it is. `section` numbers the optional section (`[ ]`)\n * it sits in, `null` outside one.\n */\nexport type MaskSlot =\n | {\n readonly kind: \"input\";\n /** The token that made it: `\"0\"`, `\"L\"`, an app's own. */\n readonly token: string;\n readonly accepts: (character: string) => boolean;\n readonly optional: boolean;\n readonly transform: ((character: string) => string) | null;\n readonly letterCase: MaskLetterCase;\n readonly section: number | null;\n }\n | {\n readonly kind: \"literal\";\n readonly character: string;\n readonly section: number | null;\n };\n\n/** A pattern compiled into its slots. */\nexport interface CompiledMask {\n readonly pattern: string;\n readonly slots: readonly MaskSlot[];\n}\n\n/**\n * A compiled pattern, or why it could not be compiled. `position` is the\n * index in the pattern where the problem starts, `null` for a problem in\n * the custom tokens.\n */\nexport type MaskCompileResult =\n | { readonly kind: \"compiled\"; readonly mask: CompiledMask }\n | {\n readonly kind: \"error\";\n readonly message: string;\n readonly position: number | null;\n };\n\ninterface Token {\n readonly accepts: (character: string) => boolean;\n readonly optional: boolean;\n readonly transform: ((character: string) => string) | null;\n}\n\nconst DIGIT = /^[0-9]$/;\nconst LETTER = /^\\p{L}$/u;\nconst LETTER_OR_DIGIT = /^[\\p{L}0-9]$/u;\n\nfunction digit(character: string): boolean {\n return DIGIT.test(character);\n}\n\nfunction letter(character: string): boolean {\n return LETTER.test(character);\n}\n\nfunction letterOrDigit(character: string): boolean {\n return LETTER_OR_DIGIT.test(character);\n}\n\nconst BUILT_IN_TOKENS: Readonly<Record<string, Token>> = {\n \"0\": { accepts: digit, optional: false, transform: null },\n \"9\": { accepts: digit, optional: true, transform: null },\n \"#\": {\n accepts: (character) =>\n digit(character) || character === \"+\" || character === \"-\",\n optional: true,\n transform: null,\n },\n L: { accepts: letter, optional: false, transform: null },\n \"?\": { accepts: letter, optional: true, transform: null },\n \"&\": {\n accepts: (character) => !/^\\s$/u.test(character),\n optional: false,\n transform: null,\n },\n C: { accepts: () => true, optional: true, transform: null },\n A: { accepts: letterOrDigit, optional: false, transform: null },\n a: { accepts: letterOrDigit, optional: true, transform: null },\n};\n\n/** Characters the grammar itself uses, which no token may be named. */\nconst GRAMMAR = new Set([\"\\\\\", \"[\", \"]\", \">\", \"<\", \"|\"]);\n\nconst CASES: Readonly<Record<string, MaskLetterCase>> = {\n \">\": \"upper\",\n \"<\": \"lower\",\n \"|\": \"keep\",\n};\n\n/** `pattern` tested against a whole character: `g` and `y` make `test` remember where it stopped, so they are dropped. */\nfunction characterTest(pattern: RegExp): (character: string) => boolean {\n const whole = new RegExp(\n `^(?:${pattern.source})$`,\n pattern.flags.replace(/[gy]/g, \"\"),\n );\n return (character) => whole.test(character);\n}\n\nfunction customToken(definition: RegExp | MaskTokenDefinition): Token {\n if (definition instanceof RegExp) {\n return {\n accepts: characterTest(definition),\n optional: false,\n transform: null,\n };\n }\n return {\n accepts: characterTest(definition.accept),\n optional: definition.optional ?? false,\n transform: definition.transform ?? null,\n };\n}\n\nfunction compileError(\n message: string,\n position: number | null,\n): MaskCompileResult {\n return { kind: \"error\", message, position };\n}\n\n/** The built-in tokens with `tokens` laid over them, or why `tokens` cannot be used. */\nfunction tokenTable(\n tokens: MaskTokens | undefined,\n): Readonly<Record<string, Token>> | string {\n if (tokens === undefined) {\n return BUILT_IN_TOKENS;\n }\n const table: Record<string, Token> = { ...BUILT_IN_TOKENS };\n for (const [name, definition] of Object.entries(tokens)) {\n if (Array.from(name).length !== 1) {\n return `A token's name is one character, not \"${name}\"`;\n }\n if (GRAMMAR.has(name)) {\n return `\"${name}\" is part of the mask grammar and cannot name a token`;\n }\n table[name] = customToken(definition);\n }\n return table;\n}\n\n/**\n * Compiles `pattern` on the .NET-style grammar: `0` a digit, `9` an\n * optional digit, `#` an optional digit, `+` or `-`, `L` a letter, `?` an\n * optional letter, `&` any character but a space, `C` any optional\n * character, `A` a letter or digit, `a` an optional one; `>`, `<` and `|`\n * upper-case, lower-case or keep the letters after them; `\\` makes the next\n * character a literal; `[ ]` holds an optional section, which appears once\n * one of its slots is filled; anything else is a literal. `tokens` adds\n * one-character tokens of an app's own, or replaces built-in ones.\n *\n * A malformed pattern (an unclosed, nested or stray bracket, an empty\n * section, a trailing `\\`, no slot at all) is an error with its position.\n */\nexport function compileMask(\n pattern: string,\n tokens?: MaskTokens,\n): MaskCompileResult {\n const table = tokenTable(tokens);\n if (typeof table === \"string\") {\n return compileError(table, null);\n }\n const slots: MaskSlot[] = [];\n let letterCase: MaskLetterCase = \"keep\";\n let section: { readonly id: number; readonly start: number } | null = null;\n let sections = 0;\n let sectionHasInput = false;\n let escaped = false;\n let index = 0;\n for (const character of pattern) {\n const position = index;\n index += character.length;\n if (escaped) {\n slots.push({ kind: \"literal\", character, section: section?.id ?? null });\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (character === \"[\") {\n if (section !== null) {\n return compileError(\"Optional sections cannot nest\", position);\n }\n section = { id: sections, start: position };\n sections += 1;\n sectionHasInput = false;\n continue;\n }\n if (character === \"]\") {\n if (section === null) {\n return compileError(\n 'A \"]\" closes no section; write \"\\\\]\" for the character',\n position,\n );\n }\n if (!sectionHasInput) {\n return compileError(\n \"An optional section needs at least one slot\",\n section.start,\n );\n }\n section = null;\n continue;\n }\n const nextCase = CASES[character];\n if (nextCase !== undefined) {\n letterCase = nextCase;\n continue;\n }\n const token = table[character];\n if (token === undefined) {\n slots.push({ kind: \"literal\", character, section: section?.id ?? null });\n continue;\n }\n slots.push({\n kind: \"input\",\n token: character,\n accepts: token.accepts,\n optional: token.optional,\n transform: token.transform,\n letterCase,\n section: section?.id ?? null,\n });\n sectionHasInput = true;\n }\n if (escaped) {\n return compileError(\n 'A \"\\\\\" at the end escapes nothing',\n pattern.length - 1,\n );\n }\n if (section !== null) {\n return compileError(\"This optional section is not closed\", section.start);\n }\n if (!slots.some((slot) => slot.kind === \"input\")) {\n return compileError(\"A mask needs at least one slot\", 0);\n }\n return { kind: \"compiled\", mask: { pattern, slots } };\n}\n\n/** Patterns compiled so far, per token set: a mask compiles on every edit. */\nconst compiledByTokens = new WeakMap<MaskTokens, Map<string, CompiledMask>>();\nconst compiledBuiltIn = new Map<string, CompiledMask>();\n\n/**\n * `pattern` compiled with `tokens`, from the cache when it has been before.\n * Throws on a malformed pattern: an input checks its patterns with\n * `compileMask` before it relies on them.\n */\nexport function compiledPattern(\n pattern: string,\n tokens: MaskTokens | undefined,\n): CompiledMask {\n let cache = compiledBuiltIn;\n if (tokens !== undefined) {\n cache = compiledByTokens.get(tokens) ?? new Map<string, CompiledMask>();\n compiledByTokens.set(tokens, cache);\n }\n const cached = cache.get(pattern);\n if (cached !== undefined) {\n return cached;\n }\n const result = compileMask(pattern, tokens);\n if (result.kind === \"error\") {\n throw new SyntaxError(\n `Mask \"${pattern}\": ${result.message}${\n result.position === null ? \"\" : ` (at ${String(result.position)})`\n }`,\n );\n }\n cache.set(pattern, result.mask);\n return result.mask;\n}\n","import { digitValue, isDigit } from \"../number/digits\";\nimport type { CompiledMask, MaskSlot } from \"./grammar\";\n\n// The mask's model: a compiled pattern's slots, each input slot filled,\n// empty or skipped (an optional slot typed past). An edit works on items,\n// the characters typed and the steps past literals that skipped slots,\n// laid into the slots in order with no holes. The engine keeps nothing\n// between edits: it reads the text on screen back into cells, edits the\n// items, lays them out again and writes the text.\n\n/** What one input slot holds. Entries for literals stay empty. */\nexport type MaskCell =\n | { readonly kind: \"filled\"; readonly character: string }\n | { readonly kind: \"skipped\" }\n | { readonly kind: \"empty\" };\n\n/**\n * What an edit moves around: a character for an input slot, or a step past\n * the literal `literal`, leaving the optional slots before it skipped\n * (typing \".\" after \"19\" in an IPv4 mask).\n */\nexport type MaskItem =\n | { readonly kind: \"character\"; readonly character: string }\n | { readonly kind: \"jump\"; readonly literal: string };\n\n/** An item, and the index in the text where it was read. */\nexport interface PlacedItem {\n readonly item: MaskItem;\n readonly at: number;\n}\n\n/**\n * What laying out does with an item no slot takes: `truncate` drops it\n * with every item after it, `lenient` (a paste) drops it alone.\n */\nexport type LayoutMode = \"truncate\" | \"lenient\";\n\n/** Items laid into a pattern. */\nexport interface MaskLayout {\n readonly mask: CompiledMask;\n readonly cells: readonly MaskCell[];\n /** For each item, the slot it filled or the literal it stepped past; `null` when dropped. */\n readonly landed: readonly (number | null)[];\n /** How many characters found a slot. */\n readonly kept: number;\n}\n\nconst EMPTY: MaskCell = { kind: \"empty\" };\nconst SKIPPED: MaskCell = { kind: \"skipped\" };\n\n/**\n * `character` as a mask keeps it: a decimal digit of any script as its\n * ASCII digit, a full-width form (from an input method) as its ASCII.\n */\nexport function maskCharacter(character: string): string {\n if (isDigit(character)) {\n return String(digitValue(character));\n }\n const code = character.codePointAt(0) ?? 0;\n if (code >= 0xff01 && code <= 0xff5e) {\n return String.fromCodePoint(code - 0xfee0);\n }\n return code === 0x3000 ? \" \" : character;\n}\n\n/** `character` as `slot` keeps it, after its transform and case; `null` when the slot refuses it. */\nfunction accepted(\n slot: Extract<MaskSlot, { kind: \"input\" }>,\n character: string,\n locale: Intl.LocalesArgument,\n): string | null {\n if (!slot.accepts(character)) {\n return null;\n }\n const kept = slot.transform === null ? character : slot.transform(character);\n switch (slot.letterCase) {\n case \"upper\":\n return kept.toLocaleUpperCase(locale);\n case \"lower\":\n return kept.toLocaleLowerCase(locale);\n case \"keep\":\n return kept;\n }\n}\n\n/**\n * Places `item` in the first slot from `from` that takes it, into `cells`.\n * A character fills the next input slot that accepts it, crossing\n * literals; one equal to a literal it reaches steps past it. Either may\n * skip optional slots that refuse it on the way, which are then marked\n * skipped; a required slot that refuses it stops it. A slot that accepts\n * the character wins over a literal after it.\n */\nfunction place(\n slots: readonly MaskSlot[],\n cells: MaskCell[],\n from: number,\n item: MaskItem,\n locale: Intl.LocalesArgument,\n): number | null {\n const skipped: number[] = [];\n const settle = (slot: number, cell: MaskCell | null) => {\n for (const index of skipped) {\n cells[index] = SKIPPED;\n }\n if (cell !== null) {\n cells[slot] = cell;\n }\n return slot;\n };\n const character = item.kind === \"jump\" ? item.literal : item.character;\n for (let index = from; index < slots.length; index += 1) {\n const slot = slots[index];\n if (slot === undefined) {\n break;\n }\n if (slot.kind === \"literal\") {\n if (slot.character === character) {\n return settle(index, null);\n }\n continue;\n }\n if (item.kind === \"character\") {\n const kept = accepted(slot, character, locale);\n if (kept !== null) {\n return settle(index, { kind: \"filled\", character: kept });\n }\n }\n if (!slot.optional) {\n return null;\n }\n skipped.push(index);\n }\n return null;\n}\n\n/** `items` laid into `mask` from its start. */\nexport function layOut(\n mask: CompiledMask,\n items: readonly MaskItem[],\n mode: LayoutMode,\n locale: Intl.LocalesArgument,\n): MaskLayout {\n const cells: MaskCell[] = mask.slots.map(() => EMPTY);\n const landed: (number | null)[] = [];\n let next = 0;\n let kept = 0;\n let stopped = false;\n for (const item of items) {\n const slot = stopped ? null : place(mask.slots, cells, next, item, locale);\n if (slot === null) {\n stopped = mode === \"truncate\";\n landed.push(null);\n continue;\n }\n landed.push(slot);\n next = slot + 1;\n if (item.kind === \"character\") {\n kept += 1;\n }\n }\n return { mask, cells, landed, kept };\n}\n\n/** Whether every item found a place. */\nexport function fits(layout: MaskLayout): boolean {\n return layout.landed.every((slot) => slot !== null);\n}\n\n/**\n * The items a layout holds, each at the text index `at` gives its slot: a\n * character per filled slot, and a jump at each literal that follows\n * skipped slots.\n */\nexport function itemsOf(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n at: readonly number[],\n): PlacedItem[] {\n const items: PlacedItem[] = [];\n let skipping = false;\n mask.slots.forEach((slot, index) => {\n const cell = cells[index] ?? EMPTY;\n if (slot.kind === \"literal\") {\n if (skipping) {\n items.push({\n item: { kind: \"jump\", literal: slot.character },\n at: at[index] ?? 0,\n });\n skipping = false;\n }\n } else if (cell.kind === \"filled\") {\n items.push({\n item: { kind: \"character\", character: cell.character },\n at: at[index] ?? 0,\n });\n skipping = false;\n } else if (cell.kind === \"skipped\") {\n skipping = true;\n }\n });\n return items;\n}\n\n/** Cells read from text, with the text index of each slot (where it would be, when not printed). */\nexport interface MaskReading {\n readonly cells: readonly MaskCell[];\n readonly at: readonly number[];\n}\n\n/**\n * Reads `text` as `mask` writes it, focused or not: a prompt character is\n * an empty slot, an optional slot facing a character it refuses is\n * skipped, and a literal that is not there was not printed. `null` when the\n * text is not this pattern's: a required slot refuses its character, a\n * required slot is empty before a filled one, or text is left over.\n */\nexport function readExact(\n mask: CompiledMask,\n text: string,\n prompt: string,\n locale: Intl.LocalesArgument,\n): MaskReading | null {\n const characters = Array.from(text);\n const cells: MaskCell[] = [];\n const at: number[] = [];\n let next = 0;\n let index = 0;\n for (const slot of mask.slots) {\n at.push(index);\n const typed = characters[next];\n if (slot.kind === \"literal\") {\n cells.push(EMPTY);\n if (typed === slot.character) {\n next += 1;\n index += typed.length;\n }\n continue;\n }\n if (typed === undefined || (prompt !== \"\" && typed === prompt)) {\n cells.push(EMPTY);\n } else {\n const kept = accepted(slot, maskCharacter(typed), locale);\n if (kept !== null) {\n cells.push({ kind: \"filled\", character: kept });\n } else if (slot.optional) {\n cells.push(SKIPPED);\n continue;\n } else {\n return null;\n }\n }\n if (typed !== undefined) {\n next += 1;\n index += typed.length;\n }\n }\n if (next < characters.length) {\n return null;\n }\n const last = cells.findLastIndex((cell) => cell.kind === \"filled\");\n for (let slot = 0; slot < last; slot += 1) {\n const definition = mask.slots[slot];\n if (definition?.kind === \"input\" && cells[slot]?.kind === \"empty\") {\n if (!definition.optional) {\n return null;\n }\n cells[slot] = SKIPPED;\n }\n }\n return { cells, at };\n}\n\n/** The sections with a filled slot: only they print. */\nfunction filledSections(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): ReadonlySet<number> {\n const sections = new Set<number>();\n mask.slots.forEach((slot, index) => {\n if (slot.section !== null && cells[index]?.kind === \"filled\") {\n sections.add(slot.section);\n }\n });\n return sections;\n}\n\n/** Text written from cells, with where each slot starts in it (`offsets[slots.length]` is the end). */\nexport interface MaskWriting {\n readonly text: string;\n readonly offsets: readonly number[];\n}\n\n/**\n * The text cells show. While focused: literals, filled characters, the\n * prompt in each empty slot, nothing for skipped slots, and nothing of an\n * optional section with no slot filled; with no prompt character, the text\n * ends at the first empty slot. Otherwise (display, and the formatted\n * value): literals and filled characters up to the last filled slot.\n */\nexport function writeCells(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n focused: boolean,\n prompt: string,\n): MaskWriting {\n const sections = filledSections(mask, cells);\n const last = cells.findLastIndex((cell) => cell.kind === \"filled\");\n const offsets: number[] = [];\n let text = \"\";\n let ended = false;\n mask.slots.forEach((slot, index) => {\n offsets.push(text.length);\n const hidden =\n ended ||\n (slot.section !== null && !sections.has(slot.section)) ||\n (!focused && index > last);\n if (hidden) {\n return;\n }\n if (slot.kind === \"literal\") {\n text += slot.character;\n return;\n }\n const cell = cells[index] ?? EMPTY;\n if (cell.kind === \"filled\") {\n text += cell.character;\n } else if (cell.kind === \"empty\") {\n if (prompt === \"\") {\n ended = true;\n } else {\n text += prompt;\n }\n }\n });\n offsets.push(text.length);\n return { text, offsets };\n}\n\n/**\n * Where the caret goes after the slot `slot` (`null` for the start of the\n * text): after what it prints, then past the literals and skipped slots\n * that follow, so typing goes on at the next input slot.\n */\nexport function caretAfter(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n { offsets }: MaskWriting,\n slot: number | null,\n): number {\n let caret = slot === null ? 0 : (offsets[slot + 1] ?? 0);\n for (\n let index = slot === null ? 0 : slot + 1;\n index < mask.slots.length;\n index += 1\n ) {\n const definition = mask.slots[index];\n if (definition?.kind === \"input\" && cells[index]?.kind !== \"skipped\") {\n break;\n }\n caret = offsets[index + 1] ?? caret;\n }\n return caret;\n}\n\n/** The filled characters alone. */\nexport function rawOf(cells: readonly MaskCell[]): string {\n return cells\n .map((cell) => (cell.kind === \"filled\" ? cell.character : \"\"))\n .join(\"\");\n}\n\n/** Every required slot is filled: those outside sections, and those of each section begun. */\nexport function isComplete(\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): boolean {\n const sections = filledSections(mask, cells);\n return mask.slots.every(\n (slot, index) =>\n slot.kind === \"literal\" ||\n slot.optional ||\n (slot.section !== null && !sections.has(slot.section)) ||\n cells[index]?.kind === \"filled\",\n );\n}\n","import { compiledPattern, type CompiledMask, type MaskTokens } from \"./grammar\";\nimport {\n caretAfter,\n fits,\n isComplete,\n itemsOf,\n layOut,\n maskCharacter,\n rawOf,\n readExact,\n writeCells,\n type LayoutMode,\n type MaskCell,\n type MaskItem,\n type MaskLayout,\n type MaskWriting,\n type PlacedItem,\n} from \"./layout\";\n\n/** A pattern, several tried in order as the text grows, or a function choosing one from the raw text. */\nexport type MaskSource = string | readonly string[] | ((raw: string) => string);\n\n/** A mask: its pattern, its own tokens and how it prints. */\nexport interface MaskOptions {\n readonly mask: MaskSource;\n /** One-character names, beside the built-in tokens, which they may replace. */\n readonly tokens?: MaskTokens | undefined;\n /** One character, shown in empty slots while focused; `\"_\"` by default, `\"\"` for none. */\n readonly promptCharacter?: string | undefined;\n /** Whose rules `>` and `<` change case by; the runtime's by default. */\n readonly locale?: Intl.LocalesArgument;\n}\n\n/** Text in a masked control, with the selection. */\nexport interface MaskedText {\n readonly text: string;\n readonly selectionStart: number;\n readonly selectionEnd: number;\n}\n\n/** A browser edit, as `beforeinput` reports it. */\nexport interface MaskEdit {\n readonly inputType: string;\n /** The text inserted; `null` for a deletion. */\n readonly data: string | null;\n}\n\n/** What a mask makes of some text. */\nexport interface MaskDetails {\n /** Only the characters typed into input slots. */\n readonly raw: string;\n /** With literals, without prompt characters, cut after the last character typed. */\n readonly formatted: string;\n /** Every required slot (of the pattern in use, and of each optional section begun) is filled. */\n readonly complete: boolean;\n /** The pattern in use. */\n readonly pattern: string;\n}\n\n/** What an edit leaves. */\nexport interface MaskResult extends MaskDetails {\n /** The text to show, prompt characters included while focused. */\n readonly text: string;\n readonly caret: number;\n /** False when the edit changed nothing the mask accepts (a letter in a digit slot): the input refuses it. */\n readonly accepted: boolean;\n}\n\n/** Whether a mask's value is only the characters typed, or the text with its literals. */\nexport type MaskValueFormat = \"raw\" | \"formatted\";\n\n/** A pattern's text read into cells, and the items an edit works on. */\ninterface TextReading {\n readonly layout: Pick<MaskLayout, \"mask\" | \"cells\">;\n readonly items: readonly PlacedItem[];\n /** Whether characters other than prompt characters had to be dropped to read the text. */\n readonly dropped: boolean;\n}\n\n/**\n * Edits that cannot be refused or come whole from elsewhere: a paste, a\n * drop, autofill or a correction, and the text an input method composed.\n * Their characters that fit nowhere are dropped and the rest go in.\n */\nconst LENIENT_INPUT = new Set([\n \"insertFromPaste\",\n \"insertFromPasteAsQuotation\",\n \"insertFromDrop\",\n \"insertFromYank\",\n \"insertReplacementText\",\n \"insertCompositionText\",\n \"insertFromComposition\",\n]);\n\nfunction promptOf(options: MaskOptions): string {\n return options.promptCharacter ?? \"_\";\n}\n\nfunction compiled(options: MaskOptions, pattern: string): CompiledMask {\n return compiledPattern(pattern, options.tokens);\n}\n\nfunction characterItems(text: string): MaskItem[] {\n return Array.from(text, (character) => ({\n kind: \"character\",\n character: maskCharacter(character),\n }));\n}\n\n/**\n * The patterns `items` may be laid into: the one pattern, every one of\n * several in order, or the one a function picks for the raw text the items\n * make when laid leniently into `current` (the pattern before the edit).\n */\nfunction candidates(\n options: MaskOptions,\n items: readonly MaskItem[],\n current: CompiledMask | null,\n): readonly [CompiledMask, ...CompiledMask[]] {\n const { mask } = options;\n if (typeof mask === \"string\") {\n return [compiled(options, mask)];\n }\n if (typeof mask !== \"function\") {\n const [first, ...rest] = mask;\n if (first === undefined) {\n throw new TypeError(\"A mask needs at least one pattern\");\n }\n return [\n compiled(options, first),\n ...rest.map((pattern) => compiled(options, pattern)),\n ];\n }\n const start = current ?? compiled(options, mask(\"\"));\n const provisional = layOut(start, items, \"lenient\", options.locale);\n return [compiled(options, mask(rawOf(provisional.cells)))];\n}\n\n/** `items` laid into the first pattern that holds every one of them, in order; `null` when none does. */\nfunction fittingLayout(\n options: MaskOptions,\n items: readonly MaskItem[],\n current: CompiledMask | null,\n): MaskLayout | null {\n for (const mask of candidates(options, items, current)) {\n const layout = layOut(mask, items, \"truncate\", options.locale);\n if (fits(layout)) {\n return layout;\n }\n }\n return null;\n}\n\n/** `items` laid into the pattern that keeps most of their characters, the first of equals. */\nfunction bestLayout(\n options: MaskOptions,\n items: readonly MaskItem[],\n mode: LayoutMode,\n current: CompiledMask | null,\n): MaskLayout {\n const [first, ...rest] = candidates(options, items, current);\n let best = layOut(first, items, mode, options.locale);\n for (const mask of rest) {\n const layout = layOut(mask, items, mode, options.locale);\n if (layout.kept > best.kept) {\n best = layout;\n }\n }\n return best;\n}\n\n/** `text` laid in as a paste would be, prompt characters left out. */\nfunction readLeniently(\n options: MaskOptions,\n text: string,\n current: CompiledMask | null,\n): TextReading {\n const prompt = promptOf(options);\n const typed: { readonly character: string; readonly at: number }[] = [];\n let index = 0;\n for (const character of text) {\n if (character !== prompt) {\n typed.push({ character: maskCharacter(character), at: index });\n }\n index += character.length;\n }\n const layout = bestLayout(\n options,\n typed.map(({ character }) => ({ kind: \"character\", character })),\n \"lenient\",\n current,\n );\n const at = layout.mask.slots.map(() => text.length);\n layout.landed.forEach((slot, item) => {\n if (slot !== null) {\n at[slot] = typed[item]?.at ?? text.length;\n }\n });\n return {\n layout,\n items: itemsOf(layout.mask, layout.cells, at),\n dropped: layout.landed.some((slot) => slot === null),\n };\n}\n\nfunction readIn(\n options: MaskOptions,\n mask: CompiledMask,\n text: string,\n): TextReading | null {\n const reading = readExact(mask, text, promptOf(options), options.locale);\n return (\n reading && {\n layout: { mask, cells: reading.cells },\n items: itemsOf(mask, reading.cells, reading.at),\n dropped: false,\n }\n );\n}\n\n/**\n * Reads the text on screen back into the mask: as the first pattern that\n * wrote it, or, for text no pattern wrote (after an undo), laid in as a\n * paste. A function mask is read with the pattern it picks for the text's\n * raw characters.\n */\nfunction readText(options: MaskOptions, text: string): TextReading {\n const { mask } = options;\n if (typeof mask !== \"function\") {\n for (const pattern of typeof mask === \"string\" ? [mask] : mask) {\n const reading = readIn(options, compiled(options, pattern), text);\n if (reading !== null) {\n return reading;\n }\n }\n return readLeniently(options, text, null);\n }\n const start = compiled(options, mask(\"\"));\n const first =\n readIn(options, start, text) ?? readLeniently(options, text, start);\n const picked = compiled(options, mask(rawOf(first.layout.cells)));\n if (picked === start) {\n return first;\n }\n return readIn(options, picked, text) ?? readLeniently(options, text, picked);\n}\n\nfunction resultOf(\n options: MaskOptions,\n { mask, cells }: Pick<MaskLayout, \"mask\" | \"cells\">,\n focused: boolean,\n caretSlot: (writing: MaskWriting) => number,\n accepted: boolean,\n): MaskResult {\n const writing = writeCells(mask, cells, focused, promptOf(options));\n return {\n ...detailsOf(options, mask, cells),\n text: writing.text,\n caret: caretSlot(writing),\n accepted,\n };\n}\n\n/** The slot item `index` landed in, or the last one before it that landed. */\nfunction slotBefore(\n landed: readonly (number | null)[],\n index: number,\n): number | null {\n for (let item = Math.min(index, landed.length) - 1; item >= 0; item -= 1) {\n const slot = landed[item];\n if (slot !== undefined && slot !== null) {\n return slot;\n }\n }\n return null;\n}\n\n/** Whether items `a` and `b` (in that order) are characters next to each other in the text: one group. */\nfunction sameGroup(a: PlacedItem | undefined, b: PlacedItem | undefined) {\n return (\n a !== undefined &&\n b !== undefined &&\n a.item.kind === \"character\" &&\n b.item.kind === \"character\" &&\n b.at - a.at === a.item.character.length\n );\n}\n\n/**\n * The items a deletion with nothing selected removes, as `[from, to)`:\n * the item before the caret (or after it, forward), stepping over\n * literals; a word removes the group of characters around it, between\n * literals; a line, every item on that side. `null` when there is none.\n */\nfunction deletedItems(\n items: readonly PlacedItem[],\n caret: number,\n inputType: string,\n): readonly [from: number, to: number] | null {\n const before = items.filter(({ at }) => at < caret).length;\n const forward = inputType.endsWith(\"Forward\");\n if (forward ? before >= items.length : before === 0) {\n return null;\n }\n if (inputType.includes(\"Line\")) {\n return forward ? [before, items.length] : [0, before];\n }\n let from = forward ? before : before - 1;\n let to = from + 1;\n if (inputType.includes(\"Word\")) {\n while (forward && sameGroup(items[to - 1], items[to])) {\n to += 1;\n }\n while (!forward && sameGroup(items[from - 1], items[from])) {\n from -= 1;\n }\n }\n return [from, to];\n}\n\n/**\n * What `edit` does to `current` under the mask. A selection removes the\n * characters in it; Backspace removes the character before the caret and\n * Delete the one after it, stepping over literals; the characters after\n * move back, and one that no longer fits is dropped with the rest. An\n * insert fills the slots from the caret, each character the next slot that\n * accepts it, and a character equal to the next literal steps past it\n * (skipping optional slots before it). Typing is strict: a character no\n * slot takes, or one that would push another out, refuses the whole edit.\n * A paste, a drop, autofill or composed text is lenient: what fits nowhere\n * is dropped. The pattern is chosen again for what the edit leaves.\n *\n * The caret goes after the last character inserted and past the literals\n * after it; after a deletion, to where the first removed character was.\n * Undo, redo and other edits the mask cannot place leave `accepted` false.\n */\nexport function applyMaskEdit(\n options: MaskOptions,\n current: MaskedText,\n edit: MaskEdit,\n focused: boolean,\n): MaskResult {\n const reading = readText(options, current.text);\n const start = Math.min(current.selectionStart, current.selectionEnd);\n const end = Math.max(current.selectionStart, current.selectionEnd);\n const refused = () =>\n resultOf(\n options,\n reading.layout,\n focused,\n () => Math.min(start, current.text.length),\n false,\n );\n const inserting = edit.inputType.startsWith(\"insert\");\n if (!inserting && !edit.inputType.startsWith(\"delete\")) {\n return refused();\n }\n let items = reading.items;\n if (start < end) {\n items = items.filter(({ at }) => at < start || at >= end);\n } else if (!inserting) {\n const range = deletedItems(items, start, edit.inputType);\n if (range === null) {\n return refused();\n }\n items = [...items.slice(0, range[0]), ...items.slice(range[1])];\n }\n const position = items.filter(({ at }) => at < start).length;\n const inserted = inserting ? characterItems(edit.data ?? \"\") : [];\n const next = [\n ...items.slice(0, position).map(({ item }) => item),\n ...inserted,\n ...items.slice(position).map(({ item }) => item),\n ];\n const shownMask = reading.layout.mask;\n const layout =\n inserting && !LENIENT_INPUT.has(edit.inputType)\n ? fittingLayout(options, next, shownMask)\n : bestLayout(\n options,\n next,\n inserting ? \"lenient\" : \"truncate\",\n shownMask,\n );\n if (layout === null) {\n return refused();\n }\n const insertedLanded = layout.landed.slice(\n position,\n position + inserted.length,\n );\n if (inserted.length > 0 && insertedLanded.every((slot) => slot === null)) {\n return refused();\n }\n const result = resultOf(\n options,\n layout,\n focused,\n (writing) =>\n caretAfter(\n layout.mask,\n layout.cells,\n writing,\n slotBefore(layout.landed, position + inserted.length),\n ),\n true,\n );\n return result.text === current.text ? refused() : result;\n}\n\n/**\n * `raw` laid into the mask, as a value from the app or a commit shows it,\n * with the caret at the first empty slot. Laid in leniently, so a\n * formatted value (with its literals) reads too.\n */\nexport function formatMasked(\n options: MaskOptions,\n raw: string,\n focused: boolean,\n): MaskResult {\n const items = characterItems(raw);\n const layout = bestLayout(options, items, \"lenient\", null);\n return resultOf(\n options,\n layout,\n focused,\n (writing) =>\n caretAfter(\n layout.mask,\n layout.cells,\n writing,\n slotBefore(layout.landed, items.length),\n ),\n true,\n );\n}\n\n/** Whether `raw` can still become complete by typing more: some pattern takes every character of it, in order. */\nexport function isValidMaskStart(options: MaskOptions, raw: string): boolean {\n return fittingLayout(options, characterItems(raw), null) !== null;\n}\n\n/** What the mask makes of `text`, focused or display text alike. */\nexport function maskDetails(options: MaskOptions, text: string): MaskDetails {\n const { layout } = readText(options, text);\n return detailsOf(options, layout.mask, layout.cells);\n}\n\nfunction detailsOf(\n options: MaskOptions,\n mask: CompiledMask,\n cells: readonly MaskCell[],\n): MaskDetails {\n return {\n raw: rawOf(cells),\n formatted: writeCells(mask, cells, false, promptOf(options)).text,\n complete: isComplete(mask, cells),\n pattern: mask.pattern,\n };\n}\n\n/** `text` read by the mask, and whether reading it had to drop characters. */\nexport function readMasked(\n options: MaskOptions,\n text: string,\n): MaskDetails & { readonly dropped: boolean } {\n const { layout, dropped } = readText(options, text);\n return { ...detailsOf(options, layout.mask, layout.cells), dropped };\n}\n","import type { InputFilterDecision, TextEdit } from \"../field/plan\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n applyMaskEdit,\n formatMasked,\n readMasked,\n type MaskOptions,\n type MaskValueFormat,\n} from \"./applyMask\";\nimport { compiledPattern } from \"./grammar\";\n\n/** The options with the field's locale, unless they name one. */\nfunction inLocale(\n options: MaskOptions,\n locale: Intl.LocalesArgument,\n): MaskOptions {\n return options.locale === undefined ? { ...options, locale } : options;\n}\n\n/**\n * A masked field's own reading: no character typed is `null`; complete\n * text is its raw characters, or with `valueFormat: \"formatted\"` its\n * formatted text; incomplete text is unreadable with\n * `messages.maskIncomplete`, so the value stays the last complete one.\n * Text with characters no slot takes (after an undo) is unreadable with\n * `messages.patternMismatch`.\n */\nexport function maskParser(\n options: MaskOptions,\n valueFormat: MaskValueFormat = \"raw\",\n): (text: string, context: ParseContext<string>) => ParseResult<string> {\n return (text, { locale, messages }) => {\n const read = readMasked(inLocale(options, locale), text);\n if (read.dropped) {\n return unreadable(messages.patternMismatch);\n }\n if (read.raw === \"\") {\n return parsed(null);\n }\n if (!read.complete) {\n return unreadable(messages.maskIncomplete);\n }\n return parsed(valueFormat === \"raw\" ? read.raw : read.formatted);\n };\n}\n\n/**\n * A masked field's own writing: the value laid into the mask, with the\n * prompt in empty slots while the field has focus (`purpose: \"edit\"`, so\n * an empty field shows the template), and the formatted text otherwise.\n */\nexport function maskFormatter(\n options: MaskOptions,\n): (value: string | null, context: FormatContext<string>) => string {\n return (value, { locale, purpose }) =>\n formatMasked(inLocale(options, locale), value ?? \"\", purpose === \"edit\")\n .text;\n}\n\n/**\n * A masked field's judgement of an edit, its `filterInput`: the edit\n * worked out by `applyMaskEdit` on the text before it and the selection,\n * replacing the whole text and placing the caret, or refused. An edit with\n * no browser report (an app's change) and undo or redo stand as they are.\n * `options` hold the field's locale.\n */\nexport function filterMaskEdit<N>(\n edit: TextEdit<N>,\n before: string,\n options: MaskOptions,\n): InputFilterDecision {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (input === null || inputType === null || inputType.startsWith(\"history\")) {\n return { kind: \"allow\" };\n }\n const start = Math.min(input.selectionStart ?? before.length, before.length);\n const end = Math.min(input.selectionEnd ?? start, before.length);\n const result = applyMaskEdit(\n options,\n { text: before, selectionStart: start, selectionEnd: end },\n { inputType, data: input.data },\n true,\n );\n return result.accepted\n ? { kind: \"replace\", text: result.text, caret: result.caret }\n : { kind: \"prevent\" };\n}\n\n/** What a masked input tells the browser's keyboard. */\nexport interface MaskInputHints {\n /** `\"numeric\"` when every slot of every pattern is a built-in digit slot (`0`, `9`); a function mask is `\"text\"`. */\n readonly inputMode: \"numeric\" | \"text\";\n /** Whether a pattern upper-cases letters, for `autocapitalize=\"characters\"`. A function mask is judged by its first pattern. */\n readonly upperCase: boolean;\n}\n\n/** The keyboard a mask wants. Throws on a malformed pattern, as the engine does. */\nexport function maskInputHints(options: MaskOptions): MaskInputHints {\n const { mask, tokens } = options;\n const patterns =\n typeof mask === \"function\"\n ? [mask(\"\")]\n : typeof mask === \"string\"\n ? [mask]\n : mask;\n const slots = patterns.flatMap(\n (pattern) => compiledPattern(pattern, tokens).slots,\n );\n const inputs = slots.filter((slot) => slot.kind === \"input\");\n const digitsOnly = inputs.every(\n (slot) =>\n (slot.token === \"0\" || slot.token === \"9\") &&\n tokens?.[slot.token] === undefined,\n );\n return {\n inputMode: typeof mask !== \"function\" && digitsOnly ? \"numeric\" : \"text\",\n upperCase: inputs.some((slot) => slot.letterCase === \"upper\"),\n };\n}\n","import type { Validator } from \"../validation/validators\";\n\n/** IBAN lengths by country code, from the SWIFT IBAN registry. */\nexport const IBAN_LENGTHS: Readonly<Record<string, number>> = {\n AD: 24,\n AE: 23,\n AL: 28,\n AT: 20,\n AZ: 28,\n BA: 20,\n BE: 16,\n BG: 22,\n BH: 22,\n BI: 27,\n BR: 29,\n BY: 28,\n CH: 21,\n CR: 22,\n CY: 28,\n CZ: 24,\n DE: 22,\n DJ: 27,\n DK: 18,\n DO: 28,\n EE: 20,\n EG: 29,\n ES: 24,\n FI: 18,\n FK: 18,\n FO: 18,\n FR: 27,\n GB: 22,\n GE: 22,\n GI: 23,\n GL: 18,\n GR: 27,\n GT: 28,\n HN: 28,\n HR: 21,\n HU: 28,\n IE: 22,\n IL: 23,\n IQ: 23,\n IS: 26,\n IT: 27,\n JO: 30,\n KW: 30,\n KZ: 20,\n LB: 28,\n LC: 32,\n LI: 21,\n LT: 20,\n LU: 20,\n LV: 21,\n LY: 25,\n MC: 27,\n MD: 24,\n ME: 22,\n MK: 19,\n MN: 20,\n MR: 27,\n MT: 31,\n MU: 30,\n NI: 28,\n NL: 18,\n NO: 15,\n OM: 23,\n PK: 24,\n PL: 28,\n PS: 29,\n PT: 25,\n QA: 29,\n RO: 24,\n RS: 22,\n RU: 33,\n SA: 24,\n SC: 31,\n SD: 18,\n SE: 24,\n SI: 19,\n SK: 24,\n SM: 27,\n SO: 23,\n ST: 25,\n SV: 28,\n TL: 23,\n TN: 24,\n TR: 26,\n UA: 29,\n VA: 22,\n VG: 24,\n XK: 20,\n YE: 30,\n};\n\n/** Whether `value` is an IBAN of its country's length whose check digits hold (mod 97 is 1). */\nfunction isIban(value: string): boolean {\n const iban = value.replace(/\\s/g, \"\").toUpperCase();\n if (\n !/^[A-Z]{2}[0-9]{2}[A-Z0-9]+$/.test(iban) ||\n IBAN_LENGTHS[iban.slice(0, 2)] !== iban.length\n ) {\n return false;\n }\n let remainder = 0;\n for (const character of iban.slice(4) + iban.slice(0, 4)) {\n // Letters count as two digits, A = 10 to Z = 35.\n const digits = Number.parseInt(character, 36);\n remainder = (remainder * (digits < 10 ? 10 : 100) + digits) % 97;\n }\n return remainder === 1;\n}\n\n/** Whether the digits of `value` pass the Luhn check. */\nfunction passesLuhn(value: string): boolean {\n const digits = value.replace(/\\s/g, \"\");\n if (!/^[0-9]{2,}$/.test(digits)) {\n return false;\n }\n let sum = 0;\n Array.from(digits)\n .reverse()\n .forEach((character, index) => {\n const digit = Number(character);\n const doubled = index % 2 === 1 ? digit * 2 : digit;\n sum += doubled > 9 ? doubled - 9 : doubled;\n });\n return sum % 10 === 0;\n}\n\nconst IPV4_PART = /^(?:0|[1-9][0-9]{0,2})$/;\n\n/** Whether `value` is four dotted parts from 0 to 255, none with a leading zero. */\nfunction isIpv4(value: string): boolean {\n const parts = value.split(\".\");\n return (\n parts.length === 4 &&\n parts.every((part) => IPV4_PART.test(part) && Number(part) <= 255)\n );\n}\n\n/**\n * An IBAN with the wrong length for its country, or whose check digits\n * fail, is `messages.ibanInvalid`. Spaces are ignored. `null` passes.\n */\nexport function ibanRule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !isIban(value)\n ? { text: messages.ibanInvalid, code: \"iban\" }\n : null;\n}\n\n/** A card number whose check digit fails (Luhn) is `messages.cardNumberInvalid`. Spaces are ignored. `null` passes. */\nexport function luhnRule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !passesLuhn(value)\n ? { text: messages.cardNumberInvalid, code: \"cardNumber\" }\n : null;\n}\n\n/** An IPv4 address with a part above 255 or a leading zero is `messages.ipv4Invalid`. `null` passes. */\nexport function ipv4Rule(): Validator<string> {\n return (value, { messages }) =>\n value !== null && !isIpv4(value)\n ? { text: messages.ipv4Invalid, code: \"ipv4\" }\n : null;\n}\n","import type { Validator } from \"../validation/validators\";\nimport type { MaskOptions, MaskValueFormat } from \"./applyMask\";\nimport type { MaskTokens } from \"./grammar\";\nimport { IBAN_LENGTHS, ibanRule, ipv4Rule, luhnRule } from \"./rules\";\n\n/** A ready-made mask: its options, its check, the keyboard it wants and the value it keeps. */\nexport interface MaskPreset {\n readonly options: MaskOptions;\n /** Checks a complete value further: a checksum, a range. */\n readonly validate?: Validator<string> | undefined;\n readonly inputMode: \"numeric\" | \"decimal\" | \"text\";\n readonly autoComplete?: string | undefined;\n readonly valueFormat: MaskValueFormat;\n}\n\n/** Codes are ASCII: these tokens keep out the letters and digits of other scripts that the built-in ones accept. */\nconst ASCII_TOKENS: MaskTokens = {\n L: /[A-Za-z]/,\n A: /[A-Za-z0-9]/,\n a: { accept: /[A-Za-z0-9]/, optional: true },\n};\n\n/** Upper-casing codes the same in every locale (\"i\" is \"I\", not the Turkish \"İ\"). */\nconst CODE_LOCALE = \"en\";\n\n/** The longest IBAN, and the shortest, which an unknown country's pattern spans. */\nconst IBAN_MAX = 34;\nconst IBAN_MIN = 15;\n\n/**\n * An IBAN's pattern for the raw text typed: two letters, two check digits\n * and the rest, sized by the country the letters name and grouped in\n * fours; up to 34 characters (15 required) for a country it does not know.\n */\nfunction ibanPattern(raw: string): string {\n const length = IBAN_LENGTHS[raw.slice(0, 2).toUpperCase()];\n const tokens = Array.from({ length: length ?? IBAN_MAX }, (_, index) => {\n if (index < 2) {\n return \"L\";\n }\n if (index < 4) {\n return \"0\";\n }\n return length === undefined && index >= IBAN_MIN ? \"a\" : \"A\";\n });\n const groups: string[] = [];\n for (let start = 0; start < tokens.length; start += 4) {\n groups.push(tokens.slice(start, start + 4).join(\"\"));\n }\n return `>${groups.join(\" \")}`;\n}\n\n/** A card number's pattern: American Express (34, 37) groups 4-6-5; the rest 4-4-4-4, with up to three more digits. */\nfunction cardNumberPattern(raw: string): string {\n return /^3[47]/.test(raw) ? \"0000 000000 00000\" : \"0000 0000 0000 0000[ 000]\";\n}\n\nfunction postalCode(\n mask: MaskOptions[\"mask\"],\n inputMode: \"numeric\" | \"text\",\n): MaskPreset {\n return {\n options:\n inputMode === \"text\"\n ? { mask, tokens: ASCII_TOKENS, locale: CODE_LOCALE }\n : { mask },\n inputMode,\n autoComplete: \"postal-code\",\n valueFormat: \"formatted\",\n };\n}\n\n/** The presets `MaskedInput` takes by name. */\nexport interface MaskPresets {\n /** An IBAN, grouped in fours, sized by its country; raw value, checked by `ibanRule`. */\n readonly iban: MaskPreset;\n /** A card number, grouped by its length; raw digits, checked by `luhnRule`. */\n readonly cardNumber: MaskPreset;\n /** An IPv4 address, `.` moving to the next part; formatted value, checked by `ipv4Rule`. */\n readonly ipv4: MaskPreset;\n /** `12345` or `12345-6789`. */\n readonly postalCodeUS: MaskPreset;\n /** `K1A 0B1`. */\n readonly postalCodeCA: MaskPreset;\n /** `SW1A 1AA`, `M1 1AA` and the other UK shapes. */\n readonly postalCodeGB: MaskPreset;\n /** `10115`. */\n readonly postalCodeDE: MaskPreset;\n /** `1012 AB`. */\n readonly postalCodeNL: MaskPreset;\n /** `01310-100`. */\n readonly postalCodeBR: MaskPreset;\n /** `100-0001`. */\n readonly postalCodeJP: MaskPreset;\n}\n\n/**\n * Ready-made masks. Postal codes keep their separators, as addresses print\n * them; an IPv4 address keeps its dots, which its raw digits would lose.\n */\nexport const maskPresets: MaskPresets = {\n iban: {\n options: { mask: ibanPattern, tokens: ASCII_TOKENS, locale: CODE_LOCALE },\n validate: ibanRule(),\n inputMode: \"text\",\n valueFormat: \"raw\",\n },\n cardNumber: {\n options: { mask: cardNumberPattern },\n validate: luhnRule(),\n inputMode: \"numeric\",\n autoComplete: \"cc-number\",\n valueFormat: \"raw\",\n },\n ipv4: {\n options: { mask: \"099.099.099.099\" },\n validate: ipv4Rule(),\n // The decimal keypad has the dot.\n inputMode: \"decimal\",\n valueFormat: \"formatted\",\n },\n postalCodeUS: postalCode(\"00000[-0000]\", \"numeric\"),\n postalCodeCA: postalCode(\">L0L 0L0\", \"text\"),\n postalCodeGB: postalCode(\n [\">L0 0LL\", \">L00 0LL\", \">LL0 0LL\", \">LL00 0LL\", \">L0L 0LL\", \">LL0L 0LL\"],\n \"text\",\n ),\n postalCodeDE: postalCode(\"00000\", \"numeric\"),\n postalCodeNL: postalCode(\"0000 >LL\", \"text\"),\n postalCodeBR: postalCode(\"00000-000\", \"numeric\"),\n postalCodeJP: postalCode(\"000-0000\", \"numeric\"),\n};\n","import type { SegmentType } from \"../date/layout\";\nimport type { RelativeDateRule } from \"../date/relative\";\nimport { localeKey } from \"../localeKey\";\nimport type { Severity } from \"./severity\";\n\n/**\n * Every string the forms show or announce of their own: validation\n * messages, button names, counters, display-mode text and the message\n * summary, so the forms can speak a language other than English. A message\n * that names something takes a function, so a translation can put it where\n * its own grammar wants it. Counts print in the locale's digits: \"1,000\"\n * under `\"en\"`, \"1.000\" under `\"de-DE\"`.\n *\n * A minor release may add keys. `resolveFormsMessages` lays a partial set\n * over the defaults, so a translation without a new key shows its English\n * default until it gains one.\n */\nexport interface FormsMessages {\n /** A required field is empty. */\n required: string;\n /** A required checkbox is not checked. */\n requiredChecked: string;\n /** A required switch is off. */\n requiredOn: string;\n /** A required choice list has nothing chosen. */\n requiredChoice: string;\n /** The text is shorter than `minLength`. */\n tooShort: (min: number) => string;\n /** The text is longer than `maxLength`. */\n tooLong: (max: number) => string;\n /** The text does not match `pattern`. */\n patternMismatch: string;\n /** A custom parser's fallback when the text cannot be read. */\n unreadable: string;\n /** A number field's text is not a number. */\n notANumber: string;\n /** A number field's text groups digits where the field does not; names its separators. */\n numberGrouping: (decimal: string, group: string) => string;\n /** A number field holding JS numbers was given more digits than one keeps exactly. */\n numberTooPrecise: string;\n /** A number is below `min`, written as the field writes numbers. */\n rangeUnderflow: (min: string) => string;\n /** A number is above `max`, written as the field writes numbers. */\n rangeOverflow: (max: string) => string;\n /** A number is off its step, written as the field writes numbers. */\n stepMismatch: (step: string) => string;\n /** A date or time is before `min`, written as display mode writes it. */\n tooEarly: (limit: string) => string;\n /** A date or time is after `max`, written as display mode writes it. */\n tooLate: (limit: string) => string;\n /** A day `isDateDisabled` marks unavailable. */\n dateUnavailable: string;\n /** A date's segments are partly filled. */\n dateIncomplete: string;\n /** A time's segments are partly filled, or a 12-hour time has no AM or PM. */\n timeIncomplete: string;\n /** A date's month has no such day: 31 February. */\n dateNonexistent: string;\n /** Text that is not a date; `example` is today as the field writes it. */\n dateUnreadable: (example: string) => string;\n /** Text that is not a time; `example` is a time as the field writes it. */\n timeUnreadable: (example: string) => string;\n /** A year typed with three digits. */\n dateYearDigits: string;\n /** A wall clock in an hour the clocks skipped, read as the hour after: `typed` and `read` as the field writes times. */\n timeSkipped: (typed: string, read: string) => string;\n /** A wall clock in an hour that happens twice, read with `offset` (\"GMT+02:00\"). */\n timeRepeated: (time: string, offset: string) => string;\n /** A wall clock in an hour the clocks skipped, refused. */\n timeNonexistent: (typed: string) => string;\n /** A wall clock in an hour that happens twice, refused. */\n timeAmbiguous: (typed: string) => string;\n /** A segment's name, read with the field's label: \"month\". */\n dateSegmentName: (type: SegmentType) => string;\n /** What an empty segment shows: \"mm\". */\n dateSegmentPlaceholder: (type: SegmentType) => string;\n /** An empty segment's value, as a screen reader reads it. */\n segmentEmpty: string;\n /** The button that opens a date input's calendar, and the calendar popup itself. */\n chooseDate: string;\n /** The button that opens a time input's time columns, and their popup. */\n chooseTime: string;\n /** The button that opens a date-time input's calendar and time columns, and their popup. */\n chooseDateTime: string;\n /** A time picker's button that chooses the time it is now. */\n pickerNow: string;\n /** A date-time picker's button that closes it. */\n pickerDone: string;\n /** The button that opens a period input's picker, and the picker popup itself. */\n choosePeriod: string;\n /** A period picker's button to the year before. */\n previousYear: string;\n /** A period picker's button to the year after. */\n nextYear: string;\n /** A year picker's button to the twelve years before. */\n previousYears: string;\n /** A year picker's button to the twelve years after. */\n nextYears: string;\n /** A calendar's button to the month before. */\n previousMonth: string;\n /** A calendar's button to the month after. */\n nextMonth: string;\n /** A calendar's view of months and years, which its title opens. */\n chooseMonthYear: string;\n /** The list of years in a calendar's month and year view. */\n calendarYears: string;\n /** The heading of a calendar's column of week numbers, as a screen reader reads it. */\n weekColumn: string;\n /** A week number in a calendar, as a screen reader reads it. */\n weekLabel: (week: number) => string;\n /** Read after the first day of a range in a calendar. */\n calendarRangeStart: string;\n /** Read after the last day of a range in a calendar. */\n calendarRangeEnd: string;\n /** A relative rule's name, for a preset or a rule held as the value: \"Last 7 days\", \"This month\". */\n relativeRangeLabel: (rule: RelativeDateRule) => string;\n /** Written after a time range's end on the day after its start: \"22:00 – 06:00 +1\". */\n rangeNextDay: string;\n /** Written before a quarter: \"Q3 2026\". */\n periodQuarterPrefix: string;\n /** Written before a fiscal year: \"FY2026\". */\n fiscalYearPrefix: string;\n /** Written before a fiscal period: \"FY2026 P04\". */\n fiscalPeriodPrefix: string;\n /** Text that is not a period; `example` is the current period as the field writes it. */\n periodUnreadable: (example: string) => string;\n /** Text that is not a duration; `example` is 90 minutes as the field writes them. */\n durationUnreadable: (example: string) => string;\n /** A negative duration where the field takes none. */\n durationNegative: string;\n /** A commit refused without a message, or a check that failed. */\n checkFailed: string;\n /** The clear button's accessible name. */\n clear: string;\n /** The password reveal button's accessible name. */\n showPassword: string;\n /** A number input's stepper button that steps up. */\n increase: string;\n /** A number input's stepper button that steps down. */\n decrease: string;\n /** A range input's first end, read with the field's label. */\n rangeStart: string;\n /** A range input's second end, read with the field's label. */\n rangeEnd: string;\n /** Drawn between a range input's two ends. */\n rangeSeparator: string;\n /** A range with only a start, in display mode; `start` as the input writes it. */\n rangeFrom: (start: string) => string;\n /** A range with only an end, in display mode; `end` as the input writes it. */\n rangeUpTo: (end: string) => string;\n /** A range's end comes before its start, and the input does not swap them. */\n rangeReversed: string;\n /** A half-open range's start is its end, so it holds nothing. */\n rangeEmpty: string;\n /** A range spans less than its minimum, written as the input writes spans. */\n rangeTooShort: (span: string) => string;\n /** A range spans more than its maximum, written as the input writes spans. */\n rangeTooLong: (span: string) => string;\n /** A range input's span, shown after its end. */\n rangeSpanLabel: (span: string) => string;\n /** A masked field's text leaves required slots empty. */\n maskIncomplete: string;\n /** An IBAN has the wrong length for its country, or fails its check digits. */\n ibanInvalid: string;\n /** A card number fails its check digit. */\n cardNumberInvalid: string;\n /** An IPv4 address has a part above 255, or one with a leading zero. */\n ipv4Invalid: string;\n /** The visible character counter. */\n counter: (count: number, max: number) => string;\n /** The counter's description, read with the control. */\n counterLabel: (max: number) => string;\n /** Announced as typing pauses near the limit. */\n charactersLeft: (left: number) => string;\n /** Announced as typing pauses over the limit. */\n charactersOver: (over: number) => string;\n /** Announced while an input loads. */\n loading: string;\n /** Read beside the dash an empty field shows in display mode. */\n emptyValue: string;\n /** A checked checkbox in display mode, and its event text. */\n displayChecked: string;\n /** An unchecked checkbox in display mode, and its event text. */\n displayUnchecked: string;\n /** A switch that is on, in display mode. */\n displayOn: string;\n /** A switch that is off, in display mode. */\n displayOff: string;\n /** The marker on an optional field's label. */\n optional: string;\n /** The help button's accessible name. */\n fieldHelp: string;\n /** A search input's placeholder. */\n searchPlaceholder: string;\n /** The button beside a choice list's search box that opens its options. */\n showOptions: string;\n /** Shown in a choice list that has no options at all. */\n noOptions: string;\n /** Announced once a choice list's search has settled on its options. */\n resultCount: (count: number) => string;\n /** Announced once a choice list's search has settled on none; `query` as typed. */\n noMatches: (query: string) => string;\n /** Announced as an option is ticked or unticked in a list taking several values. */\n selectedCount: (count: number) => string;\n /** Shown in a choice list whose source searches only from `min` characters. */\n typeMore: (min: number) => string;\n /** Shown and announced when a choice list's options failed to load. */\n optionsFailed: string;\n /** The row that asks a failed choice list's source again. */\n retry: string;\n /** The count of chosen options a collapsed field does not show: \"+3\". */\n moreChosen: (count: number) => string;\n /** The same count read by a screen reader: \"and 3 more\". */\n moreChosenLabel: (count: number) => string;\n /** The name of the list of chosen options' chips. */\n chosenList: string;\n /** A chip's remove button. */\n removeChoice: (label: string) => string;\n /** Announced as a chip is removed. */\n choiceRemoved: (label: string) => string;\n /** The row that chooses every option shown. */\n selectAll: string;\n /** The same row when the list holds only the options loaded so far. */\n selectAllLoaded: (count: number) => string;\n /** The row that creates an option from the search text. */\n createOption: (text: string) => string;\n /** Shown when the app could not create an option from `text`. */\n createFailed: (text: string) => string;\n /** A chosen key whose option no longer exists; `label` is the key as text. */\n optionMissing: (label: string) => string;\n /** More options chosen than `maxCount` allows. */\n tooManyChoices: (max: number) => string;\n /** Fewer options chosen than `minCount` asks for. */\n tooFewChoices: (min: number) => string;\n /** Shown and announced once `maxCount` options are chosen. */\n maxChoicesReached: (max: number) => string;\n /** Read before a message, naming its severity. */\n severityLabel: (severity: Severity) => string;\n /** How many messages of one severity a summary holds. */\n severityCount: (severity: Severity, count: number) => string;\n /** The message summary's title. */\n messageSummaryTitle: (count: number) => string;\n}\n\ntype CountFormat = (count: number) => string;\n\n/**\n * Count formats already built, one per locale: building an\n * `Intl.NumberFormat` costs far more than using one.\n */\nconst countFormats = new Map<string, CountFormat>();\n\n/** A count in `locale`'s digits and separators, whole. */\nfunction countFormat(locale: Intl.LocalesArgument): CountFormat {\n const key = localeKey(locale);\n let format = countFormats.get(key);\n if (format === undefined) {\n const numberFormat = new Intl.NumberFormat(locale, {\n maximumFractionDigits: 0,\n });\n format = (count) => numberFormat.format(count);\n countFormats.set(key, format);\n }\n return format;\n}\n\nconst SEVERITY_LABELS: Readonly<Record<Severity, string>> = {\n error: \"Error\",\n warning: \"Warning\",\n info: \"Information\",\n success: \"Success\",\n};\n\nconst SEGMENT_NAMES: Readonly<Record<SegmentType, string>> = {\n year: \"year\",\n month: \"month\",\n day: \"day\",\n hour: \"hour\",\n minute: \"minute\",\n second: \"second\",\n dayPeriod: \"AM/PM\",\n quarter: \"quarter\",\n period: \"period\",\n};\n\nconst SEGMENT_PLACEHOLDERS: Readonly<Record<SegmentType, string>> = {\n year: \"yyyy\",\n month: \"mm\",\n day: \"dd\",\n hour: \"--\",\n minute: \"--\",\n second: \"--\",\n dayPeriod: \"--\",\n quarter: \"-\",\n period: \"--\",\n};\n\n/** \"day\", \"fiscal quarter\": a rule's unit as words. */\nfunction unitWords(unit: string, fiscal: boolean | undefined): string {\n return fiscal === true && (unit === \"quarter\" || unit === \"year\")\n ? `fiscal ${unit}`\n : unit;\n}\n\n/** A rule's English name: \"Today\", \"Last month\", \"Last 7 days\", \"Year to date\". */\nfunction relativeLabel(rule: RelativeDateRule, n: CountFormat): string {\n switch (rule.kind) {\n case \"period\": {\n const { offset } = rule;\n const unit = unitWords(rule.unit, rule.fiscal);\n const units = counted(n, Math.abs(offset), [unit, `${unit}s`]);\n const days = rule.unit === \"day\";\n if (offset === 0) {\n return days ? \"Today\" : `This ${unit}`;\n }\n if (offset === -1) {\n return days ? \"Yesterday\" : `Last ${unit}`;\n }\n if (offset === 1) {\n return days ? \"Tomorrow\" : `Next ${unit}`;\n }\n return offset < 0 ? `${units} ago` : `In ${units}`;\n }\n case \"last\":\n case \"next\": {\n const units = counted(n, rule.count, [rule.unit, `${rule.unit}s`]);\n if (rule.kind === \"last\") {\n return rule.includeToday\n ? `Last ${units}`\n : `Last ${units} before today`;\n }\n return rule.includeToday ? `Next ${units} from today` : `Next ${units}`;\n }\n case \"toDate\": {\n const unit = unitWords(rule.unit, rule.fiscal);\n return `${unit.charAt(0).toUpperCase()}${unit.slice(1)} to date`;\n }\n }\n}\n\n/** The singular and plural noun a count of each severity takes. */\nconst SEVERITY_NOUNS: Readonly<Record<Severity, readonly [string, string]>> = {\n error: [\"error\", \"errors\"],\n warning: [\"warning\", \"warnings\"],\n info: [\"note\", \"notes\"],\n success: [\"confirmation\", \"confirmations\"],\n};\n\n/** \"1 character\", \"3 characters\": `count` with the noun in its number. */\nfunction counted(\n n: CountFormat,\n count: number,\n [one, many]: readonly [string, string],\n): string {\n return count === 1 ? `1 ${one}` : `${n(count)} ${many}`;\n}\n\n/**\n * The forms' own English, counts printed in `locale`'s digits. Without a\n * locale, the runtime's own; that one is `defaultFormsMessages`.\n */\nexport function createDefaultFormsMessages(\n locale?: Intl.LocalesArgument,\n): FormsMessages {\n const n = countFormat(locale);\n const characters = [\"character\", \"characters\"] as const;\n return {\n required: \"Enter a value\",\n requiredChecked: \"Check this box to continue\",\n requiredOn: \"Turn this on to continue\",\n requiredChoice: \"Choose an option\",\n tooShort: (min) => `Enter at least ${counted(n, min, characters)}`,\n tooLong: (max) => `Enter no more than ${counted(n, max, characters)}`,\n patternMismatch: \"Enter a value in the expected format\",\n unreadable: \"This value can't be read\",\n notANumber: \"Enter a number\",\n numberGrouping: (decimal, group) =>\n `Use “${decimal}” for decimals and “${group}” between thousands`,\n numberTooPrecise: \"This number has more digits than can be kept exactly\",\n rangeUnderflow: (min) => `Enter ${min} or more`,\n rangeOverflow: (max) => `Enter ${max} or less`,\n stepMismatch: (step) => `Enter a multiple of ${step}`,\n tooEarly: (limit) => `Enter ${limit} or later`,\n tooLate: (limit) => `Enter ${limit} or earlier`,\n dateUnavailable: \"This date isn't available\",\n dateIncomplete: \"Complete the date\",\n timeIncomplete: \"Complete the time\",\n dateNonexistent: \"This date doesn't exist\",\n dateUnreadable: (example) => `Enter a date such as ${example}`,\n timeUnreadable: (example) => `Enter a time such as ${example}`,\n dateYearDigits: \"Enter the year with 2 or 4 digits\",\n timeSkipped: (typed, read) =>\n `Clocks go forward here: ${typed} is read as ${read}`,\n timeRepeated: (time, offset) => `${time} happens twice; read as ${offset}`,\n timeNonexistent: (typed) =>\n `${typed} doesn't exist here: clocks go forward`,\n timeAmbiguous: (typed) => `${typed} happens twice here: clocks go back`,\n dateSegmentName: (type) => SEGMENT_NAMES[type],\n dateSegmentPlaceholder: (type) => SEGMENT_PLACEHOLDERS[type],\n segmentEmpty: \"Empty\",\n chooseDate: \"Choose date\",\n chooseTime: \"Choose time\",\n chooseDateTime: \"Choose date and time\",\n pickerNow: \"Now\",\n pickerDone: \"Done\",\n choosePeriod: \"Choose period\",\n previousYear: \"Previous year\",\n nextYear: \"Next year\",\n previousYears: \"Previous years\",\n nextYears: \"Next years\",\n previousMonth: \"Previous month\",\n nextMonth: \"Next month\",\n chooseMonthYear: \"Choose month and year\",\n calendarYears: \"Years\",\n weekColumn: \"Week\",\n weekLabel: (week) => `Week ${n(week)}`,\n calendarRangeStart: \"start of range\",\n calendarRangeEnd: \"end of range\",\n relativeRangeLabel: (rule) => relativeLabel(rule, n),\n rangeNextDay: \"+1\",\n periodQuarterPrefix: \"Q\",\n fiscalYearPrefix: \"FY\",\n fiscalPeriodPrefix: \"P\",\n periodUnreadable: (example) => `Enter a period such as ${example}`,\n durationUnreadable: (example) => `Enter a duration such as ${example}`,\n durationNegative: \"Enter a duration of zero or more\",\n checkFailed: \"This value could not be checked\",\n clear: \"Clear\",\n showPassword: \"Show password\",\n increase: \"Increase\",\n decrease: \"Decrease\",\n rangeStart: \"From\",\n rangeEnd: \"To\",\n rangeSeparator: \"–\",\n rangeFrom: (start) => `from ${start}`,\n rangeUpTo: (end) => `up to ${end}`,\n rangeReversed: \"The end comes before the start\",\n rangeEmpty: \"The range is empty\",\n rangeTooShort: (span) => `The range must span at least ${span}`,\n rangeTooLong: (span) => `The range must span no more than ${span}`,\n rangeSpanLabel: (span) => `Span: ${span}`,\n maskIncomplete: \"Complete this field\",\n ibanInvalid: \"Enter a valid IBAN\",\n cardNumberInvalid: \"Enter a valid card number\",\n ipv4Invalid: \"Enter a valid IPv4 address\",\n counter: (count, max) => `${n(count)}/${n(max)}`,\n counterLabel: (max) => `Up to ${counted(n, max, characters)}`,\n charactersLeft: (left) => `${counted(n, left, characters)} left`,\n charactersOver: (over) => `${counted(n, over, characters)} too many`,\n loading: \"Loading\",\n emptyValue: \"No value\",\n displayChecked: \"Yes\",\n displayUnchecked: \"No\",\n displayOn: \"On\",\n displayOff: \"Off\",\n optional: \"optional\",\n fieldHelp: \"More information\",\n searchPlaceholder: \"Search\",\n showOptions: \"Show options\",\n noOptions: \"No options\",\n resultCount: (count) => counted(n, count, [\"result\", \"results\"]),\n noMatches: (query) => `No matches for “${query}”`,\n selectedCount: (count) => `${n(count)} selected`,\n typeMore: (min) => `Type at least ${counted(n, min, characters)}`,\n optionsFailed: \"Couldn't load the options.\",\n retry: \"Try again\",\n moreChosen: (count) => `+${n(count)}`,\n moreChosenLabel: (count) => `and ${n(count)} more`,\n chosenList: \"Chosen\",\n removeChoice: (label) => `Remove ${label}`,\n choiceRemoved: (label) => `${label} removed`,\n selectAll: \"Select all\",\n selectAllLoaded: (count) => `Select all ${n(count)} loaded`,\n createOption: (text) => `Create “${text}”`,\n createFailed: (text) => `Couldn't create “${text}”`,\n optionMissing: (label) => `“${label}” is no longer available`,\n tooManyChoices: (max) => `Choose no more than ${n(max)}`,\n tooFewChoices: (min) => `Choose at least ${n(min)}`,\n maxChoicesReached: (max) =>\n max === 1 ? \"Up to 1 choice\" : `Up to ${n(max)} choices`,\n severityLabel: (severity) => SEVERITY_LABELS[severity],\n severityCount: (severity, count) =>\n counted(n, count, SEVERITY_NOUNS[severity]),\n messageSummaryTitle: (count) =>\n count === 1\n ? \"There is 1 problem with this form\"\n : `There are ${n(count)} problems with this form`,\n };\n}\n\n/** The forms' own English, which an app's messages replace key by key. */\nexport const defaultFormsMessages: FormsMessages = createDefaultFormsMessages();\n\n/** The defaults made for each locale so far, one object per locale. */\nconst localeDefaults = new Map<string, FormsMessages>();\n\nfunction defaultsFor(locale: Intl.LocalesArgument): FormsMessages {\n if (locale === undefined) {\n return defaultFormsMessages;\n }\n const key = localeKey(locale);\n let defaults = localeDefaults.get(key);\n if (defaults === undefined) {\n defaults = createDefaultFormsMessages(locale);\n localeDefaults.set(key, defaults);\n }\n return defaults;\n}\n\n/**\n * `messages` over the defaults for `locale`: every key the forms need,\n * whichever the caller gave. The defaults themselves, the same object for\n * the same locale, when it gave none, so a renderer memoizing on the result\n * sees no change that is not one.\n */\nexport function resolveFormsMessages(\n messages: Partial<FormsMessages> | undefined,\n locale?: Intl.LocalesArgument,\n): FormsMessages {\n const defaults = defaultsFor(locale);\n return messages === undefined ? defaults : { ...defaults, ...messages };\n}\n","/**\n * An exact decimal number as text: an optional `-`, digits, and a point\n * before any fraction digits, as in `\"-1234.5\"`. A number field holds one\n * with `valueType: \"decimal\"`, and every value goes through one to be\n * stepped, rounded and compared without binary rounding.\n */\nexport type DecimalString = string;\n\n/** A value as a number field holds it: a JS number, or an exact decimal string. */\nexport type NumberLike = number | string;\n\n/**\n * Intl's rounding modes, with Intl's meanings. Spelled out rather than read\n * from `Intl.NumberFormatOptions`, which has them only from TypeScript's\n * ES2023 lib, so an app type-checking against ES2022 can still read them.\n */\nexport type RoundingMode =\n | \"ceil\"\n | \"floor\"\n | \"expand\"\n | \"trunc\"\n | \"halfCeil\"\n | \"halfFloor\"\n | \"halfExpand\"\n | \"halfTrunc\"\n | \"halfEven\";\n\n/** A decimal as `coefficient × 10^-scale`. */\ninterface Decimal {\n readonly coefficient: bigint;\n readonly scale: number;\n}\n\nconst DECIMAL_TEXT = /^([+-]?)(?:(\\d+)(?:\\.(\\d+))?|\\.(\\d+))$/;\n\nfunction readDecimal(text: string): Decimal | null {\n const match = DECIMAL_TEXT.exec(text);\n if (match === null) {\n return null;\n }\n const fraction = match[3] ?? match[4] ?? \"\";\n const magnitude = BigInt((match[2] ?? \"\") + fraction);\n return {\n coefficient: match[1] === \"-\" ? -magnitude : magnitude,\n scale: fraction.length,\n };\n}\n\nfunction toDecimal(text: DecimalString): Decimal {\n const decimal = readDecimal(text);\n if (decimal === null) {\n throw new RangeError(`\"${text}\" is not a decimal string`);\n }\n return decimal;\n}\n\n/** `decimal` in normal form, its fraction padded to `minimumFractionDigits`. */\nfunction writeDecimal(\n { coefficient, scale }: Decimal,\n minimumFractionDigits = 0,\n): DecimalString {\n const negative = coefficient < 0n;\n const digits = (negative ? -coefficient : coefficient)\n .toString()\n .padStart(scale + 1, \"0\");\n const point = digits.length - scale;\n const fraction = digits\n .slice(point)\n .replace(/0+$/, \"\")\n .padEnd(minimumFractionDigits, \"0\");\n return (\n (negative ? \"-\" : \"\") +\n digits.slice(0, point) +\n (fraction === \"\" ? \"\" : `.${fraction}`)\n );\n}\n\nfunction pow10(exponent: number): bigint {\n return 10n ** BigInt(exponent);\n}\n\n/** The coefficients of `a` and `b` at one scale, and that scale. */\nfunction aligned(\n a: Decimal,\n b: Decimal,\n): readonly [a: bigint, b: bigint, scale: number] {\n const scale = Math.max(a.scale, b.scale);\n return [\n a.coefficient * pow10(scale - a.scale),\n b.coefficient * pow10(scale - b.scale),\n scale,\n ];\n}\n\n/** Whether `text` is a decimal string: `[+-]digits[.digits]` or `[+-].digits`. */\nexport function isDecimalString(text: string): boolean {\n return DECIMAL_TEXT.test(text);\n}\n\n/**\n * `text` in normal form: a `-` only when it is not zero, no leading zeros\n * (one `0` before the point), and no trailing fraction zeros beyond\n * `minimumFractionDigits`. `null` when `text` is not a decimal string.\n */\nexport function normalizeDecimal(\n text: string,\n minimumFractionDigits = 0,\n): DecimalString | null {\n const decimal = readDecimal(text);\n return decimal === null ? null : writeDecimal(decimal, minimumFractionDigits);\n}\n\n/**\n * Orders two decimals by value: `\"12.5\"` and `\"12.50\"` are equal. Throws a\n * `RangeError` for text that is not a decimal string, as every function\n * here does.\n */\nexport function compareDecimals(\n a: DecimalString,\n b: DecimalString,\n): -1 | 0 | 1 {\n const [x, y] = aligned(toDecimal(a), toDecimal(b));\n return x < y ? -1 : x > y ? 1 : 0;\n}\n\n/** `a + b`, exactly. */\nexport function addDecimals(a: DecimalString, b: DecimalString): DecimalString {\n const [x, y, scale] = aligned(toDecimal(a), toDecimal(b));\n return writeDecimal({ coefficient: x + y, scale });\n}\n\n/** `a - b`, exactly. */\nexport function subtractDecimals(\n a: DecimalString,\n b: DecimalString,\n): DecimalString {\n const [x, y, scale] = aligned(toDecimal(a), toDecimal(b));\n return writeDecimal({ coefficient: x - y, scale });\n}\n\n/** Whether a dropped remainder takes the kept digits one further from zero. */\nfunction roundsAway(\n mode: RoundingMode,\n negative: boolean,\n twiceRemainder: bigint,\n divisor: bigint,\n quotient: bigint,\n): boolean {\n const above = twiceRemainder > divisor;\n const tie = twiceRemainder === divisor;\n switch (mode) {\n case \"trunc\":\n return false;\n case \"expand\":\n return true;\n case \"ceil\":\n return !negative;\n case \"floor\":\n return negative;\n case \"halfTrunc\":\n return above;\n case \"halfExpand\":\n return above || tie;\n case \"halfCeil\":\n return above || (tie && !negative);\n case \"halfFloor\":\n return above || (tie && negative);\n case \"halfEven\":\n return above || (tie && quotient % 2n !== 0n);\n }\n}\n\n/**\n * `value` rounded to `fractionDigits` digits after the point by `mode`,\n * exactly as Intl rounds the same text: `\"2.345\"` is `\"2.35\"` with\n * `halfExpand` and `\"2.34\"` with `halfEven`. A value that rounds to zero\n * is `\"0\"`, never `\"-0\"`.\n */\nexport function roundDecimal(\n value: DecimalString,\n fractionDigits: number,\n mode: RoundingMode,\n): DecimalString {\n if (!Number.isInteger(fractionDigits) || fractionDigits < 0) {\n throw new RangeError(`${String(fractionDigits)} is not a digit count`);\n }\n const { coefficient, scale } = toDecimal(value);\n if (scale <= fractionDigits) {\n return writeDecimal({ coefficient, scale });\n }\n const divisor = pow10(scale - fractionDigits);\n const quotient = coefficient / divisor;\n const remainder = coefficient % divisor;\n const negative = coefficient < 0n;\n const away =\n remainder !== 0n &&\n roundsAway(\n mode,\n negative,\n (negative ? -remainder : remainder) * 2n,\n divisor,\n quotient,\n );\n return writeDecimal({\n coefficient: away ? quotient + (negative ? -1n : 1n) : quotient,\n scale: fractionDigits,\n });\n}\n\n/** `value` times 10 to the `places`, exactly: `shiftDecimal(\"0.125\", 2)` is `\"12.5\"`. */\nexport function shiftDecimal(\n value: DecimalString,\n places: number,\n): DecimalString {\n if (!Number.isInteger(places)) {\n throw new RangeError(`${String(places)} is not a whole number of places`);\n }\n const { coefficient, scale } = toDecimal(value);\n const shifted = scale - places;\n return shifted >= 0\n ? writeDecimal({ coefficient, scale: shifted })\n : writeDecimal({ coefficient: coefficient * pow10(-shifted), scale: 0 });\n}\n\n/**\n * The multiple of `step` counted from `base` that is nearest `value` on\n * its `side`: the greatest not above it (`\"below\"`) or the least not below\n * it (`\"above\"`); `value` itself when it is one.\n */\nexport function snapDecimal(\n value: DecimalString,\n base: DecimalString,\n step: DecimalString,\n side: \"below\" | \"above\",\n): DecimalString {\n const target = toDecimal(value);\n const origin = toDecimal(base);\n const size = toDecimal(step);\n const scale = Math.max(target.scale, origin.scale, size.scale);\n const scaled = (decimal: Decimal) =>\n decimal.coefficient * pow10(scale - decimal.scale);\n const unit = scaled(size);\n if (unit <= 0n) {\n throw new RangeError(`The step \"${step}\" is not above zero`);\n }\n const offset = scaled(target) - scaled(origin);\n let steps = offset / unit;\n const remainder = offset % unit;\n if (remainder < 0n && side === \"below\") {\n steps -= 1n;\n } else if (remainder > 0n && side === \"above\") {\n steps += 1n;\n }\n return writeDecimal({ coefficient: scaled(origin) + steps * unit, scale });\n}\n\n/**\n * The shortest decimal that reads back as `value`, with no exponent:\n * `1e21` is `\"1000000000000000000000\"`, `-0` is `\"0\"`. Throws a\n * `RangeError` for `NaN` and the infinities.\n */\nexport function numberToDecimal(value: number): DecimalString {\n const match = /^(\\d+)(?:\\.(\\d+))?(?:e([+-]\\d+))?$/.exec(\n String(Math.abs(value)),\n );\n if (match === null) {\n throw new RangeError(`${String(value)} has no decimal form`);\n }\n const integer = match[1] ?? \"\";\n const fraction = match[2] ?? \"\";\n const scale = fraction.length - Number(match[3] ?? 0);\n const magnitude = BigInt(integer + fraction);\n const coefficient = scale < 0 ? magnitude * pow10(-scale) : magnitude;\n return writeDecimal({\n coefficient: value < 0 ? -coefficient : coefficient,\n scale: Math.max(scale, 0),\n });\n}\n\n/**\n * `value` as a JS number, and whether that number writes back as exactly\n * this decimal: `\"0.1\"` is exact, `\"9007199254740993\"` is not (it becomes\n * …992), and neither is a decimal beyond the number range.\n */\nexport function decimalToNumber(value: DecimalString): {\n readonly number: number;\n readonly exact: boolean;\n} {\n const decimal = writeDecimal(toDecimal(value));\n const number = Number(decimal);\n return {\n number,\n exact:\n Number.isFinite(number) &&\n compareDecimals(numberToDecimal(number), decimal) === 0,\n };\n}\n\n/**\n * `value` as a decimal in normal form, whichever value type it is, its\n * fraction padded to `minimumFractionDigits`.\n */\nexport function decimalOf(\n value: NumberLike,\n minimumFractionDigits = 0,\n): DecimalString {\n return writeDecimal(\n toDecimal(typeof value === \"number\" ? numberToDecimal(value) : value),\n minimumFractionDigits,\n );\n}\n\n/** How many digits `value` has after the point, trailing zeros not counted. */\nexport function fractionDigitsOf(value: DecimalString): number {\n const normal = writeDecimal(toDecimal(value));\n const point = normal.indexOf(\".\");\n return point === -1 ? 0 : normal.length - point - 1;\n}\n","import type { RoundingMode } from \"./decimal\";\nimport type { NumberSymbolOverrides } from \"./symbols\";\n\nexport type NumberStyle = \"decimal\" | \"percent\" | \"currency\" | \"unit\";\n\n/** How a negative number is written: `-12`, `(12)` or `12-`. Each is read in every field. */\nexport type NegativeStyle = \"minus\" | \"parentheses\" | \"trailingMinus\";\n\n/** Whether 12 % is stored as 0.12 (`\"fraction\"`, Intl's reading) or as 12 (`\"percent\"`). */\nexport type PercentScale = \"fraction\" | \"percent\";\n\n/** What a number field holds: a JS `number`, or an exact decimal string. */\nexport type NumberValueType = \"number\" | \"decimal\";\n\n/** The value type `T` names. */\nexport type NumberValue<T extends NumberValueType> = T extends \"decimal\"\n ? string\n : number;\n\n/**\n * How numbers read and write. Every name `Intl.NumberFormatOptions` also\n * has means what it means there, so a grid column's `format` can be passed\n * on. As in Intl, `currency` and `unit` take effect with their `style`, and\n * an unknown currency code or unit throws Intl's `RangeError`.\n */\nexport interface NumberOptions extends NumberSymbolOverrides {\n readonly locale?: Intl.LocalesArgument;\n /** `\"decimal\"` by default. */\n readonly style?: NumberStyle | undefined;\n /** ISO 4217 code; with `style: \"currency\"`. */\n readonly currency?: string | undefined;\n /** `\"symbol\"` by default. */\n readonly currencyDisplay?:\n \"symbol\" | \"narrowSymbol\" | \"code\" | \"name\" | undefined;\n /** An Intl unit identifier (`\"kilogram\"`, `\"kilometer-per-hour\"`); with `style: \"unit\"`. */\n readonly unit?: string | undefined;\n /** `\"short\"` by default. */\n readonly unitDisplay?: \"short\" | \"narrow\" | \"long\" | undefined;\n /** 0 by default; a currency's minor units. For a percent, of the number shown. */\n readonly minimumFractionDigits?: number | undefined;\n /** Unset: no rounding, every digit typed is kept (a currency: its minor units). */\n readonly maximumFractionDigits?: number | undefined;\n /** `\"halfExpand\"` (ties away from zero) by default. */\n readonly roundingMode?: RoundingMode | undefined;\n /** Group the integer digits when the value is shown formatted. On by default. */\n readonly useGrouping?: boolean | undefined;\n /** `\"minus\"` by default. */\n readonly negative?: NegativeStyle | undefined;\n /** `\"fraction\"` by default. */\n readonly percentScale?: PercentScale | undefined;\n}\n\n/** The fraction digits a field writes, and rounds its value to. */\nexport interface FractionDigits {\n readonly minimum: number;\n /** `null`: no rounding, every digit is kept. */\n readonly maximum: number | null;\n}\n\n/** Minor units per currency code, read from Intl once. */\nconst currencyDigits = new Map<string, number>();\n\n/** The digits ISO 4217 gives `currency`: 2 for EUR, 0 for JPY, 3 for KWD. */\nfunction minorUnits(currency: string): number {\n let digits = currencyDigits.get(currency);\n if (digits === undefined) {\n digits =\n new Intl.NumberFormat(\"en\", {\n style: \"currency\",\n currency,\n }).resolvedOptions().maximumFractionDigits ?? 2;\n currencyDigits.set(currency, digits);\n }\n return digits;\n}\n\n/**\n * The fraction digits `options` ask for: the minimum written and the\n * maximum kept. A currency defaults both to its minor units; otherwise the\n * minimum is 0 and there is no maximum. A maximum below the minimum is\n * raised to it. A field has fixed decimals when the two are equal.\n */\nexport function numberFractionDigits(\n options: NumberOptions = {},\n): FractionDigits {\n const own =\n options.style === \"currency\" && options.currency !== undefined\n ? minorUnits(options.currency)\n : null;\n const maximum = options.maximumFractionDigits ?? own;\n const minimum =\n options.minimumFractionDigits ??\n (own === null ? 0 : Math.min(own, maximum ?? own));\n return {\n minimum,\n maximum: maximum === null ? null : Math.max(maximum, minimum),\n };\n}\n","import { localeKey } from \"../localeKey\";\n\n/** How a locale writes numbers, read from `Intl.NumberFormat#formatToParts`. */\nexport interface NumberSymbols {\n /** The numbering system the field writes in: `\"latn\"`, `\"arab\"`, `\"deva\"`, ... */\n readonly numberingSystem: string;\n /** Its ten digits, zero first. */\n readonly digits: string;\n readonly decimal: string;\n /** `\"\"` when the field writes no grouping. */\n readonly group: string;\n /** Digits in the last group, then in every group before it: `[3, 3]`, or `[3, 2]` for lakh grouping. */\n readonly groupSizes: readonly [primary: number, secondary: number];\n /** 2 where a four-digit number is written ungrouped (\"1234\" in `es-ES`), else 1. */\n readonly minimumGroupingDigits: 1 | 2;\n /** Without the direction marks Intl puts around it. */\n readonly minus: string;\n readonly percent: string;\n /** Whether the locale writes numbers left to right inside right-to-left text. */\n readonly numbersLeftToRight: boolean;\n}\n\n/** What a field may set over its locale's symbols. */\nexport interface NumberSymbolOverrides {\n /** Replaces the locale's decimal separator; it must differ from the group separator. */\n readonly decimalSeparator?: string | undefined;\n /** Replaces the locale's group separator; `\"\"` writes no grouping. */\n readonly groupSeparator?: string | undefined;\n readonly groupSizes?:\n readonly [primary: number, secondary: number] | undefined;\n /** The digits the field writes: `\"latn\"` keeps Latin digits in `ar-EG`. */\n readonly numberingSystem?: string | undefined;\n}\n\n/** Marks Intl puts around a sign to keep it in place in right-to-left text. */\nexport const DIRECTION_MARKS =\n /[\\u200E\\u200F\\u061C\\u202A-\\u202E\\u2066-\\u2069]/g;\n\nconst RIGHT_TO_LEFT_MARK = /[\\u061C\\u200F]/;\n\n/**\n * Symbols already read, one per locale and overrides: building an\n * `Intl.NumberFormat` costs far more than using one, and a page has few.\n */\nconst cache = new Map<string, NumberSymbols>();\n\n/** The symbols `locale` writes with, in `numberingSystem` when given. */\nfunction localeSymbols(\n locale: Intl.LocalesArgument,\n numberingSystem: string | undefined,\n): NumberSymbols {\n const options = numberingSystem === undefined ? {} : { numberingSystem };\n const format = new Intl.NumberFormat(locale, options);\n const parts = format.formatToParts(-1234567.891);\n const part = (type: Intl.NumberFormatPartTypes) =>\n parts.find((found) => found.type === type)?.value;\n const groups = parts\n .filter((found) => found.type === \"integer\")\n .map((found) => found.value.length);\n const primary = groups.at(-1) ?? 3;\n const secondary = groups.length > 2 ? (groups.at(-2) ?? primary) : primary;\n const group = part(\"group\") ?? \"\";\n const percent = new Intl.NumberFormat(locale, {\n ...options,\n style: \"percent\",\n })\n .formatToParts(0.5)\n .find((found) => found.type === \"percentSign\")?.value;\n return {\n numberingSystem: format.resolvedOptions().numberingSystem,\n digits: Array.from({ length: 10 }, (_, digit) => format.format(digit)).join(\n \"\",\n ),\n decimal: part(\"decimal\") ?? \".\",\n group,\n groupSizes: [primary, secondary],\n minimumGroupingDigits:\n group !== \"\" &&\n !format.formatToParts(1234).some((found) => found.type === \"group\")\n ? 2\n : 1,\n minus: (part(\"minusSign\") ?? \"-\").replace(DIRECTION_MARKS, \"\"),\n percent: percent ?? \"%\",\n numbersLeftToRight: !RIGHT_TO_LEFT_MARK.test(format.format(-1)),\n };\n}\n\nfunction isGroupSize(size: number): boolean {\n return Number.isInteger(size) && size > 0;\n}\n\n/**\n * How `locale` writes numbers: its separators, group sizes, digits, minus\n * and percent signs, read from Intl at run time (they differ between ICU\n * versions), with the field's overrides laid over them. Separators that\n * would clash (an empty decimal separator, or both the same) and group\n * sizes that are not positive whole numbers are ignored, leaving the\n * locale's own. Cached per locale and overrides.\n */\nexport function numberSymbols(\n locale: Intl.LocalesArgument,\n overrides: NumberSymbolOverrides = {},\n): NumberSymbols {\n const { decimalSeparator, groupSeparator, groupSizes, numberingSystem } =\n overrides;\n const key = JSON.stringify([\n localeKey(locale),\n decimalSeparator,\n groupSeparator,\n groupSizes,\n numberingSystem,\n ]);\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const own = localeSymbols(locale, numberingSystem);\n const decimal = decimalSeparator ?? own.decimal;\n const group = groupSeparator ?? own.group;\n const separators =\n decimal === \"\" || decimal === group\n ? { decimal: own.decimal, group: own.group }\n : { decimal, group };\n const symbols: NumberSymbols = {\n ...own,\n ...separators,\n groupSizes:\n groupSizes !== undefined && groupSizes.every(isGroupSize)\n ? groupSizes\n : own.groupSizes,\n };\n cache.set(key, symbols);\n return symbols;\n}\n","import { localeKey } from \"../localeKey\";\nimport {\n decimalOf,\n fractionDigitsOf,\n shiftDecimal,\n type DecimalString,\n type NumberLike,\n} from \"./decimal\";\nimport {\n numberFractionDigits,\n type FractionDigits,\n type NumberOptions,\n} from \"./options\";\nimport { DIRECTION_MARKS, numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/**\n * Which text `formatNumber` writes:\n *\n * - `display`: what a field shows when it does not have focus: grouped,\n * fraction digits padded, the negative style; no currency, percent sign\n * or unit.\n * - `edit`: what a focused field shows: no grouping, a leading minus, the\n * digits the value has, padded to the minimum.\n * - `full`: Intl's whole text, with the currency, percent sign or unit, as\n * display mode, the `formatted` event detail and a grid cell show it.\n */\nexport type NumberTextForm = \"display\" | \"edit\" | \"full\";\n\n/** Where the currency, percent sign or unit sits around the number, for an input's adornments. */\nexport interface NumberAffixes {\n readonly prefix: string;\n readonly suffix: string;\n}\n\nconst NO_AFFIXES: NumberAffixes = { prefix: \"\", suffix: \"\" };\n\n/** Intl allows no more fraction digits than this. */\nconst MAX_FRACTION_DIGITS = 100;\n\nconst EDGE_SPACING = /^[\\s\\u200E\\u200F\\u061C]+|[\\s\\u200E\\u200F\\u061C]+$/g;\n\ninterface Part {\n readonly type: string;\n readonly value: string;\n}\n\n/** Formats already built, by locale and options. */\nconst formats = new Map<string, Intl.NumberFormat>();\n\nfunction intlFormat(\n locale: Intl.LocalesArgument,\n options: Intl.NumberFormatOptions,\n): Intl.NumberFormat {\n const key = JSON.stringify([localeKey(locale), options]);\n let format = formats.get(key);\n if (format === undefined) {\n format = new Intl.NumberFormat(locale, options);\n formats.set(key, format);\n }\n return format;\n}\n\nfunction isPercent(options: NumberOptions): boolean {\n return options.style === \"percent\";\n}\n\n/** The number a field shows for `value`: for a percent, the percent number (12.5 for 0.125). */\nfunction shownDecimal(\n value: NumberLike,\n options: NumberOptions,\n): DecimalString {\n const decimal = decimalOf(value);\n return isPercent(options) && options.percentScale !== \"percent\"\n ? shiftDecimal(decimal, 2)\n : decimal;\n}\n\n/** What Intl formats for `value`: for a percent, the fraction it multiplies by 100. */\nfunction intlValue(\n value: NumberLike,\n options: NumberOptions,\n): Intl.StringNumericLiteral {\n const decimal = decimalOf(value);\n const scaled =\n isPercent(options) && options.percentScale === \"percent\"\n ? shiftDecimal(decimal, -2)\n : decimal;\n // A decimal string is a numeric string, which Intl formats exactly.\n return scaled as Intl.StringNumericLiteral;\n}\n\n/** The fraction digits to write `shown` with: with no maximum, every digit it has. */\nfunction digitsFor(\n options: NumberOptions,\n shown: readonly DecimalString[],\n): FractionDigits & { readonly maximum: number } {\n const { minimum, maximum } = numberFractionDigits(options);\n const kept =\n maximum ??\n Math.max(minimum, ...shown.map((value) => fractionDigitsOf(value)));\n return { minimum, maximum: Math.min(kept, MAX_FRACTION_DIGITS) };\n}\n\nfunction intlOptions(\n options: NumberOptions,\n form: NumberTextForm,\n digits: FractionDigits & { readonly maximum: number },\n grouping: boolean,\n): Intl.NumberFormatOptions {\n const base: Intl.NumberFormatOptions = {\n minimumFractionDigits: digits.minimum,\n maximumFractionDigits: digits.maximum,\n roundingMode: options.roundingMode ?? \"halfExpand\",\n // `true` would group four-digit numbers in locales that do not.\n useGrouping: grouping ? \"auto\" : false,\n // Intl writes \"-0\" for a negative value that rounds to zero otherwise.\n signDisplay: \"negative\",\n numberingSystem: options.numberingSystem,\n };\n if (form !== \"full\") {\n return { ...base, style: \"decimal\" };\n }\n switch (options.style ?? \"decimal\") {\n case \"decimal\":\n return { ...base, style: \"decimal\" };\n case \"percent\":\n return { ...base, style: \"percent\" };\n case \"currency\":\n return {\n ...base,\n style: \"currency\",\n currency: options.currency,\n currencyDisplay: options.currencyDisplay ?? \"symbol\",\n };\n case \"unit\":\n return {\n ...base,\n style: \"unit\",\n unit: options.unit,\n unitDisplay: options.unitDisplay ?? \"short\",\n };\n }\n}\n\n/** Whether `form` groups the integer digits. */\nfunction groups(\n options: NumberOptions,\n symbols: NumberSymbols,\n form: NumberTextForm,\n): boolean {\n return (\n form !== \"edit\" && options.useGrouping !== false && symbols.group !== \"\"\n );\n}\n\n/** `digits` grouped by the field's sizes and separator. */\nfunction regroup(digits: string, symbols: NumberSymbols): string {\n const characters = Array.from(digits);\n const [primary, secondary] = symbols.groupSizes;\n if (characters.length < primary + symbols.minimumGroupingDigits) {\n return digits;\n }\n let end = characters.length - primary;\n const grouped = [characters.slice(end).join(\"\")];\n while (end > 0) {\n const start = Math.max(0, end - secondary);\n grouped.unshift(characters.slice(start, end).join(\"\"));\n end = start;\n }\n return grouped.join(symbols.group);\n}\n\n/**\n * Intl's parts with the field's own separators and group sizes where it\n * overrides the locale's (an override `numberSymbols` ignored is not in\n * them): the integer digits of each number are grouped again when the\n * text is grouped and the sizes are the field's own.\n */\nfunction withFieldSymbols(\n parts: readonly Part[],\n options: NumberOptions,\n symbols: NumberSymbols,\n grouping: boolean,\n): Part[] {\n const decimal =\n options.decimalSeparator === symbols.decimal ? symbols.decimal : null;\n const group = options.groupSeparator === symbols.group ? symbols.group : null;\n const sizes = options.groupSizes;\n const ownSizes =\n grouping &&\n sizes !== undefined &&\n sizes.every((size, index) => size === symbols.groupSizes[index]);\n const written: Part[] = [];\n for (const part of parts) {\n if (ownSizes && (part.type === \"integer\" || part.type === \"group\")) {\n const previous = written.at(-1);\n const digits = part.type === \"integer\" ? part.value : \"\";\n if (previous?.type === \"integer\") {\n written[written.length - 1] = {\n type: \"integer\",\n value: previous.value + digits,\n };\n } else {\n written.push({ type: \"integer\", value: digits });\n }\n } else if (part.type === \"decimal\" && decimal !== null) {\n written.push({ type: \"decimal\", value: decimal });\n } else if (part.type === \"group\" && group !== null) {\n written.push({ type: \"group\", value: group });\n } else {\n written.push(part);\n }\n }\n return ownSizes\n ? written.map((part) =>\n part.type === \"integer\"\n ? { type: \"integer\", value: regroup(part.value, symbols) }\n : part,\n )\n : written;\n}\n\nconst NUMERIC_PARTS = new Set([\"integer\", \"group\", \"decimal\", \"fraction\"]);\n\n/** The text of `parts`, its minus written in the `negative` style. */\nfunction joinWithSign(\n parts: readonly Part[],\n negative: NumberOptions[\"negative\"],\n): string {\n const minusAt = parts.findIndex((part) => part.type === \"minusSign\");\n const minus = parts[minusAt];\n if (minus === undefined || negative === undefined || negative === \"minus\") {\n return parts.map((part) => part.value).join(\"\");\n }\n const rest = parts.filter((_, index) => index !== minusAt);\n const text = (list: readonly Part[]) =>\n list.map((part) => part.value).join(\"\");\n if (negative === \"parentheses\") {\n return `(${text(rest)})`;\n }\n const lastDigit = rest.findLastIndex(\n (part) => part.type === \"integer\" || part.type === \"fraction\",\n );\n return (\n text(rest.slice(0, lastDigit + 1)) +\n minus.value.replace(DIRECTION_MARKS, \"\") +\n text(rest.slice(lastDigit + 1))\n );\n}\n\n/**\n * `value` as text, in one of three forms (`display` by default; see\n * `NumberTextForm`). A decimal string is formatted without passing through\n * a JS number, so every digit of a 20-digit amount is written. With no\n * maximum, every fraction digit of the value is written; with one, the\n * value is rounded to it by `roundingMode`. Nothing is written as \"-0\".\n * Throws a `RangeError` for a string that is not a decimal, or a number\n * that is not finite.\n */\nexport function formatNumber(\n value: NumberLike,\n options: NumberOptions = {},\n form: NumberTextForm = \"display\",\n): string {\n const symbols = numberSymbols(options.locale, options);\n const shown = shownDecimal(value, options);\n const grouping = groups(options, symbols, form);\n const format = intlFormat(\n options.locale,\n intlOptions(options, form, digitsFor(options, [shown]), grouping),\n );\n const parts = withFieldSymbols(\n format.formatToParts(\n form === \"full\"\n ? intlValue(value, options)\n : (shown as Intl.StringNumericLiteral),\n ),\n options,\n symbols,\n grouping,\n );\n const text = joinWithSign(\n parts,\n form === \"edit\" ? \"minus\" : options.negative,\n );\n return form === \"full\" ? text : text.replace(DIRECTION_MARKS, \"\");\n}\n\n/**\n * The currency, percent sign or unit written before and after the number\n * in `full` text, trimmed of spacing, for an input to draw beside its\n * text: `$` before in `en-US`, `€` after in `de-DE`, `%` before in\n * `tr-TR`. A spelled-out name agrees with `value` (\"1 euro\", \"2 euros\");\n * without one it is written for 0. Both are `\"\"` for a plain decimal.\n */\nexport function numberAffixes(\n options: NumberOptions = {},\n value: NumberLike = 0,\n): NumberAffixes {\n if ((options.style ?? \"decimal\") === \"decimal\") {\n return NO_AFFIXES;\n }\n const positive = decimalOf(value).replace(/^-/, \"\");\n const format = intlFormat(\n options.locale,\n intlOptions(\n options,\n \"full\",\n digitsFor(options, [shownDecimal(positive, options)]),\n false,\n ),\n );\n const parts = format.formatToParts(intlValue(positive, options));\n const first = parts.findIndex((part) => NUMERIC_PARTS.has(part.type));\n const last = parts.findLastIndex((part) => NUMERIC_PARTS.has(part.type));\n const text = (list: readonly Part[]) =>\n list\n .map((part) => part.value)\n .join(\"\")\n .replace(EDGE_SPACING, \"\");\n return {\n prefix: text(parts.slice(0, first)),\n suffix: text(parts.slice(last + 1)),\n };\n}\n\n/**\n * Intl's text for the range from `start` to `end`, in the `full` form:\n * \"10–20\", \"10,00–20,00 €\". Ends that write the same are written once\n * (\"10\", where Intl writes \"~10\"). A negative end in another `negative`\n * style than the minus writes each end whole around the locale's range\n * separator: \"(10)–20\".\n */\nexport function formatNumberRange(\n start: NumberLike,\n end: NumberLike,\n options: NumberOptions = {},\n): string {\n const symbols = numberSymbols(options.locale, options);\n const grouping = groups(options, symbols, \"full\");\n const format = intlFormat(\n options.locale,\n intlOptions(\n options,\n \"full\",\n digitsFor(options, [\n shownDecimal(start, options),\n shownDecimal(end, options),\n ]),\n grouping,\n ),\n );\n const parts = format.formatRangeToParts(\n intlValue(start, options),\n intlValue(end, options),\n );\n if (!parts.some((part) => part.source === \"endRange\")) {\n return formatNumber(start, options, \"full\");\n }\n if (\n (options.negative ?? \"minus\") !== \"minus\" &&\n parts.some((part) => part.type === \"minusSign\")\n ) {\n const lastStart = parts.findLastIndex(\n (part) => part.source === \"startRange\",\n );\n const firstEnd = parts.findIndex((part) => part.source === \"endRange\");\n const separator = parts\n .slice(lastStart + 1, firstEnd)\n .filter((part) => part.type === \"literal\")\n .map((part) => part.value)\n .join(\"\");\n return (\n formatNumber(start, options, \"full\") +\n separator +\n formatNumber(end, options, \"full\")\n );\n }\n return withFieldSymbols(parts, options, symbols, grouping)\n .map((part) => part.value)\n .join(\"\");\n}\n","import { isDigit, numberingSystemOf } from \"./digits\";\nimport { numberAffixes } from \"./formatNumber\";\nimport type { NegativeStyle, NumberOptions } from \"./options\";\nimport { DIRECTION_MARKS, type NumberSymbols } from \"./symbols\";\n\n/** How a text was read. */\nexport interface NumberReadingInfo {\n /** The character taken as the decimal point, as typed; `null` when there was none. */\n readonly decimalSeparator: string | null;\n /** Whether the integer digits were grouped. */\n readonly grouped: boolean;\n /** How a negative number was written; `null` for one that is not negative. */\n readonly negative: NegativeStyle | null;\n /** The numbering systems of the digits typed, in the order met: `[\"latn\"]`, `[\"arab\"]`, `[\"latn\", \"fullwide\"]`. */\n readonly digits: readonly string[];\n /** The text was a paste or drop that clean-up rewrote. */\n readonly cleaned: boolean;\n}\n\nconst FULL_WIDTH = /[\\uFF01-\\uFF5E]/g;\nconst MINUS_SIGNS = /[\\u2212\\uFE63]/g;\n\n/**\n * `text` with the noise of where it came from removed: direction marks\n * dropped, full-width forms (which a Chinese or Japanese input method\n * types) turned into ASCII, every minus sign into `-`, and trimmed.\n */\nexport function plainNumberText(text: string): string {\n return text\n .replace(DIRECTION_MARKS, \"\")\n .replace(FULL_WIDTH, (char) =>\n String.fromCharCode(char.charCodeAt(0) - 0xfee0),\n )\n .replace(MINUS_SIGNS, \"-\")\n .trim();\n}\n\n/** The numbering systems of the digits in `text`, in the order met. */\nexport function digitSystems(text: string): string[] {\n const systems = new Set<string>();\n for (const char of text) {\n if (isDigit(char)) {\n systems.add(numberingSystemOf(char));\n }\n }\n return [...systems];\n}\n\nconst SPACES = [\" \", \"\\u00A0\", \"\\u202F\", \"\\u2009\"];\n/** The apostrophes typed for an apostrophe group separator, as in `de-CH`. */\nexport const APOSTROPHES: readonly string[] = [\"'\", \"\\u2019\", \"\\u02BC\"];\nconst ARABIC_GROUP = \"\\u066C\";\nconst ARABIC_DECIMAL = \"\\u066B\";\n\n/** `separator` and the characters typed for it: any space for a space, any apostrophe for an apostrophe. */\nfunction lookalikes(separator: string): readonly string[] {\n if (SPACES.includes(separator)) {\n return SPACES;\n }\n if (APOSTROPHES.includes(separator)) {\n return APOSTROPHES;\n }\n if (separator === ARABIC_GROUP) {\n return [ARABIC_GROUP, \",\", \"\\u060C\"];\n }\n if (separator === ARABIC_DECIMAL) {\n return [ARABIC_DECIMAL, \".\"];\n }\n return separator === \"\" ? [] : [separator];\n}\n\n/** The characters a field reads as its decimal point and as its group separator. */\nexport interface FieldSeparators {\n readonly decimal: ReadonlySet<string>;\n readonly group: ReadonlySet<string>;\n}\n\n/** The field's separators and their lookalikes; the decimal's own character wins a clash. */\nexport function fieldSeparators(symbols: NumberSymbols): FieldSeparators {\n const decimal = new Set(\n lookalikes(symbols.decimal).filter((char) => char !== symbols.group),\n );\n const group = new Set(\n lookalikes(symbols.group).filter((char) => !decimal.has(char)),\n );\n return { decimal, group };\n}\n\n/**\n * Whether integer digit groups (as split by group separators) are grouped\n * the way the field groups: the first group 1 to the larger size long, the\n * last exactly the primary size, every one between either size. So `en-IN`\n * reads both \"12,34,567\" and \"1,234,567\", and `en-US` neither \"12,34,567\"\n * nor \"1,5\".\n */\nexport function groupingFits(\n groups: readonly string[],\n [primary, secondary]: NumberSymbols[\"groupSizes\"],\n): boolean {\n const [first = \"\", ...rest] = groups;\n const last = rest.at(-1);\n return (\n first.length >= 1 &&\n first.length <= Math.max(primary, secondary) &&\n last?.length === primary &&\n rest\n .slice(0, -1)\n .every((group) => group.length === secondary || group.length === primary)\n );\n}\n\n/** The currency, percent and unit texts a field accepts around its number, longest first. */\nfunction affixTokens(options: NumberOptions, symbols: NumberSymbols): string[] {\n const style = options.style ?? \"decimal\";\n if (style === \"decimal\") {\n return [];\n }\n const { prefix, suffix } = numberAffixes(options);\n const tokens = [prefix, suffix];\n if (style === \"currency\" && options.currency !== undefined) {\n tokens.push(options.currency.toUpperCase());\n }\n if (style === \"percent\") {\n tokens.push(\"%\", symbols.percent);\n }\n return [...new Set(tokens.map(plainNumberText))]\n .filter((token) => token !== \"\")\n .sort((a, b) => b.length - a.length);\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * `text` with the field's own currency sign or code, percent sign or unit\n * removed from either end, inside or outside a sign: \"-$1,234.50\",\n * \"1.234,50- €\" and \"(1.234,50 €)\" keep their signs.\n */\nexport function withoutAffixes(\n text: string,\n options: NumberOptions,\n symbols: NumberSymbols,\n): string {\n let rest = text;\n for (const token of affixTokens(options, symbols)) {\n const escaped = escapeRegExp(token);\n rest = rest\n .replace(new RegExp(`^([-+(]?)\\\\s*${escaped}\\\\s*`, \"u\"), \"$1\")\n .replace(new RegExp(`\\\\s*${escaped}\\\\s*([-)]?)$`, \"u\"), \"$1\");\n }\n return rest.trim();\n}\n\n/** The sign of a number's text, and the text inside it. */\nexport interface SignedText {\n readonly body: string;\n readonly negative: NegativeStyle | null;\n /** False for an opening parenthesis with no closing one yet. */\n readonly closed: boolean;\n}\n\n/** Reads a leading `-` or `+`, a trailing `-`, or parentheses around the whole text. */\nexport function readSign(text: string): SignedText {\n if (text.startsWith(\"(\")) {\n const closed = text.endsWith(\")\") && text.length > 1;\n return {\n body: text.slice(1, closed ? -1 : undefined).trim(),\n negative: \"parentheses\",\n closed,\n };\n }\n if (text.startsWith(\"-\") || text.startsWith(\"+\")) {\n return {\n body: text.slice(1).trim(),\n negative: text.startsWith(\"-\") ? \"minus\" : null,\n closed: true,\n };\n }\n if (text.endsWith(\"-\")) {\n return {\n body: text.slice(0, -1).trim(),\n negative: \"trailingMinus\",\n closed: true,\n };\n }\n return { body: text, negative: null, closed: true };\n}\n","import { digitValue, isDigit } from \"./digits\";\nimport type { NumberOptions } from \"./options\";\nimport {\n APOSTROPHES,\n digitSystems,\n fieldSeparators,\n groupingFits,\n plainNumberText,\n readSign,\n withoutAffixes,\n type NumberReadingInfo,\n} from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/** A paste turned into the field's own text, and how it was read. */\nexport interface CleanedNumber {\n /** The field's edit text: its digits and decimal separator, a leading minus, no grouping, every digit kept. */\n readonly text: string;\n /** How the pasted text was read; `cleaned` is true. */\n readonly info: NumberReadingInfo;\n}\n\nconst CURRENCY_SIGN = /\\p{Sc}/gu;\nconst PERCENT_SIGNS = /[%\\u066A\\uFE6A]/g;\nconst UPPER_WORD = /(?<![A-Za-z])[A-Z]{3}(?![A-Za-z])/g;\n/** The Arabic group separator and comma, which never mark a decimal point. */\nconst ARABIC_GROUPS = new Set([\"\\u066C\", \"\\u060C\"]);\nconst ARABIC_DECIMAL = \"\\u066B\";\n\n/** ISO 4217 codes Intl knows, read once. */\nlet currencyCodes: ReadonlySet<string> | undefined;\n\nfunction isCurrencyCode(word: string): boolean {\n currencyCodes ??= new Set(Intl.supportedValuesOf(\"currency\"));\n return currencyCodes.has(word);\n}\n\n/** `text` without currency signs and codes or percent signs; other letters stay, to refuse the paste. */\nfunction withoutSymbols(text: string, symbols: NumberSymbols): string {\n return text\n .replace(UPPER_WORD, (word) => (isCurrencyCode(word) ? \" \" : word))\n .replace(CURRENCY_SIGN, \"\")\n .replace(PERCENT_SIGNS, \"\")\n .replaceAll(symbols.percent, \"\")\n .trim();\n}\n\ntype Character =\n | { readonly kind: \"digit\"; readonly value: number }\n | { readonly kind: \"group\" }\n | { readonly kind: \"decimal\" }\n | { readonly kind: \"mark\"; readonly char: string };\n\n/**\n * What one pasted character can be: spaces and apostrophes always group,\n * as do the Arabic group separator and comma; the Arabic decimal separator\n * is always the point; `.`, `,` and the field's own separators are marks\n * whose role depends on the rest. `null` for anything else.\n */\nfunction characterOf(char: string, symbols: NumberSymbols): Character | null {\n if (isDigit(char)) {\n return { kind: \"digit\", value: digitValue(char) };\n }\n if (\n /\\s/u.test(char) ||\n APOSTROPHES.includes(char) ||\n ARABIC_GROUPS.has(char)\n ) {\n return { kind: \"group\" };\n }\n if (char === ARABIC_DECIMAL) {\n return { kind: \"decimal\" };\n }\n return char === \".\" ||\n char === \",\" ||\n char === symbols.decimal ||\n char === symbols.group\n ? { kind: \"mark\", char }\n : null;\n}\n\n/**\n * Which mark is the decimal point, or `null` for none:\n *\n * - two different marks: the one that comes last;\n * - one mark, more than once: none, it groups;\n * - one mark, once: the field's decimal separator (or a lookalike) is the\n * point; any other mark groups when the field's grouping fits it and is\n * the point when it does not (\"1,5\" is 1.5 in `en-US`, \"1.234\" 1234 in\n * `de-DE`).\n */\nfunction decimalMark(\n characters: readonly Character[],\n symbols: NumberSymbols,\n): string | null {\n const marks = characters.flatMap((character) =>\n character.kind === \"mark\" ? [character.char] : [],\n );\n const distinct = new Set(marks);\n const [only] = distinct;\n if (distinct.size > 1) {\n return marks.at(-1) ?? null;\n }\n if (only === undefined || marks.length > 1) {\n return null;\n }\n if (fieldSeparators(symbols).decimal.has(only)) {\n return only;\n }\n const groups: string[] = [];\n let group = \"\";\n for (const character of characters) {\n if (character.kind === \"digit\") {\n group += String(character.value);\n } else {\n groups.push(group);\n group = \"\";\n }\n }\n groups.push(group);\n return groupingFits(groups, symbols.groupSizes) ? null : only;\n}\n\n/**\n * Turns pasted or dropped text, copied from a web page, a PDF or a\n * spreadsheet in another locale, into the field's own edit text, or\n * returns `null` to refuse it. Currency signs and codes, percent signs and\n * the field's unit are dropped; parentheses or a leading or trailing minus\n * give the sign; any other letter refuses the paste, since dropping it\n * could change the number (\"12abc\", \"1e5\"). When both `.` and `,` appear,\n * the last is the decimal point (\"$1,234.50\" becomes \"1234,50\" in\n * `de-DE`); a lone mark is decided by the field's locale, so \"1.234\"\n * pasted into `de-DE` is 1234.\n */\nexport function cleanPastedNumber(\n text: string,\n options: NumberOptions = {},\n): CleanedNumber | null {\n const symbols = numberSymbols(options.locale, options);\n const rest = withoutSymbols(\n withoutAffixes(plainNumberText(text), options, symbols),\n symbols,\n );\n const sign = readSign(rest);\n if (!sign.closed) {\n return null;\n }\n const characters: Character[] = [];\n for (const char of sign.body) {\n const character = characterOf(char, symbols);\n if (character === null) {\n return null;\n }\n characters.push(character);\n }\n const point = characters.some((character) => character.kind === \"decimal\")\n ? ARABIC_DECIMAL\n : decimalMark(characters, symbols);\n const fieldDigits = Array.from(symbols.digits);\n let integer = \"\";\n let fraction: string | null = null;\n let grouped = false;\n for (const character of characters) {\n const isPoint =\n character.kind === \"decimal\" ||\n (character.kind === \"mark\" && character.char === point);\n if (isPoint) {\n if (fraction !== null) {\n return null;\n }\n fraction = \"\";\n } else if (character.kind === \"digit\") {\n const digit = fieldDigits[character.value] ?? String(character.value);\n if (fraction === null) {\n integer += digit;\n } else {\n fraction += digit;\n }\n } else if (fraction === null) {\n grouped = true;\n } else {\n return null;\n }\n }\n const digits = integer + (fraction ?? \"\");\n if (digits === \"\") {\n return null;\n }\n const negative =\n sign.negative !== null &&\n characters.some(\n (character) => character.kind === \"digit\" && character.value > 0,\n )\n ? sign.negative\n : null;\n return {\n text: `${negative === null ? \"\" : symbols.minus}${integer}${fraction === null ? \"\" : symbols.decimal + fraction}`,\n info: {\n decimalSeparator: fraction === null ? null : point,\n grouped,\n negative,\n digits: digitSystems(text),\n cleaned: true,\n },\n };\n}\n","import type { DecimalString } from \"./decimal\";\nimport { digitValue, isDigit } from \"./digits\";\nimport type { NumberOptions } from \"./options\";\nimport {\n digitSystems,\n fieldSeparators,\n groupingFits,\n plainNumberText,\n readSign,\n withoutAffixes,\n type FieldSeparators,\n type NumberReadingInfo,\n} from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/**\n * Why a text is not a number:\n *\n * - `notANumber`: a letter, a second decimal separator, a group separator\n * after it, an exponent.\n * - `incomplete`: a sign or separator with no digit yet (\"-\", \",\"), or an\n * opening parenthesis with no closing one.\n * - `grouping`: group separators where the field does not group (\"1,5\" in\n * `en-US`).\n * - `tooPrecise`: more digits than a JS number keeps exactly, for a field\n * holding numbers (`numberParser`).\n *\n * A minor release may add a member.\n */\nexport type NumberUnreadableReason =\n \"notANumber\" | \"incomplete\" | \"grouping\" | \"tooPrecise\";\n\n/** What a text reads as: nothing, an exact number, or why it is not one. */\nexport type NumberReading =\n | { readonly kind: \"empty\" }\n | {\n readonly kind: \"number\";\n /** Exact, as typed: point decimal, no grouping, no trailing fraction zeros. */\n readonly decimal: DecimalString;\n readonly info: NumberReadingInfo;\n }\n | { readonly kind: \"unreadable\"; readonly reason: NumberUnreadableReason };\n\nconst EMPTY = { kind: \"empty\" } as const;\n\nfunction unreadableBecause(reason: NumberUnreadableReason): NumberReading {\n return { kind: \"unreadable\", reason };\n}\n\n/** The digits of a number's text, in ASCII, and how it was written. */\ninterface NumberBody {\n readonly integer: string;\n readonly fraction: string;\n readonly decimalSeparator: string | null;\n readonly grouped: boolean;\n}\n\n/** Reads digits and separators: any decimal digits, the field's separators and their lookalikes. */\nfunction readBody(\n body: string,\n separators: FieldSeparators,\n groupSizes: NumberSymbols[\"groupSizes\"],\n): NumberBody | NumberUnreadableReason {\n const groups: string[] = [];\n let group = \"\";\n let fraction = \"\";\n let decimalSeparator: string | null = null;\n for (const char of body) {\n if (isDigit(char)) {\n const digit = String(digitValue(char));\n if (decimalSeparator === null) {\n group += digit;\n } else {\n fraction += digit;\n }\n } else if (decimalSeparator === null && separators.decimal.has(char)) {\n decimalSeparator = char;\n } else if (decimalSeparator === null && separators.group.has(char)) {\n groups.push(group);\n group = \"\";\n } else {\n return \"notANumber\";\n }\n }\n groups.push(group);\n const integer = groups.join(\"\");\n if (integer === \"\" && fraction === \"\") {\n return \"incomplete\";\n }\n const grouped = groups.length > 1;\n if (grouped && !groupingFits(groups, groupSizes)) {\n return \"grouping\";\n }\n return { integer, fraction, decimalSeparator, grouped };\n}\n\n/**\n * Reads text a user typed, strictly by the field's symbols, as an exact\n * decimal; it never rounds or guesses. It takes:\n *\n * - any Unicode decimal digits (`١٢٣` reads as 123 in `en-US`), and\n * full-width forms from an input method;\n * - the field's decimal separator once, and its group separator between\n * integer digits where its grouping allows (\"1,5\" is `grouping` in\n * `en-US`), each with its lookalikes (any space for a space);\n * - a leading `-` or `+`, a trailing `-`, or parentheses;\n * - the field's own currency sign or code, percent sign or unit at either\n * end, so its `full` text reads back.\n *\n * \"12,\" reads as 12, \",5\" as 0.5, \"007\" as 7, and \"-0\" as 0.\n */\nexport function parseNumber(\n text: string,\n options: NumberOptions = {},\n): NumberReading {\n const plain = plainNumberText(text);\n if (plain === \"\") {\n return EMPTY;\n }\n const symbols = numberSymbols(options.locale, options);\n const sign = readSign(withoutAffixes(plain, options, symbols));\n const body = readBody(\n sign.body,\n fieldSeparators(symbols),\n symbols.groupSizes,\n );\n if (typeof body === \"string\") {\n return unreadableBecause(body);\n }\n if (!sign.closed) {\n return unreadableBecause(\"incomplete\");\n }\n const integer = body.integer.replace(/^0+(?=\\d)/, \"\") || \"0\";\n const fraction = body.fraction.replace(/0+$/, \"\");\n const negative =\n sign.negative !== null && /[1-9]/.test(integer + fraction)\n ? sign.negative\n : null;\n return {\n kind: \"number\",\n decimal: `${negative === null ? \"\" : \"-\"}${integer}${fraction === \"\" ? \"\" : `.${fraction}`}`,\n info: {\n decimalSeparator: body.decimalSeparator,\n grouped: body.grouped,\n negative,\n digits: digitSystems(text),\n cleaned: false,\n },\n };\n}\n","import type { InputFilterDecision, TextEdit } from \"../field/plan\";\nimport { cleanPastedNumber } from \"./cleanPastedNumber\";\nimport { roundDecimal, type DecimalString } from \"./decimal\";\nimport { digitValue, isDigit } from \"./digits\";\nimport { formatNumber } from \"./formatNumber\";\nimport { numberFractionDigits, type NumberOptions } from \"./options\";\nimport { parseNumber } from \"./parseNumber\";\nimport { fieldSeparators, type NumberReadingInfo } from \"./reading\";\nimport { numberSymbols, type NumberSymbols } from \"./symbols\";\n\n/** How a number field takes what is typed, pasted and dropped into it. */\nexport interface NumberEntryOptions extends NumberOptions {\n /** Whether a minus or parentheses may be typed; false for a field whose `min` is 0 or above. True by default. */\n readonly negatives?: boolean | undefined;\n /** Refuses a digit that would type more fraction digits than the maximum, instead of rounding them. */\n readonly limitFractionDigits?: boolean | undefined;\n /**\n * `\"fixed\"` (default): a field with fixed decimals shows them all while\n * it has a value, the decimal separator jumps into them and they are\n * typed over. `\"free\"`: digits and one separator, typed as anywhere else.\n */\n readonly decimalEntry?: \"fixed\" | \"free\" | undefined;\n}\n\n/** What a number field does with an edit, and how clean-up read a paste. */\nexport interface NumberEntry {\n readonly decision: InputFilterDecision;\n /** How clean-up read the paste or drop the decision inserts; `null` for any other edit. */\n readonly pasted: NumberReadingInfo | null;\n}\n\nconst ALLOW = { kind: \"allow\" } as const;\nconst PREVENT = { kind: \"prevent\" } as const;\nconst SIGNS = new Set([\"-\", \"\\u2212\", \"+\", \"(\", \")\"]);\nconst MINUS_SIGNS = new Set([\"-\", \"\\u2212\", \"\\uFE63\"]);\n\nfunction entry(\n decision: InputFilterDecision,\n pasted: NumberReadingInfo | null = null,\n): NumberEntry {\n return { decision, pasted };\n}\n\n/**\n * The fraction digits a field types in place, or `null` when it types\n * them freely: with fixed-decimal entry, a minimum equal to a maximum\n * above zero.\n */\nexport function fixedFractionDigits(\n options: NumberEntryOptions,\n): number | null {\n const { minimum, maximum } = numberFractionDigits(options);\n return options.decimalEntry !== \"free\" && maximum === minimum && minimum > 0\n ? minimum\n : null;\n}\n\nfunction isPaste(edit: TextEdit<unknown>): boolean {\n return edit.source === \"paste\" || edit.source === \"drop\";\n}\n\n/** What an edit inserted, from the text before and after it: the middle that differs. */\nfunction insertedText(before: string, after: string): string {\n let start = 0;\n while (\n start < before.length &&\n start < after.length &&\n before[start] === after[start]\n ) {\n start += 1;\n }\n let end = 0;\n while (\n end < before.length - start &&\n end < after.length - start &&\n before[before.length - 1 - end] === after[after.length - 1 - end]\n ) {\n end += 1;\n }\n return after.slice(start, after.length - end);\n}\n\n/** The stretch of `before` an edit removed, from the text after it. */\nfunction removedRange(\n before: string,\n after: string,\n): readonly [start: number, end: number] {\n let start = 0;\n while (\n start < before.length &&\n start < after.length &&\n before[start] === after[start]\n ) {\n start += 1;\n }\n let end = before.length;\n while (\n end > start &&\n end - start > before.length - after.length &&\n before[end - 1] === after[after.length - (before.length - end) - 1]\n ) {\n end -= 1;\n }\n return [start, end];\n}\n\n/** The characters typed for the decimal point: the field's separator and its lookalikes. */\nfunction decimalChars(symbols: NumberSymbols): ReadonlySet<string> {\n return fieldSeparators(symbols).decimal;\n}\n\n/**\n * Whether the groups typed so far fit the field's grouping, the last one\n * still being typed: the first 1 to the larger size long, the ones after\n * either size, the last no longer than the primary size.\n */\nfunction groupsSoFarFit(integer: string, symbols: NumberSymbols): boolean {\n const separators = fieldSeparators(symbols).group;\n const groups: string[] = [];\n let group = \"\";\n for (const char of integer) {\n if (separators.has(char)) {\n groups.push(group);\n group = \"\";\n } else {\n group += char;\n }\n }\n groups.push(group);\n const [primary, secondary] = symbols.groupSizes;\n const [first = \"\", ...rest] = groups;\n const last = rest.pop();\n return (\n first.length >= 1 &&\n first.length <= Math.max(primary, secondary) &&\n rest.every(\n (group) => group.length === primary || group.length === secondary,\n ) &&\n (last === undefined || last.length <= primary)\n );\n}\n\n/** The integer part of typed text: its characters before the decimal separator, signs left out. */\nfunction integerText(text: string, decimals: ReadonlySet<string>): string {\n let integer = \"\";\n for (const char of text) {\n if (decimals.has(char)) {\n break;\n }\n if (!SIGNS.has(char)) {\n integer += char;\n }\n }\n return integer;\n}\n\n/** The text a number field could still become a number from: anything but `notANumber`. */\nfunction isValidStart(text: string, options: NumberOptions): boolean {\n const reading = parseNumber(text, options);\n return reading.kind !== \"unreadable\" || reading.reason !== \"notANumber\";\n}\n\n/** The digits typed after the decimal separator of `text`. */\nfunction fractionDigitsTyped(text: string, symbols: NumberSymbols): number {\n const decimals = decimalChars(symbols);\n const point = Array.from(text).findIndex((char) => decimals.has(char));\n if (point === -1) {\n return 0;\n }\n return Array.from(text)\n .slice(point + 1)\n .filter(isDigit).length;\n}\n\n/** Free entry: the edit stands when it leaves text that can still become a number. */\nfunction filterFree<N>(\n edit: TextEdit<N>,\n before: string,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (\n inputType === null ||\n inputType.startsWith(\"delete\") ||\n inputType.startsWith(\"history\")\n ) {\n return entry(ALLOW);\n }\n if (isPaste(edit)) {\n const pasted = input?.data ?? insertedText(before, edit.text);\n const cleaned = cleanPastedNumber(pasted, options);\n if (cleaned === null) {\n return entry(PREVENT);\n }\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n const text = before.slice(0, start) + cleaned.text + before.slice(end);\n return isValidStart(text, options)\n ? entry({ kind: \"rewrite\", data: cleaned.text }, cleaned.info)\n : entry(PREVENT);\n }\n const data = input?.data ?? insertedText(before, edit.text);\n const separators = fieldSeparators(symbols);\n const fractions = numberFractionDigits(options).maximum !== 0;\n const negatives = options.negatives !== false;\n for (const char of data) {\n const allowed =\n isDigit(char) ||\n (fractions && separators.decimal.has(char)) ||\n separators.group.has(char) ||\n (SIGNS.has(char) && (negatives || char === \"+\"));\n if (!allowed) {\n return entry(PREVENT);\n }\n }\n const text = edit.text;\n if (!isValidStart(text, options)) {\n return entry(PREVENT);\n }\n if (\n Array.from(data).some((char) => separators.group.has(char)) &&\n !groupsSoFarFit(integerText(text, separators.decimal), symbols)\n ) {\n return entry(PREVENT);\n }\n const { maximum } = numberFractionDigits(options);\n if (\n options.limitFractionDigits === true &&\n maximum !== null &&\n fractionDigitsTyped(text, symbols) > maximum\n ) {\n return entry(PREVENT);\n }\n return entry(ALLOW);\n}\n\n/**\n * A fixed-decimal text, read into its parts: an optional sign, the integer\n * digits and the fraction digits, with where each starts in the text.\n */\ninterface FixedText {\n readonly negative: boolean;\n readonly integer: string;\n readonly fraction: string;\n /** Where the integer digits start: after the sign. */\n readonly integerStart: number;\n /** Where the integer digits end: at the separator, or the end of the text. */\n readonly integerEnd: number;\n /** Where the fraction digits start: after the separator. */\n readonly fractionStart: number;\n}\n\n/** Where an edit is, in the parts of a fixed-decimal text. */\ntype FixedCaret =\n | { readonly part: \"integer\"; readonly index: number }\n | { readonly part: \"fraction\"; readonly index: number };\n\n/** A fixed-decimal number being edited: its digits as arrays, and the caret. */\ninterface FixedDraft {\n negative: boolean;\n integer: string[];\n fraction: string[];\n caret: FixedCaret;\n}\n\n/** Reads `text` as a fixed-decimal text, or `null` when it holds anything else. */\nfunction readFixed(text: string, symbols: NumberSymbols): FixedText | null {\n const decimals = decimalChars(symbols);\n const at = (offset: number) => text[offset] ?? \"\";\n let index = 0;\n let negative = false;\n if (MINUS_SIGNS.has(at(0)) || (text !== \"\" && at(0) === symbols.minus)) {\n negative = true;\n index = 1;\n }\n const integerStart = index;\n let integer = \"\";\n while (index < text.length && isDigit(at(index))) {\n integer += at(index);\n index += 1;\n }\n const integerEnd = index;\n let fraction = \"\";\n let fractionStart = index;\n if (index < text.length && decimals.has(at(index))) {\n index += 1;\n fractionStart = index;\n while (index < text.length && isDigit(at(index))) {\n fraction += at(index);\n index += 1;\n }\n }\n return index === text.length\n ? { negative, integer, fraction, integerStart, integerEnd, fractionStart }\n : null;\n}\n\n/** Where `offset` in the text falls among a fixed-decimal text's parts. */\nfunction caretAt(text: FixedText, offset: number): FixedCaret {\n if (offset <= text.integerEnd) {\n return {\n part: \"integer\",\n index: Math.max(0, offset - text.integerStart),\n };\n }\n return {\n part: \"fraction\",\n index: Math.min(\n text.fraction.length,\n Math.max(0, offset - text.fractionStart),\n ),\n };\n}\n\n/** The field's own digit for a typed one in any script. */\nfunction fieldDigit(char: string, symbols: NumberSymbols): string {\n return Array.from(symbols.digits)[digitValue(char)] ?? char;\n}\n\nfunction zeroOf(symbols: NumberSymbols): string {\n return Array.from(symbols.digits)[0] ?? \"0\";\n}\n\n/** `fraction` padded or cut to `digits`, with the field's zero. */\nfunction fitFraction(\n fraction: readonly string[],\n digits: number,\n zero: string,\n): string[] {\n const fitted = fraction.slice(0, digits);\n while (fitted.length < digits) {\n fitted.push(zero);\n }\n return fitted;\n}\n\n/**\n * Removes `start` to `end` of the text: integer digits go, fraction digits\n * turn to zero in place (so the decimals never shift), a sign inside it\n * goes, the separator stays. The caret lands at `start`.\n */\nfunction removeFixed(\n draft: FixedDraft,\n text: FixedText,\n start: number,\n end: number,\n zero: string,\n): void {\n if (start < text.integerStart && end > 0) {\n draft.negative = false;\n }\n const integerFrom = Math.max(start, text.integerStart) - text.integerStart;\n const integerTo = Math.min(end, text.integerEnd) - text.integerStart;\n if (integerTo > integerFrom) {\n draft.integer.splice(integerFrom, integerTo - integerFrom);\n }\n const fractionFrom = Math.max(start, text.fractionStart) - text.fractionStart;\n const fractionTo =\n Math.min(end, text.fractionStart + draft.fraction.length) -\n text.fractionStart;\n for (let index = fractionFrom; index < fractionTo; index += 1) {\n draft.fraction[index] = zero;\n }\n draft.caret =\n start <= text.integerEnd\n ? { part: \"integer\", index: integerFrom }\n : { part: \"fraction\", index: Math.max(0, fractionFrom) };\n}\n\n/**\n * Backspace or Delete with nothing selected, keeping the decimals' shape:\n * in the decimals one turns to zero and the caret moves past it; from the\n * first decimal Backspace deletes the last integer digit, and Delete from\n * the end of the integer part zeroes the first decimal. `beforeSign`: the\n * caret is in front of the minus. False when there is nothing to delete.\n */\nfunction deleteFixed(\n draft: FixedDraft,\n backward: boolean,\n beforeSign: boolean,\n zero: string,\n): boolean {\n const { caret } = draft;\n if (backward) {\n if (caret.part === \"fraction\" && caret.index > 0) {\n draft.fraction[caret.index - 1] = zero;\n draft.caret = { part: \"fraction\", index: caret.index - 1 };\n return true;\n }\n const index =\n caret.part === \"fraction\" ? draft.integer.length : caret.index;\n if (index > 0) {\n draft.integer.splice(index - 1, 1);\n draft.caret = { part: \"integer\", index: index - 1 };\n return true;\n }\n if (draft.negative && !beforeSign) {\n draft.negative = false;\n return true;\n }\n return false;\n }\n if (beforeSign) {\n draft.negative = false;\n return true;\n }\n if (caret.part === \"integer\" && caret.index < draft.integer.length) {\n draft.integer.splice(caret.index, 1);\n return true;\n }\n const index = caret.part === \"fraction\" ? caret.index : 0;\n if (index < draft.fraction.length) {\n draft.fraction[index] = zero;\n draft.caret = { part: \"fraction\", index: index + 1 };\n return true;\n }\n return false;\n}\n\n/**\n * Types one character into a fixed-decimal draft: a digit goes into the\n * integer part or over the next decimal, the decimal separator (or `.`\n * or `,`) moves into the decimals, a minus at the start makes it negative. False\n * when the character is refused.\n */\nfunction typeFixed(\n draft: FixedDraft,\n char: string,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): boolean {\n const { caret } = draft;\n if (isDigit(char)) {\n const digit = fieldDigit(char, symbols);\n if (caret.part === \"integer\") {\n // A lone zero holds the place of the integer part, so a digit typed\n // beside it takes its place.\n if (draft.integer.length === 1 && draft.integer[0] === zeroOf(symbols)) {\n draft.integer = [digit];\n draft.caret = { part: \"integer\", index: 1 };\n return true;\n }\n draft.integer.splice(caret.index, 0, digit);\n draft.caret = { part: \"integer\", index: caret.index + 1 };\n return true;\n }\n if (caret.index >= draft.fraction.length) {\n return false;\n }\n draft.fraction[caret.index] = digit;\n draft.caret = { part: \"fraction\", index: caret.index + 1 };\n return true;\n }\n // Both marks jump, whichever the locale groups with: a phone's decimal\n // key types the device's separator, which need not be the field's.\n if (char === \".\" || char === \",\" || decimalChars(symbols).has(char)) {\n if (caret.part === \"integer\") {\n if (draft.integer.length === 0) {\n draft.integer = [zeroOf(symbols)];\n }\n draft.caret = { part: \"fraction\", index: 0 };\n }\n return true;\n }\n if (\n (MINUS_SIGNS.has(char) || char === symbols.minus) &&\n options.negatives !== false &&\n !draft.negative &&\n caret.part === \"integer\" &&\n caret.index === 0\n ) {\n draft.negative = true;\n return true;\n }\n return false;\n}\n\n/**\n * A fixed-decimal draft as the field's edit text, and where the caret goes\n * in it. Leading zeros go; an integer part with no digits shows \"0\" while\n * a decimal is not zero; with no digit that counts left, the text is\n * empty (or the lone minus just typed).\n */\nfunction writeFixed(\n draft: FixedDraft,\n digits: number,\n symbols: NumberSymbols,\n): { readonly text: string; readonly caret: number } {\n const zero = zeroOf(symbols);\n let integer = [...draft.integer];\n let { caret } = draft;\n while (integer.length > 1 && integer[0] === zero) {\n integer = integer.slice(1);\n if (caret.part === \"integer\") {\n caret = { part: \"integer\", index: Math.max(0, caret.index - 1) };\n }\n }\n const fraction = fitFraction(draft.fraction, digits, zero);\n const typedFraction = draft.fraction.some((digit) => digit !== zero);\n if (integer.length === 0) {\n if (!typedFraction && draft.fraction.length > 0) {\n return { text: \"\", caret: 0 };\n }\n if (!typedFraction) {\n const sign = draft.negative ? symbols.minus : \"\";\n return { text: sign, caret: sign.length };\n }\n integer = [zero];\n if (caret.part === \"integer\") {\n caret = { part: \"integer\", index: 1 };\n }\n }\n const sign = draft.negative ? symbols.minus : \"\";\n const integerText = integer.join(\"\");\n const text = sign + integerText + symbols.decimal + fraction.join(\"\");\n const fractionStart =\n sign.length + integerText.length + symbols.decimal.length;\n return {\n text,\n caret:\n caret.part === \"integer\"\n ? sign.length + Math.min(caret.index, integerText.length)\n : fractionStart + Math.min(caret.index, digits),\n };\n}\n\n/** A pasted number as the field's fixed-decimal edit text, rounded, with the caret at the end of its integer part. */\nfunction pastedFixed(\n decimal: DecimalString,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): InputFilterDecision {\n const rounded = roundDecimal(\n decimal,\n digits,\n options.roundingMode ?? \"halfExpand\",\n );\n const text = formatNumber(\n rounded,\n {\n ...options,\n style: \"decimal\",\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n },\n \"edit\",\n );\n const point = text.lastIndexOf(symbols.decimal);\n return { kind: \"replace\", text, caret: point === -1 ? text.length : point };\n}\n\n/** Fixed-decimal entry for a paste or drop. */\nfunction pasteFixed<N>(\n edit: TextEdit<N>,\n before: string,\n current: FixedText,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry {\n const input = edit.input;\n const pasted = input?.data ?? insertedText(before, edit.text);\n const cleaned = cleanPastedNumber(pasted, options);\n if (cleaned === null) {\n return entry(PREVENT);\n }\n const reading = parseNumber(cleaned.text, { ...options, style: \"decimal\" });\n if (reading.kind !== \"number\") {\n return entry(PREVENT);\n }\n const start = input?.selectionStart ?? before.length;\n const end = input?.selectionEnd ?? start;\n const whole = start === 0 && end === before.length;\n const intoInteger =\n !whole &&\n before !== \"\" &&\n cleaned.info.decimalSeparator === null &&\n cleaned.info.negative === null &&\n end <= current.integerEnd &&\n start >= current.integerStart;\n if (!intoInteger) {\n return entry(\n pastedFixed(reading.decimal, digits, options, symbols),\n cleaned.info,\n );\n }\n const draft: FixedDraft = {\n negative: current.negative,\n integer: Array.from(current.integer),\n fraction: Array.from(current.fraction),\n caret: caretAt(current, start),\n };\n removeFixed(draft, current, start, end, zeroOf(symbols));\n for (const char of cleaned.text) {\n typeFixed(draft, char, options, symbols);\n }\n const written = writeFixed(draft, digits, symbols);\n return entry(\n { kind: \"replace\", text: written.text, caret: written.caret },\n cleaned.info,\n );\n}\n\n/**\n * Fixed-decimal entry: every edit is worked out on the text's parts and\n * the whole text replaced, so the decimals keep their count and place.\n */\nfunction filterFixed<N>(\n edit: TextEdit<N>,\n before: string,\n digits: number,\n options: NumberEntryOptions,\n symbols: NumberSymbols,\n): NumberEntry | null {\n const input = edit.input;\n const inputType = input?.inputType ?? null;\n if (input === null || inputType === null || inputType.startsWith(\"history\")) {\n return entry(ALLOW);\n }\n const current = readFixed(before, symbols);\n if (current === null) {\n return null;\n }\n if (isPaste(edit)) {\n return pasteFixed(edit, before, current, digits, options, symbols);\n }\n const zero = zeroOf(symbols);\n const start = Math.min(input.selectionStart ?? before.length, before.length);\n const end = Math.min(input.selectionEnd ?? start, before.length);\n const whole = before !== \"\" && start === 0 && end === before.length;\n const draft: FixedDraft = whole\n ? {\n negative: false,\n integer: [],\n fraction: [],\n caret: { part: \"integer\", index: 0 },\n }\n : {\n negative: current.negative,\n integer: Array.from(current.integer),\n fraction: Array.from(current.fraction),\n caret: caretAt(current, start),\n };\n const deleting = inputType.startsWith(\"delete\");\n if (whole && deleting) {\n return entry({ kind: \"replace\", text: \"\", caret: 0 });\n }\n if (!whole && start < end) {\n removeFixed(draft, current, start, end, zero);\n } else if (!whole && deleting) {\n if (\n inputType === \"deleteContentBackward\" ||\n inputType === \"deleteContentForward\"\n ) {\n if (\n !deleteFixed(\n draft,\n inputType === \"deleteContentBackward\",\n start < current.integerStart,\n zero,\n )\n ) {\n return entry(PREVENT);\n }\n } else {\n const [from, to] = removedRange(before, edit.text);\n if (from === to) {\n return entry(PREVENT);\n }\n removeFixed(draft, current, from, to, zero);\n }\n }\n if (!deleting) {\n const data = input.data ?? insertedText(before, edit.text);\n for (const char of data) {\n if (!typeFixed(draft, char, options, symbols)) {\n return entry(PREVENT);\n }\n }\n }\n const written = writeFixed(draft, digits, symbols);\n if (written.text === before && start === end && written.caret === start) {\n return entry(PREVENT);\n }\n return entry({ kind: \"replace\", text: written.text, caret: written.caret });\n}\n\n/**\n * A number field's judgement of an edit, its `filterInput`: `edit` is the\n * edit as the app's `onBeforeInput` left it, `before` the text before it.\n *\n * Free entry keeps what can still become a number: digits, the decimal\n * separator once (none in a field with no fraction digits), group\n * separators where the grouping allows, a sign (none when `negatives` is\n * false). Letters, currency signs and the rest are refused, deletions and\n * undo always stand, and a paste or drop is cleaned by `cleanPastedNumber`\n * and inserted in its place, or refused.\n *\n * A field with fixed decimals (`fixedFractionDigits`) replaces the whole\n * text on every edit instead: the decimals always show once it has a\n * value, digits go before them, the decimal separator (or `.` or `,`)\n * moves the caret into them, they are typed over and never grow, and deleting turns\n * one to zero. A paste is rounded to them. Text that is not a\n * fixed-decimal text (after an undo) is edited freely until it is again.\n */\nexport function filterNumberEdit<N>(\n edit: TextEdit<N>,\n before: string,\n options: NumberEntryOptions = {},\n): NumberEntry {\n const symbols = numberSymbols(options.locale, options);\n const digits = fixedFractionDigits(options);\n if (digits !== null) {\n const fixed = filterFixed(edit, before, digits, options, symbols);\n if (fixed !== null) {\n return fixed;\n }\n }\n return filterFree(edit, before, options, symbols);\n}\n\n/**\n * Where the caret goes when a number field's text is written again (the\n * edit form on focus, the padded text on commit): after as many digits,\n * decimal separators and signs as it had before it, so group separators\n * added or removed around it do not move it. A caret at the end stays at\n * the end.\n */\nexport function numberCaret(\n options: NumberOptions = {},\n): (previousText: string, caret: number, nextText: string) => number {\n const symbols = numberSymbols(options.locale, options);\n const decimals = decimalChars(symbols);\n const significant = (char: string) =>\n isDigit(char) ||\n decimals.has(char) ||\n SIGNS.has(char) ||\n char === symbols.minus;\n return (previousText, caret, nextText) => {\n if (caret >= previousText.length) {\n return nextText.length;\n }\n let count = 0;\n for (let index = 0; index < caret; index += 1) {\n if (significant(previousText[index] ?? \"\")) {\n count += 1;\n }\n }\n if (count === 0) {\n return 0;\n }\n for (let index = 0; index < nextText.length; index += 1) {\n if (significant(nextText[index] ?? \"\")) {\n count -= 1;\n if (count === 0) {\n return index + 1;\n }\n }\n }\n return nextText.length;\n };\n}\n","import {\n addDecimals,\n compareDecimals,\n decimalOf,\n snapDecimal,\n subtractDecimals,\n type DecimalString,\n} from \"./decimal\";\n\nexport type StepDirection = \"up\" | \"down\";\n\n/** One `step`, one `largeStep`, or all the way to the limit (`edge`). */\nexport type StepSize = \"step\" | \"large\" | \"edge\";\n\n/** A step to take, every number an exact decimal. */\nexport interface StepRequest {\n /** The value to step from; `null` for an empty field. */\n readonly value: DecimalString | null;\n readonly direction: StepDirection;\n readonly size: StepSize;\n /** Above zero. */\n readonly step: DecimalString;\n readonly largeStep: DecimalString;\n readonly min: DecimalString | null;\n readonly max: DecimalString | null;\n}\n\n/** `value` within `min` and `max`. */\nfunction clamp(\n value: DecimalString,\n min: DecimalString | null,\n max: DecimalString | null,\n): DecimalString {\n if (min !== null && compareDecimals(value, min) < 0) {\n return decimalOf(min);\n }\n if (max !== null && compareDecimals(value, max) > 0) {\n return decimalOf(max);\n }\n return value;\n}\n\n/**\n * The value one step on, in normal form:\n *\n * - From empty, the starting point: 0, or `min` when it is above 0, or\n * `max` when it is below 0.\n * - On the step grid (multiples of `step` from `min`, or from 0 without\n * one), one step or one large step; off it, to the grid value that way\n * first, as native number inputs do (1.37 with step 0.5: up to 1.5, down\n * to 1).\n * - `edge`: to `max` going up and `min` going down; the value unchanged\n * when that limit is not set.\n * - Never past `min` or `max`: a step from a limit returns that limit,\n * which `compareDecimals` tells the caller is the value it had.\n *\n * The result can have more fraction digits than the field keeps; the\n * caller rounds it. Throws a `RangeError` for a step that is not above\n * zero.\n */\nexport function stepNumber(request: StepRequest): DecimalString | null {\n const { value, direction, size, step, largeStep, min, max } = request;\n if (size === \"edge\") {\n const edge = direction === \"up\" ? max : min;\n return edge === null ? value : decimalOf(edge);\n }\n if (value === null) {\n if (min !== null && compareDecimals(min, \"0\") > 0) {\n return decimalOf(min);\n }\n return max !== null && compareDecimals(max, \"0\") < 0 ? decimalOf(max) : \"0\";\n }\n const amount = size === \"large\" ? largeStep : step;\n const base = min ?? \"0\";\n // The farthest grid value no more than one step away, so an off-grid\n // value lands on the grid and an on-grid one moves a whole step.\n const target =\n direction === \"up\"\n ? snapDecimal(addDecimals(value, amount), base, step, \"below\")\n : snapDecimal(subtractDecimals(value, amount), base, step, \"above\");\n return clamp(target, min, max);\n}\n","import type { FieldState } from \"../field/state\";\nimport type { FormsMessages } from \"../messages/formsMessages\";\nimport {\n parsed,\n unreadable,\n type FormatContext,\n type ParseContext,\n type ParseResult,\n} from \"../parse\";\nimport {\n decimalOf,\n decimalToNumber,\n roundDecimal,\n shiftDecimal,\n type DecimalString,\n type NumberLike,\n} from \"./decimal\";\nimport { formatNumber } from \"./formatNumber\";\nimport {\n numberFractionDigits,\n type NumberOptions,\n type NumberValue,\n type NumberValueType,\n} from \"./options\";\nimport { parseNumber, type NumberUnreadableReason } from \"./parseNumber\";\nimport type { NumberReadingInfo } from \"./reading\";\nimport { numberSymbols } from \"./symbols\";\nimport { stepNumber, type StepDirection, type StepSize } from \"./stepNumber\";\n\n/** How a number field reads and writes, and the value type it holds. */\nexport interface NumberFieldOptions<\n T extends NumberValueType = NumberValueType,\n> extends NumberOptions {\n /** `\"number\"` (default): a JS number. `\"decimal\"`: an exact decimal string (`\"1234.50\"`). */\n readonly valueType?: T | undefined;\n}\n\n/** What a number field adds to every event it fires. */\nexport interface NumberDetails {\n /** The value as an exact decimal string, whatever the value type; `null` when empty. */\n readonly decimal: DecimalString | null;\n /** The value as display mode writes it, currency, percent sign or unit included; `\"\"` when empty. */\n readonly formatted: string;\n /** How the text on screen reads; `null` while it shows the value formatted, or cannot be read. */\n readonly reading: NumberReadingInfo | null;\n}\n\n/** Places a percent's stored value sits below the number shown: 2 for a fraction (0.125 for 12.5). */\nfunction percentShift(options: NumberOptions): number {\n return options.style === \"percent\" && options.percentScale !== \"percent\"\n ? 2\n : 0;\n}\n\n/**\n * The value a field stores for a number shown as `typed`: rounded to the\n * maximum fraction digits, scaled back for a percent, in normal form with\n * the minimum digits.\n */\nfunction storedDecimal(\n typed: DecimalString,\n options: NumberOptions,\n): DecimalString {\n const { minimum, maximum } = numberFractionDigits(options);\n const rounded =\n maximum === null\n ? typed\n : roundDecimal(typed, maximum, options.roundingMode ?? \"halfExpand\");\n const shift = percentShift(options);\n return decimalOf(shiftDecimal(rounded, -shift), minimum + shift);\n}\n\n/** The message a field shows for text it cannot read. */\nfunction unreadableMessage(\n reason: NumberUnreadableReason,\n options: NumberOptions,\n messages: FormsMessages,\n): string {\n switch (reason) {\n case \"notANumber\":\n case \"incomplete\":\n return messages.notANumber;\n case \"grouping\": {\n const { decimal, group } = numberSymbols(options.locale, options);\n return messages.numberGrouping(decimal, group);\n }\n case \"tooPrecise\":\n return messages.numberTooPrecise;\n }\n}\n\n/**\n * A number field's own reading: `parseNumber`, then the value rounded to\n * the maximum fraction digits by `roundingMode` (so `onChange` carries the\n * value that will be stored), scaled for a percent, and held as the value\n * type. As a JS number, text whose rounded digits a number cannot keep\n * exactly (\"9007199254740993\") is unreadable rather than silently changed.\n * The locale is the field's unless `options` names one.\n */\nexport function numberParser<T extends NumberValueType = \"number\">(\n options: NumberFieldOptions<T> = {},\n): (\n text: string,\n context: ParseContext<NumberValue<T>>,\n) => ParseResult<NumberValue<T>> {\n return (text, context) => {\n const field = { ...options, locale: options.locale ?? context.locale };\n const reading = parseNumber(text, field);\n switch (reading.kind) {\n case \"empty\":\n return parsed(null);\n case \"unreadable\":\n return unreadable(\n unreadableMessage(reading.reason, field, context.messages),\n );\n case \"number\": {\n const decimal = storedDecimal(reading.decimal, field);\n if (options.valueType === \"decimal\") {\n return parsed(decimal as NumberValue<T>);\n }\n const { number, exact } = decimalToNumber(decimal);\n return exact\n ? parsed(number as NumberValue<T>)\n : unreadable(\n unreadableMessage(\"tooPrecise\", field, context.messages),\n );\n }\n }\n };\n}\n\n/**\n * A number field's own writing: the `edit` form while it has focus and the\n * `display` form otherwise (`FormatContext.purpose`), `\"\"` for `null`. The\n * locale is the field's unless `options` names one.\n */\nexport function numberFormatter<V extends NumberLike>(\n options: NumberOptions = {},\n): (value: V | null, context: FormatContext<V>) => string {\n return (value, { locale, purpose }) =>\n value === null\n ? \"\"\n : formatNumber(\n value,\n { ...options, locale: options.locale ?? locale },\n purpose,\n );\n}\n\n/**\n * A number field's details for `state`, what its `FieldOptions.details`\n * returns. `pasted` is how clean-up read the paste the text on screen came\n * from, which the input remembers until the next edit (`cleanPastedNumber`);\n * without it, `reading` describes the text as typed. `options` holds the\n * field's locale.\n */\nexport function numberDetails<V extends NumberLike>(\n state: FieldState<V>,\n options: NumberOptions,\n pasted: NumberReadingInfo | null = null,\n): NumberDetails {\n const { value, draft } = state;\n return {\n decimal:\n value === null\n ? null\n : decimalOf(\n value,\n numberFractionDigits(options).minimum + percentShift(options),\n ),\n formatted: value === null ? \"\" : formatNumber(value, options, \"full\"),\n reading:\n draft.kind === \"text\" ? (pasted ?? readingOf(draft.text, options)) : null,\n };\n}\n\n/** A step a number field takes, its numbers in the field's value units. */\nexport interface NumberStep {\n readonly direction: StepDirection;\n readonly size: StepSize;\n /** Above zero. */\n readonly step: NumberLike;\n readonly largeStep: NumberLike;\n readonly min: NumberLike | null;\n readonly max: NumberLike | null;\n}\n\n/**\n * The value a step takes a number field to, as `stepNumber` works it out\n * exactly, rounded to the field's maximum fraction digits (of the number\n * shown, for a percent) and held as its value type. At a limit it is the\n * value the field has; from empty, the starting point.\n */\nexport function stepNumberValue<T extends NumberValueType = \"number\">(\n value: NumberValue<T> | null,\n step: NumberStep,\n options: NumberFieldOptions<T> = {},\n): NumberValue<T> | null {\n const limit = (bound: NumberLike | null) =>\n bound === null ? null : decimalOf(bound);\n const next = stepNumber({\n value: value === null ? null : decimalOf(value),\n direction: step.direction,\n size: step.size,\n step: decimalOf(step.step),\n largeStep: decimalOf(step.largeStep),\n min: limit(step.min),\n max: limit(step.max),\n });\n if (next === null) {\n return null;\n }\n const { minimum, maximum } = numberFractionDigits(options);\n const shift = percentShift(options);\n const rounded =\n maximum === null\n ? next\n : roundDecimal(\n next,\n maximum + shift,\n options.roundingMode ?? \"halfExpand\",\n );\n if (options.valueType === \"decimal\") {\n return decimalOf(rounded, minimum + shift) as NumberValue<T>;\n }\n return decimalToNumber(rounded).number as NumberValue<T>;\n}\n\nfunction readingOf(\n text: string,\n options: NumberOptions,\n): NumberReadingInfo | null {\n const reading = parseNumber(text, options);\n return reading.kind === \"number\" ? reading.info : null;\n}\n","import type { NoFlags, RangeKind } from \"../range/range\";\nimport {\n compareDecimals,\n decimalOf,\n decimalToNumber,\n subtractDecimals,\n type DecimalString,\n} from \"./decimal\";\nimport type { NumberValue, NumberValueType } from \"./options\";\n\n/** Orders two ends: an end before its start is reversed. */\nfunction orient(order: number) {\n return order >= 0\n ? ({ kind: \"ordered\", flags: {} } as const)\n : ({ kind: \"reversed\" } as const);\n}\n\n/**\n * The range kind of JS numbers. The span is `end - start`, worked out\n * exactly (0.3 to 0.1 spans 0.2, never 0.19999999999999998), the same\n * whatever the bounds. Numbers show the end they store, so it has no\n * shown-versus-stored conversion.\n */\nexport const numberRangeKind: RangeKind<number> = {\n compare: (a, b) => compareDecimals(decimalOf(a), decimalOf(b)),\n orient: (start, end) =>\n orient(compareDecimals(decimalOf(end), decimalOf(start))),\n openFlags: {},\n span: (start, end) =>\n decimalToNumber(subtractDecimals(decimalOf(end), decimalOf(start))).number,\n compareSpans: (a, b) => compareDecimals(decimalOf(a), decimalOf(b)),\n};\n\n/** The range kind of exact decimal strings: as `numberRangeKind`, the span a decimal string too. */\nexport const decimalRangeKind: RangeKind<\n DecimalString,\n NoFlags,\n DecimalString\n> = {\n compare: compareDecimals,\n orient: (start, end) => orient(compareDecimals(end, start)),\n openFlags: {},\n span: (start, end) => subtractDecimals(end, start),\n compareSpans: compareDecimals,\n};\n\n/** The range kind of a number field's value type: `numberRangeKind`, or `decimalRangeKind` for `\"decimal\"`. */\nexport function numberRangeKindOf<T extends NumberValueType = \"number\">(\n valueType: T | undefined,\n): RangeKind<NumberValue<T>, NoFlags, NumberValue<T>> {\n // `NumberValue<T>` is a string exactly when `T` is \"decimal\".\n return (valueType === \"decimal\"\n ? decimalRangeKind\n : numberRangeKind) as unknown as RangeKind<\n NumberValue<T>,\n NoFlags,\n NumberValue<T>\n >;\n}\n","import type { Validator } from \"../validation/validators\";\nimport {\n compareDecimals,\n decimalOf,\n snapDecimal,\n type NumberLike,\n} from \"./decimal\";\nimport { formatNumber } from \"./formatNumber\";\nimport type { NumberOptions } from \"./options\";\n\n/** `limit` as the field writes numbers in its messages: the `full` form, in its locale unless `options` names one. */\nfunction written(\n limit: NumberLike,\n options: NumberOptions,\n locale: Intl.LocalesArgument,\n): string {\n return formatNumber(\n limit,\n { ...options, locale: options.locale ?? locale },\n \"full\",\n );\n}\n\n/**\n * A number below `min` is `messages.rangeUnderflow`, \"Enter 10 or more\".\n * Compared as exact decimals, so either value type works and a decimal\n * limit keeps every digit. `options` are the field's, to write `min` the\n * way it writes numbers. `null` passes.\n */\nexport function minRule<V extends NumberLike>(\n min: NumberLike,\n options: NumberOptions = {},\n): Validator<V> {\n const limit = decimalOf(min);\n return (value, { locale, messages }) =>\n value !== null && compareDecimals(decimalOf(value), limit) < 0\n ? {\n text: messages.rangeUnderflow(written(min, options, locale)),\n code: \"rangeUnderflow\",\n }\n : null;\n}\n\n/** A number above `max` is `messages.rangeOverflow`, \"Enter 100 or less\"; otherwise as `minRule`. */\nexport function maxRule<V extends NumberLike>(\n max: NumberLike,\n options: NumberOptions = {},\n): Validator<V> {\n const limit = decimalOf(max);\n return (value, { locale, messages }) =>\n value !== null && compareDecimals(decimalOf(value), limit) > 0\n ? {\n text: messages.rangeOverflow(written(max, options, locale)),\n code: \"rangeOverflow\",\n }\n : null;\n}\n\n/**\n * A number that is not a whole number of `step`s from `base` is\n * `messages.stepMismatch`, \"Enter a multiple of 0.05\". Exact, so 0.15 is\n * three steps of 0.05. A number input's `step` only drives stepping; this\n * rule is for a field whose values must sit on it. Throws a `RangeError`\n * for a step that is not above zero. `null` passes.\n */\nexport function stepRule<V extends NumberLike>(\n step: NumberLike,\n base: NumberLike = 0,\n options: NumberOptions = {},\n): Validator<V> {\n const size = decimalOf(step);\n const origin = decimalOf(base);\n if (compareDecimals(size, \"0\") <= 0) {\n throw new RangeError(`The step ${size} is not above zero`);\n }\n return (value, { locale, messages }) => {\n if (value === null) {\n return null;\n }\n const decimal = decimalOf(value);\n return compareDecimals(\n snapDecimal(decimal, origin, size, \"below\"),\n decimal,\n ) === 0\n ? null\n : {\n text: messages.stepMismatch(written(step, options, locale)),\n code: \"stepMismatch\",\n };\n };\n}\n","/**\n * What opened a popup: its button, a key in the field (F4, Alt+ArrowDown),\n * or typing in a search box. A minor release may add a member, so a\n * `switch` over it needs a `default`.\n */\nexport type PopupOpenReason = \"button\" | \"keyboard\" | \"typing\";\n\n/**\n * What closed a popup: Escape; a press outside it; a scroll outside it or\n * the window resizing, which would leave it behind its field; focus or\n * the window leaving it; the overlay it was opened above closing\n * (`\"parent\"`); its button pressed again; a value chosen in it\n * (`\"picker\"`); or the field turning disabled, read-only or display-only.\n */\nexport type PopupCloseReason =\n | \"escape\"\n | \"outside\"\n | \"scroll\"\n | \"resize\"\n | \"blur\"\n | \"parent\"\n | \"button\"\n | \"picker\"\n | \"disabled\";\n\n/** What `onOpenChange` is told as a popup opens or closes. */\nexport type PopupOpenChange =\n | { readonly open: true; readonly reason: PopupOpenReason }\n | { readonly open: false; readonly reason: PopupCloseReason };\n\n/** Whether a popup is open, and what opened it. */\nexport type PopupState =\n | { readonly kind: \"closed\" }\n | { readonly kind: \"open\"; readonly openedBy: PopupOpenReason };\n\n/** What can happen to a popup. */\nexport type PopupAction =\n | { readonly type: \"open\"; readonly reason: PopupOpenReason }\n | { readonly type: \"close\"; readonly reason: PopupCloseReason }\n /** Its button: opens a closed popup, closes an open one. */\n | { readonly type: \"toggle\" };\n\n/** The popup after an action, and what `onOpenChange` is told: `null` when nothing changed. */\nexport interface PopupStep {\n readonly state: PopupState;\n readonly change: PopupOpenChange | null;\n}\n\nexport const POPUP_CLOSED: PopupState = { kind: \"closed\" };\n\n/**\n * A popup's open state after `action`. Opening an open popup and closing\n * a closed one change nothing, so `onOpenChange` hears each change once.\n */\nexport function popupReducer(\n state: PopupState,\n action: PopupAction,\n): PopupStep {\n switch (action.type) {\n case \"open\":\n return state.kind === \"open\"\n ? { state, change: null }\n : {\n state: { kind: \"open\", openedBy: action.reason },\n change: { open: true, reason: action.reason },\n };\n case \"close\":\n return state.kind === \"closed\"\n ? { state, change: null }\n : {\n state: POPUP_CLOSED,\n change: { open: false, reason: action.reason },\n };\n case \"toggle\":\n return popupReducer(\n state,\n state.kind === \"open\"\n ? { type: \"close\", reason: \"button\" }\n : { type: \"open\", reason: \"button\" },\n );\n }\n}\n","import type {\n AssembleContext,\n PartChange,\n PartTexts,\n PartValues,\n} from \"../field/createCompositeController\";\nimport { parsed, unreadable, type ParseResult } from \"../parse\";\nimport {\n orderRange,\n rangeSpan,\n shownEnd,\n type NoFlags,\n type Range,\n type RangeBounds,\n type RangeEnd,\n type RangeKind,\n type RangeOptions,\n} from \"./range\";\n\n/** The parts of a range input: its two ends, each a value of `T`. */\nexport type RangeEnds<T> = { start: T; end: T };\n\n/** What every range input adds to its events. */\nexport interface RangeDetails<\n T,\n F extends object = NoFlags,\n S = number,\n R = never,\n> {\n /**\n * The end this event is about: the end typed in; `\"both\"` for a value\n * set whole (`setValue`, a controlled value, a revert or clear); on a\n * commit, the end that differs from the last commit (`\"both\"` when both\n * do, `null` when neither does).\n */\n readonly changedEnd: RangeEnd | \"both\" | null;\n /** The ends the value stands for now: the value itself, or its rule resolved. `null` when empty. */\n readonly resolved: Range<T, F> | null;\n /** From start to end; `null` while an end is open or the field is empty. */\n readonly span: S | null;\n readonly bounds: RangeBounds;\n /** Each end's text as shown. */\n readonly startText: string;\n readonly endText: string;\n /** The rule, when the value is one. */\n readonly rule: R | null;\n}\n\n/**\n * The range two ends as shown make, for a range input's `assemble`:\n * `orderRange` with its refusals as `messages.rangeReversed` and\n * `messages.rangeEmpty`, and both ends empty as `null`.\n */\nexport function readRangeEnds<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n ends: PartValues<RangeEnds<T>>,\n options: RangeOptions<S>,\n context: C,\n { messages }: AssembleContext,\n): ParseResult<Range<T, F>> {\n const reading = orderRange(kind, ends.start, ends.end, options, context);\n switch (reading.kind) {\n case \"none\":\n return parsed(null);\n case \"range\":\n return parsed(reading.range);\n case \"unreadable\":\n return unreadable(\n reading.reason === \"reversed\"\n ? messages.rangeReversed\n : messages.rangeEmpty,\n );\n }\n}\n\n/** The ends a range input shows for `range`, for its `split`: the end through `toShownEnd` when half-open. */\nexport function rangeEnds<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n range: Range<T, F> | null,\n bounds: RangeBounds,\n context: C,\n): PartValues<RangeEnds<T>> {\n return range === null\n ? { start: null, end: null }\n : { start: range.start, end: shownEnd(kind, range, bounds, context) };\n}\n\n/** What a range input's events carry, from its value and its ends' texts. */\nexport function rangeDetails<T, F extends object, S, C, R = never>(\n kind: RangeKind<T, F, S, C, R>,\n resolved: Range<T, F> | null,\n changed: PartChange<RangeEnds<T>>,\n texts: PartTexts<RangeEnds<T>>,\n bounds: RangeBounds,\n context: C,\n rule: R | null = null,\n): RangeDetails<T, F, S, R> {\n return {\n changedEnd: changed === \"all\" ? \"both\" : changed,\n resolved,\n span: resolved === null ? null : rangeSpan(kind, resolved, context),\n bounds,\n startText: texts.start,\n endText: texts.end,\n rule,\n };\n}\n","import type { FieldMessageInput } from \"../messages/fieldMessage\";\nimport type {\n ValidationResult,\n Validator,\n ValidatorContext,\n} from \"../validation/validators\";\nimport { rangeSpan, type Range, type RangeKind } from \"./range\";\n\n/** Writes a span for a message: \"10\", \"14 days\". */\nexport type SpanFormatter<S> = (span: S, context: ValidatorContext) => string;\n\n/**\n * A range shorter than `minSpan`, measured by the kind, is\n * `messages.rangeTooShort`, with `minSpan` written by `formatSpan`.\n * `context` gives the kind's context when the rule runs. A range with an\n * open end, and `null`, pass.\n */\nexport function minSpanRule<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n minSpan: S,\n context: () => C,\n formatSpan: SpanFormatter<S>,\n): Validator<Range<T, F>> {\n return (range, validator) => {\n const span = range === null ? null : rangeSpan(kind, range, context());\n return span !== null && kind.compareSpans(span, minSpan) < 0\n ? {\n text: validator.messages.rangeTooShort(\n formatSpan(minSpan, validator),\n ),\n code: \"rangeTooShort\",\n }\n : null;\n };\n}\n\n/** A range longer than `maxSpan` is `messages.rangeTooLong`; otherwise as `minSpanRule`. */\nexport function maxSpanRule<T, F extends object, S, C, R>(\n kind: RangeKind<T, F, S, C, R>,\n maxSpan: S,\n context: () => C,\n formatSpan: SpanFormatter<S>,\n): Validator<Range<T, F>> {\n return (range, validator) => {\n const span = range === null ? null : rangeSpan(kind, range, context());\n return span !== null && kind.compareSpans(span, maxSpan) > 0\n ? {\n text: validator.messages.rangeTooLong(formatSpan(maxSpan, validator)),\n code: \"rangeTooLong\",\n }\n : null;\n };\n}\n\n// `Array.isArray` does not narrow a readonly array, hence the guard.\nfunction isList(\n result: FieldMessageInput | readonly FieldMessageInput[],\n): result is readonly FieldMessageInput[] {\n return Array.isArray(result);\n}\n\nfunction asList(result: ValidationResult): readonly FieldMessageInput[] {\n if (result === null || result === undefined) {\n return [];\n }\n return isList(result) ? result : [result];\n}\n\nfunction textOf(message: FieldMessageInput): string {\n return typeof message === \"string\" ? message : message.text;\n}\n\n/**\n * Runs `rule`, a check of one value, on each present end of a range: a\n * number range's `min` and `max` bound both ends. A message both ends\n * earn is given once. Open ends and `null` pass.\n */\nexport function endsRule<T, F extends object>(\n rule: Validator<T>,\n): Validator<Range<T, F>> {\n return (range, context) => {\n if (range === null) {\n return null;\n }\n const messages: FieldMessageInput[] = [];\n for (const end of [range.start, range.end]) {\n if (end === null) {\n continue;\n }\n for (const message of asList(rule(end, context))) {\n if (!messages.some((held) => textOf(held) === textOf(message))) {\n messages.push(message);\n }\n }\n }\n return messages;\n };\n}\n","import { sortFieldMessages, type FieldMessage } from \"./messages/fieldMessage\";\nimport { severityRank, type Severity } from \"./messages/severity\";\n\n/** What a form knows of one of its fields: enough to list its messages. */\nexport interface RegisteredField {\n /** Unique in the form: the id of the element a message links to. */\n readonly id: string;\n /** The messages the field shows, in its own order. */\n readonly messages: readonly FieldMessage[];\n}\n\n/**\n * The fields of one form, for a summary of their messages, and the fields'\n * ways to reveal their messages, for a submit attempt. A renderer creates\n * one per form; fields register and unregister themselves.\n */\nexport interface FieldRegistry<F extends RegisteredField> {\n /**\n * Adds `field`, in place of a field registered under the same id, and\n * returns what removes it again.\n */\n readonly register: (field: F) => () => void;\n /**\n * Adds what shows one field's messages, as a commit attempt would, and\n * returns what removes it again.\n */\n readonly addRevealer: (reveal: () => void) => () => void;\n /** Shows every field's messages, as a submit attempt does. */\n readonly revealAll: () => void;\n /**\n * Every registered field, in the order the registry was created with.\n * The same array until a field registers or unregisters.\n */\n readonly getFields: () => readonly F[];\n /** Calls `listener` whenever the fields change, and returns what stops it. */\n readonly subscribe: (listener: () => void) => () => void;\n}\n\n/**\n * A registry of a form's fields, listed in `order`, or in the order they\n * registered without one. A renderer passes its fields' place in the page,\n * which forms-core cannot see.\n */\nexport function createFieldRegistry<F extends RegisteredField>(\n order?: (a: F, b: F) => number,\n): FieldRegistry<F> {\n const fields = new Map<string, F>();\n const revealers = new Set<() => void>();\n const listeners = new Set<() => void>();\n let listed: readonly F[] | null = null;\n\n function changed(): void {\n listed = null;\n for (const listener of [...listeners]) {\n listener();\n }\n }\n\n return {\n register(field) {\n fields.set(field.id, field);\n changed();\n return () => {\n if (fields.get(field.id) === field) {\n fields.delete(field.id);\n changed();\n }\n };\n },\n addRevealer(reveal) {\n revealers.add(reveal);\n return () => {\n revealers.delete(reveal);\n };\n },\n revealAll() {\n for (const reveal of [...revealers]) {\n reveal();\n }\n },\n getFields() {\n if (listed === null) {\n const all = [...fields.values()];\n listed = order === undefined ? all : all.sort(order);\n }\n return listed;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/** One line of a message summary: a message and the field showing it. */\nexport interface SummaryItem<F extends RegisteredField> {\n readonly field: F;\n readonly message: FieldMessage;\n}\n\n/** How many messages of one severity a summary lists. */\nexport interface SeverityCount {\n readonly severity: Severity;\n readonly count: number;\n}\n\n/** What a message summary lists. */\nexport interface MessageSummary<F extends RegisteredField> {\n /** Field by field in their order, each field's most serious first. */\n readonly items: readonly SummaryItem<F>[];\n /** Most serious first, leaving out a severity with none. */\n readonly counts: readonly SeverityCount[];\n}\n\n/** The messages of `fields` whose severity is one of `severities`, with their counts. */\nexport function summarizeMessages<F extends RegisteredField>(\n fields: readonly F[],\n severities: readonly Severity[],\n): MessageSummary<F> {\n const wanted = new Set(severities);\n const items = fields.flatMap((field) =>\n sortFieldMessages(field.messages)\n .filter((message) => wanted.has(message.severity))\n .map((message) => ({ field, message })),\n );\n const counts = new Map<Severity, number>();\n for (const { message } of items) {\n counts.set(message.severity, (counts.get(message.severity) ?? 0) + 1);\n }\n return {\n items,\n counts: [...counts]\n .map(([severity, count]) => ({ severity, count }))\n .sort((a, b) => severityRank(a.severity) - severityRank(b.severity)),\n };\n}\n","/**\n * One entry per row: its measured height once known, `undefined` until then.\n * A row never yet rendered (or rendered but not yet observed) falls back to\n * `visibleRange`'s own `estimatedHeight` argument.\n */\nexport type RowHeights = readonly (number | undefined)[];\n\nexport interface VisibleRange {\n readonly startIndex: number;\n readonly endIndex: number; // inclusive\n /** Total height of every row before `startIndex` — the leading spacer's height. */\n readonly offsetBefore: number;\n /** Total height of every row after `endIndex` — the trailing spacer's height. */\n readonly offsetAfter: number;\n}\n\n/**\n * Which rows of a dynamic-height, virtualized list fall within\n * `[scrollTop, scrollTop + viewportHeight)`, padded by `overscan` rows on\n * each side and clamped to the array's own bounds.\n *\n * Walks a cumulative-offset prefix sum built from `heights` (measured height\n * where known, `estimatedHeight` otherwise) rather than assuming a uniform\n * row height — a grid's rows are not uniform (`.is-wrapped` cells, group\n * header/summary rows), so a fixed-height virtualizer would either break\n * wrapping or force it out of scope.\n *\n * `O(n)` in `heights.length`. Deliberately not a Fenwick tree or a\n * binary-searchable prefix-sum structure — that optimization belongs in the\n * mutable height cache that already owns mutability (`createRowVirtualizer`\n * in `@gridkitjs/forms-dom`), not in this pure function's contract, and is not\n * worth taking on until a profiled scenario actually shows it matters at\n * realistic row counts.\n */\nexport function visibleRange(\n heights: RowHeights,\n estimatedHeight: number,\n scrollTop: number,\n viewportHeight: number,\n overscan: number,\n): VisibleRange {\n const rowCount = heights.length;\n if (rowCount === 0) {\n return { startIndex: 0, endIndex: -1, offsetBefore: 0, offsetAfter: 0 };\n }\n\n function heightAt(index: number): number {\n return heights[index] ?? estimatedHeight;\n }\n\n const viewportBottom = scrollTop + viewportHeight;\n\n // The first row whose bottom edge crosses `scrollTop` — everything before\n // it is fully scrolled past. `top` tracks that row's own top edge (the\n // cumulative height of every row before it) as the walk advances. Stops at\n // the last row rather than walking off the end when `scrollTop` reaches or\n // exceeds the total height.\n let start = 0;\n let top = 0;\n while (start < rowCount - 1 && top + heightAt(start) <= scrollTop) {\n top += heightAt(start);\n start += 1;\n }\n const startTop = top;\n\n // From `start`, the last row whose top edge is still above `viewportBottom`\n // — the first row no longer even partially visible ends the walk one row\n // earlier than it, or the array itself runs out first. `bottom` tracks the\n // current row's own bottom edge.\n let end = start;\n let bottom = startTop + heightAt(start);\n while (end < rowCount - 1 && bottom < viewportBottom) {\n end += 1;\n bottom += heightAt(end);\n }\n\n const overscanStart = Math.max(0, start - overscan);\n const overscanEnd = Math.min(rowCount - 1, end + overscan);\n\n let offsetBefore = 0;\n for (let index = 0; index < overscanStart; index++) {\n offsetBefore += heightAt(index);\n }\n let offsetAfter = 0;\n for (let index = overscanEnd + 1; index < rowCount; index++) {\n offsetAfter += heightAt(index);\n }\n\n return {\n startIndex: overscanStart,\n endIndex: overscanEnd,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EACxE;AAEA,WAAS,SAAS,OAAuB;AACvC,WAAO,QAAQ,KAAK,KAAK;AAAA,EAC3B;AAEA,QAAM,iBAAiB,YAAY;AAOnC,MAAI,QAAQ;AACZ,MAAI,MAAM;AACV,SAAO,QAAQ,WAAW,KAAK,MAAM,SAAS,KAAK,KAAK,WAAW;AACjE,WAAO,SAAS,KAAK;AACrB,aAAS;AAAA,EACX;AACA,QAAM,WAAW;AAMjB,MAAI,MAAM;AACV,MAAI,SAAS,WAAW,SAAS,KAAK;AACtC,SAAO,MAAM,WAAW,KAAK,SAAS,gBAAgB;AACpD,WAAO;AACP,cAAU,SAAS,GAAG;AAAA,EACxB;AAEA,QAAM,gBAAgB,KAAK,IAAI,GAAG,QAAQ,QAAQ;AAClD,QAAM,cAAc,KAAK,IAAI,WAAW,GAAG,MAAM,QAAQ;AAEzD,MAAI,eAAe;AACnB,WAAS,QAAQ,GAAG,QAAQ,eAAe,SAAS;AAClD,oBAAgB,SAAS,KAAK;AAAA,EAChC;AACA,MAAI,cAAc;AAClB,WAAS,QAAQ,cAAc,GAAG,QAAQ,UAAU,SAAS;AAC3D,mBAAe,SAAS,KAAK;AAAA,EAC/B;AAEA,SAAO;AAAA,IACL,YAAY;AAAA,IACZ,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACF;","names":["next","chosen","groups","fields","offset","step","entry","cache","next","next","monthIndex","offset","dayNumber","year","_","dayNumber","offset","chosen","digit","values","index","next","offset","groups","word","DAY_MS","offset","pad","candidates","example","offset","rangeOf","times","next","step","written","place","offset","yearOf","canonical","layoutFor","example","anchored","IDLE","entry","segmentOf","digit","fits","digits","letter","candidates","offset","isPeriod","DAY_MS","stepOf","startOf","step","entry","unreadable","UNREADABLE","values","value","next","read","next","step","API","next","values","DIGIT","cache","EMPTY","next","accepted","next","read","digit","groups","offset","step","example","read","step","offset","groups","digit","formats","intlOptions","written","FULL_WIDTH","SPACES","groups","escapeRegExp","ARABIC_DECIMAL","groups","digit","EMPTY","unreadableBecause","groups","digit","ALLOW","PREVENT","SIGNS","MINUS_SIGNS","groups","group","text","offset","index","digit","sign","integerText","written","clamp","step","unreadableMessage","readingOf","step","next","step","isList","textOf","reveal"]}
|