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