@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,1587 @@
1
+ import { Dynamic, type JSX } from "@solidjs/web";
2
+ import {
3
+ bandRounding,
4
+ buildMonthGrid,
5
+ type CalendarEvent,
6
+ type CalendarLabels,
7
+ compareDayEvents,
8
+ type DateRange,
9
+ type DateSelectionConstraints,
10
+ dayAccessibilityLabel,
11
+ dayBadgeKind,
12
+ type EventAccessibilityLabeler,
13
+ groupEventsByDay,
14
+ isAllDayEvent,
15
+ isBackgroundEvent,
16
+ layoutMonthWeek,
17
+ monthCreateRange,
18
+ monthDropBounds,
19
+ type MonthGridDay,
20
+ type MonthGridWeek,
21
+ overlapsOtherEvents,
22
+ rangeBandKind,
23
+ resolveCalendarLabels,
24
+ type WeekdayFormat,
25
+ type WeekStartsOn,
26
+ } from "@super-calendar/core/vanilla";
27
+ import {
28
+ addDays,
29
+ endOfMonth,
30
+ format,
31
+ isSameMonth,
32
+ type Locale,
33
+ startOfDay,
34
+ startOfMonth,
35
+ } from "date-fns";
36
+ import {
37
+ type Component,
38
+ createEffect,
39
+ createMemo,
40
+ createSignal,
41
+ For,
42
+ Show,
43
+ untrack,
44
+ } from "solid-js";
45
+ import { withDefaults } from "./props";
46
+ import { createSlots, dataState, type SlotDefault, type SlotStyleProps } from "./slots";
47
+ import { css, type CSSProperties, type DomKeyboardEvent, type ElementRef } from "./styles";
48
+ import { mergeSolidTheme, type SolidCalendarTheme } from "./theme";
49
+
50
+ /**
51
+ * Styleable parts of {@link MonthView}. Pass a class or inline style per slot via
52
+ * the `classNames` / `styles` props to restyle just that part.
53
+ */
54
+ export type MonthViewSlot =
55
+ | "title"
56
+ | "weekdays"
57
+ | "weekday"
58
+ | "grid"
59
+ | "week"
60
+ | "day"
61
+ | "dayBadge"
62
+ | "rangeBand"
63
+ | "events"
64
+ | "chipButton"
65
+ | "chip"
66
+ | "more"
67
+ | "morePopover";
68
+
69
+ // Stable empty layout for rows with no events (avoids a fresh object per render).
70
+ const EMPTY_LAYOUT = {
71
+ segments: [],
72
+ laneCount: 0,
73
+ } as const;
74
+
75
+ // Chip metrics for the events layout (when `events` is provided).
76
+ const DATE_ROW = 24;
77
+ const CHIP_HEIGHT = 18;
78
+ const CHIP_GAP = 2;
79
+ const CELL_PAD = 4;
80
+ // Opacity of an event chip while it is being dragged to another day.
81
+ const DRAGGED_CHIP_OPACITY = 0.4;
82
+
83
+ /** Props passed to a custom month event chip renderer. */
84
+ export interface SolidMonthEventArgs<T = unknown> {
85
+ /** The event to render. */
86
+ event: CalendarEvent<T>;
87
+ /** Call to fire the view's `onPressEvent` for this chip. */
88
+ onPress: () => void;
89
+ }
90
+
91
+ /** A component that renders a single month-grid event chip. */
92
+ export type SolidMonthEvent<T = unknown> = Component<SolidMonthEventArgs<T>>;
93
+
94
+ // An in-progress month drag: either a day span being swept out for a new event,
95
+ // or an existing event being carried to another day. Days are held as start-of-day
96
+ // timestamps, so the reducer-ish updates compare cheaply.
97
+ type MonthDrag<T> =
98
+ | {
99
+ kind: "create";
100
+ pointerId: number;
101
+ anchor: number;
102
+ hover: number;
103
+ }
104
+ | {
105
+ kind: "move";
106
+ pointerId: number;
107
+ event: CalendarEvent<T>;
108
+ from: number;
109
+ to: number;
110
+ };
111
+
112
+ /** Props for {@link MonthView}. */
113
+ export interface MonthViewProps<T = unknown>
114
+ extends DateSelectionConstraints, SlotStyleProps<MonthViewSlot> {
115
+ /** Any day within the month to render. */
116
+ date: Date;
117
+ /** First day of the week. Sunday = 0 (default) … Saturday = 6. */
118
+ weekStartsOn?: WeekStartsOn;
119
+ /** Weekdays (0=Sunday…6=Saturday) hidden from the grid, e.g. `[0, 6]` for weekends off. */
120
+ hiddenDays?: number[];
121
+ /** Weekday header label width: `narrow` ("M"), `short` ("Mon", default), or `long` ("Monday"). */
122
+ weekdayFormat?: WeekdayFormat;
123
+ /**
124
+ * Events to render as chips in each day cell. Passing this (even `[]`) switches
125
+ * the grid to the calendar layout (date in the corner, chips below); omit it for
126
+ * the compact date-picker look.
127
+ */
128
+ events?: CalendarEvent<T>[];
129
+ /** Custom chip renderer; falls back to the built-in titled chip. */
130
+ renderEvent?: SolidMonthEvent<T>;
131
+ /**
132
+ * Override the screen-reader label for each event chip. Receives the event and a
133
+ * `{ mode: "month", isAllDay, ampm: false }` context; return the full text to
134
+ * announce. Defaults to the event title and day (e.g. "Standup, 15 July").
135
+ */
136
+ eventAccessibilityLabel?: EventAccessibilityLabeler<T>;
137
+ /**
138
+ * Max event lanes (stacked rows) shown per week before the rest of a day's
139
+ * events collapse into a "+N more" row (default 3). Because multi-day events draw
140
+ * as one bar spanning a lane across the week, this caps lanes per row, not chips
141
+ * per day, so a long bar can push a lightly-booked day's own events into "+N more".
142
+ */
143
+ maxVisibleEventCount?: number;
144
+ /** Height of an event chip and of the "+N more" row, in px (default 18). */
145
+ chipHeight?: number;
146
+ /** Vertical gap between event chips, in px (default 2). */
147
+ chipGap?: number;
148
+ /** Template for the overflow row; `{moreCount}` is replaced (default "{moreCount} More"). */
149
+ moreLabel?: string;
150
+ /** Translations for the screen-reader words and gutter text; omitted keys use English. */
151
+ labels?: Partial<CalendarLabels>;
152
+ /** Tap an event chip. */
153
+ onPressEvent?: (event: CalendarEvent<T>) => void;
154
+ /** Tap the "+N more" overflow row. */
155
+ onPressMore?: (events: CalendarEvent<T>[], date: Date) => void;
156
+ /** Selected span; days between the endpoints get the range band. */
157
+ selectedRange?: DateRange;
158
+ /** Discrete selected days (single / multiple). */
159
+ selectedDates?: Date[];
160
+ /** Render days from the neighbouring months in the leading/trailing cells (default true). */
161
+ showAdjacentMonths?: boolean;
162
+ /** Tint weekend day cells with the theme's weekend background (default true). */
163
+ highlightWeekends?: boolean;
164
+ /**
165
+ * Fill the whole cell with the range background instead of the default
166
+ * centered rounded "pill" strip. Default false.
167
+ */
168
+ fillCellOnSelection?: boolean;
169
+ /** Render the "Month yyyy" title above the grid (default true). */
170
+ showTitle?: boolean;
171
+ /** Render the weekday header row (default true). */
172
+ showWeekdays?: boolean;
173
+ /** date-fns locale for the title and weekday labels. */
174
+ locale?: Locale;
175
+ /** Theme overrides; falls back to the default light theme. */
176
+ theme?: Partial<SolidCalendarTheme>;
177
+ /** Fired when a selectable day is clicked. */
178
+ onPressDay?: (date: Date) => void;
179
+ /**
180
+ * Fired alongside `onPressDay` when a day cell is clicked, with the same day at
181
+ * midnight, so one handler can create events across month and week/day modes.
182
+ */
183
+ onPressCell?: (date: Date) => void;
184
+ /**
185
+ * In events mode, enables drag-to-create: press on a day and drag across others
186
+ * to sketch a span, then release to fire this with the all-day range (`start` at
187
+ * midnight of the first day, `end` at midnight after the last, exclusive). A plain
188
+ * click without dragging still fires `onPressDay`, not this. Days being sketched
189
+ * carry `data-creating` for styling.
190
+ */
191
+ onCreateEvent?: (start: Date, end: Date) => void;
192
+ /**
193
+ * Reports the day span of a create sweep **as it happens**, as the ordered
194
+ * inclusive `[start, end]` days (both at midnight), so a selection highlight can
195
+ * follow the drag instead of appearing only on release. Pair it with
196
+ * `createDateRange`'s `selectRange` to drive `selectedRange`. Enables the sweep on
197
+ * its own, so it works without `onCreateEvent`.
198
+ */
199
+ onSelectDrag?: (start: Date, end: Date) => void;
200
+ /**
201
+ * In events mode, enables drag-to-reschedule: press an event chip and drop it on
202
+ * another day. Called with the event and its new `start`/`end`, both shifted by
203
+ * the whole days dragged, so the time of day and duration are preserved. Return
204
+ * `false` to reject the drop. The day under the pointer carries `data-drop` for
205
+ * styling.
206
+ */
207
+ onDragEvent?: (event: CalendarEvent<T>, start: Date, end: Date) => void | boolean;
208
+ /** Fired the instant an event is picked up for a drag, before anything is committed. */
209
+ onDragStart?: (event: CalendarEvent<T>) => void;
210
+ /** Allow moving events by default (per-event `startEditable` overrides). Default true. */
211
+ eventStartEditable?: boolean;
212
+ /** Reject a drop that would overlap another event (default true = allowed). */
213
+ eventOverlap?: boolean;
214
+ /**
215
+ * When events are shown, also make the day cells keyboard-navigable: a single
216
+ * roving tab stop, arrow keys move the focus, Enter opens the day (`onPressDay`).
217
+ * Default false, so keyboard focus moves through events only. The date picker
218
+ * (rendered without `events`) is always navigable regardless of this flag.
219
+ */
220
+ keyboardDayNavigation?: boolean;
221
+ /** Class applied to the root element. */
222
+ className?: string;
223
+ /** Inline styles applied to the root element. */
224
+ style?: CSSProperties;
225
+ }
226
+
227
+ // Each helper returns the slot's built-in styling split into `base` (structural,
228
+ // always applied) and `themed` (colour/type/spacing, dropped when a class is set).
229
+
230
+ function dayCellDefault(
231
+ day: MonthGridDay,
232
+ theme: SolidCalendarTheme,
233
+ highlightWeekends: boolean,
234
+ ): SlotDefault {
235
+ return {
236
+ base: {
237
+ position: "relative",
238
+ height: theme.cellHeight,
239
+ border: "none",
240
+ font: "inherit",
241
+ cursor: day.isDisabled ? "default" : "pointer",
242
+ display: "flex",
243
+ alignItems: "center",
244
+ justifyContent: "center",
245
+ padding: 0,
246
+ WebkitTapHighlightColor: "transparent",
247
+ },
248
+ themed: {
249
+ // The range band is a separate layer; the cell only carries the weekend tint.
250
+ background:
251
+ highlightWeekends && day.isWeekend && !day.isInRange
252
+ ? theme.weekendBackground
253
+ : "transparent",
254
+ fontSize: 15,
255
+ color: day.isDisabled ? theme.textDisabled : theme.text,
256
+ },
257
+ };
258
+ }
259
+
260
+ /**
261
+ * The range band behind a day, rendered as its own layer so it can be a centered
262
+ * rounded strip (the default) or fill the whole cell (`fillCell`). Returns null
263
+ * for days with no band. Endpoints get the leading/trailing pill rounding. Its
264
+ * geometry is structural; only the fill colour is themed.
265
+ *
266
+ * In events mode the strip tracks the compact date badge instead of the picker's
267
+ * tall cell, so it reads as a band across the dates rather than a block over the
268
+ * event chips (and matches the native renderer's month grid).
269
+ */
270
+ function rangeBandDefault(
271
+ day: MonthGridDay,
272
+ theme: SolidCalendarTheme,
273
+ fillCell: boolean,
274
+ eventsMode: boolean,
275
+ ): SlotDefault | null {
276
+ const kind = rangeBandKind(day, fillCell);
277
+ if (kind === "none") return null;
278
+ const fill = kind === "fill";
279
+ const badgeSize = eventsMode ? DATE_ROW - 2 : theme.dayBadgeSize;
280
+ const bandHeight = eventsMode ? badgeSize : theme.rangeBandHeight;
281
+ const inset = fill ? 0 : eventsMode ? CELL_PAD : Math.max(0, (theme.cellHeight - bandHeight) / 2);
282
+ const radius = fill ? 0 : bandHeight / 2;
283
+ const rounding = bandRounding(kind);
284
+ // Cap the pill at the endpoint circles: a start/end band stops at the circle's
285
+ // outer edge (half a badge in from the cell centre) rather than spilling to the
286
+ // cell edge, so no band shows in the empty space beside the day circles. Events
287
+ // mode puts the badge in the cell's corner instead of its centre, so there the
288
+ // band spans the whole cell and only rounds its outer ends.
289
+ const cap = eventsMode ? 0 : `calc(50% - ${badgeSize / 2}px)`;
290
+ const base: CSSProperties = {
291
+ position: "absolute",
292
+ left: rounding.start ? cap : 0,
293
+ right: rounding.end ? cap : 0,
294
+ top: inset,
295
+ // An events cell is far taller than its date row, so the strip is sized from
296
+ // the badge rather than stretched to the cell's bottom.
297
+ ...(fill || !eventsMode
298
+ ? {
299
+ bottom: inset,
300
+ }
301
+ : {
302
+ height: bandHeight,
303
+ }),
304
+ zIndex: 0,
305
+ };
306
+ if (rounding.start) {
307
+ base.borderTopLeftRadius = radius;
308
+ base.borderBottomLeftRadius = radius;
309
+ }
310
+ if (rounding.end) {
311
+ base.borderTopRightRadius = radius;
312
+ base.borderBottomRightRadius = radius;
313
+ }
314
+ return {
315
+ base,
316
+ themed: {
317
+ background: theme.rangeBackground,
318
+ },
319
+ };
320
+ }
321
+ function badgeDefault(day: MonthGridDay, theme: SolidCalendarTheme, hovered: boolean): SlotDefault {
322
+ const badge = dayBadgeKind(day, day.isToday);
323
+ const filled = badge !== "none";
324
+ const background = filled
325
+ ? badge === "today"
326
+ ? theme.todayBackground
327
+ : theme.selectedBackground
328
+ : hovered
329
+ ? theme.hoverBackground
330
+ : "transparent";
331
+ return {
332
+ base: {
333
+ position: "relative",
334
+ zIndex: 1,
335
+ width: theme.dayBadgeSize,
336
+ height: theme.dayBadgeSize,
337
+ borderRadius: "50%",
338
+ display: "flex",
339
+ alignItems: "center",
340
+ justifyContent: "center",
341
+ },
342
+ themed: {
343
+ background,
344
+ color: filled ? (day.isToday ? theme.todayText : theme.selectedText) : "inherit",
345
+ },
346
+ };
347
+ }
348
+
349
+ // --- Calendar (events) layout styles -------------------------------------
350
+
351
+ function eventCellDefault(
352
+ day: MonthGridDay,
353
+ theme: SolidCalendarTheme,
354
+ height: number,
355
+ highlightWeekends: boolean,
356
+ // True while a drag is over this day: a create sweep covering it, or a move
357
+ // about to land on it. Tinted over the weekend shading so the drag reads live.
358
+ isDragTarget: boolean,
359
+ chipGap: number,
360
+ ): SlotDefault {
361
+ return {
362
+ base: {
363
+ position: "relative",
364
+ minHeight: height,
365
+ minWidth: 0,
366
+ border: "none",
367
+ cursor: day.isDisabled ? "default" : "pointer",
368
+ display: "flex",
369
+ flexDirection: "column",
370
+ gap: chipGap,
371
+ padding: CELL_PAD,
372
+ boxSizing: "border-box",
373
+ textAlign: "left",
374
+ WebkitTapHighlightColor: "transparent",
375
+ },
376
+ themed: {
377
+ borderTop: `1px solid ${theme.gridLine}`,
378
+ background: isDragTarget
379
+ ? theme.rangeBackground
380
+ : highlightWeekends && day.isWeekend && !day.isInRange
381
+ ? theme.weekendBackground
382
+ : "transparent",
383
+ color: day.isDisabled ? theme.textDisabled : theme.text,
384
+ },
385
+ };
386
+ }
387
+ function compactBadgeDefault(day: MonthGridDay, theme: SolidCalendarTheme): SlotDefault {
388
+ const badge = dayBadgeKind(day, day.isToday);
389
+ const filled = badge !== "none";
390
+ return {
391
+ base: {
392
+ position: "relative",
393
+ zIndex: 1,
394
+ alignSelf: "flex-end",
395
+ width: DATE_ROW - 2,
396
+ height: DATE_ROW - 2,
397
+ borderRadius: "50%",
398
+ display: "flex",
399
+ alignItems: "center",
400
+ justifyContent: "center",
401
+ },
402
+ themed: {
403
+ fontSize: 13,
404
+ background: filled
405
+ ? badge === "today"
406
+ ? theme.todayBackground
407
+ : theme.selectedBackground
408
+ : "transparent",
409
+ color: filled ? (day.isToday ? theme.todayText : theme.selectedText) : "inherit",
410
+ },
411
+ };
412
+ }
413
+ const chipButtonDefault: SlotDefault = {
414
+ base: {
415
+ position: "relative",
416
+ zIndex: 1,
417
+ border: "none",
418
+ padding: 0,
419
+ margin: 0,
420
+ background: "transparent",
421
+ cursor: "pointer",
422
+ textAlign: "left",
423
+ fontFamily: "inherit",
424
+ },
425
+ };
426
+ function chipDefault(theme: SolidCalendarTheme, chipHeight: number): SlotDefault {
427
+ return {
428
+ base: {
429
+ display: "block",
430
+ height: chipHeight,
431
+ lineHeight: `${chipHeight}px`,
432
+ whiteSpace: "nowrap",
433
+ overflow: "hidden",
434
+ textOverflow: "ellipsis",
435
+ },
436
+ themed: {
437
+ padding: "0 6px",
438
+ borderRadius: 4,
439
+ background: theme.eventBackground,
440
+ color: theme.eventText,
441
+ fontSize: 11,
442
+ fontWeight: 600,
443
+ },
444
+ };
445
+ }
446
+ function moreButtonDefault(theme: SolidCalendarTheme, chipHeight: number): SlotDefault {
447
+ return {
448
+ base: {
449
+ position: "relative",
450
+ zIndex: 1,
451
+ border: "none",
452
+ background: "transparent",
453
+ cursor: "pointer",
454
+ textAlign: "left",
455
+ height: chipHeight,
456
+ lineHeight: `${chipHeight}px`,
457
+ fontFamily: "inherit",
458
+ },
459
+ themed: {
460
+ padding: "0 6px",
461
+ fontSize: 11,
462
+ fontWeight: 600,
463
+ color: theme.textMuted,
464
+ },
465
+ };
466
+ }
467
+
468
+ // Internal-only: MonthList passes a day→events index built once for the whole
469
+ // list (via `groupEventsByDay`) so each month doesn't rebuild it. Not exported,
470
+ // so it stays off the public MonthViewProps surface.
471
+ interface MonthViewInternalProps<T = unknown> extends MonthViewProps<T> {
472
+ eventsByDay?: ReadonlyMap<string, CalendarEvent<T>[]>;
473
+ }
474
+
475
+ // The distinct events touching a week row, in the per-day index's sorted order.
476
+ // A multi-day event lives in each covered day's bucket, so dedupe by reference;
477
+ // this scans only the row's days, not every event in the month.
478
+ function collectRowEvents<T>(
479
+ week: MonthGridWeek,
480
+ eventsByDay: ReadonlyMap<string, CalendarEvent<T>[]>,
481
+ ): CalendarEvent<T>[] {
482
+ const seen = new Set<CalendarEvent<T>>();
483
+ const out: CalendarEvent<T>[] = [];
484
+ for (const day of week.days) {
485
+ const list = eventsByDay.get(startOfDay(day.date).toISOString());
486
+ if (!list) continue;
487
+ for (const event of list) {
488
+ if (!seen.has(event)) {
489
+ seen.add(event);
490
+ out.push(event);
491
+ }
492
+ }
493
+ }
494
+ return out;
495
+ }
496
+
497
+ /**
498
+ * A single static month grid, rendered with plain DOM elements.
499
+ *
500
+ * @example
501
+ * ```tsx
502
+ * <MonthView date={new Date()} events={events} onPressDay={(d) => setDate(d)} />
503
+ * ```
504
+ */
505
+ export function MonthView<T = unknown>(incoming: MonthViewInternalProps<T>): JSX.Element {
506
+ const props = withDefaults(
507
+ {
508
+ weekStartsOn: 0,
509
+ weekdayFormat: "short",
510
+ maxVisibleEventCount: 3,
511
+ chipHeight: CHIP_HEIGHT,
512
+ chipGap: CHIP_GAP,
513
+ moreLabel: "{moreCount} More",
514
+ showAdjacentMonths: true,
515
+ highlightWeekends: true,
516
+ fillCellOnSelection: false,
517
+ showTitle: true,
518
+ showWeekdays: true,
519
+ eventStartEditable: true,
520
+ eventOverlap: true,
521
+ keyboardDayNavigation: false,
522
+ } satisfies Partial<MonthViewInternalProps<T>>,
523
+ incoming,
524
+ );
525
+ const theme = createMemo(() => mergeSolidTheme(props.theme));
526
+ const labels = createMemo(() => resolveCalendarLabels(props.labels));
527
+ const slot = createSlots<MonthViewSlot>(props);
528
+
529
+ // Calendar layout (date in the corner + event chips) is on whenever `events`
530
+ // is provided; otherwise the compact picker badge layout is used.
531
+ const eventsMode = createMemo(() => props.events !== undefined);
532
+ // The day cells form a roving tab stop (arrow keys + Enter) in the picker
533
+ // always, and in events mode only when the consumer opts in. Otherwise events
534
+ // mode tabs through the event chips alone.
535
+ const dayRoving = createMemo(() => !eventsMode() || props.keyboardDayNavigation);
536
+ // Use the list-built index when provided (MonthList), else build it for this
537
+ // month. Either way lookups use startOfDay(date).toISOString().
538
+ const eventsByDay = createMemo(() => {
539
+ // The list (MonthList) sorts before passing its index in; only sort here when
540
+ // building our own, so each day reads all-day events first, then by start.
541
+ if (props.eventsByDay) return props.eventsByDay;
542
+ // Background events shade the time grid; the month grid ignores them.
543
+ const map = groupEventsByDay((props.events ?? []).filter((event) => !isBackgroundEvent(event)));
544
+ for (const list of map.values()) list.sort(compareDayEvents);
545
+ return map;
546
+ });
547
+ const Chip = createMemo(() => props.renderEvent);
548
+ // Built-in "+N more" popover: opens when the consumer doesn't handle
549
+ // `onPressMore` themselves. Keyed by the day id; closes on outside click,
550
+ // Escape, or picking an event.
551
+ const [moreOpenFor, setMoreOpenFor] = createSignal<string | null>(null);
552
+ const morePopoverRef: ElementRef<HTMLDivElement | null> = {
553
+ current: null,
554
+ };
555
+ // The "+N more" button that opened the popover, so focus can return to it.
556
+ const moreTriggerRef: ElementRef<HTMLButtonElement | null> = {
557
+ current: null,
558
+ };
559
+ createEffect(
560
+ () => [moreOpenFor()],
561
+ () =>
562
+ untrack(() => {
563
+ if (moreOpenFor()) {
564
+ // Move focus into the dialog so keyboard users land on the first event.
565
+ morePopoverRef.current?.querySelector<HTMLElement>("button")?.focus();
566
+ return;
567
+ }
568
+ // Return focus to the trigger when the popover closes.
569
+ moreTriggerRef.current?.focus();
570
+ moreTriggerRef.current = null;
571
+ }),
572
+ );
573
+ createEffect(
574
+ () => [moreOpenFor()],
575
+ () =>
576
+ untrack(() => {
577
+ if (!moreOpenFor()) return;
578
+ const onDocPointerDown = (e: PointerEvent) => {
579
+ if (!morePopoverRef.current?.contains(e.target as Node)) {
580
+ // A pointer dismissal moves focus to whatever was clicked; don't yank
581
+ // it back to the trigger (that's for Escape and event selection).
582
+ moreTriggerRef.current = null;
583
+ setMoreOpenFor(null);
584
+ }
585
+ };
586
+ const onKey = (e: KeyboardEvent) => {
587
+ if (e.key === "Escape") setMoreOpenFor(null);
588
+ };
589
+ document.addEventListener("pointerdown", onDocPointerDown);
590
+ document.addEventListener("keydown", onKey);
591
+ return () => {
592
+ document.removeEventListener("pointerdown", onDocPointerDown);
593
+ document.removeEventListener("keydown", onKey);
594
+ };
595
+ }),
596
+ );
597
+ // Reserve `maxVisibleEventCount` rows below the date so every cell is uniform;
598
+ // when a day overflows, the last row becomes the "+N more" affordance.
599
+ const eventRowHeight = createMemo(
600
+ () => CELL_PAD * 2 + DATE_ROW + props.maxVisibleEventCount * (props.chipHeight + props.chipGap),
601
+ );
602
+ const _grid = createMemo(() =>
603
+ buildMonthGrid(props.date, {
604
+ weekStartsOn: props.weekStartsOn,
605
+ hiddenDays: props.hiddenDays,
606
+ weekdayFormat: props.weekdayFormat,
607
+ selectedRange: props.selectedRange,
608
+ selectedDates: props.selectedDates,
609
+ minDate: props.minDate,
610
+ maxDate: props.maxDate,
611
+ isDateDisabled: props.isDateDisabled,
612
+ locale: props.locale,
613
+ }),
614
+ );
615
+
616
+ // Lay out each week row's spanning bars once per data change, not per render, so
617
+ // hover / popover / drag-create state changes don't relay out every row.
618
+ const weekLayouts = createMemo(() =>
619
+ eventsMode()
620
+ ? _grid().weeks.map((week) =>
621
+ layoutMonthWeek(
622
+ week.days.map((d) => d.date),
623
+ collectRowEvents(week, eventsByDay()),
624
+ ),
625
+ )
626
+ : [],
627
+ );
628
+
629
+ // Roving tabindex: only one day is in the tab order; arrow keys move focus
630
+ // within the month, so the grid is a single, sensible tab stop.
631
+ const initialFocus = createMemo(() => {
632
+ const inMonth = (d?: Date | null) => !!d && isSameMonth(d, props.date);
633
+ if (inMonth(props.selectedRange?.start)) return startOfDay(props.selectedRange!.start);
634
+ const picked = props.selectedDates?.find(inMonth);
635
+ if (picked) return startOfDay(picked);
636
+ const today = new Date();
637
+ return isSameMonth(today, props.date) ? startOfDay(today) : startOfMonth(props.date);
638
+ });
639
+ const [focusedDate, setFocusedDate] = createSignal(untrack(() => initialFocus()));
640
+ const initialFocusRef = {
641
+ current: untrack(() => initialFocus()),
642
+ };
643
+ createEffect(
644
+ () => initialFocus(),
645
+ (value) => {
646
+ initialFocusRef.current = value;
647
+ },
648
+ );
649
+ const monthKey = createMemo(() => format(props.date, "yyyy-MM"));
650
+ let focusedMonth = untrack(monthKey);
651
+ createEffect(monthKey, (month) =>
652
+ untrack(() => {
653
+ if (month === focusedMonth) return;
654
+ focusedMonth = month;
655
+ setFocusedDate(initialFocusRef.current);
656
+ }),
657
+ );
658
+ const [hoveredKey, setHoveredKey] = createSignal<string | null>(null);
659
+ const gridRef: ElementRef<HTMLDivElement | null> = {
660
+ current: null,
661
+ };
662
+ const focusKey = createMemo(() => format(focusedDate(), "yyyy-MM-dd"));
663
+
664
+ // Dragging (events mode): press a day and drag across others to sketch an
665
+ // all-day span, or press an event chip and drop it on another day. Both are
666
+ // released on a window pointerup, so letting go anywhere still commits.
667
+ const [drag, setDrag] = createSignal<MonthDrag<T> | null>(null);
668
+ const dragRef: ElementRef<MonthDrag<T> | null> = { current: null };
669
+ const applyDrag = (value: MonthDrag<T> | null) => {
670
+ dragRef.current = value;
671
+ setDrag(value);
672
+ };
673
+ const movedRef = {
674
+ current: false,
675
+ };
676
+ // Set when a drag commits, so the click the browser fires next is swallowed (it
677
+ // must not also open the day, or the event the drag landed on). A drag that ends
678
+ // over a different element than it began on gets its trailing click on their
679
+ // common ancestor instead, where no handler consumes the guard, so every press
680
+ // clears it first, keeping it scoped to the one interaction that set it.
681
+ const suppressClickRef = {
682
+ current: false,
683
+ };
684
+ const consumeSuppressedClick = () => {
685
+ if (!suppressClickRef.current) return false;
686
+ suppressClickRef.current = false;
687
+ return true;
688
+ };
689
+ // `disabled` and `draggable: false` lock an event outright; `startEditable`
690
+ // (per event, falling back to the grid default) allows or blocks a move.
691
+ const canMove = (event: CalendarEvent<T>) =>
692
+ props.onDragEvent != null &&
693
+ !event.disabled &&
694
+ event.draggable !== false &&
695
+ (event.startEditable ?? props.eventStartEditable);
696
+ // A fresh press starts a new interaction, so any guard left over from the
697
+ // previous one is stale.
698
+ const beginPress = (e: PointerEvent) => {
699
+ if (dragRef.current || e.isPrimary === false) return false;
700
+ suppressClickRef.current = false;
701
+ movedRef.current = false;
702
+ return true;
703
+ };
704
+ const beginCreate = (day: Date, pointerId: number) => {
705
+ if (!props.onCreateEvent && !props.onSelectDrag) return;
706
+ const t = startOfDay(day).getTime();
707
+ applyDrag({
708
+ kind: "create",
709
+ pointerId,
710
+ anchor: t,
711
+ hover: t,
712
+ });
713
+ };
714
+ const beginMove = (event: CalendarEvent<T>, day: Date, pointerId: number) => {
715
+ if (!canMove(event)) return;
716
+ const t = startOfDay(day).getTime();
717
+ applyDrag({
718
+ kind: "move",
719
+ pointerId,
720
+ event,
721
+ from: t,
722
+ to: t,
723
+ });
724
+ props.onDragStart?.(event);
725
+ };
726
+ const extendDrag = (day: Date, pointerId: number) => {
727
+ const current = dragRef.current;
728
+ if (!current || current.pointerId !== pointerId) return;
729
+ const t = startOfDay(day).getTime();
730
+ if (t === (current.kind === "create" ? current.hover : current.to)) return;
731
+ movedRef.current = true;
732
+ applyDrag(
733
+ current.kind === "create"
734
+ ? {
735
+ ...current,
736
+ hover: t,
737
+ }
738
+ : {
739
+ ...current,
740
+ to: t,
741
+ },
742
+ );
743
+ // A sweep reports its span live, so a selection can track the drag; a move
744
+ // has nothing to report until it is dropped.
745
+ if (current.kind === "create") {
746
+ const [lo, hi] = current.anchor <= t ? [current.anchor, t] : [t, current.anchor];
747
+ props.onSelectDrag?.(new Date(lo), new Date(hi));
748
+ }
749
+ };
750
+ const isDragging = createMemo(() => drag() !== null);
751
+ // Whether any month drag is wired up at all, so the cells only take over touch
752
+ // scrolling and pointer tracking when one of the handlers can actually fire.
753
+ const dragWired = createMemo(
754
+ () => props.onCreateEvent != null || props.onSelectDrag != null || props.onDragEvent != null,
755
+ );
756
+ createEffect(
757
+ () => [isDragging(), props.onCreateEvent, props.onDragEvent, props.eventOverlap, props.events],
758
+ () =>
759
+ untrack(() => {
760
+ if (!isDragging()) return;
761
+ const finish = (e: PointerEvent) => {
762
+ const current = dragRef.current;
763
+ if (!current || current.pointerId !== e.pointerId) return;
764
+ applyDrag(null);
765
+ if (!movedRef.current) return;
766
+ suppressClickRef.current = true;
767
+ if (current.kind === "create") {
768
+ const range = monthCreateRange(new Date(current.anchor), new Date(current.hover));
769
+ props.onCreateEvent?.(range.start, range.end);
770
+ return;
771
+ }
772
+ const next = monthDropBounds(current.event, new Date(current.from), new Date(current.to));
773
+ if (!next) return;
774
+ // Reject a drop that would land the event on top of another when
775
+ // `eventOverlap` is off, before the consumer's handler ever sees it.
776
+ if (
777
+ props.eventOverlap === false &&
778
+ overlapsOtherEvents(props.events ?? [], current.event, next.start, next.end)
779
+ ) {
780
+ return;
781
+ }
782
+ props.onDragEvent?.(current.event, next.start, next.end);
783
+ };
784
+ const cancel = (e: PointerEvent) => {
785
+ if (dragRef.current?.pointerId !== e.pointerId) return;
786
+ applyDrag(null);
787
+ movedRef.current = false;
788
+ suppressClickRef.current = true;
789
+ };
790
+ window.addEventListener("pointerup", finish);
791
+ window.addEventListener("pointercancel", cancel);
792
+ return () => {
793
+ window.removeEventListener("pointerup", finish);
794
+ window.removeEventListener("pointercancel", cancel);
795
+ };
796
+ }),
797
+ );
798
+ const onKeyDown = (e: DomKeyboardEvent<HTMLDivElement>) => {
799
+ let next: Date | null = null;
800
+ if (e.key === "ArrowLeft") next = addDays(focusedDate(), -1);
801
+ else if (e.key === "ArrowRight") next = addDays(focusedDate(), 1);
802
+ else if (e.key === "ArrowUp") next = addDays(focusedDate(), -7);
803
+ else if (e.key === "ArrowDown") next = addDays(focusedDate(), 7);
804
+ else if (e.key === "Home") next = startOfMonth(props.date);
805
+ else if (e.key === "End") next = endOfMonth(props.date);
806
+ else return;
807
+ e.preventDefault();
808
+ if (!isSameMonth(next, props.date)) return;
809
+ setFocusedDate(next);
810
+ const key = format(next, "yyyy-MM-dd");
811
+ gridRef.current?.querySelector<HTMLElement>(`[data-day="${key}"]`)?.focus();
812
+ };
813
+ return (
814
+ <div
815
+ class={props.className}
816
+ style={css({
817
+ fontFamily: theme().fontFamily,
818
+ color: theme().text,
819
+ ...props.style,
820
+ })}
821
+ >
822
+ {props.showTitle ? (
823
+ <div
824
+ {...slot("title", {
825
+ themed: {
826
+ fontSize: 17,
827
+ fontWeight: 700,
828
+ padding: "10px 14px 6px",
829
+ },
830
+ })}
831
+ >
832
+ {format(
833
+ props.date,
834
+ "MMMM yyyy",
835
+ props.locale
836
+ ? {
837
+ locale: props.locale,
838
+ }
839
+ : undefined,
840
+ )}
841
+ </div>
842
+ ) : null}
843
+ {props.showWeekdays ? (
844
+ <div
845
+ {...slot("weekdays", {
846
+ base: {
847
+ display: "grid",
848
+ gridTemplateColumns: "repeat(7, minmax(0, 1fr))",
849
+ },
850
+ themed: {
851
+ borderBottom: `1px solid ${theme().gridLine}`,
852
+ padding: "6px 0",
853
+ },
854
+ })}
855
+ >
856
+ {
857
+ <For each={_grid().weekdays} keyed={false}>
858
+ {(wd) => (
859
+ <span
860
+ {...slot("weekday", {
861
+ themed: {
862
+ textAlign: "center",
863
+ fontSize: 12,
864
+ fontWeight: 600,
865
+ color: theme().textMuted,
866
+ },
867
+ })}
868
+ >
869
+ {wd().label}
870
+ </span>
871
+ )}
872
+ </For>
873
+ }
874
+ </div>
875
+ ) : null}
876
+ <div
877
+ ref={(el) => (gridRef.current = el)}
878
+ role="grid"
879
+ aria-label={format(
880
+ props.date,
881
+ "MMMM yyyy",
882
+ props.locale
883
+ ? {
884
+ locale: props.locale,
885
+ }
886
+ : undefined,
887
+ )}
888
+ // Arrow-key roving applies whenever the day cells are a tab stop: the
889
+ // picker always, events mode only when keyboardDayNavigation is set.
890
+ onKeyDown={dayRoving() ? onKeyDown : undefined}
891
+ {...slot("grid")}
892
+ >
893
+ {
894
+ <For each={_grid().weeks} keyed={false}>
895
+ {(week, weekIndex) => {
896
+ // Spanning bars for this row (laid out once in `weekLayouts`). A multi-day
897
+ // event is one bar across its columns, stacked into lanes; each bar renders
898
+ // inside its start-column cell (valid grid content that reads with that day)
899
+ // and overflows right across the days it spans. The cells reserve the lane
900
+ // rows so "+more" sits below the bars.
901
+ const rowLayout = createMemo(() => weekLayouts()[weekIndex] ?? EMPTY_LAYOUT);
902
+ // When lanes overflow, keep the last row for "+more" but always show at
903
+ // least one bar, so a day never collapses to only the overflow row.
904
+ const overflowing = createMemo(
905
+ () => rowLayout().laneCount > props.maxVisibleEventCount,
906
+ );
907
+ const visibleLanes = createMemo(() =>
908
+ overflowing() ? Math.max(props.maxVisibleEventCount - 1, 1) : rowLayout().laneCount,
909
+ );
910
+ // With adjacent months hidden, clamp bars to the current-month columns so
911
+ // none draw over the blank leading/trailing cells.
912
+ const cols = createMemo(() => week().days.length);
913
+ const columns = createMemo(() => {
914
+ let first = 0;
915
+ let last = cols() - 1;
916
+ if (eventsMode() && !props.showAdjacentMonths) {
917
+ const start = week().days.findIndex((d) => d.isCurrentMonth);
918
+ const end = [...week().days].reverse().findIndex((d) => d.isCurrentMonth);
919
+ if (start !== -1) {
920
+ first = start;
921
+ last = cols() - 1 - end;
922
+ }
923
+ }
924
+ return {
925
+ first,
926
+ last,
927
+ };
928
+ });
929
+ return (
930
+ <>
931
+ {(() => {
932
+ const barSegs = createMemo(() =>
933
+ rowLayout()
934
+ .segments.filter((s) => s.lane < visibleLanes())
935
+ .map((s) => {
936
+ const startCol = Math.max(s.startCol, columns().first);
937
+ const endCol = Math.min(s.endCol, columns().last);
938
+ return {
939
+ seg: s,
940
+ startCol,
941
+ endCol,
942
+ continuesBefore: s.continuesBefore || startCol > s.startCol,
943
+ continuesAfter: s.continuesAfter || endCol < s.endCol,
944
+ };
945
+ })
946
+ .filter((b) => b.startCol <= b.endCol),
947
+ );
948
+ const barChipButton = createMemo(() => slot("chipButton", chipButtonDefault));
949
+ const barChip = createMemo(() =>
950
+ slot("chip", chipDefault(theme(), props.chipHeight)),
951
+ );
952
+ return (
953
+ <div
954
+ role="row"
955
+ {...slot("week", {
956
+ base: {
957
+ display: "grid",
958
+ gridTemplateColumns: "repeat(7, minmax(0, 1fr))",
959
+ },
960
+ })}
961
+ >
962
+ {
963
+ <For each={week().days} keyed={false}>
964
+ {(day, dayCol) => {
965
+ const hidden = createMemo(
966
+ () => !props.showAdjacentMonths && !day().isCurrentMonth,
967
+ );
968
+ const cellHeight = createMemo(() =>
969
+ eventsMode() ? eventRowHeight() : theme().cellHeight,
970
+ );
971
+ return (
972
+ <>
973
+ {(() => {
974
+ if (hidden()) {
975
+ return (
976
+ <div
977
+ role="gridcell"
978
+ aria-hidden="true"
979
+ style={css({
980
+ height: cellHeight(),
981
+ })}
982
+ />
983
+ );
984
+ }
985
+ const band = createMemo(() =>
986
+ rangeBandDefault(
987
+ day(),
988
+ theme(),
989
+ props.fillCellOnSelection,
990
+ eventsMode(),
991
+ ),
992
+ );
993
+ const dateLabel = createMemo(() =>
994
+ format(
995
+ day().date,
996
+ "EEEE, d MMMM yyyy",
997
+ props.locale
998
+ ? {
999
+ locale: props.locale,
1000
+ }
1001
+ : undefined,
1002
+ ),
1003
+ );
1004
+ const label = createMemo(() =>
1005
+ dayAccessibilityLabel({
1006
+ dateLabel: dateLabel(),
1007
+ isToday: day().isToday,
1008
+ labels: labels(),
1009
+ }),
1010
+ );
1011
+ const dayTime = createMemo(() =>
1012
+ startOfDay(day().date).getTime(),
1013
+ );
1014
+ const inCreate = createMemo(() => {
1015
+ const currentDrag = drag();
1016
+ return (
1017
+ currentDrag?.kind === "create" &&
1018
+ dayTime() >=
1019
+ Math.min(currentDrag.anchor, currentDrag.hover) &&
1020
+ dayTime() <= Math.max(currentDrag.anchor, currentDrag.hover)
1021
+ );
1022
+ });
1023
+ // The day an event is about to land on (not the one it came from).
1024
+ const isDropTarget = createMemo(() => {
1025
+ const currentDrag = drag();
1026
+ return (
1027
+ currentDrag?.kind === "move" &&
1028
+ dayTime() === currentDrag.to &&
1029
+ currentDrag.to !== currentDrag.from
1030
+ );
1031
+ });
1032
+ // Present/absent data-* attributes so consumers can style day state
1033
+ // with CSS/Tailwind variants (e.g. `data-[today]:bg-blue-500`).
1034
+ const dayData = createMemo(() =>
1035
+ dataState({
1036
+ "data-today": day().isToday,
1037
+ "data-selected": day().isSelected,
1038
+ "data-range": day().isInRange,
1039
+ "data-weekend": day().isWeekend,
1040
+ "data-outside": !day().isCurrentMonth,
1041
+ "data-disabled": day().isDisabled,
1042
+ "data-creating": inCreate(),
1043
+ "data-drop": isDropTarget(),
1044
+ }),
1045
+ );
1046
+ if (eventsMode()) {
1047
+ const dayEvents = createMemo(
1048
+ () =>
1049
+ eventsByDay().get(startOfDay(day().date).toISOString()) ??
1050
+ [],
1051
+ );
1052
+ // Events past the visible lanes (this day's segments in a lane the
1053
+ // row doesn't show) collapse into "+N more"; the popover lists the
1054
+ // whole day.
1055
+ const hiddenEvents = createMemo(() =>
1056
+ rowLayout()
1057
+ .segments.filter(
1058
+ (s) =>
1059
+ s.startCol <= dayCol &&
1060
+ s.endCol >= dayCol &&
1061
+ s.lane >= visibleLanes(),
1062
+ )
1063
+ .map((s) => s.event),
1064
+ );
1065
+ const dayLabel = createMemo(() =>
1066
+ format(
1067
+ day().date,
1068
+ "d MMMM",
1069
+ props.locale
1070
+ ? {
1071
+ locale: props.locale,
1072
+ }
1073
+ : undefined,
1074
+ ),
1075
+ );
1076
+ const dayCellProps = createMemo(() =>
1077
+ slot(
1078
+ "day",
1079
+ eventCellDefault(
1080
+ day(),
1081
+ theme(),
1082
+ cellHeight(),
1083
+ props.highlightWeekends,
1084
+ inCreate() || isDropTarget(),
1085
+ props.chipGap,
1086
+ ),
1087
+ ),
1088
+ );
1089
+ return (
1090
+ // Events mode: by default the cell is not a tab stop, so keyboard
1091
+ // focus moves through the event chips (real buttons) only, not
1092
+ // every empty day. With keyboardDayNavigation the cell joins the
1093
+ // roving tab order (arrow keys + Enter to open the day). A pointer
1094
+ // click always drills into the day.
1095
+ <div
1096
+ role="gridcell"
1097
+ data-day={day().id}
1098
+ onFocusIn={(event) => {
1099
+ if (event.target === event.currentTarget)
1100
+ setFocusedDate(day().date);
1101
+ }}
1102
+ {...dayData()}
1103
+ tabindex={
1104
+ props.keyboardDayNavigation
1105
+ ? day().id === focusKey()
1106
+ ? 0
1107
+ : -1
1108
+ : undefined
1109
+ }
1110
+ aria-disabled={
1111
+ (day().isDisabled || undefined) == null
1112
+ ? undefined
1113
+ : day().isDisabled || undefined
1114
+ ? "true"
1115
+ : "false"
1116
+ }
1117
+ aria-label={dayAccessibilityLabel({
1118
+ dateLabel: dateLabel(),
1119
+ isToday: day().isToday,
1120
+ isSelected: day().isSelected,
1121
+ eventCount: dayEvents().length,
1122
+ labels: labels(),
1123
+ })}
1124
+ {...dayCellProps()}
1125
+ // Dragging disables touch scroll on the cell so a swipe
1126
+ // sketches a span (or carries an event) instead of scrolling
1127
+ // the grid, and stops the sweep from text-selecting the day
1128
+ // numbers and chip titles it passes over.
1129
+ style={css(
1130
+ dragWired()
1131
+ ? {
1132
+ ...dayCellProps().style,
1133
+ touchAction: "none",
1134
+ userSelect: "none",
1135
+ }
1136
+ : dayCellProps().style,
1137
+ )}
1138
+ onPointerDown={
1139
+ dragWired() && !day().isDisabled
1140
+ ? (e) => {
1141
+ if (e.button !== 0 || !beginPress(e)) return;
1142
+ beginCreate(day().date, e.pointerId);
1143
+ }
1144
+ : undefined
1145
+ }
1146
+ // A disabled day is out of every selection, drag included, so
1147
+ // a sweep never extends onto it and no drop lands there.
1148
+ onPointerEnter={
1149
+ dragWired() && !day().isDisabled
1150
+ ? (e) => extendDrag(day().date, e.pointerId)
1151
+ : undefined
1152
+ }
1153
+ onClick={
1154
+ day().isDisabled
1155
+ ? undefined
1156
+ : () => {
1157
+ if (consumeSuppressedClick()) return;
1158
+ props.onPressDay?.(day().date);
1159
+ props.onPressCell?.(startOfDay(day().date));
1160
+ }
1161
+ }
1162
+ onKeyDown={
1163
+ props.keyboardDayNavigation && !day().isDisabled
1164
+ ? (e) => {
1165
+ // Let Enter/Space on a focused chip activate the chip.
1166
+ if (e.target !== e.currentTarget) return;
1167
+ if (e.key === "Enter" || e.key === " ") {
1168
+ e.preventDefault();
1169
+ props.onPressDay?.(day().date);
1170
+ props.onPressCell?.(startOfDay(day().date));
1171
+ }
1172
+ }
1173
+ : undefined
1174
+ }
1175
+ >
1176
+ {
1177
+ <Show when={band()}>
1178
+ {(band) => (
1179
+ <span
1180
+ data-band
1181
+ aria-hidden="true"
1182
+ {...slot("rangeBand", band())}
1183
+ />
1184
+ )}
1185
+ </Show>
1186
+ }
1187
+ <span
1188
+ {...dayData()}
1189
+ {...slot(
1190
+ "dayBadge",
1191
+ compactBadgeDefault(day(), theme()),
1192
+ )}
1193
+ >
1194
+ {day().label}
1195
+ </span>
1196
+ {/* Spanning bars that start in this column: absolutely placed,
1197
+ overflowing right across the days they span. Rendered here
1198
+ (not a row overlay) so each bar is valid content of its
1199
+ start day's gridcell and reads with that day. Made
1200
+ non-interactive mid drag so a sweep (or a move) reaches the
1201
+ cells beneath. */}
1202
+ {
1203
+ <For
1204
+ each={barSegs().filter((b) => b.startCol === dayCol)}
1205
+ keyed={false}
1206
+ >
1207
+ {(b) => {
1208
+ const span = createMemo(
1209
+ () => b().endCol - b().startCol + 1,
1210
+ );
1211
+ const isDragged = createMemo(() => {
1212
+ const currentDrag = drag();
1213
+ return (
1214
+ currentDrag?.kind === "move" &&
1215
+ currentDrag.event === b().seg.event
1216
+ );
1217
+ });
1218
+ return (
1219
+ <button
1220
+ type="button"
1221
+ onPointerDown={
1222
+ canMove(b().seg.event)
1223
+ ? (e) => {
1224
+ if (e.button !== 0 || !beginPress(e))
1225
+ return;
1226
+ e.stopPropagation();
1227
+ beginMove(
1228
+ b().seg.event,
1229
+ day().date,
1230
+ e.pointerId,
1231
+ );
1232
+ }
1233
+ : undefined
1234
+ }
1235
+ onClick={(e) => {
1236
+ e.stopPropagation();
1237
+ if (consumeSuppressedClick()) return;
1238
+ props.onPressEvent?.(b().seg.event);
1239
+ }}
1240
+ {...barChipButton()}
1241
+ title={b().seg.event.title}
1242
+ aria-label={
1243
+ props.eventAccessibilityLabel
1244
+ ? props.eventAccessibilityLabel(
1245
+ b().seg.event,
1246
+ {
1247
+ mode: "month",
1248
+ isAllDay: isAllDayEvent(
1249
+ b().seg.event,
1250
+ ),
1251
+ ampm: false,
1252
+ },
1253
+ )
1254
+ : `${b().seg.event.title}, ${dayLabel()}`
1255
+ }
1256
+ style={css({
1257
+ ...barChipButton().style,
1258
+ position: "absolute",
1259
+ left: 2,
1260
+ width: `calc(${span() * 100}% - 4px)`,
1261
+ top:
1262
+ CELL_PAD +
1263
+ DATE_ROW +
1264
+ props.chipGap +
1265
+ b().seg.lane *
1266
+ (props.chipHeight + props.chipGap),
1267
+ height: props.chipHeight,
1268
+ pointerEvents: isDragging() ? "none" : "auto",
1269
+ // Fade the bar being carried, so the tinted drop
1270
+ // target reads as where it is going.
1271
+ opacity: isDragged()
1272
+ ? DRAGGED_CHIP_OPACITY
1273
+ : undefined,
1274
+ cursor: canMove(b().seg.event)
1275
+ ? "grab"
1276
+ : undefined,
1277
+ touchAction: dragWired() ? "none" : undefined,
1278
+ zIndex: 2,
1279
+ })}
1280
+ >
1281
+ {Chip() ? (
1282
+ <Dynamic
1283
+ component={Chip()}
1284
+ event={b().seg.event}
1285
+ onPress={() =>
1286
+ props.onPressEvent?.(b().seg.event)
1287
+ }
1288
+ />
1289
+ ) : (
1290
+ <span
1291
+ {...barChip()}
1292
+ style={css({
1293
+ ...barChip().style,
1294
+ ...(b().continuesBefore
1295
+ ? {
1296
+ borderTopLeftRadius: 0,
1297
+ borderBottomLeftRadius: 0,
1298
+ }
1299
+ : null),
1300
+ ...(b().continuesAfter
1301
+ ? {
1302
+ borderTopRightRadius: 0,
1303
+ borderBottomRightRadius: 0,
1304
+ }
1305
+ : null),
1306
+ })}
1307
+ >
1308
+ {b().seg.event.title}
1309
+ </span>
1310
+ )}
1311
+ </button>
1312
+ );
1313
+ }}
1314
+ </For>
1315
+ }
1316
+ <div
1317
+ {...slot("events", {
1318
+ base: {
1319
+ display: "flex",
1320
+ flexDirection: "column",
1321
+ gap: props.chipGap,
1322
+ },
1323
+ })}
1324
+ >
1325
+ {/* Reserve one row per visible lane so the absolute bars have
1326
+ space and "+more" sits below them. */}
1327
+ {Array.from(
1328
+ {
1329
+ length: visibleLanes(),
1330
+ },
1331
+ () => (
1332
+ <div
1333
+ aria-hidden="true"
1334
+ style={css({
1335
+ height: props.chipHeight,
1336
+ })}
1337
+ />
1338
+ ),
1339
+ )}
1340
+ {hiddenEvents().length > 0 ? (
1341
+ <button
1342
+ type="button"
1343
+ // In built-in-popover mode, keep the document
1344
+ // pointerdown dismiss from firing before this click's
1345
+ // toggle, so pressing the button again closes it.
1346
+ onPointerDown={
1347
+ props.onPressMore
1348
+ ? undefined
1349
+ : (e) => e.stopPropagation()
1350
+ }
1351
+ onClick={(e) => {
1352
+ e.stopPropagation();
1353
+ if (props.onPressMore)
1354
+ props.onPressMore(hiddenEvents(), day().date);
1355
+ else {
1356
+ moreTriggerRef.current = e.currentTarget;
1357
+ setMoreOpenFor((open) =>
1358
+ open === day().id ? null : day().id,
1359
+ );
1360
+ }
1361
+ }}
1362
+ {...slot(
1363
+ "more",
1364
+ moreButtonDefault(theme(), props.chipHeight),
1365
+ )}
1366
+ aria-label={`${labels().moreEvents(hiddenEvents().length)}, ${dayLabel()}`}
1367
+ aria-expanded={
1368
+ (props.onPressMore
1369
+ ? undefined
1370
+ : moreOpenFor() === day().id) == null
1371
+ ? undefined
1372
+ : (
1373
+ props.onPressMore
1374
+ ? undefined
1375
+ : moreOpenFor() === day().id
1376
+ )
1377
+ ? "true"
1378
+ : "false"
1379
+ }
1380
+ >
1381
+ {props.moreLabel.replace(
1382
+ "{moreCount}",
1383
+ String(hiddenEvents().length),
1384
+ )}
1385
+ </button>
1386
+ ) : null}
1387
+ {moreOpenFor() === day().id ? (
1388
+ <div
1389
+ ref={(el) => (morePopoverRef.current = el)}
1390
+ // A non-modal dialog: Tab stays inside and Escape closes,
1391
+ // but the page behind is not inert (outside clicks work),
1392
+ // so no aria-modal claim.
1393
+ role="dialog"
1394
+ aria-label={dayLabel()}
1395
+ onPointerDown={(e) => e.stopPropagation()}
1396
+ // Contain Tab inside the dialog; Escape (handled on the
1397
+ // document) closes it and restores focus to the trigger.
1398
+ onKeyDown={(e) => {
1399
+ if (e.key !== "Tab") return;
1400
+ const buttons =
1401
+ morePopoverRef.current?.querySelectorAll<HTMLElement>(
1402
+ "button",
1403
+ );
1404
+ if (!buttons?.length) return;
1405
+ const first = buttons[0];
1406
+ const last = buttons[buttons.length - 1];
1407
+ if (
1408
+ e.shiftKey &&
1409
+ document.activeElement === first
1410
+ ) {
1411
+ e.preventDefault();
1412
+ last.focus();
1413
+ } else if (
1414
+ !e.shiftKey &&
1415
+ document.activeElement === last
1416
+ ) {
1417
+ e.preventDefault();
1418
+ first.focus();
1419
+ }
1420
+ }}
1421
+ {...slot("morePopover", {
1422
+ base: {
1423
+ position: "absolute",
1424
+ top: 2,
1425
+ left: 2,
1426
+ right: 2,
1427
+ zIndex: 10,
1428
+ display: "flex",
1429
+ flexDirection: "column",
1430
+ gap: 2,
1431
+ maxHeight: 240,
1432
+ overflowY: "auto",
1433
+ },
1434
+ themed: {
1435
+ background: theme().surface,
1436
+ border: `1px solid ${theme().gridLine}`,
1437
+ borderRadius: 8,
1438
+ padding: 6,
1439
+ boxShadow: "0 4px 16px rgba(0,0,0,0.12)",
1440
+ },
1441
+ })}
1442
+ >
1443
+ <div
1444
+ style={css({
1445
+ fontSize: 11,
1446
+ fontWeight: 600,
1447
+ color: theme().textMuted,
1448
+ })}
1449
+ >
1450
+ {dayLabel()}
1451
+ </div>
1452
+ {
1453
+ <For each={dayEvents()} keyed={false}>
1454
+ {(event) => {
1455
+ return (
1456
+ <button
1457
+ type="button"
1458
+ onClick={() => {
1459
+ setMoreOpenFor(null);
1460
+ props.onPressEvent?.(event());
1461
+ }}
1462
+ style={css({
1463
+ display: "block",
1464
+ width: "100%",
1465
+ border: "none",
1466
+ background: "transparent",
1467
+ padding: 0,
1468
+ font: "inherit",
1469
+ textAlign: "left",
1470
+ cursor: "pointer",
1471
+ })}
1472
+ >
1473
+ {Chip() ? (
1474
+ <Dynamic
1475
+ component={Chip()}
1476
+ event={event()}
1477
+ onPress={() =>
1478
+ props.onPressEvent?.(event())
1479
+ }
1480
+ />
1481
+ ) : (
1482
+ <span
1483
+ {...slot(
1484
+ "chip",
1485
+ chipDefault(
1486
+ theme(),
1487
+ props.chipHeight,
1488
+ ),
1489
+ )}
1490
+ >
1491
+ {event().title}
1492
+ </span>
1493
+ )}
1494
+ </button>
1495
+ );
1496
+ }}
1497
+ </For>
1498
+ }
1499
+ </div>
1500
+ ) : null}
1501
+ </div>
1502
+ </div>
1503
+ );
1504
+ }
1505
+ return (
1506
+ <button
1507
+ type="button"
1508
+ role="gridcell"
1509
+ data-day={day().id}
1510
+ onFocusIn={(event) => {
1511
+ if (event.target === event.currentTarget)
1512
+ setFocusedDate(day().date);
1513
+ }}
1514
+ {...dayData()}
1515
+ tabindex={day().id === focusKey() ? 0 : -1}
1516
+ aria-disabled={
1517
+ (day().isDisabled || undefined) == null
1518
+ ? undefined
1519
+ : day().isDisabled || undefined
1520
+ ? "true"
1521
+ : "false"
1522
+ }
1523
+ aria-label={label()}
1524
+ aria-selected={
1525
+ day().isSelected || day().isInRange ? "true" : "false"
1526
+ }
1527
+ {...slot(
1528
+ "day",
1529
+ dayCellDefault(day(), theme(), props.highlightWeekends),
1530
+ )}
1531
+ onClick={
1532
+ day().isDisabled
1533
+ ? undefined
1534
+ : () => {
1535
+ props.onPressDay?.(day().date);
1536
+ props.onPressCell?.(startOfDay(day().date));
1537
+ }
1538
+ }
1539
+ onMouseEnter={
1540
+ day().isDisabled
1541
+ ? undefined
1542
+ : () => setHoveredKey(day().id)
1543
+ }
1544
+ onMouseLeave={() =>
1545
+ setHoveredKey((k) => (k === day().id ? null : k))
1546
+ }
1547
+ >
1548
+ {
1549
+ <Show when={band()}>
1550
+ {(band) => (
1551
+ <span
1552
+ data-band
1553
+ aria-hidden="true"
1554
+ {...slot("rangeBand", band())}
1555
+ />
1556
+ )}
1557
+ </Show>
1558
+ }
1559
+ <span
1560
+ {...dayData()}
1561
+ {...slot(
1562
+ "dayBadge",
1563
+ badgeDefault(day(), theme(), hoveredKey() === day().id),
1564
+ )}
1565
+ >
1566
+ {day().label}
1567
+ </span>
1568
+ </button>
1569
+ );
1570
+ })()}
1571
+ </>
1572
+ );
1573
+ }}
1574
+ </For>
1575
+ }
1576
+ </div>
1577
+ );
1578
+ })()}
1579
+ </>
1580
+ );
1581
+ }}
1582
+ </For>
1583
+ }
1584
+ </div>
1585
+ </div>
1586
+ );
1587
+ }