@super-calendar/solid 0.0.0-stage → 2.16.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,405 @@
1
+ import { type JSX } from "@solidjs/web";
2
+ import {
3
+ type DateRange,
4
+ type DateSelectionConstraints,
5
+ nextDateRange,
6
+ type WeekStartsOn,
7
+ } from "@super-calendar/core/vanilla";
8
+ import { format } from "date-fns";
9
+ import { createEffect, createMemo, createSignal, createUniqueId, untrack } from "solid-js";
10
+ import { MonthList, type MonthListSlot } from "./MonthList";
11
+ import { withDefaults } from "./props";
12
+ import { createSlots, type SlotStyleProps } from "./slots";
13
+ import { css, type CSSProperties, type ElementRef } from "./styles";
14
+ import { mergeSolidTheme, type SolidCalendarTheme } from "./theme";
15
+
16
+ /** Styleable chrome of the pickers (the calendar's own slots forward through too). */
17
+ export type DatePickerSlot = "trigger" | "popover" | "footer" | "clear";
18
+ interface PickerBaseProps
19
+ extends DateSelectionConstraints, SlotStyleProps<DatePickerSlot | MonthListSlot> {
20
+ /** First day of the week. Sunday = 0 (default) … Saturday = 6. */
21
+ weekStartsOn?: WeekStartsOn;
22
+ /** Height of the popover calendar viewport in px (default 320). */
23
+ height?: number;
24
+ /** Placeholder shown on the trigger when nothing is selected. */
25
+ placeholder?: string;
26
+ /** Disable the field and close its popover. Re-enabling leaves the popover closed. */
27
+ disabled?: boolean;
28
+ /** Theme overrides for the calendar. */
29
+ theme?: Partial<SolidCalendarTheme>;
30
+ /** Class applied to the root element. */
31
+ className?: string;
32
+ /** Inline styles applied to the root element. */
33
+ style?: CSSProperties;
34
+ }
35
+ const triggerDefault: CSSProperties = {
36
+ display: "inline-flex",
37
+ alignItems: "center",
38
+ justifyContent: "space-between",
39
+ gap: 8,
40
+ minWidth: 220,
41
+ padding: "8px 12px",
42
+ borderRadius: 8,
43
+ cursor: "pointer",
44
+ font: "inherit",
45
+ textAlign: "left",
46
+ };
47
+ const popoverDefault: CSSProperties = {
48
+ position: "absolute",
49
+ zIndex: 20,
50
+ marginTop: 6,
51
+ overflow: "hidden",
52
+ borderRadius: 12,
53
+ minWidth: 300,
54
+ };
55
+
56
+ // Where keyboard focus lands when the popover opens: the picked (or today's)
57
+ // day, else that month's roving tab stop, else an enabled day in that month. Unavailable days
58
+ // stay focusable for arrow navigation but are skipped as a starting point.
59
+ function initialPickerFocus(dialog: HTMLElement, day: string): HTMLElement | null {
60
+ const usable = ':not([aria-disabled="true"]):not([data-outside])';
61
+ return (
62
+ dialog.querySelector<HTMLElement>(`[data-day="${day}"]${usable}`) ??
63
+ dialog.querySelector<HTMLElement>(`[data-day^="${day.slice(0, 7)}"][tabindex="0"]${usable}`) ??
64
+ dialog.querySelector<HTMLElement>(`[data-day^="${day.slice(0, 7)}"]${usable}`)
65
+ );
66
+ }
67
+
68
+ /**
69
+ * The shared popover shell: a trigger button and a calendar panel that closes on
70
+ * outside-click and Escape, and returns focus to the trigger. `renderCalendar`
71
+ * gets a close callback so a single-date pick can dismiss immediately.
72
+ */
73
+ function createPopover(disabled: () => boolean | undefined) {
74
+ const [open, setOpen] = createSignal(false);
75
+ const rootRef: ElementRef<HTMLDivElement | null> = {
76
+ current: null,
77
+ };
78
+ const triggerRef: ElementRef<HTMLButtonElement | null> = {
79
+ current: null,
80
+ };
81
+ createEffect(
82
+ () => [open(), disabled()],
83
+ () =>
84
+ untrack(() => {
85
+ if (!open()) return;
86
+ if (disabled()) {
87
+ setOpen(false);
88
+ return;
89
+ }
90
+ const onDown = (e: MouseEvent) => {
91
+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
92
+ };
93
+ const onKey = (e: KeyboardEvent) => {
94
+ if (e.key === "Escape") {
95
+ setOpen(false);
96
+ triggerRef.current?.focus();
97
+ }
98
+ };
99
+ document.addEventListener("mousedown", onDown);
100
+ document.addEventListener("keydown", onKey);
101
+ return () => {
102
+ document.removeEventListener("mousedown", onDown);
103
+ document.removeEventListener("keydown", onKey);
104
+ };
105
+ }),
106
+ );
107
+ return {
108
+ open: () => open() && !disabled(),
109
+ setOpen,
110
+ rootRef,
111
+ triggerRef,
112
+ };
113
+ }
114
+ interface ShellProps {
115
+ open: boolean;
116
+ setOpen: (open: boolean) => void;
117
+ rootRef: ElementRef<HTMLDivElement | null>;
118
+ triggerRef: ElementRef<HTMLButtonElement | null>;
119
+ theme: SolidCalendarTheme;
120
+ slot: ReturnType<typeof createSlots<DatePickerSlot | MonthListSlot>>;
121
+ label: string;
122
+ hasValue: boolean;
123
+ placeholder: string;
124
+ disabled?: boolean;
125
+ className?: string;
126
+ style?: CSSProperties;
127
+ ariaLabel: string;
128
+ /** The day (`yyyy-MM-dd`) to focus when the popover opens. */
129
+ focusDay: string;
130
+ children: JSX.Element;
131
+ }
132
+ function PickerShell(props: ShellProps): JSX.Element {
133
+ const dialogId = createUniqueId();
134
+ const dialogRef: ElementRef<HTMLDivElement | null> = { current: null };
135
+ // Move focus into the popover once per opening (not on every reactive update),
136
+ // so keyboard users land on a date. Wait for the intended month to mount instead
137
+ // of focusing a neighbouring virtualized row that happens to render first.
138
+ createEffect(
139
+ // Read the day here, untracked: the effect phase must not read props, and a
140
+ // new day while open must not pull focus back.
141
+ () => (props.open ? untrack(() => props.focusDay) : null),
142
+ (day) => {
143
+ if (day === null) return;
144
+ const dialog = dialogRef.current;
145
+ if (!dialog) return;
146
+ const place = () => {
147
+ if (dialog.contains(document.activeElement)) {
148
+ observer.disconnect();
149
+ return;
150
+ }
151
+ const target = initialPickerFocus(dialog, day);
152
+ const monthMounted = dialog.querySelector(
153
+ `[data-day^="${day.slice(0, 7)}"]:not([data-outside])`,
154
+ );
155
+ if (target || monthMounted) {
156
+ (target ?? dialog).focus();
157
+ observer.disconnect();
158
+ }
159
+ };
160
+ const observer = new MutationObserver(place);
161
+ observer.observe(dialog, { childList: true, subtree: true });
162
+ place();
163
+ return () => observer.disconnect();
164
+ },
165
+ );
166
+ return (
167
+ <div
168
+ ref={(el) => (props.rootRef.current = el)}
169
+ class={props.className}
170
+ style={css({
171
+ position: "relative",
172
+ display: "inline-block",
173
+ fontFamily: props.theme.fontFamily,
174
+ ...props.style,
175
+ })}
176
+ >
177
+ <button
178
+ ref={(el) => (props.triggerRef.current = el)}
179
+ type="button"
180
+ disabled={props.disabled}
181
+ aria-haspopup="dialog"
182
+ aria-expanded={props.open == null ? undefined : props.open ? "true" : "false"}
183
+ aria-controls={props.open ? dialogId : undefined}
184
+ onClick={() => props.setOpen(!props.open)}
185
+ {...props.slot("trigger", {
186
+ base: triggerDefault,
187
+ themed: {
188
+ border: `1px solid ${props.theme.gridLine}`,
189
+ background: props.theme.surface,
190
+ color: props.hasValue ? props.theme.text : props.theme.textMuted,
191
+ opacity: props.disabled ? 0.5 : 1,
192
+ },
193
+ })}
194
+ >
195
+ <span>{props.hasValue ? props.label : props.placeholder}</span>
196
+ <span aria-hidden="true">▾</span>
197
+ </button>
198
+ {props.open ? (
199
+ <div
200
+ ref={(el) => (dialogRef.current = el)}
201
+ id={dialogId}
202
+ role="dialog"
203
+ tabindex={-1}
204
+ aria-label={props.ariaLabel}
205
+ {...props.slot("popover", {
206
+ base: popoverDefault,
207
+ themed: {
208
+ background: props.theme.surface,
209
+ border: `1px solid ${props.theme.gridLine}`,
210
+ },
211
+ })}
212
+ >
213
+ {props.children}
214
+ </div>
215
+ ) : null}
216
+ </div>
217
+ );
218
+ }
219
+
220
+ /** Props for {@link DatePicker}. */
221
+ export interface DatePickerProps extends PickerBaseProps {
222
+ /** The selected day, or `null`. */
223
+ value: Date | null;
224
+ /** Called with the day the user picks. */
225
+ onChange: (date: Date) => void;
226
+ /** Format the trigger label. Default: `d MMM yyyy`. */
227
+ formatLabel?: (date: Date) => string;
228
+ }
229
+
230
+ /**
231
+ * A single-date input with a popover calendar. Controlled via `value` / `onChange`.
232
+ * Composed from {@link MonthList}; forward calendar slots (e.g. `dayBadge`) through
233
+ * `classNames` to restyle the popover.
234
+ *
235
+ * @example
236
+ * ```tsx
237
+ * const [value, setValue] = createSignal<Date | null>(null);
238
+ * <DatePicker value={value} onChange={setValue} />
239
+ * ```
240
+ */
241
+ export function DatePicker(incoming: DatePickerProps): JSX.Element {
242
+ const props = withDefaults(
243
+ {
244
+ formatLabel: (d) => format(d, "d MMM yyyy"),
245
+ weekStartsOn: 0,
246
+ height: 320,
247
+ placeholder: "Select a date",
248
+ } satisfies Partial<DatePickerProps>,
249
+ incoming,
250
+ );
251
+ const theme = createMemo(() => mergeSolidTheme(props.theme));
252
+ const slot = createSlots<DatePickerSlot | MonthListSlot>(props);
253
+ const { open, setOpen, rootRef, triggerRef } = createPopover(() => props.disabled);
254
+ return (
255
+ <PickerShell
256
+ open={open()}
257
+ setOpen={setOpen}
258
+ rootRef={rootRef}
259
+ triggerRef={triggerRef}
260
+ theme={theme()}
261
+ slot={slot}
262
+ label={props.value ? props.formatLabel(props.value) : ""}
263
+ hasValue={!!props.value}
264
+ placeholder={props.placeholder}
265
+ disabled={props.disabled}
266
+ className={props.className}
267
+ style={props.style}
268
+ ariaLabel="Choose a date"
269
+ focusDay={format(props.value ?? new Date(), "yyyy-MM-dd")}
270
+ >
271
+ <MonthList
272
+ theme={props.theme}
273
+ date={props.value ?? new Date()}
274
+ weekStartsOn={props.weekStartsOn}
275
+ selectedDates={props.value ? [props.value] : []}
276
+ minDate={props.minDate}
277
+ maxDate={props.maxDate}
278
+ isDateDisabled={props.isDateDisabled}
279
+ onPressDay={(day) => {
280
+ props.onChange(day);
281
+ setOpen(false);
282
+ triggerRef.current?.focus();
283
+ }}
284
+ height={props.height}
285
+ classNames={props.classNames}
286
+ styles={props.styles}
287
+ />
288
+ </PickerShell>
289
+ );
290
+ }
291
+
292
+ /** Props for {@link DateRangePicker}. */
293
+ export interface DateRangePickerProps extends PickerBaseProps {
294
+ /** The selected range, or `null`. `end` is `null` while only the start is picked. */
295
+ value: DateRange | null;
296
+ /** Called with the next range on each pick (start-only, then complete). */
297
+ onChange: (range: DateRange | null) => void;
298
+ /** Format the trigger label. Default: `d MMM – d MMM yyyy`. */
299
+ formatLabel?: (range: DateRange) => string;
300
+ }
301
+ function defaultRangeLabel(range: DateRange): string {
302
+ const start = format(range.start, "d MMM yyyy");
303
+ return range.end ? `${start} – ${format(range.end, "d MMM yyyy")}` : `${start} – …`;
304
+ }
305
+
306
+ /**
307
+ * A date-range input with a popover calendar. Controlled via `value` / `onChange`;
308
+ * each pick advances the range through {@link nextDateRange} (start, then end), and
309
+ * the popover closes once both ends are set.
310
+ *
311
+ * @example
312
+ * ```tsx
313
+ * const [range, setRange] = createSignal<DateRange | null>(null);
314
+ * <DateRangePicker value={range} onChange={setRange} />
315
+ * ```
316
+ */
317
+ export function DateRangePicker(incoming: DateRangePickerProps): JSX.Element {
318
+ const props = withDefaults(
319
+ {
320
+ formatLabel: defaultRangeLabel,
321
+ weekStartsOn: 0,
322
+ height: 320,
323
+ placeholder: "Select dates",
324
+ } satisfies Partial<DateRangePickerProps>,
325
+ incoming,
326
+ );
327
+ const theme = createMemo(() => mergeSolidTheme(props.theme));
328
+ const slot = createSlots<DatePickerSlot | MonthListSlot>(props);
329
+ const { open, setOpen, rootRef, triggerRef } = createPopover(() => props.disabled);
330
+ const constraints = createMemo<DateSelectionConstraints>(() => ({
331
+ minDate: props.minDate,
332
+ maxDate: props.maxDate,
333
+ isDateDisabled: props.isDateDisabled,
334
+ }));
335
+ return (
336
+ <PickerShell
337
+ open={open()}
338
+ setOpen={setOpen}
339
+ rootRef={rootRef}
340
+ triggerRef={triggerRef}
341
+ theme={theme()}
342
+ slot={slot}
343
+ label={props.value ? props.formatLabel(props.value) : ""}
344
+ hasValue={!!props.value}
345
+ placeholder={props.placeholder}
346
+ disabled={props.disabled}
347
+ className={props.className}
348
+ style={props.style}
349
+ ariaLabel="Choose a date range"
350
+ focusDay={format(props.value?.start ?? new Date(), "yyyy-MM-dd")}
351
+ >
352
+ <MonthList
353
+ theme={props.theme}
354
+ date={props.value?.start ?? new Date()}
355
+ weekStartsOn={props.weekStartsOn}
356
+ selectedRange={props.value ?? undefined}
357
+ minDate={props.minDate}
358
+ maxDate={props.maxDate}
359
+ isDateDisabled={props.isDateDisabled}
360
+ onPressDay={(day) => {
361
+ const next = nextDateRange(props.value, day, constraints());
362
+ props.onChange(next);
363
+ // Close once a full range is set.
364
+ if (next?.end) {
365
+ setOpen(false);
366
+ triggerRef.current?.focus();
367
+ }
368
+ }}
369
+ height={props.height}
370
+ classNames={props.classNames}
371
+ styles={props.styles}
372
+ />
373
+ <div
374
+ {...slot("footer", {
375
+ base: {
376
+ display: "flex",
377
+ justifyContent: "flex-end",
378
+ padding: "8px 10px",
379
+ },
380
+ themed: {
381
+ borderTop: `1px solid ${theme().gridLine}`,
382
+ },
383
+ })}
384
+ >
385
+ <button
386
+ type="button"
387
+ onClick={() => props.onChange(null)}
388
+ {...slot("clear", {
389
+ base: {
390
+ border: "none",
391
+ background: "transparent",
392
+ cursor: "pointer",
393
+ font: "inherit",
394
+ },
395
+ themed: {
396
+ color: theme().textMuted,
397
+ },
398
+ })}
399
+ >
400
+ Clear
401
+ </button>
402
+ </div>
403
+ </PickerShell>
404
+ );
405
+ }