glimmervoid 0.52.3-next.749 → 0.52.3-next.751

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/bin/glimmervoid.js +7 -7
  2. package/dist/chunks/agent-api-cli-D5LpKt3J.js +1 -0
  3. package/dist/chunks/{agent-api-cli-PgRkZU4P.js → agent-api-cli-DvnXm4kI.js} +1 -1
  4. package/dist/chunks/{main-Buf2PV_P.js → main-BWbKEWLs.js} +16 -2
  5. package/dist/chunks/{packs-cli-s61MOWh7.js → packs-cli-BY5iV3hA.js} +1 -1
  6. package/dist/chunks/{pr-flows-cli-D6M6kXRm.js → pr-flows-cli-DMrno1BY.js} +2 -2
  7. package/dist/chunks/{settings-cli-CYaiaFRJ.js → settings-cli-D6vMWRbr.js} +1 -1
  8. package/dist/chunks/{ssh-sign-cli-BAlpaJTq.js → ssh-sign-cli-CYoKi2i6.js} +1 -1
  9. package/dist/chunks/whiteboard-svg-core-Cidy3DqV.js +3844 -0
  10. package/dist/client/assets/{agent-mark-CvEqiBo4.js → agent-mark-CPPMGmer.js} +1 -1
  11. package/dist/client/assets/agent-mark-CPPMGmer.js.br +0 -0
  12. package/dist/client/assets/{arena-panel-ISlMnhdr.js → arena-panel-Dgw6ZGdZ.js} +2 -2
  13. package/dist/client/assets/arena-panel-Dgw6ZGdZ.js.br +0 -0
  14. package/dist/client/assets/{benchmark-panel-CbNeD1Aa.js → benchmark-panel-DR6aAOVJ.js} +1 -1
  15. package/dist/client/assets/benchmark-panel-DR6aAOVJ.js.br +0 -0
  16. package/dist/client/assets/boards-view-BzjY5fys.js +1 -0
  17. package/dist/client/assets/boards-view-BzjY5fys.js.br +0 -0
  18. package/dist/client/assets/{community-panel-DFjyCuQn.js → community-panel-BMBam6Rk.js} +1 -1
  19. package/dist/client/assets/community-panel-BMBam6Rk.js.br +0 -0
  20. package/dist/client/assets/{dialogs-3m6N2GQi.js → dialogs-HOpRh5gr.js} +1 -1
  21. package/dist/client/assets/dialogs-HOpRh5gr.js.br +0 -0
  22. package/dist/client/assets/{doc-editor-ui-CrshwKCN.js → doc-editor-ui-BQW70vY2.js} +1 -1
  23. package/dist/client/assets/doc-editor-ui-BQW70vY2.js.br +0 -0
  24. package/dist/client/assets/{feature-hint-DOqkkS_S.js → feature-hint-CqdX9ZAW.js} +1 -1
  25. package/dist/client/assets/feature-hint-CqdX9ZAW.js.br +0 -0
  26. package/dist/client/assets/{first-run-checklist-DLbuF9fv.js → first-run-checklist-BlZGURU2.js} +1 -1
  27. package/dist/client/assets/first-run-checklist-BlZGURU2.js.br +0 -0
  28. package/dist/client/assets/{hooks-panel-Cy_NwPQM.js → hooks-panel-ByIwabVS.js} +1 -1
  29. package/dist/client/assets/hooks-panel-ByIwabVS.js.br +0 -0
  30. package/dist/client/assets/index-B12zcEVW.js +75 -0
  31. package/dist/client/assets/index-B12zcEVW.js.br +0 -0
  32. package/dist/client/assets/{issues-panel-DA-TyQpb.js → issues-panel-Sus7muya.js} +1 -1
  33. package/dist/client/assets/issues-panel-Sus7muya.js.br +0 -0
  34. package/dist/client/assets/{lane-read-token-step-B2qvZxxP.js → lane-read-token-step-7jOMda7j.js} +1 -1
  35. package/dist/client/assets/lane-read-token-step-7jOMda7j.js.br +0 -0
  36. package/dist/client/assets/{my-prs-panel-BbATOOLT.js → my-prs-panel-ChhHuCoo.js} +1 -1
  37. package/dist/client/assets/my-prs-panel-ChhHuCoo.js.br +0 -0
  38. package/dist/client/assets/{nyan-cat-FdK_g6uh.js → nyan-cat-CVhgfmIv.js} +1 -1
  39. package/dist/client/assets/nyan-cat-CVhgfmIv.js.br +0 -0
  40. package/dist/client/assets/{phone-shell-9b-bf4Dm.js → phone-shell-QCuH5boT.js} +1 -1
  41. package/dist/client/assets/phone-shell-QCuH5boT.js.br +0 -0
  42. package/dist/client/assets/{plan-face-B9S4yUcj.js → plan-face-DUhdCaFO.js} +1 -1
  43. package/dist/client/assets/plan-face-DUhdCaFO.js.br +0 -0
  44. package/dist/client/assets/{plan-render-d5VbtGtB.js → plan-render-DLBH8WcZ.js} +1 -1
  45. package/dist/client/assets/plan-render-DLBH8WcZ.js.br +0 -0
  46. package/dist/client/assets/{pr-queue-columns-MoAluWAc.js → pr-queue-columns-CBvxTcrj.js} +1 -1
  47. package/dist/client/assets/pr-queue-columns-CBvxTcrj.js.br +0 -0
  48. package/dist/client/assets/{radar-panel-DxnKC0O3.js → radar-panel-BVMuKUyT.js} +1 -1
  49. package/dist/client/assets/radar-panel-BVMuKUyT.js.br +0 -0
  50. package/dist/client/assets/{repo-roots-adder-D-YdrTBd.js → repo-roots-adder-wqJpeF0h.js} +1 -1
  51. package/dist/client/assets/repo-roots-adder-wqJpeF0h.js.br +0 -0
  52. package/dist/client/assets/{resume-dialog-CuNFDUKu.js → resume-dialog-CiIZCDh7.js} +1 -1
  53. package/dist/client/assets/resume-dialog-CiIZCDh7.js.br +0 -0
  54. package/dist/client/assets/{review-queue-panel-CREnMu2I.js → review-queue-panel-DcpL1Oa_.js} +1 -1
  55. package/dist/client/assets/review-queue-panel-DcpL1Oa_.js.br +0 -0
  56. package/dist/client/assets/{session-actions-BGzOI9VS.js → session-actions-9ZhnsG51.js} +2 -2
  57. package/dist/client/assets/session-actions-9ZhnsG51.js.br +0 -0
  58. package/dist/client/assets/{session-row-B9VNB7jC.js → session-row-DGItX9OU.js} +1 -1
  59. package/dist/client/assets/session-row-DGItX9OU.js.br +0 -0
  60. package/dist/client/assets/{settings-panel-C8mHUg30.js → settings-panel-DbON5896.js} +2 -2
  61. package/dist/client/assets/settings-panel-DbON5896.js.br +0 -0
  62. package/dist/client/assets/{trace-panel-Bsr2Easc.js → trace-panel-BBnR2Rin.js} +1 -1
  63. package/dist/client/assets/trace-panel-BBnR2Rin.js.br +0 -0
  64. package/dist/client/assets/{usage-panel-DWVbDiG1.js → usage-panel-Cj4D9QUu.js} +1 -1
  65. package/dist/client/assets/usage-panel-Cj4D9QUu.js.br +0 -0
  66. package/dist/client/assets/{your-day-tip-DGI6fbHA.js → your-day-tip-Ckl6WABy.js} +1 -1
  67. package/dist/client/assets/your-day-tip-Ckl6WABy.js.br +0 -0
  68. package/dist/client/index.html +4 -4
  69. package/dist/client/index.html.br +0 -0
  70. package/dist/server/index.js +1 -1
  71. package/package.json +1 -1
  72. package/dist/chunks/agent-api-cli-Hv7ZSe1j.js +0 -1
  73. package/dist/chunks/whiteboard-svg-core-bnP72KuQ.js +0 -2476
  74. package/dist/client/assets/agent-mark-CvEqiBo4.js.br +0 -0
  75. package/dist/client/assets/arena-panel-ISlMnhdr.js.br +0 -0
  76. package/dist/client/assets/benchmark-panel-CbNeD1Aa.js.br +0 -0
  77. package/dist/client/assets/boards-view-DQTSAGYw.js +0 -1
  78. package/dist/client/assets/boards-view-DQTSAGYw.js.br +0 -0
  79. package/dist/client/assets/community-panel-DFjyCuQn.js.br +0 -0
  80. package/dist/client/assets/dialogs-3m6N2GQi.js.br +0 -0
  81. package/dist/client/assets/doc-editor-ui-CrshwKCN.js.br +0 -0
  82. package/dist/client/assets/feature-hint-DOqkkS_S.js.br +0 -0
  83. package/dist/client/assets/first-run-checklist-DLbuF9fv.js.br +0 -0
  84. package/dist/client/assets/hooks-panel-Cy_NwPQM.js.br +0 -0
  85. package/dist/client/assets/index-CrpXpbdb.js +0 -75
  86. package/dist/client/assets/index-CrpXpbdb.js.br +0 -0
  87. package/dist/client/assets/issues-panel-DA-TyQpb.js.br +0 -0
  88. package/dist/client/assets/lane-read-token-step-B2qvZxxP.js.br +0 -0
  89. package/dist/client/assets/my-prs-panel-BbATOOLT.js.br +0 -0
  90. package/dist/client/assets/nyan-cat-FdK_g6uh.js.br +0 -0
  91. package/dist/client/assets/phone-shell-9b-bf4Dm.js.br +0 -0
  92. package/dist/client/assets/plan-face-B9S4yUcj.js.br +0 -0
  93. package/dist/client/assets/plan-render-d5VbtGtB.js.br +0 -0
  94. package/dist/client/assets/pr-queue-columns-MoAluWAc.js.br +0 -0
  95. package/dist/client/assets/radar-panel-DxnKC0O3.js.br +0 -0
  96. package/dist/client/assets/repo-roots-adder-D-YdrTBd.js.br +0 -0
  97. package/dist/client/assets/resume-dialog-CuNFDUKu.js.br +0 -0
  98. package/dist/client/assets/review-queue-panel-CREnMu2I.js.br +0 -0
  99. package/dist/client/assets/session-actions-BGzOI9VS.js.br +0 -0
  100. package/dist/client/assets/session-row-B9VNB7jC.js.br +0 -0
  101. package/dist/client/assets/settings-panel-C8mHUg30.js.br +0 -0
  102. package/dist/client/assets/trace-panel-Bsr2Easc.js.br +0 -0
  103. package/dist/client/assets/usage-panel-DWVbDiG1.js.br +0 -0
  104. package/dist/client/assets/your-day-tip-DGI6fbHA.js.br +0 -0
