@pritzlaff/celldeck 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/core.js ADDED
@@ -0,0 +1,1434 @@
1
+ // Cell Deck core: schemas, scene reducers, physics. Pure — no DOM, no clock, no randomness.
2
+ // Ids and timestamps are always passed in from the edge. Runs in the browser (via the page's
3
+ // import map) and in Node (npm test).
4
+ import { Type } from '@sinclair/typebox';
5
+ import { Value } from '@sinclair/typebox/value';
6
+
7
+ // === CORE START ===
8
+ // Pure core: schemas, scene reducers, physics. No DOM, no clock, no randomness.
9
+ // Ids and timestamps are always passed in from the edge.
10
+
11
+ export const HUES = ['teal', 'violet', 'amber', 'rose', 'blue', 'green', 'orange', 'pink', 'cyan', 'lime', 'slate'];
12
+
13
+ // 24×24 stroke icons (Path2D / SVG path data).
14
+ export const ICONS = {
15
+ ui: ['Interface', 'M3 5h18v14H3z M3 9h18 M6 7h.01 M9 7h.01'],
16
+ user: ['Identity', 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M4 21c0-4 4-6 8-6s8 2 8 6'],
17
+ users: ['People', 'M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z M2 20c0-3.5 3-5.5 7-5.5s7 2 7 5.5 M16 4.5a3.5 3.5 0 0 1 0 6.5 M18 14.6c2.4.6 4 2.4 4 5.4'],
18
+ storage: ['Storage', 'M3 4h18v4H3z M5 8v12h14V8 M10 12h4'],
19
+ database: ['Database', 'M4 6c0-1.7 3.6-3 8-3s8 1.3 8 3-3.6 3-8 3-8-1.3-8-3z M4 6v12c0 1.7 3.6 3 8 3s8-1.3 8-3V6 M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3'],
20
+ doc: ['Document', 'M6 2h9l5 5v15H6z M14 2v6h6'],
21
+ api: ['API', 'M8 4c-2 0-3 1-3 3v2c0 1.5-1 3-2 3 1 0 2 1.5 2 3v2c0 2 1 3 3 3 M16 4c2 0 3 1 3 3v2c0 1.5 1 3 2 3-1 0-2 1.5-2 3v2c0 2-1 3-3 3'],
22
+ server: ['Server', 'M4 4h16v6H4z M4 14h16v6H4z M8 7h.01 M8 17h.01'],
23
+ cloud: ['Cloud', 'M7 18a4.5 4.5 0 0 1-.5-9A6 6 0 0 1 18 8a4 4 0 0 1 0 10z'],
24
+ fn: ['Function', 'M5 20l7-11 M7 4h2c1.5 0 2.5 1 3 2.5L18 20h2'],
25
+ queue: ['Queue', 'M2 10h5v9H2z M9.5 10h5v9h-5z M17 10h5v9h-5z M3 5.5h17 M17 3l3 2.5-3 2.5'],
26
+ events: ['Events', 'M13 2L4 14h7l-1 8 9-12h-7z'],
27
+ chip: ['Cache', 'M6 6h12v12H6z M9 2v4 M15 2v4 M9 18v4 M15 18v4 M2 9h4 M2 15h4 M18 9h4 M18 15h4'],
28
+ key: ['Key', 'M8 11a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M10.8 12.2L20 3 M17 6l3 3 M15 8l2 2'],
29
+ lock: ['Lock', 'M5 11h14v10H5z M8 11V7a4 4 0 0 1 8 0v4'],
30
+ shield: ['Shield', 'M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z'],
31
+ phone: ['Phone', 'M7 2h10v20H7z M11 18h2'],
32
+ tablet: ['Tablet', 'M5 3h14v18H5z M11 18h2'],
33
+ laptop: ['Laptop', 'M5 5h14v10H5z M4 15h16l2 4H2z'],
34
+ desktop: ['Desktop', 'M3 4h18v12H3z M12 16v4 M8 20h8'],
35
+ office: ['Office', 'M5 21V4h10v17 M15 9h4v12 M3 21h18 M8 7h1 M11 7h1 M8 11h1 M11 11h1 M8 15h1 M11 15h1 M17 13h.01 M17 17h.01'],
36
+ store: ['Store', 'M4 9l1.5-5h13L20 9 M4 9a2.67 2.67 0 0 0 5.33 0a2.67 2.67 0 0 0 5.34 0a2.67 2.67 0 0 0 5.33 0 M5 11v9h14v-9 M10 20v-5h4v5'],
37
+ globe: ['Web', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M3 12h18 M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9c-2.5-2.5-3.5-5.5-3.5-9s1-6.5 3.5-9z'],
38
+ mail: ['Mail', 'M3 5h18v14H3z M3 6l9 7 9-7'],
39
+ chart: ['Analytics', 'M4 20V10 M10 20V4 M16 20v-7 M3 20h18'],
40
+ search: ['Search', 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z M16 16l5 5'],
41
+ card: ['Payments', 'M3 6h18v12H3z M3 10h18 M7 15h4'],
42
+ wallet: ['Wallet', 'M4 6h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a3 3 0 0 1 3-3h10v2 M14 11h7v4h-7z M16.5 13h.01'],
43
+ bell: ['Notify', 'M6 16V11a6 6 0 0 1 12 0v5l2 2H4z M10 21h4'],
44
+ gear: ['Config', 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z M12 2v3 M12 19v3 M2 12h3 M19 12h3 M4.9 4.9l2.1 2.1 M17 17l2.1 2.1 M4.9 19.1L7 17 M17 7l2.1-2.1'],
45
+ cog: ['Settings', 'M18.7 9.9 L21.4 10.4 L21.4 13.6 L18.7 14.1 L18.2 15.3 L19.8 17.5 L17.5 19.8 L15.3 18.2 L14.1 18.7 L13.6 21.4 L10.4 21.4 L9.9 18.7 L8.7 18.2 L6.5 19.8 L4.2 17.5 L5.8 15.3 L5.3 14.1 L2.6 13.6 L2.6 10.4 L5.3 9.9 L5.8 8.7 L4.2 6.5 L6.5 4.2 L8.7 5.8 L9.9 5.3 L10.4 2.6 L13.6 2.6 L14.1 5.3 L15.3 5.8 L17.5 4.2 L19.8 6.5 L18.2 8.7z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z'],
46
+ spark: ['AI', 'M12 3v4 M12 17v4 M3 12h4 M17 12h4 M12 8l1.5 2.5L16 12l-2.5 1.5L12 16l-1.5-2.5L8 12l2.5-1.5z'],
47
+ trash: ['Trash', 'M4 7h16 M9 7V4h6v3 M6 7l1 13h10l1-13 M10 11v6 M14 11v6'],
48
+ noentry: ['No entry', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M7 12h10'],
49
+ yield: ['Yield', 'M3 4h18L12 20z M7.5 6.5h9L12 15z'],
50
+ x: ['Cross', 'M6 6l12 12 M18 6L6 18'],
51
+ car: ['Car', 'M5 11l2-5h10l2 5 M3 11h18v6H3z M7 14h.01 M17 14h.01 M6 17v2 M18 17v2'],
52
+ train: ['Train', 'M6 3h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z M4 11h16 M8 14h.01 M16 14h.01 M8 17l-2 4 M16 17l2 4'],
53
+ eye: ['Eye', 'M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z'],
54
+ watch: ['Timer', 'M12 6a7.5 7.5 0 1 0 0 15 7.5 7.5 0 0 0 0-15z M12 10v3.5l2.5 1.5 M10 2h4 M12 2v4 M18.5 6.5L20 5'],
55
+ plane: ['Plane', 'M12 2c1 0 1.5 1 1.5 2.5V9l7.5 4.5V16l-7.5-2.5V18l2.5 2v1.5L12 20.5l-4 1V20l2.5-2v-4.5L3 16v-2.5L10.5 9V4.5C10.5 3 11 2 12 2z'],
56
+ folder: ['Folder', 'M3 6a1 1 0 0 1 1-1h5l2 2h9a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z'],
57
+ code: ['Code', 'M9 7l-5 5 5 5 M15 7l5 5-5 5'],
58
+ terminal: ['Terminal', 'M3 4h18v16H3z M7 9l3 3-3 3 M12 15h5'],
59
+ branch: ['Branch', 'M6 3v12 M6 15a3 3 0 1 0 0 6 3 3 0 0 0 0-6z M18 3a3 3 0 1 0 0 6 3 3 0 0 0 0-6z M18 9a9 9 0 0 1-9 9'],
60
+ box: ['Container', 'M12 2l9 5v10l-9 5-9-5V7z M3 7l9 5 9-5 M12 12v10'],
61
+ link: ['Link', 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1 M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1'],
62
+ chat: ['Chat', 'M4 4h16v12H9l-5 4z'],
63
+ calendar: ['Calendar', 'M3 5h18v16H3z M3 10h18 M8 3v4 M16 3v4'],
64
+ image: ['Image', 'M3 4h18v16H3z M8.5 8a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z M21 15l-5-5L5 20'],
65
+ cart: ['Cart', 'M2 3h3l2.5 12h11L21 7H6.2 M9 19a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z M18 19a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z'],
66
+ pin: ['Location', 'M12 22s7-6.5 7-12a7 7 0 0 0-14 0c0 5.5 7 12 7 12z M12 7a3 3 0 1 0 0 6 3 3 0 0 0 0-6z'],
67
+ check: ['Check', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M8 12l3 3 5-6'],
68
+ };
69
+ export const ICON_KEYS = Object.keys(ICONS);
70
+
71
+ export const LIMITS = { bubbles: 40, elements: 80 };
72
+
73
+ // ---------- schemas ----------
74
+ const Id = (what, example) => Type.String({
75
+ pattern: '^[A-Za-z0-9_-]{1,40}$',
76
+ description: `Stable id of ${what}. Views are matched by id, so the same ${what} in two views morphs between them instead of popping in and out.`,
77
+ examples: [example],
78
+ });
79
+
80
+ export const TAG_PATTERN = '^[a-z0-9][a-z0-9 _-]{0,23}$';
81
+ const Tags = (what) => Type.Array(Type.String({ pattern: TAG_PATTERN, description: 'One lowercase tag: letters, digits, spaces, - and _; at most 24 characters.' }), {
82
+ maxItems: 12, uniqueItems: true,
83
+ description: `Free-form tags on ${what}. The filter bar matches them as text and lists them as toggles, so tag by layer, owner or concern (e.g. "frontend", "data", "pii").`,
84
+ examples: [['data', 'pii']],
85
+ });
86
+
87
+ /** Turn typed text into a valid tag, or throw a UserError explaining why it cannot be one. */
88
+ export function normalizeTag(raw) {
89
+ const t = String(raw).toLowerCase().trim().replace(/\s+/g, ' ');
90
+ if (!new RegExp(TAG_PATTERN).test(t)) throw new UserError('Tags are up to 24 characters of letters, digits, spaces, - and _, starting with a letter or digit.');
91
+ return t;
92
+ }
93
+
94
+ const HueLiteral = Type.Union(HUES.map((h) => Type.Literal(h)));
95
+ const IconLiteral = Type.Union(ICON_KEYS.map((k) => Type.Literal(k)));
96
+
97
+ export const ElementSchema = Type.Object({
98
+ id: Id('an element', 'el-ui'),
99
+ bubbleId: Type.String({ pattern: '^[A-Za-z0-9_-]{1,40}$', description: 'Id of the bubble this element sits in. When it differs between two views, the element travels from one bubble to the other during the morph.', examples: ['bb-app'] }),
100
+ label: Type.String({ maxLength: 60, description: 'Caption drawn under the icon or image. With no icon and no image the label alone is the element, drawn larger.', examples: ['Identity'] }),
101
+ icon: Type.Union([Type.Null(), Type.Union(ICON_KEYS.map((k) => Type.Literal(k)))], { description: 'Built-in line icon, or null for none. Ignored when imageId is set.', examples: ['user'] }),
102
+ imageId: Type.Union([Type.Null(), Type.String({ pattern: '^[0-9a-f]{32}$' })], { description: 'Uploaded image asset id (served at /_blob/<id>), or null. Takes precedence over the icon so a logo or screenshot can stand in for it.', examples: [null] }),
103
+ tags: Tags('this element'),
104
+ hue: Type.Union([Type.Null(), HueLiteral], { description: 'Colour of the element\'s chip ring, or null to follow its bubble\'s membrane colour. Lets an element added by a message stand out from its neighbours.', examples: [null, 'amber'] }),
105
+ textHue: Type.Optional(Type.Union([Type.Null(), HueLiteral], { description: 'Colour of the label text, or null (or absent) for the default text colour.', examples: [null, 'rose'] })),
106
+ description: Type.Optional(Type.String({ maxLength: 4000, description: 'Rich-text notes as a small HTML subset (b, i, u, ul, ol, li, a href, p, br). The page sanitises it before showing it, so any other markup is dropped. Absent or empty for none.', examples: ['<b>Primary</b> store<ul><li>EU only</li></ul>'] })),
107
+ showDescription: Type.Optional(Type.Boolean({ description: 'In present mode, show the description along the footer when this element is clicked. Absent means false.', examples: [true] })),
108
+ seq: Type.Optional(Type.Integer({ minimum: 1, description: 'Creation counter: elements added later have a higher number. Builds between views add elements in this order. Absent on elements from before it existed; those come first, in deck order.', examples: [12] })),
109
+ fill: Type.Optional(Type.Boolean({ description: 'Fill the icon chip with its colour instead of only ringing it. Absent means false.', examples: [false] })),
110
+ strike: Type.Optional(Type.Boolean({ description: 'Draw the label struck through, e.g. for something removed or deprecated. Absent means false.', examples: [false] })),
111
+ cell: Type.Optional(Type.Integer({ minimum: 0, maximum: 999, description: 'Cell group within its bubble. A bubble whose elements are in two or more cells is drawn divided into inner cells, one per group. Absent means 0.', examples: [1] })),
112
+ }, { additionalProperties: false, description: 'One draggable thing inside a bubble: an icon, an image or a text label.' });
113
+
114
+ export const BubbleSchema = Type.Object({
115
+ id: Id('a bubble', 'bb-app'),
116
+ title: Type.String({ maxLength: 40, description: 'Name of the bubble. Drawn under the membrane when the bubble has elements, or in its centre when it is empty. Empty string for none.', examples: ['Web app'] }),
117
+ hue: Type.Union([...HUES.map((h) => Type.Literal(h)), Type.String({ pattern: '^#[0-9a-f]{6}$' })], { description: 'Membrane colour: one of the named theme-aware cell hues (they adjust for light and dark mode), or a custom lowercase #rrggbb used as is.', examples: ['teal', '#8a2be2'] }),
118
+ pinch: Type.Optional(Type.Number({ minimum: 0, maximum: 1, description: 'How sharply a bubble with inner cells pinches in where its cells meet: 0 fills the waists until it is nearly round, 1 leaves a crisp crease. Absent means 0.6.', examples: [0.3] })),
119
+ space: Type.Optional(Type.Number({ minimum: 0.2, maximum: 2, description: 'Room inside the membrane: scales the padding around elements and between inner cells. Absent means 1.', examples: [0.6] })),
120
+ x: Type.Number({ description: 'Resting position in world units (CSS px at zoom 1). Free bubbles spring back here; bubbles in orbit ignore it and sit on their ring.', examples: [0] }),
121
+ y: Type.Number({ description: 'Resting position in world units; +y is down.', examples: [0] }),
122
+ orbit: Type.Union([Type.Null(), Type.Object({
123
+ hubId: Type.String({ pattern: '^[A-Za-z0-9_-]{1,40}$', description: 'Bubble this one circles. All satellites of a hub are spaced evenly around it, so adding one pushes the rest round.', examples: ['bb-storage'] }),
124
+ }, { additionalProperties: false })], { description: 'Ring membership, or null for a free bubble.', examples: [null] }),
125
+ tags: Tags('this bubble; a tag here also matches every element inside it'),
126
+ }, { additionalProperties: false, description: 'A cell: a gooey membrane holding zero or more elements.' });
127
+
128
+ // Message fields: a message can ask for values when it is sent; text in its steps refers to them as $name ($$ is a literal $).
129
+ export const FIELD_PATTERN = '^[a-z][a-z0-9_]{0,23}$';
130
+ const PLACEHOLDER = /\$\$|\$([a-z][a-z0-9_]{0,23})/g;
131
+ /** Replace $name with values[name]; $$ becomes $. A $name that is not in values is left as written. */
132
+ export const fillText = (text, values) => text.replace(PLACEHOLDER, (m, name) => (name === undefined ? '$' : Object.hasOwn(values, name) ? values[name] : m));
133
+ /** Field names a piece of text refers to. */
134
+ export const fieldRefs = (text) => [...text.matchAll(PLACEHOLDER)].map((m) => m[1]).filter(Boolean);
135
+ // Tags inside message steps may contain $field placeholders; they are checked as real tags once filled in.
136
+ export const TEMPLATE_TAG_PATTERN = '^[a-z0-9$][a-z0-9 _$-]{0,23}$';
137
+ const TagList = (why) => Type.Array(Type.String({ pattern: TEMPLATE_TAG_PATTERN }), { maxItems: 12, uniqueItems: true, description: `${why} May use $field placeholders.` });
138
+ const TargetSelector = Type.Object({ kind: Type.Literal('target') }, { additionalProperties: false, description: 'The element the message arrives at.' });
139
+ const QuerySelector = Type.Object({
140
+ kind: Type.Literal('query'),
141
+ q: Type.String({ maxLength: 60, description: 'Text matched against labels, tags, icon names and bubble titles, as in the filter bar. Empty for no text condition.', examples: ['cache'] }),
142
+ tags: TagList('Elements with all of these tags, counting their bubble\'s tags as theirs (so ["system1", "database"] is the databases in the system1 bubble). Empty for no tag condition.'),
143
+ icons: Type.Array(IconLiteral, { maxItems: ICON_KEYS.length, uniqueItems: true, description: 'Elements showing any of these icons. Empty for no icon condition.' }),
144
+ }, { additionalProperties: false, description: 'Every element on the stage matching all the conditions given, evaluated when the message arrives. A query with no conditions matches nothing.' });
145
+ /** Which elements a split, clone or remove step acts on. */
146
+ const Which = (verb) => Type.Optional(Type.Union([TargetSelector, QuerySelector], { description: `What to ${verb}: the target (the default when absent), or every element a query matches when the message arrives. Query text and tags may use $fields, e.g. a tag of "$env".` }));
147
+ export const SelectorSchema = Type.Union([
148
+ Type.Object({ kind: Type.Literal('source') }, { additionalProperties: false, description: 'The element the message was sent from.' }),
149
+ TargetSelector,
150
+ QuerySelector,
151
+ ], { description: 'Which elements one end of a new connection attaches to.' });
152
+
153
+ export const ActionSchema = Type.Union([
154
+ Type.Object({
155
+ kind: Type.Literal('add'),
156
+ label: Type.String({ maxLength: 60, description: 'Label of the element the message creates. May be empty when it has an icon (an icon-only element).', examples: ['Postgres', ''] }),
157
+ icon: Type.Union([Type.Null(), IconLiteral], { description: 'Icon of the new element, or null for a text-only element.', examples: ['database'] }),
158
+ tags: TagList('Tags given to the new element.'),
159
+ hue: Type.Union([Type.Null(), HueLiteral], { description: 'Chip colour of the new element, or null to follow its bubble.', examples: ['blue'] }),
160
+ }, { additionalProperties: false, description: 'Create a new element in the target\'s bubble; it buds out of the target.' }),
161
+ Type.Object({ kind: Type.Literal('split'), which: Which('split out') }, { additionalProperties: false, description: 'Knock elements (the target by default) out of their bubbles into new bubbles, carried on in the direction the message travelled.' }),
162
+ Type.Object({ kind: Type.Literal('clone'), which: Which('clone') }, { additionalProperties: false, description: 'Elements (the target by default) divide: a copy of each (label, icon, image, tags, colour; not its connections) appears beside it in the same bubble.' }),
163
+ Type.Object({
164
+ kind: Type.Literal('remove'),
165
+ which: Which('delete'),
166
+ }, { additionalProperties: false, description: 'Delete elements (the target by default), and with them their connections; a bubble left empty and untitled goes too.' }),
167
+ Type.Object({
168
+ kind: Type.Literal('connect'),
169
+ from: SelectorSchema,
170
+ to: SelectorSchema,
171
+ label: Type.String({ maxLength: 60, description: 'Label for each new connection.', examples: ['reads'] }),
172
+ head: Type.Union([Type.Literal('none'), Type.Literal('end'), Type.Literal('both')], { description: 'Arrowheads on each new connection.', examples: ['end'] }),
173
+ dash: Type.Union([Type.Literal('solid'), Type.Literal('dashed'), Type.Literal('flow')], { description: 'Line style of each new connection.', examples: ['flow'] }),
174
+ elasticity: Type.Number({ minimum: 0, maximum: 1, description: 'Elasticity of each new connection: 0 is a rigid straight line; above 0 it behaves like a rubber band (sags, wobbles, tugs its ends together), looser as it rises.', examples: [0, 0.5] }),
175
+ }, { additionalProperties: false, description: 'Draw a connection from every "from" element to every "to" element, skipping an element to itself and any identical connection that already exists (same direction and label). Two elements can have several connections; parallel ones bow apart.' }),
176
+ Type.Object({
177
+ kind: Type.Literal('send'),
178
+ from: SelectorSchema,
179
+ message: Type.String({ minLength: 1, maxLength: 40, description: 'Label of the message to send. Every element the selector picks sends each of its messages with this label along the connection that carries it, so one message can set off the next.', examples: ['archive'] }),
180
+ args: Type.Optional(Type.Record(Type.String({ pattern: FIELD_PATTERN }), Type.String({ maxLength: 60 }), { additionalProperties: false, description: 'Values for the sent message\'s fields, by field name. Each may use this message\'s own $fields, e.g. { "fizz": "$foo" }. Fields not listed are sent empty.', examples: [{ fizz: '$foo' }] })),
181
+ }, { additionalProperties: false, description: 'Make other elements send one of their own messages: a chain reaction. Chains stop after a fixed number of hops so a loop cannot run forever.' }),
182
+ ], { description: 'One step of what happens when the message reaches the target.' });
183
+ export const LIMIT_ACTIONS = 8;
184
+ export const LIMIT_CHAIN = 12;
185
+
186
+ export const MessageSchema = Type.Object({
187
+ id: Id('a message', 'msg-provision'),
188
+ label: Type.String({ minLength: 1, maxLength: 40, description: 'Shown on the send button and on the packet as it travels.', examples: ['provision DB'] }),
189
+ fields: Type.Optional(Type.Array(Type.String({ pattern: FIELD_PATTERN }), { maxItems: 8, uniqueItems: true, description: 'Input fields asked for when the message is sent from its button. Steps refer to them as $name in labels, tags, query text and message names.', examples: [['name', 'env']] })),
190
+ actions: Type.Array(ActionSchema, { minItems: 1, maxItems: LIMIT_ACTIONS, description: 'Steps applied in order when the packet arrives; each sees the stage as the previous step left it (e.g. split, then send a message from the target).' }),
191
+ }, { additionalProperties: false, description: 'Something the start element can send along this connection. Sending animates a packet to the end element, then applies its actions.' });
192
+ export const LIMIT_MESSAGES = 12;
193
+
194
+ const ElementRef = (end, example) => Type.String({ pattern: '^[A-Za-z0-9_-]{1,40}$', description: `Id of the element at the ${end} of the line. The line follows that element wherever it goes, including into other bubbles; deleting the element deletes the line.`, examples: [example] });
195
+ export const LinkSchema = Type.Object({
196
+ id: Id('a connection', 'ln-ui-identity'),
197
+ from: ElementRef('start', 'el-ui'),
198
+ to: ElementRef('end', 'el-identity'),
199
+ label: Type.String({ maxLength: 60, description: 'Text drawn on a pill at the middle of the line. Empty string for none.', examples: ['signs in'] }),
200
+ head: Type.Union([Type.Literal('none'), Type.Literal('end'), Type.Literal('both')], { description: 'Arrowheads: none (a plain association), end (from → to, a call or data flow), both (two-way).', examples: ['end'] }),
201
+ dash: Type.Union([Type.Literal('solid'), Type.Literal('dashed'), Type.Literal('flow')], { description: 'solid; dashed (weak or optional dependency); flow (dashes that march from → to, for traffic or data moving now).', examples: ['flow'] }),
202
+ tags: Tags('this connection; matching one in the filter lights the line and both of its ends'),
203
+ messages: Type.Array(MessageSchema, { maxItems: LIMIT_MESSAGES, description: 'Messages the start element can send along this line, in button order.' }),
204
+ opacity: Type.Optional(Type.Number({ minimum: 0, maximum: 1, description: 'How solid the line, its arrowheads and its label are drawn: 0 invisible, 1 (the default when absent) fully opaque. Handy for background relationships.', examples: [1, 0.4] })),
205
+ elasticity: Type.Number({ minimum: 0, maximum: 1, description: '0 is a rigid straight line. Above 0 the line acts like a rubber band: it sags, lags and wobbles when its ends move, and tugs its two elements slightly toward each other. Higher is looser.', examples: [0, 0.5] }),
206
+ }, { additionalProperties: false, description: 'A line between two elements.' });
207
+ export const LIMIT_LINKS = 120;
208
+
209
+ export const StageSchema = Type.Object({
210
+ grid: Type.Boolean({ description: 'Show the dot grid. Turn it off for a clean backdrop when presenting or taking screenshots.', examples: [true] }),
211
+ color: Type.Union([Type.Null(), Type.String({ pattern: '^#[0-9a-f]{6}$' })], { description: 'Custom backdrop colour as #rrggbb, or null for none. In present mode a slide with none keeps the colour (and opacity) of the nearest earlier slide that set one; set a colour at opacity 0 to go back to the theme background.', examples: [null, '#101828'] }),
212
+ opacity: Type.Number({ minimum: 0, maximum: 1, description: 'How strongly the custom colour covers the theme background: 0 shows the theme background, 1 the colour at full strength. Ignored when color is null.', examples: [1] }),
213
+ description: Type.Optional(Type.String({ maxLength: 4000, description: 'Rich-text notes for this slide, in the same HTML subset as an element description. Absent or empty for none.', examples: ['Next: <a href="https://example.com">rollout plan</a>'] })),
214
+ showDescription: Type.Optional(Type.Boolean({ description: 'In present mode, show the description along the footer while no element with shown notes is clicked. Absent means false.', examples: [true] })),
215
+ }, { additionalProperties: false, description: 'Backdrop behind the bubbles, plus the slide notes. Saved with each view, so a talk can change backdrop between slides.' });
216
+ export const DEFAULT_STAGE = Object.freeze({ grid: true, color: null, opacity: 1 });
217
+
218
+ /** The scene a view presents: with no colour of its own it keeps the nearest earlier view's backdrop colour and opacity. */
219
+ const carriedStage = (views, i) => views.slice(0, i).findLast((v) => v.scene.stage.color !== null)?.scene.stage;
220
+ export function presentedScene(views, id) {
221
+ const i = views.findIndex((v) => v.id === id);
222
+ const scene = views[i].scene, from = carriedStage(views, i);
223
+ if (scene.stage.color !== null || !from) return scene;
224
+ return { ...scene, stage: { ...scene.stage, color: from.color, opacity: from.opacity } };
225
+ }
226
+ /** The inverse when saving over view `id`: a backdrop that just repeats the carried one is stored as none, so it keeps following earlier slides. */
227
+ export function ownedScene(views, id, scene) {
228
+ const i = views.findIndex((v) => v.id === id), from = carriedStage(views, i);
229
+ if (!from || scene.stage.color !== from.color || scene.stage.opacity !== from.opacity) return scene;
230
+ return { ...scene, stage: { ...scene.stage, color: null, opacity: views[i].scene.stage.opacity } };
231
+ }
232
+
233
+ /** What the backdrop is easing toward: custom colour and its strength (0 = theme background), and grid visibility. */
234
+ export function stageTarget(stage) {
235
+ return stage.color === null ? { rgb: [0, 0, 0], a: 0, grid: stage.grid ? 1 : 0 } : { rgb: hexRgb(stage.color), a: stage.opacity, grid: stage.grid ? 1 : 0 };
236
+ }
237
+ /** Pure #rrggbb → [r, g, b] in 0..1; throws on anything else. */
238
+ export function hexRgb(hex) {
239
+ const m = /^#([0-9a-f]{6})$/i.exec(String(hex).trim());
240
+ if (!m) throw new Error(`bug: not a #rrggbb colour: "${hex}"`);
241
+ const n = parseInt(m[1], 16);
242
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
243
+ }
244
+
245
+ export const SceneSchema = Type.Object({
246
+ stage: StageSchema,
247
+ bubbles: Type.Array(BubbleSchema, { maxItems: LIMITS.bubbles, description: 'Bubbles in draw order (later on top).' }),
248
+ elements: Type.Array(ElementSchema, { maxItems: LIMITS.elements, description: 'Elements; their order within a bubble sets their slot order.' }),
249
+ links: Type.Array(LinkSchema, { maxItems: LIMIT_LINKS, description: 'Connections between elements, drawn under the elements and over the membranes.' }),
250
+ }, { additionalProperties: false, description: 'Everything on the stage that a view captures, apart from the camera.' });
251
+
252
+ /**
253
+ * Explicit format migrations for scenes saved by earlier versions of the page:
254
+ * v2 → v3: connections added (`links`).
255
+ * v3 → v4: tags added on bubbles, elements and connections (`tags`).
256
+ * v4 → v5: backdrop settings added (`stage`), defaulting to the grid on the theme background as before.
257
+ * v5 → v6: messages on connections (`messages`) and an optional own colour on elements (`hue`, null = follow the bubble).
258
+ * v6 → v7: connect steps in messages gain `elasticity` for the lines they draw (0 = rigid, as before).
259
+ * Only those exact absences are filled in; anything else passes through untouched for the schema to judge.
260
+ */
261
+ export function migrateScene(raw) {
262
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return raw;
263
+ const addKey = (key, value) => (xs) => (Array.isArray(xs) ? xs.map((x) => (x && typeof x === 'object' && !(key in x) ? { ...x, [key]: value } : x)) : xs);
264
+ const addTags = addKey('tags', []);
265
+ const connectElastic = (l) => (l && typeof l === 'object' && Array.isArray(l.messages)
266
+ ? { ...l, messages: l.messages.map((m) => (m && Array.isArray(m.actions) ? { ...m, actions: m.actions.map((a) => (a && a.kind === 'connect' && !('elasticity' in a) ? { ...a, elasticity: 0 } : a)) } : m)) }
267
+ : l);
268
+ const links = 'links' in raw ? addKey('messages', [])(addTags(raw.links)).map(connectElastic) : [];
269
+ return { ...raw, stage: 'stage' in raw ? raw.stage : { ...DEFAULT_STAGE }, links, bubbles: addTags(raw.bubbles), elements: addKey('hue', null)(addTags(raw.elements)) };
270
+ }
271
+
272
+ // ---------- filter ----------
273
+ export const EMPTY_FILTER = Object.freeze({ q: '', tags: Object.freeze([]), icons: Object.freeze([]) });
274
+ export const filterActive = (f) => f.q.trim() !== '' || f.tags.length > 0 || f.icons.length > 0;
275
+
276
+ /** Which elements and bubbles a filter keeps lit; null when no filter is active. Text matches labels, titles, tags and icon names; tag and icon toggles are OR within a group and AND across groups. */
277
+ export function filterMatch(scene, f) {
278
+ if (!filterActive(f)) return null;
279
+ const ix = indexOf(scene);
280
+ const q = f.q.trim().toLowerCase();
281
+ const T = new Set(f.tags), I = new Set(f.icons);
282
+ const text = (xs) => !q || xs.some((x) => x.toLowerCase().includes(q));
283
+ const elements = new Set(), bubbles = new Set();
284
+ for (const e of scene.elements) {
285
+ const b = ix.bubbles.get(e.bubbleId);
286
+ const okQ = text([e.label, ...e.tags, ...(e.icon ? [e.icon, ICONS[e.icon][0]] : []), b.title, ...b.tags]);
287
+ const okT = !T.size || [...e.tags, ...b.tags].some((t) => T.has(t));
288
+ const okI = !I.size || (e.icon !== null && I.has(e.icon));
289
+ if (okQ && okT && okI) { elements.add(e.id); bubbles.add(b.id); }
290
+ }
291
+ if (!I.size) {
292
+ for (const b of scene.bubbles) if (text([b.title, ...b.tags]) && (!T.size || b.tags.some((t) => T.has(t)))) bubbles.add(b.id);
293
+ }
294
+ // A connection is lit when both of its ends are, or when it matches on its own label/tags
295
+ // (then its two ends light up with it, so the matched relationship reads in context).
296
+ const links = new Set();
297
+ for (const l of scene.links) {
298
+ if (elements.has(l.from) && elements.has(l.to)) { links.add(l.id); continue; }
299
+ const self = !I.size && text([l.label, ...l.tags]) && (!T.size || l.tags.some((t) => T.has(t))) && (q !== '' || T.size > 0);
300
+ if (self) {
301
+ links.add(l.id);
302
+ for (const eid of [l.from, l.to]) { elements.add(eid); bubbles.add(ix.elements.get(eid).bubbleId); }
303
+ }
304
+ }
305
+ return { elements, bubbles, links };
306
+ }
307
+ /** Opacity for a body's filter highlight (1 = matched, 0 = filtered out but still faintly visible for context). */
308
+ export const litAlpha = (lit) => 0.13 + 0.87 * lit;
309
+ export const tagsInScene = (scene) => [...new Set([...scene.bubbles, ...scene.elements, ...scene.links].flatMap((x) => x.tags))].sort();
310
+ export const iconsInScene = (scene) => ICON_KEYS.filter((k) => scene.elements.some((e) => e.icon === k));
311
+
312
+ export const CameraSchema = Type.Object({
313
+ x: Type.Number({ description: 'World x at the centre of the stage.', examples: [0] }),
314
+ y: Type.Number({ description: 'World y at the centre of the stage.', examples: [0] }),
315
+ zoom: Type.Number({ minimum: 0.25, maximum: 3, description: 'Screen px per world unit. Views store it so a talk can zoom in on one ring.', examples: [1] }),
316
+ }, { additionalProperties: false });
317
+
318
+ export const ViewSchema = Type.Object({
319
+ id: Id('a view', 'v-pulled-apart'),
320
+ name: Type.String({ maxLength: 60, description: 'Shown on the view chip and in the presenter HUD; ?view=<id or name> opens it.', examples: ['Pulled apart'] }),
321
+ scene: SceneSchema,
322
+ camera: CameraSchema,
323
+ }, { additionalProperties: false, description: 'One saved view (slide): a snapshot of the stage and camera.' });
324
+ export const LIMIT_VIEWS = 100;
325
+
326
+ /** deck.json format version. Bump on a breaking change and teach parseDeck to migrate the old shape. */
327
+ export const DECK_VERSION = 1;
328
+
329
+ export const DeckSchema = Type.Object({
330
+ version: Type.Literal(DECK_VERSION, { description: 'Format version of this file. Files without one are version 1. A newer version than this page knows is refused rather than misread.', examples: [DECK_VERSION] }),
331
+ scene: SceneSchema,
332
+ camera: CameraSchema,
333
+ views: Type.Array(ViewSchema, { maxItems: LIMIT_VIEWS, description: 'Saved views in presenting order.' }),
334
+ }, { additionalProperties: false, description: 'A whole deck — the editor stage as last left plus its saved views. This is the deck.json file format.' });
335
+
336
+ /** The deck a new page starts with. */
337
+ export const EMPTY_DECK = Object.freeze({
338
+ version: DECK_VERSION,
339
+ scene: {
340
+ bubbles: [{ id: 'bb-app', title: 'Web app', hue: 'teal', x: 0, y: 0, orbit: null, tags: [] }],
341
+ elements: [
342
+ { id: 'el-ui', bubbleId: 'bb-app', label: 'UI', icon: 'ui', imageId: null, tags: ['frontend'], hue: null },
343
+ { id: 'el-identity', bubbleId: 'bb-app', label: 'Identity', icon: 'user', imageId: null, tags: ['security'], hue: null },
344
+ { id: 'el-storage', bubbleId: 'bb-app', label: 'Storage', icon: 'storage', imageId: null, tags: ['data'], hue: null },
345
+ ],
346
+ links: [],
347
+ stage: { grid: true, color: null, opacity: 1 },
348
+ },
349
+ camera: { x: 0, y: 0, zoom: 1 },
350
+ views: [],
351
+ });
352
+
353
+ /**
354
+ * Validate untrusted deck JSON (a file, a URL, local storage): migrates scenes from older versions, then checks
355
+ * the schema, scene references and view-id uniqueness. Returns the deck or throws a message fit to show the user.
356
+ */
357
+ export function parseDeck(raw, what = 'The deck') {
358
+ const isObj = (x) => x && typeof x === 'object' && !Array.isArray(x);
359
+ if (!isObj(raw)) throw new Error(`${what} is not a JSON object.`);
360
+ const version = raw.version ?? 1; // files saved before versioning are version 1
361
+ if (typeof version === 'number' && version > DECK_VERSION) throw new Error(`${what} was saved by a newer Cell Deck (format version ${version}; this page reads up to ${DECK_VERSION}). Reload to get the latest version.`);
362
+ const migrated = { version, ...raw, scene: migrateScene(raw.scene), views: Array.isArray(raw.views) ? raw.views.map((v) => (isObj(v) ? { ...v, scene: migrateScene(v.scene) } : v)) : raw.views };
363
+ const deck = parseOrThrow(DeckSchema, migrated, what);
364
+ const check = (scene, where) => { try { checkScene(scene); } catch (err) { throw new Error(`${what}: ${where} has broken references: ${err.message}`); } };
365
+ check(deck.scene, 'the stage');
366
+ const ids = new Set();
367
+ for (const v of deck.views) {
368
+ if (ids.has(v.id)) throw new Error(`${what}: two views share the id "${v.id}".`);
369
+ ids.add(v.id);
370
+ check(v.scene, `view "${v.name}"`);
371
+ }
372
+ return deck;
373
+ }
374
+
375
+ // Share links carry the whole deck in the URL hash (#deck=…): JSON, deflate-raw, base64url. The hash never reaches a server.
376
+ // ponytail: chat apps and some browsers choke well before Chrome's 2 MB URL cap; 32k chars is a safe-ish ceiling, raise if decks outgrow it.
377
+ export const LIMIT_LINK = 32000;
378
+ const pipeBytes = async (bytes, stream) => new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());
379
+ /** Deck → base64url string for #deck=. */
380
+ export async function encodeDeckLink(deck) {
381
+ const z = await pipeBytes(new TextEncoder().encode(JSON.stringify(deck)), new CompressionStream('deflate-raw'));
382
+ let bin = '';
383
+ for (let i = 0; i < z.length; i += 0x8000) bin += String.fromCharCode(...z.subarray(i, i + 0x8000));
384
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
385
+ }
386
+ /** #deck= string → validated deck; throws a message fit to show the user. */
387
+ export async function decodeDeckLink(s) {
388
+ let json;
389
+ try {
390
+ const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));
391
+ json = JSON.parse(new TextDecoder().decode(await pipeBytes(Uint8Array.from(bin, (c) => c.charCodeAt(0)), new DecompressionStream('deflate-raw'))));
392
+ } catch { throw new Error('The deck in this link is damaged or cut off. Ask for the link again.'); }
393
+ return parseDeck(json, 'The deck in this link');
394
+ }
395
+
396
+ export function parseOrThrow(schema, value, what) {
397
+ if (Value.Check(schema, value)) return value;
398
+ const first = [...Value.Errors(schema, value)][0];
399
+ throw new Error(`${what} is malformed at ${first?.path || '/'}: ${first?.message ?? 'unknown error'}`);
400
+ }
401
+
402
+ export class UserError extends Error {}
403
+
404
+ // ---------- layout ----------
405
+ export const K = {
406
+ ELEM_R: 26, // icon chip radius
407
+ ELEM_BALL: 40, // metaball radius an element adds to its membrane
408
+ SLOT: 100, // centre spacing between elements in a bubble
409
+ PAD: 58, // membrane padding beyond the outermost slot
410
+ TITLE_ONLY_R: 64,
411
+ SINGLE_R: 70,
412
+ BLEND: 34, // smooth-union radius inside one bubble
413
+ LANE: 46, // sideways bow between parallel connections joining the same two elements
414
+ DETACH_GAP: 70, // how far past the membrane an element pulls before it pinches off
415
+ BREAK_GAP: 18, // gap at which a bud/merge bridge snaps
416
+ RING_GAP: 70,
417
+ CELL_TRIM: 12, // inner cell radius = its own slot layout radius minus this
418
+ CELL_GAP: 14, // space between neighbouring inner cells
419
+ CELL_PAD: 22, // outer membrane padding around its inner cells
420
+ DT: 1 / 120,
421
+ };
422
+
423
+ const layoutMemo = new Map();
424
+ export function slotLayout(n) {
425
+ if (!Number.isInteger(n) || n < 0) throw new Error(`bug: slotLayout(${n})`);
426
+ const hit = layoutMemo.get(n);
427
+ if (hit) return hit;
428
+ let out;
429
+ if (n === 0) out = { offsets: [], R: K.TITLE_ONLY_R };
430
+ else if (n === 1) out = { offsets: [{ x: 0, y: 0 }], R: K.SINGLE_R };
431
+ else if (n <= 6) {
432
+ const rho = (K.SLOT / 2) / Math.sin(Math.PI / n);
433
+ const start = n === 2 ? Math.PI : -Math.PI / 2;
434
+ out = { offsets: Array.from({ length: n }, (_, i) => ({ x: rho * Math.cos(start + (i * 2 * Math.PI) / n), y: rho * Math.sin(start + (i * 2 * Math.PI) / n) })), R: rho + K.PAD };
435
+ } else {
436
+ const c = K.SLOT * 0.56;
437
+ out = { offsets: Array.from({ length: n }, (_, i) => ({ x: c * Math.sqrt(i + 0.5) * Math.cos(i * 2.39996), y: c * Math.sqrt(i + 0.5) * Math.sin(i * 2.39996) })), R: c * Math.sqrt(n - 0.5) + K.PAD };
438
+ }
439
+ Object.freeze(out);
440
+ layoutMemo.set(n, out);
441
+ return out;
442
+ }
443
+
444
+ const indexMemo = new WeakMap();
445
+ export function indexOf(scene) {
446
+ const hit = indexMemo.get(scene);
447
+ if (hit) return hit;
448
+ const bubbles = new Map(scene.bubbles.map((b) => [b.id, b]));
449
+ const elements = new Map(scene.elements.map((e) => [e.id, e]));
450
+ const members = new Map(scene.bubbles.map((b) => [b.id, []]));
451
+ for (const e of scene.elements) {
452
+ const list = members.get(e.bubbleId);
453
+ if (!list) throw new Error(`bug: element ${e.id} points at missing bubble ${e.bubbleId}`);
454
+ list.push(e.id);
455
+ }
456
+ const satellites = new Map();
457
+ for (const b of scene.bubbles) {
458
+ if (b.orbit) {
459
+ if (!bubbles.has(b.orbit.hubId)) throw new Error(`bug: bubble ${b.id} orbits missing hub ${b.orbit.hubId}`);
460
+ satellites.set(b.orbit.hubId, [...(satellites.get(b.orbit.hubId) ?? []), b.id]);
461
+ }
462
+ }
463
+ const links = new Map(scene.links.map((l) => [l.id, l]));
464
+ for (const l of scene.links) {
465
+ if (!elements.has(l.from) || !elements.has(l.to)) throw new Error(`bug: connection ${l.id} points at a missing element`);
466
+ }
467
+ const ix = { bubbles, elements, members, satellites, links };
468
+ indexMemo.set(scene, ix);
469
+ return ix;
470
+ }
471
+
472
+ export const cellOf = (e) => e.cell ?? 0;
473
+
474
+ /** Smooth-union radius of a bubble's membrane in world units: wide (rounder) at pinch 0, tight (creased) at 1. */
475
+ export const membraneBlend = (b) => 8 + 65 * (1 - (b.pinch ?? 0.6)); // 0.6 keeps the original blend (34)
476
+ /** Polynomial smooth minimum, as the membrane shader blends its balls. */
477
+ export const smin = (a, b, k) => { if (k < 0.01) return Math.min(a, b); const h = Math.max(k - Math.abs(a - b), 0) / k; return Math.min(a, b) - h * h * k * 0.25; };
478
+ /** Signed distance to a membrane made of lobes [{x, y, r}] blended with radius k (negative inside). */
479
+ export const lobeField = (lobes, k, x, y) => lobes.reduce((d, l) => smin(d, Math.hypot(x - l.x, y - l.y) - l.r, k), 1e5);
480
+
481
+ const bubbleLayoutMemo = new WeakMap();
482
+ /** One bubble's layout: radius R, each member's offset from the centre, and its inner cells ({ cell, x, y, r }; empty unless 2+). */
483
+ export function bubbleLayout(scene, id) {
484
+ let memo = bubbleLayoutMemo.get(scene);
485
+ if (!memo) bubbleLayoutMemo.set(scene, (memo = new Map()));
486
+ const hit = memo.get(id);
487
+ if (hit) return hit;
488
+ const ix = indexOf(scene);
489
+ const m = ix.members.get(id);
490
+ if (!m) throw new Error(`bug: bubbleLayout of missing bubble ${id}`);
491
+ const groups = new Map();
492
+ for (const eid of m) { const c = cellOf(ix.elements.get(eid)); groups.set(c, [...(groups.get(c) ?? []), eid]); }
493
+ let out;
494
+ const sp = ix.bubbles.get(id).space ?? 1;
495
+ const core = (n) => slotLayout(n).R - K.PAD; // reach of the slots themselves, before padding
496
+ if (groups.size < 2) {
497
+ const L = slotLayout(m.length);
498
+ out = { R: core(m.length) + K.PAD * sp, offsets: new Map(m.map((eid, i) => [eid, L.offsets[i]])), cells: [], lobes: [] };
499
+ } else {
500
+ const cs = [...groups].map(([cell, ids]) => ({ cell, ids, r: core(ids.length) + (K.PAD - K.CELL_TRIM) * sp, x: 0, y: 0 }));
501
+ const g = K.CELL_GAP * sp;
502
+ if (cs.length === 2) { cs[0].x = -(cs[1].r + g / 2); cs[1].x = cs[0].r + g / 2; } // touching, centred as a pair
503
+ else {
504
+ // Round a ring with each neighbour pair just touching: find the ring radius whose pair angles sum to a full turn.
505
+ const need = cs.map((c, i) => c.r + cs[(i + 1) % cs.length].r + g); // centre distance per neighbour pair
506
+ const turn = (rho) => need.reduce((a, d) => a + 2 * Math.asin(Math.min(1, d / (2 * rho))), 0);
507
+ let lo = Math.max(...need) / 2, hi = lo * cs.length;
508
+ for (let it = 0; it < 50; it++) { const mid = (lo + hi) / 2; if (turn(mid) > 2 * Math.PI) lo = mid; else hi = mid; }
509
+ let a = -Math.PI / 2;
510
+ cs.forEach((c, i) => { c.x = hi * Math.cos(a); c.y = hi * Math.sin(a); a += 2 * Math.asin(Math.min(1, need[i] / (2 * hi))); });
511
+ }
512
+ const offsets = new Map();
513
+ for (const c of cs) { const L = slotLayout(c.ids.length); c.ids.forEach((eid, i) => offsets.set(eid, { x: c.x + L.offsets[i].x, y: c.y + L.offsets[i].y })); }
514
+ // Each cell is a lobe of the membrane (radius m), overlapping its neighbours so they pinch where they meet.
515
+ const cells = cs.map(({ cell, x, y, r }) => ({ cell, x, y, r, m: r + K.CELL_PAD * sp }));
516
+ // Three or more lobes round a ring can leave a hole in the middle; a filler lobe closes it.
517
+ const ring = cs.length > 2 ? Math.max(...cs.map((c) => Math.hypot(c.x, c.y))) : 0;
518
+ const lobes = [...cells.map(({ x, y, m }) => ({ x, y, r: m })), ...(ring ? [{ x: 0, y: 0, r: ring * 0.85 }] : [])];
519
+ out = { R: Math.max(...cells.map((c) => Math.hypot(c.x, c.y) + c.m)), offsets, cells, lobes };
520
+ }
521
+ memo.set(id, out);
522
+ return out;
523
+ }
524
+
525
+ export const bubbleRadius = (scene, id) => bubbleLayout(scene, id).R;
526
+
527
+ export function slotOffset(scene, elementId) {
528
+ const e = indexOf(scene).elements.get(elementId);
529
+ if (!e) throw new Error(`bug: slotOffset of missing element ${elementId}`);
530
+ return bubbleLayout(scene, e.bubbleId).offsets.get(elementId);
531
+ }
532
+
533
+ /** A cell number no element of the bubble uses yet. */
534
+ export function nextCell(scene, id) {
535
+ const ix = indexOf(scene);
536
+ return Math.max(0, ...ix.members.get(id).map((eid) => cellOf(ix.elements.get(eid)))) + 1;
537
+ }
538
+
539
+ // Cell walls split a round bubble into a power diagram of its cells: each wall sits where two cells
540
+ // are equally "close" once weighted by size (|p - c|² - r²), so it runs through the gap between them.
541
+ /** Half-plane n·p <= k where site i beats site j. */
542
+ export const powerHalf = (a, b) => ({ nx: 2 * (b.x - a.x), ny: 2 * (b.y - a.y), k: b.x * b.x + b.y * b.y - a.x * a.x - a.y * a.y - b.r * b.r + a.r * a.r });
543
+
544
+ /** Wall segments between lobes [{x, y, r}]: each runs along two lobes' shared chord, between the pinch points. */
545
+ export function cellWalls(sites) {
546
+ const out = [];
547
+ for (let i = 0; i < sites.length; i++) for (let j = i + 1; j < sites.length; j++) {
548
+ const { nx, ny, k } = powerHalf(sites[i], sites[j]);
549
+ const nn = nx * nx + ny * ny;
550
+ if (nn < 1e-9) continue;
551
+ const px = (nx * k) / nn, py = (ny * k) / nn, l = Math.sqrt(nn), dx = -ny / l, dy = nx / l;
552
+ // inside lobe i (the power line is the two lobes' radical axis, so this is their shared chord)
553
+ const R = sites[i].r, ox = px - sites[i].x, oy = py - sites[i].y, bq = ox * dx + oy * dy, disc = bq * bq - (ox * ox + oy * oy - R * R);
554
+ if (disc <= 0) continue;
555
+ let lo = -bq - Math.sqrt(disc), hi = -bq + Math.sqrt(disc);
556
+ // every other site must lose to i along the wall
557
+ for (let m = 0; m < sites.length && lo < hi; m++) {
558
+ if (m === i || m === j) continue;
559
+ const h = powerHalf(sites[i], sites[m]);
560
+ const a = h.nx * dx + h.ny * dy, c = h.k - (h.nx * px + h.ny * py); // a t <= c
561
+ if (Math.abs(a) < 1e-9) { if (c < 0) hi = lo; } else if (a > 0) hi = Math.min(hi, c / a); else lo = Math.max(lo, c / a);
562
+ }
563
+ if (lo < hi) out.push({ a: { x: px + lo * dx, y: py + lo * dy }, b: { x: px + hi * dx, y: py + hi * dy } });
564
+ }
565
+ return out;
566
+ }
567
+
568
+ /** Cell of bubble `id` under a world point (whose side of the walls it is on); 0 for a bubble without cells. */
569
+ export function cellAt(rt, scene, id, wx, wy) {
570
+ const b = rt.bubbles[id];
571
+ let best = 0, bestD = Infinity;
572
+ for (const c of bubbleLayout(scene, id).cells) {
573
+ const d = (wx - b.x - c.x) ** 2 + (wy - b.y - c.y) ** 2 - c.m * c.m;
574
+ if (d < bestD) { best = c.cell; bestD = d; }
575
+ }
576
+ return best;
577
+ }
578
+ /** Element with its cell set; cell 0 is stored as absent. */
579
+ const withCell = (e, cell) => { const { cell: _, ...rest } = e; return cell ? { ...rest, cell } : rest; };
580
+
581
+ export function ringRadius(scene, hubId) {
582
+ const sats = indexOf(scene).satellites.get(hubId) ?? [];
583
+ const maxSat = sats.reduce((a, id) => Math.max(a, bubbleRadius(scene, id)), K.SINGLE_R);
584
+ return bubbleRadius(scene, hubId) + maxSat + K.RING_GAP;
585
+ }
586
+
587
+ // ---------- scene reducers ----------
588
+ export function checkScene(scene) {
589
+ const ids = new Set();
590
+ for (const x of [...scene.bubbles, ...scene.elements, ...scene.links]) {
591
+ if (ids.has(x.id)) throw new Error(`bug: duplicate id ${x.id}`);
592
+ ids.add(x.id);
593
+ }
594
+ const ix = indexOf(scene); // throws on dangling refs
595
+ for (const b of scene.bubbles) {
596
+ const seen = new Set([b.id]);
597
+ let cur = b.orbit?.hubId;
598
+ while (cur) {
599
+ if (seen.has(cur)) throw new UserError('That would make two bubbles orbit each other.');
600
+ seen.add(cur);
601
+ cur = ix.bubbles.get(cur).orbit?.hubId;
602
+ }
603
+ }
604
+ return scene;
605
+ }
606
+
607
+ const mapBubble = (scene, id, f) => {
608
+ if (!indexOf(scene).bubbles.has(id)) throw new Error(`bug: unknown bubble ${id}`);
609
+ return scene.bubbles.map((b) => (b.id === id ? f(b) : b));
610
+ };
611
+ const mapElement = (scene, id, f) => {
612
+ if (!indexOf(scene).elements.has(id)) throw new Error(`bug: unknown element ${id}`);
613
+ return scene.elements.map((e) => (e.id === id ? f(e) : e));
614
+ };
615
+ const dropEmptyUntitled = (scene, bubbleId) => {
616
+ const ix = indexOf(scene);
617
+ const b = ix.bubbles.get(bubbleId);
618
+ if (!b || b.title || ix.members.get(bubbleId).length) return scene;
619
+ return removeBubble(scene, bubbleId);
620
+ };
621
+ function removeBubble(scene, id) {
622
+ return pruneLinks({
623
+ ...scene,
624
+ bubbles: scene.bubbles.filter((b) => b.id !== id).map((b) => (b.orbit?.hubId === id ? { ...b, orbit: null } : b)),
625
+ elements: scene.elements.filter((e) => e.bubbleId !== id),
626
+ links: scene.links,
627
+ });
628
+ }
629
+ function pruneLinks(scene) {
630
+ const alive = new Set(scene.elements.map((e) => e.id));
631
+ return { ...scene, links: scene.links.filter((l) => alive.has(l.from) && alive.has(l.to)) };
632
+ }
633
+ const mapLink = (scene, id, f) => {
634
+ if (!indexOf(scene).links.has(id)) throw new Error(`bug: unknown connection ${id}`);
635
+ return scene.links.map((l) => (l.id === id ? f(l) : l));
636
+ };
637
+
638
+ // ---------- builds: step from one view to the next an element at a time ----------
639
+ /** Build order: elements without a creation counter first (deck order), then by counter. */
640
+ export function buildOrder(elements) {
641
+ return elements.map((e, i) => [e, i]).sort(([a, i], [b, j]) => ((a.seq ?? 0) - (b.seq ?? 0)) || i - j).map(([e]) => e);
642
+ }
643
+ const sameItem = (a, b) => JSON.stringify(a.orbit ? { ...a, x: 0, y: 0 } : a) === JSON.stringify(b.orbit ? { ...b, x: 0, y: 0 } : b);
644
+
645
+ /**
646
+ * Scenes to step through from `from` to `to`, ending exactly at `to`. The first step removes what `to` drops and
647
+ * applies changes to what both share (when there are any); then each element new in `to` arrives on its own step,
648
+ * with its bubble if that is new too. New empty bubbles come last. Connections appear once both ends are present.
649
+ * Returns [to] when there is nothing to add one at a time.
650
+ */
651
+ export function buildSteps(from, to) {
652
+ const had = new Set([...from.bubbles, ...from.elements, ...from.links].map((x) => x.id));
653
+ const present = new Set([...to.bubbles, ...to.elements].filter((x) => had.has(x.id)).map((x) => x.id));
654
+ for (const e of to.elements) if (present.has(e.id)) present.add(e.bubbleId);
655
+ const project = () => {
656
+ const bubbles = to.bubbles.filter((b) => present.has(b.id)).map((b) => (b.orbit && !present.has(b.orbit.hubId) ? { ...b, orbit: null } : b));
657
+ const elements = to.elements.filter((e) => present.has(e.id));
658
+ const links = to.links.filter((l) => present.has(l.from) && present.has(l.to));
659
+ return checkScene({ ...to, bubbles, elements, links });
660
+ };
661
+ const units = [
662
+ ...buildOrder(to.elements.filter((e) => !present.has(e.id))).map((e) => [e.bubbleId, e.id]),
663
+ ...to.bubbles.filter((b) => !present.has(b.id) && !to.elements.some((e) => e.bubbleId === b.id)).map((b) => [b.id]),
664
+ ];
665
+ if (!units.length) return [to];
666
+ const fromIx = indexOf(from);
667
+ const first = project();
668
+ const changed = from.bubbles.length + from.elements.length + from.links.length !== first.bubbles.length + first.elements.length + first.links.length
669
+ || JSON.stringify(from.stage) !== JSON.stringify(to.stage)
670
+ || first.bubbles.some((b) => !fromIx.bubbles.has(b.id) || !sameItem(b, fromIx.bubbles.get(b.id)))
671
+ || first.elements.some((e) => !sameItem(e, fromIx.elements.get(e.id)))
672
+ || first.links.some((l) => JSON.stringify(l) !== JSON.stringify(fromIx.links.get(l.id)));
673
+ const steps = changed ? [first] : [];
674
+ for (const ids of units) { for (const id of ids) present.add(id); steps.push(project()); }
675
+ steps[steps.length - 1] = to;
676
+ return steps;
677
+ }
678
+
679
+ /** Next creation counter for a new element in this scene. */
680
+ const nextSeq = (scene) => scene.elements.reduce((m, e) => Math.max(m, e.seq ?? 0), 0) + 1;
681
+
682
+ export function applyCommand(scene, cmd) {
683
+ switch (cmd.type) {
684
+ case 'batch':
685
+ return cmd.cmds.reduce(applyCommand, scene);
686
+ case 'addBubble': {
687
+ if (scene.bubbles.length >= LIMITS.bubbles) throw new UserError(`A stage holds up to ${LIMITS.bubbles} bubbles.`);
688
+ if (scene.elements.length + cmd.elements.length > LIMITS.elements) throw new UserError(`A stage holds up to ${LIMITS.elements} elements.`);
689
+ return checkScene({
690
+ ...scene,
691
+ bubbles: [...scene.bubbles, cmd.bubble],
692
+ elements: [...scene.elements, ...cmd.elements.map((e, i) => ({ ...e, bubbleId: cmd.bubble.id, seq: nextSeq(scene) + i }))],
693
+ });
694
+ }
695
+ case 'addElement': {
696
+ if (scene.elements.length >= LIMITS.elements) throw new UserError(`A stage holds up to ${LIMITS.elements} elements.`);
697
+ if (!indexOf(scene).bubbles.has(cmd.bubbleId)) throw new Error(`bug: unknown bubble ${cmd.bubbleId}`);
698
+ return checkScene({ ...scene, elements: [...scene.elements, { ...cmd.element, bubbleId: cmd.bubbleId, seq: nextSeq(scene) }] });
699
+ }
700
+ case 'duplicateElement': {
701
+ if (scene.elements.length >= LIMITS.elements) throw new UserError(`A stage holds up to ${LIMITS.elements} elements.`);
702
+ const src = indexOf(scene).elements.get(cmd.id);
703
+ if (!src) throw new Error(`bug: unknown element ${cmd.id}`);
704
+ const at = scene.elements.indexOf(src) + 1;
705
+ return checkScene({ ...scene, elements: [...scene.elements.slice(0, at), { ...src, id: cmd.newId, seq: nextSeq(scene) }, ...scene.elements.slice(at)] });
706
+ }
707
+ case 'updateElement':
708
+ return checkScene({ ...scene, elements: mapElement(scene, cmd.id, (e) => ({ ...e, ...cmd.patch })) });
709
+ case 'updateBubble':
710
+ return checkScene({ ...scene, bubbles: mapBubble(scene, cmd.id, (b) => ({ ...b, ...cmd.patch })) });
711
+ case 'deleteElement': {
712
+ const e = indexOf(scene).elements.get(cmd.id);
713
+ if (!e) throw new Error(`bug: unknown element ${cmd.id}`);
714
+ return checkScene(dropEmptyUntitled(pruneLinks({ ...scene, elements: scene.elements.filter((x) => x.id !== cmd.id) }), e.bubbleId));
715
+ }
716
+ case 'addLink': {
717
+ const ix = indexOf(scene);
718
+ if (scene.links.length >= LIMIT_LINKS) throw new UserError(`A stage holds up to ${LIMIT_LINKS} connections.`);
719
+ if (cmd.link.from === cmd.link.to) throw new UserError('Connect two different elements.');
720
+ if (!ix.elements.has(cmd.link.from) || !ix.elements.has(cmd.link.to)) throw new Error('bug: connection to a missing element');
721
+ if (scene.links.some((l) => l.from === cmd.link.from && l.to === cmd.link.to && l.label === cmd.link.label)) throw new UserError(cmd.link.label ? `Those two elements already have a “${cmd.link.label}” connection in that direction.` : 'Those two elements are already connected in that direction. Give the new connection a label to add another.');
722
+ return checkScene({ ...scene, links: [...scene.links, cmd.link] });
723
+ }
724
+ case 'updateLink':
725
+ return checkScene({ ...scene, links: mapLink(scene, cmd.id, (l) => ({ ...l, ...cmd.patch })) });
726
+ case 'deleteLink':
727
+ if (!indexOf(scene).links.has(cmd.id)) throw new Error(`bug: unknown connection ${cmd.id}`);
728
+ return checkScene({ ...scene, links: scene.links.filter((l) => l.id !== cmd.id) });
729
+ case 'deleteBubble':
730
+ if (!indexOf(scene).bubbles.has(cmd.id)) throw new Error(`bug: unknown bubble ${cmd.id}`);
731
+ return checkScene(removeBubble(scene, cmd.id));
732
+ case 'moveElement': {
733
+ const e = indexOf(scene).elements.get(cmd.id);
734
+ if (!e) throw new Error(`bug: unknown element ${cmd.id}`);
735
+ if (!indexOf(scene).bubbles.has(cmd.toBubbleId)) throw new Error(`bug: unknown bubble ${cmd.toBubbleId}`);
736
+ if (e.bubbleId === cmd.toBubbleId && cellOf(e) === (cmd.cell ?? 0)) return scene;
737
+ const moved = { ...scene, elements: [...scene.elements.filter((x) => x.id !== cmd.id), withCell({ ...e, bubbleId: cmd.toBubbleId }, cmd.cell ?? 0)] };
738
+ return checkScene(dropEmptyUntitled(moved, e.bubbleId));
739
+ }
740
+ case 'detachElement': {
741
+ if (scene.bubbles.length >= LIMITS.bubbles) throw new UserError(`A stage holds up to ${LIMITS.bubbles} bubbles.`);
742
+ const withBubble = { ...scene, bubbles: [...scene.bubbles, { id: cmd.newBubbleId, title: '', hue: cmd.hue, x: cmd.x, y: cmd.y, orbit: null, tags: [] }] };
743
+ const from = indexOf(scene).elements.get(cmd.id)?.bubbleId;
744
+ return checkScene(dropEmptyUntitled({ ...withBubble, elements: mapElement(withBubble, cmd.id, (e) => withCell({ ...e, bubbleId: cmd.newBubbleId }, 0)) }, from));
745
+ }
746
+ case 'mergeBubble': {
747
+ const ix = indexOf(scene);
748
+ const from = ix.bubbles.get(cmd.fromId);
749
+ if (!from || !ix.bubbles.has(cmd.intoId) || cmd.fromId === cmd.intoId) throw new Error(`bug: bad merge ${cmd.fromId} → ${cmd.intoId}`);
750
+ const titleEl = from.title ? [withCell({ id: cmd.titleElementId, bubbleId: cmd.intoId, label: from.title, icon: null, imageId: null, tags: from.tags, hue: null, seq: nextSeq(scene) }, cmd.cell ?? 0)] : [];
751
+ if (scene.elements.length + titleEl.length > LIMITS.elements) throw new UserError(`A stage holds up to ${LIMITS.elements} elements.`);
752
+ const moved = {
753
+ ...scene,
754
+ elements: [...scene.elements.filter((e) => e.bubbleId !== cmd.fromId), ...scene.elements.filter((e) => e.bubbleId === cmd.fromId).map((e) => withCell({ ...e, bubbleId: cmd.intoId }, cmd.cell ?? 0)), ...titleEl],
755
+ };
756
+ return checkScene(removeBubble(moved, cmd.fromId));
757
+ }
758
+ case 'setStage': {
759
+ const stage = { ...scene.stage, ...cmd.patch };
760
+ if (!Value.Check(StageSchema, stage)) throw new Error(`bug: bad stage patch ${JSON.stringify(cmd.patch)}`);
761
+ return { ...scene, stage };
762
+ }
763
+ case 'setHome':
764
+ return checkScene({ ...scene, bubbles: mapBubble(scene, cmd.id, (b) => ({ ...b, x: cmd.x, y: cmd.y })) });
765
+ case 'setOrbit': {
766
+ if (cmd.hubId === cmd.id) throw new UserError('A bubble cannot orbit itself.');
767
+ if (cmd.hubId !== null && !indexOf(scene).bubbles.has(cmd.hubId)) throw new Error(`bug: unknown hub ${cmd.hubId}`);
768
+ return checkScene({ ...scene, bubbles: mapBubble(scene, cmd.id, (b) => ({ ...b, orbit: cmd.hubId === null ? null : { hubId: cmd.hubId } })) });
769
+ }
770
+ default:
771
+ throw new Error(`bug: unknown command ${cmd.type}`);
772
+ }
773
+ }
774
+
775
+ // ---------- runtime (physics state) ----------
776
+ export function hashPhase(id) {
777
+ let h = 2166136261;
778
+ for (let i = 0; i < id.length; i++) { h ^= id.charCodeAt(i); h = Math.imul(h, 16777619); }
779
+ return ((h >>> 0) / 4294967296) * Math.PI * 2;
780
+ }
781
+
782
+ const bubbleBody = (b, x, y, r) => ({ id: b.id, x, y, vx: 0, vy: 0, r, vr: 0, w2: 0, v2: 0, w3: 0, v3: 0, phase: hashPhase(b.id), dying: false, followId: null, hue: b.hue, title: b.title, lit: 1 });
783
+ const elementBody = (e, x, y, s) => ({ id: e.id, x, y, vx: 0, vy: 0, s, vs: 0, dying: false, lit: 1, bubbleId: e.bubbleId, label: e.label, icon: e.icon, imageId: e.imageId, hue: e.hue, textHue: e.textHue ?? null, strike: !!e.strike, fill: !!e.fill });
784
+ const kick = (b, amt) => ({ ...b, v2: b.v2 + amt, v3: b.v3 - amt * 0.7 });
785
+ const linkBody = (l, elements, a) => {
786
+ const A = elements[l.from], B = elements[l.to];
787
+ if (!A || !B) throw new Error(`bug: connection ${l.id} has an end without a body`);
788
+ return { id: l.id, from: l.from, to: l.to, label: l.label, head: l.head, dash: l.dash, e: l.elasticity, op: l.opacity ?? 1, cx: (A.x + B.x) / 2, cy: (A.y + B.y) / 2, vx: 0, vy: 0, a, lit: 1, dying: false };
789
+ };
790
+
791
+ export function createRuntime(scene, camera) {
792
+ const bubbles = {};
793
+ for (const b of scene.bubbles) bubbles[b.id] = bubbleBody(b, b.x, b.y, bubbleRadius(scene, b.id));
794
+ const t0 = { bubbles, elements: {}, bridges: [], camera: { ...camera } };
795
+ // Satellites start on their ring so a reload does not replay the bud animation.
796
+ const ot = orbitTargets(scene, t0);
797
+ for (const [id, p] of Object.entries(ot)) bubbles[id] = { ...bubbles[id], x: p.x, y: p.y };
798
+ const elements = {};
799
+ for (const e of scene.elements) {
800
+ const b = bubbles[e.bubbleId];
801
+ const o = slotOffset(scene, e.id);
802
+ elements[e.id] = elementBody(e, b.x + o.x, b.y + o.y, 1);
803
+ }
804
+ const links = Object.fromEntries(scene.links.map((l) => [l.id, linkBody(l, elements, 1)]));
805
+ return { ...t0, bubbles, elements, links, t: 0, stage: stageTarget(scene.stage) };
806
+ }
807
+
808
+ const centroid = (pts) => ({ x: pts.reduce((a, p) => a + p.x, 0) / pts.length, y: pts.reduce((a, p) => a + p.y, 0) / pts.length });
809
+ const argmaxCount = (xs) => {
810
+ const c = new Map();
811
+ for (const x of xs) c.set(x, (c.get(x) ?? 0) + 1);
812
+ let best = null, n = 0;
813
+ for (const [k, v] of c) if (v > n) { best = k; n = v; }
814
+ return best;
815
+ };
816
+
817
+ /** Reconcile physics bodies with a new scene. Newborn bubbles bud from where their members are now; removed ones shrink toward where their members went. */
818
+ export function syncRuntime(rt, prev, next, hints = { spawnFrom: {} }) {
819
+ const bubbles = { ...rt.bubbles };
820
+ const elements = { ...rt.elements };
821
+ const bridges = [...rt.bridges];
822
+ const nix = indexOf(next);
823
+ const living = (id) => bubbles[id] && !bubbles[id].dying;
824
+
825
+ // 1. bubbles that are new (or revived ghosts)
826
+ const spawnAt = {};
827
+ for (const b of next.bubbles) {
828
+ if (living(b.id)) { bubbles[b.id] = { ...bubbles[b.id], hue: b.hue, title: b.title }; continue; }
829
+ if (bubbles[b.id]?.dying) { bubbles[b.id] = { ...bubbles[b.id], dying: false, followId: null, hue: b.hue, title: b.title }; continue; }
830
+ const present = nix.members.get(b.id).filter((eid) => elements[eid] && !elements[eid].dying);
831
+ let pos, parent = null, r0;
832
+ if (present.length) {
833
+ pos = centroid(present.map((eid) => elements[eid]));
834
+ parent = argmaxCount(present.map((eid) => elements[eid].bubbleId).filter(living));
835
+ r0 = K.ELEM_BALL;
836
+ } else if (b.orbit && living(b.orbit.hubId)) {
837
+ const h = bubbles[b.orbit.hubId];
838
+ pos = { x: h.x + (b.x - h.x) * 0.3, y: h.y + (b.y - h.y) * 0.3 };
839
+ parent = b.orbit.hubId;
840
+ r0 = 10;
841
+ } else {
842
+ pos = { x: b.x, y: b.y };
843
+ r0 = 4;
844
+ }
845
+ bubbles[b.id] = kick(bubbleBody(b, pos.x, pos.y, r0), 0.6);
846
+ spawnAt[b.id] = pos;
847
+ if (parent) {
848
+ bridges.push({ a: parent, b: b.id, k: K.BLEND, broken: false });
849
+ bubbles[parent] = kick(bubbles[parent], 0.9);
850
+ }
851
+ }
852
+
853
+ // 2. bubbles that are gone become shrinking ghosts
854
+ for (const [id, body] of Object.entries(bubbles)) {
855
+ if (body.dying || nix.bubbles.has(id)) continue;
856
+ const dests = Object.values(elements).filter((e) => e.bubbleId === id && !e.dying && nix.elements.has(e.id)).map((e) => nix.elements.get(e.id).bubbleId);
857
+ const follow = argmaxCount(dests);
858
+ bubbles[id] = { ...body, dying: true, followId: follow };
859
+ if (follow) {
860
+ bridges.push({ a: follow, b: id, k: K.BLEND, broken: false });
861
+ bubbles[follow] = kick(bubbles[follow], 0.9);
862
+ }
863
+ }
864
+
865
+ // 3. elements
866
+ for (const e of next.elements) {
867
+ const cur = elements[e.id];
868
+ const srcId = hints.spawnFrom[e.id];
869
+ if (!cur && srcId) {
870
+ const src = elements[srcId];
871
+ if (!src) throw new Error(`bug: duplicate source ${srcId} has no body`);
872
+ elements[e.id] = { ...elementBody(e, src.x + 1, src.y + 1, 0.55), vx: 140, vy: -60 };
873
+ elements[srcId] = { ...src, vx: src.vx - 140, vy: src.vy + 60 };
874
+ if (living(e.bubbleId)) bubbles[e.bubbleId] = kick(bubbles[e.bubbleId], 0.8);
875
+ continue;
876
+ }
877
+ if (!cur || cur.dying) {
878
+ const bp = spawnAt[e.bubbleId] ?? bubbles[e.bubbleId];
879
+ const o = slotOffset(next, e.id);
880
+ elements[e.id] = { ...elementBody(e, bp.x + o.x, bp.y + o.y, 0), ...(cur ? { x: cur.x, y: cur.y, s: cur.s } : {}) };
881
+ continue;
882
+ }
883
+ if (cur.bubbleId !== e.bubbleId && living(e.bubbleId)) bubbles[e.bubbleId] = kick(bubbles[e.bubbleId], 0.7);
884
+ elements[e.id] = { ...cur, bubbleId: e.bubbleId, label: e.label, icon: e.icon, imageId: e.imageId, hue: e.hue, textHue: e.textHue ?? null, strike: !!e.strike, fill: !!e.fill };
885
+ }
886
+ for (const [id, body] of Object.entries(elements)) {
887
+ if (!body.dying && !nix.elements.has(id)) elements[id] = { ...body, dying: true };
888
+ }
889
+
890
+ // 4. connections fade in and out
891
+ const links = { ...rt.links };
892
+ for (const l of next.links) {
893
+ const cur = links[l.id];
894
+ const meta = { from: l.from, to: l.to, label: l.label, head: l.head, dash: l.dash, e: l.elasticity, op: l.opacity ?? 1 };
895
+ links[l.id] = cur ? { ...cur, ...meta, dying: false } : linkBody(l, elements, 0);
896
+ }
897
+ for (const [id, body] of Object.entries(links)) {
898
+ if (!body.dying && !nix.links.has(id)) links[id] = { ...body, dying: true };
899
+ }
900
+ return { ...rt, bubbles, elements, bridges, links };
901
+ }
902
+
903
+ /** Even angular spacing of each hub's satellites, keeping their current cyclic order. */
904
+ export function orbitTargets(scene, rt) {
905
+ const ix = indexOf(scene);
906
+ const out = {};
907
+ for (const [hubId, sats] of ix.satellites) {
908
+ const hub = rt.bubbles[hubId];
909
+ if (!hub) continue;
910
+ const ring = ringRadius(scene, hubId);
911
+ const withAngle = sats.map((id) => {
912
+ const body = rt.bubbles[id];
913
+ const p = body ?? ix.bubbles.get(id);
914
+ return { id, th: Math.atan2(p.y - hub.y, p.x - hub.x) };
915
+ }).sort((a, b) => a.th - b.th || (a.id < b.id ? -1 : 1));
916
+ const n = withAngle.length;
917
+ const stepA = (Math.PI * 2) / n;
918
+ let sx = 0, sy = 0;
919
+ withAngle.forEach((s, i) => { sx += Math.cos(s.th - i * stepA); sy += Math.sin(s.th - i * stepA); });
920
+ const off = Math.atan2(sy, sx);
921
+ withAngle.forEach((s, i) => { out[s.id] = { x: hub.x + ring * Math.cos(off + i * stepA), y: hub.y + ring * Math.sin(off + i * stepA) }; });
922
+ }
923
+ return out;
924
+ }
925
+
926
+ /** Angle (radians) in the widest gap between a hub's satellites; where a new one should bud. */
927
+ export function gapAngle(scene, rt, hubId) {
928
+ const hub = rt.bubbles[hubId];
929
+ if (!hub) throw new Error(`bug: gapAngle for missing hub ${hubId}`);
930
+ const sats = indexOf(scene).satellites.get(hubId) ?? [];
931
+ const ths = sats.map((id) => rt.bubbles[id]).filter(Boolean).map((b) => Math.atan2(b.y - hub.y, b.x - hub.x)).sort((a, b) => a - b);
932
+ if (ths.length === 0) return 0;
933
+ if (ths.length === 1) return ths[0] + Math.PI;
934
+ let best = 0, bestGap = -1;
935
+ ths.forEach((th, i) => {
936
+ const nxt = i === ths.length - 1 ? ths[0] + Math.PI * 2 : ths[i + 1];
937
+ if (nxt - th > bestGap) { bestGap = nxt - th; best = th + (nxt - th) / 2; }
938
+ });
939
+ return best;
940
+ }
941
+
942
+ /** Write current ring positions into the homes of orbiting bubbles so a saved view reproduces the layout. */
943
+ export function freezeScene(scene, rt) {
944
+ return { ...scene, bubbles: scene.bubbles.map((b) => (b.orbit && rt.bubbles[b.id] && !rt.bubbles[b.id].dying ? { ...b, x: Math.round(rt.bubbles[b.id].x), y: Math.round(rt.bubbles[b.id].y) } : b)) };
945
+ }
946
+
947
+ export function detachGap(scene, rt, elementId, px, py) {
948
+ const e = rt.elements[elementId];
949
+ if (!e) throw new Error(`bug: detachGap for missing element ${elementId}`);
950
+ const b = rt.bubbles[e.bubbleId];
951
+ return Math.hypot(px - b.x, py - b.y) - bubbleRadius(scene, e.bubbleId);
952
+ }
953
+
954
+ const P = { PULL: 60, LEAN: 22, TUG: 900, KB: 40, CB: 6.5, KE: 160, CE: 11, KR: 180, CR: 10, KS: 220, CS: 16, W2: 15, W3: 20.7, CW: 3.2, EXC: 0.0006, REP: 30, TEN: 14, WMAX: 0.16 };
955
+ export const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
956
+
957
+ /** Lane of each connection among those joining the same two elements: 0 when alone, else spread ±0.5, ±1, … around the middle. */
958
+ const laneMemo = new WeakMap();
959
+ export function linkLanes(scene) {
960
+ const hit = laneMemo.get(scene);
961
+ if (hit) return hit;
962
+ const groups = new Map();
963
+ for (const l of scene.links) {
964
+ const k = l.from < l.to ? `${l.from}|${l.to}` : `${l.to}|${l.from}`;
965
+ groups.set(k, [...(groups.get(k) ?? []), l.id]);
966
+ }
967
+ const out = new Map();
968
+ for (const ids of groups.values()) ids.forEach((id, i) => out.set(id, i - (ids.length - 1) / 2));
969
+ laneMemo.set(scene, out);
970
+ return out;
971
+ }
972
+
973
+ /** Advance the simulation by dt seconds. Pure: same inputs, same output. */
974
+ export function step(rt, scene, input, dt) {
975
+ const drag = input.drag;
976
+ const ix = indexOf(scene);
977
+ const ot = orbitTargets(scene, rt);
978
+ const ids = Object.keys(rt.bubbles);
979
+ const f = Object.fromEntries(ids.map((id) => [id, { x: 0, y: 0 }]));
980
+ const draggedBubble = drag?.kind === 'bubble' ? drag.id : null;
981
+ const bridged = new Set(rt.bridges.filter((b) => !b.broken).flatMap((b) => [`${b.a}|${b.b}`, `${b.b}|${b.a}`]));
982
+
983
+ for (let i = 0; i < ids.length; i++) {
984
+ const A = rt.bubbles[ids[i]];
985
+ if (A.dying || A.id === draggedBubble) continue;
986
+ for (let j = i + 1; j < ids.length; j++) {
987
+ const B = rt.bubbles[ids[j]];
988
+ if (B.dying || B.id === draggedBubble || bridged.has(`${A.id}|${B.id}`)) continue;
989
+ const dx = B.x - A.x, dy = B.y - A.y;
990
+ const d = Math.hypot(dx, dy) || 0.001;
991
+ const overlap = A.r + B.r + 16 - d;
992
+ if (overlap <= 0) continue;
993
+ const push = Math.min(overlap, 60) * P.REP;
994
+ f[A.id].x -= (dx / d) * push; f[A.id].y -= (dy / d) * push;
995
+ f[B.id].x += (dx / d) * push; f[B.id].y += (dy / d) * push;
996
+ }
997
+ }
998
+ // A grabbed connection pulls the bubbles at both ends toward the pointer once it is stretched past
999
+ // the distance each had when grabbed, and makes the end elements lean out of their bubbles.
1000
+ const rope = drag?.kind === 'rope' && rt.links[drag.id] ? { id: drag.id, x: drag.x, y: drag.y, rest: drag.rest } : null;
1001
+ const ropeTug = {};
1002
+ if (rope) {
1003
+ const l = rt.links[rope.id];
1004
+ for (const eid of [l.from, l.to]) {
1005
+ const e = rt.elements[eid];
1006
+ if (!e || e.dying) continue;
1007
+ const b = rt.bubbles[e.bubbleId];
1008
+ if (!b || b.dying) continue;
1009
+ const dx = rope.x - b.x, dy = rope.y - b.y, d = Math.hypot(dx, dy) || 1;
1010
+ const rest = rope.rest[eid];
1011
+ if (rest === undefined) throw new Error(`bug: no rest length for rope end ${eid}`);
1012
+ const over = clamp(d - rest, 0, 500);
1013
+ f[b.id].x += (dx / d) * over * P.PULL; f[b.id].y += (dy / d) * over * P.PULL;
1014
+ const ex = rope.x - e.x, ey = rope.y - e.y, ed = Math.hypot(ex, ey) || 1;
1015
+ const lean = Math.min(over, 120) * P.LEAN;
1016
+ ropeTug[eid] = { x: (ex / ed) * lean, y: (ey / ed) * lean };
1017
+ }
1018
+ }
1019
+ let tether = null;
1020
+ if (drag?.kind === 'element' && drag.tether) {
1021
+ const e = rt.elements[drag.id];
1022
+ const b = rt.bubbles[e.bubbleId];
1023
+ const dx = drag.x - b.x, dy = drag.y - b.y;
1024
+ const d = Math.hypot(dx, dy) || 0.001;
1025
+ const gap = d - bubbleRadius(scene, e.bubbleId);
1026
+ if (gap > 0) {
1027
+ const t = Math.min(gap, K.DETACH_GAP) * P.TEN;
1028
+ f[b.id].x += (dx / d) * t; f[b.id].y += (dy / d) * t;
1029
+ }
1030
+ tether = { bubbleId: b.id, elementId: e.id, gap };
1031
+ }
1032
+
1033
+ const bubbles = {};
1034
+ for (const id of ids) {
1035
+ const b = rt.bubbles[id];
1036
+ let x, y, vx, vy;
1037
+ if (id === draggedBubble) {
1038
+ x = drag.x; y = drag.y;
1039
+ vx = b.vx + ((x - b.x) / dt - b.vx) * 0.25;
1040
+ vy = b.vy + ((y - b.y) / dt - b.vy) * 0.25;
1041
+ } else {
1042
+ let tx = b.x, ty = b.y;
1043
+ if (b.dying) {
1044
+ const fb = b.followId && rt.bubbles[b.followId];
1045
+ if (fb) { tx = fb.x; ty = fb.y; }
1046
+ } else {
1047
+ const sb = ix.bubbles.get(id);
1048
+ if (!sb) throw new Error(`bug: living body ${id} has no scene bubble`);
1049
+ const o = ot[id];
1050
+ tx = o ? o.x : sb.x; ty = o ? o.y : sb.y;
1051
+ }
1052
+ const ax = P.KB * (tx - b.x) - P.CB * b.vx + f[id].x;
1053
+ const ay = P.KB * (ty - b.y) - P.CB * b.vy + f[id].y;
1054
+ vx = b.vx + ax * dt; vy = b.vy + ay * dt;
1055
+ x = b.x + vx * dt; y = b.y + vy * dt;
1056
+ }
1057
+ const tr = b.dying ? 0 : bubbleRadius(scene, id);
1058
+ const vr = b.vr + (P.KR * (tr - b.r) - P.CR * b.vr) * dt;
1059
+ const r = Math.max(0, b.r + vr * dt);
1060
+ if (b.dying && r < 1.5) continue;
1061
+ const dv = Math.hypot(vx - b.vx, vy - b.vy);
1062
+ const exc = Math.min(dv * P.EXC, 0.5);
1063
+ const v2 = b.v2 + (-P.W2 * P.W2 * b.w2 - P.CW * b.v2) * dt + exc;
1064
+ const v3 = b.v3 + (-P.W3 * P.W3 * b.w3 - P.CW * b.v3) * dt - exc * 0.6;
1065
+ const litT = !input.match || b.dying || input.match.bubbles.has(id) ? 1 : 0;
1066
+ bubbles[id] = { ...b, lit: b.lit + (litT - b.lit) * (1 - Math.exp(-dt * 9)), x, y, vx, vy, r, vr, v2, v3, w2: clamp(b.w2 + v2 * dt, -P.WMAX, P.WMAX), w3: clamp(b.w3 + v3 * dt, -P.WMAX, P.WMAX) };
1067
+ }
1068
+
1069
+ // Elastic connections tug their two elements toward each other.
1070
+ const tug = {};
1071
+ for (const l of Object.values(rt.links)) {
1072
+ if (l.dying || l.e <= 0) continue;
1073
+ const A = rt.elements[l.from], B = rt.elements[l.to];
1074
+ if (!A || !B) continue;
1075
+ const dx = B.x - A.x, dy = B.y - A.y, d = Math.hypot(dx, dy) || 1;
1076
+ const m = l.e * P.TUG;
1077
+ tug[A.id] = { x: (tug[A.id]?.x ?? 0) + (dx / d) * m, y: (tug[A.id]?.y ?? 0) + (dy / d) * m };
1078
+ tug[B.id] = { x: (tug[B.id]?.x ?? 0) - (dx / d) * m, y: (tug[B.id]?.y ?? 0) - (dy / d) * m };
1079
+ }
1080
+
1081
+ const elements = {};
1082
+ for (const [id, e] of Object.entries(rt.elements)) {
1083
+ let x, y, vx, vy;
1084
+ const follow = drag?.kind === 'element' && (drag.id === id ? { x: 0, y: 0 } : drag.offsets?.[id]); // offsets: other grabbed elements, relative to the pointer's
1085
+ if (follow) {
1086
+ x = drag.x + follow.x; y = drag.y + follow.y;
1087
+ vx = e.vx + ((x - e.x) / dt - e.vx) * 0.25;
1088
+ vy = e.vy + ((y - e.y) / dt - e.vy) * 0.25;
1089
+ } else {
1090
+ let tx = e.x, ty = e.y;
1091
+ const host = bubbles[e.bubbleId];
1092
+ if (!e.dying) {
1093
+ if (!host) throw new Error(`bug: element ${id} lost its bubble ${e.bubbleId}`);
1094
+ const o = slotOffset(scene, id);
1095
+ tx = host.x + o.x; ty = host.y + o.y;
1096
+ } else if (host) {
1097
+ tx = host.x; ty = host.y;
1098
+ }
1099
+ const tg = e.dying ? null : tug[id];
1100
+ const rg = e.dying ? null : ropeTug[id];
1101
+ vx = e.vx + (P.KE * (tx - e.x) - P.CE * e.vx + (tg ? tg.x : 0) + (rg ? rg.x : 0)) * dt;
1102
+ vy = e.vy + (P.KE * (ty - e.y) - P.CE * e.vy + (tg ? tg.y : 0) + (rg ? rg.y : 0)) * dt;
1103
+ x = e.x + vx * dt; y = e.y + vy * dt;
1104
+ }
1105
+ const ts = e.dying ? 0 : 1;
1106
+ const vs = e.vs + (P.KS * (ts - e.s) - P.CS * e.vs) * dt;
1107
+ const s = Math.max(0, e.s + vs * dt);
1108
+ if (e.dying && s < 0.03) continue;
1109
+ const litT = !input.match || e.dying || input.match.elements.has(id) ? 1 : 0;
1110
+ elements[id] = { ...e, lit: e.lit + (litT - e.lit) * (1 - Math.exp(-dt * 9)), x, y, vx, vy, s, vs };
1111
+ }
1112
+
1113
+ const bridges = [];
1114
+ for (const br of rt.bridges) {
1115
+ const A = bubbles[br.a], B = bubbles[br.b];
1116
+ if (!A || !B) continue;
1117
+ const gap = Math.hypot(A.x - B.x, A.y - B.y) - A.r - B.r;
1118
+ const broken = br.broken || gap > K.BREAK_GAP;
1119
+ const k = br.k + ((broken ? 0 : K.BLEND) - br.k) * (1 - Math.exp(-dt * 14));
1120
+ if (broken && k < 0.5) continue;
1121
+ bridges.push({ ...br, k, broken });
1122
+ }
1123
+
1124
+ const ct = input.cameraTarget;
1125
+ const a = 1 - Math.exp(-dt * 5);
1126
+ const c = rt.camera;
1127
+ const camera = { x: c.x + (ct.x - c.x) * a, y: c.y + (ct.y - c.y) * a, zoom: c.zoom * Math.exp(Math.log(ct.zoom / c.zoom) * a) };
1128
+
1129
+ const lanes = linkLanes(scene);
1130
+ const links = {};
1131
+ for (const [id, l] of Object.entries(rt.links)) {
1132
+ const A = elements[l.from], B = elements[l.to];
1133
+ if (!A || !B) continue;
1134
+ const a = l.a + ((l.dying ? 0 : 1) - l.a) * (1 - Math.exp(-dt * 10));
1135
+ if (l.dying && a < 0.02) continue;
1136
+ // Parallel connections between the same two elements bow apart, each in its own lane.
1137
+ const laneN = lanes.get(id) ?? 0;
1138
+ const [P, Q] = l.from < l.to ? [A, B] : [B, A];
1139
+ const ux = Q.x - P.x, uy = Q.y - P.y, ul = Math.hypot(ux, uy) || 1;
1140
+ const mx = (A.x + B.x) / 2 + (-uy / ul) * laneN * K.LANE, my = (A.y + B.y) / 2 + (ux / ul) * laneN * K.LANE;
1141
+ const lit = l.lit + ((!input.match || l.dying || input.match.links.has(id) ? 1 : 0) - l.lit) * (1 - Math.exp(-dt * 9));
1142
+ if (rope && rope.id === id) {
1143
+ // Grabbed: the curve passes through the pointer (linkGeometry adds the chips' vertical offset back).
1144
+ const chipOff = ((A.icon || A.imageId ? -8 : 0) + (B.icon || B.imageId ? -8 : 0)) / 2;
1145
+ links[id] = { ...l, a, lit, cx: rope.x, cy: rope.y - chipOff, vx: (rope.x - l.cx) / dt * 0.2, vy: (rope.y - chipOff - l.cy) / dt * 0.2 };
1146
+ continue;
1147
+ }
1148
+ if (l.e <= 0) { links[id] = { ...l, a, lit, cx: mx, cy: my, vx: 0, vy: 0 }; continue; }
1149
+ const sag = l.e * Math.hypot(B.x - A.x, B.y - A.y) * 0.14;
1150
+ const k = 420 * (1 - l.e) + 14 * l.e;
1151
+ const c = 34 * (1 - l.e) + 2.4 * l.e;
1152
+ const vx = l.vx + (k * (mx - l.cx) - c * l.vx) * dt;
1153
+ const vy = l.vy + (k * (my + sag - l.cy) - c * l.vy) * dt;
1154
+ links[id] = { ...l, a, lit, vx, vy, cx: l.cx + vx * dt, cy: l.cy + vy * dt };
1155
+ }
1156
+
1157
+ const st = stageTarget(scene.stage);
1158
+ const sa = 1 - Math.exp(-dt * 6);
1159
+ const stage = {
1160
+ // Hold the old colour while fading out, so a custom backdrop dissolves into the theme instead of flashing through black.
1161
+ rgb: st.a > 0 ? rt.stage.rgb.map((v, i) => v + (st.rgb[i] - v) * sa) : rt.stage.rgb,
1162
+ a: rt.stage.a + (st.a - rt.stage.a) * sa,
1163
+ grid: rt.stage.grid + (st.grid - rt.stage.grid) * sa,
1164
+ };
1165
+
1166
+ return { bubbles, elements, bridges, camera, tether, links, t: rt.t + dt, stage };
1167
+ }
1168
+
1169
+ /** World-space polyline of a connection, trimmed at both chips, plus its label point and end tangents. Null when an end has no body. */
1170
+ export function linkGeometry(rt, l) {
1171
+ const A = rt.elements[l.from], B = rt.elements[l.to];
1172
+ if (!A || !B) return null;
1173
+ const chipY = (e) => (e.icon || e.imageId ? -8 : 0);
1174
+ const p0 = { x: A.x, y: A.y + chipY(A) }, p2 = { x: B.x, y: B.y + chipY(B) };
1175
+ const c = { x: l.cx, y: l.cy + (chipY(A) + chipY(B)) / 2 };
1176
+ const q = { x: 2 * c.x - (p0.x + p2.x) / 2, y: 2 * c.y - (p0.y + p2.y) / 2 };
1177
+ const at = (t) => ({ x: (1 - t) * (1 - t) * p0.x + 2 * (1 - t) * t * q.x + t * t * p2.x, y: (1 - t) * (1 - t) * p0.y + 2 * (1 - t) * t * q.y + t * t * p2.y });
1178
+ const N = 32;
1179
+ const all = Array.from({ length: N + 1 }, (_, i) => at(i / N));
1180
+ const ra = (K.ELEM_R + 6) * A.s, rb = (K.ELEM_R + 6) * B.s;
1181
+ const pts = all.filter((p) => Math.hypot(p.x - p0.x, p.y - p0.y) > ra && Math.hypot(p.x - p2.x, p.y - p2.y) > rb);
1182
+ if (pts.length < 2) return null;
1183
+ return { pts, mid: at(0.5) };
1184
+ }
1185
+
1186
+ /** Element ids a connect selector resolves to when the message lands. */
1187
+ export function resolveSelector(scene, sel, link) {
1188
+ switch (sel.kind) {
1189
+ case 'source': return [link.from];
1190
+ case 'target': return [link.to];
1191
+ case 'query': {
1192
+ const f = { q: sel.q, tags: sel.tags, icons: sel.icons };
1193
+ if (!filterActive(f)) return [];
1194
+ // Connections are left out: in the filter a matching connection lights its ends, but a selector wants elements matching on their own.
1195
+ const own = filterMatch({ ...scene, links: [] }, f);
1196
+ // Unlike the filter bar (any of), a selector wants every tag: system1 + database means system1's databases.
1197
+ // An element carries its bubble's tags too.
1198
+ const ix = indexOf(scene);
1199
+ const hasAll = (e) => sel.tags.every((t) => e.tags.includes(t) || ix.bubbles.get(e.bubbleId).tags.includes(t));
1200
+ return scene.elements.filter((e) => own.elements.has(e.id) && hasAll(e)).map((e) => e.id);
1201
+ }
1202
+ default: throw new Error(`bug: unknown selector kind ${sel.kind}`);
1203
+ }
1204
+ }
1205
+
1206
+ /** Short human summary of a message's effect, e.g. "Add “Postgres”". */
1207
+ export function describeAction(a, scene) {
1208
+ const sel = (s) => (s.kind === 'source' ? 'source' : s.kind === 'target' ? 'target'
1209
+ : [s.q && `“${s.q}”`, ...s.tags.map((t) => `#${t}`), ...s.icons.map((k) => ICONS[k][0])].filter(Boolean).join(' + ') || 'nothing');
1210
+ switch (a.kind) {
1211
+ case 'add': return a.label ? `Add “${a.label}”` : `Add ${ICONS[a.icon]?.[0] ?? 'an'} icon`;
1212
+ case 'split': return `Split ${sel(a.which ?? { kind: 'target' })} out`;
1213
+ case 'clone': return `Clone ${sel(a.which ?? { kind: 'target' })}`;
1214
+ case 'remove': return `Remove ${sel(a.which ?? { kind: 'target' })}`;
1215
+ case 'connect': return `Connect ${sel(a.from)} → ${sel(a.to)}`;
1216
+ case 'send': return `Send “${a.message}” from ${sel(a.from)}`;
1217
+ default: throw new Error(`bug: unknown action ${a.kind}`);
1218
+ }
1219
+ }
1220
+ export const describeMessage = (m, scene) => m.actions.map((a) => describeAction(a, scene)).join(', then ');
1221
+
1222
+ /** Labels of the messages each of these elements can send, for the editor's "send" picker. */
1223
+ export function sendableMessages(scene, elementIds) {
1224
+ const ix = indexOf(scene);
1225
+ const out = new Map(); // label → { senders: Set, fields: Set }
1226
+ for (const id of elementIds) {
1227
+ if (!ix.elements.has(id)) continue;
1228
+ for (const l of scene.links) if (l.from === id) for (const m of l.messages) {
1229
+ const o = out.get(m.label) ?? { senders: new Set(), fields: new Set() };
1230
+ o.senders.add(ix.elements.get(id).label || 'unnamed');
1231
+ for (const f of m.fields ?? []) o.fields.add(f);
1232
+ out.set(m.label, o);
1233
+ }
1234
+ }
1235
+ return [...out.entries()].map(([label, o]) => ({ label, senders: [...o.senders], fields: [...o.fields] })).sort((a, b) => a.label.localeCompare(b.label));
1236
+ }
1237
+
1238
+ /**
1239
+ * What one action does, given the stage as earlier actions of the same message left it.
1240
+ * Returns { cmd | null, hints, sends } or throws a UserError saying why it has nothing to do.
1241
+ */
1242
+ /** The action with this message's field values filled into its text; throws a UserError when a result is unusable. */
1243
+ export function fillAction(a, values) {
1244
+ const t = (s) => fillText(s, values);
1245
+ const tags = (list) => [...new Set(list.map((x) => t(x).toLowerCase().trim().replace(/\s+/g, ' ')).filter(Boolean))].map((tag) => {
1246
+ if (!new RegExp(TAG_PATTERN).test(tag)) throw new UserError(`“${tag}” is not a usable tag (up to 24 letters, digits, spaces, - and _).`);
1247
+ return tag;
1248
+ });
1249
+ const sel = (x) => (x.kind === 'query' ? { ...x, q: t(x.q).slice(0, 60), tags: tags(x.tags) } : x);
1250
+ switch (a.kind) {
1251
+ case 'add': {
1252
+ const label = t(a.label).trim().slice(0, 60);
1253
+ if (!label && !a.icon) throw new UserError(a.label ? `the new element's label (“${a.label}”) came out empty, and it has no icon.` : 'the new element has neither a label nor an icon.');
1254
+ return { ...a, label, tags: tags(a.tags) };
1255
+ }
1256
+ case 'connect': return { ...a, from: sel(a.from), to: sel(a.to), label: t(a.label).slice(0, 60) };
1257
+ case 'remove': case 'split': case 'clone': return a.which ? { ...a, which: sel(a.which) } : a;
1258
+ case 'send': return { ...a, from: sel(a.from), message: t(a.message), args: Object.fromEntries(Object.entries(a.args ?? {}).map(([k, v]) => [k, t(v)])) };
1259
+ default: return a;
1260
+ }
1261
+ }
1262
+
1263
+ function actionCommand(scene, rt, link, msg, template, seed, values) {
1264
+ const ix = indexOf(scene);
1265
+ let a;
1266
+ try { a = fillAction(template, values); } catch (err) { if (err instanceof UserError) err.message = `“${msg.label}”: ${err.message}`; throw err; }
1267
+ const id = (n) => `${seed}-${n}`;
1268
+ const none = { spawnFrom: {} };
1269
+ const target = ix.elements.get(link.to);
1270
+ const needTarget = () => { if (!target) throw new UserError(`“${msg.label}”: the target was removed by an earlier step, so “${describeAction(a, scene)}” was skipped.`); return target; };
1271
+ /** Element ids a split/clone/remove step acts on: the target, or what its query matches now. */
1272
+ const picked = () => {
1273
+ if (a.which?.kind !== 'query') return [needTarget().id];
1274
+ const ids = resolveSelector(scene, a.which, link).filter((x) => ix.elements.has(x));
1275
+ if (!ids.length) throw new UserError(`“${msg.label}”: nothing matched ${describeAction(a, scene).replace(/^\S+ /, '').replace(/ out$/, '')} to ${a.kind === 'split' ? 'split out' : a.kind}.`);
1276
+ return ids;
1277
+ };
1278
+ switch (a.kind) {
1279
+ case 'add': {
1280
+ const t = needTarget();
1281
+ if (scene.elements.length >= LIMITS.elements) throw new UserError(`“${msg.label}”: the stage already has ${LIMITS.elements} elements.`);
1282
+ return { cmd: { type: 'addElement', bubbleId: t.bubbleId, element: { id: id(0), label: a.label, icon: a.icon, imageId: null, tags: a.tags, hue: a.hue } }, hints: { spawnFrom: { [id(0)]: t.id } }, sends: [] };
1283
+ }
1284
+ case 'clone': {
1285
+ const ids = picked();
1286
+ if (scene.elements.length + ids.length > LIMITS.elements) throw new UserError(`“${msg.label}”: cloning ${ids.length} would pass the stage's limit of ${LIMITS.elements} elements.`);
1287
+ return { cmd: { type: 'batch', cmds: ids.map((x, i) => ({ type: 'duplicateElement', id: x, newId: id(i) })) }, hints: { spawnFrom: Object.fromEntries(ids.map((x, i) => [id(i), x])) }, sends: [] };
1288
+ }
1289
+ case 'remove':
1290
+ return { cmd: { type: 'batch', cmds: picked().map((x) => ({ type: 'deleteElement', id: x })) }, hints: none, sends: [] };
1291
+ case 'split': {
1292
+ // Each element flies out away from the sender; several from one bubble fan out a little so they don't stack.
1293
+ const ids = picked();
1294
+ const src = rt.elements[link.from];
1295
+ let cur = scene;
1296
+ const cmds = [], alone = [];
1297
+ ids.forEach((x, k) => {
1298
+ const cix = indexOf(cur);
1299
+ const e = cix.elements.get(x), b = cix.bubbles.get(e.bubbleId);
1300
+ if (cix.members.get(b.id).length < 2 && !b.title) { alone.push(e.label || 'the target'); return; }
1301
+ const el = rt.elements[x], hb = rt.bubbles[b.id];
1302
+ if (!el || !hb) throw new Error('bug: split element has no body');
1303
+ const dx = src ? el.x - src.x : 1, dy = src ? el.y - src.y : 0, d = Math.hypot(dx, dy);
1304
+ const ang = (d > 1 ? Math.atan2(dy, dx) : 0) + (k - (ids.length - 1) / 2) * 0.35;
1305
+ const dist = bubbleRadius(cur, b.id) + K.SINGLE_R + 90;
1306
+ const cmd = { type: 'detachElement', id: x, newBubbleId: id(k), x: Math.round(hb.x + Math.cos(ang) * dist), y: Math.round(hb.y + Math.sin(ang) * dist), hue: HUES[cur.bubbles.length % HUES.length] };
1307
+ cur = applyCommand(cur, cmd);
1308
+ cmds.push(cmd);
1309
+ });
1310
+ if (!cmds.length) throw new UserError(`“${msg.label}”: ${alone.join(', ')} ${alone.length > 1 ? 'are' : 'is'} already in a bubble of ${alone.length > 1 ? 'their' : 'its'} own.`);
1311
+ return { cmd: { type: 'batch', cmds }, hints: none, sends: [] };
1312
+ }
1313
+ case 'connect': {
1314
+ const live = (ids) => ids.filter((x) => ix.elements.has(x));
1315
+ const froms = live(resolveSelector(scene, a.from, link)), tos = live(resolveSelector(scene, a.to, link));
1316
+ const key = (f, t) => `${f}|${t}|${a.label}`;
1317
+ const have = new Set(scene.links.map((l) => `${l.from}|${l.to}|${l.label}`));
1318
+ const pairs = [];
1319
+ for (const f of froms) for (const t of tos) {
1320
+ if (f === t || have.has(key(f, t))) continue;
1321
+ have.add(key(f, t));
1322
+ pairs.push([f, t]);
1323
+ }
1324
+ if (!pairs.length) throw new UserError(`“${msg.label}” found nothing new to connect (${describeAction(a, scene)}${a.label ? `, labelled “${a.label}”` : ''}): every pair already has that connection.${a.label ? '' : ' Give the new line a label in this step to add one alongside the existing line.'}`);
1325
+ if (scene.links.length + pairs.length > LIMIT_LINKS) throw new UserError(`“${msg.label}” would make ${pairs.length} connections, more than the stage's limit of ${LIMIT_LINKS}.`);
1326
+ return { cmd: { type: 'batch', cmds: pairs.map(([f, t], i) => ({ type: 'addLink', link: { id: id(i), from: f, to: t, label: a.label, head: a.head, dash: a.dash, elasticity: a.elasticity, tags: [], messages: [] } })) }, hints: none, sends: [] };
1327
+ }
1328
+ case 'send': {
1329
+ const froms = new Set(resolveSelector(scene, a.from, link).filter((x) => ix.elements.has(x)));
1330
+ // Each sent message gets its own fields from this step's mapping (by name); unmapped fields are empty.
1331
+ const sends = scene.links.filter((l) => froms.has(l.from)).flatMap((l) => l.messages.filter((m) => m.label === a.message).map((m) => ({ linkId: l.id, messageId: m.id, values: Object.fromEntries((m.fields ?? []).map((f) => [f, a.args?.[f] ?? ''])) })));
1332
+ if (!sends.length) throw new UserError(`“${msg.label}”: nothing could send “${a.message}” (${describeAction(a, scene)}).`);
1333
+ return { cmd: null, hints: none, sends };
1334
+ }
1335
+ default:
1336
+ throw new Error(`bug: unknown message action ${a.kind}`);
1337
+ }
1338
+ }
1339
+
1340
+ /**
1341
+ * Everything a message does when it arrives: its actions applied in order, each on the stage the previous left.
1342
+ * Pure: positions come from rt, new ids are derived from seed. Returns
1343
+ * { cmd, hints, sends: [{ linkId, messageId }] (messages to launch next), notes: [why a step was skipped] };
1344
+ * throws a UserError when no step had anything to do.
1345
+ */
1346
+ export function messageCommand(scene, rt, linkId, messageId, seed, values = {}) {
1347
+ const link = indexOf(scene).links.get(linkId);
1348
+ if (!link) throw new UserError('The connection was removed before the message arrived.');
1349
+ const msg = link.messages.find((m) => m.id === messageId);
1350
+ if (!msg) throw new UserError('The message was deleted before it arrived.');
1351
+ const vals = Object.fromEntries((msg.fields ?? []).map((f) => [f, String(values[f] ?? '')]));
1352
+ let cur = scene;
1353
+ const cmds = [], sends = [], notes = [];
1354
+ const spawnFrom = {};
1355
+ msg.actions.forEach((a, i) => {
1356
+ try {
1357
+ const r = actionCommand(cur, rt, link, msg, a, `${seed}${i}`, vals);
1358
+ if (r.cmd) { cur = applyCommand(cur, r.cmd); cmds.push(r.cmd); }
1359
+ Object.assign(spawnFrom, r.hints.spawnFrom);
1360
+ sends.push(...r.sends);
1361
+ } catch (err) {
1362
+ if (!(err instanceof UserError)) throw err;
1363
+ notes.push(err.message);
1364
+ }
1365
+ });
1366
+ if (!cmds.length && !sends.length) throw new UserError(notes.join(' '));
1367
+ return { cmd: { type: 'batch', cmds }, hints: { spawnFrom }, sends, notes };
1368
+ }
1369
+
1370
+ /** Point a fraction p (0..1) of the way along a polyline, by length. */
1371
+ export function pointAlong(pts, p) {
1372
+ const segs = pts.slice(1).map((q, i) => Math.hypot(q.x - pts[i].x, q.y - pts[i].y));
1373
+ const total = segs.reduce((x, y) => x + y, 0);
1374
+ let want = clamp(p, 0, 1) * total;
1375
+ for (let i = 0; i < segs.length; i++) {
1376
+ if (want <= segs[i] || i === segs.length - 1) {
1377
+ const t = segs[i] ? want / segs[i] : 0;
1378
+ return { x: pts[i].x + (pts[i + 1].x - pts[i].x) * t, y: pts[i].y + (pts[i + 1].y - pts[i].y) * t, total };
1379
+ }
1380
+ want -= segs[i];
1381
+ }
1382
+ throw new Error('bug: pointAlong on an empty polyline');
1383
+ }
1384
+
1385
+ /** Topmost thing under a world point: an element chip first, then the smallest bubble containing it. */
1386
+ export function hitTest(rt, scene, wx, wy) {
1387
+ const ix = indexOf(scene);
1388
+ let best = null, bestD = Infinity;
1389
+ for (const e of Object.values(rt.elements)) {
1390
+ if (e.dying || !ix.elements.has(e.id)) continue;
1391
+ const d = Math.hypot(wx - e.x, wy - e.y);
1392
+ if (d < 36 && d < bestD) { best = { kind: 'element', id: e.id }; bestD = d; }
1393
+ }
1394
+ if (best) return best;
1395
+ const tol = 9 / rt.camera.zoom;
1396
+ for (const l of Object.values(rt.links)) {
1397
+ if (l.dying || !ix.links.has(l.id)) continue;
1398
+ const g = linkGeometry(rt, l);
1399
+ if (!g) continue;
1400
+ if (Math.hypot(wx - g.mid.x, wy - g.mid.y) < 18 / rt.camera.zoom) return { kind: 'link', id: l.id };
1401
+ for (let i = 1; i < g.pts.length; i++) {
1402
+ if (segDist(wx, wy, g.pts[i - 1], g.pts[i]) < tol) return { kind: 'link', id: l.id };
1403
+ }
1404
+ }
1405
+ return bubbleAt(rt, scene, wx, wy, null);
1406
+ }
1407
+ function segDist(px, py, a, b) {
1408
+ const dx = b.x - a.x, dy = b.y - a.y;
1409
+ const L = dx * dx + dy * dy || 1;
1410
+ const t = clamp(((px - a.x) * dx + (py - a.y) * dy) / L, 0, 1);
1411
+ return Math.hypot(px - (a.x + t * dx), py - (a.y + t * dy));
1412
+ }
1413
+
1414
+ export function elementAt(rt, scene, wx, wy, excludeId) {
1415
+ const ix = indexOf(scene);
1416
+ let best = null, bestD = 36;
1417
+ for (const e of Object.values(rt.elements)) {
1418
+ if (e.dying || e.id === excludeId || !ix.elements.has(e.id)) continue;
1419
+ const d = Math.hypot(wx - e.x, wy - e.y);
1420
+ if (d < bestD) { best = e.id; bestD = d; }
1421
+ }
1422
+ return best;
1423
+ }
1424
+
1425
+ export function bubbleAt(rt, scene, wx, wy, excludeId) {
1426
+ const ix = indexOf(scene);
1427
+ let best = null, bestR = Infinity;
1428
+ for (const b of Object.values(rt.bubbles)) {
1429
+ if (b.dying || b.id === excludeId || !ix.bubbles.has(b.id)) continue;
1430
+ if (Math.hypot(wx - b.x, wy - b.y) < b.r && b.r < bestR) { best = { kind: 'bubble', id: b.id }; bestR = b.r; }
1431
+ }
1432
+ return best;
1433
+ }
1434
+ // === CORE END ===