universal-datetime-picker 2.0.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.
@@ -0,0 +1,1831 @@
1
+ 'use strict';
2
+
3
+ var dayjs = require('dayjs');
4
+ var customParseFormat = require('dayjs/plugin/customParseFormat');
5
+ var isSameOrAfter = require('dayjs/plugin/isSameOrAfter');
6
+ var isSameOrBefore = require('dayjs/plugin/isSameOrBefore');
7
+ var localeData = require('dayjs/plugin/localeData');
8
+ var weekday = require('dayjs/plugin/weekday');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var dayjs__default = /*#__PURE__*/_interopDefault(dayjs);
13
+ var customParseFormat__default = /*#__PURE__*/_interopDefault(customParseFormat);
14
+ var isSameOrAfter__default = /*#__PURE__*/_interopDefault(isSameOrAfter);
15
+ var isSameOrBefore__default = /*#__PURE__*/_interopDefault(isSameOrBefore);
16
+ var localeData__default = /*#__PURE__*/_interopDefault(localeData);
17
+ var weekday__default = /*#__PURE__*/_interopDefault(weekday);
18
+
19
+ // src/core/logic/date.ts
20
+ dayjs__default.default.extend(customParseFormat__default.default);
21
+ dayjs__default.default.extend(isSameOrAfter__default.default);
22
+ dayjs__default.default.extend(isSameOrBefore__default.default);
23
+ dayjs__default.default.extend(localeData__default.default);
24
+ dayjs__default.default.extend(weekday__default.default);
25
+ var DEFAULT_FORMAT = "YYYY-MM-DD HH:mm:ss";
26
+ var DATE_FORMAT = "YYYY-MM-DD";
27
+ function resolveFormat(options) {
28
+ if (options.format) {
29
+ return options.format;
30
+ }
31
+ const mode = options.mode ?? "datetime";
32
+ const showSeconds = options.showSeconds !== false;
33
+ const use12Hours = Boolean(options.use12Hours);
34
+ const timePart = use12Hours ? showSeconds ? "hh:mm:ss A" : "hh:mm A" : showSeconds ? "HH:mm:ss" : "HH:mm";
35
+ if (mode === "date") {
36
+ return DATE_FORMAT;
37
+ }
38
+ if (mode === "time") {
39
+ return timePart;
40
+ }
41
+ return `${DATE_FORMAT} ${timePart}`;
42
+ }
43
+ function buildTimeValue(value, format) {
44
+ const hour24 = value.hour();
45
+ const { hour, isAm } = to12Hour(hour24);
46
+ return {
47
+ hour,
48
+ hour24,
49
+ minute: value.minute(),
50
+ second: value.second(),
51
+ ampm: isAm ? "AM" : "PM",
52
+ formatted: value.format(format)
53
+ };
54
+ }
55
+ var asStringDeprecationWarned = false;
56
+ function warnAsStringDeprecation() {
57
+ if (asStringDeprecationWarned) {
58
+ return;
59
+ }
60
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production") {
61
+ return;
62
+ }
63
+ asStringDeprecationWarned = true;
64
+ console.warn(
65
+ "[universal-datetime-picker] Omitting `asString` currently returns a formatted string. Set `asString={true}` to keep strings, or `asString={false}` to receive a Date / TimeValue. A future major release will default to Date / TimeValue."
66
+ );
67
+ }
68
+ function parseValue(value, format = DEFAULT_FORMAT) {
69
+ if (value === void 0 || value === null || value === "") {
70
+ return null;
71
+ }
72
+ if (dayjs__default.default.isDayjs(value)) {
73
+ return value.isValid() ? value : null;
74
+ }
75
+ if (value instanceof Date) {
76
+ const parsed2 = dayjs__default.default(value);
77
+ return parsed2.isValid() ? parsed2 : null;
78
+ }
79
+ if (typeof value === "string") {
80
+ const parsed2 = dayjs__default.default(value, format, true);
81
+ if (parsed2.isValid()) {
82
+ return parsed2;
83
+ }
84
+ const fallback = dayjs__default.default(value);
85
+ return fallback.isValid() ? fallback : null;
86
+ }
87
+ const parsed = dayjs__default.default(value);
88
+ return parsed.isValid() ? parsed : null;
89
+ }
90
+ function formatValue(value, format = DEFAULT_FORMAT) {
91
+ if (!value || !value.isValid()) {
92
+ return null;
93
+ }
94
+ return value.format(format);
95
+ }
96
+ function pad2(n) {
97
+ return String(n).padStart(2, "0");
98
+ }
99
+ var HOURS_24 = Array.from({ length: 24 }, (_, i) => pad2(i));
100
+ var HOURS_12 = Array.from(
101
+ { length: 12 },
102
+ (_, i) => pad2(i === 0 ? 12 : i)
103
+ );
104
+ var MINUTES = Array.from({ length: 60 }, (_, i) => pad2(i));
105
+ function to12Hour(hour24) {
106
+ const isAm = hour24 < 12;
107
+ const hour = hour24 % 12 === 0 ? 12 : hour24 % 12;
108
+ return { hour, isAm };
109
+ }
110
+ function to24Hour(hour12, isAm) {
111
+ if (hour12 === 12) {
112
+ return isAm ? 0 : 12;
113
+ }
114
+ return isAm ? hour12 : hour12 + 12;
115
+ }
116
+ function formatLocalized(date, template, locale) {
117
+ return date.locale(locale).format(template);
118
+ }
119
+ function getWeekdayLabels(locale, weekStartsOn) {
120
+ const labels = dayjs__default.default().locale(locale).localeData().weekdaysMin();
121
+ return [...labels.slice(weekStartsOn), ...labels.slice(0, weekStartsOn)];
122
+ }
123
+ function startOfWeek(date, weekStartsOn) {
124
+ const day = date.day();
125
+ const diff = (day - weekStartsOn + 7) % 7;
126
+ return date.subtract(diff, "day").startOf("day");
127
+ }
128
+ function endOfWeek(date, weekStartsOn) {
129
+ return startOfWeek(date, weekStartsOn).add(6, "day").endOf("day");
130
+ }
131
+
132
+ // src/core/logic/calendar.ts
133
+ function isDisabledDay(date, options) {
134
+ const today = dayjs__default.default().startOf("day");
135
+ const day = date.startOf("day");
136
+ if (options.disablePastDates && day.isBefore(today, "day")) {
137
+ return true;
138
+ }
139
+ if (options.disableFutureDates && day.isAfter(today, "day")) {
140
+ return true;
141
+ }
142
+ const min = parseValue(options.minDate ?? null);
143
+ const max = parseValue(options.maxDate ?? null);
144
+ if (min && day.isBefore(min.startOf("day"), "day")) {
145
+ return true;
146
+ }
147
+ if (max && day.isAfter(max.startOf("day"), "day")) {
148
+ return true;
149
+ }
150
+ return false;
151
+ }
152
+ function buildCalendarMonth(options) {
153
+ const weekStartsOn = options.weekStartsOn ?? 0;
154
+ const monthStart = options.viewMonth.startOf("month");
155
+ const monthEnd = options.viewMonth.endOf("month");
156
+ const gridStart = startOfWeek(monthStart, weekStartsOn);
157
+ const gridEnd = endOfWeek(monthEnd, weekStartsOn);
158
+ const weeks = [];
159
+ let cursor = gridStart.clone();
160
+ while (cursor.isBefore(gridEnd) || cursor.isSame(gridEnd, "day")) {
161
+ const week = [];
162
+ for (let i = 0; i < 7; i += 1) {
163
+ const date = cursor.clone();
164
+ const isCurrentMonth = date.isSame(options.viewMonth, "month");
165
+ const isSelected = Boolean(
166
+ options.selected && date.isSame(options.selected, "day")
167
+ );
168
+ const isRangeStart = Boolean(
169
+ options.rangeStart && date.isSame(options.rangeStart, "day")
170
+ );
171
+ const isRangeEnd = Boolean(
172
+ options.rangeEnd && date.isSame(options.rangeEnd, "day")
173
+ );
174
+ const effectiveEnd = options.rangeEnd ?? options.hoverEnd ?? null;
175
+ let isInRange = false;
176
+ if (options.rangeStart && effectiveEnd) {
177
+ const rangeLow = options.rangeStart.isBefore(effectiveEnd, "day") ? options.rangeStart : effectiveEnd;
178
+ const rangeHigh = options.rangeStart.isBefore(effectiveEnd, "day") ? effectiveEnd : options.rangeStart;
179
+ isInRange = date.isAfter(rangeLow, "day") && date.isBefore(rangeHigh, "day") || date.isSame(rangeLow, "day") || date.isSame(rangeHigh, "day");
180
+ }
181
+ week.push({
182
+ date,
183
+ isCurrentMonth,
184
+ isCurrentDate: date.isSame(dayjs__default.default(), "day"),
185
+ isFuture: date.isAfter(dayjs__default.default(), "day"),
186
+ isPast: date.isBefore(dayjs__default.default(), "day"),
187
+ isWeekend: date.day() === 0 || date.day() === 6,
188
+ isDisabled: isDisabledDay(date, options),
189
+ isSelected,
190
+ isInRange,
191
+ isRangeStart,
192
+ isRangeEnd
193
+ });
194
+ cursor = cursor.add(1, "day");
195
+ }
196
+ weeks.push(week);
197
+ }
198
+ return weeks;
199
+ }
200
+
201
+ // src/core/types.ts
202
+ var DEFAULT_LABELS = {
203
+ date: "Date",
204
+ time: "Time",
205
+ clear: "Clear",
206
+ close: "Close",
207
+ ok: "OK",
208
+ start: "Start",
209
+ end: "End",
210
+ chooseDate: "Choose date",
211
+ chooseDateRange: "Choose date range",
212
+ chooseMonth: "Choose month",
213
+ chooseYear: "Choose year",
214
+ previousMonth: "Previous month",
215
+ nextMonth: "Next month",
216
+ previousYear: "Previous year",
217
+ nextYear: "Next year",
218
+ selectEnd: "Select end date"
219
+ };
220
+
221
+ // src/core/controller.ts
222
+ function padDisplay(n) {
223
+ return String(n).padStart(2, "0");
224
+ }
225
+ var PickerController = class {
226
+ constructor(options = {}) {
227
+ this.listeners = /* @__PURE__ */ new Set();
228
+ this.calPanel = "day";
229
+ this.showHours = false;
230
+ this.showMinutes = false;
231
+ this.showSecondsOpen = false;
232
+ this.showAmPm = false;
233
+ this.subscribe = (listener) => {
234
+ this.listeners.add(listener);
235
+ return () => {
236
+ this.listeners.delete(listener);
237
+ };
238
+ };
239
+ this.getSnapshot = () => this.snapshot;
240
+ /** Stable for useSyncExternalStore — returns same reference until mutate. */
241
+ this.getServerSnapshot = () => this.snapshot;
242
+ this.options = { ...options };
243
+ const mode = options.mode ?? "datetime";
244
+ const showSeconds = options.showSeconds !== false;
245
+ const use12Hours = Boolean(options.use12Hours);
246
+ const format = resolveFormat({
247
+ mode,
248
+ format: options.format,
249
+ use12Hours,
250
+ showSeconds
251
+ });
252
+ const initial = parseValue(options.value ?? options.defaultValue ?? dayjs__default.default(), format) ?? dayjs__default.default();
253
+ this.draft = initial;
254
+ this.viewMonth = initial.startOf("month");
255
+ this.focusedDay = initial;
256
+ this.tab = mode === "time" ? "time" : "date";
257
+ this.open = options.open ?? (options.inline ? true : options.defaultOpen ?? true);
258
+ this.snapshot = this.buildSnapshot();
259
+ }
260
+ setOptions(partial) {
261
+ const prev = this.options;
262
+ this.options = { ...this.options, ...partial };
263
+ if (partial.mode !== void 0 && partial.mode !== prev.mode) {
264
+ this.tab = partial.mode === "time" ? "time" : "date";
265
+ }
266
+ if (partial.open !== void 0) {
267
+ this.open = partial.open;
268
+ }
269
+ if ("value" in partial) {
270
+ if (partial.value === null) {
271
+ const fallback = dayjs__default.default();
272
+ this.draft = fallback;
273
+ this.viewMonth = fallback.startOf("month");
274
+ this.focusedDay = fallback;
275
+ } else if (partial.value !== void 0) {
276
+ const format = this.getResolvedFormat();
277
+ const parsed = parseValue(partial.value, format);
278
+ if (parsed) {
279
+ this.draft = parsed;
280
+ this.viewMonth = parsed.startOf("month");
281
+ this.focusedDay = parsed;
282
+ }
283
+ }
284
+ }
285
+ this.emit();
286
+ }
287
+ getResolvedFormat() {
288
+ return resolveFormat({
289
+ mode: this.options.mode ?? "datetime",
290
+ format: this.options.format,
291
+ use12Hours: Boolean(this.options.use12Hours),
292
+ showSeconds: this.options.showSeconds !== false
293
+ });
294
+ }
295
+ getLabels() {
296
+ return { ...DEFAULT_LABELS, ...this.options.labels };
297
+ }
298
+ emit() {
299
+ this.snapshot = this.buildSnapshot();
300
+ this.listeners.forEach((l) => l());
301
+ }
302
+ buildSnapshot() {
303
+ const mode = this.options.mode ?? "datetime";
304
+ const layout = this.options.layout ?? "combined";
305
+ const showSeconds = this.options.showSeconds !== false;
306
+ const use12Hours = Boolean(this.options.use12Hours);
307
+ const inline = Boolean(this.options.inline);
308
+ const popover = Boolean(this.options.popover);
309
+ const weekStartsOn = this.options.weekStartsOn ?? 0;
310
+ const locale = this.options.locale ?? "en";
311
+ const resolvedFormat = this.getResolvedFormat();
312
+ const labels = this.getLabels();
313
+ const weeks = buildCalendarMonth({
314
+ viewMonth: this.viewMonth,
315
+ selected: this.draft,
316
+ minDate: this.options.minDate,
317
+ maxDate: this.options.maxDate,
318
+ disablePastDates: this.options.disablePastDates,
319
+ disableFutureDates: this.options.disableFutureDates,
320
+ weekStartsOn
321
+ });
322
+ const showDate = mode !== "time";
323
+ const showTime = mode !== "date";
324
+ const useTabs = mode === "datetime" && layout === "tabs";
325
+ const showDatePanel = showDate && (!useTabs || this.tab === "date");
326
+ const showTimePanel = showTime && (!useTabs || this.tab === "time");
327
+ const hour24 = this.draft.hour();
328
+ const { hour: hour12, isAm } = to12Hour(hour24);
329
+ return {
330
+ draft: this.draft,
331
+ viewMonth: this.viewMonth,
332
+ calPanel: this.calPanel,
333
+ tab: this.tab,
334
+ showHours: this.showHours,
335
+ showMinutes: this.showMinutes,
336
+ showSecondsOpen: this.showSecondsOpen,
337
+ showAmPm: this.showAmPm,
338
+ focusedDay: this.focusedDay,
339
+ open: this.open,
340
+ mode,
341
+ layout,
342
+ showSeconds,
343
+ use12Hours,
344
+ inline,
345
+ popover,
346
+ weekStartsOn,
347
+ locale,
348
+ labels,
349
+ resolvedFormat,
350
+ asString: this.options.asString,
351
+ className: this.options.className,
352
+ theme: this.options.theme,
353
+ weeks,
354
+ weekdayLabels: getWeekdayLabels(locale, weekStartsOn),
355
+ showDate,
356
+ showTime,
357
+ useTabs,
358
+ showDatePanel,
359
+ showTimePanel,
360
+ showModeTabs: useTabs,
361
+ hour24,
362
+ hour12,
363
+ isAm,
364
+ hourOptions: use12Hours ? HOURS_12 : HOURS_24,
365
+ displayHour: use12Hours ? padDisplay(hour12) : padDisplay(hour24),
366
+ displayMinute: padDisplay(this.draft.minute()),
367
+ displaySecond: padDisplay(this.draft.second()),
368
+ minuteOptions: MINUTES
369
+ };
370
+ }
371
+ setOpen(open) {
372
+ if (this.options.inline) {
373
+ return;
374
+ }
375
+ this.open = open;
376
+ this.options.onOpenChange?.(open);
377
+ this.emit();
378
+ }
379
+ close() {
380
+ if (!this.options.inline) {
381
+ this.setOpen(false);
382
+ }
383
+ }
384
+ setTab(tab) {
385
+ this.tab = tab;
386
+ this.emit();
387
+ }
388
+ setCalPanel(panel) {
389
+ this.calPanel = panel;
390
+ this.emit();
391
+ }
392
+ setViewMonth(next) {
393
+ this.viewMonth = typeof next === "function" ? next(this.viewMonth) : next;
394
+ this.emit();
395
+ }
396
+ selectDay(day) {
397
+ this.draft = this.draft.year(day.year()).month(day.month()).date(day.date());
398
+ this.focusedDay = day;
399
+ this.emit();
400
+ }
401
+ setHour(hourValue) {
402
+ this.draft = this.draft.hour(hourValue);
403
+ this.emit();
404
+ }
405
+ setMinute(minute) {
406
+ this.draft = this.draft.minute(minute);
407
+ this.emit();
408
+ }
409
+ setSecond(second) {
410
+ this.draft = this.draft.second(second);
411
+ this.emit();
412
+ }
413
+ setAmPm(isAm) {
414
+ const { hour } = to12Hour(this.draft.hour());
415
+ this.draft = this.draft.hour(to24Hour(hour, isAm));
416
+ this.emit();
417
+ }
418
+ toggleHours() {
419
+ this.showHours = !this.showHours;
420
+ this.showMinutes = false;
421
+ this.showSecondsOpen = false;
422
+ this.showAmPm = false;
423
+ this.emit();
424
+ }
425
+ toggleMinutes() {
426
+ this.showMinutes = !this.showMinutes;
427
+ this.showHours = false;
428
+ this.showSecondsOpen = false;
429
+ this.showAmPm = false;
430
+ this.emit();
431
+ }
432
+ toggleSeconds() {
433
+ this.showSecondsOpen = !this.showSecondsOpen;
434
+ this.showHours = false;
435
+ this.showMinutes = false;
436
+ this.showAmPm = false;
437
+ this.emit();
438
+ }
439
+ toggleAmPm() {
440
+ this.showAmPm = !this.showAmPm;
441
+ this.showHours = false;
442
+ this.showMinutes = false;
443
+ this.showSecondsOpen = false;
444
+ this.emit();
445
+ }
446
+ closeTimeColumns() {
447
+ this.showHours = false;
448
+ this.showMinutes = false;
449
+ this.showSecondsOpen = false;
450
+ this.showAmPm = false;
451
+ this.emit();
452
+ }
453
+ selectHourOption(opt) {
454
+ const snap = this.snapshot;
455
+ if (snap.use12Hours) {
456
+ this.draft = this.draft.hour(to24Hour(Number(opt), snap.isAm));
457
+ } else {
458
+ this.draft = this.draft.hour(Number(opt));
459
+ }
460
+ this.showHours = false;
461
+ this.emit();
462
+ }
463
+ selectMinuteOption(opt) {
464
+ this.draft = this.draft.minute(Number(opt));
465
+ this.showMinutes = false;
466
+ this.emit();
467
+ }
468
+ selectSecondOption(opt) {
469
+ this.draft = this.draft.second(Number(opt));
470
+ this.showSecondsOpen = false;
471
+ this.emit();
472
+ }
473
+ selectAmPmOption(opt) {
474
+ const { hour } = to12Hour(this.draft.hour());
475
+ this.draft = this.draft.hour(to24Hour(hour, opt === "AM"));
476
+ this.showAmPm = false;
477
+ this.emit();
478
+ }
479
+ handleGridKeyDown(key) {
480
+ const snap = this.snapshot;
481
+ let next = this.focusedDay;
482
+ switch (key) {
483
+ case "ArrowLeft":
484
+ next = this.focusedDay.subtract(1, "day");
485
+ break;
486
+ case "ArrowRight":
487
+ next = this.focusedDay.add(1, "day");
488
+ break;
489
+ case "ArrowUp":
490
+ next = this.focusedDay.subtract(7, "day");
491
+ break;
492
+ case "ArrowDown":
493
+ next = this.focusedDay.add(7, "day");
494
+ break;
495
+ case "Home":
496
+ next = startOfWeek(this.focusedDay, snap.weekStartsOn);
497
+ break;
498
+ case "End":
499
+ next = endOfWeek(this.focusedDay, snap.weekStartsOn);
500
+ break;
501
+ case "PageUp":
502
+ next = this.focusedDay.subtract(1, "month");
503
+ this.viewMonth = next.startOf("month");
504
+ break;
505
+ case "PageDown":
506
+ next = this.focusedDay.add(1, "month");
507
+ this.viewMonth = next.startOf("month");
508
+ break;
509
+ case "Enter":
510
+ case " ": {
511
+ const cell = snap.weeks.flat().find((d) => d.date.isSame(this.focusedDay, "day"));
512
+ if (cell && !cell.isDisabled && cell.isCurrentMonth) {
513
+ this.selectDay(cell.date);
514
+ }
515
+ return true;
516
+ }
517
+ default:
518
+ return false;
519
+ }
520
+ this.focusedDay = next;
521
+ if (!next.isSame(this.viewMonth, "month")) {
522
+ this.viewMonth = next.startOf("month");
523
+ }
524
+ this.emit();
525
+ return true;
526
+ }
527
+ confirm() {
528
+ const snap = this.snapshot;
529
+ let payload;
530
+ if (snap.asString === false) {
531
+ if (snap.mode === "time") {
532
+ payload = buildTimeValue(this.draft, snap.resolvedFormat);
533
+ } else if (snap.mode === "date") {
534
+ payload = this.draft.startOf("day").toDate();
535
+ } else {
536
+ payload = this.draft.toDate();
537
+ }
538
+ } else {
539
+ if (snap.asString === void 0) {
540
+ warnAsStringDeprecation();
541
+ }
542
+ payload = formatValue(this.draft, snap.resolvedFormat);
543
+ }
544
+ this.options.onChange?.(payload);
545
+ this.close();
546
+ return payload;
547
+ }
548
+ clear() {
549
+ this.options.onChange?.(null);
550
+ this.close();
551
+ }
552
+ /** Year window helpers for month/year panels */
553
+ yearWindowStart(year) {
554
+ return Math.floor(year / 12) * 12;
555
+ }
556
+ navigatePrev() {
557
+ if (this.calPanel === "day") {
558
+ this.viewMonth = this.viewMonth.subtract(1, "month");
559
+ } else if (this.calPanel === "month") {
560
+ this.viewMonth = this.viewMonth.subtract(1, "year");
561
+ } else {
562
+ this.viewMonth = this.viewMonth.subtract(12, "year");
563
+ }
564
+ this.emit();
565
+ }
566
+ navigateNext() {
567
+ if (this.calPanel === "day") {
568
+ this.viewMonth = this.viewMonth.add(1, "month");
569
+ } else if (this.calPanel === "month") {
570
+ this.viewMonth = this.viewMonth.add(1, "year");
571
+ } else {
572
+ this.viewMonth = this.viewMonth.add(12, "year");
573
+ }
574
+ this.emit();
575
+ }
576
+ selectMonth(monthIndex) {
577
+ this.viewMonth = this.viewMonth.month(monthIndex);
578
+ this.calPanel = "day";
579
+ this.emit();
580
+ }
581
+ selectYear(year) {
582
+ this.viewMonth = this.viewMonth.year(year);
583
+ this.calPanel = "month";
584
+ this.emit();
585
+ }
586
+ };
587
+
588
+ // src/vanilla/a11y.ts
589
+ var FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
590
+ var POPOVER_GAP = 8;
591
+ var POPOVER_PADDING = 8;
592
+ var DEFAULT_PICKER_WIDTH = 300;
593
+ var DEFAULT_PICKER_HEIGHT = 360;
594
+ function attachFocusTrap(container, active) {
595
+ if (!active) {
596
+ return () => {
597
+ };
598
+ }
599
+ const previouslyFocused = document.activeElement;
600
+ const focusables = () => Array.from(container.querySelectorAll(FOCUSABLE)).filter(
601
+ (el3) => !el3.hasAttribute("disabled") && el3.offsetParent !== null
602
+ );
603
+ const first = focusables()[0];
604
+ first?.focus({ preventScroll: true });
605
+ const onKeyDown = (event) => {
606
+ if (event.key !== "Tab") {
607
+ return;
608
+ }
609
+ const items = focusables();
610
+ if (items.length === 0) {
611
+ return;
612
+ }
613
+ const firstItem = items[0];
614
+ const lastItem = items[items.length - 1];
615
+ if (event.shiftKey && document.activeElement === firstItem) {
616
+ event.preventDefault();
617
+ lastItem.focus({ preventScroll: true });
618
+ } else if (!event.shiftKey && document.activeElement === lastItem) {
619
+ event.preventDefault();
620
+ firstItem.focus({ preventScroll: true });
621
+ }
622
+ };
623
+ container.addEventListener("keydown", onKeyDown);
624
+ return () => {
625
+ container.removeEventListener("keydown", onKeyDown);
626
+ previouslyFocused?.focus?.({ preventScroll: true });
627
+ };
628
+ }
629
+ function attachEscape(handler, active) {
630
+ if (!active) {
631
+ return () => {
632
+ };
633
+ }
634
+ const onKeyDown = (event) => {
635
+ if (event.key === "Escape") {
636
+ event.preventDefault();
637
+ handler();
638
+ }
639
+ };
640
+ document.addEventListener("keydown", onKeyDown);
641
+ return () => document.removeEventListener("keydown", onKeyDown);
642
+ }
643
+ function attachClickOutside(handler, active, floating, anchorEl) {
644
+ if (!active) {
645
+ return () => {
646
+ };
647
+ }
648
+ const onPointerDown = (event) => {
649
+ const target = event.target;
650
+ if (!(target instanceof Node)) {
651
+ return;
652
+ }
653
+ if (floating?.contains(target)) {
654
+ return;
655
+ }
656
+ if (anchorEl?.contains(target)) {
657
+ return;
658
+ }
659
+ handler();
660
+ };
661
+ document.addEventListener("pointerdown", onPointerDown, true);
662
+ return () => {
663
+ document.removeEventListener("pointerdown", onPointerDown, true);
664
+ };
665
+ }
666
+ function computePopoverPosition(anchorEl, pickerWidth, pickerHeight) {
667
+ const rect = anchorEl.getBoundingClientRect();
668
+ let top = rect.bottom + POPOVER_GAP;
669
+ let left = rect.left;
670
+ if (left + pickerWidth > window.innerWidth - POPOVER_PADDING) {
671
+ left = Math.max(
672
+ POPOVER_PADDING,
673
+ window.innerWidth - pickerWidth - POPOVER_PADDING
674
+ );
675
+ }
676
+ if (left < POPOVER_PADDING) {
677
+ left = POPOVER_PADDING;
678
+ }
679
+ if (top + pickerHeight > window.innerHeight - POPOVER_PADDING) {
680
+ const above = rect.top - pickerHeight - POPOVER_GAP;
681
+ if (above >= POPOVER_PADDING) {
682
+ top = above;
683
+ } else {
684
+ top = Math.max(
685
+ POPOVER_PADDING,
686
+ window.innerHeight - pickerHeight - POPOVER_PADDING
687
+ );
688
+ }
689
+ }
690
+ return { top, left };
691
+ }
692
+ function attachPopoverPosition(anchorEl, open, enabled, floating, onPosition) {
693
+ if (!open || !enabled || !anchorEl) {
694
+ onPosition(null);
695
+ return () => {
696
+ };
697
+ }
698
+ const update = () => {
699
+ if (!floating) {
700
+ onPosition(
701
+ computePopoverPosition(
702
+ anchorEl,
703
+ DEFAULT_PICKER_WIDTH,
704
+ DEFAULT_PICKER_HEIGHT
705
+ )
706
+ );
707
+ return;
708
+ }
709
+ const width = floating.offsetWidth || DEFAULT_PICKER_WIDTH;
710
+ const height = floating.offsetHeight || DEFAULT_PICKER_HEIGHT;
711
+ onPosition(computePopoverPosition(anchorEl, width, height));
712
+ };
713
+ update();
714
+ window.addEventListener("resize", update);
715
+ window.addEventListener("scroll", update, true);
716
+ let observer;
717
+ if (floating && typeof ResizeObserver !== "undefined") {
718
+ observer = new ResizeObserver(() => update());
719
+ observer.observe(floating);
720
+ }
721
+ return () => {
722
+ window.removeEventListener("resize", update);
723
+ window.removeEventListener("scroll", update, true);
724
+ observer?.disconnect();
725
+ };
726
+ }
727
+ function resolveThemeAttr(theme, anchorEl) {
728
+ if (theme === "light" || theme === "dark") {
729
+ return theme;
730
+ }
731
+ let node = anchorEl ?? null;
732
+ while (node) {
733
+ const attr = node.getAttribute("data-ctp-theme");
734
+ if (attr === "dark" || attr === "light") {
735
+ return attr;
736
+ }
737
+ node = node.parentElement;
738
+ }
739
+ if (typeof document !== "undefined") {
740
+ const root = document.documentElement.getAttribute("data-ctp-theme");
741
+ if (root === "dark" || root === "light") {
742
+ return root;
743
+ }
744
+ }
745
+ return void 0;
746
+ }
747
+ function cx(...parts) {
748
+ return parts.filter(Boolean).join(" ");
749
+ }
750
+
751
+ // src/vanilla/renderer.ts
752
+ function applyStyle(el3, style) {
753
+ if (!style) {
754
+ return;
755
+ }
756
+ if (typeof style === "string") {
757
+ el3.setAttribute("style", style);
758
+ return;
759
+ }
760
+ Object.assign(el3.style, style);
761
+ }
762
+ function el(tag, props = {}, children = []) {
763
+ const node = document.createElement(tag);
764
+ for (const [key, value] of Object.entries(props)) {
765
+ if (value === void 0 || value === null || value === false) {
766
+ continue;
767
+ }
768
+ if (key === "className") {
769
+ node.className = String(value);
770
+ } else if (key === "textContent") {
771
+ node.textContent = String(value);
772
+ } else if (key.startsWith("on") && typeof value === "function") {
773
+ const event = key.slice(2).toLowerCase();
774
+ node.addEventListener(event, value);
775
+ } else if (key === "disabled") {
776
+ node.disabled = Boolean(value);
777
+ } else if (key === "tabIndex") {
778
+ node.tabIndex = Number(value);
779
+ } else {
780
+ node.setAttribute(
781
+ key === "ariaLabel" ? "aria-label" : key === "ariaSelected" ? "aria-selected" : key === "ariaDisabled" ? "aria-disabled" : key === "ariaExpanded" ? "aria-expanded" : key === "ariaControls" ? "aria-controls" : key === "ariaHaspopup" ? "aria-haspopup" : key === "ariaModal" ? "aria-modal" : key === "ariaLabelledby" ? "aria-labelledby" : key === "ariaCurrent" ? "aria-current" : key,
782
+ String(value)
783
+ );
784
+ }
785
+ }
786
+ for (const child of children) {
787
+ if (child == null) {
788
+ continue;
789
+ }
790
+ node.append(typeof child === "string" ? child : child);
791
+ }
792
+ return node;
793
+ }
794
+ function renderHeader(controller, snap, titleId) {
795
+ const year = snap.viewMonth.year();
796
+ const windowStart = controller.yearWindowStart(year);
797
+ const windowEnd = windowStart + 11;
798
+ const now = dayjs__default.default();
799
+ const prevLabel = snap.calPanel === "day" ? snap.labels.previousMonth : snap.labels.previousYear;
800
+ const nextLabel = snap.calPanel === "day" ? snap.labels.nextMonth : snap.labels.nextYear;
801
+ let title;
802
+ if (snap.calPanel === "day") {
803
+ title = el(
804
+ "button",
805
+ {
806
+ type: "button",
807
+ className: "ctp-current-month",
808
+ id: titleId,
809
+ ariaLabel: `${formatLocalized(snap.viewMonth, "MMMM YYYY", snap.locale)}. ${snap.labels.chooseMonth}`,
810
+ onClick: () => controller.setCalPanel("month"),
811
+ textContent: formatLocalized(snap.viewMonth, "MMMM YYYY", snap.locale)
812
+ }
813
+ );
814
+ } else if (snap.calPanel === "month") {
815
+ title = el(
816
+ "button",
817
+ {
818
+ type: "button",
819
+ className: "ctp-current-month",
820
+ id: titleId,
821
+ ariaLabel: `${year}. ${snap.labels.chooseYear}`,
822
+ onClick: () => controller.setCalPanel("year"),
823
+ textContent: String(year)
824
+ }
825
+ );
826
+ } else {
827
+ title = el("span", {
828
+ className: "ctp-current-month",
829
+ id: titleId,
830
+ textContent: `${windowStart} \u2013 ${windowEnd}`
831
+ });
832
+ }
833
+ const fragment = el("div", { className: "ctp-body ctp-body-calendar-date" }, [
834
+ el("div", { className: "ctp-month-year" }, [
835
+ el("button", {
836
+ type: "button",
837
+ className: "ctp-prev-month",
838
+ ariaLabel: prevLabel,
839
+ onClick: () => controller.navigatePrev(),
840
+ textContent: "\u2039"
841
+ }),
842
+ title,
843
+ el("button", {
844
+ type: "button",
845
+ className: "ctp-next-month",
846
+ ariaLabel: nextLabel,
847
+ onClick: () => controller.navigateNext(),
848
+ textContent: "\u203A"
849
+ })
850
+ ])
851
+ ]);
852
+ if (snap.calPanel === "month") {
853
+ const grid = el("div", {
854
+ className: "ctp-month-grid",
855
+ role: "grid",
856
+ ariaLabel: snap.labels.chooseMonth
857
+ });
858
+ for (let monthIndex = 0; monthIndex < 12; monthIndex += 1) {
859
+ const monthDate = snap.viewMonth.month(monthIndex);
860
+ const isCurrent = snap.viewMonth.year() === now.year() && monthIndex === now.month();
861
+ grid.append(
862
+ el("button", {
863
+ type: "button",
864
+ role: "gridcell",
865
+ ariaCurrent: isCurrent ? "date" : void 0,
866
+ ariaLabel: formatLocalized(monthDate, "MMMM YYYY", snap.locale),
867
+ className: cx(
868
+ "ctp-box",
869
+ "ctp-box-month",
870
+ isCurrent && "ctp-current"
871
+ ),
872
+ onClick: () => controller.selectMonth(monthIndex),
873
+ textContent: formatLocalized(monthDate, "MMM", snap.locale)
874
+ })
875
+ );
876
+ }
877
+ fragment.append(grid);
878
+ } else if (snap.calPanel === "year") {
879
+ const grid = el("div", {
880
+ className: "ctp-year-grid",
881
+ role: "grid",
882
+ ariaLabel: snap.labels.chooseYear
883
+ });
884
+ for (let offset = 0; offset < 12; offset += 1) {
885
+ const y = windowStart + offset;
886
+ const isCurrent = now.year() === y;
887
+ grid.append(
888
+ el("button", {
889
+ type: "button",
890
+ role: "gridcell",
891
+ ariaCurrent: isCurrent ? "date" : void 0,
892
+ ariaLabel: String(y),
893
+ className: cx("ctp-box", "ctp-box-year", isCurrent && "ctp-current"),
894
+ onClick: () => controller.selectYear(y),
895
+ textContent: String(y)
896
+ })
897
+ );
898
+ }
899
+ fragment.append(grid);
900
+ } else {
901
+ const grid = el("div", {
902
+ className: "ctp-main-calendar",
903
+ role: "grid",
904
+ ariaLabel: snap.labels.chooseDate,
905
+ tabIndex: 0,
906
+ onKeydown: (event) => {
907
+ const ke = event;
908
+ if (controller.handleGridKeyDown(ke.key)) {
909
+ ke.preventDefault();
910
+ }
911
+ }
912
+ });
913
+ for (const label of snap.weekdayLabels) {
914
+ grid.append(
915
+ el("div", {
916
+ className: "ctp-box ctp-box-days",
917
+ role: "columnheader",
918
+ textContent: label
919
+ })
920
+ );
921
+ }
922
+ for (const week of snap.weeks) {
923
+ for (const dayData of week) {
924
+ const selected = dayData.isSelected;
925
+ const focused = dayData.date.isSame(snap.focusedDay, "day");
926
+ const disabled = !dayData.isCurrentMonth || dayData.isDisabled;
927
+ grid.append(
928
+ el("button", {
929
+ type: "button",
930
+ role: "gridcell",
931
+ tabIndex: focused ? 0 : -1,
932
+ ariaSelected: selected,
933
+ ariaDisabled: disabled,
934
+ disabled,
935
+ ariaLabel: formatLocalized(
936
+ dayData.date,
937
+ "dddd, MMMM D, YYYY",
938
+ snap.locale
939
+ ),
940
+ className: cx(
941
+ "ctp-box",
942
+ "ctp-box-date",
943
+ !dayData.isCurrentMonth && "not-current-month",
944
+ selected && "selected",
945
+ dayData.isDisabled && "disabled-date",
946
+ dayData.isWeekend && "weekend-day",
947
+ dayData.isCurrentDate && "ctp-today",
948
+ dayData.isInRange && "ctp-in-range",
949
+ dayData.isRangeStart && "ctp-range-start",
950
+ dayData.isRangeEnd && "ctp-range-end"
951
+ ),
952
+ onClick: () => {
953
+ if (!disabled) {
954
+ controller.selectDay(dayData.date);
955
+ }
956
+ },
957
+ textContent: dayData.date.format("D")
958
+ })
959
+ );
960
+ }
961
+ }
962
+ fragment.append(grid);
963
+ }
964
+ return fragment;
965
+ }
966
+ function renderTimeColumn(label, open, display, options, onToggle, onSelect) {
967
+ const listId = `ctp-${label}-${Math.random().toString(36).slice(2, 8)}`;
968
+ const cls = label === "am-pm" ? "am-pm" : label.endsWith("s") ? label.slice(0, -1) : label;
969
+ const list = el(
970
+ "div",
971
+ {
972
+ id: listId,
973
+ role: "listbox",
974
+ ariaLabel: label,
975
+ className: cx(`ctp-overflow-${label}`, !open && "not-visible")
976
+ },
977
+ options.map(
978
+ (opt) => el("button", {
979
+ type: "button",
980
+ role: "option",
981
+ ariaSelected: opt === display,
982
+ className: `ctp-${cls}`,
983
+ onClick: () => onSelect(opt),
984
+ textContent: opt
985
+ })
986
+ )
987
+ );
988
+ return el(
989
+ "div",
990
+ { className: cx("ctp-box", "ctp-box-time", !open && "not-opened") },
991
+ [
992
+ el("button", {
993
+ type: "button",
994
+ className: `ctp-${cls} ctp-initial-time`,
995
+ ariaHaspopup: "listbox",
996
+ ariaExpanded: open,
997
+ ariaControls: listId,
998
+ ariaLabel: `Select ${label}`,
999
+ onClick: onToggle,
1000
+ textContent: display
1001
+ }),
1002
+ list
1003
+ ]
1004
+ );
1005
+ }
1006
+ function renderTimePanel(controller, snap, titleId) {
1007
+ const body = el("div", { className: "ctp-body ctp-body-calendar-time" });
1008
+ if (snap.showDatePanel) {
1009
+ body.append(
1010
+ el("div", { className: "ctp-section-label", textContent: snap.labels.time })
1011
+ );
1012
+ } else {
1013
+ body.append(
1014
+ el("span", {
1015
+ className: "ctp-visually-hidden",
1016
+ id: titleId,
1017
+ textContent: snap.labels.time
1018
+ })
1019
+ );
1020
+ }
1021
+ const header = el("div", { className: "ctp-main-time-header" }, [
1022
+ el("div", { className: "ctp-box", textContent: "Hr" }),
1023
+ el("div", { className: "ctp-box", textContent: "Min" }),
1024
+ snap.showSeconds ? el("div", { className: "ctp-box", textContent: "Sec" }) : null,
1025
+ snap.use12Hours ? el("div", { className: "ctp-box", textContent: "AM/PM" }) : null
1026
+ ]);
1027
+ const timeBody = el("div", { className: "ctp-main-time-body" }, [
1028
+ renderTimeColumn(
1029
+ "hours",
1030
+ snap.showHours,
1031
+ snap.displayHour,
1032
+ snap.hourOptions,
1033
+ () => controller.toggleHours(),
1034
+ (opt) => controller.selectHourOption(opt)
1035
+ ),
1036
+ renderTimeColumn(
1037
+ "minutes",
1038
+ snap.showMinutes,
1039
+ snap.displayMinute,
1040
+ snap.minuteOptions,
1041
+ () => controller.toggleMinutes(),
1042
+ (opt) => controller.selectMinuteOption(opt)
1043
+ ),
1044
+ snap.showSeconds ? renderTimeColumn(
1045
+ "seconds",
1046
+ snap.showSecondsOpen,
1047
+ snap.displaySecond,
1048
+ snap.minuteOptions,
1049
+ () => controller.toggleSeconds(),
1050
+ (opt) => controller.selectSecondOption(opt)
1051
+ ) : null,
1052
+ snap.use12Hours ? renderTimeColumn(
1053
+ "am-pm",
1054
+ snap.showAmPm,
1055
+ snap.isAm ? "AM" : "PM",
1056
+ ["AM", "PM"],
1057
+ () => controller.toggleAmPm(),
1058
+ (opt) => controller.selectAmPmOption(opt)
1059
+ ) : null
1060
+ ]);
1061
+ body.append(
1062
+ el("div", { className: "ctp-main-time" }, [header, timeBody])
1063
+ );
1064
+ return body;
1065
+ }
1066
+ function renderPicker(controller, snap, titleId, position, options) {
1067
+ const themeAttr = resolveThemeAttr(options.theme, options.anchorEl);
1068
+ const picker = el("div", {
1069
+ className: cx(
1070
+ "ctp-calendar-time-picker",
1071
+ snap.popover && !snap.inline && "ctp-popover",
1072
+ snap.use12Hours && "ctp-use-12h",
1073
+ snap.mode === "time" && "ctp-mode-time",
1074
+ !snap.showSeconds && "ctp-no-seconds",
1075
+ snap.showDatePanel && snap.showTimePanel && "ctp-layout-combined",
1076
+ snap.className
1077
+ ),
1078
+ role: snap.inline ? void 0 : "dialog",
1079
+ ariaModal: snap.inline ? void 0 : true,
1080
+ ariaLabelledby: titleId
1081
+ });
1082
+ if (themeAttr) {
1083
+ picker.setAttribute("data-ctp-theme", themeAttr);
1084
+ }
1085
+ applyStyle(picker, options.style);
1086
+ if (snap.popover && !snap.inline && position) {
1087
+ picker.style.position = "fixed";
1088
+ picker.style.top = `${position.top}px`;
1089
+ picker.style.left = `${position.left}px`;
1090
+ }
1091
+ if (snap.showModeTabs) {
1092
+ picker.append(
1093
+ el("div", { className: "ctp-header" }, [
1094
+ el(
1095
+ "div",
1096
+ {
1097
+ className: "ctp-button-container",
1098
+ role: "tablist",
1099
+ ariaLabel: "Picker mode"
1100
+ },
1101
+ [
1102
+ el("button", {
1103
+ type: "button",
1104
+ role: "tab",
1105
+ ariaSelected: snap.tab === "date",
1106
+ className: cx("ctp-date", snap.tab === "date" && "ctp-active"),
1107
+ onClick: () => controller.setTab("date"),
1108
+ textContent: snap.labels.date
1109
+ }),
1110
+ el("button", {
1111
+ type: "button",
1112
+ role: "tab",
1113
+ ariaSelected: snap.tab === "time",
1114
+ className: cx("ctp-time", snap.tab === "time" && "ctp-active"),
1115
+ onClick: () => controller.setTab("time"),
1116
+ textContent: snap.labels.time
1117
+ })
1118
+ ]
1119
+ )
1120
+ ])
1121
+ );
1122
+ }
1123
+ if (snap.showDatePanel) {
1124
+ picker.append(renderHeader(controller, snap, titleId));
1125
+ }
1126
+ if (snap.showTimePanel) {
1127
+ picker.append(renderTimePanel(controller, snap, titleId));
1128
+ }
1129
+ const footerChildren = [
1130
+ el("button", {
1131
+ type: "button",
1132
+ className: "close-button",
1133
+ onClick: () => controller.clear(),
1134
+ textContent: snap.labels.clear
1135
+ })
1136
+ ];
1137
+ if (!snap.inline) {
1138
+ footerChildren.push(
1139
+ el("button", {
1140
+ type: "button",
1141
+ className: "ctp-cancel",
1142
+ onClick: () => controller.close(),
1143
+ textContent: snap.labels.close
1144
+ })
1145
+ );
1146
+ }
1147
+ footerChildren.push(
1148
+ el("button", {
1149
+ type: "button",
1150
+ onClick: () => controller.confirm(),
1151
+ textContent: snap.labels.ok
1152
+ })
1153
+ );
1154
+ picker.append(el("div", { className: "ctp-footer" }, footerChildren));
1155
+ return picker;
1156
+ }
1157
+ function createDateTimePicker(target, options = {}) {
1158
+ const controller = new PickerController(options);
1159
+ const titleId = `ctp-title-${Math.random().toString(36).slice(2, 9)}`;
1160
+ let cleanups = [];
1161
+ let position = null;
1162
+ let host = null;
1163
+ let portalRoot = null;
1164
+ const teardown = () => {
1165
+ cleanups.forEach((c) => c());
1166
+ cleanups = [];
1167
+ portalRoot?.remove();
1168
+ portalRoot = null;
1169
+ if (host && host.parentElement === target) {
1170
+ host.remove();
1171
+ }
1172
+ host = null;
1173
+ };
1174
+ const paint = () => {
1175
+ teardown();
1176
+ const snap = controller.getSnapshot();
1177
+ if (!snap.open && !snap.inline) {
1178
+ return;
1179
+ }
1180
+ const opts = { ...options };
1181
+ const picker = renderPicker(
1182
+ controller,
1183
+ snap,
1184
+ titleId,
1185
+ position,
1186
+ opts
1187
+ );
1188
+ if (snap.inline) {
1189
+ host = picker;
1190
+ target.append(picker);
1191
+ return;
1192
+ }
1193
+ if (snap.popover) {
1194
+ portalRoot = picker;
1195
+ document.body.append(picker);
1196
+ cleanups.push(
1197
+ attachFocusTrap(picker, true),
1198
+ attachEscape(() => controller.close(), true),
1199
+ attachClickOutside(
1200
+ () => controller.close(),
1201
+ true,
1202
+ picker,
1203
+ options.anchorEl
1204
+ ),
1205
+ attachPopoverPosition(
1206
+ options.anchorEl,
1207
+ true,
1208
+ true,
1209
+ picker,
1210
+ (pos) => {
1211
+ position = pos;
1212
+ if (pos) {
1213
+ picker.style.position = "fixed";
1214
+ picker.style.top = `${pos.top}px`;
1215
+ picker.style.left = `${pos.left}px`;
1216
+ }
1217
+ }
1218
+ )
1219
+ );
1220
+ return;
1221
+ }
1222
+ const themeAttr = resolveThemeAttr(options.theme, options.anchorEl);
1223
+ const backdrop = el("div", {
1224
+ className: "ctp-calendar-time-picker-absolute-container",
1225
+ onClick: (event) => {
1226
+ if (event.target === event.currentTarget) {
1227
+ controller.close();
1228
+ }
1229
+ }
1230
+ });
1231
+ if (themeAttr) {
1232
+ backdrop.setAttribute("data-ctp-theme", themeAttr);
1233
+ }
1234
+ backdrop.append(picker);
1235
+ portalRoot = backdrop;
1236
+ document.body.append(backdrop);
1237
+ cleanups.push(
1238
+ attachFocusTrap(picker, true),
1239
+ attachEscape(() => controller.close(), true)
1240
+ );
1241
+ };
1242
+ const unsub = controller.subscribe(paint);
1243
+ paint();
1244
+ return {
1245
+ update(partial) {
1246
+ Object.assign(options, partial);
1247
+ controller.setOptions(partial);
1248
+ },
1249
+ destroy() {
1250
+ unsub();
1251
+ teardown();
1252
+ },
1253
+ getController: () => controller
1254
+ };
1255
+ }
1256
+
1257
+ // src/core/rangeController.ts
1258
+ var RangeController = class {
1259
+ constructor(options = {}) {
1260
+ this.listeners = /* @__PURE__ */ new Set();
1261
+ this.hoverEnd = null;
1262
+ this.calPanel = "day";
1263
+ this.subscribe = (listener) => {
1264
+ this.listeners.add(listener);
1265
+ return () => {
1266
+ this.listeners.delete(listener);
1267
+ };
1268
+ };
1269
+ this.getSnapshot = () => this.snapshot;
1270
+ this.getServerSnapshot = () => this.snapshot;
1271
+ this.options = { ...options };
1272
+ const format = options.format ?? DATE_FORMAT;
1273
+ const parsed = this.parseRange(options.value ?? options.defaultValue, format);
1274
+ this.start = parsed.start;
1275
+ this.end = parsed.end;
1276
+ this.viewMonth = (parsed.start ?? dayjs__default.default()).startOf("month");
1277
+ this.focusedDay = parsed.start ?? dayjs__default.default();
1278
+ this.open = options.open ?? (options.inline ? true : options.defaultOpen ?? true);
1279
+ this.snapshot = this.buildSnapshot();
1280
+ }
1281
+ parseRange(range, format) {
1282
+ return {
1283
+ start: parseValue(range?.start ?? null, format),
1284
+ end: parseValue(range?.end ?? null, format)
1285
+ };
1286
+ }
1287
+ setOptions(partial) {
1288
+ this.options = { ...this.options, ...partial };
1289
+ if (partial.open !== void 0) {
1290
+ this.open = partial.open;
1291
+ }
1292
+ if ("value" in partial) {
1293
+ if (partial.value === null) {
1294
+ this.start = null;
1295
+ this.end = null;
1296
+ this.hoverEnd = null;
1297
+ } else if (partial.value !== void 0) {
1298
+ const format = this.options.format ?? DATE_FORMAT;
1299
+ const parsed = this.parseRange(partial.value, format);
1300
+ this.start = parsed.start;
1301
+ this.end = parsed.end;
1302
+ if (parsed.start) {
1303
+ this.viewMonth = parsed.start.startOf("month");
1304
+ this.focusedDay = parsed.start;
1305
+ }
1306
+ }
1307
+ }
1308
+ this.emit();
1309
+ }
1310
+ getLabels() {
1311
+ return { ...DEFAULT_LABELS, ...this.options.labels };
1312
+ }
1313
+ emit() {
1314
+ this.snapshot = this.buildSnapshot();
1315
+ this.listeners.forEach((l) => l());
1316
+ }
1317
+ buildSnapshot() {
1318
+ const format = this.options.format ?? DATE_FORMAT;
1319
+ const weekStartsOn = this.options.weekStartsOn ?? 0;
1320
+ const locale = this.options.locale ?? "en";
1321
+ const weeks = buildCalendarMonth({
1322
+ viewMonth: this.viewMonth,
1323
+ rangeStart: this.start,
1324
+ rangeEnd: this.end,
1325
+ hoverEnd: this.start && !this.end ? this.hoverEnd : null,
1326
+ minDate: this.options.minDate,
1327
+ maxDate: this.options.maxDate,
1328
+ disablePastDates: this.options.disablePastDates,
1329
+ disableFutureDates: this.options.disableFutureDates,
1330
+ weekStartsOn
1331
+ });
1332
+ return {
1333
+ start: this.start,
1334
+ end: this.end,
1335
+ hoverEnd: this.hoverEnd,
1336
+ viewMonth: this.viewMonth,
1337
+ focusedDay: this.focusedDay,
1338
+ calPanel: this.calPanel,
1339
+ open: this.open,
1340
+ inline: Boolean(this.options.inline),
1341
+ format,
1342
+ asString: this.options.asString,
1343
+ weekStartsOn,
1344
+ locale,
1345
+ labels: this.getLabels(),
1346
+ className: this.options.className,
1347
+ weeks,
1348
+ weekdayLabels: getWeekdayLabels(locale, weekStartsOn)
1349
+ };
1350
+ }
1351
+ setOpen(open) {
1352
+ if (this.options.inline) {
1353
+ return;
1354
+ }
1355
+ this.open = open;
1356
+ this.options.onOpenChange?.(open);
1357
+ this.emit();
1358
+ }
1359
+ close() {
1360
+ if (!this.options.inline) {
1361
+ this.setOpen(false);
1362
+ }
1363
+ }
1364
+ setCalPanel(panel) {
1365
+ this.calPanel = panel;
1366
+ this.emit();
1367
+ }
1368
+ setViewMonth(next) {
1369
+ this.viewMonth = typeof next === "function" ? next(this.viewMonth) : next;
1370
+ this.emit();
1371
+ }
1372
+ navigatePrev() {
1373
+ if (this.calPanel === "day") {
1374
+ this.viewMonth = this.viewMonth.subtract(1, "month");
1375
+ } else if (this.calPanel === "month") {
1376
+ this.viewMonth = this.viewMonth.subtract(1, "year");
1377
+ } else {
1378
+ this.viewMonth = this.viewMonth.subtract(12, "year");
1379
+ }
1380
+ this.emit();
1381
+ }
1382
+ navigateNext() {
1383
+ if (this.calPanel === "day") {
1384
+ this.viewMonth = this.viewMonth.add(1, "month");
1385
+ } else if (this.calPanel === "month") {
1386
+ this.viewMonth = this.viewMonth.add(1, "year");
1387
+ } else {
1388
+ this.viewMonth = this.viewMonth.add(12, "year");
1389
+ }
1390
+ this.emit();
1391
+ }
1392
+ selectMonth(monthIndex) {
1393
+ this.viewMonth = this.viewMonth.month(monthIndex);
1394
+ this.calPanel = "day";
1395
+ this.emit();
1396
+ }
1397
+ selectYear(year) {
1398
+ this.viewMonth = this.viewMonth.year(year);
1399
+ this.calPanel = "month";
1400
+ this.emit();
1401
+ }
1402
+ emitRange(nextStart, nextEnd) {
1403
+ if (this.options.asString === false) {
1404
+ this.options.onChange?.({
1405
+ start: nextStart ? nextStart.toDate() : null,
1406
+ end: nextEnd ? nextEnd.toDate() : null
1407
+ });
1408
+ } else {
1409
+ if (this.options.asString === void 0) {
1410
+ warnAsStringDeprecation();
1411
+ }
1412
+ const format = this.options.format ?? DATE_FORMAT;
1413
+ this.options.onChange?.({
1414
+ start: formatValue(nextStart, format),
1415
+ end: formatValue(nextEnd, format)
1416
+ });
1417
+ }
1418
+ }
1419
+ pickDay(day) {
1420
+ if (!this.start || this.start && this.end) {
1421
+ this.start = day;
1422
+ this.end = null;
1423
+ this.hoverEnd = null;
1424
+ this.focusedDay = day;
1425
+ } else if (day.isBefore(this.start, "day")) {
1426
+ this.start = day;
1427
+ this.end = null;
1428
+ this.hoverEnd = null;
1429
+ this.focusedDay = day;
1430
+ } else {
1431
+ this.end = day;
1432
+ this.hoverEnd = null;
1433
+ this.focusedDay = day;
1434
+ }
1435
+ this.emit();
1436
+ }
1437
+ setHoverEnd(day) {
1438
+ if (this.start && !this.end) {
1439
+ this.hoverEnd = day;
1440
+ this.emit();
1441
+ }
1442
+ }
1443
+ handleGridKeyDown(key) {
1444
+ const snap = this.snapshot;
1445
+ let next = this.focusedDay;
1446
+ switch (key) {
1447
+ case "ArrowLeft":
1448
+ next = this.focusedDay.subtract(1, "day");
1449
+ break;
1450
+ case "ArrowRight":
1451
+ next = this.focusedDay.add(1, "day");
1452
+ break;
1453
+ case "ArrowUp":
1454
+ next = this.focusedDay.subtract(7, "day");
1455
+ break;
1456
+ case "ArrowDown":
1457
+ next = this.focusedDay.add(7, "day");
1458
+ break;
1459
+ case "Home":
1460
+ next = startOfWeek(this.focusedDay, snap.weekStartsOn);
1461
+ break;
1462
+ case "End":
1463
+ next = endOfWeek(this.focusedDay, snap.weekStartsOn);
1464
+ break;
1465
+ case "PageUp":
1466
+ next = this.focusedDay.subtract(1, "month");
1467
+ this.viewMonth = next.startOf("month");
1468
+ break;
1469
+ case "PageDown":
1470
+ next = this.focusedDay.add(1, "month");
1471
+ this.viewMonth = next.startOf("month");
1472
+ break;
1473
+ case "Enter":
1474
+ case " ": {
1475
+ const cell = snap.weeks.flat().find((d) => d.date.isSame(this.focusedDay, "day"));
1476
+ if (cell && !cell.isDisabled && cell.isCurrentMonth) {
1477
+ this.pickDay(cell.date);
1478
+ }
1479
+ return true;
1480
+ }
1481
+ default:
1482
+ return false;
1483
+ }
1484
+ this.focusedDay = next;
1485
+ if (!next.isSame(this.viewMonth, "month")) {
1486
+ this.viewMonth = next.startOf("month");
1487
+ }
1488
+ this.emit();
1489
+ return true;
1490
+ }
1491
+ confirm() {
1492
+ if (!this.start || !this.end) {
1493
+ return null;
1494
+ }
1495
+ this.emitRange(this.start, this.end);
1496
+ this.close();
1497
+ return {
1498
+ start: this.start.toDate(),
1499
+ end: this.end.toDate()
1500
+ };
1501
+ }
1502
+ clear() {
1503
+ this.start = null;
1504
+ this.end = null;
1505
+ this.hoverEnd = null;
1506
+ this.emitRange(null, null);
1507
+ this.emit();
1508
+ this.close();
1509
+ }
1510
+ };
1511
+
1512
+ // src/vanilla/rangeRenderer.ts
1513
+ function el2(tag, props = {}, children = []) {
1514
+ const node = document.createElement(tag);
1515
+ for (const [key, value] of Object.entries(props)) {
1516
+ if (value === void 0 || value === null || value === false) {
1517
+ continue;
1518
+ }
1519
+ if (key === "className") {
1520
+ node.className = String(value);
1521
+ } else if (key === "textContent") {
1522
+ node.textContent = String(value);
1523
+ } else if (key.startsWith("on") && typeof value === "function") {
1524
+ node.addEventListener(
1525
+ key.slice(2).toLowerCase(),
1526
+ value
1527
+ );
1528
+ } else if (key === "disabled") {
1529
+ node.disabled = Boolean(value);
1530
+ } else if (key === "tabIndex") {
1531
+ node.tabIndex = Number(value);
1532
+ } else {
1533
+ const attr = key === "ariaLabel" ? "aria-label" : key === "ariaSelected" ? "aria-selected" : key === "ariaDisabled" ? "aria-disabled" : key === "ariaModal" ? "aria-modal" : key === "ariaLabelledby" ? "aria-labelledby" : key === "ariaCurrent" ? "aria-current" : key;
1534
+ node.setAttribute(attr, String(value));
1535
+ }
1536
+ }
1537
+ for (const child of children) {
1538
+ if (child == null) {
1539
+ continue;
1540
+ }
1541
+ node.append(typeof child === "string" ? child : child);
1542
+ }
1543
+ return node;
1544
+ }
1545
+ function applyStyle2(node, style) {
1546
+ if (!style) {
1547
+ return;
1548
+ }
1549
+ if (typeof style === "string") {
1550
+ node.setAttribute("style", style);
1551
+ return;
1552
+ }
1553
+ Object.assign(node.style, style);
1554
+ }
1555
+ function createDateTimeRangePicker(target, options = {}) {
1556
+ const controller = new RangeController(options);
1557
+ const titleId = `ctp-range-${Math.random().toString(36).slice(2, 9)}`;
1558
+ let cleanups = [];
1559
+ let host = null;
1560
+ let portalRoot = null;
1561
+ const teardown = () => {
1562
+ cleanups.forEach((c) => c());
1563
+ cleanups = [];
1564
+ portalRoot?.remove();
1565
+ portalRoot = null;
1566
+ host?.remove();
1567
+ host = null;
1568
+ };
1569
+ const paint = () => {
1570
+ teardown();
1571
+ const snap = controller.getSnapshot();
1572
+ if (!snap.open && !snap.inline) {
1573
+ return;
1574
+ }
1575
+ const now = dayjs__default.default();
1576
+ const year = snap.viewMonth.year();
1577
+ const windowStart = Math.floor(year / 12) * 12;
1578
+ const windowEnd = windowStart + 11;
1579
+ const statusText = snap.start && !snap.end ? snap.labels.selectEnd : `${snap.start ? formatLocalized(snap.start, "MMM D, YYYY", snap.locale) : snap.labels.start} \u2014 ${snap.end ? formatLocalized(snap.end, "MMM D, YYYY", snap.locale) : snap.labels.end}`;
1580
+ let title;
1581
+ if (snap.calPanel === "day") {
1582
+ title = el2("button", {
1583
+ type: "button",
1584
+ className: "ctp-current-month",
1585
+ ariaLabel: `${formatLocalized(snap.viewMonth, "MMMM YYYY", snap.locale)}. ${snap.labels.chooseMonth}`,
1586
+ onClick: () => controller.setCalPanel("month"),
1587
+ textContent: formatLocalized(snap.viewMonth, "MMMM YYYY", snap.locale)
1588
+ });
1589
+ } else if (snap.calPanel === "month") {
1590
+ title = el2("button", {
1591
+ type: "button",
1592
+ className: "ctp-current-month",
1593
+ ariaLabel: `${year}. ${snap.labels.chooseYear}`,
1594
+ onClick: () => controller.setCalPanel("year"),
1595
+ textContent: String(year)
1596
+ });
1597
+ } else {
1598
+ title = el2("span", {
1599
+ className: "ctp-current-month",
1600
+ textContent: `${windowStart} \u2013 ${windowEnd}`
1601
+ });
1602
+ }
1603
+ const body = el2("div", { className: "ctp-body ctp-body-calendar-date" }, [
1604
+ el2("div", { className: "ctp-month-year" }, [
1605
+ el2("button", {
1606
+ type: "button",
1607
+ className: "ctp-prev-month",
1608
+ ariaLabel: snap.calPanel === "day" ? snap.labels.previousMonth : snap.labels.previousYear,
1609
+ onClick: () => controller.navigatePrev(),
1610
+ textContent: "\u2039"
1611
+ }),
1612
+ title,
1613
+ el2("button", {
1614
+ type: "button",
1615
+ className: "ctp-next-month",
1616
+ ariaLabel: snap.calPanel === "day" ? snap.labels.nextMonth : snap.labels.nextYear,
1617
+ onClick: () => controller.navigateNext(),
1618
+ textContent: "\u203A"
1619
+ })
1620
+ ])
1621
+ ]);
1622
+ if (snap.calPanel === "day") {
1623
+ const grid = el2("div", {
1624
+ className: "ctp-main-calendar",
1625
+ role: "grid",
1626
+ ariaLabel: snap.labels.chooseDateRange,
1627
+ tabIndex: 0,
1628
+ onKeydown: (event) => {
1629
+ const ke = event;
1630
+ if (controller.handleGridKeyDown(ke.key)) {
1631
+ ke.preventDefault();
1632
+ }
1633
+ }
1634
+ });
1635
+ for (const label of snap.weekdayLabels) {
1636
+ grid.append(
1637
+ el2("div", {
1638
+ className: "ctp-box ctp-box-days",
1639
+ role: "columnheader",
1640
+ textContent: label
1641
+ })
1642
+ );
1643
+ }
1644
+ for (const week of snap.weeks) {
1645
+ for (const dayData of week) {
1646
+ const focused = dayData.date.isSame(snap.focusedDay, "day");
1647
+ const disabled = !dayData.isCurrentMonth || dayData.isDisabled;
1648
+ grid.append(
1649
+ el2("button", {
1650
+ type: "button",
1651
+ role: "gridcell",
1652
+ tabIndex: focused ? 0 : -1,
1653
+ ariaSelected: Boolean(
1654
+ dayData.isRangeStart || dayData.isRangeEnd
1655
+ ),
1656
+ ariaDisabled: disabled,
1657
+ disabled,
1658
+ ariaLabel: formatLocalized(
1659
+ dayData.date,
1660
+ "dddd, MMMM D, YYYY",
1661
+ snap.locale
1662
+ ),
1663
+ className: cx(
1664
+ "ctp-box",
1665
+ "ctp-box-date",
1666
+ !dayData.isCurrentMonth && "not-current-month",
1667
+ dayData.isDisabled && "disabled-date",
1668
+ dayData.isWeekend && "weekend-day",
1669
+ dayData.isCurrentDate && "ctp-today",
1670
+ dayData.isInRange && "ctp-in-range",
1671
+ dayData.isRangeStart && "ctp-range-start",
1672
+ dayData.isRangeEnd && "ctp-range-end"
1673
+ ),
1674
+ onClick: () => {
1675
+ if (!disabled) {
1676
+ controller.pickDay(dayData.date);
1677
+ }
1678
+ },
1679
+ onMouseenter: () => {
1680
+ if (!disabled && snap.start && !snap.end) {
1681
+ controller.setHoverEnd(dayData.date);
1682
+ }
1683
+ },
1684
+ textContent: dayData.date.format("D")
1685
+ })
1686
+ );
1687
+ }
1688
+ }
1689
+ body.append(grid);
1690
+ } else if (snap.calPanel === "month") {
1691
+ const grid = el2("div", {
1692
+ className: "ctp-month-grid",
1693
+ role: "grid",
1694
+ ariaLabel: snap.labels.chooseMonth
1695
+ });
1696
+ for (let monthIndex = 0; monthIndex < 12; monthIndex += 1) {
1697
+ const monthDate = snap.viewMonth.month(monthIndex);
1698
+ const isCurrent = snap.viewMonth.year() === now.year() && monthIndex === now.month();
1699
+ grid.append(
1700
+ el2("button", {
1701
+ type: "button",
1702
+ role: "gridcell",
1703
+ ariaCurrent: isCurrent ? "date" : void 0,
1704
+ className: cx(
1705
+ "ctp-box",
1706
+ "ctp-box-month",
1707
+ isCurrent && "ctp-current"
1708
+ ),
1709
+ onClick: () => controller.selectMonth(monthIndex),
1710
+ textContent: formatLocalized(monthDate, "MMM", snap.locale)
1711
+ })
1712
+ );
1713
+ }
1714
+ body.append(grid);
1715
+ } else {
1716
+ const grid = el2("div", {
1717
+ className: "ctp-year-grid",
1718
+ role: "grid",
1719
+ ariaLabel: snap.labels.chooseYear
1720
+ });
1721
+ for (let offset = 0; offset < 12; offset += 1) {
1722
+ const y = windowStart + offset;
1723
+ grid.append(
1724
+ el2("button", {
1725
+ type: "button",
1726
+ role: "gridcell",
1727
+ ariaCurrent: now.year() === y ? "date" : void 0,
1728
+ className: cx(
1729
+ "ctp-box",
1730
+ "ctp-box-year",
1731
+ now.year() === y && "ctp-current"
1732
+ ),
1733
+ onClick: () => controller.selectYear(y),
1734
+ textContent: String(y)
1735
+ })
1736
+ );
1737
+ }
1738
+ body.append(grid);
1739
+ }
1740
+ const footerChildren = [
1741
+ el2("button", {
1742
+ type: "button",
1743
+ className: "close-button",
1744
+ onClick: () => controller.clear(),
1745
+ textContent: snap.labels.clear
1746
+ })
1747
+ ];
1748
+ if (!snap.inline) {
1749
+ footerChildren.push(
1750
+ el2("button", {
1751
+ type: "button",
1752
+ className: "ctp-cancel",
1753
+ onClick: () => controller.close(),
1754
+ textContent: snap.labels.close
1755
+ })
1756
+ );
1757
+ }
1758
+ footerChildren.push(
1759
+ el2("button", {
1760
+ type: "button",
1761
+ disabled: !snap.start || !snap.end,
1762
+ onClick: () => controller.confirm(),
1763
+ textContent: snap.labels.ok
1764
+ })
1765
+ );
1766
+ const picker = el2(
1767
+ "div",
1768
+ {
1769
+ className: cx("ctp-calendar-time-picker", snap.className),
1770
+ role: snap.inline ? void 0 : "dialog",
1771
+ ariaModal: snap.inline ? void 0 : true,
1772
+ ariaLabelledby: titleId
1773
+ },
1774
+ [
1775
+ el2("div", { className: "ctp-header" }, [
1776
+ el2("span", {
1777
+ id: titleId,
1778
+ className: "ctp-range-title",
1779
+ textContent: statusText
1780
+ })
1781
+ ]),
1782
+ body,
1783
+ el2("div", { className: "ctp-footer" }, footerChildren)
1784
+ ]
1785
+ );
1786
+ applyStyle2(picker, options.style);
1787
+ if (snap.inline) {
1788
+ host = picker;
1789
+ target.append(picker);
1790
+ return;
1791
+ }
1792
+ const backdrop = el2("div", {
1793
+ className: "ctp-calendar-time-picker-absolute-container",
1794
+ onClick: (event) => {
1795
+ if (event.target === event.currentTarget) {
1796
+ controller.close();
1797
+ }
1798
+ }
1799
+ });
1800
+ backdrop.append(picker);
1801
+ portalRoot = backdrop;
1802
+ document.body.append(backdrop);
1803
+ cleanups.push(
1804
+ attachFocusTrap(picker, true),
1805
+ attachEscape(() => controller.close(), true)
1806
+ );
1807
+ };
1808
+ const unsub = controller.subscribe(paint);
1809
+ paint();
1810
+ return {
1811
+ update(partial) {
1812
+ Object.assign(options, partial);
1813
+ controller.setOptions(partial);
1814
+ },
1815
+ destroy() {
1816
+ unsub();
1817
+ teardown();
1818
+ },
1819
+ getController: () => controller
1820
+ };
1821
+ }
1822
+
1823
+ exports.attachClickOutside = attachClickOutside;
1824
+ exports.attachEscape = attachEscape;
1825
+ exports.attachFocusTrap = attachFocusTrap;
1826
+ exports.attachPopoverPosition = attachPopoverPosition;
1827
+ exports.computePopoverPosition = computePopoverPosition;
1828
+ exports.createDateTimePicker = createDateTimePicker;
1829
+ exports.createDateTimeRangePicker = createDateTimeRangePicker;
1830
+ exports.cx = cx;
1831
+ exports.resolveThemeAttr = resolveThemeAttr;