@bimetal/calendar-headless 0.29.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.
- package/README.md +53 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/click-intent.d.ts +39 -0
- package/dist/click-intent.d.ts.map +1 -0
- package/dist/click-intent.js +29 -0
- package/dist/click-intent.js.map +1 -0
- package/dist/controller/config.d.ts +12 -0
- package/dist/controller/config.d.ts.map +1 -0
- package/dist/controller/config.js +103 -0
- package/dist/controller/config.js.map +1 -0
- package/dist/controller/create-controller.d.ts +20 -0
- package/dist/controller/create-controller.d.ts.map +1 -0
- package/dist/controller/create-controller.js +634 -0
- package/dist/controller/create-controller.js.map +1 -0
- package/dist/controller/types.d.ts +302 -0
- package/dist/controller/types.d.ts.map +1 -0
- package/dist/controller/types.js +10 -0
- package/dist/controller/types.js.map +1 -0
- package/dist/controller/view-configs.d.ts +11 -0
- package/dist/controller/view-configs.d.ts.map +1 -0
- package/dist/controller/view-configs.js +74 -0
- package/dist/controller/view-configs.js.map +1 -0
- package/dist/date-strings.d.ts +16 -0
- package/dist/date-strings.d.ts.map +1 -0
- package/dist/date-strings.js +14 -0
- package/dist/date-strings.js.map +1 -0
- package/dist/defaults.d.ts +22 -0
- package/dist/defaults.d.ts.map +1 -0
- package/dist/defaults.js +24 -0
- package/dist/defaults.js.map +1 -0
- package/dist/drag-helpers.d.ts +56 -0
- package/dist/drag-helpers.d.ts.map +1 -0
- package/dist/drag-helpers.js +69 -0
- package/dist/drag-helpers.js.map +1 -0
- package/dist/drag-preview.d.ts +102 -0
- package/dist/drag-preview.d.ts.map +1 -0
- package/dist/drag-preview.js +181 -0
- package/dist/drag-preview.js.map +1 -0
- package/dist/event-actions.d.ts +64 -0
- package/dist/event-actions.d.ts.map +1 -0
- package/dist/event-actions.js +135 -0
- package/dist/event-actions.js.map +1 -0
- package/dist/event-text.d.ts +21 -0
- package/dist/event-text.d.ts.map +1 -0
- package/dist/event-text.js +37 -0
- package/dist/event-text.js.map +1 -0
- package/dist/grid-geometry.d.ts +52 -0
- package/dist/grid-geometry.d.ts.map +1 -0
- package/dist/grid-geometry.js +50 -0
- package/dist/grid-geometry.js.map +1 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/validate-save.d.ts +18 -0
- package/dist/validate-save.d.ts.map +1 -0
- package/dist/validate-save.js +56 -0
- package/dist/validate-save.js.map +1 -0
- package/package.json +50 -0
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical, framework-agnostic calendar controller.
|
|
3
|
+
*
|
|
4
|
+
* Owns the ENTIRE calendar interaction state and every decision: navigation,
|
|
5
|
+
* dialog routing (incl. recurrence-instance classification and isNew), drag/
|
|
6
|
+
* drop intents, selection, category/resource filtering, undo/rule-error
|
|
7
|
+
* surfacing, and keyboard semantics. Framework packages (React/Vue/Svelte/
|
|
8
|
+
* Angular) bind to it and do nothing but: subscribe → render the snapshot,
|
|
9
|
+
* and translate a DOM event into an intent call.
|
|
10
|
+
*
|
|
11
|
+
* The cut line is: DOM measurement & event-listener registration = framework;
|
|
12
|
+
* every `if` = controller. This is what makes cross-framework drift
|
|
13
|
+
* structurally impossible instead of a matter of discipline.
|
|
14
|
+
*
|
|
15
|
+
* Derived from the de-facto reference `packages/react-components/src/
|
|
16
|
+
* components/Calendar.tsx`.
|
|
17
|
+
*/
|
|
18
|
+
import { now as coreNow, getYear, getMonth, getDayOfMonth, createDateTime, addDays, createTimeRange, visibleRange, getRecurrenceInstanceMetadata, stripRecurrenceInstanceMetadata, } from '@bimetal/calendar-core';
|
|
19
|
+
import { DataValidationError } from '@bimetal/calendar-data';
|
|
20
|
+
import { createRuleEngine, withRules, RuleViolationError } from '@bimetal/calendar-rules';
|
|
21
|
+
import { createControllerCore, deepCopy } from '@bimetal/headless-core';
|
|
22
|
+
import { createEventActions } from '../event-actions.js';
|
|
23
|
+
import { validateSavePreview } from '../validate-save.js';
|
|
24
|
+
import { computeDragPreview, computeTimedDragPreview, findExpandedEvent, computePreviewEvent } from '../drag-preview.js';
|
|
25
|
+
import { toDateStr, toTimeStr, parseDateStr, parseDateTimeStr } from '../date-strings.js';
|
|
26
|
+
import { mergeCalendarConfig } from './config.js';
|
|
27
|
+
import { createViewConfigs } from './view-configs.js';
|
|
28
|
+
export function createCalendarController(opts) {
|
|
29
|
+
const baseStore = opts.store;
|
|
30
|
+
const nowFn = opts.now ?? (() => coreNow(config.core.timezone, config.core.clock));
|
|
31
|
+
let eventDialogKind = opts.eventDialogKind ?? 'builtin';
|
|
32
|
+
const onError = opts.onError;
|
|
33
|
+
// ── Mutable option state (reactive via setConfig/setRules/setCustomViews) ──
|
|
34
|
+
let config = mergeCalendarConfig(opts.config);
|
|
35
|
+
let rules = opts.rules ?? [];
|
|
36
|
+
let customViews = opts.customViews ?? [];
|
|
37
|
+
// ── Rule-wrapped store + event actions (rebuilt when rules/core change) ──
|
|
38
|
+
let ruleStore;
|
|
39
|
+
let actions;
|
|
40
|
+
let masterEvents = [];
|
|
41
|
+
// ── Interaction state ──
|
|
42
|
+
let currentDate;
|
|
43
|
+
let currentView = 'month';
|
|
44
|
+
let dialog = null;
|
|
45
|
+
let selection = null;
|
|
46
|
+
let hiddenCategories = new Set();
|
|
47
|
+
let hiddenResources = new Set();
|
|
48
|
+
let dragPreview = null;
|
|
49
|
+
let previewEvent = null; // B-CAL-1: rebuilt dragged event
|
|
50
|
+
let expandedMonthDay = null; // B-CAL-3: hover-expanded month cell
|
|
51
|
+
let dragInfo = null; // transient — never part of the snapshot
|
|
52
|
+
// ── Derived caches (rebuilt on config/customViews change) ──
|
|
53
|
+
let viewConfigList = [];
|
|
54
|
+
// ── Shared controller core (identity-stable snapshot, listener bus,
|
|
55
|
+
// errors-as-state). Assigned in Init below; markChanged delegates so
|
|
56
|
+
// every existing call site stays unchanged. ──
|
|
57
|
+
let core;
|
|
58
|
+
function markChanged() { core.markChanged(); }
|
|
59
|
+
// ── Store lifecycle ─────────────────────────────────────────────
|
|
60
|
+
function buildRuleStore() {
|
|
61
|
+
if (actions)
|
|
62
|
+
actions.destroy();
|
|
63
|
+
ruleStore = rules.length > 0 ? withRules(baseStore, createRuleEngine(rules), config.core) : baseStore;
|
|
64
|
+
actions = createEventActions(ruleStore);
|
|
65
|
+
masterEvents = actions.getEvents();
|
|
66
|
+
actions.subscribe(evts => { masterEvents = evts; markChanged(); });
|
|
67
|
+
}
|
|
68
|
+
function rebuildViewConfigs() {
|
|
69
|
+
const viewConfigs = createViewConfigs(config.locale, config.core.weekStart);
|
|
70
|
+
const builtIns = Object.values(viewConfigs).filter(v => (v.type !== 'resource' && v.type !== 'timeline') || config.resources.length > 0);
|
|
71
|
+
const customs = customViews.map(v => ({
|
|
72
|
+
type: v.id,
|
|
73
|
+
label: v.label,
|
|
74
|
+
step: v.step ?? ((dt, dir) => addDays(dt, dir)),
|
|
75
|
+
formatTitle: v.formatTitle ?? ((dt) => new Intl.DateTimeFormat(config.locale.code, { dateStyle: 'full', timeZone: config.core.timezone })
|
|
76
|
+
.format(new Date(dt.epochMs))),
|
|
77
|
+
}));
|
|
78
|
+
viewConfigList = [...builtIns, ...customs];
|
|
79
|
+
// F7: if the active view no longer exists (e.g. resources removed, or a
|
|
80
|
+
// custom-view id dropped), fall back to the first available view so
|
|
81
|
+
// `currentView` can never point at a non-existent view.
|
|
82
|
+
if (!viewConfigList.some(v => v.type === currentView) && viewConfigList.length > 0) {
|
|
83
|
+
currentView = viewConfigList[0].type;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// ── Derivations ─────────────────────────────────────────────────
|
|
87
|
+
function activeViewConfig() {
|
|
88
|
+
return viewConfigList.find(v => v.type === currentView) ?? viewConfigList[0];
|
|
89
|
+
}
|
|
90
|
+
function computeRange() {
|
|
91
|
+
const custom = customViews.find(v => v.id === currentView);
|
|
92
|
+
if (custom?.visibleRange)
|
|
93
|
+
return custom.visibleRange(currentDate, config.core);
|
|
94
|
+
return visibleRange(currentView, currentDate, config.core);
|
|
95
|
+
}
|
|
96
|
+
function isVisibleCategory(e) {
|
|
97
|
+
return !hiddenCategories.has(e.metadata.category ?? '');
|
|
98
|
+
}
|
|
99
|
+
/** Expanded → category-filtered. THE canonical visible-event list. */
|
|
100
|
+
function currentEvents() {
|
|
101
|
+
const range = computeRange();
|
|
102
|
+
return actions.getEventsInRange(range.start, range.end).filter(isVisibleCategory);
|
|
103
|
+
}
|
|
104
|
+
// ── Dialog draft (B-CAL-2): the controller owns defaults, parsing, assembly,
|
|
105
|
+
// id minting and the derived field policy. Bindings render raw strings. ──
|
|
106
|
+
/** Seed a CREATE draft with the controller's defaults (the '09:00'/'10:00',
|
|
107
|
+
* allDay-default, first-category policy that used to live ×5 in the views). */
|
|
108
|
+
function freshDraft(date, resourceId) {
|
|
109
|
+
const cat = config.categories[0];
|
|
110
|
+
const dateStr = toDateStr(date);
|
|
111
|
+
const startT = toTimeStr(date);
|
|
112
|
+
return {
|
|
113
|
+
title: '', startDate: dateStr, endDate: dateStr, allDay: true,
|
|
114
|
+
startTime: startT !== '00:00' ? startT : '09:00', endTime: '10:00',
|
|
115
|
+
category: cat?.name ?? 'default', color: cat?.color ?? '#007AFF',
|
|
116
|
+
location: '', description: '', resourceId: resourceId ?? '',
|
|
117
|
+
recurring: false, recFreq: 'weekly', recInterval: 1, recUntil: '',
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Seed an EDIT draft from the event (C1): event → strings, inclusive allDay
|
|
121
|
+
* end. The edit path is now as parse-free in the binding as the create path. */
|
|
122
|
+
function draftFromEvent(event) {
|
|
123
|
+
const cat = config.categories[0];
|
|
124
|
+
return {
|
|
125
|
+
title: event.title,
|
|
126
|
+
startDate: toDateStr(event.timeRange.start),
|
|
127
|
+
endDate: toDateStr(event.allDay ? addDays(event.timeRange.end, -1) : event.timeRange.end),
|
|
128
|
+
allDay: event.allDay ?? false,
|
|
129
|
+
startTime: toTimeStr(event.timeRange.start),
|
|
130
|
+
endTime: toTimeStr(event.timeRange.end),
|
|
131
|
+
category: event.metadata.category ?? cat?.name ?? 'default',
|
|
132
|
+
color: event.metadata.color ?? cat?.color ?? '#007AFF',
|
|
133
|
+
location: event.metadata.location ?? '',
|
|
134
|
+
description: event.metadata.description ?? '',
|
|
135
|
+
resourceId: event.resourceId ?? '',
|
|
136
|
+
recurring: !!event.recurrence,
|
|
137
|
+
recFreq: event.recurrence?.freq ?? 'weekly',
|
|
138
|
+
recInterval: event.recurrence?.interval ?? 1,
|
|
139
|
+
recUntil: event.recurrence?.until ? toDateStr(event.recurrence.until) : '',
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** Assemble the held draft into a CalendarEvent: re-encode the inclusive allDay
|
|
143
|
+
* end (+1), build recurrence (only for a non-instance), preserve the original
|
|
144
|
+
* event's metadata markers (so a recurrence INSTANCE keeps its _masterEventId/
|
|
145
|
+
* _instanceDate and saveDialog routes through modifyInstance — C2), and MINT
|
|
146
|
+
* the id here (never in the view → R3). */
|
|
147
|
+
function assembleDraftEvent(state) {
|
|
148
|
+
const d = state.draft;
|
|
149
|
+
const event = state.event;
|
|
150
|
+
const tz = state.defaultDate.timezone;
|
|
151
|
+
// Parse via the shared date-string helpers (NOT a re-inlined split('-') — that
|
|
152
|
+
// is the exact duplication this epic removes; 3227d9c was a date-parse copy).
|
|
153
|
+
const timeRange = d.allDay
|
|
154
|
+
? createTimeRange(parseDateStr(d.startDate, tz), addDays(parseDateStr(d.endDate, tz), 1))
|
|
155
|
+
: createTimeRange(parseDateTimeStr(d.startDate, d.startTime, tz), parseDateTimeStr(d.endDate, d.endTime, tz));
|
|
156
|
+
const recurrence = d.recurring && !state.isInstance
|
|
157
|
+
? { freq: d.recFreq, interval: d.recInterval, ...(d.recUntil ? { until: parseDateStr(d.recUntil, tz) } : {}) }
|
|
158
|
+
: undefined;
|
|
159
|
+
return {
|
|
160
|
+
id: event?.id ?? crypto.randomUUID(),
|
|
161
|
+
title: d.title.trim(),
|
|
162
|
+
timeRange,
|
|
163
|
+
allDay: d.allDay,
|
|
164
|
+
metadata: {
|
|
165
|
+
...event?.metadata,
|
|
166
|
+
color: d.color,
|
|
167
|
+
category: d.category,
|
|
168
|
+
location: d.location || undefined,
|
|
169
|
+
description: d.description || undefined,
|
|
170
|
+
},
|
|
171
|
+
domains: event?.domains,
|
|
172
|
+
recurrence,
|
|
173
|
+
resourceId: d.resourceId || undefined,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function buildSnapshot() {
|
|
177
|
+
const viewConfig = activeViewConfig();
|
|
178
|
+
const range = computeRange();
|
|
179
|
+
const events = actions.getEventsInRange(range.start, range.end).filter(isVisibleCategory);
|
|
180
|
+
const visibleResources = config.resources.filter(r => !hiddenResources.has(r.id));
|
|
181
|
+
// Deep defensive copies (F4) — a consumer must not be able to reach internal
|
|
182
|
+
// controller state through ANY level of the snapshot graph. `events` are
|
|
183
|
+
// freshly expanded/filtered on each call (already detached), so they stay
|
|
184
|
+
// raw. Everything else is deep-copied (function refs preserved). Copies, not
|
|
185
|
+
// Object.freeze — frozen objects break framework reactive proxies (Vue).
|
|
186
|
+
// Built only when the version actually moves (cached), so the cost is fine.
|
|
187
|
+
return {
|
|
188
|
+
currentView,
|
|
189
|
+
title: viewConfig.formatTitle(currentDate),
|
|
190
|
+
events,
|
|
191
|
+
currentDate: deepCopy(currentDate),
|
|
192
|
+
viewConfig: deepCopy(viewConfig),
|
|
193
|
+
viewConfigList: viewConfigList.map(deepCopy),
|
|
194
|
+
range: deepCopy(range),
|
|
195
|
+
visibleResources: deepCopy(visibleResources),
|
|
196
|
+
dialog: deepCopy(dialog),
|
|
197
|
+
selection: deepCopy(selection),
|
|
198
|
+
previewEvent: deepCopy(previewEvent),
|
|
199
|
+
expandedMonthDay,
|
|
200
|
+
lastAction: deepCopy(core.getLastAction()),
|
|
201
|
+
hiddenCategories: new Set(hiddenCategories),
|
|
202
|
+
hiddenResources: new Set(hiddenResources),
|
|
203
|
+
config: deepCopy(config),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
// ── Internal helpers ────────────────────────────────────────────
|
|
207
|
+
function setLastAction(entityId, description) {
|
|
208
|
+
core.setLastAction(entityId, description);
|
|
209
|
+
}
|
|
210
|
+
// The unified controller error contract: a DOMAIN rejection (a rule violation)
|
|
211
|
+
// surfaces as `lastAction` (errors-as-state). ANY other error — ConcurrencyError,
|
|
212
|
+
// storage, a bug — PROPAGATES to the consumer via `onError`, or (if none given)
|
|
213
|
+
// by rethrowing so the intent's promise rejects loudly. Never silently swallowed.
|
|
214
|
+
function handleError(err) {
|
|
215
|
+
if (err instanceof RuleViolationError) {
|
|
216
|
+
const msg = err.violations
|
|
217
|
+
.filter(v => !v.passed)
|
|
218
|
+
.map(v => !v.passed ? v.message : '')
|
|
219
|
+
.join(', ');
|
|
220
|
+
setLastAction('', msg);
|
|
221
|
+
markChanged();
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if (err instanceof DataValidationError) {
|
|
225
|
+
setLastAction('', err.message);
|
|
226
|
+
markChanged();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (onError) {
|
|
230
|
+
onError(err);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
throw err;
|
|
234
|
+
}
|
|
235
|
+
/** Undo through the SAME error router as save/delete/drop — a domain rejection
|
|
236
|
+
* surfaces as `lastAction`, an infra/concurrency error propagates via
|
|
237
|
+
* `onError`/rethrow. Returns whether the undo actually happened. */
|
|
238
|
+
async function undoSafely(entityId) {
|
|
239
|
+
try {
|
|
240
|
+
await ruleStore.undo(entityId);
|
|
241
|
+
return true;
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
handleError(err);
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** Surface rule warnings from the last dispatch — but only when no action
|
|
249
|
+
* toast is already showing (mirrors the React `prev ? prev : …` effect). */
|
|
250
|
+
function pullWarnings() {
|
|
251
|
+
const warnings = ruleStore.lastWarnings;
|
|
252
|
+
if (warnings && warnings.length > 0) {
|
|
253
|
+
const msg = warnings.filter(w => !w.passed).map(w => !w.passed ? w.message : '').join(', ');
|
|
254
|
+
if (msg && !core.getLastAction()) {
|
|
255
|
+
setLastAction('', msg);
|
|
256
|
+
markChanged();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
// ── Init ────────────────────────────────────────────────────────
|
|
261
|
+
// Core first: buildRuleStore's store subscription calls markChanged, which
|
|
262
|
+
// delegates to the core. buildSnapshot is only invoked lazily (on the first
|
|
263
|
+
// getSnapshot), by which point all state below is initialised.
|
|
264
|
+
core = createControllerCore({ buildSnapshot });
|
|
265
|
+
buildRuleStore();
|
|
266
|
+
rebuildViewConfigs();
|
|
267
|
+
currentDate = nowFn();
|
|
268
|
+
// ── Controller object ───────────────────────────────────────────
|
|
269
|
+
const controller = {
|
|
270
|
+
getSnapshot() { return core.getSnapshot(); },
|
|
271
|
+
subscribe(listener) { return core.subscribe(listener); },
|
|
272
|
+
destroy() {
|
|
273
|
+
actions.destroy();
|
|
274
|
+
core.destroy();
|
|
275
|
+
},
|
|
276
|
+
// ── Reactive option updates ──
|
|
277
|
+
setConfig(input) {
|
|
278
|
+
config = mergeCalendarConfig(input);
|
|
279
|
+
buildRuleStore(); // rules re-wrapped with fresh core (timezone/hours)
|
|
280
|
+
rebuildViewConfigs();
|
|
281
|
+
markChanged();
|
|
282
|
+
},
|
|
283
|
+
setRules(next) {
|
|
284
|
+
rules = next ?? [];
|
|
285
|
+
buildRuleStore();
|
|
286
|
+
markChanged();
|
|
287
|
+
},
|
|
288
|
+
setCustomViews(next) {
|
|
289
|
+
customViews = next ?? [];
|
|
290
|
+
rebuildViewConfigs();
|
|
291
|
+
markChanged();
|
|
292
|
+
},
|
|
293
|
+
// F8: dialog mode is a dynamic prop — keep it in sync after mount instead of
|
|
294
|
+
// freezing it at construction (it routes openEdit/openCreate to builtin vs.
|
|
295
|
+
// the consumer callbacks). No snapshot field reflects it, so no markChanged.
|
|
296
|
+
setEventDialogKind(kind) { eventDialogKind = kind; },
|
|
297
|
+
// ── Navigation ──
|
|
298
|
+
prev() { currentDate = activeViewConfig().step(currentDate, -1); markChanged(); },
|
|
299
|
+
next() { currentDate = activeViewConfig().step(currentDate, 1); markChanged(); },
|
|
300
|
+
today() { currentDate = nowFn(); markChanged(); },
|
|
301
|
+
setView(view) { currentView = view; markChanged(); },
|
|
302
|
+
goToMonth(year, month) {
|
|
303
|
+
currentDate = createDateTime(year, month, 1, 0, 0, currentDate.timezone);
|
|
304
|
+
currentView = 'month';
|
|
305
|
+
markChanged();
|
|
306
|
+
},
|
|
307
|
+
// ── Dialog lifecycle ──
|
|
308
|
+
openEdit(eventId, anchorRect, instanceDate) {
|
|
309
|
+
if (eventDialogKind === 'none') {
|
|
310
|
+
opts.onEventClickExternal?.(eventId, anchorRect, instanceDate);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
// For recurring instances multiple visible events share the same id; the
|
|
314
|
+
// instanceDate (epochMs) selects the exact occurrence the user clicked.
|
|
315
|
+
const event = findExpandedEvent(currentEvents(), eventId, instanceDate);
|
|
316
|
+
if (!event)
|
|
317
|
+
return;
|
|
318
|
+
// C1: the EDIT draft is seeded in the controller (event → strings), so the
|
|
319
|
+
// binding's edit path is as parse-free as create.
|
|
320
|
+
dialog = {
|
|
321
|
+
event, defaultDate: event.timeRange.start, anchorRect,
|
|
322
|
+
draft: draftFromEvent(event),
|
|
323
|
+
isNew: false,
|
|
324
|
+
isInstance: getRecurrenceInstanceMetadata(event) !== null,
|
|
325
|
+
validationErrors: [],
|
|
326
|
+
};
|
|
327
|
+
markChanged();
|
|
328
|
+
},
|
|
329
|
+
openCreate(date, anchorRect, resourceId) {
|
|
330
|
+
if (eventDialogKind === 'none') {
|
|
331
|
+
opts.onNewEventRequestedExternal?.(date, anchorRect, resourceId);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
dialog = {
|
|
335
|
+
event: null, defaultDate: date, anchorRect, defaultResourceId: resourceId,
|
|
336
|
+
draft: freshDraft(date, resourceId),
|
|
337
|
+
isNew: true,
|
|
338
|
+
isInstance: false,
|
|
339
|
+
validationErrors: [],
|
|
340
|
+
};
|
|
341
|
+
markChanged();
|
|
342
|
+
},
|
|
343
|
+
openCreateFromResourceCell(date, time, resourceId, anchorRect) {
|
|
344
|
+
// Combine the cell's date + the HH:MM string via the shared parser (not a
|
|
345
|
+
// re-inlined split(':') — same date-parse-duplication class the epic removes).
|
|
346
|
+
const dt = parseDateTimeStr(toDateStr(date), time, date.timezone);
|
|
347
|
+
controller.openCreate(dt, anchorRect, resourceId);
|
|
348
|
+
},
|
|
349
|
+
closeDialog() { dialog = null; markChanged(); },
|
|
350
|
+
setDraft(patch) {
|
|
351
|
+
if (!dialog)
|
|
352
|
+
return;
|
|
353
|
+
const d = { ...dialog.draft, ...patch };
|
|
354
|
+
// Derived field policy lives in the controller (every `if` is controller):
|
|
355
|
+
// a category pick also sets its color; a start past end bumps end; the
|
|
356
|
+
// recurrence interval is clamped to ≥1.
|
|
357
|
+
if (patch.category !== undefined) {
|
|
358
|
+
const cat = config.categories.find(c => c.name === patch.category);
|
|
359
|
+
if (cat)
|
|
360
|
+
d.color = cat.color;
|
|
361
|
+
}
|
|
362
|
+
if (patch.startDate !== undefined && d.startDate > d.endDate)
|
|
363
|
+
d.endDate = d.startDate;
|
|
364
|
+
if (patch.recInterval !== undefined)
|
|
365
|
+
d.recInterval = Math.max(1, Math.floor(patch.recInterval) || 1);
|
|
366
|
+
dialog = { ...dialog, draft: d, validationErrors: [] };
|
|
367
|
+
markChanged();
|
|
368
|
+
},
|
|
369
|
+
async saveDialogFromInput() {
|
|
370
|
+
if (!dialog)
|
|
371
|
+
return;
|
|
372
|
+
if (!dialog.draft.title.trim())
|
|
373
|
+
return; // title is required (save button also disabled)
|
|
374
|
+
const assembled = assembleDraftEvent(dialog);
|
|
375
|
+
const errors = validateSavePreview(assembled, masterEvents, config.core, rules);
|
|
376
|
+
if (errors.length > 0) {
|
|
377
|
+
dialog = { ...dialog, validationErrors: errors };
|
|
378
|
+
markChanged();
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
await controller.saveDialog(assembled);
|
|
382
|
+
},
|
|
383
|
+
async saveDialog(updated) {
|
|
384
|
+
const instanceMarkers = getRecurrenceInstanceMetadata(updated);
|
|
385
|
+
try {
|
|
386
|
+
if (instanceMarkers) {
|
|
387
|
+
const instanceDate = { epochMs: instanceMarkers.instanceDate, timezone: config.core.timezone };
|
|
388
|
+
await actions.modifyInstance(instanceMarkers.masterEventId, instanceDate, {
|
|
389
|
+
title: updated.title,
|
|
390
|
+
timeRange: updated.timeRange,
|
|
391
|
+
allDay: updated.allDay,
|
|
392
|
+
metadata: stripRecurrenceInstanceMetadata(updated.metadata),
|
|
393
|
+
domains: updated.domains,
|
|
394
|
+
resourceId: updated.resourceId,
|
|
395
|
+
});
|
|
396
|
+
setLastAction(instanceMarkers.masterEventId, config.locale.eventUpdated);
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
const isNew = !currentEvents().some(e => e.id === updated.id);
|
|
400
|
+
await actions.saveEvent(updated);
|
|
401
|
+
setLastAction(updated.id, isNew ? config.locale.eventCreated : config.locale.eventUpdated);
|
|
402
|
+
}
|
|
403
|
+
dialog = null;
|
|
404
|
+
markChanged();
|
|
405
|
+
pullWarnings();
|
|
406
|
+
}
|
|
407
|
+
catch (err) {
|
|
408
|
+
handleError(err);
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
async deleteDialog(eventId) {
|
|
412
|
+
const dialogEvent = dialog?.event;
|
|
413
|
+
const instanceMarkers = dialogEvent ? getRecurrenceInstanceMetadata(dialogEvent) : null;
|
|
414
|
+
try {
|
|
415
|
+
if (instanceMarkers) {
|
|
416
|
+
const instanceDate = { epochMs: instanceMarkers.instanceDate, timezone: config.core.timezone };
|
|
417
|
+
await actions.deleteInstance(instanceMarkers.masterEventId, instanceDate);
|
|
418
|
+
setLastAction(instanceMarkers.masterEventId, config.locale.eventDeleted);
|
|
419
|
+
}
|
|
420
|
+
else {
|
|
421
|
+
await actions.deleteEvent(eventId);
|
|
422
|
+
setLastAction(eventId, config.locale.eventDeleted);
|
|
423
|
+
}
|
|
424
|
+
dialog = null;
|
|
425
|
+
markChanged();
|
|
426
|
+
pullWarnings();
|
|
427
|
+
}
|
|
428
|
+
catch (err) {
|
|
429
|
+
handleError(err);
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
validateSave(evt) {
|
|
433
|
+
return validateSavePreview(evt, masterEvents, config.core, rules);
|
|
434
|
+
},
|
|
435
|
+
// ── Drag/drop ──
|
|
436
|
+
async dropAllDay(info, dropDate) {
|
|
437
|
+
const ev = findExpandedEvent(currentEvents(), info.eventId, info.instanceDate);
|
|
438
|
+
if (!ev) {
|
|
439
|
+
controller.endDrag();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
try {
|
|
443
|
+
if (info.type === 'resize')
|
|
444
|
+
await actions.resizeEvent(ev, dropDate, info.edge);
|
|
445
|
+
else
|
|
446
|
+
await actions.moveEvent(ev, dropDate, info.dayOffset);
|
|
447
|
+
setLastAction(info.eventId, config.locale.eventUpdated);
|
|
448
|
+
pullWarnings();
|
|
449
|
+
}
|
|
450
|
+
catch (err) {
|
|
451
|
+
handleError(err);
|
|
452
|
+
}
|
|
453
|
+
finally {
|
|
454
|
+
// Cleanup must run even when an infra error propagates, so the drag
|
|
455
|
+
// state never gets stuck on a failed drop.
|
|
456
|
+
controller.endDrag();
|
|
457
|
+
}
|
|
458
|
+
},
|
|
459
|
+
async dropTimed(info, dropDate, dropTime) {
|
|
460
|
+
const ev = findExpandedEvent(currentEvents(), info.eventId, info.instanceDate);
|
|
461
|
+
if (!ev) {
|
|
462
|
+
controller.endDrag();
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
try {
|
|
466
|
+
if (info.type === 'resize-timed')
|
|
467
|
+
await actions.resizeTimedEvent(ev, dropDate, dropTime, info.edge);
|
|
468
|
+
else if (info.type === 'move-timed')
|
|
469
|
+
await actions.moveTimedEvent(ev, dropDate, dropTime, info.minuteOffset);
|
|
470
|
+
setLastAction(info.eventId, config.locale.eventUpdated);
|
|
471
|
+
pullWarnings();
|
|
472
|
+
}
|
|
473
|
+
catch (err) {
|
|
474
|
+
handleError(err);
|
|
475
|
+
}
|
|
476
|
+
finally {
|
|
477
|
+
// Cleanup must run even when an infra error propagates, so the drag
|
|
478
|
+
// state never gets stuck on a failed drop.
|
|
479
|
+
controller.endDrag();
|
|
480
|
+
}
|
|
481
|
+
},
|
|
482
|
+
async dropResource(info, dropDate, dropTime, resourceId) {
|
|
483
|
+
const ev = findExpandedEvent(currentEvents(), info.eventId, info.instanceDate);
|
|
484
|
+
if (!ev) {
|
|
485
|
+
controller.endDrag();
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
if (info.type === 'resize-timed') {
|
|
490
|
+
// Resize keeps the resource binding — only the timeRange changes.
|
|
491
|
+
await actions.resizeTimedEvent(ev, dropDate, dropTime, info.edge);
|
|
492
|
+
}
|
|
493
|
+
else if (info.type === 'move-timed') {
|
|
494
|
+
// Single resource per event: drop = atomic resourceId reassignment.
|
|
495
|
+
await actions.moveTimedEvent(ev, dropDate, dropTime, info.minuteOffset, resourceId);
|
|
496
|
+
}
|
|
497
|
+
setLastAction(info.eventId, config.locale.eventUpdated);
|
|
498
|
+
pullWarnings();
|
|
499
|
+
}
|
|
500
|
+
catch (err) {
|
|
501
|
+
handleError(err);
|
|
502
|
+
}
|
|
503
|
+
finally {
|
|
504
|
+
// Cleanup must run even when an infra error propagates, so the drag
|
|
505
|
+
// state never gets stuck on a failed drop.
|
|
506
|
+
controller.endDrag();
|
|
507
|
+
}
|
|
508
|
+
},
|
|
509
|
+
async dropTimeline(info, dropDate, targetResourceId) {
|
|
510
|
+
const ev = findExpandedEvent(currentEvents(), info.eventId, info.instanceDate);
|
|
511
|
+
if (!ev) {
|
|
512
|
+
controller.endDrag();
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
if (info.type === 'move') {
|
|
517
|
+
// Day-grain move + resource reassignment in one instance-aware op.
|
|
518
|
+
await actions.moveEvent(ev, dropDate, info.dayOffset, targetResourceId);
|
|
519
|
+
}
|
|
520
|
+
else if (info.type === 'resize') {
|
|
521
|
+
// Timeline always day-snaps the resized edge, regardless of allDay.
|
|
522
|
+
await actions.resizeEventByDay(ev, dropDate, info.edge);
|
|
523
|
+
}
|
|
524
|
+
setLastAction(info.eventId, config.locale.eventUpdated);
|
|
525
|
+
pullWarnings();
|
|
526
|
+
}
|
|
527
|
+
catch (err) {
|
|
528
|
+
handleError(err);
|
|
529
|
+
}
|
|
530
|
+
finally {
|
|
531
|
+
// Cleanup must run even when an infra error propagates, so the drag
|
|
532
|
+
// state never gets stuck on a failed drop.
|
|
533
|
+
controller.endDrag();
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
startDrag(info) { dragInfo = info; }, // transient: no snapshot change
|
|
537
|
+
updatePreview(hoverDate) {
|
|
538
|
+
if (!dragInfo)
|
|
539
|
+
return;
|
|
540
|
+
const evs = currentEvents();
|
|
541
|
+
const preview = computeDragPreview(dragInfo, hoverDate, evs);
|
|
542
|
+
if (!preview && !dragPreview)
|
|
543
|
+
return;
|
|
544
|
+
if (dragPreview && preview
|
|
545
|
+
&& dragPreview.previewStart === preview.previewStart
|
|
546
|
+
&& dragPreview.previewEnd === preview.previewEnd)
|
|
547
|
+
return;
|
|
548
|
+
dragPreview = preview;
|
|
549
|
+
// B-CAL-1: rebuild the dragged event from the SAME inputs (not the lossy
|
|
550
|
+
// preview strings) so the projection preserves time-of-day for every view.
|
|
551
|
+
previewEvent = preview ? computePreviewEvent(dragInfo, hoverDate, undefined, evs) : null;
|
|
552
|
+
markChanged();
|
|
553
|
+
},
|
|
554
|
+
updateTimedPreview(hoverDate, hoverTime) {
|
|
555
|
+
if (!dragInfo)
|
|
556
|
+
return;
|
|
557
|
+
const evs = currentEvents();
|
|
558
|
+
const preview = computeTimedDragPreview(dragInfo, hoverDate, hoverTime, evs);
|
|
559
|
+
if (!preview)
|
|
560
|
+
return;
|
|
561
|
+
if (dragPreview
|
|
562
|
+
&& dragPreview.previewStart === preview.previewStart
|
|
563
|
+
&& dragPreview.previewEnd === preview.previewEnd
|
|
564
|
+
&& dragPreview.previewStartTime === preview.previewStartTime
|
|
565
|
+
&& dragPreview.previewEndTime === preview.previewEndTime)
|
|
566
|
+
return;
|
|
567
|
+
dragPreview = preview;
|
|
568
|
+
previewEvent = computePreviewEvent(dragInfo, hoverDate, hoverTime, evs);
|
|
569
|
+
markChanged();
|
|
570
|
+
},
|
|
571
|
+
hidePreview() { if (dragPreview === null)
|
|
572
|
+
return; dragPreview = null; previewEvent = null; markChanged(); },
|
|
573
|
+
endDrag() { dragInfo = null; dragPreview = null; previewEvent = null; markChanged(); },
|
|
574
|
+
// ── Selection ──
|
|
575
|
+
selectEvent(eventId, instanceDate) { selection = { eventId, instanceDate }; markChanged(); },
|
|
576
|
+
clearSelection() { if (!selection)
|
|
577
|
+
return; selection = null; markChanged(); },
|
|
578
|
+
// B-CAL-3: month-cell hover-expand owned by the controller (no binding useState).
|
|
579
|
+
expandMonthCell(dayEpochMs) { if (expandedMonthDay === dayEpochMs)
|
|
580
|
+
return; expandedMonthDay = dayEpochMs; markChanged(); },
|
|
581
|
+
collapseMonthCell() { if (expandedMonthDay === null)
|
|
582
|
+
return; expandedMonthDay = null; markChanged(); },
|
|
583
|
+
// ── Filters ──
|
|
584
|
+
toggleCategory(name) {
|
|
585
|
+
const next = new Set(hiddenCategories);
|
|
586
|
+
if (next.has(name))
|
|
587
|
+
next.delete(name);
|
|
588
|
+
else
|
|
589
|
+
next.add(name);
|
|
590
|
+
hiddenCategories = next;
|
|
591
|
+
markChanged();
|
|
592
|
+
},
|
|
593
|
+
toggleResource(resourceId) {
|
|
594
|
+
const next = new Set(hiddenResources);
|
|
595
|
+
if (next.has(resourceId))
|
|
596
|
+
next.delete(resourceId);
|
|
597
|
+
else
|
|
598
|
+
next.add(resourceId);
|
|
599
|
+
hiddenResources = next;
|
|
600
|
+
markChanged();
|
|
601
|
+
},
|
|
602
|
+
// ── Undo / errors ──
|
|
603
|
+
async undo(entityId) { await undoSafely(entityId); },
|
|
604
|
+
dismissUndo() { if (core.dismissLastAction())
|
|
605
|
+
markChanged(); },
|
|
606
|
+
trackAction(entityId, description) { setLastAction(entityId, description); markChanged(); },
|
|
607
|
+
handleError,
|
|
608
|
+
getHistory(entityId) { return ruleStore.getHistory(entityId); },
|
|
609
|
+
// ── Keyboard ──
|
|
610
|
+
handleKeydown(e) {
|
|
611
|
+
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
|
|
612
|
+
e.preventDefault();
|
|
613
|
+
const la = core.getLastAction();
|
|
614
|
+
if (la) {
|
|
615
|
+
// Route through the error contract; clear the toast only on success.
|
|
616
|
+
// Fire-and-forget: a rejection (infra error, no onError) was already
|
|
617
|
+
// offered to the contract — swallow here so it never escapes as an
|
|
618
|
+
// unhandled global rejection (rereview F6). The public undo() still
|
|
619
|
+
// rejects loudly for callers that await it.
|
|
620
|
+
void undoSafely(la.entityId).then(ok => { if (ok) {
|
|
621
|
+
core.dismissLastAction();
|
|
622
|
+
markChanged();
|
|
623
|
+
} }, () => { });
|
|
624
|
+
}
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
if (e.key === 'Escape' && !dialog && selection !== null) {
|
|
628
|
+
controller.clearSelection();
|
|
629
|
+
}
|
|
630
|
+
},
|
|
631
|
+
};
|
|
632
|
+
return controller;
|
|
633
|
+
}
|
|
634
|
+
//# sourceMappingURL=create-controller.js.map
|