@jsb188/schedule 1.1.11

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 (60) hide show
  1. package/package.json +61 -0
  2. package/src/constants/schedule.ts +549 -0
  3. package/src/css.d.ts +7 -0
  4. package/src/libs/gantt-geometry.ts +771 -0
  5. package/src/libs/gantt-histogram.ts +124 -0
  6. package/src/libs/gantt-keyboard.ts +113 -0
  7. package/src/libs/gantt-state.ts +57 -0
  8. package/src/libs/gantt-url.ts +63 -0
  9. package/src/modules/Gantt.helpers.ts +138 -0
  10. package/src/modules/Gantt.tsx +719 -0
  11. package/src/types/schedule.d.ts +1149 -0
  12. package/src/ui/ActivityFormUI.tsx +133 -0
  13. package/src/ui/GanttEditorsUI.tsx +102 -0
  14. package/src/ui/GanttHistogramUI.tsx +236 -0
  15. package/src/ui/GanttUI.tsx +792 -0
  16. package/src/ui/ProjectFormUI.tsx +273 -0
  17. package/src/ui/ProjectMobileListUI.tsx +80 -0
  18. package/src/ui/ProjectToolbarUI.tsx +54 -0
  19. package/src/ui/RelationshipListUI.tsx +176 -0
  20. package/src/ui/ScheduleRunUI.tsx +173 -0
  21. package/src/ui/ScheduleSettingsUI.tsx +420 -0
  22. package/src/utils/coverage.helpers.ts +679 -0
  23. package/src/utils/coverage.ts +630 -0
  24. package/src/utils/cpm.helpers.ts +674 -0
  25. package/src/utils/cpm.ts +907 -0
  26. package/src/utils/cpmLeveling.helpers.ts +564 -0
  27. package/src/utils/cpmLeveling.ts +367 -0
  28. package/src/utils/defaults.ts +8 -0
  29. package/src/utils/eligibility.ts +457 -0
  30. package/src/utils/planCsv.ts +344 -0
  31. package/src/utils/predecessorText.ts +96 -0
  32. package/src/utils/recurrence.ts +616 -0
  33. package/src/utils/request.ts +153 -0
  34. package/src/utils/resource.ts +182 -0
  35. package/src/utils/rule.ts +216 -0
  36. package/src/utils/run.ts +43 -0
  37. package/src/utils/series.ts +161 -0
  38. package/src/utils/slot.ts +208 -0
  39. package/src/utils/workTime.ts +1382 -0
  40. package/tests/coverage.fixtures.ts +111 -0
  41. package/tests/coverage.test.ts +503 -0
  42. package/tests/cpm.bench.test.ts +154 -0
  43. package/tests/cpm.test.ts +354 -0
  44. package/tests/cpmCorrectness.test.ts +327 -0
  45. package/tests/cpmLeveling.test.ts +471 -0
  46. package/tests/eligibility.test.ts +320 -0
  47. package/tests/gantt-geometry.test.ts +367 -0
  48. package/tests/gantt-histogram.test.ts +78 -0
  49. package/tests/gantt-keyboard.test.ts +69 -0
  50. package/tests/helpers/cpmFixtures.ts +101 -0
  51. package/tests/projectInputs.test.ts +165 -0
  52. package/tests/recurrence.test.ts +68 -0
  53. package/tests/request.test.ts +99 -0
  54. package/tests/resource.test.ts +95 -0
  55. package/tests/rule.test.ts +98 -0
  56. package/tests/series.test.ts +120 -0
  57. package/tests/workTime.test.ts +1007 -0
  58. package/tests/workTimeContracts.test.ts +111 -0
  59. package/tsconfig.json +13 -0
  60. package/vitest.config.ts +8 -0
