@quartzio/gantt 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/API.md +533 -0
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/index.d.ts +1341 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6556 -0
- package/dist/index.js.map +1 -0
- package/dist/styles.css +1299 -0
- package/package.json +51 -3
- package/src/calendar/duration.ts +42 -0
- package/src/calendar/project.ts +29 -0
- package/src/calendar/workingCalendar.ts +218 -0
- package/src/data/draft.ts +78 -0
- package/src/data/graph.ts +215 -0
- package/src/data/normalize.ts +661 -0
- package/src/data/operations.ts +112 -0
- package/src/data/project.ts +194 -0
- package/src/data/serialize.ts +26 -0
- package/src/data/transaction.ts +460 -0
- package/src/data/tree.ts +156 -0
- package/src/data/types.ts +229 -0
- package/src/index.ts +139 -0
- package/src/scheduling/schedule.ts +310 -0
- package/src/styles.css +1299 -0
- package/src/timeaxis/align.ts +120 -0
- package/src/timeaxis/format.ts +72 -0
- package/src/timeaxis/presets.ts +219 -0
- package/src/timeaxis/timeAxis.ts +205 -0
- package/src/util/civil.ts +38 -0
- package/src/util/emitter.ts +53 -0
- package/src/util/equal.ts +23 -0
- package/src/util/errors.ts +4 -0
- package/src/util/parse.ts +70 -0
- package/src/util/time.ts +18 -0
- package/src/util/zone.ts +303 -0
- package/src/view/bars.ts +63 -0
- package/src/view/binding.ts +162 -0
- package/src/view/cellEditor.ts +239 -0
- package/src/view/cells.ts +89 -0
- package/src/view/columns.ts +197 -0
- package/src/view/createGantt.ts +1164 -0
- package/src/view/dates.ts +14 -0
- package/src/view/dependencies.ts +147 -0
- package/src/view/editing.ts +303 -0
- package/src/view/history.ts +72 -0
- package/src/view/interaction.ts +671 -0
- package/src/view/keyboard.ts +149 -0
- package/src/view/listWidth.ts +201 -0
- package/src/view/menu.ts +265 -0
- package/src/view/nonWorking.ts +113 -0
- package/src/view/range.ts +41 -0
- package/src/view/rows.ts +235 -0
- package/src/view/selection.ts +156 -0
- package/src/view/taskActions.ts +71 -0
- package/src/view/taskEditor.ts +553 -0
- package/src/view/timeline.ts +155 -0
- package/src/view/tooltip.ts +117 -0
- package/src/view/types.ts +328 -0
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quartzio/gantt",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Headless, framework-agnostic Gantt chart engine",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Sindre Glomnes",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Sindreglo/quartzio.git",
|
|
10
|
+
"directory": "packages/gantt"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/Sindreglo/quartzio#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/Sindreglo/quartzio/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"gantt",
|
|
18
|
+
"gantt-chart",
|
|
19
|
+
"scheduling",
|
|
20
|
+
"timeline",
|
|
21
|
+
"headless",
|
|
22
|
+
"project-management"
|
|
23
|
+
],
|
|
24
|
+
"type": "module",
|
|
25
|
+
"sideEffects": [
|
|
26
|
+
"**/*.css"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.ts",
|
|
31
|
+
"default": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./styles.css": {
|
|
34
|
+
"default": "./dist/styles.css"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"src",
|
|
40
|
+
"!src/**/*.test.*",
|
|
41
|
+
"API.md"
|
|
42
|
+
],
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"tsdown": "^0.23.0",
|
|
45
|
+
"typescript": "~6.0.3",
|
|
46
|
+
"vitest": "^5.0.1"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"test:watch": "vitest"
|
|
53
|
+
}
|
|
6
54
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { ProjectSettings } from '../data/types';
|
|
2
|
+
import { MS_PER_HOUR, MS_PER_MINUTE, MS_PER_SECOND } from '../util/civil';
|
|
3
|
+
import type { TimeUnit } from '../util/time';
|
|
4
|
+
|
|
5
|
+
export type DurationSettings = Pick<ProjectSettings, 'hoursPerDay' | 'daysPerWeek' | 'daysPerMonth'>;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Working milliseconds in one unit. Durations are working time (like MS Project): with 8 hours per day,
|
|
9
|
+
* "1 day" is 8 working hours, and "1 week" is `daysPerWeek` such days — not 7 calendar days.
|
|
10
|
+
*/
|
|
11
|
+
export function workingMsPerUnit(unit: TimeUnit, settings: DurationSettings): number {
|
|
12
|
+
const day = settings.hoursPerDay * MS_PER_HOUR;
|
|
13
|
+
const month = settings.daysPerMonth * day;
|
|
14
|
+
switch (unit) {
|
|
15
|
+
case 'millisecond':
|
|
16
|
+
return 1;
|
|
17
|
+
case 'second':
|
|
18
|
+
return MS_PER_SECOND;
|
|
19
|
+
case 'minute':
|
|
20
|
+
return MS_PER_MINUTE;
|
|
21
|
+
case 'hour':
|
|
22
|
+
return MS_PER_HOUR;
|
|
23
|
+
case 'day':
|
|
24
|
+
return day;
|
|
25
|
+
case 'week':
|
|
26
|
+
return settings.daysPerWeek * day;
|
|
27
|
+
case 'month':
|
|
28
|
+
return month;
|
|
29
|
+
case 'quarter':
|
|
30
|
+
return 3 * month;
|
|
31
|
+
case 'year':
|
|
32
|
+
return 12 * month;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function durationToWorkingMs(value: number, unit: TimeUnit, settings: DurationSettings): number {
|
|
37
|
+
return value * workingMsPerUnit(unit, settings);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function workingMsToDuration(ms: number, unit: TimeUnit, settings: DurationSettings): number {
|
|
41
|
+
return ms / workingMsPerUnit(unit, settings);
|
|
42
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { STANDARD_CALENDAR } from '../data/normalize';
|
|
2
|
+
import type { Calendar, Id, ProjectState } from '../data/types';
|
|
3
|
+
import { QuartzioError } from '../util/errors';
|
|
4
|
+
import type { TimeZone } from '../util/zone';
|
|
5
|
+
import { createWorkingCalendar, type WorkingCalendar } from './workingCalendar';
|
|
6
|
+
|
|
7
|
+
// Keyed by the calendar record, so edits (which create new records) naturally get a fresh instance.
|
|
8
|
+
const cache = new WeakMap<Calendar, Map<TimeZone, WorkingCalendar>>();
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The working calendar for a project: the calendar with `calendarId`, or the project calendar
|
|
12
|
+
* (`settings.calendarId`, falling back to the standard Mon–Fri 08:00–16:00 calendar), in the project's
|
|
13
|
+
* time zone. Instances are cached and cache their day computations. With `timeZone: 'local'`, the cached
|
|
14
|
+
* results assume the host's zone doesn't change while the app runs.
|
|
15
|
+
*/
|
|
16
|
+
export function getWorkingCalendar(
|
|
17
|
+
state: ProjectState,
|
|
18
|
+
calendarId: Id | null = state.settings.calendarId,
|
|
19
|
+
): WorkingCalendar {
|
|
20
|
+
const calendar = calendarId === null ? STANDARD_CALENDAR : state.calendars.byId.get(calendarId);
|
|
21
|
+
if (!calendar) throw new QuartzioError(`Calendar "${String(calendarId)}" does not exist.`);
|
|
22
|
+
|
|
23
|
+
const zone = state.settings.timeZone;
|
|
24
|
+
let byZone = cache.get(calendar);
|
|
25
|
+
if (!byZone) cache.set(calendar, (byZone = new Map<TimeZone, WorkingCalendar>()));
|
|
26
|
+
let working = byZone.get(zone);
|
|
27
|
+
if (!working) byZone.set(zone, (working = createWorkingCalendar(calendar, zone)));
|
|
28
|
+
return working;
|
|
29
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { WEEKDAYS } from '../data/normalize';
|
|
2
|
+
import type { Calendar, Id } from '../data/types';
|
|
3
|
+
import { weekdayFromDays } from '../util/civil';
|
|
4
|
+
import { QuartzioError } from '../util/errors';
|
|
5
|
+
import { parseCivilDate, parseTimeOfDay } from '../util/parse';
|
|
6
|
+
import { wallDay, wallDayTime, type TimeZone } from '../util/zone';
|
|
7
|
+
|
|
8
|
+
/** A working period as instants: `[start, end)`. */
|
|
9
|
+
export type Interval = readonly [start: number, end: number];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A calendar bound to a time zone, answering working-time questions in epoch milliseconds.
|
|
13
|
+
* Durations here are working milliseconds (see `durationToWorkingMs`).
|
|
14
|
+
*/
|
|
15
|
+
export interface WorkingCalendar {
|
|
16
|
+
readonly calendarId: Id;
|
|
17
|
+
readonly timeZone: TimeZone;
|
|
18
|
+
isWorking: (time: number) => boolean;
|
|
19
|
+
/** The earliest working instant at or after `time`. */
|
|
20
|
+
nextWorkingTime: (time: number) => number;
|
|
21
|
+
/** The latest instant at or before `time` that ends working time (working time lies just before it). */
|
|
22
|
+
previousWorkingTime: (time: number) => number;
|
|
23
|
+
/**
|
|
24
|
+
* Walks forward from `start` until `workingMs` of working time has passed and returns that instant.
|
|
25
|
+
* When the duration ends exactly at the end of a working period, that end is returned (end dates
|
|
26
|
+
* are exclusive). Zero returns `start` unchanged. Negative walks backwards.
|
|
27
|
+
*/
|
|
28
|
+
addWorkingTime: (start: number, workingMs: number) => number;
|
|
29
|
+
/** Walks backwards from `end`; the mirror of `addWorkingTime`. */
|
|
30
|
+
subtractWorkingTime: (end: number, workingMs: number) => number;
|
|
31
|
+
/** Working milliseconds in `[from, to)`. Negative when `to` is before `from`. */
|
|
32
|
+
workingTimeBetween: (from: number, to: number) => number;
|
|
33
|
+
/** Working intervals overlapping `[from, to)`, clipped to it. For drawing working/non-working time. */
|
|
34
|
+
workingIntervals: (from: number, to: number) => Interval[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** How far to search for working time before deciding the calendar has none (~10 years). */
|
|
38
|
+
const MAX_EMPTY_DAYS = 3660;
|
|
39
|
+
/**
|
|
40
|
+
* The longest span (~25 years) any calculation walks through day by day. Longer spans are almost always
|
|
41
|
+
* typos (a year like 2126 instead of 2026), and walking them would freeze the page, so they throw instead.
|
|
42
|
+
*/
|
|
43
|
+
export const MAX_SPAN_DAYS = 9150;
|
|
44
|
+
const MAX_CACHED_DAYS = 20_000;
|
|
45
|
+
|
|
46
|
+
type MinuteInterval = readonly [from: number, to: number];
|
|
47
|
+
|
|
48
|
+
const toMinutes = (intervals: Calendar['week']['monday']): MinuteInterval[] =>
|
|
49
|
+
intervals.map(({ start, end }) => [parseTimeOfDay(start) ?? 0, parseTimeOfDay(end) ?? 0] as const);
|
|
50
|
+
|
|
51
|
+
export function createWorkingCalendar(calendar: Calendar, zone: TimeZone): WorkingCalendar {
|
|
52
|
+
const week = WEEKDAYS.map((day) => toMinutes(calendar.week[day]));
|
|
53
|
+
const hasWeeklyWork = week.some((intervals) => intervals.length > 0);
|
|
54
|
+
|
|
55
|
+
// Kept as ranges (not expanded per day), so a long exception costs nothing extra. Later ones win.
|
|
56
|
+
const exceptions = calendar.exceptions.map((exception) => {
|
|
57
|
+
const first = parseCivilDate(exception.startDate) ?? 0;
|
|
58
|
+
return {
|
|
59
|
+
first,
|
|
60
|
+
last: parseCivilDate(exception.endDate) ?? first,
|
|
61
|
+
intervals: toMinutes(exception.intervals),
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
const exceptionOn = (day: number): MinuteInterval[] | undefined => {
|
|
65
|
+
for (let i = exceptions.length - 1; i >= 0; i--) {
|
|
66
|
+
const exception = exceptions[i];
|
|
67
|
+
if (exception && exception.first <= day && day <= exception.last) return exception.intervals;
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const cache = new Map<number, readonly Interval[]>();
|
|
73
|
+
|
|
74
|
+
const intervalsOnDay = (day: number): readonly Interval[] => {
|
|
75
|
+
let intervals = cache.get(day);
|
|
76
|
+
if (!intervals) {
|
|
77
|
+
const minutes = exceptionOn(day) ?? week[weekdayFromDays(day)] ?? [];
|
|
78
|
+
intervals = minutes
|
|
79
|
+
.map(([from, to]): Interval => [wallDayTime(day, from, zone), wallDayTime(day, to, zone)])
|
|
80
|
+
// A DST change can squeeze an interval to nothing (e.g. 02:00–03:00 on spring-forward day).
|
|
81
|
+
.filter(([start, end]) => end > start);
|
|
82
|
+
if (cache.size >= MAX_CACHED_DAYS) cache.clear();
|
|
83
|
+
cache.set(day, intervals);
|
|
84
|
+
}
|
|
85
|
+
return intervals;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const noWorkingTime = (): QuartzioError =>
|
|
89
|
+
new QuartzioError(
|
|
90
|
+
`Calendar "${String(calendar.id)}" has no working time within ${String(MAX_EMPTY_DAYS)} days. ` +
|
|
91
|
+
'Check its weekly schedule and exceptions.',
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
/** Calls `visit` for each working interval from `time` onward (or backward) until it returns true. */
|
|
95
|
+
const scan = (time: number, direction: 1 | -1, visit: (interval: Interval) => boolean): void => {
|
|
96
|
+
let day = wallDay(time, zone);
|
|
97
|
+
let emptyDays = 0;
|
|
98
|
+
for (let scanned = 0; ; scanned++) {
|
|
99
|
+
if (scanned > MAX_SPAN_DAYS) throw tooLong();
|
|
100
|
+
const intervals = intervalsOnDay(day);
|
|
101
|
+
if (intervals.length === 0) {
|
|
102
|
+
// Only exceptions can produce long runs of empty days when the week has working time.
|
|
103
|
+
if (++emptyDays > MAX_EMPTY_DAYS || (!hasWeeklyWork && exceptions.length === 0))
|
|
104
|
+
throw noWorkingTime();
|
|
105
|
+
} else {
|
|
106
|
+
emptyDays = 0;
|
|
107
|
+
const ordered = direction === 1 ? intervals : [...intervals].reverse();
|
|
108
|
+
for (const interval of ordered) if (visit(interval)) return;
|
|
109
|
+
}
|
|
110
|
+
day += direction;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const tooLong = (): QuartzioError =>
|
|
115
|
+
new QuartzioError(
|
|
116
|
+
`Working-time calculation spans more than ${String(MAX_SPAN_DAYS)} days (~25 years). Check the dates and durations.`,
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
const assertFinite = (...values: number[]): void => {
|
|
120
|
+
if (!values.every(Number.isFinite)) {
|
|
121
|
+
throw new QuartzioError('Working-time calculations need finite numbers (not NaN or Infinity).');
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const addWorkingTime = (start: number, workingMs: number): number => {
|
|
126
|
+
assertFinite(start, workingMs);
|
|
127
|
+
if (workingMs === 0) return start;
|
|
128
|
+
if (workingMs < 0) return subtractWorkingTime(start, -workingMs);
|
|
129
|
+
let remaining = workingMs;
|
|
130
|
+
let result = start;
|
|
131
|
+
scan(start, 1, ([intervalStart, intervalEnd]) => {
|
|
132
|
+
if (intervalEnd <= start) return false;
|
|
133
|
+
const from = Math.max(intervalStart, start);
|
|
134
|
+
if (intervalEnd - from >= remaining) {
|
|
135
|
+
result = from + remaining;
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
remaining -= intervalEnd - from;
|
|
139
|
+
return false;
|
|
140
|
+
});
|
|
141
|
+
return result;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const subtractWorkingTime = (end: number, workingMs: number): number => {
|
|
145
|
+
assertFinite(end, workingMs);
|
|
146
|
+
if (workingMs === 0) return end;
|
|
147
|
+
if (workingMs < 0) return addWorkingTime(end, -workingMs);
|
|
148
|
+
let remaining = workingMs;
|
|
149
|
+
let result = end;
|
|
150
|
+
scan(end, -1, ([intervalStart, intervalEnd]) => {
|
|
151
|
+
if (intervalStart >= end) return false;
|
|
152
|
+
const to = Math.min(intervalEnd, end);
|
|
153
|
+
if (to - intervalStart >= remaining) {
|
|
154
|
+
result = to - remaining;
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
remaining -= to - intervalStart;
|
|
158
|
+
return false;
|
|
159
|
+
});
|
|
160
|
+
return result;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const workingIntervals = (from: number, to: number): Interval[] => {
|
|
164
|
+
assertFinite(from, to);
|
|
165
|
+
if (wallDay(to, zone) - wallDay(from, zone) > MAX_SPAN_DAYS) throw tooLong();
|
|
166
|
+
const result: Interval[] = [];
|
|
167
|
+
for (let day = wallDay(from, zone), last = wallDay(to, zone); day <= last; day++) {
|
|
168
|
+
for (const [start, end] of intervalsOnDay(day)) {
|
|
169
|
+
const clippedStart = Math.max(start, from);
|
|
170
|
+
const clippedEnd = Math.min(end, to);
|
|
171
|
+
if (clippedEnd > clippedStart) result.push([clippedStart, clippedEnd]);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return result;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const workingTimeBetween = (from: number, to: number): number => {
|
|
178
|
+
if (to < from) return -workingTimeBetween(to, from);
|
|
179
|
+
return workingIntervals(from, to).reduce((total, [start, end]) => total + end - start, 0);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
calendarId: calendar.id,
|
|
184
|
+
timeZone: zone,
|
|
185
|
+
|
|
186
|
+
isWorking: (time) =>
|
|
187
|
+
Number.isFinite(time) &&
|
|
188
|
+
intervalsOnDay(wallDay(time, zone)).some(([start, end]) => start <= time && time < end),
|
|
189
|
+
|
|
190
|
+
nextWorkingTime(time) {
|
|
191
|
+
assertFinite(time);
|
|
192
|
+
let result = time;
|
|
193
|
+
scan(time, 1, ([start, end]) => {
|
|
194
|
+
if (end <= time) return false;
|
|
195
|
+
result = Math.max(start, time);
|
|
196
|
+
return true;
|
|
197
|
+
});
|
|
198
|
+
return result;
|
|
199
|
+
},
|
|
200
|
+
|
|
201
|
+
previousWorkingTime(time) {
|
|
202
|
+
assertFinite(time);
|
|
203
|
+
let result = time;
|
|
204
|
+
scan(time, -1, ([start, end]) => {
|
|
205
|
+
if (start >= time) return false;
|
|
206
|
+
result = Math.min(end, time);
|
|
207
|
+
return true;
|
|
208
|
+
});
|
|
209
|
+
return result;
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
addWorkingTime,
|
|
213
|
+
subtractWorkingTime,
|
|
214
|
+
|
|
215
|
+
workingTimeBetween,
|
|
216
|
+
workingIntervals,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { shareDependencyEnds } from './graph';
|
|
2
|
+
import { shareTreeIndex } from './tree';
|
|
3
|
+
import type { Id, ProjectSettings, ProjectState, StoreName, StoreRecords, Table } from './types';
|
|
4
|
+
|
|
5
|
+
export interface DraftTable<R extends { readonly id: Id }> {
|
|
6
|
+
byId: Map<Id, R>;
|
|
7
|
+
order: Id[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Mutable, copy-on-write view of a ProjectState. Tables are cloned on first write only, so
|
|
12
|
+
* untouched tables keep their identity in the finished state (cheap change detection downstream).
|
|
13
|
+
*/
|
|
14
|
+
export class Draft {
|
|
15
|
+
private readonly base: ProjectState;
|
|
16
|
+
private readonly writable = new Map<StoreName, DraftTable<{ readonly id: Id }>>();
|
|
17
|
+
private readonly version = new Map<StoreName, number>();
|
|
18
|
+
private readonly structureVersion = new Map<StoreName, number>();
|
|
19
|
+
private settings: ProjectSettings | undefined;
|
|
20
|
+
|
|
21
|
+
constructor(base: ProjectState) {
|
|
22
|
+
this.base = base;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
read<S extends StoreName>(store: S): Table<StoreRecords[S]> {
|
|
26
|
+
const table: Table<{ readonly id: Id }> = this.writable.get(store) ?? this.base[store];
|
|
27
|
+
return table as Table<StoreRecords[S]>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
write<S extends StoreName>(store: S): DraftTable<StoreRecords[S]> {
|
|
31
|
+
this.version.set(store, (this.version.get(store) ?? 0) + 1);
|
|
32
|
+
let table = this.writable.get(store);
|
|
33
|
+
if (!table) {
|
|
34
|
+
const source: Table<{ readonly id: Id }> = this.base[store];
|
|
35
|
+
table = { byId: new Map(source.byId), order: [...source.order] };
|
|
36
|
+
this.writable.set(store, table);
|
|
37
|
+
}
|
|
38
|
+
return table as DraftTable<StoreRecords[S]>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
readSettings(): ProjectSettings {
|
|
42
|
+
return this.settings ?? this.base.settings;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
writeSettings(settings: ProjectSettings): void {
|
|
46
|
+
this.settings = settings;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Increments on every write to the store; lets callers cache derived data per version. */
|
|
50
|
+
versionOf(store: StoreName): number {
|
|
51
|
+
return this.version.get(store) ?? 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Records a change to the store's structure: records added, removed or moved, or a task's parent. */
|
|
55
|
+
markStructure(store: StoreName): void {
|
|
56
|
+
this.structureVersion.set(store, (this.structureVersion.get(store) ?? 0) + 1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Increments on every structural change (see markStructure), e.g. to cache the task tree. */
|
|
60
|
+
structureVersionOf(store: StoreName): number {
|
|
61
|
+
return this.structureVersion.get(store) ?? 0;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
finish(): ProjectState {
|
|
65
|
+
if (this.writable.size === 0 && this.settings === undefined) return this.base;
|
|
66
|
+
const tasks = this.read('tasks');
|
|
67
|
+
if (this.structureVersionOf('tasks') === 0) shareTreeIndex(this.base.tasks, tasks);
|
|
68
|
+
const dependencies = this.read('dependencies');
|
|
69
|
+
if (this.structureVersionOf('dependencies') === 0)
|
|
70
|
+
shareDependencyEnds(this.base.dependencies, dependencies);
|
|
71
|
+
return {
|
|
72
|
+
settings: this.readSettings(),
|
|
73
|
+
calendars: this.read('calendars'),
|
|
74
|
+
tasks,
|
|
75
|
+
dependencies,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { QuartzioError } from '../util/errors';
|
|
2
|
+
import { getTreeIndex, type TreeIndex } from './tree';
|
|
3
|
+
import type { Dependency, Id, ProjectState, Table } from './types';
|
|
4
|
+
|
|
5
|
+
const NONE: readonly Dependency[] = [];
|
|
6
|
+
|
|
7
|
+
export interface DependencyIndex {
|
|
8
|
+
/** Dependencies where the task is the successor (`to`). */
|
|
9
|
+
incoming: (taskId: Id) => readonly Dependency[];
|
|
10
|
+
/** Dependencies where the task is the predecessor (`from`). */
|
|
11
|
+
outgoing: (taskId: Id) => readonly Dependency[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const dependencyCache = new WeakMap<Table<Dependency>, DependencyIndex>();
|
|
15
|
+
|
|
16
|
+
/** Dependencies per task, in table order. Built in O(n); cached per table. */
|
|
17
|
+
export function getDependencyIndex(dependencies: Table<Dependency>): DependencyIndex {
|
|
18
|
+
let index = dependencyCache.get(dependencies);
|
|
19
|
+
if (!index) {
|
|
20
|
+
const incoming = new Map<Id, Dependency[]>();
|
|
21
|
+
const outgoing = new Map<Id, Dependency[]>();
|
|
22
|
+
const add = (map: Map<Id, Dependency[]>, key: Id, dependency: Dependency) => {
|
|
23
|
+
const list = map.get(key);
|
|
24
|
+
if (list) list.push(dependency);
|
|
25
|
+
else map.set(key, [dependency]);
|
|
26
|
+
};
|
|
27
|
+
for (const id of dependencies.order) {
|
|
28
|
+
const dependency = dependencies.byId.get(id) as Dependency;
|
|
29
|
+
add(incoming, dependency.to, dependency);
|
|
30
|
+
add(outgoing, dependency.from, dependency);
|
|
31
|
+
}
|
|
32
|
+
index = {
|
|
33
|
+
incoming: (taskId) => incoming.get(taskId) ?? NONE,
|
|
34
|
+
outgoing: (taskId) => outgoing.get(taskId) ?? NONE,
|
|
35
|
+
};
|
|
36
|
+
dependencyCache.set(dependencies, index);
|
|
37
|
+
}
|
|
38
|
+
return index;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The order to schedule in. Every task has two nodes: `in` (its requirements) and `out` (its dates). Node
|
|
43
|
+
* `2i` is the `in` node and `2i + 1` the `out` node of task `ids[i]`. Edges:
|
|
44
|
+
* - `out(predecessor) → in(successor)` for each dependency;
|
|
45
|
+
* - `in(parent) → in(child)`: requirements on a parent apply to its children;
|
|
46
|
+
* - `out(child) → out(parent)`: a parent spans its children;
|
|
47
|
+
* - `in(task) → out(task)`.
|
|
48
|
+
* Splitting parents in two is what lets a parent both pass requirements down and roll dates up.
|
|
49
|
+
*/
|
|
50
|
+
export interface ScheduleGraph {
|
|
51
|
+
readonly ids: readonly Id[];
|
|
52
|
+
/** Node numbers in topological order. */
|
|
53
|
+
readonly order: Int32Array;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const graphCache = new WeakMap<TreeIndex, WeakMap<Table<Dependency>, ScheduleGraph>>();
|
|
57
|
+
// Dependency tables with the same ends (`from`/`to`, in the same order) as an earlier table, so the graph is
|
|
58
|
+
// shared when only other fields (lag, type) change. Points at the first table of such a run, never along a
|
|
59
|
+
// chain, so it keeps at most one old table alive.
|
|
60
|
+
const sameEnds = new WeakMap<Table<Dependency>, Table<Dependency>>();
|
|
61
|
+
|
|
62
|
+
/** Records that `next` has the same dependency ends as `previous`, so they can share a schedule graph. */
|
|
63
|
+
export function shareDependencyEnds(previous: Table<Dependency>, next: Table<Dependency>): void {
|
|
64
|
+
if (previous !== next) sameEnds.set(next, sameEnds.get(previous) ?? previous);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Whether two dependency tables have the same records in the same order with the same ends. */
|
|
68
|
+
export function sameDependencyEnds(table: Table<Dependency>, previous: Table<Dependency>): boolean {
|
|
69
|
+
if (previous.order.length !== table.order.length) return false;
|
|
70
|
+
for (let i = 0; i < table.order.length; i++) {
|
|
71
|
+
const id = table.order[i] as Id;
|
|
72
|
+
const a = table.byId.get(id);
|
|
73
|
+
const b = previous.byId.get(id);
|
|
74
|
+
if (previous.order[i] !== id || a?.from !== b?.from || a?.to !== b?.to) return false;
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Builds the scheduling order in O(n), cached per task structure and dependency table (so field edits reuse it).
|
|
81
|
+
* Throws QuartzioError when dependencies form a cycle, directly or through the hierarchy (e.g. a task that
|
|
82
|
+
* depends on its own parent).
|
|
83
|
+
*/
|
|
84
|
+
export function getScheduleGraph(state: ProjectState): ScheduleGraph {
|
|
85
|
+
const tree = getTreeIndex(state.tasks);
|
|
86
|
+
const dependencyKey = sameEnds.get(state.dependencies) ?? state.dependencies;
|
|
87
|
+
let byDependencies = graphCache.get(tree);
|
|
88
|
+
const cached = byDependencies?.get(dependencyKey);
|
|
89
|
+
if (cached) return cached;
|
|
90
|
+
const graph = buildScheduleGraph(state);
|
|
91
|
+
if (!byDependencies) {
|
|
92
|
+
byDependencies = new WeakMap();
|
|
93
|
+
graphCache.set(tree, byDependencies);
|
|
94
|
+
}
|
|
95
|
+
byDependencies.set(dependencyKey, graph);
|
|
96
|
+
return graph;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Builds the graph (uncached), optionally with one more dependency, e.g. to try it for cycles. */
|
|
100
|
+
function buildScheduleGraph(state: ProjectState, extra?: { from: Id; to: Id }): ScheduleGraph {
|
|
101
|
+
const ids = state.tasks.order;
|
|
102
|
+
const indexOf = new Map<Id, number>();
|
|
103
|
+
ids.forEach((id, i) => indexOf.set(id, i));
|
|
104
|
+
|
|
105
|
+
// Edges as linked lists in flat arrays: fast to build for 10 000s of tasks.
|
|
106
|
+
const nodeCount = ids.length * 2;
|
|
107
|
+
const head = new Int32Array(nodeCount).fill(-1);
|
|
108
|
+
const next: number[] = [];
|
|
109
|
+
const target: number[] = [];
|
|
110
|
+
const inDegree = new Int32Array(nodeCount);
|
|
111
|
+
const edge = (from: number, to: number) => {
|
|
112
|
+
target.push(to);
|
|
113
|
+
next.push(head[from] as number);
|
|
114
|
+
head[from] = target.length - 1;
|
|
115
|
+
inDegree[to] = (inDegree[to] as number) + 1;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
ids.forEach((id, i) => {
|
|
119
|
+
edge(2 * i, 2 * i + 1);
|
|
120
|
+
const parentId = state.tasks.byId.get(id)?.parentId ?? null;
|
|
121
|
+
const p = parentId === null ? undefined : indexOf.get(parentId);
|
|
122
|
+
if (p !== undefined) {
|
|
123
|
+
edge(2 * p, 2 * i);
|
|
124
|
+
edge(2 * i + 1, 2 * p + 1);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
const ends: Iterable<{ from: Id; to: Id }> = extra
|
|
128
|
+
? [...state.dependencies.byId.values(), extra]
|
|
129
|
+
: state.dependencies.byId.values();
|
|
130
|
+
for (const dependency of ends) {
|
|
131
|
+
const from = indexOf.get(dependency.from);
|
|
132
|
+
const to = indexOf.get(dependency.to);
|
|
133
|
+
if (from !== undefined && to !== undefined) edge(2 * from + 1, 2 * to);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Kahn's algorithm, iterative.
|
|
137
|
+
const order = new Int32Array(nodeCount);
|
|
138
|
+
let size = 0;
|
|
139
|
+
for (let node = 0; node < nodeCount; node++) if (inDegree[node] === 0) order[size++] = node;
|
|
140
|
+
for (let read = 0; read < size; read++) {
|
|
141
|
+
for (let e = head[order[read] as number] as number; e !== -1; e = next[e] as number) {
|
|
142
|
+
const to = target[e] as number;
|
|
143
|
+
inDegree[to] = (inDegree[to] as number) - 1;
|
|
144
|
+
if (inDegree[to] === 0) order[size++] = to;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (size < nodeCount) throw cycleError(ids, head, next, target, inDegree);
|
|
148
|
+
|
|
149
|
+
return { ids, order };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Names the tasks of one cycle. Nodes left over by Kahn's algorithm (in-degree > 0) all have a leftover
|
|
154
|
+
* predecessor, so walking predecessors from any of them must come back around.
|
|
155
|
+
*/
|
|
156
|
+
function cycleError(
|
|
157
|
+
ids: readonly Id[],
|
|
158
|
+
head: Int32Array,
|
|
159
|
+
next: readonly number[],
|
|
160
|
+
target: readonly number[],
|
|
161
|
+
inDegree: Int32Array,
|
|
162
|
+
): QuartzioError {
|
|
163
|
+
const predecessor = new Map<number, number>();
|
|
164
|
+
for (let from = 0; from < head.length; from++) {
|
|
165
|
+
if (inDegree[from] === 0) continue;
|
|
166
|
+
for (let e = head[from] as number; e !== -1; e = next[e] as number) {
|
|
167
|
+
const to = target[e] as number;
|
|
168
|
+
if ((inDegree[to] as number) > 0 && !predecessor.has(to)) predecessor.set(to, from);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
let node = predecessor.keys().next().value as number;
|
|
172
|
+
const seen = new Map<number, number>();
|
|
173
|
+
const path: number[] = [];
|
|
174
|
+
while (!seen.has(node)) {
|
|
175
|
+
seen.set(node, path.length);
|
|
176
|
+
path.push(node);
|
|
177
|
+
node = predecessor.get(node) as number;
|
|
178
|
+
}
|
|
179
|
+
const cycle = path.slice(seen.get(node)).reverse();
|
|
180
|
+
// Two nodes per task: name each task once, in order around the cycle.
|
|
181
|
+
const names: string[] = [];
|
|
182
|
+
for (const n of cycle) {
|
|
183
|
+
const name = `"${String(ids[n >> 1])}"`;
|
|
184
|
+
if (names[names.length - 1] !== name) names.push(name);
|
|
185
|
+
}
|
|
186
|
+
if (names.length > 1 && names[0] === names[names.length - 1]) names.pop();
|
|
187
|
+
names.push(names[0] as string);
|
|
188
|
+
return new QuartzioError(
|
|
189
|
+
`Dependencies form a cycle: ${names.join(' → ')}. (A task can't depend on its own parent or child, ` +
|
|
190
|
+
`and a task inherits the dependencies of its parents.)`,
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const cycleCache = new WeakMap<ProjectState, Map<string, boolean>>();
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Whether a dependency from `from` to `to` would form a cycle (also through the hierarchy). Tries it: builds the
|
|
198
|
+
* graph with it added, in O(n). Cached per state and pair, since a drag asks again on every pointer move.
|
|
199
|
+
*/
|
|
200
|
+
export function wouldCreateCycle(state: ProjectState, from: Id, to: Id): boolean {
|
|
201
|
+
let byPair = cycleCache.get(state);
|
|
202
|
+
if (!byPair) cycleCache.set(state, (byPair = new Map<string, boolean>()));
|
|
203
|
+
const key = `${typeof from}:${String(from)}→${typeof to}:${String(to)}`;
|
|
204
|
+
const known = byPair.get(key);
|
|
205
|
+
if (known !== undefined) return known;
|
|
206
|
+
let cycle = false;
|
|
207
|
+
try {
|
|
208
|
+
buildScheduleGraph(state, { from, to });
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (!(error instanceof QuartzioError)) throw error;
|
|
211
|
+
cycle = true;
|
|
212
|
+
}
|
|
213
|
+
byPair.set(key, cycle);
|
|
214
|
+
return cycle;
|
|
215
|
+
}
|