@super-calendar/dom 2.15.0 → 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,470 @@
1
+ import { type ReactElement, type RefObject, useEffect, useId, useRef, useState } from "react";
2
+ import { format } from "date-fns";
3
+ import type { ResolvedSlot, SlotDefault } from "./slots";
4
+ import type { DomCalendarTheme } from "./theme";
5
+
6
+ /** Styleable parts of the built-in move and resize actions. */
7
+ export type EventActionsSlot =
8
+ | "eventActionsTrigger"
9
+ | "eventActionsList"
10
+ | "eventActions"
11
+ | "eventAction";
12
+
13
+ /** One move or resize the actions dialog offers. */
14
+ export interface EventEditAction {
15
+ id: string;
16
+ label: string;
17
+ /** False when the change is refused before reaching `onDragEvent` (e.g. below one step). */
18
+ available: boolean;
19
+ }
20
+
21
+ function moveFocus(event: { key: string; preventDefault(): void }, container: HTMLElement | null) {
22
+ const buttons = [...(container?.querySelectorAll<HTMLElement>("button") ?? [])];
23
+ const index = buttons.indexOf(document.activeElement as HTMLElement);
24
+ const target =
25
+ event.key === "ArrowDown"
26
+ ? buttons[(index + 1) % buttons.length]
27
+ : event.key === "ArrowUp"
28
+ ? buttons[index < 0 ? buttons.length - 1 : (index - 1 + buttons.length) % buttons.length]
29
+ : event.key === "Home"
30
+ ? buttons[0]
31
+ : event.key === "End"
32
+ ? buttons[buttons.length - 1]
33
+ : undefined;
34
+ if (!target) return;
35
+ event.preventDefault();
36
+ target.focus();
37
+ }
38
+
39
+ type SlotFn = (name: EventActionsSlot, defaults?: SlotDefault) => ResolvedSlot;
40
+
41
+ export function describeEventDates(event: { start: Date; end: Date }): string {
42
+ const start = format(event.start, "yyyy-MM-dd");
43
+ const end = format(event.end, "yyyy-MM-dd");
44
+ return start === end ? start : `${start} - ${end}`;
45
+ }
46
+
47
+ /**
48
+ * Open/close state for one component's actions dialog. `commit` applies an
49
+ * action through the component's drag path and returns a matcher for the event
50
+ * the consumer will render in its place, or null when the change was refused.
51
+ * The dialog follows that replacement so repeated steps keep working, and
52
+ * closes when its event disappears or can no longer be edited.
53
+ */
54
+ export function useEventActions<E extends object>(
55
+ events: readonly E[],
56
+ actionsFor: (event: E) => EventEditAction[],
57
+ commit: (event: E, actionId: string) => ((candidate: E) => boolean) | null,
58
+ getEventId?: (event: E) => string | number,
59
+ ) {
60
+ const [openEvent, setOpenEvent] = useState<E | null>(null);
61
+ const [rejections, setRejections] = useState(0);
62
+ const identity = useRef<{ id: string | number } | null>(null);
63
+ // Read by handlers that can run before the next render (see `current`).
64
+ const openRef = useRef<E | null>(null);
65
+ const show = (event: E | null) => {
66
+ openRef.current = event;
67
+ setOpenEvent(event);
68
+ };
69
+ const triggers = useRef(new WeakMap<E, HTMLElement>());
70
+ const dialogRef = useRef<HTMLDialogElement | null>(null);
71
+ const rootRef = useRef<HTMLDivElement | null>(null);
72
+ const pending = useRef<{
73
+ from: E;
74
+ events: readonly E[];
75
+ matches: (candidate: E) => boolean;
76
+ } | null>(null);
77
+
78
+ // The open event as the consumer renders it now: itself, or the event that
79
+ // replaced it after an accepted change. Handlers can run after that update
80
+ // renders but before the dialog follows it, so they resolve it here too.
81
+ const current = (): E | undefined => {
82
+ const event = openRef.current;
83
+ if (!event) return undefined;
84
+ if (identity.current) {
85
+ if (!getEventId) return undefined;
86
+ const id = identity.current.id;
87
+ const matches = events.filter((candidate) => getEventId(candidate) === id);
88
+ return matches.length === 1 ? matches[0] : undefined;
89
+ }
90
+ if (getEventId) return undefined;
91
+ if (events.includes(event)) return event;
92
+ const committed = pending.current;
93
+ if (committed?.from !== event) return undefined;
94
+ // Without stable IDs, replacing other event objects makes identity ambiguous.
95
+ if (committed.events.some((previous) => previous !== event && !events.includes(previous)))
96
+ return undefined;
97
+ // A matching event that already existed is not the consumer's replacement.
98
+ const replacements = events.filter(
99
+ (candidate) => !committed.events.includes(candidate) && committed.matches(candidate),
100
+ );
101
+ return replacements.length === 1 ? replacements[0] : undefined;
102
+ };
103
+
104
+ const close = (restoreFocus: boolean, fallbackToRoot = false) => {
105
+ const event = openRef.current;
106
+ if (!event) return;
107
+ const shown = current() ?? event;
108
+ pending.current = null;
109
+ const dialog = dialogRef.current;
110
+ // Close before moving focus: the page behind a modal dialog is inert.
111
+ if (dialog?.open) {
112
+ if (typeof dialog.close === "function") dialog.close();
113
+ else dialog.removeAttribute("open");
114
+ }
115
+ if (restoreFocus) {
116
+ // Back to the button that opened the dialog, or, when its event is gone
117
+ // (moved off the page, removed), to the first control in the calendar.
118
+ const trigger = triggers.current.get(shown);
119
+ (fallbackToRoot
120
+ ? rootRef.current
121
+ : trigger?.isConnected
122
+ ? trigger
123
+ : ([
124
+ ...(rootRef.current?.querySelectorAll<HTMLElement>(
125
+ 'button:not(:disabled), [tabindex="0"]',
126
+ ) ?? []),
127
+ ].find((element) => !dialog?.contains(element)) ?? rootRef.current)
128
+ )?.focus();
129
+ }
130
+ show(null);
131
+ };
132
+
133
+ useEffect(() => {
134
+ if (!openRef.current) return;
135
+ const next = current();
136
+ // Once the events change after a commit, that change has settled.
137
+ if (pending.current && pending.current.events !== events) pending.current = null;
138
+ if (next && actionsFor(next).length > 0) {
139
+ if (next !== openEvent) show(next);
140
+ return;
141
+ }
142
+ close(
143
+ document.activeElement === document.body ||
144
+ !!dialogRef.current?.contains(document.activeElement),
145
+ true,
146
+ );
147
+ });
148
+
149
+ const run = (actionId: string) => {
150
+ const event = current();
151
+ if (!event) return;
152
+ openRef.current = event;
153
+ pending.current = null;
154
+ const matches = commit(event, actionId);
155
+ setRejections((count) => (matches ? 0 : count + 1));
156
+ if (matches) pending.current = { from: event, events, matches };
157
+ };
158
+
159
+ const select = (event: E, trigger: HTMLElement) => {
160
+ const id = getEventId?.(event);
161
+ identity.current = typeof id === "string" || typeof id === "number" ? { id } : null;
162
+ setRejections(0);
163
+ triggers.current.set(event, trigger);
164
+ show(event);
165
+ };
166
+
167
+ return { openEvent, close, run, select, dialogRef, rootRef, rejections };
168
+ }
169
+
170
+ export function EventActionsMenu<E extends object>({
171
+ events,
172
+ label,
173
+ labelFor,
174
+ descriptionFor,
175
+ onSelect,
176
+ rootRef,
177
+ slot,
178
+ theme,
179
+ }: {
180
+ events: readonly E[];
181
+ label: string;
182
+ labelFor: (event: E) => string;
183
+ descriptionFor: (event: E) => string;
184
+ onSelect: (event: E, trigger: HTMLElement) => void;
185
+ rootRef: RefObject<HTMLElement | null>;
186
+ slot: SlotFn;
187
+ theme: DomCalendarTheme;
188
+ }): ReactElement | null {
189
+ const [expanded, setExpanded] = useState(false);
190
+ const trigger = useRef<HTMLButtonElement>(null);
191
+ const listRef = useRef<HTMLDivElement>(null);
192
+ useEffect(() => {
193
+ if (expanded) listRef.current?.querySelector<HTMLElement>("button")?.focus();
194
+ }, [expanded]);
195
+ const id = useId();
196
+ const focused = useRef<HTMLElement | null>(null);
197
+ const keys = useRef(new WeakMap<E, number>());
198
+ const nextKey = useRef(0);
199
+ const keyFor = (event: E) => {
200
+ let key = keys.current.get(event);
201
+ if (key === undefined) {
202
+ key = nextKey.current++;
203
+ keys.current.set(event, key);
204
+ }
205
+ return key;
206
+ };
207
+ useEffect(() => {
208
+ const previous = focused.current;
209
+ if (!previous || document.activeElement !== document.body) return;
210
+ (previous.isConnected ? previous : (trigger.current ?? rootRef.current))?.focus();
211
+ });
212
+ if (!events.length) return null;
213
+ return (
214
+ <div
215
+ onFocusCapture={(e) => {
216
+ focused.current = e.target as HTMLElement;
217
+ }}
218
+ onBlurCapture={(e) => {
219
+ if (e.relatedTarget && !e.currentTarget.contains(e.relatedTarget as Node))
220
+ focused.current = null;
221
+ }}
222
+ onKeyDown={(e) => {
223
+ if (!expanded) return;
224
+ if (e.key !== "Escape") {
225
+ moveFocus(e, listRef.current);
226
+ return;
227
+ }
228
+ e.preventDefault();
229
+ e.stopPropagation();
230
+ setExpanded(false);
231
+ trigger.current?.focus();
232
+ }}
233
+ >
234
+ <button
235
+ ref={trigger}
236
+ id={id}
237
+ type="button"
238
+ aria-expanded={expanded}
239
+ aria-controls={expanded ? id + "-list" : undefined}
240
+ onClick={() => setExpanded(!expanded)}
241
+ {...slot("eventActionsTrigger", {
242
+ base: { minHeight: 32, font: "inherit", cursor: "pointer" },
243
+ themed: {
244
+ margin: "4px 0",
245
+ padding: "4px 10px",
246
+ border: `1px solid ${theme.gridLine}`,
247
+ borderRadius: 6,
248
+ background: theme.surface,
249
+ color: theme.text,
250
+ },
251
+ })}
252
+ >
253
+ {label}
254
+ </button>
255
+ {expanded ? (
256
+ <div
257
+ ref={listRef}
258
+ id={id + "-list"}
259
+ role="group"
260
+ aria-labelledby={id}
261
+ {...slot("eventActionsList", {
262
+ base: {
263
+ display: "flex",
264
+ flexDirection: "column",
265
+ gap: 4,
266
+ maxHeight: "min(20rem, 50vh)",
267
+ overflowY: "auto",
268
+ },
269
+ themed: {
270
+ padding: 4,
271
+ background: theme.surface,
272
+ border: `1px solid ${theme.gridLine}`,
273
+ borderRadius: 6,
274
+ },
275
+ })}
276
+ >
277
+ {events.map((event, index) => (
278
+ <button
279
+ key={keyFor(event)}
280
+ type="button"
281
+ aria-haspopup="dialog"
282
+ aria-label={labelFor(event)}
283
+ aria-describedby={id + "-" + index}
284
+ onClick={() => {
285
+ setExpanded(false);
286
+ focused.current = null;
287
+ onSelect(event, trigger.current!);
288
+ }}
289
+ {...slot("eventAction", {
290
+ base: {
291
+ minHeight: 32,
292
+ flexShrink: 0,
293
+ overflowWrap: "anywhere",
294
+ font: "inherit",
295
+ cursor: "pointer",
296
+ textAlign: "left",
297
+ },
298
+ themed: {
299
+ padding: "6px 10px",
300
+ border: `1px solid ${theme.gridLine}`,
301
+ borderRadius: 6,
302
+ background: theme.surface,
303
+ color: theme.text,
304
+ },
305
+ })}
306
+ >
307
+ <span>{labelFor(event)}</span>
308
+ <small id={id + "-" + index} style={{ display: "block" }}>
309
+ {descriptionFor(event)}
310
+ </small>
311
+ </button>
312
+ ))}
313
+ </div>
314
+ ) : null}
315
+ </div>
316
+ );
317
+ }
318
+
319
+ /** The modal dialog listing an event's move and resize actions. */
320
+ export function EventActionsDialog({
321
+ dialogRef,
322
+ title,
323
+ description,
324
+ actions,
325
+ closeLabel,
326
+ rejectedLabel,
327
+ rejections,
328
+ onAction,
329
+ onClose,
330
+ slot,
331
+ theme,
332
+ }: {
333
+ dialogRef: RefObject<HTMLDialogElement | null>;
334
+ title: string;
335
+ description: string;
336
+ actions: EventEditAction[];
337
+ closeLabel: string;
338
+ rejectedLabel: string;
339
+ rejections: number;
340
+ onAction: (actionId: string) => void;
341
+ onClose: () => void;
342
+ slot: SlotFn;
343
+ theme: DomCalendarTheme;
344
+ }): ReactElement {
345
+ const titleId = useId();
346
+ const descriptionId = useId();
347
+
348
+ useEffect(() => {
349
+ const dialog = dialogRef.current;
350
+ if (!dialog || dialog.open) return;
351
+ // jsdom has no showModal; the open attribute shows it there.
352
+ if (typeof dialog.showModal === "function") dialog.showModal();
353
+ else dialog.setAttribute("open", "");
354
+ }, [dialogRef]);
355
+
356
+ // Keep focus inside: land on the first action when opening, and again if the
357
+ // focused action goes away when the dialog follows a moved event.
358
+ useEffect(() => {
359
+ const dialog = dialogRef.current;
360
+ if (dialog && !dialog.contains(document.activeElement))
361
+ dialog.querySelector<HTMLElement>("button")?.focus();
362
+ });
363
+
364
+ const buttonSlot = (available: boolean) =>
365
+ slot("eventAction", {
366
+ base: {
367
+ display: "block",
368
+ width: "100%",
369
+ minHeight: 32,
370
+ boxSizing: "border-box",
371
+ textAlign: "left",
372
+ font: "inherit",
373
+ cursor: available ? "pointer" : "default",
374
+ },
375
+ themed: {
376
+ padding: "6px 10px",
377
+ border: `1px solid ${theme.gridLine}`,
378
+ borderRadius: 8,
379
+ background: theme.surface,
380
+ color: theme.text,
381
+ fontSize: 13,
382
+ opacity: available ? 1 : 0.5,
383
+ },
384
+ });
385
+
386
+ return (
387
+ <dialog
388
+ ref={dialogRef}
389
+ aria-labelledby={titleId}
390
+ aria-describedby={descriptionId}
391
+ // Other close requests (e.g. a platform back gesture) close it natively;
392
+ // sync the state and restore focus.
393
+ onClose={() => onClose()}
394
+ onCancel={(e) => {
395
+ e.preventDefault();
396
+ onClose();
397
+ }}
398
+ // A click on the backdrop targets the dialog itself (the content fills it).
399
+ onClick={(e) => {
400
+ if (e.target === e.currentTarget) onClose();
401
+ }}
402
+ // Arrow keys step through the actions, alongside Tab (which some
403
+ // platforms limit to form fields and links).
404
+ onKeyDown={(e) => {
405
+ if (e.key === "PageUp" || e.key === "PageDown") e.stopPropagation();
406
+ if (e.key === "Escape") {
407
+ e.preventDefault();
408
+ e.stopPropagation();
409
+ onClose();
410
+ return;
411
+ }
412
+ moveFocus(e, e.currentTarget);
413
+ }}
414
+ {...slot("eventActions", {
415
+ base: {
416
+ margin: "auto",
417
+ overflowWrap: "anywhere",
418
+ padding: 0,
419
+ width: "max-content",
420
+ maxWidth: "min(22rem, calc(100vw - 32px))",
421
+ maxHeight: "calc(100vh - 32px)",
422
+ overflowY: "auto",
423
+ boxSizing: "border-box",
424
+ },
425
+ themed: {
426
+ fontFamily: theme.fontFamily,
427
+ background: theme.surface,
428
+ color: theme.text,
429
+ border: `1px solid ${theme.gridLine}`,
430
+ borderRadius: 12,
431
+ boxShadow: "0 8px 24px rgba(0,0,0,0.18)",
432
+ },
433
+ })}
434
+ >
435
+ <div style={{ display: "flex", flexDirection: "column", gap: 6, padding: 12 }}>
436
+ <p id={titleId} style={{ margin: 0, fontWeight: 600, fontSize: 14 }}>
437
+ {title}
438
+ </p>
439
+ {/* Announces the event's new time after an accepted change. */}
440
+ <p
441
+ id={descriptionId}
442
+ aria-live="polite"
443
+ style={{ margin: "0 0 4px", fontSize: 12, color: theme.textMuted }}
444
+ >
445
+ {description}
446
+ </p>
447
+ {actions.map((action) => (
448
+ <button
449
+ key={action.id}
450
+ type="button"
451
+ data-action={action.id}
452
+ aria-disabled={action.available ? undefined : true}
453
+ onClick={() => {
454
+ if (action.available) onAction(action.id);
455
+ }}
456
+ {...buttonSlot(action.available)}
457
+ >
458
+ {action.label}
459
+ </button>
460
+ ))}
461
+ <div role="status" aria-atomic="true" style={{ fontSize: 13 }}>
462
+ {rejections > 0 ? <span key={rejections}>{rejectedLabel}</span> : null}
463
+ </div>
464
+ <button type="button" data-action="close" onClick={() => onClose()} {...buttonSlot(true)}>
465
+ {closeLabel}
466
+ </button>
467
+ </div>
468
+ </dialog>
469
+ );
470
+ }
@@ -0,0 +1,7 @@
1
+ import { createElement, type HTMLAttributes } from "react";
2
+
3
+ export function InertDiv(props: HTMLAttributes<HTMLDivElement>) {
4
+ // React 18 needs a string; React 19 needs a nonempty value. The canonical
5
+ // attribute value works in both and applies before children can take focus.
6
+ return createElement("div", { ...props, inert: props.inert ? "inert" : undefined });
7
+ }
package/src/MonthList.tsx CHANGED
@@ -1,6 +1,6 @@
1
1
  import { LegendList } from "@legendapp/list/react";
