@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,113 @@
1
+ import { getWorkingCalendar } from '../calendar/project';
2
+ import type { WorkingCalendar } from '../calendar/workingCalendar';
3
+ import type { ProjectState } from '../data/types';
4
+ import type { TimeAxis } from '../timeaxis/timeAxis';
5
+ import { QuartzioError } from '../util/errors';
6
+ import { addUnits, startOfUnit } from '../util/zone';
7
+ import { UNMEASURED_WIDTH } from './timeline';
8
+ import type { Viewport } from './types';
9
+
10
+ /** A time range drawn on the timeline, in timeline coordinates. */
11
+ export interface TimeSpan {
12
+ /** Stable key for rendering lists. */
13
+ readonly key: string;
14
+ readonly start: number;
15
+ readonly end: number;
16
+ readonly x: number;
17
+ readonly width: number;
18
+ }
19
+
20
+ const EMPTY: readonly TimeSpan[] = [];
21
+ const SUB_DAY_TICKS = new Set(['millisecond', 'second', 'minute', 'hour']);
22
+
23
+ /**
24
+ * Non-working time to shade, around the visible part of the timeline. What is shown depends on the tick size,
25
+ * so the shading stays readable: with ticks under a day, every non-working interval (nights, weekends); with
26
+ * day ticks, only whole days without working time (weekends, holidays) — shading nights would cover most of
27
+ * every day; with longer ticks, nothing.
28
+ */
29
+ export function createNonWorkingView(): {
30
+ spansFor: (
31
+ project: ProjectState,
32
+ axis: TimeAxis,
33
+ viewport: Viewport,
34
+ enabled: boolean,
35
+ ) => readonly TimeSpan[];
36
+ } {
37
+ let cache: { key: unknown[]; from: number; to: number; spans: readonly TimeSpan[] } | undefined;
38
+
39
+ const compute = (calendar: WorkingCalendar, axis: TimeAxis, from: number, to: number): TimeSpan[] => {
40
+ const zone = axis.timeZone;
41
+ const ranges: [number, number][] = [];
42
+ const push = (start: number, end: number) => {
43
+ const last = ranges[ranges.length - 1];
44
+ if (last && last[1] >= start) last[1] = Math.max(last[1], end);
45
+ else if (end > start) ranges.push([start, end]);
46
+ };
47
+
48
+ if (SUB_DAY_TICKS.has(axis.preset.tickUnit)) {
49
+ let cursor = from;
50
+ for (const [start, end] of calendar.workingIntervals(from, to)) {
51
+ push(cursor, start);
52
+ cursor = end;
53
+ }
54
+ push(cursor, to);
55
+ } else {
56
+ for (let day = startOfUnit(from, 'day', zone); day < to;) {
57
+ // Re-align: after a day that starts late (a DST gap at midnight), adding a day keeps the late start.
58
+ const next = startOfUnit(addUnits(day, 1, 'day', zone), 'day', zone);
59
+ if (calendar.workingIntervals(day, next).length === 0) push(day, next);
60
+ day = next;
61
+ }
62
+ }
63
+
64
+ return ranges.map(([start, end]) => {
65
+ const x = axis.dateToX(start);
66
+ return { key: String(start), start, end, x, width: axis.dateToX(end) - x };
67
+ });
68
+ };
69
+
70
+ const spansFor = (project: ProjectState, axis: TimeAxis, viewport: Viewport, enabled: boolean) => {
71
+ const tickUnit = axis.preset.tickUnit;
72
+ if (!enabled || (tickUnit !== 'day' && !SUB_DAY_TICKS.has(tickUnit))) return EMPTY;
73
+
74
+ const width = viewport.width > 0 ? viewport.width : UNMEASURED_WIDTH;
75
+ const visibleFrom = viewport.scrollLeft;
76
+ const visibleTo = viewport.scrollLeft + width;
77
+ const key = [axis, project.calendars, project.settings];
78
+ if (
79
+ cache &&
80
+ key.every((part, i) => part === cache?.key[i]) &&
81
+ cache.from <= visibleFrom &&
82
+ visibleTo <= cache.to
83
+ ) {
84
+ return cache.spans;
85
+ }
86
+
87
+ // One extra viewport on each side, like the header.
88
+ const fromX = Math.max(0, visibleFrom - width);
89
+ const toX = Math.min(axis.totalWidth, visibleTo + width);
90
+ let spans: readonly TimeSpan[];
91
+ try {
92
+ const calendar = getWorkingCalendar(project);
93
+ spans = compute(
94
+ calendar,
95
+ axis,
96
+ Math.max(axis.start, axis.xToDate(fromX)),
97
+ Math.min(axis.end, axis.xToDate(toX)),
98
+ );
99
+ } catch (error) {
100
+ if (!(error instanceof QuartzioError)) throw error;
101
+ spans = EMPTY; // e.g. a range beyond what the calendar will calculate; shading is decoration
102
+ }
103
+ cache = {
104
+ key,
105
+ from: fromX === 0 ? Number.NEGATIVE_INFINITY : fromX,
106
+ to: toX === axis.totalWidth ? Number.POSITIVE_INFINITY : toX,
107
+ spans,
108
+ };
109
+ return spans;
110
+ };
111
+
112
+ return { spansFor };
113
+ }
@@ -0,0 +1,41 @@
1
+ import type { ProjectState } from '../data/types';
2
+ import type { ViewPreset } from '../timeaxis/presets';
3
+ import { addUnits, startOfUnit } from '../util/zone';
4
+
5
+ /** Ticks of empty space added on each side of the tasks. */
6
+ const PADDING_TICKS = 2;
7
+ /** Shown when there are no dated tasks. */
8
+ const EMPTY_WEEKS = 4;
9
+
10
+ /**
11
+ * The time range to show when none is given: from the earliest to the latest task date, padded by a few
12
+ * ticks. Without dated tasks, a few weeks from the start of the current week.
13
+ */
14
+ export function defaultTimelineRange(
15
+ state: ProjectState,
16
+ preset: ViewPreset,
17
+ now: number,
18
+ ): { start: number; end: number } {
19
+ let min = Number.POSITIVE_INFINITY;
20
+ let max = Number.NEGATIVE_INFINITY;
21
+ for (const task of state.tasks.byId.values()) {
22
+ for (const time of [task.startDate, task.endDate]) {
23
+ if (time !== null) {
24
+ if (time < min) min = time;
25
+ if (time > max) max = time;
26
+ }
27
+ }
28
+ }
29
+
30
+ const { timeZone, weekStartsOn } = state.settings;
31
+ if (min === Number.POSITIVE_INFINITY) {
32
+ const start = startOfUnit(now, 'week', timeZone, weekStartsOn);
33
+ return { start, end: addUnits(start, EMPTY_WEEKS, 'week', timeZone) };
34
+ }
35
+ const padding = PADDING_TICKS * preset.tickIncrement;
36
+ return {
37
+ start: addUnits(min, -padding, preset.tickUnit, timeZone),
38
+ // A zero-length range (one milestone) still gets room after it.
39
+ end: addUnits(max, padding, preset.tickUnit, timeZone),
40
+ };
41
+ }
@@ -0,0 +1,235 @@
1
+ import { getWorkingCalendar } from '../calendar/project';
2
+ import type { WorkingCalendar } from '../calendar/workingCalendar';
3
+ import { getTreeIndex } from '../data/tree';
4
+ import type { Id, ProjectState, Task } from '../data/types';
5
+ import { taskDates, type TaskDates } from './dates';
6
+ import type { TimeAxis } from '../timeaxis/timeAxis';
7
+ import { computeBar, sameBar, type Bar } from './bars';
8
+ import type { ResolvedColumns } from './columns';
9
+ import type { Selection } from './selection';
10
+ import type { Viewport } from './types';
11
+
12
+ /** A string key per task for rendering lists: tasks 1 and "1" are different. */
13
+ export const rowKey = (id: Id): string => `${typeof id === 'number' ? 'n' : 's'}:${String(id)}`;
14
+
15
+ export interface Row {
16
+ readonly id: Id;
17
+ /** Unique string key for rendering lists (ids 1 and "1" are different tasks). */
18
+ readonly key: string;
19
+ /** Position among the visible rows. */
20
+ readonly index: number;
21
+ readonly y: number;
22
+ readonly height: number;
23
+ /** 0 for root tasks. */
24
+ readonly depth: number;
25
+ readonly task: Task;
26
+ readonly hasChildren: boolean;
27
+ readonly expanded: boolean;
28
+ /** Computed display dates, or `null` for unscheduled tasks. */
29
+ readonly dates: TaskDates | null;
30
+ /** Cell texts, one per column. */
31
+ readonly cells: readonly string[];
32
+ /** The task's bar on the timeline, or `null` for unscheduled tasks. */
33
+ readonly bar: Bar | null;
34
+ readonly selected: boolean;
35
+ /** The keyboard cursor is on this row. */
36
+ readonly active: boolean;
37
+ }
38
+
39
+ export interface RowsState {
40
+ readonly rowHeight: number;
41
+ /** Visible rows in total (not counting collapsed descendants). */
42
+ readonly count: number;
43
+ readonly totalHeight: number;
44
+ /**
45
+ * Rows around the visible part only (virtualized). Unchanged rows keep their identity, so they can be
46
+ * memoized, and the array itself is reused while scrolling within the rendered window.
47
+ */
48
+ readonly items: readonly Row[];
49
+ }
50
+
51
+ export interface RowsInput {
52
+ readonly project: ProjectState;
53
+ readonly collapsed: ReadonlySet<Id>;
54
+ /** Changes whenever `collapsed` changes. */
55
+ readonly collapsedVersion: number;
56
+ readonly viewport: Viewport;
57
+ readonly rowHeight: number;
58
+ readonly columns: ResolvedColumns;
59
+ readonly locale: string | undefined;
60
+ readonly timeAxis: TimeAxis;
61
+ readonly selection: Selection;
62
+ }
63
+
64
+ /** Assumed viewport height before it has been measured (and when rendering on the server). */
65
+ export const UNMEASURED_HEIGHT = 800;
66
+
67
+ interface VisibleRows {
68
+ readonly ids: readonly Id[];
69
+ readonly depths: readonly number[];
70
+ /** Row index per visible task. */
71
+ readonly index: ReadonlyMap<Id, number>;
72
+ }
73
+
74
+ /** Tree order, skipping the descendants of collapsed tasks. Iterative, so deep trees can't overflow. */
75
+ function visibleRows(project: ProjectState, collapsed: ReadonlySet<Id>): VisibleRows {
76
+ const tree = getTreeIndex(project.tasks);
77
+ const ids: Id[] = [];
78
+ const depths: number[] = [];
79
+ const index = new Map<Id, number>();
80
+ const stack: [Id, number][] = [...tree.children(null)].reverse().map((id): [Id, number] => [id, 0]);
81
+ while (stack.length > 0) {
82
+ const [id, depth] = stack.pop() as [Id, number];
83
+ index.set(id, ids.length);
84
+ ids.push(id);
85
+ depths.push(depth);
86
+ if (!collapsed.has(id)) {
87
+ const children = tree.children(id);
88
+ for (let i = children.length - 1; i >= 0; i--) stack.push([children[i] as Id, depth + 1]);
89
+ }
90
+ }
91
+ return { ids, depths, index };
92
+ }
93
+
94
+ const sameCells = (a: readonly string[], b: readonly string[]) =>
95
+ a.length === b.length && a.every((text, i) => text === b[i]);
96
+
97
+ const sameDates = (a: TaskDates | null, b: TaskDates | null) =>
98
+ a === b || (a !== null && b !== null && a.start === b.start && a.end === b.end);
99
+
100
+ export function createRowsView(): {
101
+ /** The rows, the row index of every visible task and the task of every row (the same while visibility is unchanged). */
102
+ rowsFor: (input: RowsInput) => {
103
+ rows: RowsState;
104
+ rowIndex: ReadonlyMap<Id, number>;
105
+ rowIds: readonly Id[];
106
+ };
107
+ } {
108
+ let visibleCache: { key: unknown[]; rows: VisibleRows } | undefined;
109
+ let calendarCache: { project: ProjectState; calendar: WorkingCalendar | undefined } | undefined;
110
+ let windowCache: { key: unknown[]; first: number; last: number; state: RowsState } | undefined;
111
+ let previousRows = new Map<Id, Row>();
112
+
113
+ const calendarFor = (project: ProjectState): WorkingCalendar | undefined => {
114
+ if (calendarCache?.project !== project) {
115
+ let calendar: WorkingCalendar | undefined;
116
+ try {
117
+ calendar = getWorkingCalendar(project);
118
+ } catch {
119
+ calendar = undefined;
120
+ }
121
+ calendarCache = { project, calendar };
122
+ }
123
+ return calendarCache.calendar;
124
+ };
125
+
126
+ const rowsFor = (input: RowsInput): RowsState => {
127
+ const {
128
+ project,
129
+ collapsed,
130
+ collapsedVersion,
131
+ viewport,
132
+ rowHeight,
133
+ columns,
134
+ locale,
135
+ timeAxis,
136
+ selection,
137
+ } = input;
138
+
139
+ const visibleKey = [project.tasks, collapsedVersion];
140
+ if (!visibleCache || visibleKey.some((part, i) => part !== visibleCache?.key[i])) {
141
+ visibleCache = { key: visibleKey, rows: visibleRows(project, collapsed) };
142
+ }
143
+ const visible = visibleCache.rows;
144
+ const count = visible.ids.length;
145
+
146
+ const height = viewport.height > 0 ? viewport.height : UNMEASURED_HEIGHT;
147
+ const clamp = (index: number) => Math.max(0, Math.min(count, index));
148
+ const visibleFirst = clamp(Math.floor(viewport.scrollTop / rowHeight));
149
+ const visibleLast = clamp(Math.ceil((viewport.scrollTop + height) / rowHeight));
150
+
151
+ const key = [visible, project, rowHeight, columns, locale, timeAxis, selection];
152
+ if (
153
+ windowCache &&
154
+ key.every((part, i) => part === windowCache?.key[i]) &&
155
+ windowCache.first <= visibleFirst &&
156
+ visibleLast <= windowCache.last
157
+ ) {
158
+ return windowCache.state;
159
+ }
160
+
161
+ // Render one extra viewport above and below, so most scrolling reuses the same rows.
162
+ const first = clamp(Math.floor((viewport.scrollTop - height) / rowHeight));
163
+ const last = clamp(Math.ceil((viewport.scrollTop + 2 * height) / rowHeight));
164
+ const tree = getTreeIndex(project.tasks);
165
+ const calendar = calendarFor(project);
166
+ const rows = new Map<Id, Row>();
167
+ const items: Row[] = [];
168
+
169
+ for (let index = first; index < last; index++) {
170
+ const id = visible.ids[index] as Id;
171
+ const task = project.tasks.byId.get(id) as Task;
172
+ const hasChildren = !tree.isLeaf(id);
173
+ const rowDates = taskDates(task);
174
+ const context = {
175
+ task,
176
+ isParent: hasChildren,
177
+ dates: rowDates,
178
+ settings: project.settings,
179
+ locale,
180
+ calendar,
181
+ };
182
+ const row: Row = {
183
+ id,
184
+ key: rowKey(id),
185
+ index,
186
+ y: index * rowHeight,
187
+ height: rowHeight,
188
+ depth: visible.depths[index] as number,
189
+ task,
190
+ hasChildren,
191
+ expanded: hasChildren && !collapsed.has(id),
192
+ dates: rowDates,
193
+ cells: columns.values.map((value) => value(context)),
194
+ bar: computeBar(task, rowDates, hasChildren, timeAxis),
195
+ selected: selection.set.has(id),
196
+ active: selection.active === id,
197
+ };
198
+ const previous = previousRows.get(id);
199
+ const same =
200
+ previous?.task === row.task &&
201
+ previous.index === row.index &&
202
+ previous.height === row.height &&
203
+ previous.depth === row.depth &&
204
+ previous.expanded === row.expanded &&
205
+ previous.hasChildren === row.hasChildren &&
206
+ previous.selected === row.selected &&
207
+ previous.active === row.active &&
208
+ sameDates(previous.dates, row.dates) &&
209
+ sameCells(previous.cells, row.cells) &&
210
+ sameBar(previous.bar, row.bar);
211
+ const kept = same ? previous : row;
212
+ rows.set(id, kept);
213
+ items.push(kept);
214
+ }
215
+
216
+ previousRows = rows;
217
+ const state: RowsState = { rowHeight, count, totalHeight: count * rowHeight, items };
218
+ // At the list's edges the window can't grow, so treat it as open-ended there.
219
+ windowCache = {
220
+ key,
221
+ first: first === 0 ? -1 : first,
222
+ last: last === count ? Number.POSITIVE_INFINITY : last,
223
+ state,
224
+ };
225
+ return state;
226
+ };
227
+
228
+ return {
229
+ rowsFor: (input) => {
230
+ const rows = rowsFor(input);
231
+ const visible = (visibleCache as { rows: VisibleRows }).rows;
232
+ return { rows, rowIndex: visible.index, rowIds: visible.ids };
233
+ },
234
+ };
235
+ }
@@ -0,0 +1,156 @@
1
+ import type { TreeIndex } from '../data/tree';
2
+ import type { Id, Task } from '../data/types';
3
+
4
+ /** Which keys were held, for clicks and key presses. Ctrl and Cmd (meta) mean the same. */
5
+ export interface KeyModifiers {
6
+ readonly shift?: boolean | undefined;
7
+ readonly ctrl?: boolean | undefined;
8
+ readonly meta?: boolean | undefined;
9
+ readonly alt?: boolean | undefined;
10
+ }
11
+
12
+ /** Selected tasks, the keyboard cursor, and where Shift ranges start from. */
13
+ export interface Selection {
14
+ /** In the order they were selected; a range in row order. */
15
+ readonly ids: readonly Id[];
16
+ readonly set: ReadonlySet<Id>;
17
+ readonly active: Id | null;
18
+ readonly anchor: Id | null;
19
+ }
20
+
21
+ export const NO_SELECTION: Selection = { ids: [], set: new Set(), active: null, anchor: null };
22
+
23
+ /** The visible rows, to find ranges and neighbours in. */
24
+ export interface VisibleRows {
25
+ readonly rowIds: readonly Id[];
26
+ readonly rowIndex: ReadonlyMap<Id, number>;
27
+ readonly tree: TreeIndex;
28
+ }
29
+
30
+ const sameIds = (a: readonly Id[], b: readonly Id[]) =>
31
+ a.length === b.length && a.every((id, i) => id === b[i]);
32
+
33
+ /** A selection, or `previous` when nothing changed (so its arrays keep their identity). */
34
+ export function selectionOf(
35
+ previous: Selection,
36
+ ids: readonly Id[],
37
+ active: Id | null,
38
+ anchor: Id | null,
39
+ ): Selection {
40
+ const same = sameIds(previous.ids, ids);
41
+ if (same && previous.active === active && previous.anchor === anchor) return previous;
42
+ return same
43
+ ? { ...previous, active, anchor }
44
+ : {
45
+ ids: previous.ids.length === 0 && ids.length === 0 ? previous.ids : ids,
46
+ set: new Set(ids),
47
+ active,
48
+ anchor,
49
+ };
50
+ }
51
+
52
+ /** The row showing a task: its own, or its nearest visible ancestor's when collapsed away. */
53
+ export function visibleRowOf(id: Id | null, rows: VisibleRows): number | undefined {
54
+ if (id === null) return undefined;
55
+ const own = rows.rowIndex.get(id);
56
+ if (own !== undefined) return own;
57
+ for (const ancestor of rows.tree.ancestors(id)) {
58
+ const index = rows.rowIndex.get(ancestor);
59
+ if (index !== undefined) return index;
60
+ }
61
+ return undefined;
62
+ }
63
+
64
+ /** The rows from the anchor (or its visible ancestor) to `target`, in row order. */
65
+ function rangeTo(selection: Selection, target: number, rows: VisibleRows): Id[] {
66
+ const from = visibleRowOf(selection.anchor, rows) ?? target;
67
+ return rows.rowIds.slice(Math.min(from, target), Math.max(from, target) + 1);
68
+ }
69
+
70
+ const union = (a: readonly Id[], b: readonly Id[]) => {
71
+ const seen = new Set(a);
72
+ return [...a, ...b.filter((id) => !seen.has(id))];
73
+ };
74
+
75
+ /**
76
+ * Moves the cursor to a row: selects just it; with `extend` (Shift), the rows from the anchor to it (added to
77
+ * the selection with `add`); with `add` alone (Ctrl/Cmd), leaves the selection as it is.
78
+ */
79
+ export function moveTo(
80
+ selection: Selection,
81
+ target: number,
82
+ rows: VisibleRows,
83
+ { extend, add }: { extend: boolean; add: boolean },
84
+ multiSelect: boolean,
85
+ ): Selection {
86
+ const id = rows.rowIds[target] as Id;
87
+ if (multiSelect && extend) {
88
+ const range = rangeTo(selection, target, rows);
89
+ return selectionOf(selection, add ? union(selection.ids, range) : range, id, selection.anchor ?? id);
90
+ }
91
+ if (multiSelect && add) return selectionOf(selection, selection.ids, id, selection.anchor);
92
+ return selectionOf(selection, [id], id, id);
93
+ }
94
+
95
+ /** Selects or deselects a row (Ctrl/Cmd-click, Space). */
96
+ export function toggleRow(
97
+ selection: Selection,
98
+ target: number,
99
+ rows: VisibleRows,
100
+ multiSelect: boolean,
101
+ ): Selection {
102
+ const id = rows.rowIds[target] as Id;
103
+ const has = selection.set.has(id);
104
+ if (!multiSelect) return selectionOf(selection, has && selection.ids.length === 1 ? [] : [id], id, id);
105
+ return selectionOf(
106
+ selection,
107
+ has ? selection.ids.filter((other) => other !== id) : [...selection.ids, id],
108
+ id,
109
+ id,
110
+ );
111
+ }
112
+
113
+ /** A click on a visible row, as in a file list: select it, toggle with Ctrl/Cmd, a range with Shift. */
114
+ export function clickRow(
115
+ selection: Selection,
116
+ id: Id,
117
+ modifiers: KeyModifiers,
118
+ rows: VisibleRows,
119
+ multiSelect: boolean,
120
+ ): Selection {
121
+ const target = rows.rowIndex.get(id);
122
+ if (target === undefined) return selection;
123
+ const add = modifiers.ctrl === true || modifiers.meta === true;
124
+ const extend = modifiers.shift === true && selection.anchor !== null;
125
+ if (add && !extend) return toggleRow(selection, target, rows, multiSelect);
126
+ return moveTo(selection, target, rows, { extend, add }, multiSelect);
127
+ }
128
+
129
+ /** Selects existing tasks by id (duplicates and unknown ids skipped); the last one becomes the cursor. */
130
+ export function selectIds(
131
+ selection: Selection,
132
+ ids: readonly unknown[],
133
+ tasks: ReadonlyMap<Id, Task>,
134
+ multiSelect: boolean,
135
+ ): Selection {
136
+ const known = [...new Set(ids)].filter((id): id is Id => tasks.has(id as Id));
137
+ const kept = multiSelect ? known : known.slice(-1);
138
+ const last = kept.at(-1);
139
+ return last === undefined
140
+ ? selectionOf(selection, [], selection.active, selection.anchor)
141
+ : selectionOf(selection, kept, last, last);
142
+ }
143
+
144
+ /** Drops tasks that no longer exist (the same selection when none were removed). */
145
+ export function pruneSelection(selection: Selection, tasks: ReadonlyMap<Id, Task>): Selection {
146
+ const exists = (id: Id | null) => (id !== null && tasks.has(id) ? id : null);
147
+ if (selection.ids.every((id) => tasks.has(id)) && exists(selection.active) === selection.active) {
148
+ if (exists(selection.anchor) === selection.anchor) return selection;
149
+ }
150
+ return selectionOf(
151
+ selection,
152
+ selection.ids.filter((id) => tasks.has(id)),
153
+ exists(selection.active),
154
+ exists(selection.anchor),
155
+ );
156
+ }
@@ -0,0 +1,71 @@
1
+ import type { Transaction } from '../data/transaction';
2
+ import type { TreeIndex } from '../data/tree';
3
+ import type { Dependency, Id, Task } from '../data/types';
4
+
5
+ export type AddWhere = 'above' | 'below' | 'subtask' | 'milestone' | 'successor' | 'predecessor';
6
+
7
+ const NEW_TASK_NAME = 'New task';
8
+
9
+ /**
10
+ * Adds a task next to (or in) `target`: 1 day, or 0 for a milestone; a successor or predecessor is linked with
11
+ * FS. Returns the new task's id. `id` is used when given (it must be new), otherwise the data makes one up.
12
+ */
13
+ export function addTask(tx: Transaction, target: Task, where: AddWhere, id: Id | undefined): Id {
14
+ const parentId = target.parentId;
15
+ const index = tx.tasks.children(parentId).indexOf(target.id);
16
+ const before = where === 'above' || where === 'predecessor';
17
+ const fields = {
18
+ ...(id === undefined ? {} : { id }),
19
+ name: NEW_TASK_NAME,
20
+ duration: where === 'milestone' ? 0 : 1,
21
+ };
22
+ const added =
23
+ where === 'subtask'
24
+ ? tx.tasks.add(fields, { parentId: target.id })
25
+ : tx.tasks.add(fields, { parentId, index: before ? index : index + 1 });
26
+ if (where === 'successor') tx.dependencies.add({ from: target.id, to: added.id, type: 'FS' });
27
+ if (where === 'predecessor') tx.dependencies.add({ from: added.id, to: target.id, type: 'FS' });
28
+ return added.id;
29
+ }
30
+
31
+ /**
32
+ * Makes each task the last child of the sibling before it (in tree order; those without one stay). Links between
33
+ * the task (or its subtasks) and its new parent go: a parent and its children can't be linked.
34
+ */
35
+ export function indent(
36
+ tx: Transaction,
37
+ ids: readonly Id[],
38
+ tree: TreeIndex,
39
+ dependencies: Iterable<Dependency>,
40
+ ): Id[] {
41
+ const parents: Id[] = [];
42
+ const links = [...dependencies];
43
+ for (const id of ids) {
44
+ const task = tx.tasks.get(id);
45
+ if (!task) continue;
46
+ const siblings = tx.tasks.children(task.parentId);
47
+ const before = siblings[siblings.indexOf(id) - 1];
48
+ if (before === undefined) continue;
49
+ const subtree = new Set([id, ...tree.descendants(id)]);
50
+ for (const link of links) {
51
+ const between =
52
+ (subtree.has(link.from) && link.to === before) || (link.from === before && subtree.has(link.to));
53
+ if (between && tx.dependencies.get(link.id)) tx.dependencies.remove(link.id);
54
+ }
55
+ tx.tasks.move(id, { parentId: before });
56
+ parents.push(before);
57
+ }
58
+ return parents;
59
+ }
60
+
61
+ /** Moves each task out of its parent, right after it (root tasks stay). */
62
+ export function outdent(tx: Transaction, ids: readonly Id[]): void {
63
+ // Last first, so several siblings end up after their parent in their own order.
64
+ for (const id of [...ids].reverse()) {
65
+ const task = tx.tasks.get(id);
66
+ const parent = task?.parentId === null || task === undefined ? undefined : tx.tasks.get(task.parentId);
67
+ if (!parent) continue;
68
+ const index = tx.tasks.children(parent.parentId).indexOf(parent.id);
69
+ tx.tasks.move(id, { parentId: parent.parentId, index: index + 1 });
70
+ }
71
+ }