{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "date-picker",
  "title": "Date Picker",
  "description": "Single-date and range picker with range presets, date shortcuts, billing cycles, min and max dates, an Apply step, and Date or unix timestamp values.",
  "dependencies": [
    "date-fns",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "calendar",
    "input",
    "popover"
  ],
  "files": [
    {
      "path": "components/dentil/date-picker/date-picker.tsx",
      "content": "'use client';\n\nimport {\n  endOfDay as toEndOfDay,\n  format,\n  fromUnixTime,\n  getUnixTime,\n  isAfter,\n  isBefore,\n  isValid,\n  startOfDay,\n} from 'date-fns';\nimport { CalendarIcon, XIcon } from 'lucide-react';\nimport * as React from 'react';\n\nimport { Button } from '@/components/ui/button';\nimport { Calendar } from '@/components/ui/calendar';\nimport { Input } from '@/components/ui/input';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\nimport { cn } from '@/lib/utils';\n\nimport {\n  defaultSingleDateShortcuts,\n  getCycleDate,\n  quickSelectOptions,\n  type CycleConfig,\n  type QuickSelectOption,\n  type SingleDateShortcut,\n} from './presets';\n\nexport type DatePickerMode = 'single' | 'range';\n/** `'date'` returns `Date` objects, `'timestamp'` returns unix seconds. */\nexport type DatePickerReturnFormat = 'date' | 'timestamp';\n\ntype Output<F extends DatePickerReturnFormat> = F extends 'date' ? Date : number;\n\nexport type DatePickerValue<T extends DatePickerMode, F extends DatePickerReturnFormat = 'date'> = T extends 'single'\n  ? Output<F> | undefined\n  : { start: Output<F> | undefined; end: Output<F> | undefined };\n\nexport interface DatePickerProps<T extends DatePickerMode, F extends DatePickerReturnFormat = 'date'> {\n  mode: T;\n  returnFormat?: F;\n  value: DatePickerValue<T, F> | null | undefined;\n  onChange: (value: DatePickerValue<T, F> | undefined) => void;\n  placeholder?: string;\n  /** A date-fns format string for the trigger label. */\n  dateFormat?: string;\n  className?: string;\n  disabled?: boolean;\n  showClear?: boolean;\n  align?: 'start' | 'center' | 'end';\n  buttonSize?: 'sm' | 'default';\n  /** Move a range's end to 23:59:59.999 of its day. */\n  endOfDay?: boolean;\n  /** Show range presets beside the calendar. */\n  showQuickSelect?: boolean;\n  presets?: QuickSelectOption[];\n  /** Show `shortcuts` and `cycleConfig` cycles beside the single-date calendar. */\n  showShortcuts?: boolean;\n  shortcuts?: SingleDateShortcut[];\n  cycleConfig?: CycleConfig;\n  /** A `Date` or unix seconds. Earlier days are disabled. */\n  minDate?: Date | number;\n  /** A `Date` or unix seconds. Later days are disabled. */\n  maxDate?: Date | number;\n  /** A `Date` or unix seconds. The month shown on open when there's no value. */\n  defaultMonth?: Date | number;\n  /** Hold the selection until Apply is clicked. Closing without applying discards it. */\n  showApplyButton?: boolean;\n}\n\ntype Range = { from?: Date; to?: Date };\n\nfunction toDate(value: Date | number | null | undefined): Date | undefined {\n  if (value instanceof Date) return isValid(value) ? value : undefined;\n  if (typeof value === 'number' && Number.isFinite(value)) return fromUnixTime(value);\n  return undefined;\n}\n\nfunction isInBounds(date: Date, min?: Date, max?: Date) {\n  const day = startOfDay(date);\n  if (min && isBefore(day, startOfDay(min))) return false;\n  if (max && isAfter(day, startOfDay(max))) return false;\n  return true;\n}\n\nconst sideButtonClassName =\n  'hover:bg-muted focus-visible:bg-muted w-full rounded-md p-2 text-left text-sm transition-colors outline-none disabled:pointer-events-none disabled:opacity-50';\n\nfunction QuickSelect({\n  presets,\n  onSelect,\n}: {\n  presets: QuickSelectOption[];\n  onSelect: (option: QuickSelectOption) => void;\n}) {\n  return (\n    <div className=\"w-38 border-l p-3\">\n      {presets.map((option) => (\n        <button key={option.value} type=\"button\" onClick={() => onSelect(option)} className={sideButtonClassName}>\n          {option.label}\n        </button>\n      ))}\n    </div>\n  );\n}\n\nfunction SingleShortcuts({\n  shortcuts,\n  cycleConfig,\n  onSelect,\n  minDate,\n  maxDate,\n  dateFormat,\n}: {\n  shortcuts: SingleDateShortcut[];\n  cycleConfig?: CycleConfig;\n  onSelect: (date: Date) => void;\n  minDate?: Date;\n  maxDate?: Date;\n  dateFormat: string;\n}) {\n  const [customCycles, setCustomCycles] = React.useState('');\n  const durationMonths = cycleConfig?.durationMonths ?? 1;\n  const cycleLabel = durationMonths === 1 ? 'month' : `${durationMonths} months`;\n\n  const custom = Number.parseInt(customCycles, 10);\n  const customDate =\n    cycleConfig && custom >= 1 ? getCycleDate(cycleConfig.startDate, custom, durationMonths) : undefined;\n  const customValid = !!customDate && isInBounds(customDate, minDate, maxDate);\n\n  const applyCustom = () => {\n    if (!customDate || !customValid) return;\n    onSelect(customDate);\n    setCustomCycles('');\n  };\n\n  return (\n    <div className=\"w-46 border-l p-3\">\n      {shortcuts.length > 0 && (\n        <div className=\"mb-2\">\n          {shortcuts.map((shortcut) => {\n            const date = shortcut.getDate();\n            return (\n              <button\n                key={shortcut.value}\n                type=\"button\"\n                disabled={!isInBounds(date, minDate, maxDate)}\n                onClick={() => onSelect(date)}\n                className={sideButtonClassName}>\n                {shortcut.label}\n              </button>\n            );\n          })}\n        </div>\n      )}\n\n      {cycleConfig && (\n        <div className={cn(shortcuts.length > 0 && 'border-t pt-2')}>\n          <div className=\"text-muted-foreground mb-1 px-2 text-xs font-medium\">Cycles ({cycleLabel})</div>\n          {[1, 3, 4, 6, 12].map((cycles) => {\n            const date = getCycleDate(cycleConfig.startDate, cycles, durationMonths);\n            return (\n              <button\n                key={cycles}\n                type=\"button\"\n                disabled={!isInBounds(date, minDate, maxDate)}\n                onClick={() => onSelect(date)}\n                className={sideButtonClassName}>\n                {cycles} cycle{cycles > 1 ? 's' : ''}\n                <span className=\"text-muted-foreground ml-1 text-xs\">({format(date, dateFormat)})</span>\n              </button>\n            );\n          })}\n          <div className=\"mt-2 flex gap-1 px-1\">\n            <Input\n              type=\"number\"\n              min={1}\n              placeholder=\"24\"\n              aria-label=\"Number of cycles\"\n              value={customCycles}\n              onChange={(e) => setCustomCycles(e.target.value)}\n              onKeyDown={(e) => {\n                if (e.key === 'Enter') {\n                  e.preventDefault();\n                  applyCustom();\n                }\n              }}\n              className=\"h-8\"\n            />\n            <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={!customValid} onClick={applyCustom}>\n              Apply\n            </Button>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport function DatePicker<T extends DatePickerMode, F extends DatePickerReturnFormat = 'date'>({\n  mode,\n  returnFormat = 'date' as F,\n  value,\n  onChange,\n  placeholder,\n  dateFormat = 'd MMM yyyy',\n  className,\n  disabled = false,\n  showClear = true,\n  align = 'start',\n  buttonSize = 'default',\n  endOfDay = true,\n  showQuickSelect = false,\n  presets = quickSelectOptions,\n  showShortcuts = false,\n  shortcuts = defaultSingleDateShortcuts,\n  cycleConfig,\n  minDate,\n  maxDate,\n  defaultMonth,\n  showApplyButton = false,\n}: DatePickerProps<T, F>) {\n  const [open, setOpen] = React.useState(false);\n  const [draftDate, setDraftDate] = React.useState<Date>();\n  const [draftRange, setDraftRange] = React.useState<Range>();\n\n  const min = toDate(minDate);\n  const max = toDate(maxDate);\n\n  const single = mode === 'single' ? toDate(value as Date | number | undefined) : undefined;\n  const rangeValue = mode === 'range' ? (value as { start?: Date | number; end?: Date | number } | null) : null;\n  const range: Range = { from: toDate(rangeValue?.start), to: toDate(rangeValue?.end) };\n\n  const out = (date: Date) => (returnFormat === 'timestamp' ? getUnixTime(date) : date) as Output<F>;\n  const emit = (next: DatePickerValue<T, F> | undefined) => onChange(next);\n\n  const commitSingle = (date: Date | undefined) => emit((date ? out(date) : undefined) as DatePickerValue<T, F>);\n  const commitRange = (from: Date, to: Date) =>\n    emit({ start: out(from), end: out(endOfDay ? toEndOfDay(to) : to) } as DatePickerValue<T, F>);\n\n  const handleOpenChange = (next: boolean) => {\n    if (next) {\n      setDraftDate(undefined);\n      setDraftRange(range.from ? range : undefined);\n    }\n    setOpen(next);\n  };\n\n  const selectSingle = (date: Date | undefined) => {\n    if (showApplyButton) {\n      setDraftDate(date);\n      return;\n    }\n    commitSingle(date);\n    if (date) setOpen(false);\n  };\n\n  const selectRangeDay = (day: Date) => {\n    const current = draftRange;\n    let next: Range;\n    if (!current?.from || current.to) next = { from: day };\n    else if (isBefore(day, current.from)) next = { from: day, to: current.from };\n    else next = { from: current.from, to: day };\n\n    setDraftRange(next);\n    if (next.from && next.to && !showApplyButton) {\n      commitRange(next.from, next.to);\n      setOpen(false);\n    }\n  };\n\n  const selectPreset = (option: QuickSelectOption) => {\n    const { start, end } = option.getRange();\n    setDraftRange({ from: start, to: end });\n    if (!showApplyButton) {\n      commitRange(start, end);\n      setOpen(false);\n    }\n  };\n\n  const apply = () => {\n    if (mode === 'single' && draftDate) commitSingle(draftDate);\n    if (mode === 'range' && draftRange?.from && draftRange.to) commitRange(draftRange.from, draftRange.to);\n    setOpen(false);\n  };\n\n  const clear = () => {\n    setDraftDate(undefined);\n    setDraftRange(undefined);\n    emit(undefined);\n  };\n\n  const isEmpty = mode === 'single' ? !single : !range.from && !range.to;\n  const canApply = mode === 'single' ? !!draftDate : !!(draftRange?.from && draftRange.to);\n\n  let label: string;\n  if (mode === 'single') {\n    label = single ? format(single, dateFormat) : (placeholder ?? 'Select a date');\n  } else if (range.from && range.to) {\n    label = `${format(range.from, dateFormat)} - ${format(range.to, dateFormat)}`;\n  } else if (range.from) {\n    label = format(range.from, dateFormat);\n  } else {\n    label = placeholder ?? 'Select a date range';\n  }\n\n  const disabledDays = disabled ? true : [...(min ? [{ before: min }] : []), ...(max ? [{ after: max }] : [])];\n  const month = toDate(defaultMonth) ?? (mode === 'single' ? single : (draftRange?.from ?? range.from)) ?? min;\n  const showClearButton = showClear && !isEmpty && !disabled;\n\n  return (\n    <div data-slot=\"date-picker\" className={cn('relative inline-flex', className)}>\n      <Popover open={open} onOpenChange={handleOpenChange}>\n        <PopoverTrigger asChild>\n          <Button\n            type=\"button\"\n            size={buttonSize}\n            variant=\"outline\"\n            disabled={disabled}\n            data-empty={isEmpty}\n            className={cn(\n              'data-[empty=true]:text-muted-foreground w-full justify-start text-left font-normal',\n              showClearButton && 'pr-9'\n            )}>\n            <CalendarIcon className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"flex-1 truncate\">{label}</span>\n          </Button>\n        </PopoverTrigger>\n        <PopoverContent className=\"w-auto p-0\" align={align}>\n          <div className=\"flex\">\n            {mode === 'single' ? (\n              <Calendar\n                mode=\"single\"\n                selected={showApplyButton ? (draftDate ?? single) : single}\n                onSelect={selectSingle}\n                defaultMonth={month}\n                disabled={disabledDays}\n              />\n            ) : (\n              <Calendar\n                mode=\"range\"\n                selected={draftRange ? { from: draftRange.from, to: draftRange.to } : undefined}\n                onSelect={(_, day) => selectRangeDay(day)}\n                defaultMonth={month}\n                disabled={disabledDays}\n                numberOfMonths={2}\n              />\n            )}\n            {mode === 'range' && showQuickSelect && <QuickSelect presets={presets} onSelect={selectPreset} />}\n            {mode === 'single' && showShortcuts && (shortcuts.length > 0 || cycleConfig) && (\n              <SingleShortcuts\n                shortcuts={shortcuts}\n                cycleConfig={cycleConfig}\n                onSelect={(date) => selectSingle(date)}\n                minDate={min}\n                maxDate={max}\n                dateFormat={dateFormat}\n              />\n            )}\n          </div>\n          {showApplyButton && (\n            <div className=\"flex justify-end gap-2 border-t p-3\">\n              <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => handleOpenChange(false)}>\n                Cancel\n              </Button>\n              <Button type=\"button\" size=\"sm\" disabled={!canApply} onClick={apply}>\n                Apply\n              </Button>\n            </div>\n          )}\n        </PopoverContent>\n      </Popover>\n      {showClearButton && (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon\"\n          aria-label={mode === 'single' ? 'Clear date' : 'Clear date range'}\n          onClick={clear}\n          className=\"text-muted-foreground absolute top-1/2 right-1.5 size-6 -translate-y-1/2\">\n          <XIcon className=\"size-3.5\" />\n        </Button>\n      )}\n    </div>\n  );\n}\n\nexport function SingleDatePicker<F extends DatePickerReturnFormat = 'date'>(\n  props: Omit<DatePickerProps<'single', F>, 'mode'>\n) {\n  return <DatePicker mode=\"single\" {...props} />;\n}\n\nexport function DateRangePicker<F extends DatePickerReturnFormat = 'date'>(\n  props: Omit<DatePickerProps<'range', F>, 'mode'>\n) {\n  return <DatePicker mode=\"range\" {...props} />;\n}\n\nexport type { CycleConfig, QuickSelectOption, SingleDateShortcut } from './presets';\nexport { defaultSingleDateShortcuts, getCycleDate, quickSelectOptions } from './presets';\n",
      "type": "registry:component",
      "target": "components/dentil/date-picker/date-picker.tsx"
    },
    {
      "path": "components/dentil/date-picker/presets.ts",
      "content": "import {\n  addMonths,\n  addSeconds,\n  endOfDay,\n  fromUnixTime,\n  startOfDay,\n  startOfMonth,\n  startOfQuarter,\n  startOfYear,\n  subDays,\n  subMonths,\n  subWeeks,\n} from 'date-fns';\n\n/** A range preset shown beside the range calendar. */\nexport interface QuickSelectOption {\n  label: string;\n  value: string;\n  getRange: () => { start: Date; end: Date };\n}\n\n/** A one-click date shown beside the single-date calendar. */\nexport interface SingleDateShortcut {\n  label: string;\n  value: string;\n  getDate: () => Date;\n}\n\n/** Billing-style cycles: each one ends the second before `startDate` plus `durationMonths`. */\nexport interface CycleConfig {\n  /** A `Date` or unix seconds. */\n  startDate: Date | number;\n  durationMonths?: number;\n}\n\nexport const quickSelectOptions: QuickSelectOption[] = [\n  {\n    label: 'Last 7 days',\n    value: 'last_7_days',\n    getRange: () => ({ start: startOfDay(subDays(new Date(), 6)), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Last 4 weeks',\n    value: 'last_4_weeks',\n    getRange: () => ({ start: startOfDay(subWeeks(new Date(), 4)), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Last 6 months',\n    value: 'last_6_months',\n    getRange: () => ({ start: startOfDay(subMonths(new Date(), 6)), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Last 12 months',\n    value: 'last_12_months',\n    getRange: () => ({ start: startOfDay(subMonths(new Date(), 12)), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Month to date',\n    value: 'month_to_date',\n    getRange: () => ({ start: startOfMonth(new Date()), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Quarter to date',\n    value: 'quarter_to_date',\n    getRange: () => ({ start: startOfQuarter(new Date()), end: endOfDay(new Date()) }),\n  },\n  {\n    label: 'Year to date',\n    value: 'year_to_date',\n    getRange: () => ({ start: startOfYear(new Date()), end: endOfDay(new Date()) }),\n  },\n];\n\nexport const defaultSingleDateShortcuts: SingleDateShortcut[] = [\n  { label: 'Today', value: 'today', getDate: () => startOfDay(new Date()) },\n  { label: '1st of next month', value: 'first_next_month', getDate: () => startOfMonth(addMonths(new Date(), 1)) },\n];\n\n/** The last second of the given cycle, e.g. cycle 1 from 15 Jan ends 14 Feb 23:59:59. */\nexport function getCycleDate(startDate: Date | number, cycles: number, durationMonths = 1): Date {\n  const start = typeof startDate === 'number' ? fromUnixTime(startDate) : startDate;\n  return addSeconds(startOfDay(addMonths(start, cycles * durationMonths)), -1);\n}\n",
      "type": "registry:lib",
      "target": "components/dentil/date-picker/presets.ts"
    }
  ],
  "type": "registry:block"
}
