@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,671 @@
1
+ import { workingMsPerUnit } from '../calendar/duration';
2
+ import { getWorkingCalendar } from '../calendar/project';
3
+ import { getDependencyIndex, wouldCreateCycle } from '../data/graph';
4
+ import type { Transaction } from '../data/transaction';
5
+ import { getTreeIndex } from '../data/tree';
6
+ import type { DependencyType, Id, ProjectState, Task } from '../data/types';
7
+ import type { TimeAxis } from '../timeaxis/timeAxis';
8
+ import { QuartzioError } from '../util/errors';
9
+ import { addUnits } from '../util/zone';
10
+ import { computeBar, type Bar } from './bars';
11
+ import { formatDate, formatDateTime, formatEndDate } from './cells';
12
+ import { taskDates } from './dates';
13
+ import { rowKey, type RowsState } from './rows';
14
+ import type { Viewport } from './types';
15
+
16
+ /** A point on the timeline body: x from the start of the axis, y from the top of the first row. */
17
+ export interface TimelinePoint {
18
+ readonly x: number;
19
+ readonly y: number;
20
+ }
21
+
22
+ /**
23
+ * What a press would grab: a bar to move, its end to resize, its progress handle, an empty row of an
24
+ * unscheduled task to draw a bar in, or a link handle at either end of a bar to draw a dependency from.
25
+ */
26
+ export type HitArea = 'bar' | 'resize-end' | 'progress' | 'create' | 'link-start' | 'link-end';
27
+
28
+ /** What's under a point (only what's enabled). */
29
+ export interface TimelineHit {
30
+ readonly taskId: Id;
31
+ readonly area: HitArea;
32
+ }
33
+
34
+ /** A change an interaction proposes, for `validateChange`. */
35
+ export type ProposedChange =
36
+ | {
37
+ readonly kind: 'move' | 'resize' | 'create';
38
+ readonly task: Task;
39
+ readonly start: number;
40
+ readonly end: number;
41
+ }
42
+ | { readonly kind: 'progress'; readonly task: Task; readonly percentDone: number }
43
+ | { readonly kind: 'link'; readonly from: Task; readonly to: Task; readonly type: DependencyType };
44
+
45
+ interface InteractionBase {
46
+ /** Whether the drop would be applied: `validateChange` (and, for links, the rules) allow it. */
47
+ readonly valid: boolean;
48
+ /** Why it isn't valid, if there's a reason to show. */
49
+ readonly message: string | null;
50
+ /** Text for a tooltip: the new dates, the percentage, or the link. */
51
+ readonly label: string;
52
+ /**
53
+ * Pixels per frame to scroll by, while the pointer is near or past an edge of the visible timeline. The
54
+ * renderer scrolls and then sends the pointer position again.
55
+ */
56
+ readonly autoScroll: { readonly x: number; readonly y: number };
57
+ }
58
+
59
+ /** A bar being moved, resized, drawn (created) or having its progress dragged: where it would land. */
60
+ export interface BarInteraction extends InteractionBase {
61
+ readonly kind: 'move' | 'resize' | 'create' | 'progress';
62
+ readonly taskId: Id;
63
+ /** Key of the task's row, to set the original bar apart. */
64
+ readonly rowKey: string;
65
+ /** The bar at its new place (snapped), in timeline coordinates, in the task's row. */
66
+ readonly bar: Bar;
67
+ readonly start: number;
68
+ readonly end: number;
69
+ /** 0–100; for progress. */
70
+ readonly percent: number;
71
+ }
72
+
73
+ /** A dependency being drawn from a bar's end (or start) to the pointer. */
74
+ export interface LinkInteraction extends InteractionBase {
75
+ readonly kind: 'link';
76
+ readonly from: Id;
77
+ /** The bar under the pointer, if any. */
78
+ readonly to: Id | null;
79
+ /** The type the drop would create (from the sides), when over a bar. */
80
+ readonly type: DependencyType | null;
81
+ /** SVG path data of the line, in timeline coordinates. */
82
+ readonly path: string;
83
+ /** Where the line ends (the pointer), e.g. to put a tooltip there. */
84
+ readonly end: TimelinePoint;
85
+ }
86
+
87
+ export type TaskInteraction = BarInteraction | LinkInteraction;
88
+
89
+ /** Movement (px) below which a press and release is a click, not a drag. */
90
+ export const CLICK_TOLERANCE = 3;
91
+ /** Hit targets are at least this wide, so short bars can still be grabbed. */
92
+ const MIN_HIT_WIDTH = 6;
93
+ /** The resize handle at a bar's end; less on short bars, so their middle can still be moved. */
94
+ const RESIZE_HANDLE = 6;
95
+ /** Link handles sit just outside a bar's ends. */
96
+ const LINK_HANDLE = 10;
97
+ /** The progress handle: this far either side of the progress edge, low in the bar (fractions of the row). */
98
+ const PROGRESS_HANDLE = 5;
99
+ const PROGRESS_TOP = 0.6;
100
+ const PROGRESS_BOTTOM = 0.9;
101
+ /** Half a milestone diamond (matches the default --qz-milestone-size; a changed size doesn't move the target). */
102
+ const MILESTONE_RADIUS = 7;
103
+ /** Auto-scroll: within this distance of an edge, up to this many px per frame (more past the edge). */
104
+ const EDGE = 30;
105
+ const MAX_SPEED = 20;
106
+ /** Dates must stay within what the data accepts (years 1000–9999). */
107
+ const MIN_TIME = Date.UTC(1000, 0, 1);
108
+ const MAX_TIME = Date.UTC(10_000, 0, 1) - 1;
109
+ const SUB_DAY = new Set(['millisecond', 'second', 'minute', 'hour']);
110
+ const NO_SCROLL = { x: 0, y: 0 };
111
+
112
+ /** What the interaction needs from the view. */
113
+ export interface InteractionView {
114
+ readonly project: ProjectState;
115
+ readonly timeAxis: TimeAxis;
116
+ readonly rows: RowsState;
117
+ readonly viewport: Viewport;
118
+ /** Row index of every visible task. */
119
+ readonly rowIndex: ReadonlyMap<Id, number>;
120
+ /** Task ids of the visible rows, by row index. */
121
+ readonly rowIds: readonly Id[];
122
+ readonly locale: string | undefined;
123
+ readonly enabled: {
124
+ readonly drag: boolean;
125
+ readonly resize: boolean;
126
+ readonly create: boolean;
127
+ readonly progress: boolean;
128
+ readonly link: boolean;
129
+ };
130
+ readonly validate: ((change: ProposedChange) => boolean | string) | undefined;
131
+ }
132
+
133
+ export interface InteractionContext {
134
+ readonly view: () => InteractionView;
135
+ readonly show: (interaction: TaskInteraction | null) => void;
136
+ readonly commit: (fn: (tx: Transaction) => void) => void;
137
+ }
138
+
139
+ export interface Interaction {
140
+ hitTest: (point: TimelinePoint) => TimelineHit | null;
141
+ pointerDown: (point: TimelinePoint) => boolean;
142
+ pointerMove: (point: TimelinePoint) => void;
143
+ pointerUp: (point: TimelinePoint) => void;
144
+ /** Drops the drag; returns whether there was one. */
145
+ cancel: () => boolean;
146
+ /**
147
+ * For a new view, before it's shown: whether the drag still applies. A drag on a stale basis (another time
148
+ * axis, a changed or hidden task, turned-off options) is dropped silently, so no outdated preview is shown.
149
+ */
150
+ keep: (next: InteractionView) => boolean;
151
+ /**
152
+ * After the chart scrolled: the pointer is now over another part of it, so the drag follows (with the fresh
153
+ * viewport). Lets auto-scrolling work without the renderer sending the pointer again.
154
+ */
155
+ follow: () => void;
156
+ }
157
+
158
+ /** A drop to apply, decided by the latest preview. */
159
+ type Drop = (tx: Transaction) => void;
160
+
161
+ interface Pending {
162
+ readonly hit: TimelineHit;
163
+ readonly origin: TimelinePoint;
164
+ readonly task: Task;
165
+ /** The task's bar; `null` when drawing a new one. */
166
+ readonly bar: Bar | null;
167
+ readonly axis: TimeAxis;
168
+ readonly row: number;
169
+ started: boolean;
170
+ preview: TaskInteraction | null;
171
+ drop: Drop | null;
172
+ /** The last pointer position, and the scroll position at that moment (to follow scrolling). */
173
+ last: TimelinePoint | null;
174
+ scroll: { left: number; top: number };
175
+ }
176
+
177
+ const finite = (point: TimelinePoint) => Number.isFinite(point.x) && Number.isFinite(point.y);
178
+ const inRange = (time: number) => Number.isFinite(time) && time >= MIN_TIME && time <= MAX_TIME;
179
+ const round = (value: number) => Math.round(value * 10) / 10;
180
+
181
+ /** Link type from the sides: out of the predecessor's end or start, into the successor's start or end. */
182
+ function linkType(fromSide: 'start' | 'end', toSide: 'start' | 'end'): DependencyType {
183
+ if (fromSide === 'end') return toSide === 'start' ? 'FS' : 'FF';
184
+ return toSide === 'start' ? 'SS' : 'SF';
185
+ }
186
+
187
+ /** Speed towards an edge: 0 far from it, growing inside EDGE px, and more past it. */
188
+ function speed(position: number, low: number, high: number): number {
189
+ if (high - low <= 2 * EDGE) return 0; // too small to tell an edge from the middle
190
+ const ease = (distance: number) =>
191
+ Math.min(MAX_SPEED * 2, Math.ceil(((EDGE - distance) / EDGE) * MAX_SPEED));
192
+ if (position > high - EDGE) return ease(high - position);
193
+ if (position < low + EDGE) return -ease(position - low);
194
+ return 0;
195
+ }
196
+
197
+ function barOf(view: Pick<InteractionView, 'project' | 'timeAxis' | 'rows'>, id: Id): Bar | null {
198
+ const rendered = view.rows.items.find((row) => row.id === id);
199
+ if (rendered) return rendered.bar;
200
+ const task = view.project.tasks.byId.get(id);
201
+ if (!task) return null;
202
+ return computeBar(task, taskDates(task), !getTreeIndex(view.project.tasks).isLeaf(id), view.timeAxis);
203
+ }
204
+
205
+ /** The bar extent a point is tested against: milestones are their diamond; short bars get a minimum width. */
206
+ const extent = (bar: Bar) => {
207
+ const left = bar.kind === 'milestone' ? bar.x - MILESTONE_RADIUS : bar.x;
208
+ const width = bar.kind === 'milestone' ? 2 * MILESTONE_RADIUS : bar.width;
209
+ const extra = Math.max(0, MIN_HIT_WIDTH - width) / 2;
210
+ return { left, width, from: left - extra, to: left + width + extra };
211
+ };
212
+
213
+ const rowAt = (view: Pick<InteractionView, 'rows' | 'rowIds'>, point: TimelinePoint) => {
214
+ if (!finite(point) || point.y < 0) return null;
215
+ const index = Math.floor(point.y / view.rows.rowHeight);
216
+ const taskId = view.rowIds[index];
217
+ return taskId === undefined ? null : { taskId, index };
218
+ };
219
+
220
+ /** The bar under a point (its whole extent, whatever is enabled), for the task tooltip. */
221
+ export function barUnder(
222
+ view: Pick<InteractionView, 'project' | 'timeAxis' | 'rows' | 'rowIds'>,
223
+ point: TimelinePoint,
224
+ ): { taskId: Id; index: number; bar: Bar } | null {
225
+ const row = rowAt(view, point);
226
+ if (!row) return null;
227
+ const bar = barOf(view, row.taskId);
228
+ if (!bar) return null;
229
+ const { from, to } = extent(bar);
230
+ return point.x >= from && point.x <= to ? { ...row, bar } : null;
231
+ }
232
+
233
+ /**
234
+ * Dragging on the timeline, as a small state machine fed with pointer events in timeline coordinates: moving,
235
+ * resizing, drawing bars, dragging progress and drawing dependencies. Snaps to the preset's time resolution; a
236
+ * drop becomes one transaction.
237
+ */
238
+ export function createInteraction(context: InteractionContext): Interaction {
239
+ let pending: Pending | null = null;
240
+
241
+ const hitTest = (point: TimelinePoint): TimelineHit | null => {
242
+ const view = context.view();
243
+ const { enabled } = view;
244
+ const row = rowAt(view, point);
245
+ if (!row) return null;
246
+ const { taskId } = row;
247
+ const bar = barOf(view, taskId);
248
+ // Drawing gives a task its own dates, so not a parent (it spans its children).
249
+ if (!bar) {
250
+ return enabled.create && getTreeIndex(view.project.tasks).isLeaf(taskId)
251
+ ? { taskId, area: 'create' }
252
+ : null;
253
+ }
254
+
255
+ const { left, width, from, to } = extent(bar);
256
+ const inRow = (point.y - row.index * view.rows.rowHeight) / view.rows.rowHeight;
257
+ if (point.x >= from && point.x <= to) {
258
+ const progressX = bar.x + bar.progress * bar.width;
259
+ if (
260
+ enabled.progress &&
261
+ bar.kind === 'task' &&
262
+ Math.abs(point.x - progressX) <= PROGRESS_HANDLE &&
263
+ inRow >= PROGRESS_TOP &&
264
+ inRow <= PROGRESS_BOTTOM
265
+ ) {
266
+ return { taskId, area: 'progress' };
267
+ }
268
+ const handle = Math.min(RESIZE_HANDLE, width / 3);
269
+ if (enabled.resize && bar.kind === 'task' && point.x >= left + width - handle)
270
+ return { taskId, area: 'resize-end' };
271
+ return enabled.drag ? { taskId, area: 'bar' } : null;
272
+ }
273
+ if (enabled.link && point.x >= from - LINK_HANDLE && point.x < from)
274
+ return { taskId, area: 'link-start' };
275
+ if (enabled.link && point.x > to && point.x <= to + LINK_HANDLE) return { taskId, area: 'link-end' };
276
+ return null;
277
+ };
278
+
279
+ /** Where a move to `start` lands: the end the drop will give, from the duration in working time. */
280
+ const moved = (
281
+ view: InteractionView,
282
+ task: Task,
283
+ bar: Bar,
284
+ start: number,
285
+ ): { start: number; end: number } => {
286
+ if (bar.kind === 'milestone') return { start, end: start };
287
+ try {
288
+ const calendar = getWorkingCalendar(view.project);
289
+ const ms =
290
+ task.duration !== null && bar.kind === 'task'
291
+ ? Math.round(task.duration * workingMsPerUnit(task.durationUnit, view.project.settings))
292
+ : calendar.workingTimeBetween(bar.start, bar.end);
293
+ // Automatic tasks start at working time (scheduling moves them there; predecessors may push further).
294
+ const begin = task.manuallyScheduled || ms === 0 ? start : calendar.nextWorkingTime(start);
295
+ return { start: begin, end: calendar.addWorkingTime(begin, ms) };
296
+ } catch (error) {
297
+ if (!(error instanceof QuartzioError)) throw error;
298
+ return { start, end: start + (bar.end - bar.start) }; // e.g. no working time: keep the span
299
+ }
300
+ };
301
+
302
+ /** One step of the time resolution after `time`, snapped: the least a bar may span. */
303
+ const stepAfter = (axis: TimeAxis, time: number, zone: ProjectState['settings']['timeZone']): number => {
304
+ const snapped = axis.snap(time);
305
+ if (snapped > time) return snapped;
306
+ const { unit, increment } = axis.preset.timeResolution;
307
+ return addUnits(snapped, increment, unit, zone);
308
+ };
309
+
310
+ /** Where an automatic task drawn over `first`–`last` lands: at working time, lasting the span's working time. */
311
+ const landing = (view: InteractionView, first: number, last: number) => {
312
+ try {
313
+ const calendar = getWorkingCalendar(view.project);
314
+ const ms = calendar.workingTimeBetween(first, last);
315
+ if (ms === 0) return { start: first, end: last, empty: true };
316
+ const start = calendar.nextWorkingTime(first);
317
+ return { start, end: calendar.addWorkingTime(start, ms), empty: false };
318
+ } catch (error) {
319
+ if (!(error instanceof QuartzioError)) throw error;
320
+ return { start: first, end: last, empty: true };
321
+ }
322
+ };
323
+
324
+ const dateLabel = (view: InteractionView, start: number, end: number, milestone: boolean): string => {
325
+ const zone = view.project.settings.timeZone;
326
+ const subDay = SUB_DAY.has(view.timeAxis.preset.timeResolution.unit);
327
+ const format = (time: number) =>
328
+ subDay ? formatDateTime(time, zone, view.locale) : formatDate(time, zone, view.locale);
329
+ if (milestone) return format(start);
330
+ return `${format(start)} – ${subDay ? format(end) : formatEndDate(start, end, zone, view.locale)}`;
331
+ };
332
+
333
+ const verdict = (
334
+ view: InteractionView,
335
+ change: ProposedChange,
336
+ ): { valid: boolean; message: string | null } => {
337
+ let result: boolean | string;
338
+ try {
339
+ result = view.validate?.(change) ?? true;
340
+ } catch (error) {
341
+ // A validator that throws refuses: pointer handlers (and what renders) must not throw.
342
+ return { valid: false, message: error instanceof Error && error.message !== '' ? error.message : null };
343
+ }
344
+ if (result === true) return { valid: true, message: null };
345
+ return { valid: false, message: typeof result === 'string' && result !== '' ? result : null };
346
+ };
347
+
348
+ // Bar gestures stay in their row, so only links (to other rows) scroll vertically.
349
+ const autoScroll = (view: InteractionView, point: TimelinePoint, vertical: boolean) => {
350
+ const { scrollLeft, scrollTop, width, height } = view.viewport;
351
+ if (width <= 0 || height <= 0) return NO_SCROLL;
352
+ // Only as far as there is to scroll: nothing towards an edge already reached.
353
+ const limit = (value: number, position: number, max: number) =>
354
+ (value < 0 && position <= 0) || (value > 0 && position >= max) ? 0 : value;
355
+ const x = limit(
356
+ speed(point.x, scrollLeft, scrollLeft + width),
357
+ scrollLeft,
358
+ view.timeAxis.totalWidth - width,
359
+ );
360
+ const y = vertical
361
+ ? limit(speed(point.y, scrollTop, scrollTop + height), scrollTop, view.rows.totalHeight - height)
362
+ : 0;
363
+ return x === 0 && y === 0 ? NO_SCROLL : { x, y };
364
+ };
365
+
366
+ /** Preview and drop for moving, resizing, creating and progress. */
367
+ const barPreview = (
368
+ view: InteractionView,
369
+ current: Pending,
370
+ point: TimelinePoint,
371
+ ): { interaction: BarInteraction; drop: Drop | null } | null => {
372
+ const { timeAxis, project } = view;
373
+ const { task, bar, hit } = current;
374
+ const zone = project.settings.timeZone;
375
+ const dx = point.x - current.origin.x;
376
+ const scroll = autoScroll(view, point, false);
377
+ const base = { taskId: task.id, rowKey: rowKey(task.id), autoScroll: scroll };
378
+
379
+ if (hit.area === 'progress' && bar) {
380
+ const percent = Math.round(Math.max(0, Math.min(1, (point.x - bar.x) / bar.width)) * 100);
381
+ const change: ProposedChange = { kind: 'progress', task, percentDone: percent };
382
+ const { valid, message } = verdict(view, change);
383
+ const interaction: BarInteraction = {
384
+ ...base,
385
+ kind: 'progress',
386
+ bar: { ...bar, progress: percent / 100 },
387
+ start: bar.start,
388
+ end: bar.end,
389
+ percent,
390
+ label: `${String(percent)}%`,
391
+ valid,
392
+ message,
393
+ };
394
+ const drop: Drop | null =
395
+ valid && percent !== task.percentDone
396
+ ? (tx) => {
397
+ tx.tasks.update(task.id, { percentDone: percent });
398
+ }
399
+ : null;
400
+ return { interaction, drop };
401
+ }
402
+
403
+ // From the dates, not the bar: a bar far outside the axis is clipped to near it.
404
+ let kind: BarInteraction['kind'];
405
+ let start: number;
406
+ let end: number;
407
+ let drop: Drop | null = null;
408
+ if (hit.area === 'create') {
409
+ const a = timeAxis.snap(timeAxis.xToDate(current.origin.x));
410
+ const b = timeAxis.snap(timeAxis.xToDate(point.x));
411
+ if (!inRange(a) || !inRange(b)) return null;
412
+ kind = 'create';
413
+ const first = Math.min(a, b);
414
+ const last = Math.max(Math.max(a, b), stepAfter(timeAxis, first, zone));
415
+ // An automatic task lands at working time, with the working time in the span as its duration.
416
+ const landed = task.manuallyScheduled
417
+ ? { start: first, end: last, empty: false }
418
+ : landing(view, first, last);
419
+ start = landed.start;
420
+ end = landed.end;
421
+ if (landed.empty) {
422
+ const drawn = computeBar(task, { start: first, end: last }, false, timeAxis);
423
+ if (!drawn) return null;
424
+ const interaction: BarInteraction = {
425
+ ...base,
426
+ kind,
427
+ bar: drawn,
428
+ start: first,
429
+ end: last,
430
+ percent: task.percentDone,
431
+ label: dateLabel(view, first, last, false),
432
+ valid: false,
433
+ message: 'No working time in the drawn span',
434
+ };
435
+ return { interaction, drop: null };
436
+ }
437
+ drop = (tx) => {
438
+ if (task.manuallyScheduled) tx.tasks.update(task.id, { startDate: first, endDate: last });
439
+ else {
440
+ // Automatic: held at the drawn start ("start no earlier than"); the duration comes from the drawn span.
441
+ tx.tasks.update(task.id, {
442
+ startDate: first,
443
+ endDate: last,
444
+ constraintType: 'startnoearlierthan',
445
+ constraintDate: first,
446
+ });
447
+ }
448
+ };
449
+ } else if (hit.area === 'bar' && bar) {
450
+ const snapped = timeAxis.snap(timeAxis.xToDate(timeAxis.dateToX(bar.start) + dx));
451
+ if (!inRange(snapped)) return null;
452
+ kind = 'move';
453
+ ({ start, end } = moved(view, task, bar, snapped));
454
+ // Compared with where the bar snaps to without moving: an automatic task starting at 08:00 snaps to
455
+ // midnight, which isn't a move.
456
+ if (snapped !== timeAxis.snap(bar.start)) {
457
+ drop = (tx) => {
458
+ if (task.manuallyScheduled) tx.tasks.update(task.id, { startDate: snapped });
459
+ else tx.tasks.update(task.id, { constraintType: 'startnoearlierthan', constraintDate: snapped });
460
+ };
461
+ }
462
+ } else if (bar) {
463
+ const snapped = timeAxis.snap(timeAxis.xToDate(timeAxis.dateToX(bar.end) + dx));
464
+ if (!inRange(snapped)) return null;
465
+ kind = 'resize';
466
+ start = bar.start;
467
+ end = Math.max(stepAfter(timeAxis, start, zone), snapped);
468
+ if (end !== timeAxis.snap(bar.end)) {
469
+ const newEnd = end;
470
+ drop = (tx) => {
471
+ tx.tasks.update(task.id, { endDate: newEnd });
472
+ };
473
+ }
474
+ } else {
475
+ return null;
476
+ }
477
+ if (!inRange(start) || !inRange(end)) return null;
478
+
479
+ const isParent = bar?.kind === 'summary' || !getTreeIndex(project.tasks).isLeaf(task.id);
480
+ const next = computeBar(task, { start, end }, isParent, timeAxis);
481
+ if (!next) return null;
482
+ const { valid, message } = verdict(view, { kind, task, start, end });
483
+ const interaction: BarInteraction = {
484
+ ...base,
485
+ kind,
486
+ bar: next,
487
+ start,
488
+ end,
489
+ percent: task.percentDone,
490
+ label: dateLabel(view, start, end, next.kind === 'milestone'),
491
+ valid,
492
+ message,
493
+ };
494
+ return { interaction, drop: valid ? drop : null };
495
+ };
496
+
497
+ /** Preview and drop for drawing a dependency. */
498
+ const linkPreview = (
499
+ view: InteractionView,
500
+ current: Pending,
501
+ point: TimelinePoint,
502
+ ): { interaction: LinkInteraction; drop: Drop | null } | null => {
503
+ const { task, bar, hit, row } = current;
504
+ if (!bar) return null;
505
+ const fromSide = hit.area === 'link-start' ? 'start' : 'end';
506
+ const { from, to } = extent(bar);
507
+ const x1 = fromSide === 'start' ? from : to;
508
+ const y1 = row * view.rows.rowHeight + view.rows.rowHeight / 2;
509
+ const base = {
510
+ kind: 'link' as const,
511
+ from: task.id,
512
+ path: `M${String(round(x1))} ${String(round(y1))} L${String(round(point.x))} ${String(round(point.y))}`,
513
+ end: { x: point.x, y: point.y },
514
+ autoScroll: autoScroll(view, point, true),
515
+ };
516
+ const nothing = { ...base, to: null, type: null, label: '', valid: false, message: null };
517
+
518
+ const target = rowAt(view, point);
519
+ const targetBar = target && barOf(view, target.taskId);
520
+ const targetTask = target && view.project.tasks.byId.get(target.taskId);
521
+ if (!target || !targetBar || !targetTask) return { interaction: nothing, drop: null };
522
+ const edges = extent(targetBar);
523
+ if (point.x < edges.from - LINK_HANDLE || point.x > edges.to + LINK_HANDLE)
524
+ return { interaction: nothing, drop: null };
525
+ // Onto the end handle (or the last third of the bar): into its end; otherwise into its start.
526
+ const toSide = point.x > edges.left + (edges.width * 2) / 3 ? 'end' : 'start';
527
+ const type = linkType(fromSide, toSide);
528
+ const label = `${task.name || String(task.id)} → ${targetTask.name || String(targetTask.id)} (${type})`;
529
+
530
+ let rule: string | null = null;
531
+ const tree = getTreeIndex(view.project.tasks);
532
+ if (targetTask.id === task.id) rule = 'Can’t link a task to itself';
533
+ else if (
534
+ tree.ancestors(task.id).includes(targetTask.id) ||
535
+ tree.ancestors(targetTask.id).includes(task.id)
536
+ ) {
537
+ rule = 'Can’t link a task to its parent or child';
538
+ } else if (
539
+ getDependencyIndex(view.project.dependencies)
540
+ .outgoing(task.id)
541
+ .some((d) => d.to === targetTask.id)
542
+ ) {
543
+ rule = 'Already linked';
544
+ } else if (wouldCreateCycle(view.project, task.id, targetTask.id)) rule = 'Would create a cycle';
545
+ const checked = rule === null ? verdict(view, { kind: 'link', from: task, to: targetTask, type }) : null;
546
+ const valid = checked?.valid ?? false;
547
+ const interaction: LinkInteraction = {
548
+ ...base,
549
+ to: targetTask.id,
550
+ type,
551
+ label,
552
+ valid,
553
+ message: rule ?? checked?.message ?? null,
554
+ };
555
+ const drop: Drop | null = valid
556
+ ? (tx) => {
557
+ tx.dependencies.add({ from: task.id, to: targetTask.id, type });
558
+ }
559
+ : null;
560
+ return { interaction, drop };
561
+ };
562
+
563
+ const cancel = (): boolean => {
564
+ if (!pending) return false;
565
+ const shown = pending.preview !== null;
566
+ pending = null;
567
+ if (shown) context.show(null);
568
+ return true;
569
+ };
570
+
571
+ const pointerMove = (point: TimelinePoint) => {
572
+ if (!pending || !finite(point)) return;
573
+ if (!pending.started) {
574
+ if (Math.hypot(point.x - pending.origin.x, point.y - pending.origin.y) < CLICK_TOLERANCE) return;
575
+ pending.started = true;
576
+ }
577
+ const view = context.view();
578
+ pending.last = point;
579
+ pending.scroll = { left: view.viewport.scrollLeft, top: view.viewport.scrollTop };
580
+ const isLink = pending.hit.area === 'link-start' || pending.hit.area === 'link-end';
581
+ const next = isLink ? linkPreview(view, pending, point) : barPreview(view, pending, point);
582
+ if (!next) return;
583
+ pending.drop = next.drop;
584
+ if (!sameInteraction(pending.preview, next.interaction)) {
585
+ pending.preview = next.interaction;
586
+ context.show(next.interaction);
587
+ }
588
+ };
589
+
590
+ return {
591
+ hitTest,
592
+ pointerMove,
593
+ cancel,
594
+
595
+ pointerDown(point) {
596
+ cancel();
597
+ const hit = hitTest(point);
598
+ if (!hit) return false;
599
+ const view = context.view();
600
+ const task = view.project.tasks.byId.get(hit.taskId);
601
+ const row = view.rowIndex.get(hit.taskId);
602
+ if (!task || row === undefined) return false;
603
+ const bar = barOf(view, hit.taskId);
604
+ if (!bar && hit.area !== 'create') return false;
605
+ pending = {
606
+ hit,
607
+ origin: point,
608
+ task,
609
+ bar,
610
+ axis: view.timeAxis,
611
+ row,
612
+ started: false,
613
+ preview: null,
614
+ drop: null,
615
+ last: null,
616
+ scroll: { left: view.viewport.scrollLeft, top: view.viewport.scrollTop },
617
+ };
618
+ return true;
619
+ },
620
+
621
+ pointerUp(point) {
622
+ const current = pending;
623
+ if (!current) return;
624
+ try {
625
+ if (current.started) pointerMove(point);
626
+ } finally {
627
+ cancel(); // the drag ends with the release, whatever happens
628
+ }
629
+ if (current.started && current.drop) context.commit(current.drop);
630
+ },
631
+
632
+ follow() {
633
+ if (!pending?.started || !pending.last) return;
634
+ const { viewport } = context.view();
635
+ const dx = viewport.scrollLeft - pending.scroll.left;
636
+ const dy = viewport.scrollTop - pending.scroll.top;
637
+ if (dx !== 0 || dy !== 0) pointerMove({ x: pending.last.x + dx, y: pending.last.y + dy });
638
+ },
639
+
640
+ keep(next) {
641
+ if (!pending) return true;
642
+ const { hit, task, axis, row } = pending;
643
+ const { enabled } = next;
644
+ const allowed = {
645
+ bar: enabled.drag,
646
+ 'resize-end': enabled.resize,
647
+ progress: enabled.progress,
648
+ create: enabled.create,
649
+ 'link-start': enabled.link,
650
+ 'link-end': enabled.link,
651
+ }[hit.area];
652
+ const stillValid =
653
+ allowed &&
654
+ next.timeAxis === axis &&
655
+ next.project.tasks.byId.get(hit.taskId) === task &&
656
+ next.rowIndex.get(hit.taskId) === row;
657
+ if (!stillValid) pending = null;
658
+ return stillValid;
659
+ },
660
+ };
661
+ }
662
+
663
+ /** Whether a new preview shows the same as the last (so nothing needs rendering). */
664
+ function sameInteraction(a: TaskInteraction | null, b: TaskInteraction): boolean {
665
+ if (a?.kind !== b.kind || a.valid !== b.valid || a.message !== b.message) return false;
666
+ if (a.autoScroll.x !== b.autoScroll.x || a.autoScroll.y !== b.autoScroll.y) return false;
667
+ if (a.kind === 'link' && b.kind === 'link') return a.path === b.path && a.to === b.to && a.type === b.type;
668
+ if (a.kind !== 'link' && b.kind !== 'link')
669
+ return a.start === b.start && a.end === b.end && a.percent === b.percent;
670
+ return false;
671
+ }