@salmonui/gantt 0.0.0-stage → 0.3.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 (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +43 -2
  3. package/dist/gantt/Gantt.d.ts +5 -0
  4. package/dist/gantt/Gantt.d.ts.map +1 -0
  5. package/dist/gantt/Gantt.js +516 -0
  6. package/dist/gantt/Gantt.js.map +1 -0
  7. package/dist/gantt/adaptive.d.ts +8 -0
  8. package/dist/gantt/adaptive.d.ts.map +1 -0
  9. package/dist/gantt/adaptive.js +38 -0
  10. package/dist/gantt/adaptive.js.map +1 -0
  11. package/dist/gantt/api.d.ts +9 -0
  12. package/dist/gantt/api.d.ts.map +1 -0
  13. package/dist/gantt/api.js +181 -0
  14. package/dist/gantt/api.js.map +1 -0
  15. package/dist/gantt/chart.d.ts +70 -0
  16. package/dist/gantt/chart.d.ts.map +1 -0
  17. package/dist/gantt/chart.js +580 -0
  18. package/dist/gantt/chart.js.map +1 -0
  19. package/dist/gantt/columns.d.ts +9 -0
  20. package/dist/gantt/columns.d.ts.map +1 -0
  21. package/dist/gantt/columns.js +139 -0
  22. package/dist/gantt/columns.js.map +1 -0
  23. package/dist/gantt/export.d.ts +53 -0
  24. package/dist/gantt/export.d.ts.map +1 -0
  25. package/dist/gantt/export.js +241 -0
  26. package/dist/gantt/export.js.map +1 -0
  27. package/dist/gantt/fields.d.ts +42 -0
  28. package/dist/gantt/fields.d.ts.map +1 -0
  29. package/dist/gantt/fields.js +235 -0
  30. package/dist/gantt/fields.js.map +1 -0
  31. package/dist/gantt/instance.d.ts +214 -0
  32. package/dist/gantt/instance.d.ts.map +1 -0
  33. package/dist/gantt/instance.js +1029 -0
  34. package/dist/gantt/instance.js.map +1 -0
  35. package/dist/gantt/interact.d.ts +7 -0
  36. package/dist/gantt/interact.d.ts.map +1 -0
  37. package/dist/gantt/interact.js +315 -0
  38. package/dist/gantt/interact.js.map +1 -0
  39. package/dist/gantt/loading.d.ts +21 -0
  40. package/dist/gantt/loading.d.ts.map +1 -0
  41. package/dist/gantt/loading.js +81 -0
  42. package/dist/gantt/loading.js.map +1 -0
  43. package/dist/gantt/locale.d.ts +161 -0
  44. package/dist/gantt/locale.d.ts.map +1 -0
  45. package/dist/gantt/locale.js +145 -0
  46. package/dist/gantt/locale.js.map +1 -0
  47. package/dist/gantt/menu-items.d.ts +8 -0
  48. package/dist/gantt/menu-items.d.ts.map +1 -0
  49. package/dist/gantt/menu-items.js +16 -0
  50. package/dist/gantt/menu-items.js.map +1 -0
  51. package/dist/gantt/menu-run.d.ts +5 -0
  52. package/dist/gantt/menu-run.d.ts.map +1 -0
  53. package/dist/gantt/menu-run.js +69 -0
  54. package/dist/gantt/menu-run.js.map +1 -0
  55. package/dist/gantt/modules.d.ts +19 -0
  56. package/dist/gantt/modules.d.ts.map +1 -0
  57. package/dist/gantt/modules.js +8 -0
  58. package/dist/gantt/modules.js.map +1 -0
  59. package/dist/gantt/popups.d.ts +23 -0
  60. package/dist/gantt/popups.d.ts.map +1 -0
  61. package/dist/gantt/popups.js +158 -0
  62. package/dist/gantt/popups.js.map +1 -0
  63. package/dist/gantt/registry-lazy.d.ts +4 -0
  64. package/dist/gantt/registry-lazy.d.ts.map +1 -0
  65. package/dist/gantt/registry-lazy.js +54 -0
  66. package/dist/gantt/registry-lazy.js.map +1 -0
  67. package/dist/gantt/registry-static.d.ts +4 -0
  68. package/dist/gantt/registry-static.d.ts.map +1 -0
  69. package/dist/gantt/registry-static.js +13 -0
  70. package/dist/gantt/registry-static.js.map +1 -0
  71. package/dist/gantt/remote.d.ts +16 -0
  72. package/dist/gantt/remote.d.ts.map +1 -0
  73. package/dist/gantt/remote.js +178 -0
  74. package/dist/gantt/remote.js.map +1 -0
  75. package/dist/gantt/resource-view.d.ts +57 -0
  76. package/dist/gantt/resource-view.d.ts.map +1 -0
  77. package/dist/gantt/resource-view.js +123 -0
  78. package/dist/gantt/resource-view.js.map +1 -0
  79. package/dist/gantt/toolbar.d.ts +11 -0
  80. package/dist/gantt/toolbar.d.ts.map +1 -0
  81. package/dist/gantt/toolbar.js +166 -0
  82. package/dist/gantt/toolbar.js.map +1 -0
  83. package/dist/gantt/tooltip.d.ts +7 -0
  84. package/dist/gantt/tooltip.d.ts.map +1 -0
  85. package/dist/gantt/tooltip.js +180 -0
  86. package/dist/gantt/tooltip.js.map +1 -0
  87. package/dist/gantt/types.d.ts +625 -0
  88. package/dist/gantt/types.d.ts.map +1 -0
  89. package/dist/gantt/types.js +7 -0
  90. package/dist/gantt/types.js.map +1 -0
  91. package/dist/gantt.css +5593 -0
  92. package/dist/gantt.d.ts +6 -0
  93. package/dist/gantt.d.ts.map +1 -0
  94. package/dist/gantt.js +13 -0
  95. package/dist/gantt.js.map +1 -0
  96. package/dist/internal/timeline/project/calendar.d.ts +50 -0
  97. package/dist/internal/timeline/project/calendar.d.ts.map +1 -0
  98. package/dist/internal/timeline/project/calendar.js +312 -0
  99. package/dist/internal/timeline/project/calendar.js.map +1 -0
  100. package/dist/internal/timeline/project/critical.d.ts +34 -0
  101. package/dist/internal/timeline/project/critical.d.ts.map +1 -0
  102. package/dist/internal/timeline/project/critical.js +135 -0
  103. package/dist/internal/timeline/project/critical.js.map +1 -0
  104. package/dist/internal/timeline/project/dependencies.d.ts +16 -0
  105. package/dist/internal/timeline/project/dependencies.d.ts.map +1 -0
  106. package/dist/internal/timeline/project/dependencies.js +87 -0
  107. package/dist/internal/timeline/project/dependencies.js.map +1 -0
  108. package/dist/internal/timeline/project/engine.d.ts +118 -0
  109. package/dist/internal/timeline/project/engine.d.ts.map +1 -0
  110. package/dist/internal/timeline/project/engine.js +1907 -0
  111. package/dist/internal/timeline/project/engine.js.map +1 -0
  112. package/dist/internal/timeline/project/format.d.ts +22 -0
  113. package/dist/internal/timeline/project/format.d.ts.map +1 -0
  114. package/dist/internal/timeline/project/format.js +41 -0
  115. package/dist/internal/timeline/project/format.js.map +1 -0
  116. package/dist/internal/timeline/project/history.d.ts +27 -0
  117. package/dist/internal/timeline/project/history.d.ts.map +1 -0
  118. package/dist/internal/timeline/project/history.js +74 -0
  119. package/dist/internal/timeline/project/history.js.map +1 -0
  120. package/dist/internal/timeline/project/resources.d.ts +26 -0
  121. package/dist/internal/timeline/project/resources.d.ts.map +1 -0
  122. package/dist/internal/timeline/project/resources.js +109 -0
  123. package/dist/internal/timeline/project/resources.js.map +1 -0
  124. package/dist/internal/timeline/project/types.d.ts +99 -0
  125. package/dist/internal/timeline/project/types.d.ts.map +1 -0
  126. package/dist/internal/timeline/project/types.js +6 -0
  127. package/dist/internal/timeline/project/types.js.map +1 -0
  128. package/dist/internal/timeline/scale.d.ts +60 -0
  129. package/dist/internal/timeline/scale.d.ts.map +1 -0
  130. package/dist/internal/timeline/scale.js +156 -0
  131. package/dist/internal/timeline/scale.js.map +1 -0
  132. package/package.json +55 -4
@@ -0,0 +1,1907 @@
1
+ // Project scheduling engine (project
2
+ // subsystem of `internal/timeline`, with change
3
+ // records): the task tree, working-time duration math, task modes and
4
+ // types, constraints, dependency propagation with lag (parent dependencies
5
+ // through parent gates), cycle detection, roll-ups, validation, tree edits and
6
+ // the per-task frozen `TaskSchedule`. The graph has two nodes per task (the
7
+ // task or roll-up node and a parent gate that carries a parent's
8
+ // dependencies to its children) in one topological order; an edit marks
9
+ // nodes dirty and recomputes forward from the first dirty position, so only
10
+ // the affected subgraph is rescheduled. Numeric state lives in one strided
11
+ // Float64Array. Pure: no React, no DOM globals, zero dependencies, no
12
+ // module-level mutable state.
13
+ import { createWorkCalendar } from './calendar.js';
14
+ import { formatDependency } from './dependencies.js';
15
+ import { formatDurationValue, parseDurationText } from './format.js';
16
+ // ---------------------------------------------------------------------------
17
+ const CONSTRAINT = {
18
+ asSoonAsPossible: 0,
19
+ asLateAsPossible: 1,
20
+ startNoEarlierThan: 2,
21
+ startNoLaterThan: 3,
22
+ finishNoEarlierThan: 4,
23
+ finishNoLaterThan: 5,
24
+ mustStartOn: 6,
25
+ mustFinishOn: 7,
26
+ };
27
+ const DEP_CODE = { fs: 0, ss: 1, ff: 2, sf: 3 };
28
+ const DEP_NAME = ['fs', 'ss', 'ff', 'sf'];
29
+ const EMPTY = Object.freeze([]);
30
+ /** Tolerance (ms) when comparing a requested start with the allowed one. */
31
+ const TOL = 500;
32
+ // Strided numeric state per task.
33
+ const S = 0; // start (final)
34
+ const E = 1; // end (final)
35
+ const ES = 2; // early start (what successors read)
36
+ const EE = 3; // early end
37
+ const W = 4; // working ms of the duration
38
+ const SW = 5; // roll-up weight (leaf duration, 0 for milestones; parents: sum)
39
+ const SWP = 6; // weight x progress
40
+ const PR = 7; // parent progress
41
+ const RS = 8; // roll-up start
42
+ const RE = 9; // roll-up end
43
+ const G = 10; // parent gate: earliest start its dependencies allow its children
44
+ const B = 11; // dependency bound of the last computation
45
+ const UN = 12; // unscheduled
46
+ const BP = 13; // bound predecessor index
47
+ const BT = 14; // bound type code
48
+ const GP = 15; // gate predecessor index
49
+ const GT = 16; // gate type code
50
+ const WK = 17; // work ms (duration x units; parents: sum)
51
+ const K = 18;
52
+ const same = (a, b) => a === b || (a !== a && b !== b);
53
+ const finite = (v) => typeof v === 'number' && Number.isFinite(v);
54
+ const round4 = (v) => Math.round(v * 1e4) / 1e4;
55
+ function makeCtx(opt) {
56
+ const holidays = opt.holidays ?? [];
57
+ const base = createWorkCalendar(opt.workingTime, holidays);
58
+ const named = new Map();
59
+ for (const c of opt.calendars ?? [])
60
+ named.set(c.id, createWorkCalendar(c.workingTime ?? opt.workingTime, [...(c.exceptions ?? []), ...holidays]));
61
+ return {
62
+ opt,
63
+ base,
64
+ project: (opt.projectCalendar && named.get(opt.projectCalendar)) || base,
65
+ named,
66
+ autoSchedule: opt.autoSchedule !== false,
67
+ taskMode: opt.taskMode ?? 'auto',
68
+ durationUnit: opt.durationUnit ?? 'day',
69
+ workUnit: opt.workUnit ?? 'hour',
70
+ taskType: opt.taskType ?? 'fixedUnit',
71
+ validateManual: opt.validateManualTasks === true,
72
+ parentDeps: opt.parentDependencies !== false,
73
+ allowed: new Set(opt.dependencyTypes ?? DEP_NAME),
74
+ unscheduledTasks: opt.unscheduledTasks === true,
75
+ };
76
+ }
77
+ /** Start snapping: tasks to the next working start, milestones also stay at a range end. */
78
+ function snap(cal, t, span) {
79
+ if (!Number.isFinite(t))
80
+ return t;
81
+ if (span > 0)
82
+ return cal.nextWorkingStart(t);
83
+ return cal.prevWorkingEnd(t) === t ? t : cal.nextWorkingStart(t);
84
+ }
85
+ function unitsOf(resources) {
86
+ if (!resources || !resources.length)
87
+ return 1;
88
+ let sum = 0;
89
+ for (const r of resources)
90
+ sum += finite(r.unit) ? r.unit : 100;
91
+ return sum / 100;
92
+ }
93
+ function prepare(input, parent, ctx, defaultStart) {
94
+ const cal = (input.calendar && ctx.named.get(input.calendar)) || ctx.project;
95
+ const unit = input.durationUnit ?? ctx.durationUnit;
96
+ const manual = ctx.taskMode === 'manual' || (ctx.taskMode === 'custom' && input.manual === true);
97
+ const auto = !manual && ctx.autoSchedule;
98
+ const s = finite(input.start) ? input.start : NaN;
99
+ const e = finite(input.end) ? input.end : NaN;
100
+ const dur = finite(input.duration) && input.duration >= 0 ? input.duration : NaN;
101
+ const units = unitsOf(input.resources);
102
+ const hasDates = !Number.isNaN(s) || !Number.isNaN(e);
103
+ let segOff = null;
104
+ let segLen = null;
105
+ let w;
106
+ let span;
107
+ let first = s;
108
+ const segs = !parent ? input.segments : null;
109
+ if (segs && segs.length > 1) {
110
+ const abs = [];
111
+ let prev = Number.isNaN(s) ? defaultStart : s;
112
+ for (const g of segs) {
113
+ let a = finite(g.start) ? g.start : prev;
114
+ if (auto)
115
+ a = cal.nextWorkingStart(a);
116
+ const b = finite(g.end) ? g.end : cal.addWork(a, finite(g.duration) ? Math.round(cal.toWorkMs(g.duration, unit)) : cal.unitMs('day'));
117
+ abs.push([a, Math.max(a, b)]);
118
+ prev = Math.max(a, b);
119
+ }
120
+ abs.sort((x, y) => x[0] - y[0]);
121
+ const s0 = abs[0][0];
122
+ segOff = new Float64Array(abs.length);
123
+ segLen = new Float64Array(abs.length);
124
+ w = 0;
125
+ for (let k = 0; k < abs.length; k++) {
126
+ const [a, b] = abs[k];
127
+ segOff[k] = Math.max(k ? segOff[k - 1] + segLen[k - 1] : 0, cal.workBetween(s0, a));
128
+ segLen[k] = Math.max(0, cal.workBetween(a, b));
129
+ w += segLen[k];
130
+ }
131
+ span = segOff[abs.length - 1] + segLen[abs.length - 1];
132
+ if (Number.isNaN(first))
133
+ first = s0;
134
+ }
135
+ else {
136
+ if (!parent && input.milestone === true)
137
+ w = 0;
138
+ else if (!Number.isNaN(dur))
139
+ w = Math.round(cal.toWorkMs(dur, unit));
140
+ else if (!Number.isNaN(s) && !Number.isNaN(e))
141
+ w = Math.max(0, cal.workBetween(auto ? cal.nextWorkingStart(s) : s, e));
142
+ else if (finite(input.work) && input.work >= 0)
143
+ w = Math.round((input.work * cal.unitMs(ctx.workUnit)) / units);
144
+ else
145
+ w = cal.unitMs('day');
146
+ span = w;
147
+ }
148
+ const unscheduled = ctx.unscheduledTasks && Number.isNaN(s) && Number.isNaN(e) && Number.isNaN(dur) && !segOff;
149
+ let dStart;
150
+ if (!Number.isNaN(first))
151
+ dStart = auto ? snap(cal, first, span) : first;
152
+ else if (!Number.isNaN(e))
153
+ dStart = auto ? snap(cal, cal.addWork(e, -span), span) : cal.addWork(e, -span);
154
+ else
155
+ dStart = auto ? snap(cal, defaultStart, span) : defaultStart;
156
+ const dEnd = !auto && !Number.isNaN(e) && Number.isNaN(dur) && !segOff && !Number.isNaN(s) ? e : span ? cal.addWork(dStart, span) : dStart;
157
+ let cType = CONSTRAINT[input.constraintType ?? 'asSoonAsPossible'] ?? 0;
158
+ const cDate = finite(input.constraintDate) ? input.constraintDate : NaN;
159
+ if (cType > 1 && Number.isNaN(cDate))
160
+ cType = 0;
161
+ return {
162
+ input,
163
+ cal,
164
+ auto,
165
+ manual,
166
+ unscheduled,
167
+ milestone: !parent && !unscheduled && w === 0,
168
+ hasDates,
169
+ dStart,
170
+ dEnd,
171
+ w,
172
+ span,
173
+ segOff,
174
+ segLen,
175
+ units,
176
+ progress: Math.max(0, Math.min(100, finite(input.progress) ? input.progress : 0)),
177
+ cType,
178
+ cDate,
179
+ unit,
180
+ taskType: input.taskType ?? ctx.taskType,
181
+ };
182
+ }
183
+ /** Tree order of a list: DFS from roots in array order; children in array order; parent cycles become roots. */
184
+ function treeOrder(list) {
185
+ const ids = new Map();
186
+ const keep = [];
187
+ list.forEach((t, i) => {
188
+ if (!ids.has(t.id)) {
189
+ ids.set(t.id, i);
190
+ keep.push(i);
191
+ }
192
+ });
193
+ const kids = new Map();
194
+ const roots = [];
195
+ for (const i of keep) {
196
+ const p = list[i].parentId;
197
+ const pi = p === null || p === undefined ? undefined : ids.get(p);
198
+ if (pi === undefined || pi === i)
199
+ roots.push(i);
200
+ else {
201
+ let arr = kids.get(pi);
202
+ if (!arr)
203
+ kids.set(pi, (arr = []));
204
+ arr.push(i);
205
+ }
206
+ }
207
+ const out = [];
208
+ const seen = new Uint8Array(list.length);
209
+ const visit = (r) => {
210
+ const stack = [r];
211
+ while (stack.length) {
212
+ const i = stack.pop();
213
+ if (seen[i])
214
+ continue;
215
+ seen[i] = 1;
216
+ out.push(list[i]);
217
+ const c = kids.get(i);
218
+ if (c)
219
+ for (let k = c.length - 1; k >= 0; k--)
220
+ stack.push(c[k]);
221
+ }
222
+ };
223
+ for (const r of roots)
224
+ visit(r);
225
+ for (const i of keep)
226
+ if (!seen[i])
227
+ visit(i);
228
+ return out;
229
+ }
230
+ function buildGraph(w, ctx) {
231
+ const { n, ids, isParent, prep } = w;
232
+ const depStart = new Int32Array(n + 1);
233
+ const pred = [];
234
+ const type = [];
235
+ const lag = [];
236
+ const index = [];
237
+ for (let s = 0; s < n; s++) {
238
+ depStart[s] = pred.length;
239
+ const p = prep[s];
240
+ const deps = p.input.predecessors;
241
+ if (!deps)
242
+ continue;
243
+ for (let j = 0; j < deps.length; j++) {
244
+ const d = deps[j];
245
+ const q = ids.get(d.id);
246
+ if (q === undefined || q === s || !ctx.allowed.has(d.type))
247
+ continue;
248
+ if (!ctx.parentDeps && (isParent[q] || isParent[s]))
249
+ continue;
250
+ pred.push(q);
251
+ type.push(DEP_CODE[d.type] ?? 0);
252
+ lag.push(finite(d.lag) ? Math.round(p.cal.toWorkMs(d.lag, d.lagUnit ?? 'day')) : 0);
253
+ index.push(j);
254
+ }
255
+ }
256
+ depStart[n] = pred.length;
257
+ const m = pred.length;
258
+ const depSucc = new Int32Array(m);
259
+ for (let s = 0; s < n; s++)
260
+ for (let d = depStart[s]; d < depStart[s + 1]; d++)
261
+ depSucc[d] = s;
262
+ const N = 2 * n;
263
+ // Edges: deps, gate -> child, child -> parent.
264
+ const from = [];
265
+ const to = [];
266
+ const dep = [];
267
+ for (let d = 0; d < m; d++) {
268
+ const s = depSucc[d];
269
+ from.push(pred[d]);
270
+ to.push(isParent[s] ? n + s : s);
271
+ dep.push(d);
272
+ }
273
+ for (let p = 0; p < n; p++) {
274
+ if (!isParent[p])
275
+ continue;
276
+ for (let k = w.childStart[p]; k < w.childStart[p + 1]; k++) {
277
+ const c = w.childList[k];
278
+ from.push(n + p);
279
+ to.push(isParent[c] ? n + c : c);
280
+ dep.push(-1);
281
+ from.push(c);
282
+ to.push(p);
283
+ dep.push(-1);
284
+ }
285
+ }
286
+ const M = from.length;
287
+ const outStart = new Int32Array(N + 1);
288
+ // Counting sort into CSR.
289
+ const deg = new Int32Array(N + 1);
290
+ for (let e = 0; e < M; e++)
291
+ deg[from[e] + 1] = deg[from[e] + 1] + 1;
292
+ for (let v = 0; v < N; v++)
293
+ deg[v + 1] = deg[v + 1] + deg[v];
294
+ outStart.set(deg);
295
+ const fill = deg.slice(0, N);
296
+ const outTo = new Int32Array(M);
297
+ const outDep = new Int32Array(M);
298
+ for (let e = 0; e < M; e++) {
299
+ const f = from[e];
300
+ const at = fill[f];
301
+ fill[f] = at + 1;
302
+ outTo[at] = to[e];
303
+ outDep[at] = dep[e];
304
+ }
305
+ // Kahn's algorithm; a stuck remainder is a cycle: drop its closing link and continue.
306
+ const indeg = new Int32Array(N);
307
+ for (let e = 0; e < M; e++)
308
+ indeg[outTo[e]] = indeg[outTo[e]] + 1;
309
+ const depDropped = new Uint8Array(m);
310
+ let droppedCount = 0;
311
+ const topo = new Int32Array(N);
312
+ const done = new Uint8Array(N);
313
+ let head = 0;
314
+ let tail = 0;
315
+ for (let v = 0; v < N; v++)
316
+ if (!indeg[v])
317
+ topo[tail++] = v;
318
+ let inStart = null;
319
+ let inFrom = null;
320
+ let inEdge = null;
321
+ let scan = 0;
322
+ while (tail < N) {
323
+ while (head < tail) {
324
+ const v = topo[head++];
325
+ done[v] = 1;
326
+ for (let e = outStart[v]; e < outStart[v + 1]; e++) {
327
+ const d = outDep[e];
328
+ if (d >= 0 && depDropped[d])
329
+ continue;
330
+ const t = outTo[e];
331
+ indeg[t] = indeg[t] - 1;
332
+ if (!indeg[t])
333
+ topo[tail++] = t;
334
+ }
335
+ }
336
+ if (tail >= N)
337
+ break;
338
+ if (!inStart || !inFrom || !inEdge) {
339
+ inStart = new Int32Array(N + 1);
340
+ for (let e = 0; e < M; e++)
341
+ inStart[outTo[e] + 1] = inStart[outTo[e] + 1] + 1;
342
+ for (let v = 0; v < N; v++)
343
+ inStart[v + 1] = inStart[v + 1] + inStart[v];
344
+ const f2 = inStart.slice(0, N);
345
+ inFrom = new Int32Array(M);
346
+ inEdge = new Int32Array(M);
347
+ for (let v = 0; v < N; v++)
348
+ for (let e = outStart[v]; e < outStart[v + 1]; e++) {
349
+ const t = outTo[e];
350
+ const at = f2[t];
351
+ f2[t] = at + 1;
352
+ inFrom[at] = v;
353
+ inEdge[at] = e;
354
+ }
355
+ }
356
+ while (scan < N && (done[scan] || !indeg[scan]))
357
+ scan++;
358
+ const v0 = scan;
359
+ // Walk backwards along live edges from unfinished nodes until a node repeats.
360
+ const via = new Map();
361
+ let cur = v0;
362
+ while (!via.has(cur)) {
363
+ let picked = -1;
364
+ for (let k = inStart[cur]; k < inStart[cur + 1]; k++) {
365
+ const e = inEdge[k];
366
+ const d = outDep[e];
367
+ if (d >= 0 && depDropped[d])
368
+ continue;
369
+ if (!done[inFrom[k]]) {
370
+ picked = k;
371
+ break;
372
+ }
373
+ }
374
+ if (picked < 0)
375
+ break;
376
+ via.set(cur, picked);
377
+ cur = inFrom[picked];
378
+ }
379
+ let drop = -1;
380
+ if (via.has(cur)) {
381
+ const startNode = cur;
382
+ let x = startNode;
383
+ let rank = -1;
384
+ do {
385
+ const k = via.get(x);
386
+ const d = outDep[inEdge[k]];
387
+ if (d >= 0) {
388
+ // The closing link points backwards in tree order (predecessor after successor); else the last defined.
389
+ const q = pred[d];
390
+ const sc = depSucc[d];
391
+ const r = (q > sc ? 2 ** 40 + q * 65536 : sc * 65536) + index[d];
392
+ if (r > rank) {
393
+ rank = r;
394
+ drop = d;
395
+ }
396
+ }
397
+ x = inFrom[k];
398
+ } while (x !== startNode);
399
+ }
400
+ if (drop >= 0) {
401
+ depDropped[drop] = 1;
402
+ droppedCount++;
403
+ const s = depSucc[drop];
404
+ const t = isParent[s] ? n + s : s;
405
+ indeg[t] = indeg[t] - 1;
406
+ if (!indeg[t])
407
+ topo[tail++] = t;
408
+ }
409
+ else {
410
+ indeg[v0] = 0;
411
+ topo[tail++] = v0;
412
+ }
413
+ }
414
+ const pos = new Int32Array(N);
415
+ for (let k = 0; k < N; k++)
416
+ pos[topo[k]] = k;
417
+ return {
418
+ depStart,
419
+ depPred: Int32Array.from(pred),
420
+ depSucc,
421
+ depType: Uint8Array.from(type),
422
+ depLag: Float64Array.from(lag),
423
+ depDropped,
424
+ depIndex: Int32Array.from(index),
425
+ droppedCount,
426
+ outStart,
427
+ outTo,
428
+ outDep,
429
+ topo,
430
+ pos,
431
+ };
432
+ }
433
+ // ---------------------------------------------------------------------------
434
+ export function createProjectEngine(initial = {}) {
435
+ let ctx = makeCtx(initial);
436
+ let world = buildWorld([], null, false);
437
+ let version = 0;
438
+ const listeners = new Set();
439
+ const recorders = new Set();
440
+ let critical = new Set();
441
+ // Batch state.
442
+ let depth = 0;
443
+ let batchAction = '';
444
+ let batchList = [];
445
+ let batchTouched = new Set();
446
+ let batchChanged = new Set();
447
+ let batchNotify = false;
448
+ let recording = true;
449
+ // ---- world construction -------------------------------------------------
450
+ function buildWorld(input, prev, normalize) {
451
+ const list = treeOrder(input);
452
+ const n = list.length;
453
+ const ids = new Map();
454
+ list.forEach((t, i) => ids.set(t.id, i));
455
+ const parentOf = new Int32Array(n).fill(-1);
456
+ const isParent = new Uint8Array(n);
457
+ const level = new Int32Array(n);
458
+ const counts = new Int32Array(n + 1);
459
+ for (let i = 0; i < n; i++) {
460
+ const p = list[i].parentId;
461
+ const pi = p === null || p === undefined ? undefined : ids.get(p);
462
+ if (pi !== undefined && pi < i) {
463
+ parentOf[i] = pi;
464
+ isParent[pi] = 1;
465
+ level[i] = level[pi] + 1;
466
+ counts[pi + 1] = counts[pi + 1] + 1;
467
+ }
468
+ }
469
+ for (let i = 0; i < n; i++)
470
+ counts[i + 1] = counts[i + 1] + counts[i];
471
+ const childStart = counts;
472
+ const fill = counts.slice(0, n);
473
+ const childList = new Int32Array(Math.max(0, childStart[n]));
474
+ const wbs = new Array(n);
475
+ let rootCount = 0;
476
+ for (let i = 0; i < n; i++) {
477
+ const p = parentOf[i];
478
+ if (p < 0)
479
+ wbs[i] = String(++rootCount);
480
+ else {
481
+ const at = fill[p];
482
+ fill[p] = at + 1;
483
+ childList[at] = i;
484
+ wbs[i] = `${wbs[p]}.${at - childStart[p] + 1}`;
485
+ }
486
+ }
487
+ const subEnd = new Int32Array(n);
488
+ for (let i = n - 1; i >= 0; i--) {
489
+ let end = i + 1;
490
+ const c0 = childStart[i];
491
+ const c1 = childStart[i + 1];
492
+ if (c1 > c0)
493
+ end = subEnd[childList[c1 - 1]];
494
+ subEnd[i] = end;
495
+ }
496
+ let defaultStart = finite(ctx.opt.projectStart) ? ctx.opt.projectStart : Infinity;
497
+ if (!Number.isFinite(defaultStart)) {
498
+ for (const t of list)
499
+ if (finite(t.start) && t.start < defaultStart)
500
+ defaultStart = t.start;
501
+ if (!Number.isFinite(defaultStart))
502
+ for (const t of list)
503
+ if (finite(t.end) && t.end < defaultStart)
504
+ defaultStart = t.end;
505
+ if (!Number.isFinite(defaultStart))
506
+ defaultStart = 0;
507
+ }
508
+ const prep = list.map((t, i) => prepare(t, isParent[i] === 1, ctx, defaultStart));
509
+ const partial = { n, ids, isParent, parentOf, childStart, childList, prep };
510
+ const g = buildGraph(partial, ctx);
511
+ const w = {
512
+ list,
513
+ n,
514
+ ids,
515
+ parentOf,
516
+ isParent,
517
+ childStart,
518
+ childList,
519
+ level,
520
+ subEnd,
521
+ wbs,
522
+ prep,
523
+ g,
524
+ st: new Float64Array(n * K),
525
+ conf: new Array(n).fill(null),
526
+ segs: new Array(n).fill(null),
527
+ sched: new Array(n),
528
+ dirty: new Uint8Array(2 * n),
529
+ pending: 0,
530
+ minPos: 2 * n,
531
+ touchMark: new Uint8Array(n),
532
+ touched: [],
533
+ journal: null,
534
+ alap: null,
535
+ defaultStart,
536
+ normalizing: normalize,
537
+ };
538
+ const topo = g.topo;
539
+ for (let k = 0; k < topo.length; k++)
540
+ computeNode(w, topo[k]);
541
+ w.normalizing = false;
542
+ applyAlap(w);
543
+ w.touched = [];
544
+ w.touchMark.fill(0);
545
+ for (let i = 0; i < n; i++) {
546
+ const old = prev ? prev.sched[prev.ids.get(list[i].id) ?? -1] : undefined;
547
+ w.sched[i] = makeSchedule(w, i, old);
548
+ }
549
+ return w;
550
+ }
551
+ // ---- node computation ----------------------------------------------------
552
+ function save(w, i) {
553
+ const j = w.journal;
554
+ if (!j || j.has(i))
555
+ return;
556
+ j.set(i, { st: w.st.slice(i * K, i * K + K), conf: w.conf[i] ?? null, segs: w.segs[i] ?? null, sched: w.sched[i] });
557
+ }
558
+ function touch(w, i) {
559
+ if (!w.touchMark[i]) {
560
+ w.touchMark[i] = 1;
561
+ w.touched.push(i);
562
+ }
563
+ }
564
+ function computeNode(w, v) {
565
+ if (v < w.n)
566
+ return w.isParent[v] ? computeRollup(w, v) : computeLeaf(w, v);
567
+ return w.isParent[v - w.n] ? computeGate(w, v - w.n) : false;
568
+ }
569
+ function conflict(w, kind, i, pred, type, earliest) {
570
+ return Object.freeze({
571
+ kind,
572
+ taskId: w.list[i].id,
573
+ predecessorId: pred >= 0 ? w.list[pred].id : null,
574
+ type: pred >= 0 ? DEP_NAME[type] : null,
575
+ earliestStart: earliest,
576
+ });
577
+ }
578
+ /** Earliest start the links of task `i` allow (with `span` for finish links); sets BP/BT-like outputs. */
579
+ function depBound(w, i, span, out) {
580
+ const g = w.g;
581
+ const st = w.st;
582
+ const cal = w.prep[i].cal;
583
+ let bound = -Infinity;
584
+ let bp = -1;
585
+ let bt = 0;
586
+ for (let d = g.depStart[i], e = g.depStart[i + 1]; d < e; d++) {
587
+ if (g.depDropped[d])
588
+ continue;
589
+ const q = g.depPred[d];
590
+ const qo = q * K;
591
+ if (st[qo + UN])
592
+ continue;
593
+ const lag = g.depLag[d];
594
+ const t = g.depType[d];
595
+ let b;
596
+ if (t === 0) {
597
+ const x = st[qo + EE];
598
+ b = lag ? cal.addWork(x, lag) : x;
599
+ }
600
+ else if (t === 1) {
601
+ const x = st[qo + ES];
602
+ b = lag ? cal.addWork(x, lag) : x;
603
+ }
604
+ else {
605
+ const x = (t === 2 ? st[qo + EE] : st[qo + ES]);
606
+ const eb = lag ? cal.addWork(x, lag) : x;
607
+ b = span ? cal.addWork(eb, -span) : eb;
608
+ }
609
+ if (b > bound) {
610
+ bound = b;
611
+ bp = q;
612
+ bt = t;
613
+ }
614
+ }
615
+ out[0] = bp;
616
+ out[1] = bt;
617
+ return bound;
618
+ }
619
+ const scratch = new Float64Array(2);
620
+ /** Places the segments of task `i` from `start`; returns the end. */
621
+ function placeSegments(w, i, start) {
622
+ const p = w.prep[i];
623
+ const off = p.segOff;
624
+ const len = p.segLen;
625
+ const out = [];
626
+ let end = start;
627
+ for (let k = 0; k < off.length; k++) {
628
+ const o = off[k];
629
+ const s = k === 0 ? start : p.auto ? p.cal.nextWorkingStart(p.cal.addWork(start, o)) : p.cal.addWork(start, o);
630
+ const l = len[k];
631
+ end = l ? p.cal.addWork(s, l) : s;
632
+ out.push(Object.freeze({ start: s, end }));
633
+ }
634
+ w.segs[i] = Object.freeze(out);
635
+ return end;
636
+ }
637
+ /** Rewrites the lags of task `i` so its links land exactly on its data dates (`dependencyLag.normalizeOnLoad`). */
638
+ function normalizeLags(w, i) {
639
+ const p = w.prep[i];
640
+ const g = w.g;
641
+ const deps = p.input.predecessors;
642
+ if (!deps || !p.hasDates || g.depStart[i] === g.depStart[i + 1])
643
+ return;
644
+ const next = deps.slice();
645
+ const end = p.span ? p.cal.addWork(p.dStart, p.span) : p.dStart;
646
+ for (let d = g.depStart[i]; d < g.depStart[i + 1]; d++) {
647
+ if (g.depDropped[d])
648
+ continue;
649
+ const qo = g.depPred[d] * K;
650
+ if (w.st[qo + UN])
651
+ continue;
652
+ const t = g.depType[d];
653
+ const from = (t === 0 || t === 2 ? w.st[qo + EE] : w.st[qo + ES]);
654
+ const gap = p.cal.workBetween(from, t < 2 ? p.dStart : end);
655
+ g.depLag[d] = gap;
656
+ const j = g.depIndex[d];
657
+ const dep = next[j];
658
+ next[j] = { ...dep, lag: p.cal.fromWorkMs(gap, dep.lagUnit ?? 'day') };
659
+ }
660
+ const input = { ...p.input, predecessors: next };
661
+ w.list[i] = input;
662
+ w.prep[i] = { ...p, input };
663
+ }
664
+ function computeLeaf(w, i) {
665
+ const st = w.st;
666
+ const o = i * K;
667
+ const p = w.prep[i];
668
+ save(w, i);
669
+ touch(w, i);
670
+ const oS = st[o + S];
671
+ const oE = st[o + E];
672
+ const oSW = st[o + SW];
673
+ const oSWP = st[o + SWP];
674
+ const oUN = st[o + UN];
675
+ const oWK = st[o + WK];
676
+ if (p.unscheduled) {
677
+ st[o + S] = st[o + E] = st[o + ES] = st[o + EE] = NaN;
678
+ st[o + W] = p.w;
679
+ st[o + SW] = st[o + SWP] = st[o + WK] = 0;
680
+ st[o + UN] = 1;
681
+ st[o + B] = -Infinity;
682
+ st[o + BP] = -1;
683
+ w.conf[i] = null;
684
+ w.segs[i] = null;
685
+ return !(same(oS, NaN) && oUN === 1 && oSW === 0 && oSWP === 0);
686
+ }
687
+ if (w.normalizing && p.auto)
688
+ normalizeLags(w, i);
689
+ const cal = p.cal;
690
+ const span = p.span;
691
+ let cf = null;
692
+ let bound = depBound(w, i, span, scratch);
693
+ let bp = scratch[0];
694
+ let bt = scratch[1];
695
+ const par = w.parentOf[i];
696
+ if (par >= 0) {
697
+ const po = par * K;
698
+ if (st[po + G] > bound) {
699
+ bound = st[po + G];
700
+ bp = st[po + GP];
701
+ bt = st[po + GT];
702
+ }
703
+ }
704
+ st[o + B] = bound;
705
+ st[o + BP] = bp;
706
+ st[o + BT] = bt;
707
+ let start = p.dStart;
708
+ let moved = false;
709
+ if (p.auto) {
710
+ if (bound > start)
711
+ start = bound;
712
+ const cd = p.cDate;
713
+ const c = p.cType;
714
+ if (c >= 2) {
715
+ const sb = () => snap(cal, bound, span);
716
+ if (c === 2) {
717
+ if (cd > start)
718
+ start = cd;
719
+ }
720
+ else if (c === 4) {
721
+ const ls = span ? cal.addWork(cd, -span) : cd;
722
+ if (ls > start)
723
+ start = ls;
724
+ }
725
+ else if (c === 3 || c === 5) {
726
+ const lim = c === 3 ? cd : span ? cal.addWork(cd, -span) : cd;
727
+ if (snap(cal, start, span) > snap(cal, lim, span) + TOL) {
728
+ if (Number.isFinite(bound) && sb() > snap(cal, lim, span) + TOL)
729
+ (cf ??= []).push(conflict(w, 'constraint', i, bp, bt, sb()));
730
+ else
731
+ start = lim;
732
+ }
733
+ }
734
+ else {
735
+ const lim = c === 6 ? cd : span ? cal.addWork(cd, -span) : cd;
736
+ if (Number.isFinite(bound) && sb() > snap(cal, lim, span) + TOL)
737
+ (cf ??= []).push(conflict(w, 'constraint', i, bp, bt, sb()));
738
+ start = lim;
739
+ }
740
+ }
741
+ start = snap(cal, start, span);
742
+ moved = true;
743
+ }
744
+ else if (Number.isFinite(bound)) {
745
+ const sb = snap(cal, bound, span);
746
+ if (sb > start + TOL) {
747
+ if (ctx.validateManual && ctx.autoSchedule) {
748
+ start = sb;
749
+ moved = true;
750
+ }
751
+ else
752
+ (cf ??= []).push(conflict(w, 'dependency', i, bp, bt, sb));
753
+ }
754
+ }
755
+ let end;
756
+ if (p.segOff)
757
+ end = placeSegments(w, i, start);
758
+ else {
759
+ w.segs[i] = null;
760
+ end = !moved && start === p.dStart ? p.dEnd : span ? cal.addWork(start, span) : start;
761
+ }
762
+ const g = w.g;
763
+ for (let d = g.depStart[i], e = g.depStart[i + 1]; d < e; d++)
764
+ if (g.depDropped[d])
765
+ (cf ??= []).push(conflict(w, 'dependency', i, g.depPred[d], g.depType[d], start));
766
+ w.conf[i] = cf;
767
+ st[o + S] = st[o + ES] = start;
768
+ st[o + E] = st[o + EE] = end;
769
+ st[o + W] = p.w;
770
+ const weight = p.milestone ? 0 : p.w;
771
+ st[o + SW] = weight;
772
+ st[o + SWP] = weight * p.progress;
773
+ st[o + WK] = p.w * p.units;
774
+ st[o + UN] = 0;
775
+ return !(same(oS, start) && same(oE, end) && oSW === weight && oSWP === weight * p.progress && oUN === 0 && oWK === p.w * p.units);
776
+ }
777
+ function computeGate(w, i) {
778
+ const st = w.st;
779
+ const o = i * K;
780
+ const p = w.prep[i];
781
+ save(w, i);
782
+ touch(w, i);
783
+ const og = st[o + G];
784
+ let g = -Infinity;
785
+ let gp = -1;
786
+ let gt = 0;
787
+ const par = w.parentOf[i];
788
+ if (par >= 0) {
789
+ g = st[par * K + G];
790
+ gp = st[par * K + GP];
791
+ gt = st[par * K + GT];
792
+ }
793
+ if (p.auto) {
794
+ const b = depBound(w, i, st[o + W] || 0, scratch);
795
+ if (b > g) {
796
+ g = b;
797
+ gp = scratch[0];
798
+ gt = scratch[1];
799
+ }
800
+ }
801
+ let cf = null;
802
+ const gr = w.g;
803
+ for (let d = gr.depStart[i], e = gr.depStart[i + 1]; d < e; d++)
804
+ if (gr.depDropped[d])
805
+ (cf ??= []).push(conflict(w, 'dependency', i, gr.depPred[d], gr.depType[d], st[o + S]));
806
+ w.conf[i] = cf;
807
+ st[o + G] = g;
808
+ st[o + GP] = gp;
809
+ st[o + GT] = gt;
810
+ return !same(og, g);
811
+ }
812
+ function computeRollup(w, i) {
813
+ const st = w.st;
814
+ const o = i * K;
815
+ const p = w.prep[i];
816
+ save(w, i);
817
+ touch(w, i);
818
+ const old = st.slice(o, o + 10);
819
+ const oUN = st[o + UN];
820
+ const oWK = st[o + WK];
821
+ let mn = Infinity;
822
+ let mx = -Infinity;
823
+ let sw = 0;
824
+ let swp = 0;
825
+ let wk = 0;
826
+ let any = false;
827
+ for (let k = w.childStart[i], e = w.childStart[i + 1]; k < e; k++) {
828
+ const c = w.childList[k];
829
+ const co = c * K;
830
+ if (st[co + UN])
831
+ continue;
832
+ any = true;
833
+ if (st[co + S] < mn)
834
+ mn = st[co + S];
835
+ if (st[co + E] > mx)
836
+ mx = st[co + E];
837
+ sw += st[co + SW];
838
+ swp += st[co + SWP];
839
+ wk += st[co + WK];
840
+ }
841
+ let s;
842
+ let e;
843
+ if (!any) {
844
+ if (p.unscheduled) {
845
+ st[o + S] = st[o + E] = st[o + ES] = st[o + EE] = st[o + RS] = st[o + RE] = NaN;
846
+ st[o + W] = st[o + SW] = st[o + SWP] = st[o + WK] = 0;
847
+ st[o + PR] = p.progress;
848
+ st[o + UN] = 1;
849
+ return oUN !== 1;
850
+ }
851
+ s = p.dStart;
852
+ e = p.dEnd;
853
+ sw = p.w;
854
+ swp = p.w * p.progress;
855
+ wk = p.w * p.units;
856
+ mn = mx = NaN;
857
+ }
858
+ else if (p.manual && p.hasDates) {
859
+ s = p.dStart;
860
+ e = p.dEnd;
861
+ }
862
+ else {
863
+ s = mn;
864
+ e = mx;
865
+ }
866
+ st[o + S] = st[o + ES] = s;
867
+ st[o + E] = st[o + EE] = e;
868
+ st[o + W] = any ? Math.max(0, p.cal.workBetween(s, e)) : p.w;
869
+ st[o + SW] = sw;
870
+ st[o + SWP] = swp;
871
+ st[o + PR] = sw > 0 ? swp / sw : p.progress;
872
+ st[o + RS] = mn;
873
+ st[o + RE] = mx;
874
+ st[o + WK] = wk;
875
+ st[o + UN] = 0;
876
+ for (let k = 0; k < 10; k++)
877
+ if (!same(old[k], st[o + k]))
878
+ return true;
879
+ return oUN !== 0 || oWK !== wk;
880
+ }
881
+ /** As-late-as-possible tasks: after the forward pass, move to the latest start their successors and the project finish allow. */
882
+ function applyAlap(w) {
883
+ if (!ctx.autoSchedule)
884
+ return;
885
+ if (!w.alap) {
886
+ const list = [];
887
+ for (let i = 0; i < w.n; i++) {
888
+ const p = w.prep[i];
889
+ if (p.cType === 1 && p.auto && !w.isParent[i] && !p.unscheduled)
890
+ list.push(i);
891
+ }
892
+ list.sort((a, b) => w.g.pos[b] - w.g.pos[a]);
893
+ w.alap = Int32Array.from(list);
894
+ }
895
+ if (!w.alap.length)
896
+ return;
897
+ const st = w.st;
898
+ let finish = finite(ctx.opt.projectEnd) ? ctx.opt.projectEnd : -Infinity;
899
+ if (!finite(ctx.opt.projectEnd))
900
+ for (let i = 0; i < w.n; i++)
901
+ if (!w.isParent[i] && !st[i * K + UN] && st[i * K + EE] > finish)
902
+ finish = st[i * K + EE];
903
+ if (!Number.isFinite(finish))
904
+ return;
905
+ const g = w.g;
906
+ const parents = new Set();
907
+ for (const i of w.alap) {
908
+ const p = w.prep[i];
909
+ const cal = p.cal;
910
+ const span = p.span;
911
+ let lf = finish;
912
+ for (let x = i; x >= 0; x = w.parentOf[x]) {
913
+ for (let e = g.outStart[x]; e < g.outStart[x + 1]; e++) {
914
+ const d = g.outDep[e];
915
+ if (d < 0 || g.depDropped[d])
916
+ continue;
917
+ const so = g.depSucc[d] * K;
918
+ if (st[so + UN])
919
+ continue;
920
+ const lag = g.depLag[d];
921
+ const t = g.depType[d];
922
+ const base = (t === 0 || t === 1 ? st[so + S] : st[so + E]);
923
+ const lim = lag ? cal.addWork(base, -lag) : base;
924
+ const b = t === 0 || t === 2 ? lim : span ? cal.addWork(lim, span) : lim;
925
+ if (b < lf)
926
+ lf = b;
927
+ }
928
+ }
929
+ const o = i * K;
930
+ let start = span ? cal.addWork(lf, -span) : lf;
931
+ start = snap(cal, start, span);
932
+ if (start < st[o + ES])
933
+ start = st[o + ES];
934
+ if (same(start, st[o + S]))
935
+ continue;
936
+ save(w, i);
937
+ touch(w, i);
938
+ st[o + S] = start;
939
+ st[o + E] = p.segOff ? placeSegments(w, i, start) : span ? cal.addWork(start, span) : start;
940
+ for (let x = w.parentOf[i]; x >= 0; x = w.parentOf[x])
941
+ parents.add(x);
942
+ }
943
+ if (parents.size) {
944
+ const order = [...parents].sort((a, b) => g.pos[a] - g.pos[b]);
945
+ for (const pIdx of order)
946
+ computeRollup(w, pIdx);
947
+ }
948
+ }
949
+ // ---- schedules -----------------------------------------------------------
950
+ function sameConflicts(a, b) {
951
+ if (a === b)
952
+ return true;
953
+ if (a.length !== b.length)
954
+ return false;
955
+ for (let k = 0; k < a.length; k++) {
956
+ const x = a[k];
957
+ const y = b[k];
958
+ if (x.kind !== y.kind || x.predecessorId !== y.predecessorId || x.type !== y.type || x.earliestStart !== y.earliestStart || x.taskId !== y.taskId)
959
+ return false;
960
+ }
961
+ return true;
962
+ }
963
+ function sameSegments(a, b) {
964
+ if (a === b)
965
+ return true;
966
+ if (!a || !b || a.length !== b.length)
967
+ return false;
968
+ for (let k = 0; k < a.length; k++)
969
+ if (a[k].start !== b[k].start || a[k].end !== b[k].end)
970
+ return false;
971
+ return true;
972
+ }
973
+ function makeSchedule(w, i, old, crit) {
974
+ const p = w.prep[i];
975
+ const st = w.st;
976
+ const o = i * K;
977
+ const parent = w.isParent[i] === 1;
978
+ const unscheduled = st[o + UN] === 1;
979
+ const num = (v) => (unscheduled || !Number.isFinite(v) ? null : v);
980
+ const workMs = st[o + W];
981
+ const next = {
982
+ id: p.input.id,
983
+ parentId: w.parentOf[i] >= 0 ? w.list[w.parentOf[i]].id : null,
984
+ level: w.level[i],
985
+ index: i,
986
+ start: num(st[o + S]),
987
+ end: num(st[o + E]),
988
+ duration: round4(p.cal.fromWorkMs(workMs, p.unit)),
989
+ durationUnit: p.unit,
990
+ workMs,
991
+ progress: Math.round((parent ? st[o + PR] : p.progress) * 100) / 100,
992
+ milestone: p.milestone,
993
+ parent,
994
+ manual: p.manual,
995
+ unscheduled,
996
+ work: round4(st[o + WK] / p.cal.unitMs(ctx.workUnit)),
997
+ taskType: p.taskType,
998
+ segments: w.segs[i] ?? null,
999
+ rollupStart: parent ? num(st[o + RS]) : null,
1000
+ rollupEnd: parent ? num(st[o + RE]) : null,
1001
+ wbs: w.wbs[i],
1002
+ critical: crit ? crit.critical : (old?.critical ?? false),
1003
+ totalFloat: crit ? crit.totalFloat : (old?.totalFloat ?? 0),
1004
+ freeFloat: crit ? crit.freeFloat : (old?.freeFloat ?? 0),
1005
+ conflicts: w.conf[i] ?? EMPTY,
1006
+ };
1007
+ if (old &&
1008
+ old.id === next.id &&
1009
+ old.parentId === next.parentId &&
1010
+ old.level === next.level &&
1011
+ old.index === next.index &&
1012
+ old.start === next.start &&
1013
+ old.end === next.end &&
1014
+ old.duration === next.duration &&
1015
+ old.durationUnit === next.durationUnit &&
1016
+ old.workMs === next.workMs &&
1017
+ old.progress === next.progress &&
1018
+ old.milestone === next.milestone &&
1019
+ old.parent === next.parent &&
1020
+ old.manual === next.manual &&
1021
+ old.unscheduled === next.unscheduled &&
1022
+ old.work === next.work &&
1023
+ old.taskType === next.taskType &&
1024
+ sameSegments(old.segments, next.segments) &&
1025
+ old.rollupStart === next.rollupStart &&
1026
+ old.rollupEnd === next.rollupEnd &&
1027
+ old.wbs === next.wbs &&
1028
+ old.critical === next.critical &&
1029
+ old.totalFloat === next.totalFloat &&
1030
+ old.freeFloat === next.freeFloat &&
1031
+ sameConflicts(old.conflicts, next.conflicts))
1032
+ return old;
1033
+ return Object.freeze(next);
1034
+ }
1035
+ // ---- incremental propagation ---------------------------------------------
1036
+ function markNode(w, v) {
1037
+ if (w.dirty[v])
1038
+ return;
1039
+ w.dirty[v] = 1;
1040
+ w.pending++;
1041
+ const p = w.g.pos[v];
1042
+ if (p < w.minPos)
1043
+ w.minPos = p;
1044
+ }
1045
+ function propagate(w) {
1046
+ const g = w.g;
1047
+ const N = 2 * w.n;
1048
+ for (let pos = w.minPos; pos < N && w.pending > 0; pos++) {
1049
+ const v = g.topo[pos];
1050
+ if (!w.dirty[v])
1051
+ continue;
1052
+ w.dirty[v] = 0;
1053
+ w.pending--;
1054
+ if (!computeNode(w, v))
1055
+ continue;
1056
+ for (let e = g.outStart[v], end = g.outStart[v + 1]; e < end; e++) {
1057
+ const d = g.outDep[e];
1058
+ if (d >= 0 && g.depDropped[d])
1059
+ continue;
1060
+ const t = g.outTo[e];
1061
+ if (!w.dirty[t]) {
1062
+ w.dirty[t] = 1;
1063
+ w.pending++;
1064
+ }
1065
+ }
1066
+ }
1067
+ w.minPos = N;
1068
+ w.pending = 0;
1069
+ }
1070
+ function isStructural(a, b) {
1071
+ if (a.length !== b.length)
1072
+ return true;
1073
+ for (let i = 0; i < a.length; i++) {
1074
+ const x = a[i];
1075
+ const y = b[i];
1076
+ if (x === y)
1077
+ continue;
1078
+ if (x.id !== y.id || (x.parentId ?? null) !== (y.parentId ?? null))
1079
+ return true;
1080
+ }
1081
+ return false;
1082
+ }
1083
+ function sameLinks(a, b) {
1084
+ if (a === b)
1085
+ return 'same';
1086
+ const x = a ?? [];
1087
+ const y = b ?? [];
1088
+ if (x.length !== y.length)
1089
+ return 'links';
1090
+ let lag = false;
1091
+ for (let k = 0; k < x.length; k++) {
1092
+ const p = x[k];
1093
+ const q = y[k];
1094
+ if (p.id !== q.id || p.type !== q.type)
1095
+ return 'links';
1096
+ if (p.lag !== q.lag || p.lagUnit !== q.lagUnit)
1097
+ lag = true;
1098
+ }
1099
+ return lag ? 'lag' : 'same';
1100
+ }
1101
+ /** Applies `next` (tree order) to the world, tentatively. */
1102
+ function begin(next) {
1103
+ const w = world;
1104
+ if (isStructural(w.list, next)) {
1105
+ const tx = { oldWorld: w, structural: true, oldList: w.list, oldPrep: new Map(), oldGraph: null };
1106
+ world = buildWorld(next, w, false);
1107
+ return tx;
1108
+ }
1109
+ const tx = { oldWorld: w, structural: false, oldList: w.list, oldPrep: new Map(), oldGraph: null };
1110
+ w.journal = new Map();
1111
+ w.list = next.slice();
1112
+ let rebuild = false;
1113
+ const lagOnly = [];
1114
+ let alapDirty = false;
1115
+ for (let i = 0; i < w.n; i++) {
1116
+ const before = tx.oldList[i];
1117
+ const after = w.list[i];
1118
+ if (before === after)
1119
+ continue;
1120
+ const oldPrep = w.prep[i];
1121
+ tx.oldPrep.set(i, oldPrep);
1122
+ const p = prepare(after, w.isParent[i] === 1, ctx, w.defaultStart);
1123
+ w.prep[i] = p;
1124
+ const links = sameLinks(before.predecessors, after.predecessors);
1125
+ if (links === 'links' || p.cal !== oldPrep.cal)
1126
+ rebuild = true;
1127
+ else if (links === 'lag')
1128
+ lagOnly.push(i);
1129
+ if (p.cType !== oldPrep.cType || p.auto !== oldPrep.auto)
1130
+ alapDirty = true;
1131
+ markNode(w, i);
1132
+ if (w.isParent[i])
1133
+ markNode(w, w.n + i);
1134
+ }
1135
+ if (rebuild) {
1136
+ const oldG = w.g;
1137
+ tx.oldGraph = oldG;
1138
+ w.g = buildGraph(w, ctx);
1139
+ w.alap = null;
1140
+ // Positions changed: re-mark the dirty nodes against the new order and every task touched by a cycle change.
1141
+ w.minPos = 2 * w.n;
1142
+ for (let v = 0; v < 2 * w.n; v++)
1143
+ if (w.dirty[v])
1144
+ w.minPos = Math.min(w.minPos, w.g.pos[v]);
1145
+ if (oldG.droppedCount || w.g.droppedCount)
1146
+ for (let d = 0; d < w.g.depDropped.length; d++)
1147
+ markNode(w, w.g.depSucc[d]);
1148
+ for (let d = 0; d < oldG.depDropped.length; d++)
1149
+ if (oldG.depDropped[d])
1150
+ markNode(w, oldG.depSucc[d]);
1151
+ }
1152
+ else if (lagOnly.length) {
1153
+ tx.oldGraph = w.g;
1154
+ const depLag = w.g.depLag.slice();
1155
+ for (const i of lagOnly) {
1156
+ const p = w.prep[i];
1157
+ const deps = p.input.predecessors ?? [];
1158
+ for (let d = w.g.depStart[i]; d < w.g.depStart[i + 1]; d++) {
1159
+ const dep = deps[w.g.depIndex[d]];
1160
+ depLag[d] = finite(dep.lag) ? Math.round(p.cal.toWorkMs(dep.lag, dep.lagUnit ?? 'day')) : 0;
1161
+ }
1162
+ }
1163
+ w.g = { ...w.g, depLag };
1164
+ }
1165
+ if (alapDirty)
1166
+ w.alap = null;
1167
+ propagate(w);
1168
+ applyAlap(w);
1169
+ for (const i of w.touched) {
1170
+ w.touchMark[i] = 0;
1171
+ w.sched[i] = makeSchedule(w, i, w.sched[i]);
1172
+ }
1173
+ w.touched = [];
1174
+ return tx;
1175
+ }
1176
+ function changedOf(tx) {
1177
+ const out = new Set();
1178
+ if (tx.structural) {
1179
+ const old = tx.oldWorld;
1180
+ for (let i = 0; i < world.n; i++) {
1181
+ const s = world.sched[i];
1182
+ const j = old.ids.get(s.id);
1183
+ if (j === undefined || old.sched[j] !== s)
1184
+ out.add(s.id);
1185
+ }
1186
+ return out;
1187
+ }
1188
+ const j = world.journal;
1189
+ if (j)
1190
+ for (const [i, saved] of j)
1191
+ if (world.sched[i] !== saved.sched)
1192
+ out.add(world.sched[i].id);
1193
+ return out;
1194
+ }
1195
+ function rollback(tx) {
1196
+ if (tx.structural) {
1197
+ world = tx.oldWorld;
1198
+ return;
1199
+ }
1200
+ const w = world;
1201
+ const j = w.journal;
1202
+ if (j)
1203
+ for (const [i, s] of j) {
1204
+ w.st.set(s.st, i * K);
1205
+ w.conf[i] = s.conf;
1206
+ w.segs[i] = s.segs;
1207
+ w.sched[i] = s.sched;
1208
+ }
1209
+ for (const [i, p] of tx.oldPrep)
1210
+ w.prep[i] = p;
1211
+ w.list = tx.oldList;
1212
+ if (tx.oldGraph) {
1213
+ if (tx.oldGraph.topo !== w.g.topo)
1214
+ w.alap = null;
1215
+ w.g = tx.oldGraph;
1216
+ }
1217
+ w.alap = null;
1218
+ w.journal = null;
1219
+ }
1220
+ function finish(tx) {
1221
+ if (!tx.structural)
1222
+ world.journal = null;
1223
+ }
1224
+ function snapshots(list, ids) {
1225
+ const out = [];
1226
+ list.forEach((task, index) => {
1227
+ if (ids.has(task.id))
1228
+ out.push(Object.freeze({ id: task.id, index, task }));
1229
+ });
1230
+ return out;
1231
+ }
1232
+ function emit(action, before, after, touched, changed) {
1233
+ version++;
1234
+ if (depth > 0) {
1235
+ for (const id of touched)
1236
+ batchTouched.add(id);
1237
+ if (changed && batchChanged)
1238
+ for (const id of changed)
1239
+ batchChanged.add(id);
1240
+ else
1241
+ batchChanged = null;
1242
+ batchNotify = true;
1243
+ return;
1244
+ }
1245
+ if (recording && touched.size && recorders.size) {
1246
+ const record = Object.freeze({ action, before: snapshots(before, touched), after: snapshots(after, touched) });
1247
+ for (const r of recorders)
1248
+ r(record);
1249
+ }
1250
+ for (const l of listeners)
1251
+ l(changed);
1252
+ }
1253
+ /** Applies a new list, validates, then commits (records and notifies) or rolls back. */
1254
+ function commit(action, next, touched, opts = {}) {
1255
+ const before = world.list;
1256
+ const tx = begin(next);
1257
+ const reject = (conflicts) => {
1258
+ rollback(tx);
1259
+ return { changed: new Set(), conflicts, schedules: new Map() };
1260
+ };
1261
+ if (opts.cycleCheck && !tx.structural && world.g.droppedCount > (tx.oldGraph ?? world.g).droppedCount) {
1262
+ const w = world;
1263
+ const found = [];
1264
+ for (let d = 0; d < w.g.depDropped.length; d++)
1265
+ if (w.g.depDropped[d])
1266
+ found.push(conflict(w, 'dependency', w.g.depSucc[d], w.g.depPred[d], w.g.depType[d], NaN));
1267
+ return reject(found);
1268
+ }
1269
+ if (opts.validateId !== undefined && opts.validate) {
1270
+ const id = tx.oldList[opts.validateId]?.id;
1271
+ const i = id === undefined ? undefined : world.ids.get(id);
1272
+ if (i !== undefined) {
1273
+ const w = world;
1274
+ const p = w.prep[i];
1275
+ const o = i * K;
1276
+ const bound = w.st[o + B];
1277
+ if (p.auto && !w.isParent[i] && Number.isFinite(bound)) {
1278
+ const allowed = snap(p.cal, bound, p.span);
1279
+ if (allowed > p.dStart + TOL)
1280
+ return reject([conflict(w, 'dependency', i, w.st[o + BP], w.st[o + BT], allowed)]);
1281
+ }
1282
+ }
1283
+ }
1284
+ const changed = changedOf(tx);
1285
+ const schedules = new Map();
1286
+ const conflicts = [];
1287
+ for (const id of changed) {
1288
+ const s = world.sched[world.ids.get(id)];
1289
+ schedules.set(id, s);
1290
+ for (const c of s.conflicts)
1291
+ conflicts.push(c);
1292
+ }
1293
+ if (opts.preview) {
1294
+ rollback(tx);
1295
+ return { changed, conflicts, schedules };
1296
+ }
1297
+ finish(tx);
1298
+ emit(action, before, world.list, touched, tx.structural ? null : changed);
1299
+ return { changed, conflicts, schedules };
1300
+ }
1301
+ // ---- edits -----------------------------------------------------------------
1302
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
1303
+ /** The inputs an update writes (normalized for taskbar semantics and the task type). */
1304
+ function normalize(i, changes, source) {
1305
+ const w = world;
1306
+ const old = w.list[i];
1307
+ const sch = w.sched[i];
1308
+ const p = w.prep[i];
1309
+ const out = new Map();
1310
+ const next = { ...old, ...changes };
1311
+ const hasS = has(changes, 'start');
1312
+ const hasE = has(changes, 'end');
1313
+ const hasD = has(changes, 'duration');
1314
+ const dates = hasS || hasE || hasD;
1315
+ if (w.isParent[i]) {
1316
+ if (hasS && finite(changes.start) && sch.start !== null && !p.manual) {
1317
+ // Moving an auto parent shifts its descendants by the same working time.
1318
+ const delta = p.cal.workBetween(sch.start, changes.start);
1319
+ if (delta)
1320
+ for (let d = i + 1; d < w.subEnd[i]; d++) {
1321
+ if (w.isParent[d])
1322
+ continue;
1323
+ const sd = w.sched[d];
1324
+ if (sd.start === null)
1325
+ continue;
1326
+ const pd = w.prep[d];
1327
+ const input = w.list[d];
1328
+ out.set(input.id, { ...input, start: pd.cal.addWork(sd.start, delta), end: null, duration: sd.duration, durationUnit: sd.durationUnit });
1329
+ }
1330
+ }
1331
+ out.set(old.id, next);
1332
+ return out;
1333
+ }
1334
+ if (dates) {
1335
+ if (hasS && !hasE && !hasD) {
1336
+ next['duration'] = sch.duration;
1337
+ next['durationUnit'] = sch.durationUnit;
1338
+ next['end'] = null;
1339
+ }
1340
+ else if (hasE && !hasS && !hasD) {
1341
+ if (p.segOff && sch.segments && finite(changes.end)) {
1342
+ const segs = sch.segments.map((s) => ({ start: s.start, end: s.end }));
1343
+ const last = segs[segs.length - 1];
1344
+ segs[segs.length - 1] = { start: last.start ?? null, end: Math.max(last.start ?? changes.end, changes.end) };
1345
+ next['segments'] = segs;
1346
+ next['end'] = null;
1347
+ next['duration'] = null;
1348
+ }
1349
+ else {
1350
+ next['start'] = sch.start;
1351
+ next['duration'] = null;
1352
+ }
1353
+ }
1354
+ else if (hasD && !hasS && !hasE) {
1355
+ next['end'] = null;
1356
+ if (!finite(next['start']))
1357
+ next['start'] = sch.start;
1358
+ }
1359
+ else if (hasS && hasE && !hasD)
1360
+ next['duration'] = null;
1361
+ else if (hasS && hasD)
1362
+ next['end'] = null;
1363
+ else if (hasE && hasD)
1364
+ next['start'] = null;
1365
+ if (hasD && finite(changes.duration) && changes.duration > 0 && !has(changes, 'milestone'))
1366
+ next['milestone'] = false;
1367
+ }
1368
+ // Task types: which of duration, work and units follows an edit.
1369
+ const tt = next['taskType'] ?? ctx.taskType;
1370
+ const unitMs = p.cal.unitMs(ctx.workUnit);
1371
+ const oldWork = p.w * p.units;
1372
+ const scale = (factor) => {
1373
+ const res = next['resources'];
1374
+ if (res && res.length && Number.isFinite(factor) && factor > 0)
1375
+ next['resources'] = res.map((r) => ({ ...r, unit: round4((finite(r.unit) ? r.unit : 100) * factor) }));
1376
+ };
1377
+ if (has(changes, 'work') && finite(changes.work) && !dates) {
1378
+ const workMs = changes.work * unitMs;
1379
+ if (tt === 'fixedDuration')
1380
+ scale(oldWork > 0 ? workMs / oldWork : NaN);
1381
+ else {
1382
+ next['duration'] = p.cal.fromWorkMs(workMs / p.units, p.unit);
1383
+ next['end'] = null;
1384
+ if (!finite(next['start']))
1385
+ next['start'] = sch.start;
1386
+ }
1387
+ }
1388
+ else if (dates && tt === 'fixedWork' && !has(changes, 'work')) {
1389
+ const np = prepare(next, false, ctx, w.defaultStart);
1390
+ if (np.w > 0 && p.w > 0)
1391
+ scale(p.w / np.w);
1392
+ }
1393
+ else if (has(changes, 'resources') && !dates && !has(changes, 'work') && tt !== 'fixedDuration') {
1394
+ const units = unitsOf(next['resources']);
1395
+ if (oldWork > 0 && units > 0) {
1396
+ next['duration'] = p.cal.fromWorkMs(oldWork / units, p.unit);
1397
+ next['end'] = null;
1398
+ if (!finite(next['start']))
1399
+ next['start'] = sch.start;
1400
+ }
1401
+ }
1402
+ // Taskbar edits rewrite the lags of the task's links to the new gap.
1403
+ if (source === 'taskbar' && dates && ctx.opt.dependencyLag?.updateOnTaskbarEdit && old.predecessors?.length) {
1404
+ const np = prepare(next, false, ctx, w.defaultStart);
1405
+ const start = np.dStart;
1406
+ const end = np.span ? np.cal.addWork(start, np.span) : start;
1407
+ next['predecessors'] = old.predecessors.map((d) => {
1408
+ const q = w.ids.get(d.id);
1409
+ if (q === undefined)
1410
+ return d;
1411
+ const qs = w.sched[q];
1412
+ if (qs.start === null || qs.end === null)
1413
+ return d;
1414
+ const from = d.type === 'fs' || d.type === 'ff' ? qs.end : qs.start;
1415
+ const gap = np.cal.workBetween(from, d.type === 'fs' || d.type === 'ss' ? start : end);
1416
+ return { ...d, lag: np.cal.fromWorkMs(gap, d.lagUnit ?? 'day') };
1417
+ });
1418
+ }
1419
+ out.set(old.id, next);
1420
+ return out;
1421
+ }
1422
+ function replaced(inputs) {
1423
+ return world.list.map((t) => inputs.get(t.id) ?? t);
1424
+ }
1425
+ function runUpdate(action, id, changes, options, opts) {
1426
+ const i = world.ids.get(id);
1427
+ if (i === undefined)
1428
+ return { changed: new Set(), conflicts: [], schedules: new Map() };
1429
+ const source = options?.source ?? 'api';
1430
+ const inputs = opts.raw ? new Map([[id, { ...world.list[i], ...changes }]]) : normalize(i, changes, source);
1431
+ // Only a new start can be earlier than the dependencies allow; duration and end edits keep the scheduled start.
1432
+ const dates = has(changes, 'start') && changes.start !== null;
1433
+ const validate = options?.validate ?? ((source === 'taskbar' || source === 'edit') && ctx.opt.validateDependencies !== false);
1434
+ const commitOpts = {
1435
+ ...(dates && validate ? { validateId: i, validate: true } : {}),
1436
+ ...(opts.preview ? { preview: true } : {}),
1437
+ ...(opts.cycleCheck ? { cycleCheck: true } : {}),
1438
+ };
1439
+ return commit(action, replaced(inputs), new Set(inputs.keys()), commitOpts);
1440
+ }
1441
+ const strip = (r) => ({ changed: r.changed, conflicts: r.conflicts });
1442
+ function subtreeIds(i) {
1443
+ const out = [];
1444
+ for (let k = i; k < world.subEnd[i]; k++)
1445
+ out.push(world.list[k].id);
1446
+ return out;
1447
+ }
1448
+ /** Top-most selected tasks (a selected descendant moves with its ancestor), in tree order. */
1449
+ function roots(ids) {
1450
+ const set = new Set();
1451
+ for (const id of ids) {
1452
+ const i = world.ids.get(id);
1453
+ if (i !== undefined)
1454
+ set.add(i);
1455
+ }
1456
+ const out = [];
1457
+ for (const i of [...set].sort((a, b) => a - b)) {
1458
+ let covered = false;
1459
+ for (let p = world.parentOf[i]; p >= 0; p = world.parentOf[p])
1460
+ if (set.has(p))
1461
+ covered = true;
1462
+ if (!covered)
1463
+ out.push(i);
1464
+ }
1465
+ return out;
1466
+ }
1467
+ /** Moves blocks of a tree-order list (pure list surgery). */
1468
+ function moveBlocks(list, blockIds, targetId, position, touched) {
1469
+ const moving = new Set(blockIds.flat());
1470
+ if (moving.has(targetId))
1471
+ return null;
1472
+ const rest = list.filter((t) => !moving.has(t.id));
1473
+ const ti = rest.findIndex((t) => t.id === targetId);
1474
+ if (ti < 0)
1475
+ return null;
1476
+ const target = rest[ti];
1477
+ // End of the target's subtree in `rest`.
1478
+ const byId = new Map(rest.map((t) => [t.id, t]));
1479
+ const inside = (t) => {
1480
+ for (let p = t.parentId; p !== null && p !== undefined; p = byId.get(p)?.parentId ?? null)
1481
+ if (p === targetId)
1482
+ return true;
1483
+ return false;
1484
+ };
1485
+ let end = ti + 1;
1486
+ while (end < rest.length && inside(rest[end]))
1487
+ end++;
1488
+ const at = position === 'above' ? ti : end;
1489
+ const parentId = position === 'child' ? targetId : (target.parentId ?? null);
1490
+ const insert = [];
1491
+ const firstIds = new Set(blockIds.map((b) => b[0]));
1492
+ const byOld = new Map(list.map((t) => [t.id, t]));
1493
+ for (const block of blockIds)
1494
+ for (const id of block) {
1495
+ const t = byOld.get(id);
1496
+ insert.push(firstIds.has(id) && (t.parentId ?? null) !== parentId ? { ...t, parentId } : t);
1497
+ touched.add(id);
1498
+ }
1499
+ return [...rest.slice(0, at), ...insert, ...rest.slice(at)];
1500
+ }
1501
+ function structuralCommit(action, next, touched) {
1502
+ if (!next)
1503
+ return;
1504
+ commit(action, next, touched);
1505
+ }
1506
+ // ---- API -------------------------------------------------------------------
1507
+ const engine = {
1508
+ load(tasks) {
1509
+ world = buildWorld(tasks, null, ctx.opt.dependencyLag?.normalizeOnLoad === true);
1510
+ critical = new Set();
1511
+ version++;
1512
+ for (const l of listeners)
1513
+ l(null);
1514
+ },
1515
+ setOptions(options) {
1516
+ ctx = makeCtx(options);
1517
+ world = buildWorld(world.list, world, false);
1518
+ version++;
1519
+ for (const l of listeners)
1520
+ l(null);
1521
+ },
1522
+ get options() {
1523
+ return ctx.opt;
1524
+ },
1525
+ getTask: (id) => {
1526
+ const i = world.ids.get(id);
1527
+ return i === undefined ? undefined : world.list[i];
1528
+ },
1529
+ getSchedule: (id) => {
1530
+ const i = world.ids.get(id);
1531
+ return i === undefined ? undefined : world.sched[i];
1532
+ },
1533
+ getTasks: () => world.list,
1534
+ getSchedules: () => world.sched,
1535
+ get version() {
1536
+ return version;
1537
+ },
1538
+ subscribe(listener) {
1539
+ listeners.add(listener);
1540
+ return () => void listeners.delete(listener);
1541
+ },
1542
+ update(id, changes, options) {
1543
+ return strip(runUpdate(options?.source === 'taskbar' ? 'taskbarEdit' : 'edit', id, changes, options, {}));
1544
+ },
1545
+ preview(id, changes, options) {
1546
+ const r = runUpdate('edit', id, changes, options, { preview: true });
1547
+ return { changed: r.changed, conflicts: r.conflicts, schedules: r.schedules };
1548
+ },
1549
+ add(task, at) {
1550
+ if (world.ids.has(task.id))
1551
+ return;
1552
+ const list = world.list.slice();
1553
+ let index = at?.index;
1554
+ if (index === undefined) {
1555
+ const p = task.parentId === null || task.parentId === undefined ? undefined : world.ids.get(task.parentId);
1556
+ index = p === undefined ? list.length : world.subEnd[p];
1557
+ }
1558
+ list.splice(Math.max(0, Math.min(list.length, index)), 0, task);
1559
+ commit('add', list, new Set([task.id]));
1560
+ },
1561
+ remove(ids) {
1562
+ const gone = new Set();
1563
+ for (const i of roots(ids))
1564
+ for (const id of subtreeIds(i))
1565
+ gone.add(id);
1566
+ if (!gone.size)
1567
+ return;
1568
+ const touched = new Set(gone);
1569
+ const next = [];
1570
+ for (const t of world.list) {
1571
+ if (gone.has(t.id))
1572
+ continue;
1573
+ if (t.predecessors?.some((d) => gone.has(d.id))) {
1574
+ next.push({ ...t, predecessors: t.predecessors.filter((d) => !gone.has(d.id)) });
1575
+ touched.add(t.id);
1576
+ }
1577
+ else
1578
+ next.push(t);
1579
+ }
1580
+ commit('delete', next, touched);
1581
+ },
1582
+ changeId(id, newId) {
1583
+ if (id === newId || !world.ids.has(id) || world.ids.has(newId))
1584
+ return;
1585
+ const touched = new Set([id, newId]);
1586
+ const next = world.list.map((t) => {
1587
+ let r = t;
1588
+ if (t.id === id)
1589
+ r = { ...r, id: newId };
1590
+ if (t.parentId === id)
1591
+ r = { ...r, parentId: newId };
1592
+ if (t.predecessors?.some((d) => d.id === id))
1593
+ r = { ...r, predecessors: t.predecessors.map((d) => (d.id === id ? { ...d, id: newId } : d)) };
1594
+ if (r !== t)
1595
+ touched.add(t.id).add(r.id);
1596
+ return r;
1597
+ });
1598
+ commit('changeId', next, touched);
1599
+ },
1600
+ move(ids, targetId, position) {
1601
+ const blocks = roots(ids).map(subtreeIds);
1602
+ const touched = new Set();
1603
+ structuralCommit('move', moveBlocks(world.list, blocks, targetId, position, touched), touched);
1604
+ },
1605
+ indent(ids) {
1606
+ const w = world;
1607
+ const newParent = new Map();
1608
+ const touched = new Set();
1609
+ for (const i of roots(ids)) {
1610
+ let j = i - 1;
1611
+ while (j >= 0 && w.level[j] > w.level[i])
1612
+ j--;
1613
+ if (j < 0 || w.parentOf[j] !== w.parentOf[i])
1614
+ continue;
1615
+ const sib = w.list[j].id;
1616
+ newParent.set(w.list[i].id, newParent.get(sib) ?? sib);
1617
+ }
1618
+ if (!newParent.size)
1619
+ return;
1620
+ const next = w.list.map((t) => {
1621
+ const p = newParent.get(t.id);
1622
+ if (p === undefined)
1623
+ return t;
1624
+ touched.add(t.id);
1625
+ return { ...t, parentId: p };
1626
+ });
1627
+ commit('indent', next, touched);
1628
+ },
1629
+ outdent(ids) {
1630
+ let list = world.list;
1631
+ const touched = new Set();
1632
+ const sel = roots(ids).filter((i) => world.parentOf[i] >= 0);
1633
+ for (let k = sel.length - 1; k >= 0; k--) {
1634
+ const i = sel[k];
1635
+ const parentId = world.list[world.parentOf[i]].id;
1636
+ const moved = moveBlocks(list, [subtreeIdsIn(list, world.list[i].id)], parentId, 'below', touched);
1637
+ if (moved)
1638
+ list = moved;
1639
+ }
1640
+ if (touched.size)
1641
+ commit('outdent', list, touched);
1642
+ },
1643
+ addDependency(taskId, dep) {
1644
+ const t = engine.getTask(taskId);
1645
+ if (!t)
1646
+ return { changed: new Set(), conflicts: [] };
1647
+ const deps = (t.predecessors ?? []).filter((d) => d.id !== dep.id);
1648
+ return strip(runUpdate('dependency', taskId, { predecessors: [...deps, dep] }, undefined, { raw: true, cycleCheck: true }));
1649
+ },
1650
+ removeDependency(taskId, predecessorId) {
1651
+ const t = engine.getTask(taskId);
1652
+ if (!t || !t.predecessors?.some((d) => d.id === predecessorId))
1653
+ return { changed: new Set(), conflicts: [] };
1654
+ return strip(runUpdate('dependency', taskId, { predecessors: t.predecessors.filter((d) => d.id !== predecessorId) }, undefined, { raw: true }));
1655
+ },
1656
+ setDependencies(taskId, deps) {
1657
+ return strip(runUpdate('dependency', taskId, { predecessors: deps.slice() }, undefined, { raw: true, cycleCheck: true }));
1658
+ },
1659
+ splitTask(id, at, gapWorkMs) {
1660
+ const i = world.ids.get(id);
1661
+ if (i === undefined || world.isParent[i])
1662
+ return { changed: new Set(), conflicts: [] };
1663
+ const s = world.sched[i];
1664
+ const p = world.prep[i];
1665
+ if (s.start === null || s.end === null)
1666
+ return { changed: new Set(), conflicts: [] };
1667
+ const gap = gapWorkMs ?? p.cal.unitMs('day');
1668
+ const segs = (s.segments ?? [{ start: s.start, end: s.end }]).map((x) => ({ start: x.start, end: x.end }));
1669
+ const k = segs.findIndex((x) => at > x.start && at < x.end);
1670
+ if (k < 0 || gap <= 0)
1671
+ return { changed: new Set(), conflicts: [] };
1672
+ const cut = segs[k];
1673
+ const restWork = p.cal.workBetween(at, cut.end);
1674
+ const nextStart = p.cal.nextWorkingStart(p.cal.addWork(at, gap));
1675
+ const out = [];
1676
+ for (let j = 0; j < segs.length; j++) {
1677
+ const x = segs[j];
1678
+ if (j < k)
1679
+ out.push(x);
1680
+ else if (j === k) {
1681
+ out.push({ start: x.start, end: at });
1682
+ out.push({ start: nextStart, end: p.cal.addWork(nextStart, restWork) });
1683
+ }
1684
+ else {
1685
+ const shifted = p.cal.nextWorkingStart(p.cal.addWork(x.start, gap));
1686
+ out.push({ start: shifted, end: p.cal.addWork(shifted, p.cal.workBetween(x.start, x.end)) });
1687
+ }
1688
+ }
1689
+ return strip(runUpdate('split', id, { segments: out, start: s.start, end: null, duration: null }, undefined, { raw: true }));
1690
+ },
1691
+ mergeSegments(id, indexes) {
1692
+ const i = world.ids.get(id);
1693
+ const s = i === undefined ? undefined : world.sched[i];
1694
+ if (!s || !s.segments || indexes.length < 2)
1695
+ return { changed: new Set(), conflicts: [] };
1696
+ const lo = Math.max(0, Math.min(...indexes));
1697
+ const hi = Math.min(s.segments.length - 1, Math.max(...indexes));
1698
+ if (hi <= lo)
1699
+ return { changed: new Set(), conflicts: [] };
1700
+ const segs = [];
1701
+ s.segments.forEach((x, j) => {
1702
+ if (j < lo || j > hi)
1703
+ segs.push({ start: x.start, end: x.end });
1704
+ else if (j === lo)
1705
+ segs.push({ start: x.start, end: s.segments[hi].end });
1706
+ });
1707
+ if (segs.length === 1)
1708
+ return strip(runUpdate('merge', id, { segments: null, start: s.start, end: segs[0].end ?? null, duration: null }, undefined, { raw: true }));
1709
+ return strip(runUpdate('merge', id, { segments: segs, start: s.start, end: null, duration: null }, undefined, { raw: true }));
1710
+ },
1711
+ setTaskMode(id, manual) {
1712
+ const s = engine.getSchedule(id);
1713
+ const changes = s && s.start !== null && manual ? { manual, start: s.start, end: s.end } : { manual };
1714
+ return strip(runUpdate('taskMode', id, changes, undefined, { raw: true }));
1715
+ },
1716
+ convertToMilestone(id) {
1717
+ const s = engine.getSchedule(id);
1718
+ if (!s || s.parent)
1719
+ return { changed: new Set(), conflicts: [] };
1720
+ return strip(runUpdate('convertToMilestone', id, { milestone: true, duration: 0, end: null, start: s.start, segments: null }, undefined, { raw: true }));
1721
+ },
1722
+ convertToTask(id) {
1723
+ const s = engine.getSchedule(id);
1724
+ if (!s || s.parent)
1725
+ return { changed: new Set(), conflicts: [] };
1726
+ const unit = s.durationUnit;
1727
+ const cal = engine.calendarOf(id);
1728
+ return strip(runUpdate('convertToTask', id, { milestone: false, duration: cal.fromWorkMs(cal.unitMs('day'), unit), end: null, start: s.start }, undefined, { raw: true }));
1729
+ },
1730
+ projectRange() {
1731
+ let start = finite(ctx.opt.projectStart) ? ctx.opt.projectStart : Infinity;
1732
+ let end = finite(ctx.opt.projectEnd) ? ctx.opt.projectEnd : -Infinity;
1733
+ const fixedStart = finite(ctx.opt.projectStart);
1734
+ const fixedEnd = finite(ctx.opt.projectEnd);
1735
+ if (!fixedStart || !fixedEnd)
1736
+ for (const s of world.sched) {
1737
+ if (s.start === null || s.end === null)
1738
+ continue;
1739
+ if (!fixedStart && s.start < start)
1740
+ start = s.start;
1741
+ if (!fixedEnd && s.end > end)
1742
+ end = s.end;
1743
+ }
1744
+ return Number.isFinite(start) && Number.isFinite(end) ? { start, end: Math.max(start, end) } : null;
1745
+ },
1746
+ setProjectDates(start, end) {
1747
+ engine.setOptions({ ...ctx.opt, projectStart: start, projectEnd: end });
1748
+ },
1749
+ computeCriticalPath(computeCritical) {
1750
+ const w = world;
1751
+ const n = w.n;
1752
+ const start = new Float64Array(n);
1753
+ const end = new Float64Array(n);
1754
+ const span = new Float64Array(n);
1755
+ const unscheduled = new Uint8Array(n);
1756
+ const calendars = new Array(n);
1757
+ for (let i = 0; i < n; i++) {
1758
+ const o = i * K;
1759
+ start[i] = w.st[o + S];
1760
+ end[i] = w.st[o + E];
1761
+ unscheduled[i] = w.st[o + UN] ? 1 : 0;
1762
+ const p = w.prep[i];
1763
+ span[i] = w.isParent[i] ? w.st[o + W] : p.span;
1764
+ calendars[i] = p.cal;
1765
+ }
1766
+ const r = computeCritical({
1767
+ n,
1768
+ topo: w.g.topo,
1769
+ parentOf: w.parentOf,
1770
+ isParent: w.isParent,
1771
+ childStart: w.childStart,
1772
+ childList: w.childList,
1773
+ depStart: w.g.depStart,
1774
+ depPred: w.g.depPred,
1775
+ depType: w.g.depType,
1776
+ depLag: w.g.depLag,
1777
+ depDropped: w.g.depDropped,
1778
+ start,
1779
+ end,
1780
+ span,
1781
+ unscheduled,
1782
+ calendars,
1783
+ finish: finite(ctx.opt.projectEnd) ? ctx.opt.projectEnd : null,
1784
+ });
1785
+ const set = new Set();
1786
+ const changed = new Set();
1787
+ for (let i = 0; i < n; i++) {
1788
+ const old = w.sched[i];
1789
+ const crit = !unscheduled[i] && r.critical[i] === 1;
1790
+ if (crit)
1791
+ set.add(old.id);
1792
+ const next = makeSchedule(w, i, old, { critical: crit, totalFloat: Math.round(r.totalFloat[i]), freeFloat: Math.round(r.freeFloat[i]) });
1793
+ if (next !== old) {
1794
+ w.sched[i] = next;
1795
+ changed.add(old.id);
1796
+ }
1797
+ }
1798
+ critical = set;
1799
+ if (changed.size) {
1800
+ version++;
1801
+ for (const l of listeners)
1802
+ l(changed);
1803
+ }
1804
+ return { critical, finish: r.finish };
1805
+ },
1806
+ formatDuration(task, text) {
1807
+ const s = typeof task === 'string' ? engine.getSchedule(task) : task;
1808
+ return s ? formatDurationValue(s.duration, s.durationUnit, text) : '';
1809
+ },
1810
+ parseDuration: (text, unit, words) => parseDurationText(text, unit, words),
1811
+ formatWork(task, text) {
1812
+ const s = typeof task === 'string' ? engine.getSchedule(task) : task;
1813
+ return s ? formatDurationValue(s.work, ctx.workUnit, text) : '';
1814
+ },
1815
+ formatWbsPredecessors(id) {
1816
+ const t = engine.getTask(id);
1817
+ if (!t?.predecessors)
1818
+ return '';
1819
+ const out = [];
1820
+ for (const d of t.predecessors) {
1821
+ const q = world.ids.get(d.id);
1822
+ if (q !== undefined)
1823
+ out.push(formatDependency(d, world.wbs[q]));
1824
+ }
1825
+ return out.join(',');
1826
+ },
1827
+ successorsOf(id) {
1828
+ const out = [];
1829
+ for (const t of world.list)
1830
+ if (t.predecessors?.some((d) => d.id === id))
1831
+ out.push(t.id);
1832
+ return out;
1833
+ },
1834
+ calendarOf(id) {
1835
+ const i = id === null ? undefined : world.ids.get(id);
1836
+ return i === undefined ? ctx.project : world.prep[i].cal;
1837
+ },
1838
+ batch(action, fn) {
1839
+ if (depth === 0) {
1840
+ batchAction = action;
1841
+ batchList = world.list;
1842
+ batchTouched = new Set();
1843
+ batchChanged = new Set();
1844
+ batchNotify = false;
1845
+ }
1846
+ depth++;
1847
+ try {
1848
+ return fn();
1849
+ }
1850
+ finally {
1851
+ depth--;
1852
+ if (depth === 0) {
1853
+ if (recording && batchTouched.size && recorders.size) {
1854
+ const record = Object.freeze({ action: batchAction, before: snapshots(batchList, batchTouched), after: snapshots(world.list, batchTouched) });
1855
+ for (const r of recorders)
1856
+ r(record);
1857
+ }
1858
+ if (batchNotify)
1859
+ for (const l of listeners)
1860
+ l(batchChanged);
1861
+ }
1862
+ }
1863
+ },
1864
+ onCommit(listener) {
1865
+ recorders.add(listener);
1866
+ return () => void recorders.delete(listener);
1867
+ },
1868
+ applyRecord(record, side) {
1869
+ const to = side === 'before' ? record.before : record.after;
1870
+ const drop = new Set();
1871
+ for (const s of record.before)
1872
+ drop.add(s.id);
1873
+ for (const s of record.after)
1874
+ drop.add(s.id);
1875
+ const next = world.list.filter((t) => !drop.has(t.id));
1876
+ for (const s of [...to].sort((a, b) => a.index - b.index))
1877
+ next.splice(Math.min(next.length, s.index), 0, s.task);
1878
+ const was = recording;
1879
+ recording = false;
1880
+ try {
1881
+ return strip(commit(record.action, next, drop));
1882
+ }
1883
+ finally {
1884
+ recording = was;
1885
+ }
1886
+ },
1887
+ };
1888
+ function subtreeIdsIn(list, id) {
1889
+ const i = list.findIndex((t) => t.id === id);
1890
+ if (i < 0)
1891
+ return [];
1892
+ const inSub = new Set([id]);
1893
+ const out = [id];
1894
+ for (let k = i + 1; k < list.length; k++) {
1895
+ const t = list[k];
1896
+ if (t.parentId !== null && t.parentId !== undefined && inSub.has(t.parentId)) {
1897
+ inSub.add(t.id);
1898
+ out.push(t.id);
1899
+ }
1900
+ else
1901
+ break;
1902
+ }
1903
+ return out;
1904
+ }
1905
+ return engine;
1906
+ }
1907
+ //# sourceMappingURL=engine.js.map