{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dates",
  "title": "Dates",
  "description": "Every date calculation in one place: yyyy-mm-dd dates and yyyy-mm months, adding days and months, weeks and month grids, today in a time zone, the locale's first weekday and names, and the matchers and limits for days that can't be picked.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "files": [
    {
      "path": "registry/lib/dates.ts",
      "content": "import * as plain from '@ui-sdk/core/date'\nimport { useSyncExternalStore } from 'react'\n\n/*\n * Every date calculation Kino makes, in one place: plain dates as\n * `yyyy-mm-dd` and months as `yyyy-mm`, with no time and no time zone, so a\n * date means the same day everywhere. The arithmetic runs in UTC, where no\n * day is ever 23 or 25 hours long; only `today` looks at a time zone. Names\n * and labels come from `Intl`, in any language, on the Gregorian calendar.\n * Pure, so every component that works with dates shares it and it is tested\n * without a DOM.\n */\n\n/** A day of the week, as JavaScript counts it: 0 is Sunday, 6 is Saturday. */\nexport type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6\n\n/** A date as its parts; a part not known yet is null, as while it is typed. */\nexport interface DateFields {\n  year: number | null\n  month: number | null\n  day: number | null\n}\n\nexport const EMPTY_DATE: DateFields = { year: null, month: null, day: null }\n\nconst ISO_MONTH = /^(\\d{4})-(\\d{2})$/\n\nconst pad = (value: number, length: number) => String(value).padStart(length, '0')\n\n/** How many days `month` (1 to 12) has, in a leap year when the year isn't known yet. */\nexport function daysInMonth(month: number, year: number | null): number {\n  // 2000 was a leap year.\n  return plain.daysInMonth(year ?? 2000, month)\n}\n\n/** The date as `yyyy-mm-dd`, or null until every part holds a day that exists, from year 1 to 9999. */\nexport function toISODate(fields: DateFields): string | null {\n  const { year, month, day } = fields\n  if (year === null || month === null || day === null) return null\n  return plain.isoDate(year, month, day) ?? null\n}\n\n/** The parts of a `yyyy-mm-dd` date, or all empty when it isn't a day that exists. */\nexport function fromISODate(value: string | null | undefined): DateFields {\n  return plain.dateParts(value) ?? EMPTY_DATE\n}\n\n/** Whether `value` is a `yyyy-mm-dd` day that exists. */\nexport function isISODate(value: unknown): value is string {\n  return plain.isISODate(value)\n}\n\n/** Whether `value` is a `yyyy-mm` month, from 0001-01 to 9999-12. */\nexport function isISOMonth(value: unknown): value is string {\n  if (typeof value !== 'string') return false\n  const match = ISO_MONTH.exec(value)\n  return (\n    match !== null &&\n    Number(match[1]) >= 1 &&\n    Number(match[2]) >= 1 &&\n    Number(match[2]) <= 12\n  )\n}\n\n/** The date `count` days after `date` (before, when negative), held between years 1 and 9999. */\nexport function addDays(value: string, count: number): string {\n  return plain.addDays(value, count)\n}\n\n/** How many days from `from` to `to`: 1 for the next day, -1 for the day before. */\nexport function daysBetween(from: string, to: string): number {\n  return plain.daysBetween(from, to)\n}\n\n/** Its day of the week. */\nexport function weekday(value: string): Weekday {\n  return plain.weekday(value) as Weekday\n}\n\n/** The month a date is in, as `yyyy-mm`. */\nexport function monthOf(value: string): string {\n  return value.slice(0, 7)\n}\n\n/** A `yyyy-mm` month as its year and its number, 1 to 12. */\nexport function monthParts(month: string): { year: number; month: number } {\n  if (!isISOMonth(month)) throw new RangeError(`Not a yyyy-mm month: ${String(month)}`)\n  return { year: Number(month.slice(0, 4)), month: Number(month.slice(5, 7)) }\n}\n\n/** The month `count` months after `month` (before, when negative), held between 0001-01 and 9999-12. */\nexport function shiftMonth(month: string, count: number): string {\n  return monthOf(plain.addMonths(firstOfMonth(month), count))\n}\n\n/** How many months from `from` to `to`, both `yyyy-mm`: 1 for the next month. */\nexport function monthsBetween(from: string, to: string): number {\n  const a = monthParts(from)\n  const b = monthParts(to)\n  return (b.year - a.year) * 12 + (b.month - a.month)\n}\n\n/** The same day `count` months on, or that month's last day when it is shorter: 31 January and a month is 28 or 29 February. */\nexport function addMonths(value: string, count: number): string {\n  return plain.addMonths(value, count)\n}\n\n/** The same day `count` years on; 29 February becomes 28 February outside a leap year. */\nexport function addYears(value: string, count: number): string {\n  return plain.addYears(value, count)\n}\n\n/** The first day of a `yyyy-mm` month. */\nexport function firstOfMonth(month: string): string {\n  monthParts(month)\n  return `${month}-01`\n}\n\n/** The last day of a `yyyy-mm` month: 28 February 2026, 29 February 2028. */\nexport function lastOfMonth(month: string): string {\n  return plain.endOfMonth(firstOfMonth(month))\n}\n\n/** The first day of the week `date` is in, for weeks that start on `first`. */\nexport function startOfWeek(value: string, first: Weekday): string {\n  return plain.startOfWeek(value, first)\n}\n\n/** The last day of the week `date` is in, for weeks that start on `first`. */\nexport function endOfWeek(value: string, first: Weekday): string {\n  return plain.endOfWeek(value, first)\n}\n\n/**\n * The number of the week `date` is in, for weeks that start on `first`. A\n * week starting on Monday is numbered as ISO 8601 does: week 1 holds the\n * year's first Thursday. Any other week is numbered as in the United States:\n * week 1 holds 1 January.\n */\nexport function weekOfYear(value: string, first: Weekday): number {\n  // How many of a week's days must fall in a year for it to be that year's.\n  const fewest = first === 1 ? 4 : 1\n  const start = startOfWeek(value, first)\n  const year = fromISODate(addDays(start, 7 - fewest)).year ?? 1\n  const opening = startOfWeek(`${pad(year, 4)}-01-01`, first)\n  const firstWeek =\n    fromISODate(addDays(opening, 7 - fewest)).year === year\n      ? opening\n      : addDays(opening, 7)\n  return daysBetween(firstWeek, start) / 7 + 1\n}\n\n/**\n * The weeks a month shows, each seven dates from `first`, with the days of\n * the months either side that share its first and last week. With\n * `fixedWeeks`, always six, so every month is as tall as the next.\n */\nexport function monthGrid(\n  month: string,\n  first: Weekday,\n  { fixedWeeks = false }: { fixedWeeks?: boolean } = {},\n): string[][] {\n  return plain.monthGrid(firstOfMonth(month), { weekStartsOn: first, fixedWeeks })\n}\n\n/** The date moved inside `min` and `max`, either of which may be missing. */\nexport function clampDate(\n  value: string,\n  min?: string | null,\n  max?: string | null,\n): string {\n  return plain.clampDate(value, min, max)\n}\n\nconst zoneFormats = new Map<string, Intl.DateTimeFormat>()\n\n/**\n * The formatter that reads an instant's date or time of day in `timeZone`,\n * made once per zone: a list of notifications reads hundreds of instants.\n */\nfunction zoneFormatter(part: 'date' | 'time', timeZone: string | undefined) {\n  const key = `${part}|${timeZone ?? ''}`\n  let format = zoneFormats.get(key)\n  if (!format) {\n    format = new Intl.DateTimeFormat(\n      'en-US',\n      part === 'date'\n        ? {\n            timeZone,\n            calendar: 'gregory',\n            numberingSystem: 'latn',\n            year: 'numeric',\n            month: '2-digit',\n            day: '2-digit',\n          }\n        : {\n            timeZone,\n            numberingSystem: 'latn',\n            hour: '2-digit',\n            minute: '2-digit',\n            second: '2-digit',\n            hourCycle: 'h23',\n          },\n    )\n    zoneFormats.set(key, format)\n  }\n  return format\n}\n\n/**\n * Today's date in `timeZone` (the visitor's own by default) at the instant\n * `now`, in milliseconds. Near midnight, two zones disagree: it is already\n * tomorrow in Auckland while it is still today in Honolulu.\n */\nexport function today(timeZone?: string, now: number = Date.now()): string {\n  const parts = zoneFormatter('date', timeZone).formatToParts(now)\n  const value = (type: string) => Number(parts.find((part) => part.type === type)?.value)\n  return `${pad(value('year'), 4)}-${pad(value('month'), 2)}-${pad(value('day'), 2)}`\n}\n\n/**\n * The date `days` days before today in the visitor's own time zone, as\n * `addDays(today(), -days)` gives it, written to be inlined in a script that\n * runs before the first paint, such as the consent script's check of a\n * saved choice: it references nothing outside itself.\n */\nexport function daysAgoInline(days: number): string {\n  const day = new Date()\n  day.setDate(day.getDate() - days)\n  return [\n    String(day.getFullYear()).padStart(4, '0'),\n    String(day.getMonth() + 1).padStart(2, '0'),\n    String(day.getDate()).padStart(2, '0'),\n  ].join('-')\n}\n\n/** The browser's own locale, which a field uses when it is given none. */\nexport function browserLocale(): string {\n  return new Intl.DateTimeFormat().resolvedOptions().locale\n}\n\n/** The browser's locale never changes while the page is open. */\nconst noChange = () => () => {}\n\n/** Today in `timeZone`; null while the server renders, which can't know the visitor's day. */\nexport function useToday(timeZone?: string): string | null {\n  return useSyncExternalStore(\n    noChange,\n    () => today(timeZone),\n    () => null,\n  )\n}\n\n/*\n * The time now, a minute at a time, shared by everything that shows how long\n * ago something was. On the server, and before hydration, there is none, so a\n * time is never written twice.\n */\nlet minute = 0\n\nfunction watchMinutes(change: () => void) {\n  const tick = () => {\n    minute = Date.now()\n    change()\n  }\n  tick()\n  const timer = setInterval(tick, 60_000)\n  return () => clearInterval(timer)\n}\n\n/** The time now in epoch ms, a minute at a time; null while the server renders, which can't know it. */\nexport function useNow(): number | null {\n  return useSyncExternalStore(\n    watchMinutes,\n    () => minute || null,\n    () => null,\n  )\n}\n\n/** How the locale writes an empty date to type, such as `DD/MM/YYYY` or `MM/DD/YYYY`. */\nexport function datePlaceholder(locale?: string): string {\n  return plain.datePattern(locale).placeholder\n}\n\n/**\n * The locale a field uses: the one given, else the browser's. The server\n * can't know the browser's, so it renders en-US and the field moves to the\n * visitor's right after hydration, keeping its value, rather than failing\n * to hydrate where their clock or date order differs.\n */\nexport function useLocale(locale: string | undefined): string {\n  const browser = useSyncExternalStore(noChange, browserLocale, () => 'en-US')\n  return locale ?? browser\n}\n\n// Regions whose week doesn't start on Monday (CLDR 48's weekData), for\n// engines without `Intl.Locale`'s week info, such as Firefox. A test walks\n// every region and compares this with the engine's own.\nconst SUNDAY_REGIONS = new Set(\n  'AG AS BD BR BS BT BW BZ CA CO DM DO ET GT GU HK HN ID IL IN IS 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_REGIONS = new Set('AF BH DJ DZ EG IQ IR JO KW LY OM QA SD SY'.split(' '))\nconst FRIDAY_REGIONS = new Set(['MV'])\n\nconst FW_DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']\n\n/** Where an engine keeps a locale's week: a method in most, a property in older Chromium and Safari. */\ntype WeekInfoLocale = Intl.Locale & {\n  getWeekInfo?: () => { firstDay?: number }\n  weekInfo?: { firstDay?: number }\n}\n\n/**\n * The day `locale`'s week starts on, from the tables above, for engines\n * without `Intl.Locale`'s week info: a `-u-fw-` extension's day, else its\n * region's.\n */\nexport function tableWeekStart(locale: string): Weekday {\n  const tag = new Intl.Locale(locale)\n  const named = /-u(?:-[a-z0-9]{2,8})*?-fw-([a-z]{3})(?:-|$)/i.exec(tag.toString())?.[1]\n  const day = FW_DAYS.indexOf(named?.toLowerCase() ?? '')\n  if (day >= 0) return day as Weekday\n  const region = tag.maximize().region ?? ''\n  if (SUNDAY_REGIONS.has(region)) return 0\n  if (SATURDAY_REGIONS.has(region)) return 6\n  if (FRIDAY_REGIONS.has(region)) return 5\n  return 1\n}\n\n/**\n * The day `locale`'s week starts on: Monday in en-GB, Sunday in en-US,\n * Saturday in ar-EG, or the day a `-u-fw-` extension names.\n */\nexport function weekStart(locale?: string): Weekday {\n  let tag: WeekInfoLocale\n  try {\n    tag = new Intl.Locale(locale ?? browserLocale())\n  } catch {\n    return 1\n  }\n  // 1 is Monday and 7 is Sunday here.\n  const first = (tag.getWeekInfo?.() ?? tag.weekInfo)?.firstDay\n  if (first !== undefined && first >= 1 && first <= 7) return (first % 7) as Weekday\n  return tableWeekStart(tag.toString())\n}\n\nconst formats = new Map<string, Intl.DateTimeFormat>()\n\nfunction formatter(locale: string | undefined, options: Intl.DateTimeFormatOptions) {\n  const key = `${locale ?? ''}|${JSON.stringify(options)}`\n  let format = formats.get(key)\n  if (!format) {\n    format = new Intl.DateTimeFormat(locale, {\n      ...options,\n      calendar: 'gregory',\n      timeZone: 'UTC',\n    })\n    formats.set(key, format)\n  }\n  return format\n}\n\n/**\n * The instant that formats in UTC as a date (its midnight), or as a date and\n * time (`yyyy-mm-ddTHH:mm` or `yyyy-mm-ddTHH:mm:ss`).\n */\nfunction instant(value: string): number {\n  const { date, time } = splitDateTime(value)\n  if (date === null) throw new RangeError(`Not a date: ${value}`)\n  const parts = time === null ? null : timeParts(time)\n  const seconds = parts ? parts.hours * 3600 + parts.minutes * 60 + parts.seconds : 0\n  const { year, month, day } = fromISODate(date)\n  // `Date.UTC` reads years 0 to 99 as 1900 to 1999.\n  const at = new Date(0)\n  at.setUTCFullYear(year ?? 1, (month ?? 1) - 1, day ?? 1)\n  return at.getTime() + seconds * 1000\n}\n\n/**\n * A date as `locale` writes it with `options` (`dateStyle: 'full'`: Friday\n * 27 November 2026), always the same day. Given a date and time\n * (`yyyy-mm-ddTHH:mm`), `options` can write its time too.\n */\nexport function formatDate(\n  date: string,\n  locale: string | undefined,\n  options: Omit<Intl.DateTimeFormatOptions, 'timeZone'>,\n): string {\n  return formatter(locale, options).format(instant(date))\n}\n\n/** Two dates as `locale` writes a span of days, sharing what they have in common: 2–8 Nov 2026, 28 Nov – 3 Dec 2026. */\nexport function formatDateRange(\n  start: string,\n  end: string,\n  locale: string | undefined,\n  options: Omit<Intl.DateTimeFormatOptions, 'timeZone'>,\n): string {\n  // Newer CLDR puts thin spaces around the dash, and a browser and Node seldom\n  // share a version: plain spaces, so a page's server and browser agree.\n  return formatter(locale, options)\n    .formatRange(instant(start), instant(end))\n    .replace(/[\\u2009\\u202f]–[\\u2009\\u202f]/g, ' – ')\n}\n\n/** The parts of a formatted date, as `Intl.DateTimeFormat.formatToParts` gives them. */\nexport function formatDateToParts(\n  date: string,\n  locale: string | undefined,\n  options: Omit<Intl.DateTimeFormatOptions, 'timeZone'>,\n): Intl.DateTimeFormatPart[] {\n  return formatter(locale, options).formatToParts(instant(date))\n}\n\n/**\n * The months' names in `locale`, January first: `short` (Nov) or `long`\n * (November), as they are written inside a whole date, so Japanese gives 11\n * beside its 月.\n */\nexport function monthNames(locale?: string, width: 'short' | 'long' = 'short'): string[] {\n  return Array.from(\n    { length: 12 },\n    (_, index) =>\n      formatDateToParts(`2000-${pad(index + 1, 2)}-01`, locale, {\n        year: 'numeric',\n        month: width,\n        day: '2-digit',\n        numberingSystem: 'latn',\n      }).find((part) => part.type === 'month')?.value ?? String(index + 1),\n  )\n}\n\n/** The week's days in the order the calendar shows them, from `first`. */\nexport function weekdayNames(\n  locale: string | undefined,\n  first: Weekday,\n  width: 'narrow' | 'short' | 'long' = 'short',\n): string[] {\n  // 2023-01-01 was a Sunday.\n  return Array.from({ length: 7 }, (_, index) =>\n    formatDate(`2023-01-0${((first + index) % 7) + 1}`, locale, {\n      weekday: width,\n    }),\n  )\n}\n\n/** A month as its heading reads: November 2026, or Nov 2026 with `short`. */\nexport function monthLabel(\n  month: string,\n  locale?: string,\n  width: 'long' | 'short' | 'narrow' = 'long',\n): string {\n  return formatDate(`${month}-01`, locale, {\n    month: width,\n    year: 'numeric',\n    numberingSystem: 'latn',\n  })\n}\n\n/** A day's number as a calendar's grid shows it: 7, in the same Latin digits as the Date input. */\nexport function dayLabel(date: string, locale?: string): string {\n  return formatDate(date, locale, { day: 'numeric', numberingSystem: 'latn' })\n}\n\n/** A year as `locale` writes it on its own, in Latin digits: 2026, or 2026年. */\nexport function yearLabel(year: number, locale?: string): string {\n  return formatDate(`${yearMonth(year, 1)}-01`, locale, {\n    year: 'numeric',\n    numberingSystem: 'latn',\n  })\n}\n\n/** A month's short or long name on its own, as a picker of months shows it: Nov, or November. */\nexport function monthName(\n  month: string,\n  locale?: string,\n  width: 'short' | 'long' = 'short',\n): string {\n  return formatDate(`${month}-01`, locale, { month: width })\n}\n\n/** The `yyyy-mm` month of `year` numbered `month`, 1 to 12. */\nexport function yearMonth(year: number, month: number): string {\n  const value = `${pad(year, 4)}-${pad(month, 2)}`\n  if (!isISOMonth(value)) throw new RangeError(`Not a month: ${year}, ${month}`)\n  return value\n}\n\n/** The first of the `size` years a page of years shows around `year`, pages starting at year 1: 2017 for 2026 in twelves. */\nexport function yearPage(year: number, size: number): number {\n  return year - ((((year - 1) % size) + size) % size)\n}\n\n/**\n * Dates that can't be picked, as data or a function: a `yyyy-mm-dd` date,\n * `{ from, to }` for the days between two, both included, `{ weekday: [0, 6] }`\n * for weekends, `{ before }` and `{ after }` (the day itself not included), a\n * function, or a list of any of these.\n */\nexport type DateMatcher =\n  | string\n  | { from: string; to: string }\n  | { weekday: readonly Weekday[] }\n  | { before: string }\n  | { after: string }\n  | ((date: string) => boolean)\n\nexport type DateMatchers = DateMatcher | readonly DateMatcher[]\n\n/** Whether `date` is one of the dates `matchers` name. */\nexport function matchesDate(\n  date: string,\n  matchers: DateMatchers | null | undefined,\n): boolean {\n  if (!matchers) return false\n  const list: readonly DateMatcher[] = Array.isArray(matchers) ? matchers : [matchers]\n  return list.some((matcher) => {\n    if (typeof matcher === 'string') return date === matcher\n    if (typeof matcher === 'function') return matcher(date)\n    if ('from' in matcher) return date >= matcher.from && date <= matcher.to\n    if ('weekday' in matcher) return matcher.weekday.includes(weekday(date))\n    if ('before' in matcher) return date < matcher.before\n    return date > matcher.after\n  })\n}\n\n/** A range of days, start first, both included. */\nexport type DateRange = readonly [start: string, end: string]\n\n/** What a range must keep to. Lengths count both ends: a day to itself is 1 day. */\nexport interface RangeRules {\n  minDays?: number\n  maxDays?: number\n  /** Lets a range hold unavailable days, which still can't be its ends. */\n  allowUnavailable?: boolean\n  unavailable?: DateMatchers | null\n}\n\n/** The range from two days picked in either order. */\nexport function orderRange(a: string, b: string): DateRange {\n  return a <= b ? [a, b] : [b, a]\n}\n\n/** How many days a range covers, both ends included. */\nexport function rangeLength([start, end]: DateRange): number {\n  return daysBetween(start, end) + 1\n}\n\n/** Whether a range keeps to `rules`. */\nexport function isAllowedRange(range: DateRange, rules: RangeRules): boolean {\n  const [start, end] = range\n  if (start > end) return false\n  const length = rangeLength(range)\n  if (rules.minDays !== undefined && length < rules.minDays) return false\n  if (rules.maxDays !== undefined && length > rules.maxDays) return false\n  if (matchesDate(start, rules.unavailable) || matchesDate(end, rules.unavailable))\n    return false\n  if (!rules.allowUnavailable && rules.unavailable) {\n    for (let day = addDays(start, 1); day < end; day = addDays(day, 1)) {\n      if (matchesDate(day, rules.unavailable)) return false\n    }\n  }\n  return true\n}\n\n/*\n * Years, months and days as one kind of value, and times beside them. A\n * value is as fine as its granularity: a year is `yyyy`, a month `yyyy-mm`,\n * a day `yyyy-mm-dd`, and anything finer is a date and a time,\n * `yyyy-mm-ddTHH:mm` or `yyyy-mm-ddTHH:mm:ss`, as a native\n * `datetime-local` input gives it. Times are wall-clock times with no time\n * zone, as dates are: 09:30 is 09:30 wherever it is read.\n */\n\n/** The smallest unit a date holds: a year (`yyyy`), a month (`yyyy-mm`) or a day (`yyyy-mm-dd`). */\nexport type DateGranularity = 'year' | 'month' | 'day'\n\n/** The smallest unit a time holds: `HH:00`, `HH:mm` or `HH:mm:ss`. */\nexport type TimeGranularity = 'hour' | 'minute' | 'second'\n\n/** The smallest unit a value holds, from a year to a second. Finer than a day, it is a date and a time. */\nexport type Granularity = DateGranularity | TimeGranularity\n\nconst ISO_YEAR = /^\\d{4}$/\n\n/** Whether `value` is a `yyyy` year, from 0001 to 9999. */\nexport function isISOYear(value: unknown): value is string {\n  return typeof value === 'string' && ISO_YEAR.test(value) && Number(value) >= 1\n}\n\n/** The date part of a granularity: a day for anything finer, whose time is held apart. */\nexport function dateGranularity(granularity: Granularity): DateGranularity {\n  return granularity === 'year' || granularity === 'month' ? granularity : 'day'\n}\n\n/** The time part of a granularity, or null for a year, a month or a day, which hold no time. */\nexport function timeGranularity(granularity: Granularity): TimeGranularity | null {\n  return granularity === 'hour' || granularity === 'minute' || granularity === 'second'\n    ? granularity\n    : null\n}\n\n/**\n * A date's parts as a value of `granularity`: 2026, 2026-11 or 2026-11-14.\n * Null until it holds the parts that granularity needs, and parts that\n * exist; the parts finer than it don't count.\n */\nexport function toDateValue(\n  fields: DateFields,\n  granularity: DateGranularity,\n): string | null {\n  if (granularity === 'day') return toISODate(fields)\n  const { year, month } = fields\n  if (year === null || year < 1 || year > 9999) return null\n  if (granularity === 'year') return pad(year, 4)\n  if (month === null || month < 1 || month > 12) return null\n  return yearMonth(year, month)\n}\n\n/** The parts of a `yyyy`, `yyyy-mm` or `yyyy-mm-dd` value; the parts it doesn't hold, or all of them when it isn't one, are null. */\nexport function fromDateValue(value: string | null | undefined): DateFields {\n  if (isISOYear(value)) return { year: Number(value), month: null, day: null }\n  if (isISOMonth(value)) {\n    const { year, month } = monthParts(value)\n    return { year, month, day: null }\n  }\n  return fromISODate(value)\n}\n\n/** The granularity a date value is written in, or null when it isn't a year, a month or a day. */\nexport function granularityOf(value: unknown): DateGranularity | null {\n  if (isISOYear(value)) return 'year'\n  if (isISOMonth(value)) return 'month'\n  return isISODate(value) ? 'day' : null\n}\n\n/**\n * The first and last days a year, a month or a day covers: 2028 runs from\n * 2028-01-01 to 2028-12-31, and 2028-02 from 2028-02-01 to 2028-02-29.\n * Null when `value` isn't one of the three.\n */\nexport function dateSpan(value: string): DateRange | null {\n  if (isISOYear(value)) return [`${value}-01-01`, `${value}-12-31`]\n  if (isISOMonth(value)) return [firstOfMonth(value), lastOfMonth(value)]\n  return isISODate(value) ? [value, value] : null\n}\n\nconst ISO_TIME = /^(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?$/\n\n/** The hours, minutes and seconds of an `HH:mm` or `HH:mm:ss` time, or null when it isn't one. */\nexport function timeParts(\n  value: string | null | undefined,\n): { hours: number; minutes: number; seconds: number } | null {\n  const match = value ? ISO_TIME.exec(value) : null\n  if (!match) return null\n  const [hours, minutes, seconds] = [match[1], match[2], match[3] ?? '0'].map(Number)\n  if (hours > 23 || minutes > 59 || seconds > 59) return null\n  return { hours, minutes, seconds }\n}\n\n/** Whether `value` is an `HH:mm` or `HH:mm:ss` time of day. */\nexport function isISOTime(value: unknown): value is string {\n  return typeof value === 'string' && timeParts(value) !== null\n}\n\n/**\n * A time of day as a value of `granularity`: `HH:mm`, with `second`\n * `HH:mm:ss`, and with `hour` `HH:00`, its minutes left at the hour.\n */\nexport function timeValue(\n  hours: number,\n  minutes: number,\n  seconds: number,\n  granularity: TimeGranularity = 'minute',\n): string | null {\n  if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null\n  if (seconds < 0 || seconds > 59) return null\n  const time = `${pad(hours, 2)}:${pad(granularity === 'hour' ? 0 : minutes, 2)}`\n  return granularity === 'second' ? `${time}:${pad(seconds, 2)}` : time\n}\n\n/** A time in seconds since midnight, or null when it isn't one. */\nfunction secondsOf(value: string): number | null {\n  const time = timeParts(value)\n  return time ? time.hours * 3600 + time.minutes * 60 + time.seconds : null\n}\n\n/**\n * Whether a time falls outside `min` and `max`, each `HH:mm` or `HH:mm:ss`.\n * A `min` later than `max` runs over midnight, as a native time input's\n * does: 22:00 to 06:00 is the night.\n */\nexport function timeOutOfRange(\n  value: string | null,\n  min?: string,\n  max?: string,\n): boolean {\n  const time = value === null ? null : secondsOf(value)\n  if (time === null) return false\n  const from = min === undefined ? null : secondsOf(min)\n  const to = max === undefined ? null : secondsOf(max)\n  if (from !== null && to !== null && from > to) return time < from && time > to\n  return (from !== null && time < from) || (to !== null && time > to)\n}\n\n/** The time it is now in `timeZone` (the visitor's own by default) as `HH:mm:ss`, at `now` in milliseconds. */\nexport function currentTime(timeZone?: string, now: number = Date.now()): string {\n  const parts = zoneFormatter('time', timeZone).formatToParts(now)\n  const value = (type: string) => Number(parts.find((part) => part.type === type)?.value)\n  return `${pad(value('hour'), 2)}:${pad(value('minute'), 2)}:${pad(value('second'), 2)}`\n}\n\n/** A clock of 12 hours with AM and PM, or of 24. */\nexport type HourCycle = 12 | 24\n\n/** The clock `locale` tells the time by: 12 hours in en-US, 24 in de-DE. */\nexport function localeHourCycle(locale?: string): HourCycle {\n  const cycle = new Intl.DateTimeFormat(locale, {\n    hour: 'numeric',\n  }).resolvedOptions().hourCycle\n  return cycle === 'h11' || cycle === 'h12' ? 12 : 24\n}\n\n/** What `locale` calls the morning and the afternoon on a 12-hour clock: AM and PM, 午前 and 午後. */\nexport function dayPeriodNames(locale?: string): [string, string] {\n  const name = (time: string, fallback: string) =>\n    formatDateToParts(`2000-01-01T${time}`, locale, {\n      hour: 'numeric',\n      hourCycle: 'h12',\n    }).find((part) => part.type === 'dayPeriod')?.value ?? fallback\n  return [name('01:00', 'AM'), name('13:00', 'PM')]\n}\n\n/** How `locale` writes an `HH:mm` or `HH:mm:ss` time on `hourCycle`: 9:00 AM, 09:00. Its seconds show when it has any. */\nexport function formatTime(\n  value: string,\n  locale: string | undefined,\n  hourCycle: HourCycle,\n): string {\n  const time = timeParts(value)\n  if (!time) return value\n  return formatDate(`2000-01-01T${value}`, locale, {\n    hour: 'numeric',\n    minute: '2-digit',\n    ...(time.seconds ? { second: '2-digit' } : {}),\n    hourCycle: hourCycle === 12 ? 'h12' : 'h23',\n  })\n}\n\n/**\n * A date and time's two halves: `2026-11-14T09:30` is the day and the time.\n * Either half can be missing while it is entered (`2026-11-14T` has no time\n * yet, `T09:30` no day); a plain date has no time. A half that isn't a day\n * or a time is null.\n */\nexport function splitDateTime(value: string | null | undefined): {\n  date: string | null\n  time: string | null\n} {\n  if (!value) return { date: null, time: null }\n  const at = value.indexOf('T')\n  const date = at === -1 ? value : value.slice(0, at)\n  const time = at === -1 ? '' : value.slice(at + 1)\n  return {\n    date: isISODate(date) ? date : null,\n    time: isISOTime(time) ? time : null,\n  }\n}\n\n/**\n * A day and a time as one value, `yyyy-mm-ddTHH:mm`. With one half missing,\n * the half that is in, marked as half (`2026-11-14T` or `T09:30`); null with\n * neither.\n */\nexport function joinDateTime(date: string | null, time: string | null): string | null {\n  if (date === null && time === null) return null\n  return `${date ?? ''}T${time ?? ''}`\n}\n\n/** Whether `value` holds both a day and a time, `yyyy-mm-ddTHH:mm` or `yyyy-mm-ddTHH:mm:ss`. */\nexport function isISODateTime(value: string | null | undefined): boolean {\n  if (!value?.includes('T')) return false\n  const { date, time } = splitDateTime(value)\n  return date !== null && time !== null\n}\n\n/**\n * A value of any granularity as `locale` writes it: 2026, November 2026,\n * 14 Nov 2026, or 14 Nov 2026, 09:30 with its time, and its seconds when\n * it has any. Null when it isn't\n * one. `hourCycle` sets the clock; the locale's by default.\n */\nexport function formatValue(\n  value: string,\n  locale: string | undefined,\n  hourCycle?: HourCycle,\n): string | null {\n  if (isISOYear(value)) return yearLabel(Number(value), locale)\n  if (isISOMonth(value)) return monthLabel(value, locale)\n  if (isISODate(value)) return formatDate(value, locale, { dateStyle: 'medium' })\n  if (!isISODateTime(value)) return null\n  const seconds = timeParts(splitDateTime(value).time)?.seconds\n  return formatDate(value, locale, {\n    dateStyle: 'medium',\n    timeStyle: seconds ? 'medium' : 'short',\n    ...(hourCycle ? { hourCycle: hourCycle === 12 ? 'h12' : 'h23' } : {}),\n  })\n}\n\n/** A value's first and last moments, as text that sorts in time: a year's, month's or day's first and last seconds, or a date and time's own. */\nfunction momentsOf(value: string): [string, string] | null {\n  if (isISODateTime(value)) {\n    const { date, time } = splitDateTime(value)\n    const parts = timeParts(time)\n    if (!parts || date === null) return null\n    const at = `${date}T${timeValue(parts.hours, parts.minutes, parts.seconds, 'second')}`\n    return [at, at]\n  }\n  const span = dateSpan(value)\n  return span && [`${span[0]}T00:00:00`, `${span[1]}T23:59:59`]\n}\n\n/**\n * Whether a value falls wholly before `min` or after `max`. Each can be a\n * year, a month, a day or a date and time, and they needn't match: a month\n * is in range while any of its days is, and a date and time is in range on\n * the day `max` names. A value that isn't whole is never out of range.\n */\nexport function outsideBounds(\n  value: string | null,\n  min?: string | null,\n  max?: string | null,\n): boolean {\n  const own = value === null ? null : momentsOf(value)\n  if (!own) return false\n  const low = min ? momentsOf(min) : null\n  const high = max ? momentsOf(max) : null\n  return (low !== null && own[1] < low[0]) || (high !== null && own[0] > high[1])\n}\n\n/**\n * The first (`start`) or last (`end`) day a bound of any granularity\n * allows: 2026 starts on 2026-01-01 and ends on 2026-12-31, and a date and\n * time allows its own day. Undefined when it isn't a year, a month, a day or\n * a date and time.\n */\nexport function boundDay(\n  value: string | null | undefined,\n  side: 'start' | 'end',\n): string | undefined {\n  if (!value) return undefined\n  const day = splitDateTime(value).date\n  const span = isISODateTime(value) && day ? dateSpan(day) : dateSpan(value)\n  return span ? span[side === 'start' ? 0 : 1] : undefined\n}\n\n/*\n * Instants: a moment, such as when a notification was sent, written as an\n * ISO instant (`2026-11-17T09:42:00Z`) or as milliseconds. They are read\n * on the wall clock of a time zone, the visitor's own by default.\n */\n\n/** An instant in milliseconds. */\nfunction instantTime(instant: string | number): number {\n  const time = typeof instant === 'number' ? instant : Date.parse(instant)\n  if (Number.isNaN(time)) throw new RangeError(`Not an instant: ${instant}`)\n  return time\n}\n\n/** A moment in milliseconds as an ISO instant: `2026-11-17T09:42:00.000Z`. */\nexport function isoInstant(time: number): string {\n  return new Date(instantTime(time)).toISOString()\n}\n\n/** Which of two instants comes first, for sorting: negative when `a` does. */\nexport function compareInstants(a: string | number, b: string | number): number {\n  return instantTime(a) - instantTime(b)\n}\n\n/** An instant as the wall clock in `timeZone` reads it: `2026-11-17T09:42:00`. */\nexport function wallClock(instant: string | number, timeZone?: string): string {\n  const time = instantTime(instant)\n  return `${today(timeZone, time)}T${currentTime(timeZone, time)}`\n}\n\n/**\n * The instant `timeZone`'s wall clock reads as `dateTime` (`yyyy-mm-ddTHH:mm`):\n * 10:00 on 3 December in Los Angeles is 18:00 UTC. A time the clock skips\n * when it goes forward lands an hour on; one it reads twice when it goes\n * back is the second.\n */\nexport function zonedInstant(dateTime: string, timeZone?: string): number {\n  const wanted = instant(dateTime)\n  // The zone's offset at a guess, then again at the answer, which differs\n  // from the guess only across a change of the clocks.\n  let at = wanted\n  for (let pass = 0; pass < 2; pass++)\n    at = wanted - (instant(wallClock(at, timeZone)) - at)\n  return at\n}\n\nconst relativeFormats = new Map<string, Intl.RelativeTimeFormat>()\n\n/** Words for a time before or after now, as `locale` writes them, made once each. */\nfunction relativeFormatter(locale: string | undefined, style: 'long' | 'narrow') {\n  const key = `${locale ?? ''}|${style}`\n  let format = relativeFormats.get(key)\n  if (!format) {\n    format = new Intl.RelativeTimeFormat(locale, { style, numeric: 'auto' })\n    relativeFormats.set(key, format)\n  }\n  return format\n}\n\n/** The first letter as `locale` writes it at the start of a heading: yesterday becomes Yesterday. */\nfunction capitalise(text: string, locale: string | undefined): string {\n  return text.charAt(0).toLocaleUpperCase(locale) + text.slice(1)\n}\n\n/**\n * A day as a list of what happened heads it, seen from `now` (both\n * `yyyy-mm-dd`): Today, Yesterday, the weekday for the rest of the last\n * week, then the date, with its year once it isn't this year's. A day after\n * `now`, from a clock that runs ahead, is Today.\n */\nexport function dayHeading(date: string, now: string, locale?: string): string {\n  const ago = daysBetween(date, now)\n  if (ago <= 1) {\n    const words = relativeFormatter(locale, 'long')\n    return capitalise(words.format(-Math.max(0, ago), 'day'), locale)\n  }\n  if (ago < 7) return capitalise(formatDate(date, locale, { weekday: 'long' }), locale)\n  return formatDate(date, locale, {\n    day: 'numeric',\n    month: 'short',\n    ...(date.slice(0, 4) === now.slice(0, 4) ? {} : { year: 'numeric' }),\n  })\n}\n\n/**\n * A day near `now` as a sentence writes it (both `yyyy-mm-dd`): yesterday,\n * today or tomorrow in `locale`'s words, and null for any other day, which\n * reads better as its date.\n */\nexport function nearDay(date: string, now: string, locale?: string): string | null {\n  const ahead = -daysBetween(date, now)\n  if (Math.abs(ahead) > 1) return null\n  return relativeFormatter(locale, 'long').format(ahead, 'day')\n}\n\n/**\n * How long ago `instant` was at `now`, in a word or two: now, 5m ago, 2h ago,\n * as `locale` writes it narrow. Null once it was a day or more ago, when a\n * clock time reads better.\n */\nexport function timeAgo(\n  instant: string | number,\n  now: number,\n  locale?: string,\n): string | null {\n  const seconds = Math.max(0, (now - instantTime(instant)) / 1000)\n  const words = relativeFormatter(locale, 'narrow')\n  if (seconds < 60) return words.format(0, 'second')\n  if (seconds < 3600) return words.format(-Math.floor(seconds / 60), 'minute')\n  if (seconds < 86_400) return words.format(-Math.floor(seconds / 3600), 'hour')\n  return null\n}\n\n/** The time of day `instant` falls on in `timeZone`, as `locale` tells it: 2:05 PM, 14:05. */\nexport function clockTime(\n  instant: string | number,\n  locale?: string,\n  timeZone?: string,\n): string {\n  const time = wallClock(instant, timeZone).slice(11, 16)\n  return formatTime(time, locale, localeHourCycle(locale))\n}\n\n/** `instant` in full on `timeZone`'s wall clock: 17 Nov 2026, 09:42. */\nexport function instantLabel(\n  instant: string | number,\n  locale?: string,\n  timeZone?: string,\n): string {\n  return formatDate(wallClock(instant, timeZone).slice(0, 16), locale, {\n    dateStyle: 'medium',\n    timeStyle: 'short',\n  })\n}\n\n/*\n * Times along a chart's axis. A time is an instant in milliseconds, read\n * once from what the data holds. A calendar value (`yyyy-mm-dd`, `yyyy-mm`,\n * or a date and time with no zone) means the same day and hour everywhere,\n * so it is read on a UTC calendar, where no day is 23 or 25 hours long, and\n * written there. An instant (an ISO string with `Z` or an offset, a `Date`,\n * or milliseconds) is one moment, written on the wall clock of a time zone.\n * Ticks fall on that clock's boundaries: midnights, firsts of the month,\n * whole hours, and are placed at the instant they fall on, so a day the\n * clock changes is as long as it really is.\n */\n\n/** A calendar unit a time can fall on, coarsest last. */\nexport type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'\n\n/** A time read from data: its instant in ms, and whether it was a moment rather than a calendar value. */\nexport interface ReadTime {\n  time: number\n  instant: boolean\n}\n\nconst ZONED = /(?:Z|[+-]\\d{2}:?\\d{2})$/i\nconst SECOND_MS = 1000\nconst MINUTE_MS = 60_000\nconst HOUR_MS = 3_600_000\n\n/**\n * The time `value` holds, or null when it holds none: a `yyyy-mm-dd` day or a\n * `yyyy-mm` month at its first midnight, a `yyyy-mm-ddTHH:mm[:ss]` date and\n * time, each on a UTC calendar; an ISO instant with `Z` or an offset, a\n * valid `Date`, or a finite number of milliseconds, each a moment.\n */\nexport function readTime(value: unknown): ReadTime | null {\n  if (typeof value === 'number')\n    return Number.isFinite(value) ? { time: value, instant: true } : null\n  if (value instanceof Date) {\n    const time = value.getTime()\n    return Number.isNaN(time) ? null : { time, instant: true }\n  }\n  if (typeof value !== 'string') return null\n  const text: string = value\n  const day = text.slice(0, 10)\n  if (isISOMonth(text)) return { time: instant(firstOfMonth(text)), instant: false }\n  if (isISODate(text)) return { time: instant(text), instant: false }\n  if (ZONED.test(text)) {\n    const time = Date.parse(text)\n    return Number.isNaN(time) || !isISODate(day) ? null : { time, instant: true }\n  }\n  const { date, time } = splitDateTime(text)\n  if (date === null || time === null) return null\n  const parts = timeParts(time)\n  if (!parts) return null\n  return { time: instant(`${date}T${time.slice(0, 8)}`), instant: false }\n}\n\n/** A time's fields on the wall clock of a zone. */\ninterface WallFields {\n  year: number\n  month: number\n  day: number\n  hour: number\n  minute: number\n  second: number\n}\n\nconst wallFormats = new Map<string, Intl.DateTimeFormat>()\n\n/** `time`'s fields on `timeZone`'s wall clock; on UTC's, worked out with no formatter. */\nfunction wallFields(time: number, timeZone: string): WallFields {\n  if (timeZone === 'UTC') {\n    const at = new Date(time)\n    return {\n      year: at.getUTCFullYear(),\n      month: at.getUTCMonth() + 1,\n      day: at.getUTCDate(),\n      hour: at.getUTCHours(),\n      minute: at.getUTCMinutes(),\n      second: at.getUTCSeconds(),\n    }\n  }\n  let format = wallFormats.get(timeZone)\n  if (!format) {\n    format = new Intl.DateTimeFormat('en-US', {\n      timeZone,\n      calendar: 'gregory',\n      numberingSystem: 'latn',\n      year: 'numeric',\n      month: 'numeric',\n      day: 'numeric',\n      hour: 'numeric',\n      minute: 'numeric',\n      second: 'numeric',\n      hourCycle: 'h23',\n    })\n    wallFormats.set(timeZone, format)\n  }\n  const fields: Record<string, number> = {}\n  for (const part of format.formatToParts(time)) fields[part.type] = Number(part.value)\n  return {\n    year: fields.year ?? 1970,\n    month: fields.month ?? 1,\n    day: fields.day ?? 1,\n    // Some engines write midnight as 24 even with `h23`.\n    hour: (fields.hour ?? 0) % 24,\n    minute: fields.minute ?? 0,\n    second: fields.second ?? 0,\n  }\n}\n\n/** The wall clock `fields` names, as milliseconds on a UTC calendar. */\nfunction wallTime({ year, month, day, hour, minute, second }: WallFields): number {\n  const at = new Date(0)\n  at.setUTCFullYear(year, month - 1, day)\n  at.setUTCHours(hour, minute, second, 0)\n  return at.getTime()\n}\n\n/** How far `timeZone`'s wall clock is ahead of UTC at `time`, in ms. */\nfunction zoneOffset(time: number, timeZone: string): number {\n  if (timeZone === 'UTC') return 0\n  const whole = Math.floor(time / SECOND_MS) * SECOND_MS\n  return wallTime(wallFields(whole, timeZone)) - whole\n}\n\n/**\n * The instant `timeZone`'s wall clock shows `fields`. A time the clock skips\n * as it springs forward lands just after the change; one it shows twice as\n * it falls back is the first.\n */\nfunction zonedTime(fields: WallFields, timeZone: string): number {\n  const wall = wallTime(fields)\n  if (timeZone === 'UTC') return wall\n  const first = wall - zoneOffset(wall, timeZone)\n  const second = wall - zoneOffset(first, timeZone)\n  if (first === second) return first\n  // Across a change, the earlier reading that shows this wall time, else the later one.\n  const earlier = Math.min(first, second)\n  return wallTime(wallFields(earlier, timeZone)) === wall\n    ? earlier\n    : Math.max(first, second)\n}\n\n/** The visitor's own time zone. */\nexport function browserTimeZone(): string {\n  return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC'\n}\n\n/**\n * The time zone instants are written in: the one given, else the browser's.\n * The server can't know the browser's, so it writes UTC and the browser\n * moves to the visitor's own right after hydration, as `useLocale` does.\n */\nexport function useTimeZone(timeZone: string | undefined): string {\n  const browser = useSyncExternalStore(noChange, browserTimeZone, () => 'UTC')\n  return timeZone ?? browser\n}\n\n/** One step between ticks: a unit, so many of it. */\nexport interface TimeInterval {\n  unit: TimeUnit\n  step: number\n}\n\nconst DAY_LENGTH = 24 * HOUR_MS\nconst UNIT_MS: Record<TimeUnit, number> = {\n  second: SECOND_MS,\n  minute: MINUTE_MS,\n  hour: HOUR_MS,\n  day: DAY_LENGTH,\n  week: 7 * DAY_LENGTH,\n  // The Gregorian calendar's average month and year.\n  month: (365.2425 / 12) * DAY_LENGTH,\n  year: 365.2425 * DAY_LENGTH,\n}\n\n// d3-time's tick intervals: a step a person counts in, from a second to a year.\nconst INTERVALS: readonly TimeInterval[] = [\n  { unit: 'second', step: 1 },\n  { unit: 'second', step: 5 },\n  { unit: 'second', step: 15 },\n  { unit: 'second', step: 30 },\n  { unit: 'minute', step: 1 },\n  { unit: 'minute', step: 5 },\n  { unit: 'minute', step: 15 },\n  { unit: 'minute', step: 30 },\n  { unit: 'hour', step: 1 },\n  { unit: 'hour', step: 3 },\n  { unit: 'hour', step: 6 },\n  { unit: 'hour', step: 12 },\n  { unit: 'day', step: 1 },\n  { unit: 'day', step: 2 },\n  { unit: 'week', step: 1 },\n  { unit: 'month', step: 1 },\n  { unit: 'month', step: 3 },\n  { unit: 'year', step: 1 },\n]\n\nconst intervalLength = ({ unit, step }: TimeInterval) => UNIT_MS[unit] * step\n\n/**\n * The intervals of d3's list, then round numbers of years, that mark at\n * least one and at most `most` ticks over `span` ms, coarsest first: the\n * steps an axis of times chooses among by the room it has.\n */\nexport function timeIntervals(span: number, most = 40): TimeInterval[] {\n  const years: TimeInterval[] = []\n  for (let power = 1; power <= 1e4; power *= 10) {\n    for (const share of [1, 2, 5]) {\n      if (power * share > 1) years.push({ unit: 'year', step: power * share })\n    }\n  }\n  return [...INTERVALS, ...years]\n    .filter((interval) => {\n      const count = span / intervalLength(interval)\n      return count <= most && count >= 0.5\n    })\n    .toReversed()\n}\n\n/** The first of `fields`' boundaries of `unit` at or before it, on its wall clock. */\nfunction floorFields(fields: WallFields, unit: TimeUnit, firstDay: Weekday): WallFields {\n  const { year, month, day } = fields\n  switch (unit) {\n    case 'second':\n      return fields\n    case 'minute':\n      return { ...fields, second: 0 }\n    case 'hour':\n      return { ...fields, minute: 0, second: 0 }\n    case 'day':\n      return { year, month, day, hour: 0, minute: 0, second: 0 }\n    case 'week': {\n      const date = startOfWeek(toISODate({ year, month, day }) ?? '1970-01-01', firstDay)\n      const parts = fromISODate(date)\n      return {\n        year: parts.year ?? year,\n        month: parts.month ?? month,\n        day: parts.day ?? day,\n        hour: 0,\n        minute: 0,\n        second: 0,\n      }\n    }\n    case 'month':\n      return { year, month, day: 1, hour: 0, minute: 0, second: 0 }\n    case 'year':\n      return { year, month: 1, day: 1, hour: 0, minute: 0, second: 0 }\n  }\n}\n\n/** `fields` moved on by one `unit` of the calendar. */\nfunction nextFields(fields: WallFields, unit: TimeUnit): WallFields {\n  switch (unit) {\n    case 'second':\n    case 'minute':\n    case 'hour':\n      return fields\n    case 'day':\n    case 'week': {\n      const date = addDays(toISODate(fields) ?? '1970-01-01', unit === 'day' ? 1 : 7)\n      const parts = fromISODate(date)\n      return {\n        ...fields,\n        year: parts.year ?? fields.year,\n        month: parts.month ?? fields.month,\n        day: parts.day ?? fields.day,\n      }\n    }\n    case 'month':\n      return fields.month === 12\n        ? { ...fields, year: fields.year + 1, month: 1 }\n        : { ...fields, month: fields.month + 1 }\n    case 'year':\n      return { ...fields, year: fields.year + 1 }\n  }\n}\n\n/** Whether a boundary of `interval` is one its ticks mark: every `step`th, counted from the unit above. */\nfunction marks(fields: WallFields, { unit, step }: TimeInterval): boolean {\n  if (step === 1) return true\n  switch (unit) {\n    case 'second':\n      return fields.second % step === 0\n    case 'minute':\n      return fields.minute % step === 0\n    case 'hour':\n      return fields.hour % step === 0\n    case 'day':\n      return (fields.day - 1) % step === 0\n    case 'week':\n      return true\n    case 'month':\n      return (fields.month - 1) % step === 0\n    case 'year':\n      return fields.year % step === 0\n  }\n}\n\n/**\n * The ticks of `interval` from `domain[0]` to `domain[1]`, both instants in\n * ms, on `timeZone`'s wall clock: its whole seconds, minutes and hours, its\n * midnights, the starts of its weeks (on `firstDay`), months and years.\n * Seconds, minutes and hours count on in real time, so an hour the clock\n * repeats is marked once each time it passes; longer units count on the\n * calendar, each at the instant its midnight falls on.\n */\nexport function timeTicks(\n  domain: readonly [number, number],\n  interval: TimeInterval,\n  timeZone: string,\n  firstDay: Weekday = 1,\n): number[] {\n  const [low, high] = domain\n  if (!(high >= low) || !Number.isFinite(low) || !Number.isFinite(high)) return []\n  const { unit } = interval\n  const ticks: number[] = []\n  // A guard against a span far longer than the interval suits, which would mark thousands.\n  const limit = 1000\n  if (unit === 'second' || unit === 'minute') {\n    // A zone's offset is a whole number of minutes, so these steps fall on the wall clock's own.\n    const length = UNIT_MS[unit] * interval.step\n    const offset = zoneOffset(low, timeZone)\n    for (\n      let time = Math.ceil((low + offset) / length) * length - offset;\n      time <= high && ticks.length < limit;\n      time += length\n    ) {\n      ticks.push(time)\n    }\n    return ticks\n  }\n  if (unit === 'hour') {\n    // Hours count on in real time, each marked by the hour the wall clock shows then.\n    let time = zonedTime(\n      floorFields(wallFields(low, timeZone), 'hour', firstDay),\n      timeZone,\n    )\n    if (time > low) time -= HOUR_MS\n    for (; time <= high && ticks.length < limit; time += HOUR_MS) {\n      if (time >= low && marks(wallFields(time, timeZone), interval)) ticks.push(time)\n    }\n    return ticks\n  }\n  let fields = floorFields(wallFields(low, timeZone), unit, firstDay)\n  for (let count = 0; count < limit * interval.step * 31; count += 1) {\n    const time = zonedTime(fields, timeZone)\n    if (time > high || ticks.length >= limit) break\n    if (time >= low && marks(fields, interval)) ticks.push(time)\n    fields = nextFields(fields, unit)\n  }\n  return ticks\n}\n\n/** The coarsest unit `time` falls on the boundary of, on `timeZone`'s wall clock, weeks aside. */\nfunction boundaryOf(time: number, timeZone: string): TimeUnit {\n  const { month, day, hour, minute, second } = wallFields(time, timeZone)\n  if (time % SECOND_MS !== 0 || second !== 0) return 'second'\n  if (minute !== 0) return 'minute'\n  // A zone that springs forward at midnight starts that day at 1:00.\n  if (hour !== 0 && wallFields(time - 1, timeZone).day === day) return 'hour'\n  if (day !== 1) return 'day'\n  if (month !== 1) return 'month'\n  return 'year'\n}\n\n/**\n * The finest unit any of `times` holds on `timeZone`'s wall clock: `year`\n * when each is the start of one, `day` when each is a midnight, `second`\n * when any has seconds. A tick's or a row's label is written that fine.\n */\nexport function timeUnitOf(\n  times: readonly number[],\n  timeZone: string,\n): Exclude<TimeUnit, 'week'> {\n  const order = ['second', 'minute', 'hour', 'day', 'month', 'year'] as const\n  let finest = order.length - 1\n  for (const time of times) {\n    finest = Math.min(\n      finest,\n      order.indexOf(boundaryOf(time, timeZone) as (typeof order)[number]),\n    )\n    if (finest === 0) break\n  }\n  return order[finest]!\n}\n\nconst instantFormats = new Map<string, Intl.DateTimeFormat>()\n\n/** `time` as `locale` writes it with `options` on `timeZone`'s wall clock. */\nexport function formatInstant(\n  time: number,\n  locale: Intl.LocalesArgument,\n  options: Omit<Intl.DateTimeFormatOptions, 'timeZone'>,\n  timeZone: string,\n): string {\n  const key = `${String(locale ?? '')}|${timeZone}|${JSON.stringify(options)}`\n  let format = instantFormats.get(key)\n  if (!format) {\n    format = new Intl.DateTimeFormat(locale, {\n      ...options,\n      calendar: 'gregory',\n      timeZone,\n    })\n    instantFormats.set(key, format)\n  }\n  return format.format(time)\n}\n\nconst TICK_FORMATS: Record<Exclude<TimeUnit, 'week'>, Intl.DateTimeFormatOptions> = {\n  second: { hour: 'numeric', minute: '2-digit', second: '2-digit' },\n  minute: { hour: 'numeric', minute: '2-digit' },\n  hour: { hour: 'numeric', minute: '2-digit' },\n  day: { day: 'numeric', month: 'short' },\n  month: { month: 'short' },\n  year: { year: 'numeric' },\n}\n\n/**\n * A tick's label, as short as the boundary it falls on lets it be, as d3's\n * multi-scale format writes it: 14:05:30, 14:05, 14:00, 17 Nov, Dec, 2027.\n * Each tick says only what changed at it, so the months after a year's\n * tick read Feb, Mar, and the tick at midnight names its day.\n */\nexport function timeTickLabel(\n  time: number,\n  locale: Intl.LocalesArgument,\n  timeZone: string,\n): string {\n  const unit = boundaryOf(time, timeZone)\n  return formatInstant(\n    time,\n    locale,\n    TICK_FORMATS[unit as Exclude<TimeUnit, 'week'>],\n    timeZone,\n  )\n}\n\n/**\n * A time as a tooltip, the data table and a screen reader name it, as fine\n * as `unit`, the finest its chart's times hold: 2026, Nov 2026, 17 Nov\n * 2026, 17 Nov 2026, 14:05, or the time of day alone when `oneDay`, every\n * time the chart shows being on one day.\n */\nexport function timeLabel(\n  time: number,\n  unit: Exclude<TimeUnit, 'week'>,\n  locale: Intl.LocalesArgument,\n  timeZone: string,\n  oneDay = false,\n): string {\n  const date: Intl.DateTimeFormatOptions = {\n    day: 'numeric',\n    month: 'short',\n    year: 'numeric',\n  }\n  const clock: Intl.DateTimeFormatOptions = {\n    hour: 'numeric',\n    minute: '2-digit',\n    ...(unit === 'second' ? { second: '2-digit' } : {}),\n  }\n  const options: Intl.DateTimeFormatOptions =\n    unit === 'year'\n      ? { year: 'numeric' }\n      : unit === 'month'\n        ? { month: 'short', year: 'numeric' }\n        : unit === 'day'\n          ? date\n          : oneDay\n            ? clock\n            : { ...date, ...clock }\n  return formatInstant(time, locale, options, timeZone)\n}\n\n/** Whether every one of `times` falls on one day of `timeZone`'s wall clock. */\nexport function onOneDay(times: readonly number[], timeZone: string): boolean {\n  const [first] = times\n  if (first === undefined) return true\n  const day = (time: number) => {\n    const { year, month, day } = wallFields(time, timeZone)\n    return `${year}-${month}-${day}`\n  }\n  const firstDay = day(first)\n  return times.every((time) => day(time) === firstDay)\n}\n\n/** About how long one `unit` lasts, in ms: a month and a year as the calendar's averages. */\nexport function unitLength(unit: TimeUnit): number {\n  return UNIT_MS[unit]\n}\n",
      "type": "registry:lib",
      "target": "@lib/dates.ts"
    }
  ],
  "type": "registry:lib"
}