@vmscloud/moz-ui-gantt-core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { createInput, createButton } from "@vmscloud/moz-ui-components-core";
4
+ import { createTooltip, createContextMenu, createInput, createButton } from "@vmscloud/moz-ui-components-core";
5
5
  function categoryFieldOf(f) {
6
6
  return f.kind === "category" ? f.field : null;
7
7
  }
@@ -410,7 +410,13 @@ ${samples}
410
410
  this.cellSlotOrder.set(id, i);
411
411
  }
412
412
  }
413
- if (groupsChanged) this.orderedLeafGroupIds = this.sortLeafGroups(rowFields);
413
+ const sortFields = new Set(rowFields.flatMap((field) => field.sortField ? [field.sortField] : []));
414
+ const sortChanged = sortFields.size > 0 && (changes.added.length > 0 || changes.removed.length > 0 || changes.updated.some((update) => update.changedFields.some((field) => sortFields.has(field) || rowFields.some((def) => def.field === field))));
415
+ if (groupsChanged || sortChanged) {
416
+ const ordered = this.sortLeafGroups(rowFields);
417
+ if (ordered.some((id, index) => id !== this.orderedLeafGroupIds[index])) membershipChanged = true;
418
+ this.orderedLeafGroupIds = ordered;
419
+ }
414
420
  return { affectedLeaves, membershipChanged };
415
421
  }
