@quartzio/gantt 0.0.0-stage → 0.0.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 (58) hide show
  1. package/API.md +533 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -2
  4. package/dist/index.d.ts +1341 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +6556 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/styles.css +1299 -0
  9. package/package.json +51 -3
  10. package/src/calendar/duration.ts +42 -0
  11. package/src/calendar/project.ts +29 -0
  12. package/src/calendar/workingCalendar.ts +218 -0
  13. package/src/data/draft.ts +78 -0
  14. package/src/data/graph.ts +215 -0
  15. package/src/data/normalize.ts +661 -0
  16. package/src/data/operations.ts +112 -0
  17. package/src/data/project.ts +194 -0
  18. package/src/data/serialize.ts +26 -0
  19. package/src/data/transaction.ts +460 -0
  20. package/src/data/tree.ts +156 -0
  21. package/src/data/types.ts +229 -0
  22. package/src/index.ts +139 -0
  23. package/src/scheduling/schedule.ts +310 -0
  24. package/src/styles.css +1299 -0
  25. package/src/timeaxis/align.ts +120 -0
  26. package/src/timeaxis/format.ts +72 -0
  27. package/src/timeaxis/presets.ts +219 -0
  28. package/src/timeaxis/timeAxis.ts +205 -0
  29. package/src/util/civil.ts +38 -0
  30. package/src/util/emitter.ts +53 -0
  31. package/src/util/equal.ts +23 -0
  32. package/src/util/errors.ts +4 -0
  33. package/src/util/parse.ts +70 -0
  34. package/src/util/time.ts +18 -0
  35. package/src/util/zone.ts +303 -0
  36. package/src/view/bars.ts +63 -0
  37. package/src/view/binding.ts +162 -0
  38. package/src/view/cellEditor.ts +239 -0
  39. package/src/view/cells.ts +89 -0
  40. package/src/view/columns.ts +197 -0
  41. package/src/view/createGantt.ts +1164 -0
  42. package/src/view/dates.ts +14 -0
  43. package/src/view/dependencies.ts +147 -0
  44. package/src/view/editing.ts +303 -0
  45. package/src/view/history.ts +72 -0
  46. package/src/view/interaction.ts +671 -0
  47. package/src/view/keyboard.ts +149 -0
  48. package/src/view/listWidth.ts +201 -0
  49. package/src/view/menu.ts +265 -0
  50. package/src/view/nonWorking.ts +113 -0
  51. package/src/view/range.ts +41 -0
  52. package/src/view/rows.ts +235 -0
  53. package/src/view/selection.ts +156 -0
  54. package/src/view/taskActions.ts +71 -0
  55. package/src/view/taskEditor.ts +553 -0
  56. package/src/view/timeline.ts +155 -0
  57. package/src/view/tooltip.ts +117 -0
  58. package/src/view/types.ts +328 -0
