@salmonui/scheduler 0.0.0-stage → 0.2.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.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +44 -2
  3. package/dist/internal/scheduler/crud.d.ts +30 -0
  4. package/dist/internal/scheduler/crud.d.ts.map +1 -0
  5. package/dist/internal/scheduler/crud.js +165 -0
  6. package/dist/internal/scheduler/crud.js.map +1 -0
  7. package/dist/internal/scheduler/export.d.ts +157 -0
  8. package/dist/internal/scheduler/export.d.ts.map +1 -0
  9. package/dist/internal/scheduler/export.js +382 -0
  10. package/dist/internal/scheduler/export.js.map +1 -0
  11. package/dist/internal/scheduler/field-rules.d.ts +17 -0
  12. package/dist/internal/scheduler/field-rules.d.ts.map +1 -0
  13. package/dist/internal/scheduler/field-rules.js +27 -0
  14. package/dist/internal/scheduler/field-rules.js.map +1 -0
  15. package/dist/internal/scheduler/fields.d.ts +44 -0
  16. package/dist/internal/scheduler/fields.d.ts.map +1 -0
  17. package/dist/internal/scheduler/fields.js +190 -0
  18. package/dist/internal/scheduler/fields.js.map +1 -0
  19. package/dist/internal/scheduler/layout.d.ts +71 -0
  20. package/dist/internal/scheduler/layout.d.ts.map +1 -0
  21. package/dist/internal/scheduler/layout.js +145 -0
  22. package/dist/internal/scheduler/layout.js.map +1 -0
  23. package/dist/internal/scheduler/occurrences.d.ts +22 -0
  24. package/dist/internal/scheduler/occurrences.d.ts.map +1 -0
  25. package/dist/internal/scheduler/occurrences.js +89 -0
  26. package/dist/internal/scheduler/occurrences.js.map +1 -0
  27. package/dist/internal/scheduler/resources.d.ts +97 -0
  28. package/dist/internal/scheduler/resources.d.ts.map +1 -0
  29. package/dist/internal/scheduler/resources.js +215 -0
  30. package/dist/internal/scheduler/resources.js.map +1 -0
  31. package/dist/internal/scheduler/rules.d.ts +23 -0
  32. package/dist/internal/scheduler/rules.d.ts.map +1 -0
  33. package/dist/internal/scheduler/rules.js +81 -0
  34. package/dist/internal/scheduler/rules.js.map +1 -0
  35. package/dist/internal/scheduler/store.d.ts +76 -0
  36. package/dist/internal/scheduler/store.d.ts.map +1 -0
  37. package/dist/internal/scheduler/store.js +33 -0
  38. package/dist/internal/scheduler/store.js.map +1 -0
  39. package/dist/internal/scheduler/time.d.ts +25 -0
  40. package/dist/internal/scheduler/time.d.ts.map +1 -0
  41. package/dist/internal/scheduler/time.js +69 -0
  42. package/dist/internal/scheduler/time.js.map +1 -0
  43. package/dist/internal/scheduler/timeline.d.ts +24 -0
  44. package/dist/internal/scheduler/timeline.d.ts.map +1 -0
  45. package/dist/internal/scheduler/timeline.js +52 -0
  46. package/dist/internal/scheduler/timeline.js.map +1 -0
  47. package/dist/internal/scheduler/types.d.ts +63 -0
  48. package/dist/internal/scheduler/types.d.ts.map +1 -0
  49. package/dist/internal/scheduler/types.js +19 -0
  50. package/dist/internal/scheduler/types.js.map +1 -0
  51. package/dist/internal/scheduler/views.d.ts +36 -0
  52. package/dist/internal/scheduler/views.d.ts.map +1 -0
  53. package/dist/internal/scheduler/views.js +117 -0
  54. package/dist/internal/scheduler/views.js.map +1 -0
  55. package/dist/internal/timeline/virtual.d.ts +14 -0
  56. package/dist/internal/timeline/virtual.d.ts.map +1 -0
  57. package/dist/internal/timeline/virtual.js +45 -0
  58. package/dist/internal/timeline/virtual.js.map +1 -0
  59. package/dist/recurrence-editor/RecurrenceEditor.d.ts +75 -0
  60. package/dist/recurrence-editor/RecurrenceEditor.d.ts.map +1 -0
  61. package/dist/recurrence-editor/RecurrenceEditor.js +192 -0
  62. package/dist/recurrence-editor/RecurrenceEditor.js.map +1 -0
  63. package/dist/scheduler/Scheduler.d.ts +5 -0
  64. package/dist/scheduler/Scheduler.d.ts.map +1 -0
  65. package/dist/scheduler/Scheduler.js +1095 -0
  66. package/dist/scheduler/Scheduler.js.map +1 -0
  67. package/dist/scheduler/context-menu.d.ts +31 -0
  68. package/dist/scheduler/context-menu.d.ts.map +1 -0
  69. package/dist/scheduler/context-menu.js +137 -0
  70. package/dist/scheduler/context-menu.js.map +1 -0
  71. package/dist/scheduler/context.d.ts +85 -0
  72. package/dist/scheduler/context.d.ts.map +1 -0
  73. package/dist/scheduler/context.js +17 -0
  74. package/dist/scheduler/context.js.map +1 -0
  75. package/dist/scheduler/date-popup.d.ts +14 -0
  76. package/dist/scheduler/date-popup.d.ts.map +1 -0
  77. package/dist/scheduler/date-popup.js +14 -0
  78. package/dist/scheduler/date-popup.js.map +1 -0
  79. package/dist/scheduler/drag.d.ts +28 -0
  80. package/dist/scheduler/drag.d.ts.map +1 -0
  81. package/dist/scheduler/drag.js +551 -0
  82. package/dist/scheduler/drag.js.map +1 -0
  83. package/dist/scheduler/editor.d.ts +42 -0
  84. package/dist/scheduler/editor.d.ts.map +1 -0
  85. package/dist/scheduler/editor.js +129 -0
  86. package/dist/scheduler/editor.js.map +1 -0
  87. package/dist/scheduler/export.d.ts +23 -0
  88. package/dist/scheduler/export.d.ts.map +1 -0
  89. package/dist/scheduler/export.js +83 -0
  90. package/dist/scheduler/export.js.map +1 -0
  91. package/dist/scheduler/families.d.ts +63 -0
  92. package/dist/scheduler/families.d.ts.map +1 -0
  93. package/dist/scheduler/families.js +7 -0
  94. package/dist/scheduler/families.js.map +1 -0
  95. package/dist/scheduler/grouping.d.ts +21 -0
  96. package/dist/scheduler/grouping.d.ts.map +1 -0
  97. package/dist/scheduler/grouping.js +155 -0
  98. package/dist/scheduler/grouping.js.map +1 -0
  99. package/dist/scheduler/interact.d.ts +84 -0
  100. package/dist/scheduler/interact.d.ts.map +1 -0
  101. package/dist/scheduler/interact.js +459 -0
  102. package/dist/scheduler/interact.js.map +1 -0
  103. package/dist/scheduler/list.d.ts +3 -0
  104. package/dist/scheduler/list.d.ts.map +1 -0
  105. package/dist/scheduler/list.js +109 -0
  106. package/dist/scheduler/list.js.map +1 -0
  107. package/dist/scheduler/locale.d.ts +82 -0
  108. package/dist/scheduler/locale.d.ts.map +1 -0
  109. package/dist/scheduler/locale.js +80 -0
  110. package/dist/scheduler/locale.js.map +1 -0
  111. package/dist/scheduler/model.d.ts +60 -0
  112. package/dist/scheduler/model.d.ts.map +1 -0
  113. package/dist/scheduler/model.js +107 -0
  114. package/dist/scheduler/model.js.map +1 -0
  115. package/dist/scheduler/popup-node.d.ts +4 -0
  116. package/dist/scheduler/popup-node.d.ts.map +1 -0
  117. package/dist/scheduler/popup-node.js +174 -0
  118. package/dist/scheduler/popup-node.js.map +1 -0
  119. package/dist/scheduler/popups.d.ts +51 -0
  120. package/dist/scheduler/popups.d.ts.map +1 -0
  121. package/dist/scheduler/popups.js +70 -0
  122. package/dist/scheduler/popups.js.map +1 -0
  123. package/dist/scheduler/print.d.ts +3 -0
  124. package/dist/scheduler/print.d.ts.map +1 -0
  125. package/dist/scheduler/print.js +73 -0
  126. package/dist/scheduler/print.js.map +1 -0
  127. package/dist/scheduler/registry-lazy.d.ts +6 -0
  128. package/dist/scheduler/registry-lazy.d.ts.map +1 -0
  129. package/dist/scheduler/registry-lazy.js +59 -0
  130. package/dist/scheduler/registry-lazy.js.map +1 -0
  131. package/dist/scheduler/registry-static.d.ts +5 -0
  132. package/dist/scheduler/registry-static.d.ts.map +1 -0
  133. package/dist/scheduler/registry-static.js +12 -0
  134. package/dist/scheduler/registry-static.js.map +1 -0
  135. package/dist/scheduler/timeline.d.ts +3 -0
  136. package/dist/scheduler/timeline.d.ts.map +1 -0
  137. package/dist/scheduler/timeline.js +214 -0
  138. package/dist/scheduler/timeline.js.map +1 -0
  139. package/dist/scheduler/tooltip.d.ts +13 -0
  140. package/dist/scheduler/tooltip.d.ts.map +1 -0
  141. package/dist/scheduler/tooltip.js +148 -0
  142. package/dist/scheduler/tooltip.js.map +1 -0
  143. package/dist/scheduler/types.d.ts +947 -0
  144. package/dist/scheduler/types.d.ts.map +1 -0
  145. package/dist/scheduler/types.js +5 -0
  146. package/dist/scheduler/types.js.map +1 -0
  147. package/dist/scheduler/views.d.ts +69 -0
  148. package/dist/scheduler/views.d.ts.map +1 -0
  149. package/dist/scheduler/views.js +304 -0
  150. package/dist/scheduler/views.js.map +1 -0
  151. package/dist/scheduler.css +2520 -0
  152. package/dist/scheduler.d.ts +11 -0
  153. package/dist/scheduler.d.ts.map +1 -0
  154. package/dist/scheduler.js +14 -0
  155. package/dist/scheduler.js.map +1 -0
  156. package/package.json +54 -4
