@classic-homes/gantt-core 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@
4
4
  var MINUTE = 6e4;
5
5
  var HOUR = 60 * MINUTE;
6
6
  var DAY = 24 * HOUR;
7
- var ISO_RE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/;
7
+ var ISO_RE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(?:Z|[+-](?:[01]\d|2[0-3]):?[0-5]\d)?)?$/;
8
8
  function isDateOnly(input) {
9
9
  return typeof input === "string" && /^\d{4}-\d{2}-\d{2}$/.test(input.trim());
10
10
  }
@@ -15,21 +15,25 @@ function parseTime(input) {
15
15
  }
16
16
  if (input instanceof Date) {
17
17
  if (Number.isNaN(input.getTime())) throw new RangeError("Invalid Date");
18
- return Date.UTC(
19
- input.getFullYear(),
20
- input.getMonth(),
21
- input.getDate(),
18
+ const date2 = /* @__PURE__ */ new Date(0);
19
+ date2.setUTCFullYear(input.getFullYear(), input.getMonth(), input.getDate());
20
+ date2.setUTCHours(
22
21
  input.getHours(),
23
22
  input.getMinutes(),
24
- input.getSeconds()
23
+ input.getSeconds(),
24
+ input.getMilliseconds()
25
25
  );
26
+ return date2.getTime();
26
27
  }
27
28
  const m = ISO_RE.exec(input.trim());
28
29
  if (!m) throw new RangeError(`Invalid time: "${input}"`);
29
- const [, y, mo, d, h = "0", mi = "0", s = "0"] = m;
30
- const t = Date.UTC(+y, +mo - 1, +d, +h, +mi, +s);
31
- if (Number.isNaN(t)) throw new RangeError(`Invalid time: "${input}"`);
32
- return t;
30
+ const [, y, mo, d, h = "0", mi = "0", s = "0", fraction = "0"] = m;
31
+ const date = /* @__PURE__ */ new Date(0);
32
+ date.setUTCFullYear(+y, +mo - 1, +d);
33
+ date.setUTCHours(+h, +mi, +s, +fraction.padEnd(3, "0"));
34
+ if (date.getUTCFullYear() !== +y || date.getUTCMonth() !== +mo - 1 || date.getUTCDate() !== +d || date.getUTCHours() !== +h || date.getUTCMinutes() !== +mi || date.getUTCSeconds() !== +s)
35
+ throw new RangeError(`Invalid time: "${input}"`);
36
+ return date.getTime();
33
37
  }