@@ -0,0 +1,661 @@
1
+ import { deepFreeze, isEqual } from '../util/equal';
2
+ import { QuartzioError } from '../util/errors';
3
+ import { parseCivilDate, parseDateString, parseTimeOfDay } from '../util/parse';
4
+ import { isTimeUnit, type TimeUnit } from '../util/time';
5
+ import { assertTimeZone, type TimeZone } from '../util/zone';
6
+ import { getScheduleGraph, sameDependencyEnds, shareDependencyEnds } from './graph';
7
+ import { shareTreeIndex } from './tree';
8
+ import type {
9
+ Calendar,
10
+ CalendarException,
11
+ ConstraintType,
12
+ CalendarExceptionInput,
13
+ CalendarInput,
14
+ DateInput,
15
+ Dependency,
16
+ DependencyInput,
17
+ DependencyType,
18
+ Id,
19
+ ProjectInput,
20
+ ProjectSettings,
21
+ ProjectSettingsInput,
22
+ ProjectState,
23
+ Table,
24
+ Task,
25
+ TaskInput,
26
+ Weekday,
27
+ WorkingInterval,
28
+ } from './types';
29
+
30
+ const DEPENDENCY_TYPES: readonly DependencyType[] = ['FS', 'SS', 'FF', 'SF'];
31
+
32
+ /** Index = weekday number (0 = Sunday), matching `Date` and `weekStartsOn`. */
33
+ export const WEEKDAYS: readonly Weekday[] = [
34
+ 'sunday',
35
+ 'monday',
36
+ 'tuesday',
37
+ 'wednesday',
38
+ 'thursday',
39
+ 'friday',
40
+ 'saturday',
41
+ ];
42
+
43
+ export const DEFAULT_DURATION_UNIT: TimeUnit = 'day';
44
+ export const DEFAULT_LAG_UNIT: TimeUnit = 'day';
45
+
46
+ export const DEFAULT_SETTINGS: ProjectSettings = deepFreeze({
47
+ timeZone: 'local',
48
+ calendarId: null,
49
+ hoursPerDay: 8,
50
+ daysPerWeek: 5,
51
+ daysPerMonth: 20,
52
+ weekStartsOn: 1,
53
+ startDate: null,
54
+ });
55
+
56
+ const OFFICE_HOURS: readonly WorkingInterval[] = [{ start: '08:00', end: '16:00' }];
57
+
58
+ /** Used when `settings.calendarId` is `null`: Monday–Friday 08:00–16:00, no exceptions. */
59
+ export const STANDARD_CALENDAR: Calendar = deepFreeze({
60
+ id: 'standard',
61
+ name: 'Standard',
62
+ week: {
63
+ sunday: [],
64
+ monday: OFFICE_HOURS,
65
+ tuesday: OFFICE_HOURS,
66
+ wednesday: OFFICE_HOURS,
67
+ thursday: OFFICE_HOURS,
68
+ friday: OFFICE_HOURS,
69
+ saturday: [],
70
+ },
71
+ exceptions: [],
72
+ });
73
+
74
+ const label = (kind: string, id: Id): string => `${kind} "${String(id)}"`;
75
+
76
+ export function isId(value: unknown): value is Id {
77
+ return (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value));
78
+ }
79
+
80
+ // --- Fields ---
81
+
82
+ /** Dates must fall in the years 1000–9999; anything outside is almost certainly a typo. */
83
+ const MIN_TIME = Date.UTC(1000, 0, 1);
84
+ const MAX_TIME = Date.UTC(10_000, 0, 1) - 1;
85
+
86
+ export function toTime(
87
+ value: DateInput | null | undefined,
88
+ field: string,
89
+ owner: string,
90
+ zone: TimeZone,
91
+ ): number | null {
92
+ if (value === null || value === undefined) return null;
93
+ const time =
94
+ typeof value === 'string'
95
+ ? parseDateString(value, zone)
96
+ : value instanceof Date
97
+ ? value.getTime()
98
+ : value;
99
+ if (typeof time !== 'number' || !Number.isFinite(time)) {
100
+ throw new QuartzioError(
101
+ `${owner}: "${field}" must be a valid Date, epoch milliseconds or an ISO 8601 string like "2026-10-05".`,
102
+ );
103
+ }
104
+ if (time < MIN_TIME || time > MAX_TIME) {
105
+ throw new QuartzioError(`${owner}: "${field}" must be between the years 1000 and 9999.`);
106
+ }
107
+ // Fractions of a millisecond would make working-time arithmetic (and so scheduling) inexact.
108
+ if (!Number.isInteger(time)) throw new QuartzioError(`${owner}: "${field}" must be whole milliseconds.`);
109
+ return time;
110
+ }
111
+
112
+ function toName(value: unknown, owner: string): string {
113
+ if (value === undefined) return '';
114
+ if (typeof value !== 'string') throw new QuartzioError(`${owner}: "name" must be a string.`);
115
+ return value;
116
+ }
117
+
118
+ function toDuration(value: number | null | undefined, owner: string): number | null {
119
+ if (value === null || value === undefined) return null;
120
+ if (!Number.isFinite(value) || value < 0) {
121
+ throw new QuartzioError(`${owner}: "duration" must be a finite number >= 0.`);
122
+ }
123
+ return value;
124
+ }
125
+
126
+ function toPercent(value: number | undefined, owner: string): number {
127
+ if (value === undefined) return 0;
128
+ if (!Number.isFinite(value) || value < 0 || value > 100) {
129
+ throw new QuartzioError(`${owner}: "percentDone" must be between 0 and 100.`);
130
+ }
131
+ return value;
132
+ }
133
+
134
+ function toBoolean(value: unknown, field: string, owner: string): boolean {
135
+ if (value === undefined) return false;
136
+ if (typeof value !== 'boolean') throw new QuartzioError(`${owner}: "${field}" must be true or false.`);
137
+ return value;
138
+ }
139
+
140
+ const CONSTRAINT_TYPES: readonly ConstraintType[] = ['startnoearlierthan'];
141
+ // Recognized, so the error can say they're coming rather than unknown.
142
+ const FUTURE_CONSTRAINT_TYPES = [
143
+ 'startnolaterthan',
144
+ 'finishnoearlierthan',
145
+ 'finishnolaterthan',
146
+ 'muststarton',
147
+ 'mustfinishon',
148
+ ];
149
+
150
+ function toConstraintType(value: unknown, owner: string): ConstraintType | null {
151
+ if (value === undefined || value === null) return null;
152
+ if (CONSTRAINT_TYPES.includes(value as ConstraintType)) return value as ConstraintType;
153
+ if (typeof value === 'string' && FUTURE_CONSTRAINT_TYPES.includes(value)) {
154
+ throw new QuartzioError(`${owner}: constraint "${value}" is not supported yet.`);
155
+ }
156
+ throw new QuartzioError(
157
+ `${owner}: "constraintType" must be one of ${CONSTRAINT_TYPES.join(', ')}, or null.`,
158
+ );
159
+ }
160
+
161
+ function toUnit(value: TimeUnit | undefined, fallback: TimeUnit, field: string, owner: string): TimeUnit {
162
+ if (value === undefined) return fallback;
163
+ if (!isTimeUnit(value)) throw new QuartzioError(`${owner}: "${field}" is not a valid time unit.`);
164
+ return value;
165
+ }
166
+
167
+ // --- Tasks ---
168
+
169
+ export type TaskFieldsInput = Omit<TaskInput, 'id' | 'parentId' | 'children'>;
170
+ export type TaskFields = Omit<Task, 'id' | 'parentId'>;
171
+
172
+ export function normalizeTaskFields(input: TaskFieldsInput, owner: string, zone: TimeZone): TaskFields {
173
+ return {
174
+ name: toName(input.name, owner),
175
+ startDate: toTime(input.startDate, 'startDate', owner, zone),
176
+ endDate: toTime(input.endDate, 'endDate', owner, zone),
177
+ duration: toDuration(input.duration, owner),
178
+ durationUnit: toUnit(input.durationUnit, DEFAULT_DURATION_UNIT, 'durationUnit', owner),
179
+ percentDone: toPercent(input.percentDone, owner),
180
+ manuallyScheduled: toBoolean(input.manuallyScheduled, 'manuallyScheduled', owner),
181
+ constraintType: toConstraintType(input.constraintType, owner),
182
+ constraintDate: toTime(input.constraintDate, 'constraintDate', owner, zone),
183
+ };
184
+ }
185
+
186
+ /** Normalizes only the fields present in `input` (for updates). */
187
+ export function normalizeTaskChanges(
188
+ input: TaskFieldsInput,
189
+ owner: string,
190
+ zone: TimeZone,
191
+ ): Partial<TaskFields> {
192
+ const changes: { -readonly [K in keyof TaskFields]?: TaskFields[K] } = {};
193
+ if (input.name !== undefined) changes.name = toName(input.name, owner);
194
+ if (input.startDate !== undefined) changes.startDate = toTime(input.startDate, 'startDate', owner, zone);
195
+ if (input.endDate !== undefined) changes.endDate = toTime(input.endDate, 'endDate', owner, zone);
196
+ if (input.duration !== undefined) changes.duration = toDuration(input.duration, owner);
197
+ if (input.durationUnit !== undefined) {
198
+ changes.durationUnit = toUnit(input.durationUnit, DEFAULT_DURATION_UNIT, 'durationUnit', owner);
199
+ }
200
+ if (input.percentDone !== undefined) changes.percentDone = toPercent(input.percentDone, owner);
201
+ if (input.manuallyScheduled !== undefined) {
202
+ changes.manuallyScheduled = toBoolean(input.manuallyScheduled, 'manuallyScheduled', owner);
203
+ }
204
+ if (input.constraintType !== undefined)
205
+ changes.constraintType = toConstraintType(input.constraintType, owner);
206
+ if (input.constraintDate !== undefined) {
207
+ changes.constraintDate = toTime(input.constraintDate, 'constraintDate', owner, zone);
208
+ }
209
+ return changes;
210
+ }
211
+
212
+ /** Structure is changed with `position`/`move`, not with fields; catch data passed in by mistake. */
213
+ export function assertNoStructureFields(input: object, owner: string): void {
214
+ if ('children' in input) {
215
+ throw new QuartzioError(
216
+ `${owner}: "children" is not supported here. Add child tasks with a parentId position.`,
217
+ );
218
+ }
219
+ if ('parentId' in input) {
220
+ throw new QuartzioError(
221
+ `${owner}: "parentId" is not supported here. Use a position ({ parentId }) or move().`,
222
+ );
223
+ }
224
+ }
225
+
226
+ /** A constraint has a type and a date, or neither. */
227
+ export function assertTaskConstraint(task: Task): void {
228
+ if ((task.constraintType === null) !== (task.constraintDate === null)) {
229
+ throw new QuartzioError(
230
+ `${label('Task', task.id)}: "constraintType" and "constraintDate" are set together (both or neither).`,
231
+ );
232
+ }
233
+ }
234
+
235
+ export function assertTaskDates(task: Task): void {
236
+ if (task.startDate !== null && task.endDate !== null && task.endDate < task.startDate) {
237
+ throw new QuartzioError(`${label('Task', task.id)}: "endDate" is before "startDate".`);
238
+ }
239
+ }
240
+
241
+ // --- Dependencies ---
242
+
243
+ export type DependencyFieldsInput = Omit<DependencyInput, 'id' | 'from' | 'to'>;
244
+ export type DependencyFields = Omit<Dependency, 'id' | 'from' | 'to'>;
245
+
246
+ function toDependencyType(value: DependencyType | undefined, owner: string): DependencyType {
247
+ if (value === undefined) return 'FS';
248
+ if (!DEPENDENCY_TYPES.includes(value)) {
249
+ throw new QuartzioError(`${owner}: "type" must be one of ${DEPENDENCY_TYPES.join(', ')}.`);
250
+ }
251
+ return value;
252
+ }
253
+
254
+ function toLag(value: number | undefined, owner: string): number {
255
+ if (value === undefined) return 0;
256
+ if (!Number.isFinite(value)) throw new QuartzioError(`${owner}: "lag" must be a finite number.`);
257
+ return value;
258
+ }
259
+
260
+ export function normalizeDependencyFields(input: DependencyFieldsInput, owner: string): DependencyFields {
261
+ return {
262
+ type: toDependencyType(input.type, owner),
263
+ lag: toLag(input.lag, owner),
264
+ lagUnit: toUnit(input.lagUnit, DEFAULT_LAG_UNIT, 'lagUnit', owner),
265
+ };
266
+ }
267
+
268
+ export function normalizeDependencyChanges(
269
+ input: DependencyFieldsInput,
270
+ owner: string,
271
+ ): Partial<DependencyFields> {
272
+ const changes: { -readonly [K in keyof DependencyFields]?: DependencyFields[K] } = {};
273
+ if (input.type !== undefined) changes.type = toDependencyType(input.type, owner);
274
+ if (input.lag !== undefined) changes.lag = toLag(input.lag, owner);
275
+ if (input.lagUnit !== undefined)
276
+ changes.lagUnit = toUnit(input.lagUnit, DEFAULT_LAG_UNIT, 'lagUnit', owner);
277
+ return changes;
278
+ }
279
+
280
+ export function assertDependencyEnds(tasks: Table<Task>['byId'], from: Id, to: Id, owner: string): void {
281
+ if (!tasks.has(from)) throw new QuartzioError(`${owner}: "from" task "${String(from)}" does not exist.`);
282
+ if (!tasks.has(to)) throw new QuartzioError(`${owner}: "to" task "${String(to)}" does not exist.`);
283
+ if (from === to) throw new QuartzioError(`${owner}: a task cannot depend on itself.`);
284
+ }
285
+
286
+ // --- Settings ---
287
+
288
+ function toPositive(value: unknown, field: string, max: number): number {
289
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > max) {
290
+ throw new QuartzioError(
291
+ `Project settings: "${field}" must be a number above 0 and at most ${String(max)}.`,
292
+ );
293
+ }
294
+ return value;
295
+ }
296
+
297
+ /**
298
+ * Normalizes only the settings present in `input`. Date strings are read in `input.timeZone`, or `zone` (the
299
+ * project's current time zone) when the input doesn't change it.
300
+ */
301
+ export function normalizeSettingsChanges(
302
+ input: ProjectSettingsInput,
303
+ zone: TimeZone = DEFAULT_SETTINGS.timeZone,
304
+ ): Partial<ProjectSettings> {
305
+ const changes: { -readonly [K in keyof ProjectSettings]?: ProjectSettings[K] } = {};
306
+ if (input.timeZone !== undefined) {
307
+ assertTimeZone(input.timeZone);
308
+ changes.timeZone = input.timeZone;
309
+ }
310
+ if (input.calendarId !== undefined) {
311
+ if (input.calendarId !== null && !isId(input.calendarId)) {
312
+ throw new QuartzioError('Project settings: "calendarId" must be a calendar id or null.');
313
+ }
314
+ changes.calendarId = input.calendarId;
315
+ }
316
+ if (input.hoursPerDay !== undefined) changes.hoursPerDay = toPositive(input.hoursPerDay, 'hoursPerDay', 24);
317
+ if (input.daysPerWeek !== undefined) changes.daysPerWeek = toPositive(input.daysPerWeek, 'daysPerWeek', 7);
318
+ if (input.daysPerMonth !== undefined)
319
+ changes.daysPerMonth = toPositive(input.daysPerMonth, 'daysPerMonth', 31);
320
+ if (input.weekStartsOn !== undefined) {
321
+ if (!Number.isInteger(input.weekStartsOn) || input.weekStartsOn < 0 || input.weekStartsOn > 6) {
322
+ throw new QuartzioError(
323
+ 'Project settings: "weekStartsOn" must be an integer from 0 (Sunday) to 6 (Saturday).',
324
+ );
325
+ }
326
+ changes.weekStartsOn = input.weekStartsOn;
327
+ }
328
+ if (input.startDate !== undefined) {
329
+ changes.startDate = toTime(input.startDate, 'startDate', 'Project settings', changes.timeZone ?? zone);
330
+ }
331
+ return changes;
332
+ }
333
+
334
+ export function normalizeSettings(input: ProjectSettingsInput = {}): ProjectSettings {
335
+ return { ...DEFAULT_SETTINGS, ...normalizeSettingsChanges(input) };
336
+ }
337
+
338
+ // --- Calendars ---
339
+
340
+ function normalizeIntervals(input: unknown, owner: string): readonly WorkingInterval[] {
341
+ if (!Array.isArray(input)) throw new QuartzioError(`${owner}: working intervals must be an array.`);
342
+ const parsed = (input as unknown[]).map((interval) => {
343
+ const { start, end } = (interval ?? {}) as Partial<WorkingInterval>;
344
+ const from = typeof start === 'string' ? parseTimeOfDay(start) : null;
345
+ const to = typeof end === 'string' ? parseTimeOfDay(end) : null;
346
+ if (from === null || to === null || from >= to) {
347
+ throw new QuartzioError(
348
+ `${owner}: working intervals need "start" before "end", as "HH:mm" (e.g. { start: "08:00", end: "16:00" }).`,
349
+ );
350
+ }
351
+ return { start: start as string, end: end as string, from, to };
352
+ });
353
+ parsed.sort((a, b) => a.from - b.from);
354
+ for (let i = 1; i < parsed.length; i++) {
355
+ if ((parsed[i] as { from: number }).from < (parsed[i - 1] as { to: number }).to) {
356
+ throw new QuartzioError(`${owner}: working intervals overlap.`);
357
+ }
358
+ }
359
+ return parsed.map(({ start, end }) => ({ start, end }));
360
+ }
361
+
362
+ function normalizeWeek(input: CalendarInput['week'], owner: string): Calendar['week'] {
363
+ if (input === undefined) return STANDARD_CALENDAR.week;
364
+ const week = {} as Record<Weekday, readonly WorkingInterval[]>;
365
+ for (const day of WEEKDAYS) week[day] = normalizeIntervals(input[day] ?? [], `${owner} (${day})`);
366
+ for (const key of Object.keys(input)) {
367
+ if (!(WEEKDAYS as readonly string[]).includes(key)) {
368
+ throw new QuartzioError(`${owner}: "${key}" is not a weekday. Use ${WEEKDAYS.join(', ')}.`);
369
+ }
370
+ }
371
+ return week;
372
+ }
373
+
374
+ function normalizeException(input: CalendarExceptionInput, owner: string): CalendarException {
375
+ const endDate = input.endDate ?? input.startDate;
376
+ const start = typeof input.startDate === 'string' ? parseCivilDate(input.startDate) : null;
377
+ const end = typeof endDate === 'string' ? parseCivilDate(endDate) : null;
378
+ if (start === null || end === null) {
379
+ throw new QuartzioError(`${owner}: exception dates must be "YYYY-MM-DD".`);
380
+ }
381
+ if (end < start) throw new QuartzioError(`${owner}: exception "endDate" is before "startDate".`);
382
+ return {
383
+ startDate: input.startDate,
384
+ endDate,
385
+ name: toName(input.name, owner),
386
+ intervals: normalizeIntervals(input.intervals ?? [], owner),
387
+ };
388
+ }
389
+
390
+ export type CalendarFieldsInput = Omit<CalendarInput, 'id'>;
391
+ export type CalendarFields = Omit<Calendar, 'id'>;
392
+
393
+ export function normalizeCalendarFields(input: CalendarFieldsInput, owner: string): CalendarFields {
394
+ return {
395
+ name: toName(input.name, owner),
396
+ week: normalizeWeek(input.week, owner),
397
+ exceptions: (input.exceptions ?? []).map((exception) => normalizeException(exception, owner)),
398
+ };
399
+ }
400
+
401
+ export function normalizeCalendarChanges(input: CalendarFieldsInput, owner: string): Partial<CalendarFields> {
402
+ const changes: { -readonly [K in keyof CalendarFields]?: CalendarFields[K] } = {};
403
+ if (input.name !== undefined) changes.name = toName(input.name, owner);
404
+ if (input.week !== undefined) changes.week = normalizeWeek(input.week, owner);
405
+ if (input.exceptions !== undefined) {
406
+ changes.exceptions = input.exceptions.map((exception) => normalizeException(exception, owner));
407
+ }
408
+ return changes;
409
+ }
410
+
411
+ function assertCalendarExists(calendars: ReadonlyMap<Id, Calendar>, calendarId: Id | null): void {
412
+ if (calendarId !== null && !calendars.has(calendarId)) {
413
+ throw new QuartzioError(`Project settings: calendar "${String(calendarId)}" does not exist.`);
414
+ }
415
+ }
416
+
417
+ // --- Structure ---
418
+
419
+ /** Throws if placing task `id` under `parentId` would make the task its own ancestor. */
420
+ export function assertNoParentCycle(byId: ReadonlyMap<Id, Task>, id: Id, parentId: Id | null): void {
421
+ let current = parentId;
422
+ const seen = new Set<Id>();
423
+ while (current !== null) {
424
+ if (current === id) {
425
+ throw new QuartzioError(`${label('Task', id)} cannot be placed inside its own subtree.`);
426
+ }
427
+ if (seen.has(current)) break; // pre-existing cycle elsewhere; reported by load validation
428
+ seen.add(current);
429
+ current = byId.get(current)?.parentId ?? null;
430
+ }
431
+ }
432
+
433
+ /** Throws unless every parent exists and no parent chain loops. O(n). */
434
+ function assertTaskHierarchy(tasks: ReadonlyMap<Id, Task>): void {
435
+ const verified = new Set<Id>();
436
+ for (const task of tasks.values()) {
437
+ const chain = new Set<Id>();
438
+ let current: Task = task;
439
+ while (current.parentId !== null && !verified.has(current.id)) {
440
+ chain.add(current.id);
441
+ const parent = tasks.get(current.parentId);
442
+ if (!parent) {
443
+ throw new QuartzioError(
444
+ `${label('Task', current.id)} has parentId "${String(current.parentId)}", which does not exist.`,
445
+ );
446
+ }
447
+ if (chain.has(parent.id)) {
448
+ throw new QuartzioError(`${label('Task', parent.id)} is part of a parent cycle.`);
449
+ }
450
+ current = parent;
451
+ }
452
+ for (const id of chain) verified.add(id);
453
+ }
454
+ }
455
+
456
+ // --- Whole project ---
457
+
458
+ /** The first candidate structurally equal to `record`, or `record` itself. */
459
+ function reuse<R>(record: R, ...candidates: unknown[]): R {
460
+ for (const candidate of candidates) {
461
+ if (candidate !== undefined && isEqual(candidate, record)) return candidate as R;
462
+ }
463
+ return record;
464
+ }
465
+
466
+ /**
467
+ * Whether two task tables have the same order and parents, so the new one can share the tree index. Checked
468
+ * after reuseTable, for controlled data coming back with field changes only (the common case).
469
+ */
470
+ function sameTaskStructure(table: Table<Task>, previous: Table<Task>): boolean {
471
+ if (previous.order.length !== table.order.length) return false;
472
+ for (let i = 0; i < table.order.length; i++) {
473
+ const id = table.order[i] as Id;
474
+ if (previous.order[i] !== id || previous.byId.get(id)?.parentId !== table.byId.get(id)?.parentId) {
475
+ return false;
476
+ }
477
+ }
478
+ return true;
479
+ }
480
+
481
+ /** The previous table when order and every record are unchanged, so downstream caches keep hitting. */
482
+ function reuseTable<R extends { readonly id: Id }>(
483
+ table: Table<R>,
484
+ previous: Table<R> | undefined,
485
+ ): Table<R> {
486
+ if (previous?.order.length !== table.order.length) return table;
487
+ for (let i = 0; i < table.order.length; i++) {
488
+ const id = table.order[i] as Id;
489
+ if (previous.order[i] !== id || previous.byId.get(id) !== table.byId.get(id)) return table;
490
+ }
491
+ return previous;
492
+ }
493
+
494
+ /**
495
+ * Normalizes and validates user input into an immutable ProjectState. Throws QuartzioError on invalid data.
496
+ *
497
+ * Unchanged records keep their identity: a record equal to the one in `previous` (or to the input object
498
+ * itself, when that is already canonical) is reused, and so is a whole table when nothing in it changed.
499
+ * That lets memoized views skip work after `load()`/`applyPatch()`. Treat data you pass in as immutable.
500
+ */
501
+ export function createProjectState(input: ProjectInput = {}, previous?: ProjectState): ProjectState {
502
+ const settings = reuse(normalizeSettings(input.settings), previous?.settings, input.settings);
503
+
504
+ const calendars = new Map<Id, Calendar>();
505
+ const calendarOrder: Id[] = [];
506
+ for (const calendar of input.calendars ?? []) {
507
+ if (!isId(calendar.id))
508
+ throw new QuartzioError('Calendar id must be a non-empty string or a finite number.');
509
+ const owner = label('Calendar', calendar.id);
510
+ if (calendars.has(calendar.id)) throw new QuartzioError(`${owner} is defined more than once.`);
511
+ const record: Calendar = { id: calendar.id, ...normalizeCalendarFields(calendar, owner) };
512
+ calendars.set(calendar.id, reuse(record, previous?.calendars.byId.get(calendar.id), calendar));
513
+ calendarOrder.push(calendar.id);
514
+ }
515
+ assertCalendarExists(calendars, settings.calendarId);
516
+
517
+ const tasks = new Map<Id, Task>();
518
+ const taskOrder: Id[] = [];
519
+ // Depth-first with an explicit stack (not recursion), so deeply nested input can't overflow the stack.
520
+ const stack: [TaskInput, Id | undefined][] = [...(input.tasks ?? [])]
521
+ .reverse()
522
+ .map((task): [TaskInput, Id | undefined] => [task, undefined]);
523
+ while (stack.length > 0) {
524
+ const [task, nestedParent] = stack.pop() as [TaskInput, Id | undefined];
525
+ if (!isId(task.id)) throw new QuartzioError('Task id must be a non-empty string or a finite number.');
526
+ const owner = label('Task', task.id);
527
+ if (tasks.has(task.id)) throw new QuartzioError(`${owner} is defined more than once.`);
528
+ if (nestedParent !== undefined && task.parentId != null && task.parentId !== nestedParent) {
529
+ throw new QuartzioError(
530
+ `${owner} is nested under "${String(nestedParent)}" but has parentId "${String(task.parentId)}".`,
531
+ );
532
+ }
533
+ const record: Task = {
534
+ id: task.id,
535
+ parentId: nestedParent ?? task.parentId ?? null,
536
+ ...normalizeTaskFields(task, owner, settings.timeZone),
537
+ };
538
+ assertTaskDates(record);
539
+ assertTaskConstraint(record);
540
+ tasks.set(task.id, reuse(record, previous?.tasks.byId.get(task.id), task));
541
+ taskOrder.push(task.id);
542
+ const children: unknown = task.children ?? [];
543
+ if (!Array.isArray(children)) throw new QuartzioError(`${owner}: "children" must be an array.`);
544
+ for (let i = children.length - 1; i >= 0; i--) stack.push([children[i] as TaskInput, task.id]);
545
+ }
546
+ assertTaskHierarchy(tasks);
547
+
548
+ const dependencies = new Map<Id, Dependency>();
549
+ const dependencyOrder: Id[] = [];
550
+ for (const dependency of input.dependencies ?? []) {
551
+ if (!isId(dependency.id)) {
552
+ throw new QuartzioError('Dependency id must be a non-empty string or a finite number.');
553
+ }
554
+ const owner = label('Dependency', dependency.id);
555
+ if (dependencies.has(dependency.id)) throw new QuartzioError(`${owner} is defined more than once.`);
556
+ assertDependencyEnds(tasks, dependency.from, dependency.to, owner);
557
+ const record: Dependency = {
558
+ id: dependency.id,
559
+ from: dependency.from,
560
+ to: dependency.to,
561
+ ...normalizeDependencyFields(dependency, owner),
562
+ };
563
+ dependencies.set(
564
+ dependency.id,
565
+ reuse(record, previous?.dependencies.byId.get(dependency.id), dependency),
566
+ );
567
+ dependencyOrder.push(dependency.id);
568
+ }
569
+
570
+ const taskTable = reuseTable({ byId: tasks, order: taskOrder }, previous?.tasks);
571
+ if (previous && sameTaskStructure(taskTable, previous.tasks)) shareTreeIndex(previous.tasks, taskTable);
572
+
573
+ const dependencyTable = reuseTable({ byId: dependencies, order: dependencyOrder }, previous?.dependencies);
574
+ if (previous && sameDependencyEnds(dependencyTable, previous.dependencies)) {
575
+ shareDependencyEnds(previous.dependencies, dependencyTable);
576
+ }
577
+ const state: ProjectState = {
578
+ settings,
579
+ calendars: reuseTable({ byId: calendars, order: calendarOrder }, previous?.calendars),
580
+ tasks: taskTable,
581
+ dependencies: dependencyTable,
582
+ };
583
+ getScheduleGraph(state); // rejects dependency cycles
584
+ return state;
585
+ }
586
+
587
+ /** Records touched by operations from outside; only these get full field validation. */
588
+ export interface TouchedRecords {
589
+ settings: boolean;
590
+ calendars: ReadonlySet<Id>;
591
+ tasks: ReadonlySet<Id>;
592
+ dependencies: ReadonlySet<Id>;
593
+ }
594
+
595
+ function assertNormalized(record: object, expected: object, owner: string): void {
596
+ if (!isEqual(record, expected)) {
597
+ throw new QuartzioError(
598
+ `${owner} is not a valid, normalized record (from an operation that was applied).`,
599
+ );
600
+ }
601
+ }
602
+
603
+ function assertValidSettings(settings: ProjectSettings): void {
604
+ for (const [key, value] of Object.entries(settings)) {
605
+ if (!Object.hasOwn(DEFAULT_SETTINGS, key))
606
+ throw new QuartzioError(`Project settings: unknown setting "${key}".`);
607
+ if (value === undefined) throw new QuartzioError(`Project settings: "${key}" is undefined.`);
608
+ }
609
+ assertNormalized(settings, normalizeSettings(settings), 'Project settings');
610
+ }
611
+
612
+ /**
613
+ * Checks the invariants of a state produced by applying operations from outside (undo stacks, servers).
614
+ * Transactions keep these invariants by construction. Structure is checked in O(n); record fields only
615
+ * for `touched` records (all records when omitted).
616
+ */
617
+ export function assertValidState(
618
+ state: ProjectState,
619
+ touched?: TouchedRecords,
620
+ { taskDates = true }: { taskDates?: boolean } = {},
621
+ ): void {
622
+ const check = <R>(store: keyof Omit<TouchedRecords, 'settings'>, table: Table<R & { readonly id: Id }>) =>
623
+ touched ? [...touched[store]].flatMap((id) => table.byId.get(id) ?? []) : [...table.byId.values()];
624
+
625
+ if (!touched || touched.settings) assertValidSettings(state.settings);
626
+ assertCalendarExists(state.calendars.byId, state.settings.calendarId);
627
+
628
+ for (const calendar of check('calendars', state.calendars)) {
629
+ const owner = label('Calendar', calendar.id);
630
+ if (!isId(calendar.id)) throw new QuartzioError(`${owner}: invalid id.`);
631
+ assertNormalized(calendar, { id: calendar.id, ...normalizeCalendarFields(calendar, owner) }, owner);
632
+ }
633
+
634
+ for (const task of check('tasks', state.tasks)) {
635
+ const owner = label('Task', task.id);
636
+ if (!isId(task.id) || (task.parentId !== null && !isId(task.parentId))) {
637
+ throw new QuartzioError(`${owner}: invalid id or parentId.`);
638
+ }
639
+ // Stored dates are numbers, so the zone passed here doesn't matter; strings would fail the comparison.
640
+ assertNormalized(
641
+ task,
642
+ { id: task.id, parentId: task.parentId, ...normalizeTaskFields(task, owner, 'UTC') },
643
+ owner,
644
+ );
645
+ if (taskDates) assertTaskDates(task);
646
+ assertTaskConstraint(task);
647
+ }
648
+ assertTaskHierarchy(state.tasks.byId);
649
+
650
+ const touchedDependencies = new Set(check('dependencies', state.dependencies));
651
+ for (const dependency of state.dependencies.byId.values()) {
652
+ const owner = label('Dependency', dependency.id);
653
+ assertDependencyEnds(state.tasks.byId, dependency.from, dependency.to, owner);
654
+ if (touchedDependencies.has(dependency)) {
655
+ const { id, from, to } = dependency;
656
+ assertNormalized(dependency, { id, from, to, ...normalizeDependencyFields(dependency, owner) }, owner);
657
+ }
658
+ }
659
+ // Cycles, including ones through the hierarchy. Cached per structure, so field edits don't repeat it.
660
+ getScheduleGraph(state);
661
+ }