@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,1748 @@
1
+ import { Dynamic, type JSX } from "@solidjs/web";
2
+ import {
3
+ backgroundBandsForDay,
4
+ type BusinessHoursBand,
5
+ type BusinessHoursValue,
6
+ type CalendarEvent,
7
+ type CalendarLabels,
8
+ type CreateGhostArgs,
9
+ cellRangeFromDrag,
10
+ eventAccessibilityLabel,
11
+ closedHourBands,
12
+ eventTimeLabel,
13
+ formatHour,
14
+ isSameCalendarDay,
15
+ layoutDayEvents,
16
+ isAllDayEvent,
17
+ isBackgroundEvent,
18
+ movedClockSpan,
19
+ type PositionedEvent,
20
+ resolveCalendarLabels,
21
+ resolveDraggedBounds,
22
+ } from "@super-calendar/core/vanilla";
23
+ import {
24
+ type Component,
25
+ createEffect,
26
+ createMemo,
27
+ createSignal,
28
+ For,
29
+ onCleanup,
30
+ Show,
31
+ untrack,
32
+ } from "solid-js";
33
+ import {
34
+ createEventActions,
35
+ EventActionsDialog,
36
+ describeEventDates,
37
+ type EventActionsSlot,
38
+ EventActionsMenu,
39
+ type EventEditAction,
40
+ } from "./EventActions";
41
+ import { withDefaults } from "./props";
42
+ import { createSlots, dataState, type ResolvedSlot, type SlotStyleProps } from "./slots";
43
+ import { createNow } from "./state";
44
+ import { css, type CSSProperties, type DomPointerEvent, type ElementRef } from "./styles";
45
+ import { mergeSolidTheme, type SolidCalendarTheme } from "./theme";
46
+
47
+ /**
48
+ * Styleable parts of {@link ResourceTimeline}. Pass a class or inline style per
49
+ * slot via the `classNames` / `styles` props.
50
+ */
51
+ export type ResourceTimelineSlot =
52
+ | "header"
53
+ | "corner"
54
+ | "timeAxis"
55
+ | "hourTick"
56
+ | "resourceLabel"
57
+ | "row"
58
+ | "track"
59
+ | "gridLines"
60
+ | "businessHours"
61
+ | "backgroundEvent"
62
+ | "event"
63
+ | "eventBox"
64
+ | "nowIndicator"
65
+ | "createGhost"
66
+ | EventActionsSlot;
67
+
68
+ /** A schedulable lane (room, person, machine) that events are grouped under. */
69
+ export interface Resource {
70
+ /** Stable id events reference via their `resourceId`. */
71
+ id: string;
72
+ /** Row label; falls back to the id. */
73
+ title?: string;
74
+ }
75
+
76
+ /** Props passed to a custom resource-timeline event renderer. */
77
+ export interface ResourceEventArgs<T = unknown> {
78
+ event: CalendarEvent<T>;
79
+ /**
80
+ * Pixel width of the event bar. In the vertical orientation the columns flex
81
+ * to the container, so this is 0 there; size against `height` instead.
82
+ */
83
+ width: number;
84
+ /** Pixel height of the event bar; set in the vertical orientation. */
85
+ height?: number;
86
+ onPress: () => void;
87
+ }
88
+
89
+ /** Props for {@link ResourceTimeline}. */
90
+ export interface ResourceTimelineProps<T = unknown> extends SlotStyleProps<ResourceTimelineSlot> {
91
+ /** The day to lay out along the time axis. */
92
+ date: Date;
93
+ /**
94
+ * Lay the day out along the horizontal axis with resources as rows (the
95
+ * default), or down the vertical axis with resources as columns, like the
96
+ * time grid. Vertical reads better on narrow screens: the columns share the
97
+ * width instead of the axis scrolling sideways.
98
+ */
99
+ orientation?: "horizontal" | "vertical";
100
+ /** The resource lanes: rows when horizontal, columns when vertical. */
101
+ resources: Resource[];
102
+ /**
103
+ * Cap the number of lanes shown at once; the rest sit on further pages. Pair
104
+ * with `resourcePage` and your own prev/next controls to page through them
105
+ * (like `date` drives the time axis). Omit to show every lane, sharing the
106
+ * available space.
107
+ */
108
+ resourcesPerPage?: number;
109
+ /**
110
+ * The 0-based page of lanes to show when `resourcesPerPage` is set (default
111
+ * 0, clamped to the last page). Controlled: update it from your own paging
112
+ * controls.
113
+ */
114
+ resourcePage?: number;
115
+ /** Events; each is placed in the row named by `resourceId(event)`. */
116
+ events: CalendarEvent<T>[];
117
+ /** Read an event's resource id. Default: `event.resourceId`. */
118
+ resourceId?: (event: CalendarEvent<T>) => string | undefined;
119
+ /** First hour shown (default 0). */
120
+ startHour?: number;
121
+ /** Last hour shown, exclusive (default 24). */
122
+ endHour?: number;
123
+ /** Pixels per hour along the horizontal axis (default 80). Horizontal only. */
124
+ hourWidth?: number;
125
+ /** Pixels per hour down the vertical axis (default 48). Vertical only. */
126
+ hourHeight?: number;
127
+ /** Height of each resource row in px (default 56). Horizontal only. */
128
+ rowHeight?: number;
129
+ /** Width of the left resource-label column in px (default 140). Horizontal only. */
130
+ labelWidth?: number;
131
+ /** 12-hour AM/PM axis labels (default false). */
132
+ ampm?: boolean;
133
+ /** Theme overrides; falls back to the default light theme. */
134
+ theme?: Partial<SolidCalendarTheme>;
135
+ /** Custom event renderer; falls back to the built-in bar. */
136
+ renderEvent?: Component<ResourceEventArgs<T>>;
137
+ /** Tap an event. */
138
+ onPressEvent?: (event: CalendarEvent<T>) => void;
139
+ /**
140
+ * Enables drag-to-move and edge-resize along the time axis; called with the
141
+ * proposed new start/end. Return `false` to reject the drop (it snaps back).
142
+ */
143
+ onDragEvent?: (
144
+ event: CalendarEvent<T>,
145
+ start: Date,
146
+ end: Date,
147
+ resource: Resource,
148
+ ) => void | boolean;
149
+ /** Stable, unique event identity for the web editing dialog across data refreshes. */
150
+ getEventId?: (event: CalendarEvent<T>) => string | number;
151
+ /** Tap empty lane space; called with the snapped time and the lane's resource. */
152
+ onPressCell?: (at: Date, resource: Resource) => void;
153
+ /** Drag empty lane space to create; called with the swept start/end and the lane's resource. */
154
+ onCreateEvent?: (start: Date, end: Date, resource: Resource) => void;
155
+ /**
156
+ * A component that draws content inside the drag-to-create preview, such as a
157
+ * draft title and the live time range. It receives the snapped `start` and
158
+ * `end` that `onCreateEvent` would get if the pointer were released now, plus
159
+ * the lane's resource, and its props update as the sweep changes them. The
160
+ * board keeps positioning, sizing and styling the preview and clips the
161
+ * content to it; the content is non-interactive and hidden from assistive
162
+ * tech. Renders only while a sweep can create, so it needs `onCreateEvent` and
163
+ * does not enable creation itself. Applies to both orientations.
164
+ */
165
+ renderCreateGhost?: Component<CreateGhostArgs & { resource: Resource }>;
166
+ /**
167
+ * Shade the hours outside this window, per lane. Same shape as the Calendar's
168
+ * `businessHours` plus the lane's resource, so per-resource opening hours work
169
+ * (return `null` for a fully closed lane). A date-only function is accepted.
170
+ */
171
+ businessHours?: (date: Date, resource: Resource) => BusinessHoursValue;
172
+ /**
173
+ * Render a closed-hours band's content yourself (a label, icon, pattern). The
174
+ * board keeps positioning the band; when set, the themed tint is dropped and
175
+ * your output fills the band instead. Receives the lane's resource. Decorative only: the
176
+ * band stays non-interactive and hidden from assistive tech.
177
+ */
178
+ renderBusinessHours?: (
179
+ band: BusinessHoursBand & {
180
+ resource: Resource;
181
+ },
182
+ ) => JSX.Element;
183
+ /**
184
+ * Render each resource's header cell yourself (an avatar, a subtitle, a status
185
+ * dot). Receives the resource and its index; return the cell's content. The board
186
+ * keeps the header cell's sizing so columns stay aligned, so this replaces only
187
+ * the label content. Falls back to the resource title (or id). Applies to both
188
+ * orientations: the top header cells when vertical, the row labels when horizontal.
189
+ */
190
+ renderResourceHeader?: (resource: Resource, index: number) => JSX.Element;
191
+ /** Snap dragged events to this many minutes (default 15). */
192
+ dragStepMinutes?: number;
193
+ /**
194
+ * Words for the move and resize actions and the event labels. Keys you omit
195
+ * stay in English (`defaultCalendarLabels`).
196
+ */
197
+ labels?: Partial<CalendarLabels>;
198
+ /** Show the current-time line when `date` is today (default true). */
199
+ showNowIndicator?: boolean;
200
+ /** Fixed "now" instant for the indicator (doesn't tick). Defaults to the device clock. */
201
+ now?: Date;
202
+ /** Shift the now indicator into this IANA zone (pair with `eventsInTimeZone`). */
203
+ timeZone?: string;
204
+ /** Class applied to the root element. */
205
+ className?: string;
206
+ /** Inline styles applied to the root element. */
207
+ style?: CSSProperties;
208
+ }
209
+ const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
210
+ // Two create-preview ranges cover the same times.
211
+ const sameRange = (a: CreateGhostArgs | null, b: CreateGhostArgs | null) =>
212
+ a === b ||
213
+ (!!a && !!b && a.start.getTime() === b.start.getTime() && a.end.getTime() === b.end.getTime());
214
+
215
+ // Hour-gutter width in the vertical orientation, matching the time grid's axis.
216
+ const GUTTER_WIDTH = 56;
217
+ type DragState<T> = {
218
+ pointerId: number;
219
+ event: CalendarEvent<T>;
220
+ /** The lane the drag started in, so its row can be lifted while dragging. */
221
+ resource: Resource;
222
+ kind: "move" | "resize";
223
+ startHours: number;
224
+ durationHours: number;
225
+ /** Live cross-axis offset (px) of a move, for the follow-the-pointer ghost. */
226
+ crossPx: number;
227
+ moved: boolean;
228
+ };
229
+ function DefaultBar<T>(
230
+ props: ResourceEventArgs<T> & {
231
+ boxProps: ResolvedSlot;
232
+ theme: SolidCalendarTheme;
233
+ },
234
+ ) {
235
+ // Vertical bars gate the time line on their height (short slots show just the
236
+ // title); horizontal bars keep it always, as before.
237
+ const showTime = createMemo(() => (props.height != null ? props.height > 34 : true));
238
+ const time = createMemo(() =>
239
+ eventTimeLabel({
240
+ mode: "day",
241
+ isAllDay: false,
242
+ start: props.event.start,
243
+ end: props.event.end,
244
+ ampm: false,
245
+ showTime: true,
246
+ }),
247
+ );
248
+ const base = createMemo<CSSProperties>(() => ({
249
+ height: "100%",
250
+ boxSizing: "border-box",
251
+ overflow: "hidden",
252
+ }));
253
+ const themed = createMemo<CSSProperties>(() => ({
254
+ padding: "2px 6px",
255
+ borderRadius: 6,
256
+ background: props.theme.eventBackground,
257
+ color: props.theme.eventText,
258
+ fontSize: 12,
259
+ }));
260
+ return (
261
+ <div
262
+ class={props.boxProps.class}
263
+ data-slot={props.boxProps["data-slot"]}
264
+ style={css(
265
+ props.boxProps.class
266
+ ? {
267
+ ...base(),
268
+ ...props.boxProps.style,
269
+ }
270
+ : {
271
+ ...base(),
272
+ ...themed(),
273
+ ...props.boxProps.style,
274
+ },
275
+ )}
276
+ >
277
+ <div
278
+ style={css({
279
+ fontWeight: 600,
280
+ whiteSpace: "nowrap",
281
+ overflow: "hidden",
282
+ textOverflow: "ellipsis",
283
+ })}
284
+ >
285
+ {props.event.title}
286
+ </div>
287
+ {time() && showTime() ? (
288
+ <div
289
+ style={css({
290
+ opacity: 0.75,
291
+ fontSize: 11,
292
+ })}
293
+ >
294
+ {time()}
295
+ </div>
296
+ ) : null}
297
+ </div>
298
+ );
299
+ }
300
+
301
+ /**
302
+ * A horizontal resource timeline: rows are resources (rooms, people, machines)
303
+ * and the x-axis is one day's hours. Events sit in their resource's row, and
304
+ * overlapping events in the same row stack into sub-lanes (via the shared
305
+ * `layoutDayEvents`). Pass `onDragEvent` to enable drag-to-move and edge-resize
306
+ * along the axis.
307
+ *
308
+ * @example
309
+ * ```tsx
310
+ * <ResourceTimeline
311
+ * date={new Date()}
312
+ * resources={[{ id: "a", title: "Room A" }, { id: "b", title: "Room B" }]}
313
+ * events={events} // each event carries a `resourceId`
314
+ * />
315
+ * ```
316
+ */
317
+ export function ResourceTimeline<T = unknown>(incoming: ResourceTimelineProps<T>): JSX.Element {
318
+ const props = withDefaults(
319
+ {
320
+ orientation: "horizontal",
321
+ resourcePage: 0,
322
+ resourceId: (event) =>
323
+ (
324
+ event as {
325
+ resourceId?: string;
326
+ }
327
+ ).resourceId,
328
+ startHour: 0,
329
+ endHour: 24,
330
+ hourWidth: 80,
331
+ hourHeight: 48,
332
+ rowHeight: 56,
333
+ labelWidth: 140,
334
+ ampm: false,
335
+ dragStepMinutes: 15,
336
+ showNowIndicator: true,
337
+ } satisfies Partial<ResourceTimelineProps<T>>,
338
+ incoming,
339
+ );
340
+ // Window the lanes to the requested page when resourcesPerPage caps them.
341
+ const resources = createMemo(() => {
342
+ if (!props.resourcesPerPage || props.resourcesPerPage <= 0) return props.resources;
343
+ const pages = Math.max(1, Math.ceil(props.resources.length / props.resourcesPerPage));
344
+ const page = Math.min(Math.max(props.resourcePage, 0), pages - 1);
345
+ return props.resources.slice(
346
+ page * props.resourcesPerPage,
347
+ (page + 1) * props.resourcesPerPage,
348
+ );
349
+ });
350
+ const theme = createMemo(() => mergeSolidTheme(props.theme));
351
+ const slot = createSlots<ResourceTimelineSlot>(props);
352
+ const labels = createMemo(() => resolveCalendarLabels(props.labels));
353
+ const Renderer = createMemo(() => props.renderEvent);
354
+ const snapHours = createMemo(() => props.dragStepMinutes / 60);
355
+ const vertical = createMemo(() => props.orientation === "vertical");
356
+ // Pixels per hour along whichever axis carries the time.
357
+ const hourSize = createMemo(() => (vertical() ? props.hourHeight : props.hourWidth));
358
+ // The current-time line, shown only when the board's day is the zone's today.
359
+ const now = createNow(() => ({
360
+ enabled: props.showNowIndicator,
361
+ now: props.now,
362
+ timeZone: props.timeZone,
363
+ }));
364
+ const nowHours = createMemo(() => now().getHours() + now().getMinutes() / 60);
365
+ const showNow = createMemo(
366
+ () =>
367
+ props.showNowIndicator &&
368
+ isSameCalendarDay(now(), props.date) &&
369
+ nowHours() >= props.startHour &&
370
+ nowHours() <= props.endHour,
371
+ );
372
+ const nowLine = (_resourceKey: string) =>
373
+ showNow() ? (
374
+ <div
375
+ aria-hidden="true"
376
+ {...slot("nowIndicator", {
377
+ base: vertical()
378
+ ? {
379
+ position: "absolute",
380
+ left: 0,
381
+ right: 0,
382
+ top: (nowHours() - props.startHour) * hourSize(),
383
+ height: 2,
384
+ pointerEvents: "none",
385
+ zIndex: 2,
386
+ }
387
+ : {
388
+ position: "absolute",
389
+ top: 0,
390
+ bottom: 0,
391
+ left: (nowHours() - props.startHour) * hourSize(),
392
+ width: 2,
393
+ pointerEvents: "none",
394
+ zIndex: 2,
395
+ },
396
+ themed: {
397
+ background: theme().nowIndicator,
398
+ },
399
+ })}
400
+ />
401
+ ) : null;
402
+
403
+ // `drag` drives the visual; `dragRef` is the source of truth the pointer
404
+ // handlers read so they never see a stale closure between events.
405
+ const [drag, setDrag] = createSignal<DragState<T> | null>(null);
406
+ let handledClick: HTMLButtonElement | null = null;
407
+ const dragRef: ElementRef<DragState<T> | null> = {
408
+ current: null,
409
+ };
410
+ const origin: ElementRef<{
411
+ element: HTMLButtonElement;
412
+ x: number;
413
+ cross: number;
414
+ startHours: number;
415
+ durationHours: number;
416
+ // The event's own bounds, for previewing a move across a DST change; null
417
+ // for a bar clipped to the day.
418
+ span: {
419
+ start: Date;
420
+ end: Date;
421
+ } | null;
422
+ } | null> = {
423
+ current: null,
424
+ };
425
+ const applyDrag = (next: DragState<T> | null) => {
426
+ dragRef.current = next;
427
+ setDrag(next);
428
+ };
429
+ const clearDrag = () => {
430
+ const previous = dragRef.current;
431
+ const element = origin.current?.element;
432
+ applyDrag(null);
433
+ origin.current = null;
434
+ try {
435
+ if (previous) element?.releasePointerCapture?.(previous.pointerId);
436
+ } catch {
437
+ // The browser may have already released capture.
438
+ }
439
+ };
440
+ const beginDrag = (
441
+ e: DomPointerEvent,
442
+ resource: Resource,
443
+ kind: "move" | "resize",
444
+ pe: PositionedEvent<T>,
445
+ ) => {
446
+ const { startHours, durationHours } = pe;
447
+ if (e.button === 0 && e.isPrimary !== false && !dragRef.current) handledClick = null;
448
+ if (
449
+ !props.onDragEvent ||
450
+ pe.event.draggable === false ||
451
+ dragRef.current ||
452
+ createOrigin.current ||
453
+ e.isPrimary === false ||
454
+ e.button !== 0
455
+ )
456
+ return;
457
+ const element = e.currentTarget.closest("button");
458
+ if (!element) return;
459
+ e.stopPropagation();
460
+ try {
461
+ element.setPointerCapture?.(e.pointerId);
462
+ } catch {
463
+ // Pointer capture is best-effort.
464
+ }
465
+ origin.current = {
466
+ element,
467
+ x: vertical() ? e.clientY : e.clientX,
468
+ cross: vertical() ? e.clientX : e.clientY,
469
+ startHours,
470
+ durationHours,
471
+ span:
472
+ pe.continuesBefore || pe.continuesAfter
473
+ ? null
474
+ : {
475
+ start: pe.event.start,
476
+ end: pe.event.end,
477
+ },
478
+ };
479
+ applyDrag({
480
+ pointerId: e.pointerId,
481
+ event: pe.event,
482
+ resource,
483
+ kind,
484
+ startHours,
485
+ durationHours,
486
+ crossPx: 0,
487
+ moved: false,
488
+ });
489
+ };
490
+ const moveDrag = (e: DomPointerEvent) => {
491
+ const d = dragRef.current;
492
+ if (!d || d.pointerId !== e.pointerId || !origin.current) return;
493
+ const dHours = ((vertical() ? e.clientY : e.clientX) - origin.current.x) / hourSize();
494
+ const snap = (v: number) => Math.round(v / snapHours()) * snapHours();
495
+ if (d.kind === "move") {
496
+ const o = origin.current;
497
+ const requestedHours = clamp(
498
+ snap(o.startHours + dHours),
499
+ props.startHour,
500
+ props.endHour - o.durationHours,
501
+ );
502
+ // Draw the bar where the drop commits it: a start in the hour a
503
+ // spring-forward change skips moves on past it, and the kept elapsed
504
+ // duration covers a different number of hours once a DST change falls
505
+ // inside it or stops falling inside it.
506
+ const span = o.span;
507
+ const moved = span
508
+ ? movedClockSpan(span.start, span.end, Math.round((requestedHours - o.startHours) * 60))
509
+ : null;
510
+ const startHours = moved ? o.startHours + moved.startHours : requestedHours;
511
+ const durationHours = moved ? moved.hours : o.durationHours;
512
+ const crossPx = (vertical() ? e.clientX : e.clientY) - o.cross;
513
+ applyDrag({
514
+ ...d,
515
+ startHours,
516
+ durationHours,
517
+ crossPx,
518
+ moved: true,
519
+ });
520
+ } else {
521
+ const durationHours = clamp(
522
+ snap(origin.current.durationHours + dHours),
523
+ snapHours(),
524
+ props.endHour - d.startHours,
525
+ );
526
+ applyDrag({
527
+ ...d,
528
+ durationHours,
529
+ moved: true,
530
+ });
531
+ }
532
+ };
533
+ // Which visible lane the pointer is over, found by hit-testing rather than
534
+ // measuring flexed columns. The dragged bar is momentarily made
535
+ // pointer-transparent so `elementFromPoint` sees the lane, not the bar (which
536
+ // stays a DOM child of its origin lane however far it's visually translated).
537
+ const laneAt = (e: DomPointerEvent, fallback: Resource): Resource => {
538
+ if (typeof document === "undefined" || typeof document.elementFromPoint !== "function") {
539
+ return fallback;
540
+ }
541
+ const bar = e.currentTarget as HTMLElement;
542
+ const prev = bar.style.pointerEvents;
543
+ // Restore in a finally: a left-behind "none" would permanently disable this
544
+ // bar, because this inline style is set imperatively during the drag.
545
+ let hit: Element | null;
546
+ bar.style.pointerEvents = "none";
547
+ try {
548
+ hit = document.elementFromPoint(e.clientX, e.clientY);
549
+ } finally {
550
+ bar.style.pointerEvents = prev;
551
+ }
552
+ const laneEl = (hit as HTMLElement | null)?.closest?.("[data-resource-id]");
553
+ const id = laneEl?.getAttribute("data-resource-id");
554
+ return (id && resources().find((r) => r.id === id)) || fallback;
555
+ };
556
+ const endDrag = (e: DomPointerEvent) => {
557
+ const d = dragRef.current;
558
+ if (!d || d.pointerId !== e.pointerId) return;
559
+ handledClick = origin.current?.element ?? null;
560
+ if (!d.moved) {
561
+ clearDrag();
562
+ props.onPressEvent?.(d.event);
563
+ return;
564
+ }
565
+ const resource = resources().find((resource) => resource.id === d.resource.id);
566
+ if (!resource) {
567
+ clearDrag();
568
+ return;
569
+ }
570
+ const target = d.kind === "move" ? laneAt(e, resource) : resource;
571
+ // Shift the event by how far its bar moved, like the native renderer, so a
572
+ // move keeps its elapsed duration across a DST change.
573
+ const o = origin.current;
574
+ const startDelta = o ? Math.round((d.startHours - o.startHours) * 60) : 0;
575
+ // A move shifts both edges alike; its preview duration only redraws the
576
+ // kept elapsed duration.
577
+ const endDelta =
578
+ d.kind === "move" ? startDelta : o ? Math.round((d.durationHours - o.durationHours) * 60) : 0;
579
+ const next = resolveDraggedBounds(
580
+ d.event.start,
581
+ d.event.end,
582
+ startDelta,
583
+ endDelta,
584
+ props.dragStepMinutes,
585
+ );
586
+ clearDrag();
587
+ if (next) props.onDragEvent?.(d.event, next.start, next.end, target);
588
+ };
589
+ const cancelDrag = (e: DomPointerEvent) => {
590
+ if (dragRef.current?.pointerId !== e.pointerId) return;
591
+ handledClick = origin.current?.element ?? null;
592
+ clearDrag();
593
+ };
594
+
595
+ // Create-by-drag / tap on empty lane space, mirroring the time grid: mouse and
596
+ // pen sweep out a new event, and a tap without movement fires onPressCell. Touch
597
+ // is left free to scroll the board, so cell taps are pointer (mouse/pen) only.
598
+ const [createBox, setCreateBox] = createSignal<{
599
+ resourceKey: string;
600
+ startPx: number;
601
+ curPx: number;
602
+ } | null>(null);
603
+ const createOrigin: ElementRef<{
604
+ pointerId: number;
605
+ clientX: number;
606
+ clientY: number;
607
+ el: HTMLElement;
608
+ resource: Resource;
609
+ startPx: number;
610
+ dayKey: string;
611
+ creating: boolean;
612
+ } | null> = {
613
+ current: null,
614
+ };
615
+ createEffect(
616
+ () => (createBox() ? (vertical() ? "vertical" : "horizontal") : null),
617
+ (axis) => {
618
+ if (!axis) return;
619
+ const onScroll = () => {
620
+ const origin = createOrigin.current;
621
+ if (!origin) return;
622
+ const rect = origin.el.getBoundingClientRect();
623
+ const curPx = axis === "vertical" ? origin.clientY - rect.top : origin.clientX - rect.left;
624
+ setCreateBox((current) =>
625
+ current && current.curPx !== curPx ? { ...current, curPx } : current,
626
+ );
627
+ };
628
+ window.addEventListener("scroll", onScroll, true);
629
+ return () => window.removeEventListener("scroll", onScroll, true);
630
+ },
631
+ );
632
+ const clearCreate = () => {
633
+ const previous = createOrigin.current;
634
+ createOrigin.current = null;
635
+ setCreateBox(null);
636
+ try {
637
+ previous?.el.releasePointerCapture?.(previous.pointerId);
638
+ } catch {
639
+ // The browser may have already released capture.
640
+ }
641
+ };
642
+ createEffect(
643
+ () => [],
644
+ () => {
645
+ const onKeyDown = (event: KeyboardEvent) => {
646
+ if (event.key !== "Escape" || !createOrigin.current) return;
647
+ event.preventDefault();
648
+ event.stopPropagation();
649
+ clearCreate();
650
+ };
651
+ document.addEventListener("keydown", onKeyDown);
652
+ return () => document.removeEventListener("keydown", onKeyDown);
653
+ },
654
+ );
655
+ const cellEnabled = createMemo(() => !!props.onPressCell || !!props.onCreateEvent);
656
+ createEffect(
657
+ () => ({
658
+ dayKey: props.date.toDateString(),
659
+ creating: !!props.onCreateEvent,
660
+ enabled: cellEnabled(),
661
+ }),
662
+ (state) => {
663
+ const origin = createOrigin.current;
664
+ if (
665
+ origin &&
666
+ (!state.enabled || (origin.creating && !state.creating) || origin.dayKey !== state.dayKey)
667
+ )
668
+ clearCreate();
669
+ },
670
+ );
671
+ const pxAlongAxis = (el: HTMLElement, e: DomPointerEvent) => {
672
+ const rect = el.getBoundingClientRect();
673
+ return vertical() ? e.clientY - rect.top : e.clientX - rect.left;
674
+ };
675
+ const beginCreate = (e: DomPointerEvent, resource: Resource) => {
676
+ // Only from the lane background, primary button, never on an event bar.
677
+ if (
678
+ !cellEnabled() ||
679
+ e.pointerType === "touch" ||
680
+ e.isPrimary === false ||
681
+ createOrigin.current ||
682
+ dragRef.current
683
+ )
684
+ return;
685
+ if (e.target !== e.currentTarget || e.button > 0) return;
686
+ const el = e.currentTarget as HTMLElement;
687
+ const startPx = pxAlongAxis(el, e);
688
+ try {
689
+ el.setPointerCapture?.(e.pointerId);
690
+ } catch {
691
+ // Best-effort capture.
692
+ }
693
+ createOrigin.current = {
694
+ pointerId: e.pointerId,
695
+ clientX: e.clientX,
696
+ clientY: e.clientY,
697
+ el,
698
+ resource,
699
+ startPx,
700
+ dayKey: props.date.toDateString(),
701
+ creating: !!props.onCreateEvent,
702
+ };
703
+ // Only preview a ghost when a create can happen; in press-only mode
704
+ // (onPressCell without onCreateEvent) the tap still commits via endCreate.
705
+ if (props.onCreateEvent)
706
+ setCreateBox({
707
+ resourceKey: resource.id,
708
+ startPx,
709
+ curPx: startPx,
710
+ });
711
+ };
712
+ const moveCreate = (e: DomPointerEvent) => {
713
+ const o = createOrigin.current;
714
+ if (!o || o.pointerId !== e.pointerId || !props.onCreateEvent) return;
715
+ o.clientX = e.clientX;
716
+ o.clientY = e.clientY;
717
+ setCreateBox({
718
+ resourceKey: o.resource.id,
719
+ startPx: o.startPx,
720
+ curPx: pxAlongAxis(o.el, e),
721
+ });
722
+ };
723
+ const endCreate = (e: DomPointerEvent) => {
724
+ const o = createOrigin.current;
725
+ if (!o || o.pointerId !== e.pointerId) return;
726
+ const endPx = pxAlongAxis(o.el, e);
727
+ const moved = Math.abs(endPx - o.startPx) > 4;
728
+ clearCreate();
729
+ const resource = resources().find((resource) => resource.id === o.resource.id);
730
+ if (!resource) return;
731
+ if (moved && props.onCreateEvent) {
732
+ const range = cellRangeFromDrag(
733
+ props.date,
734
+ o.startPx,
735
+ endPx,
736
+ hourSize(),
737
+ props.startHour,
738
+ props.dragStepMinutes,
739
+ );
740
+ if (range) props.onCreateEvent(range.start, range.end, resource);
741
+ } else if (props.onPressCell) {
742
+ const at = cellRangeFromDrag(
743
+ props.date,
744
+ o.startPx,
745
+ o.startPx,
746
+ hourSize(),
747
+ props.startHour,
748
+ props.dragStepMinutes,
749
+ );
750
+ if (at) props.onPressCell(at.start, resource);
751
+ }
752
+ };
753
+ // A gesture the browser cancels (scroll takeover, etc.) must not commit.
754
+ const cancelCreate = (e: DomPointerEvent) => {
755
+ if (createOrigin.current?.pointerId !== e.pointerId) return;
756
+ clearCreate();
757
+ };
758
+ // What `onCreateEvent` would receive if the sweep ended here. Kept while the
759
+ // range holds, so content updates only when it changes.
760
+ const createRange = createMemo(
761
+ () => {
762
+ const box = createBox();
763
+ return box && props.renderCreateGhost && props.onCreateEvent
764
+ ? cellRangeFromDrag(
765
+ props.date,
766
+ box.startPx,
767
+ box.curPx,
768
+ hourSize(),
769
+ props.startHour,
770
+ props.dragStepMinutes,
771
+ )
772
+ : null;
773
+ },
774
+ { equals: sameRange },
775
+ );
776
+ const trackInteractionProps = (resource: Resource) => ({
777
+ onPointerDown: (e: DomPointerEvent) => beginCreate(e, resource),
778
+ onPointerMove: moveCreate,
779
+ onPointerUp: endCreate,
780
+ onPointerCancel: cancelCreate,
781
+ onLostPointerCapture: cancelCreate,
782
+ });
783
+ // The closed-hours bands to shade in a lane, resolved per resource.
784
+ const bandsFor = (resource: Resource) => {
785
+ const businessHours = props.businessHours;
786
+ return businessHours
787
+ ? closedHourBands(
788
+ props.date,
789
+ (d) => businessHours(d, resource),
790
+ props.startHour,
791
+ props.endHour,
792
+ )
793
+ : [];
794
+ };
795
+ // `display: "background"` events in a lane, clipped to the visible window.
796
+ const backgroundBandsFor = (resource: Resource) =>
797
+ backgroundBandsForDay(
798
+ props.events.filter((e) => props.resourceId(e) === resource.id),
799
+ props.date,
800
+ )
801
+ .map((b) => ({
802
+ ...b,
803
+ startHours: Math.max(b.startHours, props.startHour),
804
+ endHours: Math.min(b.endHours, props.endHour),
805
+ }))
806
+ .filter((b) => b.endHours > b.startHours);
807
+ const hours = createMemo(() =>
808
+ Array.from(
809
+ {
810
+ length: Math.max(0, props.endHour - props.startHour),
811
+ },
812
+ (_, i) => props.startHour + i,
813
+ ),
814
+ );
815
+ const trackWidth = createMemo(() => (props.endHour - props.startHour) * props.hourWidth);
816
+ const trackHeight = createMemo(() => (props.endHour - props.startHour) * props.hourHeight);
817
+ const vGridLines = createMemo(
818
+ () =>
819
+ `repeating-linear-gradient(to bottom, transparent 0, transparent ${props.hourHeight - 1}px, ${theme().gridLine} ${props.hourHeight - 1}px, ${theme().gridLine} ${props.hourHeight}px)`,
820
+ );
821
+
822
+ // The actions dialog's steps, matching the native screen-reader actions: one
823
+ // snap step along the axis, or one lane across, through the same commit as a
824
+ // drop. `draggable: false` locks a bar, as it does for a drag.
825
+ const laneOf = (event: CalendarEvent<T>) =>
826
+ resources().findIndex((resource) => resource.id === props.resourceId(event));
827
+ const eventDescription = (event: CalendarEvent<T>) =>
828
+ `${resources().find((resource) => resource.id === props.resourceId(event))?.title ?? ""}, ${describeEventDates(event)}, ${eventAccessibilityLabel({ title: event.title, isAllDay: false, start: event.start, end: event.end, ampm: props.ampm, labels: labels() })}`;
829
+ const actionDelta = (id: string): [number, number, number] | null => {
830
+ const step = props.dragStepMinutes;
831
+ switch (id) {
832
+ case "move-later":
833
+ return [step, step, 0];
834
+ case "move-earlier":
835
+ return [-step, -step, 0];
836
+ case "extend":
837
+ return [0, step, 0];
838
+ case "shorten":
839
+ return [0, -step, 0];
840
+ case "move-next-resource":
841
+ return [0, 0, 1];
842
+ case "move-previous-resource":
843
+ return [0, 0, -1];
844
+ default:
845
+ return null;
846
+ }
847
+ };
848
+ const editActions = (event: CalendarEvent<T>): EventEditAction[] => {
849
+ if (isAllDayEvent(event) || isBackgroundEvent(event)) return [];
850
+ const lane = laneOf(event);
851
+ if (!props.onDragEvent || event.draggable === false || lane < 0) return [];
852
+ const step = props.dragStepMinutes;
853
+ const words = labels();
854
+ const action = (id: string, label: string): EventEditAction => {
855
+ const [startDelta, endDelta] = actionDelta(id) ?? [0, 0];
856
+ const next = resolveDraggedBounds(event.start, event.end, startDelta, endDelta, step);
857
+ return { id, label, available: next !== null };
858
+ };
859
+ const laneTitle = (resource?: Resource) => resource && (resource.title || resource.id);
860
+ const nextLane = laneTitle(resources()[lane + 1]);
861
+ const previousLane = laneTitle(resources()[lane - 1]);
862
+ return [
863
+ action("move-later", words.moveLater(step)),
864
+ action("move-earlier", words.moveEarlier(step)),
865
+ action("extend", words.extend(step)),
866
+ action("shorten", words.shorten(step)),
867
+ ...(nextLane ? [action("move-next-resource", words.moveToResource(nextLane))] : []),
868
+ ...(previousLane
869
+ ? [action("move-previous-resource", words.moveToResource(previousLane))]
870
+ : []),
871
+ ];
872
+ };
873
+ const eventActions = createEventActions<CalendarEvent<T>>(
874
+ () => props.events,
875
+ editActions,
876
+ (event, id) => {
877
+ const delta = actionDelta(id);
878
+ const target = delta ? resources()[laneOf(event) + delta[2]] : undefined;
879
+ const next =
880
+ delta &&
881
+ target &&
882
+ resolveDraggedBounds(event.start, event.end, delta[0], delta[1], props.dragStepMinutes);
883
+ if (!next || !target || props.onDragEvent?.(event, next.start, next.end, target) === false)
884
+ return null;
885
+ return (candidate) =>
886
+ candidate !== event &&
887
+ candidate.start.getTime() === next.start.getTime() &&
888
+ candidate.end.getTime() === next.end.getTime() &&
889
+ candidate.title === event.title &&
890
+ props.resourceId(candidate) === target.id;
891
+ },
892
+ () => props.getEventId,
893
+ );
894
+
895
+ // Group the positioned (overlap-resolved) events by resource, once.
896
+ const byResource = createMemo(() => {
897
+ const map = new Map<string, ReturnType<typeof layoutDayEvents<T>>>();
898
+ for (const resource of resources()) {
899
+ const own = props.events.filter((e) => props.resourceId(e) === resource.id);
900
+ map.set(resource.id, layoutDayEvents(own, props.date));
901
+ }
902
+ return map;
903
+ });
904
+
905
+ // The lane a move is dragging in, lifted above its siblings so the ghost
906
+ // stays visible as it crosses into another lane (a later DOM sibling).
907
+ const dragLaneId = createMemo(() => {
908
+ const currentDrag = drag();
909
+ return currentDrag?.kind === "move" && currentDrag.moved ? currentDrag.resource.id : null;
910
+ });
911
+ return (
912
+ <>
913
+ {(() => {
914
+ if (vertical()) {
915
+ // Time flows down like the time grid: hour gutter on the left, one flexed
916
+ // column per resource, so narrow screens share the width instead of
917
+ // scrolling sideways.
918
+ return (
919
+ <div
920
+ ref={(el) => (eventActions.rootRef.current = el)}
921
+ tabindex={-1}
922
+ class={props.className}
923
+ style={css({
924
+ fontFamily: theme().fontFamily,
925
+ color: theme().text,
926
+ overflowY: "auto",
927
+ ...props.style,
928
+ })}
929
+ >
930
+ <EventActionsMenu
931
+ events={[
932
+ ...new Set([...byResource().values()].flat().map((pe) => pe.event)),
933
+ ].filter((event) => editActions(event).length > 0)}
934
+ label={labels().editEvents}
935
+ labelFor={(event) => labels().eventActions(event.title ?? "")}
936
+ descriptionFor={eventDescription}
937
+ onSelect={eventActions.select}
938
+ rootRef={eventActions.rootRef}
939
+ slot={slot}
940
+ theme={theme()}
941
+ />
942
+
943
+ {/* Header: corner above the hour gutter + one label per resource column */}
944
+ <div
945
+ {...slot("header", {
946
+ // Sticky so the resource labels stay visible while the hours scroll
947
+ // (matching the native renderer's fixed header row).
948
+ base: {
949
+ display: "flex",
950
+ position: "sticky",
951
+ top: 0,
952
+ zIndex: 2,
953
+ },
954
+ themed: {
955
+ borderBottom: `1px solid ${theme().gridLine}`,
956
+ background: theme().surface,
957
+ },
958
+ })}
959
+ >
960
+ <div
961
+ {...slot("corner", {
962
+ base: {
963
+ width: GUTTER_WIDTH,
964
+ flex: "none",
965
+ },
966
+ })}
967
+ />
968
+ {
969
+ <For each={resources()} keyed={false}>
970
+ {(resource, index) => (
971
+ <div
972
+ {...slot("resourceLabel", {
973
+ base: {
974
+ flex: 1,
975
+ minWidth: 0,
976
+ padding: "6px 4px",
977
+ textAlign: "center",
978
+ overflow: "hidden",
979
+ textOverflow: "ellipsis",
980
+ whiteSpace: "nowrap",
981
+ boxSizing: "border-box",
982
+ },
983
+ themed: {
984
+ fontSize: 13,
985
+ fontWeight: 600,
986
+ borderLeft: `1px solid ${theme().gridLine}`,
987
+ },
988
+ })}
989
+ >
990
+ {props.renderResourceHeader
991
+ ? props.renderResourceHeader(resource(), index)
992
+ : (resource().title ?? resource().id)}
993
+ </div>
994
+ )}
995
+ </For>
996
+ }
997
+ </div>
998
+ <div
999
+ style={css({
1000
+ display: "flex",
1001
+ })}
1002
+ >
1003
+ <div
1004
+ {...slot("timeAxis", {
1005
+ base: {
1006
+ position: "relative",
1007
+ width: GUTTER_WIDTH,
1008
+ flex: "none",
1009
+ height: trackHeight(),
1010
+ },
1011
+ })}
1012
+ >
1013
+ {
1014
+ <For each={hours()} keyed={false}>
1015
+ {(h) => (
1016
+ <div
1017
+ {...slot("hourTick", {
1018
+ base: {
1019
+ position: "absolute",
1020
+ top: Math.max(0, (h() - props.startHour) * props.hourHeight - 6),
1021
+ right: 6,
1022
+ },
1023
+ themed: {
1024
+ fontSize: 10,
1025
+ color: theme().textMuted,
1026
+ },
1027
+ })}
1028
+ >
1029
+ {formatHour(h(), {
1030
+ ampm: props.ampm,
1031
+ })}
1032
+ </div>
1033
+ )}
1034
+ </For>
1035
+ }
1036
+ </div>
1037
+ {
1038
+ <For each={resources()} keyed={(resource) => resource.id}>
1039
+ {(resource) => {
1040
+ const resourceKey = untrack(() => resource().id);
1041
+ onCleanup(() => {
1042
+ if (createOrigin.current?.resource.id === resourceKey) clearCreate();
1043
+ });
1044
+ const ghost = createMemo(() => {
1045
+ const box = createBox();
1046
+ return box?.resourceKey === resource().id ? box : null;
1047
+ });
1048
+ const positioned = createMemo(() => byResource().get(resource().id) ?? []);
1049
+ return (
1050
+ <div
1051
+ {...slot("row", {
1052
+ base: {
1053
+ flex: 1,
1054
+ minWidth: 0,
1055
+ ...(dragLaneId() === resource().id
1056
+ ? {
1057
+ position: "relative",
1058
+ zIndex: 5,
1059
+ }
1060
+ : null),
1061
+ },
1062
+ themed: {
1063
+ borderLeft: `1px solid ${theme().gridLine}`,
1064
+ },
1065
+ })}
1066
+ >
1067
+ <div
1068
+ data-resource-id={resource().id}
1069
+ {...trackInteractionProps(resource())}
1070
+ {...slot("track", {
1071
+ base: {
1072
+ position: "relative",
1073
+ height: trackHeight(),
1074
+ },
1075
+ })}
1076
+ >
1077
+ {/* Closed-hours shade, behind the grid lines and events. */}
1078
+ {
1079
+ <For each={bandsFor(resource())} keyed={false}>
1080
+ {(b) => (
1081
+ <div
1082
+ aria-hidden="true"
1083
+ {...slot("businessHours", {
1084
+ base: {
1085
+ position: "absolute",
1086
+ left: 0,
1087
+ right: 0,
1088
+ top: (b().start - props.startHour) * props.hourHeight,
1089
+ height: (b().end - b().start) * props.hourHeight,
1090
+ pointerEvents: "none",
1091
+ zIndex: 0,
1092
+ },
1093
+ themed: props.renderBusinessHours
1094
+ ? undefined
1095
+ : {
1096
+ background: theme().outsideHoursBackground,
1097
+ },
1098
+ })}
1099
+ >
1100
+ {props.renderBusinessHours?.({
1101
+ date: props.date,
1102
+ start: b().start,
1103
+ end: b().end,
1104
+ resource: resource(),
1105
+ })}
1106
+ </div>
1107
+ )}
1108
+ </For>
1109
+ }
1110
+ {
1111
+ <For each={backgroundBandsFor(resource())} keyed={false}>
1112
+ {(b) => (
1113
+ <div
1114
+ aria-hidden="true"
1115
+ title={b().event.title}
1116
+ {...slot("backgroundEvent", {
1117
+ base: {
1118
+ position: "absolute",
1119
+ left: 0,
1120
+ right: 0,
1121
+ top: (b().startHours - props.startHour) * props.hourHeight,
1122
+ height: (b().endHours - b().startHours) * props.hourHeight,
1123
+ pointerEvents: "none",
1124
+ zIndex: 0,
1125
+ },
1126
+ themed: {
1127
+ background: theme().backgroundEvent,
1128
+ },
1129
+ })}
1130
+ />
1131
+ )}
1132
+ </For>
1133
+ }
1134
+ <div
1135
+ aria-hidden="true"
1136
+ {...slot("gridLines", {
1137
+ base: {
1138
+ position: "absolute",
1139
+ inset: 0,
1140
+ pointerEvents: "none",
1141
+ },
1142
+ themed: {
1143
+ backgroundImage: vGridLines(),
1144
+ },
1145
+ })}
1146
+ />
1147
+ {
1148
+ <For each={positioned()} keyed={(pe) => pe.event}>
1149
+ {(pe) => {
1150
+ const event = untrack(() => pe().event);
1151
+ onCleanup(() => {
1152
+ if (dragRef.current?.event === event) clearDrag();
1153
+ });
1154
+ const active = createMemo(() => {
1155
+ const currentDrag = drag();
1156
+ return currentDrag?.event === event &&
1157
+ currentDrag.resource.id === resource().id
1158
+ ? currentDrag
1159
+ : null;
1160
+ });
1161
+ const startH = createMemo(() => {
1162
+ const currentActive = active();
1163
+ return currentActive
1164
+ ? currentActive.startHours
1165
+ : pe().startHours;
1166
+ });
1167
+ const durH = createMemo(() => {
1168
+ const currentActive = active();
1169
+ return currentActive
1170
+ ? currentActive.durationHours
1171
+ : pe().durationHours;
1172
+ });
1173
+ const top = createMemo(
1174
+ () =>
1175
+ clamp(
1176
+ startH() - props.startHour,
1177
+ 0,
1178
+ props.endHour - props.startHour,
1179
+ ) * props.hourHeight,
1180
+ );
1181
+ const bottom = createMemo(
1182
+ () =>
1183
+ clamp(
1184
+ startH() + durH() - props.startHour,
1185
+ 0,
1186
+ props.endHour - props.startHour,
1187
+ ) * props.hourHeight,
1188
+ );
1189
+ const height = createMemo(() => Math.max(bottom() - top(), 2));
1190
+ // Overlapping events share the column as side-by-side sub-lanes.
1191
+ const lanePct = createMemo(() => 100 / pe().columns);
1192
+ const onPress = () => props.onPressEvent?.(pe().event);
1193
+ const args = createMemo<ResourceEventArgs<T>>(() => ({
1194
+ event: pe().event,
1195
+ width: 0,
1196
+ height: height(),
1197
+ onPress,
1198
+ }));
1199
+ // `draggable: false` locks a single bar (keeps clicks, blocks drag).
1200
+ const draggable = createMemo(
1201
+ () => !!props.onDragEvent && pe().event.draggable !== false,
1202
+ );
1203
+ return (
1204
+ <button
1205
+ type="button"
1206
+ onClick={(e) => {
1207
+ if (e.detail !== 0 && handledClick === e.currentTarget) {
1208
+ handledClick = null;
1209
+ return;
1210
+ }
1211
+ if (!draggable() || e.detail === 0) onPress();
1212
+ }}
1213
+ aria-label={pe().event.title}
1214
+ {...dataState({
1215
+ "data-dragging": !!active(),
1216
+ })}
1217
+ onPointerDown={(e) => beginDrag(e, resource(), "move", pe())}
1218
+ onPointerMove={moveDrag}
1219
+ onPointerUp={endDrag}
1220
+ onPointerCancel={cancelDrag}
1221
+ onLostPointerCapture={cancelDrag}
1222
+ {...slot("event", {
1223
+ base: {
1224
+ position: "absolute",
1225
+ top: top(),
1226
+ height: height(),
1227
+ left: `${pe().column * lanePct()}%`,
1228
+ width: `${lanePct()}%`,
1229
+ transform:
1230
+ active()?.kind === "move"
1231
+ ? `translateX(${active()?.crossPx}px)`
1232
+ : undefined,
1233
+ padding: 1,
1234
+ border: "none",
1235
+ background: "transparent",
1236
+ cursor: draggable() ? "grab" : "pointer",
1237
+ touchAction: draggable() ? "none" : "auto",
1238
+ font: "inherit",
1239
+ textAlign: "left",
1240
+ boxSizing: "border-box",
1241
+ zIndex: active() ? 3 : 1,
1242
+ opacity: active() ? 0.85 : 1,
1243
+ },
1244
+ })}
1245
+ >
1246
+ {Renderer() ? (
1247
+ <Dynamic component={Renderer()} {...args()} />
1248
+ ) : (
1249
+ <DefaultBar
1250
+ {...args()}
1251
+ theme={theme()}
1252
+ boxProps={slot("eventBox")}
1253
+ />
1254
+ )}
1255
+ {draggable() ? (
1256
+ <span
1257
+ aria-hidden="true"
1258
+ onPointerDown={(e) => {
1259
+ e.stopPropagation();
1260
+ beginDrag(e, resource(), "resize", pe());
1261
+ }}
1262
+ style={css({
1263
+ position: "absolute",
1264
+ left: 0,
1265
+ right: 0,
1266
+ bottom: 0,
1267
+ height: 8,
1268
+ cursor: "ns-resize",
1269
+ touchAction: "none",
1270
+ })}
1271
+ />
1272
+ ) : null}
1273
+ </button>
1274
+ );
1275
+ }}
1276
+ </For>
1277
+ }
1278
+ {nowLine(resource().id)}
1279
+ {
1280
+ <Show when={ghost()}>
1281
+ {(ghost) => (
1282
+ <div
1283
+ aria-hidden="true"
1284
+ // Custom content stays out of the tab order and pointer input.
1285
+ inert={createRange() ? true : undefined}
1286
+ {...slot("createGhost", {
1287
+ base: {
1288
+ position: "absolute",
1289
+ left: 1,
1290
+ right: 1,
1291
+ top: Math.min(ghost().startPx, ghost().curPx),
1292
+ height: Math.max(
1293
+ Math.abs(ghost().curPx - ghost().startPx),
1294
+ 2,
1295
+ ),
1296
+ ...(createRange() ? { overflow: "hidden" } : null),
1297
+ opacity: 0.7,
1298
+ pointerEvents: "none",
1299
+ zIndex: 2,
1300
+ },
1301
+ themed: {
1302
+ background: theme().rangeBackground,
1303
+ border: `1px solid ${theme().selectedBackground}`,
1304
+ borderRadius: 6,
1305
+ },
1306
+ })}
1307
+ >
1308
+ <Show when={createRange()}>
1309
+ {(range) => (
1310
+ <Dynamic
1311
+ component={props.renderCreateGhost}
1312
+ start={range().start}
1313
+ end={range().end}
1314
+ resource={resource()}
1315
+ />
1316
+ )}
1317
+ </Show>
1318
+ </div>
1319
+ )}
1320
+ </Show>
1321
+ }
1322
+ </div>
1323
+ </div>
1324
+ );
1325
+ }}
1326
+ </For>
1327
+ }
1328
+ </div>
1329
+ </div>
1330
+ );
1331
+ }
1332
+ const gridLines = createMemo(
1333
+ () =>
1334
+ `repeating-linear-gradient(to right, transparent 0, transparent ${props.hourWidth - 1}px, ${theme().gridLine} ${props.hourWidth - 1}px, ${theme().gridLine} ${props.hourWidth}px)`,
1335
+ );
1336
+ return (
1337
+ <div
1338
+ ref={(el) => (eventActions.rootRef.current = el)}
1339
+ tabindex={-1}
1340
+ class={props.className}
1341
+ style={css({
1342
+ fontFamily: theme().fontFamily,
1343
+ color: theme().text,
1344
+ overflowX: "auto",
1345
+ ...props.style,
1346
+ })}
1347
+ >
1348
+ <EventActionsMenu
1349
+ events={[...new Set([...byResource().values()].flat().map((pe) => pe.event))].filter(
1350
+ (event) => editActions(event).length > 0,
1351
+ )}
1352
+ label={labels().editEvents}
1353
+ labelFor={(event) => labels().eventActions(event.title ?? "")}
1354
+ descriptionFor={eventDescription}
1355
+ onSelect={eventActions.select}
1356
+ rootRef={eventActions.rootRef}
1357
+ slot={slot}
1358
+ theme={theme()}
1359
+ />
1360
+ <div
1361
+ style={css({
1362
+ minWidth: props.labelWidth + trackWidth(),
1363
+ })}
1364
+ >
1365
+ {/* Header: corner + hour axis */}
1366
+ <div
1367
+ {...slot("header", {
1368
+ base: {
1369
+ display: "flex",
1370
+ },
1371
+ themed: {
1372
+ borderBottom: `1px solid ${theme().gridLine}`,
1373
+ },
1374
+ })}
1375
+ >
1376
+ <div
1377
+ {...slot("corner", {
1378
+ base: {
1379
+ width: props.labelWidth,
1380
+ flex: "none",
1381
+ },
1382
+ })}
1383
+ />
1384
+ <div
1385
+ {...slot("timeAxis", {
1386
+ base: {
1387
+ position: "relative",
1388
+ height: 24,
1389
+ width: trackWidth(),
1390
+ },
1391
+ })}
1392
+ >
1393
+ {
1394
+ <For each={hours()} keyed={false}>
1395
+ {(h) => (
1396
+ <div
1397
+ {...slot("hourTick", {
1398
+ base: {
1399
+ position: "absolute",
1400
+ left: (h() - props.startHour) * props.hourWidth,
1401
+ top: 4,
1402
+ },
1403
+ themed: {
1404
+ fontSize: 10,
1405
+ color: theme().textMuted,
1406
+ },
1407
+ })}
1408
+ >
1409
+ {formatHour(h(), {
1410
+ ampm: props.ampm,
1411
+ })}
1412
+ </div>
1413
+ )}
1414
+ </For>
1415
+ }
1416
+ </div>
1417
+ </div>
1418
+
1419
+ {/* Resource rows */}
1420
+ {
1421
+ <For each={resources()} keyed={(resource) => resource.id}>
1422
+ {(resource, index) => {
1423
+ const resourceKey = untrack(() => resource().id);
1424
+ onCleanup(() => {
1425
+ if (createOrigin.current?.resource.id === resourceKey) clearCreate();
1426
+ });
1427
+ const ghost = createMemo(() => {
1428
+ const box = createBox();
1429
+ return box?.resourceKey === resource().id ? box : null;
1430
+ });
1431
+ const positioned = createMemo(() => byResource().get(resource().id) ?? []);
1432
+ return (
1433
+ <div
1434
+ {...slot("row", {
1435
+ base: {
1436
+ display: "flex",
1437
+ height: props.rowHeight,
1438
+ ...(dragLaneId() === resource().id
1439
+ ? {
1440
+ position: "relative",
1441
+ zIndex: 5,
1442
+ }
1443
+ : null),
1444
+ },
1445
+ themed: {
1446
+ borderBottom: `1px solid ${theme().gridLine}`,
1447
+ },
1448
+ })}
1449
+ >
1450
+ <div
1451
+ {...slot("resourceLabel", {
1452
+ base: {
1453
+ width: props.labelWidth,
1454
+ flex: "none",
1455
+ display: "flex",
1456
+ alignItems: "center",
1457
+ padding: "0 10px",
1458
+ boxSizing: "border-box",
1459
+ },
1460
+ themed: {
1461
+ fontSize: 13,
1462
+ fontWeight: 600,
1463
+ borderRight: `1px solid ${theme().gridLine}`,
1464
+ },
1465
+ })}
1466
+ >
1467
+ {props.renderResourceHeader
1468
+ ? props.renderResourceHeader(resource(), index())
1469
+ : (resource().title ?? resource().id)}
1470
+ </div>
1471
+ <div
1472
+ data-resource-id={resource().id}
1473
+ {...trackInteractionProps(resource())}
1474
+ {...slot("track", {
1475
+ base: {
1476
+ position: "relative",
1477
+ width: trackWidth(),
1478
+ },
1479
+ })}
1480
+ >
1481
+ {/* Closed-hours shade, behind the grid lines and events. */}
1482
+ {
1483
+ <For each={bandsFor(resource())} keyed={false}>
1484
+ {(b) => (
1485
+ <div
1486
+ aria-hidden="true"
1487
+ {...slot("businessHours", {
1488
+ base: {
1489
+ position: "absolute",
1490
+ top: 0,
1491
+ bottom: 0,
1492
+ left: (b().start - props.startHour) * props.hourWidth,
1493
+ width: (b().end - b().start) * props.hourWidth,
1494
+ pointerEvents: "none",
1495
+ zIndex: 0,
1496
+ },
1497
+ themed: props.renderBusinessHours
1498
+ ? undefined
1499
+ : {
1500
+ background: theme().outsideHoursBackground,
1501
+ },
1502
+ })}
1503
+ >
1504
+ {props.renderBusinessHours?.({
1505
+ date: props.date,
1506
+ start: b().start,
1507
+ end: b().end,
1508
+ resource: resource(),
1509
+ })}
1510
+ </div>
1511
+ )}
1512
+ </For>
1513
+ }
1514
+ {
1515
+ <For each={backgroundBandsFor(resource())} keyed={false}>
1516
+ {(b) => (
1517
+ <div
1518
+ aria-hidden="true"
1519
+ title={b().event.title}
1520
+ {...slot("backgroundEvent", {
1521
+ base: {
1522
+ position: "absolute",
1523
+ top: 0,
1524
+ bottom: 0,
1525
+ left: (b().startHours - props.startHour) * props.hourWidth,
1526
+ width: (b().endHours - b().startHours) * props.hourWidth,
1527
+ pointerEvents: "none",
1528
+ zIndex: 0,
1529
+ },
1530
+ themed: {
1531
+ background: theme().backgroundEvent,
1532
+ },
1533
+ })}
1534
+ />
1535
+ )}
1536
+ </For>
1537
+ }
1538
+ <div
1539
+ aria-hidden="true"
1540
+ {...slot("gridLines", {
1541
+ base: {
1542
+ position: "absolute",
1543
+ inset: 0,
1544
+ pointerEvents: "none",
1545
+ },
1546
+ themed: {
1547
+ backgroundImage: gridLines(),
1548
+ },
1549
+ })}
1550
+ />
1551
+ {
1552
+ <For each={positioned()} keyed={(pe) => pe.event}>
1553
+ {(pe) => {
1554
+ const event = untrack(() => pe().event);
1555
+ onCleanup(() => {
1556
+ if (dragRef.current?.event === event) clearDrag();
1557
+ });
1558
+ const active = createMemo(() => {
1559
+ const currentDrag = drag();
1560
+ return currentDrag?.event === event &&
1561
+ currentDrag.resource.id === resource().id
1562
+ ? currentDrag
1563
+ : null;
1564
+ });
1565
+ const startH = createMemo(() => {
1566
+ const currentActive = active();
1567
+ return currentActive ? currentActive.startHours : pe().startHours;
1568
+ });
1569
+ const durH = createMemo(() => {
1570
+ const currentActive = active();
1571
+ return currentActive
1572
+ ? currentActive.durationHours
1573
+ : pe().durationHours;
1574
+ });
1575
+ const left = createMemo(
1576
+ () =>
1577
+ clamp(
1578
+ startH() - props.startHour,
1579
+ 0,
1580
+ props.endHour - props.startHour,
1581
+ ) * props.hourWidth,
1582
+ );
1583
+ const right = createMemo(
1584
+ () =>
1585
+ clamp(
1586
+ startH() + durH() - props.startHour,
1587
+ 0,
1588
+ props.endHour - props.startHour,
1589
+ ) * props.hourWidth,
1590
+ );
1591
+ const width = createMemo(() => Math.max(right() - left(), 2));
1592
+ // Overlapping events in a row share the height as stacked sub-lanes.
1593
+ const laneHeight = createMemo(() => props.rowHeight / pe().columns);
1594
+ const onPress = () => props.onPressEvent?.(pe().event);
1595
+ const args = createMemo<ResourceEventArgs<T>>(() => ({
1596
+ event: pe().event,
1597
+ width: width(),
1598
+ onPress,
1599
+ }));
1600
+ const draggable = createMemo(
1601
+ () => !!props.onDragEvent && pe().event.draggable !== false,
1602
+ );
1603
+ return (
1604
+ <button
1605
+ type="button"
1606
+ onClick={(e) => {
1607
+ if (e.detail !== 0 && handledClick === e.currentTarget) {
1608
+ handledClick = null;
1609
+ return;
1610
+ }
1611
+ if (!draggable() || e.detail === 0) onPress();
1612
+ }}
1613
+ aria-label={pe().event.title}
1614
+ {...dataState({
1615
+ "data-dragging": !!active(),
1616
+ })}
1617
+ onPointerDown={(e) => beginDrag(e, resource(), "move", pe())}
1618
+ onPointerMove={moveDrag}
1619
+ onPointerUp={endDrag}
1620
+ onPointerCancel={cancelDrag}
1621
+ onLostPointerCapture={cancelDrag}
1622
+ {...slot("event", {
1623
+ base: {
1624
+ position: "absolute",
1625
+ left: left(),
1626
+ width: width(),
1627
+ top: pe().column * laneHeight(),
1628
+ height: laneHeight(),
1629
+ transform:
1630
+ active()?.kind === "move"
1631
+ ? `translateY(${active()?.crossPx}px)`
1632
+ : undefined,
1633
+ padding: 1,
1634
+ border: "none",
1635
+ background: "transparent",
1636
+ cursor: draggable() ? "grab" : "pointer",
1637
+ touchAction: draggable() ? "none" : "auto",
1638
+ font: "inherit",
1639
+ textAlign: "left",
1640
+ boxSizing: "border-box",
1641
+ zIndex: active() ? 3 : 1,
1642
+ opacity: active() ? 0.85 : 1,
1643
+ },
1644
+ })}
1645
+ >
1646
+ {Renderer() ? (
1647
+ <Dynamic component={Renderer()} {...args()} />
1648
+ ) : (
1649
+ <DefaultBar
1650
+ {...args()}
1651
+ theme={theme()}
1652
+ boxProps={slot("eventBox")}
1653
+ />
1654
+ )}
1655
+ {draggable() ? (
1656
+ <span
1657
+ aria-hidden="true"
1658
+ onPointerDown={(e) => {
1659
+ e.stopPropagation();
1660
+ beginDrag(e, resource(), "resize", pe());
1661
+ }}
1662
+ style={css({
1663
+ position: "absolute",
1664
+ top: 0,
1665
+ bottom: 0,
1666
+ right: 0,
1667
+ width: 8,
1668
+ cursor: "ew-resize",
1669
+ touchAction: "none",
1670
+ })}
1671
+ />
1672
+ ) : null}
1673
+ </button>
1674
+ );
1675
+ }}
1676
+ </For>
1677
+ }
1678
+ {nowLine(resource().id)}
1679
+ {
1680
+ <Show when={ghost()}>
1681
+ {(ghost) => (
1682
+ <div
1683
+ aria-hidden="true"
1684
+ // Custom content stays out of the tab order and pointer input.
1685
+ inert={createRange() ? true : undefined}
1686
+ {...slot("createGhost", {
1687
+ base: {
1688
+ position: "absolute",
1689
+ top: 1,
1690
+ bottom: 1,
1691
+ left: Math.min(ghost().startPx, ghost().curPx),
1692
+ width: Math.max(Math.abs(ghost().curPx - ghost().startPx), 2),
1693
+ ...(createRange() ? { overflow: "hidden" } : null),
1694
+ opacity: 0.7,
1695
+ pointerEvents: "none",
1696
+ zIndex: 2,
1697
+ },
1698
+ themed: {
1699
+ background: theme().rangeBackground,
1700
+ border: `1px solid ${theme().selectedBackground}`,
1701
+ borderRadius: 6,
1702
+ },
1703
+ })}
1704
+ >
1705
+ <Show when={createRange()}>
1706
+ {(range) => (
1707
+ <Dynamic
1708
+ component={props.renderCreateGhost}
1709
+ start={range().start}
1710
+ end={range().end}
1711
+ resource={resource()}
1712
+ />
1713
+ )}
1714
+ </Show>
1715
+ </div>
1716
+ )}
1717
+ </Show>
1718
+ }
1719
+ </div>
1720
+ </div>
1721
+ );
1722
+ }}
1723
+ </For>
1724
+ }
1725
+ </div>
1726
+ </div>
1727
+ );
1728
+ })()}
1729
+ <Show when={eventActions.openEvent()}>
1730
+ {(event) => (
1731
+ <EventActionsDialog
1732
+ dialogRef={eventActions.dialogRef}
1733
+ title={labels().eventActions(event().title ?? "")}
1734
+ description={eventDescription(event())}
1735
+ actions={editActions(event())}
1736
+ closeLabel={labels().close}
1737
+ rejectedLabel={labels().eventChangeRejected}
1738
+ rejections={eventActions.rejections()}
1739
+ onAction={eventActions.run}
1740
+ onClose={() => eventActions.close(true)}
1741
+ slot={slot}
1742
+ theme={theme()}
1743
+ />
1744
+ )}
1745
+ </Show>
1746
+ </>
1747
+ );
1748
+ }