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