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