@quartzio/gantt 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/API.md +533 -0
  2. package/LICENSE +21 -0
  3. package/README.md +83 -2
  4. package/dist/index.d.ts +1341 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +6556 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/styles.css +1299 -0
  9. package/package.json +51 -3
  10. package/src/calendar/duration.ts +42 -0
  11. package/src/calendar/project.ts +29 -0
  12. package/src/calendar/workingCalendar.ts +218 -0
  13. package/src/data/draft.ts +78 -0
  14. package/src/data/graph.ts +215 -0
  15. package/src/data/normalize.ts +661 -0
  16. package/src/data/operations.ts +112 -0
  17. package/src/data/project.ts +194 -0
  18. package/src/data/serialize.ts +26 -0
  19. package/src/data/transaction.ts +460 -0
  20. package/src/data/tree.ts +156 -0
  21. package/src/data/types.ts +229 -0
  22. package/src/index.ts +139 -0
  23. package/src/scheduling/schedule.ts +310 -0
  24. package/src/styles.css +1299 -0
  25. package/src/timeaxis/align.ts +120 -0
  26. package/src/timeaxis/format.ts +72 -0
  27. package/src/timeaxis/presets.ts +219 -0
  28. package/src/timeaxis/timeAxis.ts +205 -0
  29. package/src/util/civil.ts +38 -0
  30. package/src/util/emitter.ts +53 -0
  31. package/src/util/equal.ts +23 -0
  32. package/src/util/errors.ts +4 -0
  33. package/src/util/parse.ts +70 -0
  34. package/src/util/time.ts +18 -0
  35. package/src/util/zone.ts +303 -0
  36. package/src/view/bars.ts +63 -0
  37. package/src/view/binding.ts +162 -0
  38. package/src/view/cellEditor.ts +239 -0
  39. package/src/view/cells.ts +89 -0
  40. package/src/view/columns.ts +197 -0
  41. package/src/view/createGantt.ts +1164 -0
  42. package/src/view/dates.ts +14 -0
  43. package/src/view/dependencies.ts +147 -0
  44. package/src/view/editing.ts +303 -0
  45. package/src/view/history.ts +72 -0
  46. package/src/view/interaction.ts +671 -0
  47. package/src/view/keyboard.ts +149 -0
  48. package/src/view/listWidth.ts +201 -0
  49. package/src/view/menu.ts +265 -0
  50. package/src/view/nonWorking.ts +113 -0
  51. package/src/view/range.ts +41 -0
  52. package/src/view/rows.ts +235 -0
  53. package/src/view/selection.ts +156 -0
  54. package/src/view/taskActions.ts +71 -0
  55. package/src/view/taskEditor.ts +553 -0
  56. package/src/view/timeline.ts +155 -0
  57. package/src/view/tooltip.ts +117 -0
  58. package/src/view/types.ts +328 -0
