@ofrnsb/whiteboard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1981 @@
1
+ // src/core/config.ts
2
+ var LEN = {
3
+ prefix: 6,
4
+ short: 12,
5
+ tag: 30,
6
+ id: 40,
7
+ name: 60,
8
+ key: 64,
9
+ label: 80,
10
+ title: 120,
11
+ ident: 128,
12
+ line: 200,
13
+ host: 255,
14
+ message: 300,
15
+ note: 400,
16
+ para: 500,
17
+ detail: 600,
18
+ text: 1e3,
19
+ long: 2e3,
20
+ doc: 4e3,
21
+ instructions: 12e3
22
+ };
23
+ var BOARD = {
24
+ note: { w: 200, h: 120 },
25
+ gap: 16,
26
+ pad: 24,
27
+ head: 48,
28
+ maxNotes: 400,
29
+ maxLinks: 400,
30
+ maxTabs: 12,
31
+ maxRows: 2e3,
32
+ maxCols: 40,
33
+ maxText: 2e3,
34
+ maxInkPoints: 4e3,
35
+ inkWeight: { min: 1, max: 400 },
36
+ coordLimit: 1e5,
37
+ minSize: { mark: { w: 24, h: 16 }, shape: { w: 80, h: 40 }, note: { w: 120, h: 80 } },
38
+ frame: { default: { w: 480, h: 360 }, min: { w: 160, h: 100 } },
39
+ gridSectionsPerRow: 3,
40
+ gridNotesPerRow: 2,
41
+ textRows: 200,
42
+ draw: {
43
+ pad: 24,
44
+ head: 48,
45
+ gapX: 16,
46
+ gapY: 12,
47
+ sectionGap: 40,
48
+ wrapAt: 1150,
49
+ stackSlack: 160,
50
+ aspect: 2.2,
51
+ flowGapX: 56,
52
+ diagramGap: { x: 64, y: 48 },
53
+ belowExisting: 96,
54
+ item: { stack: { w: 560, h: 56 }, grid: { w: 200, h: 88 }, row: { w: 184, h: 80 }, flow: { w: 168, h: 88 }, diagram: { w: 184, h: 72 }, timeline: { w: 200, h: 120 }, matrix: { w: 176, h: 56 } },
55
+ heading: { w: 720, h: 44, step: 52, subH: 28, subStep: 36, titleRoom: 40, titleCharW: 22, stickerGap: 24 },
56
+ /** An emoji card: room for the illustration above the title. */
57
+ iconCard: { extraH: 64 },
58
+ sticker: { w: 112, h: 112, captionH: 28 },
59
+ /** The road: cards alternate above and below a gentle wave; `step` is the distance between milestones. */
60
+ timeline: { step: 136, amp: 34, waveSteps: 2.4, sample: 24, lead: 56, cardGap: 56, pill: { w: 88, h: 32 }, dot: { w: 22, h: 22 }, trackPad: 24, labelH: 32 },
61
+ matrix: { headW: 132, headH: 40, cellW: 208, cellMinH: 96, cellPad: 12, itemGap: 8, gap: 6 },
62
+ /** A hand-composed section: its own space in board units, and the limits on what the agent may place in it. */
63
+ free: { w: 2200, h: 920, titleH: 56, titleGap: 12, titleMinW: 320, titleCharW: 13, itemW: 220, itemH: 120, gap: 24, strokes: 24, points: 80, strokeW: { pena: { s: 3, m: 6, l: 10 }, spidol: { s: 8, m: 14, l: 22 } } },
64
+ /**
65
+ * The marker sketch. Letter widths are Patrick Hand's measured average advance per em (lower and upper case), with a
66
+ * little slack for word wrap. Blocks and loose text come in four sizes; the board measures every item with these
67
+ * same numbers before placing it, so words always fit their outline.
68
+ */
69
+ sketch: {
70
+ lower: 0.36,
71
+ upper: 0.43,
72
+ wrapSlack: 1.12,
73
+ pad: 14,
74
+ gap: 18,
75
+ groupPad: 26,
76
+ groupTitle: 40,
77
+ roundInner: 0.76,
78
+ block: { s: { title: 19, titleLh: 23, text: 16, textLh: 20, icon: 34 }, m: { title: 24, titleLh: 28, text: 20, textLh: 25, icon: 52 }, l: { title: 32, titleLh: 37, text: 24, textLh: 30, icon: 72 }, xl: { title: 44, titleLh: 50, text: 30, textLh: 37, icon: 92 } },
79
+ words: { s: { size: 20, lh: 25, upper: false }, m: { size: 26, lh: 31, upper: false }, l: { size: 32, lh: 37, upper: true }, xl: { size: 46, lh: 50, upper: true } },
80
+ headline: { w: 1500, gapBelow: 10, contextW: 1500, below: 34, iconGap: 28, icon: 96 },
81
+ pillH: 46,
82
+ maxPush: 60
83
+ },
84
+ /**
85
+ * A free board: items where the agent put them, `gap` kept between any two, sticky notes `noteW` wide parked
86
+ * `noteGap` from what they are about. Sticky notes are lettered in the board's own type: about `noteChar` wide
87
+ * per letter at 14px, `noteLh` a line, `noteTop` for the margins.
88
+ */
89
+ tell: {
90
+ widths: { s: 240, m: 300, l: 380, xl: 480 },
91
+ minTextW: 150,
92
+ gap: 56,
93
+ noteW: 230,
94
+ noteMaxW: 330,
95
+ noteGap: 16,
96
+ below: 80,
97
+ minAspect: { diamond: 0.75, triangle: 0.8, pentagon: 0.85, hexagon: 0.5, parallelogram: 0.3 },
98
+ noteChar: 7.2,
99
+ noteLh: 20,
100
+ noteTop: 34,
101
+ notePad: 32,
102
+ maxItems: 40,
103
+ legend: { fact: "black: facts", problem: "red: what goes wrong", action: "green: what we do", insight: "purple: what it means", person: "blue: people and desks", system: "orange: systems and data", note: "yellow notes: what I said while drawing", wires: "black wires: the main flow; each layer of detail below it has its own wire colour (1 blue, 2 teal, 3 violet, 4 orange, 5 magenta, 6 olive, 7 brown, 8 slate, 9 cyan)" }
104
+ },
105
+ sectionItems: 60,
106
+ gridColumns: 6,
107
+ gridColumnsDefault: 2,
108
+ textItemH: 32,
109
+ minFrameW: 280,
110
+ titleCharW: 8,
111
+ minFrameExtraH: 40,
112
+ fit: { charW: 7.2, minLineW: 80, inset: 28, base: 24, lineH: 20, titleGap: 4 }
113
+ },
114
+ /** Sticky notes of a column or grid board (retro, brainstorm): square-ish with large text. */
115
+ sticky: { w: 168, h: 140, top: 30, titleLh: 21, titleCharW: 8.4, byH: 16, charW: 7.2, lh: 20, pad: 32 }
116
+ };
117
+ var COUNT = { xxs: 3, xs: 4, s: 5, sm: 6, ms: 8, m: 10, ml: 12, l: 20, xl: 30, wide: 40, xxl: 50, long: 60, huge: 100, max: 200, bulk: 500, points: 4e3 };
118
+ var BOARD_ARGS = {
119
+ ref: 40,
120
+ why: 200,
121
+ title: { min: 3, max: 120 },
122
+ noteText: 1e3,
123
+ owner: 80,
124
+ due: 40,
125
+ sectionTitle: 120,
126
+ sectionNotes: 60,
127
+ sections: 12,
128
+ cell: 1e3,
129
+ colName: 60,
130
+ options: 40,
131
+ option: 80,
132
+ formula: 200,
133
+ itemTitle: 120,
134
+ itemText: 600,
135
+ gridMax: 12,
136
+ subtitle: 200,
137
+ sectionCols: 6,
138
+ items: 60,
139
+ linkLabel: 60,
140
+ headingTitle: 200,
141
+ headingSubtitle: 300,
142
+ connectors: 80,
143
+ beats: 16,
144
+ beatItems: 40,
145
+ say: 220,
146
+ freeSpan: 2e4,
147
+ kids: 8,
148
+ answer: 320,
149
+ noteIds: 200,
150
+ columns: 40,
151
+ rows: 2e3,
152
+ tabs: 8,
153
+ addNotes: 100,
154
+ moveNotes: 400,
155
+ updates: 200,
156
+ addLinks: 60,
157
+ addColumns: 20,
158
+ addTabs: 6,
159
+ editNote: 120,
160
+ listed: 40
161
+ };
162
+ var LOOSE_NOTES = { perRow: 3, dx: 216, dy: 136 };
163
+ var SECTION_NOTE_INSET = 24;
164
+ var BOARD_EDITS_KEPT = 20;
165
+ var BOARD_CHATS_KEPT = 20;
166
+ var BOARD_HISTORY = { whiteboardEdits: 60, opsMax: 400, opsBytes: 2e5, activityMs: 3e4, stepMs: 900, stepsTotalMs: 12e3, beat: { baseMs: 1600, perItemMs: 320, maxMs: 4800, sayChars: 140 }, cardsPerStep: 2, planMs: 1400, planMax: 200 };
167
+
168
+ // src/core/illustrations.ts
169
+ var ILLUSTRATIONS = [
170
+ // money and documents
171
+ "invoice",
172
+ "receipt",
173
+ "banknote",
174
+ "coin",
175
+ "wallet",
176
+ "credit-card",
177
+ "bank",
178
+ "piggy-bank",
179
+ "safe",
180
+ "cash-register",
181
+ "calculator",
182
+ "ledger",
183
+ "budget",
184
+ "tax",
185
+ "refund",
186
+ "loan",
187
+ "audit",
188
+ "currency-dollar",
189
+ "file-text",
190
+ "file-check",
191
+ "file-spreadsheet",
192
+ "clipboard-check",
193
+ "rubber-stamp",
194
+ "signature",
195
+ // performance and planning
196
+ "trending-up",
197
+ "bar-chart",
198
+ "line-chart",
199
+ "pie-chart",
200
+ "darts",
201
+ "trophy",
202
+ "medal",
203
+ "rocket",
204
+ "bulb",
205
+ "milestone",
206
+ "kanban",
207
+ "layout-dashboard",
208
+ "presentation",
209
+ // time and contact
210
+ "calendar",
211
+ "calendar-check",
212
+ "clock",
213
+ "hourglass",
214
+ "timer",
215
+ "phone",
216
+ "mail",
217
+ "chat",
218
+ "messages",
219
+ "megaphone",
220
+ "bell-ring",
221
+ // people
222
+ "user",
223
+ "users",
224
+ "briefcase",
225
+ "id-card",
226
+ "office-chair",
227
+ // operations and logistics
228
+ "truck",
229
+ "van",
230
+ "forklift",
231
+ "warehouse",
232
+ "factory",
233
+ "store",
234
+ "shopping-cart",
235
+ "cargo-ship",
236
+ "route",
237
+ "map-pin",
238
+ "globe",
239
+ "barcode",
240
+ "archive",
241
+ "toolbox",
242
+ // control and risk
243
+ "alert-triangle",
244
+ "check-circle",
245
+ "shield-check",
246
+ "lock",
247
+ "courthouse",
248
+ "hammer",
249
+ "scale",
250
+ "search",
251
+ "flag",
252
+ "stop-sign",
253
+ "signpost",
254
+ // systems
255
+ "database",
256
+ "server",
257
+ "cloud",
258
+ "settings",
259
+ "refresh",
260
+ "laptop",
261
+ "exchange"
262
+ ];
263
+ var NAMES = new Set(ILLUSTRATIONS);
264
+ var isIllustration = (x) => typeof x === "string" && NAMES.has(x);
265
+
266
+ // src/core/board-geometry.ts
267
+ var POLYGONS = {
268
+ diamond: { pts: [[0.5, 0], [1, 0.5], [0.5, 1], [0, 0.5]], inset: [0.24, 0.22, 0.24, 0.22] },
269
+ triangle: { pts: [[0.5, 0], [1, 1], [0, 1]], inset: [0.46, 0.24, 0.06, 0.24] },
270
+ pentagon: { pts: [[0.5, 0], [1, 0.38], [0.81, 1], [0.19, 1], [0, 0.38]], inset: [0.26, 0.15, 0.06, 0.15] },
271
+ hexagon: { pts: [[0.24, 0], [0.76, 0], [1, 0.5], [0.76, 1], [0.24, 1], [0, 0.5]], inset: [0.08, 0.17, 0.08, 0.17] },
272
+ parallelogram: { pts: [[0.16, 0], [1, 0], [0.84, 1], [0, 1]], inset: [0.06, 0.17, 0.06, 0.17] }
273
+ };
274
+ var isPolygon = (s) => typeof s === "string" && s in POLYGONS;
275
+ var polygonPoints = (p, w, h) => POLYGONS[p].pts.map(([x, y]) => [Math.round(1 + x * (w - 2)), Math.round(1 + y * (h - 2))]);
276
+ var polygonPad = (p, w, h) => {
277
+ const [t, r, b, l] = POLYGONS[p].inset;
278
+ return [Math.round(t * h), Math.round(r * w), Math.round(b * h), Math.round(l * w)];
279
+ };
280
+ function wrapLines(s, charW, width) {
281
+ if (!s) return 0;
282
+ const max = Math.max(40, width);
283
+ let n = 0;
284
+ for (const part of s.split("\n")) {
285
+ let line = 0;
286
+ n += 1;
287
+ for (const word of part.split(/\s+/).filter(Boolean)) {
288
+ const ww = word.length * charW;
289
+ if (line && line + charW + ww > max) {
290
+ n += 1;
291
+ line = 0;
292
+ }
293
+ if (ww > max) {
294
+ n += Math.ceil(ww / max) - 1;
295
+ line = ww % max;
296
+ } else line += (line ? charW : 0) + ww;
297
+ }
298
+ }
299
+ return n;
300
+ }
301
+ var hits = (a, b, gap = 0) => a.x < b.x + b.w + gap && b.x < a.x + a.w + gap && a.y < b.y + b.h + gap && b.y < a.y + a.h + gap;
302
+ var overlaps = (a, list, gap = 0) => list.some((b) => hits(a, b, gap));
303
+ function freeSpot(want, taken, gap, step = 24, reach = 4e3) {
304
+ if (!overlaps(want, taken, gap)) return want;
305
+ for (let r = step; r <= reach; r += step) {
306
+ const ring = [];
307
+ for (let d = -r; d <= r; d += step) ring.push([d, -r], [d, r], [-r, d], [r, d]);
308
+ ring.sort((p, q) => Math.hypot(p[0], p[1]) - Math.hypot(q[0], q[1]) || p[1] - q[1] || p[0] - q[0]);
309
+ for (const [dx, dy] of ring) {
310
+ const b = { ...want, x: want.x + dx, y: want.y + dy };
311
+ if (!overlaps(b, taken, gap)) return b;
312
+ }
313
+ }
314
+ return want;
315
+ }
316
+ var WIRE = { cell: 16, clear: 18, margin: 360, bend: 20, cross: 6, along: 30, away: 8 };
317
+ var labelSize = (label, charW) => ({ w: Math.round(label.length * charW + 24), h: 30 });
318
+ var DX = [0, 1, 0, -1];
319
+ var DY = [-1, 0, 1, 0];
320
+ var Heap = class {
321
+ a = [];
322
+ k = [];
323
+ get size() {
324
+ return this.a.length;
325
+ }
326
+ // Ties break on the node number, so the same board always routes the same way.
327
+ less(i, j) {
328
+ return this.k[i] < this.k[j] || this.k[i] === this.k[j] && this.a[i] < this.a[j];
329
+ }
330
+ swap(i, j) {
331
+ [this.a[i], this.a[j]] = [this.a[j], this.a[i]];
332
+ [this.k[i], this.k[j]] = [this.k[j], this.k[i]];
333
+ }
334
+ push(v, key2) {
335
+ this.a.push(v);
336
+ this.k.push(key2);
337
+ let i = this.a.length - 1;
338
+ while (i > 0) {
339
+ const p = i - 1 >> 1;
340
+ if (!this.less(i, p)) break;
341
+ this.swap(i, p);
342
+ i = p;
343
+ }
344
+ }
345
+ pop() {
346
+ const top = this.a[0], last = this.a.length - 1;
347
+ this.swap(0, last);
348
+ this.a.pop();
349
+ this.k.pop();
350
+ let i = 0;
351
+ for (; ; ) {
352
+ const l = i * 2 + 1, r = l + 1;
353
+ let m = i;
354
+ if (l < this.a.length && this.less(l, m)) m = l;
355
+ if (r < this.a.length && this.less(r, m)) m = r;
356
+ if (m === i) break;
357
+ this.swap(i, m);
358
+ i = m;
359
+ }
360
+ return top;
361
+ }
362
+ };
363
+ var ALONG = {
364
+ ellipse: [[0.5], [0.5], [0.5], [0.5]],
365
+ cloud: [[0.5], [0.5], [0.5], [0.5]],
366
+ diamond: [[0.5], [0.5], [0.5], [0.5]],
367
+ triangle: [[0.5], [], [0.5, 0.3, 0.7], []],
368
+ pentagon: [[0.5], [0.38], [0.5, 0.3, 0.7], [0.38]],
369
+ hexagon: [[0.5, 0.35, 0.65], [0.5], [0.5, 0.35, 0.65], [0.5]],
370
+ parallelogram: [[0.58, 0.35, 0.8], [], [0.42, 0.2, 0.65], []]
371
+ };
372
+ var BOX_ALONG = [[0.5, 0.25, 0.75], [0.5, 0.25, 0.75], [0.5, 0.25, 0.75], [0.5, 0.25, 0.75]];
373
+ var FLAT = /* @__PURE__ */ new Set([void 0, "box", "note", "cylinder", "text"]);
374
+ function ports(b, other) {
375
+ const out = [];
376
+ const along = (b.shape && ALONG[b.shape] || BOX_ALONG).map((fs) => [...fs]);
377
+ if (FLAT.has(b.shape) && FLAT.has(other.shape)) {
378
+ const y0 = Math.max(b.y, other.y), y1 = Math.min(b.y + b.h, other.y + other.h);
379
+ if (y1 - y0 > 24) {
380
+ const f = ((y0 + y1) / 2 - b.y) / b.h;
381
+ along[1].unshift(f);
382
+ along[3].unshift(f);
383
+ }
384
+ const x0 = Math.max(b.x, other.x), x1 = Math.min(b.x + b.w, other.x + other.w);
385
+ if (x1 - x0 > 24) {
386
+ const f = ((x0 + x1) / 2 - b.x) / b.w;
387
+ along[0].unshift(f);
388
+ along[2].unshift(f);
389
+ }
390
+ }
391
+ const dx = other.x + other.w / 2 - (b.x + b.w / 2), dy = other.y + other.h / 2 - (b.y + b.h / 2);
392
+ const facing = [dy < 0, dx > 0, dy > 0, dx < 0];
393
+ along.forEach((fs, side) => fs.forEach((f, k) => {
394
+ const off = (k === 0 ? 0 : 2) + (facing[side] ? 0 : WIRE.away);
395
+ if (side === 0) out.push({ x: b.x + b.w * f, y: b.y, side: 0, off });
396
+ else if (side === 1) out.push({ x: b.x + b.w, y: b.y + b.h * f, side: 1, off });
397
+ else if (side === 2) out.push({ x: b.x + b.w * f, y: b.y + b.h, side: 2, off });
398
+ else out.push({ x: b.x, y: b.y + b.h * f, side: 3, off });
399
+ }));
400
+ return out;
401
+ }
402
+ function routeWires(items, wires, labelW) {
403
+ const out = /* @__PURE__ */ new Map();
404
+ const boxes = [...items.values()];
405
+ const usedH = /* @__PURE__ */ new Set(), usedV = /* @__PURE__ */ new Set();
406
+ const labels = [];
407
+ wires.forEach((wire, i) => {
408
+ const a = items.get(wire.from), c = items.get(wire.to);
409
+ if (!a || !c || wire.from === wire.to) return;
410
+ const pts = routeOne(a, c, boxes, usedH, usedV) ?? fallback(a, c);
411
+ for (let k = 0; k + 3 < pts.length; k += 2) mark(pts[k], pts[k + 1], pts[k + 2], pts[k + 3], usedH, usedV);
412
+ const r = { pts };
413
+ if (wire.label) {
414
+ const spot = labelSpot(pts, labelW(wire.label), [...boxes, ...labels]);
415
+ r.label = spot;
416
+ labels.push(spot);
417
+ }
418
+ out.set(i, r);
419
+ });
420
+ return out;
421
+ }
422
+ var key = (x, y) => `${Math.round(x / WIRE.cell)},${Math.round(y / WIRE.cell)}`;
423
+ function mark(x1, y1, x2, y2, usedH, usedV) {
424
+ const n = Math.max(1, Math.round(Math.hypot(x2 - x1, y2 - y1) / WIRE.cell));
425
+ const set = y1 === y2 ? usedH : usedV;
426
+ for (let s = 0; s <= n; s++) set.add(key(x1 + (x2 - x1) * s / n, y1 + (y2 - y1) * s / n));
427
+ }
428
+ function routeOne(a, c, boxes, usedH, usedV) {
429
+ for (const margin of [WIRE.margin, WIRE.margin * 3]) {
430
+ const r = search(a, c, boxes, usedH, usedV, margin);
431
+ if (r) return r;
432
+ }
433
+ return null;
434
+ }
435
+ function search(a, c, boxes, usedH, usedV, margin) {
436
+ const C = WIRE.cell;
437
+ const x0 = Math.floor((Math.min(a.x, c.x) - margin) / C) * C, y0 = Math.floor((Math.min(a.y, c.y) - margin) / C) * C;
438
+ const x1 = Math.max(a.x + a.w, c.x + c.w) + margin, y1 = Math.max(a.y + a.h, c.y + c.h) + margin;
439
+ const W = Math.ceil((x1 - x0) / C) + 1, H = Math.ceil((y1 - y0) / C) + 1;
440
+ if (W * H > 4e5) return null;
441
+ const cx = (i) => x0 + i * C, cy = (j) => y0 + j * C;
442
+ const blocked = new Uint8Array(W * H);
443
+ for (const b of boxes) {
444
+ if (!hits(b, { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })) continue;
445
+ const i0 = Math.max(0, Math.ceil((b.x - WIRE.clear - x0) / C)), i1 = Math.min(W - 1, Math.floor((b.x + b.w + WIRE.clear - x0) / C));
446
+ const j0 = Math.max(0, Math.ceil((b.y - WIRE.clear - y0) / C)), j1 = Math.min(H - 1, Math.floor((b.y + b.h + WIRE.clear - y0) / C));
447
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) blocked[j * W + i] = 1;
448
+ }
449
+ const exits = (b, other) => ports(b, other).map((p) => {
450
+ let i = Math.round((p.x - x0) / C), j = Math.round((p.y - y0) / C);
451
+ if (p.side === 0 || p.side === 2) i = Math.min(Math.max(i, Math.ceil((b.x + 4 - x0) / C)), Math.floor((b.x + b.w - 4 - x0) / C));
452
+ else j = Math.min(Math.max(j, Math.ceil((b.y + 4 - y0) / C)), Math.floor((b.y + b.h - 4 - y0) / C));
453
+ const px = p.side === 0 || p.side === 2 ? cx(i) : p.x, py = p.side === 1 || p.side === 3 ? cy(j) : p.y;
454
+ const own = { x: b.x - WIRE.clear - 1, y: b.y - WIRE.clear - 1, w: b.w + WIRE.clear * 2 + 2, h: b.h + WIRE.clear * 2 + 2 };
455
+ let steps = 0;
456
+ while (steps === 0 || cx(i) >= own.x && cx(i) <= own.x + own.w && cy(j) >= own.y && cy(j) <= own.y + own.h) {
457
+ i += DX[p.side];
458
+ j += DY[p.side];
459
+ steps++;
460
+ }
461
+ return { i, j, px, py, side: p.side, steps, off: p.off };
462
+ }).filter((e) => e.i >= 0 && e.j >= 0 && e.i < W && e.j < H && !blocked[e.j * W + e.i]);
463
+ const from = exits(a, c), to = exits(c, a);
464
+ if (!from.length || !to.length) return null;
465
+ const goal = /* @__PURE__ */ new Map();
466
+ for (const e of to) {
467
+ const n = e.j * W + e.i, d = (e.side + 2) % 4;
468
+ if (!goal.has(n * 4 + d)) goal.set(n * 4 + d, e);
469
+ }
470
+ const g = new Float64Array(W * H * 4).fill(Infinity), prev = new Int32Array(W * H * 4).fill(-1);
471
+ const start = /* @__PURE__ */ new Map();
472
+ const heap = new Heap();
473
+ const hx = (i, j) => Math.min(...to.map((e) => Math.abs(e.i - i) + Math.abs(e.j - j)));
474
+ for (const e of from) {
475
+ const s2 = (e.j * W + e.i) * 4 + e.side;
476
+ const cost = e.steps + e.off;
477
+ if (cost < g[s2]) {
478
+ g[s2] = cost;
479
+ start.set(s2, e);
480
+ heap.push(s2, cost + hx(e.i, e.j));
481
+ }
482
+ }
483
+ let end = -1;
484
+ while (heap.size) {
485
+ const s2 = heap.pop();
486
+ if (goal.has(s2)) {
487
+ end = s2;
488
+ break;
489
+ }
490
+ const n = s2 >> 2, d = s2 & 3, i = n % W, j = (n - i) / W;
491
+ for (let nd = 0; nd < 4; nd++) {
492
+ if (nd === (d + 2) % 4) continue;
493
+ const ni = i + DX[nd], nj = j + DY[nd];
494
+ if (ni < 0 || nj < 0 || ni >= W || nj >= H || blocked[nj * W + ni]) continue;
495
+ const k = key(cx(ni), cy(nj));
496
+ const horiz = nd === 1 || nd === 3;
497
+ const pen = (horiz ? usedH : usedV).has(k) ? WIRE.along : (horiz ? usedV : usedH).has(k) ? WIRE.cross : 0;
498
+ const t = (nj * W + ni) * 4 + nd, cost = g[s2] + 1 + (nd !== d ? WIRE.bend : 0) + pen;
499
+ if (cost < g[t]) {
500
+ g[t] = cost;
501
+ prev[t] = s2;
502
+ heap.push(t, cost + hx(ni, nj));
503
+ }
504
+ }
505
+ }
506
+ if (end < 0) return null;
507
+ const cells = [];
508
+ let s = end;
509
+ while (s >= 0) {
510
+ const n = s >> 2, i = n % W;
511
+ cells.push([cx(i), cy((n - i) / W)]);
512
+ if (start.has(s)) break;
513
+ s = prev[s];
514
+ }
515
+ cells.reverse();
516
+ const a0 = start.get(s), c0 = goal.get(end);
517
+ const raw = [[a0.px, a0.py], ...cells, [c0.px, c0.py]];
518
+ return simplify(raw);
519
+ }
520
+ function simplify(p) {
521
+ const out = [];
522
+ for (const q of p) {
523
+ if (out.length && out[out.length - 1][0] === q[0] && out[out.length - 1][1] === q[1]) continue;
524
+ if (out.length >= 2) {
525
+ const [ax, ay] = out[out.length - 2], [bx, by] = out[out.length - 1];
526
+ if (ax === bx && bx === q[0] || ay === by && by === q[1]) {
527
+ out[out.length - 1] = q;
528
+ continue;
529
+ }
530
+ }
531
+ out.push(q);
532
+ }
533
+ return out.flat();
534
+ }
535
+ function fallback(a, c) {
536
+ const ax = a.x + a.w / 2, ay = a.y + a.h / 2, cx = c.x + c.w / 2, cy = c.y + c.h / 2;
537
+ if (Math.abs(cx - ax) >= Math.abs(cy - ay)) {
538
+ const x1 = cx > ax ? a.x + a.w : a.x, x2 = cx > ax ? c.x : c.x + c.w, mx = (x1 + x2) / 2;
539
+ return [x1, ay, mx, ay, mx, cy, x2, cy];
540
+ }
541
+ const y1 = cy > ay ? a.y + a.h : a.y, y2 = cy > ay ? c.y : c.y + c.h, my = (y1 + y2) / 2;
542
+ return [ax, y1, ax, my, cx, my, cx, y2];
543
+ }
544
+ function labelSpot(pts, size, avoid) {
545
+ const runs = [];
546
+ for (let k = 0; k + 3 < pts.length; k += 2) runs.push({ x1: pts[k], y1: pts[k + 1], x2: pts[k + 2], y2: pts[k + 3], len: Math.hypot(pts[k + 2] - pts[k], pts[k + 3] - pts[k + 1]) });
547
+ const order = [...runs].sort((p, q) => q.len - p.len);
548
+ const at = (x, y) => ({ x: Math.round(x - size.w / 2), y: Math.round(y - size.h / 2), w: size.w, h: size.h });
549
+ const SHOW = 28;
550
+ for (const r2 of order) {
551
+ const horiz = r2.y1 === r2.y2;
552
+ if (r2.len < (horiz ? size.w : size.h) + SHOW * 2) continue;
553
+ const b = at((r2.x1 + r2.x2) / 2, (r2.y1 + r2.y2) / 2);
554
+ if (!overlaps(b, avoid, 4)) return b;
555
+ }
556
+ for (const r2 of order) {
557
+ const horiz = r2.y1 === r2.y2, mx = (r2.x1 + r2.x2) / 2, my = (r2.y1 + r2.y2) / 2;
558
+ const sides = horiz ? [at(mx, my - size.h / 2 - 6), at(mx, my + size.h / 2 + 6)] : [at(mx + size.w / 2 + 8, my), at(mx - size.w / 2 - 8, my)];
559
+ for (const b of sides) if (!overlaps(b, avoid, 4)) return b;
560
+ }
561
+ const r = order[0];
562
+ return r ? at((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2 - size.h) : at(pts[0], pts[1]);
563
+ }
564
+ function wireBoxes(pts, pad = 6) {
565
+ const out = [];
566
+ for (let k = 0; k + 3 < pts.length; k += 2) {
567
+ const x = Math.min(pts[k], pts[k + 2]), y = Math.min(pts[k + 1], pts[k + 3]);
568
+ out.push({ x: x - pad, y: y - pad, w: Math.abs(pts[k + 2] - pts[k]) + pad * 2, h: Math.abs(pts[k + 3] - pts[k + 1]) + pad * 2 });
569
+ }
570
+ return out;
571
+ }
572
+
573
+ // src/core/line-icons.ts
574
+ var LINE_ICONS = [
575
+ "phone",
576
+ "phone-call",
577
+ "phone-incoming",
578
+ "phone-missed",
579
+ "headset",
580
+ "message-circle",
581
+ "message-square",
582
+ "messages-square",
583
+ "mail",
584
+ "send",
585
+ "bell",
586
+ "megaphone",
587
+ "user",
588
+ "users",
589
+ "user-check",
590
+ "user-x",
591
+ "user-plus",
592
+ "contact",
593
+ "crown",
594
+ "star",
595
+ "heart",
596
+ "handshake",
597
+ "briefcase",
598
+ "building",
599
+ "landmark",
600
+ "store",
601
+ "house",
602
+ "credit-card",
603
+ "wallet",
604
+ "banknote",
605
+ "coins",
606
+ "piggy-bank",
607
+ "receipt",
608
+ "percent",
609
+ "badge-dollar-sign",
610
+ "hand-coins",
611
+ "globe",
612
+ "plane",
613
+ "map-pin",
614
+ "car",
615
+ "database",
616
+ "server",
617
+ "cloud",
618
+ "cpu",
619
+ "bot",
620
+ "brain",
621
+ "sparkles",
622
+ "wand",
623
+ "zap",
624
+ "plug",
625
+ "workflow",
626
+ "network",
627
+ "git-branch",
628
+ "layers",
629
+ "boxes",
630
+ "package",
631
+ "truck",
632
+ "search",
633
+ "list-checks",
634
+ "clipboard-check",
635
+ "clipboard-list",
636
+ "file-text",
637
+ "files",
638
+ "folder",
639
+ "book-open",
640
+ "notebook-pen",
641
+ "pencil",
642
+ "calculator",
643
+ "chart-bar",
644
+ "chart-line",
645
+ "chart-pie",
646
+ "chart-no-axes-combined",
647
+ "trending-up",
648
+ "trending-down",
649
+ "target",
650
+ "gauge",
651
+ "activity",
652
+ "funnel",
653
+ "calendar",
654
+ "calendar-check",
655
+ "calendar-clock",
656
+ "clock",
657
+ "timer",
658
+ "hourglass",
659
+ "repeat",
660
+ "refresh-cw",
661
+ "infinity",
662
+ "rocket",
663
+ "flag",
664
+ "milestone",
665
+ "check",
666
+ "circle-check",
667
+ "x",
668
+ "circle-x",
669
+ "octagon-x",
670
+ "shield",
671
+ "shield-check",
672
+ "lock",
673
+ "key",
674
+ "eye",
675
+ "thumbs-up",
676
+ "thumbs-down",
677
+ "lightbulb",
678
+ "info",
679
+ "scale",
680
+ "gavel",
681
+ "award",
682
+ "trophy",
683
+ "gift",
684
+ "ticket",
685
+ "tag",
686
+ "shopping-cart",
687
+ "smartphone",
688
+ "laptop",
689
+ "monitor",
690
+ "wifi",
691
+ "arrow-right",
692
+ "arrow-down",
693
+ "arrow-up-right",
694
+ "corner-down-right",
695
+ "split",
696
+ "merge",
697
+ "plus",
698
+ "minus",
699
+ "equal",
700
+ "ban",
701
+ "hand",
702
+ "pointer"
703
+ ];
704
+ var NAMES2 = new Set(LINE_ICONS);
705
+ var isLineIcon = (x) => typeof x === "string" && NAMES2.has(x);
706
+
707
+ // src/core/copy.ts
708
+ var ERR = {
709
+ nBarisLagi: (a) => `
710
+ ... ${a} more rows`,
711
+ membuatPapan: "made the board",
712
+ batchNotFound: "That piece of agent work is not in this board's history.",
713
+ batchChangedSince: (who) => `${who.join(", ")} changed the board after the agent did. Undo version by version from History so their changes are not lost.`,
714
+ versionNotKept: (v) => `Version ${v} is no longer kept in this board's history.`,
715
+ luarBagianN: (a) => `Outside sections
716
+ ${a}`
717
+ };
718
+ var WORDS = { yes: "Yes", no: "No", agent: "Agent", untitled: "Untitled", created: "created", you: "You" };
719
+
720
+ // src/core/boards.ts
721
+ var NOTE_COLORS = ["yellow", "blue", "green", "pink", "purple", "gray", "paper", "ink", "red", "outline", "new", "orange", "peach", "sand"];
722
+ var SHAPES = ["note", "box", "text", "ellipse", "cloud", "cylinder", "ink", "track", "pill", "dot", "cell", "sticker", "diamond", "triangle", "pentagon", "hexagon", "parallelogram"];
723
+ var OUTLINED = /* @__PURE__ */ new Set(["box", "ellipse", "cloud", "cylinder", "diamond", "triangle", "pentagon", "hexagon", "parallelogram"]);
724
+ var TEXT_SIZES = ["s", "m", "l", "xl"];
725
+ var BRUSHES = ["pena", "spidol"];
726
+ var ROUTES = ["straight", "elbow", "curve", "auto"];
727
+ var MAX_LAYER = 9;
728
+ var COL_TYPES = ["text", "number", "money", "date", "select", "check"];
729
+ var NOTE_W = BOARD.note.w;
730
+ var NOTE_H = BOARD.note.h;
731
+ var GAP = BOARD.gap;
732
+ var PAD = BOARD.pad;
733
+ var HEAD = BOARD.head;
734
+ var MAX_NOTES = BOARD.maxNotes;
735
+ var MAX_ROWS = BOARD.maxRows;
736
+ var MAX_COLS = BOARD.maxCols;
737
+ var MAX_TEXT = BOARD.maxText;
738
+ function taskShape(b) {
739
+ const tab = b.tabs[0];
740
+ const lane = tab?.columns.find((c) => c.type === "select");
741
+ const title = tab?.columns.find((c) => c.type === "text" && !c.formula);
742
+ if (!tab || !lane || !title) return null;
743
+ return { tab, lane, title, lanes: lane.options ?? [], fields: tab.columns.filter((c) => c.id !== lane.id && c.id !== title.id) };
744
+ }
745
+ function taskBoardOps(o) {
746
+ const cols = [{ id: uid("c"), name: o.title, type: "text" }, { id: uid("c"), name: o.lane, type: "select", options: o.lanes }, ...o.fields.map((f) => ({ ...f, id: uid("c") }))];
747
+ const tid = uid("t");
748
+ const byName = new Map(cols.map((c) => [c.name.toLowerCase(), c.id]));
749
+ return [
750
+ { op: "tab.add", tab: { id: tid, name: o.tab, columns: cols } },
751
+ ...o.cards.map((card) => ({ op: "row.add", tab: tid, row: { id: uid("r"), cells: Object.fromEntries(Object.entries(card).flatMap(([k, v]) => {
752
+ const id = byName.get(k.toLowerCase());
753
+ return id ? [[id, v]] : [];
754
+ })) } }))
755
+ ];
756
+ }
757
+ var noEmoji = (s) => s.replace(/[\p{Extended_Pictographic}\p{Regional_Indicator}\u{FE0F}\u{200D}]/gu, "").replace(/\s{2,}/g, " ").trim();
758
+ function validIcon(s) {
759
+ const t = s?.trim().toLowerCase();
760
+ return isIllustration(t) || isLineIcon(t) ? t : void 0;
761
+ }
762
+ var PENS = ["black", "blue", "green", "red", "purple", "orange"];
763
+ var uid = (prefix) => `${prefix}${Math.random().toString(36).slice(2, 8)}${Date.now().toString(36).slice(-3)}`;
764
+ var clampText = (s) => s.slice(0, MAX_TEXT);
765
+ var finite = (n, d = 0) => typeof n === "number" && Number.isFinite(n) ? Math.max(-BOARD.coordLimit, Math.min(BOARD.coordLimit, n)) : d;
766
+ function frameAt(b, x, y) {
767
+ for (let i = b.frames.length - 1; i >= 0; i--) {
768
+ const f = b.frames[i];
769
+ if (x >= f.x && x <= f.x + f.w && y >= f.y && y <= f.y + f.h) return f.id;
770
+ }
771
+ return null;
772
+ }
773
+ function cellFor(col, v) {
774
+ if (v === null || v === "") return null;
775
+ switch (col.type) {
776
+ case "number":
777
+ case "money": {
778
+ const n = typeof v === "number" ? v : Number(String(v).replace(/\s/g, "").replace(/^Rp/i, "").replace(/\.(?=\d{3}(\D|$))/g, "").replace(",", "."));
779
+ return Number.isFinite(n) ? n : null;
780
+ }
781
+ case "check":
782
+ return v === true || v === 1 || typeof v === "string" && ["true", "ya", "yes", "1", "x", "\u2713"].includes(v.trim().toLowerCase());
783
+ case "date":
784
+ return /^\d{4}-\d{2}-\d{2}/.test(String(v)) ? String(v).slice(0, 10) : null;
785
+ case "select":
786
+ return String(v).slice(0, LEN.label);
787
+ default:
788
+ return clampText(String(v));
789
+ }
790
+ }
791
+ var MARKS = ["text", "ink", "track", "pill", "dot", "cell", "sticker"];
792
+ function minSize(shape) {
793
+ return { ...MARKS.includes(shape) ? BOARD.minSize.mark : shape && OUTLINED.has(shape) ? BOARD.minSize.shape : BOARD.minSize.note };
794
+ }
795
+ function shapeFields(n) {
796
+ const out = {};
797
+ if (n.shape && SHAPES.includes(n.shape) && n.shape !== "note") out.shape = n.shape;
798
+ if (n.title) out.title = noEmoji(n.title).slice(0, LEN.title);
799
+ if (n.size && TEXT_SIZES.includes(n.size)) out.size = n.size;
800
+ const icon = validIcon(n.icon);
801
+ if (icon) out.icon = icon;
802
+ if (n.pen && PENS.includes(n.pen)) out.pen = n.pen;
803
+ if (n.dashed === true) out.dashed = true;
804
+ if (Array.isArray(n.points) && (n.shape === "ink" || n.shape === "track")) out.points = n.points.slice(0, BOARD.maxInkPoints).map((v) => Math.round(finite(v) * 10) / 10);
805
+ if (n.shape === "ink" && n.brush && BRUSHES.includes(n.brush)) out.brush = n.brush;
806
+ if (n.shape === "ink" && typeof n.weight === "number" && Number.isFinite(n.weight)) out.weight = Math.round(Math.min(BOARD.inkWeight.max, Math.max(BOARD.inkWeight.min, n.weight)) * 10) / 10;
807
+ if (Array.isArray(n.pressure) && n.shape === "ink") out.pressure = n.pressure.slice(0, BOARD.maxInkPoints / 2).map((v) => Math.round(Math.min(1, Math.max(0, finite(v))) * 100) / 100);
808
+ return out;
809
+ }
810
+ function linkFields(l) {
811
+ return {
812
+ ...l.label ? { label: l.label.slice(0, LEN.name) } : {},
813
+ ...l.route && ROUTES.includes(l.route) ? { route: l.route } : {},
814
+ ...l.dashed ? { dashed: true } : {},
815
+ ...l.arrow === "both" || l.arrow === "none" ? { arrow: l.arrow } : {},
816
+ ...typeof l.layer === "number" && l.layer >= 1 ? { layer: Math.min(MAX_LAYER, Math.round(l.layer)) } : {}
817
+ };
818
+ }
819
+ function applyOps(board, ops, by, now = (/* @__PURE__ */ new Date()).toISOString()) {
820
+ const b = structuredClone(board);
821
+ const tab = (id) => b.tabs.find((t) => t.id === id);
822
+ for (const o of ops) {
823
+ switch (o.op) {
824
+ case "title":
825
+ b.title = o.title.trim().slice(0, LEN.title) || b.title;
826
+ break;
827
+ case "note.add": {
828
+ if (b.notes.length >= MAX_NOTES || b.notes.some((n) => n.id === o.note.id)) break;
829
+ const x = finite(o.note.x), y = finite(o.note.y);
830
+ const color = NOTE_COLORS.includes(o.note.color) ? o.note.color : "yellow";
831
+ const min = minSize(o.note.shape);
832
+ b.notes.push({
833
+ id: o.note.id,
834
+ text: clampText(o.note.text),
835
+ x,
836
+ y,
837
+ w: Math.max(min.w, finite(o.note.w, NOTE_W) || NOTE_W),
838
+ h: Math.max(min.h, finite(o.note.h, NOTE_H) || NOTE_H),
839
+ color,
840
+ frame: o.note.frame !== void 0 ? o.note.frame : frameAt(b, x + NOTE_W / 2, y + NOTE_H / 2),
841
+ ...o.note.owner ? { owner: o.note.owner.slice(0, LEN.label) } : {},
842
+ ...o.note.due ? { due: o.note.due.slice(0, LEN.id) } : {},
843
+ by,
844
+ ...shapeFields(o.note)
845
+ });
846
+ break;
847
+ }
848
+ case "note.update": {
849
+ const n = b.notes.find((x) => x.id === o.id);
850
+ if (!n) break;
851
+ const p = o.patch;
852
+ if (p.text !== void 0) n.text = clampText(p.text);
853
+ if (p.x !== void 0) n.x = finite(p.x, n.x);
854
+ if (p.y !== void 0) n.y = finite(p.y, n.y);
855
+ const min = minSize(p.shape ?? n.shape);
856
+ if (p.w !== void 0) n.w = Math.max(min.w, finite(p.w, n.w));
857
+ if (p.h !== void 0) n.h = Math.max(min.h, finite(p.h, n.h));
858
+ Object.assign(n, shapeFields({ ...n, ...p }));
859
+ if (p.title === "") delete n.title;
860
+ if (p.color && NOTE_COLORS.includes(p.color)) n.color = p.color;
861
+ if (p.owner !== void 0) n.owner = p.owner?.slice(0, LEN.label) || void 0;
862
+ if (p.due !== void 0) n.due = p.due?.slice(0, LEN.id) || void 0;
863
+ if (p.frame !== void 0) n.frame = p.frame && b.frames.some((f) => f.id === p.frame) ? p.frame : null;
864
+ else if (p.x !== void 0 || p.y !== void 0) n.frame = frameAt(b, n.x + n.w / 2, n.y + n.h / 2);
865
+ break;
866
+ }
867
+ case "note.remove":
868
+ b.notes = b.notes.filter((n) => n.id !== o.id);
869
+ b.links = b.links.filter((l) => l.from !== o.id && l.to !== o.id);
870
+ break;
871
+ case "frame.add":
872
+ if (b.frames.some((f) => f.id === o.frame.id)) break;
873
+ b.frames.push({ id: o.frame.id, title: o.frame.title.slice(0, LEN.title), x: finite(o.frame.x), y: finite(o.frame.y), w: Math.max(BOARD.frame.min.w, finite(o.frame.w, BOARD.frame.default.w)), h: Math.max(BOARD.frame.min.h, finite(o.frame.h, BOARD.frame.default.h)), ...o.frame.subtitle ? { subtitle: o.frame.subtitle.slice(0, 200) } : {} });
874
+ break;
875
+ case "frame.update": {
876
+ const f = b.frames.find((x) => x.id === o.id);
877
+ if (!f) break;
878
+ if (o.patch.title !== void 0) f.title = o.patch.title.slice(0, LEN.title);
879
+ if (o.patch.x !== void 0) f.x = finite(o.patch.x, f.x);
880
+ if (o.patch.y !== void 0) f.y = finite(o.patch.y, f.y);
881
+ if (o.patch.w !== void 0) f.w = Math.max(BOARD.frame.min.w, finite(o.patch.w, f.w));
882
+ if (o.patch.h !== void 0) f.h = Math.max(BOARD.frame.min.h, finite(o.patch.h, f.h));
883
+ if (o.patch.subtitle !== void 0) {
884
+ if (o.patch.subtitle) f.subtitle = o.patch.subtitle.slice(0, LEN.line);
885
+ else delete f.subtitle;
886
+ }
887
+ break;
888
+ }
889
+ case "frame.move": {
890
+ const f = b.frames.find((x) => x.id === o.id);
891
+ if (!f) break;
892
+ const dx = finite(o.dx), dy = finite(o.dy);
893
+ f.x += dx;
894
+ f.y += dy;
895
+ for (const n of b.notes) if (n.frame === f.id) {
896
+ n.x += dx;
897
+ n.y += dy;
898
+ }
899
+ break;
900
+ }
901
+ case "frame.remove":
902
+ b.frames = b.frames.filter((f) => f.id !== o.id);
903
+ b.notes = o.keepNotes === false ? b.notes.filter((n) => n.frame !== o.id) : b.notes.map((n) => n.frame === o.id ? { ...n, frame: null } : n);
904
+ break;
905
+ case "link.add":
906
+ if (b.links.length < BOARD.maxLinks && !b.links.some((l) => l.id === o.link.id) && [o.link.from, o.link.to].every((id) => b.notes.some((n) => n.id === id) || b.frames.some((f) => f.id === id)))
907
+ b.links.push({ id: o.link.id, from: o.link.from, to: o.link.to, ...linkFields(o.link) });
908
+ break;
909
+ case "link.update": {
910
+ const l = b.links.find((x) => x.id === o.id);
911
+ if (!l) break;
912
+ Object.assign(l, linkFields({ ...l, ...o.patch }));
913
+ if (o.patch.label === "") delete l.label;
914
+ break;
915
+ }
916
+ case "link.remove":
917
+ b.links = b.links.filter((l) => l.id !== o.id);
918
+ break;
919
+ case "tab.add":
920
+ if (b.tabs.length < BOARD.maxTabs && !tab(o.tab.id)) b.tabs.push({ id: o.tab.id, name: o.tab.name.slice(0, LEN.name) || `Tab ${b.tabs.length + 1}`, columns: (o.tab.columns ?? []).slice(0, MAX_COLS), rows: [] });
921
+ break;
922
+ case "tab.rename": {
923
+ const t = tab(o.tab);
924
+ if (t) t.name = o.name.slice(0, LEN.name) || t.name;
925
+ break;
926
+ }
927
+ case "tab.remove":
928
+ if (b.tabs.length > 1) b.tabs = b.tabs.filter((t) => t.id !== o.tab);
929
+ break;
930
+ case "col.add": {
931
+ const t = tab(o.tab);
932
+ if (!t || t.columns.length >= MAX_COLS || t.columns.some((c2) => c2.id === o.col.id)) break;
933
+ const c = { ...o.col, name: o.col.name.slice(0, LEN.name), type: COL_TYPES.includes(o.col.type) ? o.col.type : "text" };
934
+ t.columns.splice(o.at ?? t.columns.length, 0, c);
935
+ break;
936
+ }
937
+ case "col.update": {
938
+ const c = tab(o.tab)?.columns.find((x) => x.id === o.id);
939
+ if (!c) break;
940
+ Object.assign(c, o.patch);
941
+ if (!COL_TYPES.includes(c.type)) c.type = "text";
942
+ c.name = c.name.slice(0, LEN.name);
943
+ break;
944
+ }
945
+ case "col.remove": {
946
+ const t = tab(o.tab);
947
+ if (!t) break;
948
+ t.columns = t.columns.filter((c) => c.id !== o.id);
949
+ for (const r of t.rows) delete r.cells[o.id];
950
+ break;
951
+ }
952
+ case "row.add": {
953
+ const t = tab(o.tab);
954
+ if (!t || t.rows.length >= MAX_ROWS || t.rows.some((r) => r.id === o.row.id)) break;
955
+ const cells = {};
956
+ for (const c of t.columns) if (o.row.cells[c.id] !== void 0 && !c.formula) cells[c.id] = cellFor(c, o.row.cells[c.id]);
957
+ t.rows.splice(o.at ?? t.rows.length, 0, { id: o.row.id, cells });
958
+ break;
959
+ }
960
+ case "row.remove": {
961
+ const t = tab(o.tab);
962
+ if (t) t.rows = t.rows.filter((r) => r.id !== o.id);
963
+ break;
964
+ }
965
+ case "restore": {
966
+ const to = structuredClone(o.to);
967
+ b.title = to.title;
968
+ b.frames = to.frames;
969
+ b.notes = to.notes;
970
+ b.links = to.links;
971
+ b.tabs = to.tabs;
972
+ break;
973
+ }
974
+ case "cell.set": {
975
+ const t = tab(o.tab);
976
+ const c = t?.columns.find((x) => x.id === o.col);
977
+ const r = t?.rows.find((x) => x.id === o.row);
978
+ if (c && r && !c.formula) r.cells[c.id] = cellFor(c, o.value);
979
+ break;
980
+ }
981
+ }
982
+ }
983
+ b.version = board.version + 1;
984
+ b.updatedAt = now;
985
+ b.updatedBy = by;
986
+ return b;
987
+ }
988
+ function opKeys(ops) {
989
+ return ops.flatMap((o) => {
990
+ switch (o.op) {
991
+ case "note.add":
992
+ return [o.note.id];
993
+ case "note.update":
994
+ case "note.remove":
995
+ case "frame.update":
996
+ case "frame.move":
997
+ case "frame.remove":
998
+ case "link.remove":
999
+ case "link.update":
1000
+ case "row.remove":
1001
+ return [o.id];
1002
+ case "frame.add":
1003
+ return [o.frame.id];
1004
+ case "cell.set":
1005
+ return [`${o.row}:${o.col}`];
1006
+ case "row.add":
1007
+ return [o.row.id];
1008
+ case "col.add":
1009
+ return [o.col.id];
1010
+ case "col.update":
1011
+ case "col.remove":
1012
+ return [o.id];
1013
+ default:
1014
+ return [];
1015
+ }
1016
+ });
1017
+ }
1018
+ var contentOf = (b) => structuredClone({ version: b.version, title: b.title, frames: b.frames, notes: b.notes, links: b.links, tabs: b.tabs });
1019
+ function historyOf(board) {
1020
+ const from = board.base?.version ?? Infinity;
1021
+ return board.edits.flatMap((e) => e.version === void 0 ? [] : [{
1022
+ version: e.version,
1023
+ at: e.at,
1024
+ by: e.by,
1025
+ agent: e.agent,
1026
+ what: e.what,
1027
+ ...e.why ? { why: e.why } : {},
1028
+ keys: e.keys,
1029
+ replayable: !!e.ops && e.version > from,
1030
+ ...e.batch ? { batch: e.batch } : {},
1031
+ ...e.decided ? { decided: e.decided } : {},
1032
+ ...e.told ? { told: true } : {}
1033
+ }]);
1034
+ }
1035
+ var PLAN_KIND = { note: "card", box: "shape", ellipse: "shape", cloud: "shape", cylinder: "shape", diamond: "shape", triangle: "shape", pentagon: "shape", hexagon: "shape", parallelogram: "shape", text: "text", track: "track", pill: "pill", dot: "dot", cell: "cell", sticker: "sticker" };
1036
+ function planOf(ops, max = 200) {
1037
+ const out = [];
1038
+ for (const o of ops) {
1039
+ if (out.length >= max) break;
1040
+ if (o.op === "frame.add") out.push({ id: o.frame.id, kind: "frame", x: o.frame.x, y: o.frame.y, w: o.frame.w ?? NOTE_W, h: o.frame.h ?? NOTE_H });
1041
+ else if (o.op === "note.add" && o.note.shape !== "ink") {
1042
+ const k = PLAN_KIND[o.note.shape ?? "note"];
1043
+ if (k) out.push({ id: o.note.id, kind: k, x: o.note.x, y: o.note.y, w: o.note.w ?? NOTE_W, h: o.note.h ?? NOTE_H });
1044
+ }
1045
+ }
1046
+ return out;
1047
+ }
1048
+ function pendingBatchOf(board) {
1049
+ const last = [...board.edits].reverse().find((e) => e.agent && e.batch);
1050
+ if (!last?.batch) return null;
1051
+ const mine = board.edits.filter((e) => e.batch === last.batch);
1052
+ if (mine.some((e) => e.decided)) return null;
1053
+ const first = mine[0];
1054
+ return { id: last.batch, by: first.by, what: first.what, ...first.why ? { why: first.why } : {}, keys: [...new Set(mine.flatMap((e) => e.keys))].slice(0, 400), at: last.at };
1055
+ }
1056
+ function boardAt(board, version) {
1057
+ if (version === board.version) return board;
1058
+ const base = board.base;
1059
+ if (!base || version < base.version || version > board.version) return null;
1060
+ let b = { ...structuredClone(board), ...structuredClone(base), activity: void 0 };
1061
+ for (const e of board.edits) {
1062
+ if (e.version === void 0 || e.version <= base.version) continue;
1063
+ if (e.version > version) break;
1064
+ if (!e.ops || e.version !== b.version + 1) return null;
1065
+ b = applyOps(b, e.ops, e.by, e.at);
1066
+ }
1067
+ return b.version === version ? b : null;
1068
+ }
1069
+ function foldIntoBase(base, e, shell) {
1070
+ if (e.version === void 0 || e.version <= base.version || !e.ops) return base;
1071
+ return contentOf(applyOps({ ...shell, ...structuredClone(base) }, e.ops, e.by, e.at));
1072
+ }
1073
+ var CARD_SHAPES = /* @__PURE__ */ new Set([void 0, "note", ...OUTLINED]);
1074
+ function stepsOf(ops, perStep = 6) {
1075
+ const frame = [], road = [], marks = [], cards = [], changes = [], links = [], stickers = [];
1076
+ for (const o of ops) {
1077
+ if (o.op === "frame.add" || o.op === "title") frame.push(o);
1078
+ else if (o.op === "link.add") links.push(o);
1079
+ else if (o.op !== "note.add") changes.push(o);
1080
+ else if (o.note.shape === "text" || o.note.shape === "cell") frame.push(o);
1081
+ else if (o.note.shape === "track") road.push(o);
1082
+ else if (o.note.shape === "pill" || o.note.shape === "dot") marks.push(o);
1083
+ else if (o.note.shape === "sticker") stickers.push(o);
1084
+ else if (CARD_SHAPES.has(o.note.shape)) cards.push(o);
1085
+ else changes.push(o);
1086
+ }
1087
+ const along = road.length > 0;
1088
+ cards.sort((a, b) => along ? a.note.x - b.note.x : Math.round(a.note.y / 40) - Math.round(b.note.y / 40) || a.note.x - b.note.x);
1089
+ const steps = [];
1090
+ if (frame.length) steps.push({ kind: "frame", ops: frame });
1091
+ if (road.length) steps.push({ kind: "road", ops: road });
1092
+ if (marks.length) steps.push({ kind: "marks", ops: marks });
1093
+ for (let i = 0; i < cards.length; i += Math.max(1, perStep)) steps.push({ kind: "cards", ops: cards.slice(i, i + Math.max(1, perStep)) });
1094
+ if (changes.length) steps.push({ kind: "changes", ops: changes });
1095
+ if (links.length) steps.push({ kind: "links", ops: links });
1096
+ if (stickers.length) steps.push({ kind: "stickers", ops: stickers });
1097
+ return steps.length ? steps : [{ kind: "changes", ops }];
1098
+ }
1099
+ var MEANING = [
1100
+ [/baik|berhasil|sukses|lancar|good|well|win|keep/i, "green"],
1101
+ [/kendala|masalah|hambatan|gagal|problem|issue|obstacle|block|challenge/i, "pink"],
1102
+ [/peluang|ide|usul|perbaik|opportunit|idea|improve|try/i, "blue"],
1103
+ [/risiko|bahaya|ancaman|risk|concern|threat/i, "purple"]
1104
+ ];
1105
+ var colorFor = (title, fallback2) => MEANING.find(([re]) => re.test(title))?.[1] ?? fallback2;
1106
+ var DRH = BOARD.draw.heading;
1107
+ function headingOps(ops, h, x, y, id = () => uid("n")) {
1108
+ const top = y;
1109
+ const lines2 = Math.max(1, Math.ceil(h.title.length * DRH.titleCharW / DRH.w));
1110
+ ops.push({ op: "note.add", note: { id: id(), shape: "text", size: "xl", text: noEmoji(h.title).slice(0, LEN.line), x, y, w: DRH.w, h: DRH.h * lines2, color: "paper", frame: null } });
1111
+ let right = x + DRH.w;
1112
+ let subW = DRH.w;
1113
+ const icon = validIcon(h.icon);
1114
+ if (icon) {
1115
+ const sx = x + Math.min(DRH.w, h.title.length * DRH.titleCharW) + DRH.stickerGap;
1116
+ subW = Math.min(DRH.w, sx - x - DRH.stickerGap / 2);
1117
+ ops.push({ op: "note.add", note: { id: id(), shape: "sticker", icon, text: "", x: sx, y: y - BOARD.draw.sticker.h / 4, w: BOARD.draw.sticker.w, h: BOARD.draw.sticker.h, color: "paper", frame: null } });
1118
+ right = Math.max(right, sx + BOARD.draw.sticker.w);
1119
+ }
1120
+ y += DRH.step + (lines2 - 1) * DRH.h;
1121
+ if (h.subtitle) {
1122
+ ops.push({ op: "note.add", note: { id: id(), shape: "text", size: "m", color: "gray", text: noEmoji(h.subtitle).slice(0, LEN.message), x, y, w: subW, h: DRH.subH * (subW < DRH.w ? 2 : 1), frame: null } });
1123
+ y += DRH.subStep + (subW < DRH.w ? DRH.subH : 0);
1124
+ }
1125
+ return { h: y - top + DRH.titleRoom, right };
1126
+ }
1127
+ var STICKY = BOARD.sticky;
1128
+ function layoutOps(sections, layout, origin = { x: 0, y: 0 }, palette = ["yellow", "blue", "green", "pink", "purple"], heading) {
1129
+ const ops = [];
1130
+ const frameIds = [];
1131
+ const perRow = layout === "grid" ? Math.min(BOARD.gridSectionsPerRow, Math.max(1, Math.ceil(Math.sqrt(sections.length)))) : sections.length;
1132
+ const inner = layout === "grid" ? BOARD.gridNotesPerRow : 1;
1133
+ const fw = PAD * 2 + inner * STICKY.w + (inner - 1) * GAP;
1134
+ const top = heading ? headingOps(ops, heading, origin.x, origin.y).h : 0;
1135
+ let x = origin.x, y = origin.y + top, rowH = 0;
1136
+ sections.forEach((s, i) => {
1137
+ if (i > 0 && i % perRow === 0) {
1138
+ x = origin.x;
1139
+ y += rowH + GAP * 2;
1140
+ rowH = 0;
1141
+ }
1142
+ const lines2 = Math.max(1, Math.ceil(s.notes.length / inner));
1143
+ const head = HEAD + (s.subtitle ? BOARD.draw.heading.subH : 0);
1144
+ const textW = STICKY.w - STICKY.pad;
1145
+ const noteH = (n) => Math.max(STICKY.h, STICKY.top + wrapLines(n.title ? noEmoji(n.title) : "", STICKY.titleCharW, textW) * STICKY.titleLh + wrapLines(noEmoji(n.text), STICKY.charW, textW) * STICKY.lh + STICKY.byH);
1146
+ const noteRows = Array.from({ length: lines2 }, (_, r) => Math.max(...s.notes.slice(r * inner, r * inner + inner).map(noteH), STICKY.h));
1147
+ const rowY = noteRows.map((_, r) => noteRows.slice(0, r).reduce((t, v) => t + v + GAP, 0));
1148
+ const fh = head + PAD + noteRows.reduce((t, v) => t + v, 0) + (lines2 - 1) * GAP + PAD;
1149
+ const fid = uid("f");
1150
+ frameIds.push(fid);
1151
+ ops.push({ op: "frame.add", frame: { id: fid, title: s.title, ...s.subtitle ? { subtitle: s.subtitle } : {}, x, y, w: fw, h: fh } });
1152
+ const color = colorFor(s.title, palette[i % palette.length]);
1153
+ s.notes.forEach((n, k) => {
1154
+ const icon = validIcon(n.icon);
1155
+ ops.push({ op: "note.add", note: {
1156
+ id: uid("n"),
1157
+ text: noEmoji(n.text),
1158
+ ...n.title ? { title: noEmoji(n.title) } : {},
1159
+ ...icon ? { icon } : {},
1160
+ size: "m",
1161
+ x: x + PAD + k % inner * (STICKY.w + GAP),
1162
+ y: y + head + rowY[Math.floor(k / inner)],
1163
+ w: STICKY.w,
1164
+ h: noteRows[Math.floor(k / inner)],
1165
+ color: n.color ?? color,
1166
+ frame: fid,
1167
+ ...n.owner ? { owner: n.owner } : {},
1168
+ ...n.due ? { due: n.due } : {}
1169
+ } });
1170
+ });
1171
+ if (layout === "timeline" && i > 0) ops.push({ op: "link.add", link: { id: uid("l"), from: frameIds[i - 1], to: fid } });
1172
+ x += fw + GAP * 2;
1173
+ rowH = Math.max(rowH, fh);
1174
+ });
1175
+ return { ops, frameIds };
1176
+ }
1177
+ function nextOrigin(b) {
1178
+ const right = Math.max(0, ...b.frames.map((f) => f.x + f.w), ...b.notes.map((n) => n.x + n.w));
1179
+ const top = Math.min(0, ...b.frames.map((f) => f.y), ...b.notes.map((n) => n.y));
1180
+ return b.frames.length || b.notes.length ? { x: right + GAP * 4, y: top } : { x: 0, y: 0 };
1181
+ }
1182
+ var STRUCTURE = ["track", "pill", "dot", "cell", "sticker"];
1183
+ function tidyOps(b) {
1184
+ const ops = [];
1185
+ for (const f of b.frames) {
1186
+ const notes = b.notes.filter((n) => n.frame === f.id);
1187
+ if (notes.some((n) => STRUCTURE.includes(n.shape))) continue;
1188
+ const nw = Math.max(NOTE_W, ...notes.map((n) => n.w)), nh = Math.max(NOTE_H, ...notes.map((n) => n.h));
1189
+ const head = HEAD + (f.subtitle ? BOARD.draw.heading.subH : 0);
1190
+ const inner = Math.max(1, Math.floor((f.w - PAD * 2 + GAP) / (nw + GAP)));
1191
+ notes.forEach((n, k) => ops.push({ op: "note.update", id: n.id, patch: { x: f.x + PAD + k % inner * (nw + GAP), y: f.y + head + Math.floor(k / inner) * (nh + GAP), frame: f.id } }));
1192
+ const lines2 = Math.max(1, Math.ceil(notes.length / inner));
1193
+ ops.push({ op: "frame.update", id: f.id, patch: { h: head + PAD + lines2 * nh + (lines2 - 1) * GAP + PAD } });
1194
+ }
1195
+ return ops;
1196
+ }
1197
+ function tokens(src) {
1198
+ const out = [];
1199
+ let i = 0;
1200
+ while (i < src.length) {
1201
+ const ch = src[i];
1202
+ if (/\s/.test(ch)) {
1203
+ i++;
1204
+ continue;
1205
+ }
1206
+ if (ch === "{") {
1207
+ const j = src.indexOf("}", i);
1208
+ if (j < 0) return null;
1209
+ out.push({ t: "ref", v: src.slice(i + 1, j).trim() });
1210
+ i = j + 1;
1211
+ continue;
1212
+ }
1213
+ if ("+-*/()".includes(ch)) {
1214
+ out.push({ t: "op", v: ch });
1215
+ i++;
1216
+ continue;
1217
+ }
1218
+ const m = /^\d+(\.\d+)?/.exec(src.slice(i));
1219
+ if (m) {
1220
+ out.push({ t: "num", v: Number(m[0]) });
1221
+ i += m[0].length;
1222
+ continue;
1223
+ }
1224
+ return null;
1225
+ }
1226
+ return out;
1227
+ }
1228
+ var formulaRefs = (src) => tokens(src)?.flatMap((t) => t.t === "ref" ? [t.v] : []) ?? null;
1229
+ function evalFormula(src, value) {
1230
+ const toks = tokens(src);
1231
+ if (!toks?.length) return null;
1232
+ let p = 0;
1233
+ const peek = () => toks[p];
1234
+ const expr = () => {
1235
+ let l = term();
1236
+ while (l !== null && peek()?.t === "op" && (peek().v === "+" || peek().v === "-")) {
1237
+ const op = toks[p++].v;
1238
+ const r = term();
1239
+ if (r === null) return null;
1240
+ l = op === "+" ? l + r : l - r;
1241
+ }
1242
+ return l;
1243
+ };
1244
+ const term = () => {
1245
+ let l = factor();
1246
+ while (l !== null && peek()?.t === "op" && (peek().v === "*" || peek().v === "/")) {
1247
+ const op = toks[p++].v;
1248
+ const r = factor();
1249
+ if (r === null || op === "/" && r === 0) return null;
1250
+ l = op === "*" ? l * r : l / r;
1251
+ }
1252
+ return l;
1253
+ };
1254
+ const factor = () => {
1255
+ const t = toks[p++];
1256
+ if (!t) return null;
1257
+ if (t.t === "num") return t.v;
1258
+ if (t.t === "ref") return value(t.v);
1259
+ if (t.v === "-") {
1260
+ const v2 = factor();
1261
+ return v2 === null ? null : -v2;
1262
+ }
1263
+ if (t.v === "(") {
1264
+ const v2 = expr();
1265
+ if (toks[p++]?.v !== ")") return null;
1266
+ return v2;
1267
+ }
1268
+ return null;
1269
+ };
1270
+ const v = expr();
1271
+ return p === toks.length && v !== null && Number.isFinite(v) ? Math.round(v * 1e6) / 1e6 : null;
1272
+ }
1273
+ var num = (v) => typeof v === "number" ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : null;
1274
+ function cellValue(t, r, c, seen = /* @__PURE__ */ new Set()) {
1275
+ if (!c.formula) return r.cells[c.id] ?? null;
1276
+ if (seen.has(c.id)) return null;
1277
+ seen.add(c.id);
1278
+ const byName = new Map(t.columns.map((x) => [x.name.toLowerCase(), x]));
1279
+ return evalFormula(c.formula, (name) => {
1280
+ const ref = byName.get(name.toLowerCase());
1281
+ return ref ? num(cellValue(t, r, ref, new Set(seen))) : null;
1282
+ });
1283
+ }
1284
+ function columnTotal(t, c) {
1285
+ if (!c.total) return null;
1286
+ if (c.total === "count") return t.rows.filter((r) => {
1287
+ const v = cellValue(t, r, c);
1288
+ return v !== null && v !== "" && v !== false;
1289
+ }).length;
1290
+ const vals = t.rows.map((r) => num(cellValue(t, r, c))).filter((v) => v !== null);
1291
+ if (!vals.length) return null;
1292
+ const sum = vals.reduce((a, b) => a + b, 0);
1293
+ return c.total === "sum" ? Math.round(sum * 100) / 100 : Math.round(sum / vals.length * 100) / 100;
1294
+ }
1295
+ function tabRows(t) {
1296
+ return { columns: t.columns, rows: t.rows.map((r) => t.columns.map((c) => cellValue(t, r, c))) };
1297
+ }
1298
+ function boardText(b, only, maxRows = BOARD.textRows) {
1299
+ const tasks = b.mode === "tasks" ? taskShape(b) : null;
1300
+ if (tasks) {
1301
+ const { tab, lane, title, lanes, fields } = tasks;
1302
+ const inLane = (l, first) => tab.rows.filter((r) => r.cells[lane.id] === l || first && !lanes.includes(String(r.cells[lane.id])));
1303
+ const card = (r) => `- ${r.id} (#${tab.rows.indexOf(r) + 1}): ${String(r.cells[title.id] ?? "")}${fields.map((f) => r.cells[f.id] === null || r.cells[f.id] === void 0 || r.cells[f.id] === "" ? "" : `; ${f.name}: ${String(r.cells[f.id])}`).join("")}`;
1304
+ return `Lane field "${lane.name}"; lanes in order: ${lanes.join(", ")}
1305
+ ${lanes.map((l, k) => {
1306
+ const cs = inLane(l, k === 0);
1307
+ return `Lane "${l}" (${cs.length})${cs.length ? `
1308
+ ${cs.slice(0, maxRows).map(card).join("\n")}` : ""}`;
1309
+ }).join("\n")}`;
1310
+ }
1311
+ if (b.mode === "sheet" || b.mode === "tasks") {
1312
+ return b.tabs.map((t) => {
1313
+ const { columns, rows } = tabRows(t);
1314
+ const head = columns.map((c) => `${c.name}${c.formula ? ` (=${c.formula})` : ""} [${c.type}] id=${c.id}`).join(" | ");
1315
+ const body2 = rows.slice(0, maxRows).map((r, i) => `${t.rows[i].id}: ${r.map((v) => v === null ? "" : String(v)).join(" | ")}`).join("\n");
1316
+ return `Tab "${t.name}" id=${t.id}, ${t.rows.length} baris
1317
+ Kolom: ${head}
1318
+ ${body2}${t.rows.length > maxRows ? ERR.nBarisLagi(t.rows.length - maxRows) : ""}`;
1319
+ }).join("\n\n");
1320
+ }
1321
+ const drawing = (n) => n.shape === "track" || n.shape === "dot" || n.shape === "cell" && !n.text;
1322
+ const pick = (id) => !only || only.has(id);
1323
+ const line = (n) => `- ${n.id}${n.shape && n.shape !== "note" ? ` [${n.shape}${n.color === "ink" || n.color === "red" ? `, ${n.color}` : ""}]` : ""}: ${n.icon ? `(${n.icon}) ` : ""}${n.title ? `${n.title}: ` : ""}${n.text.replace(/\n/g, " ")}${n.owner ? ` (PJ ${n.owner})` : ""}${n.due ? ` (tenggat ${n.due})` : ""} [oleh ${n.by}]`;
1324
+ const parts = b.frames.filter((f) => pick(f.id) || b.notes.some((n) => n.frame === f.id && pick(n.id))).map((f) => {
1325
+ const ns = b.notes.filter((n) => n.frame === f.id && !drawing(n) && (pick(n.id) || pick(f.id)));
1326
+ return `Bagian "${f.title}"${f.subtitle ? ` (${f.subtitle})` : ""} id=${f.id}
1327
+ ${ns.map(line).join("\n") || "(kosong)"}`;
1328
+ });
1329
+ const loose = b.notes.filter((n) => !n.frame && !drawing(n) && pick(n.id));
1330
+ if (loose.length) parts.push(ERR.luarBagianN(loose.map(line).join("\n")));
1331
+ const name = (id) => b.frames.find((f) => f.id === id)?.title ?? b.notes.find((n) => n.id === id)?.text.slice(0, LEN.id) ?? id;
1332
+ const arrows = b.links.filter((l) => !only || only.has(l.from) || only.has(l.to));
1333
+ if (arrows.length) parts.push(`Panah
1334
+ ${arrows.map((l) => `- ${l.id}: ${l.from} "${name(l.from)}" \u2192 ${l.to} "${name(l.to)}"${l.label ? ` (${l.label})` : ""}${l.route === "straight" ? " lurus" : ""}${l.dashed ? " putus-putus" : ""}`).join("\n")}`);
1335
+ return parts.join("\n\n") || "(empty board)";
1336
+ }
1337
+ function rangeTsv(t, g) {
1338
+ const out = [];
1339
+ for (let r = g.r0; r <= g.r1; r++) {
1340
+ const row = t.rows[r];
1341
+ if (!row) continue;
1342
+ out.push(t.columns.slice(g.c0, g.c1 + 1).map((c) => {
1343
+ const v = cellValue(t, row, c);
1344
+ return v === null ? "" : typeof v === "boolean" ? v ? WORDS.yes : WORDS.no : String(v).replace(/[\t\n\r]+/g, " ");
1345
+ }).join(" "));
1346
+ }
1347
+ return out.join("\n");
1348
+ }
1349
+ function pasteOps(t, g, text, newId = () => uid("r")) {
1350
+ const grid = text.replace(/\r\n?/g, "\n").replace(/\n$/, "").split("\n").slice(0, MAX_ROWS).map((l) => l.split(" "));
1351
+ const one = grid.length === 1 && grid[0].length === 1;
1352
+ const h = one ? g.r1 - g.r0 + 1 : grid.length;
1353
+ const w = Math.min(t.columns.length - g.c0, one ? g.c1 - g.c0 + 1 : Math.max(...grid.map((l) => l.length)));
1354
+ const ops = [];
1355
+ for (let i = 0; i < h; i++) {
1356
+ const cells = {};
1357
+ for (let j = 0; j < w; j++) {
1358
+ const col = t.columns[g.c0 + j];
1359
+ const v = one ? grid[0][0] : grid[i]?.[j];
1360
+ if (col && !col.formula && v !== void 0) cells[col.id] = v.trim() === "" ? null : v;
1361
+ }
1362
+ const row = t.rows[g.r0 + i];
1363
+ if (row) for (const [col, value] of Object.entries(cells)) ops.push({ op: "cell.set", tab: t.id, row: row.id, col, value });
1364
+ else ops.push({ op: "row.add", tab: t.id, row: { id: newId(), cells } });
1365
+ }
1366
+ return { ops, area: { r0: g.r0, r1: g.r0 + h - 1, c0: g.c0, c1: g.c0 + Math.max(0, w - 1) } };
1367
+ }
1368
+ var DR = BOARD.draw;
1369
+ var D_PAD = DR.pad;
1370
+ var HEAD_H = DR.head;
1371
+ var GAP_X = DR.gapX;
1372
+ var GAP_Y = DR.gapY;
1373
+ var SECTION_GAP = DR.sectionGap;
1374
+ var ITEM = DR.item;
1375
+ var DIAGRAM_GAP = DR.diagramGap;
1376
+ function fitH(it, w, base) {
1377
+ const chars = (it.title ? it.title.length + 2 : 0) + (it.text?.length ?? 0);
1378
+ const lines2 = Math.ceil(chars * DR.fit.charW / Math.max(DR.fit.minLineW, w - DR.fit.inset));
1379
+ return Math.max(base, DR.fit.base + lines2 * DR.fit.lineH + (it.title && it.text ? DR.fit.titleGap : 0));
1380
+ }
1381
+ function drawOps(b, spec, ids = () => uid("n")) {
1382
+ const ops = [];
1383
+ const keys = {};
1384
+ const curved = /* @__PURE__ */ new Set();
1385
+ const boxes = [...b.frames, ...b.notes];
1386
+ const x0 = boxes.length ? Math.min(...boxes.map((r) => r.x)) : 0;
1387
+ let y = boxes.length ? Math.max(...boxes.map((r) => r.y + r.h)) + DR.belowExisting : 0;
1388
+ const top = y;
1389
+ let right = x0;
1390
+ if (spec.heading) {
1391
+ const hd = headingOps(ops, spec.heading, x0, y, ids);
1392
+ for (const o of ops) if (o.op === "note.add" && o.note.shape === "text") o.note.pen = "black";
1393
+ y += hd.h;
1394
+ right = Math.max(right, hd.right);
1395
+ }
1396
+ const lay = (sec, items, fx, fy, into, k, cv, mk) => sec.layout === "free" ? freeOps(into, sec, items, fx, fy, mk, k) : sec.layout === "timeline" ? timelineOps(into, sec, items, fx, fy, mk, k) : sec.layout === "matrix" ? matrixOps(into, sec, items, fx, fy, mk, k, cv) : boxesOps(into, sec, items, fx, fy, mk, k);
1397
+ const lone = !!spec.heading && spec.sections.length === 1;
1398
+ const drawn = spec.sections.map((s0) => {
1399
+ const sec = lone ? { ...s0, title: "" } : s0;
1400
+ const items = sec.items.slice(0, DR.sectionItems);
1401
+ return { sec, items, size: lay(sec, items, 0, 0, [], {}, /* @__PURE__ */ new Set(), () => "m") };
1402
+ });
1403
+ const n = drawn.length;
1404
+ const avgW = drawn.reduce((t, d) => t + d.size.w, 0) / Math.max(1, n), avgH = drawn.reduce((t, d) => t + d.size.h, 0) / Math.max(1, n);
1405
+ const perRow = Math.max(1, Math.min(n, Math.round(Math.sqrt(n * DR.aspect * avgH / Math.max(1, avgW)))));
1406
+ const rows = [];
1407
+ for (const d of drawn) {
1408
+ const last = rows[rows.length - 1];
1409
+ if (last && (d.sec.beside === true || d.sec.beside === void 0 && last.length < perRow)) last.push(d);
1410
+ else rows.push([d]);
1411
+ }
1412
+ let rowY = y;
1413
+ for (const row of rows) {
1414
+ let fx = x0;
1415
+ for (const d of row) {
1416
+ const { w } = lay(d.sec, d.items, fx, rowY, ops, keys, curved, ids);
1417
+ right = Math.max(right, fx + w);
1418
+ fx += w + SECTION_GAP;
1419
+ }
1420
+ rowY += Math.max(...row.map((d) => d.size.h)) + SECTION_GAP;
1421
+ }
1422
+ const bottom = rowY - SECTION_GAP;
1423
+ for (const c of spec.connectors ?? []) {
1424
+ const from = keys[c.from], to = keys[c.to];
1425
+ if (!from || !to || from === to) continue;
1426
+ const route2 = c.route ?? (curved.has(from) || curved.has(to) ? "curve" : "elbow");
1427
+ ops.push({ op: "link.add", link: { id: uid("l"), from, to, ...c.label ? { label: c.label } : {}, route: route2, ...c.dashed ? { dashed: true } : {}, ...c.arrow && c.arrow !== "end" ? { arrow: c.arrow } : {} } });
1428
+ }
1429
+ return { ops, keys, area: { x: x0, y: top, w: right - x0, h: bottom - top } };
1430
+ }
1431
+ var STK = DR.sticker;
1432
+ var stickerH = (it) => STK.h + (it.text ? STK.captionH : 0);
1433
+ var cardH = (it, w, base) => fitH(it, w, base) + (validIcon(it.icon) ? DR.iconCard.extraH : 0);
1434
+ function itemNote(it, id, shape, color, x, y, w, h, frame) {
1435
+ const icon = validIcon(it.icon);
1436
+ return { op: "note.add", note: {
1437
+ id,
1438
+ shape,
1439
+ text: noEmoji(it.text ?? "").slice(0, MAX_TEXT),
1440
+ ...it.title ? { title: noEmoji(it.title) } : {},
1441
+ ...icon ? { icon } : {},
1442
+ ...it.size ? { size: it.size } : {},
1443
+ color,
1444
+ x,
1445
+ y,
1446
+ w,
1447
+ h,
1448
+ frame,
1449
+ ...it.pen ? { pen: it.pen } : {},
1450
+ ...it.dashed ? { dashed: true } : {},
1451
+ ...it.owner ? { owner: it.owner } : {},
1452
+ ...it.due ? { due: it.due } : {}
1453
+ } };
1454
+ }
1455
+ function smoothPoints(pts, per = 8) {
1456
+ if (pts.length < 3) return pts.map(([x, y]) => [x, y]);
1457
+ const out = [];
1458
+ for (let i = 0; i < pts.length - 1; i++) {
1459
+ const p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)];
1460
+ for (let k = 0; k < per; k++) {
1461
+ const t = k / per, t2 = t * t, t3 = t2 * t;
1462
+ out.push([0, 1].map((a) => 0.5 * (2 * p1[a] + (p2[a] - p0[a]) * t + (2 * p0[a] - 5 * p1[a] + 4 * p2[a] - p3[a]) * t2 + (3 * p1[a] - p0[a] - 3 * p2[a] + p3[a]) * t3)));
1463
+ }
1464
+ }
1465
+ out.push([pts[pts.length - 1][0], pts[pts.length - 1][1]]);
1466
+ return out;
1467
+ }
1468
+ function markStrokes(kind, bx, by, bw, bh) {
1469
+ const cx = bx + bw / 2, cy = by + bh / 2;
1470
+ if (kind === "ring") {
1471
+ const rx = bw / 2 + Math.max(14, bw * 0.09), ry = bh / 2 + Math.max(12, bh * 0.16), n = 30;
1472
+ return [Array.from({ length: n + 1 }, (_, i) => {
1473
+ const a = -2 + i / n * Math.PI * 2.14, k = 1 + 0.03 * Math.sin(i * 1.7) - i / n * 0.05;
1474
+ return [cx + rx * k * Math.cos(a), cy + ry * k * Math.sin(a)];
1475
+ })];
1476
+ }
1477
+ if (kind === "underline") return [Array.from({ length: 9 }, (_, i) => [bx + bw * i / 8, by + bh + 8 + 3 * Math.sin(i * 1.3)])];
1478
+ if (kind === "highlight") return [Array.from({ length: 5 }, (_, i) => [bx - 6 + (bw + 12) * i / 4, cy + 2 * Math.sin(i * 2.1)])];
1479
+ if (kind === "tick") return [[[bx - 34, cy], [bx - 24, cy + 14], [bx - 4, cy - 16]]];
1480
+ return [[[bx + bw * 0.12, by + bh * 0.12], [bx + bw * 0.88, by + bh * 0.88]], [[bx + bw * 0.88, by + bh * 0.12], [bx + bw * 0.12, by + bh * 0.88]]];
1481
+ }
1482
+ function freeOps(ops, sec, items, fx, fy, ids, keys) {
1483
+ const F = DR.free;
1484
+ const clamp = (n, max) => Math.max(0, Math.min(max, Math.round(n)));
1485
+ let right = Math.min(F.w, sec.title.length * F.titleCharW), bottom = F.titleH;
1486
+ if (sec.title.trim()) ops.push({ op: "note.add", note: { id: ids(), shape: "text", size: "l", pen: "black", text: noEmoji(sec.title).slice(0, LEN.title), color: "paper", x: fx, y: fy, w: Math.max(F.titleMinW, right), h: F.titleH - F.titleGap, frame: null } });
1487
+ let auto = 0;
1488
+ const boxes = /* @__PURE__ */ new Map();
1489
+ const placed = [];
1490
+ for (const it of items) {
1491
+ const [bx, by, bw, bh] = it.box ?? [auto++ * (F.itemW + F.gap), F.h, F.itemW, F.itemH];
1492
+ const shape = it.shape ?? "box";
1493
+ const min = minSize(shape);
1494
+ const w = Math.max(min.w, clamp(bw, F.w)), h = shape === "sticker" ? Math.max(min.h, clamp(bh, F.h)) : Math.max(min.h, clamp(bh, F.h), shape === "text" ? 0 : cardH(it, w, 0));
1495
+ const spot = freeSpot({ x: clamp(bx, F.w), y: clamp(by, F.h + F.itemH) + F.titleH, w, h }, placed, F.gap / 2);
1496
+ placed.push(spot);
1497
+ const x = spot.x, y = spot.y;
1498
+ const id = ids();
1499
+ if (it.key) {
1500
+ keys[it.key] = id;
1501
+ boxes.set(it.key, [x, y - F.titleH, w, h]);
1502
+ }
1503
+ const sketched = shape !== "note" && shape !== "sticker";
1504
+ ops.push(itemNote(sketched ? { ...it, pen: it.pen ?? "black" } : it, id, shape, it.color ?? (shape === "note" ? "yellow" : "paper"), fx + x, fy + y, w, h, null));
1505
+ right = Math.max(right, x + w);
1506
+ bottom = Math.max(bottom, y + h);
1507
+ }
1508
+ const ink = (pts, color, size, marker) => {
1509
+ if (pts.length < 2) return;
1510
+ const brush = marker ? "spidol" : "pena";
1511
+ const m = F.strokeW[brush][size] * 2;
1512
+ const x0 = Math.min(...pts.map((q) => q[0])), y0 = Math.min(...pts.map((q) => q[1])), x1 = Math.max(...pts.map((q) => q[0])), y1 = Math.max(...pts.map((q) => q[1]));
1513
+ ops.push({ op: "note.add", note: { id: ids(), shape: "ink", brush, size, text: "", color: color === "black" || !color ? "ink" : color, x: fx + x0 - m, y: fy + F.titleH + y0 - m, w: x1 - x0 + m * 2, h: y1 - y0 + m * 2, frame: null, points: pts.flatMap(([px, py]) => [Math.round((px - x0 + m) * 10) / 10, Math.round((py - y0 + m) * 10) / 10]) } });
1514
+ right = Math.max(right, x1 + m);
1515
+ bottom = Math.max(bottom, F.titleH + y1 + m);
1516
+ };
1517
+ for (const st of (sec.strokes ?? []).slice(0, F.strokes)) ink(smoothPoints(st.points.slice(0, F.points).map(([px, py]) => [clamp(px, F.w), clamp(py, F.h)])), st.color, st.width ?? "m", !!st.marker);
1518
+ for (const mk of (sec.marks ?? []).slice(0, F.strokes)) {
1519
+ const b = boxes.get(mk.on);
1520
+ if (!b) continue;
1521
+ for (const pts of markStrokes(mk.kind, ...b)) ink(smoothPoints(pts), mk.color ?? (mk.kind === "highlight" ? "yellow" : "red"), mk.kind === "highlight" ? "l" : "m", mk.kind === "highlight");
1522
+ }
1523
+ return { w: right, h: bottom };
1524
+ }
1525
+ function boxesOps(ops, sec, items, fx, fy, ids, keys) {
1526
+ const layout = sec.layout;
1527
+ const base = ITEM[layout];
1528
+ const cols = layout === "grid" ? Math.max(1, Math.min(DR.gridColumns, sec.columns ?? DR.gridColumnsDefault)) : layout === "stack" ? 1 : items.length;
1529
+ const size = (it) => it.shape === "sticker" ? { w: STK.w, h: stickerH(it) } : { w: base.w, h: it.shape === "text" ? DR.textItemH : cardH(it, base.w, base.h) };
1530
+ const placed = [];
1531
+ if (layout === "diagram") {
1532
+ for (const it of items) {
1533
+ const [c, r] = it.at ?? [placed.length, 0];
1534
+ const sz = size(it);
1535
+ placed.push({ it, x: D_PAD + Math.max(0, c) * (base.w + DIAGRAM_GAP.x), y: HEAD_H + Math.max(0, r) * (base.h + DIAGRAM_GAP.y), ...sz });
1536
+ }
1537
+ } else {
1538
+ const gapX = layout === "flow" ? DR.flowGapX : GAP_X;
1539
+ let cy = HEAD_H;
1540
+ for (let i = 0; i < items.length; i += cols) {
1541
+ const line = items.slice(i, i + cols);
1542
+ const lh = Math.max(...line.map((it) => size(it).h));
1543
+ line.forEach((it, k) => placed.push({ it, x: D_PAD + k * (base.w + gapX), y: cy, w: size(it).w, h: it.shape === "sticker" ? size(it).h : lh }));
1544
+ cy += lh + GAP_Y;
1545
+ }
1546
+ }
1547
+ const w = Math.max(DR.minFrameW, ...placed.map((p) => p.x + p.w + D_PAD), D_PAD * 2 + sec.title.length * DR.titleCharW);
1548
+ const h = Math.max(HEAD_H + DR.minFrameExtraH, ...placed.map((p) => p.y + p.h + D_PAD));
1549
+ const fid = uid("f");
1550
+ if (sec.key) keys[sec.key] = fid;
1551
+ ops.push({ op: "frame.add", frame: { id: fid, title: sec.title.slice(0, LEN.title), ...sec.subtitle ? { subtitle: sec.subtitle } : {}, x: fx, y: fy, w, h } });
1552
+ const inSection = [];
1553
+ for (const p of placed) {
1554
+ const id = ids();
1555
+ if (p.it.key) keys[p.it.key] = id;
1556
+ inSection.push(id);
1557
+ const shape = p.it.shape ?? (layout === "stack" || layout === "flow" || layout === "diagram" ? "box" : "note");
1558
+ ops.push(itemNote(p.it, id, shape, p.it.color ?? (shape === "note" ? "yellow" : "paper"), fx + p.x, fy + p.y, p.w, p.h, fid));
1559
+ }
1560
+ if (layout === "flow") for (let i = 1; i < inSection.length; i++) ops.push({ op: "link.add", link: { id: uid("l"), from: inSection[i - 1], to: inSection[i] } });
1561
+ return { w, h };
1562
+ }
1563
+ var TL = DR.timeline;
1564
+ var WARM = ["sand", "peach", "orange", "yellow"];
1565
+ function timelineOps(ops, sec, items, fx, fy, ids, keys) {
1566
+ const base = ITEM.timeline;
1567
+ const cards = items.filter((it) => it.shape !== "sticker");
1568
+ let oy = 0;
1569
+ if (sec.title) {
1570
+ ops.push({ op: "note.add", note: { id: ids(), shape: "text", size: "l", text: sec.title.slice(0, LEN.title), x: fx, y: fy, w: Math.max(DR.minFrameW, sec.title.length * DR.titleCharW * 2), h: TL.labelH, color: "paper", frame: null } });
1571
+ oy = TL.labelH + GAP_Y;
1572
+ }
1573
+ const heights = new Map(cards.map((it) => [it, cardH(it, base.w, base.h)]));
1574
+ const above = cards.filter((_, k) => k % 2 === 0), below = cards.filter((_, k) => k % 2 === 1);
1575
+ const ha = Math.max(0, ...above.map((it) => heights.get(it)));
1576
+ const hb = Math.max(0, ...below.map((it) => heights.get(it)));
1577
+ const road = oy + ha + TL.cardGap + TL.amp;
1578
+ const wave = (x) => road + TL.amp * Math.sin(2 * Math.PI * x / (TL.step * TL.waveSteps));
1579
+ const cx = (i) => TL.lead + base.w / 2 + i * TL.step;
1580
+ const width = cx(Math.max(0, items.length - 1)) + base.w / 2 + TL.lead;
1581
+ const ty = road - TL.amp - TL.trackPad;
1582
+ const points = [];
1583
+ for (let x = 0; x <= width; x += TL.sample) points.push(Math.round(x * 10) / 10, Math.round((wave(x) - ty) * 10) / 10);
1584
+ points.push(Math.round(width * 10) / 10, Math.round((wave(width) - ty) * 10) / 10);
1585
+ const track = ids();
1586
+ if (sec.key) keys[sec.key] = track;
1587
+ ops.push({ op: "note.add", note: { id: track, shape: "track", text: "", points, x: fx, y: fy + ty, w: width, h: 2 * (TL.amp + TL.trackPad), color: "sand", frame: null } });
1588
+ let card = 0, prevPill = null;
1589
+ items.forEach((it, i) => {
1590
+ const x = cx(i), yc = wave(x);
1591
+ if (it.shape === "sticker") {
1592
+ const id2 = ids();
1593
+ if (it.key) keys[it.key] = id2;
1594
+ const sh = stickerH(it);
1595
+ ops.push(itemNote(it, id2, "sticker", "paper", fx + x - STK.w / 2, fy + yc - STK.h + TL.trackPad, STK.w, sh, null));
1596
+ return;
1597
+ }
1598
+ if (prevPill !== null) {
1599
+ const mx = (prevPill + x) / 2;
1600
+ ops.push({ op: "note.add", note: { id: ids(), shape: "dot", text: "", x: fx + mx - TL.dot.w / 2, y: fy + wave(mx) - TL.dot.h / 2, w: TL.dot.w, h: TL.dot.h, color: "paper", frame: null } });
1601
+ }
1602
+ prevPill = x;
1603
+ const pill = ids();
1604
+ ops.push({ op: "note.add", note: { id: pill, shape: "pill", text: (it.when ?? String(card + 1)).slice(0, LEN.label), x: fx + x - TL.pill.w / 2, y: fy + yc - TL.pill.h / 2, w: TL.pill.w, h: TL.pill.h, color: "red", frame: null } });
1605
+ const hgt = heights.get(it);
1606
+ const up = card % 2 === 0;
1607
+ const top = up ? road - TL.amp - TL.cardGap - hgt : road + TL.amp + TL.cardGap;
1608
+ const id = ids();
1609
+ if (it.key) keys[it.key] = id;
1610
+ ops.push(itemNote(it, id, it.shape ?? "note", it.color ?? WARM[card % WARM.length], fx + x - base.w / 2, fy + top, base.w, hgt, null));
1611
+ ops.push({ op: "link.add", link: { id: uid("l"), from: id, to: pill, route: "straight", arrow: "none" } });
1612
+ card++;
1613
+ });
1614
+ return { w: width, h: road + TL.amp + TL.cardGap + hb };
1615
+ }
1616
+ function extendTimelineOps(b, items, trackId, ids = () => uid("n")) {
1617
+ const roads = b.notes.filter((n) => n.shape === "track");
1618
+ const track = (trackId ? roads.find((n) => n.id === trackId) : null) ?? roads.at(-1);
1619
+ if (!track || !items.length) return null;
1620
+ const base = ITEM.timeline;
1621
+ const period = TL.step * TL.waveSteps;
1622
+ const road = track.y + TL.amp + TL.trackPad;
1623
+ const wave = (rel) => road + TL.amp * Math.sin(2 * Math.PI * rel / period);
1624
+ const along = (n) => n.x + n.w / 2 - track.x;
1625
+ const onRoad = b.notes.filter((n) => (n.shape === "pill" || n.shape === "sticker") && along(n) >= 0 && along(n) <= track.w + base.w && Math.abs(n.y + n.h / 2 - road) <= TL.amp + base.h);
1626
+ const index = (rel) => Math.round((rel - TL.lead - base.w / 2) / TL.step);
1627
+ let next = onRoad.length ? Math.max(...onRoad.map((n) => index(along(n)))) + 1 : 0;
1628
+ let cards = onRoad.filter((n) => n.shape === "pill").length;
1629
+ let prevPill = onRoad.filter((n) => n.shape === "pill").reduce((m, n) => m === null || along(n) > m ? along(n) : m, null);
1630
+ const cx = (i) => TL.lead + base.w / 2 + i * TL.step;
1631
+ const ops = [];
1632
+ const keys = {};
1633
+ for (const it of items) {
1634
+ const x = cx(next), yc = wave(x);
1635
+ next += 1;
1636
+ if (it.shape === "sticker") {
1637
+ const id2 = ids();
1638
+ if (it.key) keys[it.key] = id2;
1639
+ ops.push(itemNote(it, id2, "sticker", "paper", track.x + x - STK.w / 2, yc - STK.h + TL.trackPad, STK.w, stickerH(it), null));
1640
+ continue;
1641
+ }
1642
+ if (prevPill !== null) {
1643
+ const mx = (prevPill + x) / 2;
1644
+ ops.push({ op: "note.add", note: { id: ids(), shape: "dot", text: "", x: track.x + mx - TL.dot.w / 2, y: wave(mx) - TL.dot.h / 2, w: TL.dot.w, h: TL.dot.h, color: "paper", frame: null } });
1645
+ }
1646
+ prevPill = x;
1647
+ const pill = ids();
1648
+ ops.push({ op: "note.add", note: { id: pill, shape: "pill", text: (it.when ?? String(cards + 1)).slice(0, LEN.label), x: track.x + x - TL.pill.w / 2, y: yc - TL.pill.h / 2, w: TL.pill.w, h: TL.pill.h, color: "red", frame: null } });
1649
+ const hgt = cardH(it, base.w, base.h);
1650
+ const top = cards % 2 === 0 ? road - TL.amp - TL.cardGap - hgt : road + TL.amp + TL.cardGap;
1651
+ const id = ids();
1652
+ if (it.key) keys[it.key] = id;
1653
+ ops.push(itemNote(it, id, it.shape ?? "note", it.color ?? WARM[cards % WARM.length], track.x + x - base.w / 2, top, base.w, hgt, null));
1654
+ ops.push({ op: "link.add", link: { id: uid("l"), from: id, to: pill, route: "straight", arrow: "none" } });
1655
+ cards++;
1656
+ }
1657
+ const width = cx(next - 1) + base.w / 2 + TL.lead;
1658
+ if (width > track.w) {
1659
+ const ty = track.y;
1660
+ const points = [];
1661
+ for (let x = 0; x <= width; x += TL.sample) points.push(Math.round(x * 10) / 10, Math.round((wave(x) - ty) * 10) / 10);
1662
+ points.push(Math.round(width * 10) / 10, Math.round((wave(width) - ty) * 10) / 10);
1663
+ ops.unshift({ op: "note.update", id: track.id, patch: { w: width, points } });
1664
+ }
1665
+ return { ops, keys };
1666
+ }
1667
+ var MX = DR.matrix;
1668
+ var headerIndex = (v, list) => typeof v === "number" ? Number.isInteger(v) && v >= 0 && v < list.length ? v : -1 : v === void 0 ? -1 : list.findIndex((x) => x.toLowerCase() === v.trim().toLowerCase());
1669
+ function matrixOps(ops, sec, items, fx, fy, ids, keys, curved) {
1670
+ const named = (k) => [...new Set(items.map((it) => it.cell?.[k]).filter((v) => typeof v === "string" && !!v.trim()))];
1671
+ const across = (sec.across?.length ? sec.across : named(0)).slice(0, DR.gridColumns + 1);
1672
+ const down = (sec.down?.length ? sec.down : named(1)).slice(0, DR.sectionItems);
1673
+ const cols = Math.max(1, across.length), rows = Math.max(1, down.length);
1674
+ const iw = MX.cellW - MX.cellPad * 2;
1675
+ const inCell = Array.from({ length: cols * rows }, () => []);
1676
+ for (const it of items) {
1677
+ const c = Math.max(0, headerIndex(it.cell?.[0], across)), r = Math.max(0, headerIndex(it.cell?.[1], down));
1678
+ inCell[r * cols + c].push(it);
1679
+ }
1680
+ const hOf = (it) => it.shape === "sticker" ? stickerH(it) : cardH(it, iw, ITEM.matrix.h);
1681
+ const rowH = Array.from({ length: rows }, (_, r) => Math.max(MX.cellMinH, ...Array.from({ length: cols }, (_2, c) => {
1682
+ const list = inCell[r * cols + c];
1683
+ return MX.cellPad * 2 + list.reduce((a, it) => a + hOf(it), 0) + Math.max(0, list.length - 1) * MX.itemGap;
1684
+ })));
1685
+ const left = D_PAD + (down.length ? MX.headW + MX.gap : 0);
1686
+ const topY = HEAD_H + (across.length ? MX.headH + MX.gap : 0);
1687
+ const colX = (c) => left + c * (MX.cellW + MX.gap);
1688
+ const rowY = [];
1689
+ rowH.reduce((y, h2, r) => {
1690
+ rowY[r] = y;
1691
+ return y + h2 + MX.gap;
1692
+ }, topY);
1693
+ const w = Math.max(DR.minFrameW, colX(cols) - MX.gap + D_PAD);
1694
+ const h = rowY[rows - 1] + rowH[rows - 1] + D_PAD;
1695
+ const fid = uid("f");
1696
+ if (sec.key) keys[sec.key] = fid;
1697
+ ops.push({ op: "frame.add", frame: { id: fid, title: sec.title.slice(0, LEN.title), ...sec.subtitle ? { subtitle: sec.subtitle } : {}, x: fx, y: fy, w, h } });
1698
+ across.forEach((t, c) => ops.push({ op: "note.add", note: { id: ids(), shape: "pill", text: t.slice(0, LEN.label), x: fx + colX(c), y: fy + HEAD_H, w: MX.cellW, h: MX.headH, color: "blue", frame: fid } }));
1699
+ down.forEach((t, r) => ops.push({ op: "note.add", note: { id: ids(), shape: "pill", text: t.slice(0, LEN.label), x: fx + D_PAD, y: fy + rowY[r] + (rowH[r] - MX.headH) / 2, w: MX.headW, h: MX.headH, color: "blue", frame: fid } }));
1700
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
1701
+ ops.push({ op: "note.add", note: { id: ids(), shape: "cell", text: "", x: fx + colX(c), y: fy + rowY[r], w: MX.cellW, h: rowH[r], color: "paper", frame: fid } });
1702
+ let cy = rowY[r] + MX.cellPad;
1703
+ for (const it of inCell[r * cols + c]) {
1704
+ const id = ids();
1705
+ if (it.key) keys[it.key] = id;
1706
+ curved.add(id);
1707
+ const ih = hOf(it);
1708
+ const shape = it.shape ?? "note";
1709
+ ops.push(itemNote(it, id, shape, it.color ?? "yellow", fx + colX(c) + MX.cellPad, fy + cy, shape === "sticker" ? STK.w : iw, ih, fid));
1710
+ cy += ih + MX.itemGap;
1711
+ }
1712
+ }
1713
+ return { w, h };
1714
+ }
1715
+
1716
+ // src/core/free-board.ts
1717
+ var SK = BOARD.draw.sketch;
1718
+ var T = BOARD.draw.tell;
1719
+ var TONES = ["fact", "problem", "action", "insight", "person", "system"];
1720
+ var FORMS = ["rect", "square", "circle", "ellipse", "diamond", "triangle", "pentagon", "hexagon", "parallelogram", "cylinder", "cloud", "pill", "sticky", "text"];
1721
+ var PEN = { fact: "black", problem: "red", action: "green", insight: "purple", person: "blue", system: "orange" };
1722
+ var SHAPE = {
1723
+ rect: "box",
1724
+ square: "box",
1725
+ circle: "ellipse",
1726
+ ellipse: "ellipse",
1727
+ diamond: "diamond",
1728
+ triangle: "triangle",
1729
+ pentagon: "pentagon",
1730
+ hexagon: "hexagon",
1731
+ parallelogram: "parallelogram",
1732
+ cylinder: "cylinder",
1733
+ cloud: "cloud",
1734
+ pill: "pill",
1735
+ sticky: "note",
1736
+ text: "text"
1737
+ };
1738
+ var round = (n) => Math.round(n);
1739
+ var LABEL_CHAR = 19 * SK.lower * SK.wrapSlack;
1740
+ var wireLabel = (s) => labelSize(s, LABEL_CHAR);
1741
+ var lines = (s, size, upper, w) => wrapLines(s, size * (upper ? SK.upper : SK.lower) * SK.wrapSlack, w);
1742
+ function blockHeight(title, text, icon, size, w, shape = "box") {
1743
+ const t = SK.block[size];
1744
+ const poly = isPolygon(shape) ? POLYGONS[shape].inset : null;
1745
+ const roundish = shape === "ellipse" || shape === "cloud";
1746
+ const inner = poly ? w * (1 - poly[1] - poly[3]) - SK.pad * 2 : (w - SK.pad * 2) * (roundish ? SK.roundInner : 1);
1747
+ const body2 = (validIcon(icon) ? t.icon + 6 : 0) + lines(title, t.title, true, inner) * t.titleLh + lines(text, t.text, false, inner) * t.textLh;
1748
+ if (poly) return round((body2 + SK.pad * 2) / (1 - poly[0] - poly[2]));
1749
+ return round((body2 + SK.pad * 2) / (roundish ? SK.roundInner : 1)) + (shape === "cylinder" ? 28 : 0);
1750
+ }
1751
+ var noteHeight = (text, w) => T.noteTop + Math.max(1, wrapLines(text, T.noteChar, w - T.notePad)) * T.noteLh;
1752
+ function body(n) {
1753
+ const qa = [["Why", n.why], ["Who", n.who], ["When", n.when], ["Where", n.where], ["How", n.how], ["How much", n.howMuch], ["Assumes", n.assumes]];
1754
+ return [n.text, ...qa.filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`)].filter(Boolean).map((s) => noEmoji(s)).join("\n").slice(0, BOARD.maxText);
1755
+ }
1756
+ var obstacles = (notes) => new Map(notes.filter((n) => n.shape !== "ink" && n.shape !== "track").map((n) => [n.id, { x: n.x, y: n.y, w: n.w, h: n.h, ...n.shape ? { shape: n.shape } : {} }]));
1757
+ var autoWires = (links) => links.filter((l) => l.route === "auto");
1758
+ function sizeOf(it, shape, form, size, text) {
1759
+ const title = it.title ? noEmoji(it.title) : void 0;
1760
+ if (form === "sticky") {
1761
+ const w2 = Math.min(T.noteMaxW, it.w ?? T.noteW);
1762
+ return { w: w2, h: noteHeight([title, text].filter(Boolean).join("\n"), w2) };
1763
+ }
1764
+ if (form === "pill") {
1765
+ const t = SK.words[size], label = title ?? "";
1766
+ return { w: Math.max(T.minTextW, round(label.length * t.size * SK.upper * SK.wrapSlack) + 40), h: SK.pillH };
1767
+ }
1768
+ if (form === "text") {
1769
+ const t = SK.words[size], words = [title, text].filter(Boolean).join("\n");
1770
+ const w2 = it.w ?? Math.min(T.widths.xl * 2, round(Math.max(...words.split("\n").map((l) => l.length)) * t.size * (t.upper ? SK.upper : SK.lower) * SK.wrapSlack) + 8);
1771
+ return { w: w2, h: lines(words, t.size, t.upper, w2) * t.lh + 4 };
1772
+ }
1773
+ let w = Math.max(T.minTextW, it.w ?? T.widths[size]);
1774
+ if (form === "square" || form === "circle") {
1775
+ for (let i = 0; i < 16; i++) {
1776
+ const h = blockHeight(title, text, it.icon, size, w, shape);
1777
+ if (h <= w) break;
1778
+ w = round((w + h) / 2) + 8;
1779
+ }
1780
+ return { w, h: w };
1781
+ }
1782
+ const min = isPolygon(shape) ? T.minAspect[shape] * w : 0;
1783
+ return { w, h: Math.max(round(min), it.h ?? 0, blockHeight(title, text, it.icon, size, w, shape)) };
1784
+ }
1785
+ function layFree(story, origin = { x: 0, y: 0 }, board, ids = () => uid("n")) {
1786
+ const steps = [];
1787
+ const skipped = [];
1788
+ const notes = [...board?.notes ?? []];
1789
+ const links = [...board?.links ?? []];
1790
+ const add = (ops, n) => {
1791
+ const min = minSize(n.shape);
1792
+ const sized = { ...n, w: Math.max(min.w, n.w), h: Math.max(min.h, n.h) };
1793
+ ops.push({ op: "note.add", note: sized });
1794
+ notes.push(sized);
1795
+ };
1796
+ const H = SK.headline, head = [];
1797
+ const title = noEmoji(story.headline).slice(0, LEN.line);
1798
+ const titleW = Math.min(H.w, round(title.length * SK.words.xl.size * SK.upper * SK.wrapSlack) + 8);
1799
+ const titleH = lines(title, SK.words.xl.size, true, titleW) * SK.words.xl.lh + 4;
1800
+ add(head, { id: ids(), shape: "text", size: "xl", pen: "black", text: title, color: "paper", x: origin.x, y: origin.y, w: titleW, h: titleH, frame: null });
1801
+ const icon = validIcon(story.icon);
1802
+ if (icon) add(head, { id: ids(), shape: "sticker", icon, text: "", color: "paper", x: origin.x + titleW + H.iconGap, y: origin.y - 8, w: H.icon, h: H.icon, frame: null });
1803
+ let y = origin.y + titleH + H.gapBelow;
1804
+ const items = story.beats.flatMap((b) => b.items ?? []);
1805
+ const used = new Set(items.map((n) => n.tone ?? "fact"));
1806
+ const deep = items.some((n) => (n.layer ?? 0) > 0);
1807
+ const legend = [...TONES.filter((t) => used.has(t)).map((t) => T.legend[t]), T.legend.note, ...deep ? [T.legend.wires] : []].join(" \xB7 ");
1808
+ for (const text of [story.context ? noEmoji(story.context).slice(0, LEN.message) : "", legend]) {
1809
+ if (!text) continue;
1810
+ const h = lines(text, SK.words.s.size, false, H.contextW) * SK.words.s.lh + 4;
1811
+ add(head, { id: ids(), shape: "text", size: "s", pen: "black", text, color: "paper", x: origin.x, y, w: H.contextW, h, frame: null });
1812
+ y += h + 6;
1813
+ }
1814
+ steps.push({ say: title, ops: head });
1815
+ const ox = origin.x, oy = y + T.below;
1816
+ const byKey = /* @__PURE__ */ new Map();
1817
+ const layerOf = /* @__PURE__ */ new Map();
1818
+ const derived = items.every((n) => n.layer === void 0) ? depthByWires(story.beats) : null;
1819
+ let routed = route(notes, links);
1820
+ const taken = () => [...obstacles(notes).values(), ...routed.wires, ...routed.labels];
1821
+ const sticky = (ops, text, near) => {
1822
+ const min = minSize(void 0), h = Math.max(min.h, noteHeight(text, T.noteW)), w = Math.max(min.w, T.noteW), g = T.noteGap;
1823
+ const tries = [{ x: near.x, y: near.y - h - g, w, h }, { x: near.x, y: near.y + near.h + g, w, h }, { x: near.x + near.w + g, y: near.y, w, h }, { x: near.x - w - g, y: near.y, w, h }];
1824
+ const all = taken();
1825
+ const spot = tries.find((b) => !overlaps(b, all, 8)) ?? freeSpot(tries[0], all, 8);
1826
+ add(ops, { id: ids(), text, color: "yellow", x: spot.x, y: spot.y, w, h, frame: null });
1827
+ };
1828
+ for (const beat of story.beats) {
1829
+ const ops = [];
1830
+ const say = noEmoji(beat.say).slice(0, LEN.message);
1831
+ const drawn = [];
1832
+ for (const it of (beat.items ?? []).slice(0, T.maxItems)) {
1833
+ if (byKey.has(it.key)) {
1834
+ skipped.push(it.key);
1835
+ continue;
1836
+ }
1837
+ const text = body(it);
1838
+ const form = it.form === "pill" && text ? "rect" : it.form ?? "rect", shape = SHAPE[form], size = it.size ?? "m";
1839
+ const min = minSize(form === "sticky" ? void 0 : shape), sz = sizeOf(it, shape, form, size, text);
1840
+ const w = Math.max(min.w, sz.w), h = Math.max(min.h, sz.h);
1841
+ const spot = freeSpot({ x: round(ox + it.x), y: round(oy + it.y), w, h }, taken(), T.gap);
1842
+ const id = ids();
1843
+ byKey.set(it.key, id);
1844
+ layerOf.set(it.key, Math.max(0, Math.min(MAX_LAYER, Math.round(it.layer ?? derived?.get(it.key) ?? 0))));
1845
+ const ic = validIcon(it.icon);
1846
+ const pen = it.tone ? PEN[it.tone] : "black";
1847
+ const titled = it.title ? noEmoji(it.title).slice(0, LEN.title) : void 0;
1848
+ const n = form === "sticky" ? { id, text: [titled, text].filter(Boolean).join("\n"), color: "yellow", ...spot, frame: null } : form === "text" ? { id, shape: "text", size, pen, text: [titled, text].filter(Boolean).join("\n"), color: "paper", ...spot, frame: null } : form === "pill" ? { id, shape: "pill", size, pen, text: titled ?? "", color: "paper", ...spot, frame: null } : { id, shape, pen, size, ...titled ? { title: titled } : {}, text, color: "paper", ...spot, frame: null, ...ic ? { icon: ic } : {} };
1849
+ add(ops, n);
1850
+ drawn.push(spot);
1851
+ if (it.note) sticky(ops, noEmoji(it.note).slice(0, LEN.message), spot);
1852
+ }
1853
+ const firstLink = beat.links?.find((l) => byKey.has(l.from));
1854
+ const near = drawn[0] ?? (firstLink ? notes.find((n) => n.id === byKey.get(firstLink.from)) : void 0);
1855
+ if (near) sticky(ops, say, near);
1856
+ for (const l of beat.links ?? []) {
1857
+ const from = byKey.get(l.from), to = byKey.get(l.to);
1858
+ if (!from || !to) {
1859
+ skipped.push(`${l.from} -> ${l.to}`);
1860
+ continue;
1861
+ }
1862
+ const layer = Math.max(layerOf.get(l.from) ?? 0, layerOf.get(l.to) ?? 0);
1863
+ const link = { id: uid("l"), from, to, route: "auto", ...l.label ? { label: noEmoji(l.label).slice(0, LEN.label) } : {}, ...l.dashed ? { dashed: true } : {}, ...layer ? { layer } : {} };
1864
+ ops.push({ op: "link.add", link });
1865
+ links.push(link);
1866
+ }
1867
+ routed = route(notes, links);
1868
+ steps.push({ say, ops });
1869
+ }
1870
+ return { steps, skipped };
1871
+ }
1872
+ function depthByWires(beats) {
1873
+ const keys = beats.flatMap((b) => (b.items ?? []).map((i) => i.key));
1874
+ const links = beats.flatMap((b) => b.links ?? []);
1875
+ const into = new Set(links.map((l) => l.to));
1876
+ const depth = new Map(keys.filter((k) => !into.has(k)).map((k) => [k, 0]));
1877
+ for (let queue = [...depth.keys()]; queue.length; ) {
1878
+ const k = queue.shift(), d = depth.get(k);
1879
+ for (const l of links) if (l.from === k && !depth.has(l.to)) {
1880
+ depth.set(l.to, Math.min(MAX_LAYER, d + 1));
1881
+ queue.push(l.to);
1882
+ }
1883
+ }
1884
+ return depth;
1885
+ }
1886
+ function route(notes, links) {
1887
+ const auto = autoWires(links);
1888
+ const r = routeWires(obstacles(notes), auto.map((l) => ({ from: l.from, to: l.to, ...l.label ? { label: l.label } : {} })), wireLabel);
1889
+ const wires = [], labels = [];
1890
+ for (const x of r.values()) {
1891
+ wires.push(...wireBoxes(x.pts));
1892
+ if (x.label) labels.push(x.label);
1893
+ }
1894
+ return { wires, labels };
1895
+ }
1896
+
1897
+ export {
1898
+ LEN,
1899
+ BOARD,
1900
+ COUNT,
1901
+ BOARD_ARGS,
1902
+ LOOSE_NOTES,
1903
+ SECTION_NOTE_INSET,
1904
+ BOARD_EDITS_KEPT,
1905
+ BOARD_CHATS_KEPT,
1906
+ BOARD_HISTORY,
1907
+ ILLUSTRATIONS,
1908
+ isIllustration,
1909
+ POLYGONS,
1910
+ isPolygon,
1911
+ polygonPoints,
1912
+ polygonPad,
1913
+ wrapLines,
1914
+ overlaps,
1915
+ freeSpot,
1916
+ WIRE,
1917
+ labelSize,
1918
+ routeWires,
1919
+ labelSpot,
1920
+ wireBoxes,
1921
+ LINE_ICONS,
1922
+ isLineIcon,
1923
+ ERR,
1924
+ WORDS,
1925
+ NOTE_COLORS,
1926
+ SHAPES,
1927
+ OUTLINED,
1928
+ TEXT_SIZES,
1929
+ BRUSHES,
1930
+ ROUTES,
1931
+ MAX_LAYER,
1932
+ COL_TYPES,
1933
+ NOTE_W,
1934
+ NOTE_H,
1935
+ MAX_NOTES,
1936
+ MAX_ROWS,
1937
+ MAX_COLS,
1938
+ taskShape,
1939
+ taskBoardOps,
1940
+ noEmoji,
1941
+ validIcon,
1942
+ PENS,
1943
+ uid,
1944
+ frameAt,
1945
+ minSize,
1946
+ applyOps,
1947
+ opKeys,
1948
+ contentOf,
1949
+ historyOf,
1950
+ planOf,
1951
+ pendingBatchOf,
1952
+ boardAt,
1953
+ foldIntoBase,
1954
+ stepsOf,
1955
+ colorFor,
1956
+ layoutOps,
1957
+ nextOrigin,
1958
+ tidyOps,
1959
+ formulaRefs,
1960
+ evalFormula,
1961
+ cellValue,
1962
+ columnTotal,
1963
+ tabRows,
1964
+ boardText,
1965
+ rangeTsv,
1966
+ pasteOps,
1967
+ drawOps,
1968
+ smoothPoints,
1969
+ markStrokes,
1970
+ extendTimelineOps,
1971
+ TONES,
1972
+ FORMS,
1973
+ LABEL_CHAR,
1974
+ wireLabel,
1975
+ blockHeight,
1976
+ noteHeight,
1977
+ obstacles,
1978
+ autoWires,
1979
+ layFree
1980
+ };
1981
+ //# sourceMappingURL=chunk-ORDEALPW.js.map