{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "calendar-date-picker-18",
  "title": "Month and year view",
  "description": "The month name opens a list of years to jump to any month between 1980 and 2030.",
  "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/collapsible.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/scroll-area.json",
    "https://ui.ndekocode.dev/r/theme.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-18.tsx",
      "content": "'use client';\n\nimport {\n  eachMonthOfInterval,\n  eachYearOfInterval,\n  endOfYear,\n  format,\n  isAfter,\n  isBefore,\n  startOfYear,\n} from 'date-fns';\nimport { createContext, useContext, useEffect, useRef, useState } from 'react';\nimport type { CaptionLabelProps, MonthGridProps } from 'react-day-picker';\n\nimport { ChevronDownIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport {\n  Collapsible,\n  CollapsibleContent,\n  CollapsibleTrigger,\n} from '@/registry/ndeko/ui/collapsible';\nimport { ScrollArea } from '@/registry/ndeko/ui/scroll-area';\n\nimport { AnimatedCalendar } from './_parts/animated-calendar';\n\nconst START_MONTH = new Date(1980, 6);\nconst END_MONTH = new Date(2030, 6);\nconst YEARS = eachYearOfInterval({\n  start: startOfYear(START_MONTH),\n  end: endOfYear(END_MONTH),\n});\nconst FOCUS_DELAY_MS = 100;\n\ntype YearViewState = {\n  isYearView: boolean;\n  toggleYearView: () => void;\n  currentYear: number;\n  currentMonth: number;\n  selectMonth: (month: Date) => void;\n};\n\nconst YearViewContext = createContext<YearViewState | null>(null);\n\nfunction useYearView() {\n  const state = useContext(YearViewContext);\n  if (!state) {\n    throw new Error('The year view parts must sit inside its provider.');\n  }\n  return state;\n}\n\nfunction refWhen<T>(isTarget: boolean, ref: React.RefObject<T | null>) {\n  if (isTarget) {\n    return ref;\n  }\n  return undefined;\n}\n\nfunction monthVariantOf(isCurrentMonth: boolean) {\n  if (isCurrentMonth) {\n    return 'default';\n  }\n  return 'outline';\n}\n\nfunction isOutsideRange(month: Date) {\n  const isTooEarly = isBefore(month, START_MONTH);\n  const isTooLate = isAfter(month, END_MONTH);\n  return isTooEarly || isTooLate;\n}\n\nfunction monthsOf(year: Date) {\n  return eachMonthOfInterval({\n    start: startOfYear(year),\n    end: endOfYear(year),\n  });\n}\n\nfunction YearViewCaption({ children }: CaptionLabelProps) {\n  const { isYearView, toggleYearView } = useYearView();\n\n  return (\n    <Button\n      variant='ghost'\n      size='sm'\n      className='-ms-2 text-[13px] font-medium'\n      aria-expanded={isYearView}\n      onClick={toggleYearView}\n    >\n      {children}\n      <ChevronDownIcon\n        className={cn(\n          'text-muted-foreground shrink-0 transition-transform duration-200',\n          isYearView && 'rotate-180'\n        )}\n      />\n    </Button>\n  );\n}\n\nfunction YearSection({\n  title,\n  defaultOpen,\n  children,\n}: {\n  title: string;\n  defaultOpen: boolean;\n  children: React.ReactNode;\n}) {\n  return (\n    <Collapsible\n      defaultOpen={defaultOpen}\n      className='hairline-t border-border px-2 py-1.5'\n    >\n      <CollapsibleTrigger\n        render={\n          <Button\n            variant='ghost'\n            size='sm'\n            className='w-full justify-start text-[13px] font-medium [&[data-panel-open]>svg]:rotate-180'\n          />\n        }\n      >\n        <ChevronDownIcon className='text-muted-foreground shrink-0 transition-transform duration-200' />\n        {title}\n      </CollapsibleTrigger>\n      <CollapsibleContent>\n        <div className='grid grid-cols-3 gap-2 px-3 py-1'>{children}</div>\n      </CollapsibleContent>\n    </Collapsible>\n  );\n}\n\nfunction YearList() {\n  const { currentYear, currentMonth, selectMonth } = useYearView();\n  const listRef = useRef<HTMLDivElement>(null);\n  const currentYearRef = useRef<HTMLDivElement>(null);\n  const currentMonthRef = useRef<HTMLButtonElement>(null);\n\n  useEffect(() => {\n    const viewport = listRef.current?.querySelector<HTMLElement>(\n      '[data-slot=scroll-area-viewport]'\n    );\n    const yearElement = currentYearRef.current;\n    if (viewport && yearElement) {\n      viewport.scrollTop = yearElement.offsetTop;\n    }\n    const focusTimer = window.setTimeout(() => {\n      currentMonthRef.current?.focus();\n    }, FOCUS_DELAY_MS);\n    return () => window.clearTimeout(focusTimer);\n  }, []);\n\n  return (\n    <div ref={listRef} className='bg-card absolute inset-0 z-20 -mx-2 -mb-2'>\n      <ScrollArea className='h-full'>\n        {YEARS.map((year) => {\n          const yearNumber = year.getFullYear();\n          const isCurrentYear = yearNumber === currentYear;\n\n          return (\n            <div key={yearNumber} ref={refWhen(isCurrentYear, currentYearRef)}>\n              <YearSection\n                title={String(yearNumber)}\n                defaultOpen={isCurrentYear}\n              >\n                {monthsOf(year).map((month) => {\n                  const isSameMonthNumber = month.getMonth() === currentMonth;\n                  const isCurrentMonth = isSameMonthNumber && isCurrentYear;\n\n                  return (\n                    <Button\n                      key={month.getTime()}\n                      ref={refWhen(isCurrentMonth, currentMonthRef)}\n                      variant={monthVariantOf(isCurrentMonth)}\n                      size='sm'\n                      disabled={isOutsideRange(month)}\n                      onClick={() => selectMonth(month)}\n                    >\n                      {format(month, 'MMM')}\n                    </Button>\n                  );\n                })}\n              </YearSection>\n            </div>\n          );\n        })}\n      </ScrollArea>\n    </div>\n  );\n}\n\nfunction YearViewGrid({ children, ...props }: MonthGridProps) {\n  const { isYearView } = useYearView();\n\n  return (\n    <div className='relative'>\n      <table {...props}>{children}</table>\n      {isYearView && <YearList />}\n    </div>\n  );\n}\n\nexport default function CalendarDatePicker18() {\n  const [month, setMonth] = useState(() => new Date());\n  const [date, setDate] = useState<Date | undefined>(() => new Date());\n  const [isYearView, setIsYearView] = useState(false);\n\n  function toggleYearView() {\n    setIsYearView((isOpen) => !isOpen);\n  }\n\n  function selectMonth(selectedMonth: Date) {\n    setMonth(selectedMonth);\n    setIsYearView(false);\n  }\n\n  const yearView: YearViewState = {\n    isYearView,\n    toggleYearView,\n    currentYear: month.getFullYear(),\n    currentMonth: month.getMonth(),\n    selectMonth,\n  };\n\n  return (\n    <YearViewContext.Provider value={yearView}>\n      <AnimatedCalendar\n        mode='single'\n        selected={date}\n        onSelect={setDate}\n        month={month}\n        onMonthChange={setMonth}\n        startMonth={START_MONTH}\n        endMonth={END_MONTH}\n        className='bg-card hairline-ring ring-border overflow-hidden rounded-xl p-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n        classNames={{\n          month_caption: 'ms-2.5 me-20 justify-start',\n          nav: 'justify-end',\n        }}\n        components={{\n          CaptionLabel: YearViewCaption,\n          MonthGrid: YearViewGrid,\n        }}\n      />\n    </YearViewContext.Provider>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/calendar-date-picker/calendar-date-picker-18.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"
    }
  ],
  "categories": [
    "components",
    "calendar-date-picker"
  ],
  "type": "registry:component"
}