@@ -0,0 +1,229 @@
1
+ import type { TimeUnit } from '../util/time';
2
+ import type { TimeZone } from '../util/zone';
3
+
4
+ export type Id = string | number;
5
+
6
+ /**
7
+ * A task as stored by the engine. Every field is always present; `null` means "not set".
8
+ * Times are epoch milliseconds. End dates are exclusive.
9
+ */
10
+ export interface Task {
11
+ readonly id: Id;
12
+ readonly parentId: Id | null;
13
+ readonly name: string;
14
+ readonly startDate: number | null;
15
+ readonly endDate: number | null;
16
+ readonly duration: number | null;
17
+ readonly durationUnit: TimeUnit;
18
+ /** 0–100 */
19
+ readonly percentDone: number;
20
+ /**
21
+ * Uses its own dates: not moved by predecessors, and (for parents) not rolled up from its children. Still a
22
+ * predecessor for others. Otherwise the task is scheduled automatically, as soon as possible.
23
+ */
24
+ readonly manuallyScheduled: boolean;
25
+ /** Set together with `constraintDate` (both or neither). Ignored for manually scheduled tasks. */
26
+ readonly constraintType: ConstraintType | null;
27
+ readonly constraintDate: number | null;
28
+ }
29
+
30
+ /**
31
+ * A scheduling constraint on a task. For now only "start no earlier than" (set when an automatically scheduled
32
+ * task is dragged); the other types come with milestone 8.
33
+ */
34
+ export type ConstraintType = 'startnoearlierthan';
35
+
36
+ /** Finish-to-start, start-to-start, finish-to-finish, start-to-finish. */
37
+ export type DependencyType = 'FS' | 'SS' | 'FF' | 'SF';
38
+
39
+ export interface Dependency {
40
+ readonly id: Id;
41
+ /** The predecessor task. */
42
+ readonly from: Id;
43
+ /** The successor task. */
44
+ readonly to: Id;
45
+ readonly type: DependencyType;
46
+ readonly lag: number;
47
+ readonly lagUnit: TimeUnit;
48
+ }
49
+
50
+ export type Weekday = 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday';
51
+
52
+ /** Working time within a day, as wall-clock times "HH:mm". `end` is exclusive and may be "24:00". */
53
+ export interface WorkingInterval {
54
+ readonly start: string;
55
+ readonly end: string;
56
+ }
57
+
58
+ /** Overrides the weekly schedule for a range of dates (holidays, vacations, extra working days). */
59
+ export interface CalendarException {
60
+ /** "YYYY-MM-DD", a date in the project's time zone. */
61
+ readonly startDate: string;
62
+ /** "YYYY-MM-DD", inclusive. */
63
+ readonly endDate: string;
64
+ readonly name: string;
65
+ /** Working time on these dates. Empty means non-working. */
66
+ readonly intervals: readonly WorkingInterval[];
67
+ }
68
+
69
+ export interface Calendar {
70
+ readonly id: Id;
71
+ readonly name: string;
72
+ readonly week: Readonly<Record<Weekday, readonly WorkingInterval[]>>;
73
+ /** Later exceptions win where they overlap earlier ones. */
74
+ readonly exceptions: readonly CalendarException[];
75
+ }
76
+
77
+ export interface ProjectSettings {
78
+ /** Time zone for wall-clock logic (working hours, midnight, date strings). */
79
+ readonly timeZone: TimeZone;
80
+ /** The project calendar; `null` uses the built-in standard calendar (Mon–Fri 08:00–16:00). */
81
+ readonly calendarId: Id | null;
82
+ /** Conversion factors for durations in working time. */
83
+ readonly hoursPerDay: number;
84
+ readonly daysPerWeek: number;
85
+ readonly daysPerMonth: number;
86
+ /** 0 = Sunday … 6 = Saturday. */
87
+ readonly weekStartsOn: number;
88
+ /**
89
+ * Project start: automatically scheduled tasks start here at the earliest. When `null`, it's set to the
90
+ * earliest task start the first time the project is scheduled.
91
+ */
92
+ readonly startDate: number | null;
93
+ }
94
+
95
+ // --- Input: what users may pass in. Looser than the stored records. ---
96
+
97
+ /**
98
+ * A Date, epoch milliseconds, or an ISO 8601 string. Strings without an offset ("2026-10-05",
99
+ * "2026-10-05T08:00") are wall-clock times in the project's time zone.
100
+ */
101
+ export type DateInput = Date | number | string;
102
+
103
+ export interface TaskInput {
104
+ id: Id;
105
+ name?: string;
106
+ /** Ignored for tasks nested in `children`, where the parent is implied. */
107
+ parentId?: Id | null;
108
+ children?: readonly TaskInput[];
109
+ startDate?: DateInput | null;
110
+ endDate?: DateInput | null;
111
+ duration?: number | null;
112
+ durationUnit?: TimeUnit;
113
+ percentDone?: number;
114
+ manuallyScheduled?: boolean;
115
+ constraintType?: ConstraintType | null;
116
+ constraintDate?: DateInput | null;
117
+ }
118
+
119
+ export interface DependencyInput {
120
+ id: Id;
121
+ from: Id;
122
+ to: Id;
123
+ type?: DependencyType;
124
+ lag?: number;
125
+ lagUnit?: TimeUnit;
126
+ }
127
+
128
+ export interface CalendarExceptionInput {
129
+ startDate: string;
130
+ /** Defaults to `startDate`. */
131
+ endDate?: string;
132
+ name?: string;
133
+ /** Defaults to none (a non-working day). */
134
+ intervals?: readonly WorkingInterval[];
135
+ }
136
+
137
+ export interface CalendarInput {
138
+ id: Id;
139
+ name?: string;
140
+ /** Days left out are non-working. Omit entirely for Mon–Fri 08:00–16:00. */
141
+ week?: Partial<Record<Weekday, readonly WorkingInterval[]>>;
142
+ exceptions?: readonly CalendarExceptionInput[];
143
+ }
144
+
145
+ export type ProjectSettingsInput = {
146
+ -readonly [K in Exclude<keyof ProjectSettings, 'startDate'>]?: ProjectSettings[K];
147
+ } & {
148
+ /** Read in the project's time zone (the one in the same input, if given). */
149
+ startDate?: DateInput | null;
150
+ };
151
+
152
+ /** Tasks may be a flat list with `parentId`, nested via `children`, or a mix. */
153
+ export interface ProjectInput {
154
+ settings?: ProjectSettingsInput;
155
+ calendars?: readonly CalendarInput[];
156
+ tasks?: readonly TaskInput[];
157
+ dependencies?: readonly DependencyInput[];
158
+ }
159
+
160
+ /**
161
+ * The canonical, JSON-serializable form of a project: flat, fully normalized records.
162
+ * It is also valid `ProjectInput`, so it can be loaded back as-is.
163
+ */
164
+ export interface ProjectData {
165
+ readonly settings: ProjectSettings;
166
+ readonly calendars: readonly Calendar[];
167
+ readonly tasks: readonly Task[];
168
+ readonly dependencies: readonly Dependency[];
169
+ }
170
+
171
+ // --- State ---
172
+
173
+ export interface Table<R extends { readonly id: Id }> {
174
+ readonly byId: ReadonlyMap<Id, R>;
175
+ /**
176
+ * Record order. For tasks, the order of siblings under a parent is their relative order here;
177
+ * the full list is not guaranteed to be depth-first.
178
+ */
179
+ readonly order: readonly Id[];
180
+ }
181
+
182
+ /** Immutable snapshot of a project. A new object is created on every change. */
183
+ export interface ProjectState {
184
+ readonly settings: ProjectSettings;
185
+ readonly calendars: Table<Calendar>;
186
+ readonly tasks: Table<Task>;
187
+ readonly dependencies: Table<Dependency>;
188
+ }
189
+
190
+ export interface StoreRecords {
191
+ calendars: Calendar;
192
+ tasks: Task;
193
+ dependencies: Dependency;
194
+ }
195
+
196
+ export type StoreName = keyof StoreRecords;
197
+
198
+ // --- Operations & patches ---
199
+
200
+ type OperationFor<S extends StoreName> =
201
+ | { readonly type: 'add'; readonly store: S; readonly record: StoreRecords[S]; readonly index: number }
202
+ | { readonly type: 'remove'; readonly store: S; readonly id: Id }
203
+ | {
204
+ readonly type: 'update';
205
+ readonly store: S;
206
+ readonly id: Id;
207
+ readonly changes: Partial<Omit<StoreRecords[S], 'id'>>;
208
+ }
209
+ | {
210
+ readonly type: 'move';
211
+ readonly store: S;
212
+ readonly id: Id;
213
+ /** Target position in `order`, counted after the record has been taken out. */
214
+ readonly index: number;
215
+ };
216
+
217
+ export interface SettingsOperation {
218
+ readonly type: 'settings';
219
+ readonly changes: Partial<ProjectSettings>;
220
+ }
221
+
222
+ /** One low-level, JSON-serializable change to one record or to the project settings. */
223
+ export type Operation = { [S in StoreName]: OperationFor<S> }[StoreName] | SettingsOperation;
224
+
225
+ /** The result of one transaction. Applying `inverse` after `operations` restores the previous state. */
226
+ export interface Patch {
227
+ readonly operations: readonly Operation[];
228
+ readonly inverse: readonly Operation[];
229
+ }
package/src/index.ts ADDED
@@ -0,0 +1,139 @@
1
+ // Calendar
2
+ export type { DurationSettings } from './calendar/duration';
3
+ export { durationToWorkingMs, workingMsPerUnit, workingMsToDuration } from './calendar/duration';
4
+ export { getWorkingCalendar } from './calendar/project';
5
+ export type { Interval, WorkingCalendar } from './calendar/workingCalendar';
6
+
7
+ // Data
8
+ export { DEFAULT_SETTINGS, STANDARD_CALENDAR } from './data/normalize';
9
+ export type { PlannedChange, Project, ProjectChange, ProjectOptions } from './data/project';
10
+ export { createProject } from './data/project';
11
+ export { applyPatch, toProjectData } from './data/serialize';
12
+ export type {
13
+ CalendarAddInput,
14
+ CalendarTransaction,
15
+ CalendarUpdateInput,
16
+ DependencyAddInput,
17
+ DependencyTransaction,
18
+ DependencyUpdateInput,
19
+ IdGenerator,
20
+ SettingsTransaction,
21
+ TaskAddInput,
22
+ TaskPosition,
23
+ TaskTransaction,
24
+ TaskUpdateInput,
25
+ Transaction,
26
+ } from './data/transaction';
27
+ export type { TreeIndex } from './data/tree';
28
+ export { getTreeIndex } from './data/tree';
29
+ export type {
30
+ Calendar,
31
+ ConstraintType,
32
+ CalendarException,
33
+ CalendarExceptionInput,
34
+ CalendarInput,
35
+ DateInput,
36
+ Dependency,
37
+ DependencyInput,
38
+ DependencyType,
39
+ Id,
40
+ Operation,
41
+ Patch,
42
+ ProjectData,
43
+ ProjectInput,
44
+ ProjectSettings,
45
+ ProjectSettingsInput,
46
+ ProjectState,
47
+ SettingsOperation,
48
+ StoreName,
49
+ Table,
50
+ Task,
51
+ TaskInput,
52
+ Weekday,
53
+ WorkingInterval,
54
+ } from './data/types';
55
+
56
+ // Time axis
57
+ export type {
58
+ HeaderCellContext,
59
+ HeaderFormat,
60
+ HeaderFormatName,
61
+ HeaderRow,
62
+ ViewPreset,
63
+ } from './timeaxis/presets';
64
+ export { DEFAULT_PRESET_ID, resolvePreset, VIEW_PRESETS } from './timeaxis/presets';
65
+ export type { HeaderCell, Tick, TimeAxis, TimeAxisOptions } from './timeaxis/timeAxis';
66
+ export { createTimeAxis } from './timeaxis/timeAxis';
67
+
68
+ // Utilities
69
+ export { QuartzioError } from './util/errors';
70
+ export { parseDateString } from './util/parse';
71
+ export type { TimeUnit } from './util/time';
72
+ export type { TimeZone, WallTime, ZonedWallTime } from './util/zone';
73
+ export { addUnits, fromWallTime, isoWeek, isValidTimeZone, startOfUnit, toWallTime } from './util/zone';
74
+
75
+ // Scheduling
76
+ export { scheduleProject } from './scheduling/schedule';
77
+ export type { TaskDates } from './view/dates';
78
+ export { taskDates } from './view/dates';
79
+
80
+ // View
81
+ export type { Bar, BarKind } from './view/bars';
82
+ export type { DependencyLine } from './view/dependencies';
83
+ export type {
84
+ BarInteraction,
85
+ HitArea,
86
+ LinkInteraction,
87
+ ProposedChange,
88
+ TaskInteraction,
89
+ TimelineHit,
90
+ TimelinePoint,
91
+ } from './view/interaction';
92
+ export type { TimeSpan } from './view/nonWorking';
93
+ export type {
94
+ BuiltInColumnId,
95
+ CellContext,
96
+ Column,
97
+ ColumnDefinition,
98
+ ColumnInput,
99
+ ColumnsState,
100
+ } from './view/columns';
101
+ export { DEFAULT_COLUMNS } from './view/columns';
102
+ export { createGantt } from './view/createGantt';
103
+ export type { CellEdit, EditKind } from './view/editing';
104
+ export type { HistoryState } from './view/history';
105
+ export type {
106
+ MenuContext,
107
+ MenuCustomizer,
108
+ MenuItem,
109
+ MenuState,
110
+ MenuTarget,
111
+ TaskMenuItemId,
112
+ } from './view/menu';
113
+ export type {
114
+ TaskEditorAction,
115
+ TaskEditorConstraint,
116
+ TaskEditorDependency,
117
+ TaskEditorField,
118
+ TaskEditorFieldState,
119
+ TaskEditorSide,
120
+ TaskEditorState,
121
+ TaskEditorTab,
122
+ } from './view/taskEditor';
123
+ export type { TaskTooltip } from './view/tooltip';
124
+ export type { KeyInput } from './view/keyboard';
125
+ export type { ListPaneState, ListResizeAction } from './view/listWidth';
126
+ export type { Row, RowsState } from './view/rows';
127
+ export type { KeyModifiers } from './view/selection';
128
+ export type {
129
+ GanttChangeSource,
130
+ GanttController,
131
+ GanttDataChange,
132
+ GanttOptions,
133
+ HeaderState,
134
+ Interactions,
135
+ ScrollRequest,
136
+ TodayLine,
137
+ Viewport,
138
+ ViewState,
139
+ } from './view/types';
@@ -0,0 +1,310 @@
1
+ import { workingMsPerUnit } from '../calendar/duration';
2
+ import { getWorkingCalendar } from '../calendar/project';
3
+ import type { WorkingCalendar } from '../calendar/workingCalendar';
4
+ import { getDependencyIndex, getScheduleGraph } from '../data/graph';
5
+ import { getTreeIndex } from '../data/tree';
6
+ import type { Dependency, Id, Operation, ProjectState, Task } from '../data/types';
7
+ import { QuartzioError } from '../util/errors';
8
+
9
+ const NO_BOUND = Number.NEGATIVE_INFINITY;
10
+
11
+ /**
12
+ * Schedules the project and returns the operations that write the results back: for automatically scheduled
13
+ * tasks, dates as soon as possible after the project start and their predecessors' requirements; for parents,
14
+ * the span of their children; start, end and duration kept consistent everywhere.
15
+ *
16
+ * `operations` are the ones just applied (to tell a new end from a new duration), or `null` for loaded data.
17
+ * Pure, idempotent (nothing to add to a state it scheduled), and doesn't throw for calendar trouble: a task
18
+ * whose dates can't be computed (e.g. no working time at all) keeps its dates.
19
+ */
20
+ export function scheduleProject(state: ProjectState, operations: readonly Operation[] | null): Operation[] {
21
+ const { settings } = state;
22
+ if (settings.startDate !== null) return run(state, operations, settings.startDate).operations;
23
+
24
+ // No project start yet: the earliest task start. Without any, only manual tasks can get a start (e.g. from
25
+ // an end and a duration), so schedule once to find the earliest, then again from there. Written back, so it
26
+ // doesn't move when the earliest task does.
27
+ let projectStart: number | null = null;
28
+ for (const t of state.tasks.byId.values()) {
29
+ if (t.startDate !== null && (projectStart === null || t.startDate < projectStart))
30
+ projectStart = t.startDate;
31
+ }
32
+ let result = run(state, operations, projectStart);
33
+ if (projectStart === null && result.earliest !== null) {
34
+ projectStart = result.earliest;
35
+ result = run(state, operations, projectStart);
36
+ }
37
+ return projectStart === null
38
+ ? result.operations
39
+ : [{ type: 'settings', changes: { startDate: projectStart } }, ...result.operations];
40
+ }
41
+
42
+ function run(
43
+ state: ProjectState,
44
+ operations: readonly Operation[] | null,
45
+ projectStart: number | null,
46
+ ): { operations: Operation[]; earliest: number | null } {
47
+ const result: Operation[] = [];
48
+ const { settings } = state;
49
+ const calendar = getWorkingCalendar(state);
50
+ const graph = getScheduleGraph(state);
51
+ const tree = getTreeIndex(state.tasks);
52
+ const dependencies = getDependencyIndex(state.dependencies);
53
+ const ids = graph.ids;
54
+ const count = ids.length;
55
+ const indexOf = new Map<Id, number>();
56
+ ids.forEach((id, i) => indexOf.set(id, i));
57
+
58
+ // Which task fields each operation changed: a new end (without a new duration) keeps the end.
59
+ const changed = new Map<Id, Set<string>>();
60
+ for (const op of operations ?? []) {
61
+ if (op.type === 'update' && op.store === 'tasks') {
62
+ let fields = changed.get(op.id);
63
+ if (!fields) changed.set(op.id, (fields = new Set()));
64
+ for (const key of Object.keys(op.changes)) fields.add(key);
65
+ }
66
+ }
67
+
68
+ // Rounded one way only, so a derived duration converts back to exactly the same working time.
69
+ const toMs = (value: number, unit: Task['durationUnit']) =>
70
+ Math.round(value * workingMsPerUnit(unit, settings));
71
+ const fromMs = (ms: number, unit: Task['durationUnit']) => ms / workingMsPerUnit(unit, settings);
72
+ const context: Context = { calendar, toMs, fromMs };
73
+ const shift = (time: number, lag: number, unit: Task['durationUnit']) => {
74
+ const ms = toMs(lag, unit);
75
+ return ms === 0 ? time : calendar.addWorkingTime(time, ms); // negative: subtracts
76
+ };
77
+
78
+ // Per task: its requirements (from the `in` node) and its dates (from the `out` node). NaN = unscheduled.
79
+ const boundStart = new Float64Array(count).fill(NO_BOUND);
80
+ const boundEnd = new Float64Array(count).fill(NO_BOUND);
81
+ const starts = new Float64Array(count).fill(Number.NaN);
82
+ const ends = new Float64Array(count).fill(Number.NaN);
83
+ const durations = new Float64Array(count); // working ms, for weighting parents' progress
84
+ const percents = new Float64Array(count);
85
+
86
+ const requirements = (i: number, task: Task): void => {
87
+ let start = NO_BOUND;
88
+ let end = NO_BOUND;
89
+ const parent = task.parentId === null ? undefined : indexOf.get(task.parentId);
90
+ if (parent !== undefined) {
91
+ start = boundStart[parent] as number;
92
+ end = boundEnd[parent] as number;
93
+ }
94
+ // A manually scheduled task isn't pushed itself, but passes its parents' requirements on to its children.
95
+ if (!task.manuallyScheduled) {
96
+ // "Start no earlier than": like a requirement from a predecessor (and passed on to children the same way).
97
+ if (task.constraintType === 'startnoearlierthan' && task.constraintDate !== null) {
98
+ start = Math.max(start, task.constraintDate);
99
+ }
100
+ for (const dependency of dependencies.incoming(task.id)) {
101
+ const from = indexOf.get(dependency.from);
102
+ if (from === undefined || Number.isNaN(starts[from])) continue;
103
+ let required: number;
104
+ try {
105
+ required = requirement(dependency, starts[from] as number, ends[from] as number, shift);
106
+ } catch (error) {
107
+ if (!(error instanceof QuartzioError)) throw error;
108
+ continue; // e.g. a lag beyond what the calendar will calculate: skip this requirement
109
+ }
110
+ if (dependency.type === 'FS' || dependency.type === 'SS') start = Math.max(start, required);
111
+ else end = Math.max(end, required);
112
+ }
113
+ }
114
+ boundStart[i] = start;
115
+ boundEnd[i] = end;
116
+ };
117
+ let earliest: number | null = null;
118
+
119
+ for (const node of graph.order) {
120
+ const i = node >> 1;
121
+ const id = ids[i] as Id;
122
+ const task = state.tasks.byId.get(id) as Task;
123
+ if ((node & 1) === 0) {
124
+ requirements(i, task);
125
+ continue;
126
+ }
127
+
128
+ let dates: Computed | null;
129
+ try {
130
+ dates = task.manuallyScheduled
131
+ ? ownDates(task, context, changed.get(id))
132
+ : (rollUp(tree.children(id), indexOf, { starts, ends, durations, percents }, task, context) ??
133
+ asSoonAsPossible(
134
+ task,
135
+ projectStart,
136
+ boundStart[i] as number,
137
+ boundEnd[i] as number,
138
+ context,
139
+ changed.get(id),
140
+ ));
141
+ } catch (error) {
142
+ if (!(error instanceof QuartzioError)) throw error;
143
+ dates = null; // e.g. no working time in the calendar: keep what the task has
144
+ }
145
+
146
+ const start = dates?.start ?? task.startDate;
147
+ const end = dates?.end ?? task.endDate;
148
+ if (start !== null && end !== null) {
149
+ if (earliest === null || start < earliest) earliest = start;
150
+ starts[i] = start;
151
+ ends[i] = end;
152
+ durations[i] =
153
+ dates?.workingMs ?? (task.duration === null ? 0 : toMs(task.duration, task.durationUnit));
154
+ }
155
+ percents[i] = dates?.percentDone ?? task.percentDone;
156
+ if (dates) {
157
+ const changes = differences(task, dates);
158
+ if (changes) result.push({ type: 'update', store: 'tasks', id, changes });
159
+ }
160
+ }
161
+ return { operations: result, earliest };
162
+ }
163
+
164
+ interface Context {
165
+ calendar: WorkingCalendar;
166
+ toMs: (value: number, unit: Task['durationUnit']) => number;
167
+ fromMs: (ms: number, unit: Task['durationUnit']) => number;
168
+ }
169
+
170
+ interface Computed {
171
+ start: number;
172
+ end: number;
173
+ /** Only when it has to change (derived); otherwise the task's own duration stands. */
174
+ duration?: number;
175
+ workingMs: number;
176
+ percentDone?: number;
177
+ }
178
+
179
+ function requirement(
180
+ dependency: Dependency,
181
+ start: number,
182
+ end: number,
183
+ shift: (time: number, lag: number, unit: Dependency['lagUnit']) => number,
184
+ ): number {
185
+ const from = dependency.type === 'FS' || dependency.type === 'FF' ? end : start;
186
+ return shift(from, dependency.lag, dependency.lagUnit);
187
+ }
188
+
189
+ /** The duration to schedule with, in working ms, and whether it's derived (and has to be written). */
190
+ function workingDuration(
191
+ task: Task,
192
+ { calendar, toMs }: Context,
193
+ changed: Set<string> | undefined,
194
+ ): { ms: number; derived: boolean } {
195
+ const { startDate, endDate, duration } = task;
196
+ const newEnd = changed?.has('endDate') === true && !changed.has('duration') && !changed.has('durationUnit');
197
+ // (An end before the start comes from a new start on its own: the duration stands, and the end moves.)
198
+ if (startDate !== null && endDate !== null && endDate >= startDate && (newEnd || duration === null)) {
199
+ const ms = calendar.workingTimeBetween(startDate, endDate);
200
+ // A replayed patch (redo, undo, controlled data coming back) repeats the scheduler's own new ends: when the
201
+ // duration already amounts to that, it stands instead of being derived again (which could drift).
202
+ if (duration !== null && toMs(duration, task.durationUnit) === ms) return { ms, derived: false };
203
+ return { ms, derived: true };
204
+ }
205
+ if (duration !== null) return { ms: toMs(duration, task.durationUnit), derived: false };
206
+ return { ms: 0, derived: true };
207
+ }
208
+
209
+ /** No dates and no duration: left out of scheduling (no bar), like Bryntum's unscheduled tasks. */
210
+ const isUnscheduled = (task: Task) =>
211
+ task.startDate === null && task.endDate === null && task.duration === null;
212
+
213
+ function asSoonAsPossible(
214
+ task: Task,
215
+ projectStart: number | null,
216
+ startBound: number,
217
+ endBound: number,
218
+ context: Context,
219
+ changed: Set<string> | undefined,
220
+ ): Computed | null {
221
+ if (isUnscheduled(task)) return null;
222
+ const { calendar } = context;
223
+ const { ms, derived } = workingDuration(task, context, changed);
224
+ let earliest = Math.max(projectStart ?? NO_BOUND, startBound);
225
+ if (endBound !== NO_BOUND) earliest = Math.max(earliest, calendar.addWorkingTime(endBound, -ms));
226
+ if (earliest === NO_BOUND) return null; // no project start and no requirements: unscheduled
227
+ // Zero-length tasks (milestones) stay where they are required; others start at working time.
228
+ const start = ms > 0 ? calendar.nextWorkingTime(earliest) : earliest;
229
+ return computed(task, start, calendar.addWorkingTime(start, ms), ms, derived, context);
230
+ }
231
+
232
+ function ownDates(task: Task, context: Context, changed: Set<string> | undefined): Computed | null {
233
+ const { calendar } = context;
234
+ const { ms, derived } = workingDuration(task, context, changed);
235
+ if (task.startDate !== null) {
236
+ return computed(task, task.startDate, calendar.addWorkingTime(task.startDate, ms), ms, derived, context);
237
+ }
238
+ if (task.endDate !== null) {
239
+ return computed(task, calendar.addWorkingTime(task.endDate, -ms), task.endDate, ms, derived, context);
240
+ }
241
+ return null;
242
+ }
243
+
244
+ /** A parent spans its scheduled children; `null` when none are scheduled (it's then scheduled like a task). */
245
+ function rollUp(
246
+ children: readonly Id[],
247
+ indexOf: ReadonlyMap<Id, number>,
248
+ { starts, ends, durations, percents }: Record<'starts' | 'ends' | 'durations' | 'percents', Float64Array>,
249
+ task: Task,
250
+ { calendar, fromMs }: Context,
251
+ ): Computed | null {
252
+ let start = Number.POSITIVE_INFINITY;
253
+ let end = Number.NEGATIVE_INFINITY;
254
+ let weight = 0;
255
+ let weighted = 0;
256
+ let sum = 0;
257
+ for (const child of children) {
258
+ const c = indexOf.get(child) as number;
259
+ sum += percents[c] as number;
260
+ if (Number.isNaN(starts[c])) continue;
261
+ start = Math.min(start, starts[c] as number);
262
+ end = Math.max(end, ends[c] as number);
263
+ weight += durations[c] as number;
264
+ weighted += (durations[c] as number) * (percents[c] as number);
265
+ }
266
+ if (start === Number.POSITIVE_INFINITY) return null;
267
+ const ms = calendar.workingTimeBetween(start, end);
268
+ return {
269
+ start,
270
+ end,
271
+ duration: fromMs(ms, task.durationUnit),
272
+ workingMs: ms,
273
+ percentDone: weight > 0 ? weighted / weight : sum / children.length,
274
+ };
275
+ }
276
+
277
+ function computed(
278
+ task: Task,
279
+ start: number,
280
+ computedEnd: number,
281
+ ms: number,
282
+ derived: boolean,
283
+ context: Context,
284
+ ): Computed {
285
+ // Keep the task's own end when it amounts to the same working time (e.g. midnight instead of 16:00 the day
286
+ // before): the dates as given stay, and scheduling again changes nothing.
287
+ const own = task.endDate;
288
+ const keepOwn =
289
+ own !== null &&
290
+ own !== computedEnd &&
291
+ task.startDate === start &&
292
+ own >= start &&
293
+ context.calendar.workingTimeBetween(start, own) === ms;
294
+ const end = keepOwn ? own : computedEnd;
295
+ return derived
296
+ ? { start, end, workingMs: ms, duration: context.fromMs(ms, task.durationUnit) }
297
+ : { start, end, workingMs: ms };
298
+ }
299
+
300
+ /** The fields that differ from the task, or `null`. */
301
+ function differences(task: Task, dates: Computed): Partial<Task> | null {
302
+ const changes: { -readonly [K in keyof Task]?: Task[K] } = {};
303
+ if (task.startDate !== dates.start) changes.startDate = dates.start;
304
+ if (task.endDate !== dates.end) changes.endDate = dates.end;
305
+ if (dates.duration !== undefined && task.duration !== dates.duration) changes.duration = dates.duration;
306
+ if (dates.percentDone !== undefined && task.percentDone !== dates.percentDone) {
307
+ changes.percentDone = dates.percentDone;
308
+ }
309
+ return Object.keys(changes).length > 0 ? changes : null;
310
+ }