{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-date-picker-29",
  "title": "Typed date",
  "description": "A date field that reads typed words such as \"next fri 3pm\" or \"in 3 days\", rolls the date it understood under the field, and opens a calendar from its button.",
  "dependencies": [
    "date-fns",
    "motion",
    "react-day-picker"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/calendar.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/label.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/popover.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/calendar-date-picker/calendar-date-picker-29.tsx",
      "content": "'use client';\n\nimport { addDays, nextMonday } from 'date-fns';\nimport { useId, useState } from 'react';\nimport type { Matcher } from 'react-day-picker';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  typingSteps,\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport {\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { CalendarIcon } from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Label } from '@/registry/ndeko/ui/label';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from '@/registry/ndeko/ui/popover';\n\nimport { AnimatedCalendar } from './_parts/animated-calendar';\nimport { useToday } from './_parts/today';\nimport { describeTypedDate } from './_parts/typed-date';\nimport {\n  blockedReasonOf,\n  UNREADABLE_MESSAGE,\n  useTypedDate,\n  type DayLimits,\n  type TypedDatePicker,\n  type TypedDatePreview,\n} from './_parts/use-typed-date';\n\ntype QuickPickId = 'today' | 'tomorrow' | 'monday';\n\ntype QuickPick = {\n  id: QuickPickId;\n  label: string;\n  date: Date | null;\n  isBlocked: boolean;\n};\n\ntype LineKind = 'error' | 'preview' | 'stale' | 'hint';\n\ntype Line = {\n  kind: LineKind;\n  text: string;\n};\n\nconst LINE_TONE: Record<LineKind, string> = {\n  error: 'text-destructive-ink',\n  preview: 'text-foreground',\n  stale: 'text-muted-foreground',\n  hint: 'text-muted-foreground',\n};\n\nconst REST_TEXT = 'next fri 3pm';\n\nconst LATEST_DAYS_AHEAD = 90;\n\nconst SUNDAY = 0;\n\nconst QUICK_PICK_LABELS: { id: QuickPickId; label: string }[] = [\n  { id: 'today', label: 'Today' },\n  { id: 'tomorrow', label: 'Tomorrow' },\n  { id: 'monday', label: 'Next Monday' },\n];\n\nfunction quickDateOf(id: QuickPickId, today: Date | null) {\n  if (today === null) {\n    return null;\n  }\n  if (id === 'tomorrow') {\n    return addDays(today, 1);\n  }\n  if (id === 'monday') {\n    return nextMonday(today);\n  }\n  return today;\n}\n\nfunction isDateBlocked(date: Date | null, limits: DayLimits) {\n  if (date === null) {\n    return true;\n  }\n  return blockedReasonOf(date, limits) !== null;\n}\n\nfunction quickPicksOf(today: Date | null, limits: DayLimits): QuickPick[] {\n  return QUICK_PICK_LABELS.map(({ id, label }) => {\n    const date = quickDateOf(id, today);\n    return { id, label, date, isBlocked: isDateBlocked(date, limits) };\n  });\n}\n\nfunction disabledMatchersOf(limits: DayLimits) {\n  const matchers: Matcher[] = [];\n  if (limits.min) {\n    matchers.push({ before: limits.min });\n  }\n  if (limits.max) {\n    matchers.push({ after: limits.max });\n  }\n  if (limits.disabledWeekdays) {\n    matchers.push({ dayOfWeek: [...limits.disabledWeekdays] });\n  }\n  return matchers;\n}\n\nfunction lineOf(\n  error: string | null,\n  preview: TypedDatePreview | null,\n  hint: string\n): Line {\n  if (error !== null) {\n    return { kind: 'error', text: error };\n  }\n  if (preview === null) {\n    return { kind: 'hint', text: hint };\n  }\n  if (preview.isStale) {\n    return { kind: 'stale', text: preview.text };\n  }\n  return { kind: 'preview', text: preview.text };\n}\n\nfunction hintOf(withTime: boolean) {\n  if (withTime) {\n    return 'Try “next fri 3pm” or “in 3 days”';\n  }\n  return 'Try “next fri”, “in 3 days” or “14 nov”';\n}\n\nexport type TypedDateFieldProps = {\n  label: string;\n  picker: TypedDatePicker;\n  today: Date | null;\n  limits: DayLimits;\n  withTime: boolean;\n  pressedPick?: QuickPickId | null;\n};\n\nexport function TypedDateField({\n  label,\n  picker,\n  today,\n  limits,\n  withTime,\n  pressedPick = null,\n}: TypedDateFieldProps) {\n  const id = useId();\n  const lineId = `${id}-line`;\n  const [isCalendarOpen, setIsCalendarOpen] = useState(false);\n  const [announcement, setAnnouncement] = useState('');\n  const { text, changeText, value, preview, error, commit, pickDay } = picker;\n  const line = lineOf(error, preview, hintOf(withTime));\n  const picks = quickPicksOf(today, limits);\n  const matchers = disabledMatchersOf(limits);\n  const calendarMonth = value?.date ?? today ?? undefined;\n\n  function announceSet(date: Date, hasTime: boolean) {\n    if (today === null) {\n      return;\n    }\n    const spoken = describeTypedDate({ date, hasTime }, today);\n    setAnnouncement(`${label} set to ${spoken}`);\n  }\n\n  function commitFromPerson() {\n    const committed = commit();\n    if (committed) {\n      announceSet(committed.date, committed.hasTime);\n      return;\n    }\n    const hasText = text.trim() !== '';\n    if (hasText) {\n      setAnnouncement(error ?? UNREADABLE_MESSAGE);\n    }\n  }\n\n  function pickFromPerson(date: Date) {\n    const picked = pickDay(date);\n    if (picked) {\n      announceSet(picked.date, picked.hasTime);\n    }\n  }\n\n  function pickQuick(pick: QuickPick) {\n    if (pick.date === null) {\n      return;\n    }\n    pickFromPerson(pick.date);\n  }\n\n  function selectInCalendar(date: Date | undefined) {\n    if (!date) {\n      return;\n    }\n    pickFromPerson(date);\n    setIsCalendarOpen(false);\n  }\n\n  function commitOnEnter(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key !== 'Enter') {\n      return;\n    }\n    event.preventDefault();\n    commitFromPerson();\n  }\n\n  return (\n    <div className='flex w-full flex-col gap-2'>\n      <Label htmlFor={id}>{label}</Label>\n      <div className='relative'>\n        <Input\n          id={id}\n          value={text}\n          onChange={(event) => changeText(event.currentTarget.value)}\n          onKeyDown={commitOnEnter}\n          onBlur={commitFromPerson}\n          placeholder='Type a date'\n          autoComplete='off'\n          spellCheck={false}\n          aria-invalid={error !== null}\n          aria-describedby={lineId}\n          className='pe-10'\n        />\n        <Popover open={isCalendarOpen} onOpenChange={setIsCalendarOpen}>\n          <PopoverTrigger\n            render={\n              <Button\n                variant='ghost'\n                size='icon-sm'\n                aria-label='Open the calendar'\n                className='text-muted-foreground hover:text-foreground absolute end-0.5 top-0.5 size-7'\n              />\n            }\n          >\n            <CalendarIcon className='size-4' />\n          </PopoverTrigger>\n          <PopoverContent className='w-auto p-2' align='end'>\n            <AnimatedCalendar\n              mode='single'\n              selected={value?.date}\n              onSelect={selectInCalendar}\n              defaultMonth={calendarMonth}\n              disabled={matchers}\n            />\n          </PopoverContent>\n        </Popover>\n      </div>\n      <div id={lineId} className='flex min-h-5 items-center text-xs'>\n        <WordRoll text={line.text} className={LINE_TONE[line.kind]} />\n      </div>\n      <div className='flex flex-wrap gap-1.5'>\n        {picks.map((pick) => (\n          <Button\n            key={pick.id}\n            variant='outline'\n            size='sm'\n            disabled={pick.isBlocked}\n            onClick={() => pickQuick(pick)}\n            className={pressedQuietOf(pressedPick === pick.id)}\n          >\n            {pick.label}\n          </Button>\n        ))}\n      </div>\n      <LiveRegion message={announcement} />\n    </div>\n  );\n}\n\nexport default function CalendarDatePicker29() {\n  const today = useToday();\n  const { pressed, press } = usePress<QuickPickId>();\n  const limits: DayLimits = {};\n  if (today !== null) {\n    limits.min = today;\n    limits.max = addDays(today, LATEST_DAYS_AHEAD);\n    limits.disabledWeekdays = [SUNDAY];\n  }\n  const picker = useTypedDate({\n    today,\n    withTime: true,\n    initialText: REST_TEXT,\n    ...limits,\n  });\n\n  function pickNextMonday() {\n    if (today === null) {\n      return;\n    }\n    picker.pickDay(nextMonday(today));\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 2400, run: () => picker.changeText('') },\n    ...typingSteps('in 3 days', picker.changeText, {\n      startAfter: 500,\n      characterMs: 70,\n    }),\n    { after: 1000, run: () => picker.commit() },\n    { after: 1800, run: () => press('monday') },\n    { after: PRESS_LEAD_MS, run: pickNextMonday },\n    { after: 1800, run: () => picker.changeText('') },\n    ...typingSteps('someday', picker.changeText, {\n      startAfter: 500,\n      characterMs: 70,\n    }),\n    { after: 1000, run: () => picker.commit() },\n    { after: 1800, run: () => picker.changeText('') },\n    ...typingSteps(REST_TEXT, picker.changeText, {\n      startAfter: 500,\n      characterMs: 70,\n    }),\n  ];\n  const { ref } = useAutoplay(steps, {\n    loopAfter: 3200,\n    onReset: () => picker.reset(REST_TEXT),\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='min-h-[10rem] w-full max-w-xs'>\n      <TypedDateField\n        label='Due date'\n        picker={picker}\n        today={today}\n        limits={limits}\n        withTime\n        pressedPick={pressed}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/calendar-date-picker-29.tsx"
    },
    {
      "path": "registry/ndeko/components/calendar-date-picker/_parts/animated-calendar.tsx",
      "content": "'use client';\n\nimport { differenceInCalendarDays } from 'date-fns';\nimport {\n  motion,\n  type TargetAndTransition,\n  type Transition,\n} from 'motion/react';\nimport { useState } from 'react';\nimport {\n  Day,\n  useDayPicker,\n  type DayProps,\n  type MonthProps,\n} from 'react-day-picker';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Calendar } from '@/registry/ndeko/ui/calendar';\n\ntype CalendarProps = React.ComponentProps<typeof Calendar>;\n\ntype ShownMonth = { time: number; direction: number };\n\nconst MONTH_SHIFT_PX = 12;\nconst RANGE_STEP_MS = 12;\nconst RANGE_GROWTH_MAX_MS = 240;\n\nconst MONTH_TRANSITION: Transition = {\n  duration: 0.2,\n  ease: [0.23, 1, 0.32, 1],\n};\n\nconst MONTH_AT_REST: TargetAndTransition = { opacity: 1, x: 0 };\n\nconst SETTLING_DAY_BUTTON = [\n  'transition-[color,background-color,border-radius,box-shadow,scale] ease-(--ease-out-strong) active:scale-90',\n  'group-[.range-middle]:[transition-delay:var(--range-delay),var(--range-delay),0ms,0ms,0ms]',\n].join(' ');\n\nfunction rangeStartOf(selected: unknown) {\n  if (!selected) {\n    return undefined;\n  }\n  if (typeof selected !== 'object') {\n    return undefined;\n  }\n  if (!('from' in selected)) {\n    return undefined;\n  }\n  return selected.from as Date | undefined;\n}\n\nfunction rangeDelayOf(day: Date, rangeStart: Date | undefined) {\n  if (!rangeStart) {\n    return '0ms';\n  }\n  const step = differenceInCalendarDays(day, rangeStart);\n  const delay = Math.min(step * RANGE_STEP_MS, RANGE_GROWTH_MAX_MS);\n  const positiveDelay = Math.max(0, delay);\n  return `${positiveDelay}ms`;\n}\n\nfunction monthEnterOf(direction: number, shouldReduceMotion: boolean | null) {\n  if (direction === 0) {\n    return false;\n  }\n  if (shouldReduceMotion) {\n    return { opacity: 0 };\n  }\n  const offset = direction * MONTH_SHIFT_PX;\n  return { opacity: 0, x: offset };\n}\n\nfunction GrowingRangeDay({ style, ...props }: DayProps) {\n  const { selected } = useDayPicker();\n  const rangeStart = rangeStartOf(selected);\n  const delay = rangeDelayOf(props.day.date, rangeStart);\n  const dayStyle = { ...style, '--range-delay': delay } as React.CSSProperties;\n\n  return <Day {...props} style={dayStyle} />;\n}\n\nfunction SlidingMonth({\n  calendarMonth,\n  displayIndex,\n  children,\n  ...props\n}: MonthProps) {\n  const time = calendarMonth.date.getTime();\n  const [shown, setShown] = useState<ShownMonth>({ time, direction: 0 });\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  if (shown.time !== time) {\n    const direction = Math.sign(time - shown.time);\n    setShown({ time, direction });\n  }\n\n  return (\n    <div data-display-index={displayIndex} {...props}>\n      <AnimatedSize>\n        <motion.div\n          key={time}\n          initial={monthEnterOf(shown.direction, shouldReduceMotion)}\n          animate={MONTH_AT_REST}\n          transition={MONTH_TRANSITION}\n        >\n          {children}\n        </motion.div>\n      </AnimatedSize>\n    </div>\n  );\n}\n\nfunction withSettlingDays(classNames: CalendarProps['classNames']) {\n  const dayButton = cn(SETTLING_DAY_BUTTON, classNames?.day_button);\n  return { ...classNames, day_button: dayButton };\n}\n\n/**\n * The calendar primitive with the date picker micro-interactions: a picked day settles in,\n * a range grows from its start to its end, a new month slides in from the side it comes from\n * and the card resizes to the number of weeks.\n */\nfunction AnimatedCalendar({ classNames, components, ...props }: CalendarProps) {\n  return (\n    <Calendar\n      classNames={withSettlingDays(classNames)}\n      components={{ Day: GrowingRangeDay, Month: SlidingMonth, ...components }}\n      {...props}\n    />\n  );\n}\n\nexport { AnimatedCalendar };\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/_parts/animated-calendar.tsx"
    },
    {
      "path": "registry/ndeko/components/calendar-date-picker/_parts/today.ts",
      "content": "'use client';\n\nimport { startOfDay } from 'date-fns';\nimport { useSyncExternalStore } from 'react';\n\nlet cachedToday: Date | null = null;\n\nfunction subscribeNever() {\n  return () => {};\n}\n\nfunction readToday() {\n  if (cachedToday === null) {\n    cachedToday = startOfDay(new Date());\n  }\n  return cachedToday;\n}\n\nfunction readNothing() {\n  return null;\n}\n\n/** The server and the first client render know no day, so what depends on it appears once the page is live. */\nexport function useToday() {\n  return useSyncExternalStore(subscribeNever, readToday, readNothing);\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/_parts/today.ts"
    },
    {
      "path": "registry/ndeko/components/calendar-date-picker/_parts/typed-date.ts",
      "content": "import {\n  addDays,\n  addMonths,\n  addWeeks,\n  addYears,\n  format,\n  isAfter,\n  isBefore,\n  isSameYear,\n  startOfDay,\n} from 'date-fns';\n\nexport type TypedDate = {\n  date: Date;\n  hasTime: boolean;\n};\n\nexport type TypedDateOptions = {\n  today: Date;\n  withTime: boolean;\n  /** Which of day and month comes first in numbers such as 14/11. */\n  isDayFirst?: boolean;\n  /** Where a date with no year lands: the next time it comes round, or the last time it did. */\n  direction?: 'future' | 'past';\n};\n\nexport type TypedDateReading =\n  | { status: 'empty' }\n  | { status: 'unreadable' }\n  | { status: 'ready'; value: TypedDate };\n\ntype Clock = {\n  hours: number;\n  minutes: number;\n};\n\ntype Parts = {\n  year: number;\n  month: number;\n  day: number;\n};\n\nconst MONTHS = [\n  'january',\n  'february',\n  'march',\n  'april',\n  'may',\n  'june',\n  'july',\n  'august',\n  'september',\n  'october',\n  'november',\n  'december',\n];\n\nconst WEEKDAYS = [\n  'sunday',\n  'monday',\n  'tuesday',\n  'wednesday',\n  'thursday',\n  'friday',\n  'saturday',\n];\n\nconst WEEKDAY_LEADS = ['', 'this', 'next', 'on'];\n\nconst MERIDIEM_TIME = /\\b(?:at\\s+)?(\\d{1,2})(?::(\\d{2}))?\\s*(am|pm)\\b/;\nconst CLOCK_TIME = /\\b(?:at\\s+)?(\\d{1,2}):(\\d{2})\\b/;\nconst NOON = /\\b(?:at\\s+)?noon\\b/;\nconst ISO_DATE = /^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/;\nconst NUMERIC_DATE = /^(\\d{1,2})[./-](\\d{1,2})(?:[./-](\\d{4}|\\d{2}))?$/;\nconst RELATIVE_DATE = /^in (\\d+) (days?|d|weeks?|w|months?|years?|y)$/;\nconst ORDINAL_SUFFIX = /^(\\d{1,2})(?:st|nd|rd|th)$/;\n\nfunction normalized(text: string) {\n  const lower = text.toLowerCase().replace(/,/g, ' ');\n  const spaced = lower.replace(/(\\d)t(\\d)/g, '$1 $2');\n  return spaced.replace(/\\s+/g, ' ').trim();\n}\n\nfunction withoutMatch(text: string, match: RegExpMatchArray) {\n  const before = text.slice(0, match.index);\n  const after = text.slice((match.index ?? 0) + match[0].length);\n  return `${before} ${after}`.replace(/\\s+/g, ' ').trim();\n}\n\nfunction meridiemClockOf(match: RegExpMatchArray): Clock | null {\n  const hour = Number(match[1]);\n  const minutes = Number(match[2] ?? '0');\n  const isHourValid = hour >= 1 && hour <= 12;\n  const isMinuteValid = minutes <= 59;\n  if (!isHourValid || !isMinuteValid) {\n    return null;\n  }\n  const isPm = match[3] === 'pm';\n  const hoursOfDay = hour % 12;\n  if (isPm) {\n    return { hours: hoursOfDay + 12, minutes };\n  }\n  return { hours: hoursOfDay, minutes };\n}\n\nfunction clockOf(match: RegExpMatchArray): Clock | null {\n  const hours = Number(match[1]);\n  const minutes = Number(match[2]);\n  const isValid = hours <= 23 && minutes <= 59;\n  if (!isValid) {\n    return null;\n  }\n  return { hours, minutes };\n}\n\ntype TimeSplit = {\n  rest: string;\n  clock: Clock | null;\n  isBroken: boolean;\n};\n\nfunction splitTime(text: string): TimeSplit {\n  const meridiem = text.match(MERIDIEM_TIME);\n  if (meridiem) {\n    const clock = meridiemClockOf(meridiem);\n    return {\n      rest: withoutMatch(text, meridiem),\n      clock,\n      isBroken: clock === null,\n    };\n  }\n  const clockMatch = text.match(CLOCK_TIME);\n  if (clockMatch) {\n    const clock = clockOf(clockMatch);\n    return {\n      rest: withoutMatch(text, clockMatch),\n      clock,\n      isBroken: clock === null,\n    };\n  }\n  const noon = text.match(NOON);\n  if (noon) {\n    return {\n      rest: withoutMatch(text, noon),\n      clock: { hours: 12, minutes: 0 },\n      isBroken: false,\n    };\n  }\n  return { rest: text, clock: null, isBroken: false };\n}\n\nfunction isRealDate({ year, month, day }: Parts) {\n  const date = new Date(year, month, day);\n  const isSameYearNumber = date.getFullYear() === year;\n  const isSameMonth = date.getMonth() === month;\n  const isSameDay = date.getDate() === day;\n  return isSameYearNumber && isSameMonth && isSameDay;\n}\n\nfunction dateOfParts(parts: Parts) {\n  if (!isRealDate(parts)) {\n    return null;\n  }\n  return new Date(parts.year, parts.month, parts.day);\n}\n\n/** With no year, \"14 nov\" typed in December means next year, unless the field looks back in time. */\nfunction withNearestYear(\n  parts: Parts,\n  today: Date,\n  direction: 'future' | 'past'\n) {\n  const thisYear = dateOfParts(parts);\n  if (thisYear === null) {\n    return null;\n  }\n  if (direction === 'past') {\n    if (!isAfter(thisYear, today)) {\n      return thisYear;\n    }\n    return dateOfParts({ ...parts, year: parts.year - 1 });\n  }\n  if (!isBefore(thisYear, today)) {\n    return thisYear;\n  }\n  return dateOfParts({ ...parts, year: parts.year + 1 });\n}\n\nexport function monthIndexOf(word: string) {\n  if (word.length < 3) {\n    return -1;\n  }\n  return MONTHS.findIndex((name) => name.startsWith(word));\n}\n\nfunction weekdayIndexOf(word: string) {\n  if (word.length < 3) {\n    return -1;\n  }\n  return WEEKDAYS.findIndex((name) => name.startsWith(word));\n}\n\nfunction dayNumberOf(word: string) {\n  const ordinal = word.match(ORDINAL_SUFFIX);\n  if (ordinal) {\n    return Number(ordinal[1]);\n  }\n  if (/^\\d{1,2}$/.test(word)) {\n    return Number(word);\n  }\n  return null;\n}\n\nfunction weekdayDateOf(today: Date, weekday: number, isNext: boolean) {\n  const gap = (weekday - today.getDay() + 7) % 7;\n  const mustBeLater = isNext && gap === 0;\n  if (mustBeLater) {\n    return addDays(today, 7);\n  }\n  return addDays(today, gap);\n}\n\nfunction relativeDateOf(match: RegExpMatchArray, today: Date) {\n  const amount = Number(match[1]);\n  const unit = match[2][0];\n  if (unit === 'w') {\n    return addWeeks(today, amount);\n  }\n  if (unit === 'm') {\n    return addMonths(today, amount);\n  }\n  if (unit === 'y') {\n    return addYears(today, amount);\n  }\n  return addDays(today, amount);\n}\n\nfunction keywordDateOf(text: string, today: Date) {\n  if (text === '' || text === 'today') {\n    return today;\n  }\n  if (text === 'tomorrow' || text === 'tmrw') {\n    return addDays(today, 1);\n  }\n  if (text === 'yesterday') {\n    return addDays(today, -1);\n  }\n  if (text === 'next week') {\n    return addWeeks(today, 1);\n  }\n  if (text === 'next month') {\n    return addMonths(today, 1);\n  }\n  return null;\n}\n\nfunction weekdayPhraseDateOf(text: string, today: Date) {\n  const words = text.split(' ');\n  const word = words[words.length - 1];\n  const lead = words.slice(0, -1).join(' ');\n  const hasKnownLead = WEEKDAY_LEADS.includes(lead);\n  const weekday = weekdayIndexOf(word);\n  if (!hasKnownLead || weekday === -1) {\n    return null;\n  }\n  return weekdayDateOf(today, weekday, lead === 'next');\n}\n\ntype DayAndMonth = {\n  day: number;\n  month: number;\n};\n\n/** A month that cannot be one (14/11 read month first) is taken the other way round. */\nfunction dayAndMonthOf(\n  first: number,\n  second: number,\n  isDayFirst: boolean\n): DayAndMonth {\n  const ordered = { day: second, month: first };\n  if (isDayFirst) {\n    ordered.day = first;\n    ordered.month = second;\n  }\n  const needsSwap = ordered.month > 12 && ordered.day <= 12;\n  if (needsSwap) {\n    return { day: ordered.month, month: ordered.day };\n  }\n  return ordered;\n}\n\nfunction numericDateOf(match: RegExpMatchArray, options: TypedDateOptions) {\n  const first = Number(match[1]);\n  const second = Number(match[2]);\n  const rawYear = match[3];\n  const isDayFirst = options.isDayFirst ?? false;\n  const { day, month } = dayAndMonthOf(first, second, isDayFirst);\n  return datePartsDateOf(day, month - 1, rawYear, options);\n}\n\nfunction datePartsDateOf(\n  day: number,\n  month: number,\n  rawYear: string | undefined,\n  options: TypedDateOptions\n) {\n  const { today, direction = 'future' } = options;\n  if (rawYear === undefined) {\n    const parts = { year: today.getFullYear(), month, day };\n    return withNearestYear(parts, today, direction);\n  }\n  const year = fullYearOf(rawYear);\n  return dateOfParts({ year, month, day });\n}\n\nfunction fullYearOf(rawYear: string) {\n  const year = Number(rawYear);\n  if (rawYear.length === 2) {\n    return 2000 + year;\n  }\n  return year;\n}\n\nfunction monthNameDateOf(text: string, options: TypedDateOptions) {\n  const words = text.split(' ').filter((word) => word !== 'of');\n  const isShort = words.length === 2 || words.length === 3;\n  if (!isShort) {\n    return null;\n  }\n  const [first, second, third] = words;\n  const dayFirst = dayNumberOf(first);\n  const monthSecond = monthIndexOf(second);\n  if (dayFirst !== null && monthSecond !== -1) {\n    return datePartsDateOf(dayFirst, monthSecond, third, options);\n  }\n  const monthFirst = monthIndexOf(first);\n  const daySecond = dayNumberOf(second);\n  if (monthFirst !== -1 && daySecond !== null) {\n    return datePartsDateOf(daySecond, monthFirst, third, options);\n  }\n  return null;\n}\n\nfunction dateOfText(text: string, options: TypedDateOptions) {\n  const { today } = options;\n  const keyword = keywordDateOf(text, today);\n  if (keyword) {\n    return keyword;\n  }\n  const weekday = weekdayPhraseDateOf(text, today);\n  if (weekday) {\n    return weekday;\n  }\n  const relative = text.match(RELATIVE_DATE);\n  if (relative) {\n    return relativeDateOf(relative, today);\n  }\n  const iso = text.match(ISO_DATE);\n  if (iso) {\n    return dateOfParts({\n      year: Number(iso[1]),\n      month: Number(iso[2]) - 1,\n      day: Number(iso[3]),\n    });\n  }\n  const numeric = text.match(NUMERIC_DATE);\n  if (numeric) {\n    return numericDateOf(numeric, options);\n  }\n  return monthNameDateOf(text, options);\n}\n\nexport function readTypedDate(\n  text: string,\n  options: TypedDateOptions\n): TypedDateReading {\n  const clean = normalized(text);\n  if (clean === '') {\n    return { status: 'empty' };\n  }\n  const { rest, clock, isBroken } = splitTime(clean);\n  if (isBroken) {\n    return { status: 'unreadable' };\n  }\n  const isTimeAllowed = options.withTime || clock === null;\n  if (!isTimeAllowed) {\n    return { status: 'unreadable' };\n  }\n  const day = dateOfText(rest, options);\n  if (day === null) {\n    return { status: 'unreadable' };\n  }\n  const start = startOfDay(day);\n  if (clock === null) {\n    return { status: 'ready', value: { date: start, hasTime: false } };\n  }\n  const withClock = new Date(start);\n  withClock.setHours(clock.hours, clock.minutes, 0, 0);\n  return { status: 'ready', value: { date: withClock, hasTime: true } };\n}\n\nfunction dayPatternOf(hasThisYear: boolean) {\n  if (hasThisYear) {\n    return 'EEEE d MMMM';\n  }\n  return 'EEEE d MMMM y';\n}\n\nexport function describeTypedDate(value: TypedDate, today: Date) {\n  const hasThisYear = isSameYear(value.date, today);\n  const dayPattern = dayPatternOf(hasThisYear);\n  const day = format(value.date, dayPattern);\n  if (!value.hasTime) {\n    return day;\n  }\n  const time = format(value.date, 'HH:mm');\n  return `${day}, ${time}`;\n}\n\nexport function formatTypedDate(value: TypedDate) {\n  const day = format(value.date, 'd MMM y');\n  if (!value.hasTime) {\n    return day;\n  }\n  const time = format(value.date, 'HH:mm');\n  return `${day}, ${time}`;\n}\n\nexport function isDayFirstIn(locale: string) {\n  const sample = new Date(2026, 10, 13);\n  const parts = new Intl.DateTimeFormat(locale).formatToParts(sample);\n  const order = parts.map((part) => part.type);\n  return order.indexOf('day') < order.indexOf('month');\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/_parts/typed-date.ts"
    },
    {
      "path": "registry/ndeko/components/calendar-date-picker/_parts/use-typed-date.ts",
      "content": "'use client';\n\nimport { format, isAfter, isBefore, startOfDay } from 'date-fns';\nimport { useState } from 'react';\n\nimport {\n  describeTypedDate,\n  formatTypedDate,\n  isDayFirstIn,\n  readTypedDate,\n  type TypedDate,\n  type TypedDateReading,\n} from './typed-date';\n\nexport type DayLimits = {\n  min?: Date;\n  max?: Date;\n  /** Days of the week that cannot be picked, 0 for Sunday. */\n  disabledWeekdays?: readonly number[];\n};\n\nexport type TypedDatePreview = {\n  text: string;\n  /** The text typed so far reads as nothing yet, so this is the last date it did read as. */\n  isStale: boolean;\n};\n\ntype UseTypedDateOptions = DayLimits & {\n  /** Null until the page is live, since the day is only known in the browser. */\n  today: Date | null;\n  withTime: boolean;\n  initialText?: string;\n};\n\nexport const UNREADABLE_MESSAGE = 'Can’t read that. Try “next fri” or “14 nov”';\n\nconst EMPTY_READING: TypedDateReading = { status: 'empty' };\n\nexport function blockedReasonOf(date: Date, limits: DayLimits) {\n  const day = startOfDay(date);\n  const { min, max, disabledWeekdays } = limits;\n  if (min && isBefore(day, startOfDay(min))) {\n    return `Pick a day from ${format(min, 'd MMM')}`;\n  }\n  if (max && isAfter(day, startOfDay(max))) {\n    return `Pick a day up to ${format(max, 'd MMM')}`;\n  }\n  if (disabledWeekdays?.includes(day.getDay())) {\n    return `${format(day, 'EEEE')}s are not available`;\n  }\n  return null;\n}\n\nfunction localeIsDayFirst() {\n  if (typeof navigator === 'undefined') {\n    return false;\n  }\n  return isDayFirstIn(navigator.language);\n}\n\nfunction isSameTypedDate(first: TypedDate | null, second: TypedDate) {\n  if (first === null) {\n    return false;\n  }\n  const isSameTime = first.date.getTime() === second.date.getTime();\n  return isSameTime && first.hasTime === second.hasTime;\n}\n\nfunction withTimeOf(date: Date, source: TypedDate | null): TypedDate {\n  if (source?.hasTime) {\n    const merged = startOfDay(date);\n    merged.setHours(source.date.getHours(), source.date.getMinutes(), 0, 0);\n    return { date: merged, hasTime: true };\n  }\n  return { date: startOfDay(date), hasTime: false };\n}\n\nfunction errorOf(\n  blockedReason: string | null,\n  isTouched: boolean,\n  reading: TypedDateReading\n) {\n  if (blockedReason !== null) {\n    return blockedReason;\n  }\n  const isUnreadable = reading.status === 'unreadable';\n  if (isTouched && isUnreadable) {\n    return UNREADABLE_MESSAGE;\n  }\n  return null;\n}\n\nexport function useTypedDate({\n  today,\n  withTime,\n  initialText = '',\n  min,\n  max,\n  disabledWeekdays,\n}: UseTypedDateOptions) {\n  const [text, setText] = useState(initialText);\n  const [value, setValue] = useState<TypedDate | null>(null);\n  const [lastReady, setLastReady] = useState<TypedDate | null>(null);\n  const [touchedText, setTouchedText] = useState<string | null>(null);\n  const [isDayFirst] = useState(localeIsDayFirst);\n  const limits: DayLimits = { min, max, disabledWeekdays };\n  let reading = EMPTY_READING;\n  if (today !== null) {\n    reading = readTypedDate(text, { today, withTime, isDayFirst });\n  }\n\n  if (\n    reading.status === 'ready' &&\n    !isSameTypedDate(lastReady, reading.value)\n  ) {\n    setLastReady(reading.value);\n  }\n  if (reading.status === 'empty' && lastReady !== null) {\n    setLastReady(null);\n  }\n\n  let blockedReason: string | null = null;\n  if (reading.status === 'ready') {\n    blockedReason = blockedReasonOf(reading.value.date, limits);\n  }\n  const isTouched = touchedText === text;\n  const error = errorOf(blockedReason, isTouched, reading);\n\n  let preview: TypedDatePreview | null = null;\n  if (today !== null && reading.status === 'ready') {\n    preview = { text: describeTypedDate(reading.value, today), isStale: false };\n  }\n  if (today !== null && reading.status === 'unreadable' && lastReady !== null) {\n    preview = { text: describeTypedDate(lastReady, today), isStale: true };\n  }\n\n  function commit() {\n    if (reading.status === 'empty') {\n      setValue(null);\n      return null;\n    }\n    if (reading.status === 'unreadable' || blockedReason !== null) {\n      setTouchedText(text);\n      return null;\n    }\n    setValue(reading.value);\n    setText(formatTypedDate(reading.value));\n    return reading.value;\n  }\n\n  function pickDay(date: Date) {\n    const next = withTimeOf(date, value ?? lastReady);\n    const reason = blockedReasonOf(next.date, limits);\n    setText(formatTypedDate(next));\n    if (reason !== null) {\n      return null;\n    }\n    setValue(next);\n    return next;\n  }\n\n  function reset(nextText: string) {\n    setText(nextText);\n    setValue(null);\n    setLastReady(null);\n    setTouchedText(null);\n  }\n\n  return {\n    text,\n    changeText: setText,\n    value,\n    preview,\n    error,\n    commit,\n    pickDay,\n    reset,\n  };\n}\n\nexport type TypedDatePicker = ReturnType<typeof useTypedDate>;\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/_parts/use-typed-date.ts"
    }
  ],
  "categories": [
    "components",
    "calendar-date-picker"
  ],
  "type": "registry:component"
}