@dinachi/cli 1.0.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/dist/index.js +244 -72
- package/package.json +5 -1
- package/templates/accordion/accordion.tsx +5 -1
- package/templates/agent/agent.tsx +35 -18
- package/templates/alert/alert.tsx +345 -0
- package/templates/alert/index.ts +16 -0
- package/templates/alert-dialog/alert-dialog.tsx +14 -3
- package/templates/animated-icon/animated-icon.tsx +1 -0
- package/templates/animated-list/animated-list.tsx +2 -1
- package/templates/animated-tabs/animated-tabs.tsx +4 -0
- package/templates/ask-bar/ask-bar.tsx +1061 -0
- package/templates/ask-bar/index.ts +1 -0
- package/templates/autocomplete/autocomplete.tsx +14 -4
- package/templates/avatar/avatar.tsx +3 -0
- package/templates/badge/badge.tsx +1 -0
- package/templates/breadcrumb/breadcrumb.tsx +606 -0
- package/templates/breadcrumb/index.ts +9 -0
- package/templates/button/button.tsx +1 -0
- package/templates/calendar/calendar.tsx +1155 -0
- package/templates/calendar/index.ts +15 -0
- package/templates/card/card.tsx +6 -1
- package/templates/carousel/carousel.tsx +7 -0
- package/templates/checkbox/checkbox.tsx +1 -0
- package/templates/checkbox-group/checkbox-group.tsx +1 -0
- package/templates/collapsible/collapsible.tsx +3 -1
- package/templates/combobox/combobox.tsx +15 -4
- package/templates/command-items/command-items.tsx +69 -0
- package/templates/command-items/index.ts +1 -0
- package/templates/command-palette/command-palette.tsx +954 -0
- package/templates/command-palette/index.ts +1 -0
- package/templates/compare-slider/compare-slider.tsx +1 -0
- package/templates/comparison-table/comparison-table.tsx +540 -0
- package/templates/comparison-table/index.ts +15 -0
- package/templates/context-menu/context-menu.tsx +61 -14
- package/templates/data-table/data-table.tsx +2077 -0
- package/templates/data-table/index.ts +14 -0
- package/templates/date-picker/date-picker.tsx +527 -0
- package/templates/date-picker/index.ts +2 -0
- package/templates/date-range-picker/date-range-picker.tsx +504 -0
- package/templates/date-range-picker/index.ts +2 -0
- package/templates/detail-list/detail-list.tsx +419 -0
- package/templates/detail-list/index.ts +12 -0
- package/templates/dialog/dialog.tsx +13 -3
- package/templates/drawer/drawer.tsx +19 -6
- package/templates/expandable-card/expandable-card.tsx +5 -1
- package/templates/field/field.tsx +5 -1
- package/templates/fieldset/fieldset.tsx +2 -0
- package/templates/form/form.tsx +1 -0
- package/templates/heat-table/heat-table.tsx +613 -0
- package/templates/heat-table/index.ts +9 -0
- package/templates/hold-to-confirm/hold-to-confirm.tsx +1 -0
- package/templates/input/input.tsx +1 -0
- package/templates/label/label.tsx +1 -0
- package/templates/link/link.tsx +1 -0
- package/templates/load-transition/load-transition.tsx +1 -0
- package/templates/marquee/marquee.tsx +1 -0
- package/templates/menu/menu.tsx +27 -6
- package/templates/menubar/menubar.tsx +15 -3
- package/templates/meter/meter.tsx +5 -1
- package/templates/month-picker/index.ts +1 -0
- package/templates/month-picker/month-picker.tsx +351 -0
- package/templates/navigation-menu/navigation-menu.tsx +13 -2
- package/templates/number-field/number-field.tsx +7 -1
- package/templates/number-ticker/number-ticker.tsx +3 -0
- package/templates/omnibar/index.ts +1 -0
- package/templates/omnibar/omnibar.tsx +1009 -0
- package/templates/otp-field/otp-field.tsx +4 -0
- package/templates/pagination/index.ts +8 -0
- package/templates/pagination/pagination.tsx +389 -0
- package/templates/popover/popover.tsx +19 -5
- package/templates/preview-card/preview-card.tsx +11 -3
- package/templates/progress/progress.tsx +5 -1
- package/templates/progress-ring/progress-ring.tsx +1 -0
- package/templates/radio/radio.tsx +3 -0
- package/templates/scroll-area/scroll-area.tsx +14 -4
- package/templates/scroll-progress/scroll-progress.tsx +1 -0
- package/templates/scroll-reveal/scroll-reveal.tsx +1 -0
- package/templates/select/select.tsx +18 -2
- package/templates/separator/separator.tsx +1 -0
- package/templates/skeleton/skeleton.tsx +1 -0
- package/templates/slider/slider.tsx +7 -0
- package/templates/sortable/sortable.tsx +3 -0
- package/templates/stagger-list/stagger-list.tsx +2 -0
- package/templates/streaming-text/streaming-text.tsx +1 -0
- package/templates/swipeable-row/swipeable-row.tsx +1 -0
- package/templates/switch/switch.tsx +2 -0
- package/templates/table/index.ts +13 -0
- package/templates/table/table.tsx +265 -0
- package/templates/tabs/tabs.tsx +5 -0
- package/templates/text/text.tsx +1 -0
- package/templates/text-morph/text-morph.tsx +2 -0
- package/templates/text-shimmer/text-shimmer.tsx +1 -0
- package/templates/textarea/textarea.tsx +1 -0
- package/templates/time-slots/index.ts +1 -0
- package/templates/time-slots/time-slots.tsx +589 -0
- package/templates/toast/toast.tsx +10 -1
- package/templates/toggle/toggle.tsx +1 -0
- package/templates/toggle-group/toggle-group.tsx +2 -0
- package/templates/toolbar/toolbar.tsx +6 -0
- package/templates/tooltip/tooltip.tsx +9 -3
- package/templates/week-strip/index.ts +1 -0
- package/templates/week-strip/week-strip.tsx +329 -0
- package/templates/year-view/index.ts +1 -0
- package/templates/year-view/year-view.tsx +362 -0
|
@@ -0,0 +1,1155 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { DayPicker, useDayPicker, type DayButtonProps, type DayPickerLocale, type DayProps, type MonthCaptionProps, type MonthGridProps, type MonthProps, type Matcher, type NavProps } from "react-day-picker";
|
|
3
|
+
import { format, type Locale } from "date-fns";
|
|
4
|
+
import { Select as SelectPrimitive } from "@base-ui/react/select";
|
|
5
|
+
import { Check, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";
|
|
6
|
+
import { cn } from "@/lib/utils";
|
|
7
|
+
import { changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent";
|
|
8
|
+
|
|
9
|
+
/* ----------------------------------------------------------------------------------------
|
|
10
|
+
* Dates. A day is a Date at local midnight, so it means the same calendar day wherever it
|
|
11
|
+
* is read, and forms carry it as YYYY-MM-DD. Nothing here converts time zones.
|
|
12
|
+
* ------------------------------------------------------------------------------------- */
|
|
13
|
+
|
|
14
|
+
const DAY_MS = 86_400_000;
|
|
15
|
+
|
|
16
|
+
function startOfDay(date: Date): Date {
|
|
17
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function addDays(date: Date, days: number): Date {
|
|
21
|
+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function addMonths(date: Date, months: number): Date {
|
|
25
|
+
return new Date(date.getFullYear(), date.getMonth() + months, 1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isSameDay(a: Date | null | undefined, b: Date | null | undefined): boolean {
|
|
29
|
+
return !!a && !!b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Whole days from `a` to `b`, counted on the calendar so daylight saving never shifts it. */
|
|
33
|
+
function daysBetween(a: Date, b: Date): number {
|
|
34
|
+
return Math.round((Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / DAY_MS);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function monthsBetween(a: Date, b: Date): number {
|
|
38
|
+
return (b.getFullYear() - a.getFullYear()) * 12 + b.getMonth() - a.getMonth();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The ISO 8601 week number: weeks start on Monday, and week 1 holds the year's first Thursday. */
|
|
42
|
+
function isoWeek(date: Date): number {
|
|
43
|
+
const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
|
|
44
|
+
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
|
|
45
|
+
return Math.ceil(((d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 1)) / DAY_MS + 1) / 7);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const pad = (n: number) => String(n).padStart(2, "0");
|
|
49
|
+
|
|
50
|
+
/** `YYYY-MM-DD`, the form a day is submitted and reported in. */
|
|
51
|
+
function toISODate(date: Date): string {
|
|
52
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The day a real calendar date names, or null when the parts don't make one (31 Feb). */
|
|
56
|
+
function makeDate(year: number, month: number, day: number): Date | null {
|
|
57
|
+
const d = new Date(year, month, day);
|
|
58
|
+
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day ? d : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function fromISODate(text: string): Date | null {
|
|
62
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text.trim());
|
|
63
|
+
return m ? makeDate(+m[1], +m[2] - 1, +m[3]) : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
|
|
67
|
+
const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
|
|
68
|
+
|
|
69
|
+
/** The index of the name `word` spells or shortens to three letters or more, else -1. */
|
|
70
|
+
const nameIn = (names: string[], word: string) => (word.length < 3 ? -1 : names.findIndex((n) => n.startsWith(word)));
|
|
71
|
+
|
|
72
|
+
export interface ParseDateOptions {
|
|
73
|
+
/** The day relative phrases count from. Defaults to today. */
|
|
74
|
+
today?: Date;
|
|
75
|
+
/** How a numeric date such as 3/12 is read. Defaults to the order the browser's language writes dates in. */
|
|
76
|
+
order?: "day-first" | "month-first";
|
|
77
|
+
/** The day a week starts on, which decides what "next fri" means. Defaults to Monday. */
|
|
78
|
+
weekStartsOn?: number;
|
|
79
|
+
/** The earliest day the field takes. A two-digit year lands inside `min` and `max` when it can. */
|
|
80
|
+
min?: Date;
|
|
81
|
+
max?: Date;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether `locale` writes the day before the month, read off how it formats a known date. */
|
|
85
|
+
function dayFirst(locale?: Locale): boolean {
|
|
86
|
+
const page = typeof document !== "undefined" ? document.documentElement.lang : "";
|
|
87
|
+
const code = locale?.code ?? (page || (typeof navigator !== "undefined" ? navigator.language : "en-GB"));
|
|
88
|
+
try {
|
|
89
|
+
const parts = new Intl.DateTimeFormat(code, { day: "numeric", month: "numeric" }).formatToParts(new Date(2000, 10, 22));
|
|
90
|
+
return parts.findIndex((p) => p.type === "day") < parts.findIndex((p) => p.type === "month");
|
|
91
|
+
} catch {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A year as typed. Two digits land inside `min` and `max` when one century does, else up to
|
|
98
|
+
* twenty years ahead of `base` or eighty back, so 30 is 2030 and 75 is 1975.
|
|
99
|
+
*/
|
|
100
|
+
function fullYear(text: string | undefined, base: Date, min?: Date, max?: Date): number {
|
|
101
|
+
if (!text) return base.getFullYear();
|
|
102
|
+
if (text.length === 4) return +text;
|
|
103
|
+
const now = base.getFullYear();
|
|
104
|
+
const century = Math.floor(now / 100) * 100;
|
|
105
|
+
const years = [century - 100, century, century + 100].map((c) => c + +text);
|
|
106
|
+
const inside = years.filter((y) => (!min || y >= min.getFullYear()) && (!max || y <= max.getFullYear()));
|
|
107
|
+
const pool = inside.length ? inside : years;
|
|
108
|
+
return pool.find((y) => y > now - 80 && y <= now + 20) ?? pool.reduce((a, b) => (Math.abs(b - now) < Math.abs(a - now) ? b : a));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Reads what a person types into a date field: today, tomorrow, yesterday, in 3 days, in
|
|
113
|
+
* 2 weeks, fri, next fri, 21 nov, nov 21, 21/11, 2026-11-21. Returns null when the text
|
|
114
|
+
* isn't a date. English words only; pass your own parser to the pickers for other languages.
|
|
115
|
+
*/
|
|
116
|
+
function parseDate(input: string, { today = new Date(), order, weekStartsOn = 1, min, max }: ParseDateOptions = {}): Date | null {
|
|
117
|
+
const base = startOfDay(today);
|
|
118
|
+
const s = input
|
|
119
|
+
.trim()
|
|
120
|
+
.toLowerCase()
|
|
121
|
+
.replace(/\s+/g, " ")
|
|
122
|
+
.replace(/(\d)(st|nd|rd|th)\b/, "$1")
|
|
123
|
+
// A weekday before a full date, as in "Fri, 21 Nov 2026", says nothing the date doesn't.
|
|
124
|
+
.replace(/^([a-z]+)\.?,? (?=\d|[a-z]+\.? \d)/, (all, word: string) => (nameIn(WEEKDAYS, word) < 0 ? all : ""));
|
|
125
|
+
if (!s) return null;
|
|
126
|
+
if (s === "today" || s === "now") return base;
|
|
127
|
+
if (s === "tomorrow" || s === "tmr") return addDays(base, 1);
|
|
128
|
+
if (s === "yesterday") return addDays(base, -1);
|
|
129
|
+
let m: RegExpMatchArray | null;
|
|
130
|
+
if ((m = s.match(/^in (\d+) (day|week|month)s?$/))) {
|
|
131
|
+
const n = +m[1];
|
|
132
|
+
if (m[2] === "month") {
|
|
133
|
+
const target = new Date(base.getFullYear(), base.getMonth() + n, 1);
|
|
134
|
+
const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
|
|
135
|
+
return new Date(target.getFullYear(), target.getMonth(), Math.min(base.getDate(), last));
|
|
136
|
+
}
|
|
137
|
+
return addDays(base, m[2] === "week" ? n * 7 : n);
|
|
138
|
+
}
|
|
139
|
+
if ((m = s.match(/^(next |this )?([a-z]+)$/)) && nameIn(WEEKDAYS, m[2]) >= 0) {
|
|
140
|
+
const ahead = (nameIn(WEEKDAYS, m[2]) - base.getDay() + 7) % 7;
|
|
141
|
+
// "this tue" on a Tuesday is today; a bare "tue" is the next one.
|
|
142
|
+
let diff = ahead || (m[1] === "this " ? 0 : 7);
|
|
143
|
+
// "next fri" is the Friday of next week, not the coming one.
|
|
144
|
+
if (m[1] === "next " && diff <= 6 - ((base.getDay() - weekStartsOn + 7) % 7)) diff += 7;
|
|
145
|
+
return addDays(base, diff);
|
|
146
|
+
}
|
|
147
|
+
if ((m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/))) return makeDate(+m[1], +m[2] - 1, +m[3]);
|
|
148
|
+
if ((m = s.match(/^(\d{1,2})[/.\- ](\d{1,2})(?:[/.\- ](\d{2}|\d{4}))?$/))) {
|
|
149
|
+
const [day, month] = (order ?? (dayFirst() ? "day-first" : "month-first")) === "day-first" ? [+m[1], +m[2]] : [+m[2], +m[1]];
|
|
150
|
+
return makeDate(fullYear(m[3], base, min, max), month - 1, day);
|
|
151
|
+
}
|
|
152
|
+
if ((m = s.match(/^(\d{1,2}) ([a-z]+)\.?,?(?: (\d{2}|\d{4}))?$/)) && nameIn(MONTHS, m[2]) >= 0) {
|
|
153
|
+
return makeDate(fullYear(m[3], base, min, max), nameIn(MONTHS, m[2]), +m[1]);
|
|
154
|
+
}
|
|
155
|
+
if ((m = s.match(/^([a-z]+)\.? (\d{1,2}),?(?: (\d{2}|\d{4}))?$/)) && nameIn(MONTHS, m[1]) >= 0) {
|
|
156
|
+
return makeDate(fullYear(m[3], base, min, max), nameIn(MONTHS, m[1]), +m[2]);
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/* ----------------------------------------------------------------------------------------
|
|
162
|
+
* Calendar
|
|
163
|
+
* ------------------------------------------------------------------------------------- */
|
|
164
|
+
|
|
165
|
+
export interface DateRange {
|
|
166
|
+
from: Date | null;
|
|
167
|
+
to: Date | null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export type CalendarMode = "single" | "multiple" | "range";
|
|
171
|
+
|
|
172
|
+
/** Base UI's change details shape, so a handler can cancel a change the same way. */
|
|
173
|
+
export interface CalendarChangeDetails {
|
|
174
|
+
reason: "day-press" | "imperative-action" | (string & {});
|
|
175
|
+
event: Event | undefined;
|
|
176
|
+
isCanceled: boolean;
|
|
177
|
+
cancel(): void;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function changeDetails(reason: string, event?: Event): CalendarChangeDetails {
|
|
181
|
+
const details: CalendarChangeDetails = {
|
|
182
|
+
reason,
|
|
183
|
+
event,
|
|
184
|
+
isCanceled: false,
|
|
185
|
+
cancel() {
|
|
186
|
+
details.isCanceled = true;
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
return details;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
type ValueOf<M extends CalendarMode> = M extends "range" ? DateRange : M extends "multiple" ? Date[] : Date | null;
|
|
193
|
+
|
|
194
|
+
interface CalendarBaseProps
|
|
195
|
+
extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange" | "dir"> {
|
|
196
|
+
/** `scroll`: months as one column you scroll. `paged`: arrows and months side by side. */
|
|
197
|
+
layout?: "scroll" | "paged";
|
|
198
|
+
/** Months side by side in the paged layout. */
|
|
199
|
+
numberOfMonths?: number;
|
|
200
|
+
/** `dropdown` turns the month heading into month and year selects, for jumping far. */
|
|
201
|
+
captionLayout?: "label" | "dropdown";
|
|
202
|
+
/** The earliest day that can be picked. Scrolling stops at its month. */
|
|
203
|
+
min?: Date;
|
|
204
|
+
/** The latest day that can be picked. */
|
|
205
|
+
max?: Date;
|
|
206
|
+
/** Days that can't be picked, besides those outside `min` and `max`. */
|
|
207
|
+
isDateDisabled?: (date: Date) => boolean;
|
|
208
|
+
disabled?: boolean;
|
|
209
|
+
/** Shows ISO week numbers in a column before each week. */
|
|
210
|
+
weekNumbers?: boolean;
|
|
211
|
+
/**
|
|
212
|
+
* A date-fns locale, for month and weekday names and the first day of the week. One from
|
|
213
|
+
* `react-day-picker/locale` also names the month buttons and selects in its language.
|
|
214
|
+
*/
|
|
215
|
+
locale?: DayPickerLocale;
|
|
216
|
+
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
|
|
217
|
+
dir?: "ltr" | "rtl";
|
|
218
|
+
/** Defaults to the current day. */
|
|
219
|
+
today?: Date;
|
|
220
|
+
/** Submits the value with a form: a day as YYYY-MM-DD, a range as YYYY-MM-DD/YYYY-MM-DD. */
|
|
221
|
+
name?: string;
|
|
222
|
+
required?: boolean;
|
|
223
|
+
/** The day under the pointer while a range waits for its end, for a live readout. */
|
|
224
|
+
onPreview?: (range: DateRange | null) => void;
|
|
225
|
+
/** Moves focus to the selected day, or today, when the calendar mounts. */
|
|
226
|
+
autoFocus?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* Lets a range end on the first disabled day after its start, as a stay checks out on a
|
|
229
|
+
* night that is booked. The day still can't start a range.
|
|
230
|
+
*/
|
|
231
|
+
allowDisabledEnd?: boolean;
|
|
232
|
+
/** Extra content under a day's number, such as a price. Keep it short: a cell is 2.5rem. */
|
|
233
|
+
renderDay?: (date: Date) => React.ReactNode;
|
|
234
|
+
/** Classes for a day's button. */
|
|
235
|
+
dayClassName?: (date: Date) => string | undefined;
|
|
236
|
+
/** Words added to a day's accessible name, such as "sold out" or "£120". */
|
|
237
|
+
describeDay?: (date: Date) => string | undefined;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export type CalendarProps = CalendarBaseProps &
|
|
241
|
+
(
|
|
242
|
+
| {
|
|
243
|
+
mode?: "single";
|
|
244
|
+
value?: Date | null;
|
|
245
|
+
defaultValue?: Date | null;
|
|
246
|
+
onValueChange?: (value: Date | null, details: CalendarChangeDetails) => void;
|
|
247
|
+
}
|
|
248
|
+
| {
|
|
249
|
+
mode: "multiple";
|
|
250
|
+
value?: Date[];
|
|
251
|
+
defaultValue?: Date[];
|
|
252
|
+
onValueChange?: (value: Date[], details: CalendarChangeDetails) => void;
|
|
253
|
+
}
|
|
254
|
+
| {
|
|
255
|
+
mode: "range";
|
|
256
|
+
value?: DateRange;
|
|
257
|
+
defaultValue?: DateRange;
|
|
258
|
+
onValueChange?: (value: DateRange, details: CalendarChangeDetails) => void;
|
|
259
|
+
}
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
const EMPTY_RANGE: DateRange = { from: null, to: null };
|
|
263
|
+
|
|
264
|
+
function emptyFor(mode: CalendarMode): ValueOf<CalendarMode> {
|
|
265
|
+
return mode === "range" ? EMPTY_RANGE : mode === "multiple" ? [] : null;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The picked days, in order: a range gives its ends. */
|
|
269
|
+
function daysOf(mode: CalendarMode, value: ValueOf<CalendarMode>): Date[] {
|
|
270
|
+
if (mode === "single") return value ? [value as Date] : [];
|
|
271
|
+
if (mode === "multiple") return value as Date[];
|
|
272
|
+
const { from, to } = value as DateRange;
|
|
273
|
+
return [from, to].filter(Boolean) as Date[];
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** The day the calendar opens on: the selection, else today, kept inside the bounds. */
|
|
277
|
+
function anchorOf(mode: CalendarMode, value: ValueOf<CalendarMode>, today: Date, min?: Date, max?: Date): Date {
|
|
278
|
+
const picked =
|
|
279
|
+
mode === "range" ? (value as DateRange).from : mode === "multiple" ? (value as Date[])[0] : (value as Date | null);
|
|
280
|
+
let day = picked ?? today;
|
|
281
|
+
if (min && day < min) day = min;
|
|
282
|
+
if (max && day > max) day = max;
|
|
283
|
+
return day;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Months rendered either side of the anchor in the scroll layout, before scrolling adds more. */
|
|
287
|
+
const WINDOW = 6;
|
|
288
|
+
const GROW = 6;
|
|
289
|
+
/** The most months the scroll layout holds; growing one end trims the other past this. */
|
|
290
|
+
const MAX_MONTHS = WINDOW * 2 + 1 + GROW;
|
|
291
|
+
|
|
292
|
+
/** Reads a typed value an agent sent: one day, a list of days, or a from and to. */
|
|
293
|
+
function agentValue(
|
|
294
|
+
mode: CalendarMode,
|
|
295
|
+
wanted: unknown,
|
|
296
|
+
parse: ParseDateOptions,
|
|
297
|
+
blocked: (d: Date) => boolean,
|
|
298
|
+
valid: (d: Date, end: boolean) => string | null
|
|
299
|
+
): ValueOf<CalendarMode> | string {
|
|
300
|
+
const one = (item: unknown, end = false): Date | string => {
|
|
301
|
+
const d = item instanceof Date ? (isNaN(item.getTime()) ? null : startOfDay(item)) : typeof item === "string" ? parseDate(item, parse) : null;
|
|
302
|
+
if (!d) return `"${String(item)}" is not a date. Send YYYY-MM-DD.`;
|
|
303
|
+
return valid(d, end) ?? d;
|
|
304
|
+
};
|
|
305
|
+
if (mode === "single") return wanted === null || wanted === "" ? null : one(wanted);
|
|
306
|
+
let list: unknown[] = [wanted];
|
|
307
|
+
if (Array.isArray(wanted)) list = wanted;
|
|
308
|
+
else if (typeof wanted === "string") {
|
|
309
|
+
// "/" also separates the parts of 21/11, so it splits only an ISO pair.
|
|
310
|
+
list = /^\s*\d{4}-\d\d-\d\d\s*\/\s*\d{4}-\d\d-\d\d\s*$/.test(wanted) ? wanted.split("/") : wanted.split(/\s*(?:,| to )\s*/);
|
|
311
|
+
}
|
|
312
|
+
const days = list.map((item, i) => one(item, mode === "range" && i === 1));
|
|
313
|
+
const wrong = days.find((d) => typeof d === "string");
|
|
314
|
+
if (wrong) return wrong as string;
|
|
315
|
+
const dates = days as Date[];
|
|
316
|
+
if (mode === "multiple") return dates.sort((a, b) => a.getTime() - b.getTime());
|
|
317
|
+
if (dates.length !== 2) return "Send two dates, from and to.";
|
|
318
|
+
if (dates[1] < dates[0]) return "The range must end on or after its start.";
|
|
319
|
+
for (let d = addDays(dates[0], 1); d < dates[1]; d = addDays(d, 1)) {
|
|
320
|
+
if (blocked(d)) return `The range can't run across ${toISODate(d)}, which can't be picked.`;
|
|
321
|
+
}
|
|
322
|
+
return { from: dates[0], to: dates[1] };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function agentReport(mode: CalendarMode, value: ValueOf<CalendarMode>): string | string[] | undefined {
|
|
326
|
+
if (mode === "single") return value ? toISODate(value as Date) : undefined;
|
|
327
|
+
if (mode === "multiple") return (value as Date[]).map(toISODate);
|
|
328
|
+
const { from, to } = value as DateRange;
|
|
329
|
+
return from ? [toISODate(from), ...(to ? [toISODate(to)] : [])] : undefined;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The cell for `day`, not the hidden copy RDP keeps in the neighbouring month's grid. */
|
|
333
|
+
const dayCell = (day: Date) => `[data-day="${toISODate(day)}"]:not([data-outside])`;
|
|
334
|
+
|
|
335
|
+
const reducedMotion = () => typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
|
336
|
+
|
|
337
|
+
/** A function whose identity never changes but which always runs the latest render's code. */
|
|
338
|
+
function useStable<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
|
|
339
|
+
const latest = React.useRef(fn);
|
|
340
|
+
React.useLayoutEffect(() => {
|
|
341
|
+
latest.current = fn;
|
|
342
|
+
});
|
|
343
|
+
return React.useCallback((...args: A) => latest.current(...args), []);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const noop = () => {};
|
|
347
|
+
|
|
348
|
+
interface DayHooks {
|
|
349
|
+
preview: (day: Date | null) => void;
|
|
350
|
+
/** The one day Tab lands on, when it isn't RDP's choice. */
|
|
351
|
+
tabStop: Date | null;
|
|
352
|
+
/** Moves focus for PageUp and PageDown. True when it handled the key. */
|
|
353
|
+
page: (day: Date, event: React.KeyboardEvent) => boolean;
|
|
354
|
+
renderDay?: (date: Date) => React.ReactNode;
|
|
355
|
+
dayClassName?: (date: Date) => string | undefined;
|
|
356
|
+
describeDay?: (date: Date) => string | undefined;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const DayContext = React.createContext<DayHooks>({ preview: () => {}, tabStop: null, page: () => false });
|
|
360
|
+
const ModeContext = React.createContext<CalendarMode>("single");
|
|
361
|
+
|
|
362
|
+
/*
|
|
363
|
+
* RDP's parts, replaced so they carry our data-slots and classes. They live outside the
|
|
364
|
+
* component so their identity is stable: a new one each render would remount every day.
|
|
365
|
+
*/
|
|
366
|
+
function CalendarDayButton({ day, modifiers: m, className: _c, children, ...buttonProps }: DayButtonProps) {
|
|
367
|
+
const { preview, tabStop, page, renderDay, dayClassName, describeDay } = React.useContext(DayContext);
|
|
368
|
+
const date = day.date;
|
|
369
|
+
const extra = !m.hidden && renderDay?.(date);
|
|
370
|
+
const description = !m.hidden && describeDay?.(date);
|
|
371
|
+
const ref = React.useRef<HTMLButtonElement>(null);
|
|
372
|
+
// RDP moves focus by flagging the day, and its own button focuses itself; so must this one.
|
|
373
|
+
React.useEffect(() => {
|
|
374
|
+
if (m.focused) ref.current?.focus();
|
|
375
|
+
}, [m.focused]);
|
|
376
|
+
return (
|
|
377
|
+
<button
|
|
378
|
+
{...buttonProps}
|
|
379
|
+
aria-label={description ? `${buttonProps["aria-label"]}, ${description}` : buttonProps["aria-label"]}
|
|
380
|
+
onKeyDown={(e) => {
|
|
381
|
+
if (page(date, e)) {
|
|
382
|
+
e.preventDefault();
|
|
383
|
+
e.stopPropagation();
|
|
384
|
+
} else buttonProps.onKeyDown?.(e);
|
|
385
|
+
}}
|
|
386
|
+
tabIndex={tabStop && !m.hidden ? (isSameDay(date, tabStop) ? 0 : -1) : buttonProps.tabIndex}
|
|
387
|
+
ref={ref}
|
|
388
|
+
data-slot="calendar-day"
|
|
389
|
+
data-today={m.today || undefined}
|
|
390
|
+
data-selected={m.selected || undefined}
|
|
391
|
+
data-range={m.band_start ? "start" : m.band_end ? "end" : m.band ? "middle" : undefined}
|
|
392
|
+
className={cn(
|
|
393
|
+
"relative mx-auto flex size-[var(--calendar-cell)] items-center justify-center rounded-[calc(var(--radius)-2px)] text-sm tabular-nums outline-none",
|
|
394
|
+
"transition-colors duration-150 motion-reduce:transition-none",
|
|
395
|
+
"hover:bg-accent hover:text-accent-foreground",
|
|
396
|
+
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
|
|
397
|
+
m.band && !m.selected && "hover:bg-transparent",
|
|
398
|
+
(m.selected || m.band_start || m.band_end) && "bg-primary font-medium text-primary-foreground hover:bg-primary hover:text-primary-foreground",
|
|
399
|
+
m.today && "after:absolute after:bottom-1 after:left-1/2 after:size-1 after:-translate-x-1/2 after:rounded-full after:bg-current",
|
|
400
|
+
extra != null && extra !== false && "flex-col gap-0 leading-none",
|
|
401
|
+
m.disabled && "pointer-events-none text-muted-foreground opacity-50",
|
|
402
|
+
m.outside && "text-muted-foreground",
|
|
403
|
+
!m.hidden && dayClassName?.(date)
|
|
404
|
+
)}
|
|
405
|
+
onPointerEnter={() => preview(date)}
|
|
406
|
+
>
|
|
407
|
+
{children}
|
|
408
|
+
{extra != null && extra !== false && (
|
|
409
|
+
<span data-slot="calendar-day-content" className="mt-0.5 text-[0.625rem] font-normal leading-none">
|
|
410
|
+
{extra}
|
|
411
|
+
</span>
|
|
412
|
+
)}
|
|
413
|
+
</button>
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Every day of a picked range is selected, not only its ends; a previewed one is not. RDP
|
|
419
|
+
* keeps a hidden copy of each neighbouring month's days, which never take part. The band is
|
|
420
|
+
* a primary tint with a stronger edge, so it reads at 3:1 against the surface in both themes.
|
|
421
|
+
*/
|
|
422
|
+
function CalendarDay({ day: _d, modifiers: m, className, ...cellProps }: DayProps) {
|
|
423
|
+
const band = m.band && !m.hidden;
|
|
424
|
+
return (
|
|
425
|
+
<td
|
|
426
|
+
{...cellProps}
|
|
427
|
+
data-band={band ? (m.band_start ? "start" : m.band_end ? "end" : m.unavailable ? "blocked" : "middle") : undefined}
|
|
428
|
+
className={cn(
|
|
429
|
+
className,
|
|
430
|
+
band &&
|
|
431
|
+
"bg-[var(--calendar-band)] shadow-[inset_0_1px_0_var(--calendar-band-edge),inset_0_-1px_0_var(--calendar-band-edge)] first-of-type:rounded-s-[calc(var(--radius)-2px)] last-of-type:rounded-e-[calc(var(--radius)-2px)]",
|
|
432
|
+
band && m.band_start && "rounded-s-[calc(var(--radius)-2px)]",
|
|
433
|
+
band && m.band_end && "rounded-e-[calc(var(--radius)-2px)]",
|
|
434
|
+
band && m.unavailable && !m.band_start && !m.band_end && "bg-destructive/15 shadow-none"
|
|
435
|
+
)}
|
|
436
|
+
aria-selected={(!m.hidden && (m.selected || m.chosen)) || undefined}
|
|
437
|
+
/>
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** RDP is always told `multiple`, so the grid says multiselectable only when it is. */
|
|
442
|
+
function CalendarMonthGrid(props: MonthGridProps) {
|
|
443
|
+
const mode = React.useContext(ModeContext);
|
|
444
|
+
return <table {...props} aria-multiselectable={mode !== "single" || undefined} />;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function CalendarMonth({ calendarMonth: _m, displayIndex: _i, ...monthProps }: MonthProps) {
|
|
448
|
+
return <div {...monthProps} data-slot="calendar-month" />;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** The locale's own words for a label, else the plain English ones. */
|
|
452
|
+
function labelFor(locale: Partial<DayPickerLocale> | undefined, key: "labelPrevious" | "labelNext" | "labelMonthDropdown" | "labelYearDropdown", fallback: string, month?: Date): string {
|
|
453
|
+
const label = locale?.labels?.[key];
|
|
454
|
+
if (typeof label === "function") return (label as (month?: Date) => string)(month);
|
|
455
|
+
return label ?? fallback;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** The paged arrows, as plain buttons: a landmark per calendar would crowd the page's own. */
|
|
459
|
+
function CalendarNav({ onPreviousClick, onNextClick, previousMonth, nextMonth, className }: NavProps) {
|
|
460
|
+
const { locale } = useDayPicker().dayPickerProps;
|
|
461
|
+
const arrow = cn(
|
|
462
|
+
"pointer-events-auto inline-flex size-8 items-center justify-center rounded-md text-muted-foreground outline-none",
|
|
463
|
+
"hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring aria-disabled:pointer-events-none aria-disabled:opacity-40"
|
|
464
|
+
);
|
|
465
|
+
return (
|
|
466
|
+
<div data-slot="calendar-nav" className={className}>
|
|
467
|
+
<button
|
|
468
|
+
type="button"
|
|
469
|
+
data-slot="calendar-previous"
|
|
470
|
+
aria-label={labelFor(locale, "labelPrevious", "Previous month", previousMonth)}
|
|
471
|
+
aria-disabled={!previousMonth || undefined}
|
|
472
|
+
tabIndex={previousMonth ? undefined : -1}
|
|
473
|
+
className={arrow}
|
|
474
|
+
onClick={(e) => previousMonth && onPreviousClick?.(e)}
|
|
475
|
+
>
|
|
476
|
+
<ChevronLeft className="size-4 rtl:rotate-180" />
|
|
477
|
+
</button>
|
|
478
|
+
<button
|
|
479
|
+
type="button"
|
|
480
|
+
data-slot="calendar-next"
|
|
481
|
+
aria-label={labelFor(locale, "labelNext", "Next month", nextMonth)}
|
|
482
|
+
aria-disabled={!nextMonth || undefined}
|
|
483
|
+
tabIndex={nextMonth ? undefined : -1}
|
|
484
|
+
className={arrow}
|
|
485
|
+
onClick={(e) => nextMonth && onNextClick?.(e)}
|
|
486
|
+
>
|
|
487
|
+
<ChevronRight className="size-4 rtl:rotate-180" />
|
|
488
|
+
</button>
|
|
489
|
+
</div>
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
type CaptionOption = { value: number; label: string; disabled?: boolean };
|
|
494
|
+
|
|
495
|
+
// Opens with the current choice in the middle, so the years either side of it both show.
|
|
496
|
+
function centreSelected(popup: HTMLDivElement | null) {
|
|
497
|
+
if (!popup) return;
|
|
498
|
+
requestAnimationFrame(() => {
|
|
499
|
+
const item = popup.querySelector<HTMLElement>("[data-selected]");
|
|
500
|
+
if (item) popup.scrollTop = item.offsetTop - popup.clientHeight / 2 + item.offsetHeight / 2;
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Base UI's select rather than ours, so a scroll of captions doesn't register dozens of agent controls. */
|
|
505
|
+
function CaptionSelect({
|
|
506
|
+
value,
|
|
507
|
+
options,
|
|
508
|
+
onChange,
|
|
509
|
+
disabled,
|
|
510
|
+
...props
|
|
511
|
+
}: {
|
|
512
|
+
value: number;
|
|
513
|
+
options: CaptionOption[];
|
|
514
|
+
onChange: (value: number) => void;
|
|
515
|
+
disabled?: boolean;
|
|
516
|
+
"aria-label": string;
|
|
517
|
+
"data-slot": string;
|
|
518
|
+
}) {
|
|
519
|
+
return (
|
|
520
|
+
<SelectPrimitive.Root<number> value={value} onValueChange={(v) => v != null && onChange(v)} disabled={disabled} modal={false}>
|
|
521
|
+
<SelectPrimitive.Trigger
|
|
522
|
+
{...props}
|
|
523
|
+
className={cn(
|
|
524
|
+
"inline-flex h-8 items-center gap-1 rounded-md pe-1.5 ps-2 text-sm font-semibold text-foreground",
|
|
525
|
+
"hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-[popup-open]:bg-accent",
|
|
526
|
+
"disabled:pointer-events-none disabled:opacity-50"
|
|
527
|
+
)}
|
|
528
|
+
>
|
|
529
|
+
{options.find((o) => o.value === value)?.label ?? value}
|
|
530
|
+
<ChevronDown aria-hidden className="size-3.5 text-muted-foreground" />
|
|
531
|
+
</SelectPrimitive.Trigger>
|
|
532
|
+
<SelectPrimitive.Portal>
|
|
533
|
+
<SelectPrimitive.Positioner sideOffset={4} alignItemWithTrigger={false} className="z-50">
|
|
534
|
+
<SelectPrimitive.Popup
|
|
535
|
+
ref={centreSelected}
|
|
536
|
+
className={cn(
|
|
537
|
+
"max-h-[min(15rem,var(--available-height))] min-w-[max(var(--anchor-width),5rem)] overflow-y-auto overscroll-contain rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-black/5",
|
|
538
|
+
"origin-[var(--transform-origin)] transition-[scale,opacity] duration-150 ease-out motion-reduce:transition-none",
|
|
539
|
+
"data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:scale-95 data-[ending-style]:opacity-0"
|
|
540
|
+
)}
|
|
541
|
+
>
|
|
542
|
+
{options.map((o) => (
|
|
543
|
+
<SelectPrimitive.Item
|
|
544
|
+
key={o.value}
|
|
545
|
+
value={o.value}
|
|
546
|
+
disabled={o.disabled}
|
|
547
|
+
className={cn(
|
|
548
|
+
"relative flex h-8 cursor-default select-none items-center rounded-md pe-2 ps-7 text-sm tabular-nums outline-none",
|
|
549
|
+
"data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground data-[selected]:font-medium data-[disabled]:opacity-40"
|
|
550
|
+
)}
|
|
551
|
+
>
|
|
552
|
+
<SelectPrimitive.ItemIndicator className="absolute start-2 inline-flex">
|
|
553
|
+
<Check className="size-3.5" />
|
|
554
|
+
</SelectPrimitive.ItemIndicator>
|
|
555
|
+
<SelectPrimitive.ItemText>{o.label}</SelectPrimitive.ItemText>
|
|
556
|
+
</SelectPrimitive.Item>
|
|
557
|
+
))}
|
|
558
|
+
</SelectPrimitive.Popup>
|
|
559
|
+
</SelectPrimitive.Positioner>
|
|
560
|
+
</SelectPrimitive.Portal>
|
|
561
|
+
</SelectPrimitive.Root>
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* A month grid for picking a day, several days or a range. Months scroll as one column by
|
|
568
|
+
* default, with a Today button that appears once today is out of view.
|
|
569
|
+
*/
|
|
570
|
+
const Calendar = React.forwardRef<HTMLDivElement, CalendarProps>((props, ref) => {
|
|
571
|
+
const {
|
|
572
|
+
mode = "single",
|
|
573
|
+
value: valueProp,
|
|
574
|
+
defaultValue,
|
|
575
|
+
onValueChange,
|
|
576
|
+
layout = "scroll",
|
|
577
|
+
numberOfMonths = 1,
|
|
578
|
+
captionLayout = "label",
|
|
579
|
+
min: minProp,
|
|
580
|
+
max: maxProp,
|
|
581
|
+
isDateDisabled,
|
|
582
|
+
disabled,
|
|
583
|
+
weekNumbers = false,
|
|
584
|
+
locale,
|
|
585
|
+
weekStartsOn = locale?.options?.weekStartsOn ?? 1,
|
|
586
|
+
dir,
|
|
587
|
+
today: todayProp,
|
|
588
|
+
name,
|
|
589
|
+
required,
|
|
590
|
+
onPreview,
|
|
591
|
+
autoFocus,
|
|
592
|
+
allowDisabledEnd = false,
|
|
593
|
+
renderDay,
|
|
594
|
+
dayClassName,
|
|
595
|
+
describeDay,
|
|
596
|
+
className,
|
|
597
|
+
...rest
|
|
598
|
+
} = props;
|
|
599
|
+
|
|
600
|
+
const today = React.useMemo(() => startOfDay(todayProp ?? new Date()), [todayProp ? toISODate(todayProp) : null]);
|
|
601
|
+
const min = minProp && startOfDay(minProp);
|
|
602
|
+
const max = maxProp && startOfDay(maxProp);
|
|
603
|
+
const [value, change] = useAgentState<ValueOf<CalendarMode>, CalendarChangeDetails>(
|
|
604
|
+
valueProp as ValueOf<CalendarMode> | undefined,
|
|
605
|
+
(defaultValue as ValueOf<CalendarMode> | undefined) ?? emptyFor(mode),
|
|
606
|
+
onValueChange as ((v: ValueOf<CalendarMode>, d: CalendarChangeDetails) => void) | undefined
|
|
607
|
+
);
|
|
608
|
+
const [hover, setHover] = React.useState<Date | null>(null);
|
|
609
|
+
const root = React.useRef<HTMLDivElement>(null);
|
|
610
|
+
const scroller = React.useRef<HTMLDivElement>(null);
|
|
611
|
+
const scroll = layout === "scroll";
|
|
612
|
+
|
|
613
|
+
const outside = (d: Date) => (!!min && d < min) || (!!max && d > max);
|
|
614
|
+
/** A day no one can pick, whatever the calendar's own disabled state. */
|
|
615
|
+
const unavailable = (d: Date) => outside(d) || !!isDateDisabled?.(d);
|
|
616
|
+
const blocked = React.useCallback(
|
|
617
|
+
(d: Date) => !!disabled || unavailable(d),
|
|
618
|
+
[disabled, min?.getTime(), max?.getTime(), isDateDisabled]
|
|
619
|
+
);
|
|
620
|
+
/** Whether a range from `from` to `to` runs across a day that can't be picked. */
|
|
621
|
+
const crosses = (from: Date, to: Date) => {
|
|
622
|
+
for (let d = addDays(from, 1); d < to; d = addDays(d, 1)) if (unavailable(d)) return true;
|
|
623
|
+
return false;
|
|
624
|
+
};
|
|
625
|
+
/** A day that can end a range though it can't start one. */
|
|
626
|
+
const endOnly = (d: Date) => allowDisabledEnd && !outside(d) && !!isDateDisabled?.(d);
|
|
627
|
+
|
|
628
|
+
/* ---- the months on screen ---- */
|
|
629
|
+
const anchor = anchorOf(mode, value, today, min, max);
|
|
630
|
+
const clampMonth = (m: Date) => {
|
|
631
|
+
if (min && m < addMonths(min, 0)) return addMonths(min, 0);
|
|
632
|
+
if (max && m > addMonths(max, 0)) return addMonths(max, 0);
|
|
633
|
+
return m;
|
|
634
|
+
};
|
|
635
|
+
const [span, setSpan] = React.useState(() => ({
|
|
636
|
+
start: clampMonth(addMonths(anchor, scroll ? -WINDOW : 0)),
|
|
637
|
+
end: clampMonth(addMonths(anchor, scroll ? WINDOW : numberOfMonths - 1)),
|
|
638
|
+
}));
|
|
639
|
+
const count = monthsBetween(span.start, span.end) + 1;
|
|
640
|
+
|
|
641
|
+
// Switching layout or month count recentres on the anchor, since a scroll window starts months back.
|
|
642
|
+
const shape = React.useRef({ scroll, numberOfMonths });
|
|
643
|
+
React.useEffect(() => {
|
|
644
|
+
if (shape.current.scroll === scroll && shape.current.numberOfMonths === numberOfMonths) return;
|
|
645
|
+
shape.current = { scroll, numberOfMonths };
|
|
646
|
+
if (scroll) pending.current = anchor;
|
|
647
|
+
setSpan({
|
|
648
|
+
start: clampMonth(addMonths(anchor, scroll ? -WINDOW : 0)),
|
|
649
|
+
end: clampMonth(addMonths(anchor, scroll ? WINDOW : numberOfMonths - 1)),
|
|
650
|
+
});
|
|
651
|
+
}, [scroll, numberOfMonths]);
|
|
652
|
+
|
|
653
|
+
// Keeps the reading position when months are added or dropped above it, by pinning a month both renders share.
|
|
654
|
+
const pinned = React.useRef<{ month: Date; top: number } | null>(null);
|
|
655
|
+
const monthTop = (sc: HTMLElement, start: Date, month: Date) =>
|
|
656
|
+
sc.querySelectorAll("[data-slot=calendar-month]")[monthsBetween(start, month)]?.getBoundingClientRect().top;
|
|
657
|
+
React.useLayoutEffect(() => {
|
|
658
|
+
const sc = scroller.current;
|
|
659
|
+
const pin = pinned.current;
|
|
660
|
+
pinned.current = null;
|
|
661
|
+
const top = sc && pin ? monthTop(sc, span.start, pin.month) : undefined;
|
|
662
|
+
if (sc && pin && top !== undefined) {
|
|
663
|
+
const scale = sc.getBoundingClientRect().height / sc.offsetHeight || 1;
|
|
664
|
+
sc.scrollTop += (top - pin.top) / scale;
|
|
665
|
+
}
|
|
666
|
+
}, [span.start.getTime()]);
|
|
667
|
+
|
|
668
|
+
// A focused day whose month a trim drops hands focus to the nearest month still shown.
|
|
669
|
+
const refocus = React.useRef<Date | null>(null);
|
|
670
|
+
const grow = React.useCallback(() => {
|
|
671
|
+
const sc = scroller.current;
|
|
672
|
+
if (!sc || !scroll) return;
|
|
673
|
+
const room = sc.clientHeight;
|
|
674
|
+
const pin = (month: Date) => {
|
|
675
|
+
const top = monthTop(sc, span.start, month);
|
|
676
|
+
if (top !== undefined) pinned.current = { month, top };
|
|
677
|
+
};
|
|
678
|
+
const focused = fromISODate(document.activeElement?.closest?.("[data-day]")?.getAttribute("data-day") ?? "");
|
|
679
|
+
const keep = (start: Date, end: Date) => {
|
|
680
|
+
if (!focused || !sc.contains(document.activeElement)) return;
|
|
681
|
+
const month = addMonths(focused, 0);
|
|
682
|
+
if (month < start) refocus.current = start;
|
|
683
|
+
else if (month > end) refocus.current = addMonths(end, 1);
|
|
684
|
+
};
|
|
685
|
+
if (sc.scrollTop < room && (!min || span.start > addMonths(min, 0))) {
|
|
686
|
+
const start = clampMonth(addMonths(span.start, -GROW));
|
|
687
|
+
const end = monthsBetween(start, span.end) >= MAX_MONTHS ? addMonths(start, MAX_MONTHS - 1) : span.end;
|
|
688
|
+
pin(span.start);
|
|
689
|
+
keep(start, end);
|
|
690
|
+
setSpan({ start, end });
|
|
691
|
+
} else if (sc.scrollHeight - sc.scrollTop - room < room && (!max || span.end < addMonths(max, 0))) {
|
|
692
|
+
const end = clampMonth(addMonths(span.end, GROW));
|
|
693
|
+
const start = monthsBetween(span.start, end) >= MAX_MONTHS ? addMonths(end, -(MAX_MONTHS - 1)) : span.start;
|
|
694
|
+
if (start.getTime() !== span.start.getTime()) pin(start);
|
|
695
|
+
keep(start, end);
|
|
696
|
+
setSpan({ start, end });
|
|
697
|
+
}
|
|
698
|
+
}, [scroll, span.start.getTime(), span.end.getTime(), min?.getTime(), max?.getTime()]);
|
|
699
|
+
|
|
700
|
+
/** Scrolls `day` into view, keeping its month's heading on top when it fits. */
|
|
701
|
+
const reveal = React.useCallback(
|
|
702
|
+
(day: Date, smooth: boolean) => {
|
|
703
|
+
const sc = scroller.current;
|
|
704
|
+
const cell = sc?.querySelector<HTMLElement>(dayCell(day));
|
|
705
|
+
if (!sc || !cell) return;
|
|
706
|
+
// A popover opens scaled down, and rects carry the scale where scrollTop doesn't.
|
|
707
|
+
const box = sc.getBoundingClientRect();
|
|
708
|
+
const scale = box.height / sc.offsetHeight || 1;
|
|
709
|
+
const offset = (node: Element) => sc.scrollTop + (node.getBoundingClientRect().top - box.top) / scale;
|
|
710
|
+
const month = cell.closest("[data-slot=calendar-month]") ?? cell;
|
|
711
|
+
const top = Math.max(offset(cell) - sc.clientHeight / 2 + cell.offsetHeight / 2, offset(month));
|
|
712
|
+
sc.scrollTo?.({ top, behavior: smooth && !reducedMotion() ? "smooth" : "auto" });
|
|
713
|
+
},
|
|
714
|
+
[]
|
|
715
|
+
);
|
|
716
|
+
|
|
717
|
+
// A day to scroll to, and one to focus, once the months they need have rendered.
|
|
718
|
+
const pending = React.useRef<Date | null>(null);
|
|
719
|
+
const pendingFocus = React.useRef<Date | null>(null);
|
|
720
|
+
React.useLayoutEffect(() => {
|
|
721
|
+
if (pending.current) reveal(pending.current, false);
|
|
722
|
+
pending.current = null;
|
|
723
|
+
const days = () => [...(root.current?.querySelectorAll<HTMLButtonElement>("td:not([data-outside]) [data-slot=calendar-day]:not(:disabled)") ?? [])];
|
|
724
|
+
if (pendingFocus.current) root.current?.querySelector<HTMLElement>(`${dayCell(pendingFocus.current)} button`)?.focus();
|
|
725
|
+
else if (refocus.current) {
|
|
726
|
+
// Before the first day of the month after the kept span: the last day shown; else the first.
|
|
727
|
+
const edge = refocus.current;
|
|
728
|
+
const list = days();
|
|
729
|
+
const day = edge > span.end ? list[list.length - 1] : list[0];
|
|
730
|
+
day?.focus({ preventScroll: true });
|
|
731
|
+
}
|
|
732
|
+
pendingFocus.current = null;
|
|
733
|
+
refocus.current = null;
|
|
734
|
+
}, [span.start.getTime(), span.end.getTime()]);
|
|
735
|
+
|
|
736
|
+
const goTo = React.useCallback(
|
|
737
|
+
(day: Date, smooth: boolean) => {
|
|
738
|
+
const month = addMonths(day, 0);
|
|
739
|
+
if (!scroll) {
|
|
740
|
+
const last = addMonths(span.start, numberOfMonths - 1);
|
|
741
|
+
if (month < span.start || month > last) setSpan({ start: clampMonth(month), end: clampMonth(addMonths(month, numberOfMonths - 1)) });
|
|
742
|
+
} else if (month < span.start || month > span.end) {
|
|
743
|
+
pending.current = day;
|
|
744
|
+
setSpan({ start: clampMonth(addMonths(day, -WINDOW)), end: clampMonth(addMonths(day, WINDOW)) });
|
|
745
|
+
} else reveal(day, smooth);
|
|
746
|
+
},
|
|
747
|
+
[scroll, numberOfMonths, span.start.getTime(), span.end.getTime(), min?.getTime(), max?.getTime(), reveal]
|
|
748
|
+
);
|
|
749
|
+
|
|
750
|
+
// A value set from outside, by the app or an agent, brings its day into view.
|
|
751
|
+
const mounted = React.useRef(false);
|
|
752
|
+
React.useEffect(() => {
|
|
753
|
+
if (!mounted.current) return void (mounted.current = true);
|
|
754
|
+
const sc = scroller.current;
|
|
755
|
+
const cell = sc?.querySelector(dayCell(anchor));
|
|
756
|
+
if (scroll && sc && cell) {
|
|
757
|
+
const [a, b] = [sc.getBoundingClientRect(), cell.getBoundingClientRect()];
|
|
758
|
+
if (b.top >= a.top && b.bottom <= a.bottom) return;
|
|
759
|
+
}
|
|
760
|
+
goTo(anchor, true);
|
|
761
|
+
}, [anchor.getTime()]);
|
|
762
|
+
|
|
763
|
+
React.useLayoutEffect(() => {
|
|
764
|
+
if (scroll) reveal(anchor, false);
|
|
765
|
+
if (autoFocus) root.current?.querySelector<HTMLElement>("[data-slot=calendar-day][tabindex='0']")?.focus({ preventScroll: true });
|
|
766
|
+
}, []);
|
|
767
|
+
|
|
768
|
+
/* ---- Today button: shown while today is out of view ---- */
|
|
769
|
+
const [todayHidden, setTodayHidden] = React.useState(false);
|
|
770
|
+
const todayInRange = (!min || today >= min) && (!max || today <= max);
|
|
771
|
+
React.useEffect(() => {
|
|
772
|
+
const sc = scroller.current;
|
|
773
|
+
const cell = sc?.querySelector(dayCell(today));
|
|
774
|
+
if (!scroll || !sc || typeof IntersectionObserver === "undefined") return;
|
|
775
|
+
if (!cell) {
|
|
776
|
+
setTodayHidden(true);
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
const io = new IntersectionObserver(([entry]) => setTodayHidden(!entry.isIntersecting), { root: sc, threshold: 1 });
|
|
780
|
+
io.observe(cell);
|
|
781
|
+
return () => io.disconnect();
|
|
782
|
+
}, [scroll, today.getTime(), span.start.getTime(), span.end.getTime()]);
|
|
783
|
+
|
|
784
|
+
/** Focuses `day`, bringing its month into view first when it isn't rendered. */
|
|
785
|
+
const focusDay = (day: Date) => {
|
|
786
|
+
const button = root.current?.querySelector<HTMLElement>(`${dayCell(day)} button`);
|
|
787
|
+
const month = addMonths(day, 0);
|
|
788
|
+
const visible = scroll || (month >= span.start && month <= addMonths(span.start, numberOfMonths - 1));
|
|
789
|
+
if (button && visible) {
|
|
790
|
+
button.focus();
|
|
791
|
+
if (scroll) reveal(day, false);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
pendingFocus.current = day;
|
|
795
|
+
goTo(day, false);
|
|
796
|
+
};
|
|
797
|
+
|
|
798
|
+
/*
|
|
799
|
+
* PageUp and PageDown move a month, a year with Shift, to the same day or the month's last.
|
|
800
|
+
* Past min or max they stop at it; on a day that can't be picked they step back toward
|
|
801
|
+
* where focus came from, so a key never strands focus at a month's start.
|
|
802
|
+
*/
|
|
803
|
+
const page = useStable((day: Date, event: React.KeyboardEvent) => {
|
|
804
|
+
if (event.key !== "PageUp" && event.key !== "PageDown") return false;
|
|
805
|
+
const step = (event.key === "PageUp" ? -1 : 1) * (event.shiftKey ? 12 : 1);
|
|
806
|
+
const month = addMonths(day, step);
|
|
807
|
+
const last = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
|
|
808
|
+
let target = new Date(month.getFullYear(), month.getMonth(), Math.min(day.getDate(), last));
|
|
809
|
+
if (min && target < min) target = min;
|
|
810
|
+
if (max && target > max) target = max;
|
|
811
|
+
const back = step > 0 ? -1 : 1;
|
|
812
|
+
while (blocked(target) && !isSameDay(target, day)) target = addDays(target, back);
|
|
813
|
+
if (!isSameDay(target, day)) focusDay(target);
|
|
814
|
+
return true;
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
/* ---- selection ---- */
|
|
818
|
+
// Tab returns to the day last focused, or to the earliest picked day once the value changes from outside.
|
|
819
|
+
const own = React.useRef<string | null>(null);
|
|
820
|
+
const commit = (next: ValueOf<CalendarMode>, details: CalendarChangeDetails) => {
|
|
821
|
+
own.current = daysOf(mode, next).map(toISODate).join();
|
|
822
|
+
change(next, details);
|
|
823
|
+
};
|
|
824
|
+
const [tabStop, setTabStop] = React.useState<Date | null>(null);
|
|
825
|
+
const pickedKey = daysOf(mode, value).map(toISODate).join();
|
|
826
|
+
const seen = React.useRef(pickedKey);
|
|
827
|
+
React.useEffect(() => {
|
|
828
|
+
if (seen.current === pickedKey) return;
|
|
829
|
+
seen.current = pickedKey;
|
|
830
|
+
if (own.current !== pickedKey) {
|
|
831
|
+
const days = daysOf(mode, value);
|
|
832
|
+
setTabStop(days.length ? days.reduce((a, b) => (b < a ? b : a)) : null);
|
|
833
|
+
}
|
|
834
|
+
own.current = null;
|
|
835
|
+
}, [pickedKey]);
|
|
836
|
+
|
|
837
|
+
const waiting = mode === "range" && (value as DateRange).from && !(value as DateRange).to ? (value as DateRange).from : null;
|
|
838
|
+
// The day a waiting range may end on though it can't be picked: the first blocked one after its start.
|
|
839
|
+
const checkout = React.useMemo(() => {
|
|
840
|
+
if (!waiting || !allowDisabledEnd || disabled) return null;
|
|
841
|
+
for (let d = addDays(waiting, 1), i = 0; i < 731 && !(max && d > max); d = addDays(d, 1), i++) {
|
|
842
|
+
if (unavailable(d)) return endOnly(d) ? d : null;
|
|
843
|
+
}
|
|
844
|
+
return null;
|
|
845
|
+
}, [waiting?.getTime(), allowDisabledEnd, disabled, min?.getTime(), max?.getTime(), isDateDisabled]);
|
|
846
|
+
|
|
847
|
+
const pick = (day: Date, event?: React.SyntheticEvent) => {
|
|
848
|
+
const details = changeDetails("day-press", event?.nativeEvent);
|
|
849
|
+
if (mode === "range" && unavailable(day) && !isSameDay(day, checkout)) return;
|
|
850
|
+
if (mode === "single") return commit(isSameDay(value as Date | null, day) && !required ? null : day, details);
|
|
851
|
+
if (mode === "multiple") {
|
|
852
|
+
const list = value as Date[];
|
|
853
|
+
const has = list.some((d) => isSameDay(d, day));
|
|
854
|
+
return commit(has ? list.filter((d) => !isSameDay(d, day)) : [...list, day].sort((a, b) => a.getTime() - b.getTime()), details);
|
|
855
|
+
}
|
|
856
|
+
const { from, to } = value as DateRange;
|
|
857
|
+
setHover(null);
|
|
858
|
+
onPreview?.(null);
|
|
859
|
+
if (!from || to || day < from) return commit({ from: day, to: null }, details);
|
|
860
|
+
// A range must not run across a day that can't be picked; pressing past one starts afresh.
|
|
861
|
+
if (crosses(from, day)) return commit({ from: day, to: null }, changeDetails("range-blocked", event?.nativeEvent));
|
|
862
|
+
return commit({ from, to: day }, details);
|
|
863
|
+
};
|
|
864
|
+
|
|
865
|
+
const preview = useStable((day: Date | null) => {
|
|
866
|
+
if (!waiting) return;
|
|
867
|
+
const reachable = (d: Date) => d >= waiting && (!unavailable(d) || isSameDay(d, checkout)) && !crosses(waiting, d);
|
|
868
|
+
const end = day && reachable(day) ? day : null;
|
|
869
|
+
setHover(end);
|
|
870
|
+
onPreview?.(end ? { from: waiting, to: end } : null);
|
|
871
|
+
});
|
|
872
|
+
|
|
873
|
+
/* ---- what RDP is told ---- */
|
|
874
|
+
const range = mode === "range" ? (value as DateRange) : null;
|
|
875
|
+
const shown: DateRange | null = range && (range.to ? range : waiting && hover ? { from: waiting, to: hover } : range.from ? range : null);
|
|
876
|
+
// RDP is told the picked days as a plain list, which drives aria-selected and where Tab
|
|
877
|
+
// lands. A previewed end is drawn as one but not announced as picked.
|
|
878
|
+
const picked = daysOf(mode, value);
|
|
879
|
+
const modifiers: Record<string, Matcher | Matcher[] | undefined> = {
|
|
880
|
+
band: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? { from: shown.from, to: shown.to } : undefined,
|
|
881
|
+
band_start: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? shown.from : undefined,
|
|
882
|
+
band_end: shown?.from && shown.to && !isSameDay(shown.from, shown.to) ? shown.to : undefined,
|
|
883
|
+
chosen: range?.from && range.to ? { from: range.from, to: range.to } : undefined,
|
|
884
|
+
unavailable,
|
|
885
|
+
};
|
|
886
|
+
// A range's end, or the day a waiting one may end on, stays pressable though it is blocked.
|
|
887
|
+
const pressable = (d: Date) => isSameDay(d, checkout) || (!!range?.to && isSameDay(d, range.to) && endOnly(d));
|
|
888
|
+
const disabledDay = (d: Date) => blocked(d) && !(pressable(d) && !disabled);
|
|
889
|
+
|
|
890
|
+
/** A value set from outside that names a day that can't be picked, or runs across one. */
|
|
891
|
+
const problem = (() => {
|
|
892
|
+
const say = (d: Date) => `${toISODate(d)} can't be picked.`;
|
|
893
|
+
if (mode === "single") return value && unavailable(value as Date) ? say(value as Date) : null;
|
|
894
|
+
if (mode === "multiple") {
|
|
895
|
+
const bad = (value as Date[]).find(unavailable);
|
|
896
|
+
return bad ? say(bad) : null;
|
|
897
|
+
}
|
|
898
|
+
const { from, to } = value as DateRange;
|
|
899
|
+
if (from && unavailable(from)) return say(from);
|
|
900
|
+
if (to && unavailable(to) && !endOnly(to)) return say(to);
|
|
901
|
+
if (from && to && crosses(from, to)) return "The range runs across a day that can't be picked.";
|
|
902
|
+
return null;
|
|
903
|
+
})();
|
|
904
|
+
|
|
905
|
+
/* ---- agent ---- */
|
|
906
|
+
useAgentControl(() => ({
|
|
907
|
+
kind: "date",
|
|
908
|
+
element: root.current,
|
|
909
|
+
value: agentReport(mode, value),
|
|
910
|
+
multiple: mode !== "single",
|
|
911
|
+
disabled,
|
|
912
|
+
required,
|
|
913
|
+
invalid: !!problem || undefined,
|
|
914
|
+
errors: problem ? [problem] : undefined,
|
|
915
|
+
actions: {
|
|
916
|
+
setValue: (wanted: unknown) => {
|
|
917
|
+
const parse = { today, order: dayFirst(locale) ? "day-first" : "month-first", weekStartsOn, min, max } as const;
|
|
918
|
+
const next = agentValue(mode, wanted, parse, blocked, (d, end) =>
|
|
919
|
+
blocked(d) && !(end && endOnly(d) && !disabled) ? `${toISODate(d)} can't be picked${min && d < min ? `: the earliest is ${toISODate(min)}` : max && d > max ? `: the latest is ${toISODate(max)}` : ""}.` : null
|
|
920
|
+
);
|
|
921
|
+
if (typeof next === "string") return next;
|
|
922
|
+
const failed = changeAsAgent(change, next);
|
|
923
|
+
if (!failed) goTo(anchorOf(mode, next, today, min, max), false);
|
|
924
|
+
return failed;
|
|
925
|
+
},
|
|
926
|
+
clear: () => changeAsAgent(change, emptyFor(mode)),
|
|
927
|
+
},
|
|
928
|
+
}));
|
|
929
|
+
|
|
930
|
+
/* ---- render ---- */
|
|
931
|
+
// Selects reach from min to max, else a century back and twenty years ahead.
|
|
932
|
+
const years = React.useMemo(() => {
|
|
933
|
+
const from = min?.getFullYear() ?? today.getFullYear() - 100;
|
|
934
|
+
const to = max?.getFullYear() ?? today.getFullYear() + 20;
|
|
935
|
+
return Array.from({ length: to - from + 1 }, (_, i) => from + i);
|
|
936
|
+
}, [min?.getFullYear(), max?.getFullYear(), today.getFullYear()]);
|
|
937
|
+
const monthNames = React.useMemo(
|
|
938
|
+
() => Array.from({ length: 12 }, (_, i) => format(new Date(2000, i, 1), "LLL", { locale })),
|
|
939
|
+
[locale]
|
|
940
|
+
);
|
|
941
|
+
|
|
942
|
+
// Through a ref, so the caption keeps its identity and a select keeps focus after a jump.
|
|
943
|
+
const jumpTo = React.useRef((_month: Date, _index: number) => {});
|
|
944
|
+
jumpTo.current = (month, index) => {
|
|
945
|
+
if (scroll) return goTo(clampMonth(month), false);
|
|
946
|
+
let start = addMonths(month, -index);
|
|
947
|
+
if (max && monthsBetween(start, max) < numberOfMonths - 1) start = addMonths(max, -(numberOfMonths - 1));
|
|
948
|
+
start = clampMonth(start);
|
|
949
|
+
setSpan({ start, end: addMonths(start, numberOfMonths - 1) });
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
const MonthCaption = React.useCallback(
|
|
953
|
+
({ calendarMonth, displayIndex, className: _c, ...captionProps }: MonthCaptionProps) => {
|
|
954
|
+
const shown = calendarMonth.date;
|
|
955
|
+
// In the paged layout a month is out when the pages either side of this one would pass min or max.
|
|
956
|
+
const before = scroll ? 0 : displayIndex;
|
|
957
|
+
const after = scroll ? 0 : numberOfMonths - 1 - displayIndex;
|
|
958
|
+
const outside = (m: Date) =>
|
|
959
|
+
(!!min && addMonths(m, -before) < addMonths(min, 0)) || (!!max && addMonths(m, after) > addMonths(max, 0));
|
|
960
|
+
return (
|
|
961
|
+
<div
|
|
962
|
+
{...captionProps}
|
|
963
|
+
data-slot="calendar-caption"
|
|
964
|
+
className={cn(
|
|
965
|
+
"px-1 pb-2 pt-3 text-sm font-semibold",
|
|
966
|
+
scroll && "sticky top-0 z-10 bg-[var(--calendar-bg)]",
|
|
967
|
+
!scroll && "flex h-9 items-center justify-center pt-0",
|
|
968
|
+
captionLayout === "dropdown" && "flex items-center gap-1",
|
|
969
|
+
captionLayout === "dropdown" && scroll && "-ms-1.5"
|
|
970
|
+
)}
|
|
971
|
+
>
|
|
972
|
+
{captionLayout === "dropdown" ? (
|
|
973
|
+
<>
|
|
974
|
+
<CaptionSelect
|
|
975
|
+
data-slot="calendar-month-select"
|
|
976
|
+
aria-label={labelFor(locale, "labelMonthDropdown", "Month")}
|
|
977
|
+
disabled={disabled}
|
|
978
|
+
value={shown.getMonth()}
|
|
979
|
+
options={monthNames.map((label, i) => ({ value: i, label, disabled: outside(new Date(shown.getFullYear(), i, 1)) }))}
|
|
980
|
+
onChange={(m) => jumpTo.current(new Date(shown.getFullYear(), m, 1), displayIndex)}
|
|
981
|
+
/>
|
|
982
|
+
<CaptionSelect
|
|
983
|
+
data-slot="calendar-year-select"
|
|
984
|
+
aria-label={labelFor(locale, "labelYearDropdown", "Year")}
|
|
985
|
+
disabled={disabled}
|
|
986
|
+
value={shown.getFullYear()}
|
|
987
|
+
options={(years.includes(shown.getFullYear()) ? years : [...years, shown.getFullYear()].sort((x, y) => x - y)).map((y) => ({ value: y, label: String(y) }))}
|
|
988
|
+
onChange={(y) => jumpTo.current(new Date(y, shown.getMonth(), 1), displayIndex)}
|
|
989
|
+
/>
|
|
990
|
+
</>
|
|
991
|
+
) : (
|
|
992
|
+
format(shown, "LLLL y", { locale })
|
|
993
|
+
)}
|
|
994
|
+
</div>
|
|
995
|
+
);
|
|
996
|
+
},
|
|
997
|
+
[scroll, numberOfMonths, locale, captionLayout, monthNames, years, disabled, min?.getTime(), max?.getTime()]
|
|
998
|
+
);
|
|
999
|
+
|
|
1000
|
+
const weekdayNames = React.useMemo(() => {
|
|
1001
|
+
const monday = new Date(2024, 0, 1);
|
|
1002
|
+
return Array.from({ length: 7 }, (_, i) => addDays(monday, ((weekStartsOn + 6) % 7) + i));
|
|
1003
|
+
}, [weekStartsOn]);
|
|
1004
|
+
|
|
1005
|
+
const grid = "grid grid-cols-[repeat(7,var(--calendar-cell))] justify-between";
|
|
1006
|
+
const gridWithWeeks = "grid grid-cols-[1.5rem_repeat(7,var(--calendar-cell))] justify-between";
|
|
1007
|
+
|
|
1008
|
+
const values =
|
|
1009
|
+
mode === "single"
|
|
1010
|
+
? value ? [toISODate(value as Date)] : []
|
|
1011
|
+
: mode === "multiple"
|
|
1012
|
+
? (value as Date[]).map(toISODate)
|
|
1013
|
+
: range?.from && range.to ? [`${toISODate(range.from)}/${toISODate(range.to)}`] : [];
|
|
1014
|
+
|
|
1015
|
+
// A stop on a day not shown, or one that can't be focused, leaves Tab to RDP.
|
|
1016
|
+
const stop = tabStop && tabStop >= span.start && tabStop < addMonths(span.end, 1) && !disabledDay(tabStop) ? tabStop : null;
|
|
1017
|
+
const hooks = React.useMemo<DayHooks>(
|
|
1018
|
+
() => ({ preview, tabStop: stop, page, renderDay, dayClassName, describeDay }),
|
|
1019
|
+
[stop?.getTime(), renderDay, dayClassName, describeDay]
|
|
1020
|
+
);
|
|
1021
|
+
|
|
1022
|
+
return (
|
|
1023
|
+
<ModeContext.Provider value={mode}>
|
|
1024
|
+
<DayContext.Provider value={hooks}>
|
|
1025
|
+
<div
|
|
1026
|
+
ref={useMergedRef(ref, root)}
|
|
1027
|
+
data-slot="calendar"
|
|
1028
|
+
data-layout={layout}
|
|
1029
|
+
data-disabled={disabled || undefined}
|
|
1030
|
+
data-invalid={problem ? "" : undefined}
|
|
1031
|
+
dir={dir}
|
|
1032
|
+
className={cn(
|
|
1033
|
+
"relative inline-flex flex-col text-foreground [--calendar-bg:var(--card)] [--calendar-cell:2.5rem]",
|
|
1034
|
+
"[--calendar-band:color-mix(in_oklab,var(--primary)_14%,var(--calendar-bg))] [--calendar-band-edge:color-mix(in_oklab,var(--primary)_50%,var(--calendar-bg))]",
|
|
1035
|
+
scroll && "w-[calc(var(--calendar-cell)*7+1rem)]",
|
|
1036
|
+
scroll && weekNumbers && "w-[calc(var(--calendar-cell)*7+2.75rem)]",
|
|
1037
|
+
className
|
|
1038
|
+
)}
|
|
1039
|
+
role="group"
|
|
1040
|
+
{...rest}
|
|
1041
|
+
onPointerLeave={(e) => {
|
|
1042
|
+
preview(null);
|
|
1043
|
+
rest.onPointerLeave?.(e);
|
|
1044
|
+
}}
|
|
1045
|
+
>
|
|
1046
|
+
{scroll && (
|
|
1047
|
+
<div
|
|
1048
|
+
data-slot="calendar-weekdays"
|
|
1049
|
+
aria-hidden
|
|
1050
|
+
className={cn(weekNumbers ? gridWithWeeks : grid, "border-b border-border px-2 pb-2 text-center text-xs text-muted-foreground")}
|
|
1051
|
+
>
|
|
1052
|
+
{weekNumbers && <span />}
|
|
1053
|
+
{weekdayNames.map((d) => (
|
|
1054
|
+
<span key={d.getDay()}>{format(d, "EEEEEE", { locale })}</span>
|
|
1055
|
+
))}
|
|
1056
|
+
</div>
|
|
1057
|
+
)}
|
|
1058
|
+
<div
|
|
1059
|
+
ref={scroller}
|
|
1060
|
+
data-slot="calendar-scroller"
|
|
1061
|
+
onScroll={grow}
|
|
1062
|
+
className={cn(scroll && "h-[var(--calendar-height,22.5rem)] overflow-y-auto overflow-x-hidden overscroll-contain px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden")}
|
|
1063
|
+
>
|
|
1064
|
+
<DayPicker
|
|
1065
|
+
mode="multiple"
|
|
1066
|
+
selected={picked}
|
|
1067
|
+
// RDP only treats `selected` as controlled when it is given an onSelect.
|
|
1068
|
+
onSelect={noop}
|
|
1069
|
+
month={span.start}
|
|
1070
|
+
onMonthChange={(m) => {
|
|
1071
|
+
if (scroll) goTo(m, true);
|
|
1072
|
+
else setSpan({ start: m, end: addMonths(m, numberOfMonths - 1) });
|
|
1073
|
+
}}
|
|
1074
|
+
numberOfMonths={scroll ? count : numberOfMonths}
|
|
1075
|
+
startMonth={min}
|
|
1076
|
+
endMonth={max}
|
|
1077
|
+
hideNavigation={scroll}
|
|
1078
|
+
hideWeekdays={scroll}
|
|
1079
|
+
showOutsideDays={false}
|
|
1080
|
+
showWeekNumber={weekNumbers}
|
|
1081
|
+
ISOWeek={weekNumbers && weekStartsOn === 1}
|
|
1082
|
+
weekStartsOn={weekStartsOn}
|
|
1083
|
+
locale={locale}
|
|
1084
|
+
dir={dir}
|
|
1085
|
+
today={today}
|
|
1086
|
+
disabled={disabledDay}
|
|
1087
|
+
modifiers={modifiers}
|
|
1088
|
+
onDayClick={(day, m, e) => !m.disabled && pick(day, e)}
|
|
1089
|
+
onDayFocus={(day) => {
|
|
1090
|
+
setTabStop(null);
|
|
1091
|
+
preview(day);
|
|
1092
|
+
}}
|
|
1093
|
+
components={{
|
|
1094
|
+
Day: CalendarDay,
|
|
1095
|
+
DayButton: CalendarDayButton,
|
|
1096
|
+
Month: CalendarMonth,
|
|
1097
|
+
MonthCaption,
|
|
1098
|
+
MonthGrid: CalendarMonthGrid,
|
|
1099
|
+
Nav: CalendarNav,
|
|
1100
|
+
}}
|
|
1101
|
+
classNames={{
|
|
1102
|
+
root: "relative",
|
|
1103
|
+
months: cn("flex", scroll ? "flex-col" : "gap-6"),
|
|
1104
|
+
// The last month before max fills the scroller, so its heading can reach the top.
|
|
1105
|
+
month: cn("flex flex-col", scroll && max && span.end >= addMonths(max, 0) && "last:min-h-[var(--calendar-height,22.5rem)]"),
|
|
1106
|
+
month_grid: "w-full border-collapse",
|
|
1107
|
+
weekdays: weekNumbers ? gridWithWeeks : grid,
|
|
1108
|
+
weekday: "pb-2 text-center text-xs font-normal text-muted-foreground",
|
|
1109
|
+
weeks: "flex flex-col gap-0.5 pb-2",
|
|
1110
|
+
week: cn(weekNumbers ? gridWithWeeks : grid, "[&>td]:p-0"),
|
|
1111
|
+
week_number_header: "w-6",
|
|
1112
|
+
week_number: "flex items-center justify-center text-[0.6875rem] tabular-nums text-muted-foreground",
|
|
1113
|
+
day: "p-0 text-center",
|
|
1114
|
+
nav: "pointer-events-none absolute inset-x-0 top-0 z-10 flex h-9 items-center justify-between",
|
|
1115
|
+
}}
|
|
1116
|
+
/>
|
|
1117
|
+
</div>
|
|
1118
|
+
{scroll && todayInRange && (
|
|
1119
|
+
<button
|
|
1120
|
+
type="button"
|
|
1121
|
+
data-slot="calendar-today"
|
|
1122
|
+
hidden={!todayHidden}
|
|
1123
|
+
tabIndex={todayHidden ? 0 : -1}
|
|
1124
|
+
onClick={() => goTo(today, true)}
|
|
1125
|
+
className={cn(
|
|
1126
|
+
"absolute bottom-3 left-1/2 -translate-x-1/2 rounded-full border border-border bg-background px-3 py-1 text-xs font-medium shadow-sm",
|
|
1127
|
+
"transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
|
|
1128
|
+
"hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
|
1129
|
+
)}
|
|
1130
|
+
>
|
|
1131
|
+
Today
|
|
1132
|
+
</button>
|
|
1133
|
+
)}
|
|
1134
|
+
{name && (values.length ? values : [""]).map((v, i) => <input key={i} type="hidden" name={name} value={v} required={required} />)}
|
|
1135
|
+
</div>
|
|
1136
|
+
</DayContext.Provider>
|
|
1137
|
+
</ModeContext.Provider>
|
|
1138
|
+
);
|
|
1139
|
+
});
|
|
1140
|
+
Calendar.displayName = "Calendar";
|
|
1141
|
+
|
|
1142
|
+
export {
|
|
1143
|
+
Calendar,
|
|
1144
|
+
parseDate,
|
|
1145
|
+
dayFirst,
|
|
1146
|
+
startOfDay,
|
|
1147
|
+
addDays,
|
|
1148
|
+
addMonths,
|
|
1149
|
+
isSameDay,
|
|
1150
|
+
daysBetween,
|
|
1151
|
+
monthsBetween,
|
|
1152
|
+
isoWeek,
|
|
1153
|
+
toISODate,
|
|
1154
|
+
fromISODate,
|
|
1155
|
+
};
|