@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,112 @@
1
+ import { QuartzioError } from '../util/errors';
2
+ import { Draft, type DraftTable } from './draft';
3
+ import { isId, type TouchedRecords } from './normalize';
4
+ import type { Id, Operation, ProjectState, StoreName } from './types';
5
+
6
+ const STORES: readonly string[] = ['calendars', 'tasks', 'dependencies'] satisfies StoreName[];
7
+
8
+ type AnyRecord = { readonly id: Id } & Record<string, unknown>;
9
+
10
+ const clamp = (value: number, max: number): number => Math.max(0, Math.min(value, max));
11
+
12
+ /**
13
+ * Applies one operation to the draft and returns its inverse.
14
+ * Only checks what is needed to keep the tables consistent (ids exist / are unique);
15
+ * semantic validation (parents exist, no cycles, ...) is the transaction's job.
16
+ */
17
+ export function applyOperation(draft: Draft, op: Operation): Operation {
18
+ if (op.type === 'settings') {
19
+ if (typeof op.changes !== 'object' || (op.changes as unknown) === null) {
20
+ throw new QuartzioError('Settings operation: "changes" must be an object.');
21
+ }
22
+ const settings = draft.readSettings();
23
+ const previous: Record<string, unknown> = {};
24
+ for (const key of Object.keys(op.changes) as (keyof typeof settings)[]) previous[key] = settings[key];
25
+ draft.writeSettings({ ...settings, ...op.changes });
26
+ return { type: 'settings', changes: previous };
27
+ }
28
+ // Operations may come from outside (JSON, servers), so don't trust their shape.
29
+ if (!STORES.includes(op.store)) throw new QuartzioError(`Unknown store "${op.store}" in operation.`);
30
+ const table = draft.write(op.store) as unknown as DraftTable<AnyRecord>;
31
+ const store: StoreName = op.store;
32
+ if (op.type === 'update' && (typeof op.changes !== 'object' || (op.changes as unknown) === null)) {
33
+ throw new QuartzioError(`Cannot update ${store} "${String(op.id)}": "changes" must be an object.`);
34
+ }
35
+ // Structure: records added, removed or moved, a task's parent, or a dependency's ends.
36
+ if (op.type !== 'update' || 'parentId' in op.changes || 'from' in op.changes || 'to' in op.changes) {
37
+ draft.markStructure(store);
38
+ }
39
+
40
+ switch (op.type) {
41
+ case 'add': {
42
+ const record = op.record as unknown as AnyRecord;
43
+ if (!isId(record.id)) throw new QuartzioError(`Cannot add ${store}: the record has no valid id.`);
44
+ if (table.byId.has(record.id)) {
45
+ throw new QuartzioError(`Cannot add ${store} "${String(record.id)}": the id already exists.`);
46
+ }
47
+ table.order.splice(clamp(op.index, table.order.length), 0, record.id);
48
+ table.byId.set(record.id, record);
49
+ return { type: 'remove', store, id: record.id };
50
+ }
51
+ case 'remove': {
52
+ const record = table.byId.get(op.id);
53
+ if (!record) throw unknownId(store, op.id, 'remove');
54
+ const index = table.order.indexOf(op.id);
55
+ table.order.splice(index, 1);
56
+ table.byId.delete(op.id);
57
+ return { type: 'add', store, record, index } as unknown as Operation;
58
+ }
59
+ case 'update': {
60
+ const record = table.byId.get(op.id);
61
+ if (!record) throw unknownId(store, op.id, 'update');
62
+ if ('id' in op.changes)
63
+ throw new QuartzioError(`Cannot update ${store} "${String(op.id)}": ids are immutable.`);
64
+ const previous: Record<string, unknown> = {};
65
+ for (const key of Object.keys(op.changes)) previous[key] = record[key];
66
+ table.byId.set(op.id, { ...record, ...op.changes });
67
+ return { type: 'update', store, id: op.id, changes: previous };
68
+ }
69
+ case 'move': {
70
+ if (!table.byId.has(op.id)) throw unknownId(store, op.id, 'move');
71
+ const from = table.order.indexOf(op.id);
72
+ table.order.splice(from, 1);
73
+ table.order.splice(clamp(op.index, table.order.length), 0, op.id);
74
+ return { type: 'move', store, id: op.id, index: from };
75
+ }
76
+ default: {
77
+ const unknown: never = op;
78
+ throw new QuartzioError(`Unknown operation type "${String((unknown as { type: unknown }).type)}".`);
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Applies operations in order and returns the new state, the inverse operations and which records were
85
+ * added or changed (for validation).
86
+ */
87
+ export function applyOperations(
88
+ state: ProjectState,
89
+ operations: readonly Operation[],
90
+ ): { state: ProjectState; inverse: Operation[]; touched: TouchedRecords } {
91
+ const draft = new Draft(state);
92
+ const touched = {
93
+ settings: false,
94
+ calendars: new Set<Id>(),
95
+ tasks: new Set<Id>(),
96
+ dependencies: new Set<Id>(),
97
+ };
98
+ const inverse = operations
99
+ .map((op) => {
100
+ const result = applyOperation(draft, op);
101
+ if (op.type === 'settings') touched.settings = true;
102
+ else if (op.type === 'add') touched[op.store].add(op.record.id);
103
+ else if (op.type === 'update') touched[op.store].add(op.id);
104
+ return result;
105
+ })
106
+ .reverse();
107
+ return { state: draft.finish(), inverse, touched };
108
+ }
109
+
110
+ function unknownId(store: StoreName, id: Id, action: string): QuartzioError {
111
+ return new QuartzioError(`Cannot ${action} ${store} "${String(id)}": no record with that id.`);
112
+ }
@@ -0,0 +1,194 @@
1
+ import { createEmitter } from '../util/emitter';
2
+ import { QuartzioError } from '../util/errors';
3
+ import { Draft } from './draft';
4
+ import { assertTaskDates, assertValidState, createProjectState } from './normalize';
5
+ import { applyOperations } from './operations';
6
+ import { toProjectData } from './serialize';
7
+ import { createTransaction, type IdGenerator, type Transaction } from './transaction';
8
+ import type { Operation, Patch, ProjectData, ProjectInput, ProjectState, StoreName } from './types';
9
+
10
+ export interface ProjectChange {
11
+ readonly state: ProjectState;
12
+ /** `null` when the whole project was replaced via `load()`. */
13
+ readonly patch: Patch | null;
14
+ }
15
+
16
+ export interface PlannedChange {
17
+ readonly state: ProjectState;
18
+ readonly patch: Patch;
19
+ }
20
+
21
+ export interface ProjectOptions {
22
+ /** Creates ids for records added without one. Defaults to `task-1`, `dependency-1`, ... */
23
+ generateId?: IdGenerator;
24
+ /**
25
+ * Completes every change (transactions, `apply`, `load` and the initial data) with more operations, applied
26
+ * in the same change and included in its patch: this is how the scheduler writes computed dates back.
27
+ * Gets the operations that were applied, or `null` for loaded data. Must be pure, and return nothing for a
28
+ * state it already completed; if it throws, the change is rejected.
29
+ */
30
+ propagate?: (state: ProjectState, operations: readonly Operation[] | null) => readonly Operation[];
31
+ }
32
+
33
+ // Property signatures (not methods) so the functions can be passed around unbound.
34
+ export interface Project {
35
+ getState: () => ProjectState;
36
+ subscribe: (listener: (change: ProjectChange) => void) => () => void;
37
+ /**
38
+ * Replaces the whole project. Returns the operations `propagate` added to the loaded data (e.g. computed
39
+ * dates), or `null` when it added none.
40
+ */
41
+ load: (input: ProjectInput) => Patch | null;
42
+ /**
43
+ * Runs `fn` against a draft and commits all its changes at once, emitting a single change.
44
+ * If `fn` throws, nothing is changed. Returns `null` when nothing changed.
45
+ */
46
+ transact: (fn: (tx: Transaction) => void) => Patch | null;
47
+ /**
48
+ * Like `transact`, but only computes the result without committing it.
49
+ * `base` plans on top of another state than the current one (e.g. an earlier planned change).
50
+ */
51
+ plan: (fn: (tx: Transaction) => void, base?: ProjectState) => PlannedChange | null;
52
+ /**
53
+ * Applies operations, e.g. a patch's `inverse` for undo or operations received from a server.
54
+ * The result is validated (parents and dependency ends must exist, no cycles); on failure nothing changes.
55
+ */
56
+ apply: (operations: readonly Operation[]) => Patch | null;
57
+ /** Like `apply`, but only computes the result without committing it (`base` as for `plan`). */
58
+ planApply: (operations: readonly Operation[], base?: ProjectState) => PlannedChange | null;
59
+ toData: () => ProjectData;
60
+ }
61
+
62
+ const PREFIX: Record<StoreName, string> = {
63
+ calendars: 'calendar',
64
+ tasks: 'task',
65
+ dependencies: 'dependency',
66
+ };
67
+
68
+ function createDefaultIdGenerator(): IdGenerator {
69
+ const counters: Record<StoreName, number> = { calendars: 0, tasks: 0, dependencies: 0 };
70
+ return (store, exists) => {
71
+ let id: string;
72
+ do id = `${PREFIX[store]}-${String(++counters[store])}`;
73
+ while (exists(id));
74
+ return id;
75
+ };
76
+ }
77
+
78
+ function isThenable(value: unknown): boolean {
79
+ return (
80
+ typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function'
81
+ );
82
+ }
83
+
84
+ export function createProject(input: ProjectInput = {}, options: ProjectOptions = {}): Project {
85
+ const changes = createEmitter<ProjectChange>();
86
+ const generateId = options.generateId ?? createDefaultIdGenerator();
87
+ const { propagate } = options;
88
+
89
+ /** Applies what `propagate` adds to `base`, returning the state and a patch relative to `base`. */
90
+ const complete = (
91
+ base: ProjectState,
92
+ applied: readonly Operation[] | null,
93
+ ): { state: ProjectState; patch: Patch | null } => {
94
+ const extra = propagate?.(base, applied) ?? [];
95
+ if (extra.length === 0) return { state: base, patch: null };
96
+ const result = applyOperations(base, extra);
97
+ assertValidState(result.state, result.touched);
98
+ return { state: result.state, patch: { operations: [...extra], inverse: result.inverse } };
99
+ };
100
+ /** Joins a change and what propagate added to it into one patch. */
101
+ const join = (first: Patch, second: Patch | null): Patch =>
102
+ second
103
+ ? {
104
+ operations: [...first.operations, ...second.operations],
105
+ inverse: [...second.inverse, ...first.inverse],
106
+ }
107
+ : first;
108
+
109
+ /** Applies operations and what propagate adds, validated, without committing. */
110
+ const applyCompleted = (base: ProjectState, operations: readonly Operation[]): PlannedChange => {
111
+ const result = applyOperations(base, operations);
112
+ // End before start is checked after propagation, which can repair it (like transact does).
113
+ assertValidState(result.state, result.touched, { taskDates: false });
114
+ const completed = complete(result.state, operations);
115
+ for (const id of result.touched.tasks) {
116
+ const task = completed.state.tasks.byId.get(id);
117
+ if (task) assertTaskDates(task);
118
+ }
119
+ return {
120
+ state: completed.state,
121
+ patch: join({ operations: [...operations], inverse: result.inverse }, completed.patch),
122
+ };
123
+ };
124
+
125
+ let state = complete(createProjectState(input), null).state;
126
+ let running = false;
127
+
128
+ const commit = (next: ProjectState, patch: Patch | null): void => {
129
+ state = next;
130
+ changes.emit({ state, patch });
131
+ };
132
+
133
+ const assertNotRunning = (): void => {
134
+ if (running) throw new QuartzioError('Cannot change the project while a transaction is running.');
135
+ };
136
+
137
+ // `fn` is typed as returning `unknown` here: callers pass `=> void`, but an async function still
138
+ // type-checks as that, so the return value is checked at runtime.
139
+ const plan = (fn: (tx: Transaction) => unknown, base: ProjectState = state): PlannedChange | null => {
140
+ assertNotRunning();
141
+ running = true;
142
+ const recorder = createTransaction(new Draft(base), generateId);
143
+ try {
144
+ const result = fn(recorder.transaction);
145
+ if (isThenable(result)) {
146
+ throw new QuartzioError(
147
+ 'Transaction functions must be synchronous. Do the async work before transact().',
148
+ );
149
+ }
150
+ recorder.validate();
151
+ } finally {
152
+ recorder.close();
153
+ running = false;
154
+ }
155
+ if (recorder.operations.length === 0) return null;
156
+ const completed = complete(recorder.draft.finish(), recorder.operations);
157
+ recorder.validateResult(completed.state);
158
+ return {
159
+ state: completed.state,
160
+ patch: join({ operations: recorder.operations, inverse: recorder.inverse }, completed.patch),
161
+ };
162
+ };
163
+
164
+ return {
165
+ getState: () => state,
166
+ subscribe: (listener) => changes.subscribe(listener),
167
+ load(nextInput) {
168
+ assertNotRunning();
169
+ const completed = complete(createProjectState(nextInput, state), null);
170
+ commit(completed.state, null);
171
+ return completed.patch;
172
+ },
173
+ plan,
174
+ transact(fn) {
175
+ const planned = plan(fn);
176
+ if (!planned) return null;
177
+ commit(planned.state, planned.patch);
178
+ return planned.patch;
179
+ },
180
+ planApply(operations, base = state) {
181
+ assertNotRunning();
182
+ if (operations.length === 0) return null;
183
+ return applyCompleted(base, operations);
184
+ },
185
+ apply(operations) {
186
+ assertNotRunning();
187
+ if (operations.length === 0) return null;
188
+ const { state: next, patch } = applyCompleted(state, operations);
189
+ commit(next, patch);
190
+ return patch;
191
+ },
192
+ toData: () => toProjectData(state),
193
+ };
194
+ }
@@ -0,0 +1,26 @@
1
+ import { assertValidState, createProjectState } from './normalize';
2
+ import { applyOperations } from './operations';
3
+ import type { Id, Patch, ProjectData, ProjectState, Table } from './types';
4
+
5
+ const records = <R extends { readonly id: Id }>(table: Table<R>): R[] =>
6
+ table.order.map((id) => table.byId.get(id) as R);
7
+
8
+ /** Converts a state snapshot to the canonical, JSON-serializable data format. */
9
+ export function toProjectData(state: ProjectState): ProjectData {
10
+ return {
11
+ settings: state.settings,
12
+ calendars: records(state.calendars),
13
+ tasks: records(state.tasks),
14
+ dependencies: records(state.dependencies),
15
+ };
16
+ }
17
+
18
+ /**
19
+ * Returns new project data with the patch applied; the input is not modified.
20
+ * Meant for controlled usage: `onChange={({ patch }) => setData((data) => applyPatch(data, patch))}`.
21
+ */
22
+ export function applyPatch(data: ProjectData, patch: Patch): ProjectData {
23
+ const { state, touched } = applyOperations(createProjectState(data), patch.operations);
24
+ assertValidState(state, touched);
25
+ return toProjectData(state);
26
+ }