@@ -0,0 +1,1095 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ // Scheduler. It follows the Data Grid state model:
4
+ // options props are re-applied when they change, user actions fire
5
+ // before / after pairs that cancel with `preventDefault()`, `ref` receives
6
+ // the `SchedulerApi`, and the React layer reads the per-instance store
7
+ // through narrow `useSyncExternalStore` selectors. Events are instants laid
8
+ // out in the wall time of `timeZone`; the server renders a view only with
9
+ // `date`, `view` and an explicit `timeZone`, and today, the current time
10
+ // marker and the host zone are client-only.
11
+ import { Suspense, use, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
12
+ import { peekViews, preloadViews, readViews } from '#scheduler-views';
13
+ import { formatMessage, fromDays, intlSpaces as n, toPlainDate } from '@salmonui/core/internal/dates/index';
14
+ import { holdInput, PRESS_EVENTS, replayInput } from '@salmonui/core/internal/held-input';
15
+ import { useHydrated } from '@salmonui/core/internal/hydrated';
16
+ import { useLocale, useLocaleText } from '@salmonui/core/internal/locale';
17
+ import { useTimeZone } from '@salmonui/calendars/internal/picker';
18
+ import { addEvents as addRows, deleteEvent as deleteRows, saveEvent as saveRows } from '../internal/scheduler/crud.js';
19
+ import { instantOf } from '../internal/scheduler/fields.js';
20
+ import { deletedOccurrences, occurrenceAt, occurrencesIn, seriesStarts } from '../internal/scheduler/occurrences.js';
21
+ import { collisions, isSlotAvailable, validateOccurrenceMove, validateSeries } from '../internal/scheduler/rules.js';
22
+ import { createSchedulerStore } from '../internal/scheduler/store.js';
23
+ import { createZoneConverter, DAY_MS, MINUTE_MS, minutesOf } from '../internal/scheduler/time.js';
24
+ import { addMonthsDay, clampDay, navigateDay } from '../internal/scheduler/views.js';
25
+ import { SchedulerContext, useSchedulerSelector } from './context.js';
26
+ import { SCHEDULER_DEFAULT_LOCALE_TEXT } from './locale.js';
27
+ import { buildRecords, dayOf, layoutPage, pageModel, recordContext, resolveOptions, viewEntries } from './model.js';
28
+ import { familyOf } from './families.js';
29
+ import { cx, DayView, Icon, MonthView } from './views.js';
30
+ const loadEditor = () => import('./editor.js');
31
+ const loadDatePopup = () => import('./date-popup.js');
32
+ const loadPopups = () => import('./popups.js');
33
+ // One load per page (a load cache, not render state): the callbacks of every caller run in call order.
34
+ let interactLoad;
35
+ const loadInteract = () => (interactLoad ??= import('./interact.js'));
36
+ // The drag chunk is requested through the interaction chunk (no second import wrapper in the initial JS).
37
+ const loadDrag = () => loadInteract().then((m) => m.drag());
38
+ const loadMenu = () => loadInteract().then((m) => m.menu());
39
+ const loadTooltip = () => loadInteract().then((m) => m.tooltip());
40
+ /** Runs `cb` when the browser is idle (or after 300 ms); returns the cancel function. */
41
+ function onIdle(cb) {
42
+ const win = globalThis;
43
+ if (win.requestIdleCallback) {
44
+ const id = win.requestIdleCallback(cb, { timeout: 2000 });
45
+ return () => win.cancelIdleCallback?.(id);
46
+ }
47
+ const id = setTimeout(cb, 300);
48
+ return () => clearTimeout(id);
49
+ }
50
+ /** A lazy module: requested when idle after mount, at once when `needed`. */
51
+ function useLazy(load, needed, enabled) {
52
+ const [module, setModule] = useState(null);
53
+ useEffect(() => {
54
+ if (module || !enabled)
55
+ return;
56
+ let live = true;
57
+ const fetch = () => void load().then((m) => live && setModule(() => m));
58
+ if (needed)
59
+ fetch();
60
+ const cancel = needed ? null : onIdle(fetch);
61
+ return () => {
62
+ live = false;
63
+ cancel?.();
64
+ };
65
+ }, [load, needed, enabled, module]);
66
+ return module;
67
+ }
68
+ /** Reads the view family modules (suspends while a chunk loads) and renders the family view, grouped when resources are set. */
69
+ function Gate(props) {
70
+ const got = readViews(props.needed);
71
+ const m = 'then' in got ? use(got) : got;
72
+ const View = props.family ? (m[props.family]?.View ?? null) : null;
73
+ return m.resources ? _jsx(m.resources.Grouped, { ...props, View: View }) : View ? _jsx(View, { ...props }) : null;
74
+ }
75
+ const isSource = (data) => !Array.isArray(data) && typeof data?.read === 'function';
76
+ const EMPTY = Object.freeze([]);
77
+ const dayOfInput = (input) => {
78
+ if (input === undefined)
79
+ return null;
80
+ const d = toPlainDate(input);
81
+ return d ? dayOf(d) : null;
82
+ };
83
+ function makeEvent(type, source, fields) {
84
+ const e = {
85
+ type,
86
+ source,
87
+ defaultPrevented: false,
88
+ preventDefault() {
89
+ e.defaultPrevented = true;
90
+ },
91
+ ...fields,
92
+ };
93
+ return e;
94
+ }
95
+ function defaultCreateId(ids) {
96
+ let max = 0;
97
+ let numeric = true;
98
+ for (const id of ids) {
99
+ if (typeof id === 'number')
100
+ max = Math.max(max, id);
101
+ else if (id !== undefined)
102
+ numeric = false;
103
+ }
104
+ if (numeric)
105
+ return max + 1;
106
+ const c = globalThis.crypto;
107
+ return c?.randomUUID ? c.randomUUID() : `event-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
108
+ }
109
+ export function Scheduler(props) {
110
+ const locale = useLocale(props.locale) ?? 'en-US';
111
+ const text = { ...SCHEDULER_DEFAULT_LOCALE_TEXT, ...useLocaleText('scheduler', props.localeText) };
112
+ const t = (key, params) => formatMessage(text[key], params, locale);
113
+ const hydrated = useHydrated();
114
+ const zoneName = useTimeZone(props.timeZone);
115
+ const zone = useMemo(() => (zoneName ? createZoneConverter(zoneName) : null), [zoneName]);
116
+ const zones = useMemo(() => new Map(), []);
117
+ const baseId = useId();
118
+ const id = (part) => `${baseId}${part}`;
119
+ const entries = viewEntries(props.views);
120
+ const remote = isSource(props.data);
121
+ const [store] = useState(() => createSchedulerStore({
122
+ view: props.view ?? entries[0]?.name ?? 'week',
123
+ date: dayOfInput(props.date) ?? NaN,
124
+ rows: Array.isArray(props.data) ? props.data : EMPTY,
125
+ rowsVersion: 0,
126
+ selectedCells: null,
127
+ selectedEventKeys: EMPTY,
128
+ popup: null,
129
+ loading: false,
130
+ pending: EMPTY,
131
+ workHours: EMPTY,
132
+ allDayExpanded: props.allDayRowExpanded ?? false,
133
+ expandedResources: props.expandedResourceIds ?? null,
134
+ inline: null,
135
+ resourceId: props.selectedResourceId,
136
+ }));
137
+ const anyStore = store;
138
+ // Options props are re-applied when they change.
139
+ const prev = useRef({ view: props.view, date: dayOfInput(props.date), data: props.data, allDay: props.allDayRowExpanded, expanded: props.expandedResourceIds, res: props.selectedResourceId });
140
+ useLayoutEffect(() => {
141
+ const p = prev.current;
142
+ const date = dayOfInput(props.date);
143
+ const patch = {};
144
+ if (props.view !== undefined && props.view !== p.view)
145
+ patch['view'] = props.view;
146
+ if (date !== null && date !== p.date)
147
+ patch['date'] = date;
148
+ if (props.data !== p.data && Array.isArray(props.data)) {
149
+ patch['rows'] = props.data;
150
+ patch['rowsVersion'] = store.getSnapshot().rowsVersion + 1;
151
+ }
152
+ if (props.allDayRowExpanded !== undefined && props.allDayRowExpanded !== p.allDay)
153
+ patch['allDayExpanded'] = props.allDayRowExpanded;
154
+ if (props.expandedResourceIds !== undefined && props.expandedResourceIds !== p.expanded)
155
+ patch['expandedResources'] = props.expandedResourceIds;
156
+ if (props.selectedResourceId !== p.res)
157
+ patch['resourceId'] = props.selectedResourceId;
158
+ prev.current = { view: props.view, date, data: props.data, allDay: props.allDayRowExpanded, expanded: props.expandedResourceIds, res: props.selectedResourceId };
159
+ if (Object.keys(patch).length)
160
+ store.set(patch);
161
+ });
162
+ const latest = useRef(props);
163
+ useLayoutEffect(() => {
164
+ latest.current = props;
165
+ hostRef.current = interactHost;
166
+ });
167
+ const viewName = useSchedulerSelector(anyStore, (s) => s.view);
168
+ const anchorState = useSchedulerSelector(anyStore, (s) => s.date);
169
+ const rows = useSchedulerSelector(anyStore, (s) => s.rows);
170
+ const popup = useSchedulerSelector(anyStore, (s) => s.popup);
171
+ const loading = useSchedulerSelector(anyStore, (s) => s.loading);
172
+ const allDayExpanded = useSchedulerSelector(anyStore, (s) => s.allDayExpanded);
173
+ const workOverrides = useSchedulerSelector(anyStore, (s) => s.workHours);
174
+ // Adaptive layout: `true` always; `{ breakpoint }` from the container width after mount.
175
+ const compact = useSchedulerSelector(anyStore, (s) => s.compact);
176
+ const adaptive = props.adaptive === true || (!!props.adaptive && compact === true);
177
+ const breakpoint = typeof props.adaptive === 'object' ? (props.adaptive.breakpoint ?? 640) : null;
178
+ useEffect(() => {
179
+ const el = rootRef.current;
180
+ if (breakpoint === null || !el || typeof ResizeObserver === 'undefined')
181
+ return;
182
+ const ro = new ResizeObserver(([e]) => store.set({ compact: (e?.contentRect.width ?? 0) < breakpoint }));
183
+ ro.observe(el);
184
+ return () => ro.disconnect();
185
+ }, [breakpoint]); // eslint-disable-line react-hooks/exhaustive-deps
186
+ const [reloadToken, setReloadToken] = useState(0);
187
+ const [, setRefresh] = useState(0);
188
+ const entry = entries.find((e) => e.name === viewName) ?? entries[0];
189
+ const opts = resolveOptions(props, entry, locale);
190
+ const today = hydrated && zone ? zone.day(Date.now()) : null;
191
+ const minDay = dayOfInput(props.min);
192
+ const maxDay = dayOfInput(props.max);
193
+ const anchor = Number.isFinite(anchorState) ? anchorState : today;
194
+ const resDefs = props.resources ?? EMPTY;
195
+ const resKey = resDefs.map((r) => `${r.field}${r.multiple ? '*' : ''}`).join();
196
+ const resInfo = useMemo(() => resDefs.map((r) => ({ field: r.field, multiple: !!r.multiple })), [resKey]); // eslint-disable-line react-hooks/exhaustive-deps
197
+ const fieldsKey = JSON.stringify(props.eventFields ?? null);
198
+ const rctx = useMemo(() => (zone ? recordContext(props.eventFields, zone, zones, resInfo) : null), [zone, fieldsKey, zones, resInfo]); // eslint-disable-line react-hooks/exhaustive-deps
199
+ const records = useMemo(() => (rctx ? buildRecords(rows, rctx) : null), [rows, rctx]);
200
+ const page = useMemo(() => (zone && anchor !== null ? pageModel(opts, anchor, zone) : null), [zone, anchor, entry, opts.view.firstDayOfWeek, opts.view.showWeekend, JSON.stringify(opts.view.workDays)]); // eslint-disable-line react-hooks/exhaustive-deps
201
+ const occurrences = useMemo(() => (records && page && zone && rctx ? occurrencesIn(records.records, page.range, { zone, zoneFor: rctx.zoneFor }) : EMPTY), [records, page, zone, rctx]);
202
+ const layout = useMemo(() => (page && zone ? layoutPage(occurrences, opts, page, zone, props, allDayExpanded) : null), [occurrences, page, zone, allDayExpanded, opts.startMinute, opts.endMinute, JSON.stringify(props.eventLayout ?? null), props.autoRowHeight]); // eslint-disable-line react-hooks/exhaustive-deps
203
+ const editingProp = props.editing;
204
+ const editing = typeof editingProp === 'object' ? editingProp : {};
205
+ const editable = !opts.readOnly && editingProp !== false;
206
+ const can = { add: editable && editing.add !== false, edit: editable && editing.edit !== false, delete: editable && editing.delete !== false };
207
+ const quickInfo = props.quickInfo === false ? null : typeof props.quickInfo === 'object' ? props.quickInfo : {};
208
+ const overlapAllowed = props.overlap !== false;
209
+ // Formatters: wall-clock ms formatted with `timeZone: 'UTC'`, so no zone lookup per label.
210
+ const fmt = useMemo(() => {
211
+ // Intl skips undefined options.
212
+ const base = { timeZone: 'UTC', calendar: props.calendar, hourCycle: props.hourCycle };
213
+ const make = (o) => {
214
+ try {
215
+ return new Intl.DateTimeFormat(locale, { ...base, ...o });
216
+ }
217
+ catch {
218
+ return new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', ...o });
219
+ }
220
+ };
221
+ const time = make({ hour: 'numeric', minute: '2-digit' });
222
+ const slot = make({ hour: 'numeric' });
223
+ const weekday = make({ weekday: 'short' });
224
+ const dayNum = make({ day: 'numeric' });
225
+ const full = make({ dateStyle: 'full' });
226
+ const md = make({ month: 'short', day: 'numeric' });
227
+ const dateFmt = make(props.dateFormat ?? { dateStyle: 'medium' });
228
+ // ICU versions (Node on the server, the browser on the client) differ in thin, narrow no-break and
229
+ // no-break spaces; `n` (`intlSpaces`) normalizes them so server and client text match on hydration.
230
+ return {
231
+ time: (w) => n(time.format(w)),
232
+ slot: (w) => n(slot.format(w)),
233
+ weekday: (d) => n(weekday.format(d * DAY_MS)),
234
+ dayNumber: (d) => n(dayNum.format(d * DAY_MS)),
235
+ fullDate: (d) => n(full.format(d * DAY_MS)),
236
+ monthDay: (d) => n(md.format(d * DAY_MS)),
237
+ range: (o) => {
238
+ if (!zone)
239
+ return '';
240
+ if (o.allDay) {
241
+ const s = zone.day(o.start);
242
+ const e = zone.day(o.end - 1);
243
+ return n(s === e ? dateFmt.format(s * DAY_MS) : dateFmt.formatRange(s * DAY_MS, e * DAY_MS));
244
+ }
245
+ const ws = zone.wall(o.start);
246
+ const we = zone.wall(o.end);
247
+ if (Math.floor(ws / DAY_MS) === Math.floor(we / DAY_MS))
248
+ return n(`${time.format(ws)} – ${time.format(we)}`);
249
+ return n(`${dateFmt.format(ws)} ${time.format(ws)} – ${dateFmt.format(we)} ${time.format(we)}`);
250
+ },
251
+ };
252
+ }, [locale, props.calendar, props.hourCycle, JSON.stringify(props.dateFormat ?? null), zone]); // eslint-disable-line react-hooks/exhaustive-deps
253
+ const rangeText = n((() => {
254
+ if (!page || anchor === null)
255
+ return '';
256
+ const first = page.days[0] ?? anchor;
257
+ const last = page.days[page.days.length - 1] ?? anchor;
258
+ try {
259
+ if (page.weeks) {
260
+ const months = Math.max(1, opts.view.interval);
261
+ const f = new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric', timeZone: 'UTC', ...(props.calendar ? { calendar: props.calendar } : {}) });
262
+ return months === 1 ? f.format(anchor * DAY_MS) : f.formatRange(anchor * DAY_MS, addMonthsDay(anchor, months - 1) * DAY_MS);
263
+ }
264
+ const f = new Intl.DateTimeFormat(locale, { ...(props.dateFormat ?? { month: 'short', day: 'numeric', year: 'numeric' }), timeZone: 'UTC', ...(props.calendar ? { calendar: props.calendar } : {}) });
265
+ return first === last ? new Intl.DateTimeFormat(locale, { dateStyle: 'full', timeZone: 'UTC' }).format(first * DAY_MS) : f.formatRange(first * DAY_MS, last * DAY_MS);
266
+ }
267
+ catch {
268
+ return `${fromDays(first)} – ${fromDays(last)}`;
269
+ }
270
+ // ICU versions differ in the spaces around range separators (thin, narrow no-break or plain), so
271
+ // the server (Node) and the browser could print different text: normalize them to plain spaces.
272
+ })());
273
+ // -------------------------------------------------------------------------
274
+ // Remote data: one read per visible range, aborted when superseded or unmounted.
275
+ // -------------------------------------------------------------------------
276
+ const vs = opts.entry.virtualScroll ?? props.virtualScroll;
277
+ const lazyKey = useSchedulerSelector(anyStore, (s) => (typeof vs === 'object' && vs.lazyLoad ? (s.rendered?.key ?? '') : null));
278
+ const rangeKey = page ? `${page.range.start}:${page.range.end}` : '';
279
+ useEffect(() => {
280
+ if (!remote || !page)
281
+ return;
282
+ const source = props.data;
283
+ const ctrl = new AbortController();
284
+ const range = { start: new Date(page.range.start), end: new Date(page.range.end) };
285
+ store.set({ loading: true });
286
+ // The read runs in the interaction chunk (asynchronous either way).
287
+ const req = { range, view: entry.type, signal: ctrl.signal, ...(lazyKey !== null ? { resourceIds: store.getSnapshot().rendered?.ids ?? [] } : {}) };
288
+ void withInteract().then((m) => m.remoteRead(store, latest, source, req));
289
+ return () => ctrl.abort();
290
+ }, [remote, props.data, rangeKey, entry.type, reloadToken, lazyKey]); // eslint-disable-line react-hooks/exhaustive-deps
291
+ const writes = useRef(new Set());
292
+ useEffect(() => {
293
+ const set = writes.current;
294
+ return () => {
295
+ for (const c of set)
296
+ c.abort();
297
+ };
298
+ }, []);
299
+ // -------------------------------------------------------------------------
300
+ // Actions
301
+ // -------------------------------------------------------------------------
302
+ const rootRef = useRef(null);
303
+ const crudCtx = () => {
304
+ if (!rctx || !zone)
305
+ return null;
306
+ const p = latest.current;
307
+ const ed = typeof p.editing === 'object' ? p.editing : {};
308
+ const idOf = (r) => r[rctx.fields.id];
309
+ // Ids made in one write count for the next row of the same batch (paste, import).
310
+ const made = [];
311
+ const createId = (r) => {
312
+ const v = ed.createId ? ed.createId(r) : defaultCreateId([...store.getSnapshot().rows.map(idOf), ...made]);
313
+ made.push(v);
314
+ return v;
315
+ };
316
+ return { ...rctx, resourceInfo: resInfo, idOf, createId };
317
+ };
318
+ const currentRecords = () => (rctx ? buildRecords(store.getSnapshot().rows, rctx) : null);
319
+ const navigateTo = (view, date, kind, source) => {
320
+ const s = store.getSnapshot();
321
+ const prevDate = Number.isFinite(s.date) ? s.date : (today ?? date);
322
+ const clamped = clampDay(date, minDay, maxDay);
323
+ if (view === s.view && clamped === prevDate)
324
+ return false;
325
+ const p = latest.current;
326
+ if (p.onBeforeNavigate) {
327
+ const e = makeEvent('beforeNavigate', source, { kind, view, date: fromDays(clamped), previousView: s.view, previousDate: fromDays(prevDate) });
328
+ p.onBeforeNavigate(e);
329
+ if (e.defaultPrevented)
330
+ return false;
331
+ }
332
+ // Data Grid model: user actions change the Scheduler state; `view` / `date` props are re-applied only when they change.
333
+ store.set({ view, date: clamped, selectedCells: null, popup: null, rendered: null });
334
+ if (view !== s.view)
335
+ p.onViewChange?.(view, { type: 'viewChange', source, view, previousView: s.view });
336
+ if (clamped !== prevDate)
337
+ p.onDateChange?.(fromDays(clamped), { type: 'dateChange', source, date: fromDays(clamped), previousDate: fromDays(prevDate) });
338
+ return true;
339
+ };
340
+ const navigate = (dir, source) => {
341
+ if (anchor === null)
342
+ return;
343
+ const target = dir === 'today' ? (zone ? zone.day(Date.now()) : anchor) : navigateDay(opts.view, anchor, dir === 'next' ? 1 : -1);
344
+ navigateTo(viewName, target, 'date', source);
345
+ };
346
+ const openPopup = (next, row, start, end, source) => {
347
+ const p = latest.current;
348
+ if (p.onBeforePopupOpen) {
349
+ const e = makeEvent('beforePopupOpen', source, { popup: next.kind, row, start: start === null ? null : new Date(start), end: end === null ? null : new Date(end) });
350
+ p.onBeforePopupOpen(e);
351
+ if (e.defaultPrevented)
352
+ return false;
353
+ }
354
+ store.set({ popup: next });
355
+ return true;
356
+ };
357
+ const closePopup = (source = 'api') => {
358
+ const cur = store.getSnapshot().popup;
359
+ if (!cur)
360
+ return;
361
+ store.set({ popup: null });
362
+ const occ = cur.key ? findOccurrence(cur.key) : null;
363
+ latest.current.onPopupClose?.({ type: 'popupClose', source, popup: cur.kind, row: occ?.event.row ?? null });
364
+ const rf = cur.returnFocus;
365
+ if (rf && rf.isConnected)
366
+ requestAnimationFrame(() => rf.focus());
367
+ };
368
+ const findOccurrence = (key) => {
369
+ const recs = currentRecords();
370
+ if (!recs || !zone || !rctx)
371
+ return null;
372
+ const at = key.lastIndexOf('@');
373
+ const idText = at > 0 ? key.slice(0, at) : key;
374
+ const rec = recs.records.find((r) => String(r.id) === idText);
375
+ if (!rec)
376
+ return null;
377
+ if (at > 0 && rec.recurrenceRule)
378
+ return occurrenceAt(rec, Number(key.slice(at + 1)), { zone, zoneFor: rctx.zoneFor });
379
+ return { key: idText, eventId: rec.id, start: rec.start, end: rec.end, allDay: rec.allDay, generated: false, seriesId: rec.recurrenceId, event: rec };
380
+ };
381
+ /** Applies a write set: local copy, after-event, remote write with pending state and revert. */
382
+ const commit = (action, set, scope, source) => {
383
+ const before = store.getSnapshot().rows;
384
+ store.set((s) => ({ rows: set.rows, rowsVersion: s.rowsVersion + 1 }));
385
+ const p = latest.current;
386
+ if (action === 'add')
387
+ p.onAdd?.({ type: 'add', source, rows: set.added, data: set.rows });
388
+ else if (action === 'save')
389
+ p.onSave?.({ type: 'save', source, added: set.added, changed: set.changed.map((c) => c.row), deleted: set.deleted, scope, data: set.rows });
390
+ else
391
+ p.onDelete?.({ type: 'delete', source, deleted: set.deleted, changed: set.changed.map((c) => c.row), scope, data: set.rows });
392
+ const src = isSource(p.data) ? p.data : null;
393
+ if (!src?.write)
394
+ return { status: 'applied', rows: [...set.added, ...set.changed.map((c) => c.row)] };
395
+ // The write itself runs in the interaction chunk (asynchronous either way); the controller exists now, so an unmount aborts it.
396
+ const ctrl = new AbortController();
397
+ writes.current.add(ctrl);
398
+ void withInteract().then((m) => m.remoteWrite({ store, latest, writes: writes.current, ctx: crudCtx(), src, set, action, before, ctrl }));
399
+ return { status: 'pending', rows: [...set.added, ...set.changed.map((c) => c.row)] };
400
+ };
401
+ const overlapCheck = (row, start, end, excludeId, excludeOccurrenceStart, source, resources) => {
402
+ const recs = currentRecords();
403
+ if (!recs || !zone || !rctx)
404
+ return true;
405
+ const hits = collisions(recs.records, { start, end, excludeId, excludeOccurrenceStart, resources }, { zone, zoneFor: rctx.zoneFor }, latest.current.overlap === false);
406
+ if (!hits.length)
407
+ return true;
408
+ const p = latest.current;
409
+ const e = makeEvent('overlap', source, { row, conflicts: hits.map((h) => h.event.row) });
410
+ p.onOverlap?.(e);
411
+ if (!e.defaultPrevented)
412
+ store.set({ popup: { kind: 'overlapAlert', message: hits.some((h) => h.event.block) ? t('blockedMessage') : t('overlapMessage'), returnFocus: globalThis.document?.activeElement ?? null } });
413
+ return false;
414
+ };
415
+ const doAdd = (newRows, source) => {
416
+ const ctx = crudCtx();
417
+ if (!ctx)
418
+ return { status: 'rejected', rows: [], reason: 'unresolved time zone' };
419
+ const p = latest.current;
420
+ for (const r of newRows) {
421
+ const rec = buildRecords([r], ctx).records[0];
422
+ if (rec && !overlapCheck(r, rec.start, rec.end, undefined, undefined, source, rec.resources))
423
+ return { status: 'rejected', rows: [], reason: 'overlap' };
424
+ }
425
+ if (p.onBeforeAdd) {
426
+ const e = makeEvent('beforeAdd', source, { rows: newRows });
427
+ p.onBeforeAdd(e);
428
+ if (e.defaultPrevented)
429
+ return { status: 'cancelled', rows: [] };
430
+ }
431
+ return commit('add', addRows(store.getSnapshot().rows, newRows, ctx), 'series', source);
432
+ };
433
+ const doSave = (target, changes, scopeIn, source) => {
434
+ const ctx = crudCtx();
435
+ const recs = currentRecords();
436
+ if (!ctx || !recs || !zone)
437
+ return { status: 'rejected', rows: [] };
438
+ const rec = recs.byId.get(target.eventId) ?? target.event;
439
+ const p = latest.current;
440
+ const ed = typeof p.editing === 'object' ? p.editing : {};
441
+ let scope = scopeIn;
442
+ const series = rec.recurrenceRule && rec.recurrenceId === undefined;
443
+ const start = changes.start ?? target.start;
444
+ const end = changes.end ?? target.end;
445
+ if (ed.validateRecurrence !== false) {
446
+ const rule = changes.recurrenceRule === undefined ? rec.recurrenceRule : changes.recurrenceRule;
447
+ const problem = (rule && scope !== 'occurrence' ? validateSeries(rule, start, end) : null) ?? (series && scope === 'occurrence' && target.generated ? validateOccurrenceMove(rec, target.start, start, end, { zone, zoneFor: ctx.zoneFor }) : null);
448
+ if (problem) {
449
+ store.set({ popup: { kind: 'validationAlert', message: t(problem), returnFocus: globalThis.document?.activeElement ?? null } });
450
+ return { status: 'rejected', rows: [], reason: problem };
451
+ }
452
+ }
453
+ const draft = { ...rec.row };
454
+ if (!overlapCheck(draft, start, end, rec.id, target.generated ? target.start : undefined, source, changes.resources ?? rec.resources))
455
+ return { status: 'rejected', rows: [], reason: 'overlap' };
456
+ if (p.onBeforeSave) {
457
+ const e = makeEvent('beforeSave', source, {
458
+ row: draft,
459
+ previous: rec.row,
460
+ scope,
461
+ occurrenceStart: target.generated ? new Date(target.start) : null,
462
+ setScope(s) {
463
+ scope = s;
464
+ e.scope = s;
465
+ },
466
+ });
467
+ p.onBeforeSave(e);
468
+ if (e.defaultPrevented)
469
+ return { status: 'cancelled', rows: [] };
470
+ }
471
+ const children = recs.children.get(series ? rec.id : (rec.recurrenceId ?? rec.id)) ?? [];
472
+ const set = saveRows(store.getSnapshot().rows, { event: rec, occurrenceStart: series && target.generated ? target.start : undefined }, changes, scope, children, ctx);
473
+ return commit('save', set, scope, source);
474
+ };
475
+ const doDelete = (target, scopeIn, source) => {
476
+ const ctx = crudCtx();
477
+ const recs = currentRecords();
478
+ if (!ctx || !recs)
479
+ return { status: 'rejected', rows: [] };
480
+ const rec = recs.byId.get(target.eventId) ?? target.event;
481
+ let scope = scopeIn;
482
+ const p = latest.current;
483
+ if (p.onBeforeDelete) {
484
+ const e = makeEvent('beforeDelete', source, {
485
+ rows: [rec.row],
486
+ scope,
487
+ occurrenceStart: target.generated ? new Date(target.start) : null,
488
+ setScope(s) {
489
+ scope = s;
490
+ e.scope = s;
491
+ },
492
+ });
493
+ p.onBeforeDelete(e);
494
+ if (e.defaultPrevented)
495
+ return { status: 'cancelled', rows: [] };
496
+ }
497
+ const seriesId = rec.recurrenceId ?? rec.id;
498
+ const series = recs.byId.get(seriesId);
499
+ const children = recs.children.get(seriesId) ?? [];
500
+ const set = deleteRows(store.getSnapshot().rows, { event: rec, occurrenceStart: target.generated ? target.start : undefined }, scope, children, rec.recurrenceId !== undefined ? series : undefined, ctx);
501
+ return commit('delete', set, scope, source);
502
+ };
503
+ const isRecurring = (o) => o.seriesId !== undefined;
504
+ const openEditorFor = (o, cells, mode, source, scope = 'series', title = '', rule) => {
505
+ const p = latest.current;
506
+ const ed = typeof p.editing === 'object' ? p.editing : {};
507
+ if (ed.dialog === false)
508
+ return;
509
+ const start = o ? o.start : (cells?.start ?? 0);
510
+ const end = o ? o.end : (cells?.end ?? 0);
511
+ openPopup({ kind: 'editor', key: o?.key, cells: cells ?? undefined, mode, payload: { scope, title, rule }, returnFocus: globalThis.document?.activeElement ?? null }, o?.event.row ?? null, start, end, source);
512
+ };
513
+ const requestEdit = (o, source) => {
514
+ if (!can.edit || o.event.readOnly || o.event.block)
515
+ return;
516
+ const ed = typeof latest.current.editing === 'object' ? latest.current.editing : {};
517
+ if (isRecurring(o) && ed.recurrencePrompt !== false) {
518
+ openPopup({ kind: 'recurrenceAlert', key: o.key, action: 'edit', returnFocus: globalThis.document?.activeElement ?? null }, o.event.row, o.start, o.end, source);
519
+ return;
520
+ }
521
+ openEditorFor(o, null, isRecurring(o) ? 'editSeries' : 'edit', source, 'series');
522
+ };
523
+ const requestDelete = (o, source) => {
524
+ if (!can.delete || o.event.readOnly)
525
+ return;
526
+ const ed = typeof latest.current.editing === 'object' ? latest.current.editing : {};
527
+ if (isRecurring(o) && ed.recurrencePrompt !== false)
528
+ openPopup({ kind: 'recurrenceAlert', key: o.key, action: 'delete', returnFocus: globalThis.document?.activeElement ?? null }, o.event.row, o.start, o.end, source);
529
+ else
530
+ openPopup({ kind: 'deleteAlert', key: o.key, returnFocus: globalThis.document?.activeElement ?? null }, o.event.row, o.start, o.end, source);
531
+ };
532
+ const newRowFor = (cells, title) => {
533
+ const f = rctx?.fields;
534
+ const p = latest.current;
535
+ const row = {};
536
+ if (f) {
537
+ for (const [role, cfg] of Object.entries(p.eventFields ?? {})) {
538
+ if (typeof cfg === 'object' && cfg.defaultValue !== undefined)
539
+ row[f[role] ?? role] = cfg.defaultValue;
540
+ }
541
+ row[f.title] = title || row[f.title] || '';
542
+ row[f.start] = new Date(cells.start);
543
+ row[f.end] = new Date(cells.end);
544
+ row[f.allDay] = cells.allDay;
545
+ putRes(row, cells.resources);
546
+ }
547
+ return row;
548
+ };
549
+ /** Writes resource ids: an array for `multiple` resources, else the first id. */
550
+ const putRes = (row, src) => {
551
+ for (const x of resInfo) {
552
+ const ids = src?.[x.field];
553
+ if (ids?.length)
554
+ row[x.field] = x.multiple ? [...ids] : ids[0];
555
+ }
556
+ };
557
+ const refocus = (key, host) => {
558
+ requestAnimationFrame(() => {
559
+ const el = (key ? rootRef.current?.querySelector(`.salmon-scheduler__event[data-key="${CSS.escape(key)}"]`) : null) ?? host;
560
+ if (el?.isConnected)
561
+ el.focus({ preventScroll: true });
562
+ });
563
+ };
564
+ const actions = {
565
+ cellClick(start, end, allDay, element, source, double, res) {
566
+ const p = latest.current;
567
+ const e = makeEvent(double ? 'cellDoubleClick' : 'cellClick', source, { start: new Date(start), end: new Date(end), allDay, element });
568
+ (double ? p.onCellDoubleClick : p.onCellClick)?.(e);
569
+ const sel = store.getSnapshot().selectedCells;
570
+ const keep = sel && sel.allDay === allDay && sel.group === res?.key && start >= sel.start && start < sel.end && !double;
571
+ const cells = keep && sel ? sel : { start, end, allDay, group: res?.key, resources: res?.path };
572
+ if (!keep) {
573
+ store.set({ selectedCells: cells, selectedEventKeys: EMPTY });
574
+ p.onCellSelectionChange?.({ type: 'cellSelectionChange', source, start: new Date(cells.start), end: new Date(cells.end), allDay });
575
+ }
576
+ if (e.defaultPrevented || !can.add)
577
+ return;
578
+ if (double)
579
+ openEditorFor(null, cells, 'add', source);
580
+ else if (quickInfo && element && !(typeof p.editing === 'object' && p.editing.inline))
581
+ openPopup({ kind: 'quickInfo', cells, anchor: element, returnFocus: element }, null, cells.start, cells.end, source);
582
+ },
583
+ cellSelect(start, end, allDay, extend, res) {
584
+ const p = latest.current;
585
+ const cur = store.getSnapshot().selectedCells;
586
+ const g = { group: res?.key, resources: res?.path };
587
+ const cells = extend && cur && cur.allDay === allDay && cur.group === g.group ? { start: Math.min(cur.start, start), end: Math.max(cur.end, end), allDay, ...g } : { start, end, allDay, ...g };
588
+ store.set({ selectedCells: cells, selectedEventKeys: EMPTY });
589
+ p.onCellSelectionChange?.({ type: 'cellSelectionChange', source: 'pointer', start: new Date(cells.start), end: new Date(cells.end), allDay });
590
+ const qi = typeof p.quickInfo === 'object' ? p.quickInfo : null;
591
+ const el = rootRef.current?.querySelector(`[data-cell-start="${cells.start}"]${allDay ? '[data-all-day-cell]' : ':not([data-all-day-cell])'}${res ? `[data-resource="${CSS.escape(res.key)}"]` : ''}`) ?? null;
592
+ if (qi?.onSelectionEnd && can.add && el)
593
+ openPopup({ kind: 'quickInfo', cells, anchor: el, returnFocus: el }, null, cells.start, cells.end, 'pointer');
594
+ },
595
+ eventClick(o, element, source, double, additive, selKey) {
596
+ const occ = o;
597
+ const p = latest.current;
598
+ const e = makeEvent(double ? 'eventDoubleClick' : 'eventClick', source, { row: occ.event.row, start: new Date(occ.start), end: new Date(occ.end), element });
599
+ (double ? p.onEventDoubleClick : p.onEventClick)?.(e);
600
+ const k = selKey ?? occ.key;
601
+ const ix = interactRef.current;
602
+ if (ix)
603
+ ix.selectEvent(interactHost(), occ, k, additive, source);
604
+ else
605
+ void withInteract().then((m) => m.selectEvent(interactHost(), occ, k, additive, source));
606
+ if (e.defaultPrevented)
607
+ return;
608
+ if (double)
609
+ requestEdit(occ, source);
610
+ else if (quickInfo && element)
611
+ openPopup({ kind: 'quickInfo', key: occ.key, anchor: element, returnFocus: element }, occ.event.row, occ.start, occ.end, source);
612
+ },
613
+ moreClick(day, element, source) {
614
+ const p = latest.current;
615
+ const dayOcc = occurrences.filter((o) => zone && zone.day(o.start) <= day && zone.day(Math.max(o.start, o.end - 1)) >= day);
616
+ if (p.onMoreEventsClick) {
617
+ let target = null;
618
+ const e = makeEvent('moreEventsClick', source, { date: fromDays(day), rows: dayOcc.map((o) => o.event.row), navigate: (v) => void (target = v) });
619
+ p.onMoreEventsClick(e);
620
+ if (target) {
621
+ navigateTo(target, day, 'view', source);
622
+ return;
623
+ }
624
+ if (e.defaultPrevented)
625
+ return;
626
+ }
627
+ if (element)
628
+ openPopup({ kind: 'moreEvents', day, anchor: element, returnFocus: element }, null, null, null, source);
629
+ },
630
+ goToDay(day, source) {
631
+ const dayEntry = entries.find((e) => e.type === 'day');
632
+ navigateTo(dayEntry?.name ?? viewName, day, dayEntry ? 'view' : 'date', source);
633
+ },
634
+ toggleAllDay() {
635
+ const next = !store.getSnapshot().allDayExpanded;
636
+ const p = latest.current;
637
+ if (p.allDayRowExpanded === undefined)
638
+ store.set({ allDayExpanded: next });
639
+ p.onAllDayRowExpandedChange?.(next);
640
+ },
641
+ inlineStart(target, text) {
642
+ const ed = typeof latest.current.editing === 'object' ? latest.current.editing : {};
643
+ if (!ed.inline)
644
+ return false;
645
+ if ('key' in target) {
646
+ const occ = findOccurrence(target.key);
647
+ if (!occ || !can.edit || occ.event.readOnly || occ.event.block)
648
+ return false;
649
+ store.set({ inline: { key: target.key, text }, popup: null });
650
+ return true;
651
+ }
652
+ if (!can.add)
653
+ return false;
654
+ store.set({ inline: { cells: target.cells, text }, popup: null });
655
+ return true;
656
+ },
657
+ inlineCommit(text, host) {
658
+ const cur = store.getSnapshot().inline;
659
+ if (!cur)
660
+ return;
661
+ store.set({ inline: null });
662
+ if (cur.cells) {
663
+ if (text.trim())
664
+ doAdd([newRowFor(cur.cells, text)], 'keyboard');
665
+ }
666
+ else if (cur.key) {
667
+ const occ = findOccurrence(cur.key);
668
+ // A title edit of a series occurrence changes the series.
669
+ if (occ && text !== occ.event.title)
670
+ doSave(occ.generated ? { ...occ, start: occ.event.start, end: occ.event.end, generated: false } : occ, { title: text }, 'series', 'keyboard');
671
+ }
672
+ refocus(cur.key, host);
673
+ },
674
+ inlineCancel(host) {
675
+ const cur = store.getSnapshot().inline;
676
+ if (!cur)
677
+ return;
678
+ store.set({ inline: null });
679
+ refocus(cur.key, host);
680
+ },
681
+ hover(part, o, start, element) {
682
+ const h = latest.current.onHover;
683
+ if (!h)
684
+ return;
685
+ h({ type: 'hover', source: 'pointer', part, row: o?.event.row ?? null, start: start === null ? null : new Date(start), element });
686
+ },
687
+ };
688
+ // Work hours overrides feed the cell context.
689
+ const workOverride = (day) => {
690
+ const o = workOverrides.find((w) => w.day === day);
691
+ return o ? { start: o.start, end: o.end } : null;
692
+ };
693
+ const [handle] = useState(() => ({ current: {} }));
694
+ const ctxValue = {
695
+ store: anyStore,
696
+ props: props,
697
+ opts: opts,
698
+ zone: zone,
699
+ locale,
700
+ text,
701
+ t,
702
+ fmt,
703
+ actions,
704
+ view: entry.type,
705
+ today,
706
+ editable,
707
+ cellProps: (c) => {
708
+ if (c.part === 'workCell') {
709
+ const w = workOverride(dayOf(c.date));
710
+ if (w && zone) {
711
+ const m = (zone.wall(c.start.getTime()) - dayOf(c.date) * DAY_MS) / MINUTE_MS;
712
+ const work = m >= w.start && m < w.end;
713
+ const base = latest.current.getCellProps?.({ ...c, work });
714
+ return { ...base, 'data-work': work ? '' : undefined, 'data-work-override': '' };
715
+ }
716
+ }
717
+ return latest.current.getCellProps?.(c);
718
+ },
719
+ id,
720
+ handle,
721
+ adaptive,
722
+ root: rootRef,
723
+ scrollStart: (el) => scrollToTime(props.scrollTime, el),
724
+ };
725
+ // -------------------------------------------------------------------------
726
+ // Scroll to the work start: the time grid calls ctx.scrollStart
727
+ // when it mounts and on view change (views.tsx DayView).
728
+ // -------------------------------------------------------------------------
729
+ const scrollToTime = (time, el = rootRef.current?.querySelector('.salmon-scheduler__time-scroll')) => {
730
+ if (el)
731
+ el.scrollTop = ((minutesOf(time, opts.workStart) - opts.startMinute) / (opts.endMinute - opts.startMinute)) * el.scrollHeight;
732
+ };
733
+ // -------------------------------------------------------------------------
734
+ // SchedulerApi (-08, -22, -32, -34, -37, -43, -47, -49, -51, -78, -09)
735
+ // -------------------------------------------------------------------------
736
+ const info = (o) => ({ row: o.event.row, id: o.eventId, start: new Date(o.start), end: new Date(o.end), allDay: o.allDay, seriesId: o.seriesId ?? null, occurrenceStart: o.generated ? new Date(o.start) : null });
737
+ const occurrenceFromTarget = (id, occurrenceStart) => findOccurrence(occurrenceStart ? `${String(id)}@${occurrenceStart.getTime()}` : String(id));
738
+ // Resource methods live in the resources chunk (loaded whenever `resources` is set).
739
+ const res = (name, ...args) => {
740
+ const m = peekViews().resources;
741
+ return m?.[name]?.({ store: anyStore, props: latest.current, handle }, ...args);
742
+ };
743
+ // Interaction chunk: loaded on the first focus or pointer down.
744
+ const interactRef = useRef(null);
745
+ // Set by the tooltip chunk.
746
+ const closeTip = useRef(null);
747
+ const withInteract = () => loadInteract().then((m) => {
748
+ interactRef.current = m;
749
+ return m;
750
+ });
751
+ const preloadInteract = () => {
752
+ if (!interactRef.current)
753
+ void withInteract();
754
+ };
755
+ // Drag chunk: loaded on the first pointer down; a drag group loads it when idle.
756
+ const dragRef = useRef(null);
757
+ const withDrag = () => loadDrag().then((m) => (dragRef.current = m));
758
+ const getHost = () => hostRef.current();
759
+ const group = props.dragOptions?.group;
760
+ const dragModule = useLazy(loadDrag, false, hydrated && !!group);
761
+ useEffect(() => dragModule?.join(group, rootRef.current, getHost), [dragModule, group]); // eslint-disable-line react-hooks/exhaustive-deps
762
+ const interactHost = () => ({
763
+ opts,
764
+ can,
765
+ fmt,
766
+ find: findOccurrence,
767
+ save: doSave,
768
+ remove: doDelete,
769
+ store,
770
+ props: latest.current,
771
+ root: rootRef.current,
772
+ occurrences: occurrences,
773
+ records: currentRecords()?.records ?? null,
774
+ rctx,
775
+ range: page?.range ?? null,
776
+ locale,
777
+ views: entries,
778
+ anchor,
779
+ navigateTo: (v, d) => navigateTo(v, d, 'view', 'keyboard'),
780
+ navigate: (d, s = 'keyboard') => navigate(d, s),
781
+ requestDelete: (o) => requestDelete(o, 'keyboard'),
782
+ addEvents: (r) => doAdd(r, 'api'),
783
+ saveRow: (r) => api.saveEvent(r),
784
+ clip,
785
+ });
786
+ const [clip] = useState(() => ({ current: null }));
787
+ const hostRef = useRef(interactHost);
788
+ const selectedIdsKey = props.selectedEventIds === undefined ? null : JSON.stringify(props.selectedEventIds);
789
+ useLayoutEffect(() => {
790
+ if (selectedIdsKey === null)
791
+ return;
792
+ const ids = new Set(JSON.parse(selectedIdsKey).map(String));
793
+ const keys = occurrences.filter((o) => ids.has(String(o.eventId)) || (o.seriesId !== undefined && ids.has(String(o.seriesId)))).map((o) => o.key);
794
+ const cur = store.getSnapshot().selectedEventKeys;
795
+ if (keys.length !== cur.length || keys.some((k, i) => k !== cur[i]))
796
+ store.set({ selectedEventKeys: keys.length ? keys : EMPTY });
797
+ }, [selectedIdsKey, occurrences]); // eslint-disable-line react-hooks/exhaustive-deps
798
+ const api = {
799
+ get element() {
800
+ return rootRef.current;
801
+ },
802
+ navigate: (action) => navigate(action, 'api'),
803
+ setView: (view, date) => navigateTo(view, dayOfInput(date) ?? anchor ?? 0, 'view', 'api'),
804
+ setDate: (date) => {
805
+ const d = dayOfInput(date);
806
+ if (d !== null)
807
+ navigateTo(viewName, d, 'date', 'api');
808
+ },
809
+ getDateRangeText: () => rangeText,
810
+ getViewDates: () => (page?.days ?? []).map(fromDays),
811
+ addEvents: (r) => doAdd(r, 'api'),
812
+ saveEvent: (row, o) => {
813
+ const ctx = crudCtx();
814
+ if (!ctx || !zone)
815
+ return { status: 'rejected', rows: [] };
816
+ const idv = ctx.idOf(row);
817
+ const target = occurrenceFromTarget(idv, o?.occurrenceStart);
818
+ if (!target)
819
+ return { status: 'rejected', rows: [], reason: 'not found' };
820
+ const rec = buildRecords([row], ctx).records[0];
821
+ if (!rec)
822
+ return { status: 'rejected', rows: [], reason: 'invalid row' };
823
+ const changes = { title: rec.title, location: rec.location, description: rec.description, allDay: rec.allDay, start: target.generated ? target.start + (rec.start - target.event.start) : rec.start, end: target.generated ? target.end + (rec.end - target.event.end) : rec.end, recurrenceRule: rec.recurrenceRule ?? null };
824
+ return doSave(target, changes, o?.scope ?? 'series', 'api');
825
+ },
826
+ deleteEvents: (ids, o) => {
827
+ let last = { status: 'rejected', rows: [] };
828
+ for (const i of ids) {
829
+ const target = occurrenceFromTarget(i, o?.occurrenceStart);
830
+ if (target)
831
+ last = doDelete(target, o?.scope ?? 'series', 'api');
832
+ }
833
+ return last;
834
+ },
835
+ openEditor: (target, o) => {
836
+ if (typeof target === 'object') {
837
+ const s = target.start instanceof Date ? target.start.getTime() : zone ? (instantOf(target.start, zone) ?? 0) : 0;
838
+ const e = target.end === undefined ? s + 30 * MINUTE_MS : target.end instanceof Date ? target.end.getTime() : zone ? (instantOf(target.end, zone) ?? s) : s;
839
+ openEditorFor(null, { start: s, end: e, allDay: target.allDay ?? false }, 'add', 'api');
840
+ return;
841
+ }
842
+ const occ = occurrenceFromTarget(target, o?.occurrenceStart);
843
+ if (occ)
844
+ openEditorFor(occ, null, o?.mode ?? 'edit', 'api', o?.mode === 'editOccurrence' ? 'occurrence' : 'series');
845
+ },
846
+ closeEditor: () => {
847
+ if (store.getSnapshot().popup?.kind === 'editor')
848
+ closePopup('api');
849
+ },
850
+ openQuickInfo: (target) => {
851
+ if (typeof target === 'object') {
852
+ const el = rootRef.current?.querySelector(`[data-cell-start="${target.start.getTime()}"]`) ?? rootRef.current;
853
+ if (el)
854
+ openPopup({ kind: 'quickInfo', cells: { start: target.start.getTime(), end: target.end.getTime(), allDay: target.allDay ?? false }, anchor: el, returnFocus: el }, null, target.start.getTime(), target.end.getTime(), 'api');
855
+ return;
856
+ }
857
+ const occ = occurrenceFromTarget(target);
858
+ const el = rootRef.current?.querySelector(`[data-event-id="${String(target)}"]`) ?? null;
859
+ if (occ && el)
860
+ openPopup({ kind: 'quickInfo', key: occ.key, anchor: el, returnFocus: el }, occ.event.row, occ.start, occ.end, 'api');
861
+ },
862
+ closeQuickInfo: () => {
863
+ if (store.getSnapshot().popup?.kind === 'quickInfo')
864
+ closePopup('api');
865
+ },
866
+ openOverlapAlert: () => store.set({ popup: { kind: 'overlapAlert', message: t('overlapMessage') } }),
867
+ closeOverlapAlert: () => {
868
+ if (store.getSnapshot().popup?.kind === 'overlapAlert')
869
+ closePopup('api');
870
+ },
871
+ getEvents: (o) => {
872
+ const recs = currentRecords();
873
+ if (!recs || !zone || !rctx)
874
+ return [];
875
+ if (o?.includeOccurrences === false || (!o?.start && !o?.end && !o?.includeOccurrences))
876
+ return recs.records.filter((r) => (!o?.start || r.end > o.start.getTime()) && (!o?.end || r.start < o.end.getTime())).map((r) => info({ key: String(r.id), eventId: r.id, start: r.start, end: r.end, allDay: r.allDay, generated: false, seriesId: r.recurrenceId, event: r }));
877
+ return occurrencesIn(recs.records, { start: o?.start?.getTime() ?? -8.64e15, end: o?.end?.getTime() ?? 8.64e15 }, { zone, zoneFor: rctx.zoneFor }).map(info);
878
+ },
879
+ getViewEvents: () => occurrences.map(info),
880
+ getEventInfo: (target) => {
881
+ if (typeof target === 'object' && target && 'closest' in target) {
882
+ const key = target.closest('[data-key]')?.getAttribute('data-key');
883
+ const occ = key ? findOccurrence(key) : null;
884
+ return occ ? info(occ) : null;
885
+ }
886
+ const occ = occurrenceFromTarget(target);
887
+ return occ ? info(occ) : null;
888
+ },
889
+ getCellInfo: (target) => {
890
+ const cell = target.closest('[data-cell-start]');
891
+ return cell ? { start: new Date(Number(cell.dataset['cellStart'])), end: new Date(Number(cell.dataset['cellEnd'])), allDay: cell.hasAttribute('data-all-day-cell') } : null;
892
+ },
893
+ getOccurrences: (eventId) => {
894
+ const recs = currentRecords();
895
+ const rec = recs?.byId.get(eventId);
896
+ if (!rec || !zone || !rctx || !rec.recurrenceRule)
897
+ return [];
898
+ const c = { zone, zoneFor: rctx.zoneFor };
899
+ return seriesStarts(rec, { start: rec.start, end: rec.start + 3650 * DAY_MS }, c).map((s) => info(occurrenceAt(rec, s, c)));
900
+ },
901
+ getOccurrencesInRange: (s, e) => {
902
+ const recs = currentRecords();
903
+ if (!recs || !zone || !rctx)
904
+ return [];
905
+ return occurrencesIn(recs.records, { start: s.getTime(), end: e.getTime() }, { zone, zoneFor: rctx.zoneFor }).filter((o) => o.seriesId !== undefined).map(info);
906
+ },
907
+ getDeletedOccurrences: (eventId) => {
908
+ const recs = currentRecords();
909
+ const rec = recs?.byId.get(eventId);
910
+ if (!rec || !zone)
911
+ return [];
912
+ return deletedOccurrences(rec, recs?.children.get(eventId) ?? [], zone).map((x) => new Date(x));
913
+ },
914
+ getBlockEvents: () => (currentRecords()?.records ?? []).filter((r) => r.block).map((r) => r.row),
915
+ isSlotAvailable: (s, e, o) => {
916
+ const recs = currentRecords();
917
+ if (!recs || !zone || !rctx)
918
+ return true;
919
+ return isSlotAvailable(recs.records, { start: s.getTime(), end: e.getTime(), resources: o?.resources, excludeId: o?.excludeId }, { zone, zoneFor: rctx.zoneFor }, latest.current.overlap !== false);
920
+ },
921
+ getSelectedCells: () => {
922
+ const c = store.getSnapshot().selectedCells;
923
+ return c ? { start: new Date(c.start), end: new Date(c.end), allDay: c.allDay } : null;
924
+ },
925
+ setWorkHours: (dates, start, end) => {
926
+ const s = minutesOf(start, 9 * 60);
927
+ const e = minutesOf(end, 18 * 60);
928
+ const days = dates.map(dayOfInput).filter((d) => d !== null);
929
+ store.set((st) => ({ workHours: [...st.workHours.filter((w) => !days.includes(w.day)), ...days.map((day) => ({ day, start: s, end: e }))] }));
930
+ },
931
+ resetWorkHours: (dates) => {
932
+ if (!dates)
933
+ return store.set({ workHours: EMPTY });
934
+ const days = dates.map(dayOfInput);
935
+ store.set((st) => ({ workHours: st.workHours.filter((w) => !days.includes(w.day)) }));
936
+ },
937
+ scrollToTime: (time, o) => {
938
+ const d = dayOfInput(o?.date);
939
+ if (d !== null && page && !page.days.includes(d))
940
+ navigateTo(viewName, d, 'date', 'api');
941
+ requestAnimationFrame(() => scrollToTime(time));
942
+ },
943
+ refresh: () => setRefresh((n) => n + 1),
944
+ reloadEvents: () => setReloadToken((n) => n + 1),
945
+ setLoading: (l) => store.set({ loading: l }),
946
+ getState: () => {
947
+ const s = store.getSnapshot();
948
+ return { view: s.view, date: String(fromDays(Number.isFinite(s.date) ? s.date : (anchor ?? 0))), allDayExpanded: s.allDayExpanded };
949
+ },
950
+ restoreState: (st) => {
951
+ const d = st.date ? dayOfInput(st.date) : null;
952
+ store.set({ ...(st.view ? { view: st.view } : {}), ...(d !== null ? { date: d } : {}), ...(st.allDayExpanded !== undefined ? { allDayExpanded: st.allDayExpanded } : {}) });
953
+ },
954
+ getResource: (id, r) => res('getResource', id, r) ?? null,
955
+ getResources: () => res('getResources') ?? [],
956
+ expandResource: (id) => res('expandResource', id),
957
+ collapseResource: (id) => res('collapseResource', id),
958
+ scrollToResource: (id) => res('scrollToResource', id),
959
+ getRenderedRange: () => res('getRenderedRange') ?? null,
960
+ exportToExcel: (o = {}) => withInteract().then((m) => m.runExport(interactHost(), 'excel', o)),
961
+ exportToCsv: (o = {}) => withInteract().then((m) => m.runExport(interactHost(), 'csv', o)),
962
+ exportToICalendar: (o = {}) => withInteract().then((m) => m.runExport(interactHost(), 'icalendar', o)),
963
+ importICalendar: (source, o = {}) => withInteract().then((m) => m.importICalendar(interactHost(), source, o)),
964
+ copy: () => withInteract().then((m) => m.copy(interactHost(), false)),
965
+ cut: () => withInteract().then((m) => m.copy(interactHost(), true)),
966
+ paste: (target) => withInteract().then((m) => m.paste(interactHost(), target, 'api')),
967
+ closeTooltip: () => closeTip.current?.(),
968
+ print: (o = {}) => loadInteract().then((m) => m.print()).then((m) => m.printScheduler(rootRef.current, latest.current, o)),
969
+ };
970
+ const apiRef = useRef(api);
971
+ apiRef.current = api;
972
+ const [stableApi] = useState(() => {
973
+ const target = {};
974
+ for (const key of Object.keys(api)) {
975
+ if (key === 'element')
976
+ Object.defineProperty(target, 'element', { get: () => apiRef.current.element, enumerable: true });
977
+ else
978
+ target[key] = (...args) => apiRef.current[key](...args);
979
+ }
980
+ return Object.freeze(target);
981
+ });
982
+ useImperativeHandle(props.ref, () => stableApi, [stableApi]);
983
+ const readyFired = useRef(false);
984
+ useEffect(() => {
985
+ if (readyFired.current)
986
+ return;
987
+ readyFired.current = true;
988
+ latest.current.onReady?.(stableApi);
989
+ }, [stableApi]);
990
+ // -------------------------------------------------------------------------
991
+ // Popups
992
+ // -------------------------------------------------------------------------
993
+ const editorModule = useLazy(loadEditor, popup?.kind === 'editor', hydrated && editable && editing.dialog !== false);
994
+ const popups = useLazy(loadPopups, popup !== null, hydrated);
995
+ // View family chunks of the configured views are preloaded when the browser is idle after mount.
996
+ const families = [...new Set([...entries.map((e) => familyOf(e.type)), resDefs.length ? 'resources' : null])].filter(Boolean).sort().join();
997
+ useEffect(() => (families ? onIdle(() => preloadViews(families.split(','))) : undefined), [families]);
998
+ useEffect(() => onIdle(preloadInteract), []); // eslint-disable-line react-hooks/exhaustive-deps
999
+ const [datePopupOpen, setDatePopupOpen] = useState(false);
1000
+ const datePopup = useLazy(loadDatePopup, datePopupOpen, hydrated);
1001
+ const dateButtonRef = useRef(null);
1002
+ const [editorError, setEditorError] = useState(null);
1003
+ // Context menu chunk: idle after mount; a request before it loaded is kept and opened on mount.
1004
+ const [menuAsk, setMenuAsk] = useState(null);
1005
+ const menu = useLazy(loadMenu, menuAsk !== null, hydrated && !!props.contextMenu);
1006
+ const tip = useLazy(loadTooltip, false, hydrated && !!props.tooltip);
1007
+ const askMenu = (e, x, y) => {
1008
+ const el = e.target;
1009
+ if (!menu && props.contextMenu && !e.defaultPrevented && rootRef.current?.contains(el) && el.closest('[data-key],[data-cell-start]')) {
1010
+ e.preventDefault();
1011
+ setMenuAsk({ x, y, target: el });
1012
+ }
1013
+ };
1014
+ const popupNode = popup && hydrated && zone && rctx && popups ? popups.renderPopup({ popup, hydrated, zone, rctx, findOccurrence, popups, quickInfo, can, closePopup, doAdd, newRowFor, store, openEditorFor, requestEdit, requestDelete, occurrences, openPopup, latest, t, doDelete, editorModule, resDefs, editorError, setEditorError, isRecurring, putRes, editing, resInfo, doSave, validateSeries }) : null;
1015
+ // -------------------------------------------------------------------------
1016
+ // Render
1017
+ // -------------------------------------------------------------------------
1018
+ const toolbarItems = props.toolbar === false ? EMPTY : (props.toolbar ?? ['previous', 'next', 'today', 'dateRange', 'views']);
1019
+ const viewLabel = (e) => e.label ?? t(`view${e.type[0]?.toUpperCase()}${e.type.slice(1)}`);
1020
+ const atMin = minDay !== null && page !== null && (page.days[0] ?? 0) <= minDay;
1021
+ const atMax = maxDay !== null && page !== null && (page.days[page.days.length - 1] ?? 0) >= maxDay;
1022
+ const renderItem = (item) => {
1023
+ if (typeof item === 'object')
1024
+ return (_jsx("div", { className: "salmon-scheduler__toolbar-item", "data-align": item.align ?? 'start', children: item.render ? (item.render()) : (_jsx("button", { type: "button", className: "salmon-scheduler__button", onClick: item.onClick, children: item.label })) }, item.id));
1025
+ switch (item) {
1026
+ case 'previous':
1027
+ case 'next':
1028
+ return (_jsx("button", { type: "button", className: "salmon-scheduler__button salmon-scheduler__nav", "data-nav": item, "aria-label": t(item), disabled: item === 'next' ? atMax : atMin, onClick: (e) => navigate(item, e.detail === 0 ? 'keyboard' : 'pointer'), children: _jsx(Icon, { name: item }) }, item));
1029
+ case 'today':
1030
+ return (_jsx("button", { type: "button", className: "salmon-scheduler__button", "data-nav": "today", onClick: (e) => navigate('today', e.detail === 0 ? 'keyboard' : 'pointer'), children: t('today') }, item));
1031
+ case 'dateRange':
1032
+ return (_jsx("button", { ref: dateButtonRef, type: "button", id: id('range'), className: "salmon-scheduler__date-range", "aria-haspopup": "dialog", "aria-expanded": datePopupOpen, onClick: () => setDatePopupOpen((o) => !o), children: props.renderDateRange && page && anchor !== null ? props.renderDateRange({ start: fromDays(page.days[0] ?? anchor), end: fromDays(page.days[page.days.length - 1] ?? anchor), text: rangeText, view: entry.type }) : rangeText }, item));
1033
+ case 'newEvent':
1034
+ return can.add ? (_jsx("button", { type: "button", className: "salmon-scheduler__button", "data-primary": "", onClick: () => {
1035
+ if (!zone || anchor === null)
1036
+ return;
1037
+ const sel = store.getSnapshot().selectedCells;
1038
+ const s = sel?.start ?? zone.instant(anchor * DAY_MS + opts.workStart * MINUTE_MS);
1039
+ openEditorFor(null, sel ?? { start: s, end: s + 30 * MINUTE_MS, allDay: false }, 'add', 'pointer');
1040
+ }, children: t('newEvent') }, item)) : null;
1041
+ case 'views':
1042
+ return entries.length > 1 && adaptive ? (_jsx("select", { className: "salmon-scheduler__select", "aria-label": t('views'), value: entry.name, onChange: (ev) => navigateTo(ev.currentTarget.value, anchor ?? 0, 'view', 'pointer'), children: entries.map((e) => (_jsx("option", { value: e.name, children: viewLabel(e) }, e.name))) }, item)) : entries.length > 1 ? (_jsx("div", { role: "group", "aria-label": t('views'), className: "salmon-scheduler__views", children: entries.map((e) => (_jsx("button", { type: "button", className: "salmon-scheduler__button", "data-view": e.name, "aria-pressed": e.name === entry.name, onClick: (ev) => navigateTo(e.name, anchor ?? 0, 'view', ev.detail === 0 ? 'keyboard' : 'pointer'), children: viewLabel(e) }, e.name))) }, item)) : null;
1043
+ }
1044
+ };
1045
+ const items = (_jsxs(_Fragment, { children: [_jsx("div", { className: "salmon-scheduler__toolbar-start", children: toolbarItems.filter((i) => typeof i === 'string' ? i !== 'views' && i !== 'newEvent' : i.align !== 'end').map(renderItem) }), _jsx("div", { className: "salmon-scheduler__toolbar-end", children: toolbarItems.filter((i) => (typeof i === 'string' ? i === 'views' || i === 'newEvent' : i.align === 'end')).map(renderItem) })] }));
1046
+ const ready = zone !== null && anchor !== null && page !== null && layout !== null;
1047
+ const family = familyOf(entry.type);
1048
+ // React writes a number as px and skips undefined.
1049
+ const style = { ...props.style, blockSize: props.height ?? props.style?.blockSize, inlineSize: props.width ?? props.style?.inlineSize };
1050
+ return (_jsx(SchedulerContext.Provider, { value: ctxValue, children: _jsxs("div", { ref: rootRef, id: props.id, className: cx('salmon-scheduler', props.className), style: style, dir: props.dir, role: "group", "aria-label": props['aria-label'] ?? t('label'), "aria-busy": !ready || loading || undefined, "data-view": entry.type, "data-readonly": opts.readOnly ? '' : undefined, "data-adaptive": adaptive ? '' : undefined, "data-salmon-deferred": !ready ? '' : undefined, onKeyDown: (e) => {
1051
+ if ((e.key === 'F10' && e.shiftKey) || e.key === 'ContextMenu') {
1052
+ const r = e.target.getBoundingClientRect();
1053
+ askMenu(e, r.left, r.bottom);
1054
+ }
1055
+ if (interactRef.current)
1056
+ interactRef.current.rootKey(interactHost(), e);
1057
+ else {
1058
+ // A key before the chunk replays once it loads, from where focus is then (an earlier key may have
1059
+ // moved it). A grid key does not scroll natively meanwhile: that would shift the grid under the replay.
1060
+ const root = e.currentTarget;
1061
+ const doc = root.ownerDocument;
1062
+ if (/^(Arrow|Home|End)/.test(e.key) && e.target.closest('[role="gridcell"]'))
1063
+ e.preventDefault();
1064
+ void withInteract().then(() => replayInput([e.nativeEvent], () => (root.contains(doc.activeElement) ? doc.activeElement : null)));
1065
+ }
1066
+ }, onContextMenu: (e) => askMenu(e, e.clientX, e.clientY), "data-resizable": editable && props.resizable !== false ? '' : undefined, onFocus: (e) => {
1067
+ if (interactRef.current)
1068
+ interactRef.current.rootFocus(e);
1069
+ else
1070
+ void withInteract().then((m) => e.target === e.target.ownerDocument.activeElement && m.rootFocus(e));
1071
+ }, onPointerDown: (e) => {
1072
+ const n = e.nativeEvent;
1073
+ preloadInteract();
1074
+ // The rest of the press may arrive before the drag chunk: held, then replayed to its window listeners.
1075
+ const win = e.currentTarget.ownerDocument.defaultView;
1076
+ const held = holdInput(win, PRESS_EVENTS);
1077
+ void withDrag().then((m) => {
1078
+ m.down(getHost, n);
1079
+ replayInput(held(), () => win);
1080
+ }, held);
1081
+ }, onDragOver: (e) => props.onExternalDrop && (e.preventDefault(), void withDrag()), onDrop: (e) => dragRef.current?.external(interactHost(), e.nativeEvent), children: [toolbarItems.length ? (_jsx("div", { role: "toolbar", "aria-label": t('label'), className: "salmon-scheduler__toolbar", children: props.renderToolbar ? props.renderToolbar({ items, dateRangeText: rangeText }) : items })) : null, _jsxs("div", { className: "salmon-scheduler__body", children: [ready && (family || resDefs.length) ? (_jsx(Suspense, { fallback: _jsx("div", { className: "salmon-scheduler__pending", "data-salmon-pending": "", "aria-busy": "true" }), children: _jsx(Gate, { needed: [...(family ? [family] : []), ...(resDefs.length ? ['resources'] : [])], family: family, type: entry.type, days: page.days, weeks: page.weeks, anchor: anchor, occurrences: occurrences, layout: layout, allDayExpanded: allDayExpanded, occurrencesIn: (s, e) => (records && rctx ? occurrencesIn(records.records, { start: s, end: e }, { zone, zoneFor: rctx.zoneFor }) : EMPTY) }) })) : ready && entry.type === 'month' && layout?.month && page.weeks ? (_jsx(MonthView, { weeks: page.weeks, layout: layout.month, anchor: anchor })) : ready && layout?.day ? (_jsx(DayView, { days: page.days, layout: layout.day })) : null, loading ? (_jsx("div", { className: "salmon-scheduler__loading", role: "status", children: props.renderLoading ? props.renderLoading() : _jsx("span", { children: t('loading') }) })) : null] }), popupNode, menu && props.contextMenu ? (_jsx(menu.SchedulerContextMenu, { ctx: ctxValue, pending: menuAsk, host: {
1082
+ find: findOccurrence,
1083
+ info: info,
1084
+ can,
1085
+ openEditor: openEditorFor,
1086
+ edit: requestEdit,
1087
+ remove: requestDelete,
1088
+ today: (s) => navigate('today', s),
1089
+ } })) : null, tip && props.tooltip ? _jsx(tip.SchedulerTooltip, { ctx: ctxValue, find: findOccurrence, info: info, closer: closeTip }) : null, datePopupOpen && datePopup && anchor !== null ? (_jsx(datePopup.DatePopup, { anchor: dateButtonRef, value: anchor, month: entry.type === 'month' || entry.type === 'monthAgenda', min: minDay, max: maxDay, locale: locale, firstDayOfWeek: opts.view.firstDayOfWeek, label: t('chooseDate'), onClose: () => setDatePopupOpen(false), onPick: (d) => {
1090
+ setDatePopupOpen(false);
1091
+ navigateTo(viewName, d, 'date', 'pointer');
1092
+ requestAnimationFrame(() => dateButtonRef.current?.focus());
1093
+ } })) : null] }) }));
1094
+ }
1095
+ //# sourceMappingURL=Scheduler.js.map