@@ -0,0 +1,719 @@
1
+ import { cn } from '@jsb188/app/utils/string.ts';
2
+ import { useStore } from 'jotai';
3
+ import { DateTime } from 'luxon';
4
+ import {
5
+ memo,
6
+ useCallback,
7
+ useEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ type ReactNode,
12
+ } from 'react';
13
+ import {
14
+ getGanttNonWorkingColumns,
15
+ buildGanttBars,
16
+ buildGanttLinks,
17
+ buildGanttRows,
18
+ buildGanttScale,
19
+ formatGanttDate,
20
+ formatGanttDays,
21
+ getGanttVisibleRange,
22
+ getGanttX,
23
+ GANTT_ROW_HEIGHT,
24
+ type GanttActivityInput,
25
+ type GanttBaselineInput,
26
+ type GanttRelationshipInput,
27
+ type GanttRowObj,
28
+ type GanttWbsInput,
29
+ type GanttZoomEnum,
30
+ type GanttScaleObj,
31
+ } from '../libs/gantt-geometry.ts';
32
+ import {
33
+ createGanttSelectionAtom,
34
+ getGanttSelection,
35
+ } from '../libs/gantt-state.ts';
36
+ import {
37
+ GanttHeaderUI,
38
+ GanttTableHeaderUI,
39
+ GanttTableUI,
40
+ GanttTimelineUI,
41
+ type GanttColumnObj,
42
+ type GanttTableUIProps,
43
+ type GanttTimelineUIProps,
44
+ } from '../ui/GanttUI.tsx';
45
+ import {
46
+ startGanttPointerInteraction,
47
+ type GanttMoveIntent,
48
+ } from './Gantt.helpers.ts';
49
+ import { getWorkCalendarTable } from '../utils/workTime.ts';
50
+ import { handleGanttKeyboardEvent } from '../libs/gantt-keyboard.ts';
51
+ import type {
52
+ ScheduleWorkCalendarDef,
53
+ ScheduleRelationshipTypeEnum,
54
+ } from '../types/schedule.d.ts';
55
+
56
+ export interface GanttProps {
57
+ workCalendar?: ScheduleWorkCalendarDef;
58
+ onDeleteRows?: (ids: string[]) => void;
59
+ onInsertActivity?: () => void;
60
+ onInsertWbs?: () => void;
61
+ onIndentRows?: (ids: string[], outdent: boolean) => void;
62
+ onZoomChange?: (zoom: GanttZoomEnum) => void;
63
+ onFocusSearch?: () => void;
64
+ scrollLeft?: number;
65
+ onViewportChange?: (viewport: {
66
+ scale: GanttScaleObj;
67
+ scrollLeft: number;
68
+ width: number;
69
+ tableWidth: number;
70
+ }) => void;
71
+ className?: string;
72
+ wbsNodes: GanttWbsInput[];
73
+ activities: GanttActivityInput[];
74
+ relationships: GanttRelationshipInput[];
75
+ baselineActivities?: GanttBaselineInput[] | null;
76
+ timeZone: string;
77
+ now: Date;
78
+ dataDateAt?: Date | string | null;
79
+ minutesPerDay: number;
80
+ zoom: GanttZoomEnum;
81
+ selectedRowId?: string | null;
82
+ columnLabels: Record<string, string>;
83
+ columns?: GanttColumnObj[];
84
+ emptyText: string;
85
+ children?: ReactNode;
86
+ editable?: boolean;
87
+ formatters?: {
88
+ duration?: (minutes: number | null, minutesPerDay: number) => string;
89
+ date?: (date: Date | null, timeZone: string) => string;
90
+ majorTick?: (date: Date, zoom: GanttZoomEnum, timeZone: string) => string;
91
+ minorTick?: (date: Date, zoom: GanttZoomEnum, timeZone: string) => string;
92
+ };
93
+ onSelectRow?: (row: GanttRowObj) => void;
94
+ onSelectionChange?: (ids: string[]) => void;
95
+ onEditCell?: GanttTableUIProps['onEditCell'];
96
+ renderCell?: GanttTableUIProps['renderCell'];
97
+ onMoveRows?: GanttTableUIProps['onMoveRows'];
98
+ onMoveActivity?: (row: GanttRowObj, intent: GanttMoveIntent) => void;
99
+ onCreateRelationship?: (
100
+ predecessorId: string,
101
+ successorId: string,
102
+ type: ScheduleRelationshipTypeEnum,
103
+ ) => void;
104
+ }
105
+
106
+ const FILE_CONSTANTS = {
107
+ columns: [
108
+ { key: 'code', width: 76, editor: 'text' },
109
+ { key: 'name', width: 230, editor: 'text' },
110
+ { key: 'duration', width: 64, alignRight: true, editor: 'number' },
111
+ { key: 'start', width: 96, editor: 'date' },
112
+ { key: 'finish', width: 96, editor: 'date' },
113
+ { key: 'float', width: 64, alignRight: true },
114
+ ] as Omit<GanttColumnObj, 'label'>[],
115
+ scrollLeadPx: 120,
116
+ };
117
+
118
+ /* Coordinate geometry, virtualized panes and user intent while the page owns all server mutations. */
119
+ export const Gantt = memo((p: GanttProps) => {
120
+ const store = useStore();
121
+ const selection = useMemo(createGanttSelectionAtom, []);
122
+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});
123
+ const activeCell = useRef({ rowIndex: 0, columnIndex: 1 });
124
+ const pendingFocus = useRef<{ rowId: string; columnKey: string } | null>(
125
+ null,
126
+ );
127
+ const initialSelection = useRef<string | null>(null);
128
+ const cleanupResize = useRef<(() => void) | null>(null);
129
+ const [collapsed, setCollapsed] = useState(() => new Set<string>());
130
+ const [viewport, setViewport] = useState({
131
+ top: 0,
132
+ left: 0,
133
+ height: 600,
134
+ width: 1200,
135
+ });
136
+ const bodyRef = useRef<HTMLDivElement>(null);
137
+ const headerRef = useRef<HTMLDivElement>(null);
138
+ const tableHeaderRef = useRef<HTMLDivElement>(null);
139
+ const tableBodyRef = useRef<HTMLDivElement>(null);
140
+ const anchorRef = useRef<string | null>(null);
141
+ const cleanupDrag = useRef<(() => void) | null>(null);
142
+ const frame = useRef<number | null>(null);
143
+ const latest = useRef(p);
144
+ latest.current = p;
145
+ const columns = useMemo(
146
+ () =>
147
+ (
148
+ p.columns ||
149
+ FILE_CONSTANTS.columns.map((column) => ({
150
+ ...column,
151
+ label: p.columnLabels[column.key] || '',
152
+ }))
153
+ ).map((column) => ({
154
+ ...column,
155
+ width: columnWidths[column.key] || column.width,
156
+ })),
157
+ [p.columns, p.columnLabels, columnWidths],
158
+ );
159
+ const columnsWidth = useMemo(
160
+ () => columns.reduce((sum, column) => sum + column.width, 0),
161
+ [columns],
162
+ );
163
+ const tableWidth = Math.min(
164
+ columnsWidth,
165
+ Math.max(240, Math.floor(viewport.width * 0.6)),
166
+ );
167
+ const rows = useMemo(
168
+ () =>
169
+ buildGanttRows(
170
+ p.wbsNodes,
171
+ p.activities,
172
+ p.baselineActivities || [],
173
+ collapsed,
174
+ ),
175
+ [p.wbsNodes, p.activities, p.baselineActivities, collapsed],
176
+ );
177
+ const scale = useMemo(
178
+ () => buildGanttScale(rows, p.now, p.timeZone, p.zoom, p.formatters),
179
+ [rows, p.now, p.timeZone, p.zoom, p.formatters],
180
+ );
181
+ const nonWorkingColumns = useMemo(
182
+ () =>
183
+ p.workCalendar
184
+ ? getGanttNonWorkingColumns(
185
+ scale,
186
+ getWorkCalendarTable(p.workCalendar, scale.startAt, scale.endAt),
187
+ )
188
+ : [],
189
+ [scale, p.workCalendar],
190
+ );
191
+ const bars = useMemo(() => buildGanttBars(rows, scale), [rows, scale]);
192
+ const links = useMemo(
193
+ () => buildGanttLinks(rows, bars, p.relationships),
194
+ [rows, bars, p.relationships],
195
+ );
196
+ const range = getGanttVisibleRange(
197
+ viewport.top,
198
+ viewport.height,
199
+ rows.length,
200
+ );
201
+ const visibleRowTexts = useMemo(
202
+ () =>
203
+ rows.slice(range.start, range.end).map((row) => ({
204
+ duration:
205
+ row.kind === 'WBS'
206
+ ? ''
207
+ : (p.formatters?.duration || formatGanttDays)(
208
+ row.durationMinutes,
209
+ p.minutesPerDay,
210
+ ),
211
+ start: (p.formatters?.date || formatGanttDate)(row.startAt, p.timeZone),
212
+ finish: (p.formatters?.date || formatGanttDate)(
213
+ row.finishAt,
214
+ p.timeZone,
215
+ ),
216
+ float:
217
+ row.kind === 'WBS'
218
+ ? ''
219
+ : (p.formatters?.duration || formatGanttDays)(
220
+ row.totalFloatMinutes,
221
+ p.minutesPerDay,
222
+ ),
223
+ values: {
224
+ duration: String(row.durationMinutes / p.minutesPerDay),
225
+ start: row.startAt
226
+ ? DateTime.fromJSDate(row.startAt, {
227
+ zone: p.timeZone,
228
+ }).toISODate()!
229
+ : '',
230
+ finish: row.finishAt
231
+ ? DateTime.fromJSDate(row.finishAt, {
232
+ zone: p.timeZone,
233
+ }).toISODate()!
234
+ : '',
235
+ },
236
+ })),
237
+ [rows, range.start, range.end, p.minutesPerDay, p.timeZone, p.formatters],
238
+ );
239
+ const todayX = useMemo(() => getGanttX(scale, p.now), [scale, p.now]);
240
+ const dataDateX = useMemo(() => {
241
+ const value = p.dataDateAt ? new Date(p.dataDateAt) : null;
242
+ return value && Number.isFinite(value.getTime())
243
+ ? getGanttX(scale, value)
244
+ : null;
245
+ }, [scale, p.dataDateAt]);
246
+
247
+ /* Measure the scroll window at most once per animation frame. */
248
+ const measure = useCallback(() => {
249
+ if (frame.current != null) return;
250
+ frame.current = requestAnimationFrame(() => {
251
+ frame.current = null;
252
+ const body = bodyRef.current;
253
+ if (!body) return;
254
+ if (headerRef.current) headerRef.current.scrollLeft = body.scrollLeft;
255
+ setViewport((current) => {
256
+ const next = {
257
+ top: body.scrollTop,
258
+ left: body.scrollLeft,
259
+ height: body.clientHeight,
260
+ width: body.clientWidth,
261
+ };
262
+ return current.top === next.top &&
263
+ current.left === next.left &&
264
+ current.height === next.height &&
265
+ current.width === next.width
266
+ ? current
267
+ : next;
268
+ });
269
+ });
270
+ }, []);
271
+ useEffect(() => {
272
+ const observer =
273
+ typeof ResizeObserver === 'undefined'
274
+ ? null
275
+ : new ResizeObserver(measure);
276
+ if (bodyRef.current) observer?.observe(bodyRef.current);
277
+ measure();
278
+ return () => {
279
+ observer?.disconnect();
280
+ if (frame.current != null) cancelAnimationFrame(frame.current);
281
+ cleanupDrag.current?.();
282
+ cleanupResize.current?.();
283
+ };
284
+ }, [measure, rows.length === 0]);
285
+ useEffect(() => {
286
+ if (p.selectedRowId && !store.get(selection).has(p.selectedRowId))
287
+ store.set(selection, new Set([p.selectedRowId]));
288
+ }, [p.selectedRowId, selection, store]);
289
+ useEffect(() => {
290
+ const body = bodyRef.current;
291
+ if (body) {
292
+ body.scrollLeft = Math.max(
293
+ 0,
294
+ (dataDateX ?? todayX) - FILE_CONSTANTS.scrollLeadPx,
295
+ );
296
+ measure();
297
+ }
298
+ }, [p.zoom]);
299
+
300
+ /* Keep wide table columns scrollable without consuming the timeline's viewport. */
301
+ const syncTableScroll = useCallback(() => {
302
+ if (tableBodyRef.current && tableHeaderRef.current)
303
+ tableBodyRef.current.scrollLeft = tableHeaderRef.current.scrollLeft;
304
+ }, []);
305
+ useEffect(() => {
306
+ const table = tableBodyRef.current;
307
+ /* A horizontal wheel over the table scrolls columns while vertical input keeps scrolling rows. */
308
+ const wheel = (event: WheelEvent) => {
309
+ if (
310
+ !tableHeaderRef.current ||
311
+ columnsWidth <= tableWidth ||
312
+ (!event.shiftKey && Math.abs(event.deltaX) <= Math.abs(event.deltaY))
313
+ )
314
+ return;
315
+ event.preventDefault();
316
+ event.stopPropagation();
317
+ tableHeaderRef.current.scrollLeft += event.shiftKey
318
+ ? event.deltaY || event.deltaX
319
+ : event.deltaX;
320
+ syncTableScroll();
321
+ };
322
+ table?.addEventListener('wheel', wheel, { passive: false });
323
+ return () => table?.removeEventListener('wheel', wheel);
324
+ }, [columnsWidth, tableWidth, syncTableScroll, rows.length === 0]);
325
+
326
+ /* Scroll a keyboard or deep-link target into the virtual window, then focus after React mounts it. */
327
+ const focusCell = useCallback(
328
+ (rowIndex: number, columnIndex: number) => {
329
+ const row = rows[rowIndex];
330
+ const column = columns[columnIndex];
331
+ const body = bodyRef.current;
332
+ if (!row || !column || !body) return;
333
+ if (tableHeaderRef.current) {
334
+ const left = columns
335
+ .slice(0, columnIndex)
336
+ .reduce((sum, item) => sum + item.width, 0);
337
+ if (left < tableHeaderRef.current.scrollLeft)
338
+ tableHeaderRef.current.scrollLeft = left;
339
+ else if (
340
+ left + column.width >
341
+ tableHeaderRef.current.scrollLeft + tableWidth
342
+ )
343
+ tableHeaderRef.current.scrollLeft = left + column.width - tableWidth;
344
+ syncTableScroll();
345
+ }
346
+ activeCell.current = { rowIndex, columnIndex };
347
+ pendingFocus.current = { rowId: row.id, columnKey: column.key };
348
+ const top = rowIndex * GANTT_ROW_HEIGHT;
349
+ if (top < body.scrollTop) body.scrollTop = top;
350
+ else if (top + GANTT_ROW_HEIGHT > body.scrollTop + body.clientHeight)
351
+ body.scrollTop = Math.max(
352
+ 0,
353
+ top + GANTT_ROW_HEIGHT - body.clientHeight,
354
+ );
355
+ const mounted = body.querySelector<HTMLElement>(
356
+ `[data-gantt-row="${CSS.escape(row.id)}"] [data-gantt-column="${CSS.escape(column.key)}"]`,
357
+ );
358
+ if (mounted) {
359
+ mounted.focus({ preventScroll: true });
360
+ pendingFocus.current = null;
361
+ }
362
+ measure();
363
+ },
364
+ [rows, columns, measure, tableWidth, syncTableScroll],
365
+ );
366
+ useEffect(() => {
367
+ const target = pendingFocus.current;
368
+ if (!target) return;
369
+ const cell = bodyRef.current?.querySelector<HTMLElement>(
370
+ `[data-gantt-row="${CSS.escape(target.rowId)}"] [data-gantt-column="${CSS.escape(target.columnKey)}"]`,
371
+ );
372
+ if (cell) {
373
+ cell.focus({ preventScroll: true });
374
+ pendingFocus.current = null;
375
+ }
376
+ }, [range.start, range.end, rows, columns]);
377
+ useEffect(() => {
378
+ if (!p.selectedRowId || initialSelection.current === p.selectedRowId)
379
+ return;
380
+ const index = rows.findIndex((row) => row.id === p.selectedRowId);
381
+ if (index >= 0) {
382
+ initialSelection.current = p.selectedRowId;
383
+ focusCell(index, 1);
384
+ }
385
+ }, [p.selectedRowId, rows]);
386
+ /* Continue a committed editor move across rows that may not yet be mounted. */
387
+ const navigateCell = useCallback(
388
+ (
389
+ rowId: string,
390
+ columnKey: string,
391
+ direction: number,
392
+ vertical: boolean,
393
+ ) => {
394
+ let rowIndex = rows.findIndex((row) => row.id === rowId);
395
+ let columnIndex = columns.findIndex((column) => column.key === columnKey);
396
+ if (vertical) rowIndex += direction;
397
+ else {
398
+ columnIndex += direction;
399
+ if (columnIndex < 0) {
400
+ columnIndex = columns.length - 1;
401
+ rowIndex -= 1;
402
+ }
403
+ if (columnIndex >= columns.length) {
404
+ columnIndex = 0;
405
+ rowIndex += 1;
406
+ }
407
+ }
408
+ focusCell(Math.max(0, Math.min(rows.length - 1, rowIndex)), columnIndex);
409
+ },
410
+ [rows, columns, focusCell],
411
+ );
412
+ /* Resize only the chosen column and remove global pointer listeners after the gesture. */
413
+ const resizeColumn = (
414
+ event: React.PointerEvent<HTMLDivElement>,
415
+ column: GanttColumnObj,
416
+ ) => {
417
+ event.preventDefault();
418
+ cleanupResize.current?.();
419
+ const initialX = event.clientX;
420
+ /* Apply the bounded width while preserving every other column. */
421
+ const move = (next: PointerEvent) =>
422
+ setColumnWidths((current) => ({
423
+ ...current,
424
+ [column.key]: Math.max(
425
+ 40,
426
+ Math.min(800, column.width + next.clientX - initialX),
427
+ ),
428
+ }));
429
+ /* Finish or cancel a header resize without leaving window listeners active. */
430
+ const finish = () => {
431
+ window.removeEventListener('pointermove', move);
432
+ window.removeEventListener('pointerup', finish);
433
+ window.removeEventListener('pointercancel', finish);
434
+ cleanupResize.current = null;
435
+ };
436
+ cleanupResize.current = finish;
437
+ window.addEventListener('pointermove', move);
438
+ window.addEventListener('pointerup', finish);
439
+ window.addEventListener('pointercancel', finish);
440
+ };
441
+ /* Keep range/additive selection in a per-chart atom so unrelated rows do not subscribe to it. */
442
+ const selectRow = useCallback<NonNullable<GanttTableUIProps['onSelectRow']>>(
443
+ (row, event) => {
444
+ const next = getGanttSelection(
445
+ store.get(selection),
446
+ rows,
447
+ row.id,
448
+ anchorRef.current,
449
+ event.metaKey || event.ctrlKey,
450
+ event.shiftKey,
451
+ );
452
+ store.set(selection, next);
453
+ if (!event.shiftKey) anchorRef.current = row.id;
454
+ latest.current.onSelectRow?.(row);
455
+ latest.current.onSelectionChange?.([...next]);
456
+ },
457
+ [rows, store, selection],
458
+ );
459
+ /* Collapse a WBS heading without discarding the selected activities in other branches. */
460
+ const toggleCollapse = useCallback((id: string) => {
461
+ setCollapsed((current) => {
462
+ const next = new Set(current);
463
+ if (next.has(id)) next.delete(id);
464
+ else next.add(id);
465
+ return next;
466
+ });
467
+ }, []);
468
+ /* Interpret all bar and connector gestures through one cancellable pointer lifecycle. */
469
+ const barPointerDown = useCallback<
470
+ NonNullable<GanttTimelineUIProps['onBarPointerDown']>
471
+ >(
472
+ (event, row, bar, kind) => {
473
+ const body = bodyRef.current;
474
+ if (!body) return;
475
+ if (
476
+ kind.startsWith('LINK')
477
+ ? !latest.current.onCreateRelationship
478
+ : !latest.current.onMoveActivity
479
+ )
480
+ return;
481
+ cleanupDrag.current?.();
482
+ cleanupDrag.current = startGanttPointerInteraction({
483
+ event,
484
+ row,
485
+ bar,
486
+ kind,
487
+ body,
488
+ scale,
489
+ tableWidth,
490
+ onMove: latest.current.onMoveActivity,
491
+ onLink: latest.current.onCreateRelationship,
492
+ });
493
+ },
494
+ [scale, tableWidth],
495
+ );
496
+ /* Reorder all selected activities together when a selected row is dragged. */
497
+ const moveRows = useCallback<NonNullable<GanttTableUIProps['onMoveRows']>>(
498
+ (ids, wbsId, afterActivityId) => {
499
+ const selected = store.get(selection);
500
+ latest.current.onMoveRows?.(
501
+ ids.some((id) => selected.has(id)) ? [...selected] : ids,
502
+ wbsId,
503
+ afterActivityId,
504
+ );
505
+ },
506
+ [store, selection],
507
+ );
508
+ /* Dispatch navigation and command keys centrally so virtualized rows share one keyboard contract. */
509
+ const keyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
510
+ const target = event.target as HTMLElement;
511
+ if (target.closest('input,textarea,select,button,[contenteditable="true"]'))
512
+ return;
513
+ const rowId =
514
+ target.closest<HTMLElement>('[data-gantt-row]')?.dataset.ganttRow;
515
+ const columnKey = target.closest<HTMLElement>('[data-gantt-column]')
516
+ ?.dataset.ganttColumn;
517
+ const rowIndex = rowId
518
+ ? rows.findIndex((row) => row.id === rowId)
519
+ : Math.min(activeCell.current.rowIndex, rows.length - 1);
520
+ const columnIndex = columnKey
521
+ ? columns.findIndex((column) => column.key === columnKey)
522
+ : activeCell.current.columnIndex;
523
+ const row = rows[rowIndex];
524
+ const action = handleGanttKeyboardEvent(event, {
525
+ rowIndex,
526
+ rowCount: rows.length,
527
+ columnIndex,
528
+ columnCount: columns.length,
529
+ pageSize: Math.max(1, Math.floor(viewport.height / GANTT_ROW_HEIGHT)),
530
+ isWbs: row?.kind === 'WBS',
531
+ editable: !!p.editable,
532
+ zoom: p.zoom,
533
+ });
534
+ if (!action) return;
535
+ if (action.kind === 'EDIT') {
536
+ if (event.target === bodyRef.current && row) {
537
+ event.preventDefault();
538
+ focusCell(rowIndex, columnIndex);
539
+ document.activeElement?.dispatchEvent(
540
+ new MouseEvent('dblclick', { bubbles: true }),
541
+ );
542
+ }
543
+ return;
544
+ }
545
+ event.preventDefault();
546
+ const ids = [...store.get(selection)];
547
+ switch (action.kind) {
548
+ case 'MOVE': {
549
+ const next = rows[action.rowIndex];
550
+ focusCell(action.rowIndex, action.columnIndex);
551
+ if (next) {
552
+ const selected = getGanttSelection(
553
+ store.get(selection),
554
+ rows,
555
+ next.id,
556
+ anchorRef.current,
557
+ false,
558
+ action.extend,
559
+ );
560
+ store.set(selection, selected);
561
+ if (!action.extend) anchorRef.current = next.id;
562
+ latest.current.onSelectionChange?.([...selected]);
563
+ latest.current.onSelectRow?.(next);
564
+ }
565
+ break;
566
+ }
567
+ case 'ESCAPE':
568
+ cleanupDrag.current?.();
569
+ if (row) {
570
+ store.set(selection, new Set([row.id]));
571
+ latest.current.onSelectionChange?.([row.id]);
572
+ }
573
+ break;
574
+ case 'COLLAPSE':
575
+ if (row?.kind === 'WBS') toggleCollapse(row.id);
576
+ break;
577
+ case 'DELETE':
578
+ latest.current.onDeleteRows?.(ids.length ? ids : row ? [row.id] : []);
579
+ break;
580
+ case 'INSERT':
581
+ if (action.wbs) latest.current.onInsertWbs?.();
582
+ else latest.current.onInsertActivity?.();
583
+ break;
584
+ case 'INDENT':
585
+ latest.current.onIndentRows?.(
586
+ ids.length ? ids : row ? [row.id] : [],
587
+ action.outdent,
588
+ );
589
+ break;
590
+ case 'ZOOM':
591
+ latest.current.onZoomChange?.(action.zoom);
592
+ break;
593
+ case 'SEARCH':
594
+ latest.current.onFocusSearch?.();
595
+ break;
596
+ }
597
+ };
598
+ const timelineWidth = Math.max(0, viewport.width - tableWidth);
599
+ useEffect(() => {
600
+ latest.current.onViewportChange?.({
601
+ scale,
602
+ scrollLeft: viewport.left,
603
+ width: timelineWidth,
604
+ tableWidth,
605
+ });
606
+ }, [scale, viewport.left, timelineWidth, tableWidth]);
607
+ useEffect(() => {
608
+ if (
609
+ bodyRef.current &&
610
+ p.scrollLeft !== undefined &&
611
+ Math.abs(bodyRef.current.scrollLeft - p.scrollLeft) > 1
612
+ ) {
613
+ bodyRef.current.scrollLeft = p.scrollLeft;
614
+ measure();
615
+ }
616
+ }, [p.scrollLeft, measure]);
617
+ return (
618
+ <div className={cn('v_stretch of', p.className)}>
619
+ {p.children}
620
+ {!rows.length ? (
621
+ <div className="f h_0 v_center a_c">
622
+ <span className="ft_sm cl_lt">{p.emptyText}</span>
623
+ </div>
624
+ ) : (
625
+ <>
626
+ <div
627
+ className="no_shrink h_item bd_b_1 bd_b_bd"
628
+ style={{ alignItems: 'stretch' }}
629
+ >
630
+ <div
631
+ ref={tableHeaderRef}
632
+ data-gantt-columns-scroll
633
+ className="no_shrink of auto_x app_scr bd_r_1 bd_r_bd"
634
+ onScroll={syncTableScroll}
635
+ style={{ width: tableWidth }}
636
+ >
637
+ <GanttTableHeaderUI
638
+ columns={columns}
639
+ onResize={resizeColumn}
640
+ />
641
+ </div>
642
+ <div
643
+ ref={headerRef}
644
+ className="f of"
645
+ >
646
+ <GanttHeaderUI
647
+ scale={scale}
648
+ left={viewport.left}
649
+ width={timelineWidth}
650
+ />
651
+ </div>
652
+ </div>
653
+ <div
654
+ ref={bodyRef}
655
+ data-gantt-scroll
656
+ data-gantt-grid
657
+ role="grid"
658
+ tabIndex={0}
659
+ onKeyDown={keyDown}
660
+ aria-rowcount={rows.length + 1}
661
+ aria-colcount={columns.length}
662
+ className="f h_0 of auto_x auto_y app_scr"
663
+ onScroll={measure}
664
+ >
665
+ <div
666
+ className="h_item"
667
+ style={{
668
+ alignItems: 'flex-start',
669
+ width: tableWidth + scale.totalWidth,
670
+ minHeight: rows.length * GANTT_ROW_HEIGHT,
671
+ }}
672
+ >
673
+ <div
674
+ ref={tableBodyRef}
675
+ className="no_shrink sticky of bg bd_r_1 bd_r_bd"
676
+ style={{ left: 0, zIndex: 10, width: tableWidth }}
677
+ >
678
+ <GanttTableUI
679
+ rows={rows}
680
+ visibleRowTexts={visibleRowTexts}
681
+ columns={columns}
682
+ selection={selection}
683
+ visibleStart={range.start}
684
+ visibleEnd={range.end}
685
+ editable={p.editable}
686
+ onSelectRow={selectRow}
687
+ onToggleCollapse={toggleCollapse}
688
+ onEditCell={p.onEditCell}
689
+ onNavigate={navigateCell}
690
+ renderCell={p.renderCell}
691
+ onMoveRows={p.onMoveRows ? moveRows : undefined}
692
+ />
693
+ </div>
694
+ <GanttTimelineUI
695
+ nonWorkingColumns={nonWorkingColumns}
696
+ rows={rows}
697
+ bars={bars}
698
+ links={links}
699
+ scale={scale}
700
+ selection={selection}
701
+ visibleStart={range.start}
702
+ visibleEnd={range.end}
703
+ left={viewport.left}
704
+ width={timelineWidth}
705
+ todayX={todayX}
706
+ dataDateX={dataDateX}
707
+ editable={p.editable}
708
+ onSelectRow={selectRow}
709
+ onBarPointerDown={barPointerDown}
710
+ />
711
+ </div>
712
+ </div>
713
+ </>
714
+ )}
715
+ </div>
716
+ );
717
+ });
718
+
719
+ Gantt.displayName = 'Gantt';