{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "core-date",
  "type": "registry:lib",
  "title": "core/date",
  "description": "Framework-free behaviour shared by the ui-* components (date); no DOM, no lit. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/core/date.ts",
      "type": "registry:lib",
      "target": "components/ui/core/date.ts",
      "content": "/**\n * Dates for the date picker and calendar, framework-free: parsing / formatting with the Thai\n * Buddhist Era, the month grid, keyboard moves, min / max, ranges and validation. Dates are local\n * calendar days (no time zones); ISO `yyyy-mm-dd` strings compare in date order.\n */\n\nexport type DateFormat = 'dd/mm/yyyy' | 'mm/dd/yyyy' | 'yyyy-mm-dd';\n\n/** `ce` = Gregorian (ค.ศ.), `be` = Thai Buddhist Era (พ.ศ. = ค.ศ. + 543). */\nexport type Era = 'ce' | 'be';\n\nexport const BE_OFFSET = 543;\n\n/** Smallest year we accept as พ.ศ. — anything lower was almost certainly typed as ค.ศ. by mistake. */\nexport const MIN_BE_YEAR = 2400;\n\nconst pad = (n: number, len = 2) => String(n).padStart(len, '0');\n\nexport const toIso = (d: Date) => `${pad(d.getFullYear(), 4)}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;\n\n/** Local date; `setFullYear` keeps years < 100 from mapping to 19xx. */\nfunction localDate(y: number, m: number, d: number) {\n    const date = new Date(y, m - 1, d);\n    date.setFullYear(y);\n    return date;\n}\n\n/** Returns null for impossible dates such as 31/02. */\nexport function makeDate(y: number, m: number, d: number): Date | null {\n    const date = localDate(y, m, d);\n    return date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d ? date : null;\n}\n\nexport const fromIso = (iso: string): Date | null => {\n    const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(iso);\n    return m ? makeDate(+m[1], +m[2], +m[3]) : null;\n};\n\nexport const addDays = (d: Date, n: number) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);\n\n/** Same day in another month, clamped to that month's length (31 Jan + 1 month → 28/29 Feb). */\nexport function addMonths(d: Date, n: number) {\n    const last = new Date(d.getFullYear(), d.getMonth() + n + 1, 0).getDate();\n    return new Date(d.getFullYear(), d.getMonth() + n, Math.min(d.getDate(), last));\n}\n\n/** Same day/month in another (Gregorian) year, clamped for 29 Feb. */\nexport const withYear = (d: Date, year: number) => addMonths(d, (year - d.getFullYear()) * 12);\n\nexport const sameDay = (a: Date | null, b: Date | null) => !!a && !!b && toIso(a) === toIso(b);\n\nexport const toDisplayYear = (year: number, era: Era) => (era === 'be' ? year + BE_OFFSET : year);\n\nexport const fromDisplayYear = (year: number, era: Era) => (era === 'be' ? year - BE_OFFSET : year);\n\nexport function formatDate(d: Date, format: DateFormat, era: Era) {\n    const dd = pad(d.getDate());\n    const mm = pad(d.getMonth() + 1);\n    const yyyy = pad(toDisplayYear(d.getFullYear(), era), 4);\n    if (format === 'mm/dd/yyyy') return `${mm}/${dd}/${yyyy}`;\n    if (format === 'yyyy-mm-dd') return `${yyyy}-${mm}-${dd}`;\n    return `${dd}/${mm}/${yyyy}`;\n}\n\nexport type ParseResult = { date: Date } | { error: 'era' | 'unparseable' | 'incomplete' | 'impossible' };\n\ntype Token = 'd' | 'm' | 'Y';\n\n/** flatpickr's token patterns: one or two digits for day/month, exactly four for the year. */\nconst TOKEN_REGEX: Record<Token, string> = { d: String.raw`(\\d\\d|\\d)`, m: String.raw`(\\d\\d|\\d)`, Y: String.raw`(\\d{4})` };\n\nfunction tokenOrder(format: DateFormat): Token[] {\n    if (format === 'yyyy-mm-dd') return ['Y', 'm', 'd'];\n    if (format === 'mm/dd/yyyy') return ['m', 'd', 'Y'];\n    return ['d', 'm', 'Y'];\n}\n\n/**\n * Port of flatpickr's `createDateParser` (what Carbon's date picker runs on blur / Enter):\n * tokens are matched one at a time with a growing, unanchored regex in which every separator is\n * \"any character\", so text around and between the numbers is ignored (`s10/12/2026sdsd` → 10/12/2026).\n * Unlike flatpickr, all three parts must be present (`incomplete`) and must name a real day\n * (`impossible` for 31/04 or month 13) instead of being filled in or rolled over — the\n * Angular Material / MUI / GOV.UK \"must be a real date\" behaviour.\n */\nexport function parseDate(text: string, format: DateFormat, era: Era): ParseResult {\n    const order = tokenOrder(format);\n    const found = new Map<Token, number>();\n    let regexStr = '';\n    order.forEach((token, i) => {\n        regexStr += (i === 0 ? '' : '.') + TOKEN_REGEX[token];\n        const match = new RegExp(regexStr).exec(text);\n        if (match) found.set(token, Number(match[i + 1]));\n    });\n    if (found.size === 0) return { error: 'unparseable' };\n    if (found.size < order.length) return { error: 'incomplete' };\n    const displayYear = found.get('Y') as number;\n    if (era === 'be' && displayYear < MIN_BE_YEAR) return { error: 'era' };\n    const date = makeDate(fromDisplayYear(displayYear, era), found.get('m') as number, found.get('d') as number);\n    return date ? { date } : { error: 'impossible' };\n}\n\nconst THAI_ZERO = 0x0e50;\n\n/** Thai digits ๐–๙ become 0–9; everything else is untouched. */\nexport const normalizeDigits = (text: string) =>\n    text.replace(/[๐-๙]/g, (c) => String((c.codePointAt(0) ?? 0) - THAI_ZERO));\n\n/** A time box's text as its `pattern` reads it: Thai digits as 0–9 and no leading space (a paste often brings one). */\nexport const normalizeTimeText = (text: string) => normalizeDigits(text).replace(/^\\s+/, '');\n\n// ---- locale rules (strings live in core/translations/*.ts) ----\n\n/** Thai locales default to พ.ศ. and narrow weekday names; this is a locale rule, not a translation. */\nexport const isThai = (locale: string) => locale.toLowerCase().startsWith('th');\n\n// ---- limits: min / max / disabled days ----\n\n/** A picker's constraints: ISO `min` / `max` ('' or absent = none) and a per-day rule (true, or a reason, refuses the day). */\nexport interface DateLimits {\n    min?: string;\n    max?: string;\n    isDateDisabled?: (date: Date) => boolean | string;\n}\n\n/** Before `min` or after `max`. */\nexport function isOutOfRange(d: Date, { min, max }: DateLimits): boolean {\n    const iso = toIso(d);\n    return (!!min && iso < min) || (!!max && iso > max);\n}\n\n/** Out of range or refused by `isDateDisabled`: can't be picked. */\nexport function isUnavailable(d: Date, limits: DateLimits): boolean {\n    return isOutOfRange(d, limits) || !!limits.isDateDisabled?.(d);\n}\n\n/** `d` moved inside `min` / `max` (an unreadable limit is ignored). */\nexport function clampDate(d: Date, { min = '', max = '' }: DateLimits): Date {\n    const lo = fromIso(min);\n    const hi = fromIso(max);\n    if (lo && toIso(d) < min) return lo;\n    if (hi && toIso(d) > max) return hi;\n    return d;\n}\n\n// ---- month grid and keyboard (APG date picker dialog, flatpickr) ----\n\n/** The first day of `d`'s week, weeks starting on `firstDay` (0 = Sunday … 6 = Saturday). */\nexport const weekStart = (d: Date, firstDay: number) => addDays(d, -((d.getDay() - firstDay + 7) % 7));\n\n/** The month of `focus` as a fixed grid of 6 weeks × 7 days, filled with the neighbouring months' days. */\nexport function monthGrid(focus: Date, firstDay: number): Date[][] {\n    const start = weekStart(new Date(focus.getFullYear(), focus.getMonth(), 1), firstDay);\n    return Array.from({ length: 6 }, (_, w) => Array.from({ length: 7 }, (_, d) => addDays(start, w * 7 + d)));\n}\n\n/**\n * Where a key moves the focused day: ←/→ a day, ↑/↓ a week, Home / End the week's start / end,\n * Page Up / Down a month (with Shift a year). Undefined for any other key.\n */\nexport function moveByKey(focus: Date, key: string, shift: boolean, firstDay: number, rtl = false): Date | undefined {\n    switch (key) {\n        case 'ArrowLeft':\n            return addDays(focus, rtl ? 1 : -1); // right to left, the day before is on the right (Cally)\n        case 'ArrowRight':\n            return addDays(focus, rtl ? -1 : 1);\n        case 'ArrowUp':\n            return addDays(focus, -7);\n        case 'ArrowDown':\n            return addDays(focus, 7);\n        case 'Home':\n            return weekStart(focus, firstDay);\n        case 'End':\n            return addDays(weekStart(focus, firstDay), 6);\n        case 'PageUp':\n            return addMonths(focus, shift ? -12 : -1);\n        case 'PageDown':\n            return addMonths(focus, shift ? 12 : 1);\n        default:\n            return undefined;\n    }\n}\n\n/**\n * The first month on show when `count` months show from `start` and focus moves to `focus` (Cally's pagination): the\n * same page while focus is on it; focus one month past either edge turns it by `step` (`count`, Cally page-by=\"months\",\n * or 1 for \"single\"); further away it moves in whole pages, so the page keeps its months (a year on: the same months).\n * Twelve months paged by the page show a calendar year, from January. With one month it is always focus's month.\n */\nexport function pageStartFor(focus: Date, start: Date | undefined, count: number, step = count): Date {\n    const year = (d: Date) => (count === 12 && step === 12 ? new Date(d.getFullYear(), 0, 1) : d);\n    if (!start) return year(new Date(focus.getFullYear(), focus.getMonth(), 1));\n    const offset = (focus.getFullYear() - start.getFullYear()) * 12 + focus.getMonth() - start.getMonth();\n    if (offset >= 0 && offset < count) return start;\n    if (offset === -1) return year(addMonths(start, -step));\n    if (offset === count) return year(addMonths(start, step));\n    return year(addMonths(start, Math.floor(offset / count) * count));\n}\n\n/** Months a calendar shows side by side: `n` as a whole number from 1 to 12 (Cally: any; a year view is twelve). */\nexport const calendarMonths = (n: number) => Math.max(1, Math.min(12, Math.trunc(n) || 1));\n\n/** ‹ › turn the page itself by `by` months; a focused day left off the page moves to the same day in its first month (Cally). */\nexport function turnPage(focus: Date, start: Date, count: number, by: number): { start: Date; focus: Date } {\n    const next = addMonths(start, by);\n    const offset = (focus.getFullYear() - next.getFullYear()) * 12 + focus.getMonth() - next.getMonth();\n    return { start: next, focus: offset >= 0 && offset < count ? focus : addMonths(focus, -offset) };\n}\n\n/** The ISO week number of `d` (Monday weeks; the week with the year's first Thursday is week 1), as Cally's week numbers. */\nexport function isoWeek(d: Date): number {\n    const day = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));\n    day.setUTCDate(day.getUTCDate() + 3 - ((day.getUTCDay() + 6) % 7)); // the Thursday of its week decides the year\n    const week1 = new Date(Date.UTC(day.getUTCFullYear(), 0, 4)); // 4 January is always in week 1\n    return 1 + Math.round(((day.getTime() - week1.getTime()) / 86_400_000 - 3 + ((week1.getUTCDay() + 6) % 7)) / 7);\n}\n\n/** The previous / next month buttons are off when that whole month lies outside `min` / `max`. */\nexport function monthNavDisabled(focus: Date, { min = '', max = '' }: DateLimits): { previous: boolean; next: boolean } {\n    const lastOfPrevious = new Date(focus.getFullYear(), focus.getMonth(), 0);\n    const firstOfNext = new Date(focus.getFullYear(), focus.getMonth() + 1, 1);\n    return {\n        previous: !!fromIso(min) && toIso(lastOfPrevious) < min,\n        next: !!fromIso(max) && toIso(firstOfNext) > max,\n    };\n}\n\n/** The month select's choices in `focus`'s year (Cally `calendar-select-month`): 0–11, off when that whole month lies outside `min` / `max`. */\nexport function monthChoices(focus: Date, { min = '', max = '' }: DateLimits): { month: number; disabled: boolean }[] {\n    return Array.from({ length: 12 }, (_, month) => {\n        const first = toIso(new Date(focus.getFullYear(), month, 1));\n        const last = toIso(new Date(focus.getFullYear(), month + 1, 0));\n        return { month, disabled: (!!fromIso(min) && last < min) || (!!fromIso(max) && first > max) };\n    });\n}\n\n/** The year select's (Gregorian) years (Cally `calendar-select-year`): `maxYears` around `focus`'s year, cut to the years `min` / `max` allow. */\nexport function yearChoices(focus: Date, maxYears: number, { min = '', max = '' }: DateLimits): number[] {\n    const count = Math.max(1, Math.trunc(maxYears) || 1);\n    const year = focus.getFullYear();\n    const half = Math.floor(count / 2);\n    const lo = Math.max(year - half, fromIso(min)?.getFullYear() ?? -Infinity);\n    const hi = Math.min(year + count - half - 1, fromIso(max)?.getFullYear() ?? Infinity);\n    return Array.from({ length: Math.max(0, hi - lo + 1) }, (_, i) => lo + i);\n}\n\n/** The years `min` / `max` allow, as shown in `era`. */\nexport function yearBounds({ min = '', max = '' }: DateLimits, era: Era): { min?: number; max?: number } {\n    const lo = fromIso(min);\n    const hi = fromIso(max);\n    return { min: lo ? toDisplayYear(lo.getFullYear(), era) : undefined, max: hi ? toDisplayYear(hi.getFullYear(), era) : undefined };\n}\n\n/** A year typed in the year box, once it is four digits (and a plausible พ.ศ. year in `be`); undefined while partial. */\nexport function typedYear(text: string, era: Era): number | undefined {\n    if (!/^\\d{4}$/.test(text)) return undefined;\n    const year = Number(text);\n    return era === 'be' && year < MIN_BE_YEAR ? undefined : year;\n}\n\n// ---- ranges (flatpickr range mode) ----\n\n/** Which end of a range a pick sets. */\nexport type RangeField = 'start' | 'end';\n\n/**\n * The end to highlight: the chosen end, else — while the end is being picked — the provisional\n * day under the pointer or focus when it is after the start (flatpickr's preview); '' for none.\n */\nexport function displayedRangeEnd(start: string, end: string, active: RangeField, preview: string): string {\n    if (end || active !== 'end') return end;\n    return preview > start ? preview : '';\n}\n\n/**\n * The range to draw (ISO): the chosen one, or while the end is being picked the start and the previewed day (`preview`,\n * under the pointer or the keyboard focus) in order, so a day before the start previews too (Cally).\n */\nexport function shownRange(start: string, end: string, active: RangeField, preview: string): { start: string; end: string } {\n    if (end || active !== 'end' || !start || !preview) return { start, end };\n    return preview < start ? { start: preview, end: start } : { start, end: preview };\n}\n\n/** A day's place in the range `start`…`end` (ISO). */\nexport function rangePosition(iso: string, start: string, end: string): { start: boolean; end: boolean; inside: boolean } {\n    if (!start || !end) return { start: false, end: false, inside: false };\n    return { start: iso === start, end: iso === end, inside: iso > start && iso < end };\n}\n\n/** The range after a pick, and whether picking is done (close the calendar). */\nexport interface RangePick {\n    start: string;\n    end: string;\n    active: RangeField;\n    done: boolean;\n}\n\n/**\n * Range rules for a pick of `iso`: with a whole range chosen, a pick starts a new one (Cally); a pick for the start keeps\n * the calendar open for the end (and drops an end that is now before it); a pick for the end that falls before the\n * start swaps the two.\n */\nexport function pickInRange(range: { start: string; end: string; active: RangeField }, iso: string): RangePick {\n    const { start, end, active } = range;\n    if (start && end) return { start: iso, end: '', active: 'end', done: false };\n    if (active === 'start' || !start) {\n        const keptEnd = end && end < iso ? '' : end;\n        return keptEnd ? { start: iso, end: keptEnd, active, done: true } : { start: iso, end: '', active: 'end', done: false };\n    }\n    if (iso < start) return { start: iso, end: start, active, done: true };\n    return { start, end: iso, active, done: true };\n}\n\n/**\n * Carbon's focus-plugin for Tab inside the open calendar: Shift+Tab returns to the last text box;\n * Tab goes to the end box while the start was the last one (range); otherwise focus goes back to\n * the last box and the browser's Tab carries on out of the picker (`leave`: close the calendar).\n */\nexport function calendarTab(shift: boolean, range: boolean, lastField: RangeField): { focus: RangeField; leave: boolean } {\n    if (shift) return { focus: lastField, leave: false };\n    if (range && lastField === 'start') return { focus: 'end', leave: false };\n    return { focus: lastField, leave: true };\n}\n\n// ---- validation ----\n\n/** What is wrong with a date field, in the order a user would fix it; the UI words it. */\nexport type DateProblem =\n    | { kind: 'parse'; error: 'era' | 'unparseable' | 'incomplete' | 'impossible' }\n    | { kind: 'required' }\n    | { kind: 'min' }\n    | { kind: 'max' }\n    | { kind: 'disabled'; reason?: string }\n    | { kind: 'endBeforeStart' };\n\n/**\n * The first problem of one field: unreadable text, a missing required value, before `min`, after\n * `max`, a day `isDateDisabled` refuses (its string is the reason), or (for a range's end) before\n * `start`. Null when the field is fine.\n */\nexport function checkDateField(field: { text: string; value: string; required?: boolean; start?: string; format: DateFormat; era: Era }, limits: DateLimits): DateProblem | null {\n    if (field.text.trim() !== '') {\n        const parsed = parseDate(field.text, field.format, field.era);\n        if ('error' in parsed) return { kind: 'parse', error: parsed.error };\n    }\n    const { value } = field;\n    if (field.required && !value) return { kind: 'required' };\n    const date = fromIso(value);\n    if (!date) return null;\n    if (fromIso(limits.min ?? '') && value < (limits.min ?? '')) return { kind: 'min' };\n    if (fromIso(limits.max ?? '') && value > (limits.max ?? '')) return { kind: 'max' };\n    const reason = limits.isDateDisabled?.(date);\n    if (reason) return typeof reason === 'string' ? { kind: 'disabled', reason } : { kind: 'disabled' };\n    if (field.start && value < field.start) return { kind: 'endBeforeStart' };\n    return null;\n}\n"
    }
  ]
}