34
38
  function tryParseTime(input) {
35
39
  if (input === void 0 || input === null || input === "") return void 0;
@@ -42,20 +46,16 @@ function tryParseTime(input) {
42
46
  var pad = (n) => String(n).padStart(2, "0");
43
47
  function formatTime(t, options = {}) {
44
48
  const d = new Date(t);
45
- const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
49
+ const date = `${String(d.getUTCFullYear()).padStart(4, "0")}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
46
50
  if (options.dateOnly) return date;
47
51
  return `${date}T${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
48
52
  }
49
53
  function toLocalDate(t) {
50
54
  const d = new Date(t);
51
- return new Date(
52
- d.getUTCFullYear(),
53
- d.getUTCMonth(),
54
- d.getUTCDate(),
55
- d.getUTCHours(),
56
- d.getUTCMinutes(),
57
- d.getUTCSeconds()
58
- );
55
+ const local = /* @__PURE__ */ new Date(0);
56
+ local.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
57
+ local.setHours(d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds());
58
+ return local;
59
59
  }
60
60
  function startOfDay(t) {
61
61
  return Math.floor(t / DAY) * DAY;
@@ -303,18 +303,21 @@ function buildTaskTree(tasks) {
303
303
  if (p === t.id) invalidParents.push({ id: t.id, reason: "cycle" });
304
304
  }
305
305
  }
306
+ const done = /* @__PURE__ */ new Set();
306
307
  for (const t of tasks) {
307
- const seen = /* @__PURE__ */ new Set([t.id]);
308
- let cur = parent.get(t.id) ?? null;
309
- while (cur !== null) {
310
- if (seen.has(cur)) {
311
- parent.set(t.id, null);
312
- invalidParents.push({ id: t.id, reason: "cycle" });
308
+ if (done.has(t.id)) continue;
309
+ const path = /* @__PURE__ */ new Set();
310
+ let cur = t.id;
311
+ while (cur !== null && !done.has(cur)) {
312
+ if (path.has(cur)) {
313
+ parent.set(cur, null);
314
+ invalidParents.push({ id: cur, reason: "cycle" });
313
315
  break;
314
316
  }
315
- seen.add(cur);
317
+ path.add(cur);
316
318
  cur = parent.get(cur) ?? null;
317
319
  }
320
+ for (const id of path) done.add(id);
318
321
  }
319
322
  const children = /* @__PURE__ */ new Map();
320
323
  for (const t of tasks) {
@@ -375,26 +378,27 @@ function findCycle(nodes, successors) {
375
378
  const allowed = new Set(nodes);
376
379
  const state = /* @__PURE__ */ new Map();
377
380
  const path = [];
378
- const visit = (n) => {
379
- state.set(n, 1);
380
- path.push(n);
381
- for (const s of successors.get(n) ?? []) {
382
- if (!allowed.has(s)) continue;
383
- const st = state.get(s);
384
- if (st === 1) return path.slice(path.indexOf(s));
385
- if (st === void 0) {
386
- const found = visit(s);
387
- if (found) return found;
388
- }
389
- }
390
- path.pop();
391
- state.set(n, 2);
392
- return null;
393
- };
394
381
  for (const n of nodes) {
395
- if (!state.has(n)) {
396
- const found = visit(n);
397
- if (found) return found;
382
+ if (state.has(n)) continue;
383
+ const stack = [];
384
+ const enter = (id) => {
385
+ state.set(id, 1);
386
+ path.push(id);
387
+ stack.push({ id, next: (successors.get(id) ?? /* @__PURE__ */ new Set()).values() });
388
+ };
389
+ enter(n);
390
+ while (stack.length) {
391
+ const frame = stack[stack.length - 1];
392
+ const next = frame.next.next();
393
+ if (next.done) {
394
+ stack.pop();
395
+ path.pop();
396
+ state.set(frame.id, 2);
397
+ } else if (allowed.has(next.value)) {
398
+ const st = state.get(next.value);
399
+ if (st === 1) return path.slice(path.indexOf(next.value));
400
+ if (st === void 0) enter(next.value);
401
+ }
398
402
  }
399
403
  }
400
404
  return null;
@@ -454,6 +458,30 @@ function parseFinish(cal, end) {
454
458
  const t = parseTime(end);
455
459
  return cal.prevWorking(isDateOnly(end) ? t + DAY : t);
456
460
  }
461
+ function latestLagSource(cal, bound, lag) {
462
+ if (lag === 0) return bound;
463
+ const candidate = cal.add(bound, -lag);
464
+ let lo = candidate;
465
+ let hi = candidate;
466
+ let span = DAY;
467
+ if (cal.add(candidate, lag) <= bound) {
468
+ do {
469
+ hi = candidate + span;
470
+ span *= 2;
471
+ } while (cal.add(hi, lag) <= bound);
472
+ } else {
473
+ do {
474
+ lo = candidate - span;
475
+ span *= 2;
476
+ } while (cal.add(lo, lag) > bound);
477
+ }
478
+ while (hi - lo > 1) {
479
+ const mid = lo + Math.floor((hi - lo) / 2);
480
+ if (cal.add(mid, lag) <= bound) lo = mid;
481
+ else hi = mid;
482
+ }
483
+ return lo;
484
+ }
457
485
  function scheduleProject(tasks, dependencies = [], calendars = [], options = {}) {
458
486
  const conflicts = [];
459
487
  const cals = compileCalendars(calendars);
@@ -724,16 +752,16 @@ function scheduleProject(tasks, dependencies = [], calendars = [], options = {})
724
752
  const t = nodes.get(tid);
725
753
  switch (e.type) {
726
754
  case "FS":
727
- lf = min(lf, t.cal.add(t.ls, -e.lag));
755
+ lf = min(lf, latestLagSource(t.cal, t.ls, e.lag));
728
756
  break;
729
757
  case "SS":
730
- ls = min(ls, t.cal.add(t.ls, -e.lag));
758
+ ls = min(ls, latestLagSource(t.cal, t.ls, e.lag));
731
759
  break;
732
760
  case "FF":
733
- lf = min(lf, t.cal.add(t.lf, -e.lag));
761
+ lf = min(lf, latestLagSource(t.cal, t.lf, e.lag));
734
762
  break;
735
763
  case "SF":
736
- ls = min(ls, t.cal.add(t.lf, -e.lag));
764
+ ls = min(ls, latestLagSource(t.cal, t.lf, e.lag));
737
765
  break;
738
766
  }
739
767
  }
@@ -764,7 +792,10 @@ function scheduleProject(tasks, dependencies = [], calendars = [], options = {})
764
792
  if (n.deadline !== void 0) lf = min(lf, n.deadline);
765
793
  let finish = n.duration === 0 ? lf : n.cal.prevWorking(lf);
766
794
  if (ls !== INF)
767
- finish = min(finish, n.duration === 0 ? ls : n.cal.add(n.cal.prevWorking(ls), n.duration));
795
+ finish = min(
796
+ finish,
797
+ n.duration === 0 ? ls : n.cal.add(n.cal.isWorking(ls) ? ls : n.cal.prevWorking(ls) - 1, n.duration)
798
+ );
768
799
  n.lf = finish;
769
800
  n.ls = startFromFinish(n, finish);
770
801
  }
@@ -813,16 +844,16 @@ function scheduleProject(tasks, dependencies = [], calendars = [], options = {})
813
844
  let allowed;
814
845
  switch (e.type) {
815
846
  case "FS":
816
- allowed = n.cal.between(n.ef, n.cal.prevWorking(t.cal.add(t.es, -e.lag)));
847
+ allowed = n.cal.between(n.ef, n.cal.prevWorking(latestLagSource(t.cal, t.es, e.lag)));
817
848
  break;
818
849
  case "SS":
819
- allowed = n.cal.between(n.es, t.cal.add(t.es, -e.lag));
850
+ allowed = n.cal.between(n.es, latestLagSource(t.cal, t.es, e.lag));
820
851
  break;
821
852
  case "FF":
822
- allowed = n.cal.between(n.ef, t.cal.add(t.ef, -e.lag));
853
+ allowed = n.cal.between(n.ef, latestLagSource(t.cal, t.ef, e.lag));
823
854
  break;
824
855
  case "SF":
825
- allowed = n.cal.between(n.es, t.cal.add(t.ef, -e.lag));
856
+ allowed = n.cal.between(n.es, latestLagSource(t.cal, t.ef, e.lag));
826
857
  break;
827
858
  }
828
859
  freeSlack = min(freeSlack, allowed);
@@ -835,23 +866,34 @@ function scheduleProject(tasks, dependencies = [], calendars = [], options = {})
835
866
  if (isCritical) critical.push(id);
836
867
  result.set(id, toScheduled(n, totalSlack, freeSlack, isCritical));
837
868
  }
869
+ const aggregates = /* @__PURE__ */ new Map();
838
870
  for (const id of order) {
839
871
  const n = nodes.get(id);
840
- if (!n.isSummary) continue;
841
- const leafIds = leaves(id);
842
- let weighted = 0;
843
- let weight = 0;
844
- let slack = INF;
845
- let anyCritical = false;
846
- for (const l of leafIds) {
847
- const st = result.get(l);
848
- weighted += st.progress * st.duration;
849
- weight += st.duration;
850
- slack = min(slack, st.totalSlack);
851
- anyCritical || (anyCritical = st.critical);
872
+ if (!n.isSummary) {
873
+ const st = result.get(id);
874
+ aggregates.set(id, {
875
+ weighted: st.progress * st.duration,
876
+ weight: st.duration,
877
+ progress: st.progress,
878
+ count: 1,
879
+ slack: st.totalSlack,
880
+ critical: st.critical
881
+ });
882
+ continue;
852
883
  }
853
- n.progress = weight > 0 ? weighted / weight : leafIds.reduce((s, l) => s + result.get(l).progress, 0) / Math.max(1, leafIds.length);
854
- result.set(id, toScheduled(n, slack === INF ? 0 : slack, 0, anyCritical));
884
+ const sum = { weighted: 0, weight: 0, progress: 0, count: 0, slack: INF, critical: false };
885
+ for (const child of tree.children.get(id) ?? []) {
886
+ const a = aggregates.get(child);
887
+ sum.weighted += a.weighted;
888
+ sum.weight += a.weight;
889
+ sum.progress += a.progress;
890
+ sum.count += a.count;
891
+ sum.slack = min(sum.slack, a.slack);
892
+ sum.critical || (sum.critical = a.critical);
893
+ }
894
+ aggregates.set(id, sum);
895
+ n.progress = sum.weight > 0 ? sum.weighted / sum.weight : sum.progress / Math.max(1, sum.count);
896
+ result.set(id, toScheduled(n, sum.slack === INF ? 0 : sum.slack, 0, sum.critical));
855
897
  }
856
898
  function toScheduled(n, totalSlack, freeSlack, isCritical) {
857
899
  const baseline = n.task.baseline;
@@ -943,29 +985,50 @@ function flattenTasks(tasks, isExpanded, tree = buildTaskTree(tasks)) {
943
985
  const byId = new Map(tasks.map((t) => [t.id, t]));
944
986
  const rows = [];
945
987
  const wbs = /* @__PURE__ */ new Map();
946
- const walk = (parentId, prefix, level, visible) => {
947
- const kids = tree.children.get(parentId) ?? [];
948
- kids.forEach((id, i) => {
949
- const code = prefix ? `${prefix}.${i + 1}` : String(i + 1);
950
- wbs.set(id, code);
951
- const hasChildren = (tree.children.get(id)?.length ?? 0) > 0;
952
- const expanded = hasChildren && isExpanded(id);
953
- if (visible) {
954
- rows.push({
955
- id,
956
- task: byId.get(id),
957
- index: rows.length,
958
- level,
959
- wbs: code,
960
- hasChildren,
961
- expanded,
962
- parentId
963
- });
964
- }
965
- if (hasChildren) walk(id, code, level + 1, visible && expanded);
966
- });
967
- };
968
- walk(null, "", 1, true);
988
+ const stack = [
989
+ {
990
+ parentId: null,
991
+ prefix: "",
992
+ level: 1,
993
+ visible: true,
994
+ kids: tree.children.get(null) ?? [],
995
+ index: 0
996
+ }
997
+ ];
998
+ while (stack.length) {
999
+ const frame = stack[stack.length - 1];
1000
+ if (frame.index >= frame.kids.length) {
1001
+ stack.pop();
1002
+ continue;
1003
+ }
1004
+ const i = frame.index++;
1005
+ const id = frame.kids[i];
1006
+ const code = frame.prefix ? `${frame.prefix}.${i + 1}` : String(i + 1);
1007
+ wbs.set(id, code);
1008
+ const kids = tree.children.get(id) ?? [];
1009
+ const hasChildren = kids.length > 0;
1010
+ const expanded = hasChildren && isExpanded(id);
1011
+ if (frame.visible)
1012
+ rows.push({
1013
+ id,
1014
+ task: byId.get(id),
1015
+ index: rows.length,
1016
+ level: frame.level,
1017
+ wbs: code,
1018
+ hasChildren,
1019
+ expanded,
1020
+ parentId: frame.parentId
1021
+ });
1022
+ if (hasChildren)
1023
+ stack.push({
1024
+ parentId: id,
1025
+ prefix: code,
1026
+ level: frame.level + 1,
1027
+ visible: frame.visible && expanded,
1028
+ kids,
1029
+ index: 0
1030
+ });
1031
+ }
969
1032
  return { rows, wbs };
970
1033
  }
971
1034
 
@@ -983,13 +1046,29 @@ function applyOperation(data, op) {
983
1046
  const fail = (msg) => {
984
1047
  throw new GanttEditError(msg, op);
985
1048
  };
1049
+ const tree = buildTaskTree(tasks);
1050
+ const protectedIds = /* @__PURE__ */ new Set();
1051
+ const protectedStack = tasks.filter((t) => t.readonly).map((t) => t.id);
1052
+ while (protectedStack.length) {
1053
+ const id = protectedStack.pop();
1054
+ if (protectedIds.has(id)) continue;
1055
+ protectedIds.add(id);
1056
+ for (const child of tree.children.get(id) ?? []) protectedStack.push(child);
1057
+ }
1058
+ const writable = (id) => {
1059
+ if (id != null && protectedIds.has(id)) fail(`Task "${id}" is read-only`);
1060
+ };
986
1061
  switch (op.type) {
987
1062
  case "update-task": {
988
1063
  const i = tasks.findIndex((t) => t.id === op.id);
989
1064
  if (i < 0) fail(`Unknown task "${op.id}"`);
990
1065
  const prev = tasks[i];
1066
+ writable(op.id);
1067
+ writable(op.patch.parentId);
1068
+ if ("parentId" in op.patch && op.patch.parentId !== prev.parentId) {
1069
+ for (const id of descendantsOf(tree, op.id)) writable(id);
1070
+ }
991
1071
  if ("parentId" in op.patch && op.patch.parentId) {
992
- const tree = buildTaskTree(tasks);
993
1072
  if (op.patch.parentId === op.id || descendantsOf(tree, op.id).includes(op.patch.parentId)) {
994
1073
  fail("A task cannot be moved under itself");
995
1074
  }
@@ -1013,6 +1092,7 @@ function applyOperation(data, op) {
1013
1092
  case "add-task": {
1014
1093
  if (!op.task.id) fail("Task needs an id");
1015
1094
  if (tasks.some((t) => t.id === op.task.id)) fail(`Task "${op.task.id}" already exists`);
1095
+ writable(op.task.parentId);
1016
1096
  const copy = tasks.slice();
1017
1097
  const index = op.index === void 0 ? copy.length : Math.max(0, Math.min(op.index, copy.length));
1018
1098
  copy.splice(index, 0, op.task);
@@ -1024,26 +1104,34 @@ function applyOperation(data, op) {
1024
1104
  case "remove-task": {
1025
1105
  const i = tasks.findIndex((t) => t.id === op.id);
1026
1106
  if (i < 0) fail(`Unknown task "${op.id}"`);
1027
- const tree = buildTaskTree(tasks);
1028
1107
  const doomed = /* @__PURE__ */ new Set([op.id, ...descendantsOf(tree, op.id)]);
1108
+ for (const id of doomed) writable(id);
1109
+ for (const d of dependencies) {
1110
+ if (doomed.has(d.from) || doomed.has(d.to)) {
1111
+ writable(d.from);
1112
+ writable(d.to);
1113
+ }
1114
+ }
1029
1115
  const inverse = [];
1030
1116
  tasks.forEach((t, index) => {
1031
1117
  if (doomed.has(t.id)) inverse.push({ type: "add-task", task: t, index });
1032
1118
  });
1033
- const removedDeps = dependencies.filter((d) => doomed.has(d.from) || doomed.has(d.to));
1034
1119
  dependencies.forEach((d, index) => {
1035
- if (removedDeps.includes(d)) inverse.push({ type: "add-dependency", dependency: d, index });
1120
+ if (doomed.has(d.from) || doomed.has(d.to))
1121
+ inverse.push({ type: "add-dependency", dependency: d, index });
1036
1122
  });
1037
1123
  return {
1038
1124
  data: {
1039
1125
  tasks: tasks.filter((t) => !doomed.has(t.id)),
1040
- dependencies: dependencies.filter((d) => !removedDeps.includes(d))
1126
+ dependencies: dependencies.filter((d) => !doomed.has(d.from) && !doomed.has(d.to))
1041
1127
  },
1042
1128
  inverse
1043
1129
  };
1044
1130
  }
1045
1131
  case "add-dependency": {
1046
1132
  const d = op.dependency;
1133
+ writable(d.from);
1134
+ writable(d.to);
1047
1135
  if (!d.id) fail("Dependency needs an id");
1048
1136
  if (dependencies.some((x) => x.id === d.id)) fail(`Dependency "${d.id}" already exists`);
1049
1137
  if (!tasks.some((t) => t.id === d.from) || !tasks.some((t) => t.id === d.to)) {
@@ -1065,7 +1153,14 @@ function applyOperation(data, op) {
1065
1153
  const i = dependencies.findIndex((d) => d.id === op.id);
1066
1154
  if (i < 0) fail(`Unknown dependency "${op.id}"`);
1067
1155
  const prev = dependencies[i];
1156
+ writable(prev.from);
1157
+ writable(prev.to);
1068
1158
  const next = { ...prev, ...op.patch };
1159
+ writable(next.from);
1160
+ writable(next.to);
1161
+ for (const [k, v] of Object.entries(op.patch)) {
1162
+ if (v === void 0) delete next[k];
1163
+ }
1069
1164
  if (next.from !== prev.from || next.to !== prev.to) {
1070
1165
  const others = dependencies.filter((_, j) => j !== i);
1071
1166
  if (wouldCreateCycle(tasks, others, next.from, next.to))
@@ -1084,6 +1179,8 @@ function applyOperation(data, op) {
1084
1179
  case "remove-dependency": {
1085
1180
  const index = dependencies.findIndex((d) => d.id === op.id);
1086
1181
  if (index < 0) fail(`Unknown dependency "${op.id}"`);
1182
+ writable(dependencies[index].from);
1183
+ writable(dependencies[index].to);
1087
1184
  return {
1088
1185
  data: { tasks, dependencies: dependencies.filter((d) => d.id !== op.id) },
1089
1186
  inverse: [{ type: "add-dependency", dependency: dependencies[index], index }]
@@ -1122,19 +1219,61 @@ function createGanttModel(options) {
1122
1219
  let calendars = options.calendars ?? [];
1123
1220
  let scheduleOptions = options.schedule ?? {};
1124
1221
  const historyLimit = options.historyLimit ?? 100;
1222
+ if (!Number.isSafeInteger(historyLimit) || historyLimit < 0)
1223
+ throw new RangeError("historyLimit must be a nonnegative integer");
1125
1224
  const collapsed = new Set(options.collapsed ?? []);
1126
1225
  let selection = /* @__PURE__ */ new Set();
1127
1226
  let focusedId = null;
1128
1227
  let undoStack = [];
1129
1228
  let redoStack = [];
1130
1229
  let version = 0;
1131
- const run = (d) => scheduleProject(d.tasks, d.dependencies, calendars, scheduleOptions);
1230
+ const run = (d, c = calendars, o = scheduleOptions) => scheduleProject(d.tasks, d.dependencies, c, o);
1231
+ const prepare = (operations) => {
1232
+ try {
1233
+ const candidate = applyAll(data, operations);
1234
+ for (const task of candidate.data.tasks) {
1235
+ if (!task.id || typeof task.name !== "string") throw new Error("Task needs an id and name");
1236
+ if (task.duration !== void 0 && (!Number.isFinite(task.duration) || task.duration < 0))
1237
+ throw new Error(`Task "${task.id}" needs a finite, nonnegative duration`);
1238
+ if (task.progress !== void 0 && (!Number.isFinite(task.progress) || task.progress < 0 || task.progress > 100))
1239
+ throw new Error(`Task "${task.id}" progress must be between 0 and 100`);
1240
+ }
1241
+ const pairs = /* @__PURE__ */ new Set();
1242
+ for (const dep of candidate.data.dependencies) {
1243
+ if (!dep.id) throw new Error("Dependency needs an id");
1244
+ if (dep.type !== void 0 && !["FS", "SS", "FF", "SF"].includes(dep.type))
1245
+ throw new Error("Unknown dependency type");
1246
+ if (dep.lag !== void 0 && !Number.isFinite(dep.lag))
1247
+ throw new Error("Dependency needs a finite lag");
1248
+ const pair = JSON.stringify([dep.from, dep.to]);
1249
+ if (pairs.has(pair)) throw new Error("These tasks are already linked");
1250
+ pairs.add(pair);
1251
+ }
1252
+ const result = run(candidate.data);
1253
+ const invalid = result.conflicts.find(
1254
+ (c) => c.kind === "cycle" || c.kind === "invalid-dependency"
1255
+ );
1256
+ if (invalid) throw new Error(invalid.message);
1257
+ return { ...candidate, schedule: result };
1258
+ } catch (err) {
1259
+ if (err instanceof GanttEditError || !operations.length) throw err;
1260
+ throw new GanttEditError(err instanceof Error ? err.message : String(err), operations[0]);
1261
+ }
1262
+ };
1132
1263
  let schedule = run(data);
1264
+ let flattenedTasks;
1265
+ let flattened;
1266
+ let rowsDirty = true;
1133
1267
  let state = build();
1134
1268
  const listeners = /* @__PURE__ */ new Set();
1135
1269
  const changeListeners = /* @__PURE__ */ new Set();
1136
1270
  function build() {
1137
- const { rows, wbs } = flattenTasks(data.tasks, (id) => !collapsed.has(id));
1271
+ if (rowsDirty || flattenedTasks !== data.tasks) {
1272
+ flattened = flattenTasks(data.tasks, (id) => !collapsed.has(id));
1273
+ flattenedTasks = data.tasks;
1274
+ rowsDirty = false;
1275
+ }
1276
+ const { rows, wbs } = flattened;
1138
1277
  return {
1139
1278
  tasks: data.tasks,
1140
1279
  dependencies: data.dependencies,
@@ -1153,10 +1292,10 @@ function createGanttModel(options) {
1153
1292
  state = build();
1154
1293
  for (const l of listeners) l(state);
1155
1294
  }
1156
- function commit(next, source, operations, label) {
1295
+ function commit(next, source, operations, label, nextSchedule) {
1157
1296
  const before = schedule;
1158
1297
  data = next;
1159
- schedule = run(data);
1298
+ schedule = nextSchedule;
1160
1299
  const ids = new Set(data.tasks.map((t) => t.id));
1161
1300
  selection = new Set([...selection].filter((id) => ids.has(id)));
1162
1301
  if (focusedId !== null && !ids.has(focusedId)) focusedId = null;
@@ -1185,72 +1324,85 @@ function createGanttModel(options) {
1185
1324
  },
1186
1325
  apply(operations, label) {
1187
1326
  const ops = asArray(operations);
1188
- const { data: next, inverse } = applyAll(data, ops);
1189
- undoStack.push({ label, forward: ops, inverse });
1190
- if (undoStack.length > historyLimit) undoStack = undoStack.slice(-historyLimit);
1327
+ const { data: next, inverse, schedule: nextSchedule } = prepare(ops);
1328
+ if (historyLimit > 0) {
1329
+ undoStack.push({ label, forward: ops, inverse, before: data, after: next });
1330
+ if (undoStack.length > historyLimit) undoStack = undoStack.slice(-historyLimit);
1331
+ }
1191
1332
  redoStack = [];
1192
- return commit(next, "edit", ops, label);
1333
+ return commit(next, "edit", ops, label, nextSchedule);
1193
1334
  },
1194
1335
  validate(operations) {
1195
1336
  try {
1196
- applyAll(data, asArray(operations));
1337
+ prepare(asArray(operations));
1197
1338
  return null;
1198
1339
  } catch (e) {
1199
1340
  return e instanceof Error ? e.message : String(e);
1200
1341
  }
1201
1342
  },
1202
1343
  preview(operations) {
1203
- return run(applyAll(data, asArray(operations)).data);
1344
+ return prepare(asArray(operations)).schedule;
1204
1345
  },
1205
1346
  undo() {
1206
- const entry = undoStack.pop();
1347
+ const entry = undoStack[undoStack.length - 1];
1207
1348
  if (!entry) return null;
1208
- const { data: next } = applyAll(data, entry.inverse);
1349
+ const nextSchedule = run(entry.before);
1350
+ undoStack.pop();
1209
1351
  redoStack.push(entry);
1210
- return commit(next, "undo", entry.inverse, entry.label);
1352
+ return commit(entry.before, "undo", entry.inverse, entry.label, nextSchedule);
1211
1353
  },
1212
1354
  redo() {
1213
- const entry = redoStack.pop();
1355
+ const entry = redoStack[redoStack.length - 1];
1214
1356
  if (!entry) return null;
1215
- const { data: next, inverse } = applyAll(data, entry.forward);
1216
- undoStack.push({ ...entry, inverse });
1217
- return commit(next, "redo", entry.forward, entry.label);
1357
+ const nextSchedule = run(entry.after);
1358
+ redoStack.pop();
1359
+ undoStack.push(entry);
1360
+ return commit(entry.after, "redo", entry.forward, entry.label, nextSchedule);
1218
1361
  },
1219
1362
  setData(next) {
1220
- data = {
1363
+ const candidate = {
1221
1364
  tasks: next.tasks ?? data.tasks,
1222
1365
  dependencies: next.dependencies ?? data.dependencies
1223
1366
  };
1224
- if (next.calendars) calendars = next.calendars;
1367
+ const nextCalendars = next.calendars ?? calendars;
1368
+ const nextSchedule = run(candidate, nextCalendars);
1369
+ data = candidate;
1370
+ rowsDirty = true;
1371
+ calendars = nextCalendars;
1225
1372
  undoStack = [];
1226
1373
  redoStack = [];
1227
- schedule = run(data);
1374
+ schedule = nextSchedule;
1228
1375
  const ids = new Set(data.tasks.map((t) => t.id));
1229
1376
  selection = new Set([...selection].filter((id) => ids.has(id)));
1230
1377
  if (focusedId !== null && !ids.has(focusedId)) focusedId = null;
1231
1378
  emit();
1232
1379
  },
1233
1380
  setScheduleOptions(next) {
1381
+ const nextSchedule = run(data, calendars, next);
1234
1382
  scheduleOptions = next;
1235
- schedule = run(data);
1383
+ schedule = nextSchedule;
1236
1384
  emit();
1237
1385
  },
1238
1386
  toggle(id) {
1387
+ rowsDirty = true;
1239
1388
  if (collapsed.has(id)) collapsed.delete(id);
1240
1389
  else collapsed.add(id);
1241
1390
  emit();
1242
1391
  },
1243
1392
  setExpanded(id, expanded) {
1244
1393
  if (expanded === !collapsed.has(id)) return;
1394
+ rowsDirty = true;
1245
1395
  if (expanded) collapsed.delete(id);
1246
1396
  else collapsed.add(id);
1247
1397
  emit();
1248
1398
  },
1249
1399
  expandAll() {
1400
+ rowsDirty = true;
1250
1401
  collapsed.clear();
1251
1402
  emit();
1252
1403
  },
1253
1404
  collapseAll() {
1405
+ rowsDirty = true;
1254
1406
  const tree = buildTaskTree(data.tasks);
1255
1407
  for (const t of data.tasks) if (tree.children.get(t.id)?.length) collapsed.add(t.id);
1256
1408
  emit();
@@ -1634,8 +1786,12 @@ function editOperation(ctx, mode, preview) {
1634
1786
  const { source, calendar: cal, minutesPerDay, snap } = ctx;
1635
1787
  const coarse = snap !== "hour";
1636
1788
  const fmt = (t, original, isFinish) => {
1789
+ if (original instanceof Date) return toLocalDate(t);
1790
+ if (typeof original === "number") return t;
1637
1791
  if (coarse && original !== void 0 && isDateOnly(original)) {
1638
- return formatTime(isFinish && t % DAY === 0 ? t - 1 : t, { dateOnly: true });
1792
+ return formatTime(isFinish && preview.start !== preview.finish && t % DAY === 0 ? t - 1 : t, {
1793
+ dateOnly: true
1794
+ });
1639
1795
  }
1640
1796
  return formatTime(t);
1641
1797
  };
@@ -1644,7 +1800,7 @@ function editOperation(ctx, mode, preview) {
1644
1800
  const isMilestone = ctx.task.type === "milestone";
1645
1801
  if (mode === "move" || isMilestone) {
1646
1802
  patch.start = fmt(preview.start, source.start, false);
1647
- if (usesEnd && !isMilestone) patch.end = fmt(preview.finish, source.end, true);
1803
+ if (usesEnd) patch.end = fmt(preview.finish, source.end, true);
1648
1804
  } else if (mode === "resize-end") {
1649
1805
  if (usesEnd) patch.end = fmt(preview.finish, source.end, true);
1650
1806
  else patch.duration = round(cal.between(preview.start, preview.finish) / minutesPerDay);
@@ -1655,9 +1811,9 @@ function editOperation(ctx, mode, preview) {
1655
1811
  }
1656
1812
  const c = source.constraint;
1657
1813
  if (c && (c.type === "SNET" || c.type === "MSO") && patch.start !== void 0) {
1658
- patch.constraint = { ...c, date: patch.start };
1814
+ patch.constraint = { ...c, date: fmt(preview.start, c.date, false) };
1659
1815
  } else if (c && (c.type === "FNET" || c.type === "MFO") && (patch.start !== void 0 || patch.end !== void 0 || patch.duration !== void 0)) {
1660
- patch.constraint = { ...c, date: formatTime(preview.finish) };
1816
+ patch.constraint = { ...c, date: fmt(preview.finish, c.date, true) };
1661
1817
  }
1662
1818
  return { type: "update-task", id: source.id, patch };
1663
1819
  }
@@ -1730,8 +1886,14 @@ function rescheduleOperation(ctx, edit) {
1730
1886
  const patch = {};
1731
1887
  if (moved) Object.assign(patch, patchOf(editOperation(c, "move", preview)));
1732
1888
  if (resized) {
1733
- if (length === 0) patch.duration = 0;
1734
- else Object.assign(patch, patchOf(editOperation(c, "resize-end", preview)));
1889
+ if (length === 0 && ctx.source.duration === void 0 && ctx.source.end !== void 0) {
1890
+ Object.assign(patch, patchOf(editOperation(c, "resize-end", preview)));
1891
+ patch.type = "milestone";
1892
+ } else {
1893
+ Object.assign(patch, patchOf(editOperation(c, "resize-end", preview)));
1894
+ if (length === 0) patch.duration = 0;
1895
+ }
1896
+ if (length > 0 && ctx.source.type === "milestone") patch.type = "task";
1735
1897
  }
1736
1898
  return Object.keys(patch).length ? { type: "update-task", id: ctx.source.id, patch } : null;
1737
1899
  }
@@ -1761,10 +1923,15 @@ function parseDuration(text, minutesPerDay = 480) {
1761
1923
  const m = /^\s*(\d+(?:[.,]\d+)?)\s*([a-z]*)\s*$/i.exec(text);
1762
1924
  if (!m) return void 0;
1763
1925
  const n = Number(m[1].replace(",", "."));
1926
+ if (!Number.isFinite(n) || !Number.isFinite(minutesPerDay) || minutesPerDay <= 0)
1927
+ return void 0;
1764
1928
  const unit = m[2].toLowerCase();
1765
1929
  if (!unit || /^d(ays?)?$/.test(unit)) return n;
1766
- if (/^h((ou)?rs?)?$/.test(unit)) return round(n * 60 / minutesPerDay);
1767
- if (/^w((ee)?ks?)?$/.test(unit)) return n * 5;
1930
+ if (/^h((ou)?rs?)?$/.test(unit)) {
1931
+ const days = round(n * 60 / minutesPerDay);
1932
+ return Number.isFinite(days) ? days : void 0;
1933
+ }
1934
+ if (/^w((ee)?ks?)?$/.test(unit)) return Number.isFinite(n * 5) ? n * 5 : void 0;
1768
1935
  return void 0;
1769
1936
  }
1770
1937
  function indentOperation(tasks, id) {
@@ -1922,18 +2089,25 @@ function exportProject(tasks, dependencies, calendars = [], schedule) {
1922
2089
  const s = schedule?.tasks.get(t.id);
1923
2090
  const out = { ...t };
1924
2091
  if (s) {
1925
- out.start = formatTime(s.start);
1926
- if (s.type !== "milestone" && t.duration === void 0) out.end = formatTime(s.finish);
2092
+ out.start = serialiseTime(s.start);
2093
+ if (s.type !== "milestone" && t.duration === void 0) out.end = serialiseTime(s.finish);
1927
2094
  }
1928
- for (const [k, v] of Object.entries(out))
1929
- if (v instanceof Date)
1930
- out[k] = formatTime(parseTime(v));
1931
- return out;
2095
+ return serialiseWallDates(out);
1932
2096
  }),
1933
2097
  dependencies,
1934
2098
  calendars: calendars.length ? calendars : void 0
1935
2099
  };
1936
2100
  }
2101
+ var serialiseTime = (time) => time % MINUTE === 0 ? formatTime(time) : new Date(time).toISOString().slice(0, -1);
2102
+ function serialiseWallDates(value) {
2103
+ if (value instanceof Date) return serialiseTime(parseTime(value));
2104
+ if (Array.isArray(value)) return value.map(serialiseWallDates);
2105
+ if (value && typeof value === "object")
2106
+ return Object.fromEntries(
2107
+ Object.entries(value).map(([key, item]) => [key, serialiseWallDates(item)])
2108
+ );
2109
+ return value;
2110
+ }
1937
2111
  function importProject(input) {
1938
2112
  const data = typeof input === "string" ? JSON.parse(input) : input;
1939
2113
  if (!data || typeof data !== "object") throw new TypeError("Project must be an object");
@@ -1967,7 +2141,8 @@ function importProject(input) {
1967
2141
  }
1968
2142
  function tableToCsv(table) {
1969
2143
  const cell = (v) => {
1970
- const s = v === void 0 || v === null ? "" : String(v);
2144
+ const raw = v === void 0 || v === null ? "" : String(v);
2145
+ const s = /^[\s]*[=+@-]/.test(raw) ? `'${raw}` : raw;
1971
2146
  return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1972
2147
  };
1973
2148
  const lines = [table.columns.map((c) => cell(c.header)).join(",")];