@@ -0,0 +1,3844 @@
1
+ import { G as BOX_CHANGES, at as WHITEBOARD_LIMITS, nt as UNIT_STATUSES } from "./session-BOzHqxD5.js";
2
+ //#region shared/whiteboard-plan-core.ts
3
+ var LETTERS_IN_ALPHABET = 26;
4
+ var FIRST_LETTER_CODE = 97;
5
+ function unitsOf(board) {
6
+ return Object.values(board.elements).filter((element) => element.kind === "unit");
7
+ }
8
+ function letterFor(index) {
9
+ const letter = String.fromCharCode(FIRST_LETTER_CODE + index % LETTERS_IN_ALPHABET);
10
+ const round = Math.floor(index / LETTERS_IN_ALPHABET);
11
+ return round === 0 ? letter : `${letter}${round + 1}`;
12
+ }
13
+ function levelsOf(units) {
14
+ const unitById = new Map(units.map((unit) => [unit.id, unit]));
15
+ const levelById = /* @__PURE__ */ new Map();
16
+ const visiting = /* @__PURE__ */ new Set();
17
+ function levelOf(unitId) {
18
+ const known = levelById.get(unitId);
19
+ if (known !== void 0) return known;
20
+ const unit = unitById.get(unitId);
21
+ if (!unit || visiting.has(unitId)) return 0;
22
+ visiting.add(unitId);
23
+ const level = 1 + Math.max(0, ...unit.after.map(levelOf));
24
+ visiting.delete(unitId);
25
+ levelById.set(unitId, level);
26
+ return level;
27
+ }
28
+ for (const unit of units) levelOf(unit.id);
29
+ return levelById;
30
+ }
31
+ function planSteps(board) {
32
+ const units = unitsOf(board);
33
+ const levelById = levelsOf(units);
34
+ const unitsByLevel = /* @__PURE__ */ new Map();
35
+ for (const unit of units) {
36
+ const level = levelById.get(unit.id) ?? 1;
37
+ unitsByLevel.set(level, [...unitsByLevel.get(level) ?? [], unit]);
38
+ }
39
+ const labelById = /* @__PURE__ */ new Map();
40
+ const orderedUnits = [];
41
+ for (const level of [...unitsByLevel.keys()].sort((left, right) => left - right)) {
42
+ const unitsAtLevel = (unitsByLevel.get(level) ?? []).sort((left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id));
43
+ for (const [index, unit] of unitsAtLevel.entries()) {
44
+ labelById.set(unit.id, unitsAtLevel.length === 1 ? String(level) : `${level}${letterFor(index)}`);
45
+ orderedUnits.push(unit);
46
+ }
47
+ }
48
+ return orderedUnits.map((unit) => ({
49
+ unitId: unit.id,
50
+ title: unit.title,
51
+ status: unit.status,
52
+ level: levelById.get(unit.id) ?? 1,
53
+ label: labelById.get(unit.id) ?? "",
54
+ afterLabels: unit.after.flatMap((afterId) => labelById.get(afterId) ?? []),
55
+ linkedBoardId: unit.linkedBoardId
56
+ }));
57
+ }
58
+ function findDependencyCycle(board) {
59
+ const unitById = new Map(unitsOf(board).map((unit) => [unit.id, unit]));
60
+ const finished = /* @__PURE__ */ new Set();
61
+ const path = [];
62
+ function walk(unitId) {
63
+ const loopStart = path.indexOf(unitId);
64
+ if (loopStart !== -1) return [...path.slice(loopStart), unitId];
65
+ if (finished.has(unitId)) return null;
66
+ path.push(unitId);
67
+ for (const afterId of unitById.get(unitId)?.after ?? []) {
68
+ const cycle = walk(afterId);
69
+ if (cycle) return cycle;
70
+ }
71
+ path.pop();
72
+ finished.add(unitId);
73
+ return null;
74
+ }
75
+ for (const unitId of unitById.keys()) {
76
+ const cycle = walk(unitId);
77
+ if (cycle) return cycle;
78
+ }
79
+ return null;
80
+ }
81
+ //#endregion
82
+ //#region shared/whiteboard-sweep-core.ts
83
+ function flatRectsOf(rects) {
84
+ const flat = emptyFlatRects(rects.length);
85
+ rects.forEach((rect, index) => {
86
+ setFlatRect(flat, index, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
87
+ });
88
+ return flat;
89
+ }
90
+ function emptyFlatRects(count) {
91
+ return {
92
+ count,
93
+ lefts: new Float64Array(count),
94
+ tops: new Float64Array(count),
95
+ rights: new Float64Array(count),
96
+ bottoms: new Float64Array(count)
97
+ };
98
+ }
99
+ function setFlatRect(flat, index, firstX, firstY, secondX, secondY) {
100
+ flat.lefts[index] = Math.min(firstX, secondX);
101
+ flat.rights[index] = Math.max(firstX, secondX);
102
+ flat.tops[index] = Math.min(firstY, secondY);
103
+ flat.bottoms[index] = Math.max(firstY, secondY);
104
+ }
105
+ function distinctSorted(values) {
106
+ values.sort();
107
+ let distinctCount = 0;
108
+ for (let index = 0; index < values.length; index += 1) {
109
+ const value = values[index] ?? 0;
110
+ if (distinctCount > 0 && values[distinctCount - 1] === value) continue;
111
+ values[distinctCount] = value;
112
+ distinctCount += 1;
113
+ }
114
+ return values.subarray(0, distinctCount);
115
+ }
116
+ function distinctSortedYs(groups) {
117
+ const total = groups.reduce((sum, group) => sum + group.count * 2, 0);
118
+ const ys = new Float64Array(total);
119
+ let next = 0;
120
+ for (const group of groups) {
121
+ ys.set(group.tops, next);
122
+ ys.set(group.bottoms, next + group.count);
123
+ next += group.count * 2;
124
+ }
125
+ return distinctSorted(ys);
126
+ }
127
+ function leafOf(ys, value) {
128
+ let low = 0;
129
+ let high = ys.length - 1;
130
+ while (low < high) {
131
+ const middle = low + high >> 1;
132
+ if ((ys[middle] ?? 0) < value) {
133
+ low = middle + 1;
134
+ continue;
135
+ }
136
+ high = middle;
137
+ }
138
+ return low;
139
+ }
140
+ function leafCapacityOf(leafCount) {
141
+ let capacity = 1;
142
+ while (capacity < leafCount) capacity *= 2;
143
+ return capacity;
144
+ }
145
+ function keepLiveItems(items, isLive, onItem) {
146
+ let kept = 0;
147
+ for (const item of items) {
148
+ if (isLive[item] !== 1) continue;
149
+ items[kept] = item;
150
+ kept += 1;
151
+ if (onItem) onItem(item);
152
+ }
153
+ items.length = kept;
154
+ }
155
+ function createYIntervalIndex(rects, ys) {
156
+ const capacity = leafCapacityOf(ys.length);
157
+ const topLeafByItem = new Int32Array(rects.count);
158
+ const bottomLeafByItem = new Int32Array(rects.count);
159
+ for (let item = 0; item < rects.count; item += 1) {
160
+ topLeafByItem[item] = leafOf(ys, rects.tops[item] ?? 0);
161
+ bottomLeafByItem[item] = leafOf(ys, rects.bottoms[item] ?? 0);
162
+ }
163
+ const isLive = new Uint8Array(rects.count);
164
+ const coveringItemsByNode = Array.from({ length: capacity * 2 }, () => []);
165
+ const startingItemsByLeaf = Array.from({ length: capacity }, () => []);
166
+ const liveStartCountByNode = new Int32Array(capacity * 2);
167
+ const changeStartCount = (leaf, change) => {
168
+ for (let node = leaf + capacity; node >= 1; node >>= 1) liveStartCountByNode[node] = (liveStartCountByNode[node] ?? 0) + change;
169
+ };
170
+ const insert = (item) => {
171
+ isLive[item] = 1;
172
+ const topLeaf = topLeafByItem[item] ?? 0;
173
+ let left = topLeaf + capacity;
174
+ let right = (bottomLeafByItem[item] ?? 0) + capacity + 1;
175
+ while (left < right) {
176
+ if (left & 1) {
177
+ coveringItemsByNode[left]?.push(item);
178
+ left += 1;
179
+ }
180
+ if (right & 1) {
181
+ right -= 1;
182
+ coveringItemsByNode[right]?.push(item);
183
+ }
184
+ left >>= 1;
185
+ right >>= 1;
186
+ }
187
+ startingItemsByLeaf[topLeaf]?.push(item);
188
+ changeStartCount(topLeaf, 1);
189
+ };
190
+ const remove = (item) => {
191
+ if (isLive[item] !== 1) return;
192
+ isLive[item] = 0;
193
+ changeStartCount(topLeafByItem[item] ?? 0, -1);
194
+ };
195
+ const visitStartsBetween = (node, nodeFirstLeaf, nodeLastLeaf, firstLeaf, lastLeaf, onItem) => {
196
+ if ((liveStartCountByNode[node] ?? 0) === 0 || nodeLastLeaf < firstLeaf || nodeFirstLeaf > lastLeaf) return;
197
+ if (node >= capacity) {
198
+ keepLiveItems(startingItemsByLeaf[node - capacity] ?? [], isLive, onItem);
199
+ return;
200
+ }
201
+ const middleLeaf = nodeFirstLeaf + nodeLastLeaf >> 1;
202
+ visitStartsBetween(node * 2, nodeFirstLeaf, middleLeaf, firstLeaf, lastLeaf, onItem);
203
+ visitStartsBetween(node * 2 + 1, middleLeaf + 1, nodeLastLeaf, firstLeaf, lastLeaf, onItem);
204
+ };
205
+ const forEachMeeting = (top, bottom, onItem) => {
206
+ const topLeaf = leafOf(ys, top);
207
+ for (let node = topLeaf + capacity; node >= 1; node >>= 1) keepLiveItems(coveringItemsByNode[node] ?? [], isLive, onItem);
208
+ const lastLeaf = leafOf(ys, bottom);
209
+ if (lastLeaf > topLeaf) visitStartsBetween(1, 0, capacity - 1, topLeaf + 1, lastLeaf, onItem);
210
+ };
211
+ return {
212
+ insert,
213
+ remove,
214
+ forEachMeeting
215
+ };
216
+ }
217
+ function orderBy(values) {
218
+ const order = new Int32Array(values.length);
219
+ for (let index = 0; index < order.length; index += 1) order[index] = index;
220
+ return order.sort((first, second) => (values[first] ?? 0) - (values[second] ?? 0));
221
+ }
222
+ function sweepGroupsOf(groups) {
223
+ const ys = distinctSortedYs(groups);
224
+ return groups.map((rects) => ({
225
+ rects,
226
+ index: createYIntervalIndex(rects, ys),
227
+ closingOrder: orderBy(rects.rights),
228
+ nextClosing: 0
229
+ }));
230
+ }
231
+ function closeBefore(group, x) {
232
+ while (group.nextClosing < group.closingOrder.length) {
233
+ const item = group.closingOrder[group.nextClosing] ?? 0;
234
+ if ((group.rects.rights[item] ?? 0) >= x) return;
235
+ group.index.remove(item);
236
+ group.nextClosing += 1;
237
+ }
238
+ }
239
+ function forEachTouchingPairWithin(rects, onPair) {
240
+ const [group] = sweepGroupsOf([rects]);
241
+ if (!group) return;
242
+ for (const item of orderBy(rects.lefts)) {
243
+ closeBefore(group, rects.lefts[item] ?? 0);
244
+ group.index.forEachMeeting(rects.tops[item] ?? 0, rects.bottoms[item] ?? 0, (open) => onPair(open, item));
245
+ group.index.insert(item);
246
+ }
247
+ }
248
+ function forEachTouchingPairAcross(firstRects, secondRects, onPair) {
249
+ const [first, second] = sweepGroupsOf([firstRects, secondRects]);
250
+ if (!first || !second) return;
251
+ const firstOpening = orderBy(firstRects.lefts);
252
+ const secondOpening = orderBy(secondRects.lefts);
253
+ let nextFirst = 0;
254
+ let nextSecond = 0;
255
+ while (nextFirst < firstOpening.length || nextSecond < secondOpening.length) {
256
+ const firstItem = firstOpening[nextFirst] ?? -1;
257
+ const secondItem = secondOpening[nextSecond] ?? -1;
258
+ const opensFirst = secondItem < 0 || firstItem >= 0 && (firstRects.lefts[firstItem] ?? 0) <= (secondRects.lefts[secondItem] ?? 0);
259
+ const x = opensFirst ? firstRects.lefts[firstItem] ?? 0 : secondRects.lefts[secondItem] ?? 0;
260
+ closeBefore(first, x);
261
+ closeBefore(second, x);
262
+ if (opensFirst) {
263
+ second.index.forEachMeeting(firstRects.tops[firstItem] ?? 0, firstRects.bottoms[firstItem] ?? 0, (open) => onPair(firstItem, open));
264
+ first.index.insert(firstItem);
265
+ nextFirst += 1;
266
+ continue;
267
+ }
268
+ first.index.forEachMeeting(secondRects.tops[secondItem] ?? 0, secondRects.bottoms[secondItem] ?? 0, (open) => onPair(open, secondItem));
269
+ second.index.insert(secondItem);
270
+ nextSecond += 1;
271
+ }
272
+ }
273
+ function countingOrder(keys, keyCount, order) {
274
+ const startByKey = new Int32Array(keyCount + 1);
275
+ for (const position of order) startByKey[(keys[position] ?? 0) + 1] = (startByKey[(keys[position] ?? 0) + 1] ?? 0) + 1;
276
+ for (let key = 0; key < keyCount; key += 1) startByKey[key + 1] = (startByKey[key + 1] ?? 0) + (startByKey[key] ?? 0);
277
+ const sorted = new Int32Array(order.length);
278
+ for (const position of order) {
279
+ const key = keys[position] ?? 0;
280
+ sorted[startByKey[key] ?? 0] = position;
281
+ startByKey[key] = (startByKey[key] ?? 0) + 1;
282
+ }
283
+ return sorted;
284
+ }
285
+ function pairsInOrder(firsts, seconds, firstCount, secondCount) {
286
+ const firstKeys = Int32Array.from(firsts);
287
+ const secondKeys = Int32Array.from(seconds);
288
+ const identity = new Int32Array(firsts.length);
289
+ for (let position = 0; position < identity.length; position += 1) identity[position] = position;
290
+ const order = countingOrder(firstKeys, firstCount, countingOrder(secondKeys, secondCount, identity));
291
+ return Array.from(order, (position) => [firstKeys[position] ?? 0, secondKeys[position] ?? 0]);
292
+ }
293
+ function touchingPairsWithin(rects) {
294
+ const firsts = [];
295
+ const seconds = [];
296
+ forEachTouchingPairWithin(flatRectsOf(rects), (earlier, later) => {
297
+ firsts.push(Math.min(earlier, later));
298
+ seconds.push(Math.max(earlier, later));
299
+ });
300
+ return pairsInOrder(firsts, seconds, rects.length, rects.length);
301
+ }
302
+ //#endregion
303
+ //#region shared/whiteboard-nudge-core.ts
304
+ var TRACK_SPACING$1 = 10;
305
+ var BOX_MARGIN = 4;
306
+ var CHANNEL_REACH = 14;
307
+ var MIN_TRACK_SPACING = 2;
308
+ function lineOf(point, isHorizontal) {
309
+ return isHorizontal ? point.y : point.x;
310
+ }
311
+ function alongOf(point, isHorizontal) {
312
+ return isHorizontal ? point.x : point.y;
313
+ }
314
+ function lineSegmentsOf(points, isHorizontal) {
315
+ const segments = [];
316
+ points.forEach((wirePoints, wire) => {
317
+ for (let index = 0; index + 1 < wirePoints.length; index += 1) {
318
+ const from = wirePoints[index];
319
+ const to = wirePoints[index + 1];
320
+ if (!from || !to || lineOf(from, isHorizontal) !== lineOf(to, isHorizontal) || alongOf(from, isHorizontal) === alongOf(to, isHorizontal)) continue;
321
+ const isFixed = index === 0 || index + 2 === wirePoints.length;
322
+ segments.push({
323
+ wire,
324
+ index,
325
+ line: lineOf(from, isHorizontal),
326
+ low: Math.min(alongOf(from, isHorizontal), alongOf(to, isHorizontal)),
327
+ high: Math.max(alongOf(from, isHorizontal), alongOf(to, isHorizontal)),
328
+ isFixed
329
+ });
330
+ }
331
+ });
332
+ return segments.sort((first, second) => first.line - second.line || first.low - second.low);
333
+ }
334
+ function bundlesOf(members, wires) {
335
+ const bundles = [];
336
+ const bundleByWire = /* @__PURE__ */ new Map();
337
+ const bundleByExitKey = /* @__PURE__ */ new Map();
338
+ const bundleByBusKey = /* @__PURE__ */ new Map();
339
+ for (const member of members) {
340
+ const wire = wires[member.wire];
341
+ if (!wire) continue;
342
+ const found = bundleByWire.get(member.wire) ?? bundleByExitKey.get(wire.exitKey) ?? (wire.busKey === null ? void 0 : bundleByBusKey.get(wire.busKey));
343
+ const bundle = found ?? {
344
+ members: [],
345
+ low: member.low,
346
+ high: member.high,
347
+ isPinned: false,
348
+ offset: 0
349
+ };
350
+ if (!found) bundles.push(bundle);
351
+ bundle.members.push(member);
352
+ bundle.low = Math.min(bundle.low, member.low);
353
+ bundle.high = Math.max(bundle.high, member.high);
354
+ bundle.isPinned ||= member.isFixed;
355
+ bundleByWire.set(member.wire, bundle);
356
+ if (!bundleByExitKey.has(wire.exitKey)) bundleByExitKey.set(wire.exitKey, bundle);
357
+ if (wire.busKey !== null && !bundleByBusKey.has(wire.busKey)) bundleByBusKey.set(wire.busKey, bundle);
358
+ }
359
+ return bundles;
360
+ }
361
+ function sharedLinesOf(segments, wires) {
362
+ const sharedLines = [];
363
+ let groupStart = 0;
364
+ while (groupStart < segments.length) {
365
+ const first = segments[groupStart];
366
+ if (!first) break;
367
+ let groupEnd = groupStart + 1;
368
+ let high = first.high;
369
+ for (; groupEnd < segments.length; groupEnd += 1) {
370
+ const next = segments[groupEnd];
371
+ if (!next || next.line !== first.line || next.low > high) break;
372
+ high = Math.max(high, next.high);
373
+ }
374
+ const members = segments.slice(groupStart, groupEnd);
375
+ groupStart = groupEnd;
376
+ if (members.length < 2) continue;
377
+ const bundles = bundlesOf(members, wires);
378
+ if (bundles.length > 1) sharedLines.push({
379
+ line: first.line,
380
+ low: first.low,
381
+ high,
382
+ bundles
383
+ });
384
+ }
385
+ return sharedLines;
386
+ }
387
+ function turnAt(points, segment, isLowEnd, isHorizontal) {
388
+ const from = points[segment.index];
389
+ const to = points[segment.index + 1];
390
+ if (!from || !to) return 0;
391
+ const neighbor = alongOf(from, isHorizontal) < alongOf(to, isHorizontal) === isLowEnd ? points[segment.index - 1] : points[segment.index + 2];
392
+ if (!neighbor) return 0;
393
+ return Math.sign(lineOf(neighbor, isHorizontal) - segment.line);
394
+ }
395
+ function compareSegments(first, second, points, isHorizontal) {
396
+ const firstPoints = points[first.wire] ?? [];
397
+ const secondPoints = points[second.wire] ?? [];
398
+ const firstLowTurn = turnAt(firstPoints, first, true, isHorizontal);
399
+ const secondLowTurn = turnAt(secondPoints, second, true, isHorizontal);
400
+ if (firstLowTurn !== 0 && secondLowTurn !== 0 && firstLowTurn !== secondLowTurn) return firstLowTurn;
401
+ if (firstLowTurn !== 0 && firstLowTurn === secondLowTurn && first.low !== second.low) return firstLowTurn < 0 ? second.low - first.low : first.low - second.low;
402
+ const firstHighTurn = turnAt(firstPoints, first, false, isHorizontal);
403
+ const secondHighTurn = turnAt(secondPoints, second, false, isHorizontal);
404
+ if (firstHighTurn !== 0 && secondHighTurn !== 0 && firstHighTurn !== secondHighTurn) return firstHighTurn;
405
+ if (firstHighTurn !== 0 && firstHighTurn === secondHighTurn && first.high !== second.high) return firstHighTurn < 0 ? first.high - second.high : second.high - first.high;
406
+ return first.wire - second.wire;
407
+ }
408
+ function pushPending(tree, node) {
409
+ const value = tree.pending[node] ?? -1;
410
+ if (value < 0) return;
411
+ for (const child of [node * 2, node * 2 + 1]) {
412
+ tree.maxima[child] = value;
413
+ tree.pending[child] = value;
414
+ }
415
+ tree.pending[node] = -1;
416
+ }
417
+ function rangeMax(tree, node, nodeLow, nodeHigh, low, high) {
418
+ if (high < nodeLow || nodeHigh < low) return -1;
419
+ if (low <= nodeLow && nodeHigh <= high) return tree.maxima[node] ?? -1;
420
+ pushPending(tree, node);
421
+ const middle = nodeLow + nodeHigh >> 1;
422
+ return Math.max(rangeMax(tree, node * 2, nodeLow, middle, low, high), rangeMax(tree, node * 2 + 1, middle + 1, nodeHigh, low, high));
423
+ }
424
+ function raiseRange(tree, node, nodeLow, nodeHigh, low, high, value) {
425
+ if (high < nodeLow || nodeHigh < low) return;
426
+ if (low <= nodeLow && nodeHigh <= high) {
427
+ tree.maxima[node] = value;
428
+ tree.pending[node] = value;
429
+ return;
430
+ }
431
+ pushPending(tree, node);
432
+ const middle = nodeLow + nodeHigh >> 1;
433
+ raiseRange(tree, node * 2, nodeLow, middle, low, high, value);
434
+ raiseRange(tree, node * 2 + 1, middle + 1, nodeHigh, low, high, value);
435
+ tree.maxima[node] = Math.max(tree.maxima[node * 2] ?? -1, tree.maxima[node * 2 + 1] ?? -1);
436
+ }
437
+ function indexIn(sortedValues, value) {
438
+ let low = 0;
439
+ let high = sortedValues.length - 1;
440
+ while (low < high) {
441
+ const middle = low + high >> 1;
442
+ if ((sortedValues[middle] ?? 0) < value) low = middle + 1;
443
+ if ((sortedValues[middle] ?? 0) >= value) high = middle;
444
+ }
445
+ return low;
446
+ }
447
+ function assignOffsets(orderedBundles) {
448
+ const ends = distinctSorted(Float64Array.from(orderedBundles.flatMap((bundle) => [bundle.low, bundle.high])));
449
+ const size = ends.length;
450
+ const tree = {
451
+ maxima: new Int32Array(size * 4).fill(-1),
452
+ pending: new Int32Array(size * 4).fill(-1)
453
+ };
454
+ let offsetCount = 0;
455
+ for (const bundle of orderedBundles) {
456
+ const low = indexIn(ends, bundle.low);
457
+ const high = indexIn(ends, bundle.high);
458
+ bundle.offset = rangeMax(tree, 1, 0, size - 1, low, high) + 1;
459
+ raiseRange(tree, 1, 0, size - 1, low, high, bundle.offset);
460
+ offsetCount = Math.max(offsetCount, bundle.offset + 1);
461
+ }
462
+ return offsetCount;
463
+ }
464
+ function pinnedOffsetOf(bundles) {
465
+ const pinnedOffsets = new Set(bundles.flatMap((bundle) => bundle.isPinned ? [bundle.offset] : []));
466
+ if (pinnedOffsets.size > 1) return void 0;
467
+ const [pinnedOffset] = pinnedOffsets;
468
+ return pinnedOffset ?? null;
469
+ }
470
+ function channelsOf(sharedLines, offsetCounts, hardRects, isHorizontal) {
471
+ const reachOf = (index) => (offsetCounts[index] ?? 1) * TRACK_SPACING$1 + BOX_MARGIN + CHANNEL_REACH;
472
+ const channels = sharedLines.map((sharedLine, index) => ({
473
+ low: sharedLine.line - reachOf(index),
474
+ high: sharedLine.line + reachOf(index)
475
+ }));
476
+ const bands = emptyFlatRects(sharedLines.length);
477
+ sharedLines.forEach((sharedLine, index) => {
478
+ const reach = reachOf(index);
479
+ if (isHorizontal) setFlatRect(bands, index, sharedLine.low, sharedLine.line - reach, sharedLine.high, sharedLine.line + reach);
480
+ if (!isHorizontal) setFlatRect(bands, index, sharedLine.line - reach, sharedLine.low, sharedLine.line + reach, sharedLine.high);
481
+ });
482
+ const solids = flatRectsOf(hardRects);
483
+ forEachTouchingPairAcross(bands, solids, (band, solid) => {
484
+ const sharedLine = sharedLines[band];
485
+ const channel = channels[band];
486
+ if (!sharedLine || !channel) return;
487
+ const alongLow = (isHorizontal ? solids.lefts[solid] : solids.tops[solid]) ?? 0;
488
+ const alongHigh = (isHorizontal ? solids.rights[solid] : solids.bottoms[solid]) ?? 0;
489
+ if (alongLow >= sharedLine.high || alongHigh <= sharedLine.low) return;
490
+ const acrossLow = (isHorizontal ? solids.tops[solid] : solids.lefts[solid]) ?? 0;
491
+ const acrossHigh = (isHorizontal ? solids.bottoms[solid] : solids.rights[solid]) ?? 0;
492
+ if (acrossHigh <= sharedLine.line) channel.low = Math.max(channel.low, acrossHigh + BOX_MARGIN);
493
+ if (acrossLow >= sharedLine.line) channel.high = Math.min(channel.high, acrossLow - BOX_MARGIN);
494
+ });
495
+ return channels;
496
+ }
497
+ function firstTrackAndSpacing(line, offsetCount, pinnedOffset, channel) {
498
+ if (pinnedOffset !== null) {
499
+ const roomBelow = pinnedOffset > 0 ? (line - channel.low) / pinnedOffset : Infinity;
500
+ const roomAbove = offsetCount - 1 - pinnedOffset > 0 ? (channel.high - line) / (offsetCount - 1 - pinnedOffset) : Infinity;
501
+ const spacing = Math.min(TRACK_SPACING$1, roomBelow, roomAbove);
502
+ return spacing < MIN_TRACK_SPACING ? null : {
503
+ firstTrack: line - pinnedOffset * spacing,
504
+ spacing
505
+ };
506
+ }
507
+ const spacing = Math.min(TRACK_SPACING$1, (channel.high - channel.low) / (offsetCount - 1));
508
+ if (spacing < MIN_TRACK_SPACING) return null;
509
+ const span = (offsetCount - 1) * spacing;
510
+ return {
511
+ firstTrack: Math.max(channel.low, Math.min(line - span / 2, channel.high - span)),
512
+ spacing
513
+ };
514
+ }
515
+ function moveBundle(bundle, position, points, isHorizontal) {
516
+ for (const member of bundle.members) {
517
+ const wirePoints = points[member.wire] ?? [];
518
+ for (const pointIndex of [member.index, member.index + 1]) {
519
+ const point = wirePoints[pointIndex];
520
+ if (point) wirePoints[pointIndex] = isHorizontal ? {
521
+ x: point.x,
522
+ y: position
523
+ } : {
524
+ x: position,
525
+ y: point.y
526
+ };
527
+ }
528
+ }
529
+ }
530
+ function nudgeAxis(wires, points, hardRects, isHorizontal) {
531
+ const sharedLines = sharedLinesOf(lineSegmentsOf(points, isHorizontal), wires);
532
+ const offsetCounts = sharedLines.map((sharedLine) => {
533
+ sharedLine.bundles.sort((first, second) => {
534
+ const [firstMember] = first.members;
535
+ const [secondMember] = second.members;
536
+ return firstMember && secondMember ? compareSegments(firstMember, secondMember, points, isHorizontal) : 0;
537
+ });
538
+ return assignOffsets(sharedLine.bundles);
539
+ });
540
+ const channels = channelsOf(sharedLines, offsetCounts, hardRects, isHorizontal);
541
+ sharedLines.forEach((sharedLine, lineIndex) => {
542
+ const channel = channels[lineIndex];
543
+ const offsetCount = offsetCounts[lineIndex] ?? 1;
544
+ const pinnedOffset = pinnedOffsetOf(sharedLine.bundles);
545
+ if (!channel || offsetCount < 2 || pinnedOffset === void 0) return;
546
+ const tracks = firstTrackAndSpacing(sharedLine.line, offsetCount, pinnedOffset, channel);
547
+ if (!tracks) return;
548
+ for (const bundle of sharedLine.bundles) moveBundle(bundle, Math.round(tracks.firstTrack + bundle.offset * tracks.spacing), points, isHorizontal);
549
+ });
550
+ }
551
+ function nudgeSharedLines(wires, hardRects) {
552
+ const points = wires.map((wire) => wire.points.map((point) => ({
553
+ x: point.x,
554
+ y: point.y
555
+ })));
556
+ nudgeAxis(wires, points, hardRects, true);
557
+ nudgeAxis(wires, points, hardRects, false);
558
+ return points;
559
+ }
560
+ var BLOCKING_MARGIN = 1;
561
+ var FRAME_MARGIN = 42;
562
+ var MIDLINE_GAP = 42;
563
+ var CONTENT_TOP_MARGIN = 4;
564
+ var RIGHT$1 = 0;
565
+ var LEFT$1 = 1;
566
+ var DOWN = 2;
567
+ var UP = 3;
568
+ var INITIAL_NODE_CAPACITY = 1024;
569
+ var CACHED_NODES_PER_PIECE = 32;
570
+ var UNKNOWN_NEIGHBOR = -2;
571
+ var CLEAR_STEP = 1;
572
+ var SOFT_STEP = 2;
573
+ function growingNumbers() {
574
+ return {
575
+ values: /* @__PURE__ */ new Float64Array(64),
576
+ length: 0
577
+ };
578
+ }
579
+ function pushNumber(numbers, value) {
580
+ if (numbers.length === numbers.values.length) {
581
+ const grown = new Float64Array(numbers.values.length * 2);
582
+ grown.set(numbers.values);
583
+ numbers.values = grown;
584
+ }
585
+ numbers.values[numbers.length] = value;
586
+ numbers.length += 1;
587
+ }
588
+ function filled(numbers) {
589
+ return numbers.values.subarray(0, numbers.length);
590
+ }
591
+ function emptyPieces() {
592
+ return {
593
+ lines: growingNumbers(),
594
+ starts: growingNumbers(),
595
+ ends: growingNumbers()
596
+ };
597
+ }
598
+ function addPiece(pieces, line, start, end) {
599
+ if (end < start) return;
600
+ pushNumber(pieces.lines, line);
601
+ pushNumber(pieces.starts, start);
602
+ pushNumber(pieces.ends, end);
603
+ }
604
+ function emptyRays() {
605
+ return {
606
+ alongs: growingNumbers(),
607
+ acrosses: growingNumbers()
608
+ };
609
+ }
610
+ function addRay(rays, along, across) {
611
+ pushNumber(rays.alongs, along);
612
+ pushNumber(rays.acrosses, across);
613
+ return rays.alongs.length - 1;
614
+ }
615
+ function frameOf(input) {
616
+ let left = Infinity;
617
+ let top = Infinity;
618
+ let right = -Infinity;
619
+ let bottom = -Infinity;
620
+ for (const rect of [...input.hardRects, ...input.softRects]) {
621
+ left = Math.min(left, rect.x);
622
+ top = Math.min(top, rect.y);
623
+ right = Math.max(right, rect.x + rect.width);
624
+ bottom = Math.max(bottom, rect.y + rect.height);
625
+ }
626
+ for (const port of input.ports) {
627
+ left = Math.min(left, port.x);
628
+ top = Math.min(top, port.y);
629
+ right = Math.max(right, port.x);
630
+ bottom = Math.max(bottom, port.y);
631
+ }
632
+ if (left === Infinity) return null;
633
+ const topLimit = input.contentTop + CONTENT_TOP_MARGIN;
634
+ return {
635
+ left: Math.round(left - FRAME_MARGIN),
636
+ top: Math.max(Math.round(top - FRAME_MARGIN), topLimit),
637
+ right: Math.round(right + FRAME_MARGIN),
638
+ bottom: Math.round(bottom + FRAME_MARGIN)
639
+ };
640
+ }
641
+ function blockingRectsOf(hardRects) {
642
+ const blockers = emptyFlatRects(hardRects.length);
643
+ hardRects.forEach((rect, index) => {
644
+ setFlatRect(blockers, index, rect.x - BLOCKING_MARGIN, rect.y - BLOCKING_MARGIN, rect.x + rect.width + BLOCKING_MARGIN, rect.y + rect.height + BLOCKING_MARGIN);
645
+ });
646
+ return blockers;
647
+ }
648
+ function blockerViewOf(blockers, direction) {
649
+ if (direction === RIGHT$1) return {
650
+ starts: blockers.lefts,
651
+ lows: blockers.tops,
652
+ highs: blockers.bottoms
653
+ };
654
+ if (direction === LEFT$1) return {
655
+ starts: blockers.rights.map((right) => -right),
656
+ lows: blockers.tops,
657
+ highs: blockers.bottoms
658
+ };
659
+ if (direction === DOWN) return {
660
+ starts: blockers.tops,
661
+ lows: blockers.lefts,
662
+ highs: blockers.rights
663
+ };
664
+ return {
665
+ starts: blockers.bottoms.map((bottom) => -bottom),
666
+ lows: blockers.lefts,
667
+ highs: blockers.rights
668
+ };
669
+ }
670
+ function descendingOrder(values) {
671
+ const order = new Int32Array(values.length);
672
+ for (let index = 0; index < order.length; index += 1) order[index] = index;
673
+ return order.sort((first, second) => (values[second] ?? 0) - (values[first] ?? 0));
674
+ }
675
+ function firstBlockerHits(blockers, direction, rays) {
676
+ const view = blockerViewOf(blockers, direction);
677
+ const isNegated = direction === LEFT$1 || direction === UP;
678
+ const rayAlongs = filled(rays.alongs).map((along) => isNegated ? -along : along);
679
+ const rayAcrosses = filled(rays.acrosses);
680
+ const acrossValues = new Float64Array(blockers.count * 2 + rayAcrosses.length);
681
+ acrossValues.set(view.lows, 0);
682
+ acrossValues.set(view.highs, blockers.count);
683
+ acrossValues.set(rayAcrosses, blockers.count * 2);
684
+ const across = distinctSorted(acrossValues);
685
+ const capacity = leafCapacityOf(across.length);
686
+ const nearestStartByNode = new Float64Array(capacity * 2).fill(Infinity);
687
+ const hits = new Float64Array(rayAlongs.length).fill(Infinity);
688
+ const blockerOrder = descendingOrder(view.starts);
689
+ let nextBlocker = 0;
690
+ for (const ray of descendingOrder(rayAlongs)) {
691
+ const rayAlong = rayAlongs[ray] ?? 0;
692
+ for (; nextBlocker < blockerOrder.length; nextBlocker += 1) {
693
+ const blocker = blockerOrder[nextBlocker] ?? 0;
694
+ const start = view.starts[blocker] ?? 0;
695
+ if (start < rayAlong) break;
696
+ let low = leafOf(across, view.lows[blocker] ?? 0) + 1 + capacity;
697
+ let high = leafOf(across, view.highs[blocker] ?? 0) + capacity;
698
+ while (low < high) {
699
+ if (low & 1) {
700
+ nearestStartByNode[low] = Math.min(nearestStartByNode[low] ?? Infinity, start);
701
+ low += 1;
702
+ }
703
+ if (high & 1) {
704
+ high -= 1;
705
+ nearestStartByNode[high] = Math.min(nearestStartByNode[high] ?? Infinity, start);
706
+ }
707
+ low >>= 1;
708
+ high >>= 1;
709
+ }
710
+ }
711
+ let nearest = Infinity;
712
+ for (let node = leafOf(across, rayAcrosses[ray] ?? 0) + capacity; node >= 1; node >>= 1) nearest = Math.min(nearest, nearestStartByNode[node] ?? Infinity);
713
+ hits[ray] = isNegated ? -nearest : nearest;
714
+ }
715
+ return hits;
716
+ }
717
+ function insideBlockerFlags(blockers, xs, ys) {
718
+ const isInside = new Uint8Array(xs.length);
719
+ const points = emptyFlatRects(xs.length);
720
+ for (let point = 0; point < xs.length; point += 1) setFlatRect(points, point, xs[point] ?? 0, ys[point] ?? 0, xs[point] ?? 0, ys[point] ?? 0);
721
+ forEachTouchingPairAcross(points, blockers, (point, blocker) => {
722
+ const x = xs[point] ?? 0;
723
+ const y = ys[point] ?? 0;
724
+ if ((blockers.lefts[blocker] ?? 0) < x && x < (blockers.rights[blocker] ?? 0) && (blockers.tops[blocker] ?? 0) < y && y < (blockers.bottoms[blocker] ?? 0)) isInside[point] = 1;
725
+ });
726
+ return isInside;
727
+ }
728
+ function cornerOrigins(rects, frame) {
729
+ const origins = {
730
+ xs: growingNumbers(),
731
+ ys: growingNumbers(),
732
+ awayDirections: growingNumbers()
733
+ };
734
+ for (const rect of rects) {
735
+ const left = Math.round(rect.x - 14);
736
+ const right = Math.round(rect.x + rect.width + 14);
737
+ const top = Math.max(Math.round(rect.y - 14), frame.top);
738
+ const bottom = Math.round(rect.y + rect.height + 14);
739
+ for (const [x, y, horizontalAway, verticalAway] of [
740
+ [
741
+ left,
742
+ top,
743
+ LEFT$1,
744
+ UP
745
+ ],
746
+ [
747
+ right,
748
+ top,
749
+ RIGHT$1,
750
+ UP
751
+ ],
752
+ [
753
+ left,
754
+ bottom,
755
+ LEFT$1,
756
+ DOWN
757
+ ],
758
+ [
759
+ right,
760
+ bottom,
761
+ RIGHT$1,
762
+ DOWN
763
+ ]
764
+ ]) {
765
+ pushNumber(origins.xs, x);
766
+ pushNumber(origins.ys, y);
767
+ pushNumber(origins.awayDirections, horizontalAway * 4 + verticalAway);
768
+ }
769
+ }
770
+ return origins;
771
+ }
772
+ function shootAll(blockers, rays) {
773
+ return {
774
+ rays,
775
+ hits: rays.map((directionRays, direction) => firstBlockerHits(blockers, direction, directionRays))
776
+ };
777
+ }
778
+ function clampedHit(hit, direction, frame) {
779
+ if (direction === RIGHT$1) return Math.min(hit, frame.right);
780
+ if (direction === LEFT$1) return Math.max(hit, frame.left);
781
+ if (direction === DOWN) return Math.min(hit, frame.bottom);
782
+ return Math.max(hit, frame.top);
783
+ }
784
+ function midlineBeyond(origin, hit, direction) {
785
+ if (!Number.isFinite(hit)) return null;
786
+ const neighborLine = direction === RIGHT$1 || direction === DOWN ? hit + BLOCKING_MARGIN - 14 : hit - BLOCKING_MARGIN + 14;
787
+ if (Math.abs(neighborLine - origin) <= MIDLINE_GAP) return null;
788
+ return Math.round((origin + neighborLine) / 2);
789
+ }
790
+ function addUnblockedPieces(pieces, y, left, right, blockers) {
791
+ const crossings = [];
792
+ for (let index = 0; index < blockers.count; index += 1) if ((blockers.tops[index] ?? 0) < y && y < (blockers.bottoms[index] ?? 0)) crossings.push([blockers.lefts[index] ?? 0, blockers.rights[index] ?? 0]);
793
+ crossings.sort((first, second) => first[0] - second[0]);
794
+ let start = left;
795
+ for (const [crossingLeft, crossingRight] of crossings) {
796
+ if (crossingLeft > start) addPiece(pieces, y, start, Math.min(crossingLeft, right));
797
+ start = Math.max(start, crossingRight);
798
+ }
799
+ addPiece(pieces, y, start, right);
800
+ }
801
+ function buildPieces(input, frame, blockers) {
802
+ const horizontal = emptyPieces();
803
+ const vertical = emptyPieces();
804
+ const corners = cornerOrigins([...input.hardRects, ...input.softRects], frame);
805
+ const cornerXs = filled(corners.xs);
806
+ const cornerYs = filled(corners.ys);
807
+ const isCornerBlocked = insideBlockerFlags(blockers, cornerXs, cornerYs);
808
+ const cornerRays = [
809
+ emptyRays(),
810
+ emptyRays(),
811
+ emptyRays(),
812
+ emptyRays()
813
+ ];
814
+ const rayByCornerAndDirection = new Int32Array(cornerXs.length * 4).fill(-1);
815
+ for (let corner = 0; corner < cornerXs.length; corner += 1) {
816
+ if (isCornerBlocked[corner] === 1) continue;
817
+ const x = cornerXs[corner] ?? 0;
818
+ const y = cornerYs[corner] ?? 0;
819
+ for (let direction = 0; direction < 4; direction += 1) {
820
+ const directionRays = cornerRays[direction];
821
+ if (!directionRays) continue;
822
+ const isAlongX = direction === RIGHT$1 || direction === LEFT$1;
823
+ rayByCornerAndDirection[corner * 4 + direction] = addRay(directionRays, isAlongX ? x : y, isAlongX ? y : x);
824
+ }
825
+ }
826
+ const cornerShots = shootAll(blockers, cornerRays);
827
+ const hitOf = (shots, direction, ray) => clampedHit(shots.hits[direction]?.[ray] ?? Infinity, direction, frame);
828
+ const midlineRays = [
829
+ emptyRays(),
830
+ emptyRays(),
831
+ emptyRays(),
832
+ emptyRays()
833
+ ];
834
+ const verticalMidlines = [];
835
+ const horizontalMidlines = [];
836
+ for (let corner = 0; corner < cornerXs.length; corner += 1) {
837
+ if (isCornerBlocked[corner] === 1) continue;
838
+ const x = cornerXs[corner] ?? 0;
839
+ const y = cornerYs[corner] ?? 0;
840
+ const rayOf = (direction) => rayByCornerAndDirection[corner * 4 + direction] ?? -1;
841
+ addPiece(horizontal, y, hitOf(cornerShots, LEFT$1, rayOf(LEFT$1)), hitOf(cornerShots, RIGHT$1, rayOf(RIGHT$1)));
842
+ addPiece(vertical, x, hitOf(cornerShots, UP, rayOf(UP)), hitOf(cornerShots, DOWN, rayOf(DOWN)));
843
+ const away = corners.awayDirections.values[corner] ?? 0;
844
+ const horizontalAway = Math.floor(away / 4);
845
+ const verticalAway = away % 4;
846
+ const midlineX = midlineBeyond(x, cornerShots.hits[horizontalAway]?.[rayOf(horizontalAway)] ?? Infinity, horizontalAway);
847
+ if (midlineX !== null) verticalMidlines.push(addRay(midlineRays[UP] ?? emptyRays(), y, midlineX), addRay(midlineRays[DOWN] ?? emptyRays(), y, midlineX), midlineX);
848
+ const midlineY = midlineBeyond(y, cornerShots.hits[verticalAway]?.[rayOf(verticalAway)] ?? Infinity, verticalAway);
849
+ if (midlineY !== null && midlineY >= frame.top) horizontalMidlines.push(addRay(midlineRays[LEFT$1] ?? emptyRays(), x, midlineY), addRay(midlineRays[RIGHT$1] ?? emptyRays(), x, midlineY), midlineY);
850
+ }
851
+ const portRays = [
852
+ emptyRays(),
853
+ emptyRays(),
854
+ emptyRays(),
855
+ emptyRays()
856
+ ];
857
+ const portRayIndexes = input.ports.map((port) => {
858
+ const isAlongX = port.outwardDirection === RIGHT$1 || port.outwardDirection === LEFT$1;
859
+ return addRay(portRays[port.outwardDirection] ?? emptyRays(), isAlongX ? port.x : port.y, isAlongX ? port.y : port.x);
860
+ });
861
+ const midlineShots = shootAll(blockers, midlineRays);
862
+ for (let index = 0; index < verticalMidlines.length; index += 3) addPiece(vertical, verticalMidlines[index + 2] ?? 0, hitOf(midlineShots, UP, verticalMidlines[index] ?? 0), hitOf(midlineShots, DOWN, verticalMidlines[index + 1] ?? 0));
863
+ for (let index = 0; index < horizontalMidlines.length; index += 3) addPiece(horizontal, horizontalMidlines[index + 2] ?? 0, hitOf(midlineShots, LEFT$1, horizontalMidlines[index] ?? 0), hitOf(midlineShots, RIGHT$1, horizontalMidlines[index + 1] ?? 0));
864
+ const portShots = shootAll(blockers, portRays);
865
+ input.ports.forEach((port, portIndex) => {
866
+ const reach = hitOf(portShots, port.outwardDirection, portRayIndexes[portIndex] ?? 0);
867
+ if (port.outwardDirection === RIGHT$1 || port.outwardDirection === LEFT$1) {
868
+ addPiece(horizontal, port.y, Math.min(port.x, reach), Math.max(port.x, reach));
869
+ addPiece(vertical, port.x, port.y, port.y);
870
+ return;
871
+ }
872
+ addPiece(vertical, port.x, Math.min(port.y, reach), Math.max(port.y, reach));
873
+ addPiece(horizontal, port.y, port.x, port.x);
874
+ });
875
+ addUnblockedPieces(horizontal, frame.top, frame.left, frame.right, blockers);
876
+ addPiece(horizontal, frame.bottom, frame.left, frame.right);
877
+ addPiece(vertical, frame.left, frame.top, frame.bottom);
878
+ addPiece(vertical, frame.right, frame.top, frame.bottom);
879
+ return {
880
+ horizontal,
881
+ vertical
882
+ };
883
+ }
884
+ function mergedPieces(pieces) {
885
+ const lines = filled(pieces.lines);
886
+ const starts = filled(pieces.starts);
887
+ const ends = filled(pieces.ends);
888
+ const order = new Int32Array(lines.length);
889
+ for (let index = 0; index < order.length; index += 1) order[index] = index;
890
+ order.sort((first, second) => (lines[first] ?? 0) - (lines[second] ?? 0) || (starts[first] ?? 0) - (starts[second] ?? 0));
891
+ const merged = {
892
+ lines: new Float64Array(lines.length),
893
+ starts: new Float64Array(lines.length),
894
+ ends: new Float64Array(lines.length)
895
+ };
896
+ let count = 0;
897
+ for (const piece of order) {
898
+ const line = lines[piece] ?? 0;
899
+ const start = starts[piece] ?? 0;
900
+ const end = ends[piece] ?? 0;
901
+ const last = count - 1;
902
+ if (count > 0 && merged.lines[last] === line && start <= (merged.ends[last] ?? 0)) {
903
+ merged.ends[last] = Math.max(merged.ends[last] ?? 0, end);
904
+ continue;
905
+ }
906
+ merged.lines[count] = line;
907
+ merged.starts[count] = start;
908
+ merged.ends[count] = end;
909
+ count += 1;
910
+ }
911
+ return {
912
+ count,
913
+ lines: merged.lines.subarray(0, count),
914
+ starts: merged.starts.subarray(0, count),
915
+ ends: merged.ends.subarray(0, count)
916
+ };
917
+ }
918
+ function firstIndexAtLeast(values, first, end, value) {
919
+ let low = first;
920
+ let high = end;
921
+ while (low < high) {
922
+ const middle = low + high >> 1;
923
+ if ((values[middle] ?? 0) < value) {
924
+ low = middle + 1;
925
+ continue;
926
+ }
927
+ high = middle;
928
+ }
929
+ return low;
930
+ }
931
+ function firstIndexAbove(values, first, end, value) {
932
+ let low = first;
933
+ let high = end;
934
+ while (low < high) {
935
+ const middle = low + high >> 1;
936
+ if ((values[middle] ?? 0) <= value) {
937
+ low = middle + 1;
938
+ continue;
939
+ }
940
+ high = middle;
941
+ }
942
+ return low;
943
+ }
944
+ function forEachCoveringNode(capacity, firstLeaf, lastLeaf, onNode) {
945
+ let low = firstLeaf + capacity;
946
+ let high = lastLeaf + capacity + 1;
947
+ while (low < high) {
948
+ if (low & 1) {
949
+ onNode(low);
950
+ low += 1;
951
+ }
952
+ if (high & 1) {
953
+ high -= 1;
954
+ onNode(high);
955
+ }
956
+ low >>= 1;
957
+ high >>= 1;
958
+ }
959
+ }
960
+ function prefixSums(counts) {
961
+ for (let index = 1; index < counts.length; index += 1) counts[index] = (counts[index] ?? 0) + (counts[index - 1] ?? 0);
962
+ return counts;
963
+ }
964
+ function distinctLinesOf(pieces) {
965
+ return distinctSorted(Float64Array.from(pieces.lines));
966
+ }
967
+ function lineIndexOf(pieces, acrossValues) {
968
+ const capacity = leafCapacityOf(Math.max(acrossValues.length, 1));
969
+ const firstLeaves = new Int32Array(pieces.count);
970
+ const lastLeaves = new Int32Array(pieces.count);
971
+ const offsets = new Int32Array(capacity * 2 + 1);
972
+ for (let piece = 0; piece < pieces.count; piece += 1) {
973
+ firstLeaves[piece] = firstIndexAtLeast(acrossValues, 0, acrossValues.length, pieces.starts[piece] ?? 0);
974
+ lastLeaves[piece] = firstIndexAbove(acrossValues, 0, acrossValues.length, pieces.ends[piece] ?? 0) - 1;
975
+ forEachCoveringNode(capacity, firstLeaves[piece] ?? 0, lastLeaves[piece] ?? -1, (node) => {
976
+ offsets[node + 1] = (offsets[node + 1] ?? 0) + 1;
977
+ });
978
+ }
979
+ prefixSums(offsets);
980
+ const cursors = offsets.slice();
981
+ const total = offsets[capacity * 2] ?? 0;
982
+ const lines = new Float64Array(total);
983
+ const pieceIds = new Int32Array(total);
984
+ for (let piece = 0; piece < pieces.count; piece += 1) forEachCoveringNode(capacity, firstLeaves[piece] ?? 0, lastLeaves[piece] ?? -1, (node) => {
985
+ const position = cursors[node] ?? 0;
986
+ lines[position] = pieces.lines[piece] ?? 0;
987
+ pieceIds[position] = piece;
988
+ cursors[node] = position + 1;
989
+ });
990
+ return {
991
+ acrossValues,
992
+ capacity,
993
+ offsets,
994
+ lines,
995
+ pieces: pieceIds
996
+ };
997
+ }
998
+ function nearestPieceAlong(index, across, from, isForward) {
999
+ const leaf = firstIndexAtLeast(index.acrossValues, 0, index.acrossValues.length, across);
1000
+ if (index.acrossValues[leaf] !== across) return -1;
1001
+ let nearestPiece = -1;
1002
+ let nearestLine = isForward ? Infinity : -Infinity;
1003
+ for (let node = leaf + index.capacity; node >= 1; node >>= 1) {
1004
+ const first = index.offsets[node] ?? 0;
1005
+ const end = index.offsets[node + 1] ?? 0;
1006
+ const position = isForward ? firstIndexAbove(index.lines, first, end, from) : firstIndexAtLeast(index.lines, first, end, from) - 1;
1007
+ if (position < first || position >= end) continue;
1008
+ const line = index.lines[position] ?? 0;
1009
+ if (!(isForward ? line < nearestLine : line > nearestLine)) continue;
1010
+ nearestLine = line;
1011
+ nearestPiece = index.pieces[position] ?? -1;
1012
+ }
1013
+ return nearestPiece;
1014
+ }
1015
+ function softIndexOf(softRects, isAlongX) {
1016
+ const acrossLows = Float64Array.from(softRects, (rect) => isAlongX ? rect.y : rect.x);
1017
+ const acrossHighs = Float64Array.from(softRects, (rect) => isAlongX ? rect.y + rect.height : rect.x + rect.width);
1018
+ const alongLows = Float64Array.from(softRects, (rect) => isAlongX ? rect.x : rect.y);
1019
+ const alongHighs = Float64Array.from(softRects, (rect) => isAlongX ? rect.x + rect.width : rect.y + rect.height);
1020
+ const boundaryValues = new Float64Array(softRects.length * 2);
1021
+ boundaryValues.set(acrossLows, 0);
1022
+ boundaryValues.set(acrossHighs, softRects.length);
1023
+ const boundaries = distinctSorted(boundaryValues);
1024
+ const capacity = leafCapacityOf(Math.max(boundaries.length * 2 - 1, 1));
1025
+ const leafRangeOf = (rect) => [firstIndexAtLeast(boundaries, 0, boundaries.length, acrossLows[rect] ?? 0) * 2 + 1, firstIndexAtLeast(boundaries, 0, boundaries.length, acrossHighs[rect] ?? 0) * 2 - 1];
1026
+ const offsets = new Int32Array(capacity * 2 + 1);
1027
+ const rectsByAlongLow = Int32Array.from(softRects.keys()).sort((first, second) => (alongLows[first] ?? 0) - (alongLows[second] ?? 0));
1028
+ for (const rect of rectsByAlongLow) {
1029
+ const [firstLeaf, lastLeaf] = leafRangeOf(rect);
1030
+ forEachCoveringNode(capacity, firstLeaf, lastLeaf, (node) => {
1031
+ offsets[node + 1] = (offsets[node + 1] ?? 0) + 1;
1032
+ });
1033
+ }
1034
+ prefixSums(offsets);
1035
+ const cursors = offsets.slice();
1036
+ const total = offsets[capacity * 2] ?? 0;
1037
+ const sortedAlongLows = new Float64Array(total);
1038
+ const reachMaxima = new Float64Array(total);
1039
+ for (const rect of rectsByAlongLow) {
1040
+ const [firstLeaf, lastLeaf] = leafRangeOf(rect);
1041
+ forEachCoveringNode(capacity, firstLeaf, lastLeaf, (node) => {
1042
+ const position = cursors[node] ?? 0;
1043
+ const isNodeStart = position === (offsets[node] ?? 0);
1044
+ sortedAlongLows[position] = alongLows[rect] ?? 0;
1045
+ reachMaxima[position] = isNodeStart ? alongHighs[rect] ?? 0 : Math.max(reachMaxima[position - 1] ?? 0, alongHighs[rect] ?? 0);
1046
+ cursors[node] = position + 1;
1047
+ });
1048
+ }
1049
+ return {
1050
+ boundaries,
1051
+ capacity,
1052
+ offsets,
1053
+ alongLows: sortedAlongLows,
1054
+ reachMaxima
1055
+ };
1056
+ }
1057
+ function softLeafOf(boundaries, across) {
1058
+ const position = firstIndexAtLeast(boundaries, 0, boundaries.length, across);
1059
+ if (boundaries[position] === across) return position * 2;
1060
+ if (position === 0 || position === boundaries.length) return -1;
1061
+ return position * 2 - 1;
1062
+ }
1063
+ function crossesSoftRect(index, across, alongLow, alongHigh) {
1064
+ const leaf = softLeafOf(index.boundaries, across);
1065
+ if (leaf < 0) return false;
1066
+ for (let node = leaf + index.capacity; node >= 1; node >>= 1) {
1067
+ const first = index.offsets[node] ?? 0;
1068
+ const end = firstIndexAtLeast(index.alongLows, first, index.offsets[node + 1] ?? 0, alongHigh);
1069
+ if (end > first && (index.reachMaxima[end - 1] ?? 0) > alongLow) return true;
1070
+ }
1071
+ return false;
1072
+ }
1073
+ function pieceComponents(horizontal, vertical) {
1074
+ const parents = Int32Array.from({ length: horizontal.count + vertical.count }, (_, piece) => piece);
1075
+ const rootOf = (piece) => {
1076
+ let current = piece;
1077
+ while (parents[current] !== current) {
1078
+ const grandparent = parents[parents[current] ?? current] ?? current;
1079
+ parents[current] = grandparent;
1080
+ current = grandparent;
1081
+ }
1082
+ return current;
1083
+ };
1084
+ const join = (first, second) => {
1085
+ parents[rootOf(first)] = rootOf(second);
1086
+ };
1087
+ const lineValues = distinctLinesOf(horizontal);
1088
+ const capacity = leafCapacityOf(Math.max(lineValues.length, 1));
1089
+ const activeCounts = new Int32Array(capacity * 2);
1090
+ const representatives = new Int32Array(capacity * 2).fill(-1);
1091
+ const leafOfHorizontal = (piece) => firstIndexAtLeast(lineValues, 0, lineValues.length, horizontal.lines[piece] ?? 0) + capacity;
1092
+ const open = (piece) => {
1093
+ const leaf = leafOfHorizontal(piece);
1094
+ activeCounts[leaf] = 1;
1095
+ representatives[leaf] = piece;
1096
+ for (let node = leaf >> 1; node >= 1; node >>= 1) {
1097
+ activeCounts[node] = (activeCounts[node] ?? 0) + 1;
1098
+ representatives[node] = -1;
1099
+ }
1100
+ };
1101
+ const close = (piece) => {
1102
+ const leaf = leafOfHorizontal(piece);
1103
+ activeCounts[leaf] = 0;
1104
+ for (let node = leaf >> 1; node >= 1; node >>= 1) activeCounts[node] = (activeCounts[node] ?? 0) - 1;
1105
+ };
1106
+ const connect = (node, nodeFirst, nodeLast, first, last, piece) => {
1107
+ if ((activeCounts[node] ?? 0) === 0 || nodeLast < first || nodeFirst > last) return;
1108
+ const isInside = first <= nodeFirst && nodeLast <= last;
1109
+ const representative = representatives[node] ?? -1;
1110
+ if (isInside && representative >= 0) {
1111
+ join(representative, piece);
1112
+ return;
1113
+ }
1114
+ const middle = nodeFirst + nodeLast >> 1;
1115
+ connect(node * 2, nodeFirst, middle, first, last, piece);
1116
+ connect(node * 2 + 1, middle + 1, nodeLast, first, last, piece);
1117
+ if (isInside) representatives[node] = piece;
1118
+ };
1119
+ const openingOrder = Int32Array.from({ length: horizontal.count }, (_, piece) => piece).sort((first, second) => (horizontal.starts[first] ?? 0) - (horizontal.starts[second] ?? 0));
1120
+ const closingOrder = Int32Array.from({ length: horizontal.count }, (_, piece) => piece).sort((first, second) => (horizontal.ends[first] ?? 0) - (horizontal.ends[second] ?? 0));
1121
+ let nextOpening = 0;
1122
+ let nextClosing = 0;
1123
+ for (let piece = 0; piece < vertical.count; piece += 1) {
1124
+ const x = vertical.lines[piece] ?? 0;
1125
+ for (;;) {
1126
+ const opening = openingOrder[nextOpening] ?? -1;
1127
+ const closing = closingOrder[nextClosing] ?? -1;
1128
+ const openingStart = opening >= 0 ? horizontal.starts[opening] ?? 0 : Infinity;
1129
+ const closingEnd = closing >= 0 ? horizontal.ends[closing] ?? 0 : Infinity;
1130
+ if (closingEnd < x && closingEnd < openingStart) {
1131
+ close(closing);
1132
+ nextClosing += 1;
1133
+ continue;
1134
+ }
1135
+ if (openingStart > x) break;
1136
+ open(opening);
1137
+ nextOpening += 1;
1138
+ }
1139
+ const firstLeaf = firstIndexAtLeast(lineValues, 0, lineValues.length, vertical.starts[piece] ?? 0);
1140
+ const lastLeaf = firstIndexAbove(lineValues, 0, lineValues.length, vertical.ends[piece] ?? 0) - 1;
1141
+ connect(1, 0, capacity - 1, firstLeaf, lastLeaf, horizontal.count + piece);
1142
+ }
1143
+ return Int32Array.from(parents.keys(), (piece) => rootOf(piece));
1144
+ }
1145
+ function pieceAt(pieces, line, along) {
1146
+ let low = 0;
1147
+ let high = pieces.count;
1148
+ while (low < high) {
1149
+ const middle = low + high >> 1;
1150
+ const middleLine = pieces.lines[middle] ?? 0;
1151
+ if (middleLine < line || middleLine === line && (pieces.starts[middle] ?? 0) <= along) {
1152
+ low = middle + 1;
1153
+ continue;
1154
+ }
1155
+ high = middle;
1156
+ }
1157
+ const piece = low - 1;
1158
+ if (piece < 0 || pieces.lines[piece] !== line || (pieces.ends[piece] ?? 0) < along) return -1;
1159
+ return piece;
1160
+ }
1161
+ function emptyNodeStore(capacity) {
1162
+ return {
1163
+ horizontalPieces: new Int32Array(capacity),
1164
+ verticalPieces: new Int32Array(capacity),
1165
+ neighbors: new Int32Array(capacity * 4).fill(UNKNOWN_NEIGHBOR),
1166
+ softSteps: new Uint8Array(capacity * 4)
1167
+ };
1168
+ }
1169
+ function grownNodes(graph, nodes) {
1170
+ const capacity = graph.xs.length * 2;
1171
+ const grown = emptyNodeStore(capacity);
1172
+ grown.horizontalPieces.set(nodes.horizontalPieces);
1173
+ grown.verticalPieces.set(nodes.verticalPieces);
1174
+ grown.neighbors.set(nodes.neighbors);
1175
+ grown.softSteps.set(nodes.softSteps);
1176
+ const xs = new Float64Array(capacity);
1177
+ const ys = new Float64Array(capacity);
1178
+ xs.set(graph.xs);
1179
+ ys.set(graph.ys);
1180
+ graph.xs = xs;
1181
+ graph.ys = ys;
1182
+ return grown;
1183
+ }
1184
+ function buildVisibilityGraph(input) {
1185
+ const frame = frameOf(input);
1186
+ if (!frame) return null;
1187
+ const built = buildPieces(input, frame, blockingRectsOf(input.hardRects));
1188
+ const horizontal = mergedPieces(built.horizontal);
1189
+ const vertical = mergedPieces(built.vertical);
1190
+ const verticalIndex = lineIndexOf(vertical, distinctLinesOf(horizontal));
1191
+ const horizontalIndex = lineIndexOf(horizontal, distinctLinesOf(vertical));
1192
+ const softAlongX = softIndexOf(input.softRects, true);
1193
+ const softAlongY = softIndexOf(input.softRects, false);
1194
+ const componentOfPiece = pieceComponents(horizontal, vertical);
1195
+ const nodeByPieces = /* @__PURE__ */ new Map();
1196
+ let nodes = emptyNodeStore(INITIAL_NODE_CAPACITY);
1197
+ const nodeOf = (horizontalPiece, verticalPiece) => {
1198
+ const key = horizontalPiece * vertical.count + verticalPiece;
1199
+ const known = nodeByPieces.get(key);
1200
+ if (known !== void 0) return known;
1201
+ const node = graph.nodeCount;
1202
+ if (node === graph.xs.length) nodes = grownNodes(graph, nodes);
1203
+ graph.xs[node] = vertical.lines[verticalPiece] ?? 0;
1204
+ graph.ys[node] = horizontal.lines[horizontalPiece] ?? 0;
1205
+ nodes.horizontalPieces[node] = horizontalPiece;
1206
+ nodes.verticalPieces[node] = verticalPiece;
1207
+ graph.nodeCount += 1;
1208
+ nodeByPieces.set(key, node);
1209
+ return node;
1210
+ };
1211
+ const nextNodeAlong = (node, direction) => {
1212
+ const isForward = direction === RIGHT$1 || direction === DOWN;
1213
+ const x = graph.xs[node] ?? 0;
1214
+ const y = graph.ys[node] ?? 0;
1215
+ if (direction === RIGHT$1 || direction === LEFT$1) {
1216
+ const horizontalPiece = nodes.horizontalPieces[node] ?? 0;
1217
+ const verticalPiece = nearestPieceAlong(verticalIndex, y, x, isForward);
1218
+ const nextX = vertical.lines[verticalPiece] ?? NaN;
1219
+ if (verticalPiece < 0 || nextX < (horizontal.starts[horizontalPiece] ?? 0) || nextX > (horizontal.ends[horizontalPiece] ?? 0)) return -1;
1220
+ return nodeOf(horizontalPiece, verticalPiece);
1221
+ }
1222
+ const verticalPiece = nodes.verticalPieces[node] ?? 0;
1223
+ const horizontalPiece = nearestPieceAlong(horizontalIndex, x, y, isForward);
1224
+ const nextY = horizontal.lines[horizontalPiece] ?? NaN;
1225
+ if (horizontalPiece < 0 || nextY < (vertical.starts[verticalPiece] ?? 0) || nextY > (vertical.ends[verticalPiece] ?? 0)) return -1;
1226
+ return nodeOf(horizontalPiece, verticalPiece);
1227
+ };
1228
+ const neighborOf = (node, direction) => {
1229
+ const known = nodes.neighbors[node * 4 + direction] ?? UNKNOWN_NEIGHBOR;
1230
+ if (known !== UNKNOWN_NEIGHBOR) return known;
1231
+ const next = nextNodeAlong(node, direction);
1232
+ nodes.neighbors[node * 4 + direction] = next;
1233
+ if (next >= 0) nodes.neighbors[next * 4 + (direction ^ 1)] = node;
1234
+ return next;
1235
+ };
1236
+ const isSoftStep = (node, direction) => {
1237
+ const known = nodes.softSteps[node * 4 + direction] ?? 0;
1238
+ if (known !== 0) return known === SOFT_STEP;
1239
+ const next = neighborOf(node, direction);
1240
+ const isAlongX = direction === RIGHT$1 || direction === LEFT$1;
1241
+ const [across, from, to] = isAlongX ? [
1242
+ graph.ys[node] ?? 0,
1243
+ graph.xs[node] ?? 0,
1244
+ graph.xs[next] ?? 0
1245
+ ] : [
1246
+ graph.xs[node] ?? 0,
1247
+ graph.ys[node] ?? 0,
1248
+ graph.ys[next] ?? 0
1249
+ ];
1250
+ const isSoft = next >= 0 && crossesSoftRect(isAlongX ? softAlongX : softAlongY, across, Math.min(from, to), Math.max(from, to));
1251
+ const marker = isSoft ? SOFT_STEP : CLEAR_STEP;
1252
+ nodes.softSteps[node * 4 + direction] = marker;
1253
+ if (next >= 0) nodes.softSteps[next * 4 + (direction ^ 1)] = marker;
1254
+ return isSoft;
1255
+ };
1256
+ const nodeAt = (x, y) => {
1257
+ const horizontalPiece = pieceAt(horizontal, y, x);
1258
+ const verticalPiece = pieceAt(vertical, x, y);
1259
+ return horizontalPiece < 0 || verticalPiece < 0 ? -1 : nodeOf(horizontalPiece, verticalPiece);
1260
+ };
1261
+ const componentOf = (node) => componentOfPiece[nodes.horizontalPieces[node] ?? 0] ?? -1;
1262
+ const cachedNodeBudget = (horizontal.count + vertical.count) * CACHED_NODES_PER_PIECE;
1263
+ const beginSearch = () => {
1264
+ if (graph.nodeCount <= cachedNodeBudget) return;
1265
+ nodeByPieces.clear();
1266
+ nodes.neighbors.fill(UNKNOWN_NEIGHBOR, 0, graph.nodeCount * 4);
1267
+ nodes.softSteps.fill(0, 0, graph.nodeCount * 4);
1268
+ graph.nodeCount = 0;
1269
+ };
1270
+ const pieceExtentOf = (node, isAlongX) => {
1271
+ const pieces = isAlongX ? horizontal : vertical;
1272
+ const piece = (isAlongX ? nodes.horizontalPieces[node] : nodes.verticalPieces[node]) ?? 0;
1273
+ return [pieces.starts[piece] ?? 0, pieces.ends[piece] ?? 0];
1274
+ };
1275
+ const graph = {
1276
+ nodeCount: 0,
1277
+ xs: new Float64Array(INITIAL_NODE_CAPACITY),
1278
+ ys: new Float64Array(INITIAL_NODE_CAPACITY),
1279
+ neighborOf,
1280
+ isSoftStep,
1281
+ nodeAt,
1282
+ componentOf,
1283
+ beginSearch,
1284
+ pieceExtentOf
1285
+ };
1286
+ return graph;
1287
+ }
1288
+ //#endregion
1289
+ //#region shared/whiteboard-route-core.ts
1290
+ var BEND_COST = 30;
1291
+ var SOFT_OBSTACLE_COST = 300;
1292
+ var BACK_INTERIOR_COST = 400;
1293
+ var MAX_BENDS = 6;
1294
+ var MAX_WIRES_FOR_PORT_SEARCH = 12;
1295
+ var OFF_FACING_SIDE_COST = 1;
1296
+ var SIDE_CHOICE_BEND_COST = 1e6;
1297
+ var INITIAL_STATE_CAPACITY = 4096;
1298
+ var MAX_WIRES_FOR_LOCAL_ROUTING = 200;
1299
+ var LOCAL_WINDOW_MARGIN = 240;
1300
+ var WALL_THICKNESS = 2;
1301
+ var MAX_WINDOW_SHARE = .1;
1302
+ var PORT_SPACING = 14;
1303
+ var PORT_INSET = 8;
1304
+ var BOX_CROSSING_COST = 100;
1305
+ var LABEL_CHAR_WIDTH = 6.6;
1306
+ var LABEL_GAP = 5;
1307
+ var LABEL_ASCENT = 10;
1308
+ var LABEL_CLEARANCE = 2;
1309
+ var LABEL_SLIDE_FRACTIONS = [
1310
+ .5,
1311
+ .35,
1312
+ .65,
1313
+ .2,
1314
+ .8
1315
+ ];
1316
+ var RIGHT = 0;
1317
+ var LEFT = 1;
1318
+ var STEP_BY_DIRECTION = [
1319
+ {
1320
+ x: 1,
1321
+ y: 0
1322
+ },
1323
+ {
1324
+ x: -1,
1325
+ y: 0
1326
+ },
1327
+ {
1328
+ x: 0,
1329
+ y: 1
1330
+ },
1331
+ {
1332
+ x: 0,
1333
+ y: -1
1334
+ }
1335
+ ];
1336
+ var OUTWARD_DIRECTION_BY_SIDE = {
1337
+ right: 0,
1338
+ left: 1,
1339
+ bottom: 2,
1340
+ top: 3
1341
+ };
1342
+ var INWARD_DIRECTION_BY_SIDE = {
1343
+ left: 0,
1344
+ right: 1,
1345
+ top: 2,
1346
+ bottom: 3
1347
+ };
1348
+ var REVERSE_DIRECTION = [
1349
+ 1,
1350
+ 0,
1351
+ 3,
1352
+ 2
1353
+ ];
1354
+ function isSideways(side) {
1355
+ return side === "left" || side === "right";
1356
+ }
1357
+ function centerOf(rect) {
1358
+ return {
1359
+ x: rect.x + rect.width / 2,
1360
+ y: rect.y + rect.height / 2
1361
+ };
1362
+ }
1363
+ function inflated(rect, by) {
1364
+ return {
1365
+ x: rect.x - by,
1366
+ y: rect.y - by,
1367
+ width: rect.width + by * 2,
1368
+ height: rect.height + by * 2
1369
+ };
1370
+ }
1371
+ function unionOf(rects) {
1372
+ if (rects.length === 0) return null;
1373
+ let left = Infinity;
1374
+ let top = Infinity;
1375
+ let right = -Infinity;
1376
+ let bottom = -Infinity;
1377
+ for (const rect of rects) {
1378
+ left = Math.min(left, rect.x);
1379
+ top = Math.min(top, rect.y);
1380
+ right = Math.max(right, rect.x + rect.width);
1381
+ bottom = Math.max(bottom, rect.y + rect.height);
1382
+ }
1383
+ return {
1384
+ x: left,
1385
+ y: top,
1386
+ width: right - left,
1387
+ height: bottom - top
1388
+ };
1389
+ }
1390
+ function groupedBy(items, keyOf) {
1391
+ const groups = /* @__PURE__ */ new Map();
1392
+ for (const item of items) {
1393
+ const key = keyOf(item);
1394
+ const group = groups.get(key);
1395
+ if (group) {
1396
+ group.push(item);
1397
+ continue;
1398
+ }
1399
+ groups.set(key, [item]);
1400
+ }
1401
+ return groups;
1402
+ }
1403
+ function isHorizontal(segment) {
1404
+ return segment.from.y === segment.to.y;
1405
+ }
1406
+ function segmentHitsRect(segment, rect) {
1407
+ const right = rect.x + rect.width;
1408
+ const bottom = rect.y + rect.height;
1409
+ if (isHorizontal(segment)) {
1410
+ const y = segment.from.y;
1411
+ return rect.y < y && y < bottom && Math.min(segment.from.x, segment.to.x) < right && Math.max(segment.from.x, segment.to.x) > rect.x;
1412
+ }
1413
+ const x = segment.from.x;
1414
+ return rect.x < x && x < right && Math.min(segment.from.y, segment.to.y) < bottom && Math.max(segment.from.y, segment.to.y) > rect.y;
1415
+ }
1416
+ function rectsOverlap(first, second) {
1417
+ return first.x < second.x + second.width && second.x < first.x + first.width && first.y < second.y + second.height && second.y < first.y + first.height;
1418
+ }
1419
+ function withoutBends(points) {
1420
+ const distinct = points.filter((point, index) => {
1421
+ const previous = points[index - 1];
1422
+ return !previous || previous.x !== point.x || previous.y !== point.y;
1423
+ });
1424
+ return distinct.filter((point, index) => {
1425
+ const previous = distinct[index - 1];
1426
+ const next = distinct[index + 1];
1427
+ if (!previous || !next) return true;
1428
+ return !(previous.x === point.x && point.x === next.x || previous.y === point.y && point.y === next.y);
1429
+ });
1430
+ }
1431
+ function segmentsOf(points) {
1432
+ return points.slice(1).flatMap((point, index) => {
1433
+ const previous = points[index];
1434
+ return previous ? [{
1435
+ from: previous,
1436
+ to: point
1437
+ }] : [];
1438
+ });
1439
+ }
1440
+ function pathOf(points) {
1441
+ return points.map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`).join(" ");
1442
+ }
1443
+ function cappedWarnings(warnings) {
1444
+ if (warnings.length <= WHITEBOARD_LIMITS.layoutWarnings) return [...warnings];
1445
+ const shown = warnings.slice(0, WHITEBOARD_LIMITS.layoutWarnings - 1);
1446
+ return [...shown, `and ${warnings.length - shown.length} more`];
1447
+ }
1448
+ function hasHorizontalGap(first, second) {
1449
+ return second.x >= first.x + first.width || second.x + second.width <= first.x;
1450
+ }
1451
+ function facingSides(from, to, isBack) {
1452
+ if (from.id === to.id) return {
1453
+ exitSide: "right",
1454
+ entrySide: "top"
1455
+ };
1456
+ if (isBack) return {
1457
+ exitSide: "bottom",
1458
+ entrySide: "bottom"
1459
+ };
1460
+ const fromCenter = centerOf(from);
1461
+ const toCenter = centerOf(to);
1462
+ if (hasHorizontalGap(from, to)) return toCenter.x > fromCenter.x ? {
1463
+ exitSide: "right",
1464
+ entrySide: "left"
1465
+ } : {
1466
+ exitSide: "left",
1467
+ entrySide: "right"
1468
+ };
1469
+ return toCenter.y > fromCenter.y ? {
1470
+ exitSide: "bottom",
1471
+ entrySide: "top"
1472
+ } : {
1473
+ exitSide: "top",
1474
+ entrySide: "bottom"
1475
+ };
1476
+ }
1477
+ var ALL_SIDES = [
1478
+ "right",
1479
+ "left",
1480
+ "bottom",
1481
+ "top"
1482
+ ];
1483
+ function probeOf(plan, pair) {
1484
+ const centeredStart = plan.outputPort ?? portPositions(plan.from, pair.exitSide, 1)[0] ?? centerOf(plan.from);
1485
+ const centeredEnd = portPositions(plan.to, pair.entrySide, 1)[0] ?? centerOf(plan.to);
1486
+ if (!isFacing(pair.exitSide, pair.entrySide)) return {
1487
+ ...plan,
1488
+ ...pair,
1489
+ start: centeredStart,
1490
+ end: centeredEnd
1491
+ };
1492
+ const alignedEnd = alignedAlong(centeredEnd, pair.entrySide, plan.to, centeredStart);
1493
+ const start = alignedEnd === centeredEnd && !plan.outputPort ? alignedAlong(centeredStart, pair.exitSide, plan.from, centeredEnd) : centeredStart;
1494
+ return {
1495
+ ...plan,
1496
+ ...pair,
1497
+ start,
1498
+ end: alignedEnd
1499
+ };
1500
+ }
1501
+ function pointsOfStates(graph, states) {
1502
+ return withoutBends(states.map((state) => ({
1503
+ x: graph.xs[state >> 2] ?? 0,
1504
+ y: graph.ys[state >> 2] ?? 0
1505
+ })));
1506
+ }
1507
+ function sideTerminalsOf(box, sides, facingSide, facingPoint, directionBySide) {
1508
+ return sides.map((side) => ({
1509
+ side,
1510
+ point: side === facingSide ? facingPoint : portPositions(box, side, 1)[0] ?? centerOf(box),
1511
+ direction: directionBySide[side],
1512
+ bias: side === facingSide ? 0 : OFF_FACING_SIDE_COST
1513
+ }));
1514
+ }
1515
+ function otherSidesFirst(facingSide) {
1516
+ return [facingSide, ...ALL_SIDES.filter((side) => side !== facingSide)];
1517
+ }
1518
+ function sideChoiceOf(plan, facing) {
1519
+ const { wire, from, to } = plan;
1520
+ if (wire.back || from.id === to.id) return null;
1521
+ const exitSides = plan.outputPort || wire.fromSide ? [plan.exitSide] : otherSidesFirst(facing.exitSide);
1522
+ const entrySides = wire.toSide ? [wire.toSide] : otherSidesFirst(facing.entrySide);
1523
+ if (exitSides.length < 2 && entrySides.length < 2) return null;
1524
+ const facingProbe = probeOf(plan, {
1525
+ exitSide: exitSides[0] ?? facing.exitSide,
1526
+ entrySide: entrySides[0] ?? facing.entrySide
1527
+ });
1528
+ return {
1529
+ plan,
1530
+ exits: plan.outputPort ? [{
1531
+ side: plan.exitSide,
1532
+ point: plan.outputPort,
1533
+ direction: OUTWARD_DIRECTION_BY_SIDE[plan.exitSide],
1534
+ bias: 0
1535
+ }] : sideTerminalsOf(from, exitSides, exitSides[0] ?? facing.exitSide, facingProbe.start, OUTWARD_DIRECTION_BY_SIDE),
1536
+ entries: sideTerminalsOf(to, entrySides, entrySides[0] ?? facing.entrySide, facingProbe.end, INWARD_DIRECTION_BY_SIDE)
1537
+ };
1538
+ }
1539
+ function choicePortsOf(choices) {
1540
+ return choices.flatMap((choice) => [...choice.exits.map((exit) => ({
1541
+ x: exit.point.x,
1542
+ y: exit.point.y,
1543
+ outwardDirection: exit.direction
1544
+ })), ...choice.entries.map((entry) => ({
1545
+ x: entry.point.x,
1546
+ y: entry.point.y,
1547
+ outwardDirection: REVERSE_DIRECTION[entry.direction] ?? 0
1548
+ }))]);
1549
+ }
1550
+ function applySideChoice(choice, chosen) {
1551
+ if (!chosen) return;
1552
+ choice.plan.exitSide = chosen.exit.side;
1553
+ choice.plan.entrySide = chosen.entry.side;
1554
+ }
1555
+ function chooseSidesLocally(choices, input, reuse) {
1556
+ const buffers = createSearchBuffers();
1557
+ const searchOn = (graph, choice) => {
1558
+ if (!graph) return null;
1559
+ const chosen = searchBetween(graph, choice.exits, choice.entries, null, SIDE_CHOICE_BEND_COST, buffers);
1560
+ resetSearchBuffers(buffers);
1561
+ return chosen;
1562
+ };
1563
+ const wholeBoardChoices = [];
1564
+ for (const choice of choices) {
1565
+ const window = windowOf(choice.plan, reuse);
1566
+ const solidsInWindow = windowSolidsOf(input, window);
1567
+ const chosen = solidsInWindow ? searchOn(windowGraphOf(choicePortsOf([choice]), input, window, solidsInWindow), choice) : null;
1568
+ if (chosen) applySideChoice(choice, chosen);
1569
+ if (!chosen) wholeBoardChoices.push(choice);
1570
+ }
1571
+ if (wholeBoardChoices.length === 0) return;
1572
+ const wholeGraph = graphOf(choicePortsOf(wholeBoardChoices), input);
1573
+ for (const choice of wholeBoardChoices) applySideChoice(choice, searchOn(wholeGraph, choice));
1574
+ }
1575
+ function chooseSidesBySearch(plans, facingByPlan, input, reuse) {
1576
+ const choices = plans.flatMap((plan) => {
1577
+ if (reuse?.cleanIds.has(plan.wire.id)) return [];
1578
+ const choice = sideChoiceOf(plan, facingByPlan.get(plan) ?? {
1579
+ exitSide: plan.exitSide,
1580
+ entrySide: plan.entrySide
1581
+ });
1582
+ return choice ? [choice] : [];
1583
+ });
1584
+ if (choices.length === 0) return;
1585
+ if (reuse?.isLocal) {
1586
+ chooseSidesLocally(choices, input, reuse);
1587
+ return;
1588
+ }
1589
+ const graph = graphOf(choicePortsOf(choices), input);
1590
+ if (!graph) return;
1591
+ const buffers = createSearchBuffers();
1592
+ for (const choice of choices) {
1593
+ const chosen = searchBetween(graph, choice.exits, choice.entries, null, SIDE_CHOICE_BEND_COST, buffers);
1594
+ resetSearchBuffers(buffers);
1595
+ applySideChoice(choice, chosen);
1596
+ }
1597
+ }
1598
+ function joinFacingBuses(plans, facingByPlan) {
1599
+ const busOf = (plan, side) => `${plan.to.id}|${plan.styleKey}|${side}`;
1600
+ const facingEntryCountByBus = /* @__PURE__ */ new Map();
1601
+ for (const plan of plans) {
1602
+ if (plan.entrySide !== facingByPlan.get(plan)?.entrySide) continue;
1603
+ facingEntryCountByBus.set(busOf(plan, plan.entrySide), (facingEntryCountByBus.get(busOf(plan, plan.entrySide)) ?? 0) + 1);
1604
+ }
1605
+ for (const plan of plans) {
1606
+ const facing = facingByPlan.get(plan);
1607
+ if (!facing || plan.entrySide === facing.entrySide || plan.wire.toSide) continue;
1608
+ if ((facingEntryCountByBus.get(busOf(plan, facing.entrySide)) ?? 0) === 0) continue;
1609
+ plan.exitSide = plan.outputPort || plan.wire.fromSide ? plan.exitSide : facing.exitSide;
1610
+ plan.entrySide = facing.entrySide;
1611
+ }
1612
+ }
1613
+ function planWires(input, reuse) {
1614
+ const facingByPlan = /* @__PURE__ */ new Map();
1615
+ const plans = input.wires.flatMap((wire) => {
1616
+ const from = input.boxesById.get(wire.from);
1617
+ const to = input.boxesById.get(wire.to);
1618
+ if (!from || !to) return [];
1619
+ const facing = facingSides(from, to, wire.back);
1620
+ const output = from.outputs.find((candidate) => candidate.id === wire.fromOutput);
1621
+ const strokeHex = wire.tone === "lane" ? from.lane?.hex ?? null : null;
1622
+ const plan = {
1623
+ wire,
1624
+ from,
1625
+ to,
1626
+ strokeHex,
1627
+ styleKey: `${wire.dashed || wire.back}|${wire.tone}|${strokeHex}`,
1628
+ exitSide: output ? "right" : wire.fromSide ?? facing.exitSide,
1629
+ entrySide: wire.toSide ?? facing.entrySide,
1630
+ busKey: null,
1631
+ exitKey: "",
1632
+ outputPort: output?.port ?? null,
1633
+ start: output?.port ?? centerOf(from),
1634
+ end: centerOf(to)
1635
+ };
1636
+ const remembered = reuse?.cleanIds.has(wire.id) ? reuse.routeById.get(wire.id) : void 0;
1637
+ if (remembered) {
1638
+ plan.exitSide = remembered.exitSide;
1639
+ plan.entrySide = remembered.entrySide;
1640
+ }
1641
+ facingByPlan.set(plan, facing);
1642
+ return [plan];
1643
+ });
1644
+ chooseSidesBySearch(plans, facingByPlan, input, reuse);
1645
+ joinFacingBuses(plans, facingByPlan);
1646
+ for (const plan of plans) {
1647
+ const outputId = plan.wire.fromOutput;
1648
+ plan.exitKey = plan.outputPort && outputId ? `${plan.from.id}|output ${outputId}|${plan.styleKey}` : `${plan.from.id}|${plan.exitSide}|${plan.styleKey}`;
1649
+ }
1650
+ const busKeyOf = (plan) => `${plan.to.id}|${plan.entrySide}|${plan.styleKey}`;
1651
+ const memberCountByBusKey = /* @__PURE__ */ new Map();
1652
+ for (const plan of plans) memberCountByBusKey.set(busKeyOf(plan), (memberCountByBusKey.get(busKeyOf(plan)) ?? 0) + 1);
1653
+ for (const plan of plans) if ((memberCountByBusKey.get(busKeyOf(plan)) ?? 0) > 1) plan.busKey = busKeyOf(plan);
1654
+ return plans;
1655
+ }
1656
+ function portPositions(box, side, count) {
1657
+ const indexes = Array.from({ length: count }, (_, index) => index);
1658
+ if (isSideways(side)) {
1659
+ const x = Math.round(side === "left" ? box.x : box.x + box.width);
1660
+ const spacing = Math.min(PORT_SPACING, (box.height - 16) / Math.max(count - 1, 1));
1661
+ const centeredFirstY = box.y + Math.min(box.height / 2, 40) - (count - 1) * spacing / 2;
1662
+ const firstY = Math.max(box.y + PORT_INSET, Math.min(centeredFirstY, box.y + box.height - PORT_INSET - (count - 1) * spacing));
1663
+ return indexes.map((index) => ({
1664
+ x,
1665
+ y: Math.round(firstY + index * spacing)
1666
+ }));
1667
+ }
1668
+ const y = Math.round(side === "top" ? box.y : box.y + box.height);
1669
+ const firstX = box.x + box.width / 2 - (count - 1) * PORT_SPACING / 2;
1670
+ return indexes.map((index) => ({
1671
+ x: Math.round(firstX + index * PORT_SPACING),
1672
+ y
1673
+ }));
1674
+ }
1675
+ function portCapacity(box, side) {
1676
+ const sideLength = isSideways(side) ? box.height : box.width;
1677
+ return Math.max(1, Math.floor((sideLength - 16) / PORT_SPACING) + 1);
1678
+ }
1679
+ function portRequestsBySide(plans) {
1680
+ return groupedBy(plans.flatMap((plan) => [...plan.outputPort ? [] : [{
1681
+ box: plan.from,
1682
+ side: plan.exitSide,
1683
+ groupKey: `exit|${plan.styleKey}`,
1684
+ wireId: plan.wire.id,
1685
+ farPoint: centerOf(plan.to),
1686
+ assign: (point) => {
1687
+ plan.start = point;
1688
+ }
1689
+ }], {
1690
+ box: plan.to,
1691
+ side: plan.entrySide,
1692
+ groupKey: plan.busKey ? `bus|${plan.busKey}` : `entry|${plan.wire.id}`,
1693
+ wireId: plan.wire.id,
1694
+ farPoint: plan.outputPort ?? centerOf(plan.from),
1695
+ assign: (point) => {
1696
+ plan.end = point;
1697
+ }
1698
+ }]), (request) => `${request.box.id}|${request.side}`);
1699
+ }
1700
+ function defaultPortOrders(requestsBySide) {
1701
+ return new Map([...requestsBySide.entries()].map(([sideKey, sideRequests]) => {
1702
+ return [sideKey, [...groupedBy(sideRequests, (request) => request.groupKey).entries()].map(([groupKey, members]) => ({
1703
+ groupKey,
1704
+ firstWireId: members.map((member) => member.wireId).sort()[0] ?? groupKey,
1705
+ farCoordinate: members.reduce((sum, member) => sum + (isSideways(member.side) ? member.farPoint.y : member.farPoint.x), 0) / members.length
1706
+ })).sort((left, right) => left.farCoordinate - right.farCoordinate || left.firstWireId.localeCompare(right.firstWireId) || left.groupKey.localeCompare(right.groupKey)).map((group) => group.groupKey)];
1707
+ }));
1708
+ }
1709
+ function assignPorts(requestsBySide, groupOrderBySide) {
1710
+ for (const [sideKey, sideRequests] of requestsBySide) {
1711
+ const first = sideRequests[0];
1712
+ const groupOrder = groupOrderBySide.get(sideKey) ?? [];
1713
+ if (!first) continue;
1714
+ const positions = portPositions(first.box, first.side, groupOrder.length);
1715
+ for (const request of sideRequests) {
1716
+ const position = positions[groupOrder.indexOf(request.groupKey)];
1717
+ if (position) request.assign(position);
1718
+ }
1719
+ }
1720
+ }
1721
+ function isFacing(exitSide, entrySide) {
1722
+ return exitSide === "right" && entrySide === "left" || exitSide === "left" && entrySide === "right" || exitSide === "bottom" && entrySide === "top" || exitSide === "top" && entrySide === "bottom";
1723
+ }
1724
+ function alignedAlong(point, side, box, target) {
1725
+ if (isSideways(side)) return target.y >= box.y + PORT_INSET && target.y <= box.y + box.height - PORT_INSET ? {
1726
+ x: point.x,
1727
+ y: target.y
1728
+ } : point;
1729
+ return target.x >= box.x + PORT_INSET && target.x <= box.x + box.width - PORT_INSET ? {
1730
+ x: target.x,
1731
+ y: point.y
1732
+ } : point;
1733
+ }
1734
+ function alignLonePorts(plans, groupOrderBySide) {
1735
+ const isLonePort = (box, side) => (groupOrderBySide.get(`${box.id}|${side}`)?.length ?? 0) === 1;
1736
+ const memberCountByExitKey = new Map([...groupedBy(plans, (plan) => plan.exitKey)].map(([exitKey, members]) => [exitKey, members.length]));
1737
+ for (const plan of plans) {
1738
+ if (plan.from.id === plan.to.id || !isFacing(plan.exitSide, plan.entrySide)) continue;
1739
+ const alignedEnd = plan.busKey === null && isLonePort(plan.to, plan.entrySide) ? alignedAlong(plan.end, plan.entrySide, plan.to, plan.start) : plan.end;
1740
+ if (alignedEnd !== plan.end) {
1741
+ plan.end = alignedEnd;
1742
+ continue;
1743
+ }
1744
+ if (plan.outputPort === null && isLonePort(plan.from, plan.exitSide) && memberCountByExitKey.get(plan.exitKey) === 1) plan.start = alignedAlong(plan.start, plan.exitSide, plan.from, plan.end);
1745
+ }
1746
+ }
1747
+ function crowdedSideWarnings(requestsBySide, groupOrderBySide) {
1748
+ return [...requestsBySide.entries()].flatMap(([sideKey, sideRequests]) => {
1749
+ const first = sideRequests[0];
1750
+ const portCount = groupOrderBySide.get(sideKey)?.length ?? 0;
1751
+ if (!first || portCount <= portCapacity(first.box, first.side)) return [];
1752
+ return [`box ${first.box.id} has ${portCount} wires on its ${first.side} side, more than fit`];
1753
+ });
1754
+ }
1755
+ function portsOf(plans) {
1756
+ return plans.flatMap((plan) => [{
1757
+ x: plan.start.x,
1758
+ y: plan.start.y,
1759
+ outwardDirection: OUTWARD_DIRECTION_BY_SIDE[plan.exitSide]
1760
+ }, {
1761
+ x: plan.end.x,
1762
+ y: plan.end.y,
1763
+ outwardDirection: OUTWARD_DIRECTION_BY_SIDE[plan.entrySide]
1764
+ }]);
1765
+ }
1766
+ function graphOf(ports, input) {
1767
+ return buildVisibilityGraph({
1768
+ hardRects: [...input.boxesById.values(), ...input.panels],
1769
+ softRects: input.softObstacles,
1770
+ ports,
1771
+ contentTop: input.contentTop
1772
+ });
1773
+ }
1774
+ function wallsAround(window) {
1775
+ const outerLeft = window.x - WALL_THICKNESS;
1776
+ const outerTop = window.y - WALL_THICKNESS;
1777
+ const outerWidth = window.width + 4;
1778
+ const outerHeight = window.height + 4;
1779
+ return [
1780
+ {
1781
+ x: outerLeft,
1782
+ y: outerTop,
1783
+ width: outerWidth,
1784
+ height: WALL_THICKNESS
1785
+ },
1786
+ {
1787
+ x: outerLeft,
1788
+ y: window.y + window.height,
1789
+ width: outerWidth,
1790
+ height: WALL_THICKNESS
1791
+ },
1792
+ {
1793
+ x: outerLeft,
1794
+ y: outerTop,
1795
+ width: WALL_THICKNESS,
1796
+ height: outerHeight
1797
+ },
1798
+ {
1799
+ x: window.x + window.width,
1800
+ y: outerTop,
1801
+ width: WALL_THICKNESS,
1802
+ height: outerHeight
1803
+ }
1804
+ ];
1805
+ }
1806
+ function windowSolidsOf(input, window) {
1807
+ const solids = solidsOf(input);
1808
+ const solidsInWindow = solids.filter((rect) => rectsOverlap(rect, window));
1809
+ return solidsInWindow.length > solids.length * MAX_WINDOW_SHARE ? null : solidsInWindow;
1810
+ }
1811
+ function windowGraphOf(ports, input, window, solidsInWindow) {
1812
+ const softRects = input.softObstacles.filter((rect) => rectsOverlap(rect, window));
1813
+ return buildVisibilityGraph({
1814
+ hardRects: [...solidsInWindow, ...wallsAround(window)],
1815
+ softRects,
1816
+ ports,
1817
+ contentTop: input.contentTop
1818
+ });
1819
+ }
1820
+ function windowOf(plan, reuse) {
1821
+ const pointRects = (reuse.routeById.get(plan.wire.id)?.points ?? []).map((point) => ({
1822
+ x: point.x,
1823
+ y: point.y,
1824
+ width: 0,
1825
+ height: 0
1826
+ }));
1827
+ return inflated(unionOf([
1828
+ plan.from,
1829
+ plan.to,
1830
+ ...pointRects
1831
+ ]) ?? plan.from, LOCAL_WINDOW_MARGIN);
1832
+ }
1833
+ function createMinHeap() {
1834
+ return {
1835
+ states: /* @__PURE__ */ new Int32Array(1024),
1836
+ priorities: /* @__PURE__ */ new Float64Array(1024),
1837
+ tieBreaks: /* @__PURE__ */ new Float64Array(1024),
1838
+ size: 0,
1839
+ lastPoppedPriority: 0
1840
+ };
1841
+ }
1842
+ function isHeapEntryBefore(heap, first, second) {
1843
+ const firstPriority = heap.priorities[first] ?? 0;
1844
+ const secondPriority = heap.priorities[second] ?? 0;
1845
+ return firstPriority < secondPriority || firstPriority === secondPriority && (heap.tieBreaks[first] ?? 0) < (heap.tieBreaks[second] ?? 0);
1846
+ }
1847
+ function swapHeapEntries(heap, first, second) {
1848
+ const firstState = heap.states[first] ?? 0;
1849
+ const firstPriority = heap.priorities[first] ?? 0;
1850
+ const firstTieBreak = heap.tieBreaks[first] ?? 0;
1851
+ heap.states[first] = heap.states[second] ?? 0;
1852
+ heap.priorities[first] = heap.priorities[second] ?? 0;
1853
+ heap.tieBreaks[first] = heap.tieBreaks[second] ?? 0;
1854
+ heap.states[second] = firstState;
1855
+ heap.priorities[second] = firstPriority;
1856
+ heap.tieBreaks[second] = firstTieBreak;
1857
+ }
1858
+ function pushToHeap(heap, state, priority, tieBreak) {
1859
+ if (heap.size === heap.states.length) {
1860
+ const states = new Int32Array(heap.size * 2);
1861
+ const priorities = new Float64Array(heap.size * 2);
1862
+ const tieBreaks = new Float64Array(heap.size * 2);
1863
+ states.set(heap.states);
1864
+ priorities.set(heap.priorities);
1865
+ tieBreaks.set(heap.tieBreaks);
1866
+ heap.states = states;
1867
+ heap.priorities = priorities;
1868
+ heap.tieBreaks = tieBreaks;
1869
+ }
1870
+ heap.states[heap.size] = state;
1871
+ heap.priorities[heap.size] = priority;
1872
+ heap.tieBreaks[heap.size] = tieBreak;
1873
+ let index = heap.size;
1874
+ heap.size += 1;
1875
+ while (index > 0) {
1876
+ const parent = index - 1 >> 1;
1877
+ if (!isHeapEntryBefore(heap, index, parent)) return;
1878
+ swapHeapEntries(heap, parent, index);
1879
+ index = parent;
1880
+ }
1881
+ }
1882
+ function popFromHeap(heap) {
1883
+ if (heap.size === 0) return -1;
1884
+ const top = heap.states[0] ?? -1;
1885
+ heap.lastPoppedPriority = heap.priorities[0] ?? 0;
1886
+ heap.size -= 1;
1887
+ if (heap.size === 0) return top;
1888
+ swapHeapEntries(heap, 0, heap.size);
1889
+ let index = 0;
1890
+ for (;;) {
1891
+ const left = index * 2 + 1;
1892
+ const right = left + 1;
1893
+ let smallest = index;
1894
+ if (left < heap.size && isHeapEntryBefore(heap, left, smallest)) smallest = left;
1895
+ if (right < heap.size && isHeapEntryBefore(heap, right, smallest)) smallest = right;
1896
+ if (smallest === index) return top;
1897
+ swapHeapEntries(heap, smallest, index);
1898
+ index = smallest;
1899
+ }
1900
+ }
1901
+ function createSearchBuffers() {
1902
+ return {
1903
+ bestCost: new Float64Array(INITIAL_STATE_CAPACITY).fill(Infinity),
1904
+ cameFrom: new Int32Array(INITIAL_STATE_CAPACITY).fill(-1),
1905
+ touchedStates: [],
1906
+ heap: createMinHeap()
1907
+ };
1908
+ }
1909
+ function ensureStateCapacity(buffers, stateCount) {
1910
+ if (stateCount <= buffers.bestCost.length) return;
1911
+ const capacity = Math.max(stateCount, buffers.bestCost.length * 2);
1912
+ const bestCost = new Float64Array(capacity).fill(Infinity);
1913
+ const cameFrom = new Int32Array(capacity).fill(-1);
1914
+ bestCost.set(buffers.bestCost);
1915
+ cameFrom.set(buffers.cameFrom);
1916
+ buffers.bestCost = bestCost;
1917
+ buffers.cameFrom = cameFrom;
1918
+ }
1919
+ function resetSearchBuffers(buffers) {
1920
+ for (const state of buffers.touchedStates) {
1921
+ buffers.bestCost[state] = Infinity;
1922
+ buffers.cameFrom[state] = -1;
1923
+ }
1924
+ buffers.touchedStates.length = 0;
1925
+ buffers.heap.size = 0;
1926
+ }
1927
+ function routeOnGraph(graph, plan, backInterior, buffers) {
1928
+ const exit = {
1929
+ side: plan.exitSide,
1930
+ point: plan.start,
1931
+ direction: OUTWARD_DIRECTION_BY_SIDE[plan.exitSide],
1932
+ bias: 0
1933
+ };
1934
+ const entry = {
1935
+ side: plan.entrySide,
1936
+ point: plan.end,
1937
+ direction: INWARD_DIRECTION_BY_SIDE[plan.entrySide],
1938
+ bias: 0
1939
+ };
1940
+ const states = searchBetween(graph, [exit], [entry], backInterior, BEND_COST, buffers)?.states ?? null;
1941
+ resetSearchBuffers(buffers);
1942
+ return states;
1943
+ }
1944
+ function graphEdgeHitsRect(graph, node, nextNode, rect) {
1945
+ const fromX = graph.xs[node] ?? 0;
1946
+ const fromY = graph.ys[node] ?? 0;
1947
+ const toX = graph.xs[nextNode] ?? 0;
1948
+ const toY = graph.ys[nextNode] ?? 0;
1949
+ if (fromY === toY) return rect.y < fromY && fromY < rect.y + rect.height && Math.min(fromX, toX) < rect.x + rect.width && Math.max(fromX, toX) > rect.x;
1950
+ return rect.x < fromX && fromX < rect.x + rect.width && Math.min(fromY, toY) < rect.y + rect.height && Math.max(fromY, toY) > rect.y;
1951
+ }
1952
+ function isAlongX(direction) {
1953
+ return direction === RIGHT || direction === LEFT;
1954
+ }
1955
+ function fewestBendsTo(direction, entry, x, y) {
1956
+ if (direction === REVERSE_DIRECTION[entry.direction]) return 2;
1957
+ const isEntryAlongX = isAlongX(entry.direction);
1958
+ const along = isEntryAlongX ? x : y;
1959
+ const across = isEntryAlongX ? y : x;
1960
+ const approachLine = isEntryAlongX ? entry.point.y : entry.point.x;
1961
+ const isWithinApproach = entry.approachStart <= along && along <= entry.approachEnd;
1962
+ const step = STEP_BY_DIRECTION[direction] ?? {
1963
+ x: 0,
1964
+ y: 0
1965
+ };
1966
+ if (direction === entry.direction) {
1967
+ const towardPort = isEntryAlongX ? (entry.point.x - x) * step.x : (entry.point.y - y) * step.y;
1968
+ return across === approachLine && isWithinApproach && towardPort >= 0 ? 0 : 2;
1969
+ }
1970
+ const towardLine = (approachLine - across) * (isEntryAlongX ? step.y : step.x);
1971
+ return isWithinApproach && towardLine >= 0 ? 1 : 3;
1972
+ }
1973
+ function placedTerminalsOf(graph, terminals) {
1974
+ return terminals.flatMap((terminal) => {
1975
+ const node = graph.nodeAt(terminal.point.x, terminal.point.y);
1976
+ if (node < 0) return [];
1977
+ const [approachStart, approachEnd] = graph.pieceExtentOf(node, isAlongX(terminal.direction));
1978
+ return [{
1979
+ ...terminal,
1980
+ node,
1981
+ component: graph.componentOf(node),
1982
+ approachStart,
1983
+ approachEnd
1984
+ }];
1985
+ });
1986
+ }
1987
+ function terminalAt(terminals, node) {
1988
+ for (const terminal of terminals) if (terminal.node === node) return terminal;
1989
+ return null;
1990
+ }
1991
+ function searchBetween(graph, exits, entries, backInterior, bendCost, buffers) {
1992
+ graph.beginSearch();
1993
+ const placedEntries = placedTerminalsOf(graph, entries);
1994
+ const placedExits = placedTerminalsOf(graph, exits).filter((exit) => placedEntries.some((entry) => entry.component === exit.component));
1995
+ const reachableEntries = placedEntries.filter((entry) => placedExits.some((exit) => exit.component === entry.component));
1996
+ if (placedExits.length === 0 || reachableEntries.length === 0) return null;
1997
+ const { touchedStates, heap } = buffers;
1998
+ ensureStateCapacity(buffers, graph.nodeCount * 4);
1999
+ const estimate = (node, direction) => {
2000
+ const x = graph.xs[node] ?? 0;
2001
+ const y = graph.ys[node] ?? 0;
2002
+ let nearest = Infinity;
2003
+ for (const entry of reachableEntries) nearest = Math.min(nearest, Math.abs(entry.point.x - x) + Math.abs(entry.point.y - y) + fewestBendsTo(direction, entry, x, y) * bendCost + entry.bias);
2004
+ return nearest;
2005
+ };
2006
+ for (const exit of placedExits) {
2007
+ const state = exit.node * 4 + exit.direction;
2008
+ buffers.bestCost[state] = exit.bias;
2009
+ touchedStates.push(state);
2010
+ pushToHeap(heap, state, exit.bias + estimate(exit.node, exit.direction), -exit.bias);
2011
+ }
2012
+ for (;;) {
2013
+ const state = popFromHeap(heap);
2014
+ if (state < 0) return null;
2015
+ const node = state >> 2;
2016
+ const direction = state & 3;
2017
+ const arrivedEntry = terminalAt(reachableEntries, node);
2018
+ if (arrivedEntry && direction === arrivedEntry.direction) {
2019
+ const states = reconstructNodes(buffers.cameFrom, state);
2020
+ const exit = terminalAt(placedExits, (states[0] ?? 0) >> 2);
2021
+ return exit ? {
2022
+ states,
2023
+ exit,
2024
+ entry: arrivedEntry
2025
+ } : null;
2026
+ }
2027
+ const costSoFar = buffers.bestCost[state] ?? Infinity;
2028
+ if (heap.lastPoppedPriority > costSoFar + estimate(node, direction) + 1e-6) continue;
2029
+ const departingExit = terminalAt(placedExits, node);
2030
+ for (let nextDirection = 0; nextDirection < 4; nextDirection += 1) {
2031
+ if (departingExit && nextDirection !== departingExit.direction) continue;
2032
+ if (nextDirection === REVERSE_DIRECTION[direction]) continue;
2033
+ const nextNode = graph.neighborOf(node, nextDirection);
2034
+ if (nextNode < 0) continue;
2035
+ const nextEntry = terminalAt(reachableEntries, nextNode);
2036
+ if (nextEntry && nextDirection !== nextEntry.direction) continue;
2037
+ ensureStateCapacity(buffers, graph.nodeCount * 4);
2038
+ const length = Math.abs((graph.xs[nextNode] ?? 0) - (graph.xs[node] ?? 0)) + Math.abs((graph.ys[nextNode] ?? 0) - (graph.ys[node] ?? 0));
2039
+ const isInsideBackInterior = backInterior !== null && graphEdgeHitsRect(graph, node, nextNode, backInterior);
2040
+ const stepCost = length + (nextDirection === direction ? 0 : bendCost) + (graph.isSoftStep(node, nextDirection) ? SOFT_OBSTACLE_COST : 0) + (isInsideBackInterior ? BACK_INTERIOR_COST : 0);
2041
+ const nextState = nextNode * 4 + nextDirection;
2042
+ const nextCost = costSoFar + Math.max(stepCost, 1) + (nextEntry?.bias ?? 0);
2043
+ if (nextCost >= (buffers.bestCost[nextState] ?? Infinity)) continue;
2044
+ buffers.bestCost[nextState] = nextCost;
2045
+ buffers.cameFrom[nextState] = state;
2046
+ touchedStates.push(nextState);
2047
+ pushToHeap(heap, nextState, nextCost + estimate(nextNode, nextDirection), -nextCost);
2048
+ }
2049
+ }
2050
+ }
2051
+ function reconstructNodes(cameFrom, goalState) {
2052
+ const states = [];
2053
+ for (let state = goalState; state !== -1; state = cameFrom[state] ?? -1) states.push(state);
2054
+ return states.reverse();
2055
+ }
2056
+ function stubOf(point, side) {
2057
+ const step = STEP_BY_DIRECTION[OUTWARD_DIRECTION_BY_SIDE[side]] ?? {
2058
+ x: 0,
2059
+ y: 0
2060
+ };
2061
+ return {
2062
+ x: point.x + step.x * 14,
2063
+ y: point.y + step.y * 14
2064
+ };
2065
+ }
2066
+ function fallbackPoints(plan) {
2067
+ const startStub = stubOf(plan.start, plan.exitSide);
2068
+ const endStub = stubOf(plan.end, plan.entrySide);
2069
+ return withoutBends([
2070
+ plan.start,
2071
+ startStub,
2072
+ {
2073
+ x: endStub.x,
2074
+ y: startStub.y
2075
+ },
2076
+ endStub,
2077
+ plan.end
2078
+ ]);
2079
+ }
2080
+ function backInteriorOf(plan, loopFrames) {
2081
+ if (!plan.wire.back) return null;
2082
+ const span = unionOf([plan.from, plan.to]);
2083
+ if (!span) return null;
2084
+ return loopFrames.find((frame) => frame.x <= span.x && frame.y <= span.y && frame.x + frame.width >= span.x + span.width && frame.y + frame.height >= span.y + span.height) ?? span;
2085
+ }
2086
+ function drawnWireOf(graph, plan, states) {
2087
+ const points = graph && states ? pointsOfStates(graph, states) : fallbackPoints(plan);
2088
+ return {
2089
+ plan,
2090
+ points,
2091
+ segments: segmentsOf(points),
2092
+ routedPoints: points,
2093
+ states
2094
+ };
2095
+ }
2096
+ function isSamePoint(first, second) {
2097
+ return first.x === second.x && first.y === second.y;
2098
+ }
2099
+ function reusedWireOf(plan, reuse) {
2100
+ if (!reuse?.cleanIds.has(plan.wire.id)) return null;
2101
+ const remembered = reuse.routeById.get(plan.wire.id);
2102
+ if (!remembered || remembered.exitSide !== plan.exitSide || remembered.entrySide !== plan.entrySide) return null;
2103
+ if (!isSamePoint(remembered.start, plan.start) || !isSamePoint(remembered.end, plan.end)) return null;
2104
+ return {
2105
+ plan,
2106
+ points: remembered.points,
2107
+ segments: segmentsOf(remembered.points),
2108
+ routedPoints: remembered.points,
2109
+ states: remembered.isRouted ? [] : null
2110
+ };
2111
+ }
2112
+ function routedOnOneGraph(plans, input, reuse) {
2113
+ const reused = plans.map((plan) => reusedWireOf(plan, reuse));
2114
+ const graph = reused.every(Boolean) ? null : graphOf(portsOf(plans), input);
2115
+ const buffers = graph ? createSearchBuffers() : null;
2116
+ return plans.map((plan, index) => reused[index] ?? drawnWireOf(graph, plan, graph && buffers ? routeOnGraph(graph, plan, backInteriorOf(plan, input.loopFrames), buffers) : null));
2117
+ }
2118
+ function routedInWindow(plan, input, reuse, buffers) {
2119
+ const window = windowOf(plan, reuse);
2120
+ const solidsInWindow = windowSolidsOf(input, window);
2121
+ if (!solidsInWindow) return null;
2122
+ const windowGraph = windowGraphOf(portsOf([plan]), input, window, solidsInWindow);
2123
+ const windowStates = windowGraph ? routeOnGraph(windowGraph, plan, backInteriorOf(plan, input.loopFrames), buffers) : null;
2124
+ return windowStates ? drawnWireOf(windowGraph, plan, windowStates) : null;
2125
+ }
2126
+ function routedLocally(plans, input, reuse) {
2127
+ const buffers = createSearchBuffers();
2128
+ const routed = plans.map((plan) => reusedWireOf(plan, reuse) ?? routedInWindow(plan, input, reuse, buffers));
2129
+ const wholeBoardPlans = plans.filter((_, index) => !routed[index]);
2130
+ if (wholeBoardPlans.length === 0) return routed.filter((wire) => wire !== null);
2131
+ const wholeGraph = graphOf(portsOf(wholeBoardPlans), input);
2132
+ return plans.map((plan, index) => routed[index] ?? drawnWireOf(wholeGraph, plan, wholeGraph ? routeOnGraph(wholeGraph, plan, backInteriorOf(plan, input.loopFrames), buffers) : null));
2133
+ }
2134
+ function routeAll(plans, input, reuse) {
2135
+ const routed = reuse?.isLocal ? routedLocally(plans, input, reuse) : routedOnOneGraph(plans, input, reuse);
2136
+ const nudgedPoints = nudgeSharedLines(routed.map((wire) => ({
2137
+ points: wire.points,
2138
+ exitKey: wire.plan.exitKey,
2139
+ busKey: wire.plan.busKey
2140
+ })), solidsOf(input));
2141
+ return routed.map((wire, index) => {
2142
+ const points = withoutBends(nudgedPoints[index] ?? wire.points);
2143
+ return {
2144
+ ...wire,
2145
+ points,
2146
+ segments: segmentsOf(points)
2147
+ };
2148
+ });
2149
+ }
2150
+ function bendCountOf(wire) {
2151
+ return Math.max(0, wire.points.length - 2);
2152
+ }
2153
+ function labelWidthOf(label) {
2154
+ return Math.ceil(label.length * LABEL_CHAR_WIDTH);
2155
+ }
2156
+ function labelBoundsAt(baseline, width) {
2157
+ return {
2158
+ x: baseline.x - width / 2,
2159
+ y: baseline.y - LABEL_ASCENT,
2160
+ width,
2161
+ height: 13
2162
+ };
2163
+ }
2164
+ function segmentLength(segment) {
2165
+ return Math.abs(segment.from.x - segment.to.x) + Math.abs(segment.from.y - segment.to.y);
2166
+ }
2167
+ function flushLabelCandidates(segment, width) {
2168
+ if (!isHorizontal(segment)) return [];
2169
+ const y = segment.from.y;
2170
+ return [Math.min(segment.from.x, segment.to.x) + LABEL_GAP + width / 2, Math.max(segment.from.x, segment.to.x) - LABEL_GAP - width / 2].flatMap((x) => [{
2171
+ x,
2172
+ y: y - LABEL_GAP
2173
+ }, {
2174
+ x,
2175
+ y: y + LABEL_GAP + LABEL_ASCENT
2176
+ }]);
2177
+ }
2178
+ function labelCandidates(segments, width) {
2179
+ const byLength = [...segments].sort((left, right) => segmentLength(right) - segmentLength(left));
2180
+ return [...segments.slice(0, 1), ...byLength].flatMap((segment) => [...LABEL_SLIDE_FRACTIONS.flatMap((fraction) => {
2181
+ const x = segment.from.x + (segment.to.x - segment.from.x) * fraction;
2182
+ const y = segment.from.y + (segment.to.y - segment.from.y) * fraction;
2183
+ if (isHorizontal(segment)) return [{
2184
+ x,
2185
+ y: y - LABEL_GAP
2186
+ }, {
2187
+ x,
2188
+ y: y + LABEL_GAP + LABEL_ASCENT
2189
+ }];
2190
+ return [{
2191
+ x: x + LABEL_GAP + width / 2,
2192
+ y: y + LABEL_ASCENT / 2
2193
+ }, {
2194
+ x: x - LABEL_GAP - width / 2,
2195
+ y: y + LABEL_ASCENT / 2
2196
+ }];
2197
+ }), ...flushLabelCandidates(segment, width)]);
2198
+ }
2199
+ function placeLabels(drawn, input, warnings) {
2200
+ const placedById = /* @__PURE__ */ new Map();
2201
+ const allSegments = drawn.flatMap((wire) => wire.segments);
2202
+ const solids = [...input.boxesById.values(), ...input.softObstacles];
2203
+ for (const wire of drawn) {
2204
+ const label = wire.plan.wire.label;
2205
+ if (!label) continue;
2206
+ const width = labelWidthOf(label);
2207
+ const candidates = labelCandidates(wire.segments, width);
2208
+ const isClear = (baseline) => {
2209
+ const bounds = labelBoundsAt(baseline, width);
2210
+ if (bounds.y < input.contentTop) return false;
2211
+ const padded = inflated(bounds, LABEL_CLEARANCE);
2212
+ if (allSegments.some((segment) => segmentHitsRect(segment, padded))) return false;
2213
+ if (solids.some((rect) => rectsOverlap(bounds, rect))) return false;
2214
+ return ![...placedById.values()].some((placed) => rectsOverlap(bounds, placed.bounds));
2215
+ };
2216
+ const clearSpot = candidates.find(isClear);
2217
+ const at = clearSpot ?? candidates[0] ?? centerOf(wire.plan.from);
2218
+ if (!clearSpot) warnings.push(`wire ${wire.plan.wire.id} label "${label}" has no clear spot`);
2219
+ placedById.set(wire.plan.wire.id, {
2220
+ at: {
2221
+ x: Math.round(at.x),
2222
+ y: Math.round(at.y)
2223
+ },
2224
+ bounds: labelBoundsAt(at, width)
2225
+ });
2226
+ }
2227
+ return placedById;
2228
+ }
2229
+ function isStrictlyBetween(value, first, second) {
2230
+ return value > Math.min(first, second) + .5 && value < Math.max(first, second) - .5;
2231
+ }
2232
+ function segmentsCross(first, second) {
2233
+ if (isHorizontal(first) === isHorizontal(second)) return false;
2234
+ const horizontal = isHorizontal(first) ? first : second;
2235
+ const vertical = horizontal === first ? second : first;
2236
+ return isStrictlyBetween(vertical.from.x, horizontal.from.x, horizontal.to.x) && isStrictlyBetween(horizontal.from.y, vertical.from.y, vertical.to.y);
2237
+ }
2238
+ function segmentsOverlap(first, second) {
2239
+ if (isHorizontal(first) !== isHorizontal(second)) return false;
2240
+ const isAlongX = isHorizontal(first);
2241
+ const lineOf = (segment) => isAlongX ? segment.from.y : segment.from.x;
2242
+ const startOf = (segment) => Math.min(isAlongX ? segment.from.x : segment.from.y, isAlongX ? segment.to.x : segment.to.y);
2243
+ const endOf = (segment) => Math.max(isAlongX ? segment.from.x : segment.from.y, isAlongX ? segment.to.x : segment.to.y);
2244
+ return lineOf(first) === lineOf(second) && Math.min(endOf(first), endOf(second)) - Math.max(startOf(first), startOf(second)) > 1;
2245
+ }
2246
+ function areSiblings(first, second) {
2247
+ if (first.plan.busKey !== null && first.plan.busKey === second.plan.busKey) return true;
2248
+ return first.plan.exitKey === second.plan.exitKey;
2249
+ }
2250
+ function wirePiecesOf(drawn) {
2251
+ const segments = drawn.flatMap((wire) => wire.segments);
2252
+ const rects = emptyFlatRects(segments.length);
2253
+ const wireIndexByPiece = new Int32Array(segments.length);
2254
+ let piece = 0;
2255
+ drawn.forEach((wire, wireIndex) => {
2256
+ for (const segment of wire.segments) {
2257
+ setFlatRect(rects, piece, segment.from.x, segment.from.y, segment.to.x, segment.to.y);
2258
+ wireIndexByPiece[piece] = wireIndex;
2259
+ piece += 1;
2260
+ }
2261
+ });
2262
+ return {
2263
+ rects,
2264
+ segments,
2265
+ wireIndexByPiece
2266
+ };
2267
+ }
2268
+ function findCrossings(drawn, pieces) {
2269
+ const isCrossingByPairKey = /* @__PURE__ */ new Map();
2270
+ forEachTouchingPairWithin(pieces.rects, (earlierPiece, laterPiece) => {
2271
+ const earlierWire = pieces.wireIndexByPiece[earlierPiece] ?? 0;
2272
+ const laterWire = pieces.wireIndexByPiece[laterPiece] ?? 0;
2273
+ if (earlierWire === laterWire) return;
2274
+ const pairKey = Math.min(earlierWire, laterWire) * drawn.length + Math.max(earlierWire, laterWire);
2275
+ if (isCrossingByPairKey.get(pairKey) === true) return;
2276
+ const first = drawn[earlierWire];
2277
+ const second = drawn[laterWire];
2278
+ const earlierSegment = pieces.segments[earlierPiece];
2279
+ const laterSegment = pieces.segments[laterPiece];
2280
+ if (!first || !second || !earlierSegment || !laterSegment || areSiblings(first, second)) return;
2281
+ if (segmentsCross(earlierSegment, laterSegment)) {
2282
+ isCrossingByPairKey.set(pairKey, true);
2283
+ return;
2284
+ }
2285
+ if (segmentsOverlap(earlierSegment, laterSegment)) isCrossingByPairKey.set(pairKey, false);
2286
+ });
2287
+ const pairKeys = [...isCrossingByPairKey.keys()];
2288
+ return pairsInOrder(pairKeys.map((key) => Math.floor(key / drawn.length)), pairKeys.map((key) => key % drawn.length), drawn.length, drawn.length).map(([firstIndex, secondIndex]) => {
2289
+ const verb = isCrossingByPairKey.get(firstIndex * drawn.length + secondIndex) ? "crosses" : "overlaps";
2290
+ return `wire ${drawn[firstIndex]?.plan.wire.id} ${verb} wire ${drawn[secondIndex]?.plan.wire.id}`;
2291
+ });
2292
+ }
2293
+ function solidsOf(input) {
2294
+ return [...input.boxesById.values(), ...input.panels];
2295
+ }
2296
+ function findBoxCrossings(drawn, pieces, input) {
2297
+ const solids = solidsOf(input);
2298
+ const insets = solids.map((solid) => inflated(solid, -2));
2299
+ const crossedPairKeys = /* @__PURE__ */ new Set();
2300
+ forEachTouchingPairAcross(pieces.rects, flatRectsOf(insets), (piece, solidIndex) => {
2301
+ const wireIndex = pieces.wireIndexByPiece[piece] ?? 0;
2302
+ const pairKey = wireIndex * solids.length + solidIndex;
2303
+ if (crossedPairKeys.has(pairKey)) return;
2304
+ const wire = drawn[wireIndex];
2305
+ const solid = solids[solidIndex];
2306
+ const inset = insets[solidIndex];
2307
+ const segment = pieces.segments[piece];
2308
+ if (!wire || !solid || !inset || !segment) return;
2309
+ if (solid.id === wire.plan.from.id || solid.id === wire.plan.to.id) return;
2310
+ if (segmentHitsRect(segment, inset)) crossedPairKeys.add(pairKey);
2311
+ });
2312
+ const pairKeys = [...crossedPairKeys];
2313
+ return pairsInOrder(pairKeys.map((key) => Math.floor(key / solids.length)), pairKeys.map((key) => key % solids.length), drawn.length, solids.length).map(([wireIndex, solidIndex]) => `wire ${drawn[wireIndex]?.plan.wire.id} runs through ${solids[solidIndex]?.kind} ${solids[solidIndex]?.id}`);
2314
+ }
2315
+ function crossingWarningsOf(drawn, input) {
2316
+ const pieces = wirePiecesOf(drawn);
2317
+ return [...findBoxCrossings(drawn, pieces, input), ...findCrossings(drawn, pieces)];
2318
+ }
2319
+ function totalCrossingCostOf(drawn, input) {
2320
+ const pieces = wirePiecesOf(drawn);
2321
+ return findBoxCrossings(drawn, pieces, input).length * BOX_CROSSING_COST + findCrossings(drawn, pieces).length;
2322
+ }
2323
+ function routeQualityWarnings(drawn) {
2324
+ return drawn.flatMap((wire) => {
2325
+ if (!wire.states) return [`wire ${wire.plan.wire.id} found no clear route, so it is drawn as a straight dog-leg`];
2326
+ const bends = bendCountOf(wire);
2327
+ return bends > MAX_BENDS ? [`wire ${wire.plan.wire.id} bends ${bends} times`] : [];
2328
+ });
2329
+ }
2330
+ function isPointOnSegment(point, segment) {
2331
+ if (isHorizontal(segment)) return point.y === segment.from.y && point.x >= Math.min(segment.from.x, segment.to.x) && point.x <= Math.max(segment.from.x, segment.to.x);
2332
+ return point.x === segment.from.x && point.y >= Math.min(segment.from.y, segment.to.y) && point.y <= Math.max(segment.from.y, segment.to.y);
2333
+ }
2334
+ function joinPointOf(wire, leader) {
2335
+ if (!leader || leader === wire) return null;
2336
+ const joined = wire.points.find((point) => leader.segments.some((segment) => isPointOnSegment(point, segment)));
2337
+ if (!joined || joined.x === wire.plan.end.x && joined.y === wire.plan.end.y) return null;
2338
+ return joined;
2339
+ }
2340
+ function swapNeighbors(order, index) {
2341
+ const left = order[index];
2342
+ const right = order[index + 1];
2343
+ if (left === void 0 || right === void 0) return;
2344
+ order[index] = right;
2345
+ order[index + 1] = left;
2346
+ }
2347
+ function routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, reuse) {
2348
+ assignPorts(requestsBySide, groupOrderBySide);
2349
+ alignLonePorts(plans, groupOrderBySide);
2350
+ return routeAll(plans, input, reuse);
2351
+ }
2352
+ function routeWithFewestCrossings(plans, input, requestsBySide, groupOrderBySide, reuse) {
2353
+ const firstRouted = routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, reuse);
2354
+ if (plans.length > MAX_WIRES_FOR_PORT_SEARCH) return firstRouted;
2355
+ let bestCrossingCost = totalCrossingCostOf(firstRouted, input);
2356
+ for (const groupOrder of groupOrderBySide.values()) for (let index = 0; bestCrossingCost > 0 && index + 1 < groupOrder.length; index += 1) {
2357
+ swapNeighbors(groupOrder, index);
2358
+ const trialCrossingCost = totalCrossingCostOf(routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, reuse), input);
2359
+ if (trialCrossingCost < bestCrossingCost) {
2360
+ bestCrossingCost = trialCrossingCost;
2361
+ continue;
2362
+ }
2363
+ swapNeighbors(groupOrder, index);
2364
+ }
2365
+ return routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, reuse);
2366
+ }
2367
+ function obstacleRectsByKey(input) {
2368
+ const rectByKey = /* @__PURE__ */ new Map();
2369
+ const keyOfRect = (rect) => `${rect.x},${rect.y},${rect.width},${rect.height}`;
2370
+ for (const box of input.boxesById.values()) rectByKey.set(`box ${box.id}`, box);
2371
+ for (const panel of input.panels) rectByKey.set(`panel ${panel.id}`, panel);
2372
+ for (const soft of input.softObstacles) rectByKey.set(`soft ${keyOfRect(soft)}`, soft);
2373
+ for (const frame of input.loopFrames) rectByKey.set(`loop ${keyOfRect(frame)}`, frame);
2374
+ return rectByKey;
2375
+ }
2376
+ function changedRectsOf(previous, current) {
2377
+ const isSameRect = (first, second) => first !== void 0 && first.x === second.x && first.y === second.y && first.width === second.width && first.height === second.height;
2378
+ const removedOrMoved = [...previous].flatMap(([key, rect]) => isSameRect(current.get(key), rect) ? [] : [rect]);
2379
+ const addedOrMoved = [...current].flatMap(([key, rect]) => isSameRect(previous.get(key), rect) ? [] : [rect]);
2380
+ return [...removedOrMoved, ...addedOrMoved];
2381
+ }
2382
+ function wireKeyOf(wire) {
2383
+ return JSON.stringify(wire);
2384
+ }
2385
+ function routeReuseOf(input, rectByKey, previous) {
2386
+ if (!previous || previous.contentTop !== input.contentTop) return null;
2387
+ const changedRects = changedRectsOf(previous.rectByKey, rectByKey).map((rect) => inflated(rect, 14));
2388
+ const candidates = input.wires.flatMap((wire) => {
2389
+ const remembered = previous.routeById.get(wire.id);
2390
+ return remembered && remembered.wireKey === wireKeyOf(wire) ? [{
2391
+ wire,
2392
+ remembered
2393
+ }] : [];
2394
+ });
2395
+ const pieceRects = candidates.flatMap(({ wire, remembered }) => segmentsOf(remembered.points).map((segment) => ({
2396
+ wireId: wire.id,
2397
+ rect: pointBoundsOf(segment.from, segment.to)
2398
+ })));
2399
+ const touchedWireIds = /* @__PURE__ */ new Set();
2400
+ forEachTouchingPairAcross(flatRectsOf(pieceRects.map((piece) => piece.rect)), flatRectsOf(changedRects), (pieceIndex) => {
2401
+ const piece = pieceRects[pieceIndex];
2402
+ if (piece) touchedWireIds.add(piece.wireId);
2403
+ });
2404
+ const cleanIds = new Set(candidates.map(({ wire }) => wire.id).filter((wireId) => !touchedWireIds.has(wireId)));
2405
+ return {
2406
+ routeById: previous.routeById,
2407
+ cleanIds,
2408
+ isLocal: input.wires.length - cleanIds.size <= MAX_WIRES_FOR_LOCAL_ROUTING
2409
+ };
2410
+ }
2411
+ function pointBoundsOf(first, second) {
2412
+ return {
2413
+ x: Math.min(first.x, second.x),
2414
+ y: Math.min(first.y, second.y),
2415
+ width: Math.abs(first.x - second.x),
2416
+ height: Math.abs(first.y - second.y)
2417
+ };
2418
+ }
2419
+ function routeMemoryOf(input, rectByKey, drawn) {
2420
+ const routeById = new Map(drawn.map((wire) => [wire.plan.wire.id, {
2421
+ wireKey: wireKeyOf(wire.plan.wire),
2422
+ exitSide: wire.plan.exitSide,
2423
+ entrySide: wire.plan.entrySide,
2424
+ start: wire.plan.start,
2425
+ end: wire.plan.end,
2426
+ points: wire.routedPoints,
2427
+ isRouted: wire.states !== null
2428
+ }]));
2429
+ return {
2430
+ contentTop: input.contentTop,
2431
+ rectByKey,
2432
+ routeById
2433
+ };
2434
+ }
2435
+ function routeWires(input, previous) {
2436
+ const rectByKey = obstacleRectsByKey(input);
2437
+ const reuse = routeReuseOf(input, rectByKey, previous);
2438
+ const plans = planWires(input, reuse);
2439
+ const requestsBySide = portRequestsBySide(plans);
2440
+ const groupOrderBySide = defaultPortOrders(requestsBySide);
2441
+ const drawn = routeWithFewestCrossings(plans, input, requestsBySide, groupOrderBySide, reuse);
2442
+ const labelWarnings = [];
2443
+ const labelById = placeLabels(drawn, input, labelWarnings);
2444
+ const leaderByBusKey = /* @__PURE__ */ new Map();
2445
+ for (const wire of [...drawn].sort((left, right) => left.plan.wire.id.localeCompare(right.plan.wire.id))) if (wire.plan.busKey && !leaderByBusKey.has(wire.plan.busKey)) leaderByBusKey.set(wire.plan.busKey, wire);
2446
+ const wires = drawn.map((wire) => {
2447
+ const { plan, points } = wire;
2448
+ const leader = plan.busKey ? leaderByBusKey.get(plan.busKey) : void 0;
2449
+ return {
2450
+ kind: "wire",
2451
+ id: plan.wire.id,
2452
+ path: pathOf(points),
2453
+ start: plan.start,
2454
+ end: plan.end,
2455
+ label: plan.wire.label,
2456
+ labelAt: labelById.get(plan.wire.id)?.at ?? centerOf(plan.from),
2457
+ isDashed: plan.wire.dashed || plan.wire.back,
2458
+ isBack: plan.wire.back,
2459
+ strokeHex: plan.strokeHex,
2460
+ tone: plan.wire.tone,
2461
+ hasArrowhead: leader === void 0 || leader === wire,
2462
+ joinAt: joinPointOf(wire, leader)
2463
+ };
2464
+ });
2465
+ const labelRects = [...labelById.values()].map((placed) => placed.bounds);
2466
+ const pointRects = drawn.flatMap((wire) => wire.points).map((point) => ({
2467
+ x: point.x,
2468
+ y: point.y,
2469
+ width: 0,
2470
+ height: 0
2471
+ }));
2472
+ return {
2473
+ wires,
2474
+ segments: drawn.flatMap((wire) => wire.segments),
2475
+ collectWarnings: () => [
2476
+ ...routeQualityWarnings(drawn),
2477
+ ...crossingWarningsOf(drawn, input),
2478
+ ...crowdedSideWarnings(requestsBySide, groupOrderBySide),
2479
+ ...labelWarnings
2480
+ ],
2481
+ extent: unionOf([...pointRects, ...labelRects]),
2482
+ memory: routeMemoryOf(input, rectByKey, drawn)
2483
+ };
2484
+ }
2485
+ //#endregion
2486
+ //#region shared/whiteboard-layout-core.ts
2487
+ var MARGIN = 40;
2488
+ var COLUMN_HEADER_HEIGHT = 44;
2489
+ var COLUMN_WIDTH = 220;
2490
+ var COLUMN_GAP = 90;
2491
+ var BOX_GAP = 30;
2492
+ var BOX_PADDING = 12;
2493
+ var TITLE_LINE_HEIGHT$1 = 20;
2494
+ var BODY_LINE_HEIGHT$1 = 18;
2495
+ var OUTPUT_ROW_HEIGHT = 28;
2496
+ var MAX_KEY_INDENT_CHARS = 12;
2497
+ var ITEM_INDENT_CHARS = 2;
2498
+ var TITLE_CHARS_PER_LINE = 20;
2499
+ var BODY_CHARS_PER_LINE = 26;
2500
+ var FRAME_PADDING = 18;
2501
+ var FRAME_TITLE_HEIGHT = 26;
2502
+ var NOTE_WIDTH = 170;
2503
+ var NOTE_CHARS_PER_LINE = 21;
2504
+ var NOTE_LINE_HEIGHT$1 = 17;
2505
+ var NOTE_GAP = 10;
2506
+ var LEGEND_ROW_HEIGHT = 22;
2507
+ var COLUMN_TITLE_CHARS_PER_LINE = 24;
2508
+ var COLUMN_TITLE_LINE_HEIGHT$1 = 16;
2509
+ var COLUMN_TITLE_BASELINE = 16;
2510
+ var COLUMN_RULE_OFFSET = 26;
2511
+ var NOTE_OVERLAP = 24;
2512
+ var NOTE_RISE = 8;
2513
+ var CHANNEL_PAD = 10;
2514
+ var TRACK_SPACING = 14;
2515
+ var MAX_ROOM_ATTEMPTS = 4;
2516
+ var PLAN_BAND_GAP = 40;
2517
+ var BAND_HEADER_HEIGHT = 26;
2518
+ var BAND_GAP = 24;
2519
+ var MEDIA_GAP = 8;
2520
+ var MEDIA_MAX_HEIGHT = 320;
2521
+ var LANE_HEX_BY_COLOR = Object.freeze({
2522
+ blue: "#60a5fa",
2523
+ green: "#4ade80",
2524
+ orange: "#fb923c",
2525
+ pink: "#f472b6",
2526
+ cyan: "#22d3ee",
2527
+ yellow: "#facc15"
2528
+ });
2529
+ function wrapText(text, charsPerLine) {
2530
+ const words = text.split(/\s+/).filter(Boolean);
2531
+ const lines = [];
2532
+ let current = "";
2533
+ for (const word of words) {
2534
+ const pieces = word.match(new RegExp(`.{1,${charsPerLine}}`, "g")) ?? [word];
2535
+ for (const piece of pieces) {
2536
+ const candidate = current ? `${current} ${piece}` : piece;
2537
+ if (candidate.length <= charsPerLine) {
2538
+ current = candidate;
2539
+ continue;
2540
+ }
2541
+ lines.push(current);
2542
+ current = piece;
2543
+ }
2544
+ }
2545
+ if (current) lines.push(current);
2546
+ return lines.length > 0 ? lines : [""];
2547
+ }
2548
+ function rowsOfLine(line, numberInRun, bodyCharsPerLine) {
2549
+ const mutedIndentChars = line.muted ? 2 : 0;
2550
+ const marker = line.style === "numbered" ? `${numberInRun}.` : line.style === "kv" ? line.key : null;
2551
+ const rowOf = (text, index, indentChars, rowMarker) => ({
2552
+ text,
2553
+ muted: line.muted,
2554
+ style: line.style,
2555
+ marker: index === 0 ? rowMarker : null,
2556
+ indentChars,
2557
+ isFirstRow: index === 0
2558
+ });
2559
+ if (marker && marker.length + 1 > MAX_KEY_INDENT_CHARS) {
2560
+ const valueRows = wrapText(line.text, bodyCharsPerLine - mutedIndentChars - ITEM_INDENT_CHARS).map((text) => rowOf(text, 1, ITEM_INDENT_CHARS, null));
2561
+ return [rowOf("", 0, 0, marker), ...valueRows];
2562
+ }
2563
+ const indentChars = line.style === "item" ? ITEM_INDENT_CHARS : marker ? marker.length + 1 : 0;
2564
+ return wrapText(line.text, bodyCharsPerLine - mutedIndentChars - indentChars - (line.style === "code" ? 1 : 0)).map((text, index) => rowOf(text, index, indentChars, marker));
2565
+ }
2566
+ function laidOutLines(lines, bodyCharsPerLine = BODY_CHARS_PER_LINE) {
2567
+ let numberInRun = 0;
2568
+ return lines.flatMap((line) => {
2569
+ numberInRun = line.style === "numbered" ? numberInRun + 1 : 0;
2570
+ return rowsOfLine(line, numberInRun, bodyCharsPerLine);
2571
+ });
2572
+ }
2573
+ function laneOf(board, box) {
2574
+ const lane = board.lanes.find((candidate) => candidate.id === box.lane);
2575
+ if (!lane) return null;
2576
+ return {
2577
+ label: lane.label || lane.id,
2578
+ hex: LANE_HEX_BY_COLOR[lane.color]
2579
+ };
2580
+ }
2581
+ function isGridBox(box) {
2582
+ return box.column !== null && box.at === null && box.near === null;
2583
+ }
2584
+ function boxWidthOf(box) {
2585
+ return box.width ?? COLUMN_WIDTH;
2586
+ }
2587
+ function charsPerLineAt(defaultCharsPerLine, boxWidth) {
2588
+ return Math.floor(defaultCharsPerLine * (boxWidth - 24) / 196);
2589
+ }
2590
+ function mediaSizeOf(box) {
2591
+ if (!box.media) return null;
2592
+ const boxWidth = boxWidthOf(box);
2593
+ const width = boxWidth - 24;
2594
+ const maxHeight = Math.round(MEDIA_MAX_HEIGHT * boxWidth / COLUMN_WIDTH);
2595
+ return {
2596
+ width,
2597
+ height: Math.min(maxHeight, Math.max(1, Math.round(width * box.media.height / box.media.width)))
2598
+ };
2599
+ }
2600
+ function laidOutMedia(box, position, mediaTop, mediaSize) {
2601
+ if (!box.media || !mediaSize) return null;
2602
+ return {
2603
+ kind: box.media.kind,
2604
+ asset: box.media.asset,
2605
+ mime: box.media.mime,
2606
+ hasPreview: box.media.hasPreview,
2607
+ alt: box.media.alt,
2608
+ x: position.x + BOX_PADDING,
2609
+ y: position.y + mediaTop,
2610
+ width: mediaSize.width,
2611
+ height: mediaSize.height
2612
+ };
2613
+ }
2614
+ function boxShape(board, box) {
2615
+ const boxWidth = boxWidthOf(box);
2616
+ const titleCharsPerLine = charsPerLineAt(TITLE_CHARS_PER_LINE, boxWidth);
2617
+ const titleLines = wrapText(box.title, titleCharsPerLine);
2618
+ const wasLines = box.change === "relabeled" && box.was ? wrapText(box.was, titleCharsPerLine) : [];
2619
+ const bodyLines = laidOutLines(box.lines, charsPerLineAt(BODY_CHARS_PER_LINE, boxWidth));
2620
+ const lane = laneOf(board, box);
2621
+ const showsLanePill = lane !== null && !isGridBox(box);
2622
+ const textHeight = BOX_PADDING + (wasLines.length + titleLines.length) * TITLE_LINE_HEIGHT$1 + bodyLines.length * BODY_LINE_HEIGHT$1;
2623
+ const mediaSize = mediaSizeOf(box);
2624
+ const mediaRoom = mediaSize ? mediaSize.height + MEDIA_GAP : 0;
2625
+ const headerHeight = textHeight + BOX_PADDING + mediaRoom + (showsLanePill ? 26 : 0);
2626
+ const outputs = box.shape === "decision" ? box.outputs : [];
2627
+ return {
2628
+ titleLines,
2629
+ wasLines,
2630
+ bodyLines,
2631
+ lane,
2632
+ showsLanePill,
2633
+ headerHeight,
2634
+ outputs,
2635
+ mediaTop: textHeight + MEDIA_GAP,
2636
+ mediaSize,
2637
+ height: headerHeight + outputs.length * OUTPUT_ROW_HEIGHT
2638
+ };
2639
+ }
2640
+ function addByKind(elementsByKind, element) {
2641
+ switch (element.kind) {
2642
+ case "box":
2643
+ elementsByKind.box.push(element);
2644
+ return;
2645
+ case "frame":
2646
+ elementsByKind.frame.push(element);
2647
+ return;
2648
+ case "wire":
2649
+ elementsByKind.wire.push(element);
2650
+ return;
2651
+ case "note":
2652
+ elementsByKind.note.push(element);
2653
+ return;
2654
+ case "unit":
2655
+ elementsByKind.unit.push(element);
2656
+ return;
2657
+ case "panel":
2658
+ elementsByKind.panel.push(element);
2659
+ return;
2660
+ }
2661
+ }
2662
+ function indexedBoardOf(board) {
2663
+ const elementsByKind = {
2664
+ box: [],
2665
+ frame: [],
2666
+ wire: [],
2667
+ note: [],
2668
+ unit: [],
2669
+ panel: []
2670
+ };
2671
+ for (const element of Object.values(board.elements)) addByKind(elementsByKind, element);
2672
+ return {
2673
+ ...board,
2674
+ elementsByKind
2675
+ };
2676
+ }
2677
+ function elementsOfKind(board, kind) {
2678
+ return board.elementsByKind[kind];
2679
+ }
2680
+ function noteShape(note) {
2681
+ const lines = wrapText(note.text, NOTE_CHARS_PER_LINE);
2682
+ return {
2683
+ lines,
2684
+ height: 24 + (lines.length + 1) * NOTE_LINE_HEIGHT$1
2685
+ };
2686
+ }
2687
+ function noteStackHeightByBoxId(board) {
2688
+ const stackHeightByBoxId = /* @__PURE__ */ new Map();
2689
+ for (const note of elementsOfKind(board, "note")) {
2690
+ const stackedSoFar = stackHeightByBoxId.get(note.on);
2691
+ const noteHeight = noteShape(note).height;
2692
+ stackHeightByBoxId.set(note.on, stackedSoFar === void 0 ? noteHeight : stackedSoFar + NOTE_GAP + noteHeight);
2693
+ }
2694
+ return stackHeightByBoxId;
2695
+ }
2696
+ function columnTitleLines(board) {
2697
+ return board.columns.map((column) => column.title ? wrapText(column.title, COLUMN_TITLE_CHARS_PER_LINE) : []);
2698
+ }
2699
+ function headerExtraHeight(titleLinesByColumn) {
2700
+ return (Math.max(1, ...titleLinesByColumn.map((lines) => lines.length)) - 1) * COLUMN_TITLE_LINE_HEIGHT$1;
2701
+ }
2702
+ function gapReservesOf(board, stackHeightByBoxId) {
2703
+ const flowBoxes = elementsOfKind(board, "box").filter(isGridBox);
2704
+ const notedColumnIds = new Set(flowBoxes.filter((box) => stackHeightByBoxId.has(box.id)).map((box) => box.column));
2705
+ const framedBoxIds = new Set(elementsOfKind(board, "frame").flatMap((frame) => frame.contains));
2706
+ const framedColumnIds = new Set(flowBoxes.filter((box) => framedBoxIds.has(box.id)).map((box) => box.column));
2707
+ const sideReserve = (columnId) => CHANNEL_PAD + (columnId !== void 0 && framedColumnIds.has(columnId) ? FRAME_PADDING : 0);
2708
+ return board.columns.map((column, index) => {
2709
+ const isNoted = notedColumnIds.has(column.id);
2710
+ return {
2711
+ left: isNoted ? 156 : sideReserve(column.id),
2712
+ right: sideReserve(board.columns[index + 1]?.id),
2713
+ minimumWidth: isNoted ? Math.max(COLUMN_GAP, 186) : COLUMN_GAP
2714
+ };
2715
+ });
2716
+ }
2717
+ function gapWidthsOf(reserves, tracksByGap, labelWidthByGap) {
2718
+ return reserves.map((reserve, index) => {
2719
+ const tracks = tracksByGap[index] ?? 0;
2720
+ const labelWidth = labelWidthByGap[index] ?? 0;
2721
+ const trackNeed = tracks > 0 ? reserve.left + reserve.right + (tracks + 1) * TRACK_SPACING : 0;
2722
+ const labelNeed = labelWidth > 0 ? reserve.left + reserve.right + labelWidth + 20 : 0;
2723
+ return Math.max(reserve.minimumWidth, trackNeed, labelNeed);
2724
+ });
2725
+ }
2726
+ function columnWidthsOf(board) {
2727
+ const columnIndexById = new Map(board.columns.map((column, index) => [column.id, index]));
2728
+ const columnWidths = board.columns.map(() => COLUMN_WIDTH);
2729
+ for (const box of elementsOfKind(board, "box").filter(isGridBox)) {
2730
+ const columnIndex = columnIndexById.get(box.column) ?? 0;
2731
+ columnWidths[columnIndex] = Math.max(columnWidths[columnIndex] ?? COLUMN_WIDTH, boxWidthOf(box));
2732
+ }
2733
+ return columnWidths;
2734
+ }
2735
+ function columnLeftEdgesOf(columnWidths, gapWidths) {
2736
+ const columnLeftEdges = [];
2737
+ let nextX = MARGIN;
2738
+ for (const [index, columnWidth] of columnWidths.entries()) {
2739
+ columnLeftEdges.push(nextX);
2740
+ nextX += columnWidth + (gapWidths[index] ?? COLUMN_GAP);
2741
+ }
2742
+ return columnLeftEdges;
2743
+ }
2744
+ function columnsRightOf(columnLeftEdges, columnWidths) {
2745
+ return (columnLeftEdges.at(-1) ?? MARGIN) + (columnWidths.at(-1) ?? COLUMN_WIDTH);
2746
+ }
2747
+ function frameIdByBoxId(board) {
2748
+ const frameIds = /* @__PURE__ */ new Map();
2749
+ for (const frame of elementsOfKind(board, "frame")) for (const boxId of frame.contains) if (!frameIds.has(boxId)) frameIds.set(boxId, frame.id);
2750
+ return frameIds;
2751
+ }
2752
+ function frameClearance(previousFrameId, nextFrameId) {
2753
+ if (previousFrameId === nextFrameId) return 0;
2754
+ return (previousFrameId ? FRAME_PADDING : 0) + (nextFrameId ? 44 : 0);
2755
+ }
2756
+ function bandIdOf(board, box) {
2757
+ return board.lanes.some((lane) => lane.id === box.lane) ? box.lane ?? "" : "";
2758
+ }
2759
+ function bandIdsOf(board, gridBoxes) {
2760
+ const usedBandIds = new Set(gridBoxes.map((box) => bandIdOf(board, box)));
2761
+ return ["", ...board.lanes.map((lane) => lane.id)].filter((bandId) => usedBandIds.has(bandId));
2762
+ }
2763
+ function laidOutBox(board, box, position) {
2764
+ const shape = boxShape(board, box);
2765
+ const width = boxWidthOf(box);
2766
+ return {
2767
+ kind: "box",
2768
+ id: box.id,
2769
+ x: position.x,
2770
+ y: position.y,
2771
+ width,
2772
+ height: shape.height,
2773
+ titleLines: shape.titleLines,
2774
+ bodyLines: shape.bodyLines,
2775
+ lane: shape.lane,
2776
+ showsLanePill: shape.showsLanePill,
2777
+ change: box.change,
2778
+ wasLines: shape.wasLines,
2779
+ shape: box.shape,
2780
+ headerHeight: shape.headerHeight,
2781
+ media: laidOutMedia(box, position, shape.mediaTop, shape.mediaSize),
2782
+ outputs: shape.outputs.map((output, index) => ({
2783
+ id: output.id,
2784
+ label: output.label,
2785
+ port: {
2786
+ x: position.x + width,
2787
+ y: position.y + shape.headerHeight + index * OUTPUT_ROW_HEIGHT + OUTPUT_ROW_HEIGHT / 2
2788
+ }
2789
+ }))
2790
+ };
2791
+ }
2792
+ function placeGridBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId, boxesById) {
2793
+ const frameIds = frameIdByBoxId(board);
2794
+ const gridBoxes = elementsOfKind(board, "box").filter(isGridBox).map((box, index) => ({
2795
+ box,
2796
+ index
2797
+ })).sort((left, right) => left.box.order - right.box.order || left.index - right.index).map(({ box }) => box);
2798
+ const bandIds = bandIdsOf(board, gridBoxes);
2799
+ const hasLabeledBands = bandIds.some((bandId) => bandId !== "");
2800
+ const columnsRight = columnsRightOf(columnLeftEdges, columnWidths);
2801
+ const bands = [];
2802
+ let bandTop = boxesTop;
2803
+ for (const bandId of bandIds) {
2804
+ const lane = board.lanes.find((candidate) => candidate.id === bandId);
2805
+ const stackTop = bandTop + (hasLabeledBands ? BAND_HEADER_HEIGHT : 0);
2806
+ const nextYByColumnId = /* @__PURE__ */ new Map();
2807
+ const lastFrameIdByColumnId = /* @__PURE__ */ new Map();
2808
+ for (const box of gridBoxes) {
2809
+ if (bandIdOf(board, box) !== bandId) continue;
2810
+ const columnIndex = Math.max(0, board.columns.findIndex((column) => column.id === box.column));
2811
+ const frameId = frameIds.get(box.id) ?? null;
2812
+ const y = (nextYByColumnId.get(box.column) ?? stackTop) + frameClearance(lastFrameIdByColumnId.get(box.column) ?? null, frameId);
2813
+ const placed = laidOutBox(board, box, {
2814
+ x: columnLeftEdges[columnIndex] ?? MARGIN,
2815
+ y
2816
+ });
2817
+ const noteStackBottom = (stackHeightByBoxId.get(box.id) ?? 0) - NOTE_RISE;
2818
+ nextYByColumnId.set(box.column, y + Math.max(placed.height, noteStackBottom) + BOX_GAP);
2819
+ lastFrameIdByColumnId.set(box.column, frameId);
2820
+ boxesById.set(box.id, placed);
2821
+ }
2822
+ const stackBottom = Math.max(stackTop, ...nextYByColumnId.values()) - BOX_GAP;
2823
+ if (hasLabeledBands) bands.push({
2824
+ id: bandId,
2825
+ label: lane ? lane.label || lane.id : "",
2826
+ hex: lane ? LANE_HEX_BY_COLOR[lane.color] : "",
2827
+ x: MARGIN,
2828
+ y: bandTop,
2829
+ width: columnsRight - MARGIN,
2830
+ height: stackBottom - bandTop
2831
+ });
2832
+ bandTop = stackBottom + BAND_GAP + BOX_GAP;
2833
+ }
2834
+ return bands;
2835
+ }
2836
+ function nearPosition(target, near, size) {
2837
+ const centeredY = target.y + target.height / 2 - size.height / 2;
2838
+ const centeredX = target.x + target.width / 2 - size.width / 2;
2839
+ switch (near.side) {
2840
+ case "right": return {
2841
+ x: target.x + target.width + near.gap,
2842
+ y: centeredY
2843
+ };
2844
+ case "left": return {
2845
+ x: target.x - size.width - near.gap,
2846
+ y: centeredY
2847
+ };
2848
+ case "bottom": return {
2849
+ x: centeredX,
2850
+ y: target.y + target.height + near.gap
2851
+ };
2852
+ case "top": return {
2853
+ x: centeredX,
2854
+ y: target.y - size.height - near.gap
2855
+ };
2856
+ }
2857
+ }
2858
+ function freeOrigin(boxesById, boxesTop) {
2859
+ const rightmostEdge = [...boxesById.values()].reduce((rightmost, box) => Math.max(rightmost, box.x + box.width), -Infinity);
2860
+ return {
2861
+ x: boxesById.size > 0 ? rightmostEdge + COLUMN_GAP : MARGIN,
2862
+ y: boxesTop
2863
+ };
2864
+ }
2865
+ function placeNearBoxes(board, boxesTop, boxesById, warnings) {
2866
+ const nearBoxes = elementsOfKind(board, "box").filter((box) => box.at === null && box.near !== null);
2867
+ const pendingIds = new Set(nearBoxes.map((box) => box.id));
2868
+ const place = (box, chainIds) => {
2869
+ const settled = boxesById.get(box.id);
2870
+ if (settled || !box.near) return settled;
2871
+ const target = board.elements[box.near.of];
2872
+ const targetBox = target?.kind === "box" && !chainIds.has(target.id) && (boxesById.has(target.id) || pendingIds.has(target.id)) ? place(target, /* @__PURE__ */ new Set([...chainIds, box.id])) : void 0;
2873
+ if (!targetBox) warnings.push(`box ${box.id} sits near ${box.near.of}, which is not placed on the board`);
2874
+ const size = {
2875
+ width: boxWidthOf(box),
2876
+ height: boxShape(board, box).height
2877
+ };
2878
+ const position = targetBox ? nearPosition(targetBox, box.near, size) : freeOrigin(boxesById, boxesTop);
2879
+ const placed = laidOutBox(board, box, {
2880
+ x: Math.round(position.x),
2881
+ y: Math.round(position.y)
2882
+ });
2883
+ boxesById.set(box.id, placed);
2884
+ return placed;
2885
+ };
2886
+ for (const box of nearBoxes) place(box, /* @__PURE__ */ new Set());
2887
+ }
2888
+ function layoutPanels(board, besidePanels, columnLeftEdges, columnWidths, boxesTop) {
2889
+ const columnsRight = columnsRightOf(columnLeftEdges, columnWidths);
2890
+ const x = Math.max(columnsRight, ...besidePanels.map((rect) => rect.x + rect.width)) + COLUMN_GAP;
2891
+ const panels = [...elementsOfKind(board, "panel")].sort((left, right) => left.order - right.order || left.id.localeCompare(right.id));
2892
+ let nextY = boxesTop;
2893
+ return panels.map((panel) => {
2894
+ const titleLines = wrapText(panel.title, TITLE_CHARS_PER_LINE);
2895
+ const bodyLines = laidOutLines(panel.lines);
2896
+ const height = 24 + titleLines.length * TITLE_LINE_HEIGHT$1 + bodyLines.length * BODY_LINE_HEIGHT$1;
2897
+ const laidOut = {
2898
+ kind: "panel",
2899
+ id: panel.id,
2900
+ x: Math.round(x),
2901
+ y: nextY,
2902
+ width: COLUMN_WIDTH,
2903
+ height,
2904
+ titleLines,
2905
+ bodyLines
2906
+ };
2907
+ nextY += height + BOX_GAP;
2908
+ return laidOut;
2909
+ });
2910
+ }
2911
+ function layoutBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId) {
2912
+ const boxesById = /* @__PURE__ */ new Map();
2913
+ const warnings = [];
2914
+ const bands = placeGridBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId, boxesById);
2915
+ for (const box of elementsOfKind(board, "box")) if (box.at) boxesById.set(box.id, laidOutBox(board, box, box.at));
2916
+ placeNearBoxes(board, boxesTop, boxesById, warnings);
2917
+ for (const box of elementsOfKind(board, "box")) if (!boxesById.has(box.id)) boxesById.set(box.id, laidOutBox(board, box, freeOrigin(boxesById, boxesTop)));
2918
+ return {
2919
+ boxesById,
2920
+ bands,
2921
+ warnings
2922
+ };
2923
+ }
2924
+ function layoutFrames(board, boxesById) {
2925
+ return elementsOfKind(board, "frame").flatMap((frame) => {
2926
+ const around = unionOf(frame.contains.flatMap((id) => boxesById.get(id) ?? []));
2927
+ if (!around) return [];
2928
+ return [{
2929
+ kind: "frame",
2930
+ id: frame.id,
2931
+ title: frame.title,
2932
+ isLoop: frame.loop,
2933
+ x: around.x - FRAME_PADDING,
2934
+ y: around.y - FRAME_PADDING - FRAME_TITLE_HEIGHT,
2935
+ width: around.width + 36,
2936
+ height: around.height + 36 + FRAME_TITLE_HEIGHT
2937
+ }];
2938
+ });
2939
+ }
2940
+ function noteByline(note) {
2941
+ if (note.resolvedBy) return `resolved by ${note.resolvedBy}`;
2942
+ return note.author ? `from ${note.author}` : "";
2943
+ }
2944
+ function layoutNotes(board, boxesById) {
2945
+ const nextYByBoxId = /* @__PURE__ */ new Map();
2946
+ return elementsOfKind(board, "note").flatMap((note) => {
2947
+ const target = boxesById.get(note.on);
2948
+ if (!target) return [];
2949
+ const { lines, height } = noteShape(note);
2950
+ const y = nextYByBoxId.get(note.on) ?? target.y - NOTE_RISE;
2951
+ nextYByBoxId.set(note.on, y + height + NOTE_GAP);
2952
+ return [{
2953
+ kind: "note",
2954
+ id: note.id,
2955
+ x: target.x + target.width - NOTE_OVERLAP,
2956
+ y,
2957
+ width: NOTE_WIDTH,
2958
+ height,
2959
+ lines,
2960
+ byline: noteByline(note),
2961
+ isResolved: note.resolvedBy !== null
2962
+ }];
2963
+ });
2964
+ }
2965
+ function boundsOf(elements, wireExtent, columnsRight, boxesTop) {
2966
+ const around = unionOf([
2967
+ ...elements.flatMap((element) => element.kind === "wire" ? [] : [element]),
2968
+ ...wireExtent ? [wireExtent] : [],
2969
+ {
2970
+ x: 0,
2971
+ y: 0,
2972
+ width: columnsRight,
2973
+ height: boxesTop
2974
+ }
2975
+ ]);
2976
+ if (!around) return {
2977
+ x: 0,
2978
+ y: 0,
2979
+ width: columnsRight + MARGIN,
2980
+ height: 80
2981
+ };
2982
+ return {
2983
+ x: Math.min(0, around.x - MARGIN),
2984
+ y: Math.min(0, around.y - MARGIN),
2985
+ width: around.width + 80,
2986
+ height: around.height + 80
2987
+ };
2988
+ }
2989
+ function gapSpansOf(columnLeftEdges, columnWidths) {
2990
+ return columnLeftEdges.slice(0, -1).map((leftEdge, index) => {
2991
+ const left = leftEdge + (columnWidths[index] ?? COLUMN_WIDTH);
2992
+ return {
2993
+ left,
2994
+ right: columnLeftEdges[index + 1] ?? left
2995
+ };
2996
+ });
2997
+ }
2998
+ function tracksByGapOf(routing, columnLeftEdges, columnWidths) {
2999
+ const verticalXs = routing.segments.filter((segment) => segment.from.x === segment.to.x).map((segment) => segment.from.x);
3000
+ return gapSpansOf(columnLeftEdges, columnWidths).map((span) => new Set(verticalXs.filter((x) => x > span.left && x < span.right)).size);
3001
+ }
3002
+ function labelWidthByGapOf(routing, columnLeftEdges, columnWidths) {
3003
+ return gapSpansOf(columnLeftEdges, columnWidths).map((span) => routing.wires.reduce((widest, wire) => wire.label && wire.labelAt.x > span.left && wire.labelAt.x < span.right ? Math.max(widest, labelWidthOf(wire.label)) : widest, 0));
3004
+ }
3005
+ function overlapWarnings(boxesById, panels, frames, board) {
3006
+ const boxes = [...boxesById.values()];
3007
+ const solids = [...boxes, ...panels];
3008
+ const boxOverlaps = touchingPairsWithin(solids).flatMap(([firstIndex, secondIndex]) => {
3009
+ const first = solids[firstIndex];
3010
+ const second = solids[secondIndex];
3011
+ return first && second && rectsOverlap(first, second) ? [`${first.kind} ${first.id} overlaps ${second.kind} ${second.id}`] : [];
3012
+ });
3013
+ const containedIdsByFrameId = new Map(elementsOfKind(board, "frame").map((frame) => [frame.id, new Set(frame.contains)]));
3014
+ const coveredTitles = frames.flatMap((frame) => boxes.flatMap((box) => {
3015
+ const titleStrip = {
3016
+ x: frame.x,
3017
+ y: frame.y,
3018
+ width: frame.width,
3019
+ height: FRAME_TITLE_HEIGHT
3020
+ };
3021
+ return !containedIdsByFrameId.get(frame.id)?.has(box.id) && rectsOverlap(box, titleStrip) ? [`box ${box.id} covers the title of frame ${frame.id}`] : [];
3022
+ }));
3023
+ return [...boxOverlaps, ...coveredTitles];
3024
+ }
3025
+ function placeAndRoute(board, placement, previousRoute) {
3026
+ const columnWidths = columnWidthsOf(board);
3027
+ const columnLeftEdges = columnLeftEdgesOf(columnWidths, placement.gapWidths);
3028
+ const { boxesById, bands, warnings: nearWarnings } = layoutBoxes(board, columnLeftEdges, columnWidths, placement.boxesTop, placement.stackHeightByBoxId);
3029
+ const frames = layoutFrames(board, boxesById);
3030
+ const notes = layoutNotes(board, boxesById);
3031
+ const panels = layoutPanels(board, [...boxesById.values(), ...notes], columnLeftEdges, columnWidths, placement.boxesTop);
3032
+ const routing = routeWires({
3033
+ wires: elementsOfKind(board, "wire"),
3034
+ boxesById,
3035
+ panels,
3036
+ softObstacles: [...notes, ...frames.map((frame) => ({
3037
+ x: frame.x,
3038
+ y: frame.y,
3039
+ width: frame.width,
3040
+ height: FRAME_TITLE_HEIGHT
3041
+ }))],
3042
+ loopFrames: frames.filter((frame) => frame.isLoop),
3043
+ contentTop: placement.contentTop
3044
+ }, previousRoute);
3045
+ return {
3046
+ columnLeftEdges,
3047
+ columnWidths,
3048
+ boxesById,
3049
+ bands,
3050
+ frames,
3051
+ notes,
3052
+ panels,
3053
+ routing,
3054
+ collectPlacementWarnings: () => [...nearWarnings, ...overlapWarnings(boxesById, panels, frames, board)],
3055
+ tracksByGap: tracksByGapOf(routing, columnLeftEdges, columnWidths),
3056
+ labelWidthByGap: labelWidthByGapOf(routing, columnLeftEdges, columnWidths)
3057
+ };
3058
+ }
3059
+ function maxByIndex(first, second) {
3060
+ return Array.from({ length: Math.max(first.length, second.length) }, (_, index) => Math.max(first[index] ?? 0, second[index] ?? 0));
3061
+ }
3062
+ function hasUnneededRoom(placed, reservedTracksByGap, reservedLabelWidths) {
3063
+ return reservedTracksByGap.some((tracks, index) => tracks > (placed.tracksByGap[index] ?? 0)) || reservedLabelWidths.some((width, index) => width > (placed.labelWidthByGap[index] ?? 0));
3064
+ }
3065
+ function placeFromReservations(board, room, previous, seedTracksByGap, seedLabelWidths) {
3066
+ let reservedTracksByGap = seedTracksByGap;
3067
+ let reservedLabelWidths = seedLabelWidths;
3068
+ for (let attempt = 1;; attempt += 1) {
3069
+ const placed = placeAndRoute(board, {
3070
+ gapWidths: gapWidthsOf(room.reserves, reservedTracksByGap, reservedLabelWidths),
3071
+ boxesTop: room.boxesTop,
3072
+ contentTop: room.contentTop,
3073
+ stackHeightByBoxId: room.stackHeightByBoxId
3074
+ }, previous?.route ?? null);
3075
+ const needsMoreTracks = placed.tracksByGap.some((tracks, index) => tracks > (reservedTracksByGap[index] ?? 0));
3076
+ const needsWiderLabels = placed.labelWidthByGap.some((width, index) => width > (reservedLabelWidths[index] ?? 0));
3077
+ if (attempt >= MAX_ROOM_ATTEMPTS || !needsMoreTracks && !needsWiderLabels) return {
3078
+ placed,
3079
+ memory: {
3080
+ gapCount: room.reserves.length,
3081
+ reservedTracksByGap,
3082
+ reservedLabelWidths,
3083
+ route: placed.routing.memory
3084
+ }
3085
+ };
3086
+ reservedTracksByGap = maxByIndex(reservedTracksByGap, placed.tracksByGap);
3087
+ reservedLabelWidths = maxByIndex(reservedLabelWidths, placed.labelWidthByGap);
3088
+ }
3089
+ }
3090
+ function placeWithReservedRoom(board, room, previous) {
3091
+ if (!previous || previous.gapCount !== room.reserves.length) return placeFromReservations(board, room, previous, [], []);
3092
+ const seeded = placeFromReservations(board, room, previous, previous.reservedTracksByGap, previous.reservedLabelWidths);
3093
+ if (!hasUnneededRoom(seeded.placed, seeded.memory.reservedTracksByGap, seeded.memory.reservedLabelWidths)) return seeded;
3094
+ return placeFromReservations(board, room, previous, [], []);
3095
+ }
3096
+ function unitShape(unit) {
3097
+ const titleLines = wrapText(unit.title, TITLE_CHARS_PER_LINE);
3098
+ const bodyLines = laidOutLines(unit.lines);
3099
+ const linkLineCount = unit.linkedBoardId ? 1 : 0;
3100
+ return {
3101
+ titleLines,
3102
+ bodyLines,
3103
+ height: 42 + titleLines.length * TITLE_LINE_HEIGHT$1 + (bodyLines.length + linkLineCount) * BODY_LINE_HEIGHT$1
3104
+ };
3105
+ }
3106
+ function layoutUnits(board) {
3107
+ const unitsById = /* @__PURE__ */ new Map();
3108
+ const nextYByLevel = /* @__PURE__ */ new Map();
3109
+ for (const step of planSteps(board)) {
3110
+ const unit = board.elements[step.unitId];
3111
+ if (unit?.kind !== "unit") continue;
3112
+ const shape = unitShape(unit);
3113
+ const y = nextYByLevel.get(step.level) ?? 70;
3114
+ nextYByLevel.set(step.level, y + shape.height + BOX_GAP);
3115
+ unitsById.set(unit.id, {
3116
+ kind: "unit",
3117
+ id: unit.id,
3118
+ x: MARGIN + (step.level - 1) * 310,
3119
+ y,
3120
+ width: COLUMN_WIDTH,
3121
+ height: shape.height,
3122
+ label: step.label,
3123
+ status: unit.status,
3124
+ titleLines: shape.titleLines,
3125
+ bodyLines: shape.bodyLines,
3126
+ linkedBoardId: unit.linkedBoardId
3127
+ });
3128
+ }
3129
+ return unitsById;
3130
+ }
3131
+ function planArrowPath(from, to) {
3132
+ const start = {
3133
+ x: from.x + from.width,
3134
+ y: from.y + Math.round(from.height / 2)
3135
+ };
3136
+ const end = {
3137
+ x: to.x,
3138
+ y: to.y + Math.round(to.height / 2)
3139
+ };
3140
+ const bendX = to.x - Math.round(COLUMN_GAP / 2);
3141
+ return pathOf(withoutBends([
3142
+ start,
3143
+ {
3144
+ x: bendX,
3145
+ y: start.y
3146
+ },
3147
+ {
3148
+ x: bendX,
3149
+ y: end.y
3150
+ },
3151
+ end
3152
+ ]));
3153
+ }
3154
+ function planArrowPaths(board, unitsById) {
3155
+ return elementsOfKind(board, "unit").flatMap((unit) => {
3156
+ const to = unitsById.get(unit.id);
3157
+ if (!to) return [];
3158
+ return unit.after.flatMap((afterId) => {
3159
+ const from = unitsById.get(afterId);
3160
+ return from ? [planArrowPath(from, to)] : [];
3161
+ });
3162
+ });
3163
+ }
3164
+ function planBandBottom(unitsById) {
3165
+ if (unitsById.size === 0) return MARGIN;
3166
+ return Math.max(...[...unitsById.values()].map((unit) => unit.y + unit.height)) + PLAN_BAND_GAP;
3167
+ }
3168
+ function withPinnedBoxesShifted(board, offsetY) {
3169
+ if (offsetY === 0) return board;
3170
+ const elements = Object.fromEntries(Object.entries(board.elements).map(([elementId, element]) => {
3171
+ if (element.kind !== "box" || !element.at) return [elementId, element];
3172
+ return [elementId, {
3173
+ ...element,
3174
+ at: {
3175
+ x: element.at.x,
3176
+ y: element.at.y + offsetY
3177
+ }
3178
+ }];
3179
+ }));
3180
+ return {
3181
+ ...board,
3182
+ elements
3183
+ };
3184
+ }
3185
+ var WIRE_STYLE_WORDS = {
3186
+ plain: null,
3187
+ fail: "failure path",
3188
+ join: "joins",
3189
+ lane: null
3190
+ };
3191
+ function wireStyleKey(tone, isDashed, isBack) {
3192
+ return `${tone}|${isDashed}|${isBack}`;
3193
+ }
3194
+ function defaultWireStyleLabel(tone, isDashed, isBack) {
3195
+ const words = [
3196
+ WIRE_STYLE_WORDS[tone],
3197
+ isBack ? "returns to an earlier step" : null,
3198
+ isDashed && !isBack ? "optional" : null
3199
+ ].filter((word) => word !== null);
3200
+ return words.length > 0 ? words.join(", ") : null;
3201
+ }
3202
+ var CHANGE_LEGEND_LABELS = {
3203
+ added: "added by this change",
3204
+ removed: "removed by this change",
3205
+ relabeled: "renamed, old title struck through"
3206
+ };
3207
+ function changeEntriesOf(board) {
3208
+ const usedChanges = new Set(elementsOfKind(board, "box").map((box) => box.change));
3209
+ return BOX_CHANGES.flatMap((change) => change === "none" || !usedChanges.has(change) ? [] : [{
3210
+ label: CHANGE_LEGEND_LABELS[change],
3211
+ swatch: {
3212
+ kind: "change",
3213
+ change
3214
+ }
3215
+ }]);
3216
+ }
3217
+ function statusEntriesOf(unitsById) {
3218
+ if (unitsById.size === 0) return [];
3219
+ return UNIT_STATUSES.map((status) => ({
3220
+ label: `plan step ${status}`,
3221
+ swatch: {
3222
+ kind: "status",
3223
+ status
3224
+ }
3225
+ }));
3226
+ }
3227
+ function legendEntriesOf(board, unitsById) {
3228
+ const laneEntries = board.lanes.map((lane) => ({
3229
+ label: lane.label || lane.id,
3230
+ swatch: {
3231
+ kind: "lane",
3232
+ hex: LANE_HEX_BY_COLOR[lane.color]
3233
+ }
3234
+ }));
3235
+ const customLabelByKey = new Map(board.legend.map((entry) => [wireStyleKey(entry.tone, entry.dashed || entry.back, entry.back), entry.label]));
3236
+ const usedKeys = /* @__PURE__ */ new Set();
3237
+ const wireEntries = elementsOfKind(board, "wire").flatMap((wire) => {
3238
+ const isDashed = wire.dashed || wire.back;
3239
+ const key = wireStyleKey(wire.tone, isDashed, wire.back);
3240
+ const label = customLabelByKey.get(key) ?? defaultWireStyleLabel(wire.tone, isDashed, wire.back);
3241
+ if (usedKeys.has(key) || label === null) return [];
3242
+ usedKeys.add(key);
3243
+ return [{
3244
+ key,
3245
+ label,
3246
+ swatch: {
3247
+ kind: "wire",
3248
+ tone: wire.tone,
3249
+ isDashed,
3250
+ isBack: wire.back
3251
+ }
3252
+ }];
3253
+ }).sort((left, right) => left.key.localeCompare(right.key));
3254
+ const unusedCustomEntries = board.legend.filter((entry) => !usedKeys.has(wireStyleKey(entry.tone, entry.dashed || entry.back, entry.back))).map((entry) => ({
3255
+ label: entry.label,
3256
+ swatch: {
3257
+ kind: "wire",
3258
+ tone: entry.tone,
3259
+ isDashed: entry.dashed || entry.back,
3260
+ isBack: entry.back
3261
+ }
3262
+ }));
3263
+ return [
3264
+ ...laneEntries,
3265
+ ...wireEntries.map(({ label, swatch }) => ({
3266
+ label,
3267
+ swatch
3268
+ })),
3269
+ ...unusedCustomEntries,
3270
+ ...changeEntriesOf(board),
3271
+ ...statusEntriesOf(unitsById)
3272
+ ];
3273
+ }
3274
+ function layoutBoard(storedBoard) {
3275
+ return layoutBoardWithMemory(storedBoard, null).layout;
3276
+ }
3277
+ function layoutBoardWithMemory(storedBoard, previous) {
3278
+ const unitsById = layoutUnits(storedBoard);
3279
+ const freeformTop = planBandBottom(unitsById);
3280
+ const pinnedOffsetY = freeformTop - MARGIN;
3281
+ const board = indexedBoardOf(withPinnedBoxesShifted(storedBoard, pinnedOffsetY));
3282
+ const stackHeightByBoxId = noteStackHeightByBoxId(board);
3283
+ const titleLinesByColumn = columnTitleLines(board);
3284
+ const extraHeaderHeight = headerExtraHeight(titleLinesByColumn);
3285
+ const ruleY = freeformTop + COLUMN_RULE_OFFSET + extraHeaderHeight;
3286
+ const boxesTop = freeformTop + COLUMN_HEADER_HEIGHT + extraHeaderHeight;
3287
+ const { placed, memory } = placeWithReservedRoom(board, {
3288
+ reserves: gapReservesOf(board, stackHeightByBoxId),
3289
+ boxesTop,
3290
+ contentTop: ruleY,
3291
+ stackHeightByBoxId
3292
+ }, previous);
3293
+ const { columnLeftEdges, columnWidths } = placed;
3294
+ const elements = [
3295
+ ...placed.frames,
3296
+ ...placed.routing.wires,
3297
+ ...placed.boxesById.values(),
3298
+ ...placed.notes,
3299
+ ...placed.panels,
3300
+ ...unitsById.values()
3301
+ ];
3302
+ const contentBounds = boundsOf(elements, placed.routing.extent, columnsRightOf(columnLeftEdges, columnWidths), boxesTop);
3303
+ const legendTop = contentBounds.y + contentBounds.height;
3304
+ const legend = legendEntriesOf(board, unitsById).map((entry, index) => ({
3305
+ ...entry,
3306
+ x: MARGIN,
3307
+ y: legendTop + index * LEGEND_ROW_HEIGHT
3308
+ }));
3309
+ const captionTop = legendTop + legend.length * LEGEND_ROW_HEIGHT + (legend.length > 0 ? 12 : 0);
3310
+ const caption = board.caption ? {
3311
+ text: board.caption,
3312
+ x: MARGIN,
3313
+ y: captionTop
3314
+ } : null;
3315
+ const extraHeight = legend.length * LEGEND_ROW_HEIGHT + (caption ? 30 : 0) + (legend.length > 0 ? 12 : 0);
3316
+ return {
3317
+ layout: {
3318
+ columns: board.columns.map((column, index) => ({
3319
+ id: column.id,
3320
+ titleLines: titleLinesByColumn[index] ?? [],
3321
+ titleBaselineY: freeformTop + COLUMN_TITLE_BASELINE,
3322
+ ruleY,
3323
+ x: columnLeftEdges[index] ?? MARGIN,
3324
+ width: columnWidths[index] ?? COLUMN_WIDTH
3325
+ })),
3326
+ bands: placed.bands,
3327
+ elements,
3328
+ legend,
3329
+ caption,
3330
+ pinnedOffsetY,
3331
+ plan: unitsById.size > 0 ? {
3332
+ titleAt: {
3333
+ x: MARGIN,
3334
+ y: 56
3335
+ },
3336
+ arrowPaths: planArrowPaths(board, unitsById)
3337
+ } : null,
3338
+ bounds: {
3339
+ ...contentBounds,
3340
+ height: contentBounds.height + extraHeight
3341
+ },
3342
+ warnings: cappedWarnings([...placed.routing.collectWarnings(), ...placed.collectPlacementWarnings()])
3343
+ },
3344
+ memory
3345
+ };
3346
+ }
3347
+ //#endregion
3348
+ //#region shared/escape-markup.ts
3349
+ function escapeMarkup(value) {
3350
+ return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
3351
+ }
3352
+ //#endregion
3353
+ //#region shared/whiteboard-svg-core.ts
3354
+ var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
3355
+ var BOX_TEXT_INSET = 12;
3356
+ var TITLE_BASELINE = 26;
3357
+ var TITLE_LINE_HEIGHT = 20;
3358
+ var BODY_LINE_HEIGHT = 18;
3359
+ var NOTE_LINE_HEIGHT = 17;
3360
+ var MUTED_INDENT = 14;
3361
+ var COLUMN_TITLE_LINE_HEIGHT = 16;
3362
+ var UNIT_LABEL_BASELINE = 24;
3363
+ var UNIT_LABEL_HEIGHT = 18;
3364
+ var PLAN_TITLE = "Plan";
3365
+ var LINKED_BOARD_TEXT = "open linked board";
3366
+ var PORT_RADIUS = 5;
3367
+ var RESIZE_HANDLE_SIZE = 10;
3368
+ var BAND_LABEL_BASELINE = 17;
3369
+ var LOOP_BADGE_RADIUS = 6;
3370
+ var LOOP_BADGE_INSET = 20;
3371
+ var DECISION_POINT_INSET = 12;
3372
+ var OUTPUT_LABEL_BASELINE_OFFSET = 4;
3373
+ var OUTPUT_DOT_RADIUS = 3;
3374
+ var MONO_CHAR_WIDTH = 7.2;
3375
+ var CODE_BAND_RISE = 13;
3376
+ var CODE_BAND_HEIGHT = 17;
3377
+ var ITEM_DOT_RADIUS = 2.2;
3378
+ var LEGEND_SAMPLE_WIDTH = 28;
3379
+ var STANDALONE_STYLE = `
3380
+ svg { font-family: 'ComicMono', 'CommitMono', 'Cascadia Code', 'Menlo', monospace; }
3381
+ .wb-backdrop { fill: #0d0b16; }
3382
+ .wb-column-title { fill: #a79fc4; font-size: 12px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; }
3383
+ .wb-column-rule { stroke: #4a4268; stroke-width: 1; stroke-dasharray: 2 5; }
3384
+ .wb-band-rule { stroke: #2a2440; stroke-width: 1; }
3385
+ .wb-band-label { font-size: 12px; font-weight: 700; }
3386
+ .wb-box-outline { fill: #15122a; stroke: #a79fc4; stroke-width: 1.6; }
3387
+ .wb-change-added .wb-box-outline { stroke: #22c55e; stroke-dasharray: 7 5; }
3388
+ .wb-change-removed { opacity: 0.6; }
3389
+ .wb-change-removed .wb-box-outline { fill: transparent; stroke: #ef4444; stroke-dasharray: 7 5; }
3390
+ .wb-change-removed .wb-box-title { text-decoration: line-through; }
3391
+ .wb-change-relabeled .wb-box-outline { stroke: #f5c26b; }
3392
+ .wb-box-was { fill: #a79fc4; font-size: 16px; text-decoration: line-through; }
3393
+ .wb-legend-swatch.wb-box-outline { stroke-width: 1.6; }
3394
+ .wb-box-title { fill: #e6e0f5; font-size: 16px; font-weight: 700; }
3395
+ .wb-box-line { fill: #e6e0f5; font-size: 12px; }
3396
+ .wb-box-line.wb-muted { fill: #a79fc4; }
3397
+ .wb-line-code { fill: #c4b5fd; }
3398
+ .wb-code-band { fill: #221d3a; }
3399
+ .wb-line-marker { fill: #a79fc4; font-size: 12px; }
3400
+ .wb-line-key { fill: #a79fc4; font-size: 12px; font-weight: 700; }
3401
+ .wb-item-dot { fill: #a79fc4; }
3402
+ .wb-panel-outline { fill: #110f20; stroke: #4a4268; stroke-width: 1.4; }
3403
+ .wb-panel-rule { stroke: #4a4268; stroke-width: 1; }
3404
+ .wb-output-divider { stroke: #4a4268; stroke-width: 1; }
3405
+ .wb-output-label { fill: #e6e0f5; font-size: 12px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; }
3406
+ .wb-output-dot { fill: #a79fc4; }
3407
+ .wb-lane-pill { fill: transparent; stroke-width: 1.2; }
3408
+ .wb-lane-pill-text { font-size: 12px; font-weight: 700; }
3409
+ .wb-unit-outline { fill: #15122a; stroke: #c084fc; stroke-width: 1.6; }
3410
+ .wb-unit-label, .wb-unit-link { fill: #c084fc; font-size: 12px; font-weight: 700; }
3411
+ .wb-unit-status { fill: #a79fc4; font-size: 11px; }
3412
+ .wb-unit-planned { fill: #a79fc4; }
3413
+ .wb-unit-building { fill: #f59e0b; }
3414
+ .wb-unit-landed { fill: #22c55e; }
3415
+ .wb-frame-outline { fill: rgba(192, 132, 252, 0.04); stroke: #4a4268; stroke-width: 1.4; stroke-dasharray: 10 6; }
3416
+ .wb-frame-title { fill: #a79fc4; font-size: 12px; font-weight: 700; }
3417
+ .wb-loop .wb-frame-outline { stroke: #c084fc; }
3418
+ .wb-loop-badge { fill: none; stroke: #c084fc; stroke-width: 1.6; }
3419
+ .wb-back .wb-wire-line { stroke: #c084fc; }
3420
+ .wb-wire-hit, .wb-port, .wb-resize-handle { display: none; }
3421
+ .wb-wire-line { fill: none; stroke: #a79fc4; stroke-width: 1.6; }
3422
+ .wb-wire-line.wb-dashed { stroke-dasharray: 7 6; }
3423
+ .wb-tone-fail .wb-wire-line { stroke: #ef4444; }
3424
+ .wb-tone-join .wb-wire-line { stroke: #c084fc; }
3425
+ .wb-wire-dot { fill: #a79fc4; }
3426
+ .wb-wire-label { fill: #e6e0f5; font-size: 12px; text-anchor: middle; paint-order: stroke; stroke: #0d0b16; stroke-width: 5; }
3427
+ .wb-note-card { fill: #2a2213; stroke: #f5c26b; stroke-width: 1.2; }
3428
+ .wb-note-text { fill: #f8e7c4; font-size: 12px; }
3429
+ .wb-note-byline { fill: #c9a868; font-size: 12px; }
3430
+ .wb-resolved { opacity: 0.5; }
3431
+ .wb-legend-text { fill: #a79fc4; font-size: 12px; }
3432
+ .wb-caption { fill: #a79fc4; font-size: 14px; }
3433
+ .wb-image-placeholder { fill: #221d3a; stroke: #4a4268; stroke-width: 1; stroke-dasharray: 4 4; }
3434
+ .wb-image-placeholder-text { fill: #a79fc4; font-size: 12px; }
3435
+ `;
3436
+ var NO_ASSET_HREF = () => null;
3437
+ function attributesMarkup(attributes) {
3438
+ return Object.entries(attributes).flatMap(([name, value]) => value === null ? [] : [` ${name}="${escapeMarkup(value)}"`]).join("");
3439
+ }
3440
+ function tag(name, attributes, children = "") {
3441
+ return `<${name}${attributesMarkup(attributes)}>${children}</${name}>`;
3442
+ }
3443
+ function text(content, x, y, className, extra = {}) {
3444
+ return tag("text", {
3445
+ x,
3446
+ y,
3447
+ class: className,
3448
+ ...extra
3449
+ }, escapeMarkup(content));
3450
+ }
3451
+ function elementGroup(element, className, children) {
3452
+ return tag("g", {
3453
+ class: `wb-element ${className}`,
3454
+ "data-element-id": element.id,
3455
+ "data-element-kind": element.kind
3456
+ }, children.join(""));
3457
+ }
3458
+ function laneStroke(hex) {
3459
+ return hex ? `stroke:${hex}` : null;
3460
+ }
3461
+ function decisionOutlinePath(box) {
3462
+ const right = box.x + box.width;
3463
+ const headerMidY = box.y + box.headerHeight / 2;
3464
+ const top = `M${box.x + DECISION_POINT_INSET},${box.y} H${right - DECISION_POINT_INSET} L${right},${headerMidY}`;
3465
+ if (box.outputs.length === 0) return `${top} L${right - DECISION_POINT_INSET},${box.y + box.height} H${box.x + DECISION_POINT_INSET} L${box.x},${headerMidY} Z`;
3466
+ return `${top} V${box.y + box.height} H${box.x} V${headerMidY} Z`;
3467
+ }
3468
+ function outputRowsMarkup(box) {
3469
+ return box.outputs.flatMap((output) => {
3470
+ const rowHalfHeight = (box.height - box.headerHeight) / box.outputs.length / 2;
3471
+ const rowTop = output.port.y - rowHalfHeight;
3472
+ return [
3473
+ tag("line", {
3474
+ x1: box.x,
3475
+ y1: rowTop,
3476
+ x2: box.x + box.width,
3477
+ y2: rowTop,
3478
+ class: "wb-output-divider"
3479
+ }),
3480
+ text(output.label, box.x + BOX_TEXT_INSET, output.port.y + OUTPUT_LABEL_BASELINE_OFFSET, "wb-output-label"),
3481
+ tag("circle", {
3482
+ cx: output.port.x,
3483
+ cy: output.port.y,
3484
+ r: OUTPUT_DOT_RADIUS,
3485
+ class: "wb-output-dot"
3486
+ })
3487
+ ];
3488
+ });
3489
+ }
3490
+ function lineClassOf(line) {
3491
+ if (line.style === "code") return "wb-box-line wb-line-code";
3492
+ return line.muted ? "wb-box-line wb-muted" : "wb-box-line";
3493
+ }
3494
+ function lineRowMarkup(line, left, width, baseline) {
3495
+ const rowLeft = left + BOX_TEXT_INSET + (line.muted ? MUTED_INDENT : 0);
3496
+ const parts = [];
3497
+ if (line.style === "code") parts.push(tag("rect", {
3498
+ x: rowLeft - 4,
3499
+ y: baseline - CODE_BAND_RISE,
3500
+ width: left + width - BOX_TEXT_INSET + 4 - rowLeft + 4,
3501
+ height: CODE_BAND_HEIGHT,
3502
+ rx: 3,
3503
+ class: "wb-code-band"
3504
+ }));
3505
+ if (line.style === "item" && line.isFirstRow) parts.push(tag("circle", {
3506
+ cx: rowLeft + 4,
3507
+ cy: baseline - 4,
3508
+ r: ITEM_DOT_RADIUS,
3509
+ class: "wb-item-dot"
3510
+ }));
3511
+ if (line.marker !== null) parts.push(text(line.marker, rowLeft, baseline, line.style === "kv" ? "wb-line-key" : "wb-line-marker"));
3512
+ if (line.text) parts.push(text(line.text, rowLeft + line.indentChars * MONO_CHAR_WIDTH, baseline, lineClassOf(line)));
3513
+ return parts;
3514
+ }
3515
+ function bodyLinesMarkup(lines, left, width, top) {
3516
+ return lines.flatMap((line, index) => lineRowMarkup(line, left, width, top + index * BODY_LINE_HEIGHT));
3517
+ }
3518
+ function panelMarkup(panel) {
3519
+ const parts = [tag("rect", {
3520
+ x: panel.x,
3521
+ y: panel.y,
3522
+ width: panel.width,
3523
+ height: panel.height,
3524
+ rx: 6,
3525
+ class: "wb-panel-outline"
3526
+ })];
3527
+ panel.titleLines.forEach((line, index) => {
3528
+ parts.push(text(line, panel.x + BOX_TEXT_INSET, panel.y + TITLE_BASELINE + index * TITLE_LINE_HEIGHT, "wb-box-title"));
3529
+ });
3530
+ const bodyTop = panel.y + TITLE_BASELINE + panel.titleLines.length * TITLE_LINE_HEIGHT;
3531
+ if (panel.bodyLines.length > 0) parts.push(tag("line", {
3532
+ x1: panel.x + BOX_TEXT_INSET,
3533
+ y1: bodyTop - 12,
3534
+ x2: panel.x + panel.width - BOX_TEXT_INSET,
3535
+ y2: bodyTop - 12,
3536
+ class: "wb-panel-rule"
3537
+ }));
3538
+ parts.push(...bodyLinesMarkup(panel.bodyLines, panel.x, panel.width, bodyTop));
3539
+ return elementGroup(panel, "wb-panel", parts);
3540
+ }
3541
+ function boxOutlineMarkup(box) {
3542
+ if (box.shape === "decision") return tag("path", {
3543
+ d: decisionOutlinePath(box),
3544
+ class: "wb-box-outline",
3545
+ style: laneStroke(box.lane?.hex)
3546
+ });
3547
+ return tag("rect", {
3548
+ x: box.x,
3549
+ y: box.y,
3550
+ width: box.width,
3551
+ height: box.height,
3552
+ rx: 8,
3553
+ class: "wb-box-outline",
3554
+ style: laneStroke(box.lane?.hex)
3555
+ });
3556
+ }
3557
+ function mediaMarkup(media, assetHref) {
3558
+ const href = assetHref(media);
3559
+ const placeholderText = media.alt || media.kind;
3560
+ const label = tag("title", {}, escapeMarkup(placeholderText));
3561
+ if (href) return [tag("image", {
3562
+ href,
3563
+ x: media.x,
3564
+ y: media.y,
3565
+ width: media.width,
3566
+ height: media.height,
3567
+ preserveAspectRatio: "xMidYMid meet",
3568
+ class: "wb-image"
3569
+ }, label)];
3570
+ return [tag("rect", {
3571
+ x: media.x,
3572
+ y: media.y,
3573
+ width: media.width,
3574
+ height: media.height,
3575
+ rx: 6,
3576
+ class: "wb-image-placeholder"
3577
+ }, label), text(placeholderText, media.x + media.width / 2, media.y + media.height / 2 + 4, "wb-image-placeholder-text", { "text-anchor": "middle" })];
3578
+ }
3579
+ function boxMarkup(box, assetHref) {
3580
+ const parts = [boxOutlineMarkup(box), ...outputRowsMarkup(box)];
3581
+ const midX = box.x + box.width / 2;
3582
+ const midY = box.y + box.height / 2;
3583
+ for (const [cx, cy] of [
3584
+ [midX, box.y],
3585
+ [box.x + box.width, midY],
3586
+ [midX, box.y + box.height],
3587
+ [box.x, midY]
3588
+ ]) parts.push(tag("circle", {
3589
+ cx,
3590
+ cy,
3591
+ r: PORT_RADIUS,
3592
+ class: "wb-port"
3593
+ }));
3594
+ box.wasLines.forEach((line, index) => {
3595
+ parts.push(text(line, box.x + BOX_TEXT_INSET, box.y + TITLE_BASELINE + index * TITLE_LINE_HEIGHT, "wb-box-was"));
3596
+ });
3597
+ const titleTop = box.y + TITLE_BASELINE + box.wasLines.length * TITLE_LINE_HEIGHT;
3598
+ box.titleLines.forEach((line, index) => {
3599
+ parts.push(text(line, box.x + BOX_TEXT_INSET, titleTop + index * TITLE_LINE_HEIGHT, "wb-box-title"));
3600
+ });
3601
+ const bodyTop = titleTop + box.titleLines.length * TITLE_LINE_HEIGHT;
3602
+ parts.push(...bodyLinesMarkup(box.bodyLines, box.x, box.width, bodyTop));
3603
+ if (box.media) parts.push(...mediaMarkup(box.media, assetHref));
3604
+ if (box.lane && box.showsLanePill) {
3605
+ const pillY = box.y + box.headerHeight - 28;
3606
+ const pillWidth = Math.min(box.width - 24, 16 + box.lane.label.length * 8);
3607
+ parts.push(tag("rect", {
3608
+ x: box.x + BOX_TEXT_INSET,
3609
+ y: pillY,
3610
+ width: pillWidth,
3611
+ height: 18,
3612
+ rx: 9,
3613
+ class: "wb-lane-pill",
3614
+ style: laneStroke(box.lane.hex)
3615
+ }), text(box.lane.label, box.x + BOX_TEXT_INSET + 8, pillY + 13, "wb-lane-pill-text", { style: `fill:${box.lane.hex}` }));
3616
+ }
3617
+ parts.push(tag("rect", {
3618
+ x: box.x + box.width - RESIZE_HANDLE_SIZE,
3619
+ y: box.y + box.height - RESIZE_HANDLE_SIZE,
3620
+ width: RESIZE_HANDLE_SIZE,
3621
+ height: RESIZE_HANDLE_SIZE,
3622
+ rx: 2,
3623
+ class: "wb-resize-handle"
3624
+ }));
3625
+ return elementGroup(box, box.change === "none" ? "wb-box" : `wb-box wb-change-${box.change}`, parts);
3626
+ }
3627
+ function loopBadgeMarkup(frame) {
3628
+ const centerX = frame.x + frame.width - LOOP_BADGE_INSET;
3629
+ const centerY = frame.y + LOOP_BADGE_RADIUS + 6;
3630
+ return tag("path", {
3631
+ d: `M ${centerX + LOOP_BADGE_RADIUS} ${centerY} A ${LOOP_BADGE_RADIUS} ${LOOP_BADGE_RADIUS} 0 1 1 ${centerX} ${centerY - LOOP_BADGE_RADIUS}`,
3632
+ "marker-end": "url(#wb-arrow)",
3633
+ class: "wb-loop-badge"
3634
+ });
3635
+ }
3636
+ function frameMarkup(frame) {
3637
+ const parts = [tag("rect", {
3638
+ x: frame.x,
3639
+ y: frame.y,
3640
+ width: frame.width,
3641
+ height: frame.height,
3642
+ rx: 12,
3643
+ class: "wb-frame-outline"
3644
+ }), text(frame.title, frame.x + 14, frame.y + 18, "wb-frame-title")];
3645
+ if (frame.isLoop) parts.push(loopBadgeMarkup(frame));
3646
+ return elementGroup(frame, frame.isLoop ? "wb-frame wb-loop" : "wb-frame", parts);
3647
+ }
3648
+ function wireMarkup(wire) {
3649
+ const parts = [
3650
+ tag("path", {
3651
+ d: wire.path,
3652
+ class: "wb-wire-hit"
3653
+ }),
3654
+ tag("path", {
3655
+ d: wire.path,
3656
+ "marker-end": wire.hasArrowhead ? "url(#wb-arrow)" : null,
3657
+ class: wire.isDashed ? "wb-wire-line wb-dashed" : "wb-wire-line",
3658
+ style: laneStroke(wire.strokeHex ?? void 0)
3659
+ }),
3660
+ tag("circle", {
3661
+ cx: wire.start.x,
3662
+ cy: wire.start.y,
3663
+ r: 3,
3664
+ class: "wb-wire-dot"
3665
+ })
3666
+ ];
3667
+ if (wire.joinAt) parts.push(tag("circle", {
3668
+ cx: wire.joinAt.x,
3669
+ cy: wire.joinAt.y,
3670
+ r: 3,
3671
+ class: "wb-wire-dot"
3672
+ }));
3673
+ if (wire.label) parts.push(text(wire.label, wire.labelAt.x, wire.labelAt.y, "wb-wire-label"));
3674
+ return elementGroup(wire, wire.isBack ? `wb-wire wb-back wb-tone-${wire.tone}` : `wb-wire wb-tone-${wire.tone}`, parts);
3675
+ }
3676
+ function noteMarkup(note) {
3677
+ const parts = [tag("rect", {
3678
+ x: note.x,
3679
+ y: note.y,
3680
+ width: note.width,
3681
+ height: note.height,
3682
+ rx: 4,
3683
+ class: "wb-note-card"
3684
+ })];
3685
+ note.lines.forEach((line, index) => {
3686
+ parts.push(text(line, note.x + 10, note.y + 22 + index * NOTE_LINE_HEIGHT, "wb-note-text"));
3687
+ });
3688
+ if (note.byline) parts.push(text(note.byline, note.x + 10, note.y + 22 + note.lines.length * NOTE_LINE_HEIGHT, "wb-note-byline"));
3689
+ return elementGroup(note, note.isResolved ? "wb-note wb-resolved" : "wb-note", parts);
3690
+ }
3691
+ function unitMarkup(unit) {
3692
+ const parts = [
3693
+ tag("rect", {
3694
+ x: unit.x,
3695
+ y: unit.y,
3696
+ width: unit.width,
3697
+ height: unit.height,
3698
+ rx: 8,
3699
+ class: "wb-unit-outline"
3700
+ }),
3701
+ text(unit.label, unit.x + BOX_TEXT_INSET, unit.y + UNIT_LABEL_BASELINE, "wb-unit-label"),
3702
+ text(unit.status, unit.x + unit.width - BOX_TEXT_INSET, unit.y + UNIT_LABEL_BASELINE, `wb-unit-status wb-unit-${unit.status}`, { "text-anchor": "end" })
3703
+ ];
3704
+ const titleTop = unit.y + UNIT_LABEL_BASELINE + UNIT_LABEL_HEIGHT;
3705
+ unit.titleLines.forEach((line, index) => {
3706
+ parts.push(text(line, unit.x + BOX_TEXT_INSET, titleTop + index * TITLE_LINE_HEIGHT, "wb-box-title"));
3707
+ });
3708
+ const bodyTop = titleTop + unit.titleLines.length * TITLE_LINE_HEIGHT;
3709
+ parts.push(...bodyLinesMarkup(unit.bodyLines, unit.x, unit.width, bodyTop));
3710
+ if (unit.linkedBoardId) parts.push(text(LINKED_BOARD_TEXT, unit.x + BOX_TEXT_INSET, bodyTop + unit.bodyLines.length * BODY_LINE_HEIGHT, "wb-unit-link", { "data-linked-board-id": unit.linkedBoardId }));
3711
+ return elementGroup(unit, "wb-unit", parts);
3712
+ }
3713
+ function elementMarkup(element, assetHref = NO_ASSET_HREF) {
3714
+ switch (element.kind) {
3715
+ case "box": return boxMarkup(element, assetHref);
3716
+ case "frame": return frameMarkup(element);
3717
+ case "wire": return wireMarkup(element);
3718
+ case "note": return noteMarkup(element);
3719
+ case "unit": return unitMarkup(element);
3720
+ case "panel": return panelMarkup(element);
3721
+ }
3722
+ }
3723
+ function chromeMarkup(layout) {
3724
+ const parts = [];
3725
+ if (layout.plan) {
3726
+ parts.push(text(PLAN_TITLE, layout.plan.titleAt.x, layout.plan.titleAt.y, "wb-column-title"));
3727
+ for (const arrowPath of layout.plan.arrowPaths) parts.push(tag("path", {
3728
+ d: arrowPath,
3729
+ "marker-end": "url(#wb-arrow)",
3730
+ class: "wb-wire-line"
3731
+ }));
3732
+ }
3733
+ for (const band of layout.bands) {
3734
+ parts.push(tag("line", {
3735
+ x1: band.x,
3736
+ y1: band.y,
3737
+ x2: band.x + band.width,
3738
+ y2: band.y,
3739
+ class: "wb-band-rule"
3740
+ }));
3741
+ if (band.label) parts.push(text(band.label, band.x, band.y + BAND_LABEL_BASELINE, "wb-band-label", { style: `fill:${band.hex}` }));
3742
+ }
3743
+ for (const column of layout.columns) {
3744
+ if (column.titleLines.length === 0) continue;
3745
+ column.titleLines.forEach((line, index) => {
3746
+ parts.push(text(line, column.x, column.titleBaselineY + index * COLUMN_TITLE_LINE_HEIGHT, "wb-column-title"));
3747
+ });
3748
+ parts.push(tag("line", {
3749
+ x1: column.x,
3750
+ y1: column.ruleY,
3751
+ x2: column.x + column.width,
3752
+ y2: column.ruleY,
3753
+ class: "wb-column-rule"
3754
+ }));
3755
+ }
3756
+ for (const entry of layout.legend) parts.push(legendRowMarkup(entry));
3757
+ if (layout.caption) parts.push(text(layout.caption.text, layout.caption.x, layout.caption.y + 16, "wb-caption"));
3758
+ return tag("g", { class: "wb-chrome" }, parts.join(""));
3759
+ }
3760
+ function legendSwatchMarkup(entry) {
3761
+ const { swatch } = entry;
3762
+ if (swatch.kind === "lane") return tag("rect", {
3763
+ x: entry.x,
3764
+ y: entry.y,
3765
+ width: 14,
3766
+ height: 14,
3767
+ rx: 3,
3768
+ class: "wb-legend-swatch",
3769
+ style: `fill:${swatch.hex}`
3770
+ });
3771
+ if (swatch.kind === "status") return tag("rect", {
3772
+ x: entry.x,
3773
+ y: entry.y,
3774
+ width: 14,
3775
+ height: 14,
3776
+ rx: 3,
3777
+ class: `wb-legend-swatch wb-unit-outline wb-unit-${swatch.status}`
3778
+ });
3779
+ if (swatch.kind === "change") return tag("g", { class: `wb-change-${swatch.change}` }, tag("rect", {
3780
+ x: entry.x,
3781
+ y: entry.y,
3782
+ width: LEGEND_SAMPLE_WIDTH,
3783
+ height: 14,
3784
+ rx: 3,
3785
+ class: "wb-legend-swatch wb-box-outline"
3786
+ }));
3787
+ const sample = tag("path", {
3788
+ d: `M${entry.x},${entry.y + 7} H${entry.x + LEGEND_SAMPLE_WIDTH}`,
3789
+ "marker-end": "url(#wb-arrow)",
3790
+ class: swatch.isDashed ? "wb-wire-line wb-dashed" : "wb-wire-line"
3791
+ });
3792
+ return tag("g", { class: swatch.isBack ? `wb-back wb-tone-${swatch.tone}` : `wb-tone-${swatch.tone}` }, sample);
3793
+ }
3794
+ function legendRowMarkup(entry) {
3795
+ const labelX = entry.x + (entry.swatch.kind === "lane" || entry.swatch.kind === "status" ? 22 : 40);
3796
+ return legendSwatchMarkup(entry) + text(entry.label, labelX, entry.y + 12, "wb-legend-text");
3797
+ }
3798
+ function arrowDefinitionsMarkup() {
3799
+ return tag("defs", {}, tag("marker", {
3800
+ id: "wb-arrow",
3801
+ viewBox: "0 0 10 10",
3802
+ refX: 9,
3803
+ refY: 5,
3804
+ markerWidth: 8,
3805
+ markerHeight: 8,
3806
+ orient: "auto-start-reverse"
3807
+ }, tag("path", {
3808
+ d: "M 0 1 L 10 5 L 0 9 z",
3809
+ fill: "context-stroke"
3810
+ })));
3811
+ }
3812
+ var LAYER_ORDER = [
3813
+ "frame",
3814
+ "wire",
3815
+ "box",
3816
+ "panel",
3817
+ "note",
3818
+ "unit"
3819
+ ];
3820
+ function boardSvgDocument(layout, assetHref = NO_ASSET_HREF) {
3821
+ const { x, y, width, height } = layout.bounds;
3822
+ const layers = LAYER_ORDER.map((kind) => tag("g", { class: "wb-layer" }, layout.elements.filter((element) => element.kind === kind).map((element) => elementMarkup(element, assetHref)).join("")));
3823
+ const body = [
3824
+ tag("style", {}, STANDALONE_STYLE),
3825
+ arrowDefinitionsMarkup(),
3826
+ tag("rect", {
3827
+ x,
3828
+ y,
3829
+ width,
3830
+ height,
3831
+ class: "wb-backdrop"
3832
+ }),
3833
+ chromeMarkup(layout),
3834
+ ...layers
3835
+ ].join("");
3836
+ return `${tag("svg", {
3837
+ xmlns: SVG_NAMESPACE,
3838
+ viewBox: `${x} ${y} ${width} ${height}`,
3839
+ width,
3840
+ height
3841
+ }, body)}\n`;
3842
+ }
3843
+ //#endregion
3844
+ export { cappedWarnings as a, unitsOf as c, layoutBoardWithMemory as i, escapeMarkup as n, findDependencyCycle as o, layoutBoard as r, planSteps as s, boardSvgDocument as t };