@super-calendar/solid 0.0.0-stage → 2.17.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,652 @@
1
+ import { type JSX } from "@solidjs/web";
2
+ import {
3
+ bandRounding,
4
+ buildMonthWeeks,
5
+ type CalendarEvent,
6
+ type CalendarLabels,
7
+ type DateRange,
8
+ type DateSelectionConstraints,
9
+ dayAccessibilityLabel,
10
+ dayBadgeKind,
11
+ daySelectionState,
12
+ filterHiddenDays,
13
+ getIsToday,
14
+ getWeekDays,
15
+ getYearMonths,
16
+ groupEventsByDay,
17
+ isBackgroundEvent,
18
+ isSameCalendarDay,
19
+ monthCreateRange,
20
+ rangeBandKind,
21
+ resolveCalendarLabels,
22
+ weekdayFormatToken,
23
+ type WeekStartsOn,
24
+ } from "@super-calendar/core/vanilla";
25
+ import { format, type Locale, startOfDay } from "date-fns";
26
+ import { createEffect, createMemo, createSignal, For, untrack } from "solid-js";
27
+ import { withDefaults } from "./props";
28
+ import { createSlots, dataState, type SlotStyleProps } from "./slots";
29
+ import { css, type CSSProperties, type DomPointerEvent } from "./styles";
30
+ import { mergeSolidTheme, type SolidCalendarTheme } from "./theme";
31
+
32
+ /**
33
+ * Styleable parts of {@link YearView}. Pass a class or inline style per slot
34
+ * via the `classNames` / `styles` props; day cells carry `data-today`,
35
+ * `data-events`, `data-selected`, `data-range`, `data-disabled` and
36
+ * `data-creating` state attributes for variants.
37
+ */
38
+ export type YearViewSlot =
39
+ | "grid"
40
+ | "month"
41
+ | "monthTitle"
42
+ | "weekdays"
43
+ | "weekday"
44
+ | "week"
45
+ | "day"
46
+ | "dayBadge"
47
+ | "rangeBand"
48
+ | "eventDot";
49
+
50
+ /** Props for {@link YearView}, the twelve mini-month year grid. */
51
+ export interface YearViewProps<T = unknown>
52
+ extends DateSelectionConstraints, SlotStyleProps<YearViewSlot> {
53
+ /** Any date inside the year to render. */
54
+ date: Date;
55
+ /** Days holding at least one event get a dot. Omit for a plain year. */
56
+ events?: CalendarEvent<T>[];
57
+ /** First day of the week. Sunday = 0 (default) … Saturday = 6. */
58
+ weekStartsOn?: WeekStartsOn;
59
+ /** Weekdays (0=Sunday…6=Saturday) hidden from the grid, e.g. `[0, 6]` for weekends off. */
60
+ hiddenDays?: number[];
61
+ locale?: Locale;
62
+ /** Translations for the screen-reader words; omitted keys use English. */
63
+ labels?: Partial<CalendarLabels>;
64
+ /** Highlight this date instead of the real "today". */
65
+ activeDate?: Date;
66
+ /** A selected span: endpoints get a filled badge, the days between get the range band. */
67
+ selectedRange?: DateRange;
68
+ /** Discrete selected days, drawn with a filled badge. */
69
+ selectedDates?: Date[];
70
+ /**
71
+ * Smallest width a mini month may take before the grid drops a column
72
+ * (default 150). The grid fits as many columns as the container allows.
73
+ */
74
+ minMonthWidth?: number;
75
+ /** Tap a day cell (e.g. to drill into the day or month view). */
76
+ onPressDay?: (date: Date) => void;
77
+ /** Tap a month's title (e.g. to jump to that month's view). */
78
+ onPressMonth?: (month: Date) => void;
79
+ /**
80
+ * Enables drag-to-select and reports the swept span live, as the ordered
81
+ * inclusive `[start, end]` days (both at midnight). Pair it with
82
+ * `createDateRange`'s `selectRange` to drive `selectedRange`. Fires on every day the
83
+ * pointer crosses, so the highlight follows the drag; `onCreateEvent` (when also
84
+ * set) fires once on release. Either handler enables the same sweep gesture, and
85
+ * a sweep can run across mini months.
86
+ */
87
+ onSelectDrag?: (start: Date, end: Date) => void;
88
+ /**
89
+ * Enables drag-to-create: press a day and drag across others, then release to
90
+ * fire this with the all-day range (`start` at midnight of the first day, `end`
91
+ * at midnight after the last, exclusive). A plain click without dragging still
92
+ * fires `onPressDay`, not this. Days being sketched carry `data-creating`.
93
+ */
94
+ onCreateEvent?: (start: Date, end: Date) => void;
95
+ /** Theme overrides; falls back to the default light theme. */
96
+ theme?: Partial<SolidCalendarTheme>;
97
+ /** Class applied to the root element. */
98
+ className?: string;
99
+ /** Inline styles applied to the root element. */
100
+ style?: CSSProperties;
101
+ }
102
+
103
+ /**
104
+ * A year at a glance: the twelve months as compact mini grids, with today
105
+ * highlighted and a dot under days that hold events. It's the view `Calendar`
106
+ * renders for `mode="year"`.
107
+ */
108
+ export function YearView<T = unknown>(incoming: YearViewProps<T>): JSX.Element {
109
+ const props = withDefaults(
110
+ {
111
+ weekStartsOn: 0,
112
+ minMonthWidth: 150,
113
+ } satisfies Partial<YearViewProps<T>>,
114
+ incoming,
115
+ );
116
+ const theme = createMemo(() => mergeSolidTheme(props.theme));
117
+ const labels = createMemo(() => resolveCalendarLabels(props.labels));
118
+ const slot = createSlots<YearViewSlot>(props);
119
+
120
+ // Drag-to-select / drag-to-create: press a day and sweep across others (mini
121
+ // months included), released on a window pointerup so a drop anywhere commits.
122
+ // `onSelectDrag` reports the span live, `onCreateEvent` once on release.
123
+ const sweepEnabled = createMemo(() => props.onSelectDrag != null || props.onCreateEvent != null);
124
+ const [creating, setCreating] = createSignal<{
125
+ pointerId: number;
126
+ anchor: number;
127
+ hover: number;
128
+ } | null>(null);
129
+ const creatingRef: { current: ReturnType<typeof creating> } = { current: null };
130
+ const applyCreating = (value: ReturnType<typeof creating>) => {
131
+ creatingRef.current = value;
132
+ setCreating(value);
133
+ };
134
+ const movedRef = {
135
+ current: false,
136
+ };
137
+ // Set when a sweep commits, so the click the browser fires next doesn't also
138
+ // open the day via onPressDay. A sweep that ends over a different cell than it
139
+ // began on gets its trailing click on their common ancestor instead, where no
140
+ // handler consumes the guard, so every fresh press clears it first.
141
+ const suppressClickRef = {
142
+ current: false,
143
+ };
144
+ const beginPress = (e: DomPointerEvent) => {
145
+ if (creatingRef.current || e.isPrimary === false) return false;
146
+ suppressClickRef.current = false;
147
+ movedRef.current = false;
148
+ return true;
149
+ };
150
+ const beginCreate = (day: Date, pointerId: number) => {
151
+ const t = startOfDay(day).getTime();
152
+ applyCreating({
153
+ pointerId,
154
+ anchor: t,
155
+ hover: t,
156
+ });
157
+ };
158
+ const extendCreate = (day: Date, pointerId: number) => {
159
+ const current = creatingRef.current;
160
+ if (!current || current.pointerId !== pointerId) return;
161
+ const t = startOfDay(day).getTime();
162
+ if (t === current.hover) return;
163
+ movedRef.current = true;
164
+ applyCreating({ ...current, hover: t });
165
+ const [lo, hi] = current.anchor <= t ? [current.anchor, t] : [t, current.anchor];
166
+ props.onSelectDrag?.(new Date(lo), new Date(hi));
167
+ };
168
+ const isCreating = createMemo(() => creating() !== null);
169
+ createEffect(
170
+ () => [isCreating(), props.onCreateEvent],
171
+ () =>
172
+ untrack(() => {
173
+ if (!isCreating()) return;
174
+ const finish = (e: PointerEvent) => {
175
+ const c = creatingRef.current;
176
+ if (!c || c.pointerId !== e.pointerId) return;
177
+ applyCreating(null);
178
+ if (!movedRef.current) return;
179
+ suppressClickRef.current = true;
180
+ const range = monthCreateRange(new Date(c.anchor), new Date(c.hover));
181
+ props.onCreateEvent?.(range.start, range.end);
182
+ };
183
+ const cancel = (e: PointerEvent) => {
184
+ if (creatingRef.current?.pointerId !== e.pointerId) return;
185
+ applyCreating(null);
186
+ movedRef.current = false;
187
+ suppressClickRef.current = true;
188
+ };
189
+ window.addEventListener("pointerup", finish);
190
+ window.addEventListener("pointercancel", cancel);
191
+ return () => {
192
+ window.removeEventListener("pointerup", finish);
193
+ window.removeEventListener("pointercancel", cancel);
194
+ };
195
+ }),
196
+ );
197
+ const months = createMemo(() => getYearMonths(props.date));
198
+ const weekdayLabels = createMemo(() =>
199
+ filterHiddenDays(getWeekDays(props.date, props.weekStartsOn), props.hiddenDays).map((d) =>
200
+ format(d, weekdayFormatToken("narrow"), {
201
+ locale: props.locale,
202
+ }),
203
+ ),
204
+ );
205
+ // Days that hold at least one event, keyed like `groupEventsByDay`.
206
+ const eventDays = createMemo(
207
+ () =>
208
+ new Set(
209
+ props.events && props.events.length > 0
210
+ ? groupEventsByDay(props.events.filter((e) => !isBackgroundEvent(e))).keys()
211
+ : [],
212
+ ),
213
+ );
214
+ return (
215
+ <div
216
+ class={props.className}
217
+ style={css({
218
+ fontFamily: theme().fontFamily,
219
+ color: theme().text,
220
+ overflowY: "auto",
221
+ ...props.style,
222
+ })}
223
+ >
224
+ <div
225
+ {...slot("grid", {
226
+ base: {
227
+ display: "grid",
228
+ gridTemplateColumns: `repeat(auto-fill, minmax(${props.minMonthWidth}px, 1fr))`,
229
+ },
230
+ })}
231
+ >
232
+ {
233
+ <For each={months()} keyed={false}>
234
+ {(month) => {
235
+ const weeks = createMemo(() =>
236
+ buildMonthWeeks(month(), props.weekStartsOn, {
237
+ hiddenDays: props.hiddenDays,
238
+ }),
239
+ );
240
+ const monthLabel = createMemo(() =>
241
+ format(month(), "MMMM yyyy", {
242
+ locale: props.locale,
243
+ }),
244
+ );
245
+ const titleContent = createMemo(() =>
246
+ format(month(), "MMMM", {
247
+ locale: props.locale,
248
+ }),
249
+ );
250
+ return (
251
+ <div
252
+ {...slot("month", {
253
+ base: {
254
+ padding: 8,
255
+ },
256
+ })}
257
+ >
258
+ {props.onPressMonth ? (
259
+ <button
260
+ type="button"
261
+ onClick={() => props.onPressMonth?.(month())}
262
+ aria-label={monthLabel()}
263
+ {...slot("monthTitle", {
264
+ base: {
265
+ display: "block",
266
+ border: "none",
267
+ background: "transparent",
268
+ padding: "0 0 4px",
269
+ cursor: "pointer",
270
+ font: "inherit",
271
+ textAlign: "left",
272
+ },
273
+ themed: {
274
+ fontSize: 13,
275
+ fontWeight: 700,
276
+ color: theme().todayBackground,
277
+ },
278
+ })}
279
+ >
280
+ {titleContent()}
281
+ </button>
282
+ ) : (
283
+ <div
284
+ role="heading"
285
+ aria-level={3}
286
+ aria-label={monthLabel()}
287
+ {...slot("monthTitle", {
288
+ base: {
289
+ paddingBottom: 4,
290
+ },
291
+ themed: {
292
+ fontSize: 13,
293
+ fontWeight: 700,
294
+ color: theme().todayBackground,
295
+ },
296
+ })}
297
+ >
298
+ {titleContent()}
299
+ </div>
300
+ )}
301
+ <div
302
+ {...slot("weekdays", {
303
+ base: {
304
+ display: "grid",
305
+ gridTemplateColumns: "repeat(7, 1fr)",
306
+ },
307
+ })}
308
+ >
309
+ {
310
+ <For each={weekdayLabels()} keyed={false}>
311
+ {(label) => (
312
+ <div
313
+ aria-hidden="true"
314
+ {...slot("weekday", {
315
+ base: {
316
+ textAlign: "center",
317
+ },
318
+ themed: {
319
+ fontSize: 9,
320
+ fontWeight: 600,
321
+ color: theme().textMuted,
322
+ },
323
+ })}
324
+ >
325
+ {label()}
326
+ </div>
327
+ )}
328
+ </For>
329
+ }
330
+ </div>
331
+ <div role="grid" aria-label={monthLabel()}>
332
+ {
333
+ <For each={weeks()} keyed={false}>
334
+ {(week) => (
335
+ <div
336
+ role="row"
337
+ {...slot("week", {
338
+ base: {
339
+ display: "grid",
340
+ gridTemplateColumns: "repeat(7, 1fr)",
341
+ },
342
+ })}
343
+ >
344
+ {
345
+ <For each={week()} keyed={false}>
346
+ {(day) => {
347
+ return (
348
+ <>
349
+ {(() => {
350
+ // Adjacent-month days keep the grid shape but stay blank,
351
+ // like the mini months of other year views.
352
+ if (day().getMonth() !== month().getMonth()) {
353
+ return (
354
+ <div
355
+ role="gridcell"
356
+ aria-hidden="true"
357
+ style={css({
358
+ aspectRatio: "1",
359
+ })}
360
+ />
361
+ );
362
+ }
363
+ const isToday = createMemo(() => getIsToday(day()));
364
+ const isHighlighted = createMemo(() =>
365
+ props.activeDate
366
+ ? isSameCalendarDay(day(), props.activeDate)
367
+ : isToday(),
368
+ );
369
+ const hasEvents = createMemo(() =>
370
+ eventDays().has(startOfDay(day()).toISOString()),
371
+ );
372
+ // Selection/disabled flags come from core, so the year grid
373
+ // can't disagree with the month grid about a day's state.
374
+ const state = createMemo(() =>
375
+ daySelectionState(
376
+ day(),
377
+ {
378
+ selectedDates: props.selectedDates,
379
+ selectedRange: props.selectedRange,
380
+ },
381
+ {
382
+ minDate: props.minDate,
383
+ maxDate: props.maxDate,
384
+ isDateDisabled: props.isDateDisabled,
385
+ },
386
+ ),
387
+ );
388
+ const dayTime = createMemo(() =>
389
+ startOfDay(day()).getTime(),
390
+ );
391
+ const inCreate = createMemo(() => {
392
+ const currentCreating = creating();
393
+ return (
394
+ currentCreating != null &&
395
+ dayTime() >=
396
+ Math.min(
397
+ currentCreating.anchor,
398
+ currentCreating.hover,
399
+ ) &&
400
+ dayTime() <=
401
+ Math.max(
402
+ currentCreating.anchor,
403
+ currentCreating.hover,
404
+ )
405
+ );
406
+ });
407
+ const label = createMemo(() =>
408
+ dayAccessibilityLabel({
409
+ dateLabel: format(day(), "EEEE, d LLLL yyyy", {
410
+ locale: props.locale,
411
+ }),
412
+ isToday: isToday(),
413
+ isSelected: state().isSelected,
414
+ isDisabled: state().isDisabled,
415
+ hasEvents: hasEvents(),
416
+ labels: labels(),
417
+ }),
418
+ );
419
+ // Today wins over a selection, matching the month grid.
420
+ const badge = createMemo(() =>
421
+ dayBadgeKind(state(), isHighlighted()),
422
+ );
423
+ const daySlot = createMemo(() =>
424
+ slot("day", {
425
+ base: {
426
+ position: "relative",
427
+ aspectRatio: "1",
428
+ display: "flex",
429
+ alignItems: "center",
430
+ justifyContent: "center",
431
+ padding: 0,
432
+ border: "none",
433
+ background: "transparent",
434
+ font: "inherit",
435
+ cursor: state().isDisabled
436
+ ? "default"
437
+ : props.onPressDay || sweepEnabled()
438
+ ? "pointer"
439
+ : "default",
440
+ boxSizing: "border-box",
441
+ // The year grid scrolls vertically, so only the sideways
442
+ // axis is handed to the sweep: a vertical swipe still
443
+ // scrolls the months, a sideways drag sketches a range.
444
+ ...(sweepEnabled()
445
+ ? {
446
+ touchAction: "pan-y" as const,
447
+ }
448
+ : null),
449
+ },
450
+ themed: {
451
+ fontSize: 11,
452
+ color: state().isDisabled
453
+ ? theme().textDisabled
454
+ : theme().text,
455
+ },
456
+ }),
457
+ );
458
+ const states = createMemo(() =>
459
+ dataState({
460
+ // `data-today` states the fact; the activeDate highlight is
461
+ // visual only (themed), so the two can differ.
462
+ "data-today": isToday(),
463
+ "data-events": hasEvents(),
464
+ "data-selected": state().isSelected,
465
+ "data-range": state().isInRange,
466
+ "data-disabled": state().isDisabled,
467
+ "data-creating": inCreate(),
468
+ }),
469
+ );
470
+ // The range draws as a band behind the day badges. The mini
471
+ // cells sit flush in the grid, so per-cell segments read as one
472
+ // continuous strip; only the endpoints round their outer edge.
473
+ const bandKind = createMemo(() =>
474
+ rangeBandKind(state(), true),
475
+ );
476
+ const rounding = createMemo(() =>
477
+ bandRounding(rangeBandKind(state(), false)),
478
+ );
479
+ const band = createMemo(() =>
480
+ bandKind() === "none" ? null : (
481
+ <span
482
+ data-band
483
+ aria-hidden="true"
484
+ {...slot("rangeBand", {
485
+ base: {
486
+ position: "absolute",
487
+ inset: 0,
488
+ zIndex: 0,
489
+ borderTopLeftRadius: rounding().start ? "50%" : 0,
490
+ borderBottomLeftRadius: rounding().start
491
+ ? "50%"
492
+ : 0,
493
+ borderTopRightRadius: rounding().end ? "50%" : 0,
494
+ borderBottomRightRadius: rounding().end
495
+ ? "50%"
496
+ : 0,
497
+ },
498
+ themed: {
499
+ background: theme().rangeBackground,
500
+ },
501
+ })}
502
+ />
503
+ ),
504
+ );
505
+ const dot = createMemo(() =>
506
+ hasEvents() ? (
507
+ <span
508
+ aria-hidden="true"
509
+ {...slot("eventDot", {
510
+ base: {
511
+ position: "absolute",
512
+ bottom: 1,
513
+ left: "50%",
514
+ marginLeft: -1.5,
515
+ zIndex: 2,
516
+ width: 3,
517
+ height: 3,
518
+ borderRadius: 2,
519
+ },
520
+ themed: {
521
+ background:
522
+ badge() === "none"
523
+ ? theme().todayBackground
524
+ : theme().todayText,
525
+ },
526
+ })}
527
+ />
528
+ ) : null,
529
+ );
530
+ const content = createMemo(() => (
531
+ <>
532
+ {band()}
533
+ <span
534
+ {...slot("dayBadge", {
535
+ base: {
536
+ position: "relative",
537
+ zIndex: 1,
538
+ width: "100%",
539
+ height: "100%",
540
+ borderRadius: "50%",
541
+ display: "flex",
542
+ alignItems: "center",
543
+ justifyContent: "center",
544
+ },
545
+ themed:
546
+ badge() === "today"
547
+ ? {
548
+ background: theme().todayBackground,
549
+ color: theme().todayText,
550
+ }
551
+ : badge() === "selected"
552
+ ? {
553
+ background: theme().selectedBackground,
554
+ color: theme().selectedText,
555
+ }
556
+ : {},
557
+ })}
558
+ >
559
+ {day().getDate()}
560
+ </span>
561
+ {dot()}
562
+ </>
563
+ ));
564
+ // A disabled day is out of every selection, drag included, so
565
+ // it neither anchors a sweep nor extends one onto itself.
566
+ const sweepHandlers = createMemo(() =>
567
+ sweepEnabled()
568
+ ? {
569
+ onPointerDown: (e: DomPointerEvent) => {
570
+ if (
571
+ e.button === 0 &&
572
+ !state().isDisabled &&
573
+ beginPress(e)
574
+ )
575
+ beginCreate(day(), e.pointerId);
576
+ },
577
+ onPointerEnter: state().isDisabled
578
+ ? undefined
579
+ : (e: DomPointerEvent) =>
580
+ extendCreate(day(), e.pointerId),
581
+ }
582
+ : null,
583
+ );
584
+ // Only a day that does something on click is a button: with
585
+ // just the sweep wired, a button per day would be a tab stop
586
+ // whose click and Enter do nothing.
587
+ return props.onPressDay ? (
588
+ <button
589
+ type="button"
590
+ role="gridcell"
591
+ disabled={state().isDisabled}
592
+ aria-label={label()}
593
+ onClick={() => {
594
+ if (suppressClickRef.current) {
595
+ suppressClickRef.current = false;
596
+ return;
597
+ }
598
+ props.onPressDay?.(day());
599
+ }}
600
+ {...sweepHandlers()}
601
+ {...states()}
602
+ {...daySlot()}
603
+ >
604
+ {content()}
605
+ </button>
606
+ ) : sweepEnabled() ? (
607
+ <div
608
+ role="gridcell"
609
+ aria-disabled={
610
+ (state().isDisabled || undefined) == null
611
+ ? undefined
612
+ : state().isDisabled || undefined
613
+ ? "true"
614
+ : "false"
615
+ }
616
+ aria-label={label()}
617
+ {...sweepHandlers()}
618
+ {...states()}
619
+ {...daySlot()}
620
+ >
621
+ {content()}
622
+ </div>
623
+ ) : (
624
+ <div
625
+ role="gridcell"
626
+ aria-label={label()}
627
+ {...states()}
628
+ {...daySlot()}
629
+ >
630
+ {content()}
631
+ </div>
632
+ );
633
+ })()}
634
+ </>
635
+ );
636
+ }}
637
+ </For>
638
+ }
639
+ </div>
640
+ )}
641
+ </For>
642
+ }
643
+ </div>
644
+ </div>
645
+ );
646
+ }}
647
+ </For>
648
+ }
649
+ </div>
650
+ </div>
651
+ );
652
+ }