2
2
  import { addMonths, type Locale, startOfMonth } from "date-fns";
3
- import { type CSSProperties, type ReactElement, useMemo } from "react";
3
+ import { type CSSProperties, type ReactElement, useCallback, useMemo } from "react";
4
4
  import {
5
5
  buildMonthGrid,
6
6
  type CalendarEvent,
@@ -154,10 +154,66 @@ export function MonthList<T = unknown>({
154
154
  return map;
155
155
  }, [events]);
156
156
 
157
- // Cached rows refresh when selection, events, or chip dimensions change.
158
- const extraData = useMemo(
159
- () => [selectedRange, selectedDates, events, chipHeight, chipGap] as const,
160
- [selectedRange, selectedDates, events, chipHeight, chipGap],
157
+ const renderMonth = useCallback(
158
+ ({ item }: { item: Date }) => (
159
+ <MonthView<T>
160
+ date={item}
161
+ weekStartsOn={weekStartsOn}
162
+ highlightWeekends={highlightWeekends}
163
+ events={events}
164
+ eventsByDay={eventsByDay}
165
+ renderEvent={renderEvent}
166
+ eventAccessibilityLabel={eventAccessibilityLabel}
167
+ maxVisibleEventCount={maxVisibleEventCount}
168
+ chipHeight={chipHeight}
169
+ chipGap={chipGap}
170
+ moreLabel={moreLabel}
171
+ labels={labels}
172
+ onPressEvent={onPressEvent}
173
+ onPressMore={onPressMore}
174
+ selectedRange={selectedRange}
175
+ selectedDates={selectedDates}
176
+ fillCellOnSelection={fillCellOnSelection}
177
+ showAdjacentMonths={false}
178
+ showWeekdays={false}
179
+ locale={locale}
180
+ theme={themeOverrides}
181
+ minDate={minDate}
182
+ maxDate={maxDate}
183
+ isDateDisabled={isDateDisabled}
184
+ keyboardDayNavigation={keyboardDayNavigation}
185
+ onPressDay={onPressDay}
186
+ classNames={classNames}
187
+ styles={styles}
188
+ />
189
+ ),
190
+ [
191
+ weekStartsOn,
192
+ highlightWeekends,
193
+ events,
194
+ eventsByDay,
195
+ renderEvent,
196
+ eventAccessibilityLabel,
197
+ maxVisibleEventCount,
198
+ chipHeight,
199
+ chipGap,
200
+ moreLabel,
201
+ labels,
202
+ onPressEvent,
203
+ onPressMore,
204
+ selectedRange,
205
+ selectedDates,
206
+ fillCellOnSelection,
207
+ locale,
208
+ themeOverrides,
209
+ minDate,
210
+ maxDate,
211
+ isDateDisabled,
212
+ keyboardDayNavigation,
213
+ onPressDay,
214
+ classNames,
215
+ styles,
216
+ ],
161
217
  );
162
218
 
163
219
  return (
@@ -189,7 +245,8 @@ export function MonthList<T = unknown>({
189
245
  </div>
190
246
  <LegendList
191
247
  data={months}
192
- extraData={extraData}
248
+ // Legend List caches rows independently of renderItem's identity.
249
+ extraData={renderMonth}
193
250
  keyExtractor={(m: Date) => m.toISOString()}
194
251
  recycleItems={false}
195
252
  estimatedItemSize={theme.cellHeight * 7 + 40}
@@ -197,38 +254,7 @@ export function MonthList<T = unknown>({
197
254
  // `months` starts `pastMonths` before the anchor, so it sits at that index.
198
255
  initialScrollIndex={pastMonths}
199
256
  style={{ height, overflowY: "auto" }}
200
- renderItem={({ item }: { item: Date }) => (
201
- <MonthView<T>
202
- date={item}
203
- weekStartsOn={weekStartsOn}
204
- highlightWeekends={highlightWeekends}
205
- events={events}
206
- eventsByDay={eventsByDay}
207
- renderEvent={renderEvent}
208
- eventAccessibilityLabel={eventAccessibilityLabel}
209
- maxVisibleEventCount={maxVisibleEventCount}
210
- chipHeight={chipHeight}
211
- chipGap={chipGap}
212
- moreLabel={moreLabel}
213
- labels={labels}
214
- onPressEvent={onPressEvent}
215
- onPressMore={onPressMore}
216
- selectedRange={selectedRange}
217
- selectedDates={selectedDates}
218
- fillCellOnSelection={fillCellOnSelection}
219
- showAdjacentMonths={false}
220
- showWeekdays={false}
221
- locale={locale}
222
- theme={themeOverrides}
223
- minDate={minDate}
224
- maxDate={maxDate}
225
- isDateDisabled={isDateDisabled}
226
- keyboardDayNavigation={keyboardDayNavigation}
227
- onPressDay={onPressDay}
228
- classNames={classNames}
229
- styles={styles}
230
- />
231
- )}
257
+ renderItem={renderMonth}
232
258
  />
233
259
  </div>
234
260
  );