{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-date-picker-30",
  "title": "Period picker",
  "description": "A popover that reads \"since sep 3\" or \"last 2 weeks\", lists periods with their dates, steps to a two-month range calendar, and shows the previous period when you compare.",
  "dependencies": [
    "@base-ui/react",
    "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/chat-motion.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/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/recipes.json",
    "https://ui.ndekocode.dev/r/selected-mark.json",
    "https://ui.ndekocode.dev/r/switch.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-is-narrow.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-30.tsx",
      "content": "'use client';\n\nimport { Popover as PopoverPrimitive } from '@base-ui/react/popover';\nimport { addDays, addMonths } from 'date-fns';\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useState, type RefObject } from 'react';\nimport type { DateRange, 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 { useIsNarrow } from '@/registry/ndeko/hooks/use-is-narrow';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  CalendarIcon,\n  ChevronLeftIcon,\n  ChevronRightIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { MENU_ITEM, POPUP_TRANSITION } from '@/registry/ndeko/lib/recipes';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Label } from '@/registry/ndeko/ui/label';\nimport { SelectedMark } from '@/registry/ndeko/ui/selected-mark';\nimport { Switch } from '@/registry/ndeko/ui/switch';\n\nimport { AnimatedCalendar } from './_parts/animated-calendar';\nimport {\n  PERIOD_PRESETS,\n  periodTextOf,\n  previousPeriodOf,\n  readPeriod,\n  type Period,\n} from './_parts/period-words';\nimport { useToday } from './_parts/today';\n\ntype Step = 'periods' | 'days';\n\ntype Selection =\n  { kind: 'phrase'; phrase: string } | { kind: 'days'; from: Date; to: Date };\n\ntype PressKey = 'typed' | 'days' | 'apply';\n\nconst REST_SELECTION: Selection = { kind: 'phrase', phrase: 'last 30 days' };\n\nconst SWAP_SHIFT_PX = 10;\n\nconst NARROW_REM = 36;\n\nconst MARK = 'transition-[scale,opacity] duration-150 ease-(--ease-out-strong)';\n\nfunction markStateOf(isSelected: boolean) {\n  if (isSelected) {\n    return 'scale-100 opacity-100';\n  }\n  return 'scale-75 opacity-0 duration-100';\n}\n\nfunction periodOfSelection(selection: Selection | null, today: Date | null) {\n  if (selection === null || today === null) {\n    return null;\n  }\n  if (selection.kind === 'days') {\n    return { from: selection.from, to: selection.to };\n  }\n  return readPeriod(selection.phrase, today);\n}\n\nfunction rangeOfSelection(\n  selection: Selection | null,\n  today: Date | null\n): DateRange | undefined {\n  const period = periodOfSelection(selection, today);\n  if (period === null) {\n    return undefined;\n  }\n  return { from: period.from, to: period.to };\n}\n\nfunction isPhraseSelected(selection: Selection | null, phrase: string) {\n  if (selection === null || selection.kind !== 'phrase') {\n    return false;\n  }\n  return selection.phrase === phrase;\n}\n\nfunction textOfPeriod(period: Period | null, today: Date | null) {\n  if (period === null || today === null) {\n    return 'Pick a period';\n  }\n  return periodTextOf(period, today);\n}\n\nfunction capitalized(text: string) {\n  const trimmed = text.trim();\n  return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;\n}\n\nfunction isPreset(text: string) {\n  const phrase = text.trim().toLowerCase();\n  return PERIOD_PRESETS.some((preset) => preset.phrase === phrase);\n}\n\nfunction usePeriodPicker(today: Date | null) {\n  const [isOpen, setIsOpen] = useState(true);\n  const [step, setStep] = useState<Step>('periods');\n  const [stepShift, setStepShift] = useState(1);\n  const [text, setText] = useState('');\n  const [draft, setDraft] = useState<Selection | null>(REST_SELECTION);\n  const [compare, setCompare] = useState(false);\n  const [dayRange, setDayRange] = useState<DateRange | undefined>();\n  const [applied, setApplied] = useState<Selection | null>(REST_SELECTION);\n  const [appliedCompare, setAppliedCompare] = useState(false);\n  const typedPeriod = readTypedPeriod(text, today);\n\n  function openPanel() {\n    setDraft(applied);\n    setCompare(appliedCompare);\n    setStep('periods');\n    setText('');\n    setDayRange(rangeOfSelection(applied, today));\n    setIsOpen(true);\n  }\n\n  function changeOpen(next: boolean) {\n    if (next) {\n      openPanel();\n      return;\n    }\n    setIsOpen(false);\n  }\n\n  function selectPhrase(phrase: string) {\n    setDraft({ kind: 'phrase', phrase });\n  }\n\n  function selectTyped() {\n    if (typedPeriod === null) {\n      return;\n    }\n    setDraft({ kind: 'phrase', phrase: text.trim().toLowerCase() });\n  }\n\n  function chooseDays(range: DateRange | undefined) {\n    setDayRange(range);\n    if (range?.from && range?.to) {\n      setDraft({ kind: 'days', from: range.from, to: range.to });\n    }\n  }\n\n  function showDays() {\n    setStepShift(1);\n    setStep('days');\n  }\n\n  function showPeriods() {\n    setStepShift(-1);\n    setStep('periods');\n  }\n\n  function apply() {\n    setApplied(draft);\n    setAppliedCompare(compare);\n    setIsOpen(false);\n  }\n\n  function cancel() {\n    setIsOpen(false);\n  }\n\n  function reset() {\n    setIsOpen(true);\n    setStep('periods');\n    setText('');\n    setDraft(REST_SELECTION);\n    setCompare(false);\n    setDayRange(undefined);\n    setApplied(REST_SELECTION);\n    setAppliedCompare(false);\n  }\n\n  return {\n    isOpen,\n    step,\n    stepShift,\n    text,\n    changeText: setText,\n    typedPeriod,\n    draft,\n    compare,\n    changeCompare: setCompare,\n    dayRange,\n    applied,\n    appliedCompare,\n    changeOpen,\n    selectPhrase,\n    selectTyped,\n    chooseDays,\n    showDays,\n    showPeriods,\n    apply,\n    cancel,\n    reset,\n  };\n}\n\nfunction readTypedPeriod(text: string, today: Date | null) {\n  if (today === null) {\n    return null;\n  }\n  return readPeriod(text, today);\n}\n\ntype PeriodPickerState = ReturnType<typeof usePeriodPicker>;\n\ntype PeriodRowProps = {\n  label: string;\n  dates: string;\n  isSelected: boolean;\n  isPressed?: boolean;\n  onSelect: () => void;\n};\n\nfunction PeriodRow({\n  label,\n  dates,\n  isSelected,\n  isPressed = false,\n  onSelect,\n}: PeriodRowProps) {\n  return (\n    <li>\n      <button\n        type='button'\n        aria-pressed={isSelected}\n        onClick={onSelect}\n        className={cn(\n          MENU_ITEM,\n          'hover:bg-foreground/5 cursor-pointer justify-between gap-3 pr-1.5',\n          pressedQuietOf(isPressed)\n        )}\n      >\n        <span className='truncate'>{label}</span>\n        <span className='text-muted-foreground flex shrink-0 items-center gap-2 text-xs tabular-nums'>\n          {dates}\n          <SelectedMark className={cn(MARK, markStateOf(isSelected))} />\n        </span>\n      </button>\n    </li>\n  );\n}\n\ntype PanelProps = {\n  picker: PeriodPickerState;\n  today: Date | null;\n  isTwoUp: boolean;\n  pressed: PressKey | null;\n};\n\nfunction triggerLabelOf(today: Date | null, text: string) {\n  if (today === null) {\n    return <span>{text}</span>;\n  }\n  return <WordRoll text={text} />;\n}\n\nfunction readsAsOf(\n  text: string,\n  typedPeriod: Period | null,\n  today: Date | null\n) {\n  if (text.trim() === '') {\n    return 'Try “last 2 weeks”, “Q3” or “since sep 3”';\n  }\n  if (typedPeriod === null || today === null) {\n    return 'Can’t read that yet';\n  }\n  return `Reads as ${periodTextOf(typedPeriod, today)}`;\n}\n\nfunction PeriodsStep({ picker, today, pressed }: PanelProps) {\n  const { text, changeText, typedPeriod, draft, selectPhrase, selectTyped } =\n    picker;\n  const readsAs = readsAsOf(text, typedPeriod, today);\n  const showsTypedRow = typedPeriod !== null && !isPreset(text);\n  const typedPhrase = text.trim().toLowerCase();\n\n  function selectOnEnter(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key !== 'Enter') {\n      return;\n    }\n    event.preventDefault();\n    selectTyped();\n  }\n\n  return (\n    <div className='flex w-[min(20rem,calc(100vw-4rem))] flex-col gap-2'>\n      <Input\n        aria-label='Period'\n        value={text}\n        onChange={(event) => changeText(event.currentTarget.value)}\n        onKeyDown={selectOnEnter}\n        placeholder='Type a period'\n        autoComplete='off'\n        spellCheck={false}\n      />\n      <div className='text-muted-foreground flex min-h-4 items-center px-0.5 text-xs'>\n        <WordRoll text={readsAs} />\n      </div>\n      <ul className='flex flex-col'>\n        {showsTypedRow && typedPeriod && (\n          <PeriodRow\n            label={capitalized(text)}\n            dates={textOfPeriod(typedPeriod, today)}\n            isSelected={isPhraseSelected(draft, typedPhrase)}\n            isPressed={pressed === 'typed'}\n            onSelect={selectTyped}\n          />\n        )}\n        {PERIOD_PRESETS.map((preset) => (\n          <PeriodRow\n            key={preset.phrase}\n            label={preset.label}\n            dates={textOfPeriod(readTypedPeriod(preset.phrase, today), today)}\n            isSelected={isPhraseSelected(draft, preset.phrase)}\n            onSelect={() => selectPhrase(preset.phrase)}\n          />\n        ))}\n      </ul>\n    </div>\n  );\n}\n\nfunction DaysStep({ picker, today, isTwoUp }: PanelProps) {\n  const { dayRange, chooseDays, showPeriods, draft } = picker;\n  const monthCount = twoUpCountOf(isTwoUp);\n  const firstShownMonth = firstShownMonthOf(today, monthCount);\n  const futureMatcher = futureMatcherOf(today);\n  const draftText = textOfPeriod(periodOfSelection(draft, today), today);\n  const calendarKey = `${monthCount}`;\n\n  return (\n    <div className='flex flex-col gap-1'>\n      <div className='flex items-center justify-between gap-3'>\n        <Button\n          variant='ghost'\n          size='sm'\n          onClick={showPeriods}\n          className='-ms-2'\n        >\n          <ChevronLeftIcon className='size-3.5' />\n          Periods\n        </Button>\n        <span className='text-muted-foreground text-xs tabular-nums'>\n          <WordRoll text={draftText} />\n        </span>\n      </div>\n      <AnimatedCalendar\n        key={calendarKey}\n        mode='range'\n        numberOfMonths={monthCount}\n        selected={dayRange}\n        onSelect={chooseDays}\n        defaultMonth={firstShownMonth}\n        disabled={futureMatcher}\n      />\n    </div>\n  );\n}\n\nfunction firstShownMonthOf(today: Date | null, monthCount: number) {\n  if (today === null) {\n    return undefined;\n  }\n  return addMonths(today, -(monthCount - 1));\n}\n\nfunction futureMatcherOf(today: Date | null): Matcher | undefined {\n  if (today === null) {\n    return undefined;\n  }\n  return { after: today };\n}\n\nfunction twoUpCountOf(isTwoUp: boolean) {\n  if (isTwoUp) {\n    return 2;\n  }\n  return 1;\n}\n\nfunction stepVariantsOf(shouldReduceMotion: boolean | null) {\n  const shift = SWAP_SHIFT_PX;\n  if (shouldReduceMotion) {\n    return {\n      enter: { opacity: 0 },\n      center: { opacity: 1 },\n      leave: { opacity: 0 },\n    };\n  }\n  return {\n    enter: (direction: number) => ({ opacity: 0, x: direction * shift }),\n    center: { opacity: 1, x: 0 },\n    leave: (direction: number) => ({ opacity: 0, x: -direction * shift }),\n  };\n}\n\nfunction PanelFooter({\n  picker,\n  today,\n  pressed,\n}: Pick<PanelProps, 'picker' | 'today' | 'pressed'>) {\n  const compareId = useId();\n  const { compare, changeCompare, draft, apply, cancel } = picker;\n  const period = periodOfSelection(draft, today);\n  const hasPeriod = period !== null;\n  const showsPrevious = compare && hasPeriod && today !== null;\n  let previousText = '';\n  if (period !== null && today !== null) {\n    previousText = periodTextOf(previousPeriodOf(period), today);\n  }\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div className='flex items-center justify-between gap-3'>\n        <Label htmlFor={compareId} className='font-normal'>\n          Compare with previous period\n        </Label>\n        <Switch\n          id={compareId}\n          checked={compare}\n          onCheckedChange={changeCompare}\n        />\n      </div>\n      <Fold open={showsPrevious}>\n        <p className='text-muted-foreground flex gap-1 text-xs'>\n          Previous\n          <WordRoll text={previousText} className='text-foreground' />\n        </p>\n      </Fold>\n      <div className='flex justify-end gap-2'>\n        <Button variant='ghost' size='sm' onClick={cancel}>\n          Cancel\n        </Button>\n        <Button\n          size='sm'\n          disabled={!hasPeriod}\n          onClick={apply}\n          className={pressedQuietOf(pressed === 'apply')}\n        >\n          Apply\n        </Button>\n      </div>\n    </div>\n  );\n}\n\ntype PeriodPickerProps = {\n  picker: PeriodPickerState;\n  today: Date | null;\n  /** The element the panel is drawn in, so it stays inside the component. */\n  container: RefObject<HTMLElement | null>;\n  isTwoUp: boolean;\n  /** True while a demonstration plays: it neither takes the focus nor gives it back. */\n  isDemonstrating: boolean;\n  pressed?: PressKey | null;\n};\n\nexport function PeriodPicker({\n  picker,\n  today,\n  container,\n  isTwoUp,\n  isDemonstrating,\n  pressed = null,\n}: PeriodPickerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const variants = stepVariantsOf(shouldReduceMotion);\n  const keepsFocus = !isDemonstrating;\n  const appliedPeriod = periodOfSelection(picker.applied, today);\n  const triggerText = textOfPeriod(appliedPeriod, today);\n  let previousText = '';\n  if (appliedPeriod !== null && today !== null) {\n    previousText = periodTextOf(previousPeriodOf(appliedPeriod), today);\n  }\n  const showsComparison = picker.appliedCompare && appliedPeriod !== null;\n  const panelProps = { picker, today, isTwoUp, pressed };\n\n  return (\n    <PopoverPrimitive.Root\n      open={picker.isOpen}\n      onOpenChange={picker.changeOpen}\n    >\n      <div className='flex w-full max-w-xs flex-col gap-1.5'>\n        <PopoverPrimitive.Trigger\n          render={\n            <Button\n              variant='outline'\n              className='w-full justify-between font-normal'\n              aria-label={`Period: ${triggerText}`}\n            />\n          }\n        >\n          {triggerLabelOf(today, triggerText)}\n          <CalendarIcon className='text-muted-foreground size-4' />\n        </PopoverPrimitive.Trigger>\n        <Fold open={showsComparison}>\n          <p className='text-muted-foreground flex gap-1 px-1 text-xs'>\n            Compared with\n            <WordRoll text={previousText} className='text-foreground' />\n          </p>\n        </Fold>\n      </div>\n      <PopoverPrimitive.Portal container={container}>\n        <PopoverPrimitive.Positioner\n          side='bottom'\n          align='start'\n          sideOffset={6}\n          className='z-50'\n        >\n          <PopoverPrimitive.Popup\n            initialFocus={false}\n            finalFocus={keepsFocus}\n            className={cn(\n              'surface-raised max-w-(--available-width) rounded-xl p-3 text-[13px] outline-none',\n              POPUP_TRANSITION\n            )}\n          >\n            <AnimatedSize axis='both'>\n              <div className='flex flex-col gap-3'>\n                <div className='relative'>\n                  <AnimatePresence\n                    mode='popLayout'\n                    initial={false}\n                    custom={picker.stepShift}\n                  >\n                    <motion.div\n                      key={picker.step}\n                      custom={picker.stepShift}\n                      variants={variants}\n                      initial='enter'\n                      animate='center'\n                      exit='leave'\n                      transition={{ duration: 0.18, ease: [0.23, 1, 0.32, 1] }}\n                    >\n                      {picker.step === 'periods' && (\n                        <PeriodsStep {...panelProps} />\n                      )}\n                      {picker.step === 'days' && <DaysStep {...panelProps} />}\n                    </motion.div>\n                  </AnimatePresence>\n                </div>\n                {picker.step === 'periods' && (\n                  <Button\n                    variant='ghost'\n                    size='sm'\n                    onClick={picker.showDays}\n                    className={cn(\n                      'justify-between',\n                      pressedQuietOf(pressed === 'days')\n                    )}\n                  >\n                    Pick exact days\n                    <ChevronRightIcon className='size-3.5 opacity-60' />\n                  </Button>\n                )}\n                <PanelFooter picker={picker} today={today} pressed={pressed} />\n              </div>\n            </AnimatedSize>\n          </PopoverPrimitive.Popup>\n        </PopoverPrimitive.Positioner>\n      </PopoverPrimitive.Portal>\n    </PopoverPrimitive.Root>\n  );\n}\n\nexport default function CalendarDatePicker30() {\n  const today = useToday();\n  const picker = usePeriodPicker(today);\n  const { pressed, press } = usePress<PressKey>();\n\n  function chooseDemoDays(isComplete: boolean) {\n    if (today === null) {\n      return;\n    }\n    const from = addDays(today, -12);\n    if (!isComplete) {\n      picker.chooseDays({ from, to: undefined });\n      return;\n    }\n    picker.chooseDays({ from, to: addDays(today, -4) });\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 2400, run: hold },\n    ...typingSteps('since sep 3', picker.changeText, {\n      startAfter: 400,\n      characterMs: 70,\n    }),\n    { after: 900, run: () => press('typed') },\n    { after: PRESS_LEAD_MS, run: picker.selectTyped },\n    { after: 1500, run: () => picker.changeCompare(true) },\n    { after: 1800, run: () => press('days') },\n    { after: PRESS_LEAD_MS, run: picker.showDays },\n    { after: 1400, run: () => chooseDemoDays(false) },\n    { after: 700, run: () => chooseDemoDays(true) },\n    { after: 1600, run: () => press('apply') },\n    { after: PRESS_LEAD_MS, run: picker.apply },\n    { after: 3000, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 1800,\n    onReset: picker.reset,\n  });\n  const isNarrow = useIsNarrow(ref, NARROW_REM);\n\n  useKeptHeight(ref);\n\n  return (\n    <div ref={ref} className='relative min-h-[34rem] w-full max-w-2xl'>\n      <PeriodPicker\n        picker={picker}\n        today={today}\n        container={ref}\n        isTwoUp={!isNarrow}\n        isDemonstrating={isAutoplaying}\n        pressed={pressed}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/calendar-date-picker-30.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/period-words.ts",
      "content": "import {\n  addDays,\n  addMonths,\n  addYears,\n  differenceInCalendarDays,\n  endOfMonth,\n  endOfQuarter,\n  endOfYear,\n  format,\n  isAfter,\n  isBefore,\n  isSameDay,\n  isSameYear,\n  startOfMonth,\n  startOfQuarter,\n  startOfWeek,\n  startOfYear,\n} from 'date-fns';\n\nimport { monthIndexOf, readTypedDate } from './typed-date';\n\nexport type Period = {\n  from: Date;\n  to: Date;\n};\n\nexport type PeriodPreset = {\n  phrase: string;\n  label: string;\n};\n\nconst COUNTED_PERIOD = /^(?:last|past) (\\d+) (days?|weeks?|months?)$/;\nconst QUARTER_PERIOD = /^q([1-4])(?: (\\d{4}))?$/;\nconst SINCE_PERIOD = /^since (.+)$/;\n\nconst MONDAY = 1;\n\nexport const PERIOD_PRESETS: PeriodPreset[] = [\n  { phrase: 'last 7 days', label: 'Last 7 days' },\n  { phrase: 'last 30 days', label: 'Last 30 days' },\n  { phrase: 'this month', label: 'This month' },\n  { phrase: 'last month', label: 'Last month' },\n  { phrase: 'this quarter', label: 'This quarter' },\n  { phrase: 'year to date', label: 'Year to date' },\n];\n\nfunction normalized(text: string) {\n  return text.toLowerCase().replace(/\\s+/g, ' ').trim();\n}\n\nfunction lastDaysOf(today: Date, days: number): Period {\n  return { from: addDays(today, -(days - 1)), to: today };\n}\n\nfunction countedPeriodOf(match: RegExpMatchArray, today: Date): Period | null {\n  const amount = Number(match[1]);\n  if (amount < 1) {\n    return null;\n  }\n  const unit = match[2][0];\n  if (unit === 'w') {\n    return lastDaysOf(today, amount * 7);\n  }\n  if (unit === 'm') {\n    const from = addDays(addMonths(today, -amount), 1);\n    return { from, to: today };\n  }\n  return lastDaysOf(today, amount);\n}\n\nfunction earlierDateOf(first: Date, second: Date) {\n  if (isBefore(first, second)) {\n    return first;\n  }\n  return second;\n}\n\nfunction quarterPeriodOf(match: RegExpMatchArray, today: Date): Period | null {\n  const quarter = Number(match[1]);\n  const year = Number(match[2] ?? today.getFullYear());\n  const from = new Date(year, (quarter - 1) * 3, 1);\n  if (isAfter(from, today)) {\n    return null;\n  }\n  const to = earlierDateOf(endOfQuarter(from), today);\n  return { from, to };\n}\n\nfunction sincePeriodOf(match: RegExpMatchArray, today: Date): Period | null {\n  const reading = readTypedDate(match[1], {\n    today,\n    withTime: false,\n    direction: 'past',\n  });\n  if (reading.status !== 'ready') {\n    return null;\n  }\n  const from = reading.value.date;\n  if (isAfter(from, today)) {\n    return null;\n  }\n  return { from, to: today };\n}\n\n/** A month named on its own is its latest one: \"sep\" in November is this September, \"dec\" is last December. */\nfunction monthPeriodOf(text: string, today: Date): Period | null {\n  const month = monthIndexOf(text);\n  if (month === -1) {\n    return null;\n  }\n  const isLater = month > today.getMonth();\n  let year = today.getFullYear();\n  if (isLater) {\n    year -= 1;\n  }\n  const from = new Date(year, month, 1);\n  return { from, to: earlierDateOf(endOfMonth(from), today) };\n}\n\nfunction namedPeriodOf(text: string, today: Date): Period | null {\n  const weekStart = startOfWeek(today, { weekStartsOn: MONDAY });\n  const lastMonth = addMonths(today, -1);\n  const lastQuarterStart = addMonths(startOfQuarter(today), -3);\n  const lastYear = addYears(today, -1);\n  if (text === 'today') {\n    return { from: today, to: today };\n  }\n  if (text === 'yesterday') {\n    const yesterday = addDays(today, -1);\n    return { from: yesterday, to: yesterday };\n  }\n  if (text === 'this week') {\n    return { from: weekStart, to: today };\n  }\n  if (text === 'last week') {\n    const from = addDays(weekStart, -7);\n    return { from, to: addDays(from, 6) };\n  }\n  if (text === 'this month') {\n    return { from: startOfMonth(today), to: today };\n  }\n  if (text === 'last month') {\n    return { from: startOfMonth(lastMonth), to: endOfMonth(lastMonth) };\n  }\n  if (text === 'this quarter') {\n    return { from: startOfQuarter(today), to: today };\n  }\n  if (text === 'last quarter') {\n    return { from: lastQuarterStart, to: endOfQuarter(lastQuarterStart) };\n  }\n  if (text === 'this year' || text === 'year to date' || text === 'ytd') {\n    return { from: startOfYear(today), to: today };\n  }\n  if (text === 'last year') {\n    return { from: startOfYear(lastYear), to: endOfYear(lastYear) };\n  }\n  return null;\n}\n\nexport function readPeriod(text: string, today: Date): Period | null {\n  const clean = normalized(text);\n  if (clean === '') {\n    return null;\n  }\n  const named = namedPeriodOf(clean, today);\n  if (named) {\n    return named;\n  }\n  const counted = clean.match(COUNTED_PERIOD);\n  if (counted) {\n    return countedPeriodOf(counted, today);\n  }\n  const quarter = clean.match(QUARTER_PERIOD);\n  if (quarter) {\n    return quarterPeriodOf(quarter, today);\n  }\n  const since = clean.match(SINCE_PERIOD);\n  if (since) {\n    return sincePeriodOf(since, today);\n  }\n  return monthPeriodOf(clean, today);\n}\n\nexport function previousPeriodOf(period: Period): Period {\n  const length = differenceInCalendarDays(period.to, period.from) + 1;\n  const to = addDays(period.from, -1);\n  const from = addDays(to, -(length - 1));\n  return { from, to };\n}\n\nfunction dayTextOf(date: Date, hasYear: boolean) {\n  if (hasYear) {\n    return format(date, 'MMM d, y');\n  }\n  return format(date, 'MMM d');\n}\n\nexport function periodTextOf(period: Period, today: Date) {\n  const isFromThisYear = isSameYear(period.from, today);\n  const isToThisYear = isSameYear(period.to, today);\n  const hasYear = !isFromThisYear || !isToThisYear;\n  const from = dayTextOf(period.from, hasYear);\n  if (isSameDay(period.from, period.to)) {\n    return from;\n  }\n  const to = dayTextOf(period.to, hasYear);\n  return `${from} to ${to}`;\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/_parts/period-words.ts"
    },
    {
      "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"
    }
  ],
  "categories": [
    "components",
    "calendar-date-picker"
  ],
  "type": "registry:component"
}