416
422
  /**
@@ -556,6 +562,18 @@ ${samples}
556
562
  // --------------------------------------------------------------------------
557
563
  sortLeafGroups(rowFieldDefs) {
558
564
  const keys = [...this.logicalLeafGroups.keys()];
565
+ const representatives = rowFieldDefs.map((def) => def.sortField ? /* @__PURE__ */ new Map() : null);
566
+ for (let i = 0; i < rowFieldDefs.length; i++) {
567
+ const values = representatives[i], field = rowFieldDefs[i].sortField;
568
+ if (!values || !field) continue;
569
+ for (const group of this.logicalLeafGroups.values()) {
570
+ const prefix = pathKey(group.rowPath.slice(0, i + 1));
571
+ for (const row of group.sourceRows) {
572
+ const value = this.getEffectiveRow(row)[field] ?? null;
573
+ if (!values.has(prefix) || compareSortValues(value, values.get(prefix)) < 0) values.set(prefix, value);
574
+ }
575
+ }
576
+ }
559
577
  keys.sort((a, b) => {
560
578
  const ga = this.logicalLeafGroups.get(a);
561
579
  const gb = this.logicalLeafGroups.get(b);
@@ -563,7 +581,9 @@ ${samples}
563
581
  const def = rowFieldDefs[i];
564
582
  const va = ga.rowPath[i] ?? null;
565
583
  const vb = gb.rowPath[i] ?? null;
566
- const cmp = compareCellValues(va, vb);
584
+ const values = representatives[i];
585
+ const keyCompare = values ? compareSortValues(values.get(pathKey(ga.rowPath.slice(0, i + 1))), values.get(pathKey(gb.rowPath.slice(0, i + 1)))) : 0;
586
+ const cmp = keyCompare || compareCellValues(va, vb);
567
587
  if (cmp !== 0) return def.sort === "desc" ? -cmp : cmp;
568
588
  }
569
589
  return 0;
@@ -738,6 +758,14 @@ function compareCellValues(a, b) {
738
758
  if (typeof a === "number" && typeof b === "number") return a - b;
739
759
  return String(a).localeCompare(String(b));
740
760
  }
761
+ function compareSortValues(a, b) {
762
+ if (a === b || a == null && b == null) return 0;
763
+ const rank = (value) => value == null ? 0 : typeof value === "number" ? 1 : typeof value === "string" ? 2 : 3;
764
+ const typeOrder = rank(a) - rank(b);
765
+ if (typeOrder) return typeOrder;
766
+ if (typeof a === "number" && typeof b === "number") return a - b;
767
+ return a < b ? -1 : 1;
768
+ }
741
769
  function lowerBoundExclusive(prefix, target) {
742
770
  let lo = 0;
743
771
  let hi = prefix.length - 1;
@@ -1033,7 +1061,7 @@ class RowAxis {
1033
1061
  expandLeaf(group, logicalColLeaves, policy) {
1034
1062
  switch (policy.kind) {
1035
1063
  case "collapse":
1036
- return this.expandCollapse(group, policy.rowHeight ?? DEFAULT_ROW_HEIGHT);
1064
+ return this.expandCollapse(group, policy.rowHeight ?? DEFAULT_ROW_HEIGHT, policy.levelField);
1037
1065
  case "explode":
1038
1066
  return this.expandExplode(
1039
1067
  group,
@@ -1048,7 +1076,12 @@ class RowAxis {
1048
1076
  }
1049
1077
  }
1050
1078
  }
1051
- expandCollapse(group, height) {
1079
+ expandCollapse(group, height, levelField) {
1080
+ let levels = 1;
1081
+ if (levelField) for (const rows of group.sourceRowsByCol.values()) for (const row of rows) {
1082
+ const level = row[levelField];
1083
+ if (typeof level === "number" && Number.isInteger(level) && level >= 1 && level <= 100) levels = Math.max(levels, level);
1084
+ }
1052
1085
  return [
1053
1086
  {
1054
1087
  id: `${group.nodeId}#0`,
@@ -1057,7 +1090,7 @@ class RowAxis {
1057
1090
  slotIndex: 0,
1058
1091
  top: 0,
1059
1092
  // recalcPrefix에서 갱신
1060
- height,
1093
+ height: height * levels,
1061
1094
  cell: { kind: "collapse", sourceRowsByCol: group.sourceRowsByCol },
1062
1095
  type: "data"
1063
1096
  }
@@ -1302,28 +1335,120 @@ function eqCellValue(a, b) {
1302
1335
  if (a == null && b == null) return true;
1303
1336
  return false;
1304
1337
  }
1338
+ const formatters = /* @__PURE__ */ new Map();
1339
+ const DAY$1 = 864e5;
1340
+ const offsetCache = /* @__PURE__ */ new Map();
1341
+ function formatter(timeZone) {
1342
+ let value = formatters.get(timeZone);
1343
+ if (!value) {
1344
+ value = new Intl.DateTimeFormat("en-GB-u-ca-gregory-nu-latn", {
1345
+ timeZone,
1346
+ year: "numeric",
1347
+ month: "2-digit",
1348
+ day: "2-digit",
1349
+ era: "short",
1350
+ hour: "2-digit",
1351
+ minute: "2-digit",
1352
+ second: "2-digit",
1353
+ fractionalSecondDigits: 3,
1354
+ hourCycle: "h23"
1355
+ });
1356
+ if (formatters.size >= 64) formatters.delete(formatters.keys().next().value);
1357
+ formatters.set(timeZone, value);
1358
+ }
1359
+ return value;
1360
+ }
1361
+ function validateTimeZone(timeZone) {
1362
+ if (timeZone === void 0) return;
1363
+ if (typeof timeZone !== "string" || !timeZone || timeZone.length > 100) throw new RangeError("Invalid Gantt timeZone");
1364
+ try {
1365
+ formatter(timeZone);
1366
+ } catch {
1367
+ throw new RangeError(`Invalid Gantt timeZone: ${timeZone}`);
1368
+ }
1369
+ }
1370
+ function wallTime(ms, timeZone = "UTC") {
1371
+ if (timeZone === "UTC") return ms;
1372
+ const parts = formatter(timeZone).formatToParts(ms);
1373
+ const values = {};
1374
+ for (const part of parts) values[part.type] = part.value;
1375
+ const date = /* @__PURE__ */ new Date(0);
1376
+ date.setUTCFullYear(values.era === "BC" ? 1 - Number(values.year) : Number(values.year), Number(values.month) - 1, Number(values.day));
1377
+ date.setUTCHours(Number(values.hour), Number(values.minute), Number(values.second), Number(values.fractionalSecond));
1378
+ return date.getTime();
1379
+ }
1380
+ function wallTimeCandidates(localMs, timeZone = "UTC") {
1381
+ if (timeZone === "UTC") return [localMs];
1382
+ const day = Math.floor(localMs / DAY$1) * DAY$1, key = `${timeZone}:${day}`;
1383
+ let offsets = offsetCache.get(key);
1384
+ if (!offsets) {
1385
+ const found = /* @__PURE__ */ new Set();
1386
+ for (const distance of [-2, -1, 0, 1, 2, 3]) {
1387
+ const probe = day + distance * DAY$1;
1388
+ found.add(wallTime(probe, timeZone) - probe);
1389
+ }
1390
+ offsets = [...found];
1391
+ if (offsetCache.size >= 512) offsetCache.delete(offsetCache.keys().next().value);
1392
+ offsetCache.set(key, offsets);
1393
+ }
1394
+ const candidates = [...offsets].map((offset) => localMs - offset).sort((a, b) => a - b);
1395
+ const exact = candidates.filter((candidate) => wallTime(candidate, timeZone) === localMs);
1396
+ if (exact.length) return exact;
1397
+ const after = candidates.map((value) => ({ value, delta: wallTime(value, timeZone) - localMs })).filter((item) => item.delta > 0).sort((a, b) => a.delta - b.delta);
1398
+ if (after[0]) return [after[0].value];
1399
+ throw new RangeError("Invalid Gantt local time boundary");
1400
+ }
1401
+ function fromWallTime(localMs, timeZone = "UTC") {
1402
+ return wallTimeCandidates(localMs, timeZone)[0];
1403
+ }
1404
+ function localDayPeriods(localDay, timeZone = "UTC") {
1405
+ if (timeZone === "UTC") return [{ startMs: localDay, endMs: localDay + DAY$1, offset: 0 }];
1406
+ const start = fromWallTime(localDay, timeZone), end = fromWallTime(localDay + DAY$1, timeZone);
1407
+ const result = [];
1408
+ let cursor = start, offset = wallTime(start, timeZone) - start, probe = start;
1409
+ while (probe < end) {
1410
+ const right = Math.min(end - 1, probe + 6 * 36e5);
1411
+ const nextOffset = wallTime(right, timeZone) - right;
1412
+ if (nextOffset !== offset) {
1413
+ let low = probe, high = right;
1414
+ while (high - low > 1) {
1415
+ const mid = Math.floor((low + high) / 2);
1416
+ if (wallTime(mid, timeZone) - mid === offset) low = mid;
1417
+ else high = mid;
1418
+ }
1419
+ result.push({ startMs: cursor, endMs: high, offset });
1420
+ cursor = high;
1421
+ offset = nextOffset;
1422
+ }
1423
+ if (right === end - 1) break;
1424
+ probe = right;
1425
+ }
1426
+ if (cursor < end) result.push({ startMs: cursor, endMs: end, offset });
1427
+ return result;
1428
+ }
1305
1429
  const HOUR_MS = 60 * 60 * 1e3;
1306
1430
  const DAY_MS = 24 * HOUR_MS;
1307
1431
  const WEEK_MS = 7 * DAY_MS;
1308
- function enumerateTicks(range, unit) {
1309
- const start = floorTo(range.startMs, unit);
1310
- const end = ceilTo(range.endMs, unit);
1432
+ function enumerateTicks(range, unit, calendar, timeZone = "UTC") {
1433
+ const start = floorTo(range.startMs, unit, calendar, timeZone);
1434
+ const end = ceilTo(range.endMs, unit, calendar, timeZone);
1311
1435
  const out = [];
1312
1436
  let cur = start;
1313
1437
  let safety = 0;
1314
1438
  while (cur < end) {
1315
- const next = advance(cur, unit, 1);
1316
- out.push({ startMs: cur, endMs: next, label: defaultFormat(cur, unit) });
1439
+ const next = advance(cur, unit, 1, calendar, timeZone);
1440
+ if (!Number.isFinite(next) || next <= cur) throw new RangeError("Invalid time tick boundary");
1441
+ out.push({ startMs: cur, endMs: next, label: defaultFormat(cur, unit, timeZone) });
1317
1442
  cur = next;
1318
- if (++safety > 1e6) throw new Error("[enumerateTicks] safety break — too many ticks");
1443
+ if (++safety > 1e5) throw new RangeError("Gantt time axis tick columns exceed limit 100000 (100,000 ticks); use a coarser unit or smaller range");
1319
1444
  }
1320
1445
  return out;
1321
1446
  }
1322
- function groupByUnit(leaves, parentUnit) {
1447
+ function groupByUnit(leaves, parentUnit, calendar, timeZone = "UTC") {
1323
1448
  const out = [];
1324
1449
  if (leaves.length === 0) return out;
1325
- let groupStart = floorTo(leaves[0].startMs, parentUnit);
1326
- let groupEnd = advance(groupStart, parentUnit, 1);
1450
+ let groupStart = floorTo(leaves[0].startMs, parentUnit, calendar, timeZone);
1451
+ let groupEnd = advance(groupStart, parentUnit, 1, calendar, timeZone);
1327
1452
  let firstIdx = 0;
1328
1453
  for (let i = 0; i < leaves.length; i++) {
1329
1454
  const leaf = leaves[i];
@@ -1333,10 +1458,10 @@ function groupByUnit(leaves, parentUnit) {
1333
1458
  endMs: groupEnd,
1334
1459
  firstLeafIndex: firstIdx,
1335
1460
  leafCount: i - firstIdx,
1336
- label: defaultFormat(groupStart, parentUnit)
1461
+ label: defaultFormat(groupStart, parentUnit, timeZone)
1337
1462
  });
1338
- groupStart = floorTo(leaf.startMs, parentUnit);
1339
- groupEnd = advance(groupStart, parentUnit, 1);
1463
+ groupStart = floorTo(leaf.startMs, parentUnit, calendar, timeZone);
1464
+ groupEnd = advance(groupStart, parentUnit, 1, calendar, timeZone);
1340
1465
  firstIdx = i;
1341
1466
  }
1342
1467
  }
@@ -1345,12 +1470,36 @@ function groupByUnit(leaves, parentUnit) {
1345
1470
  endMs: groupEnd,
1346
1471
  firstLeafIndex: firstIdx,
1347
1472
  leafCount: leaves.length - firstIdx,
1348
- label: defaultFormat(groupStart, parentUnit)
1473
+ label: defaultFormat(groupStart, parentUnit, timeZone)
1349
1474
  });
1350
1475
  return out;
1351
1476
  }
1352
- function floorTo(ms, unit) {
1477
+ function floorTo(ms, unit, calendar, timeZone = "UTC") {
1478
+ if (timeZone !== "UTC") {
1479
+ let local = floorTo(wallTime(ms, timeZone), unit, calendar);
1480
+ for (let attempts = 0; attempts < 1e5; attempts++) {
1481
+ const candidates = wallTimeCandidates(local, timeZone).filter((value) => value <= ms);
1482
+ if (candidates.length) return unit === "minute" || unit === "hour" ? candidates[candidates.length - 1] : candidates[0];
1483
+ const previous = advance(local, unit, -1, calendar);
1484
+ if (!Number.isFinite(previous) || previous >= local) break;
1485
+ local = previous;
1486
+ }
1487
+ throw new RangeError("Invalid Gantt time tick boundary");
1488
+ }
1489
+ const offset = ["day", "week", "month", "quarter", "year"].includes(unit) ? ((calendar == null ? void 0 : calendar.dayStartHour) ?? 0) * HOUR_MS : 0;
1490
+ if (offset) return floorTo(ms - offset, unit) + offset;
1353
1491
  switch (unit) {
1492
+ case "minute":
1493
+ return Math.floor(ms / 6e4) * 6e4;
1494
+ case "oneThirdHour":
1495
+ return Math.floor(ms / (8 * HOUR_MS)) * 8 * HOUR_MS;
1496
+ case "shift": {
1497
+ const shifts = (calendar == null ? void 0 : calendar.shiftHours) ?? [6, 14, 22];
1498
+ const day = Math.floor(ms / DAY_MS) * DAY_MS;
1499
+ const hour = (ms - day) / HOUR_MS;
1500
+ for (let i = shifts.length - 1; i >= 0; i--) if (hour >= shifts[i]) return day + shifts[i] * HOUR_MS;
1501
+ return day - DAY_MS + shifts[shifts.length - 1] * HOUR_MS;
1502
+ }
1354
1503
  case "hour":
1355
1504
  return Math.floor(ms / HOUR_MS) * HOUR_MS;
1356
1505
  case "day":
@@ -1362,51 +1511,103 @@ function floorTo(ms, unit) {
1362
1511
  const date = new Date(ms);
1363
1512
  return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
1364
1513
  }
1514
+ case "quarter": {
1515
+ const date = new Date(ms);
1516
+ return Date.UTC(date.getUTCFullYear(), Math.floor(date.getUTCMonth() / 3) * 3, 1);
1517
+ }
1365
1518
  case "year": {
1366
1519
  const date = new Date(ms);
1367
1520
  return Date.UTC(date.getUTCFullYear(), 0, 1);
1368
1521
  }
1369
1522
  }
1370
1523
  }
1371
- function ceilTo(ms, unit) {
1372
- const f = floorTo(ms, unit);
1373
- return f === ms ? ms : advance(f, unit, 1);
1524
+ function ceilTo(ms, unit, calendar, timeZone = "UTC") {
1525
+ const f = floorTo(ms, unit, calendar, timeZone);
1526
+ return f === ms ? ms : advance(f, unit, 1, calendar, timeZone);
1374
1527
  }
1375
- function advance(ms, unit, step) {
1528
+ function advance(ms, unit, step, calendar, timeZone = "UTC") {
1529
+ if (timeZone !== "UTC") {
1530
+ if (!Number.isInteger(step)) throw new RangeError("Time step must be an integer");
1531
+ const direction = Math.sign(step);
1532
+ let current = ms;
1533
+ for (let i = 0; i < Math.abs(step); i++) {
1534
+ const local = wallTime(current, timeZone);
1535
+ const boundary = floorTo(local, unit, calendar);
1536
+ let target = advance(boundary, unit, direction, calendar);
1537
+ let next;
1538
+ for (let attempts = 0; attempts < 1e5; attempts++) {
1539
+ const candidates = wallTimeCandidates(target, timeZone);
1540
+ if (unit === "minute" || unit === "hour") {
1541
+ candidates.push(...wallTimeCandidates(boundary, timeZone));
1542
+ const elapsed = current + direction * (unit === "minute" ? 6e4 : HOUR_MS);
1543
+ if (floorTo(elapsed, unit, calendar, timeZone) === elapsed) candidates.push(elapsed);
1544
+ }
1545
+ next = candidates.filter((value) => direction > 0 ? value > current : value < current).sort((a, b) => direction * (a - b))[0];
1546
+ if (next !== void 0) break;
1547
+ const following = advance(target, unit, direction, calendar);
1548
+ if (!Number.isFinite(following) || direction * (following - target) <= 0) break;
1549
+ target = following;
1550
+ }
1551
+ if (next === void 0) throw new RangeError("Invalid Gantt time tick boundary");
1552
+ current = next;
1553
+ }
1554
+ return current;
1555
+ }
1376
1556
  switch (unit) {
1557
+ case "minute":
1558
+ return ms + step * 6e4;
1559
+ case "oneThirdHour":
1560
+ return ms + step * 8 * HOUR_MS;
1561
+ case "shift": {
1562
+ const shifts = (calendar == null ? void 0 : calendar.shiftHours) ?? [6, 14, 22];
1563
+ const start = floorTo(ms, unit, calendar);
1564
+ const day = Math.floor(start / DAY_MS) * DAY_MS;
1565
+ const index = shifts.indexOf((start - day) / HOUR_MS) + step;
1566
+ const dayOffset = Math.floor(index / shifts.length);
1567
+ return day + dayOffset * DAY_MS + shifts[(index % shifts.length + shifts.length) % shifts.length] * HOUR_MS;
1568
+ }
1377
1569
  case "hour":
1378
1570
  return ms + step * HOUR_MS;
1379
1571
  case "day":
1380
1572
  return ms + step * DAY_MS;
1381
1573
  case "week":
1382
1574
  return ms + step * WEEK_MS;
1575
+ case "quarter":
1383
1576
  case "month": {
1384
- const d = new Date(ms);
1577
+ const offset = ((calendar == null ? void 0 : calendar.dayStartHour) ?? 0) * HOUR_MS;
1578
+ const d = new Date(ms - offset);
1385
1579
  return Date.UTC(
1386
1580
  d.getUTCFullYear(),
1387
- d.getUTCMonth() + step,
1581
+ d.getUTCMonth() + step * (unit === "quarter" ? 3 : 1),
1388
1582
  d.getUTCDate(),
1389
1583
  d.getUTCHours(),
1390
1584
  d.getUTCMinutes(),
1391
- d.getUTCSeconds()
1392
- );
1585
+ d.getUTCSeconds(),
1586
+ d.getUTCMilliseconds()
1587
+ ) + offset;
1393
1588
  }
1394
1589
  case "year": {
1395
- const d = new Date(ms);
1590
+ const offset = ((calendar == null ? void 0 : calendar.dayStartHour) ?? 0) * HOUR_MS;
1591
+ const d = new Date(ms - offset);
1396
1592
  return Date.UTC(
1397
1593
  d.getUTCFullYear() + step,
1398
1594
  d.getUTCMonth(),
1399
1595
  d.getUTCDate(),
1400
1596
  d.getUTCHours(),
1401
1597
  d.getUTCMinutes(),
1402
- d.getUTCSeconds()
1403
- );
1598
+ d.getUTCSeconds(),
1599
+ d.getUTCMilliseconds()
1600
+ ) + offset;
1404
1601
  }
1405
1602
  }
1406
1603
  }
1407
- function defaultFormat(ms, unit) {
1408
- const d = new Date(ms);
1604
+ function defaultFormat(ms, unit, timeZone = "UTC") {
1605
+ const d = new Date(wallTime(ms, timeZone));
1409
1606
  switch (unit) {
1607
+ case "minute":
1608
+ return `${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}`;
1609
+ case "shift":
1610
+ case "oneThirdHour":
1410
1611
  case "hour":
1411
1612
  return String(d.getUTCHours()).padStart(2, "0");
1412
1613
  case "day":
@@ -1415,6 +1616,8 @@ function defaultFormat(ms, unit) {
1415
1616
  return `W${getISOWeekNumber(d)}`;
1416
1617
  case "month":
1417
1618
  return `${d.getUTCMonth() + 1}월`;
1619
+ case "quarter":
1620
+ return `Q${Math.floor(d.getUTCMonth() / 3) + 1}`;
1418
1621
  case "year":
1419
1622
  return String(d.getUTCFullYear());
1420
1623
  }
@@ -1430,6 +1633,11 @@ function getISOWeekNumber(d) {
1430
1633
  }
1431
1634
  function unitMsAvg(unit) {
1432
1635
  switch (unit) {
1636
+ case "minute":
1637
+ return 6e4;
1638
+ case "shift":
1639
+ case "oneThirdHour":
1640
+ return 8 * HOUR_MS;
1433
1641
  case "hour":
1434
1642
  return HOUR_MS;
1435
1643
  case "day":
@@ -1439,12 +1647,21 @@ function unitMsAvg(unit) {
1439
1647
  case "month":
1440
1648
  return 30.4375 * DAY_MS;
1441
1649
  // 365.25 / 12
1650
+ case "quarter":
1651
+ return 91.3125 * DAY_MS;
1442
1652
  case "year":
1443
1653
  return 365.25 * DAY_MS;
1444
1654
  }
1445
1655
  }
1656
+ const UNIT_ORDER = ["year", "quarter", "month", "week", "day", "shift", "oneThirdHour", "hour", "minute"];
1446
1657
  function deriveHierarchy(unit) {
1447
1658
  switch (unit) {
1659
+ case "minute":
1660
+ return ["day", "hour", "minute"];
1661
+ case "shift":
1662
+ return ["month", "day", "shift"];
1663
+ case "oneThirdHour":
1664
+ return ["month", "day", "oneThirdHour"];
1448
1665
  case "hour":
1449
1666
  return ["month", "day", "hour"];
1450
1667
  case "day":
@@ -1453,11 +1670,169 @@ function deriveHierarchy(unit) {
1453
1670
  return ["year", "month", "week"];
1454
1671
  case "month":
1455
1672
  return ["year", "month"];
1673
+ case "quarter":
1674
+ return ["year", "quarter"];
1456
1675
  case "year":
1457
1676
  return ["year"];
1458
1677
  }
1459
1678
  }
1679
+ const DAY = 864e5;
1680
+ const MAX_CALENDAR_DAYS = 1e5;
1681
+ const MAX_CALENDAR_RANGES = 1e5;
1682
+ function validateCalendar(calendar) {
1683
+ if (!calendar) return;
1684
+ if (typeof calendar !== "object" || Array.isArray(calendar)) throw new TypeError("Invalid Gantt calendar");
1685
+ if (calendar.dayStartHour !== void 0 && (!Number.isInteger(calendar.dayStartHour) || calendar.dayStartHour < 0 || calendar.dayStartHour > 23)) throw new RangeError("dayStartHour must be 0..23");
1686
+ const shifts = calendar.shiftHours;
1687
+ if (shifts !== void 0 && (!Array.isArray(shifts) || !shifts.length || shifts.length > 24 || shifts.some((hour, i) => !Number.isInteger(hour) || hour < 0 || hour > 23 || i > 0 && hour <= shifts[i - 1]))) throw new RangeError("shiftHours must be sorted unique hours 0..23");
1688
+ const days = calendar.workingDays;
1689
+ if (days !== void 0 && (!Array.isArray(days) || !days.length || days.length > 7 || days.some((day) => !Number.isInteger(day) || day < 0 || day > 6) || new Set(days).size !== days.length)) throw new RangeError("workingDays must contain unique weekdays 0..6");
1690
+ if (calendar.workingHours !== void 0 && (!Array.isArray(calendar.workingHours) || !calendar.workingHours.length || calendar.workingHours.length > 1440)) throw new RangeError("workingHours must contain 1..1440 intervals");
1691
+ for (const range of calendar.workingHours ?? []) if (!range || !Number.isInteger(range.startMinute) || !Number.isInteger(range.endMinute) || range.startMinute < 0 || range.endMinute > 1440 || range.endMinute <= range.startMinute) throw new RangeError("Invalid workingHours interval");
1692
+ if (calendar.excludedRanges !== void 0 && (!Array.isArray(calendar.excludedRanges) || calendar.excludedRanges.length > MAX_CALENDAR_RANGES)) throw new RangeError("Too many excluded ranges");
1693
+ for (const range of calendar.excludedRanges ?? []) if (!range || !validTime(range.startMs) || !validTime(range.endMs) || range.endMs <= range.startMs) throw new RangeError("Invalid excluded time range");
1694
+ if (calendar.excludedDates !== void 0 && (!Array.isArray(calendar.excludedDates) || calendar.excludedDates.length > MAX_CALENDAR_RANGES)) throw new RangeError("Too many excluded dates");
1695
+ for (const date of calendar.excludedDates ?? []) if (typeof date !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(date) || !Number.isFinite(Date.parse(`${date}T00:00:00Z`)) || (/* @__PURE__ */ new Date(`${date}T00:00:00Z`)).toISOString().slice(0, 10) !== date) throw new RangeError("excludedDates must be valid YYYY-MM-DD dates");
1696
+ }
1697
+ function validTime(value) {
1698
+ return typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= 864e13;
1699
+ }
1700
+ function union(ranges) {
1701
+ const result = [];
1702
+ for (const range of [...ranges].sort((a, b) => a.startMs - b.startMs)) {
1703
+ const last = result[result.length - 1];
1704
+ if (last && range.startMs <= last.endMs) last.endMs = Math.max(last.endMs, range.endMs);
1705
+ else result.push({ ...range });
1706
+ }
1707
+ return result;
1708
+ }
1709
+ function hasWorkingCalendar(calendar) {
1710
+ var _a, _b;
1711
+ return !!calendar && (calendar.workingDays !== void 0 || calendar.workingHours !== void 0 || !!((_a = calendar.excludedRanges) == null ? void 0 : _a.length) || !!((_b = calendar.excludedDates) == null ? void 0 : _b.length));
1712
+ }
1713
+ function calendarProjector(calendar, range, timeZone = "UTC") {
1714
+ validateCalendar(calendar);
1715
+ const recurring = calendar.workingDays !== void 0 || calendar.workingHours !== void 0;
1716
+ if (recurring && (range.endMs - range.startMs) / DAY > MAX_CALENDAR_DAYS) throw new RangeError("Gantt working calendar exceeds 100,000 days; use a smaller range");
1717
+ const days = calendar.workingDays ? new Set(calendar.workingDays) : null;
1718
+ const hours = union((calendar.workingHours ?? [{ startMinute: 0, endMinute: 1440 }]).map((value) => ({ startMs: value.startMinute * 6e4, endMs: value.endMinute * 6e4 })));
1719
+ const excluded = union([
1720
+ ...calendar.excludedRanges ?? [],
1721
+ ...(calendar.excludedDates ?? []).map((date) => {
1722
+ const day = Date.parse(`${date}T00:00:00Z`);
1723
+ return { startMs: fromWallTime(day, timeZone), endMs: fromWallTime(day + DAY, timeZone) };
1724
+ })
1725
+ ]);
1726
+ const daily = /* @__PURE__ */ new Map();
1727
+ const workingIntervals = (day) => {
1728
+ const existing = daily.get(day);
1729
+ if (existing) return existing;
1730
+ const intervals = [];
1731
+ if (!days || days.has(new Date(day).getUTCDay())) for (const period of localDayPeriods(day, timeZone)) {
1732
+ for (const hoursRange of hours) {
1733
+ const startMs = Math.max(period.startMs, day + hoursRange.startMs - period.offset);
1734
+ const endMs = Math.min(period.endMs, day + hoursRange.endMs - period.offset);
1735
+ if (startMs < endMs) intervals.push({ startMs, endMs });
1736
+ }
1737
+ }
1738
+ if (daily.size >= 512) daily.delete(daily.keys().next().value);
1739
+ daily.set(day, intervals);
1740
+ return intervals;
1741
+ };
1742
+ const subtract = (start, end, out) => {
1743
+ let low = 0, high = excluded.length;
1744
+ while (low < high) {
1745
+ const mid = low + high >>> 1;
1746
+ if (excluded[mid].endMs <= start) low = mid + 1;
1747
+ else high = mid;
1748
+ }
1749
+ let cursor = start;
1750
+ for (let i = low; i < excluded.length && excluded[i].startMs < end; i++) {
1751
+ const exception = excluded[i];
1752
+ if (exception.startMs > cursor) out.push({ startMs: cursor, endMs: Math.min(exception.startMs, end) });
1753
+ cursor = Math.max(cursor, exception.endMs);
1754
+ if (cursor >= end) return;
1755
+ }
1756
+ if (cursor < end) out.push({ startMs: cursor, endMs: end });
1757
+ };
1758
+ return (start, end) => {
1759
+ const out = [];
1760
+ if (!recurring) {
1761
+ subtract(start, end, out);
1762
+ return out;
1763
+ }
1764
+ const firstDay = Math.floor(wallTime(start, timeZone) / DAY) * DAY;
1765
+ const lastDay = Math.floor(wallTime(end - 1, timeZone) / DAY) * DAY;
1766
+ for (let day = firstDay; day <= lastDay; day += DAY) {
1767
+ for (const interval of workingIntervals(day)) {
1768
+ const from = Math.max(start, interval.startMs), to = Math.min(end, interval.endMs);
1769
+ if (from < to) subtract(from, to, out);
1770
+ }
1771
+ }
1772
+ return out;
1773
+ };
1774
+ }
1460
1775
  const MAX_TICK_COLUMNS = 1e5;
1776
+ function validateTimeAxisSpec(spec) {
1777
+ var _a;
1778
+ if (!(spec == null ? void 0 : spec.range) || !Number.isFinite(spec.range.startMs) || !Number.isFinite(spec.range.endMs) || Math.abs(spec.range.startMs) > 864e13 || Math.abs(spec.range.endMs) > 864e13 || spec.range.endMs <= spec.range.startMs) throw new RangeError("Gantt time range must have finite endMs > startMs");
1779
+ validateCalendar(spec.calendar);
1780
+ validateTimeZone(spec.timeZone);
1781
+ const ladder = normalizeTimeAxisSpec(spec);
1782
+ if (!Number.isFinite(ladder.initial.width) || ladder.initial.width <= 0 || !ladder.steps.some((step) => step.unit === ladder.initial.unit)) throw new RangeError("Invalid initial Gantt tick");
1783
+ if (new Set(ladder.steps.map((step) => step.unit)).size !== ladder.steps.length) throw new RangeError("Duplicate Gantt tick ladder unit");
1784
+ for (const step of ladder.steps) {
1785
+ if (!UNIT_ORDER.includes(step.unit) || ((_a = step.headerHierarchy) == null ? void 0 : _a.some((unit) => !UNIT_ORDER.includes(unit)))) throw new RangeError("Invalid Gantt time unit");
1786
+ if (spec.tickLadder && (!Number.isFinite(step.minWidth) || !Number.isFinite(step.maxWidth) || step.minWidth <= 0 || step.maxWidth < step.minWidth)) throw new RangeError("Invalid zoom bounds");
1787
+ buildTicks(spec, step.unit);
1788
+ }
1789
+ if (spec.tickLadder) {
1790
+ const step = ladder.steps.find((item) => item.unit === ladder.initial.unit);
1791
+ if (ladder.initial.width < step.minWidth || ladder.initial.width > step.maxWidth) throw new RangeError("Initial zoom is outside its tier bounds");
1792
+ }
1793
+ }
1794
+ function buildTicks(spec, unit) {
1795
+ if (!UNIT_ORDER.includes(unit)) throw new RangeError("Invalid Gantt time unit");
1796
+ const start = floorTo(spec.range.startMs, unit, spec.calendar, spec.timeZone), end = ceilTo(spec.range.endMs, unit, spec.calendar, spec.timeZone);
1797
+ if (!Number.isFinite(start) || !Number.isFinite(end)) throw new RangeError("Invalid Gantt time boundary");
1798
+ const ticks = enumerateTicks(spec.range, unit, spec.calendar, spec.timeZone);
1799
+ if (!hasWorkingCalendar(spec.calendar)) return ticks;
1800
+ const project = calendarProjector(spec.calendar, { startMs: start, endMs: end }, spec.timeZone);
1801
+ const result = [];
1802
+ for (const tick of ticks) {
1803
+ const segments = project(tick.startMs, tick.endMs);
1804
+ if (segments.length) result.push({ ...tick, segments });
1805
+ }
1806
+ if (!result.length) throw new RangeError("Gantt calendar has no working time in the visible range");
1807
+ return result;
1808
+ }
1809
+ const emptyCalendar = Object.freeze({});
1810
+ const calendarDurations = /* @__PURE__ */ new WeakMap();
1811
+ function averageTickDuration(spec, unit) {
1812
+ var _a, _b;
1813
+ if (!hasWorkingCalendar(spec.calendar) && (!spec.timeZone || spec.timeZone === "UTC")) return unit === "shift" ? 864e5 / (((_b = (_a = spec.calendar) == null ? void 0 : _a.shiftHours) == null ? void 0 : _b.length) ?? 3) : unitMsAvg(unit);
1814
+ const calendar = spec.calendar ?? emptyCalendar;
1815
+ let ranges = calendarDurations.get(calendar);
1816
+ if (!ranges) {
1817
+ ranges = /* @__PURE__ */ new WeakMap();
1818
+ calendarDurations.set(calendar, ranges);
1819
+ }
1820
+ let units = ranges.get(spec.range);
1821
+ if (!units) {
1822
+ units = /* @__PURE__ */ new Map();
1823
+ ranges.set(spec.range, units);
1824
+ }
1825
+ const key = `${spec.timeZone ?? "UTC"}:${unit}`;
1826
+ let value = units.get(key);
1827
+ if (value === void 0) {
1828
+ const ticks = buildTicks(spec, unit);
1829
+ let duration = 0;
1830
+ for (const tick of ticks) for (const segment of tick.segments ?? [tick]) duration += segment.endMs - segment.startMs;
1831
+ value = duration / ticks.length;
1832
+ units.set(key, value);
1833
+ }
1834
+ return value;
1835
+ }
1461
1836
  function normalizeTimeAxisSpec(spec) {
1462
1837
  if (spec.tickLadder && spec.ticks) {
1463
1838
  throw new Error("[TimeAxisSpec] `ticks` and `tickLadder` are mutually exclusive — use only one.");
@@ -1489,7 +1864,9 @@ function buildTimeAxisColumns(spec, startLeft, tierIdx, totalTiers, parentColPat
1489
1864
  const activeStep = ladder.steps.find((s) => s.unit === ladder.initial.unit) ?? ladder.steps[0];
1490
1865
  const activeUnit = ladder.initial.unit;
1491
1866
  const tickWidth = ladder.initial.width;
1492
- const leaves = enumerateTicks(spec.range, activeUnit);
1867
+ validateCalendar(spec.calendar);
1868
+ validateTimeZone(spec.timeZone);
1869
+ const leaves = buildTicks(spec, activeUnit);
1493
1870
  if (leaves.length > MAX_TICK_COLUMNS) {
1494
1871
  throw new Error(
1495
1872
  `[TimeAxisBuilder] tick columns ${leaves.length} exceed limit ${MAX_TICK_COLUMNS}. Use coarser unit or smaller range.`
@@ -1513,15 +1890,16 @@ function buildTimeAxisColumns(spec, startLeft, tierIdx, totalTiers, parentColPat
1513
1890
  width: tickWidth,
1514
1891
  type: "data",
1515
1892
  tickStartMs: leaf.startMs,
1516
- tickEndMs: leaf.endMs
1893
+ tickEndMs: leaf.endMs,
1894
+ timeSegments: leaf.segments
1517
1895
  });
1518
1896
  }
1519
1897
  const hierarchy = activeStep.headerHierarchy ?? [activeUnit];
1520
1898
  const fullHierarchy = hierarchy[hierarchy.length - 1] === activeUnit ? [...hierarchy] : [...hierarchy, activeUnit];
1521
- const headerNodes = buildHierarchyNodes(leaves, fullHierarchy, spec.format, tierIdx);
1899
+ const headerNodes = buildHierarchyNodes(leaves, fullHierarchy, spec.format, tierIdx, spec.calendar, spec.timeZone);
1522
1900
  return { columns, headerNodes, totalWidth };
1523
1901
  }
1524
- function buildHierarchyNodes(leaves, hierarchy, format, tierIdx) {
1902
+ function buildHierarchyNodes(leaves, hierarchy, format, tierIdx, calendar, timeZone = "UTC") {
1525
1903
  if (hierarchy.length === 0 || leaves.length === 0) return [];
1526
1904
  const leafUnit = hierarchy[hierarchy.length - 1];
1527
1905
  const leafLevel = hierarchy.length - 1;
@@ -1543,7 +1921,7 @@ function buildHierarchyNodes(leaves, hierarchy, format, tierIdx) {
1543
1921
  let currentChildrenLeafSpan = leafNodes.map(() => 1);
1544
1922
  for (let level = hierarchy.length - 2; level >= 0; level--) {
1545
1923
  const tierUnit = hierarchy[level];
1546
- const groups = groupByUnit(leaves, tierUnit);
1924
+ const groups = groupByUnit(leaves, tierUnit, calendar, timeZone);
1547
1925
  const nextLayer = [];
1548
1926
  for (const g of groups) {
1549
1927
  const firstChildIdx = g.firstLeafIndex;
@@ -1593,20 +1971,47 @@ function findColAtContentX(cols, contentX) {
1593
1971
  return null;
1594
1972
  }
1595
1973
  function pxToMs(col, contentX) {
1974
+ var _a;
1596
1975
  if (col.tickStartMs == null || col.tickEndMs == null) {
1597
1976
  return 0;
1598
1977
  }
1599
1978
  const ratio = (contentX - col.left) / col.width;
1979
+ if ((_a = col.timeSegments) == null ? void 0 : _a.length) {
1980
+ const { segments, prefix, duration } = workingProjection(col);
1981
+ const elapsed = Math.max(0, Math.min(1, ratio)) * duration;
1982
+ if (elapsed >= duration) return segments[segments.length - 1].endMs;
1983
+ let low = 0, high = segments.length;
1984
+ while (low < high) {
1985
+ const mid = low + high >>> 1;
1986
+ if (prefix[mid + 1] <= elapsed) low = mid + 1;
1987
+ else high = mid;
1988
+ }
1989
+ return segments[low].startMs + elapsed - prefix[low];
1990
+ }
1600
1991
  return col.tickStartMs + ratio * (col.tickEndMs - col.tickStartMs);
1601
1992
  }
1602
1993
  function msToPx(col, ms) {
1994
+ var _a;
1603
1995
  if (col.tickStartMs == null || col.tickEndMs == null) {
1604
1996
  return col.left;
1605
1997
  }
1998
+ if ((_a = col.timeSegments) == null ? void 0 : _a.length) {
1999
+ const { segments, prefix, duration } = workingProjection(col);
2000
+ let low = 0, high = segments.length;
2001
+ while (low < high) {
2002
+ const mid = low + high >>> 1;
2003
+ if (segments[mid].startMs <= ms) low = mid + 1;
2004
+ else high = mid;
2005
+ }
2006
+ const index = low - 1;
2007
+ const elapsed = index < 0 ? 0 : prefix[index] + Math.min(ms, segments[index].endMs) - segments[index].startMs;
2008
+ return col.left + elapsed / duration * col.width;
2009
+ }
1606
2010
  const ratio = (ms - col.tickStartMs) / (col.tickEndMs - col.tickStartMs);
1607
2011
  return col.left + ratio * col.width;
1608
2012
  }
1609
2013
  function findColAtMs(cols, ms) {
2014
+ var _a;
1610
2015
  const shape = getTimeColumnShape(cols);
1611
2016
  if (shape.ordered) {
1612
2017
  let lo = 0;
@@ -1617,7 +2022,9 @@ function findColAtMs(cols, ms) {
1617
2022
  else hi = mid;
1618
2023
  }
1619
2024
  const col = cols[lo - 1];
1620
- return col && ms >= col.tickStartMs && ms < col.tickEndMs ? col : null;
2025
+ if (col && ms >= col.tickStartMs && ms < col.tickEndMs) return col;
2026
+ if ((col == null ? void 0 : col.timeSegments) && lo < cols.length && ((_a = cols[lo]) == null ? void 0 : _a.timeSegments) && ms < cols[lo].tickStartMs) return col;
2027
+ return null;
1621
2028
  }
1622
2029
  for (const c of cols) {
1623
2030
  if (c.tickStartMs == null || c.tickEndMs == null) continue;
@@ -1625,6 +2032,48 @@ function findColAtMs(cols, ms) {
1625
2032
  }
1626
2033
  return null;
1627
2034
  }
2035
+ const projections = /* @__PURE__ */ new WeakMap();
2036
+ function workingProjection(col) {
2037
+ let value = projections.get(col);
2038
+ if (!value || value.segments !== col.timeSegments) {
2039
+ const segments = col.timeSegments;
2040
+ const prefix = new Float64Array(segments.length + 1);
2041
+ for (let i = 0; i < segments.length; i++) prefix[i + 1] = prefix[i] + segments[i].endMs - segments[i].startMs;
2042
+ value = { segments, prefix, duration: prefix[segments.length] };
2043
+ projections.set(col, value);
2044
+ }
2045
+ return value;
2046
+ }
2047
+ function hasVisibleTime(cols, startMs, endMs) {
2048
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs < startMs) return false;
2049
+ const shape = getTimeColumnShape(cols);
2050
+ let first = 0;
2051
+ if (shape.ordered) {
2052
+ let high = cols.length;
2053
+ while (first < high) {
2054
+ const mid = first + high >>> 1;
2055
+ if (cols[mid].tickEndMs <= startMs) first = mid + 1;
2056
+ else high = mid;
2057
+ }
2058
+ }
2059
+ for (let i = first; i < cols.length; i++) {
2060
+ const col = cols[i];
2061
+ if (col.tickStartMs == null || col.tickEndMs == null) continue;
2062
+ if (shape.ordered && col.tickStartMs > endMs) break;
2063
+ if (col.timeSegments) {
2064
+ const segments = col.timeSegments;
2065
+ let low = 0, high = segments.length;
2066
+ while (low < high) {
2067
+ const mid = low + high >>> 1;
2068
+ if (segments[mid].endMs <= startMs) low = mid + 1;
2069
+ else high = mid;
2070
+ }
2071
+ const segment = segments[low];
2072
+ if (segment && (startMs === endMs ? startMs >= segment.startMs && startMs < segment.endMs : startMs < segment.endMs && endMs > segment.startMs)) return true;
2073
+ } else if (startMs === endMs ? startMs >= col.tickStartMs && startMs < col.tickEndMs : startMs < col.tickEndMs && endMs > col.tickStartMs) return true;
2074
+ }
2075
+ return false;
2076
+ }
1628
2077
  const timeColumnShapes = /* @__PURE__ */ new WeakMap();
1629
2078
  function getTimeColumnShape(cols) {
1630
2079
  let shape = timeColumnShapes.get(cols);
@@ -2122,6 +2571,10 @@ class HeaderRenderer {
2122
2571
  invalidateColumnHeaders() {
2123
2572
  this.colPool.releaseAll();
2124
2573
  }
2574
+ /** 조회 patch는 행만 바뀐다. 고정 코너와 시간 헤더의 DOM을 보존한다. */
2575
+ invalidateRowHeaders() {
2576
+ this.rowPool.releaseAll();
2577
+ }
2125
2578
  /** 좌상단 코너 — rowField 헤더 라벨 표시 */
2126
2579
  /**
2127
2580
  * 좌상단 corner pane 렌더 — row header tier 라벨 (자원그룹/자원 등) 표시.
@@ -2251,7 +2704,7 @@ class HeaderRenderer {
2251
2704
  // 행 헤더
2252
2705
  // --------------------------------------------------------------------------
2253
2706
  renderRowHeader(slots, visibleRange, mergeInfo) {
2254
- var _a, _b;
2707
+ var _a, _b, _c;
2255
2708
  if (slots.length === 0) {
2256
2709
  this.rowPool.releaseAll();
2257
2710
  return;
@@ -2277,7 +2730,7 @@ class HeaderRenderer {
2277
2730
  const isSubtotalLabelCell = isSubtotal && f > subLevel;
2278
2731
  let value;
2279
2732
  if (isSubtotalLabelCell) {
2280
- value = "소계";
2733
+ value = ((_a = this.opts.labels) == null ? void 0 : _a.subtotal) ?? "소계";
2281
2734
  } else {
2282
2735
  value = isCellPartition ? fieldDef.displayFromSlotIndex({
2283
2736
  slotIndex: firstSlot.slotIndex,
@@ -2292,8 +2745,13 @@ class HeaderRenderer {
2292
2745
  const { el } = this.rowPool.acquire(key);
2293
2746
  const showCollapser = !!fieldDef.collapsible && !isCellPartition && !isSubtotalLabelCell;
2294
2747
  const ancestorKey = showCollapser ? firstSlot.rowPath.slice(0, f + 1).map((v) => String(v ?? "")).join("") : null;
2295
- const collapsed = ancestorKey != null ? ((_b = (_a = this.opts).isAncestorCollapsed) == null ? void 0 : _b.call(_a, ancestorKey)) ?? false : false;
2296
- this.applyHeaderClass(el, isSubtotalLabelCell ? "pv-rh pv-rh-subtotal" : "pv-rh");
2748
+ const collapsed = ancestorKey != null ? ((_c = (_b = this.opts).isAncestorCollapsed) == null ? void 0 : _c.call(_b, ancestorKey)) ?? false : false;
2749
+ const context = { value, field: fieldDef.field, rowPath: firstSlot.rowPath, slotIndex: firstSlot.slotIndex, isSubtotal };
2750
+ const customClass = typeof fieldDef.cellClass === "function" ? fieldDef.cellClass(context) : fieldDef.cellClass;
2751
+ this.applyHeaderClass(el, `${isSubtotalLabelCell ? "pv-rh pv-rh-subtotal" : "pv-rh"}${customClass ? ` ${customClass}` : ""}`);
2752
+ el.tabIndex = 0;
2753
+ el.setAttribute("role", "button");
2754
+ el.dataset.fullRowPath = JSON.stringify(firstSlot.rowPath);
2297
2755
  const rowPathAttr = !isCellPartition && !isSubtotalLabelCell ? firstSlot.rowPath.slice(0, f + 1).map((v) => String(v ?? "")).join("") : void 0;
2298
2756
  this.applyHeaderAttrs(el, {
2299
2757
  left: geom.lefts[f],
@@ -2304,7 +2762,12 @@ class HeaderRenderer {
2304
2762
  fieldIndex: f,
2305
2763
  rowPath: rowPathAttr
2306
2764
  });
2307
- this.applyHeaderContent(el, value == null ? "" : String(value), showCollapser, ancestorKey, collapsed, f);
2765
+ const cached = el;
2766
+ if (cached.__customCell && !fieldDef.renderCell) delete cached.__label;
2767
+ this.applyHeaderContent(el, fieldDef.formatter ? fieldDef.formatter(value, context) : value == null ? "" : String(value), showCollapser, ancestorKey, collapsed, f);
2768
+ const content = el.querySelector(".pv-rh-text, .pv-header-cell-text");
2769
+ if (fieldDef.renderCell && content) fieldDef.renderCell(content, context);
2770
+ cached.__customCell = !!fieldDef.renderCell;
2308
2771
  if (!el.parentElement) this.rowHeaderEl.appendChild(el);
2309
2772
  if (!isCellPartition) {
2310
2773
  el.__mergeY = { top, height };
@@ -2460,6 +2923,7 @@ class HeaderRenderer {
2460
2923
  * - `hasCollapser=true`: inner 안에 `<button class="pv-rh-collapser">▼/▶</button><span class="pv-rh-text">text</span>`.
2461
2924
  */
2462
2925
  applyHeaderContent(el, text, hasCollapser, ancestorKey, collapsed, level) {
2926
+ var _a, _b;
2463
2927
  const cached = el;
2464
2928
  const inner = this.ensureCellInner(el);
2465
2929
  if (!hasCollapser) {
@@ -2508,9 +2972,10 @@ class HeaderRenderer {
2508
2972
  if (cached.__collapsed !== collapsed) {
2509
2973
  btn.textContent = collapsed ? "▶" : "▼";
2510
2974
  btn.dataset.collapsed = collapsed ? "1" : "0";
2511
- btn.setAttribute("aria-label", collapsed ? "Expand" : "Collapse");
2512
2975
  cached.__collapsed = collapsed;
2513
2976
  }
2977
+ btn.setAttribute("aria-label", collapsed ? ((_a = this.opts.labels) == null ? void 0 : _a.expand) ?? "Expand" : ((_b = this.opts.labels) == null ? void 0 : _b.collapse) ?? "Collapse");
2978
+ btn.setAttribute("aria-expanded", String(!collapsed));
2514
2979
  if (cached.__label !== text) {
2515
2980
  span.textContent = text;
2516
2981
  cached.__label = text;
@@ -2745,6 +3210,7 @@ class Pivotor {
2745
3210
  // body renderer 피드백 핸들
2746
3211
  // --------------------------------------------------------------------------
2747
3212
  __publicField(this, "handle", {
3213
+ getAllSlots: () => this.rowAxis.slots,
2748
3214
  setRowHeight: (slotId, height) => this.setRowHeight(slotId, height),
2749
3215
  setColumnWidth: (colId, width) => this.setColumnWidth(colId, width),
2750
3216
  toggleCollapse: (nodeId) => this.toggleCollapse(nodeId),
@@ -2796,7 +3262,8 @@ class Pivotor {
2796
3262
  this.headerRenderer.updateOptions({
2797
3263
  headerHeight: this.config.headerHeight ?? DEFAULT_HEADER_HEIGHT,
2798
3264
  rowHeaderWidth: this.config.rowHeaderWidth ?? DEFAULT_ROW_HEADER_WIDTH,
2799
- rowFields: this.config.rowFields
3265
+ rowFields: this.config.rowFields,
3266
+ labels: this.config.labels
2800
3267
  });
2801
3268
  this.attachRowHeaderResizer();
2802
3269
  this.rowAxis.setInitiallyCollapsed(this.config.initiallyCollapsed);
@@ -2861,7 +3328,7 @@ class Pivotor {
2861
3328
  else this.partialRebuildForLeaves(affectedLeaves);
2862
3329
  this.bodyContainer.style.height = `${this.rowAxis.totalHeight}px`;
2863
3330
  this.inners.rowHeaderInner.style.height = `${this.rowAxis.totalHeight}px`;
2864
- this.headerRenderer.invalidate();
3331
+ this.headerRenderer.invalidateRowHeaders();
2865
3332
  this._version++;
2866
3333
  this.scheduleViewport();
2867
3334
  }
@@ -3244,6 +3711,7 @@ class Pivotor {
3244
3711
  }
3245
3712
  setColumnWidth(colId, width) {
3246
3713
  if (this.colAxis.setColumnWidth(colId, width)) {
3714
+ this.bodyRenderer.invalidate({ level: "axis-col" });
3247
3715
  this.bodyContainer.style.width = `${this.colAxis.totalWidth}px`;
3248
3716
  this.inners.colHeaderInner.style.width = `${this.colAxis.totalWidth}px`;
3249
3717
  this.emitter.emit("layout:columnWidth", { colId, width });
@@ -3293,6 +3761,7 @@ class Pivotor {
3293
3761
  setAllTimeAxisTickWidths(width) {
3294
3762
  const changed = this.colAxis.setAllTimeAxisColumnWidths(width);
3295
3763
  if (changed === 0) return;
3764
+ this.bodyRenderer.invalidate({ level: "axis-col" });
3296
3765
  this.bodyContainer.style.width = `${this.colAxis.totalWidth}px`;
3297
3766
  this.inners.colHeaderInner.style.width = `${this.colAxis.totalWidth}px`;
3298
3767
  this.scheduleViewport();
@@ -3411,6 +3880,7 @@ class Pivotor {
3411
3880
  headerHeight: this.config.headerHeight ?? DEFAULT_HEADER_HEIGHT,
3412
3881
  rowHeaderWidth: this.config.rowHeaderWidth ?? DEFAULT_ROW_HEADER_WIDTH,
3413
3882
  rowFields: this.config.rowFields,
3883
+ labels: this.config.labels,
3414
3884
  isAncestorCollapsed: (key) => this.rowAxis.isAncestorCollapsed(key),
3415
3885
  renderHeaderCell: this.renderHeaderCellOpt
3416
3886
  }
@@ -3418,7 +3888,7 @@ class Pivotor {
3418
3888
  rowHeader.addEventListener("click", (e) => {
3419
3889
  const target = e.target;
3420
3890
  const btn = target == null ? void 0 : target.closest(".pv-rh-collapser");
3421
- if (!btn) return;
3891
+ if (!btn || btn.closest('[aria-disabled="true"]')) return;
3422
3892
  const key = btn.dataset.ancestorKey;
3423
3893
  if (key == null) return;
3424
3894
  e.preventDefault();
@@ -3447,7 +3917,9 @@ class Pivotor {
3447
3917
  this.rowHeaderResizeHandles.splice(0).forEach((handle) => handle.remove());
3448
3918
  }
3449
3919
  attachRowHeaderResizer() {
3920
+ var _a;
3450
3921
  this.detachRowHeaderResizer();
3922
+ if (this.config.rowHeaderResizable === false) return;
3451
3923
  const fields = this.config.rowFields;
3452
3924
  for (let i = 0; i < fields.length; i++) {
3453
3925
  const handle = document.createElement("div");
@@ -3464,6 +3936,19 @@ class Pivotor {
3464
3936
  touchAction: "none"
3465
3937
  });
3466
3938
  handle.dataset.fieldIdx = String(i);
3939
+ handle.tabIndex = 0;
3940
+ handle.setAttribute("role", "separator");
3941
+ handle.setAttribute("aria-orientation", "vertical");
3942
+ handle.setAttribute("aria-label", (((_a = this.config.labels) == null ? void 0 : _a.resizeColumn) ?? "Resize {field}").replace("{field}", fields[i].header ?? fields[i].field));
3943
+ const keyResize = (event) => {
3944
+ if (handle.getAttribute("aria-disabled") === "true") return;
3945
+ if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
3946
+ event.preventDefault();
3947
+ const field = this.config.rowFields[i];
3948
+ const current = field.width ?? this.config.rowHeaderWidth ?? DEFAULT_ROW_HEADER_WIDTH;
3949
+ this.setRowFieldWidth(i, event.key === "Home" ? field.minWidth ?? 24 : event.key === "End" ? field.maxWidth ?? 2e3 : current + (event.key === "ArrowLeft" ? -10 : 10));
3950
+ };
3951
+ handle.addEventListener("keydown", keyResize);
3467
3952
  this.container.appendChild(handle);
3468
3953
  this.rowHeaderResizeHandles.push(handle);
3469
3954
  let dragging = false;
@@ -3472,6 +3957,7 @@ class Pivotor {
3472
3957
  let pointerId = null;
3473
3958
  let previousCursor = "";
3474
3959
  const startDrag = (e) => {
3960
+ if (handle.getAttribute("aria-disabled") === "true") return;
3475
3961
  if (e.button !== 0 || dragging) return;
3476
3962
  const idx = Number(handle.dataset.fieldIdx);
3477
3963
  const targetField = this.config.rowFields[idx];
@@ -3504,6 +3990,7 @@ class Pivotor {
3504
3990
  handle.addEventListener("pointercancel", endDrag);
3505
3991
  handle.addEventListener("lostpointercapture", endDrag);
3506
3992
  this.rowHeaderResizerCleanup.push(() => {
3993
+ handle.removeEventListener("keydown", keyResize);
3507
3994
  endDrag();
3508
3995
  handle.removeEventListener("pointerdown", startDrag);
3509
3996
  handle.removeEventListener("pointermove", moveDrag);
@@ -3521,6 +4008,10 @@ class Pivotor {
3521
4008
  const handle = this.rowHeaderResizeHandles[i];
3522
4009
  const fieldRight = (geom.lefts[i] ?? 0) + (geom.widths[i] ?? 0);
3523
4010
  handle.style.left = `${fieldRight - 3}px`;
4011
+ const field = this.config.rowFields[i];
4012
+ handle.setAttribute("aria-valuemin", String(field.minWidth ?? 24));
4013
+ handle.setAttribute("aria-valuemax", String(field.maxWidth ?? 2e3));
4014
+ handle.setAttribute("aria-valuenow", String(geom.widths[i]));
3524
4015
  }
3525
4016
  }
3526
4017
  // ==========================================================================
@@ -3643,7 +4134,7 @@ class Pivotor {
3643
4134
  }
3644
4135
  const after = { ...before, ...m.changes };
3645
4136
  const changedFields = Object.keys(m.changes).filter((k) => before[k] !== after[k]);
3646
- const rowFieldNames = this.config.rowFields.map((f) => f.field);
4137
+ const rowFieldNames = this.config.rowFields.flatMap((f) => f.sortField ? [f.field, f.sortField] : [f.field]);
3647
4138
  const colFieldNames = this.config.columnFields.map(categoryFieldOf).filter((x) => x != null);
3648
4139
  const axisChanged = changedFields.some((k) => rowFieldNames.includes(k)) || changedFields.some((k) => colFieldNames.includes(k));
3649
4140
  if (source === "dirty-rollback") {
@@ -4366,6 +4857,27 @@ class IntervalIndex {
4366
4857
  function comparePaintOrder(a, b) {
4367
4858
  return a.order - b.order;
4368
4859
  }
4860
+ const DEFAULT_GANTT_THEME = Object.freeze({
4861
+ surface: "#ffffff",
4862
+ header: "#f1f4f9",
4863
+ text: "#263248",
4864
+ border: "#d5dce7",
4865
+ accent: "#2563eb",
4866
+ grid: "#bbc6d9",
4867
+ bar: "#1976d2",
4868
+ barText: "#ffffff",
4869
+ barBorder: "",
4870
+ lockedBar: "#737d8b",
4871
+ addedBar: "#23834b",
4872
+ modifiedBar: "#b65e00",
4873
+ removedBar: "#c33737",
4874
+ searchMatch: "#b96a00",
4875
+ searchCurrent: "#c2410c",
4876
+ selection: "#5b43d6",
4877
+ milestone: "#7555b5",
4878
+ dependency: "#627086",
4879
+ font: "11px sans-serif"
4880
+ });
4369
4881
  const DEFAULT_DPR = 1;
4370
4882
  const MAX_OVERLAY_INDEX_ROWS = 1e5;
4371
4883
  const MAX_OVERLAY_INDEX_GROUPS = 64;
@@ -4373,6 +4885,7 @@ const INDEX_MIN_ROWS = 32;
4373
4885
  const MAX_RETAINED_HIT_REGIONS = 4096;
4374
4886
  const MAX_PATTERN_CACHE_ENTRIES = 256;
4375
4887
  const EMPTY_PAINT_ROW = Object.freeze({});
4888
+ const EMPTY_DASH = [];
4376
4889
  class GanttCanvasRenderer {
4377
4890
  constructor(opts) {
4378
4891
  __publicField(this, "pivotor", null);
@@ -4384,6 +4897,10 @@ class GanttCanvasRenderer {
4384
4897
  __publicField(this, "intervalScratch", []);
4385
4898
  __publicField(this, "overlayIndexes", /* @__PURE__ */ new Map());
4386
4899
  __publicField(this, "overlayIndexRows", 0);
4900
+ __publicField(this, "theme");
4901
+ __publicField(this, "levels", /* @__PURE__ */ new WeakMap());
4902
+ __publicField(this, "dependencyIndex", null);
4903
+ __publicField(this, "dependencyScratch", []);
4387
4904
  __publicField(this, "canvas", null);
4388
4905
  __publicField(this, "ctx2d", null);
4389
4906
  __publicField(this, "dpr", DEFAULT_DPR);
@@ -4413,19 +4930,53 @@ class GanttCanvasRenderer {
4413
4930
  borderColor = userResult.border;
4414
4931
  }
4415
4932
  if (barFill == null) {
4416
- let fb = "#1976d2";
4417
- if (paint.locked) fb = "#9e9e9e";
4418
- else if (paint.dirtyState === "added") fb = "#4caf50";
4419
- else if (paint.dirtyState === "modified") fb = "#ff9800";
4420
- else if (paint.dirtyState === "removed") fb = "#f44336";
4421
- else if (paint.dirtyState === "reordered") fb = "#9c27b0";
4933
+ let fb = paint.milestone ? this.theme.milestone : this.theme.bar;
4934
+ if (paint.locked) fb = this.theme.lockedBar;
4935
+ else if (paint.dirtyState === "added") fb = this.theme.addedBar;
4936
+ else if (paint.dirtyState === "modified" || paint.dirtyState === "reordered") fb = this.theme.modifiedBar;
4937
+ else if (paint.dirtyState === "removed") fb = this.theme.removedBar;
4422
4938
  barFill = fb;
4423
4939
  }
4424
- const labelColor = textColor ?? "#fff";
4940
+ const labelColor = textColor ?? this.theme.barText;
4941
+ borderColor ?? (borderColor = this.theme.barBorder);
4425
4942
  const padTop = 4;
4426
4943
  const barH = paint.h - padTop * 2;
4427
4944
  if (barH < 2) return;
4428
- if (typeof barFill === "string") {
4945
+ if (paint.milestone) {
4946
+ this.diamond(paint.x, paint.y + (paint.h - paint.w) / 2, paint.w, paint.w);
4947
+ c.fillStyle = typeof barFill === "string" ? barFill : barFill.background;
4948
+ c.fill();
4949
+ if (typeof barFill !== "string") {
4950
+ const pattern = this.getOrCreatePattern(barFill, c);
4951
+ if (pattern) {
4952
+ c.fillStyle = pattern;
4953
+ c.fill();
4954
+ }
4955
+ }
4956
+ if (borderColor) {
4957
+ c.strokeStyle = borderColor;
4958
+ c.lineWidth = 1 / this.dpr;
4959
+ c.stroke();
4960
+ }
4961
+ return;
4962
+ }
4963
+ const shape = this.opts.barShape ?? "rectangle";
4964
+ if (shape !== "rectangle") {
4965
+ if (shape === "diamond") this.diamond(paint.x, paint.y + padTop, paint.w, barH);
4966
+ else {
4967
+ c.beginPath();
4968
+ c.roundRect(paint.x, paint.y + padTop, paint.w, barH, Math.min(6, paint.w / 2, barH / 2));
4969
+ }
4970
+ c.fillStyle = typeof barFill === "string" ? barFill : barFill.background;
4971
+ c.fill();
4972
+ if (typeof barFill !== "string") {
4973
+ const pat = this.getOrCreatePattern(barFill, c);
4974
+ if (pat) {
4975
+ c.fillStyle = pat;
4976
+ c.fill();
4977
+ }
4978
+ }
4979
+ } else if (typeof barFill === "string") {
4429
4980
  c.fillStyle = barFill;
4430
4981
  c.fillRect(paint.x, paint.y + padTop, paint.w, barH);
4431
4982
  } else {
@@ -4446,15 +4997,16 @@ class GanttCanvasRenderer {
4446
4997
  const y1 = Math.round(paint.y + padTop) + halfPx;
4447
4998
  const x2 = Math.round(paint.x + paint.w) - halfPx;
4448
4999
  const y2 = Math.round(paint.y + padTop + barH) - halfPx;
4449
- c.strokeRect(x1, y1, x2 - x1, y2 - y1);
5000
+ if (shape === "rectangle") c.strokeRect(x1, y1, x2 - x1, y2 - y1);
5001
+ else c.stroke();
4450
5002
  }
4451
5003
  if (paint.w > 30) {
4452
5004
  const text = this.opts.barLabel ? this.opts.barLabel(paint.row, paint) : String(paint.rowId);
4453
5005
  if (text == null || text === "") return;
4454
- const entry = this.textCache.get(text, "11px sans-serif", labelColor);
5006
+ const entry = this.textCache.get(text, this.theme.font, labelColor);
4455
5007
  const textY = paint.y + padTop + (barH - entry.height) / 2;
4456
- const labelPadL = 4;
4457
- const labelPadR = 4;
5008
+ const labelPadL = shape === "diamond" ? Math.max(4, paint.w * Math.min(1, entry.height / barH) / 2) : 4;
5009
+ const labelPadR = labelPadL;
4458
5010
  const cssMaxW = paint.w - labelPadL - labelPadR;
4459
5011
  if (cssMaxW <= 0) return;
4460
5012
  const cssDrawW = Math.min(entry.width, cssMaxW);
@@ -4478,6 +5030,7 @@ class GanttCanvasRenderer {
4478
5030
  }
4479
5031
  });
4480
5032
  this.opts = opts;
5033
+ this.theme = { ...DEFAULT_GANTT_THEME, ...opts.theme };
4481
5034
  this.timeFieldKey = JSON.stringify([opts.startField, opts.endField]);
4482
5035
  this.textCache = new TextBitmapCache(opts.textCacheCapacity ?? 4096);
4483
5036
  this.paintCtx = {
@@ -4491,7 +5044,9 @@ class GanttCanvasRenderer {
4491
5044
  startMs: 0,
4492
5045
  endMs: 0,
4493
5046
  dirtyState: null,
4494
- locked: false
5047
+ locked: false,
5048
+ milestone: false,
5049
+ level: 1
4495
5050
  };
4496
5051
  }
4497
5052
  clearTimeCache() {
@@ -4503,9 +5058,14 @@ class GanttCanvasRenderer {
4503
5058
  this.clearActiveHits();
4504
5059
  this.paintCtx.row = EMPTY_PAINT_ROW;
4505
5060
  this.paintCtx.rowId = "";
5061
+ this.levels = /* @__PURE__ */ new WeakMap();
5062
+ this.dependencyIndex = null;
5063
+ this.dependencyScratch.length = 0;
4506
5064
  }
4507
5065
  invalidateTime(id) {
4508
5066
  this.clearActiveHits();
5067
+ this.levels = /* @__PURE__ */ new WeakMap();
5068
+ this.dependencyIndex = null;
4509
5069
  if (this.pivotor) invalidateRowTimes(this.pivotor, id);
4510
5070
  for (const [rows, entry] of this.overlayIndexes) {
4511
5071
  if (entry.ids.has(id)) this.dropOverlayIndex(rows, entry);
@@ -4513,12 +5073,24 @@ class GanttCanvasRenderer {
4513
5073
  }
4514
5074
  invalidateRows(ids) {
4515
5075
  this.clearActiveHits();
5076
+ this.levels = /* @__PURE__ */ new WeakMap();
5077
+ this.dependencyIndex = null;
4516
5078
  for (const id of ids) this.invalidateTime(id);
4517
5079
  }
4518
5080
  /** 표시 설정만 변경하고 시간/행 인덱스와 Canvas 인스턴스를 유지한다. */
4519
5081
  updateOptions(patch) {
4520
5082
  if ("textCacheCapacity" in patch) this.textCache.setCapacity(patch.textCacheCapacity ?? 4096);
4521
5083
  Object.assign(this.opts, patch);
5084
+ if ("theme" in patch) {
5085
+ this.theme = { ...DEFAULT_GANTT_THEME, ...patch.theme };
5086
+ this.textCache.clear();
5087
+ this.patternCache.clear();
5088
+ }
5089
+ if (["dependencies", "milestoneField", "levelField", "dirtyField", "removedField", "hideRemovedBars", "barShape"].some((key) => key in patch)) {
5090
+ this.levels = /* @__PURE__ */ new WeakMap();
5091
+ this.dependencyIndex = null;
5092
+ this.clearActiveHits();
5093
+ }
4522
5094
  }
4523
5095
  // ─── PivotBodyRenderer 인터페이스 ───────────────────────────────────────
4524
5096
  mount(container, pivotor) {
@@ -4540,11 +5112,13 @@ class GanttCanvasRenderer {
4540
5112
  this.paintCtx.ctx = ctx;
4541
5113
  }
4542
5114
  invalidate(scope, rowIds) {
5115
+ this.dependencyIndex = null;
5116
+ if (scope.level === "axis-col") this.clearActiveHits();
4543
5117
  if (rowIds) this.invalidateRows(rowIds);
4544
5118
  else if (scope.level === "full" || scope.level === "axis-row" || scope.level === "cell" || scope.level === "leaf-group") this.clearTimeCache();
4545
5119
  }
4546
5120
  renderViewport(ctx) {
4547
- var _a, _b, _c, _d;
5121
+ var _a, _b, _c, _d, _e;
4548
5122
  this.hitCount = 0;
4549
5123
  const c = this.ctx2d;
4550
5124
  if (!c || !this.canvas) return;
@@ -4580,7 +5154,7 @@ class GanttCanvasRenderer {
4580
5154
  this.dumpDevMetrics(t0, 0);
4581
5155
  return;
4582
5156
  }
4583
- c.strokeStyle = "#BBC6D9";
5157
+ c.strokeStyle = this.theme.grid;
4584
5158
  c.lineWidth = 1 / dpr;
4585
5159
  c.beginPath();
4586
5160
  const lineYTop = ctx.scrollTop;
@@ -4600,6 +5174,7 @@ class GanttCanvasRenderer {
4600
5174
  c.lineTo(lineXRight, y);
4601
5175
  }
4602
5176
  c.stroke();
5177
+ this.paintDependencies(ctx, allCols);
4603
5178
  const firstCol = timeCols[0];
4604
5179
  const lastCol = timeCols[timeCols.length - 1];
4605
5180
  for (const slot of ctx.visibleRows) {
@@ -4612,23 +5187,28 @@ class GanttCanvasRenderer {
4612
5187
  this.collectOverlayRows(slot.cell.sourceRowsByCol, firstCol.tickStartMs, lastCol.tickEndMs, rowsForSlot);
4613
5188
  }
4614
5189
  if (rowsForSlot.length === 0) continue;
5190
+ const laneCount = this.levelCount(slot);
5191
+ const laneHeight = slot.height / laneCount;
4615
5192
  for (const row of rowsForSlot) {
4616
5193
  const rowId = pivotor == null ? void 0 : pivotor.resolveRowId(row);
4617
5194
  if (rowId == null) continue;
4618
- if (this.opts.hideRemovedBars && dirtyGetter && dirtyGetter(rowId) === "removed") {
4619
- continue;
4620
- }
5195
+ const dirtyState = this.rowDirtyState(rowId, dirtyGetter);
5196
+ if (this.opts.hideRemovedBars && dirtyState === "removed") continue;
4621
5197
  const times = getRowTimes(pivotor, rowId, startField, endField, this.timeFieldKey);
4622
5198
  if (!Number.isFinite(times.startMs) || !Number.isFinite(times.endMs) || times.endMs < times.startMs) continue;
4623
5199
  if (times.endMs < firstCol.tickStartMs || times.startMs >= lastCol.tickEndMs) continue;
5200
+ if (!hasVisibleTime(allCols, times.startMs, times.endMs)) continue;
4624
5201
  const start = Math.max(times.startMs, firstCol.tickStartMs);
4625
5202
  const end = Math.min(times.endMs, lastCol.tickEndMs);
4626
5203
  const startCol = findColAtMs(allCols, start) ?? firstCol;
4627
5204
  const endCol = findColAtMs(allCols, Math.max(start, end - 1)) ?? lastCol;
4628
- const x = msToPx(startCol, start);
4629
- const w = Math.max(2, msToPx(endCol, end) - x);
4630
- const y = slot.top;
4631
- const h = slot.height;
5205
+ const milestone = !!this.opts.milestoneField && pivotor.effective(rowId, this.opts.milestoneField) === true;
5206
+ const level = slot.cell.kind === "collapse" ? this.rowLevel(rowId) : 1;
5207
+ const h = laneHeight;
5208
+ const y = slot.top + (level - 1) * h;
5209
+ const size = Math.max(2, Math.min(24, h - 8));
5210
+ const x = msToPx(startCol, start) - (milestone ? size / 2 : 0);
5211
+ const w = milestone ? size : Math.max(2, msToPx(endCol, end) - x);
4632
5212
  this.paintCtx.row = row;
4633
5213
  this.paintCtx.rowId = rowId;
4634
5214
  this.paintCtx.x = x;
@@ -4637,22 +5217,30 @@ class GanttCanvasRenderer {
4637
5217
  this.paintCtx.h = h;
4638
5218
  this.paintCtx.startMs = times.startMs;
4639
5219
  this.paintCtx.endMs = times.endMs;
4640
- this.paintCtx.dirtyState = dirtyGetter ? dirtyGetter(rowId) : null;
4641
- this.paintCtx.locked = lockedField && pivotor ? pivotor.effective(rowId, lockedField) === true : false;
5220
+ this.paintCtx.dirtyState = dirtyState;
5221
+ this.paintCtx.locked = dirtyState === "locked" || !!(lockedField && pivotor && pivotor.effective(rowId, lockedField) === true);
5222
+ this.paintCtx.milestone = milestone;
5223
+ this.paintCtx.level = level;
4642
5224
  paintFn(this.paintCtx);
4643
5225
  let hit = this.hitRegions[this.hitCount];
4644
- if (!hit) this.hitRegions[this.hitCount] = hit = { id: rowId, row, x: 0, y: 0, w: 0, h: 0 };
5226
+ if (!hit) this.hitRegions[this.hitCount] = hit = { id: rowId, row, x: 0, y: 0, w: 0, h: 0, diamond: false };
4645
5227
  hit.id = rowId;
4646
5228
  hit.row = row;
4647
5229
  hit.x = x;
4648
- hit.y = y + 4;
5230
+ hit.y = milestone ? y + (h - size) / 2 : y + 4;
4649
5231
  hit.w = w;
4650
- hit.h = Math.max(2, h - 8);
5232
+ hit.h = milestone ? size : Math.max(2, h - 8);
5233
+ hit.diamond = milestone || this.opts.barShape === "diamond";
4651
5234
  this.hitCount++;
4652
5235
  if (search == null ? void 0 : search.matchedRowIds.has(rowId)) {
4653
- c.strokeStyle = ((_c = search.current) == null ? void 0 : _c.rowId) === rowId ? "#c2410c" : "#f59e0b";
5236
+ c.strokeStyle = ((_c = search.current) == null ? void 0 : _c.rowId) === rowId ? this.theme.searchCurrent : this.theme.searchMatch;
4654
5237
  c.lineWidth = ((_d = search.current) == null ? void 0 : _d.rowId) === rowId ? 3 : 2;
4655
- c.strokeRect(x + 1, y + 4, Math.max(1, w - 2), Math.max(2, h - 8));
5238
+ this.strokeTask(hit);
5239
+ }
5240
+ if (this.opts.selectedId === rowId || ((_e = ctx.getSelectionState) == null ? void 0 : _e.call(ctx, rowId)) === "selected") {
5241
+ c.strokeStyle = this.theme.selection;
5242
+ c.lineWidth = 2;
5243
+ this.strokeTask(hit);
4656
5244
  }
4657
5245
  painted++;
4658
5246
  }
@@ -4681,11 +5269,146 @@ class GanttCanvasRenderer {
4681
5269
  onHitTest(x, y) {
4682
5270
  for (let i = this.hitCount - 1; i >= 0; i--) {
4683
5271
  const r = this.hitRegions[i];
4684
- if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) return { kind: "bar", sourceRowId: r.id, data: r.row };
5272
+ if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
5273
+ if (r.diamond && Math.abs(x - r.x - r.w / 2) / (r.w / 2) + Math.abs(y - r.y - r.h / 2) / (r.h / 2) > 1) continue;
5274
+ return { kind: "bar", sourceRowId: r.id, data: r.row };
5275
+ }
4685
5276
  }
4686
5277
  return null;
4687
5278
  }
4688
5279
  // ─── 내부 헬퍼 ─────────────────────────────────────────────────────────
5280
+ rowLevel(id) {
5281
+ var _a;
5282
+ const value = this.opts.levelField ? (_a = this.pivotor) == null ? void 0 : _a.effective(id, this.opts.levelField) : 1;
5283
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 100 ? value : 1;
5284
+ }
5285
+ levelCount(slot) {
5286
+ var _a;
5287
+ if (!this.opts.levelField || slot.cell.kind !== "collapse") return 1;
5288
+ const cached = this.levels.get(slot);
5289
+ if (cached !== void 0) return cached;
5290
+ let levels = 1;
5291
+ for (const rows of slot.cell.sourceRowsByCol.values()) for (const row of rows) {
5292
+ const id = (_a = this.pivotor) == null ? void 0 : _a.resolveRowId(row);
5293
+ if (id != null) levels = Math.max(levels, this.rowLevel(id));
5294
+ }
5295
+ this.levels.set(slot, levels);
5296
+ return levels;
5297
+ }
5298
+ rowDirtyState(id, getter) {
5299
+ var _a, _b;
5300
+ if (this.opts.removedField && ((_a = this.pivotor) == null ? void 0 : _a.effective(id, this.opts.removedField)) === true) return "removed";
5301
+ const value = this.opts.dirtyField ? (_b = this.pivotor) == null ? void 0 : _b.effective(id, this.opts.dirtyField) : void 0;
5302
+ return value === "added" || value === "modified" || value === "removed" || value === "reordered" || value === "locked" ? value : (getter == null ? void 0 : getter(id)) ?? null;
5303
+ }
5304
+ diamond(x, y, w, h) {
5305
+ const c = this.ctx2d;
5306
+ c.beginPath();
5307
+ c.moveTo(x + w / 2, y);
5308
+ c.lineTo(x + w, y + h / 2);
5309
+ c.lineTo(x + w / 2, y + h);
5310
+ c.lineTo(x, y + h / 2);
5311
+ c.closePath();
5312
+ }
5313
+ strokeTask(hit) {
5314
+ if (hit.diamond) {
5315
+ this.diamond(hit.x, hit.y, hit.w, hit.h);
5316
+ this.ctx2d.stroke();
5317
+ } else if (this.opts.barShape === "rounded") {
5318
+ this.ctx2d.beginPath();
5319
+ this.ctx2d.roundRect(hit.x, hit.y, hit.w, hit.h, Math.min(6, hit.w / 2, hit.h / 2));
5320
+ this.ctx2d.stroke();
5321
+ } else this.ctx2d.strokeRect(hit.x + 1, hit.y, Math.max(1, hit.w - 2), hit.h);
5322
+ }
5323
+ /** 의존선은 전체 task 순회 대신 변경 때 만든 y 구간 인덱스로 viewport 후보만 선택한다. */
5324
+ paintDependencies(ctx, columns) {
5325
+ var _a;
5326
+ if (!((_a = this.opts.dependencies) == null ? void 0 : _a.length) || !this.pivotor) return;
5327
+ if (!this.dependencyIndex) this.buildDependencyIndex(ctx, columns);
5328
+ this.dependencyIndex.query(ctx.scrollTop, ctx.scrollTop + ctx.viewportHeight, this.dependencyScratch);
5329
+ const c = this.ctx2d;
5330
+ for (const { value: route } of this.dependencyScratch) {
5331
+ if (route.maxX < ctx.scrollLeft || route.minX > ctx.scrollLeft + ctx.viewportWidth) continue;
5332
+ if (this.opts.hideRemovedBars && (this.rowDirtyState(route.edge.from, ctx.getDirtyState) === "removed" || this.rowDirtyState(route.edge.to, ctx.getDirtyState) === "removed")) continue;
5333
+ const points = route.points;
5334
+ c.strokeStyle = route.edge.color ?? this.theme.dependency;
5335
+ c.fillStyle = route.edge.color ?? this.theme.dependency;
5336
+ c.lineWidth = route.edge.width ?? 1.5;
5337
+ c.setLineDash(route.dash);
5338
+ c.beginPath();
5339
+ c.moveTo(points[0], points[1]);
5340
+ for (let i = 2; i < points.length; i += 2) c.lineTo(points[i], points[i + 1]);
5341
+ c.stroke();
5342
+ c.setLineDash(EMPTY_DASH);
5343
+ const x = points[points.length - 2], y = points[points.length - 1];
5344
+ c.beginPath();
5345
+ c.moveTo(x, y);
5346
+ c.lineTo(x - route.direction * 6, y - 4);
5347
+ c.lineTo(x - route.direction * 6, y + 4);
5348
+ c.closePath();
5349
+ c.fill();
5350
+ }
5351
+ this.dependencyScratch.length = 0;
5352
+ }
5353
+ buildDependencyIndex(ctx, columns) {
5354
+ var _a;
5355
+ const edges = this.opts.dependencies ?? [];
5356
+ const needed = /* @__PURE__ */ new Set();
5357
+ for (const edge of edges) {
5358
+ needed.add(edge.from);
5359
+ needed.add(edge.to);
5360
+ }
5361
+ const endpoints = /* @__PURE__ */ new Map();
5362
+ const pivotor = this.pivotor;
5363
+ const first = columns.find(isTimeColumn);
5364
+ let last;
5365
+ for (let i = columns.length - 1; i >= 0; i--) if (isTimeColumn(columns[i])) {
5366
+ last = columns[i];
5367
+ break;
5368
+ }
5369
+ if (!first || !last) {
5370
+ this.dependencyIndex = new IntervalIndex([]);
5371
+ return;
5372
+ }
5373
+ for (const slot of ((_a = pivotor.getAllSlots) == null ? void 0 : _a.call(pivotor)) ?? ctx.visibleRows) {
5374
+ if (slot.cell.kind !== "explode" && slot.cell.kind !== "collapse") continue;
5375
+ const laneHeight = slot.height / this.levelCount(slot);
5376
+ const visit = (row) => {
5377
+ if (!row) return;
5378
+ const id = pivotor.resolveRowId(row);
5379
+ if (id == null || !needed.has(id)) return;
5380
+ const times = getRowTimes(pivotor, id, this.opts.startField, this.opts.endField, this.timeFieldKey);
5381
+ if (!hasVisibleTime(columns, times.startMs, times.endMs)) return;
5382
+ const start = Math.max(first.tickStartMs, Math.min(last.tickEndMs, times.startMs));
5383
+ const end = Math.max(start, Math.min(last.tickEndMs, times.endMs));
5384
+ const startCol = findColAtMs(columns, start) ?? first;
5385
+ const endCol = findColAtMs(columns, Math.max(start, end - 1)) ?? last;
5386
+ const level = slot.cell.kind === "collapse" ? this.rowLevel(id) : 1;
5387
+ const startX = msToPx(startCol, start);
5388
+ endpoints.set(id, { startX, endX: this.opts.milestoneField && pivotor.effective(id, this.opts.milestoneField) === true ? startX : msToPx(endCol, end), y: slot.top + (level - 0.5) * laneHeight });
5389
+ };
5390
+ if (slot.cell.kind === "explode") for (const row of slot.cell.cells) visit(row);
5391
+ else for (const rows of slot.cell.sourceRowsByCol.values()) for (const row of rows) visit(row);
5392
+ }
5393
+ const routes = [];
5394
+ for (const [order, edge] of edges.entries()) {
5395
+ const from = endpoints.get(edge.from), to = endpoints.get(edge.to);
5396
+ if (!from || !to) continue;
5397
+ const type = edge.type ?? "finish-start";
5398
+ const sourceFinish = type.startsWith("finish"), targetFinish = type.endsWith("finish");
5399
+ const x1 = sourceFinish ? from.endX : from.startX, x2 = targetFinish ? to.endX : to.startX;
5400
+ const sourceStub = x1 + (sourceFinish ? 12 : -12), targetStub = x2 + (targetFinish ? 12 : -12);
5401
+ const midY = from.y === to.y ? from.y + 16 : (from.y + to.y) / 2;
5402
+ const points = [x1, from.y, sourceStub, from.y, sourceStub, midY, targetStub, midY, targetStub, to.y, x2, to.y];
5403
+ routes.push({
5404
+ value: { edge, points, dash: edge.dash ? [...edge.dash] : EMPTY_DASH, direction: targetFinish ? -1 : 1, minX: Math.min(x1, x2, sourceStub, targetStub) - 4, maxX: Math.max(x1, x2, sourceStub, targetStub) + 4 },
5405
+ start: Math.min(from.y, to.y, midY) - 4,
5406
+ end: Math.max(from.y, to.y, midY) + 4,
5407
+ order
5408
+ });
5409
+ }
5410
+ this.dependencyIndex = new IntervalIndex(routes);
5411
+ }
4689
5412
  trimHitRegions() {
4690
5413
  for (let i = this.hitCount; i < this.hitRegions.length; i++) {
4691
5414
  this.hitRegions[i].row = null;
@@ -4908,7 +5631,15 @@ class GanttEditor {
4908
5631
  barColor: opts.barColor,
4909
5632
  lockedByField: opts.lockedByField,
4910
5633
  hideRemovedBars: opts.hideRemovedBars,
4911
- textCacheCapacity: opts.textCacheCapacity
5634
+ textCacheCapacity: opts.textCacheCapacity,
5635
+ milestoneField: opts.milestoneField,
5636
+ levelField: opts.levelField,
5637
+ dirtyField: opts.dirtyField,
5638
+ removedField: opts.removedField,
5639
+ dependencies: opts.dependencies,
5640
+ theme: opts.theme,
5641
+ selectedId: opts.selectedId,
5642
+ barShape: opts.barShape
4912
5643
  });
4913
5644
  const initialData = opts.data ?? [];
4914
5645
  this.pivotor = new Pivotor({
@@ -5096,8 +5827,9 @@ function withUpdatedTimeWidth(config, newWidth) {
5096
5827
  const ladder = normalizeTimeAxisSpec(oldField.timeAxis);
5097
5828
  const currentUnit = ladder.initial.unit;
5098
5829
  const currentWidth = ladder.initial.width;
5099
- const newMpp = unitMsAvg(currentUnit) / newWidth;
5100
- const target = pickStepByMpp(ladder.steps, newMpp);
5830
+ const durationOf = (unit) => averageTickDuration(oldField.timeAxis, unit);
5831
+ const newMpp = durationOf(currentUnit) / newWidth;
5832
+ const target = pickStepByMpp(ladder.steps, newMpp, durationOf);
5101
5833
  if (target.unit === currentUnit && Math.abs(target.width - currentWidth) < 1e-3) {
5102
5834
  return { config, changed: false, unitChanged: false, newWidth: target.width };
5103
5835
  }
@@ -5111,10 +5843,10 @@ function withUpdatedTimeWidth(config, newWidth) {
5111
5843
  newWidth: target.width
5112
5844
  };
5113
5845
  }
5114
- function pickStepByMpp(steps, mpp) {
5846
+ function pickStepByMpp(steps, mpp, durationOf = unitMsAvg) {
5115
5847
  const mppOf = (step) => ({
5116
- minMpp: unitMsAvg(step.unit) / step.maxWidth,
5117
- maxMpp: unitMsAvg(step.unit) / step.minWidth
5848
+ minMpp: durationOf(step.unit) / step.maxWidth,
5849
+ maxMpp: durationOf(step.unit) / step.minWidth
5118
5850
  });
5119
5851
  const first = steps[0];
5120
5852
  const last = steps[steps.length - 1];
@@ -5124,11 +5856,11 @@ function pickStepByMpp(steps, mpp) {
5124
5856
  for (const s of steps) {
5125
5857
  const { minMpp, maxMpp } = mppOf(s);
5126
5858
  if (clamped >= minMpp && clamped <= maxMpp) {
5127
- return { unit: s.unit, width: unitMsAvg(s.unit) / clamped };
5859
+ return { unit: s.unit, width: durationOf(s.unit) / clamped };
5128
5860
  }
5129
5861
  }
5130
5862
  const fallback = clamped >= globalMaxMpp ? first : last;
5131
- return { unit: fallback.unit, width: unitMsAvg(fallback.unit) / clamped };
5863
+ return { unit: fallback.unit, width: durationOf(fallback.unit) / clamped };
5132
5864
  }
5133
5865
  function updateActiveTickState(field, unit, width) {
5134
5866
  const spec = field.timeAxis;
@@ -5222,7 +5954,7 @@ class SearchController {
5222
5954
  const matchedRowIds = /* @__PURE__ */ new Set();
5223
5955
  if (!this.searchTextFn) return { matches, matchedRowIds };
5224
5956
  const matcher = this.compileMatcher(keyword, opts);
5225
- const matchKey = JSON.stringify([keyword, !!(opts == null ? void 0 : opts.caseSensitive), !!(opts == null ? void 0 : opts.useRegex)]);
5957
+ const matchKey = JSON.stringify([keyword, !!(opts == null ? void 0 : opts.caseSensitive), !!(opts == null ? void 0 : opts.useRegex), opts == null ? void 0 : opts.mode]);
5226
5958
  const rowMap = this.pivotor.getRowMap();
5227
5959
  for (const [rowId, row] of rowMap) {
5228
5960
  let entry = this.textCache.get(rowId);
@@ -5249,6 +5981,9 @@ class SearchController {
5249
5981
  resetCache() {
5250
5982
  this.textCache.clear();
5251
5983
  }
5984
+ setOptions(options) {
5985
+ this.lastOpts = options;
5986
+ }
5252
5987
  /** 현재 검색어를 유지해 재평가하되 사용자의 스크롤 위치를 강제 이동하지 않는다. */
5253
5988
  refresh() {
5254
5989
  var _a;
@@ -5322,6 +6057,10 @@ class SearchController {
5322
6057
  compileMatcher(keyword, opts) {
5323
6058
  const caseSensitive = (opts == null ? void 0 : opts.caseSensitive) ?? false;
5324
6059
  const useRegex = (opts == null ? void 0 : opts.useRegex) ?? false;
6060
+ if ((opts == null ? void 0 : opts.mode) === "exact") {
6061
+ const needle2 = caseSensitive ? keyword : keyword.toLowerCase();
6062
+ return { findAll: (text, folded) => (caseSensitive ? text : folded) === needle2 ? [{ start: 0, end: text.length }] : [] };
6063
+ }
5325
6064
  if (useRegex) {
5326
6065
  let re;
5327
6066
  try {
@@ -5371,55 +6110,88 @@ function toTime(value) {
5371
6110
  }
5372
6111
  throw new TypeError("Gantt dates must be finite epoch milliseconds or ISO strings with an explicit timezone");
5373
6112
  }
6113
+ const validId = (id) => typeof id === "string" ? id.length > 0 : typeof id === "number" && Number.isFinite(id);
5374
6114
  function validateSettings(options, timeAxisChanged = true) {
5375
- var _a;
5376
- if (timeAxisChanged) {
5377
- const { startMs, endMs } = options.timeAxis.range;
5378
- if (typeof startMs !== "number" || typeof endMs !== "number") throw new TypeError("Gantt time range must use epoch milliseconds");
5379
- toTime(startMs);
5380
- toTime(endMs);
5381
- if (endMs <= startMs) throw new RangeError("Gantt time range must have endMs > startMs");
5382
- const ladder = normalizeTimeAxisSpec(options.timeAxis);
5383
- if (!Number.isFinite(ladder.initial.width) || ladder.initial.width <= 0) throw new RangeError("Invalid tick width");
5384
- const units = /* @__PURE__ */ new Set(["hour", "day", "week", "month", "year"]);
5385
- if (!units.has(ladder.initial.unit) || !ladder.steps.some((step) => step.unit === ladder.initial.unit)) throw new RangeError("Invalid initial time unit");
5386
- for (const step of ladder.steps) {
5387
- if (!units.has(step.unit) || ((_a = step.headerHierarchy) == null ? void 0 : _a.some((unit) => !units.has(unit)))) throw new RangeError("Invalid time unit");
5388
- const first = floorTo(startMs, step.unit);
5389
- const last = ceilTo(endMs, step.unit);
5390
- if (!Number.isFinite(first) || !Number.isFinite(last)) throw new RangeError("Invalid time axis boundary");
5391
- let cursor = first;
5392
- let count = 0;
5393
- while (cursor < last) {
5394
- const next = advance(cursor, step.unit, 1);
5395
- if (!Number.isFinite(next) || next <= cursor || ++count > 1e5) throw new RangeError("Gantt time axis exceeds 100,000 ticks; use a coarser unit or smaller range");
5396
- cursor = next;
5397
- }
5398
- }
5399
- for (const step of options.timeAxis.tickLadder ? ladder.steps : []) {
5400
- if (!Number.isFinite(step.minWidth) || !Number.isFinite(step.maxWidth) || step.minWidth <= 0 || step.maxWidth < step.minWidth) throw new RangeError("Invalid zoom bounds");
5401
- }
5402
- if (options.timeAxis.tickLadder) {
5403
- const active = ladder.steps.find((step) => step.unit === ladder.initial.unit);
5404
- if (ladder.initial.width < active.minWidth || ladder.initial.width > active.maxWidth) throw new RangeError("Initial zoom is outside its tier bounds");
5405
- }
5406
- }
6115
+ var _a, _b;
6116
+ if (timeAxisChanged) validateTimeAxisSpec(options.timeAxis);
5407
6117
  for (const [name, value] of Object.entries({ rowHeight: options.rowHeight, zoomStep: options.zoomStep, minPxPerTick: options.minPxPerTick, maxPxPerTick: options.maxPxPerTick, textCacheCapacity: options.textCacheCapacity })) {
5408
6118
  if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) throw new RangeError(`${name} must be positive and finite`);
5409
6119
  }
5410
6120
  if ((options.minPxPerTick ?? 20) > (options.maxPxPerTick ?? 2e3)) throw new RangeError("Invalid zoom bounds");
5411
6121
  if (options.zoomStep !== void 0 && options.zoomStep <= 1) throw new RangeError("zoomStep must exceed 1");
6122
+ if (options.locale !== void 0) new Intl.DateTimeFormat(options.locale);
6123
+ if (((_a = options.searchOptions) == null ? void 0 : _a.mode) && !["contains", "exact"].includes(options.searchOptions.mode)) throw new TypeError("Invalid search mode");
6124
+ for (const field of options.rowFields ?? []) {
6125
+ if (!field.field) throw new TypeError("Row fields require a field name");
6126
+ if (field.sort !== void 0 && !["asc", "desc"].includes(field.sort)) throw new TypeError("Invalid row field sort");
6127
+ if (field.sortField !== void 0 && (typeof field.sortField !== "string" || !field.sortField.trim() || field.displayFromSlotIndex)) throw new TypeError("Row sortField requires a nonempty data field");
6128
+ for (const value of [field.width, field.minWidth, field.maxWidth]) if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) throw new RangeError("Invalid row field width");
6129
+ if ((field.minWidth ?? 24) > (field.maxWidth ?? 2e3)) throw new RangeError("Invalid row field width bounds");
6130
+ }
6131
+ for (const value of Object.values(options.messages ?? {})) if (typeof value !== "string") throw new TypeError("Gantt messages must be strings");
6132
+ for (const value of Object.values(options.theme ?? {})) if (typeof value !== "string" || value.length > 512) throw new TypeError("Invalid Gantt theme");
6133
+ const menuIds = /* @__PURE__ */ new Set();
6134
+ for (const item of Array.isArray(options.contextMenu) ? options.contextMenu : []) {
6135
+ if (!item.id || typeof item.label !== "string" || menuIds.has(item.id)) throw new TypeError("Menu items require unique ids and text labels");
6136
+ menuIds.add(item.id);
6137
+ }
6138
+ const edgeIds = /* @__PURE__ */ new Set();
6139
+ for (const edge of options.dependencies ?? []) {
6140
+ if (!validId(edge.from) || !validId(edge.to) || edge.from === edge.to) throw new TypeError("Invalid dependency endpoints");
6141
+ if (edge.id !== void 0) {
6142
+ if (!validId(edge.id) || edgeIds.has(edge.id)) throw new TypeError("Duplicate or invalid dependency id");
6143
+ edgeIds.add(edge.id);
6144
+ }
6145
+ if (edge.type !== void 0 && !["finish-start", "start-start", "finish-finish", "start-finish"].includes(edge.type)) throw new TypeError("Invalid dependency type");
6146
+ if (edge.width !== void 0 && (!Number.isFinite(edge.width) || edge.width <= 0)) throw new RangeError("Invalid dependency width");
6147
+ if ((_b = edge.dash) == null ? void 0 : _b.some((value) => !Number.isFinite(value) || value < 0)) throw new RangeError("Invalid dependency dash");
6148
+ }
6149
+ }
6150
+ function validateRowSortFields(row, options) {
6151
+ for (const field of options.rowFields ?? []) {
6152
+ if (!field.sortField) continue;
6153
+ const value = row[field.sortField];
6154
+ if (value != null && typeof value !== "string" && typeof value !== "boolean" && (typeof value !== "number" || !Number.isFinite(value))) {
6155
+ throw new TypeError(`Invalid row sort value in ${field.sortField}`);
6156
+ }
6157
+ }
6158
+ }
6159
+ function validateDependencies(options, hasRow) {
6160
+ for (const edge of options.dependencies ?? []) {
6161
+ if (!hasRow(edge.from) || !hasRow(edge.to)) throw new TypeError(`Unknown dependency endpoint: ${edge.from} → ${edge.to}`);
6162
+ }
5412
6163
  }
5413
6164
  function normalizeRow(row, options) {
5414
6165
  const id = row[options.idField ?? "id"];
5415
- if (typeof id !== "string" && typeof id !== "number" || id === "" || typeof id === "number" && !Number.isFinite(id)) throw new TypeError("Each Gantt task needs a unique string or numeric id");
5416
- const startField = options.startField ?? "start";
5417
- const endField = options.endField ?? "end";
6166
+ if (!validId(id)) throw new TypeError("Each Gantt task needs a unique string or numeric id");
6167
+ for (const field of [options.milestoneField, options.removedField, options.lockedField]) {
6168
+ if (field && row[field] !== void 0 && row[field] !== null && typeof row[field] !== "boolean") throw new TypeError(`Expected a boolean in ${field}`);
6169
+ }
6170
+ const level = options.levelField ? row[options.levelField] : void 0;
6171
+ if (level !== void 0 && level !== null && (typeof level !== "number" || !Number.isInteger(level) || level < 1 || level > 100)) throw new RangeError("Task level must be an integer from 1 to 100");
6172
+ const dirty = options.dirtyField ? row[options.dirtyField] : void 0;
6173
+ if (dirty !== void 0 && dirty !== null && !["added", "modified", "removed", "reordered", "locked"].includes(String(dirty))) throw new TypeError("Invalid task dirty state");
6174
+ const startField = options.startField ?? "start", endField = options.endField ?? "end";
5418
6175
  const start = toTime(row[startField]);
5419
- const end = toTime(row[endField]);
6176
+ const milestone = !!options.milestoneField && row[options.milestoneField] === true;
6177
+ const end = milestone && row[endField] == null ? start : toTime(row[endField]);
5420
6178
  if (end < start) throw new RangeError(`Task ${id} ends before it starts`);
6179
+ if (milestone && end !== start) throw new RangeError("Milestone start and end must be equal");
5421
6180
  return { ...row, [startField]: start, [endField]: end };
5422
6181
  }
6182
+ function validateOptions(options) {
6183
+ validateSettings(options);
6184
+ const seen = /* @__PURE__ */ new Set();
6185
+ const rows = (options.data ?? []).map((row) => {
6186
+ validateRowSortFields(row, options);
6187
+ const normalized = normalizeRow(row, options), id = normalized[options.idField ?? "id"];
6188
+ if (seen.has(id)) throw new TypeError("Each Gantt task needs a unique string or numeric id");
6189
+ seen.add(id);
6190
+ return normalized;
6191
+ });
6192
+ validateDependencies(options, (id) => seen.has(id));
6193
+ return rows;
6194
+ }
5423
6195
  class GanttTaskStore {
5424
6196
  constructor(options) {
5425
6197
  __publicField(this, "records", /* @__PURE__ */ new Map());
@@ -5540,61 +6312,455 @@ class GanttTaskStore {
5540
6312
  });
5541
6313
  }
5542
6314
  }
5543
- class MozGantt {
5544
- constructor(container, options) {
5545
- __publicField(this, "element");
5546
- __publicField(this, "toolbar");
5547
- __publicField(this, "viewport");
5548
- __publicField(this, "status");
5549
- __publicField(this, "searchStatus");
5550
- __publicField(this, "editor");
5551
- __publicField(this, "searchController");
5552
- __publicField(this, "options");
5553
- __publicField(this, "store");
5554
- __publicField(this, "buttons", []);
5555
- __publicField(this, "emitter", new EventEmitter());
5556
- __publicField(this, "controls", []);
5557
- __publicField(this, "input", null);
6315
+ const en = {
6316
+ controls: "Gantt controls",
6317
+ search: "Search tasks",
6318
+ previous: "Previous result",
6319
+ next: "Next result",
6320
+ zoomOut: "Zoom out",
6321
+ zoomIn: "Zoom in",
6322
+ timeline: "Gantt timeline (UTC)",
6323
+ keyboardHelp: "Use Up/Down or Home/End to select a task, Enter or Space to activate, Shift+F10 for actions, +/- to zoom, and Escape to close or clear search.",
6324
+ loading: "Loading…",
6325
+ empty: "No tasks",
6326
+ taskCount: "{count} tasks · UTC",
6327
+ task: "Task",
6328
+ milestone: "Milestone",
6329
+ start: "Start",
6330
+ end: "End",
6331
+ details: "Show details",
6332
+ focusTask: "Focus task",
6333
+ contextMenu: "Task actions",
6334
+ expand: "Expand",
6335
+ collapse: "Collapse",
6336
+ subtotal: "Subtotal",
6337
+ resizeColumn: "Resize {field}"
6338
+ };
6339
+ const ko = {
6340
+ controls: "간트 도구",
6341
+ search: "일정 검색",
6342
+ previous: "이전 결과",
6343
+ next: "다음 결과",
6344
+ zoomOut: "축소",
6345
+ zoomIn: "확대",
6346
+ timeline: "간트 시간축 (UTC)",
6347
+ keyboardHelp: "위·아래 또는 Home·End로 작업 선택, Enter·Space로 실행, Shift+F10으로 작업 메뉴, +/-로 확대·축소, Escape로 닫기 또는 검색 해제.",
6348
+ loading: "불러오는 중…",
6349
+ empty: "표시할 일정이 없습니다.",
6350
+ taskCount: "작업 {count}개 · UTC",
6351
+ task: "작업",
6352
+ milestone: "마일스톤",
6353
+ start: "시작",
6354
+ end: "종료",
6355
+ details: "상세 보기",
6356
+ focusTask: "작업으로 이동",
6357
+ contextMenu: "작업 메뉴",
6358
+ expand: "펼치기",
6359
+ collapse: "접기",
6360
+ subtotal: "소계",
6361
+ resizeColumn: "{field} 너비 조절"
6362
+ };
6363
+ function ganttMessages(locale = "en", overrides, timeZone = "UTC") {
6364
+ const base = locale.toLowerCase().startsWith("ko") ? ko : en;
6365
+ return { ...base, timeline: base.timeline.replace("UTC", timeZone), taskCount: base.taskCount.replace("UTC", timeZone), ...overrides };
6366
+ }
6367
+ function message(template, values) {
6368
+ return template.replace(/\{(\w+)\}/g, (match, key) => String(values[key] ?? match));
6369
+ }
6370
+ function formatTimeLabel(ms, unit, locale, timeZone = "UTC") {
6371
+ const date = new Date(wallTime(ms, timeZone)), ko2 = locale.toLowerCase().startsWith("ko");
6372
+ if (unit === "year") return String(date.getUTCFullYear());
6373
+ if (unit === "quarter") return ko2 ? `${Math.floor(date.getUTCMonth() / 3) + 1}분기` : `Q${Math.floor(date.getUTCMonth() / 3) + 1}`;
6374
+ if (unit === "month") return new Intl.DateTimeFormat(locale, { month: "short", timeZone }).format(ms);
6375
+ if (unit === "day") return String(date.getUTCDate());
6376
+ if (unit === "week") return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone }).format(ms);
6377
+ return `${String(date.getUTCHours()).padStart(2, "0")}:${String(date.getUTCMinutes()).padStart(2, "0")}`;
6378
+ }
6379
+ function formatGanttDateTime(ms, locale = "en", timeZone = "UTC") {
6380
+ if (timeZone === "UTC") return new Date(ms).toISOString();
6381
+ return `${new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "long", timeZone }).format(ms)} (${timeZone})`;
6382
+ }
6383
+ const themeDefaults = { ...DEFAULT_GANTT_THEME };
6384
+ const cssName = (key) => `--moz-gantt-${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
6385
+ class GanttThemeObserver {
6386
+ constructor(element, onChange) {
6387
+ __publicField(this, "observer", null);
6388
+ __publicField(this, "media", null);
6389
+ __publicField(this, "frame", 0);
6390
+ __publicField(this, "last", "");
6391
+ __publicField(this, "overrides", {});
6392
+ __publicField(this, "schedule", () => {
6393
+ if (!this.frame) this.frame = requestAnimationFrame(() => {
6394
+ this.frame = 0;
6395
+ this.read();
6396
+ });
6397
+ });
6398
+ var _a, _b;
6399
+ this.element = element;
6400
+ this.onChange = onChange;
6401
+ if (typeof MutationObserver !== "undefined") {
6402
+ this.observer = new MutationObserver(this.schedule);
6403
+ for (let node = element; node; node = node.parentElement) {
6404
+ this.observer.observe(node, { attributes: true, attributeFilter: ["theme", "data-theme", "class", "style"] });
6405
+ }
6406
+ }
6407
+ if (typeof matchMedia === "function") {
6408
+ this.media = matchMedia("(prefers-color-scheme: dark)");
6409
+ (_b = (_a = this.media).addEventListener) == null ? void 0 : _b.call(_a, "change", this.schedule);
6410
+ }
6411
+ }
6412
+ update(overrides = {}) {
6413
+ for (const key of Object.keys(themeDefaults)) {
6414
+ const name = cssName(key);
6415
+ if (overrides[key] !== void 0) {
6416
+ if (this.element.style.getPropertyValue(name) !== overrides[key]) this.element.style.setProperty(name, overrides[key]);
6417
+ } else if (this.overrides[key] !== void 0) this.element.style.removeProperty(name);
6418
+ }
6419
+ this.overrides = { ...overrides };
6420
+ return this.read();
6421
+ }
6422
+ read() {
6423
+ const style = getComputedStyle(this.element);
6424
+ const result = { ...themeDefaults };
6425
+ for (const key of Object.keys(result)) {
6426
+ result[key] = this.overrides[key] ?? (style.getPropertyValue(cssName(key)).trim() || themeDefaults[key]);
6427
+ }
6428
+ const serialized = JSON.stringify(result);
6429
+ if (this.last !== serialized) {
6430
+ this.last = serialized;
6431
+ this.onChange(result);
6432
+ }
6433
+ return result;
6434
+ }
6435
+ destroy() {
6436
+ var _a, _b, _c;
6437
+ cancelAnimationFrame(this.frame);
6438
+ this.frame = 0;
6439
+ (_a = this.observer) == null ? void 0 : _a.disconnect();
6440
+ (_c = (_b = this.media) == null ? void 0 : _b.removeEventListener) == null ? void 0 : _c.call(_b, "change", this.schedule);
6441
+ }
6442
+ }
6443
+ let nextId = 0;
6444
+ class GanttInteractions {
6445
+ constructor(host) {
6446
+ __publicField(this, "tooltip");
6447
+ __publicField(this, "menu", null);
6448
+ __publicField(this, "anchor", document.createElement("span"));
6449
+ __publicField(this, "tooltipHost", document.createElement("div"));
6450
+ __publicField(this, "menuHost", document.createElement("div"));
6451
+ __publicField(this, "tooltipId", `moz-gantt-tooltip-${++nextId}`);
6452
+ __publicField(this, "tooltipTask", null);
6453
+ __publicField(this, "tooltipText", "");
6454
+ __publicField(this, "overlayScrollState", "");
6455
+ __publicField(this, "menuTarget", null);
6456
+ __publicField(this, "restoreFocus", null);
5558
6457
  __publicField(this, "destroyed", false);
5559
- __publicField(this, "selectedIndex", -1);
5560
- __publicField(this, "searchOff", null);
5561
- __publicField(this, "onClick", (event) => {
5562
- if (this.blocked || this.destroyed) return;
5563
- const pane = this.viewport.querySelector(".pv-pane-body");
5564
- if (!pane || !pane.contains(event.target)) return;
5565
- const rect = pane.getBoundingClientRect();
5566
- const hit = this.editor.renderer.onHitTest(event.clientX - rect.left + pane.scrollLeft, event.clientY - rect.top + pane.scrollTop);
5567
- if ((hit == null ? void 0 : hit.sourceRowId) !== void 0) {
5568
- const row = hit.data;
5569
- this.status.textContent = this.describeRow(row);
5570
- this.emitter.emit("taskClick", { id: hit.sourceRowId, row, event });
6458
+ __publicField(this, "click", (event) => {
6459
+ if (this.blocked) return;
6460
+ const row = this.host.rowEvent(event);
6461
+ if (row) {
6462
+ this.host.emit("rowClick", row);
6463
+ return;
6464
+ }
6465
+ const task = this.host.hit(event);
6466
+ if (task) this.activate(task, event);
6467
+ });
6468
+ __publicField(this, "doubleClick", (event) => {
6469
+ if (this.blocked) return;
6470
+ const row = this.host.rowEvent(event);
6471
+ if (row) {
6472
+ this.host.emit("rowDoubleClick", row);
6473
+ return;
6474
+ }
6475
+ const task = this.host.hit(event);
6476
+ if (task) this.host.emit(this.milestone(task.row) ? "milestoneDoubleClick" : "taskDoubleClick", { ...task, event });
6477
+ });
6478
+ __publicField(this, "contextMenu", (event) => {
6479
+ if (this.blocked) return;
6480
+ const row = this.host.rowEvent(event);
6481
+ if (row) {
6482
+ event.preventDefault();
6483
+ this.host.emit("rowContextMenu", row);
6484
+ return;
6485
+ }
6486
+ const task = this.host.hit(event);
6487
+ if (task) this.openMenu(task, event);
6488
+ });
6489
+ __publicField(this, "pointerMove", (event) => {
6490
+ if (this.blocked || this.menu || this.host.options().tooltip === false) return;
6491
+ const task = this.host.hit(event);
6492
+ if (task) this.showTooltip(task, event.clientX, event.clientY);
6493
+ else this.hideTooltip();
6494
+ });
6495
+ __publicField(this, "pointerLeave", () => {
6496
+ this.hideTooltip();
6497
+ });
6498
+ __publicField(this, "focused", () => {
6499
+ const task = this.selectedTask();
6500
+ if (!this.blocked && task) this.showTooltip(task);
6501
+ });
6502
+ __publicField(this, "blurred", () => {
6503
+ this.hideTooltip();
6504
+ });
6505
+ __publicField(this, "scrolled", () => {
6506
+ if (this.scrollState() === this.overlayScrollState) return;
6507
+ this.hideTooltip();
6508
+ this.closeMenu(false);
6509
+ });
6510
+ __publicField(this, "menuKeyDown", (event) => {
6511
+ var _a, _b, _c;
6512
+ const items = Array.from(((_a = this.menuTarget) == null ? void 0 : _a.querySelectorAll("[role=menuitem][aria-disabled=false]")) ?? []);
6513
+ if (event.key === "Escape" || event.key === "Tab") {
6514
+ event.preventDefault();
6515
+ this.closeMenu(true);
6516
+ return;
5571
6517
  }
6518
+ if (event.key === "Enter" || event.key === " ") {
6519
+ event.preventDefault();
6520
+ (_b = document.activeElement) == null ? void 0 : _b.click();
6521
+ return;
6522
+ }
6523
+ if (!items.length || !["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) return;
6524
+ event.preventDefault();
6525
+ const current = items.indexOf(document.activeElement);
6526
+ const index = event.key === "Home" ? 0 : event.key === "End" ? items.length - 1 : (current + (event.key === "ArrowUp" ? -1 : 1) + items.length) % items.length;
6527
+ (_c = items[index]) == null ? void 0 : _c.focus({ preventScroll: true });
5572
6528
  });
5573
- __publicField(this, "onKeyDown", (event) => {
5574
- if (event.target !== this.viewport || this.blocked || this.destroyed) return;
6529
+ __publicField(this, "keyDown", (event) => {
6530
+ if (this.blocked) return;
6531
+ const header = this.host.rowEvent(event);
6532
+ if (header && (event.key === "Enter" || event.key === " ")) {
6533
+ event.preventDefault();
6534
+ this.host.emit("rowClick", header);
6535
+ return;
6536
+ }
6537
+ if (header && (event.key === "ContextMenu" || event.key === "F10" && event.shiftKey)) {
6538
+ event.preventDefault();
6539
+ this.host.emit("rowContextMenu", header);
6540
+ return;
6541
+ }
6542
+ if (event.target !== this.host.viewport) return;
5575
6543
  if (event.key === "+" || event.key === "=") {
5576
6544
  event.preventDefault();
5577
- this.zoomIn();
6545
+ this.host.zoomIn();
5578
6546
  return;
5579
6547
  }
5580
6548
  if (event.key === "-") {
5581
6549
  event.preventDefault();
5582
- this.zoomOut();
6550
+ this.host.zoomOut();
5583
6551
  return;
5584
6552
  }
5585
6553
  if (event.key === "Escape") {
5586
- this.clearSearch();
6554
+ event.preventDefault();
6555
+ this.hideTooltip();
6556
+ this.closeMenu(true);
6557
+ this.host.clearSearch();
6558
+ return;
6559
+ }
6560
+ const selected = this.selectedTask();
6561
+ if (selected && (event.key === "Enter" || event.key === " ")) {
6562
+ event.preventDefault();
6563
+ this.activate(selected, event);
6564
+ return;
6565
+ }
6566
+ if (selected && (event.key === "ContextMenu" || event.key === "F10" && event.shiftKey)) {
6567
+ this.openMenu(selected, event);
5587
6568
  return;
5588
6569
  }
5589
6570
  if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
5590
- const rows = this.store.rows;
6571
+ const rows = this.host.rows();
5591
6572
  if (!rows.length) return;
5592
6573
  event.preventDefault();
5593
- this.selectedIndex = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : Math.max(0, Math.min(rows.length - 1, this.selectedIndex + (event.key === "ArrowUp" ? -1 : 1)));
5594
- const row = rows[this.selectedIndex];
5595
- this.scrollToTask(row[this.options.idField ?? "id"]);
5596
- this.status.textContent = this.describeRow(row);
6574
+ const field = this.host.options().idField ?? "id";
6575
+ const index = rows.findIndex((row) => row[field] === this.host.selected());
6576
+ const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowUp" ? -1 : 1)));
6577
+ this.host.select(rows[next][field]);
6578
+ const task = this.selectedTask();
6579
+ if (task) this.showTooltip(task);
5597
6580
  });
6581
+ this.host = host;
6582
+ Object.assign(this.anchor.style, { position: "fixed", width: "1px", height: "1px", pointerEvents: "none" });
6583
+ this.anchor.setAttribute("aria-hidden", "true");
6584
+ Object.assign(this.menuHost.style, { position: "fixed", left: "0", top: "0", width: "0", height: "0", zIndex: "1503" });
6585
+ document.body.append(this.anchor, this.tooltipHost, this.menuHost);
6586
+ this.tooltip = createTooltip(this.tooltipHost, { open: false, anchor: this.anchor, tooltipId: this.tooltipId, class: "moz-gantt-tooltip" }, () => {
6587
+ }, {
6588
+ slots: { content: (container) => {
6589
+ const content = document.createElement("span");
6590
+ content.style.whiteSpace = "pre-line";
6591
+ const update = () => {
6592
+ content.textContent = this.tooltipText;
6593
+ };
6594
+ container.append(content);
6595
+ update();
6596
+ return { update, dispose: () => content.remove() };
6597
+ } }
6598
+ });
6599
+ host.viewport.addEventListener("click", this.click);
6600
+ host.viewport.addEventListener("dblclick", this.doubleClick);
6601
+ host.viewport.addEventListener("contextmenu", this.contextMenu);
6602
+ host.viewport.addEventListener("pointermove", this.pointerMove);
6603
+ host.viewport.addEventListener("pointerleave", this.pointerLeave);
6604
+ host.viewport.addEventListener("keydown", this.keyDown);
6605
+ host.viewport.addEventListener("focus", this.focused);
6606
+ host.viewport.addEventListener("blur", this.blurred);
6607
+ host.viewport.addEventListener("scroll", this.scrolled, true);
6608
+ }
6609
+ get blocked() {
6610
+ const o = this.host.options();
6611
+ return this.destroyed || !!(o.loading || o.disabled);
6612
+ }
6613
+ milestone(row) {
6614
+ const field = this.host.options().milestoneField;
6615
+ return !!field && row[field] === true;
6616
+ }
6617
+ selectedTask() {
6618
+ const id = this.host.selected(), field = this.host.options().idField ?? "id";
6619
+ const row = this.host.rows().find((row2) => row2[field] === id);
6620
+ return id !== null && row ? { id, row } : null;
6621
+ }
6622
+ activate(task, event) {
6623
+ this.host.select(task.id);
6624
+ if (event instanceof MouseEvent) this.host.emit("taskClick", { ...task, event });
6625
+ if (this.milestone(task.row)) this.host.emit("milestoneClick", { ...task, event });
6626
+ this.host.emit("taskActivate", { ...task, event, source: event instanceof KeyboardEvent ? "keyboard" : "pointer" });
6627
+ if (event instanceof KeyboardEvent) this.showTooltip(task);
6628
+ }
6629
+ scrollState() {
6630
+ const pane = this.host.viewport.querySelector(".pv-pane-body");
6631
+ return `${(pane == null ? void 0 : pane.scrollLeft) ?? 0},${(pane == null ? void 0 : pane.scrollTop) ?? 0},${this.host.viewport.scrollLeft},${this.host.viewport.scrollTop}`;
6632
+ }
6633
+ showTooltip(task, x, y) {
6634
+ var _a;
6635
+ if (this.host.options().tooltip === false) return;
6636
+ const o = this.host.options(), spec = typeof o.tooltip === "object" ? o.tooltip : void 0;
6637
+ const rect = this.host.viewport.getBoundingClientRect();
6638
+ this.anchor.style.left = `${x ?? rect.left + rect.width / 2}px`;
6639
+ this.anchor.style.top = `${y ?? rect.top + 40}px`;
6640
+ const text = (spec == null ? void 0 : spec.format) ? spec.format(task.row) : ((_a = spec == null ? void 0 : spec.fields) == null ? void 0 : _a.length) ? spec.fields.map((field) => `${field}: ${String(task.row[field] ?? "")}`).join("\n") : this.host.describe(task.row);
6641
+ this.tooltipTask = task.id;
6642
+ this.tooltipText = text;
6643
+ this.overlayScrollState = this.scrollState();
6644
+ this.tooltip.update({ open: true, style: this.overlayStyle() });
6645
+ this.tooltip.api.reposition();
6646
+ this.host.viewport.setAttribute("aria-describedby", this.tooltipId);
6647
+ }
6648
+ overlayStyle() {
6649
+ const style = getComputedStyle(this.host.element);
6650
+ return {
6651
+ "--color-background": style.backgroundColor,
6652
+ "--color-text": style.color,
6653
+ background: style.backgroundColor,
6654
+ color: style.color,
6655
+ whiteSpace: "normal"
6656
+ };
6657
+ }
6658
+ hideTooltip() {
6659
+ if (this.tooltipTask === null) return;
6660
+ this.tooltipTask = null;
6661
+ this.tooltip.update({ open: false });
6662
+ this.host.viewport.removeAttribute("aria-describedby");
6663
+ }
6664
+ openMenu(task, event) {
6665
+ event.preventDefault();
6666
+ this.closeMenu(false);
6667
+ this.hideTooltip();
6668
+ this.host.select(task.id);
6669
+ this.host.emit("contextMenu", { ...task, event });
6670
+ this.host.emit(this.milestone(task.row) ? "milestoneContextMenu" : "taskContextMenu", { ...task, event });
6671
+ if (this.host.options().contextMenu === false) return;
6672
+ const o = this.host.options(), labels = ganttMessages(o.locale, o.messages);
6673
+ const items = Array.isArray(o.contextMenu) ? o.contextMenu : [{ id: "details", label: labels.details }, { id: "focus", label: labels.focusTask }];
6674
+ if (!items.length) return;
6675
+ const rect = this.host.viewport.getBoundingClientRect();
6676
+ const x = event instanceof MouseEvent ? event.clientX : rect.left + Math.min(rect.width / 2, 240);
6677
+ const y = event instanceof MouseEvent ? event.clientY : rect.top + 40;
6678
+ this.restoreFocus = document.activeElement instanceof HTMLElement ? document.activeElement : this.host.viewport;
6679
+ const menu = createContextMenu(this.menuHost, {
6680
+ itemSource: items.map((item) => ({ text: item.label, disabled: item.disabled, function: () => {
6681
+ if (item.disabled || this.blocked) return;
6682
+ this.closeMenu(true);
6683
+ if (item.id === "details") this.showTooltip(task);
6684
+ if (item.id === "focus") this.host.select(task.id);
6685
+ this.host.emit("menuAction", { ...task, action: item.id, event });
6686
+ } })),
6687
+ fixPosition: { left: Math.max(8, Math.min(x, window.innerWidth - 200)), top: Math.max(8, Math.min(y, window.innerHeight - items.length * 32 - 16)), useTeleport: false },
6688
+ class: "moz-gantt-context-menu",
6689
+ style: this.overlayStyle(),
6690
+ "aria-label": labels.contextMenu
6691
+ }, (name, ...args) => {
6692
+ var _a, _b;
6693
+ if (name === "open" && !this.destroyed && this.menu === menu) {
6694
+ const target = (_a = args[0]) == null ? void 0 : _a.target;
6695
+ if (target) {
6696
+ this.menuTarget = target;
6697
+ target.setAttribute("aria-label", labels.contextMenu);
6698
+ target.addEventListener("keydown", this.menuKeyDown);
6699
+ (_b = target.querySelector("[role=menuitem][aria-disabled=false]")) == null ? void 0 : _b.focus({ preventScroll: true });
6700
+ }
6701
+ } else if (name === "close" && this.menu === menu) this.closeMenu(true);
6702
+ });
6703
+ this.overlayScrollState = this.scrollState();
6704
+ this.menu = menu;
6705
+ menu.api.open();
6706
+ }
6707
+ closeMenu(restore) {
6708
+ var _a, _b;
6709
+ if (!this.menu) return;
6710
+ const menu = this.menu;
6711
+ this.menu = null;
6712
+ (_a = this.menuTarget) == null ? void 0 : _a.removeEventListener("keydown", this.menuKeyDown);
6713
+ this.menuTarget = null;
6714
+ menu.destroy();
6715
+ if (restore) (((_b = this.restoreFocus) == null ? void 0 : _b.isConnected) ? this.restoreFocus : this.host.viewport).focus({ preventScroll: true });
6716
+ this.restoreFocus = null;
6717
+ }
6718
+ invalidate() {
6719
+ this.hideTooltip();
6720
+ this.closeMenu(false);
6721
+ }
6722
+ destroy() {
6723
+ this.destroyed = true;
6724
+ this.invalidate();
6725
+ this.tooltip.destroy();
6726
+ const v = this.host.viewport;
6727
+ v.removeEventListener("click", this.click);
6728
+ v.removeEventListener("dblclick", this.doubleClick);
6729
+ v.removeEventListener("contextmenu", this.contextMenu);
6730
+ v.removeEventListener("pointermove", this.pointerMove);
6731
+ v.removeEventListener("pointerleave", this.pointerLeave);
6732
+ v.removeEventListener("keydown", this.keyDown);
6733
+ v.removeEventListener("focus", this.focused);
6734
+ v.removeEventListener("blur", this.blurred);
6735
+ v.removeEventListener("scroll", this.scrolled, true);
6736
+ this.anchor.remove();
6737
+ this.tooltipHost.remove();
6738
+ this.menuHost.remove();
6739
+ }
6740
+ }
6741
+ class MozGantt {
6742
+ constructor(container, options) {
6743
+ __publicField(this, "element");
6744
+ __publicField(this, "toolbar");
6745
+ __publicField(this, "viewport");
6746
+ __publicField(this, "status");
6747
+ __publicField(this, "searchStatus");
6748
+ __publicField(this, "editor");
6749
+ __publicField(this, "searchController");
6750
+ __publicField(this, "options");
6751
+ __publicField(this, "store");
6752
+ __publicField(this, "buttons", []);
6753
+ __publicField(this, "emitter", new EventEmitter());
6754
+ __publicField(this, "controls", []);
6755
+ __publicField(this, "input", null);
6756
+ __publicField(this, "destroyed", false);
6757
+ __publicField(this, "selectedId", null);
6758
+ __publicField(this, "searchOff", null);
6759
+ __publicField(this, "sourceOff", null);
6760
+ __publicField(this, "themeObserver");
6761
+ __publicField(this, "theme", { ...themeDefaults });
6762
+ __publicField(this, "interactions");
6763
+ __publicField(this, "help");
5598
6764
  validateSettings(options);
5599
6765
  this.options = { ...options };
5600
6766
  this.store = this.makeStore(options, options.data ?? []);
@@ -5608,8 +6774,6 @@ class MozGantt {
5608
6774
  this.viewport.className = "moz-gantt-viewport";
5609
6775
  this.viewport.tabIndex = 0;
5610
6776
  this.viewport.setAttribute("role", "region");
5611
- this.viewport.addEventListener("click", this.onClick);
5612
- this.viewport.addEventListener("keydown", this.onKeyDown);
5613
6777
  this.status = document.createElement("div");
5614
6778
  this.status.className = "moz-gantt-status";
5615
6779
  this.status.setAttribute("role", "status");
@@ -5617,10 +6781,35 @@ class MozGantt {
5617
6781
  this.searchStatus = document.createElement("span");
5618
6782
  this.searchStatus.className = "moz-gantt-search-count";
5619
6783
  this.searchStatus.setAttribute("aria-live", "polite");
5620
- this.element.append(this.toolbar, this.viewport, this.status);
6784
+ this.help = document.createElement("p");
6785
+ this.help.className = "moz-gantt-keyboard-help";
6786
+ this.help.id = `moz-gantt-help-${++nextGanttId}`;
6787
+ this.viewport.setAttribute("aria-details", this.help.id);
6788
+ this.element.append(this.toolbar, this.viewport, this.status, this.help);
5621
6789
  container.append(this.element);
5622
6790
  try {
6791
+ this.themeObserver = new GanttThemeObserver(this.element, (theme) => {
6792
+ var _a;
6793
+ this.theme = theme;
6794
+ (_a = this.editor) == null ? void 0 : _a.updateAppearance({ theme });
6795
+ });
6796
+ this.theme = this.themeObserver.update(options.theme);
5623
6797
  this.createViewer([...this.store.rows]);
6798
+ this.interactions = new GanttInteractions({
6799
+ element: this.element,
6800
+ viewport: this.viewport,
6801
+ options: () => this.options,
6802
+ rows: () => this.navigationRows(),
6803
+ selected: () => this.selectedId,
6804
+ select: (id) => this.selectTask(id),
6805
+ hit: (event) => this.hitTask(event),
6806
+ rowEvent: (event) => this.rowEvent(event),
6807
+ describe: (row) => this.describeRow(row),
6808
+ emit: (name, value) => this.emitter.emit(name, value),
6809
+ zoomIn: () => this.zoomIn(),
6810
+ zoomOut: () => this.zoomOut(),
6811
+ clearSearch: () => this.clearSearch()
6812
+ });
5624
6813
  } catch (error) {
5625
6814
  this.destroy();
5626
6815
  throw error;
@@ -5629,26 +6818,22 @@ class MozGantt {
5629
6818
  createViewer(data) {
5630
6819
  const o = this.options;
5631
6820
  const idField = o.idField ?? "id";
5632
- this.viewport.setAttribute("aria-label", o.ariaLabel ?? "Gantt timeline (UTC). Use Up and Down to browse tasks.");
6821
+ this.viewport.setAttribute("aria-label", o.ariaLabel ?? this.labels.timeline);
5633
6822
  this.element.setAttribute("aria-busy", String(o.loading ?? false));
5634
6823
  this.element.setAttribute("aria-disabled", String(o.disabled ?? false));
5635
6824
  this.editor = new GanttEditor({
5636
6825
  container: this.viewport,
5637
6826
  config: {
5638
6827
  keyFields: [idField],
5639
- rowFields: o.rowFields ?? [{ field: o.labelField ?? "label", header: "Task", width: 200 }],
5640
- columnFields: [{ kind: "time", timeAxis: o.timeAxis }],
5641
- rowExpansion: { kind: o.rowLayout === "overlay" ? "collapse" : "explode", rowHeight: o.rowHeight ?? 32 },
6828
+ ...this.layout(),
6829
+ columnFields: [{ kind: "time", timeAxis: this.timeAxis() }],
5642
6830
  columnExpansion: { kind: "flat" },
5643
6831
  headerHeight: 28
5644
6832
  },
5645
6833
  data,
5646
6834
  startField: o.startField ?? "start",
5647
6835
  endField: o.endField ?? "end",
5648
- barLabel: o.barLabel ?? defaultLabel(o.labelField ?? "label", idField),
5649
- barColor: o.barColor,
5650
- paintBar: o.paintBar,
5651
- textCacheCapacity: o.textCacheCapacity,
6836
+ ...this.appearance(),
5652
6837
  enableZoom: o.enableZoom !== false && !this.blocked,
5653
6838
  minPxPerTick: o.minPxPerTick,
5654
6839
  maxPxPerTick: o.maxPxPerTick,
@@ -5670,8 +6855,43 @@ class MozGantt {
5670
6855
  this.emitter.emit("search", state);
5671
6856
  });
5672
6857
  this.renderToolbar();
6858
+ this.updateControls();
5673
6859
  this.refreshStatus();
5674
6860
  }
6861
+ get labels() {
6862
+ return ganttMessages(this.options.locale, this.options.messages, this.options.timeAxis.timeZone);
6863
+ }
6864
+ layout() {
6865
+ const o = this.options;
6866
+ return {
6867
+ rowFields: (o.rowFields ?? [{ field: o.labelField ?? "label", header: this.labels.task, width: 200 }]).map((field) => ({ ...field })),
6868
+ rowExpansion: o.rowLayout === "overlay" ? { kind: "collapse", rowHeight: o.rowHeight ?? 32, levelField: o.levelField } : { kind: "explode", rowHeight: o.rowHeight ?? 32 },
6869
+ labels: this.labels,
6870
+ rowHeaderResizable: o.splitter !== false
6871
+ };
6872
+ }
6873
+ timeAxis() {
6874
+ return { ...this.options.timeAxis, format: this.options.timeAxis.format ?? ((ms, unit) => formatTimeLabel(ms, unit, this.options.locale ?? "en", this.options.timeAxis.timeZone)) };
6875
+ }
6876
+ appearance() {
6877
+ const o = this.options;
6878
+ return {
6879
+ barLabel: o.barLabel ?? defaultLabel(o.labelField ?? "label", o.idField ?? "id"),
6880
+ barColor: o.barColor,
6881
+ paintBar: o.paintBar,
6882
+ textCacheCapacity: o.textCacheCapacity,
6883
+ barShape: o.barShape,
6884
+ milestoneField: o.milestoneField,
6885
+ levelField: o.levelField,
6886
+ lockedByField: o.lockedField,
6887
+ dirtyField: o.dirtyField,
6888
+ removedField: o.removedField,
6889
+ hideRemovedBars: o.hideRemovedBars,
6890
+ dependencies: o.dependencies,
6891
+ theme: this.theme,
6892
+ selectedId: this.selectedId ?? void 0
6893
+ };
6894
+ }
5675
6895
  get blocked() {
5676
6896
  return !!(this.options.disabled || this.options.loading);
5677
6897
  }
@@ -5683,32 +6903,67 @@ class MozGantt {
5683
6903
  this.input = null;
5684
6904
  this.toolbar.replaceChildren();
5685
6905
  this.toolbar.hidden = this.options.toolbar === false;
6906
+ this.toolbar.setAttribute("aria-label", this.labels.controls);
5686
6907
  if (this.toolbar.hidden) return;
6908
+ const search = document.createElement("div");
6909
+ search.className = "moz-gantt-search";
5687
6910
  const inputHost = document.createElement("div");
5688
- this.toolbar.append(inputHost);
5689
- this.input = createInput(inputHost, { modelValue: ((_a = this.searchController.getState()) == null ? void 0 : _a.keyword) ?? "", placeholder: "Search tasks", "aria-label": "Search tasks", width: 220, disabled: this.blocked }, (name, ...args) => {
6911
+ const navigation = document.createElement("div");
6912
+ navigation.className = "moz-gantt-search-navigation";
6913
+ const zoomControls = document.createElement("div");
6914
+ zoomControls.className = "moz-gantt-zoom-controls";
6915
+ search.append(inputHost, navigation);
6916
+ this.toolbar.append(search, this.searchStatus, zoomControls);
6917
+ this.input = createInput(inputHost, { modelValue: ((_a = this.searchController.getState()) == null ? void 0 : _a.keyword) ?? "", placeholder: this.labels.search, "aria-label": this.labels.search, width: "100%", disabled: this.blocked }, (name, ...args) => {
5690
6918
  if (name === "update:modelValue") this.search(String(args[0]));
5691
6919
  if (name === "enter") this.findNext();
5692
6920
  });
5693
6921
  this.controls.push(this.input);
5694
- for (const [label, action, zoom] of [
5695
- ["Previous result", () => this.findPrevious(), false],
5696
- ["Next result", () => this.findNext(), false],
5697
- ["Zoom out", () => this.zoomOut(), true],
5698
- ["Zoom in", () => this.zoomIn(), true]
6922
+ for (const [label, action, zoom, path] of [
6923
+ [this.labels.previous, () => this.findPrevious(), false, "m12 4-6 5 6 5"],
6924
+ [this.labels.next, () => this.findNext(), false, "m6 4 6 5-6 5"],
6925
+ [this.labels.zoomOut, () => this.zoomOut(), true, "M4 9h10"],
6926
+ [this.labels.zoomIn, () => this.zoomIn(), true, "M4 9h10M9 4v10"]
5699
6927
  ]) {
5700
6928
  const host = document.createElement("div");
5701
- this.toolbar.append(host);
5702
- const control = createButton(host, { text: label, "aria-label": label, nativeType: "button", type: "outline", size: "small", disabled: this.blocked || zoom && this.options.enableZoom === false }, () => action());
6929
+ (zoom ? zoomControls : navigation).append(host);
6930
+ const control = createButton(host, { "aria-label": label, title: label, nativeType: "button", type: "icon", class: "moz-gantt-toolbar-icon", disabled: this.blocked || zoom && this.options.enableZoom === false }, () => action(), {
6931
+ slots: { icon: (container) => {
6932
+ const icon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
6933
+ icon.setAttribute("viewBox", "0 0 18 18");
6934
+ icon.setAttribute("aria-hidden", "true");
6935
+ icon.setAttribute("focusable", "false");
6936
+ const stroke = document.createElementNS(icon.namespaceURI, "path");
6937
+ stroke.setAttribute("d", path);
6938
+ stroke.setAttribute("fill", "none");
6939
+ stroke.setAttribute("stroke", "currentColor");
6940
+ stroke.setAttribute("stroke-width", "1.75");
6941
+ stroke.setAttribute("stroke-linecap", "round");
6942
+ stroke.setAttribute("stroke-linejoin", "round");
6943
+ icon.append(stroke);
6944
+ container.append(icon);
6945
+ return { dispose: () => icon.remove() };
6946
+ } }
6947
+ });
5703
6948
  this.controls.push(control);
5704
6949
  this.buttons.push({ control, zoom });
5705
6950
  }
5706
- this.toolbar.append(this.searchStatus);
5707
6951
  }
5708
6952
  makeStore(options, data) {
5709
- const fields = { idField: options.idField, startField: options.startField, endField: options.endField };
6953
+ for (const row of data) validateRowSortFields(row, options);
6954
+ const fields = {
6955
+ idField: options.idField,
6956
+ startField: options.startField,
6957
+ endField: options.endField,
6958
+ milestoneField: options.milestoneField,
6959
+ levelField: options.levelField,
6960
+ lockedField: options.lockedField,
6961
+ dirtyField: options.dirtyField,
6962
+ removedField: options.removedField
6963
+ };
5710
6964
  const store = new GanttTaskStore({ idField: fields.idField ?? "id", normalize: (row) => normalizeRow(row, fields) });
5711
6965
  store.prepareReplace(data).commit();
6966
+ validateDependencies(options, (id) => !!store.get(id));
5712
6967
  return store;
5713
6968
  }
5714
6969
  searchProjection() {
@@ -5717,7 +6972,7 @@ class MozGantt {
5717
6972
  }
5718
6973
  /** 작은 설정 객체의 의미를 비교한다. 대량 data 배열은 참조 비교 후 저장소에서 diff한다. */
5719
6974
  update(next) {
5720
- var _a, _b;
6975
+ var _a, _b, _c, _d;
5721
6976
  if (this.destroyed) return;
5722
6977
  const keys = Object.keys(next).filter((key) => key === "data" ? !Object.is(next.data, this.options.data) : !sameSetting(next[key], this.options[key]));
5723
6978
  if (!keys.length) return;
@@ -5725,35 +6980,31 @@ class MozGantt {
5725
6980
  const options = { ...this.options, ...next };
5726
6981
  if (keys.some((key) => key !== "data")) validateSettings(options, changed("timeAxis"));
5727
6982
  const keyword = ((_a = this.searchController.getState()) == null ? void 0 : _a.keyword) ?? "";
5728
- if (changed("idField", "startField", "endField")) {
6983
+ if (changed("idField", "startField", "endField", "milestoneField", "levelField", "lockedField", "dirtyField", "removedField")) {
5729
6984
  const store = this.makeStore(options, changed("data") ? options.data ?? [] : this.store.rows);
6985
+ this.detachDataSource();
5730
6986
  (_b = this.searchOff) == null ? void 0 : _b.call(this);
5731
6987
  this.searchController.destroy();
5732
6988
  this.editor.destroy();
6989
+ (_c = this.interactions) == null ? void 0 : _c.invalidate();
5733
6990
  this.options = options;
5734
6991
  this.store = store;
5735
- this.selectedIndex = -1;
6992
+ this.selectedId = null;
5736
6993
  this.createViewer([...store.rows]);
5737
- if (keyword) this.searchController.search(keyword);
6994
+ if (keyword) this.searchController.search(keyword, options.searchOptions);
5738
6995
  return;
5739
6996
  }
5740
6997
  const transaction = changed("data") ? this.store.prepareReplace(options.data ?? []) : null;
6998
+ this.checkTransaction(transaction, options);
5741
6999
  this.options = options;
5742
7000
  if (transaction) this.commitData(transaction, false);
5743
- if (changed("rowFields", "rowLayout", "rowHeight") || changed("labelField") && !options.rowFields) {
5744
- this.editor.updateLayout({
5745
- rowFields: options.rowFields ?? [{ field: options.labelField ?? "label", header: "Task", width: 200 }],
5746
- rowExpansion: { kind: options.rowLayout === "overlay" ? "collapse" : "explode", rowHeight: options.rowHeight ?? 32 }
5747
- });
7001
+ if (changed("rowFields", "rowLayout", "rowHeight", "locale", "messages", "splitter") || changed("labelField") && !options.rowFields) {
7002
+ this.editor.updateLayout(this.layout());
5748
7003
  }
5749
- if (changed("timeAxis")) this.editor.updateTimeAxis(options.timeAxis);
5750
- if (changed("barLabel", "labelField", "barColor", "paintBar", "textCacheCapacity")) {
5751
- this.editor.updateAppearance({
5752
- barLabel: options.barLabel ?? defaultLabel(options.labelField ?? "label", options.idField ?? "id"),
5753
- barColor: options.barColor,
5754
- paintBar: options.paintBar,
5755
- textCacheCapacity: options.textCacheCapacity
5756
- });
7004
+ if (changed("timeAxis", "locale")) this.editor.updateTimeAxis(this.timeAxis());
7005
+ if (changed("theme")) this.theme = this.themeObserver.update(options.theme);
7006
+ if (changed("barLabel", "labelField", "barColor", "paintBar", "textCacheCapacity", "barShape", "theme", "hideRemovedBars", "dependencies")) {
7007
+ this.editor.updateAppearance(this.appearance());
5757
7008
  }
5758
7009
  if (changed("enableZoom", "disabled", "loading", "minPxPerTick", "maxPxPerTick", "zoomStep")) {
5759
7010
  this.editor.updateZoomOptions({
@@ -5766,23 +7017,34 @@ class MozGantt {
5766
7017
  if (changed("minPxPerTick", "maxPxPerTick") && !options.timeAxis.tickLadder) {
5767
7018
  this.editor.setZoom(Math.min(options.maxPxPerTick ?? 2e3, Math.max(options.minPxPerTick ?? 20, this.getZoom())));
5768
7019
  }
5769
- if (changed("searchFields", "searchText", "labelField")) {
7020
+ if (changed("searchFields", "searchText", "labelField", "searchOptions")) {
5770
7021
  this.searchController.setSearchTextFn(this.searchProjection(), { preserveState: true });
7022
+ this.searchController.setOptions(options.searchOptions);
5771
7023
  this.searchController.refresh();
5772
7024
  } else if (transaction == null ? void 0 : transaction.changed) this.searchController.refresh();
5773
- if (changed("toolbar")) this.renderToolbar();
7025
+ if (changed("toolbar", "locale", "messages")) this.renderToolbar();
7026
+ if (changed("loading", "disabled", "tooltip", "contextMenu", "locale", "messages", "hideRemovedBars", "timeAxis")) (_d = this.interactions) == null ? void 0 : _d.invalidate();
5774
7027
  this.updateControls();
5775
7028
  this.refreshStatus();
5776
7029
  }
5777
7030
  updateControls() {
5778
7031
  var _a;
5779
- this.viewport.setAttribute("aria-label", this.options.ariaLabel ?? "Gantt timeline (UTC). Use Up and Down to browse tasks.");
7032
+ this.viewport.setAttribute("aria-label", `${this.options.ariaLabel ?? this.labels.timeline}. ${this.labels.keyboardHelp}`);
7033
+ this.viewport.setAttribute("aria-keyshortcuts", "ArrowUp ArrowDown Home End Enter Space Shift+F10 + - Escape");
7034
+ this.help.textContent = this.labels.keyboardHelp;
7035
+ for (const handle of this.viewport.querySelectorAll(".pv-row-header-resize-handle")) {
7036
+ handle.setAttribute("aria-disabled", String(this.blocked));
7037
+ handle.tabIndex = this.blocked ? -1 : 0;
7038
+ handle.style.pointerEvents = this.blocked ? "none" : "";
7039
+ }
7040
+ for (const button of this.viewport.querySelectorAll(".pv-rh-collapser")) button.disabled = this.blocked;
5780
7041
  this.element.setAttribute("aria-busy", String(this.options.loading ?? false));
5781
7042
  this.element.setAttribute("aria-disabled", String(this.options.disabled ?? false));
5782
7043
  (_a = this.input) == null ? void 0 : _a.update({ disabled: this.blocked });
5783
7044
  for (const { control, zoom } of this.buttons) control.update({ disabled: this.blocked || zoom && this.options.enableZoom === false });
5784
7045
  }
5785
7046
  commitData(transaction, refresh = true) {
7047
+ var _a;
5786
7048
  transaction.commit();
5787
7049
  if (!transaction.changed) return;
5788
7050
  const ids = [...transaction.updated.map((row) => row.id), ...transaction.removed.map((row) => row.id)];
@@ -5790,19 +7052,80 @@ class MozGantt {
5790
7052
  if (transaction.orderChanged) {
5791
7053
  this.editor.setData([...this.store.rows]);
5792
7054
  } else this.editor.applyDataChanges(transaction);
5793
- this.selectedIndex = -1;
7055
+ (_a = this.interactions) == null ? void 0 : _a.invalidate();
7056
+ if (this.selectedId !== null && !this.store.get(this.selectedId)) this.clearSelection();
5794
7057
  if (refresh) this.searchController.refresh();
5795
7058
  this.refreshStatus();
5796
7059
  }
5797
7060
  setData(data) {
5798
7061
  if (this.destroyed) return;
5799
7062
  const transaction = this.store.prepareReplace(data);
5800
- this.options = { ...this.options, data };
7063
+ this.checkTransaction(transaction, this.options);
5801
7064
  this.commitData(transaction);
5802
7065
  }
5803
7066
  /** ID 단위 원자적 추가/수정/삭제. 잘못된 patch는 데이터와 화면을 변경하지 않는다. */
5804
7067
  applyDataPatch(patch) {
5805
- if (!this.destroyed) this.commitData(this.store.preparePatch(patch));
7068
+ if (this.destroyed) return;
7069
+ const transaction = this.store.preparePatch(patch);
7070
+ this.checkTransaction(transaction, this.options);
7071
+ this.commitData(transaction);
7072
+ }
7073
+ checkTransaction(transaction, options) {
7074
+ var _a;
7075
+ if (options.rowFields !== this.options.rowFields) {
7076
+ const replaced = /* @__PURE__ */ new Set([...(transaction == null ? void 0 : transaction.updated.map((row) => row.id)) ?? [], ...(transaction == null ? void 0 : transaction.removed.map((row) => row.id)) ?? []]);
7077
+ for (const row of this.store.values()) if (!replaced.has(row[options.idField ?? "id"])) validateRowSortFields(row, options);
7078
+ }
7079
+ for (const row of (transaction == null ? void 0 : transaction.added) ?? []) validateRowSortFields(row, options);
7080
+ for (const row of (transaction == null ? void 0 : transaction.updated) ?? []) validateRowSortFields(row.after, options);
7081
+ if (!((_a = options.dependencies) == null ? void 0 : _a.length)) return;
7082
+ const added = new Set(transaction == null ? void 0 : transaction.added.map((row) => row[options.idField ?? "id"]));
7083
+ const removed = new Set(transaction == null ? void 0 : transaction.removed.map((row) => row.id));
7084
+ validateDependencies(options, (id) => added.has(id) || !removed.has(id) && !!this.store.get(id));
7085
+ }
7086
+ /** 읽기 전용 소스 미러. 잘못된 갱신은 기존 화면을 유지하고 dataError로 알린다. */
7087
+ attachDataSource(source) {
7088
+ if (this.destroyed) return () => {
7089
+ };
7090
+ const snapshot = source.getSnapshot();
7091
+ const prepared = this.store.prepareReplace(snapshot);
7092
+ this.checkTransaction(prepared, this.options);
7093
+ let active = false, pending = false;
7094
+ const unsubscribe = source.subscribe(() => {
7095
+ if (!active) {
7096
+ pending = true;
7097
+ return;
7098
+ }
7099
+ if (this.destroyed) return;
7100
+ try {
7101
+ this.setData(source.getSnapshot());
7102
+ } catch (error) {
7103
+ this.emitter.emit("dataError", { error });
7104
+ }
7105
+ });
7106
+ this.detachDataSource();
7107
+ this.commitData(prepared);
7108
+ active = true;
7109
+ const off = () => {
7110
+ if (active) {
7111
+ active = false;
7112
+ unsubscribe();
7113
+ }
7114
+ };
7115
+ this.sourceOff = off;
7116
+ if (pending) {
7117
+ try {
7118
+ this.setData(source.getSnapshot());
7119
+ } catch (error) {
7120
+ this.emitter.emit("dataError", { error });
7121
+ }
7122
+ }
7123
+ return off;
7124
+ }
7125
+ detachDataSource() {
7126
+ var _a;
7127
+ (_a = this.sourceOff) == null ? void 0 : _a.call(this);
7128
+ this.sourceOff = null;
5806
7129
  }
5807
7130
  /** 정규화된 불변 스냅샷. 새로운 options.data 스냅샷은 현재 patch 결과를 대체한다. */
5808
7131
  getData() {
@@ -5810,7 +7133,7 @@ class MozGantt {
5810
7133
  }
5811
7134
  search(keyword) {
5812
7135
  if (this.destroyed || this.blocked) return this.getSearchState();
5813
- return this.searchController.search(keyword);
7136
+ return this.searchController.search(keyword, this.options.searchOptions);
5814
7137
  }
5815
7138
  getSearchState() {
5816
7139
  return this.destroyed ? null : this.searchController.getState();
@@ -5857,28 +7180,97 @@ class MozGantt {
5857
7180
  pane.dispatchEvent(new Event("scroll"));
5858
7181
  }
5859
7182
  }
7183
+ hitTask(event) {
7184
+ const pane = this.viewport.querySelector(".pv-pane-body");
7185
+ if (!pane || !pane.contains(event.target)) return null;
7186
+ const rect = pane.getBoundingClientRect();
7187
+ const hit = this.editor.renderer.onHitTest(event.clientX - rect.left + pane.scrollLeft, event.clientY - rect.top + pane.scrollTop);
7188
+ if ((hit == null ? void 0 : hit.sourceRowId) !== void 0) {
7189
+ const row = this.store.get(hit.sourceRowId);
7190
+ if (row) return { id: hit.sourceRowId, row };
7191
+ }
7192
+ return null;
7193
+ }
7194
+ rowEvent(event) {
7195
+ const target = event.target instanceof Element ? event.target : null;
7196
+ if (!target || target.closest(".pv-rh-collapser, .pv-row-header-resize-handle")) return null;
7197
+ const cell = target.closest(".pv-rh[data-full-row-path]");
7198
+ if (!cell || !this.viewport.contains(cell)) return null;
7199
+ const fields = this.layout().rowFields, index = Number(cell.dataset.fieldIndex);
7200
+ let path;
7201
+ try {
7202
+ path = JSON.parse(cell.dataset.fullRowPath);
7203
+ } catch {
7204
+ return null;
7205
+ }
7206
+ const rowPath = path.slice(0, index + 1);
7207
+ const ids = this.store.rows.filter((row) => rowPath.every((value, i) => Object.is(row[fields[i].field] ?? null, value ?? null))).map((row) => row[this.options.idField ?? "id"]);
7208
+ return { field: cell.dataset.field ?? "", rowPath, ids, event };
7209
+ }
7210
+ navigationRows() {
7211
+ const seen = /* @__PURE__ */ new Set(), rows = [], o = this.options;
7212
+ const add = (row) => {
7213
+ if (!row) return;
7214
+ const id = row[o.idField ?? "id"];
7215
+ if (seen.has(id) || o.hideRemovedBars && (o.removedField && row[o.removedField] === true || o.dirtyField && row[o.dirtyField] === "removed")) return;
7216
+ if (!hasVisibleTime(this.editor.underlying.getAllColumns(), Number(row[o.startField ?? "start"]), Number(row[o.endField ?? "end"]))) return;
7217
+ seen.add(id);
7218
+ rows.push(row);
7219
+ };
7220
+ for (const slot of this.editor.underlying.getAllSlots()) {
7221
+ if (slot.cell.kind === "explode") slot.cell.cells.forEach(add);
7222
+ else if (slot.cell.kind === "collapse") for (const group of slot.cell.sourceRowsByCol.values()) group.forEach(add);
7223
+ }
7224
+ return rows;
7225
+ }
7226
+ selectTask(id) {
7227
+ if (this.destroyed || this.blocked) return;
7228
+ const row = id === null ? null : this.store.get(id);
7229
+ if (id !== null && !row) throw new TypeError(`Unknown Gantt task: ${id}`);
7230
+ const changed = this.selectedId !== id;
7231
+ this.selectedId = id;
7232
+ this.editor.updateAppearance({ selectedId: id ?? void 0 });
7233
+ if (row) {
7234
+ this.scrollToTask(id);
7235
+ this.status.textContent = this.describeRow(row);
7236
+ } else this.refreshStatus();
7237
+ if (changed) this.emitter.emit("selectionChange", { id, row: row ?? null });
7238
+ }
7239
+ clearSelection() {
7240
+ if (this.selectedId === null) return;
7241
+ this.selectedId = null;
7242
+ this.editor.updateAppearance({ selectedId: void 0 });
7243
+ this.emitter.emit("selectionChange", { id: null, row: null });
7244
+ }
7245
+ getSelectedTask() {
7246
+ const row = this.selectedId === null ? null : this.store.get(this.selectedId);
7247
+ return row && this.selectedId !== null ? { id: this.selectedId, row } : null;
7248
+ }
5860
7249
  describeRow(row) {
5861
- return `${row[this.options.labelField ?? "label"] ?? row[this.options.idField ?? "id"]}: ${new Date(Number(row[this.options.startField ?? "start"])).toISOString()} — ${new Date(Number(row[this.options.endField ?? "end"])).toISOString()}`;
7250
+ const format = (value) => formatGanttDateTime(Number(value), this.options.locale, this.options.timeAxis.timeZone);
7251
+ return `${row[this.options.labelField ?? "label"] ?? row[this.options.idField ?? "id"]}: ${format(row[this.options.startField ?? "start"])} — ${format(row[this.options.endField ?? "end"])}`;
5862
7252
  }
5863
7253
  refreshStatus() {
5864
- this.status.textContent = this.options.loading ? "Loading…" : this.store.size ? `${this.store.size} tasks · UTC` : "No tasks";
7254
+ this.status.textContent = this.options.loading ? this.labels.loading : this.store.size ? message(this.labels.taskCount, { count: this.store.size }) : this.labels.empty;
5865
7255
  }
5866
7256
  destroy() {
5867
- var _a, _b, _c;
7257
+ var _a, _b, _c, _d, _e;
5868
7258
  if (this.destroyed) return;
5869
7259
  this.destroyed = true;
5870
- (_a = this.searchOff) == null ? void 0 : _a.call(this);
5871
- (_b = this.searchController) == null ? void 0 : _b.destroy();
5872
- (_c = this.editor) == null ? void 0 : _c.destroy();
7260
+ this.detachDataSource();
7261
+ (_a = this.interactions) == null ? void 0 : _a.destroy();
7262
+ (_b = this.themeObserver) == null ? void 0 : _b.destroy();
7263
+ (_c = this.searchOff) == null ? void 0 : _c.call(this);
7264
+ (_d = this.searchController) == null ? void 0 : _d.destroy();
7265
+ (_e = this.editor) == null ? void 0 : _e.destroy();
5873
7266
  this.controls.forEach((control) => control.destroy());
5874
7267
  this.controls = [];
5875
7268
  this.input = null;
5876
- this.viewport.removeEventListener("click", this.onClick);
5877
- this.viewport.removeEventListener("keydown", this.onKeyDown);
5878
7269
  this.emitter.destroy();
5879
7270
  this.element.remove();
5880
7271
  }
5881
7272
  }
7273
+ let nextGanttId = 0;
5882
7274
  function sameSetting(a, b) {
5883
7275
  if (Object.is(a, b)) return true;
5884
7276
  if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
@@ -5891,6 +7283,42 @@ function sameSetting(a, b) {
5891
7283
  function defaultLabel(labelField, idField) {
5892
7284
  return (row) => String(row[labelField] ?? row[idField]);
5893
7285
  }
7286
+ function ganttDateTimeToEpoch(value, timeZone = "UTC", disambiguation = "reject") {
7287
+ validateTimeZone(timeZone);
7288
+ if (!["reject", "earlier", "later", "compatible"].includes(disambiguation)) throw new RangeError("Invalid Gantt time disambiguation");
7289
+ const { year, month, day, hour = 0, minute = 0, second = 0, millisecond = 0 } = value;
7290
+ if (![year, month, day, hour, minute, second, millisecond].every(Number.isInteger) || month < 1 || month > 12 || day < 1 || day > 31 || hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59 || millisecond < 0 || millisecond > 999) throw new RangeError("Invalid Gantt local date/time");
7291
+ const date = /* @__PURE__ */ new Date(0);
7292
+ date.setUTCFullYear(year, month - 1, day);
7293
+ date.setUTCHours(hour, minute, second, millisecond);
7294
+ const local = date.getTime();
7295
+ if (!Number.isFinite(local) || date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) throw new RangeError("Invalid Gantt local date/time");
7296
+ const candidates = wallTimeCandidates(local, timeZone);
7297
+ const exact = candidates.filter((candidate) => wallTime(candidate, timeZone) === local);
7298
+ if (exact.length === 1) return exact[0];
7299
+ if (disambiguation === "reject") throw new RangeError(exact.length ? "Ambiguous Gantt local time" : "Nonexistent Gantt local time");
7300
+ if (exact.length) return disambiguation === "later" ? exact[exact.length - 1] : exact[0];
7301
+ const later = candidates[0];
7302
+ return disambiguation === "earlier" ? later - (wallTime(later, timeZone) - local) : later;
7303
+ }
7304
+ function floorGanttTime(ms, unit, timeZone = "UTC", calendar) {
7305
+ validateTimeArguments(ms, unit, timeZone, calendar);
7306
+ return floorTo(ms, unit, calendar, timeZone);
7307
+ }
7308
+ function advanceGanttTime(ms, unit, step, timeZone = "UTC", calendar) {
7309
+ validateTimeArguments(ms, unit, timeZone, calendar);
7310
+ if (!Number.isInteger(step) || Math.abs(step) > 1e5) throw new RangeError("Invalid Gantt time step");
7311
+ return advance(ms, unit, step, calendar, timeZone);
7312
+ }
7313
+ function validateTimeArguments(ms, unit, timeZone, calendar) {
7314
+ if (typeof ms !== "number" || !Number.isFinite(ms) || Math.abs(ms) > 864e13 || !UNIT_ORDER.includes(unit)) throw new RangeError("Invalid Gantt time boundary");
7315
+ validateTimeZone(timeZone);
7316
+ validateCalendar(calendar);
7317
+ }
5894
7318
  export {
5895
- MozGantt
7319
+ MozGantt,
7320
+ advanceGanttTime,
7321
+ floorGanttTime,
7322
+ ganttDateTimeToEpoch,
7323
+ validateOptions as validateGanttOptions
5896
7324
  };