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
@@ -1,2476 +0,0 @@
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-route-core.ts
83
- var CLEARANCE = 14;
84
- var BEND_COST = 30;
85
- var CROSS_COST = 40;
86
- var OVERLAP_COST = 120;
87
- var SOFT_OBSTACLE_COST = 300;
88
- var BACK_INTERIOR_COST = 400;
89
- var MAX_GRID_NODES = 4e4;
90
- var MAX_EXPANSIONS = 2e4;
91
- var MAX_TOTAL_EXPANSIONS = 4e5;
92
- var MAX_BENDS = 6;
93
- var MAX_WIRES_FOR_PORT_SEARCH = 12;
94
- var PROBE_EXPANSIONS = 3e3;
95
- var PORT_SPACING = 14;
96
- var PORT_INSET = 8;
97
- var BOX_CROSSING_COST = 100;
98
- var LABEL_CHAR_WIDTH = 6.6;
99
- var LABEL_GAP = 5;
100
- var LABEL_ASCENT = 10;
101
- var LABEL_CLEARANCE = 2;
102
- var LABEL_SLIDE_FRACTIONS = [
103
- .5,
104
- .35,
105
- .65,
106
- .2,
107
- .8
108
- ];
109
- var STEP_BY_DIRECTION = [
110
- {
111
- x: 1,
112
- y: 0
113
- },
114
- {
115
- x: -1,
116
- y: 0
117
- },
118
- {
119
- x: 0,
120
- y: 1
121
- },
122
- {
123
- x: 0,
124
- y: -1
125
- }
126
- ];
127
- var OUTWARD_DIRECTION_BY_SIDE = {
128
- right: 0,
129
- left: 1,
130
- bottom: 2,
131
- top: 3
132
- };
133
- var INWARD_DIRECTION_BY_SIDE = {
134
- left: 0,
135
- right: 1,
136
- top: 2,
137
- bottom: 3
138
- };
139
- var REVERSE_DIRECTION = [
140
- 1,
141
- 0,
142
- 3,
143
- 2
144
- ];
145
- function isSideways(side) {
146
- return side === "left" || side === "right";
147
- }
148
- function centerOf(rect) {
149
- return {
150
- x: rect.x + rect.width / 2,
151
- y: rect.y + rect.height / 2
152
- };
153
- }
154
- function inflated(rect, by) {
155
- return {
156
- x: rect.x - by,
157
- y: rect.y - by,
158
- width: rect.width + by * 2,
159
- height: rect.height + by * 2
160
- };
161
- }
162
- function unionOf(rects) {
163
- if (rects.length === 0) return null;
164
- let left = Infinity;
165
- let top = Infinity;
166
- let right = -Infinity;
167
- let bottom = -Infinity;
168
- for (const rect of rects) {
169
- left = Math.min(left, rect.x);
170
- top = Math.min(top, rect.y);
171
- right = Math.max(right, rect.x + rect.width);
172
- bottom = Math.max(bottom, rect.y + rect.height);
173
- }
174
- return {
175
- x: left,
176
- y: top,
177
- width: right - left,
178
- height: bottom - top
179
- };
180
- }
181
- function sweepTouchingPairs(items, onPair) {
182
- const byLeftEdge = [...items].sort((first, second) => first.rect.x - second.rect.x);
183
- let active = [];
184
- for (const item of byLeftEdge) {
185
- active = active.filter((open) => open.rect.x + open.rect.width >= item.rect.x);
186
- for (const open of active) if (rectsTouch(open.rect, item.rect)) onPair(open, item);
187
- active.push(item);
188
- }
189
- }
190
- function rectsTouch(first, second) {
191
- 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;
192
- }
193
- function byIndexPair(first, second) {
194
- return first[0] - second[0] || first[1] - second[1];
195
- }
196
- function touchingPairsWithin(bounds) {
197
- const pairs = [];
198
- sweepTouchingPairs(bounds.map((rect, index) => ({
199
- group: 0,
200
- index,
201
- rect
202
- })), (first, second) => {
203
- pairs.push(first.index < second.index ? [first.index, second.index] : [second.index, first.index]);
204
- });
205
- return pairs.sort(byIndexPair);
206
- }
207
- function touchingPairsAcross(firstBounds, secondBounds) {
208
- const pairs = [];
209
- sweepTouchingPairs([...firstBounds.map((rect, index) => ({
210
- group: 0,
211
- index,
212
- rect
213
- })), ...secondBounds.map((rect, index) => ({
214
- group: 1,
215
- index,
216
- rect
217
- }))], (first, second) => {
218
- if (first.group === second.group) return;
219
- pairs.push(first.group === 0 ? [first.index, second.index] : [second.index, first.index]);
220
- });
221
- return pairs.sort(byIndexPair);
222
- }
223
- function pointBoundsOf(points) {
224
- return unionOf(points.map((point) => ({
225
- ...point,
226
- width: 0,
227
- height: 0
228
- }))) ?? {
229
- x: 0,
230
- y: 0,
231
- width: 0,
232
- height: 0
233
- };
234
- }
235
- function groupedBy(items, keyOf) {
236
- const groups = /* @__PURE__ */ new Map();
237
- for (const item of items) {
238
- const key = keyOf(item);
239
- const group = groups.get(key);
240
- if (group) {
241
- group.push(item);
242
- continue;
243
- }
244
- groups.set(key, [item]);
245
- }
246
- return groups;
247
- }
248
- function isHorizontal(segment) {
249
- return segment.from.y === segment.to.y;
250
- }
251
- function segmentHitsRect(segment, rect) {
252
- const right = rect.x + rect.width;
253
- const bottom = rect.y + rect.height;
254
- if (isHorizontal(segment)) {
255
- const y = segment.from.y;
256
- 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;
257
- }
258
- const x = segment.from.x;
259
- 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;
260
- }
261
- function rectsOverlap(first, second) {
262
- 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;
263
- }
264
- function withoutBends(points) {
265
- const distinct = points.filter((point, index) => {
266
- const previous = points[index - 1];
267
- return !previous || previous.x !== point.x || previous.y !== point.y;
268
- });
269
- return distinct.filter((point, index) => {
270
- const previous = distinct[index - 1];
271
- const next = distinct[index + 1];
272
- if (!previous || !next) return true;
273
- return !(previous.x === point.x && point.x === next.x || previous.y === point.y && point.y === next.y);
274
- });
275
- }
276
- function segmentsOf(points) {
277
- return points.slice(1).flatMap((point, index) => {
278
- const previous = points[index];
279
- return previous ? [{
280
- from: previous,
281
- to: point
282
- }] : [];
283
- });
284
- }
285
- function pathOf(points) {
286
- return points.map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`).join(" ");
287
- }
288
- function cappedWarnings(warnings) {
289
- if (warnings.length <= WHITEBOARD_LIMITS.layoutWarnings) return [...warnings];
290
- const shown = warnings.slice(0, WHITEBOARD_LIMITS.layoutWarnings - 1);
291
- return [...shown, `and ${warnings.length - shown.length} more`];
292
- }
293
- function hasHorizontalGap(first, second) {
294
- return second.x >= first.x + first.width || second.x + second.width <= first.x;
295
- }
296
- function facingSides(from, to, isBack) {
297
- if (from.id === to.id) return {
298
- exitSide: "right",
299
- entrySide: "top"
300
- };
301
- if (isBack) return {
302
- exitSide: "bottom",
303
- entrySide: "bottom"
304
- };
305
- const fromCenter = centerOf(from);
306
- const toCenter = centerOf(to);
307
- if (hasHorizontalGap(from, to)) return toCenter.x > fromCenter.x ? {
308
- exitSide: "right",
309
- entrySide: "left"
310
- } : {
311
- exitSide: "left",
312
- entrySide: "right"
313
- };
314
- return toCenter.y > fromCenter.y ? {
315
- exitSide: "bottom",
316
- entrySide: "top"
317
- } : {
318
- exitSide: "top",
319
- entrySide: "bottom"
320
- };
321
- }
322
- var ALL_SIDES = [
323
- "right",
324
- "left",
325
- "bottom",
326
- "top"
327
- ];
328
- function candidateSidePairs(plan, facing) {
329
- const { wire, from, to } = plan;
330
- if (wire.back || from.id === to.id) return [facing];
331
- const exitSides = plan.outputPort || wire.fromSide ? [plan.exitSide] : [facing.exitSide, ...ALL_SIDES.filter((side) => side !== facing.exitSide)];
332
- const entrySides = wire.toSide ? [wire.toSide] : [facing.entrySide, ...ALL_SIDES.filter((side) => side !== facing.entrySide)];
333
- return exitSides.flatMap((exitSide) => entrySides.map((entrySide) => ({
334
- exitSide,
335
- entrySide
336
- })));
337
- }
338
- function probeOf(plan, pair) {
339
- const centeredStart = plan.outputPort ?? portPositions(plan.from, pair.exitSide, 1)[0] ?? centerOf(plan.from);
340
- const centeredEnd = portPositions(plan.to, pair.entrySide, 1)[0] ?? centerOf(plan.to);
341
- if (!isFacing(pair.exitSide, pair.entrySide)) return {
342
- ...plan,
343
- ...pair,
344
- start: centeredStart,
345
- end: centeredEnd
346
- };
347
- const alignedEnd = alignedAlong(centeredEnd, pair.entrySide, plan.to, centeredStart);
348
- const start = alignedEnd === centeredEnd && !plan.outputPort ? alignedAlong(centeredStart, pair.exitSide, plan.from, centeredEnd) : centeredStart;
349
- return {
350
- ...plan,
351
- ...pair,
352
- start,
353
- end: alignedEnd
354
- };
355
- }
356
- function isBetterProbe(candidate, best) {
357
- return candidate.turnsAndCrossings < best.turnsAndCrossings || candidate.turnsAndCrossings === best.turnsAndCrossings && candidate.cost < best.cost;
358
- }
359
- function probeRoute(grid, probe, buffers) {
360
- const states = searchGrid(grid, probe, {
361
- usageByEdge: /* @__PURE__ */ new Map(),
362
- usageByNodeAndAxis: /* @__PURE__ */ new Map()
363
- }, null, buffers, { remainingExpansions: PROBE_EXPANSIONS });
364
- const goalState = states?.at(-1);
365
- const cost = goalState === void 0 ? Infinity : buffers.bestCost[goalState] ?? Infinity;
366
- resetSearchBuffers(buffers);
367
- if (!states || cost === Infinity) return null;
368
- const points = withoutBends(states.map((state) => {
369
- const node = state >> 2;
370
- const xIndex = node % grid.xs.length;
371
- return {
372
- x: grid.xs[xIndex] ?? 0,
373
- y: grid.ys[(node - xIndex) / grid.xs.length] ?? 0
374
- };
375
- }));
376
- return {
377
- segments: segmentsOf(points),
378
- bounds: pointBoundsOf(points),
379
- bends: Math.max(points.length - 2, 0),
380
- cost
381
- };
382
- }
383
- function scoreOf(route, otherRoutes) {
384
- const crossings = otherRoutes.filter((other) => rectsTouch(route.bounds, other.bounds) && other.segments.some((otherSegment) => route.segments.some((segment) => segmentsCross(segment, otherSegment)))).length;
385
- return {
386
- turnsAndCrossings: route.bends + crossings,
387
- cost: route.cost
388
- };
389
- }
390
- function chooseSidesBySearch(plans, facingByPlan, input) {
391
- const pairsByPlan = new Map(plans.map((plan) => {
392
- return [plan, candidateSidePairs(plan, facingByPlan.get(plan) ?? {
393
- exitSide: plan.exitSide,
394
- entrySide: plan.entrySide
395
- })];
396
- }));
397
- if (![...pairsByPlan.values()].some((pairs) => pairs.length > 1)) return;
398
- const grid = buildGrid([...pairsByPlan].flatMap(([plan, pairs]) => pairs.map((pair) => probeOf(plan, pair))), [...input.boxesById.values(), ...input.panels], input.softObstacles, input.contentTop);
399
- if (!grid) return;
400
- const buffers = createSearchBuffers(grid);
401
- const baselineByPlan = new Map(plans.flatMap((plan) => {
402
- const [facing] = pairsByPlan.get(plan) ?? [];
403
- const route = facing ? probeRoute(grid, probeOf(plan, facing), buffers) : null;
404
- return route ? [[plan, route]] : [];
405
- }));
406
- for (const [plan, pairs] of pairsByPlan) {
407
- const baseline = baselineByPlan.get(plan);
408
- if (pairs.length < 2 || !baseline) continue;
409
- const otherRoutes = [...baselineByPlan].flatMap(([other, route]) => other === plan ? [] : [route]);
410
- let best = {
411
- pair: pairs[0],
412
- score: scoreOf(baseline, otherRoutes)
413
- };
414
- for (const pair of pairs.slice(1)) {
415
- const route = probeRoute(grid, probeOf(plan, pair), buffers);
416
- const score = route ? scoreOf(route, otherRoutes) : null;
417
- if (score && isBetterProbe(score, best.score)) best = {
418
- pair,
419
- score
420
- };
421
- }
422
- if (!best.pair) continue;
423
- plan.exitSide = best.pair.exitSide;
424
- plan.entrySide = best.pair.entrySide;
425
- }
426
- }
427
- function joinFacingBuses(plans, facingByPlan) {
428
- const isEnteringFacing = (plan) => plan.entrySide === facingByPlan.get(plan)?.entrySide;
429
- for (let hasChanged = true; hasChanged;) {
430
- hasChanged = false;
431
- for (const plan of plans) {
432
- const facing = facingByPlan.get(plan);
433
- if (!facing || isEnteringFacing(plan) || plan.wire.toSide) continue;
434
- if (!plans.some((other) => other !== plan && other.to.id === plan.to.id && other.styleKey === plan.styleKey && other.entrySide === facing.entrySide && isEnteringFacing(other))) continue;
435
- plan.exitSide = plan.outputPort || plan.wire.fromSide ? plan.exitSide : facing.exitSide;
436
- plan.entrySide = facing.entrySide;
437
- hasChanged = true;
438
- }
439
- }
440
- }
441
- function planWires(input) {
442
- const facingByPlan = /* @__PURE__ */ new Map();
443
- const plans = input.wires.flatMap((wire) => {
444
- const from = input.boxesById.get(wire.from);
445
- const to = input.boxesById.get(wire.to);
446
- if (!from || !to) return [];
447
- const facing = facingSides(from, to, wire.back);
448
- const output = from.outputs.find((candidate) => candidate.id === wire.fromOutput);
449
- const strokeHex = wire.tone === "lane" ? from.lane?.hex ?? null : null;
450
- const plan = {
451
- wire,
452
- from,
453
- to,
454
- strokeHex,
455
- styleKey: `${wire.dashed || wire.back}|${wire.tone}|${strokeHex}`,
456
- exitSide: output ? "right" : wire.fromSide ?? facing.exitSide,
457
- entrySide: wire.toSide ?? facing.entrySide,
458
- busKey: null,
459
- exitKey: "",
460
- outputPort: output?.port ?? null,
461
- start: output?.port ?? centerOf(from),
462
- end: centerOf(to)
463
- };
464
- facingByPlan.set(plan, facing);
465
- return [plan];
466
- });
467
- chooseSidesBySearch(plans, facingByPlan, input);
468
- joinFacingBuses(plans, facingByPlan);
469
- for (const plan of plans) {
470
- const outputId = plan.wire.fromOutput;
471
- plan.exitKey = plan.outputPort && outputId ? `${plan.from.id}|output ${outputId}|${plan.styleKey}` : `${plan.from.id}|${plan.exitSide}|${plan.styleKey}`;
472
- }
473
- const busKeyOf = (plan) => `${plan.to.id}|${plan.entrySide}|${plan.styleKey}`;
474
- const memberCountByBusKey = /* @__PURE__ */ new Map();
475
- for (const plan of plans) memberCountByBusKey.set(busKeyOf(plan), (memberCountByBusKey.get(busKeyOf(plan)) ?? 0) + 1);
476
- for (const plan of plans) if ((memberCountByBusKey.get(busKeyOf(plan)) ?? 0) > 1) plan.busKey = busKeyOf(plan);
477
- return plans;
478
- }
479
- function portPositions(box, side, count) {
480
- const indexes = Array.from({ length: count }, (_, index) => index);
481
- if (isSideways(side)) {
482
- const x = Math.round(side === "left" ? box.x : box.x + box.width);
483
- const spacing = Math.min(PORT_SPACING, (box.height - 16) / Math.max(count - 1, 1));
484
- const centeredFirstY = box.y + Math.min(box.height / 2, 40) - (count - 1) * spacing / 2;
485
- const firstY = Math.max(box.y + PORT_INSET, Math.min(centeredFirstY, box.y + box.height - PORT_INSET - (count - 1) * spacing));
486
- return indexes.map((index) => ({
487
- x,
488
- y: Math.round(firstY + index * spacing)
489
- }));
490
- }
491
- const y = Math.round(side === "top" ? box.y : box.y + box.height);
492
- const firstX = box.x + box.width / 2 - (count - 1) * PORT_SPACING / 2;
493
- return indexes.map((index) => ({
494
- x: Math.round(firstX + index * PORT_SPACING),
495
- y
496
- }));
497
- }
498
- function portCapacity(box, side) {
499
- const sideLength = isSideways(side) ? box.height : box.width;
500
- return Math.max(1, Math.floor((sideLength - 16) / PORT_SPACING) + 1);
501
- }
502
- function portRequestsBySide(plans) {
503
- return groupedBy(plans.flatMap((plan) => [...plan.outputPort ? [] : [{
504
- box: plan.from,
505
- side: plan.exitSide,
506
- groupKey: `exit|${plan.styleKey}`,
507
- wireId: plan.wire.id,
508
- farPoint: centerOf(plan.to),
509
- assign: (point) => {
510
- plan.start = point;
511
- }
512
- }], {
513
- box: plan.to,
514
- side: plan.entrySide,
515
- groupKey: plan.busKey ? `bus|${plan.busKey}` : `entry|${plan.wire.id}`,
516
- wireId: plan.wire.id,
517
- farPoint: plan.outputPort ?? centerOf(plan.from),
518
- assign: (point) => {
519
- plan.end = point;
520
- }
521
- }]), (request) => `${request.box.id}|${request.side}`);
522
- }
523
- function defaultPortOrders(requestsBySide) {
524
- return new Map([...requestsBySide.entries()].map(([sideKey, sideRequests]) => {
525
- return [sideKey, [...groupedBy(sideRequests, (request) => request.groupKey).entries()].map(([groupKey, members]) => ({
526
- groupKey,
527
- firstWireId: members.map((member) => member.wireId).sort()[0] ?? groupKey,
528
- farCoordinate: members.reduce((sum, member) => sum + (isSideways(member.side) ? member.farPoint.y : member.farPoint.x), 0) / members.length
529
- })).sort((left, right) => left.farCoordinate - right.farCoordinate || left.firstWireId.localeCompare(right.firstWireId) || left.groupKey.localeCompare(right.groupKey)).map((group) => group.groupKey)];
530
- }));
531
- }
532
- function assignPorts(requestsBySide, groupOrderBySide) {
533
- for (const [sideKey, sideRequests] of requestsBySide) {
534
- const first = sideRequests[0];
535
- const groupOrder = groupOrderBySide.get(sideKey) ?? [];
536
- if (!first) continue;
537
- const positions = portPositions(first.box, first.side, groupOrder.length);
538
- for (const request of sideRequests) {
539
- const position = positions[groupOrder.indexOf(request.groupKey)];
540
- if (position) request.assign(position);
541
- }
542
- }
543
- }
544
- function isFacing(exitSide, entrySide) {
545
- return exitSide === "right" && entrySide === "left" || exitSide === "left" && entrySide === "right" || exitSide === "bottom" && entrySide === "top" || exitSide === "top" && entrySide === "bottom";
546
- }
547
- function alignedAlong(point, side, box, target) {
548
- if (isSideways(side)) return target.y >= box.y + PORT_INSET && target.y <= box.y + box.height - PORT_INSET ? {
549
- x: point.x,
550
- y: target.y
551
- } : point;
552
- return target.x >= box.x + PORT_INSET && target.x <= box.x + box.width - PORT_INSET ? {
553
- x: target.x,
554
- y: point.y
555
- } : point;
556
- }
557
- function alignLonePorts(plans, groupOrderBySide) {
558
- const isLonePort = (box, side) => (groupOrderBySide.get(`${box.id}|${side}`)?.length ?? 0) === 1;
559
- const memberCountByExitKey = new Map([...groupedBy(plans, (plan) => plan.exitKey)].map(([exitKey, members]) => [exitKey, members.length]));
560
- for (const plan of plans) {
561
- if (plan.from.id === plan.to.id || !isFacing(plan.exitSide, plan.entrySide)) continue;
562
- const alignedEnd = plan.busKey === null && isLonePort(plan.to, plan.entrySide) ? alignedAlong(plan.end, plan.entrySide, plan.to, plan.start) : plan.end;
563
- if (alignedEnd !== plan.end) {
564
- plan.end = alignedEnd;
565
- continue;
566
- }
567
- 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);
568
- }
569
- }
570
- function crowdedSideWarnings(requestsBySide, groupOrderBySide) {
571
- return [...requestsBySide.entries()].flatMap(([sideKey, sideRequests]) => {
572
- const first = sideRequests[0];
573
- const portCount = groupOrderBySide.get(sideKey)?.length ?? 0;
574
- if (!first || portCount <= portCapacity(first.box, first.side)) return [];
575
- return [`box ${first.box.id} has ${portCount} wires on its ${first.side} side, more than fit`];
576
- });
577
- }
578
- function withMidpoints(sortedValues) {
579
- const values = [...sortedValues];
580
- for (const [index, value] of sortedValues.entries()) {
581
- const next = sortedValues[index + 1];
582
- if (next !== void 0 && next - value > 42) values.push(Math.round((value + next) / 2));
583
- }
584
- return [...new Set(values)].sort((left, right) => left - right);
585
- }
586
- function firstIndexAbove(sortedValues, bound, isInclusive) {
587
- let low = 0;
588
- let high = sortedValues.length;
589
- while (low < high) {
590
- const middle = low + high >> 1;
591
- const value = sortedValues[middle] ?? Infinity;
592
- const isBelow = isInclusive ? value < bound : value <= bound;
593
- if (isBelow) low = middle + 1;
594
- if (!isBelow) high = middle;
595
- }
596
- return low;
597
- }
598
- function strictlyInsideRange(sortedValues, start, end) {
599
- return {
600
- first: firstIndexAbove(sortedValues, start, false),
601
- last: firstIndexAbove(sortedValues, end, true) - 1
602
- };
603
- }
604
- function spannedEdgeRange(sortedValues, start, end) {
605
- return {
606
- first: Math.max(0, firstIndexAbove(sortedValues, start, false) - 1),
607
- last: Math.min(firstIndexAbove(sortedValues, end, true) - 1, sortedValues.length - 2)
608
- };
609
- }
610
- function buildGrid(plans, hardRects, softRects, contentTop) {
611
- const allRects = [...hardRects, ...softRects];
612
- const around = unionOf([...allRects, ...plans.flatMap((plan) => [{
613
- ...plan.start,
614
- width: 0,
615
- height: 0
616
- }, {
617
- ...plan.end,
618
- width: 0,
619
- height: 0
620
- }])]);
621
- if (!around) return null;
622
- const portXs = plans.flatMap((plan) => [plan.start.x, plan.end.x]);
623
- const portYs = plans.flatMap((plan) => [plan.start.y, plan.end.y]);
624
- const topLimit = contentTop + 4;
625
- const rawXs = [
626
- ...allRects.flatMap((rect) => [rect.x - CLEARANCE, rect.x + rect.width + CLEARANCE]),
627
- around.x - 42,
628
- around.x + around.width + 42
629
- ].map(Math.round);
630
- const rawYs = [
631
- ...allRects.flatMap((rect) => [rect.y - CLEARANCE, rect.y + rect.height + CLEARANCE]),
632
- around.y - 42,
633
- around.y + around.height + 42
634
- ].map(Math.round).filter((y) => y >= topLimit);
635
- const xs = withMidpoints([.../* @__PURE__ */ new Set([...rawXs, ...portXs])].sort((left, right) => left - right));
636
- const ys = withMidpoints([.../* @__PURE__ */ new Set([...rawYs, ...portYs])].sort((left, right) => left - right));
637
- if (xs.length * ys.length > MAX_GRID_NODES) return null;
638
- const blockingRects = hardRects.map((rect) => inflated(rect, 1));
639
- const edgeFlags = (axis, rects) => {
640
- const flags = new Uint8Array(xs.length * ys.length);
641
- for (const rect of rects) {
642
- const crossedXs = axis === 0 ? spannedEdgeRange(xs, rect.x, rect.x + rect.width) : strictlyInsideRange(xs, rect.x, rect.x + rect.width);
643
- const crossedYs = axis === 0 ? strictlyInsideRange(ys, rect.y, rect.y + rect.height) : spannedEdgeRange(ys, rect.y, rect.y + rect.height);
644
- for (let yIndex = crossedYs.first; yIndex <= crossedYs.last; yIndex += 1) flags.fill(1, yIndex * xs.length + crossedXs.first, yIndex * xs.length + crossedXs.last + 1);
645
- }
646
- return flags;
647
- };
648
- return {
649
- xs,
650
- ys,
651
- xIndexByValue: new Map(xs.map((x, index) => [x, index])),
652
- yIndexByValue: new Map(ys.map((y, index) => [y, index])),
653
- isBlocked: [edgeFlags(0, blockingRects), edgeFlags(1, blockingRects)],
654
- isSoft: [edgeFlags(0, softRects), edgeFlags(1, softRects)]
655
- };
656
- }
657
- function createMinHeap() {
658
- const states = [];
659
- const priorities = [];
660
- const swap = (first, second) => {
661
- [states[first], states[second]] = [states[second] ?? 0, states[first] ?? 0];
662
- [priorities[first], priorities[second]] = [priorities[second] ?? 0, priorities[first] ?? 0];
663
- };
664
- return {
665
- push(state, priority) {
666
- states.push(state);
667
- priorities.push(priority);
668
- let index = states.length - 1;
669
- while (index > 0) {
670
- const parent = index - 1 >> 1;
671
- if ((priorities[parent] ?? 0) <= (priorities[index] ?? 0)) break;
672
- swap(parent, index);
673
- index = parent;
674
- }
675
- },
676
- pop() {
677
- const top = states[0];
678
- const lastState = states.pop();
679
- const lastPriority = priorities.pop();
680
- if (states.length === 0 || lastState === void 0 || lastPriority === void 0) return top;
681
- states[0] = lastState;
682
- priorities[0] = lastPriority;
683
- let index = 0;
684
- for (;;) {
685
- const left = index * 2 + 1;
686
- const right = left + 1;
687
- let smallest = index;
688
- if (left < states.length && (priorities[left] ?? 0) < (priorities[smallest] ?? 0)) smallest = left;
689
- if (right < states.length && (priorities[right] ?? 0) < (priorities[smallest] ?? 0)) smallest = right;
690
- if (smallest === index) return top;
691
- swap(smallest, index);
692
- index = smallest;
693
- }
694
- }
695
- };
696
- }
697
- function edgeKeyOf(grid, xIndex, yIndex, direction) {
698
- if (direction === 0) return {
699
- axis: 0,
700
- index: yIndex * grid.xs.length + xIndex
701
- };
702
- if (direction === 1) return {
703
- axis: 0,
704
- index: yIndex * grid.xs.length + xIndex - 1
705
- };
706
- if (direction === 2) return {
707
- axis: 1,
708
- index: yIndex * grid.xs.length + xIndex
709
- };
710
- return {
711
- axis: 1,
712
- index: (yIndex - 1) * grid.xs.length + xIndex
713
- };
714
- }
715
- function busAndExitKeyOf(busKey, exitKey) {
716
- return `${busKey}\n${exitKey}`;
717
- }
718
- function compatibleCountOf(keyUsage, plan) {
719
- const sameExitCount = keyUsage.countByExitKey.get(plan.exitKey) ?? 0;
720
- if (plan.busKey === null) return sameExitCount;
721
- const sameBusCount = keyUsage.countByBusKey.get(plan.busKey) ?? 0;
722
- const sameBusAndExitCount = keyUsage.countByBusAndExitKey.get(busAndExitKeyOf(plan.busKey, plan.exitKey)) ?? 0;
723
- return sameExitCount + sameBusCount - sameBusAndExitCount;
724
- }
725
- function usagePenalty(usage, plan, edgeKey, nodeIndex, length) {
726
- const edgeUsage = usage.usageByEdge.get(edgeKey.axis * 1e6 + edgeKey.index);
727
- const crossingUsage = usage.usageByNodeAndAxis.get((1 - edgeKey.axis) * 1e6 + nodeIndex);
728
- const compatibleOnEdge = edgeUsage ? compatibleCountOf(edgeUsage, plan) : 0;
729
- const sharesEdge = compatibleOnEdge > 0;
730
- const overlapsStranger = edgeUsage !== void 0 && edgeUsage.total > compatibleOnEdge;
731
- const crossesStranger = crossingUsage !== void 0 && crossingUsage.total > compatibleCountOf(crossingUsage, plan);
732
- return (sharesEdge ? -length * .5 : 0) + (overlapsStranger ? OVERLAP_COST : 0) + (crossesStranger ? CROSS_COST : 0);
733
- }
734
- function createSearchBuffers(grid) {
735
- const stateCount = grid.xs.length * grid.ys.length * 4;
736
- return {
737
- bestCost: new Float64Array(stateCount).fill(Infinity),
738
- cameFrom: new Int32Array(stateCount).fill(-1),
739
- touchedStates: []
740
- };
741
- }
742
- function resetSearchBuffers(buffers) {
743
- for (const state of buffers.touchedStates) {
744
- buffers.bestCost[state] = Infinity;
745
- buffers.cameFrom[state] = -1;
746
- }
747
- buffers.touchedStates.length = 0;
748
- }
749
- function routeOnGrid(grid, plan, usage, backInterior, buffers, budget) {
750
- const states = searchGrid(grid, plan, usage, backInterior, buffers, budget);
751
- resetSearchBuffers(buffers);
752
- return states;
753
- }
754
- function searchGrid(grid, plan, usage, backInterior, buffers, budget) {
755
- const width = grid.xs.length;
756
- const startX = grid.xIndexByValue.get(plan.start.x);
757
- const startY = grid.yIndexByValue.get(plan.start.y);
758
- const endX = grid.xIndexByValue.get(plan.end.x);
759
- const endY = grid.yIndexByValue.get(plan.end.y);
760
- if (startX === void 0 || startY === void 0 || endX === void 0 || endY === void 0) return null;
761
- const startNode = startY * width + startX;
762
- const endNode = endY * width + endX;
763
- const startDirection = OUTWARD_DIRECTION_BY_SIDE[plan.exitSide];
764
- const endDirection = INWARD_DIRECTION_BY_SIDE[plan.entrySide];
765
- const { bestCost, cameFrom, touchedStates } = buffers;
766
- const heap = createMinHeap();
767
- const startState = startNode * 4 + startDirection;
768
- const estimate = (xIndex, yIndex) => Math.abs((grid.xs[xIndex] ?? 0) - plan.end.x) + Math.abs((grid.ys[yIndex] ?? 0) - plan.end.y);
769
- bestCost[startState] = 0;
770
- touchedStates.push(startState);
771
- heap.push(startState, estimate(startX, startY));
772
- for (let expansions = 0; expansions < MAX_EXPANSIONS && budget.remainingExpansions > 0; expansions += 1) {
773
- budget.remainingExpansions -= 1;
774
- const state = heap.pop();
775
- if (state === void 0) return null;
776
- const node = state >> 2;
777
- const direction = state & 3;
778
- if (node === endNode && direction === endDirection) return reconstructNodes(cameFrom, state);
779
- const xIndex = node % width;
780
- const yIndex = (node - xIndex) / width;
781
- const costSoFar = bestCost[state] ?? Infinity;
782
- for (const [nextDirection, step] of STEP_BY_DIRECTION.entries()) {
783
- if (node === startNode && nextDirection !== startDirection) continue;
784
- if (nextDirection === REVERSE_DIRECTION[direction]) continue;
785
- const nextX = xIndex + step.x;
786
- const nextY = yIndex + step.y;
787
- if (nextX < 0 || nextY < 0 || nextX >= width || nextY >= grid.ys.length) continue;
788
- const nextNode = nextY * width + nextX;
789
- if (nextNode === endNode && nextDirection !== endDirection) continue;
790
- const edgeKey = edgeKeyOf(grid, xIndex, yIndex, nextDirection);
791
- if (!(node === startNode || nextNode === endNode) && grid.isBlocked[edgeKey.axis]?.[edgeKey.index] === 1) continue;
792
- const from = {
793
- x: grid.xs[xIndex] ?? 0,
794
- y: grid.ys[yIndex] ?? 0
795
- };
796
- const to = {
797
- x: grid.xs[nextX] ?? 0,
798
- y: grid.ys[nextY] ?? 0
799
- };
800
- const length = Math.abs(to.x - from.x) + Math.abs(to.y - from.y);
801
- const isInsideBackInterior = backInterior !== null && segmentHitsRect({
802
- from,
803
- to
804
- }, backInterior);
805
- const stepCost = length + (nextDirection === direction ? 0 : BEND_COST) + (grid.isSoft[edgeKey.axis]?.[edgeKey.index] === 1 ? SOFT_OBSTACLE_COST : 0) + (isInsideBackInterior ? BACK_INTERIOR_COST : 0) + usagePenalty(usage, plan, edgeKey, nextNode, length);
806
- const nextState = nextNode * 4 + nextDirection;
807
- const nextCost = costSoFar + Math.max(stepCost, 1);
808
- if (nextCost >= (bestCost[nextState] ?? Infinity)) continue;
809
- bestCost[nextState] = nextCost;
810
- cameFrom[nextState] = state;
811
- touchedStates.push(nextState);
812
- heap.push(nextState, nextCost + estimate(nextX, nextY));
813
- }
814
- }
815
- return null;
816
- }
817
- function reconstructNodes(cameFrom, goalState) {
818
- const states = [];
819
- for (let state = goalState; state !== -1; state = cameFrom[state] ?? -1) states.push(state);
820
- return states.reverse();
821
- }
822
- function adjustUsage(grid, usage, plan, states, delta) {
823
- const width = grid.xs.length;
824
- const increment = (countByKey, key) => countByKey.set(key, (countByKey.get(key) ?? 0) + delta);
825
- const remember = (usageByKey, key) => {
826
- const keyUsage = usageByKey.get(key) ?? {
827
- total: 0,
828
- countByExitKey: /* @__PURE__ */ new Map(),
829
- countByBusKey: /* @__PURE__ */ new Map(),
830
- countByBusAndExitKey: /* @__PURE__ */ new Map()
831
- };
832
- usageByKey.set(key, keyUsage);
833
- keyUsage.total += delta;
834
- increment(keyUsage.countByExitKey, plan.exitKey);
835
- if (plan.busKey === null) return;
836
- increment(keyUsage.countByBusKey, plan.busKey);
837
- increment(keyUsage.countByBusAndExitKey, busAndExitKeyOf(plan.busKey, plan.exitKey));
838
- };
839
- for (const [index, state] of states.entries()) {
840
- const previous = states[index - 1];
841
- if (previous === void 0) continue;
842
- const previousNode = previous >> 2;
843
- const direction = state & 3;
844
- const xIndex = previousNode % width;
845
- const edgeKey = edgeKeyOf(grid, xIndex, (previousNode - xIndex) / width, direction);
846
- remember(usage.usageByEdge, edgeKey.axis * 1e6 + edgeKey.index);
847
- remember(usage.usageByNodeAndAxis, edgeKey.axis * 1e6 + previousNode);
848
- remember(usage.usageByNodeAndAxis, edgeKey.axis * 1e6 + (state >> 2));
849
- }
850
- }
851
- function stubOf(point, side) {
852
- const step = STEP_BY_DIRECTION[OUTWARD_DIRECTION_BY_SIDE[side]] ?? {
853
- x: 0,
854
- y: 0
855
- };
856
- return {
857
- x: point.x + step.x * CLEARANCE,
858
- y: point.y + step.y * CLEARANCE
859
- };
860
- }
861
- function fallbackPoints(plan) {
862
- const startStub = stubOf(plan.start, plan.exitSide);
863
- const endStub = stubOf(plan.end, plan.entrySide);
864
- return withoutBends([
865
- plan.start,
866
- startStub,
867
- {
868
- x: endStub.x,
869
- y: startStub.y
870
- },
871
- endStub,
872
- plan.end
873
- ]);
874
- }
875
- function backInteriorOf(plan, loopFrames) {
876
- if (!plan.wire.back) return null;
877
- const span = unionOf([plan.from, plan.to]);
878
- if (!span) return null;
879
- 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;
880
- }
881
- function longestFirst(items, planOf) {
882
- const routeLength = (plan) => Math.abs(plan.start.x - plan.end.x) + Math.abs(plan.start.y - plan.end.y);
883
- return [...items].sort((left, right) => routeLength(planOf(right)) - routeLength(planOf(left)) || planOf(left).wire.id.localeCompare(planOf(right).wire.id));
884
- }
885
- function drawnWireOf(grid, plan, states) {
886
- const points = grid && states ? withoutBends(states.map((state) => {
887
- const node = state >> 2;
888
- const xIndex = node % grid.xs.length;
889
- return {
890
- x: grid.xs[xIndex] ?? 0,
891
- y: grid.ys[(node - xIndex) / grid.xs.length] ?? 0
892
- };
893
- })) : fallbackPoints(plan);
894
- return {
895
- plan,
896
- points,
897
- segments: segmentsOf(points),
898
- states
899
- };
900
- }
901
- function routeAll(plans, input, budget) {
902
- const grid = buildGrid(plans, [...input.boxesById.values(), ...input.panels], input.softObstacles, input.contentTop);
903
- const buffers = grid ? createSearchBuffers(grid) : null;
904
- const usage = {
905
- usageByEdge: /* @__PURE__ */ new Map(),
906
- usageByNodeAndAxis: /* @__PURE__ */ new Map()
907
- };
908
- const drawnById = /* @__PURE__ */ new Map();
909
- for (const plan of longestFirst(plans, (plan) => plan)) {
910
- const states = grid && buffers ? routeOnGrid(grid, plan, usage, backInteriorOf(plan, input.loopFrames), buffers, budget) : null;
911
- if (grid && states) adjustUsage(grid, usage, plan, states, 1);
912
- drawnById.set(plan.wire.id, drawnWireOf(grid, plan, states));
913
- }
914
- return {
915
- drawn: plans.flatMap((plan) => drawnById.get(plan.wire.id) ?? []),
916
- grid,
917
- usage
918
- };
919
- }
920
- function bendCountOf(wire) {
921
- return Math.max(0, wire.points.length - 2);
922
- }
923
- function crossingCostOf(wire, others, input) {
924
- const wireBounds = pointBoundsOf(wire.points);
925
- const wireCrossingCount = others.filter((other) => rectsTouch(wireBounds, pointBoundsOf(other.points)) && pairCrossingOf(wire, other) !== null).length;
926
- return solidsOf(input).filter((solid) => {
927
- const inset = inflated(solid, -2);
928
- return rectsTouch(wireBounds, inset) && runsThrough(wire, solid, inset);
929
- }).length * BOX_CROSSING_COST + wireCrossingCount;
930
- }
931
- function rerouteCrossedWires(routed, input) {
932
- const { grid, usage } = routed;
933
- if (!grid) return routed.drawn;
934
- const buffers = createSearchBuffers(grid);
935
- const budget = { remainingExpansions: MAX_TOTAL_EXPANSIONS };
936
- const drawnById = new Map(routed.drawn.map((wire) => [wire.plan.wire.id, wire]));
937
- for (const current of longestFirst(routed.drawn, (wire) => wire.plan)) {
938
- if (!current.states || budget.remainingExpansions <= 0) continue;
939
- const others = [...drawnById.values()].filter((other) => other.plan !== current.plan);
940
- const currentCost = crossingCostOf(current, others, input);
941
- if (currentCost === 0) continue;
942
- adjustUsage(grid, usage, current.plan, current.states, -1);
943
- const rerouted = drawnWireOf(grid, current.plan, routeOnGrid(grid, current.plan, usage, backInteriorOf(current.plan, input.loopFrames), buffers, budget));
944
- const staysWithinBendLimit = bendCountOf(rerouted) <= Math.max(bendCountOf(current), MAX_BENDS);
945
- const kept = rerouted.states && staysWithinBendLimit && crossingCostOf(rerouted, others, input) < currentCost ? rerouted : current;
946
- adjustUsage(grid, usage, kept.plan, kept.states ?? current.states, 1);
947
- drawnById.set(kept.plan.wire.id, kept);
948
- }
949
- return routed.drawn.map((wire) => drawnById.get(wire.plan.wire.id) ?? wire);
950
- }
951
- function labelWidthOf(label) {
952
- return Math.ceil(label.length * LABEL_CHAR_WIDTH);
953
- }
954
- function labelBoundsAt(baseline, width) {
955
- return {
956
- x: baseline.x - width / 2,
957
- y: baseline.y - LABEL_ASCENT,
958
- width,
959
- height: 13
960
- };
961
- }
962
- function segmentLength(segment) {
963
- return Math.abs(segment.from.x - segment.to.x) + Math.abs(segment.from.y - segment.to.y);
964
- }
965
- function flushLabelCandidates(segment, width) {
966
- if (!isHorizontal(segment)) return [];
967
- const y = segment.from.y;
968
- 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) => [{
969
- x,
970
- y: y - LABEL_GAP
971
- }, {
972
- x,
973
- y: y + LABEL_GAP + LABEL_ASCENT
974
- }]);
975
- }
976
- function labelCandidates(segments, width) {
977
- const byLength = [...segments].sort((left, right) => segmentLength(right) - segmentLength(left));
978
- return [...segments.slice(0, 1), ...byLength].flatMap((segment) => [...LABEL_SLIDE_FRACTIONS.flatMap((fraction) => {
979
- const x = segment.from.x + (segment.to.x - segment.from.x) * fraction;
980
- const y = segment.from.y + (segment.to.y - segment.from.y) * fraction;
981
- if (isHorizontal(segment)) return [{
982
- x,
983
- y: y - LABEL_GAP
984
- }, {
985
- x,
986
- y: y + LABEL_GAP + LABEL_ASCENT
987
- }];
988
- return [{
989
- x: x + LABEL_GAP + width / 2,
990
- y: y + LABEL_ASCENT / 2
991
- }, {
992
- x: x - LABEL_GAP - width / 2,
993
- y: y + LABEL_ASCENT / 2
994
- }];
995
- }), ...flushLabelCandidates(segment, width)]);
996
- }
997
- function placeLabels(drawn, input, warnings) {
998
- const placedById = /* @__PURE__ */ new Map();
999
- const allSegments = drawn.flatMap((wire) => wire.segments);
1000
- const solids = [...input.boxesById.values(), ...input.softObstacles];
1001
- for (const wire of drawn) {
1002
- const label = wire.plan.wire.label;
1003
- if (!label) continue;
1004
- const width = labelWidthOf(label);
1005
- const candidates = labelCandidates(wire.segments, width);
1006
- const isClear = (baseline) => {
1007
- const bounds = labelBoundsAt(baseline, width);
1008
- if (bounds.y < input.contentTop) return false;
1009
- const padded = inflated(bounds, LABEL_CLEARANCE);
1010
- if (allSegments.some((segment) => segmentHitsRect(segment, padded))) return false;
1011
- if (solids.some((rect) => rectsOverlap(bounds, rect))) return false;
1012
- return ![...placedById.values()].some((placed) => rectsOverlap(bounds, placed.bounds));
1013
- };
1014
- const clearSpot = candidates.find(isClear);
1015
- const at = clearSpot ?? candidates[0] ?? centerOf(wire.plan.from);
1016
- if (!clearSpot) warnings.push(`wire ${wire.plan.wire.id} label "${label}" has no clear spot`);
1017
- placedById.set(wire.plan.wire.id, {
1018
- at: {
1019
- x: Math.round(at.x),
1020
- y: Math.round(at.y)
1021
- },
1022
- bounds: labelBoundsAt(at, width)
1023
- });
1024
- }
1025
- return placedById;
1026
- }
1027
- function isStrictlyBetween(value, first, second) {
1028
- return value > Math.min(first, second) + .5 && value < Math.max(first, second) - .5;
1029
- }
1030
- function segmentsCross(first, second) {
1031
- if (isHorizontal(first) === isHorizontal(second)) return false;
1032
- const horizontal = isHorizontal(first) ? first : second;
1033
- const vertical = horizontal === first ? second : first;
1034
- return isStrictlyBetween(vertical.from.x, horizontal.from.x, horizontal.to.x) && isStrictlyBetween(horizontal.from.y, vertical.from.y, vertical.to.y);
1035
- }
1036
- function segmentsOverlap(first, second) {
1037
- if (isHorizontal(first) !== isHorizontal(second)) return false;
1038
- const isAlongX = isHorizontal(first);
1039
- const lineOf = (segment) => isAlongX ? segment.from.y : segment.from.x;
1040
- const startOf = (segment) => Math.min(isAlongX ? segment.from.x : segment.from.y, isAlongX ? segment.to.x : segment.to.y);
1041
- const endOf = (segment) => Math.max(isAlongX ? segment.from.x : segment.from.y, isAlongX ? segment.to.x : segment.to.y);
1042
- return lineOf(first) === lineOf(second) && Math.min(endOf(first), endOf(second)) - Math.max(startOf(first), startOf(second)) > 1;
1043
- }
1044
- function areSiblings(first, second) {
1045
- if (first.plan.busKey !== null && first.plan.busKey === second.plan.busKey) return true;
1046
- return first.plan.exitKey === second.plan.exitKey;
1047
- }
1048
- function pairCrossingOf(first, second) {
1049
- if (areSiblings(first, second)) return null;
1050
- const pairs = first.segments.flatMap((firstSegment) => second.segments.map((secondSegment) => [firstSegment, secondSegment]));
1051
- if (pairs.some(([firstSegment, secondSegment]) => segmentsCross(firstSegment, secondSegment))) return `wire ${first.plan.wire.id} crosses wire ${second.plan.wire.id}`;
1052
- return pairs.some(([firstSegment, secondSegment]) => segmentsOverlap(firstSegment, secondSegment)) ? `wire ${first.plan.wire.id} overlaps wire ${second.plan.wire.id}` : null;
1053
- }
1054
- function findCrossings(drawn) {
1055
- return touchingPairsWithin(drawn.map((wire) => pointBoundsOf(wire.points))).flatMap(([firstIndex, secondIndex]) => {
1056
- const first = drawn[firstIndex];
1057
- const second = drawn[secondIndex];
1058
- return first && second ? pairCrossingOf(first, second) ?? [] : [];
1059
- });
1060
- }
1061
- function solidsOf(input) {
1062
- return [...input.boxesById.values(), ...input.panels];
1063
- }
1064
- function runsThrough(wire, solid, inset) {
1065
- if (solid.id === wire.plan.from.id || solid.id === wire.plan.to.id) return false;
1066
- return wire.segments.some((segment) => segmentHitsRect(segment, inset));
1067
- }
1068
- function findBoxCrossings(drawn, input) {
1069
- const solids = solidsOf(input);
1070
- const insets = solids.map((solid) => inflated(solid, -2));
1071
- return touchingPairsAcross(drawn.map((wire) => pointBoundsOf(wire.points)), insets).flatMap(([wireIndex, solidIndex]) => {
1072
- const wire = drawn[wireIndex];
1073
- const solid = solids[solidIndex];
1074
- const inset = insets[solidIndex];
1075
- if (!wire || !solid || !inset) return [];
1076
- return runsThrough(wire, solid, inset) ? [`wire ${wire.plan.wire.id} runs through ${solid.kind} ${solid.id}`] : [];
1077
- });
1078
- }
1079
- function routeQualityWarnings(drawn) {
1080
- return drawn.flatMap((wire) => {
1081
- if (!wire.states) return [`wire ${wire.plan.wire.id} found no clear route, so it is drawn as a straight dog-leg`];
1082
- const bends = bendCountOf(wire);
1083
- return bends > MAX_BENDS ? [`wire ${wire.plan.wire.id} bends ${bends} times`] : [];
1084
- });
1085
- }
1086
- function isPointOnSegment(point, segment) {
1087
- 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);
1088
- 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);
1089
- }
1090
- function joinPointOf(wire, leader) {
1091
- if (!leader || leader === wire) return null;
1092
- const joined = wire.points.find((point) => leader.segments.some((segment) => isPointOnSegment(point, segment)));
1093
- if (!joined || joined.x === wire.plan.end.x && joined.y === wire.plan.end.y) return null;
1094
- return joined;
1095
- }
1096
- function swapNeighbors(order, index) {
1097
- const left = order[index];
1098
- const right = order[index + 1];
1099
- if (left === void 0 || right === void 0) return;
1100
- order[index] = right;
1101
- order[index + 1] = left;
1102
- }
1103
- function routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, budget) {
1104
- assignPorts(requestsBySide, groupOrderBySide);
1105
- alignLonePorts(plans, groupOrderBySide);
1106
- const routed = routeAll(plans, input, budget);
1107
- return {
1108
- routed,
1109
- crossingCost: findBoxCrossings(routed.drawn, input).length * BOX_CROSSING_COST + findCrossings(routed.drawn).length
1110
- };
1111
- }
1112
- function routeWithFewestCrossings(plans, input, requestsBySide, groupOrderBySide, budget) {
1113
- let best = routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, budget);
1114
- if (plans.length > MAX_WIRES_FOR_PORT_SEARCH) return rerouteCrossedWires(best.routed, input);
1115
- for (const groupOrder of groupOrderBySide.values()) for (let index = 0; best.crossingCost > 0 && index + 1 < groupOrder.length; index += 1) {
1116
- swapNeighbors(groupOrder, index);
1117
- const trial = routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, budget);
1118
- if (trial.crossingCost < best.crossingCost) {
1119
- best = trial;
1120
- continue;
1121
- }
1122
- swapNeighbors(groupOrder, index);
1123
- }
1124
- return rerouteCrossedWires(routeWithPortOrder(plans, input, requestsBySide, groupOrderBySide, budget).routed, input);
1125
- }
1126
- function routeWires(input) {
1127
- const plans = planWires(input);
1128
- const requestsBySide = portRequestsBySide(plans);
1129
- const groupOrderBySide = defaultPortOrders(requestsBySide);
1130
- const budget = { remainingExpansions: MAX_TOTAL_EXPANSIONS };
1131
- const drawn = routeWithFewestCrossings(plans, input, requestsBySide, groupOrderBySide, budget);
1132
- const budgetWarnings = budget.remainingExpansions > 0 ? [] : ["the board has more wires than fit in one routing pass, so some are drawn as straight dog-legs"];
1133
- const labelWarnings = [];
1134
- const labelById = placeLabels(drawn, input, labelWarnings);
1135
- const leaderByBusKey = /* @__PURE__ */ new Map();
1136
- 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);
1137
- const wires = drawn.map((wire) => {
1138
- const { plan, points } = wire;
1139
- const leader = plan.busKey ? leaderByBusKey.get(plan.busKey) : void 0;
1140
- return {
1141
- kind: "wire",
1142
- id: plan.wire.id,
1143
- path: pathOf(points),
1144
- start: plan.start,
1145
- end: plan.end,
1146
- label: plan.wire.label,
1147
- labelAt: labelById.get(plan.wire.id)?.at ?? centerOf(plan.from),
1148
- isDashed: plan.wire.dashed || plan.wire.back,
1149
- isBack: plan.wire.back,
1150
- strokeHex: plan.strokeHex,
1151
- tone: plan.wire.tone,
1152
- hasArrowhead: leader === void 0 || leader === wire,
1153
- joinAt: joinPointOf(wire, leader)
1154
- };
1155
- });
1156
- const labelRects = [...labelById.values()].map((placed) => placed.bounds);
1157
- const pointRects = drawn.flatMap((wire) => wire.points).map((point) => ({
1158
- x: point.x,
1159
- y: point.y,
1160
- width: 0,
1161
- height: 0
1162
- }));
1163
- return {
1164
- wires,
1165
- segments: drawn.flatMap((wire) => wire.segments),
1166
- warnings: [
1167
- ...budgetWarnings,
1168
- ...findBoxCrossings(drawn, input),
1169
- ...findCrossings(drawn),
1170
- ...routeQualityWarnings(drawn),
1171
- ...crowdedSideWarnings(requestsBySide, groupOrderBySide),
1172
- ...labelWarnings
1173
- ],
1174
- extent: unionOf([...pointRects, ...labelRects])
1175
- };
1176
- }
1177
- //#endregion
1178
- //#region shared/whiteboard-layout-core.ts
1179
- var MARGIN = 40;
1180
- var COLUMN_HEADER_HEIGHT = 44;
1181
- var COLUMN_WIDTH = 220;
1182
- var COLUMN_GAP = 90;
1183
- var BOX_GAP = 30;
1184
- var BOX_PADDING = 12;
1185
- var TITLE_LINE_HEIGHT$1 = 20;
1186
- var BODY_LINE_HEIGHT$1 = 18;
1187
- var OUTPUT_ROW_HEIGHT = 28;
1188
- var MAX_KEY_INDENT_CHARS = 12;
1189
- var ITEM_INDENT_CHARS = 2;
1190
- var TITLE_CHARS_PER_LINE = 20;
1191
- var BODY_CHARS_PER_LINE = 26;
1192
- var FRAME_PADDING = 18;
1193
- var FRAME_TITLE_HEIGHT = 26;
1194
- var NOTE_WIDTH = 170;
1195
- var NOTE_CHARS_PER_LINE = 21;
1196
- var NOTE_LINE_HEIGHT$1 = 17;
1197
- var NOTE_GAP = 10;
1198
- var LEGEND_ROW_HEIGHT = 22;
1199
- var COLUMN_TITLE_CHARS_PER_LINE = 24;
1200
- var COLUMN_TITLE_LINE_HEIGHT$1 = 16;
1201
- var COLUMN_TITLE_BASELINE = 16;
1202
- var COLUMN_RULE_OFFSET = 26;
1203
- var NOTE_OVERLAP = 24;
1204
- var NOTE_RISE = 8;
1205
- var CHANNEL_PAD = 10;
1206
- var TRACK_SPACING = 14;
1207
- var MAX_ROOM_ATTEMPTS = 4;
1208
- var PLAN_BAND_GAP = 40;
1209
- var BAND_HEADER_HEIGHT = 26;
1210
- var BAND_GAP = 24;
1211
- var MEDIA_GAP = 8;
1212
- var MEDIA_MAX_HEIGHT = 320;
1213
- var LANE_HEX_BY_COLOR = Object.freeze({
1214
- blue: "#60a5fa",
1215
- green: "#4ade80",
1216
- orange: "#fb923c",
1217
- pink: "#f472b6",
1218
- cyan: "#22d3ee",
1219
- yellow: "#facc15"
1220
- });
1221
- function wrapText(text, charsPerLine) {
1222
- const words = text.split(/\s+/).filter(Boolean);
1223
- const lines = [];
1224
- let current = "";
1225
- for (const word of words) {
1226
- const pieces = word.match(new RegExp(`.{1,${charsPerLine}}`, "g")) ?? [word];
1227
- for (const piece of pieces) {
1228
- const candidate = current ? `${current} ${piece}` : piece;
1229
- if (candidate.length <= charsPerLine) {
1230
- current = candidate;
1231
- continue;
1232
- }
1233
- lines.push(current);
1234
- current = piece;
1235
- }
1236
- }
1237
- if (current) lines.push(current);
1238
- return lines.length > 0 ? lines : [""];
1239
- }
1240
- function rowsOfLine(line, numberInRun, bodyCharsPerLine) {
1241
- const mutedIndentChars = line.muted ? 2 : 0;
1242
- const marker = line.style === "numbered" ? `${numberInRun}.` : line.style === "kv" ? line.key : null;
1243
- const rowOf = (text, index, indentChars, rowMarker) => ({
1244
- text,
1245
- muted: line.muted,
1246
- style: line.style,
1247
- marker: index === 0 ? rowMarker : null,
1248
- indentChars,
1249
- isFirstRow: index === 0
1250
- });
1251
- if (marker && marker.length + 1 > MAX_KEY_INDENT_CHARS) {
1252
- const valueRows = wrapText(line.text, bodyCharsPerLine - mutedIndentChars - ITEM_INDENT_CHARS).map((text) => rowOf(text, 1, ITEM_INDENT_CHARS, null));
1253
- return [rowOf("", 0, 0, marker), ...valueRows];
1254
- }
1255
- const indentChars = line.style === "item" ? ITEM_INDENT_CHARS : marker ? marker.length + 1 : 0;
1256
- return wrapText(line.text, bodyCharsPerLine - mutedIndentChars - indentChars - (line.style === "code" ? 1 : 0)).map((text, index) => rowOf(text, index, indentChars, marker));
1257
- }
1258
- function laidOutLines(lines, bodyCharsPerLine = BODY_CHARS_PER_LINE) {
1259
- let numberInRun = 0;
1260
- return lines.flatMap((line) => {
1261
- numberInRun = line.style === "numbered" ? numberInRun + 1 : 0;
1262
- return rowsOfLine(line, numberInRun, bodyCharsPerLine);
1263
- });
1264
- }
1265
- function laneOf(board, box) {
1266
- const lane = board.lanes.find((candidate) => candidate.id === box.lane);
1267
- if (!lane) return null;
1268
- return {
1269
- label: lane.label || lane.id,
1270
- hex: LANE_HEX_BY_COLOR[lane.color]
1271
- };
1272
- }
1273
- function isGridBox(box) {
1274
- return box.column !== null && box.at === null && box.near === null;
1275
- }
1276
- function boxWidthOf(box) {
1277
- return box.width ?? COLUMN_WIDTH;
1278
- }
1279
- function charsPerLineAt(defaultCharsPerLine, boxWidth) {
1280
- return Math.floor(defaultCharsPerLine * (boxWidth - 24) / 196);
1281
- }
1282
- function mediaSizeOf(box) {
1283
- if (!box.media) return null;
1284
- const boxWidth = boxWidthOf(box);
1285
- const width = boxWidth - 24;
1286
- const maxHeight = Math.round(MEDIA_MAX_HEIGHT * boxWidth / COLUMN_WIDTH);
1287
- return {
1288
- width,
1289
- height: Math.min(maxHeight, Math.max(1, Math.round(width * box.media.height / box.media.width)))
1290
- };
1291
- }
1292
- function laidOutMedia(box, position, mediaTop, mediaSize) {
1293
- if (!box.media || !mediaSize) return null;
1294
- return {
1295
- kind: box.media.kind,
1296
- asset: box.media.asset,
1297
- mime: box.media.mime,
1298
- hasPreview: box.media.hasPreview,
1299
- alt: box.media.alt,
1300
- x: position.x + BOX_PADDING,
1301
- y: position.y + mediaTop,
1302
- width: mediaSize.width,
1303
- height: mediaSize.height
1304
- };
1305
- }
1306
- function boxShape(board, box) {
1307
- const boxWidth = boxWidthOf(box);
1308
- const titleCharsPerLine = charsPerLineAt(TITLE_CHARS_PER_LINE, boxWidth);
1309
- const titleLines = wrapText(box.title, titleCharsPerLine);
1310
- const wasLines = box.change === "relabeled" && box.was ? wrapText(box.was, titleCharsPerLine) : [];
1311
- const bodyLines = laidOutLines(box.lines, charsPerLineAt(BODY_CHARS_PER_LINE, boxWidth));
1312
- const lane = laneOf(board, box);
1313
- const showsLanePill = lane !== null && !isGridBox(box);
1314
- const textHeight = BOX_PADDING + (wasLines.length + titleLines.length) * TITLE_LINE_HEIGHT$1 + bodyLines.length * BODY_LINE_HEIGHT$1;
1315
- const mediaSize = mediaSizeOf(box);
1316
- const mediaRoom = mediaSize ? mediaSize.height + MEDIA_GAP : 0;
1317
- const headerHeight = textHeight + BOX_PADDING + mediaRoom + (showsLanePill ? 26 : 0);
1318
- const outputs = box.shape === "decision" ? box.outputs : [];
1319
- return {
1320
- titleLines,
1321
- wasLines,
1322
- bodyLines,
1323
- lane,
1324
- showsLanePill,
1325
- headerHeight,
1326
- outputs,
1327
- mediaTop: textHeight + MEDIA_GAP,
1328
- mediaSize,
1329
- height: headerHeight + outputs.length * OUTPUT_ROW_HEIGHT
1330
- };
1331
- }
1332
- function elementsOfKind(board, kind) {
1333
- return Object.values(board.elements).filter((element) => element.kind === kind);
1334
- }
1335
- function noteShape(note) {
1336
- const lines = wrapText(note.text, NOTE_CHARS_PER_LINE);
1337
- return {
1338
- lines,
1339
- height: 24 + (lines.length + 1) * NOTE_LINE_HEIGHT$1
1340
- };
1341
- }
1342
- function noteStackHeightByBoxId(board) {
1343
- const stackHeightByBoxId = /* @__PURE__ */ new Map();
1344
- for (const note of elementsOfKind(board, "note")) {
1345
- const stackedSoFar = stackHeightByBoxId.get(note.on);
1346
- const noteHeight = noteShape(note).height;
1347
- stackHeightByBoxId.set(note.on, stackedSoFar === void 0 ? noteHeight : stackedSoFar + NOTE_GAP + noteHeight);
1348
- }
1349
- return stackHeightByBoxId;
1350
- }
1351
- function columnTitleLines(board) {
1352
- return board.columns.map((column) => column.title ? wrapText(column.title, COLUMN_TITLE_CHARS_PER_LINE) : []);
1353
- }
1354
- function headerExtraHeight(titleLinesByColumn) {
1355
- return (Math.max(1, ...titleLinesByColumn.map((lines) => lines.length)) - 1) * COLUMN_TITLE_LINE_HEIGHT$1;
1356
- }
1357
- function gapReservesOf(board, stackHeightByBoxId) {
1358
- const flowBoxes = elementsOfKind(board, "box").filter(isGridBox);
1359
- const notedColumnIds = new Set(flowBoxes.filter((box) => stackHeightByBoxId.has(box.id)).map((box) => box.column));
1360
- const framedBoxIds = new Set(elementsOfKind(board, "frame").flatMap((frame) => frame.contains));
1361
- const framedColumnIds = new Set(flowBoxes.filter((box) => framedBoxIds.has(box.id)).map((box) => box.column));
1362
- const sideReserve = (columnId) => CHANNEL_PAD + (columnId !== void 0 && framedColumnIds.has(columnId) ? FRAME_PADDING : 0);
1363
- return board.columns.map((column, index) => {
1364
- const isNoted = notedColumnIds.has(column.id);
1365
- return {
1366
- left: isNoted ? 156 : sideReserve(column.id),
1367
- right: sideReserve(board.columns[index + 1]?.id),
1368
- minimumWidth: isNoted ? Math.max(COLUMN_GAP, 186) : COLUMN_GAP
1369
- };
1370
- });
1371
- }
1372
- function gapWidthsOf(reserves, tracksByGap, labelWidthByGap) {
1373
- return reserves.map((reserve, index) => {
1374
- const tracks = tracksByGap[index] ?? 0;
1375
- const labelWidth = labelWidthByGap[index] ?? 0;
1376
- const trackNeed = tracks > 0 ? reserve.left + reserve.right + (tracks + 1) * TRACK_SPACING : 0;
1377
- const labelNeed = labelWidth > 0 ? reserve.left + reserve.right + labelWidth + 20 : 0;
1378
- return Math.max(reserve.minimumWidth, trackNeed, labelNeed);
1379
- });
1380
- }
1381
- function columnWidthsOf(board) {
1382
- const columnIndexById = new Map(board.columns.map((column, index) => [column.id, index]));
1383
- const columnWidths = board.columns.map(() => COLUMN_WIDTH);
1384
- for (const box of elementsOfKind(board, "box").filter(isGridBox)) {
1385
- const columnIndex = columnIndexById.get(box.column) ?? 0;
1386
- columnWidths[columnIndex] = Math.max(columnWidths[columnIndex] ?? COLUMN_WIDTH, boxWidthOf(box));
1387
- }
1388
- return columnWidths;
1389
- }
1390
- function columnLeftEdgesOf(columnWidths, gapWidths) {
1391
- const columnLeftEdges = [];
1392
- let nextX = MARGIN;
1393
- for (const [index, columnWidth] of columnWidths.entries()) {
1394
- columnLeftEdges.push(nextX);
1395
- nextX += columnWidth + (gapWidths[index] ?? COLUMN_GAP);
1396
- }
1397
- return columnLeftEdges;
1398
- }
1399
- function columnsRightOf(columnLeftEdges, columnWidths) {
1400
- return (columnLeftEdges.at(-1) ?? MARGIN) + (columnWidths.at(-1) ?? COLUMN_WIDTH);
1401
- }
1402
- function frameIdByBoxId(board) {
1403
- const frameIds = /* @__PURE__ */ new Map();
1404
- for (const frame of elementsOfKind(board, "frame")) for (const boxId of frame.contains) if (!frameIds.has(boxId)) frameIds.set(boxId, frame.id);
1405
- return frameIds;
1406
- }
1407
- function frameClearance(previousFrameId, nextFrameId) {
1408
- if (previousFrameId === nextFrameId) return 0;
1409
- return (previousFrameId ? FRAME_PADDING : 0) + (nextFrameId ? 44 : 0);
1410
- }
1411
- function bandIdOf(board, box) {
1412
- return board.lanes.some((lane) => lane.id === box.lane) ? box.lane ?? "" : "";
1413
- }
1414
- function bandIdsOf(board, gridBoxes) {
1415
- const usedBandIds = new Set(gridBoxes.map((box) => bandIdOf(board, box)));
1416
- return ["", ...board.lanes.map((lane) => lane.id)].filter((bandId) => usedBandIds.has(bandId));
1417
- }
1418
- function laidOutBox(board, box, position) {
1419
- const shape = boxShape(board, box);
1420
- const width = boxWidthOf(box);
1421
- return {
1422
- kind: "box",
1423
- id: box.id,
1424
- x: position.x,
1425
- y: position.y,
1426
- width,
1427
- height: shape.height,
1428
- titleLines: shape.titleLines,
1429
- bodyLines: shape.bodyLines,
1430
- lane: shape.lane,
1431
- showsLanePill: shape.showsLanePill,
1432
- change: box.change,
1433
- wasLines: shape.wasLines,
1434
- shape: box.shape,
1435
- headerHeight: shape.headerHeight,
1436
- media: laidOutMedia(box, position, shape.mediaTop, shape.mediaSize),
1437
- outputs: shape.outputs.map((output, index) => ({
1438
- id: output.id,
1439
- label: output.label,
1440
- port: {
1441
- x: position.x + width,
1442
- y: position.y + shape.headerHeight + index * OUTPUT_ROW_HEIGHT + OUTPUT_ROW_HEIGHT / 2
1443
- }
1444
- }))
1445
- };
1446
- }
1447
- function placeGridBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId, boxesById) {
1448
- const frameIds = frameIdByBoxId(board);
1449
- const gridBoxes = elementsOfKind(board, "box").filter(isGridBox).map((box, index) => ({
1450
- box,
1451
- index
1452
- })).sort((left, right) => left.box.order - right.box.order || left.index - right.index).map(({ box }) => box);
1453
- const bandIds = bandIdsOf(board, gridBoxes);
1454
- const hasLabeledBands = bandIds.some((bandId) => bandId !== "");
1455
- const columnsRight = columnsRightOf(columnLeftEdges, columnWidths);
1456
- const bands = [];
1457
- let bandTop = boxesTop;
1458
- for (const bandId of bandIds) {
1459
- const lane = board.lanes.find((candidate) => candidate.id === bandId);
1460
- const stackTop = bandTop + (hasLabeledBands ? BAND_HEADER_HEIGHT : 0);
1461
- const nextYByColumnId = /* @__PURE__ */ new Map();
1462
- const lastFrameIdByColumnId = /* @__PURE__ */ new Map();
1463
- for (const box of gridBoxes) {
1464
- if (bandIdOf(board, box) !== bandId) continue;
1465
- const columnIndex = Math.max(0, board.columns.findIndex((column) => column.id === box.column));
1466
- const frameId = frameIds.get(box.id) ?? null;
1467
- const y = (nextYByColumnId.get(box.column) ?? stackTop) + frameClearance(lastFrameIdByColumnId.get(box.column) ?? null, frameId);
1468
- const placed = laidOutBox(board, box, {
1469
- x: columnLeftEdges[columnIndex] ?? MARGIN,
1470
- y
1471
- });
1472
- const noteStackBottom = (stackHeightByBoxId.get(box.id) ?? 0) - NOTE_RISE;
1473
- nextYByColumnId.set(box.column, y + Math.max(placed.height, noteStackBottom) + BOX_GAP);
1474
- lastFrameIdByColumnId.set(box.column, frameId);
1475
- boxesById.set(box.id, placed);
1476
- }
1477
- const stackBottom = Math.max(stackTop, ...nextYByColumnId.values()) - BOX_GAP;
1478
- if (hasLabeledBands) bands.push({
1479
- id: bandId,
1480
- label: lane ? lane.label || lane.id : "",
1481
- hex: lane ? LANE_HEX_BY_COLOR[lane.color] : "",
1482
- x: MARGIN,
1483
- y: bandTop,
1484
- width: columnsRight - MARGIN,
1485
- height: stackBottom - bandTop
1486
- });
1487
- bandTop = stackBottom + BAND_GAP + BOX_GAP;
1488
- }
1489
- return bands;
1490
- }
1491
- function nearPosition(target, near, size) {
1492
- const centeredY = target.y + target.height / 2 - size.height / 2;
1493
- const centeredX = target.x + target.width / 2 - size.width / 2;
1494
- switch (near.side) {
1495
- case "right": return {
1496
- x: target.x + target.width + near.gap,
1497
- y: centeredY
1498
- };
1499
- case "left": return {
1500
- x: target.x - size.width - near.gap,
1501
- y: centeredY
1502
- };
1503
- case "bottom": return {
1504
- x: centeredX,
1505
- y: target.y + target.height + near.gap
1506
- };
1507
- case "top": return {
1508
- x: centeredX,
1509
- y: target.y - size.height - near.gap
1510
- };
1511
- }
1512
- }
1513
- function freeOrigin(boxesById, boxesTop) {
1514
- const rightmostEdge = [...boxesById.values()].reduce((rightmost, box) => Math.max(rightmost, box.x + box.width), -Infinity);
1515
- return {
1516
- x: boxesById.size > 0 ? rightmostEdge + COLUMN_GAP : MARGIN,
1517
- y: boxesTop
1518
- };
1519
- }
1520
- function placeNearBoxes(board, boxesTop, boxesById, warnings) {
1521
- const nearBoxes = elementsOfKind(board, "box").filter((box) => box.at === null && box.near !== null);
1522
- const pendingIds = new Set(nearBoxes.map((box) => box.id));
1523
- const place = (box, chainIds) => {
1524
- const settled = boxesById.get(box.id);
1525
- if (settled || !box.near) return settled;
1526
- const target = board.elements[box.near.of];
1527
- 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;
1528
- if (!targetBox) warnings.push(`box ${box.id} sits near ${box.near.of}, which is not placed on the board`);
1529
- const size = {
1530
- width: boxWidthOf(box),
1531
- height: boxShape(board, box).height
1532
- };
1533
- const position = targetBox ? nearPosition(targetBox, box.near, size) : freeOrigin(boxesById, boxesTop);
1534
- const placed = laidOutBox(board, box, {
1535
- x: Math.round(position.x),
1536
- y: Math.round(position.y)
1537
- });
1538
- boxesById.set(box.id, placed);
1539
- return placed;
1540
- };
1541
- for (const box of nearBoxes) place(box, /* @__PURE__ */ new Set());
1542
- }
1543
- function layoutPanels(board, besidePanels, columnLeftEdges, columnWidths, boxesTop) {
1544
- const columnsRight = columnsRightOf(columnLeftEdges, columnWidths);
1545
- const x = Math.max(columnsRight, ...besidePanels.map((rect) => rect.x + rect.width)) + COLUMN_GAP;
1546
- const panels = elementsOfKind(board, "panel").sort((left, right) => left.order - right.order || left.id.localeCompare(right.id));
1547
- let nextY = boxesTop;
1548
- return panels.map((panel) => {
1549
- const titleLines = wrapText(panel.title, TITLE_CHARS_PER_LINE);
1550
- const bodyLines = laidOutLines(panel.lines);
1551
- const height = 24 + titleLines.length * TITLE_LINE_HEIGHT$1 + bodyLines.length * BODY_LINE_HEIGHT$1;
1552
- const laidOut = {
1553
- kind: "panel",
1554
- id: panel.id,
1555
- x: Math.round(x),
1556
- y: nextY,
1557
- width: COLUMN_WIDTH,
1558
- height,
1559
- titleLines,
1560
- bodyLines
1561
- };
1562
- nextY += height + BOX_GAP;
1563
- return laidOut;
1564
- });
1565
- }
1566
- function layoutBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId) {
1567
- const boxesById = /* @__PURE__ */ new Map();
1568
- const warnings = [];
1569
- const bands = placeGridBoxes(board, columnLeftEdges, columnWidths, boxesTop, stackHeightByBoxId, boxesById);
1570
- for (const box of elementsOfKind(board, "box")) if (box.at) boxesById.set(box.id, laidOutBox(board, box, box.at));
1571
- placeNearBoxes(board, boxesTop, boxesById, warnings);
1572
- for (const box of elementsOfKind(board, "box")) if (!boxesById.has(box.id)) boxesById.set(box.id, laidOutBox(board, box, freeOrigin(boxesById, boxesTop)));
1573
- return {
1574
- boxesById,
1575
- bands,
1576
- warnings
1577
- };
1578
- }
1579
- function layoutFrames(board, boxesById) {
1580
- return elementsOfKind(board, "frame").flatMap((frame) => {
1581
- const around = unionOf(frame.contains.flatMap((id) => boxesById.get(id) ?? []));
1582
- if (!around) return [];
1583
- return [{
1584
- kind: "frame",
1585
- id: frame.id,
1586
- title: frame.title,
1587
- isLoop: frame.loop,
1588
- x: around.x - FRAME_PADDING,
1589
- y: around.y - FRAME_PADDING - FRAME_TITLE_HEIGHT,
1590
- width: around.width + 36,
1591
- height: around.height + 36 + FRAME_TITLE_HEIGHT
1592
- }];
1593
- });
1594
- }
1595
- function noteByline(note) {
1596
- if (note.resolvedBy) return `resolved by ${note.resolvedBy}`;
1597
- return note.author ? `from ${note.author}` : "";
1598
- }
1599
- function layoutNotes(board, boxesById) {
1600
- const nextYByBoxId = /* @__PURE__ */ new Map();
1601
- return elementsOfKind(board, "note").flatMap((note) => {
1602
- const target = boxesById.get(note.on);
1603
- if (!target) return [];
1604
- const { lines, height } = noteShape(note);
1605
- const y = nextYByBoxId.get(note.on) ?? target.y - NOTE_RISE;
1606
- nextYByBoxId.set(note.on, y + height + NOTE_GAP);
1607
- return [{
1608
- kind: "note",
1609
- id: note.id,
1610
- x: target.x + target.width - NOTE_OVERLAP,
1611
- y,
1612
- width: NOTE_WIDTH,
1613
- height,
1614
- lines,
1615
- byline: noteByline(note),
1616
- isResolved: note.resolvedBy !== null
1617
- }];
1618
- });
1619
- }
1620
- function boundsOf(elements, wireExtent, columnsRight, boxesTop) {
1621
- const around = unionOf([
1622
- ...elements.flatMap((element) => element.kind === "wire" ? [] : [element]),
1623
- ...wireExtent ? [wireExtent] : [],
1624
- {
1625
- x: 0,
1626
- y: 0,
1627
- width: columnsRight,
1628
- height: boxesTop
1629
- }
1630
- ]);
1631
- if (!around) return {
1632
- x: 0,
1633
- y: 0,
1634
- width: columnsRight + MARGIN,
1635
- height: 80
1636
- };
1637
- return {
1638
- x: Math.min(0, around.x - MARGIN),
1639
- y: Math.min(0, around.y - MARGIN),
1640
- width: around.width + 80,
1641
- height: around.height + 80
1642
- };
1643
- }
1644
- function gapSpansOf(columnLeftEdges, columnWidths) {
1645
- return columnLeftEdges.slice(0, -1).map((leftEdge, index) => {
1646
- const left = leftEdge + (columnWidths[index] ?? COLUMN_WIDTH);
1647
- return {
1648
- left,
1649
- right: columnLeftEdges[index + 1] ?? left
1650
- };
1651
- });
1652
- }
1653
- function tracksByGapOf(routing, columnLeftEdges, columnWidths) {
1654
- const verticalXs = routing.segments.filter((segment) => segment.from.x === segment.to.x).map((segment) => segment.from.x);
1655
- return gapSpansOf(columnLeftEdges, columnWidths).map((span) => new Set(verticalXs.filter((x) => x > span.left && x < span.right)).size);
1656
- }
1657
- function labelWidthByGapOf(routing, columnLeftEdges, columnWidths) {
1658
- 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));
1659
- }
1660
- function overlapWarnings(boxesById, panels, frames, board) {
1661
- const boxes = [...boxesById.values()];
1662
- const solids = [...boxes, ...panels];
1663
- const boxOverlaps = touchingPairsWithin(solids).flatMap(([firstIndex, secondIndex]) => {
1664
- const first = solids[firstIndex];
1665
- const second = solids[secondIndex];
1666
- return first && second && rectsOverlap(first, second) ? [`${first.kind} ${first.id} overlaps ${second.kind} ${second.id}`] : [];
1667
- });
1668
- const containedIdsByFrameId = new Map(elementsOfKind(board, "frame").map((frame) => [frame.id, new Set(frame.contains)]));
1669
- const coveredTitles = frames.flatMap((frame) => boxes.flatMap((box) => {
1670
- const titleStrip = {
1671
- x: frame.x,
1672
- y: frame.y,
1673
- width: frame.width,
1674
- height: FRAME_TITLE_HEIGHT
1675
- };
1676
- return !containedIdsByFrameId.get(frame.id)?.has(box.id) && rectsOverlap(box, titleStrip) ? [`box ${box.id} covers the title of frame ${frame.id}`] : [];
1677
- }));
1678
- return [...boxOverlaps, ...coveredTitles];
1679
- }
1680
- function placeAndRoute(board, placement) {
1681
- const columnWidths = columnWidthsOf(board);
1682
- const columnLeftEdges = columnLeftEdgesOf(columnWidths, placement.gapWidths);
1683
- const { boxesById, bands, warnings: nearWarnings } = layoutBoxes(board, columnLeftEdges, columnWidths, placement.boxesTop, placement.stackHeightByBoxId);
1684
- const frames = layoutFrames(board, boxesById);
1685
- const notes = layoutNotes(board, boxesById);
1686
- const panels = layoutPanels(board, [...boxesById.values(), ...notes], columnLeftEdges, columnWidths, placement.boxesTop);
1687
- const routing = routeWires({
1688
- wires: elementsOfKind(board, "wire"),
1689
- boxesById,
1690
- panels,
1691
- softObstacles: [...notes, ...frames.map((frame) => ({
1692
- x: frame.x,
1693
- y: frame.y,
1694
- width: frame.width,
1695
- height: FRAME_TITLE_HEIGHT
1696
- }))],
1697
- loopFrames: frames.filter((frame) => frame.isLoop),
1698
- contentTop: placement.contentTop
1699
- });
1700
- return {
1701
- columnLeftEdges,
1702
- columnWidths,
1703
- boxesById,
1704
- bands,
1705
- frames,
1706
- notes,
1707
- panels,
1708
- routing,
1709
- placementWarnings: [...nearWarnings, ...overlapWarnings(boxesById, panels, frames, board)],
1710
- tracksByGap: tracksByGapOf(routing, columnLeftEdges, columnWidths),
1711
- labelWidthByGap: labelWidthByGapOf(routing, columnLeftEdges, columnWidths)
1712
- };
1713
- }
1714
- function maxByIndex(first, second) {
1715
- return Array.from({ length: Math.max(first.length, second.length) }, (_, index) => Math.max(first[index] ?? 0, second[index] ?? 0));
1716
- }
1717
- function placeWithReservedRoom(board, room) {
1718
- let reservedTracksByGap = [];
1719
- let reservedLabelWidths = [];
1720
- for (let attempt = 1;; attempt += 1) {
1721
- const placed = placeAndRoute(board, {
1722
- gapWidths: gapWidthsOf(room.reserves, reservedTracksByGap, reservedLabelWidths),
1723
- boxesTop: room.boxesTop,
1724
- contentTop: room.contentTop,
1725
- stackHeightByBoxId: room.stackHeightByBoxId
1726
- });
1727
- const needsMoreTracks = placed.tracksByGap.some((tracks, index) => tracks > (reservedTracksByGap[index] ?? 0));
1728
- const needsWiderLabels = placed.labelWidthByGap.some((width, index) => width > (reservedLabelWidths[index] ?? 0));
1729
- if (attempt >= MAX_ROOM_ATTEMPTS || !needsMoreTracks && !needsWiderLabels) return placed;
1730
- reservedTracksByGap = maxByIndex(reservedTracksByGap, placed.tracksByGap);
1731
- reservedLabelWidths = maxByIndex(reservedLabelWidths, placed.labelWidthByGap);
1732
- }
1733
- }
1734
- function unitShape(unit) {
1735
- const titleLines = wrapText(unit.title, TITLE_CHARS_PER_LINE);
1736
- const bodyLines = laidOutLines(unit.lines);
1737
- const linkLineCount = unit.linkedBoardId ? 1 : 0;
1738
- return {
1739
- titleLines,
1740
- bodyLines,
1741
- height: 42 + titleLines.length * TITLE_LINE_HEIGHT$1 + (bodyLines.length + linkLineCount) * BODY_LINE_HEIGHT$1
1742
- };
1743
- }
1744
- function layoutUnits(board) {
1745
- const unitsById = /* @__PURE__ */ new Map();
1746
- const nextYByLevel = /* @__PURE__ */ new Map();
1747
- for (const step of planSteps(board)) {
1748
- const unit = board.elements[step.unitId];
1749
- if (unit?.kind !== "unit") continue;
1750
- const shape = unitShape(unit);
1751
- const y = nextYByLevel.get(step.level) ?? 70;
1752
- nextYByLevel.set(step.level, y + shape.height + BOX_GAP);
1753
- unitsById.set(unit.id, {
1754
- kind: "unit",
1755
- id: unit.id,
1756
- x: MARGIN + (step.level - 1) * 310,
1757
- y,
1758
- width: COLUMN_WIDTH,
1759
- height: shape.height,
1760
- label: step.label,
1761
- status: unit.status,
1762
- titleLines: shape.titleLines,
1763
- bodyLines: shape.bodyLines,
1764
- linkedBoardId: unit.linkedBoardId
1765
- });
1766
- }
1767
- return unitsById;
1768
- }
1769
- function planArrowPath(from, to) {
1770
- const start = {
1771
- x: from.x + from.width,
1772
- y: from.y + Math.round(from.height / 2)
1773
- };
1774
- const end = {
1775
- x: to.x,
1776
- y: to.y + Math.round(to.height / 2)
1777
- };
1778
- const bendX = to.x - Math.round(COLUMN_GAP / 2);
1779
- return pathOf(withoutBends([
1780
- start,
1781
- {
1782
- x: bendX,
1783
- y: start.y
1784
- },
1785
- {
1786
- x: bendX,
1787
- y: end.y
1788
- },
1789
- end
1790
- ]));
1791
- }
1792
- function planArrowPaths(board, unitsById) {
1793
- return elementsOfKind(board, "unit").flatMap((unit) => {
1794
- const to = unitsById.get(unit.id);
1795
- if (!to) return [];
1796
- return unit.after.flatMap((afterId) => {
1797
- const from = unitsById.get(afterId);
1798
- return from ? [planArrowPath(from, to)] : [];
1799
- });
1800
- });
1801
- }
1802
- function planBandBottom(unitsById) {
1803
- if (unitsById.size === 0) return MARGIN;
1804
- return Math.max(...[...unitsById.values()].map((unit) => unit.y + unit.height)) + PLAN_BAND_GAP;
1805
- }
1806
- function withPinnedBoxesShifted(board, offsetY) {
1807
- if (offsetY === 0) return board;
1808
- const elements = Object.fromEntries(Object.entries(board.elements).map(([elementId, element]) => {
1809
- if (element.kind !== "box" || !element.at) return [elementId, element];
1810
- return [elementId, {
1811
- ...element,
1812
- at: {
1813
- x: element.at.x,
1814
- y: element.at.y + offsetY
1815
- }
1816
- }];
1817
- }));
1818
- return {
1819
- ...board,
1820
- elements
1821
- };
1822
- }
1823
- var WIRE_STYLE_WORDS = {
1824
- plain: null,
1825
- fail: "failure path",
1826
- join: "joins",
1827
- lane: null
1828
- };
1829
- function wireStyleKey(tone, isDashed, isBack) {
1830
- return `${tone}|${isDashed}|${isBack}`;
1831
- }
1832
- function defaultWireStyleLabel(tone, isDashed, isBack) {
1833
- const words = [
1834
- WIRE_STYLE_WORDS[tone],
1835
- isBack ? "returns to an earlier step" : null,
1836
- isDashed && !isBack ? "optional" : null
1837
- ].filter((word) => word !== null);
1838
- return words.length > 0 ? words.join(", ") : null;
1839
- }
1840
- var CHANGE_LEGEND_LABELS = {
1841
- added: "added by this change",
1842
- removed: "removed by this change",
1843
- relabeled: "renamed, old title struck through"
1844
- };
1845
- function changeEntriesOf(board) {
1846
- const usedChanges = new Set(elementsOfKind(board, "box").map((box) => box.change));
1847
- return BOX_CHANGES.flatMap((change) => change === "none" || !usedChanges.has(change) ? [] : [{
1848
- label: CHANGE_LEGEND_LABELS[change],
1849
- swatch: {
1850
- kind: "change",
1851
- change
1852
- }
1853
- }]);
1854
- }
1855
- function statusEntriesOf(unitsById) {
1856
- if (unitsById.size === 0) return [];
1857
- return UNIT_STATUSES.map((status) => ({
1858
- label: `plan step ${status}`,
1859
- swatch: {
1860
- kind: "status",
1861
- status
1862
- }
1863
- }));
1864
- }
1865
- function legendEntriesOf(board, unitsById) {
1866
- const laneEntries = board.lanes.map((lane) => ({
1867
- label: lane.label || lane.id,
1868
- swatch: {
1869
- kind: "lane",
1870
- hex: LANE_HEX_BY_COLOR[lane.color]
1871
- }
1872
- }));
1873
- const customLabelByKey = new Map(board.legend.map((entry) => [wireStyleKey(entry.tone, entry.dashed || entry.back, entry.back), entry.label]));
1874
- const usedKeys = /* @__PURE__ */ new Set();
1875
- const wireEntries = elementsOfKind(board, "wire").flatMap((wire) => {
1876
- const isDashed = wire.dashed || wire.back;
1877
- const key = wireStyleKey(wire.tone, isDashed, wire.back);
1878
- const label = customLabelByKey.get(key) ?? defaultWireStyleLabel(wire.tone, isDashed, wire.back);
1879
- if (usedKeys.has(key) || label === null) return [];
1880
- usedKeys.add(key);
1881
- return [{
1882
- key,
1883
- label,
1884
- swatch: {
1885
- kind: "wire",
1886
- tone: wire.tone,
1887
- isDashed,
1888
- isBack: wire.back
1889
- }
1890
- }];
1891
- }).sort((left, right) => left.key.localeCompare(right.key));
1892
- const unusedCustomEntries = board.legend.filter((entry) => !usedKeys.has(wireStyleKey(entry.tone, entry.dashed || entry.back, entry.back))).map((entry) => ({
1893
- label: entry.label,
1894
- swatch: {
1895
- kind: "wire",
1896
- tone: entry.tone,
1897
- isDashed: entry.dashed || entry.back,
1898
- isBack: entry.back
1899
- }
1900
- }));
1901
- return [
1902
- ...laneEntries,
1903
- ...wireEntries.map(({ label, swatch }) => ({
1904
- label,
1905
- swatch
1906
- })),
1907
- ...unusedCustomEntries,
1908
- ...changeEntriesOf(board),
1909
- ...statusEntriesOf(unitsById)
1910
- ];
1911
- }
1912
- function layoutBoard(storedBoard) {
1913
- const unitsById = layoutUnits(storedBoard);
1914
- const freeformTop = planBandBottom(unitsById);
1915
- const pinnedOffsetY = freeformTop - MARGIN;
1916
- const board = withPinnedBoxesShifted(storedBoard, pinnedOffsetY);
1917
- const stackHeightByBoxId = noteStackHeightByBoxId(board);
1918
- const titleLinesByColumn = columnTitleLines(board);
1919
- const extraHeaderHeight = headerExtraHeight(titleLinesByColumn);
1920
- const ruleY = freeformTop + COLUMN_RULE_OFFSET + extraHeaderHeight;
1921
- const boxesTop = freeformTop + COLUMN_HEADER_HEIGHT + extraHeaderHeight;
1922
- const placed = placeWithReservedRoom(board, {
1923
- reserves: gapReservesOf(board, stackHeightByBoxId),
1924
- boxesTop,
1925
- contentTop: ruleY,
1926
- stackHeightByBoxId
1927
- });
1928
- const { columnLeftEdges, columnWidths } = placed;
1929
- const elements = [
1930
- ...placed.frames,
1931
- ...placed.routing.wires,
1932
- ...placed.boxesById.values(),
1933
- ...placed.notes,
1934
- ...placed.panels,
1935
- ...unitsById.values()
1936
- ];
1937
- const contentBounds = boundsOf(elements, placed.routing.extent, columnsRightOf(columnLeftEdges, columnWidths), boxesTop);
1938
- const legendTop = contentBounds.y + contentBounds.height;
1939
- const legend = legendEntriesOf(board, unitsById).map((entry, index) => ({
1940
- ...entry,
1941
- x: MARGIN,
1942
- y: legendTop + index * LEGEND_ROW_HEIGHT
1943
- }));
1944
- const captionTop = legendTop + legend.length * LEGEND_ROW_HEIGHT + (legend.length > 0 ? 12 : 0);
1945
- const caption = board.caption ? {
1946
- text: board.caption,
1947
- x: MARGIN,
1948
- y: captionTop
1949
- } : null;
1950
- const extraHeight = legend.length * LEGEND_ROW_HEIGHT + (caption ? 30 : 0) + (legend.length > 0 ? 12 : 0);
1951
- return {
1952
- columns: board.columns.map((column, index) => ({
1953
- id: column.id,
1954
- titleLines: titleLinesByColumn[index] ?? [],
1955
- titleBaselineY: freeformTop + COLUMN_TITLE_BASELINE,
1956
- ruleY,
1957
- x: columnLeftEdges[index] ?? MARGIN,
1958
- width: columnWidths[index] ?? COLUMN_WIDTH
1959
- })),
1960
- bands: placed.bands,
1961
- elements,
1962
- legend,
1963
- caption,
1964
- pinnedOffsetY,
1965
- plan: unitsById.size > 0 ? {
1966
- titleAt: {
1967
- x: MARGIN,
1968
- y: 56
1969
- },
1970
- arrowPaths: planArrowPaths(board, unitsById)
1971
- } : null,
1972
- bounds: {
1973
- ...contentBounds,
1974
- height: contentBounds.height + extraHeight
1975
- },
1976
- warnings: cappedWarnings([...placed.placementWarnings, ...placed.routing.warnings])
1977
- };
1978
- }
1979
- //#endregion
1980
- //#region shared/escape-markup.ts
1981
- function escapeMarkup(value) {
1982
- return String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
1983
- }
1984
- //#endregion
1985
- //#region shared/whiteboard-svg-core.ts
1986
- var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
1987
- var BOX_TEXT_INSET = 12;
1988
- var TITLE_BASELINE = 26;
1989
- var TITLE_LINE_HEIGHT = 20;
1990
- var BODY_LINE_HEIGHT = 18;
1991
- var NOTE_LINE_HEIGHT = 17;
1992
- var MUTED_INDENT = 14;
1993
- var COLUMN_TITLE_LINE_HEIGHT = 16;
1994
- var UNIT_LABEL_BASELINE = 24;
1995
- var UNIT_LABEL_HEIGHT = 18;
1996
- var PLAN_TITLE = "Plan";
1997
- var LINKED_BOARD_TEXT = "open linked board";
1998
- var PORT_RADIUS = 5;
1999
- var RESIZE_HANDLE_SIZE = 10;
2000
- var BAND_LABEL_BASELINE = 17;
2001
- var LOOP_BADGE_RADIUS = 6;
2002
- var LOOP_BADGE_INSET = 20;
2003
- var DECISION_POINT_INSET = 12;
2004
- var OUTPUT_LABEL_BASELINE_OFFSET = 4;
2005
- var OUTPUT_DOT_RADIUS = 3;
2006
- var MONO_CHAR_WIDTH = 7.2;
2007
- var CODE_BAND_RISE = 13;
2008
- var CODE_BAND_HEIGHT = 17;
2009
- var ITEM_DOT_RADIUS = 2.2;
2010
- var LEGEND_SAMPLE_WIDTH = 28;
2011
- var STANDALONE_STYLE = `
2012
- svg { font-family: 'ComicMono', 'CommitMono', 'Cascadia Code', 'Menlo', monospace; }
2013
- .wb-backdrop { fill: #0d0b16; }
2014
- .wb-column-title { fill: #a79fc4; font-size: 12px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; }
2015
- .wb-column-rule { stroke: #4a4268; stroke-width: 1; stroke-dasharray: 2 5; }
2016
- .wb-band-rule { stroke: #2a2440; stroke-width: 1; }
2017
- .wb-band-label { font-size: 12px; font-weight: 700; }
2018
- .wb-box-outline { fill: #15122a; stroke: #a79fc4; stroke-width: 1.6; }
2019
- .wb-change-added .wb-box-outline { stroke: #22c55e; stroke-dasharray: 7 5; }
2020
- .wb-change-removed { opacity: 0.6; }
2021
- .wb-change-removed .wb-box-outline { fill: transparent; stroke: #ef4444; stroke-dasharray: 7 5; }
2022
- .wb-change-removed .wb-box-title { text-decoration: line-through; }
2023
- .wb-change-relabeled .wb-box-outline { stroke: #f5c26b; }
2024
- .wb-box-was { fill: #a79fc4; font-size: 16px; text-decoration: line-through; }
2025
- .wb-legend-swatch.wb-box-outline { stroke-width: 1.6; }
2026
- .wb-box-title { fill: #e6e0f5; font-size: 16px; font-weight: 700; }
2027
- .wb-box-line { fill: #e6e0f5; font-size: 12px; }
2028
- .wb-box-line.wb-muted { fill: #a79fc4; }
2029
- .wb-line-code { fill: #c4b5fd; }
2030
- .wb-code-band { fill: #221d3a; }
2031
- .wb-line-marker { fill: #a79fc4; font-size: 12px; }
2032
- .wb-line-key { fill: #a79fc4; font-size: 12px; font-weight: 700; }
2033
- .wb-item-dot { fill: #a79fc4; }
2034
- .wb-panel-outline { fill: #110f20; stroke: #4a4268; stroke-width: 1.4; }
2035
- .wb-panel-rule { stroke: #4a4268; stroke-width: 1; }
2036
- .wb-output-divider { stroke: #4a4268; stroke-width: 1; }
2037
- .wb-output-label { fill: #e6e0f5; font-size: 12px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; }
2038
- .wb-output-dot { fill: #a79fc4; }
2039
- .wb-lane-pill { fill: transparent; stroke-width: 1.2; }
2040
- .wb-lane-pill-text { font-size: 12px; font-weight: 700; }
2041
- .wb-unit-outline { fill: #15122a; stroke: #c084fc; stroke-width: 1.6; }
2042
- .wb-unit-label, .wb-unit-link { fill: #c084fc; font-size: 12px; font-weight: 700; }
2043
- .wb-unit-status { fill: #a79fc4; font-size: 11px; }
2044
- .wb-unit-planned { fill: #a79fc4; }
2045
- .wb-unit-building { fill: #f59e0b; }
2046
- .wb-unit-landed { fill: #22c55e; }
2047
- .wb-frame-outline { fill: rgba(192, 132, 252, 0.04); stroke: #4a4268; stroke-width: 1.4; stroke-dasharray: 10 6; }
2048
- .wb-frame-title { fill: #a79fc4; font-size: 12px; font-weight: 700; }
2049
- .wb-loop .wb-frame-outline { stroke: #c084fc; }
2050
- .wb-loop-badge { fill: none; stroke: #c084fc; stroke-width: 1.6; }
2051
- .wb-back .wb-wire-line { stroke: #c084fc; }
2052
- .wb-wire-hit, .wb-port, .wb-resize-handle { display: none; }
2053
- .wb-wire-line { fill: none; stroke: #a79fc4; stroke-width: 1.6; }
2054
- .wb-wire-line.wb-dashed { stroke-dasharray: 7 6; }
2055
- .wb-tone-fail .wb-wire-line { stroke: #ef4444; }
2056
- .wb-tone-join .wb-wire-line { stroke: #c084fc; }
2057
- .wb-wire-dot { fill: #a79fc4; }
2058
- .wb-wire-label { fill: #e6e0f5; font-size: 12px; text-anchor: middle; paint-order: stroke; stroke: #0d0b16; stroke-width: 5; }
2059
- .wb-note-card { fill: #2a2213; stroke: #f5c26b; stroke-width: 1.2; }
2060
- .wb-note-text { fill: #f8e7c4; font-size: 12px; }
2061
- .wb-note-byline { fill: #c9a868; font-size: 12px; }
2062
- .wb-resolved { opacity: 0.5; }
2063
- .wb-legend-text { fill: #a79fc4; font-size: 12px; }
2064
- .wb-caption { fill: #a79fc4; font-size: 14px; }
2065
- .wb-image-placeholder { fill: #221d3a; stroke: #4a4268; stroke-width: 1; stroke-dasharray: 4 4; }
2066
- .wb-image-placeholder-text { fill: #a79fc4; font-size: 12px; }
2067
- `;
2068
- var NO_ASSET_HREF = () => null;
2069
- function attributesMarkup(attributes) {
2070
- return Object.entries(attributes).flatMap(([name, value]) => value === null ? [] : [` ${name}="${escapeMarkup(value)}"`]).join("");
2071
- }
2072
- function tag(name, attributes, children = "") {
2073
- return `<${name}${attributesMarkup(attributes)}>${children}</${name}>`;
2074
- }
2075
- function text(content, x, y, className, extra = {}) {
2076
- return tag("text", {
2077
- x,
2078
- y,
2079
- class: className,
2080
- ...extra
2081
- }, escapeMarkup(content));
2082
- }
2083
- function elementGroup(element, className, children) {
2084
- return tag("g", {
2085
- class: `wb-element ${className}`,
2086
- "data-element-id": element.id,
2087
- "data-element-kind": element.kind
2088
- }, children.join(""));
2089
- }
2090
- function laneStroke(hex) {
2091
- return hex ? `stroke:${hex}` : null;
2092
- }
2093
- function decisionOutlinePath(box) {
2094
- const right = box.x + box.width;
2095
- const headerMidY = box.y + box.headerHeight / 2;
2096
- const top = `M${box.x + DECISION_POINT_INSET},${box.y} H${right - DECISION_POINT_INSET} L${right},${headerMidY}`;
2097
- 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`;
2098
- return `${top} V${box.y + box.height} H${box.x} V${headerMidY} Z`;
2099
- }
2100
- function outputRowsMarkup(box) {
2101
- return box.outputs.flatMap((output) => {
2102
- const rowHalfHeight = (box.height - box.headerHeight) / box.outputs.length / 2;
2103
- const rowTop = output.port.y - rowHalfHeight;
2104
- return [
2105
- tag("line", {
2106
- x1: box.x,
2107
- y1: rowTop,
2108
- x2: box.x + box.width,
2109
- y2: rowTop,
2110
- class: "wb-output-divider"
2111
- }),
2112
- text(output.label, box.x + BOX_TEXT_INSET, output.port.y + OUTPUT_LABEL_BASELINE_OFFSET, "wb-output-label"),
2113
- tag("circle", {
2114
- cx: output.port.x,
2115
- cy: output.port.y,
2116
- r: OUTPUT_DOT_RADIUS,
2117
- class: "wb-output-dot"
2118
- })
2119
- ];
2120
- });
2121
- }
2122
- function lineClassOf(line) {
2123
- if (line.style === "code") return "wb-box-line wb-line-code";
2124
- return line.muted ? "wb-box-line wb-muted" : "wb-box-line";
2125
- }
2126
- function lineRowMarkup(line, left, width, baseline) {
2127
- const rowLeft = left + BOX_TEXT_INSET + (line.muted ? MUTED_INDENT : 0);
2128
- const parts = [];
2129
- if (line.style === "code") parts.push(tag("rect", {
2130
- x: rowLeft - 4,
2131
- y: baseline - CODE_BAND_RISE,
2132
- width: left + width - BOX_TEXT_INSET + 4 - rowLeft + 4,
2133
- height: CODE_BAND_HEIGHT,
2134
- rx: 3,
2135
- class: "wb-code-band"
2136
- }));
2137
- if (line.style === "item" && line.isFirstRow) parts.push(tag("circle", {
2138
- cx: rowLeft + 4,
2139
- cy: baseline - 4,
2140
- r: ITEM_DOT_RADIUS,
2141
- class: "wb-item-dot"
2142
- }));
2143
- if (line.marker !== null) parts.push(text(line.marker, rowLeft, baseline, line.style === "kv" ? "wb-line-key" : "wb-line-marker"));
2144
- if (line.text) parts.push(text(line.text, rowLeft + line.indentChars * MONO_CHAR_WIDTH, baseline, lineClassOf(line)));
2145
- return parts;
2146
- }
2147
- function bodyLinesMarkup(lines, left, width, top) {
2148
- return lines.flatMap((line, index) => lineRowMarkup(line, left, width, top + index * BODY_LINE_HEIGHT));
2149
- }
2150
- function panelMarkup(panel) {
2151
- const parts = [tag("rect", {
2152
- x: panel.x,
2153
- y: panel.y,
2154
- width: panel.width,
2155
- height: panel.height,
2156
- rx: 6,
2157
- class: "wb-panel-outline"
2158
- })];
2159
- panel.titleLines.forEach((line, index) => {
2160
- parts.push(text(line, panel.x + BOX_TEXT_INSET, panel.y + TITLE_BASELINE + index * TITLE_LINE_HEIGHT, "wb-box-title"));
2161
- });
2162
- const bodyTop = panel.y + TITLE_BASELINE + panel.titleLines.length * TITLE_LINE_HEIGHT;
2163
- if (panel.bodyLines.length > 0) parts.push(tag("line", {
2164
- x1: panel.x + BOX_TEXT_INSET,
2165
- y1: bodyTop - 12,
2166
- x2: panel.x + panel.width - BOX_TEXT_INSET,
2167
- y2: bodyTop - 12,
2168
- class: "wb-panel-rule"
2169
- }));
2170
- parts.push(...bodyLinesMarkup(panel.bodyLines, panel.x, panel.width, bodyTop));
2171
- return elementGroup(panel, "wb-panel", parts);
2172
- }
2173
- function boxOutlineMarkup(box) {
2174
- if (box.shape === "decision") return tag("path", {
2175
- d: decisionOutlinePath(box),
2176
- class: "wb-box-outline",
2177
- style: laneStroke(box.lane?.hex)
2178
- });
2179
- return tag("rect", {
2180
- x: box.x,
2181
- y: box.y,
2182
- width: box.width,
2183
- height: box.height,
2184
- rx: 8,
2185
- class: "wb-box-outline",
2186
- style: laneStroke(box.lane?.hex)
2187
- });
2188
- }
2189
- function mediaMarkup(media, assetHref) {
2190
- const href = assetHref(media);
2191
- const placeholderText = media.alt || media.kind;
2192
- const label = tag("title", {}, escapeMarkup(placeholderText));
2193
- if (href) return [tag("image", {
2194
- href,
2195
- x: media.x,
2196
- y: media.y,
2197
- width: media.width,
2198
- height: media.height,
2199
- preserveAspectRatio: "xMidYMid meet",
2200
- class: "wb-image"
2201
- }, label)];
2202
- return [tag("rect", {
2203
- x: media.x,
2204
- y: media.y,
2205
- width: media.width,
2206
- height: media.height,
2207
- rx: 6,
2208
- class: "wb-image-placeholder"
2209
- }, label), text(placeholderText, media.x + media.width / 2, media.y + media.height / 2 + 4, "wb-image-placeholder-text", { "text-anchor": "middle" })];
2210
- }
2211
- function boxMarkup(box, assetHref) {
2212
- const parts = [boxOutlineMarkup(box), ...outputRowsMarkup(box)];
2213
- const midX = box.x + box.width / 2;
2214
- const midY = box.y + box.height / 2;
2215
- for (const [cx, cy] of [
2216
- [midX, box.y],
2217
- [box.x + box.width, midY],
2218
- [midX, box.y + box.height],
2219
- [box.x, midY]
2220
- ]) parts.push(tag("circle", {
2221
- cx,
2222
- cy,
2223
- r: PORT_RADIUS,
2224
- class: "wb-port"
2225
- }));
2226
- box.wasLines.forEach((line, index) => {
2227
- parts.push(text(line, box.x + BOX_TEXT_INSET, box.y + TITLE_BASELINE + index * TITLE_LINE_HEIGHT, "wb-box-was"));
2228
- });
2229
- const titleTop = box.y + TITLE_BASELINE + box.wasLines.length * TITLE_LINE_HEIGHT;
2230
- box.titleLines.forEach((line, index) => {
2231
- parts.push(text(line, box.x + BOX_TEXT_INSET, titleTop + index * TITLE_LINE_HEIGHT, "wb-box-title"));
2232
- });
2233
- const bodyTop = titleTop + box.titleLines.length * TITLE_LINE_HEIGHT;
2234
- parts.push(...bodyLinesMarkup(box.bodyLines, box.x, box.width, bodyTop));
2235
- if (box.media) parts.push(...mediaMarkup(box.media, assetHref));
2236
- if (box.lane && box.showsLanePill) {
2237
- const pillY = box.y + box.headerHeight - 28;
2238
- const pillWidth = Math.min(box.width - 24, 16 + box.lane.label.length * 8);
2239
- parts.push(tag("rect", {
2240
- x: box.x + BOX_TEXT_INSET,
2241
- y: pillY,
2242
- width: pillWidth,
2243
- height: 18,
2244
- rx: 9,
2245
- class: "wb-lane-pill",
2246
- style: laneStroke(box.lane.hex)
2247
- }), text(box.lane.label, box.x + BOX_TEXT_INSET + 8, pillY + 13, "wb-lane-pill-text", { style: `fill:${box.lane.hex}` }));
2248
- }
2249
- parts.push(tag("rect", {
2250
- x: box.x + box.width - RESIZE_HANDLE_SIZE,
2251
- y: box.y + box.height - RESIZE_HANDLE_SIZE,
2252
- width: RESIZE_HANDLE_SIZE,
2253
- height: RESIZE_HANDLE_SIZE,
2254
- rx: 2,
2255
- class: "wb-resize-handle"
2256
- }));
2257
- return elementGroup(box, box.change === "none" ? "wb-box" : `wb-box wb-change-${box.change}`, parts);
2258
- }
2259
- function loopBadgeMarkup(frame) {
2260
- const centerX = frame.x + frame.width - LOOP_BADGE_INSET;
2261
- const centerY = frame.y + LOOP_BADGE_RADIUS + 6;
2262
- return tag("path", {
2263
- d: `M ${centerX + LOOP_BADGE_RADIUS} ${centerY} A ${LOOP_BADGE_RADIUS} ${LOOP_BADGE_RADIUS} 0 1 1 ${centerX} ${centerY - LOOP_BADGE_RADIUS}`,
2264
- "marker-end": "url(#wb-arrow)",
2265
- class: "wb-loop-badge"
2266
- });
2267
- }
2268
- function frameMarkup(frame) {
2269
- const parts = [tag("rect", {
2270
- x: frame.x,
2271
- y: frame.y,
2272
- width: frame.width,
2273
- height: frame.height,
2274
- rx: 12,
2275
- class: "wb-frame-outline"
2276
- }), text(frame.title, frame.x + 14, frame.y + 18, "wb-frame-title")];
2277
- if (frame.isLoop) parts.push(loopBadgeMarkup(frame));
2278
- return elementGroup(frame, frame.isLoop ? "wb-frame wb-loop" : "wb-frame", parts);
2279
- }
2280
- function wireMarkup(wire) {
2281
- const parts = [
2282
- tag("path", {
2283
- d: wire.path,
2284
- class: "wb-wire-hit"
2285
- }),
2286
- tag("path", {
2287
- d: wire.path,
2288
- "marker-end": wire.hasArrowhead ? "url(#wb-arrow)" : null,
2289
- class: wire.isDashed ? "wb-wire-line wb-dashed" : "wb-wire-line",
2290
- style: laneStroke(wire.strokeHex ?? void 0)
2291
- }),
2292
- tag("circle", {
2293
- cx: wire.start.x,
2294
- cy: wire.start.y,
2295
- r: 3,
2296
- class: "wb-wire-dot"
2297
- })
2298
- ];
2299
- if (wire.joinAt) parts.push(tag("circle", {
2300
- cx: wire.joinAt.x,
2301
- cy: wire.joinAt.y,
2302
- r: 3,
2303
- class: "wb-wire-dot"
2304
- }));
2305
- if (wire.label) parts.push(text(wire.label, wire.labelAt.x, wire.labelAt.y, "wb-wire-label"));
2306
- return elementGroup(wire, wire.isBack ? `wb-wire wb-back wb-tone-${wire.tone}` : `wb-wire wb-tone-${wire.tone}`, parts);
2307
- }
2308
- function noteMarkup(note) {
2309
- const parts = [tag("rect", {
2310
- x: note.x,
2311
- y: note.y,
2312
- width: note.width,
2313
- height: note.height,
2314
- rx: 4,
2315
- class: "wb-note-card"
2316
- })];
2317
- note.lines.forEach((line, index) => {
2318
- parts.push(text(line, note.x + 10, note.y + 22 + index * NOTE_LINE_HEIGHT, "wb-note-text"));
2319
- });
2320
- if (note.byline) parts.push(text(note.byline, note.x + 10, note.y + 22 + note.lines.length * NOTE_LINE_HEIGHT, "wb-note-byline"));
2321
- return elementGroup(note, note.isResolved ? "wb-note wb-resolved" : "wb-note", parts);
2322
- }
2323
- function unitMarkup(unit) {
2324
- const parts = [
2325
- tag("rect", {
2326
- x: unit.x,
2327
- y: unit.y,
2328
- width: unit.width,
2329
- height: unit.height,
2330
- rx: 8,
2331
- class: "wb-unit-outline"
2332
- }),
2333
- text(unit.label, unit.x + BOX_TEXT_INSET, unit.y + UNIT_LABEL_BASELINE, "wb-unit-label"),
2334
- 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" })
2335
- ];
2336
- const titleTop = unit.y + UNIT_LABEL_BASELINE + UNIT_LABEL_HEIGHT;
2337
- unit.titleLines.forEach((line, index) => {
2338
- parts.push(text(line, unit.x + BOX_TEXT_INSET, titleTop + index * TITLE_LINE_HEIGHT, "wb-box-title"));
2339
- });
2340
- const bodyTop = titleTop + unit.titleLines.length * TITLE_LINE_HEIGHT;
2341
- parts.push(...bodyLinesMarkup(unit.bodyLines, unit.x, unit.width, bodyTop));
2342
- 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 }));
2343
- return elementGroup(unit, "wb-unit", parts);
2344
- }
2345
- function elementMarkup(element, assetHref = NO_ASSET_HREF) {
2346
- switch (element.kind) {
2347
- case "box": return boxMarkup(element, assetHref);
2348
- case "frame": return frameMarkup(element);
2349
- case "wire": return wireMarkup(element);
2350
- case "note": return noteMarkup(element);
2351
- case "unit": return unitMarkup(element);
2352
- case "panel": return panelMarkup(element);
2353
- }
2354
- }
2355
- function chromeMarkup(layout) {
2356
- const parts = [];
2357
- if (layout.plan) {
2358
- parts.push(text(PLAN_TITLE, layout.plan.titleAt.x, layout.plan.titleAt.y, "wb-column-title"));
2359
- for (const arrowPath of layout.plan.arrowPaths) parts.push(tag("path", {
2360
- d: arrowPath,
2361
- "marker-end": "url(#wb-arrow)",
2362
- class: "wb-wire-line"
2363
- }));
2364
- }
2365
- for (const band of layout.bands) {
2366
- parts.push(tag("line", {
2367
- x1: band.x,
2368
- y1: band.y,
2369
- x2: band.x + band.width,
2370
- y2: band.y,
2371
- class: "wb-band-rule"
2372
- }));
2373
- if (band.label) parts.push(text(band.label, band.x, band.y + BAND_LABEL_BASELINE, "wb-band-label", { style: `fill:${band.hex}` }));
2374
- }
2375
- for (const column of layout.columns) {
2376
- if (column.titleLines.length === 0) continue;
2377
- column.titleLines.forEach((line, index) => {
2378
- parts.push(text(line, column.x, column.titleBaselineY + index * COLUMN_TITLE_LINE_HEIGHT, "wb-column-title"));
2379
- });
2380
- parts.push(tag("line", {
2381
- x1: column.x,
2382
- y1: column.ruleY,
2383
- x2: column.x + column.width,
2384
- y2: column.ruleY,
2385
- class: "wb-column-rule"
2386
- }));
2387
- }
2388
- for (const entry of layout.legend) parts.push(legendRowMarkup(entry));
2389
- if (layout.caption) parts.push(text(layout.caption.text, layout.caption.x, layout.caption.y + 16, "wb-caption"));
2390
- return tag("g", { class: "wb-chrome" }, parts.join(""));
2391
- }
2392
- function legendSwatchMarkup(entry) {
2393
- const { swatch } = entry;
2394
- if (swatch.kind === "lane") return tag("rect", {
2395
- x: entry.x,
2396
- y: entry.y,
2397
- width: 14,
2398
- height: 14,
2399
- rx: 3,
2400
- class: "wb-legend-swatch",
2401
- style: `fill:${swatch.hex}`
2402
- });
2403
- if (swatch.kind === "status") return tag("rect", {
2404
- x: entry.x,
2405
- y: entry.y,
2406
- width: 14,
2407
- height: 14,
2408
- rx: 3,
2409
- class: `wb-legend-swatch wb-unit-outline wb-unit-${swatch.status}`
2410
- });
2411
- if (swatch.kind === "change") return tag("g", { class: `wb-change-${swatch.change}` }, tag("rect", {
2412
- x: entry.x,
2413
- y: entry.y,
2414
- width: LEGEND_SAMPLE_WIDTH,
2415
- height: 14,
2416
- rx: 3,
2417
- class: "wb-legend-swatch wb-box-outline"
2418
- }));
2419
- const sample = tag("path", {
2420
- d: `M${entry.x},${entry.y + 7} H${entry.x + LEGEND_SAMPLE_WIDTH}`,
2421
- "marker-end": "url(#wb-arrow)",
2422
- class: swatch.isDashed ? "wb-wire-line wb-dashed" : "wb-wire-line"
2423
- });
2424
- return tag("g", { class: swatch.isBack ? `wb-back wb-tone-${swatch.tone}` : `wb-tone-${swatch.tone}` }, sample);
2425
- }
2426
- function legendRowMarkup(entry) {
2427
- const labelX = entry.x + (entry.swatch.kind === "lane" || entry.swatch.kind === "status" ? 22 : 40);
2428
- return legendSwatchMarkup(entry) + text(entry.label, labelX, entry.y + 12, "wb-legend-text");
2429
- }
2430
- function arrowDefinitionsMarkup() {
2431
- return tag("defs", {}, tag("marker", {
2432
- id: "wb-arrow",
2433
- viewBox: "0 0 10 10",
2434
- refX: 9,
2435
- refY: 5,
2436
- markerWidth: 8,
2437
- markerHeight: 8,
2438
- orient: "auto-start-reverse"
2439
- }, tag("path", {
2440
- d: "M 0 1 L 10 5 L 0 9 z",
2441
- fill: "context-stroke"
2442
- })));
2443
- }
2444
- var LAYER_ORDER = [
2445
- "frame",
2446
- "wire",
2447
- "box",
2448
- "panel",
2449
- "note",
2450
- "unit"
2451
- ];
2452
- function boardSvgDocument(layout, assetHref = NO_ASSET_HREF) {
2453
- const { x, y, width, height } = layout.bounds;
2454
- const layers = LAYER_ORDER.map((kind) => tag("g", { class: "wb-layer" }, layout.elements.filter((element) => element.kind === kind).map((element) => elementMarkup(element, assetHref)).join("")));
2455
- const body = [
2456
- tag("style", {}, STANDALONE_STYLE),
2457
- arrowDefinitionsMarkup(),
2458
- tag("rect", {
2459
- x,
2460
- y,
2461
- width,
2462
- height,
2463
- class: "wb-backdrop"
2464
- }),
2465
- chromeMarkup(layout),
2466
- ...layers
2467
- ].join("");
2468
- return `${tag("svg", {
2469
- xmlns: SVG_NAMESPACE,
2470
- viewBox: `${x} ${y} ${width} ${height}`,
2471
- width,
2472
- height
2473
- }, body)}\n`;
2474
- }
2475
- //#endregion
2476
- export { findDependencyCycle as a, cappedWarnings as i, escapeMarkup as n, planSteps as o, layoutBoard as r, unitsOf as s, boardSvgDocument as t };