@pritzlaff/celldeck 0.0.0-stage → 0.1.1

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/index.html ADDED
@@ -0,0 +1,3362 @@
1
+ <!doctype html><html><head><meta charset=utf8><meta name=viewport content="width=device-width,initial-scale=1,viewport-fit=cover"><style>:root{color-scheme:light;box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}html{scroll-padding-top:env(safe-area-inset-top,0px)}body{margin:0;padding:0;font:14px -apple-system,BlinkMacSystemFont,sans-serif;background:#fff;color:#000}img{max-width:100%}[hidden]:not([hidden=until-found i]){display:none!important}</style></head><body>
2
+ <title>Cell Deck</title>
3
+ <meta name="claude:viewport-fit-sides" content="cover">
4
+ <link rel="preconnect" href="https://fonts.googleapis.com">
5
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
6
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700&family=Instrument+Sans:wght@400;500;600&family=JetBrains+Mono:wght@500&display=swap">
7
+ <style>
8
+ /* Layout: one-screen stage app. Header bar / stage + inspector / views filmstrip. Present mode hides chrome. */
9
+ :root {
10
+ --bg: #EDF0F3;
11
+ --surface: #FFFFFF;
12
+ --surface-2: #F5F7F9;
13
+ --fg: #17202A;
14
+ --muted: #566170;
15
+ --line: #D3D9E0;
16
+ --accent: #2550B8;
17
+ --accent-fg: #FFFFFF;
18
+ --danger: #B42335;
19
+ --grid: #17202A;
20
+ --grid-a: 0.13;
21
+ --dark: 0;
22
+ --cell-teal: #0E9F8E;
23
+ --cell-violet: #6D4DF2;
24
+ --cell-amber: #D98A0B;
25
+ --cell-rose: #DB3A62;
26
+ --cell-blue: #2672E8;
27
+ --cell-green: #2F9A41;
28
+ --cell-orange: #E8590C;
29
+ --cell-pink: #D6409F;
30
+ --cell-cyan: #0B8FB8;
31
+ --cell-lime: #5F9A0A;
32
+ --cell-slate: #5C6B7A;
33
+ --font-display: "Bricolage Grotesque", "Avenir Next", system-ui, sans-serif;
34
+ --font-body: "Instrument Sans", "Segoe UI", system-ui, sans-serif;
35
+ --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;
36
+ }
37
+ @media (prefers-color-scheme: dark) {
38
+ :root:not([data-theme="light"]) {
39
+ --bg: #0D1217; --surface: #151C24; --surface-2: #1B242E; --fg: #E6ECF2; --muted: #98A5B3; --line: #27323E;
40
+ --accent: #7FA5FF; --accent-fg: #0D1217; --danger: #FF7A8A; --grid: #E6ECF2; --grid-a: 0.09; --dark: 1;
41
+ --cell-teal: #2CD3BD; --cell-violet: #A48DFF; --cell-amber: #F4B23F; --cell-rose: #FF6E92; --cell-blue: #5E9DFF; --cell-green: #5FCB6C;
42
+ --cell-orange: #FF8A4C; --cell-pink: #F783C7; --cell-cyan: #3BC9EE; --cell-lime: #A9E34B; --cell-slate: #A3B1BF;
43
+ color-scheme: dark;
44
+ }
45
+ }
46
+ :root[data-theme="dark"] {
47
+ --bg: #0D1217; --surface: #151C24; --surface-2: #1B242E; --fg: #E6ECF2; --muted: #98A5B3; --line: #27323E;
48
+ --accent: #7FA5FF; --accent-fg: #0D1217; --danger: #FF7A8A; --grid: #E6ECF2; --grid-a: 0.09; --dark: 1;
49
+ --cell-teal: #2CD3BD; --cell-violet: #A48DFF; --cell-amber: #F4B23F; --cell-rose: #FF6E92; --cell-blue: #5E9DFF; --cell-green: #5FCB6C;
50
+ --cell-orange: #FF8A4C; --cell-pink: #F783C7; --cell-cyan: #3BC9EE; --cell-lime: #A9E34B; --cell-slate: #A3B1BF;
51
+ color-scheme: dark;
52
+ }
53
+ [hidden] { display: none !important; }
54
+ html, body { height: 100%; }
55
+ body { background: var(--bg); color: var(--fg); font-family: var(--font-body); font-size: 14px; overflow: hidden; }
56
+ button, input { font: inherit; color: inherit; }
57
+ button { cursor: pointer; }
58
+ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
59
+
60
+ .app { height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; grid-template-columns: minmax(0, 1fr) 300px; grid-template-areas: "bar bar" "stage insp" "views views"; }
61
+ .bar { grid-area: bar; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding-block: 10px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); border-bottom: 1px solid var(--line); background: var(--surface); }
62
+ .brand { display: flex; align-items: center; gap: 8px; font-family: var(--font-display); font-weight: 700; font-size: 18px; letter-spacing: -0.01em; margin-right: 8px; }
63
+ .brand svg { width: 26px; height: 22px; }
64
+ .spacer { flex: 1 1 auto; }
65
+ .status { font-family: var(--font-mono); font-size: 11px; color: var(--muted); letter-spacing: 0.02em; }
66
+ .btn { display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface); font-weight: 500; }
67
+ .btn:hover:not(:disabled) { background: var(--surface-2); }
68
+ .btn:disabled { opacity: 0.45; cursor: default; }
69
+ .btn svg { width: 16px; height: 16px; }
70
+ .btn.primary { background: var(--fg); color: var(--bg); border-color: var(--fg); }
71
+ .btn.primary:hover { background: var(--fg); opacity: 0.88; }
72
+ .btn.danger { color: var(--danger); }
73
+ .btn.icon { padding: 0; width: 36px; justify-content: center; }
74
+ .menu { position: fixed; inset: auto; margin: 0; min-width: 200px; padding: 6px; background: var(--surface); color: inherit; border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 12px 32px rgb(0 0 0 / 0.14); }
75
+ .menu:popover-open { display: flex; flex-direction: column; }
76
+ .menu button { display: flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 10px; border: 0; border-radius: 8px; background: transparent; color: inherit; text-align: left; }
77
+ .menu button:hover, .menu button:focus-visible { background: var(--surface-2); }
78
+ .menu button:disabled { opacity: 0.5; background: transparent; }
79
+ .menu svg { width: 16px; height: 16px; flex: none; }
80
+ .split { display: inline-flex; }
81
+ body.cmd-held .mn { text-decoration: underline; text-underline-offset: 3px; text-decoration-thickness: 2px; } /* ⌘/Ctrl shortcut letters */
82
+ .split > .btn:first-child { border-radius: 8px 0 0 8px; }
83
+ .split > .btn + .btn { border-radius: 0 8px 8px 0; border-left: 0; width: 30px; } /* the first button's right border is the separator */
84
+ .addmenu { width: min(320px, calc(100vw - 32px)); padding: 12px; gap: 12px; }
85
+ .addmenu .icons button { display: grid; justify-content: center; min-height: 36px; padding: 0; border: 1px solid transparent; background: var(--surface-2); }
86
+ .addmenu .icons button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); background: var(--surface); }
87
+ .addmenu .btn.primary { justify-content: center; }
88
+
89
+ .stage { grid-area: stage; position: relative; overflow: hidden; min-height: 0; }
90
+ .stage canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
91
+ #ov { touch-action: none; }
92
+ .hint { position: absolute; left: 16px; bottom: 12px; right: 16px; font-size: 12px; color: var(--muted); pointer-events: none; text-wrap: balance; }
93
+ .pickbar { position: absolute; bottom: 48px; left: 50%; transform: translateX(-50%); background: var(--fg); color: var(--bg); padding: 8px 14px; border-radius: 999px; font-size: 13px; font-weight: 500; white-space: nowrap; }
94
+ .banner { position: absolute; top: 12px; left: 16px; right: 16px; display: flex; gap: 10px; align-items: flex-start; background: var(--surface); border: 1px solid var(--danger); color: var(--fg); border-radius: 10px; padding: 10px 12px; font-size: 13px; z-index: 5; }
95
+ .banner strong { color: var(--danger); }
96
+ .banner p { margin: 0; flex: 1; min-width: 0; overflow-wrap: anywhere; }
97
+ .banner button { border: 0; background: transparent; color: var(--muted); font-weight: 600; }
98
+
99
+ .insp { grid-area: insp; border-left: 1px solid var(--line); background: var(--surface); overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 16px; min-height: 0; }
100
+ .insp h2 { margin: 0; font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
101
+ .field { display: flex; flex-direction: column; gap: 6px; }
102
+ .field label, .field .lbl { font-size: 12px; font-weight: 600; color: var(--muted); }
103
+ .field input[type=text] { min-height: 38px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); }
104
+ .swatches { display: flex; flex-wrap: wrap; gap: 8px; }
105
+ .swatch { width: 32px; height: 32px; border-radius: 50%; border: 2px solid transparent; background: var(--c); box-shadow: inset 0 0 0 3px var(--surface); }
106
+ .swatch[aria-pressed="true"] { border-color: var(--fg); }
107
+ .icons { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 4px; }
108
+ .icons button { aspect-ratio: 1; border-radius: 8px; border: 1px solid transparent; background: var(--surface-2); display: grid; place-items: center; padding: 0; min-height: 36px; }
109
+ .icons button svg { width: 20px; height: 20px; }
110
+ .icons button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); background: var(--surface); }
111
+ .icons button .none { font-size: 11px; color: var(--muted); }
112
+ .icons button[hidden] { display: none; }
113
+ #eIcons, #nbIcons { max-height: 248px; overflow-y: auto; align-content: start; } /* ~6 rows, then scroll */
114
+ .iconhead { display: flex; align-items: center; gap: 6px; min-height: 30px; }
115
+ .iconhead .lbl { flex: 1; }
116
+ .iconhead input { flex: 4; min-width: 0; min-height: 30px; padding: 0 8px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); }
117
+ .iconhead .btn.icon { width: 30px; min-height: 30px; }
118
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; }
119
+ .insphead { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; }
120
+ .filter { position: relative; display: flex; align-items: center; min-height: 36px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); flex: 0 1 300px; min-width: 200px; }
121
+ .filter:focus-within { border-color: var(--accent); }
122
+ .filter .glass { width: 16px; height: 16px; margin-left: 10px; color: var(--muted); flex: none; }
123
+ .filter input { flex: 1; min-width: 0; border: 0; background: transparent; padding: 0 8px; min-height: 34px; outline: none; }
124
+ .ficon { position: relative; display: grid; place-items: center; width: 36px; height: 34px; border: 0; border-left: 1px solid var(--line); background: transparent; border-radius: 0 8px 8px 0; color: var(--muted); }
125
+ .ficon svg { width: 17px; height: 17px; }
126
+ .ficon[aria-expanded="true"], .ficon.on { color: var(--accent); }
127
+ .badge { position: absolute; top: -6px; right: -6px; box-shadow: 0 0 0 2px var(--surface); min-width: 15px; height: 15px; padding: 0 3px; border-radius: 999px; background: var(--accent); color: var(--accent-fg); font-family: var(--font-mono); font-size: 10px; line-height: 15px; text-align: center; }
128
+ .fpanel { position: absolute; top: calc(100% + 6px); left: 0; width: min(340px, calc(100vw - 32px)); max-height: 60vh; overflow-y: auto; z-index: 20; background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 12px; display: flex; flex-direction: column; gap: 8px; box-shadow: 0 12px 32px rgb(0 0 0 / 0.14); }
129
+ .fpanel h3 { margin: 4px 0 0; font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
130
+ .fhead { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 13px; }
131
+ .link { border: 0; background: transparent; color: var(--accent); font-weight: 600; padding: 4px 0; }
132
+ .fchips, .tags { display: flex; flex-wrap: wrap; gap: 6px; }
133
+ .fchip { display: inline-flex; align-items: center; gap: 6px; min-height: 30px; padding: 0 10px; border-radius: 999px; border: 1px solid var(--line); background: var(--surface-2); font-size: 13px; }
134
+ .fchip svg { width: 15px; height: 15px; }
135
+ .fchip[aria-pressed="true"] { background: var(--fg); color: var(--bg); border-color: var(--fg); }
136
+ .fempty { font-size: 13px; color: var(--muted); }
137
+ .tag { display: inline-flex; align-items: center; gap: 2px; min-height: 28px; padding-left: 10px; border-radius: 999px; background: var(--surface-2); border: 1px solid var(--line); font-size: 13px; }
138
+ .tag button { border: 0; background: transparent; color: var(--muted); width: 28px; height: 26px; border-radius: 999px; font-size: 15px; line-height: 1; }
139
+ .tag button:hover { color: var(--danger); }
140
+ .tag.locked { padding-right: 10px; }
141
+ .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); background: var(--surface-2); }
142
+ .seg { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; background: var(--surface-2); border-radius: 10px; padding: 3px; }
143
+ .seg button { min-height: 34px; border: 1px solid transparent; border-radius: 8px; background: transparent; font-size: 13px; font-weight: 500; color: var(--muted); }
144
+ .seg button[aria-pressed="true"] { background: var(--surface); border-color: var(--line); color: var(--fg); }
145
+ .check { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 500; min-height: 32px; }
146
+ .check input { width: 18px; height: 18px; accent-color: var(--accent); }
147
+ .range { display: flex; align-items: center; gap: 10px; }
148
+ .range input { flex: 1; min-width: 0; accent-color: var(--accent); }
149
+ .bgrow { display: flex; align-items: center; gap: 10px; }
150
+ .bgrow .range { flex: 1; min-width: 0; }
151
+ #stColor, #bColor { width: 44px; height: 36px; padding: 2px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); flex: none; }
152
+ #stOpacity:disabled { opacity: 0.45; }
153
+ /* Present-mode top row: the view strip takes what is left of the width and scrolls; share/exit never shrink. */
154
+ .ptopbar { position: absolute; top: max(12px, env(safe-area-inset-top, 0px)); left: max(16px, env(safe-area-inset-left, 0px)); right: max(16px, env(safe-area-inset-right, 0px)); display: flex; align-items: center; gap: 12px; pointer-events: none; }
155
+ .ptopbar > * { pointer-events: auto; }
156
+ .pstrip { flex: 1 1 auto; min-width: 0; display: flex; gap: 6px; overflow-x: auto; padding: 2px; scrollbar-width: none; }
157
+ .pstrip .chip { background: color-mix(in srgb, var(--surface) 88%, transparent); flex: none; opacity: 0.75; transition: opacity 0.2s; }
158
+ .pstrip .chip:hover, .pstrip .chip[aria-current="true"], .pstrip .chip:focus-visible { opacity: 1; }
159
+ .note { margin: 0; font-size: 12px; color: var(--muted); line-height: 1.4; }
160
+ .hint2 { font-weight: 400; }
161
+ .field select { min-height: 38px; padding: 0 8px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); width: 100%; }
162
+ .mlist { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
163
+ .mlist:empty { display: none; }
164
+ .mlist li { display: flex; align-items: center; gap: 6px; padding: 6px 6px 6px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); }
165
+ .mlist .mtxt { flex: 1; min-width: 0; display: flex; flex-direction: column; }
166
+ .mlist .mtxt b { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
167
+ .mlist .mtxt span { font-size: 12px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
168
+ .mlist button { border: 0; background: transparent; border-radius: 6px; min-height: 30px; padding: 0 8px; font-size: 12px; font-weight: 600; color: var(--muted); }
169
+ .mlist button:hover { color: var(--fg); background: var(--surface); }
170
+ .mlist button.armed { color: var(--danger); }
171
+ .msged { display: flex; flex-direction: column; gap: 12px; padding: 12px; border: 1px solid var(--accent); border-radius: 12px; }
172
+ .msged h3 { margin: 0; font-size: 14px; }
173
+ .sub { display: flex; flex-direction: column; gap: 12px; }
174
+ .acts { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; position: relative; }
175
+ .acts > li { display: flex; align-items: center; gap: 2px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); padding: 2px; position: relative; }
176
+ .acts > li.dragging { z-index: 2; box-shadow: 0 8px 20px rgb(0 0 0 / 0.16); border-color: var(--accent); }
177
+ .acts > li.drop-before::before, .acts.drop-end > li:last-child::after { content: ""; position: absolute; left: 6px; right: 6px; height: 2px; border-radius: 2px; background: var(--accent); }
178
+ .acts > li.drop-before::before { top: -4px; }
179
+ .acts.drop-end > li:last-child::after { bottom: -4px; }
180
+ .acts .grip { border: 0; background: transparent; color: var(--muted); width: 28px; min-height: 36px; border-radius: 8px; cursor: grab; touch-action: none; display: grid; place-items: center; flex: none; }
181
+ .acts .grip:active { cursor: grabbing; }
182
+ .acts .sopen { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; min-height: 36px; border: 0; background: transparent; border-radius: 8px; padding: 0 8px; text-align: left; font-size: 13px; counter-increment: none; }
183
+ .acts .sopen:hover { background: var(--surface-2); }
184
+ .acts .sopen span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
185
+ .acts .sopen svg { color: var(--accent); flex: none; }
186
+ .acts .sdel { border: 0; background: transparent; color: var(--muted); width: 32px; min-height: 36px; border-radius: 8px; flex: none; }
187
+ .acts .sdel:hover:not(:disabled) { color: var(--danger); background: var(--surface-2); }
188
+ .acts .sdel:disabled { opacity: 0.3; }
189
+ .modal { width: min(520px, calc(100vw - 32px)); max-height: min(760px, calc(100vh - 32px)); padding: 0; border: 1px solid var(--line); border-radius: 16px; background: var(--surface); color: var(--fg); box-shadow: 0 24px 64px rgb(0 0 0 / 0.25); }
190
+ .modal::backdrop { background: rgb(10 14 20 / 0.45); }
191
+ .modal form { display: flex; flex-direction: column; max-height: inherit; }
192
+ .mhead { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 10px; border-bottom: 1px solid var(--line); }
193
+ .drop { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 22px 16px; border: 2px dashed var(--line); border-radius: 12px; text-align: center; color: var(--muted); }
194
+ .drop.on { border-color: var(--accent); background: var(--surface-2); color: var(--fg); }
195
+ .urlrow { display: flex; gap: 8px; }
196
+ .urlrow input { flex: 1; min-width: 0; min-height: 38px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); font-family: var(--font-mono); font-size: 12px; }
197
+ .err { margin: 0; color: var(--danger); font-size: 13px; }
198
+ .mhead h2 { margin: 0; font-family: var(--font-display); font-size: 18px; }
199
+ .mbody { padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; }
200
+ .mfoot { display: flex; justify-content: flex-end; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--line); }
201
+ .mfoot .err { margin-right: auto; }
202
+ .btn[aria-disabled="true"] { opacity: 0.45; } /* still clickable: says what's missing */
203
+ .kinds { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
204
+ .kinds button { display: flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 10px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface-2); font-weight: 500; font-size: 13px; text-align: left; }
205
+ .kinds button svg { color: var(--accent); flex: none; }
206
+ .kinds button[aria-pressed="true"] { border-color: var(--fg); background: var(--surface); box-shadow: inset 0 0 0 1px var(--fg); font-weight: 600; }
207
+ .modal .seg button { display: inline-flex; align-items: center; justify-content: center; gap: 6px; }
208
+ .modal .icons { grid-template-columns: repeat(9, minmax(0, 1fr)); }
209
+ .modal .sel .icons { grid-template-columns: repeat(9, minmax(0, 1fr)); }
210
+ .fchip .from { font-weight: 400; color: inherit; opacity: 0.75; }
211
+ @media (max-width: 520px) { .kinds { grid-template-columns: repeat(2, minmax(0, 1fr)); } .modal .icons, .modal .sel .icons { grid-template-columns: repeat(6, minmax(0, 1fr)); } }
212
+ .found { font-size: 12px; color: var(--muted); line-height: 1.45; }
213
+ .found b { color: var(--fg); font-weight: 600; }
214
+ .row2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
215
+ .sel { margin: 0; border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px 10px; display: flex; flex-direction: column; gap: 8px; min-width: 0; }
216
+ .stepper { display: flex; gap: 6px; list-style: none; padding: 0; margin: 0; }
217
+ .stepper li { flex: 1 1 0; min-width: 0; }
218
+ .stepper button { width: 100%; display: flex; align-items: center; gap: 8px; padding: 8px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); text-align: left; color: var(--fg); }
219
+ .stepper button[aria-current="step"] { border-color: var(--fg); background: var(--surface); box-shadow: inset 0 0 0 1px var(--fg); }
220
+ .stepper .n { flex: none; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-family: var(--font-mono); font-size: 11px; border: 1px solid var(--line); background: var(--surface); }
221
+ .stepper button[aria-current="step"] .n { background: var(--fg); color: var(--bg); border-color: var(--fg); }
222
+ .stepper .t { display: flex; flex-direction: column; min-width: 0; }
223
+ .stepper .t b { font-size: 13px; }
224
+ .stepper .t small { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
225
+ .steppanel { display: flex; flex-direction: column; gap: 12px; }
226
+ .steppanel > .sel { border: 0; padding: 0; }
227
+ .steppanel > .sel > legend { display: none; }
228
+ .stepnav { display: flex; justify-content: space-between; }
229
+ .sel legend { font-size: 12px; font-weight: 600; color: var(--muted); padding: 0 4px; }
230
+ .sel .icons { grid-template-columns: repeat(8, minmax(0, 1fr)); }
231
+ .sel .icons button { min-height: 28px; }
232
+ .sel .icons button svg { width: 16px; height: 16px; }
233
+ .swatch.auto { background: var(--surface-2); box-shadow: none; border: 2px dashed var(--muted); }
234
+ .swatch.auto[aria-pressed="true"] { border-style: solid; border-color: var(--fg); }
235
+ .msgbar { position: absolute; top: 12px; left: 0; right: 0; margin-inline: auto; width: fit-content; max-width: calc(100% - 32px); display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 6px; padding: 6px; border-radius: 14px; background: color-mix(in srgb, var(--surface) 90%, transparent); border: 1px solid var(--line); box-shadow: 0 8px 24px rgb(0 0 0 / 0.10); z-index: 4; animation: msgIn 0.28s ease-out; }
236
+ .msgform { position: absolute; top: 64px; left: 0; right: 0; margin-inline: auto; width: min(360px, calc(100% - 32px)); display: flex; flex-direction: column; gap: 8px; padding: 12px; border-radius: 14px; background: var(--surface); border: 1px solid var(--line); box-shadow: 0 8px 24px rgb(0 0 0 / 0.14); z-index: 5; }
237
+ .msgform h3 { margin: 0 0 2px; font-size: 14px; }
238
+ .maprow { display: grid; grid-template-columns: minmax(60px, auto) 1fr; align-items: center; gap: 8px; }
239
+ .maprow label { font-family: var(--font-mono); font-size: 12px; color: var(--muted); }
240
+ .maprow input { min-height: 34px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); min-width: 0; }
241
+ .msgbar .from { font-size: 12px; color: var(--muted); padding: 0 6px 0 4px; white-space: nowrap; }
242
+ .msgbar .from b { color: var(--fg); }
243
+ .mbtn { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 12px 0 8px; border-radius: 999px; border: 1px solid var(--accent); background: var(--surface); color: var(--fg); font-weight: 600; font-size: 13px; white-space: nowrap; }
244
+ .mbtn:hover { background: var(--accent); color: var(--accent-fg); }
245
+ .mbtn .k { font-family: var(--font-mono); font-size: 10px; width: 18px; height: 18px; display: grid; place-items: center; border-radius: 50%; background: var(--surface-2); color: var(--muted); }
246
+ .mbtn .to { font-weight: 400; color: var(--muted); }
247
+ .mbtn:hover .to, .mbtn:hover .k { color: inherit; background: transparent; }
248
+ .app.present .msgbar { top: calc(max(12px, env(safe-area-inset-top, 0px)) + 52px); }
249
+ @keyframes msgIn { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: none; } }
250
+ @media (prefers-reduced-motion: reduce) { .msgbar { animation: none; } }
251
+ .range output { font-family: var(--font-mono); font-size: 12px; color: var(--muted); width: 4.5ch; flex: none; text-align: right; }
252
+ .tips { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 10px; font-size: 13px; color: var(--muted); line-height: 1.45; }
253
+ .tips b { color: var(--fg); font-weight: 600; }
254
+ .kbd { font-family: var(--font-mono); font-size: 11px; border: 1px solid var(--line); border-radius: 4px; padding: 1px 5px; color: var(--fg); }
255
+
256
+ .views { grid-area: views; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding-block: 10px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); border-top: 1px solid var(--line); background: var(--surface); }
257
+ .views .lbl { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
258
+ .chips { display: flex; gap: 6px; overflow-x: auto; flex: 1 1 320px; min-width: 0; padding: 2px; }
259
+ .chip { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 0 12px 0 6px; border-radius: 999px; border: 1px solid var(--line); background: var(--surface-2); white-space: nowrap; }
260
+ .chip .n { font-family: var(--font-mono); font-size: 11px; width: 22px; height: 22px; display: grid; place-items: center; border-radius: 50%; background: var(--surface); border: 1px solid var(--line); }
261
+ .chip[aria-current="true"] { border-color: var(--fg); background: var(--surface); font-weight: 600; }
262
+ .chips .chip { touch-action: pan-x; }
263
+ .chip.dragging { position: relative; z-index: 1; opacity: 0.75; cursor: grabbing; }
264
+ .chip.drop-before { box-shadow: -5px 0 0 -2px var(--accent); }
265
+ .chips.drop-end .chip:last-child { box-shadow: 5px 0 0 -2px var(--accent); }
266
+ .chip[aria-current="true"] .n { background: var(--fg); color: var(--bg); border-color: var(--fg); }
267
+ .empty { font-size: 13px; color: var(--muted); }
268
+ .vedit { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
269
+ .vedit input { min-height: 36px; width: 160px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); }
270
+
271
+ .hud { position: absolute; left: 50%; bottom: max(16px, env(safe-area-inset-bottom, 0px)); transform: translateX(-50%); display: flex; align-items: center; gap: 4px; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; padding: 4px; opacity: 0.4; transition: opacity 0.2s; }
272
+ .hud:hover, .hud:focus-within { opacity: 1; }
273
+ .hud .pos { font-family: var(--font-mono); font-size: 12px; padding: 0 10px; white-space: nowrap; max-width: 50vw; overflow: hidden; text-overflow: ellipsis; }
274
+ .hud .btn { border-radius: 999px; border: 0; }
275
+ .crumbs { display: flex; flex-wrap: wrap; align-items: center; gap: 2px; font-size: 13px; margin: -6px 0 -4px -6px; }
276
+ .crumbs .sep { color: var(--muted); padding: 0 1px; }
277
+ .crumb { position: relative; }
278
+ .crumb > .go { border: 0; background: none; padding: 4px 6px; border-radius: 6px; color: var(--muted); font-weight: 500; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
279
+ .crumb > .go:hover { background: var(--surface-2); color: var(--fg); }
280
+ .crumb > .go[aria-current="true"] { color: var(--fg); font-weight: 600; }
281
+ .crumb .qa { display: none; position: absolute; top: 100%; left: 0; z-index: 5; padding-top: 4px; }
282
+ .crumb:hover .qa, .crumb:focus-within .qa { display: block; }
283
+ .qa-in { display: flex; gap: 2px; padding: 3px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); box-shadow: 0 6px 18px rgb(0 0 0 / 0.12); }
284
+ .qa-in button { width: 30px; height: 30px; border: 0; background: none; border-radius: 7px; display: grid; place-items: center; color: var(--fg); padding: 0; }
285
+ .qa-in button:hover, .qa-in button:focus-visible { background: var(--surface-2); }
286
+ .qa-in svg { width: 16px; height: 16px; }
287
+ .rtbar { display: flex; gap: 4px; }
288
+ .rtbar .btn { width: 32px; min-height: 32px; }
289
+ .rt { min-height: 72px; max-height: 260px; overflow-y: auto; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface-2); line-height: 1.45; overflow-wrap: anywhere; }
290
+ .rt:empty::before { content: attr(data-placeholder); color: var(--muted); }
291
+ .rt ul, .rt ol, .pdesc ul, .pdesc ol { margin: 4px 0; padding-left: 20px; }
292
+ .rt p, .pdesc p { margin: 0 0 4px; }
293
+ .rt a, .pdesc a { color: var(--accent); }
294
+ .pdesc { position: absolute; left: 50%; transform: translateX(-50%); bottom: calc(max(16px, env(safe-area-inset-bottom, 0px)) + 56px); width: min(760px, calc(100% - 32px)); max-height: 30vh; overflow-y: auto; padding: 12px 16px; border-radius: 14px; background: color-mix(in srgb, var(--surface) 92%, transparent); border: 1px solid var(--line); box-shadow: 0 8px 24px rgb(0 0 0 / 0.10); font-size: 15px; line-height: 1.5; display: flex; flex-direction: column; gap: 10px; overflow-wrap: anywhere; z-index: 3; }
295
+ .pdesc h3 { margin: 0 0 2px; font-family: var(--font-display); font-size: 15px; }
296
+ .ptop { flex: none; margin-left: auto; display: flex; gap: 6px; }
297
+ .ptop .btn { opacity: 0.4; }
298
+ .ptop .btn:hover, .ptop .btn:focus-visible { opacity: 1; }
299
+
300
+ .app.present { grid-template-rows: minmax(0, 1fr); grid-template-columns: minmax(0, 1fr); grid-template-areas: "stage"; }
301
+ .app.present .bar, .app.present .insp, .app.present .views, .app.present .hint { display: none; }
302
+
303
+ @media (max-width: 760px) {
304
+ .app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr) auto auto; grid-template-areas: "bar" "stage" "insp" "views"; }
305
+ .insp { border-left: 0; border-top: 1px solid var(--line); max-height: 36vh; }
306
+ .status { order: 10; flex-basis: 100%; }
307
+ .hint { display: none; }
308
+ /* Narrow: icon-only bar buttons, brand mark only, filter takes the leftover row width. */
309
+ .brandname, #addBubble > span, #connect > span { display: none; }
310
+ .filter { flex: 1 1 160px; min-width: 0; }
311
+ .insp { padding: 12px 16px; gap: 12px; }
312
+ }
313
+ /* Collapse row: sticky at the top of the drawer, as short as the button so it costs little height. */
314
+ .insptop { position: sticky; top: -16px; z-index: 1; display: flex; justify-content: flex-end; margin: -16px -16px -8px; padding: 4px 4px 0; background: var(--surface); }
315
+ .insptop .btn { min-height: 28px; width: 28px; padding: 0; border-color: transparent; }
316
+ @media (max-width: 760px) { .insptop { top: -12px; margin: -12px -16px -4px; } .insptop svg { transform: rotate(90deg); } }
317
+ /* Collapsed: the drawer shrinks to a thin strip holding only its expand button (a column on desktop, a row when narrow). */
318
+ .app.insp-off { grid-template-columns: minmax(0, 1fr) 36px; }
319
+ .app.insp-off .insp { padding: 0; overflow: hidden; }
320
+ .app.insp-off .insp > :not(.insptop) { display: none !important; }
321
+ .app.insp-off .insptop { position: static; margin: 0; padding: 4px; justify-content: center; }
322
+ .app.insp-off .insptop svg { transform: rotate(180deg); }
323
+ @media (max-width: 760px) { .app.insp-off { grid-template-columns: minmax(0, 1fr); } .app.insp-off .insptop svg { transform: rotate(-90deg); } }
324
+ #inspToggle[aria-pressed="true"] { color: var(--accent); }
325
+ @media (prefers-reduced-motion: reduce) { .hud { transition: none; } }
326
+ </style>
327
+
328
+ <div class="app" id="app">
329
+ <header class="bar">
330
+ <div class="brand">
331
+ <svg viewBox="0 0 26 22" aria-hidden="true"><circle cx="9" cy="11" r="8" fill="none" stroke="currentColor" stroke-width="1.8"/><circle cx="19.5" cy="7" r="4.5" fill="none" stroke="currentColor" stroke-width="1.8"/></svg>
332
+ <span class="brandname">Cell Deck</span>
333
+ </div>
334
+ <button class="btn icon" id="menuBtn" type="button" popovertarget="fileMenu" aria-label="File menu" title="File menu"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>
335
+ <div class="menu" id="fileMenu" popover role="menu" aria-label="File">
336
+ <button type="button" role="menuitem" id="newBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 3H6a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8zM14 3v5h5M12 11v6M9 14h6"/></svg>New</button>
337
+ <button type="button" role="menuitem" id="openBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>Open…</button>
338
+ <button type="button" role="menuitem" id="downloadBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg><span id="downloadTxt">Download deck.json</span></button>
339
+ <button type="button" role="menuitem" id="saveAsBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"/></svg>Save as…</button>
340
+ <button type="button" role="menuitem" id="linkBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg><span id="linkTxt">Copy edit link</span></button>
341
+ <button type="button" role="menuitem" id="linkPresentBtn"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4h18v12H3zM8 20h8M12 16v4"/></svg>Copy present link</button>
342
+ </div>
343
+ <div class="split">
344
+ <button class="btn" id="addBubble" type="button" aria-label="Add bubble" title="Add bubble (⌘B)" aria-keyshortcuts="Meta+B Control+B"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg><span>Add <span class="mn">b</span>ubble</span></button>
345
+ <button class="btn icon" id="addMore" type="button" popovertarget="addMenu" aria-label="Label and icon for new bubbles" title="Label and icon for new bubbles"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 10l5 5 5-5"/></svg></button>
346
+ </div>
347
+ <div class="menu addmenu" id="addMenu" popover aria-label="New bubble">
348
+ <div class="field"><label for="nbLabel">Label</label><input type="text" id="nbLabel" maxlength="60" placeholder="New" autocomplete="off"></div>
349
+ <div class="field"><span class="lbl" id="nbIconLbl">Icon</span><div class="icons" id="nbIcons" role="group" aria-labelledby="nbIconLbl"></div></div>
350
+ <button class="btn primary" id="nbAdd" type="button">Add bubble</button>
351
+ </div>
352
+ <button class="btn" id="connect" type="button" aria-label="Connect" aria-pressed="false" title="Connect (C or ⌘E)" aria-keyshortcuts="C Meta+E Control+E"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="6" r="2.5"/><path d="M7 16.5C10 14 12 10 16.8 7.5"/></svg><span>Conn<span class="mn">e</span>ct</span></button>
353
+ <button class="btn icon" id="undo" type="button" aria-label="Undo"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14L4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/></svg></button>
354
+ <button class="btn icon" id="redo" type="button" aria-label="Redo"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 14l5-5-5-5"/><path d="M20 9H9.5a5.5 5.5 0 0 0 0 11H13"/></svg></button>
355
+ <button class="btn icon" id="inspToggle" type="button" aria-pressed="true" aria-controls="insp" aria-label="Show inspector" title="Show inspector (⌘.)" aria-keyshortcuts="Meta+. Control+."><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4h16v16H4zM15 4v16"/></svg></button>
356
+ <div class="filter" id="filterWrap" role="search">
357
+ <svg class="glass" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l4.5 4.5"/></svg>
358
+ <input type="search" id="fQuery" placeholder="Filter by name or tag" aria-label="Filter the stage by name or tag" autocomplete="off">
359
+ <button type="button" class="ficon" id="fToggle" aria-expanded="false" aria-controls="fPanel" aria-label="Filter by tags and icons" title="Filter by tags and icons">
360
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h18l-7 8.5V19l-4 2v-7.5z"/></svg>
361
+ <span class="badge" id="fBadge" hidden></span>
362
+ </button>
363
+ <div class="fpanel" id="fPanel" hidden>
364
+ <div class="fhead"><span id="fCount"></span><button type="button" class="link" id="fClear">Clear filter</button></div>
365
+ <h3 id="fTagsLbl">Tags</h3>
366
+ <div class="fchips" id="fTags" role="group" aria-labelledby="fTagsLbl"></div>
367
+ <h3 id="fIconsLbl">Icons</h3>
368
+ <div class="fchips" id="fIcons" role="group" aria-labelledby="fIconsLbl"></div>
369
+ </div>
370
+ </div>
371
+ <div class="spacer"></div>
372
+ <span class="status" id="status" role="status">Starting…</span>
373
+ <button class="btn primary" id="present" type="button"><svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>Present</button>
374
+ </header>
375
+
376
+ <main class="stage" id="stage">
377
+ <canvas id="gl" aria-hidden="true"></canvas>
378
+ <canvas id="ov" role="img" aria-label="Bubble stage. Drag elements out of bubbles to split them off; drop onto a bubble to merge."></canvas>
379
+ <div class="msgbar" id="msgbar" role="toolbar" aria-label="Messages" hidden></div>
380
+ <form class="msgform" id="msgForm" aria-label="Message fields" hidden></form>
381
+ <div class="pickbar" id="pickbar" hidden>Click the bubble to orbit around · Esc to cancel</div>
382
+ <div class="banner" id="banner" role="alert" hidden><p><strong>Problem: </strong><span id="bannerText"></span></p><button type="button" id="bannerClose">Dismiss</button></div>
383
+ <p class="hint">Drag an element past the membrane to split it off · Drop it on another bubble to merge (hold ⌘/Ctrl to drop it into a new inner cell) · Double-click empty space to add a bubble · Scroll to zoom, drag the background to pan</p>
384
+ <div class="hud" id="hud" hidden>
385
+ <button class="btn icon" id="prev" type="button" aria-label="Previous view"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button>
386
+ <span class="pos" id="hudPos"></span>
387
+ <button class="btn icon" id="next" type="button" aria-label="Next view"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button>
388
+ <button class="btn" id="navMode" type="button"></button>
389
+ </div>
390
+ <aside class="pdesc" id="pdesc" aria-label="Notes" hidden></aside>
391
+ <div class="ptopbar">
392
+ <nav class="pstrip" id="pstrip" aria-label="Views" hidden></nav>
393
+ <div class="ptop" id="ptop" hidden>
394
+ <button class="btn" id="share" type="button" title="Copy a link to this slide"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7M16 6l-4-4-4 4M12 2v13"/></svg><span id="shareTxt">Share</span></button>
395
+ <button class="btn" id="exit" type="button">Exit · Esc</button>
396
+ </div>
397
+ </div>
398
+ </main>
399
+
400
+ <aside class="insp" id="insp" aria-label="Inspector">
401
+ <div class="insptop"><button class="btn icon" id="inspHide" type="button" aria-label="Hide inspector" title="Hide inspector (⌘.)"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button></div>
402
+ <nav class="crumbs" id="crumbs" aria-label="Selection path" hidden></nav>
403
+ <section id="inspNone">
404
+ <h2>Background</h2>
405
+ <div class="field" style="margin:12px 0 20px">
406
+ <label class="check" for="stGrid"><input type="checkbox" id="stGrid">Dot grid</label>
407
+ <label for="stColor">Background colour</label>
408
+ <div class="bgrow">
409
+ <input type="color" id="stColor">
410
+ <div class="range"><input type="range" id="stOpacity" min="0" max="100" step="5" aria-label="Background colour strength"><output id="stOpacityOut" for="stOpacity"></output></div>
411
+ </div>
412
+ </div>
413
+ <h2>Slide notes</h2>
414
+ <div style="margin:12px 0 20px">
415
+ <div class="field">
416
+ <span class="lbl" id="stDescLbl">Description</span>
417
+ <div class="rtbar" id="stDescBar" role="toolbar" aria-label="Description formatting">
418
+ <button type="button" class="btn icon" data-cmd="bold" aria-label="Bold" title="Bold (⌘B)"><b>B</b></button>
419
+ <button type="button" class="btn icon" data-cmd="italic" aria-label="Italic" title="Italic (⌘I)"><i>I</i></button>
420
+ <button type="button" class="btn icon" data-cmd="insertUnorderedList" aria-label="Bullet list" title="Bullet list"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01"/></svg></button>
421
+ <button type="button" class="btn icon" data-cmd="link" aria-label="Link" title="Link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg></button>
422
+ <button type="button" class="btn icon" data-cmd="unlink" aria-label="Remove link" title="Remove link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1M4 4l16 16"/></svg></button>
423
+ </div>
424
+ <div class="rt" id="stDesc" contenteditable="true" role="textbox" aria-multiline="true" aria-labelledby="stDescLbl" data-placeholder="Optional notes for this slide"></div>
425
+ <label class="check" for="stDescShow"><input type="checkbox" id="stDescShow">Show in presentation</label>
426
+ </div>
427
+ </div>
428
+ <h2>Stage</h2>
429
+ <ul class="tips" style="margin-top:12px">
430
+ <li><b>Pull apart.</b> Drag an icon out of its bubble. Past the membrane it pinches off into its own bubble.</li>
431
+ <li><b>Merge.</b> Drop an element or a whole bubble onto another bubble. Hold <kbd>⌘</kbd>/<kbd>Ctrl</kbd> while dropping to put it in a new inner cell; drop on a cell to join it.</li>
432
+ <li><b>Add around.</b> Select a bubble, then Add around. New bubbles bud off and the ring re-spaces itself evenly.</li>
433
+ <li><b>Tags &amp; filter.</b> Tag bubbles and elements in this panel. Type in the filter bar (<span class="kbd">/</span>) or use the funnel to pick tags and icons; everything else fades back.</li>
434
+ <li><b>Connect.</b> Turn on Connect (<span class="kbd">C</span>), then drag from one element to another. Click a line to label and style it.</li>
435
+ <li><b>Views.</b> Save as new snapshots the stage into a new view; Save updates the selected one. In Present, <span class="kbd">→</span> morphs to the next one.</li>
436
+ </ul>
437
+ </section>
438
+ <section id="inspBubble" hidden>
439
+ <div style="display:flex;flex-direction:column;gap:16px">
440
+ <h2>Bubble</h2>
441
+ <div class="field"><label for="bTitle">Title</label><input type="text" id="bTitle" maxlength="40" placeholder="Untitled"></div>
442
+ <div class="field"><label for="bTagIn">Tags</label><div class="tags" id="bTags"></div><input type="text" id="bTagIn" list="tagList" maxlength="24" placeholder="Add a tag and press Enter" autocomplete="off"></div>
443
+ <div class="field"><span class="lbl" id="bHueLbl">Membrane colour</span><div class="swatches" id="bHues" role="group" aria-labelledby="bHueLbl"></div><input type="color" id="bColor" aria-label="Custom membrane colour" title="Custom colour"></div>
444
+ <div class="field"><label for="bSpace">Membrane space</label><div class="range"><input type="range" id="bSpace" min="0.2" max="2" step="0.05"><output id="bSpaceOut" for="bSpace"></output></div></div>
445
+ <div class="field" id="bPinchField"><label for="bPinch">Pinch</label><div class="range"><input type="range" id="bPinch" min="0" max="1" step="0.05"><output id="bPinchOut" for="bPinch"></output></div></div>
446
+ <div class="actions">
447
+ <button class="btn" type="button" id="bAddEl" title="Add element (⌘L)" aria-keyshortcuts="Meta+L Control+L"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg><span>Add e<span class="mn">l</span>ement</span></button>
448
+ <button class="btn" type="button" id="bAround" title="Add around (⌘U)" aria-keyshortcuts="Meta+U Control+U"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M12 8v8M8 12h8"/></svg><span>Add aro<span class="mn">u</span>nd</span></button>
449
+ <button class="btn" type="button" id="bOrbit"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M12 12h.01"/></svg>Orbit…</button>
450
+ <button class="btn" type="button" id="bUnorbit"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 4.5A9 9 0 1 0 19.5 9 M14 10l7-7 M15 3h6v6"/></svg>Leave orbit</button>
451
+ <button class="btn" type="button" id="bDup" title="Duplicate (⌘D)" aria-keyshortcuts="Meta+D Control+D"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 9h11v11H9z M5 15H4V4h11v1"/></svg><span><span class="mn">D</span>uplicate</span></button>
452
+ <button class="btn danger" type="button" id="bDel" title="Delete bubble (⌫)" aria-keyshortcuts="Backspace Delete"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16 M9 7V4h6v3 M6 7l1 13h10l1-13 M10 11v6 M14 11v6"/></svg>Delete bubble</button>
453
+ </div>
454
+ </div>
455
+ </section>
456
+ <section id="inspElement" hidden>
457
+ <div style="display:flex;flex-direction:column;gap:16px">
458
+ <div class="insphead">
459
+ <h2 id="eHead">Element</h2>
460
+ <div class="actions">
461
+ <button class="btn icon" type="button" id="eDup" aria-label="Duplicate" title="Duplicate (⌘D)" aria-keyshortcuts="Meta+D Control+D"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 9h11v11H9z M5 15H4V4h11v1"/></svg></button>
462
+ <button class="btn icon" type="button" id="ePull" aria-label="Pull out" title="Pull out into its own bubble (⌘P)" aria-keyshortcuts="Meta+P Control+P"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 15a6 6 0 1 1 0-12 M12 12l9 9 M14 21h7v-7"/></svg></button>
463
+ <button class="btn icon danger" type="button" id="eDel" aria-label="Delete element" title="Delete element (⌫)" aria-keyshortcuts="Backspace Delete"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16 M9 7V4h6v3 M6 7l1 13h10l1-13 M10 11v6 M14 11v6"/></svg></button>
464
+ </div>
465
+ </div>
466
+ <div class="field"><label for="eLabel">Label</label><input type="text" id="eLabel" maxlength="60"></div>
467
+ <div class="field">
468
+ <span class="lbl" id="eDescLbl">Description</span>
469
+ <div class="rtbar" id="eDescBar" role="toolbar" aria-label="Description formatting">
470
+ <button type="button" class="btn icon" data-cmd="bold" aria-label="Bold" title="Bold (⌘B)"><b>B</b></button>
471
+ <button type="button" class="btn icon" data-cmd="italic" aria-label="Italic" title="Italic (⌘I)"><i>I</i></button>
472
+ <button type="button" class="btn icon" data-cmd="insertUnorderedList" aria-label="Bullet list" title="Bullet list"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01"/></svg></button>
473
+ <button type="button" class="btn icon" data-cmd="link" aria-label="Link" title="Link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg></button>
474
+ <button type="button" class="btn icon" data-cmd="unlink" aria-label="Remove link" title="Remove link"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1M4 4l16 16"/></svg></button>
475
+ </div>
476
+ <div class="rt" id="eDesc" contenteditable="true" role="textbox" aria-multiline="true" aria-labelledby="eDescLbl" data-placeholder="Optional notes, bullets and links"></div>
477
+ <label class="check" for="eDescShow"><input type="checkbox" id="eDescShow">Show in presentation</label>
478
+ </div>
479
+ <div class="field"><label for="eTagIn">Tags</label><div class="tags" id="eTags"></div><input type="text" id="eTagIn" list="tagList" maxlength="24" placeholder="Add a tag and press Enter" autocomplete="off"></div>
480
+ <div class="field"><div class="iconhead"><span class="lbl" id="eIconLbl">Icon</span><input type="search" id="eIconQ" placeholder="Filter icons" aria-label="Filter icons" autocomplete="off" hidden><button class="btn icon" type="button" id="eIconFind" aria-label="Filter icons" title="Filter icons" aria-expanded="false"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z M16 16l5 5"/></svg></button></div><div class="icons" id="eIcons" role="group" aria-labelledby="eIconLbl"></div></div>
481
+ <div class="field"><span class="lbl" id="eHueLbl">Chip colour</span><div class="swatches" id="eHues" role="group" aria-labelledby="eHueLbl"></div></div>
482
+ <div class="field"><span class="lbl" id="eTextLbl">Label style</span><div class="swatches" id="eText" role="group" aria-labelledby="eTextLbl"></div></div>
483
+ <div class="field">
484
+ <span class="lbl">Image</span>
485
+ <div class="actions">
486
+ <label class="btn" id="eUploadLbl" for="eUpload">Upload image</label>
487
+ <input type="file" id="eUpload" accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml" hidden>
488
+ <button class="btn" type="button" id="eNoImg">Remove image</button>
489
+ </div>
490
+ <span class="status" id="eImgNote"></span>
491
+ </div>
492
+ </div>
493
+ </section>
494
+ <datalist id="tagList"></datalist>
495
+ <section id="inspLink" hidden>
496
+ <div style="display:flex;flex-direction:column;gap:16px">
497
+ <h2>Connection</h2>
498
+ <div class="field"><label for="lLabel">Label</label><input type="text" id="lLabel" maxlength="60" placeholder="e.g. signs in"></div>
499
+ <div class="field"><label for="lTagIn">Tags</label><div class="tags" id="lTags"></div><input type="text" id="lTagIn" list="tagList" maxlength="24" placeholder="Add a tag and press Enter" autocomplete="off"></div>
500
+ <div class="field"><span class="lbl" id="lHeadLbl">Arrow</span>
501
+ <div class="seg" id="lHead" role="group" aria-labelledby="lHeadLbl">
502
+ <button type="button" data-v="none">None</button><button type="button" data-v="end">End</button><button type="button" data-v="both">Both</button>
503
+ </div>
504
+ </div>
505
+ <div class="field"><span class="lbl" id="lDashLbl">Line</span>
506
+ <div class="seg" id="lDash" role="group" aria-labelledby="lDashLbl">
507
+ <button type="button" data-v="solid">Solid</button><button type="button" data-v="dashed">Dashed</button><button type="button" data-v="flow">Flowing</button>
508
+ </div>
509
+ </div>
510
+ <div class="field"><span class="lbl">Elasticity</span>
511
+ <label class="check" for="lElastic"><input type="checkbox" id="lElastic">Rubber band</label>
512
+ <div class="range"><input type="range" id="lElasticity" min="0.05" max="1" step="0.05" aria-label="Elasticity amount"><output id="lElasticOut" for="lElasticity"></output></div>
513
+ </div>
514
+ <div class="field"><label for="lOpacity">Opacity</label>
515
+ <div class="range"><input type="range" id="lOpacity" min="0" max="100" step="5"><output id="lOpacityOut" for="lOpacity"></output></div>
516
+ </div>
517
+ <div class="field">
518
+ <span class="lbl" id="lMsgsLbl">Messages</span>
519
+ <p class="note">Messages travel from the start of the line to its end. Select the start element to send one.</p>
520
+ <ul class="mlist" id="lMsgs" aria-labelledby="lMsgsLbl"></ul>
521
+ <button class="btn" type="button" id="lMsgAdd">Add message</button>
522
+ </div>
523
+ <form class="msged" id="msgEd" hidden aria-labelledby="msgEdTitle">
524
+ <h3 id="msgEdTitle">New message</h3>
525
+ <div class="field"><label for="mLabel">Label</label><input type="text" id="mLabel" maxlength="40" placeholder="e.g. provision DB" autocomplete="off"></div>
526
+ <div class="field"><label for="mFieldIn">Input fields <span class="hint2">optional</span></label><div class="tags" id="mFieldTags"></div><input type="text" id="mFieldIn" maxlength="24" placeholder="Add a field and press Enter" autocomplete="off"><input type="hidden" id="mFields"><p class="note">Asked for when the message is sent. Use them in steps as <code>$name</code> (<code>$$</code> for a plain $); any a step uses are added here and stay while it does.</p></div>
527
+ <div class="field">
528
+ <span class="lbl" id="mActsLbl">When it arrives, in order</span>
529
+ <p class="note">Click a step to change it. Drag the handle to reorder.</p>
530
+ <ol class="acts" id="mActs" aria-labelledby="mActsLbl"></ol>
531
+ <button class="btn" type="button" id="mActAdd">Add step</button>
532
+ </div>
533
+ <div class="actions">
534
+ <button class="btn primary" type="submit">Save message</button>
535
+ <button class="btn" type="button" id="mCancel">Cancel</button>
536
+ </div>
537
+ </form>
538
+ <div class="actions">
539
+ <button class="btn" type="button" id="lReverse">Reverse</button>
540
+ <button class="btn danger" type="button" id="lDel">Delete connection</button>
541
+ </div>
542
+ </div>
543
+ </section>
544
+ </aside>
545
+
546
+ <dialog class="modal" id="openDlg" aria-labelledby="openDlgTitle">
547
+ <form id="openForm">
548
+ <header class="mhead"><h2 id="openDlgTitle">Open a deck</h2><button type="button" class="btn icon" id="openClose" aria-label="Close"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></header>
549
+ <div class="mbody" style="display:flex;flex-direction:column;gap:16px">
550
+ <div class="drop" id="openDrop">
551
+ <span>Drop a deck .json file here, or</span>
552
+ <label class="btn" for="openFile" id="openFileLbl">Choose file…</label>
553
+ <input type="file" id="openFile" accept=".json,application/json" hidden>
554
+ </div>
555
+ <div class="field">
556
+ <label for="openUrl">Or open from a URL</label>
557
+ <div class="urlrow"><input type="url" id="openUrl" placeholder="https://…/deck.json" autocomplete="off"><button type="submit" class="btn primary" id="openGo">Open</button></div>
558
+ <p class="note">Opening replaces the deck saved in this browser. To share a deck, link to it with <code>?src=</code> instead.</p>
559
+ </div>
560
+ <p class="err" id="openErr" role="alert" hidden></p>
561
+ </div>
562
+ </form>
563
+ </dialog>
564
+
565
+ <dialog class="modal" id="stepDlg" aria-labelledby="stepDlgTitle">
566
+ <form id="stepForm">
567
+ <header class="mhead"><h2 id="stepDlgTitle">Step</h2><button type="button" class="btn icon" id="stepClose" aria-label="Close without saving"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></header>
568
+ <div class="mbody">
569
+ <div class="field" id="stepMsgField" hidden><label for="stepMsgLabel">Message label</label><input type="text" id="stepMsgLabel" maxlength="40" placeholder="e.g. provision DB" autocomplete="off" aria-describedby="stepMsgErr"><p class="err" id="stepMsgErr" hidden>Label is required.</p></div>
570
+ <div class="field"><span class="lbl" id="stepKindsLbl">What happens</span><div class="kinds" id="stepKinds" role="group" aria-labelledby="stepKindsLbl"></div></div>
571
+ <div id="stepBody"></div>
572
+ </div>
573
+ <footer class="mfoot"><p class="err" id="stepErr" role="alert" hidden></p><button type="button" class="btn" id="stepCancel">Cancel</button><button type="submit" class="btn primary" id="stepSave">Save step</button></footer>
574
+ </form>
575
+ </dialog>
576
+
577
+ <footer class="views">
578
+ <span class="lbl">Views</span>
579
+ <div class="chips" id="chips"></div>
580
+ <div class="vedit" id="vedit" hidden>
581
+ <input type="text" id="vName" maxlength="60" aria-label="View name">
582
+ <button class="btn icon" type="button" id="vLeft" aria-label="Move view earlier"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M15 6l-6 6 6 6"/></svg></button>
583
+ <button class="btn icon" type="button" id="vRight" aria-label="Move view later"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></button>
584
+ <button class="btn" type="button" id="vUpdate" title="Save the stage into this view (⌘S)">Save</button>
585
+ <button class="btn danger" type="button" id="vDel">Delete</button>
586
+ </div>
587
+ <button class="btn primary" type="button" id="vSave" title="Save the stage as a new view (Ctrl/Cmd+S updates the selected view)">Save as new</button>
588
+ </footer>
589
+ </div>
590
+
591
+ <script>
592
+ // Visible failure if the module (or its CDN imports) never boots.
593
+ setTimeout(() => {
594
+ if (!window.__cellDeckBooted) {
595
+ const b = document.getElementById('banner');
596
+ document.getElementById('bannerText').textContent = 'The stage engine did not load. Check your connection and reload the page.';
597
+ b.hidden = false;
598
+ }
599
+ }, 9000);
600
+ </script>
601
+
602
+ <script type="importmap">
603
+ { "imports": {
604
+ "@sinclair/typebox": "https://cdn.jsdelivr.net/npm/@sinclair/typebox@0.32.35/+esm",
605
+ "@sinclair/typebox/value": "https://cdn.jsdelivr.net/npm/@sinclair/typebox@0.32.35/value/+esm"
606
+ } }
607
+ </script>
608
+ <script type="module">
609
+ import {
610
+ HUES, ICONS, ICON_KEYS, LIMITS, TAG_PATTERN, normalizeTag, ElementSchema, BubbleSchema, SelectorSchema, ActionSchema, LIMIT_ACTIONS, LIMIT_CHAIN, MessageSchema, LIMIT_MESSAGES, LinkSchema, LIMIT_LINKS, StageSchema, DEFAULT_STAGE, stageTarget, presentedScene, ownedScene, hexRgb, SceneSchema, migrateScene, EMPTY_FILTER, filterActive, filterMatch, litAlpha, tagsInScene, iconsInScene, CameraSchema, ViewSchema, LIMIT_VIEWS, DeckSchema, EMPTY_DECK, parseDeck, parseOrThrow, UserError, K, slotLayout, indexOf, bubbleRadius, slotOffset, ringRadius, checkScene, applyCommand, hashPhase, createRuntime, syncRuntime, orbitTargets, gapAngle, freezeScene, buildSteps, detachGap, clamp, FIELD_PATTERN, TEMPLATE_TAG_PATTERN, fieldRefs, linkLanes, step, linkGeometry, resolveSelector, describeAction, describeMessage, sendableMessages, messageCommand, pointAlong, hitTest, elementAt, bubbleAt, bubbleLayout, cellAt, nextCell, cellWalls, powerHalf, membraneBlend, lobeField,
611
+ encodeDeckLink, decodeDeckLink, LIMIT_LINK,
612
+ } from './lib/core.js';
613
+ import { createDeckStore, memoryStorage } from './lib/store.js';
614
+
615
+
616
+ // ====================================================================
617
+ // Edge: rendering, input, persistence, UI.
618
+ // ====================================================================
619
+ window.__cellDeckBooted = true;
620
+
621
+ const $ = (id) => {
622
+ const el = document.getElementById(id);
623
+ if (!el) throw new Error(`bug: missing #${id}`);
624
+ return el;
625
+ };
626
+ const newId = (prefix) => `${prefix}-${[...crypto.getRandomValues(new Uint8Array(6))].map((b) => b.toString(16).padStart(2, '0')).join('')}`;
627
+
628
+ // ---------- theme ----------
629
+ function hexToRgb(hex) {
630
+ const m = /^#([0-9a-f]{6})$/i.exec(hex.trim());
631
+ if (!m) throw new Error(`bug: theme token is not #rrggbb: "${hex}"`);
632
+ const n = parseInt(m[1], 16);
633
+ return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
634
+ }
635
+ function readTheme() {
636
+ const cs = getComputedStyle(document.documentElement);
637
+ const tok = (n) => cs.getPropertyValue(n).trim();
638
+ return {
639
+ bg: hexToRgb(tok('--bg')), grid: hexToRgb(tok('--grid')), gridA: parseFloat(tok('--grid-a')), dark: parseFloat(tok('--dark')),
640
+ css: { fg: tok('--fg'), muted: tok('--muted'), surface: tok('--surface'), accent: tok('--accent'), cells: Object.fromEntries(HUES.map((h) => [h, tok(`--cell-${h}`)])) },
641
+ cells: Object.fromEntries(HUES.map((h) => [h, hexToRgb(tok(`--cell-${h}`))])),
642
+ };
643
+ }
644
+
645
+ // ---------- WebGL membrane renderer ----------
646
+ const MAXB = 256, MAXG = 96, MAXBR = 64, TEXW = 256, TEXH = 8;
647
+ const VS = `#version 300 es
648
+ void main(){ vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2)); gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); }`;
649
+ const FS = `#version 300 es
650
+ precision highp float; precision highp int;
651
+ #define MAXG ${MAXG}
652
+ uniform highp sampler2D uData; uniform int uNumGroups; uniform int uNumBridges;
653
+ uniform vec2 uRes; uniform vec3 uBg; uniform vec4 uGrid; uniform vec3 uCam; uniform float uDpr; uniform float uDark;
654
+ out vec4 outColor;
655
+ vec4 F(int x, int y) { return texelFetch(uData, ivec2(x, y), 0); }
656
+ float smin(float a, float b, float k) { if (k < 0.01) return min(a, b); float h = max(k - abs(a - b), 0.0) / k; return min(a, b) - h * h * k * 0.25; }
657
+ float ballD(int i, vec2 p) {
658
+ vec4 A = F(i, 0); vec4 B = F(i, 1); vec4 C = F(i, 2);
659
+ vec2 q = p - A.xy; float s = length(C.xy);
660
+ if (s > 0.001) { vec2 u = C.xy / s; float al = dot(q, u); vec2 pe = q - u * al; q = u * (al / (1.0 + s)) + pe * (1.0 + 0.45 * s); }
661
+ float th = atan(q.y, q.x);
662
+ float re = A.z * (1.0 + B.x * sin(2.0 * th + B.z) + B.y * sin(3.0 * th + B.z * 1.7));
663
+ return length(q) - re;
664
+ }
665
+ void main() {
666
+ vec2 p = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
667
+ vec2 w = (p - uRes * 0.5) / uCam.z + uCam.xy;
668
+ float sp = 32.0; if (sp * uCam.z < 16.0 * uDpr) sp *= 4.0;
669
+ vec2 g = mod(w + sp * 0.5, sp) - sp * 0.5;
670
+ float dotv = 1.0 - smoothstep(0.7 * uDpr, 1.7 * uDpr, length(g) * uCam.z);
671
+ vec3 col = mix(uBg, uGrid.rgb, dotv * uGrid.a);
672
+ float dg[MAXG];
673
+ for (int gi = 0; gi < MAXG; gi++) {
674
+ if (gi >= uNumGroups) break;
675
+ vec4 R = F(gi, 3); vec4 Bd = F(gi, 7);
676
+ float bd = length(p - Bd.xy) - Bd.z;
677
+ float d = bd;
678
+ float gk = R.w; // this membrane's own blend radius
679
+ if (bd < gk * 2.0 + 90.0 * uCam.z) {
680
+ d = 1e5; int st = int(R.x); int n = int(R.y);
681
+ for (int i = 0; i < ${MAXB}; i++) { if (i >= n) break; d = smin(d, ballD(st + i, p), gk); }
682
+ }
683
+ dg[gi] = d;
684
+ }
685
+ for (int j = 0; j < ${MAXBR}; j++) {
686
+ if (j >= uNumBridges) break;
687
+ vec4 Bv = F(j, 6); int a = int(Bv.x); int b = int(Bv.y);
688
+ float da = dg[a]; float db = dg[b]; float m = smin(da, db, Bv.z);
689
+ if (da <= db) dg[a] = min(da, m); else dg[b] = min(db, m);
690
+ }
691
+ float px = uDpr; float zs = uCam.z;
692
+ for (int gi = 0; gi < MAXG; gi++) {
693
+ if (gi >= uNumGroups) break;
694
+ vec4 R = F(gi, 3); vec4 Cc = F(gi, 4); vec4 H = F(gi, 5);
695
+ float d = dg[gi]; float fade = R.z; vec3 gc = Cc.rgb;
696
+ if (d > 0.0) col = mix(col, gc, fade * 0.10 * exp(-d / (18.0 * zs)));
697
+ float cov = clamp(0.5 - d / px, 0.0, 1.0);
698
+ if (cov > 0.0) {
699
+ float inner = 0.10 + 0.42 * exp(d / (14.0 * zs));
700
+ col = mix(col, gc, cov * inner * fade);
701
+ vec2 hp = p - (H.xy + vec2(-0.34, -0.40) * H.z); float hr = 0.30 * H.z;
702
+ float hl = exp(-dot(hp, hp) / max(hr * hr, 1.0)) * mix(0.30, 0.10, uDark);
703
+ col = mix(col, vec3(1.0), cov * hl * fade);
704
+ }
705
+ float rim = 1.0 - smoothstep(0.5 * px, 1.6 * px, abs(d + px));
706
+ vec3 rc = mix(gc * 0.80, mix(gc, vec3(1.0), 0.18), uDark);
707
+ col = mix(col, rc, rim * 0.95 * fade);
708
+ }
709
+ outColor = vec4(col, 1.0);
710
+ }`;
711
+
712
+ function createMembraneRenderer(canvas) {
713
+ const gl = canvas.getContext('webgl2', { antialias: false, premultipliedAlpha: false });
714
+ if (!gl) throw new Error('This browser has no WebGL2, which the bubble stage needs. Try a current Chrome, Edge, Firefox or Safari.');
715
+ const compile = (type, src) => {
716
+ const s = gl.createShader(type);
717
+ gl.shaderSource(s, src); gl.compileShader(s);
718
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(`bug: shader compile failed: ${gl.getShaderInfoLog(s)}`);
719
+ return s;
720
+ };
721
+ const prog = gl.createProgram();
722
+ gl.attachShader(prog, compile(gl.VERTEX_SHADER, VS));
723
+ gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FS));
724
+ gl.linkProgram(prog);
725
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(`bug: shader link failed: ${gl.getProgramInfoLog(prog)}`);
726
+ const U = Object.fromEntries(['uData', 'uNumGroups', 'uNumBridges', 'uRes', 'uBg', 'uGrid', 'uCam', 'uDpr', 'uDark'].map((n) => [n, gl.getUniformLocation(prog, n)]));
727
+ const vao = gl.createVertexArray();
728
+ const tex = gl.createTexture();
729
+ gl.bindTexture(gl.TEXTURE_2D, tex);
730
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
731
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
732
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
733
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
734
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, TEXW, TEXH, 0, gl.RGBA, gl.FLOAT, null);
735
+ return {
736
+ draw(frame, theme) {
737
+ gl.viewport(0, 0, canvas.width, canvas.height);
738
+ gl.useProgram(prog);
739
+ gl.bindVertexArray(vao);
740
+ gl.activeTexture(gl.TEXTURE0);
741
+ gl.bindTexture(gl.TEXTURE_2D, tex);
742
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, TEXW, TEXH, gl.RGBA, gl.FLOAT, frame.data);
743
+ gl.uniform1i(U.uData, 0);
744
+ gl.uniform1i(U.uNumGroups, frame.numGroups);
745
+ gl.uniform1i(U.uNumBridges, frame.numBridges);
746
+ gl.uniform2f(U.uRes, canvas.width, canvas.height);
747
+ gl.uniform3f(U.uBg, ...theme.bg);
748
+ gl.uniform4f(U.uGrid, ...theme.grid, theme.gridA);
749
+ gl.uniform3f(U.uCam, frame.cam.x, frame.cam.y, frame.zs);
750
+ gl.uniform1f(U.uDpr, frame.dpr);
751
+ gl.uniform1f(U.uDark, theme.dark);
752
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
753
+ },
754
+ };
755
+ }
756
+
757
+ /** A bubble's membrane lobes and inner cells in world space, scaled with its body so they grow and shrink with it. */
758
+ function cellLobes(scene, b) {
759
+ const L = bubbleLayout(scene, b.id), k = b.r / L.R;
760
+ const at = (o, r) => ({ x: b.x + o.x * k, y: b.y + o.y * k, r: r * k });
761
+ return { cells: L.cells.map((c) => ({ ...at(c, c.m), cell: c.cell })), lobes: L.lobes.map((l) => at(l, l.r)) };
762
+ }
763
+
764
+ /** Pack runtime bodies into the shader's data texture. Pure apart from the returned buffer. */
765
+ function buildFrame(rt, scene, opts) {
766
+ const { dpr, W, H, theme, dragBubbleId } = opts;
767
+ const data = new Float32Array(TEXW * TEXH * 4);
768
+ const put = (col, row, a, b, c, d) => { const i = (row * TEXW + col) * 4; data[i] = a; data[i + 1] = b; data[i + 2] = c; data[i + 3] = d; };
769
+ const cam = rt.camera;
770
+ const zs = cam.zoom * dpr;
771
+ const sx = (x) => (x - cam.x) * zs + (W * dpr) / 2;
772
+ const sy = (y) => (y - cam.y) * zs + (H * dpr) / 2;
773
+ const ix = indexOf(scene);
774
+ const order = Object.values(rt.bubbles).sort((a, b) => {
775
+ const rank = (x) => (x.dying ? 0 : x.id === dragBubbleId ? 2 : 1);
776
+ return rank(a) - rank(b) || (ix.bubbles.has(a.id) && ix.bubbles.has(b.id) ? scene.bubbles.indexOf(ix.bubbles.get(a.id)) - scene.bubbles.indexOf(ix.bubbles.get(b.id)) : 0);
777
+ });
778
+ if (order.length > MAXG) throw new Error(`bug: ${order.length} membranes exceed the renderer limit of ${MAXG}`);
779
+ const elsBy = new Map();
780
+ for (const e of Object.values(rt.elements)) elsBy.set(e.bubbleId, [...(elsBy.get(e.bubbleId) ?? []), e]);
781
+ const gIndex = new Map();
782
+ let ball = 0;
783
+ order.forEach((b, g) => {
784
+ gIndex.set(b.id, g);
785
+ const start = ball;
786
+ const add = (x, y, r, w2, w3, ph, stx, sty) => {
787
+ if (ball >= MAXB) throw new Error(`bug: more than ${MAXB} metaballs`);
788
+ put(ball, 0, sx(x), sy(y), r * zs, g); put(ball, 1, w2, w3, ph, 0); put(ball, 2, stx, sty, 0, 0);
789
+ ball++;
790
+ };
791
+ let stx = b.vx / 1800, sty = b.vy / 1800;
792
+ if (rt.tether && rt.tether.bubbleId === b.id) {
793
+ const e = rt.elements[rt.tether.elementId];
794
+ const dx = e.x - b.x, dy = e.y - b.y, d = Math.hypot(dx, dy) || 1;
795
+ const k = clamp(rt.tether.gap / K.DETACH_GAP, 0, 1) * 0.22;
796
+ stx += (dx / d) * k; sty += (dy / d) * k;
797
+ }
798
+ const sl = Math.hypot(stx, sty);
799
+ if (sl > 0.35) { stx *= 0.35 / sl; sty *= 0.35 / sl; }
800
+ const lobes = ix.bubbles.has(b.id) ? cellLobes(scene, b).lobes : [];
801
+ if (lobes.length) for (const l of lobes) add(l.x, l.y, l.r, b.w2 * 0.5, b.w3 * 0.5, b.phase, stx, sty);
802
+ else add(b.x, b.y, b.r, b.w2, b.w3, b.phase, stx, sty);
803
+ let bound = b.r * (1.25 + sl);
804
+ for (const e of elsBy.get(b.id) ?? []) {
805
+ const ev = Math.hypot(e.vx, e.vy) / 2600;
806
+ const f = ev > 0.3 ? 0.3 / ev : 1;
807
+ add(e.x, e.y, K.ELEM_BALL * Math.min(e.s, 1), 0, 0, 0, (e.vx / 2600) * f, (e.vy / 2600) * f);
808
+ bound = Math.max(bound, Math.hypot(e.x - b.x, e.y - b.y) + K.ELEM_BALL * 1.3);
809
+ }
810
+ if (rt.tether && rt.tether.bubbleId === b.id && rt.tether.gap > 0) {
811
+ const e = rt.elements[rt.tether.elementId];
812
+ const dx = e.x - b.x, dy = e.y - b.y, d = Math.hypot(dx, dy) || 1;
813
+ const R = bubbleRadius(scene, b.id);
814
+ const rimX = b.x + (dx / d) * R * 0.92, rimY = b.y + (dy / d) * R * 0.92;
815
+ const eX = e.x - (dx / d) * K.ELEM_BALL * 0.8, eY = e.y - (dy / d) * K.ELEM_BALL * 0.8;
816
+ const t = clamp(rt.tether.gap / K.DETACH_GAP, 0, 1);
817
+ const nr = 26 * (1 - t) + 6 * t;
818
+ add((rimX + eX) / 2, (rimY + eY) / 2, nr, 0, 0, 0, 0, 0);
819
+ }
820
+ const cell = theme.cells[b.hue];
821
+ if (!cell) throw new Error(`bug: unknown hue ${b.hue}`);
822
+ const fade = (b.dying ? clamp(b.r / 40, 0, 1) : 1) * litAlpha(b.lit);
823
+ put(g, 3, start, ball - start, fade, (lobes.length ? membraneBlend(ix.bubbles.get(b.id)) : K.BLEND) * zs);
824
+ put(g, 4, cell[0], cell[1], cell[2], 0);
825
+ put(g, 5, sx(b.x), sy(b.y), b.r * zs, 0);
826
+ put(g, 7, sx(b.x), sy(b.y), bound * zs, 0);
827
+ });
828
+ let nb = 0;
829
+ for (const br of rt.bridges) {
830
+ if (nb >= MAXBR) break;
831
+ const a = gIndex.get(br.a), b = gIndex.get(br.b);
832
+ if (a === undefined || b === undefined) continue;
833
+ put(nb, 6, a, b, br.k * zs, 0);
834
+ nb++;
835
+ }
836
+ return { data, numGroups: order.length, numBridges: nb, zs, dpr, cam: { x: cam.x, y: cam.y } };
837
+ }
838
+
839
+ // ---------- overlay (icons, labels, selection) ----------
840
+ const iconPaths = Object.fromEntries(ICON_KEYS.map((k) => [k, new Path2D(ICONS[k][1])]));
841
+ const imgCache = new Map();
842
+ function imageFor(id) {
843
+ let im = imgCache.get(id);
844
+ if (!im) { im = new Image(); im.src = `/_blob/${id}`; imgCache.set(id, im); }
845
+ return im;
846
+ }
847
+
848
+ function drawOverlay(ctx, rt, scene, ui) {
849
+ const { W, H, dpr, theme, mode, selection, dropTargetId, dropCell, dragElementId, pickMode } = ui;
850
+ const cam = rt.camera;
851
+ const z = cam.zoom;
852
+ const sx = (x) => (x - cam.x) * z + W / 2;
853
+ const sy = (y) => (y - cam.y) * z + H / 2;
854
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
855
+ ctx.clearRect(0, 0, W, H);
856
+ const ix = indexOf(scene);
857
+ const c = theme.css;
858
+
859
+ // Inner cells: a wall between each pair of touching lobes, from pinch to pinch.
860
+ const cellSites = (b) => cellLobes(scene, b).cells;
861
+ for (const b of Object.values(rt.bubbles)) {
862
+ if (b.dying || !ix.bubbles.has(b.id) || !bubbleLayout(scene, b.id).cells.length) continue;
863
+ const col = c.cells[b.hue];
864
+ ctx.save();
865
+ ctx.globalAlpha = litAlpha(b.lit);
866
+ ctx.lineCap = 'round';
867
+ const { lobes } = cellLobes(scene, b), kb = membraneBlend(ix.bubbles.get(b.id));
868
+ for (const w0 of cellWalls(cellSites(b))) {
869
+ // stop just short of the rim so the wall tucks into the pinch
870
+ const wl = Math.hypot(w0.b.x - w0.a.x, w0.b.y - w0.a.y), tr = Math.min(4, wl / 3), ux = (w0.b.x - w0.a.x) / (wl || 1), uy = (w0.b.y - w0.a.y) / (wl || 1);
871
+ // A rounder membrane fills the waist past the pinch point: carry rim ends (not inner junctions) out to it.
872
+ const reach = (p, dx, dy) => {
873
+ if (lobeField(lobes, kb, p.x, p.y) < -kb / 4 - 6) return 0; // an inner junction
874
+ let t = 0;
875
+ while (t < kb && lobeField(lobes, kb, p.x + dx * (t + 1), p.y + dy * (t + 1)) < 0) t++;
876
+ return t;
877
+ };
878
+ const ta = reach(w0.a, -ux, -uy) - tr, tb = reach(w0.b, ux, uy) - tr;
879
+ const w = { a: { x: w0.a.x - ux * ta, y: w0.a.y - uy * ta }, b: { x: w0.b.x + ux * tb, y: w0.b.y + uy * tb } };
880
+ const line = () => { ctx.beginPath(); ctx.moveTo(sx(w.a.x), sy(w.a.y)); ctx.lineTo(sx(w.b.x), sy(w.b.y)); ctx.stroke(); };
881
+ // a wall is a thin double membrane: soft body, then a rim on each side
882
+ ctx.strokeStyle = col;
883
+ ctx.save(); ctx.globalAlpha *= 0.18; ctx.lineWidth = 10 * z; line(); ctx.restore();
884
+ const len = Math.hypot(w.b.x - w.a.x, w.b.y - w.a.y) || 1, ox = (-(w.b.y - w.a.y) / len) * 3, oy = ((w.b.x - w.a.x) / len) * 3;
885
+ ctx.save(); ctx.globalAlpha *= 0.7; ctx.lineWidth = 1.4;
886
+ for (const s of [1, -1]) { ctx.beginPath(); ctx.moveTo(sx(w.a.x + s * ox), sy(w.a.y + s * oy)); ctx.lineTo(sx(w.b.x + s * ox), sy(w.b.y + s * oy)); ctx.stroke(); }
887
+ ctx.restore();
888
+ }
889
+ ctx.restore();
890
+ }
891
+
892
+ if (mode === 'edit') {
893
+ ctx.save();
894
+ ctx.setLineDash([3, 6]);
895
+ ctx.lineWidth = 1;
896
+ ctx.strokeStyle = c.muted;
897
+ ctx.globalAlpha = 0.45;
898
+ for (const [hubId] of ix.satellites) {
899
+ const hub = rt.bubbles[hubId];
900
+ if (!hub) continue;
901
+ ctx.beginPath(); ctx.arc(sx(hub.x), sy(hub.y), ringRadius(scene, hubId) * z, 0, Math.PI * 2); ctx.stroke();
902
+ }
903
+ ctx.restore();
904
+ }
905
+
906
+ for (const b of Object.values(rt.bubbles)) {
907
+ if (!b.title) continue;
908
+ const n = ix.members.get(b.id)?.length ?? 0;
909
+ const alpha = (b.dying ? clamp(b.r / 40, 0, 1) : 1) * litAlpha(b.lit);
910
+ ctx.save();
911
+ ctx.globalAlpha = alpha;
912
+ ctx.textAlign = 'center';
913
+ if (n === 0) {
914
+ ctx.fillStyle = c.fg;
915
+ ctx.font = `700 ${20 * z}px "Bricolage Grotesque", system-ui, sans-serif`;
916
+ ctx.textBaseline = 'middle';
917
+ ctx.fillText(b.title, sx(b.x), sy(b.y), b.r * 1.8 * z);
918
+ } else {
919
+ ctx.fillStyle = c.muted;
920
+ ctx.font = `600 ${12 * z}px "Instrument Sans", system-ui, sans-serif`;
921
+ if ('letterSpacing' in ctx) ctx.letterSpacing = `${1.2 * z}px`;
922
+ ctx.textBaseline = 'top';
923
+ const lobes = ix.bubbles.has(b.id) ? cellLobes(scene, b).lobes : [];
924
+ const bottom = lobes.length ? Math.max(...lobes.map((l) => l.y + l.r)) : b.y + b.r;
925
+ ctx.fillText(b.title.toUpperCase(), sx(b.x), sy(bottom + 12));
926
+ }
927
+ ctx.restore();
928
+ }
929
+
930
+ for (const l of Object.values(rt.links)) {
931
+ const g = linkGeometry(rt, l);
932
+ if (!g) continue;
933
+ const selected = mode === 'edit' && selection?.kind === 'link' && selection.id === l.id;
934
+ const pts = g.pts.map((p) => ({ x: sx(p.x), y: sy(p.y) }));
935
+ ctx.save();
936
+ // A faded or hidden line stays findable while it is selected.
937
+ ctx.globalAlpha = l.a * litAlpha(l.lit) * Math.max(l.op ?? 1, selected ? 0.35 : 0);
938
+ const stroke = selected ? c.accent : c.fg;
939
+ ctx.strokeStyle = stroke; ctx.fillStyle = stroke;
940
+ ctx.lineWidth = 2 * Math.max(z, 0.6);
941
+ ctx.lineCap = 'round'; ctx.lineJoin = 'round';
942
+ if (l.dash === 'dashed') ctx.setLineDash([8 * z, 7 * z]);
943
+ else if (l.dash === 'flow') { ctx.setLineDash([10 * z, 9 * z]); ctx.lineDashOffset = -rt.t * 38 * z; }
944
+ else if (l.dash !== 'solid') throw new Error(`bug: unknown dash ${l.dash}`);
945
+ ctx.beginPath();
946
+ pts.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));
947
+ ctx.stroke();
948
+ ctx.setLineDash([]);
949
+ const head = (tip, from) => {
950
+ const ang = Math.atan2(tip.y - from.y, tip.x - from.x);
951
+ const L = 11 * Math.max(z, 0.6), Wd = 0.42;
952
+ ctx.beginPath();
953
+ ctx.moveTo(tip.x, tip.y);
954
+ ctx.lineTo(tip.x - L * Math.cos(ang - Wd), tip.y - L * Math.sin(ang - Wd));
955
+ ctx.lineTo(tip.x - L * Math.cos(ang + Wd), tip.y - L * Math.sin(ang + Wd));
956
+ ctx.closePath(); ctx.fill();
957
+ };
958
+ const n = pts.length;
959
+ if (l.head === 'end' || l.head === 'both') head(pts[n - 1], pts[Math.max(0, n - 3)]);
960
+ if (l.head === 'both') head(pts[0], pts[Math.min(n - 1, 2)]);
961
+ if (l.label) {
962
+ const m = { x: sx(g.mid.x), y: sy(g.mid.y) };
963
+ ctx.font = `600 ${12 * z}px "Instrument Sans", system-ui, sans-serif`;
964
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
965
+ const w = ctx.measureText(l.label).width + 14 * z, h = 22 * z;
966
+ ctx.beginPath();
967
+ ctx.roundRect(m.x - w / 2, m.y - h / 2, w, h, h / 2);
968
+ ctx.fillStyle = c.surface; ctx.fill();
969
+ ctx.lineWidth = 1; ctx.strokeStyle = selected ? c.accent : c.muted; ctx.stroke();
970
+ ctx.fillStyle = c.fg; ctx.fillText(l.label, m.x, m.y + 0.5 * z);
971
+ }
972
+ ctx.restore();
973
+ }
974
+ if (ui.pendingLink) {
975
+ const from = rt.elements[ui.pendingLink.fromId];
976
+ const to = ui.pendingLink.targetId ? rt.elements[ui.pendingLink.targetId] : null;
977
+ if (from) {
978
+ ctx.save();
979
+ ctx.strokeStyle = c.accent; ctx.lineWidth = 2; ctx.setLineDash([6, 5]);
980
+ ctx.beginPath();
981
+ ctx.moveTo(sx(from.x), sy(from.y - 8));
982
+ ctx.lineTo(to ? sx(to.x) : sx(ui.pendingLink.x), to ? sy(to.y - 8) : sy(ui.pendingLink.y));
983
+ ctx.stroke();
984
+ if (to) { ctx.setLineDash([]); ctx.beginPath(); ctx.arc(sx(to.x), sy(to.y - 8), (K.ELEM_R + 6) * z, 0, Math.PI * 2); ctx.stroke(); }
985
+ ctx.restore();
986
+ }
987
+ }
988
+
989
+ const drawLabel = (e, y, w, lw) => {
990
+ ctx.fillStyle = e.textHue ? c.cells[e.textHue] : c.fg;
991
+ ctx.fillText(e.label, 0, y);
992
+ if (e.strike && e.label) ctx.fillRect(-w / 2, y - lw / 2, w, lw);
993
+ };
994
+ for (const e of Object.values(rt.elements)) {
995
+ if (e.s < 0.02) continue;
996
+ const host = rt.bubbles[e.bubbleId];
997
+ const hue = e.hue ? c.cells[e.hue] : host ? c.cells[host.hue] : c.muted;
998
+ ctx.save();
999
+ ctx.globalAlpha = litAlpha(e.lit);
1000
+ ctx.translate(sx(e.x), sy(e.y));
1001
+ ctx.scale(z * e.s, z * e.s);
1002
+ ctx.textAlign = 'center';
1003
+ ctx.textBaseline = 'middle';
1004
+ const hasChip = e.imageId || e.icon;
1005
+ if (hasChip) {
1006
+ ctx.beginPath(); ctx.arc(0, -8, K.ELEM_R, 0, Math.PI * 2);
1007
+ ctx.fillStyle = e.fill ? hue : c.surface; ctx.fill();
1008
+ if (e.imageId) {
1009
+ const im = imageFor(e.imageId);
1010
+ if (im.complete && im.naturalWidth) {
1011
+ ctx.save(); ctx.clip();
1012
+ const s = Math.max((K.ELEM_R * 2) / im.naturalWidth, (K.ELEM_R * 2) / im.naturalHeight);
1013
+ ctx.drawImage(im, -im.naturalWidth * s / 2, -8 - im.naturalHeight * s / 2, im.naturalWidth * s, im.naturalHeight * s);
1014
+ ctx.restore();
1015
+ }
1016
+ } else {
1017
+ ctx.save();
1018
+ ctx.translate(-12 * 1.1, -8 - 12 * 1.1); ctx.scale(1.1, 1.1);
1019
+ ctx.strokeStyle = e.fill ? c.surface : c.fg; ctx.lineWidth = 1.7; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
1020
+ ctx.stroke(iconPaths[e.icon]);
1021
+ ctx.restore();
1022
+ }
1023
+ ctx.beginPath(); ctx.arc(0, -8, K.ELEM_R, 0, Math.PI * 2);
1024
+ ctx.strokeStyle = hue; ctx.lineWidth = 1.5; ctx.stroke();
1025
+ if (e.label) {
1026
+ ctx.font = '600 13px "Instrument Sans", system-ui, sans-serif';
1027
+ const w = ctx.measureText(e.label).width;
1028
+ const f = w > 96 ? 96 / w : 1;
1029
+ ctx.save(); ctx.scale(f, f);
1030
+ drawLabel(e, 32 / f, w, 1.5);
1031
+ ctx.restore();
1032
+ }
1033
+ } else {
1034
+ ctx.font = '700 17px "Bricolage Grotesque", system-ui, sans-serif';
1035
+ const w = ctx.measureText(e.label || ' ').width;
1036
+ const f = w > 92 ? 92 / w : 1;
1037
+ ctx.scale(f, f);
1038
+ drawLabel(e, 0, w, 2);
1039
+ }
1040
+ ctx.restore();
1041
+ }
1042
+
1043
+ for (const pk of ui.packets) {
1044
+ const l = rt.links[pk.linkId];
1045
+ const g = l && linkGeometry(rt, l);
1046
+ if (!g) continue;
1047
+ const raw = clamp((rt.t - pk.start) / pk.dur, 0, 1);
1048
+ const p = raw < 0.5 ? 2 * raw * raw : 1 - Math.pow(-2 * raw + 2, 2) / 2;
1049
+ const at = pointAlong(g.pts, p);
1050
+ const x = sx(at.x), y = sy(at.y);
1051
+ const fadeIn = clamp(raw * 8, 0, 1);
1052
+ ctx.save();
1053
+ ctx.globalAlpha = fadeIn;
1054
+ ctx.shadowColor = c.accent; ctx.shadowBlur = 16;
1055
+ ctx.fillStyle = c.accent;
1056
+ ctx.beginPath(); ctx.arc(x, y, 7 * Math.max(z, 0.7), 0, Math.PI * 2); ctx.fill();
1057
+ ctx.shadowBlur = 0;
1058
+ ctx.font = `700 ${12 * Math.max(z, 0.8)}px "Instrument Sans", system-ui, sans-serif`;
1059
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
1060
+ const w = ctx.measureText(pk.label).width + 16, h = 22 * Math.max(z, 0.8);
1061
+ ctx.beginPath(); ctx.roundRect(x - w / 2, y - h - 14, w, h, h / 2);
1062
+ ctx.fillStyle = c.accent; ctx.fill();
1063
+ ctx.fillStyle = c.surface; ctx.fillText(pk.label, x, y - h / 2 - 14 + 0.5);
1064
+ ctx.restore();
1065
+ }
1066
+
1067
+ if (mode === 'present' && selection?.kind === 'element' && rt.elements[selection.id]) {
1068
+ const e = rt.elements[selection.id];
1069
+ ctx.save();
1070
+ ctx.strokeStyle = c.accent; ctx.lineWidth = 2; ctx.globalAlpha = 0.8;
1071
+ ctx.beginPath(); ctx.arc(sx(e.x), sy(e.y - 8), (K.ELEM_R + 6) * z, 0, Math.PI * 2); ctx.stroke();
1072
+ ctx.restore();
1073
+ }
1074
+ if (mode === 'edit' && selection) {
1075
+ ctx.save();
1076
+ ctx.strokeStyle = c.accent; ctx.lineWidth = 1.5; ctx.setLineDash([5, 4]);
1077
+ if (selection.kind === 'bubble' && rt.bubbles[selection.id]) {
1078
+ const b = rt.bubbles[selection.id];
1079
+ ctx.beginPath(); ctx.arc(sx(b.x), sy(b.y), b.r * z + 8, 0, Math.PI * 2); ctx.stroke();
1080
+ } else if (selection.kind === 'element') {
1081
+ for (const id of ui.selectedIds) {
1082
+ const e = rt.elements[id];
1083
+ if (e) { ctx.beginPath(); ctx.arc(sx(e.x), sy(e.y - 8), (K.ELEM_R + 7) * z, 0, Math.PI * 2); ctx.stroke(); }
1084
+ }
1085
+ }
1086
+ ctx.restore();
1087
+ }
1088
+ if (ui.marquee) {
1089
+ const m = ui.marquee, x = Math.min(sx(m.x0), sx(m.x)), y = Math.min(sy(m.y0), sy(m.y));
1090
+ ctx.save();
1091
+ ctx.strokeStyle = ctx.fillStyle = c.accent; ctx.lineWidth = 1; ctx.setLineDash([4, 3]);
1092
+ ctx.globalAlpha = 0.08; ctx.fillRect(x, y, Math.abs(sx(m.x) - sx(m.x0)), Math.abs(sy(m.y) - sy(m.y0)));
1093
+ ctx.globalAlpha = 0.9; ctx.strokeRect(x, y, Math.abs(sx(m.x) - sx(m.x0)), Math.abs(sy(m.y) - sy(m.y0)));
1094
+ ctx.restore();
1095
+ }
1096
+ if (dropTargetId && rt.bubbles[dropTargetId]) {
1097
+ const b = rt.bubbles[dropTargetId];
1098
+ const sites = cellSites(b), me = sites.find((x) => x.cell === dropCell);
1099
+ ctx.save();
1100
+ ctx.strokeStyle = ctx.fillStyle = c.cells[b.hue]; ctx.lineWidth = 3; ctx.globalAlpha = 0.7;
1101
+ if (me) {
1102
+ // tint the target compartment: its lobe clipped by the half-plane of each neighbour
1103
+ ctx.beginPath(); ctx.arc(sx(me.x), sy(me.y), me.r * z, 0, Math.PI * 2); ctx.clip();
1104
+ for (const o of sites) {
1105
+ if (o === me) continue;
1106
+ const h = powerHalf(me, o), l = Math.hypot(h.nx, h.ny), ux = h.nx / l, uy = h.ny / l, px = (ux * h.k) / l, py = (uy * h.k) / l, L = 1e4;
1107
+ ctx.beginPath(); // big quad on the n·p <= k side
1108
+ for (const [a, d] of [[-L, 0], [L, 0], [L, -L], [-L, -L]]) ctx.lineTo(sx(px - uy * a + ux * d), sy(py + ux * a + uy * d));
1109
+ ctx.clip();
1110
+ }
1111
+ ctx.globalAlpha = 0.16; ctx.fillRect(0, 0, W, H);
1112
+ } else {
1113
+ if (dropCell === 'new') ctx.setLineDash([8, 7]);
1114
+ ctx.beginPath(); ctx.arc(sx(b.x), sy(b.y), b.r * z + 7, 0, Math.PI * 2); ctx.stroke();
1115
+ }
1116
+ ctx.restore();
1117
+ }
1118
+ if (pickMode) {
1119
+ ctx.save(); ctx.fillStyle = c.accent; ctx.globalAlpha = 0.06; ctx.fillRect(0, 0, W, H); ctx.restore();
1120
+ }
1121
+ }
1122
+
1123
+ // ---------- app state (the only mutable holder) ----------
1124
+ const app = {
1125
+ scene: EMPTY_DECK.scene,
1126
+ downloadName: 'deck.json', // file name for plain downloads; Save as changes it where there is no file picker
1127
+ build: null, // present mode, step navigation: { toId, steps: [scene], i } while building toward the next view
1128
+ navMode: (() => { try { return localStorage.getItem('celldeck.nav') === 'jump' ? 'jump' : 'step'; } catch { return 'step'; } })(),
1129
+ fileHandle: null, // FileSystemFileHandle the deck was opened from or saved as; Download writes back to it
1130
+ rt: createRuntime(EMPTY_DECK.scene, EMPTY_DECK.camera),
1131
+ cam: { ...EMPTY_DECK.camera },
1132
+ past: [], future: [],
1133
+ selection: null,
1134
+ multi: [], // shift-clicked element ids; counts only while it includes the selected element
1135
+ mode: 'edit',
1136
+ pick: null,
1137
+ drag: null,
1138
+ dropTargetId: null,
1139
+ dropCell: null, // with dropTargetId: the inner cell number the drop lands in, or 'new' (⌘/Ctrl held) for a new cell
1140
+ views: [],
1141
+ activeViewId: null,
1142
+ filter: EMPTY_FILTER,
1143
+ packets: [],
1144
+ msgDraft: null, // { linkId, messageId | null } while the message editor is open
1145
+ filterOpen: false,
1146
+ presentStash: null,
1147
+ store: null, persist: false, unsaved: false, unsub: null, assets: null,
1148
+ saveState: 'saved',
1149
+ theme: readTheme(),
1150
+ };
1151
+
1152
+ function showError(err) {
1153
+ const msg = err instanceof Error ? err.message : String(err);
1154
+ console.error(err);
1155
+ // The banner sits behind an open modal, so the step dialog shows its own problems.
1156
+ if ($('stepDlg').open) { $('stepErr').textContent = msg; $('stepErr').hidden = false; return; }
1157
+ $('bannerText').textContent = msg;
1158
+ $('banner').hidden = false;
1159
+ }
1160
+ $('bannerClose').addEventListener('click', () => { $('banner').hidden = true; });
1161
+
1162
+ function setScene(next, { history, hints = { spawnFrom: {} } }) {
1163
+ if (next === app.scene) return;
1164
+ app.rt = syncRuntime(app.rt, app.scene, next, hints);
1165
+ if (history) {
1166
+ app.past = [...app.past.slice(-99), app.scene];
1167
+ app.future = [];
1168
+ }
1169
+ app.scene = next;
1170
+ const ix = indexOf(next);
1171
+ if (app.selection && !({ bubble: ix.bubbles, element: ix.elements, link: ix.links }[app.selection.kind]).has(app.selection.id)) app.selection = null;
1172
+ app.multi = app.multi.filter((id) => ix.elements.has(id));
1173
+ scheduleSave();
1174
+ renderUI();
1175
+ }
1176
+
1177
+ function dispatch(cmd, hints = { spawnFrom: {} }) {
1178
+ try {
1179
+ const frozen = freezeScene(app.scene, app.rt);
1180
+ setScene(applyCommand(frozen, cmd), { history: true, hints }); // present mode has its own short-lived history
1181
+ return true;
1182
+ } catch (err) {
1183
+ showError(err);
1184
+ return false;
1185
+ }
1186
+ }
1187
+ const nextHue = (scene) => HUES[scene.bubbles.length % HUES.length];
1188
+ /** Every selected element: the shift-click group, or just the selected element. */
1189
+ const selIds = () => app.selection?.kind !== 'element' ? [] : app.multi.includes(app.selection.id) ? app.multi : [app.selection.id];
1190
+
1191
+ function undo() {
1192
+ if (!app.past.length) return;
1193
+ const prev = app.past[app.past.length - 1];
1194
+ app.past = app.past.slice(0, -1);
1195
+ app.future = [app.scene, ...app.future];
1196
+ setScene(prev, { history: false });
1197
+ }
1198
+ function redo() {
1199
+ if (!app.future.length) return;
1200
+ const [nxt, ...rest] = app.future;
1201
+ app.future = rest;
1202
+ app.past = [...app.past, app.scene];
1203
+ setScene(nxt, { history: false });
1204
+ }
1205
+
1206
+ // ---------- persistence ----------
1207
+ // The deck lives in a DeckStore (lib/store.js): localStorage normally, or memory when opened from ?src=
1208
+ // so a shared deck never overwrites local work. Download writes deck.json; Open replaces the local deck.
1209
+ const STORAGE_KEY = 'celldeck:deck:v1';
1210
+ const params = new URLSearchParams(location.search);
1211
+ let saveTimer = null;
1212
+ function setStatus() {
1213
+ $('status').textContent =
1214
+ app.saveState === 'error' ? 'Save failed'
1215
+ : app.persist ? (app.saveState === 'dirty' ? 'Unsaved changes' : 'Saved in this browser')
1216
+ : app.unsaved ? 'Changed · Download to keep' : 'Not saved in this browser';
1217
+ }
1218
+ function scheduleSave() {
1219
+ if (!app.store || app.mode !== 'edit') return;
1220
+ app.saveState = 'dirty'; setStatus();
1221
+ clearTimeout(saveTimer);
1222
+ saveTimer = setTimeout(saveWorking, 700);
1223
+ }
1224
+ function saveWorking() {
1225
+ clearTimeout(saveTimer);
1226
+ if (!app.store || app.mode !== 'edit') return;
1227
+ storeWrite('save the stage', () => app.store.saveStage({ scene: freezeScene(app.scene, app.rt), camera: roundCam(app.cam) }));
1228
+ }
1229
+ /** Run one store write; failures (quota, invalid data) are shown, never swallowed. */
1230
+ function storeWrite(what, f) {
1231
+ try { f(); app.saveState = 'saved'; }
1232
+ catch (err) { app.saveState = 'error'; showError(new Error(`Could not ${what}: ${err?.message ?? err}`)); }
1233
+ setStatus();
1234
+ }
1235
+ const roundCam = (c) => ({ x: Math.round(c.x), y: Math.round(c.y), zoom: Math.round(c.zoom * 1000) / 1000 });
1236
+
1237
+ /** The browser's deck store, or null (with the reason shown) when storage is unavailable or holds a broken deck. */
1238
+ function localStore() {
1239
+ try { return createDeckStore(localStorage, STORAGE_KEY); }
1240
+ catch (err) { showError(new Error(`${err?.message ?? err} Working in memory only; Download to keep changes.`)); return null; }
1241
+ }
1242
+ function useStore(store, persist) {
1243
+ app.unsub?.();
1244
+ app.store = store; app.persist = persist; app.unsaved = false;
1245
+ app.cleanViews = JSON.stringify(store.get().views);
1246
+ const deck = store.get();
1247
+ app.scene = deck.scene;
1248
+ app.rt = createRuntime(deck.scene, deck.camera);
1249
+ app.cam = { ...deck.camera };
1250
+ app.past = []; app.future = [];
1251
+ app.selection = null; app.activeViewId = null;
1252
+ app.views = deck.views;
1253
+ app.saveState = 'saved';
1254
+ app.unsub = store.subscribe((d) => {
1255
+ app.views = d.views;
1256
+ // ponytail: only view edits count as unsaved; clicking through views also moves the stage, and that shouldn't nag on leave.
1257
+ app.unsaved = !app.persist && JSON.stringify(d.views) !== app.cleanViews;
1258
+ if (app.activeViewId && !d.views.some((v) => v.id === app.activeViewId)) app.activeViewId = null;
1259
+ renderUI();
1260
+ });
1261
+ renderUI(); setStatus();
1262
+ }
1263
+ /** Fetches and parses a deck; `writable` when the server (the `celldeck` CLI) accepts a PUT back to the same URL. */
1264
+ async function fetchDeck(raw) {
1265
+ const url = new URL(raw, location.href);
1266
+ let res;
1267
+ try { res = await fetch(url); } catch (err) { throw new Error(`Could not fetch ${url.href} (${err.message}). A deck on another site must allow CORS.`); }
1268
+ if (!res.ok) throw new Error(`Could not fetch ${url.href}: HTTP ${res.status}`);
1269
+ let json;
1270
+ try { json = await res.json(); } catch { throw new Error(`${url.href} is not JSON.`); }
1271
+ return { deck: parseDeck(json, url.pathname.split('/').pop() || url.href), writable: res.headers.get('x-celldeck-writable') === '1' };
1272
+ }
1273
+ /**
1274
+ * A file handle (the shape downloadDeck uses) that PUTs the deck back to the URL it came from.
1275
+ * Only the `celldeck` CLI server offers one: it marks the deck it serves with x-celldeck-writable.
1276
+ */
1277
+ function putHandle(url) {
1278
+ return {
1279
+ name: decodeURIComponent(url.pathname.split('/').pop() || url.href),
1280
+ createWritable: async () => {
1281
+ let body = '';
1282
+ return {
1283
+ write: async (t) => { body += t; },
1284
+ close: async () => {
1285
+ const res = await fetch(url, { method: 'PUT', body, headers: { 'content-type': 'application/json' } });
1286
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`.trim());
1287
+ },
1288
+ };
1289
+ },
1290
+ };
1291
+ }
1292
+ /** Open a deck from a file or URL: it replaces the deck saved in this browser, and ?src= is dropped. */
1293
+ function openDeck(deck) {
1294
+ if (app.persist && !confirm('Replace the deck saved in this browser? Download it first to keep a copy.')) return false;
1295
+ let store = null;
1296
+ try { localStorage.setItem(STORAGE_KEY, JSON.stringify(deck)); store = localStore(); } catch (err) { showError(new Error(`Could not save to this browser (${err.message}). Working in memory only.`)); }
1297
+ useStore(store ?? createDeckStore(memoryStorage(), 'deck', deck), !!store);
1298
+ setParams({ src: null, view: null, present: null });
1299
+ if (location.hash.startsWith('#deck=')) history.replaceState(null, '', location.pathname + location.search);
1300
+ return true;
1301
+ }
1302
+ // File System Access API (Chromium): opening a file through it keeps a handle, so Download writes back to that file.
1303
+ // Elsewhere Download is a normal browser download, and Save as asks for the file name first.
1304
+ const canSaveAs = 'showSaveFilePicker' in window;
1305
+ const JSON_TYPES = [{ description: 'Cell Deck', accept: { 'application/json': ['.json'] } }];
1306
+ function setFileHandle(h) {
1307
+ app.fileHandle = h ?? null;
1308
+ $('downloadTxt').textContent = app.fileHandle ? `Save to ${app.fileHandle.name}` : 'Download deck.json';
1309
+ }
1310
+ async function downloadDeck(saveAs = false) {
1311
+ if (app.mode === 'edit') saveWorking();
1312
+ const text = JSON.stringify(app.store.get(), null, 2) + '\n';
1313
+ try {
1314
+ if (saveAs && canSaveAs) setFileHandle(await showSaveFilePicker({ suggestedName: app.fileHandle?.name ?? app.downloadName, types: JSON_TYPES }));
1315
+ else if (saveAs) {
1316
+ // No file picker here (Safari, Firefox, insecure origin, iframe): ask for a name and download under it.
1317
+ const name = prompt('Save as', app.downloadName)?.trim();
1318
+ if (!name) return;
1319
+ app.downloadName = /\.json$/i.test(name) ? name : `${name}.json`;
1320
+ }
1321
+ if (app.fileHandle) {
1322
+ if ((await app.fileHandle.requestPermission?.({ mode: 'readwrite' })) === 'denied') throw new Error(`No permission to write ${app.fileHandle.name}. Use Save as.`);
1323
+ const w = await app.fileHandle.createWritable();
1324
+ await w.write(text); await w.close();
1325
+ } else {
1326
+ const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
1327
+ const a = Object.assign(document.createElement('a'), { href: url, download: app.downloadName });
1328
+ document.body.append(a); a.click(); a.remove();
1329
+ setTimeout(() => URL.revokeObjectURL(url), 0);
1330
+ }
1331
+ } catch (err) {
1332
+ if (err?.name !== 'AbortError') showError(new Error(`Could not save: ${err?.message ?? err}`));
1333
+ return;
1334
+ }
1335
+ app.cleanViews = JSON.stringify(app.store.get().views); app.unsaved = false; setStatus();
1336
+ }
1337
+ window.addEventListener('beforeunload', (ev) => { if (!app.persist && app.unsaved) ev.preventDefault(); });
1338
+
1339
+ /** ?src=<deck.json url> ?view=<view id or name> ?present — shareable links into a deck. */
1340
+ function setParams(kv) {
1341
+ const q = new URLSearchParams(location.search);
1342
+ for (const [k, v] of Object.entries(kv)) v === null ? q.delete(k) : q.set(k, v);
1343
+ const s = q.toString().replace(/%2F/gi, '/').replace(/%3A/gi, ':').replace(/=(&|$)/g, '$1');
1344
+ history.replaceState(null, '', location.pathname + (s ? `?${s}` : '') + location.hash);
1345
+ }
1346
+ async function boot() {
1347
+ const src = params.get('src');
1348
+ const linked = location.hash.startsWith('#deck=') ? location.hash.slice(6) : null;
1349
+ if (linked) {
1350
+ // Like ?src: the linked deck lives in memory so it never overwrites the deck saved in this browser.
1351
+ try { useStore(createDeckStore(memoryStorage(), 'deck', await decodeDeckLink(linked)), false); }
1352
+ catch (err) { showError(err); useStore(createDeckStore(memoryStorage(), 'deck'), false); return; }
1353
+ } else if (src) {
1354
+ try {
1355
+ const { deck, writable } = await fetchDeck(src);
1356
+ useStore(createDeckStore(memoryStorage(), 'deck', deck), false);
1357
+ // Served by the `celldeck` CLI: Save writes back to the file on disk.
1358
+ if (writable) setFileHandle(putHandle(new URL(src, location.href)));
1359
+ }
1360
+ catch (err) { showError(err); useStore(createDeckStore(memoryStorage(), 'deck'), false); return; }
1361
+ } else {
1362
+ const store = localStore();
1363
+ useStore(store ?? createDeckStore(memoryStorage(), 'deck'), !!store);
1364
+ }
1365
+ const want = params.get('view');
1366
+ if (want !== null) {
1367
+ const v = app.store.findView(want);
1368
+ if (v) goToView(v.id); else showError(`This deck has no view "${want}".`);
1369
+ }
1370
+ if (params.has('present')) enterPresent();
1371
+ }
1372
+
1373
+ // ---------- views ----------
1374
+ function saveView() {
1375
+ const id = newId('v');
1376
+ storeWrite('save the view', () => app.store.createView({ id, name: `View ${app.views.length + 1}`, scene: freezeScene(app.scene, app.rt), camera: roundCam(app.cam) }));
1377
+ goToView(id);
1378
+ }
1379
+ function updateView(patch) {
1380
+ if (!app.activeViewId) throw new Error('bug: no active view to update');
1381
+ storeWrite('update the view', () => app.store.updateView(app.activeViewId, patch));
1382
+ }
1383
+ function moveView(dir) {
1384
+ if (app.activeViewId) storeWrite('reorder', () => app.store.moveView(app.activeViewId, dir));
1385
+ }
1386
+ let deleteArmed = null;
1387
+ function deleteView() {
1388
+ const v = app.views.find((x) => x.id === app.activeViewId);
1389
+ if (!v) return;
1390
+ if (deleteArmed !== v.id) {
1391
+ deleteArmed = v.id; $('vDel').textContent = 'Confirm delete';
1392
+ setTimeout(() => { deleteArmed = null; $('vDel').textContent = 'Delete'; }, 3000);
1393
+ return;
1394
+ }
1395
+ deleteArmed = null; $('vDel').textContent = 'Delete';
1396
+ storeWrite('delete the view', () => app.store.deleteView(v.id));
1397
+ setParams({ view: null });
1398
+ }
1399
+ function goToView(id) {
1400
+ const v = app.views.find((x) => x.id === id);
1401
+ if (!v) throw new Error(`bug: unknown view ${id}`);
1402
+ app.build = null;
1403
+ app.activeViewId = id;
1404
+ app.selection = null;
1405
+ setScene(presentedScene(app.views, id), { history: app.mode === 'edit' });
1406
+ if (app.mode === 'present') { app.past = []; app.future = []; } // undo in present stays within the current slide
1407
+ app.cam = { ...v.camera };
1408
+ setParams({ view: id });
1409
+ renderUI();
1410
+ }
1411
+ function stepView(dir) {
1412
+ if (!app.views.length) return;
1413
+ const i = app.views.findIndex((x) => x.id === app.activeViewId);
1414
+ if (app.mode === 'present' && app.navMode === 'step') {
1415
+ const b = app.build;
1416
+ if (b) {
1417
+ const k = b.i + dir;
1418
+ if (k < 0) goToView(app.activeViewId); // back past the first step: the view we started from
1419
+ else if (k >= b.steps.length - 1) goToView(b.toId); // the last step is the next view itself
1420
+ else { b.i = k; showBuildStep(); }
1421
+ return;
1422
+ }
1423
+ const next = dir > 0 && i >= 0 ? app.views[i + 1] : null;
1424
+ let steps = [];
1425
+ try { if (next) steps = buildSteps(freezeScene(app.scene, app.rt), presentedScene(app.views, next.id)); } catch (err) { console.error(err); } // fall back to a jump
1426
+ if (steps.length > 1) {
1427
+ app.build = { toId: next.id, steps, i: 0 };
1428
+ app.cam = { ...next.camera };
1429
+ showBuildStep();
1430
+ return;
1431
+ }
1432
+ }
1433
+ const j = i < 0 ? 0 : clamp(i + dir, 0, app.views.length - 1);
1434
+ if (j !== i) goToView(app.views[j].id);
1435
+ }
1436
+
1437
+ function showBuildStep() {
1438
+ app.selection = null;
1439
+ setScene(app.build.steps[app.build.i], { history: false });
1440
+ app.past = []; app.future = [];
1441
+ renderUI();
1442
+ }
1443
+ function toggleNavMode() {
1444
+ app.navMode = app.navMode === 'step' ? 'jump' : 'step';
1445
+ try { localStorage.setItem('celldeck.nav', app.navMode); } catch {}
1446
+ if (app.build) goToView(app.build.toId); // switching mid-build finishes it
1447
+ else renderUI();
1448
+ }
1449
+
1450
+ // ---------- present mode ----------
1451
+ function enterPresent() {
1452
+ app.presentStash = { scene: freezeScene(app.scene, app.rt), cam: { ...app.cam }, past: app.past, future: app.future };
1453
+ app.past = []; app.future = [];
1454
+ app.mode = 'present'; app.pick = null; app.selection = null;
1455
+ $('app').classList.add('present');
1456
+ setParams({ present: '' });
1457
+ document.documentElement.requestFullscreen?.().catch(() => {});
1458
+ if (app.views.length) goToView((app.views.find((v) => v.id === app.activeViewId) ?? app.views[0]).id);
1459
+ renderUI();
1460
+ resize();
1461
+ }
1462
+ function exitPresent() {
1463
+ if (app.mode !== 'present') return;
1464
+ app.mode = 'edit';
1465
+ app.build = null;
1466
+ $('app').classList.remove('present');
1467
+ setParams({ present: null });
1468
+ if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
1469
+ const st = app.presentStash;
1470
+ app.presentStash = null;
1471
+ setScene(st.scene, { history: false });
1472
+ app.past = st.past; app.future = st.future; // present-mode deletions and messages never reach the edit history
1473
+ app.cam = st.cam;
1474
+ renderUI();
1475
+ resize();
1476
+ }
1477
+ document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && app.mode === 'present') exitPresent(); });
1478
+
1479
+ // ---------- UI binding ----------
1480
+ const iconSvg = (key) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${ICONS[key][1]}"/></svg>`;
1481
+ (function buildPickers() {
1482
+ const hues = $('bHues');
1483
+ for (const h of HUES) {
1484
+ const b = document.createElement('button');
1485
+ b.type = 'button'; b.className = 'swatch'; b.style.setProperty('--c', `var(--cell-${h})`);
1486
+ b.setAttribute('aria-label', h); b.dataset.hue = h;
1487
+ b.addEventListener('click', () => app.selection && dispatch({ type: 'updateBubble', id: app.selection.id, patch: { hue: h } }));
1488
+ hues.append(b);
1489
+ }
1490
+ $('bColor').addEventListener('input', (ev) => app.selection && dispatch({ type: 'updateBubble', id: app.selection.id, patch: { hue: ev.target.value.toLowerCase() } }));
1491
+ $('bPinch').addEventListener('input', (ev) => app.selection && dispatch({ type: 'updateBubble', id: app.selection.id, patch: { pinch: Number(ev.target.value) } }));
1492
+ $('bSpace').addEventListener('input', (ev) => app.selection && dispatch({ type: 'updateBubble', id: app.selection.id, patch: { space: Number(ev.target.value) } }));
1493
+ const icons = $('eIcons');
1494
+ const none = document.createElement('button');
1495
+ none.type = 'button'; none.dataset.icon = ''; none.setAttribute('aria-label', 'No icon'); none.innerHTML = '<span class="none">None</span>';
1496
+ none.addEventListener('click', () => { lastIcon = null; app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch: { icon: null } }); });
1497
+ icons.append(none);
1498
+ for (const k of ICON_KEYS) {
1499
+ const b = document.createElement('button');
1500
+ b.type = 'button'; b.dataset.icon = k; b.setAttribute('aria-label', ICONS[k][0]); b.title = ICONS[k][0]; b.innerHTML = iconSvg(k);
1501
+ // Keep focus (and the selection) in the label while the label is being edited, so clicking icons can retitle it.
1502
+ b.addEventListener('mousedown', (ev) => { if (document.activeElement === $('eLabel')) ev.preventDefault(); });
1503
+ b.addEventListener('click', () => {
1504
+ lastIcon = k;
1505
+ if (!app.selection) return;
1506
+ const e = indexOf(app.scene).elements.get(app.selection.id);
1507
+ const input = $('eLabel');
1508
+ // A fully selected label (e.g. "New" on a fresh element) is a placeholder: the icon's name replaces it.
1509
+ const allSelected = document.activeElement === input && input.value !== '' && input.selectionStart === 0 && input.selectionEnd === input.value.length;
1510
+ const patch = { icon: k };
1511
+ if (allSelected || !e.label || Object.values(ICONS).some(([n]) => n === e.label)) patch.label = ICONS[k][0];
1512
+ dispatch({ type: 'updateElement', id: app.selection.id, patch });
1513
+ if (allSelected) { input.value = patch.label; input.select(); }
1514
+ });
1515
+ icons.append(b);
1516
+ }
1517
+ })();
1518
+
1519
+ function renderUI() {
1520
+ const ix = indexOf(app.scene);
1521
+ const sel = app.selection;
1522
+ const selB = sel?.kind === 'bubble' ? ix.bubbles.get(sel.id) : null;
1523
+ const selE = sel?.kind === 'element' ? ix.elements.get(sel.id) : null;
1524
+ const selL = sel?.kind === 'link' ? ix.links.get(sel.id) : null;
1525
+ $('inspNone').hidden = !!(selB || selE || selL);
1526
+ $('inspBubble').hidden = !selB;
1527
+ $('inspElement').hidden = !selE;
1528
+ if (selE) { const n = selIds().length; $('eHead').textContent = n > 1 ? `${n} elements` : 'Element'; $('eDel').title = n > 1 ? `Delete ${n} elements (⌫)` : 'Delete element (⌫)'; }
1529
+ $('inspLink').hidden = !selL;
1530
+ if (selL) {
1531
+ if (document.activeElement !== $('lLabel')) $('lLabel').value = selL.label;
1532
+ for (const b of $('lHead').children) b.setAttribute('aria-pressed', String(b.dataset.v === selL.head));
1533
+ for (const b of $('lDash').children) b.setAttribute('aria-pressed', String(b.dataset.v === selL.dash));
1534
+ $('lElastic').checked = selL.elasticity > 0;
1535
+ $('lElasticity').disabled = selL.elasticity <= 0;
1536
+ if (selL.elasticity > 0) $('lElasticity').value = String(selL.elasticity);
1537
+ $('lElasticOut').textContent = selL.elasticity > 0 ? selL.elasticity.toFixed(2) : 'off';
1538
+ const op = Math.round((selL.opacity ?? 1) * 100);
1539
+ if (document.activeElement !== $('lOpacity')) $('lOpacity').value = String(op);
1540
+ $('lOpacityOut').textContent = `${op}%`;
1541
+ }
1542
+ $('connect').setAttribute('aria-pressed', String(app.pick === 'connect'));
1543
+ if (selB) renderTagChips($('bTags'), selB.tags, (t) => dispatch({ type: 'updateBubble', id: selB.id, patch: { tags: selB.tags.filter((x) => x !== t) } }));
1544
+ if (selL) renderTagChips($('lTags'), selL.tags, (t) => dispatch({ type: 'updateLink', id: selL.id, patch: { tags: selL.tags.filter((x) => x !== t) } }));
1545
+ if (selE) renderTagChips($('eTags'), selE.tags, (t) => dispatch({ type: 'updateElement', id: selE.id, patch: { tags: selE.tags.filter((x) => x !== t) } }));
1546
+ renderCrumbs(selB, selE);
1547
+ renderFilter();
1548
+ renderStageControls();
1549
+ renderPresentStrip();
1550
+ renderMessages();
1551
+ if (selB) {
1552
+ if (document.activeElement !== $('bTitle')) $('bTitle').value = selB.title;
1553
+ for (const b of $('bHues').children) b.setAttribute('aria-pressed', String(b.dataset.hue === selB.hue));
1554
+ if (document.activeElement !== $('bColor')) $('bColor').value = selB.hue.startsWith('#') ? selB.hue : (app.theme.css.cells[selB.hue] ?? '#000000').toLowerCase();
1555
+ const sp = selB.space ?? 1;
1556
+ if (document.activeElement !== $('bSpace')) $('bSpace').value = String(sp);
1557
+ $('bSpaceOut').value = `${Math.round(sp * 100)}%`;
1558
+ const pinch = selB.pinch ?? 0.6;
1559
+ $('bPinchField').hidden = !bubbleLayout(app.scene, selB.id).cells.length; // only cells pinch
1560
+ if (document.activeElement !== $('bPinch')) $('bPinch').value = String(pinch);
1561
+ $('bPinchOut').value = `${Math.round(pinch * 100)}%`;
1562
+ $('bOrbit').hidden = !!selB.orbit;
1563
+ $('bUnorbit').hidden = !selB.orbit;
1564
+ }
1565
+ if (selE) {
1566
+ if (document.activeElement !== $('eLabel')) $('eLabel').value = selE.label;
1567
+ syncRich('eDesc', selE.id, selE);
1568
+ for (const b of $('eIcons').children) b.setAttribute('aria-pressed', String((b.dataset.icon || null) === selE.icon));
1569
+ const canUpload = !!app.assets;
1570
+ $('eUploadLbl').hidden = !canUpload;
1571
+ $('eNoImg').hidden = !selE.imageId;
1572
+ $('eImgNote').textContent = canUpload ? '' : 'Image upload is not supported yet.';
1573
+ $('ePull').disabled = ix.members.get(selE.bubbleId).length < 2 && !ix.bubbles.get(selE.bubbleId).title;
1574
+ }
1575
+ $('undo').disabled = !app.past.length;
1576
+ $('redo').disabled = !app.future.length;
1577
+ $('pickbar').hidden = !app.pick;
1578
+ if (app.pick) {
1579
+ const txt = { orbit: 'Click the bubble to orbit around · Esc to cancel', connect: 'Drag from one element to another to connect them · Esc when done' }[app.pick];
1580
+ if (!txt) throw new Error(`bug: unknown pick mode ${app.pick}`);
1581
+ $('pickbar').textContent = txt;
1582
+ }
1583
+
1584
+ const chips = $('chips');
1585
+ chips.replaceChildren();
1586
+ if (!app.views.length) {
1587
+ const p = document.createElement('span');
1588
+ p.className = 'empty';
1589
+ p.textContent = 'No views yet. Arrange the stage, then Save as new.';
1590
+ chips.append(p);
1591
+ }
1592
+ app.views.forEach((v, i) => {
1593
+ const b = document.createElement('button');
1594
+ b.type = 'button'; b.className = 'chip';
1595
+ b.setAttribute('aria-current', String(v.id === app.activeViewId));
1596
+ const n = document.createElement('span'); n.className = 'n'; n.textContent = String(i + 1);
1597
+ const t = document.createElement('span'); t.textContent = v.name;
1598
+ b.append(n, t);
1599
+ b.title = 'Click to show · drag to reorder';
1600
+ b.dataset.i = String(i);
1601
+ b.addEventListener('pointerdown', (ev) => startViewDrag(ev, b, v.id));
1602
+ b.addEventListener('click', (ev) => { if (b.dataset.dragged) { ev.preventDefault(); return; } goToView(v.id); });
1603
+ chips.append(b);
1604
+ });
1605
+ const active = app.views.find((v) => v.id === app.activeViewId);
1606
+ $('vedit').hidden = !active;
1607
+ if (active && document.activeElement !== $('vName')) $('vName').value = active.name;
1608
+
1609
+ const hudOn = app.mode === 'present';
1610
+ $('hud').hidden = !hudOn; $('ptop').hidden = !hudOn;
1611
+ // Footer notes: the clicked element's; otherwise (nothing clicked, or it has no shown notes) the slide's.
1612
+ const shown = (x) => (x?.showDescription && x.description ? x : null);
1613
+ const clicked = hudOn && app.selection?.kind === 'element' ? shown(indexOf(app.scene).elements.get(app.selection.id)) : null;
1614
+ const note = hudOn ? clicked ?? shown(app.scene.stage) : null;
1615
+ $('pdesc').hidden = !note;
1616
+ $('pdesc').replaceChildren(...(clicked?.label ? [Object.assign(document.createElement('h3'), { textContent: clicked.label })] : []), ...(note ? [safeHtml(note.description)] : []));
1617
+ if (hudOn) {
1618
+ const i = app.views.findIndex((v) => v.id === app.activeViewId);
1619
+ const b = app.build, to = b && app.views.find((v) => v.id === b.toId);
1620
+ $('hudPos').textContent = !app.views.length ? 'No saved views'
1621
+ : b ? `${i + 1} → ${i + 2} / ${app.views.length} · ${to.name} · step ${b.i + 1} of ${b.steps.length}`
1622
+ : `${i + 1} / ${app.views.length} · ${active?.name ?? ''}`;
1623
+ $('prev').disabled = i <= 0 && !b;
1624
+ $('next').disabled = !b && (i < 0 ? !app.views.length : i >= app.views.length - 1);
1625
+ const step = app.navMode === 'step';
1626
+ $('navMode').textContent = step ? 'Step' : 'Jump';
1627
+ $('navMode').title = step ? '→ adds one element at a time. Click to jump straight to each view.' : '→ jumps straight to the next view. Click to add one element at a time.';
1628
+ $('navMode').setAttribute('aria-label', `Navigation: ${step ? 'step through each element' : 'jump between views'}. Click to switch.`);
1629
+ }
1630
+ }
1631
+
1632
+ function renderTagChips(box, tags, onRemove, locked = new Set()) {
1633
+ box.replaceChildren(...tags.map((t) => {
1634
+ const chip = document.createElement('span');
1635
+ chip.className = 'tag';
1636
+ const name = document.createElement('span');
1637
+ name.textContent = t;
1638
+ if (locked.has(t)) { chip.classList.add('locked'); chip.title = 'Used in a step'; chip.append(name); return chip; }
1639
+ const x = document.createElement('button');
1640
+ x.type = 'button'; x.textContent = '×'; x.setAttribute('aria-label', `Remove tag ${t}`);
1641
+ x.addEventListener('click', () => onRemove(t));
1642
+ chip.append(name, x);
1643
+ return chip;
1644
+ }));
1645
+ }
1646
+
1647
+ function renderFilter() {
1648
+ const f = app.filter;
1649
+ const tags = tagsInScene(app.scene);
1650
+ const icons = iconsInScene(app.scene);
1651
+ $('tagList').replaceChildren(...tags.map((t) => Object.assign(document.createElement('option'), { value: t })));
1652
+ const n = f.tags.length + f.icons.length;
1653
+ $('fBadge').hidden = n === 0;
1654
+ $('fBadge').textContent = String(n);
1655
+ $('fToggle').classList.toggle('on', n > 0);
1656
+ $('fToggle').setAttribute('aria-expanded', String(app.filterOpen));
1657
+ $('fPanel').hidden = !app.filterOpen;
1658
+ if (document.activeElement !== $('fQuery')) $('fQuery').value = f.q;
1659
+ const m = filterMatch(app.scene, f);
1660
+ $('fCount').textContent = m ? `${m.elements.size} of ${app.scene.elements.length} elements match` : `${app.scene.elements.length} elements · nothing filtered`;
1661
+ $('fClear').hidden = !filterActive(f);
1662
+ const chip = (label, pressed, onClick, svg) => {
1663
+ const b = document.createElement('button');
1664
+ b.type = 'button'; b.className = 'fchip';
1665
+ b.setAttribute('aria-pressed', String(pressed));
1666
+ if (svg) b.innerHTML = svg;
1667
+ b.append(document.createTextNode(label));
1668
+ b.addEventListener('click', onClick);
1669
+ return b;
1670
+ };
1671
+ const toggle = (list, v) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v]);
1672
+ const empty = (text) => Object.assign(document.createElement('span'), { className: 'fempty', textContent: text });
1673
+ // Selected tags stay listed even if nothing uses them any more, so they can be turned off.
1674
+ const tagOpts = [...new Set([...tags, ...f.tags])].sort();
1675
+ $('fTags').replaceChildren(...(tagOpts.length ? tagOpts.map((t) => chip(t, f.tags.includes(t), () => setFilter({ ...f, tags: toggle(f.tags, t) }))) : [empty('No tags yet. Add them in the inspector.')]));
1676
+ const iconOpts = ICON_KEYS.filter((k) => icons.includes(k) || f.icons.includes(k));
1677
+ $('fIcons').replaceChildren(...(iconOpts.length ? iconOpts.map((k) => chip(ICONS[k][0], f.icons.includes(k), () => setFilter({ ...f, icons: toggle(f.icons, k) }), iconSvg(k))) : [empty('No icons on the stage.')]));
1678
+ }
1679
+ function setFilter(f) { app.filter = f; renderFilter(); }
1680
+
1681
+ function addTag(input, kind) {
1682
+ if (app.selection?.kind !== kind) throw new Error(`bug: tag input for ${kind} without that selection`);
1683
+ const raw = input.value;
1684
+ if (!raw.trim()) return;
1685
+ let tag;
1686
+ try { tag = normalizeTag(raw); } catch (err) { showError(err); return; }
1687
+ const ix = indexOf(app.scene);
1688
+ const map = { bubble: [ix.bubbles, 'updateBubble'], element: [ix.elements, 'updateElement'], link: [ix.links, 'updateLink'] }[kind];
1689
+ if (!map) throw new Error(`bug: tags on unknown kind ${kind}`);
1690
+ const cur = map[0].get(app.selection.id);
1691
+ input.value = '';
1692
+ if (cur.tags.includes(tag)) return;
1693
+ if (cur.tags.length >= 12) { showError('Each bubble, element or connection can have up to 12 tags.'); return; }
1694
+ dispatch({ type: map[1], id: cur.id, patch: { tags: [...cur.tags, tag] } });
1695
+ }
1696
+ for (const [id, kind] of [['bTagIn', 'bubble'], ['eTagIn', 'element'], ['lTagIn', 'link']]) {
1697
+ $(id).addEventListener('keydown', (ev) => {
1698
+ if (ev.key === 'Enter' || ev.key === ',') { ev.preventDefault(); addTag(ev.target, kind); }
1699
+ });
1700
+ $(id).addEventListener('change', (ev) => { if (tagsInScene(app.scene).includes(ev.target.value.trim().toLowerCase())) addTag(ev.target, kind); });
1701
+ }
1702
+
1703
+ $('fQuery').addEventListener('input', (ev) => setFilter({ ...app.filter, q: ev.target.value }));
1704
+ $('fToggle').addEventListener('click', () => { app.filterOpen = !app.filterOpen; renderFilter(); });
1705
+ $('fClear').addEventListener('click', () => { setFilter(EMPTY_FILTER); $('fQuery').value = ''; });
1706
+ document.addEventListener('pointerdown', (ev) => {
1707
+ if (app.filterOpen && !$('filterWrap').contains(ev.target)) { app.filterOpen = false; renderFilter(); }
1708
+ });
1709
+
1710
+ // ---------- messages ----------
1711
+ const ACTION_GLYPH = {
1712
+ add: 'M12 6v12M6 12h12',
1713
+ split: 'M8 12a4 4 0 1 1 0 .01M16 12a4 4 0 1 1 0 .01',
1714
+ clone: 'M8 8h11v11H8z M5 16V5h11',
1715
+ remove: 'M6 6l12 12M18 6L6 18',
1716
+ connect: 'M5 18l5-5M14 9l5-5M9 9l6 6',
1717
+ send: 'M4 12h13M13 7l5 5-5 5',
1718
+ };
1719
+ const glyph = (kind) => {
1720
+ const d = ACTION_GLYPH[kind];
1721
+ if (!d) throw new Error(`bug: no glyph for ${kind}`);
1722
+ return `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="${d}"/></svg>`;
1723
+ };
1724
+
1725
+ /** Messages the selected element can send right now: one per message on each connection that starts at it. */
1726
+ function availableMessages() {
1727
+ if (app.selection?.kind !== 'element') return [];
1728
+ const ix = indexOf(app.scene);
1729
+ return app.scene.links.filter((l) => l.from === app.selection.id).flatMap((l) => l.messages.map((msg) => ({ link: l, msg, target: ix.elements.get(l.to) })));
1730
+ }
1731
+
1732
+ function sendMessage(linkId, messageId, depth = 0, values = {}) {
1733
+ const l = indexOf(app.scene).links.get(linkId);
1734
+ if (!l) throw new Error(`bug: send on missing connection ${linkId}`);
1735
+ const msg = l.messages.find((m) => m.id === messageId);
1736
+ if (!msg) throw new Error(`bug: send of missing message ${messageId}`);
1737
+ const body = app.rt.links[linkId];
1738
+ const g = body && linkGeometry(app.rt, body);
1739
+ const len = g ? pointAlong(g.pts, 1).total : 200;
1740
+ app.packets = [...app.packets, { key: newId('pk'), linkId, messageId, depth, values, label: msg.label, start: app.rt.t, dur: clamp(len / 380, 0.7, 1.8) }];
1741
+ }
1742
+
1743
+ /** Send a message from its button: straight away, or after asking for its fields in a small form under the message bar. */
1744
+ function requestSend(linkId, messageId) {
1745
+ const msg = indexOf(app.scene).links.get(linkId)?.messages.find((m) => m.id === messageId);
1746
+ if (!msg) throw new Error(`bug: send of missing message ${messageId}`);
1747
+ if (!msg.fields?.length) { sendMessage(linkId, messageId); return; }
1748
+ const form = $('msgForm');
1749
+ const inputs = msg.fields.map((f) => Object.assign(document.createElement('input'), { type: 'text', id: uid('mf'), name: f, maxLength: 60, autocomplete: 'off', required: true }));
1750
+ form.replaceChildren(
1751
+ Object.assign(document.createElement('h3'), { textContent: msg.label }),
1752
+ ...inputs.map((inp) => {
1753
+ const row = Object.assign(document.createElement('div'), { className: 'maprow' });
1754
+ row.append(Object.assign(document.createElement('label'), { htmlFor: inp.id, textContent: inp.name }), inp);
1755
+ return row;
1756
+ }),
1757
+ (() => {
1758
+ const row = Object.assign(document.createElement('div'), { className: 'actions' });
1759
+ const cancel = Object.assign(document.createElement('button'), { type: 'button', className: 'btn', textContent: 'Cancel' });
1760
+ cancel.addEventListener('click', closeSendForm);
1761
+ row.append(Object.assign(document.createElement('button'), { type: 'submit', className: 'btn primary', textContent: 'Send' }), cancel);
1762
+ return row;
1763
+ })(),
1764
+ );
1765
+ form.onsubmit = (ev) => {
1766
+ ev.preventDefault();
1767
+ closeSendForm();
1768
+ if (!indexOf(app.scene).links.get(linkId)?.messages.some((m) => m.id === messageId)) { showError(new UserError(`“${msg.label}” is no longer on the stage.`)); return; }
1769
+ sendMessage(linkId, messageId, 0, Object.fromEntries(inputs.map((inp) => [inp.name, inp.value.trim()])));
1770
+ };
1771
+ const bar = $('msgbar');
1772
+ form.style.top = bar.hidden ? '' : `${bar.offsetTop + bar.offsetHeight + 8}px`;
1773
+ form.hidden = false;
1774
+ inputs[0].focus();
1775
+ }
1776
+ function closeSendForm() { $('msgForm').hidden = true; $('msgForm').replaceChildren(); }
1777
+ $('msgForm').addEventListener('keydown', (ev) => { ev.stopPropagation(); if (ev.key === 'Escape') closeSendForm(); }); // typing here is not a stage shortcut
1778
+
1779
+ function deliverArrivedPackets() {
1780
+ const arrived = app.packets.filter((pk) => app.rt.t - pk.start >= pk.dur);
1781
+ if (!arrived.length) return;
1782
+ app.packets = app.packets.filter((pk) => !arrived.includes(pk));
1783
+ for (const pk of arrived) {
1784
+ try {
1785
+ const { cmd, hints, sends, notes } = messageCommand(app.scene, app.rt, pk.linkId, pk.messageId, newId('m'), pk.values);
1786
+ if (cmd.cmds.length && !dispatch(cmd, hints)) continue;
1787
+ if (notes.length) showError(new UserError(notes.join(' ')));
1788
+ if (sends.length && pk.depth + 1 >= LIMIT_CHAIN) { showError(new UserError(`Stopped a chain of messages after ${LIMIT_CHAIN} hops, so a loop cannot run forever.`)); continue; }
1789
+ for (const sd of sends) sendMessage(sd.linkId, sd.messageId, pk.depth + 1, sd.values);
1790
+ } catch (err) { showError(err); }
1791
+ }
1792
+ }
1793
+
1794
+ let uidN = 0;
1795
+ const uid = (p) => `${p}${++uidN}`;
1796
+ // Tags typed into message steps: plain tags, or ones with $field placeholders that are checked once filled in.
1797
+ const parseTags = (raw) => [...new Set(raw.split(',').map((t) => t.trim()).filter(Boolean).map((t) => {
1798
+ if (!t.includes('$')) return normalizeTag(t);
1799
+ const x = t.toLowerCase().replace(/\s+/g, ' ');
1800
+ if (!new RegExp(TEMPLATE_TAG_PATTERN).test(x)) throw new UserError(`“${t}”: a tag with $fields is still up to 24 letters, digits, spaces, - and _.`);
1801
+ return x;
1802
+ }))];
1803
+ /**
1804
+ * Tag chips plus an "Add a tag" box, as in the element panel, for message steps. A tag starting with $ uses a
1805
+ * message field ($env); the suggestions list the stage's tags and the message's fields.
1806
+ */
1807
+ function tagEditor(initial, onChange = () => {}, label = '') {
1808
+ let tags = [...initial];
1809
+ const chips = Object.assign(document.createElement('div'), { className: 'tags' });
1810
+ const list = Object.assign(document.createElement('datalist'), { id: uid('dl') });
1811
+ let fields = [];
1812
+ try { fields = parseFields($('mFields').value); } catch { /* reported when the message is saved */ }
1813
+ list.append(...[...fields.map((f) => `$${f}`), ...[...$('tagList').options].map((o) => o.value)].map((value) => Object.assign(document.createElement('option'), { value })));
1814
+ const input = textInput('', fields.length ? `Add a tag or $${fields[0]}, press Enter` : 'Add a tag and press Enter', 24, list.id);
1815
+ const render = () => renderTagChips(chips, tags, (t) => { tags = tags.filter((x) => x !== t); render(); onChange(); });
1816
+ /** Turn the typed text into a chip; returns false (after reporting) when it isn't a usable tag. */
1817
+ const commit = (report = true) => {
1818
+ const raw = input.value.replace(/,/g, ' ').trim();
1819
+ if (!raw) return true;
1820
+ let t;
1821
+ try { [t] = parseTags(raw); } catch (err) { if (report) showError(err); return false; }
1822
+ if (!tags.includes(t)) {
1823
+ if (tags.length >= 12) { if (report) showError(new UserError('A step can use up to 12 tags.')); return false; }
1824
+ tags = [...tags, t];
1825
+ }
1826
+ input.value = '';
1827
+ render(); onChange();
1828
+ return true;
1829
+ };
1830
+ input.addEventListener('keydown', (ev) => { if (ev.key === 'Enter' || ev.key === ',') { ev.preventDefault(); commit(); } }); // Enter must not submit the step
1831
+ render();
1832
+ return {
1833
+ field: () => { const f = field('Tags', input, label); input.before(chips); f.append(list); return f; },
1834
+ /** Current tags, including any still being typed; strict=false (live previews) ignores a half-typed one. */
1835
+ read: (strict = true) => {
1836
+ if (strict && !commit()) throw new UserError(`“${input.value.trim()}” isn't a usable tag.`);
1837
+ return tags;
1838
+ },
1839
+ };
1840
+ }
1841
+ /** Field names typed as "name, env": lowercase identifiers, at most 8. */
1842
+ function parseFields(raw) {
1843
+ const names = [...new Set(raw.split(',').map((f) => f.trim().replace(/^\$/, '')).filter(Boolean))];
1844
+ for (const f of names) if (!new RegExp(FIELD_PATTERN).test(f)) throw new UserError(`“${f}” can't be a field name: use lowercase letters, digits and _, starting with a letter.`);
1845
+ if (names.length > 8) throw new UserError('A message can ask for up to 8 fields.');
1846
+ return names;
1847
+ }
1848
+ /** Every piece of text in a step that may hold $fields. */
1849
+ function actionTexts(a) {
1850
+ const sel = (x) => (x?.kind === 'query' ? [x.q, ...x.tags] : []);
1851
+ switch (a.kind) {
1852
+ case 'add': return [a.label, ...a.tags];
1853
+ case 'connect': return [a.label, ...sel(a.from), ...sel(a.to)];
1854
+ case 'send': return [a.message, ...Object.values(a.args ?? {}), ...sel(a.from)];
1855
+ case 'remove': case 'split': case 'clone': return sel(a.which);
1856
+ default: return [];
1857
+ }
1858
+ }
1859
+ const field = (labelText, control, hint) => {
1860
+ const f = document.createElement('div');
1861
+ f.className = 'field';
1862
+ const lab = document.createElement('label');
1863
+ lab.htmlFor = control.id;
1864
+ lab.append(labelText);
1865
+ if (hint) lab.append(' ', Object.assign(document.createElement('span'), { className: 'hint2', textContent: hint }));
1866
+ f.append(lab, control);
1867
+ return f;
1868
+ };
1869
+ const select = (options, value) => {
1870
+ const el = document.createElement('select');
1871
+ el.id = uid('s');
1872
+ el.append(...options.map(([v, t]) => new Option(t, v)));
1873
+ el.value = value;
1874
+ return el;
1875
+ };
1876
+ const textInput = (value, placeholder, maxLength, list) => {
1877
+ const el = Object.assign(document.createElement('input'), { type: 'text', id: uid('t'), value, placeholder, maxLength, autocomplete: 'off' });
1878
+ if (list) el.setAttribute('list', list);
1879
+ return el;
1880
+ };
1881
+
1882
+ // ---- small controls: button groups, icon picker, colour picker ----
1883
+ /** One-line description of a selector, for stepper summaries. */
1884
+ const selSummary = (s) => (s.kind === 'source' ? 'Source' : s.kind === 'target' ? 'Target'
1885
+ : [s.q && `“${s.q}”`, ...s.tags.map((t) => `#${t}`), ...s.icons.map((k) => ICONS[k][0])].filter(Boolean).join(' + ') || 'Query: nothing yet');
1886
+ /**
1887
+ * Horizontal stepper: numbered headers (title + live summary) above one visible panel, with Back / Next.
1888
+ * Headers are clickable, so steps can be visited in any order; hidden panels keep their state.
1889
+ */
1890
+ function stepper(steps) {
1891
+ const el = document.createElement('div');
1892
+ el.className = 'steppanel';
1893
+ const head = document.createElement('ol');
1894
+ head.className = 'stepper';
1895
+ const panels = steps.map((st) => { const p = document.createElement('div'); p.className = 'steppanel'; p.append(st.el); return p; });
1896
+ const back = Object.assign(document.createElement('button'), { type: 'button', className: 'btn', textContent: 'Back' });
1897
+ const next = Object.assign(document.createElement('button'), { type: 'button', className: 'btn', textContent: 'Next' });
1898
+ const nav = Object.assign(document.createElement('div'), { className: 'stepnav' });
1899
+ nav.append(back, next);
1900
+ let cur = 0;
1901
+ const heads = steps.map((st, i) => {
1902
+ const b = document.createElement('button');
1903
+ b.type = 'button';
1904
+ const t = document.createElement('span'); t.className = 't';
1905
+ t.append(Object.assign(document.createElement('b'), { textContent: st.title }), document.createElement('small'));
1906
+ b.append(Object.assign(document.createElement('span'), { className: 'n', textContent: String(i + 1) }), t);
1907
+ b.addEventListener('click', () => go(i));
1908
+ const li = document.createElement('li'); li.append(b); head.append(li);
1909
+ return b;
1910
+ });
1911
+ const refresh = () => heads.forEach((b, i) => { b.querySelector('small').textContent = steps[i].summary(); });
1912
+ const go = (i) => {
1913
+ cur = i;
1914
+ panels.forEach((p, k) => { p.hidden = k !== i; });
1915
+ heads.forEach((b, k) => (k === i ? b.setAttribute('aria-current', 'step') : b.removeAttribute('aria-current')));
1916
+ back.disabled = i === 0;
1917
+ next.hidden = i === steps.length - 1;
1918
+ refresh();
1919
+ };
1920
+ back.addEventListener('click', () => go(cur - 1));
1921
+ next.addEventListener('click', () => go(cur + 1));
1922
+ el.append(head, ...panels, nav);
1923
+ go(0);
1924
+ return { el, refresh };
1925
+ }
1926
+
1927
+ /** Single-choice button group. options: [[value, label, svgHtml?]]. */
1928
+ function segmented(options, value, labelText) {
1929
+ const el = document.createElement('div');
1930
+ el.className = 'seg';
1931
+ el.setAttribute('role', 'group');
1932
+ el.style.gridTemplateColumns = `repeat(${options.length}, minmax(0, 1fr))`;
1933
+ if (labelText) el.setAttribute('aria-label', labelText);
1934
+ const listeners = [];
1935
+ let cur = value;
1936
+ const btns = options.map(([v, label, svg]) => {
1937
+ const b = document.createElement('button');
1938
+ b.type = 'button'; b.dataset.v = v;
1939
+ if (svg) b.insertAdjacentHTML('beforeend', svg);
1940
+ b.append(label);
1941
+ b.addEventListener('click', () => { cur = v; sync(); listeners.forEach((f) => f(v)); });
1942
+ return b;
1943
+ });
1944
+ const sync = () => btns.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.v === cur)));
1945
+ sync();
1946
+ el.append(...btns);
1947
+ return { el, get value() { return cur; }, onChange: (f) => listeners.push(f) };
1948
+ }
1949
+ /** The element panel's icon grid, single choice, with a None option. */
1950
+ function iconPicker(value, labelId) {
1951
+ const el = document.createElement('div');
1952
+ el.className = 'icons';
1953
+ el.setAttribute('role', 'group');
1954
+ el.setAttribute('aria-labelledby', labelId);
1955
+ let cur = value;
1956
+ const opts = [['', 'None'], ...ICON_KEYS.map((k) => [k, ICONS[k][0]])];
1957
+ const btns = opts.map(([k, name]) => {
1958
+ const b = document.createElement('button');
1959
+ b.type = 'button'; b.dataset.icon = k; b.title = name; b.setAttribute('aria-label', k ? name : 'No icon');
1960
+ b.innerHTML = k ? iconSvg(k) : '<span class="none">None</span>';
1961
+ b.addEventListener('click', () => { cur = k || null; sync(); });
1962
+ return b;
1963
+ });
1964
+ const sync = () => btns.forEach((b) => b.setAttribute('aria-pressed', String((b.dataset.icon || null) === cur)));
1965
+ sync();
1966
+ el.append(...btns);
1967
+ return { el, get value() { return cur; } };
1968
+ }
1969
+ /** The membrane swatches, with "same as the bubble" first. */
1970
+ function huePicker(value, labelId) {
1971
+ const el = document.createElement('div');
1972
+ el.className = 'swatches';
1973
+ el.setAttribute('role', 'group');
1974
+ el.setAttribute('aria-labelledby', labelId);
1975
+ let cur = value;
1976
+ const btns = [null, ...HUES].map((h) => {
1977
+ const b = document.createElement('button');
1978
+ b.type = 'button'; b.dataset.hue = h ?? '';
1979
+ b.className = h ? 'swatch' : 'swatch auto';
1980
+ if (h) b.style.setProperty('--c', `var(--cell-${h})`);
1981
+ b.setAttribute('aria-label', h ?? 'Same as the bubble'); b.title = h ?? 'Same as the bubble';
1982
+ b.addEventListener('click', () => { cur = h; sync(); });
1983
+ return b;
1984
+ });
1985
+ const sync = () => btns.forEach((b) => b.setAttribute('aria-pressed', String((b.dataset.hue || null) === cur)));
1986
+ sync();
1987
+ el.append(...btns);
1988
+ return { el, get value() { return cur; } };
1989
+ }
1990
+ const labelled = (text, control) => {
1991
+ const f = document.createElement('div');
1992
+ f.className = 'field';
1993
+ const id = uid('lbl');
1994
+ f.append(Object.assign(document.createElement('span'), { className: 'lbl', id, textContent: text }));
1995
+ control.el.setAttribute('aria-labelledby', id);
1996
+ f.append(control.el);
1997
+ return f;
1998
+ };
1999
+
2000
+ /** A From/To/Senders selector: source, target, or a query. Returns its element, a reader and a change hook. */
2001
+ function selectorControl(legend, sel, kinds = [['source', 'Source'], ['target', 'Target'], ['query', 'Query']]) {
2002
+ const box = document.createElement('fieldset');
2003
+ box.className = 'sel';
2004
+ box.append(Object.assign(document.createElement('legend'), { textContent: legend }));
2005
+ const kind = segmented(kinds, sel.kind, `${legend}: which elements`);
2006
+ const q = document.createElement('div');
2007
+ q.className = 'sub';
2008
+ const text = textInput(sel.kind === 'query' ? sel.q : '', 'label, tag or icon name', 60);
2009
+ const tags = tagEditor(sel.kind === 'query' ? sel.tags : [], () => changed(), 'all of; a bubble\'s tags count for its elements');
2010
+ const icons = document.createElement('div');
2011
+ icons.className = 'icons'; icons.setAttribute('role', 'group');
2012
+ const iconsLbl = Object.assign(document.createElement('span'), { className: 'lbl', id: uid('l'), textContent: 'Icons (any of)' });
2013
+ icons.setAttribute('aria-labelledby', iconsLbl.id);
2014
+ const listeners = [];
2015
+ const changed = () => listeners.forEach((f) => f());
2016
+ for (const k of ICON_KEYS) {
2017
+ const b = document.createElement('button');
2018
+ b.type = 'button'; b.dataset.icon = k; b.title = ICONS[k][0]; b.setAttribute('aria-label', ICONS[k][0]);
2019
+ b.setAttribute('aria-pressed', String(sel.kind === 'query' && sel.icons.includes(k)));
2020
+ b.innerHTML = iconSvg(k);
2021
+ b.addEventListener('click', () => { b.setAttribute('aria-pressed', String(b.getAttribute('aria-pressed') !== 'true')); changed(); });
2022
+ icons.append(b);
2023
+ }
2024
+ const iconField = document.createElement('div');
2025
+ iconField.className = 'field';
2026
+ iconField.append(iconsLbl, icons);
2027
+ q.append(field('Text', text), tags.field(), iconField);
2028
+ q.hidden = sel.kind !== 'query';
2029
+ kind.onChange((v) => { q.hidden = v !== 'query'; changed(); });
2030
+ text.addEventListener('input', changed);
2031
+ box.append(kind.el, q);
2032
+ return {
2033
+ el: box,
2034
+ onChange: (f) => listeners.push(f),
2035
+ /** strict=false is used for live previews, where half-typed input should not raise errors. */
2036
+ read: (strict = true) => {
2037
+ const k = kind.value;
2038
+ if (k === 'source' || k === 'target') return { kind: k };
2039
+ if (k !== 'query') throw new Error(`bug: selector kind ${k}`);
2040
+ let tagList;
2041
+ tagList = tags.read(strict);
2042
+ const out = { kind: 'query', q: text.value.trim(), tags: tagList, icons: [...icons.querySelectorAll('[aria-pressed="true"]')].map((b) => b.dataset.icon) };
2043
+ if (strict && !out.q && !out.tags.length && !out.icons.length) throw new UserError(`Give the “${legend}” query some text, tags or icons to match.`);
2044
+ return out;
2045
+ },
2046
+ };
2047
+ }
2048
+
2049
+ const ACTION_KINDS = [['add', 'Add element'], ['split', 'Split out'], ['clone', 'Clone'], ['remove', 'Remove'], ['connect', 'Connect'], ['send', 'Send message']];
2050
+ const DEFAULT_ACTION = {
2051
+ add: () => ({ kind: 'add', label: '', icon: null, tags: [], hue: null }),
2052
+ split: () => ({ kind: 'split' }), clone: () => ({ kind: 'clone' }), remove: () => ({ kind: 'remove' }),
2053
+ connect: () => ({ kind: 'connect', from: { kind: 'source' }, to: { kind: 'query', q: '', tags: [], icons: [] }, label: '', head: 'end', dash: 'solid', elasticity: 0 }),
2054
+ send: () => ({ kind: 'send', from: { kind: 'target' }, message: '' }),
2055
+ };
2056
+
2057
+ /** Settings for one step, shown in the dialog; returns { el, read } where read() builds the action or throws a UserError. */
2058
+ function actionBody(a, link) {
2059
+ const el = document.createElement('div');
2060
+ el.className = 'sub';
2061
+ switch (a.kind) {
2062
+ case 'add': {
2063
+ const label = textInput(a.label, 'e.g. Postgres (optional with an icon)', 60);
2064
+ const tags = tagEditor(a.tags);
2065
+ const iconLbl = uid('lbl'), hueLbl = uid('lbl');
2066
+ const icon = iconPicker(a.icon, iconLbl);
2067
+ const hue = huePicker(a.hue, hueLbl);
2068
+ const iconField = document.createElement('div'); iconField.className = 'field';
2069
+ iconField.append(Object.assign(document.createElement('span'), { className: 'lbl', id: iconLbl, textContent: 'Icon' }), icon.el);
2070
+ const hueField = document.createElement('div'); hueField.className = 'field';
2071
+ hueField.append(Object.assign(document.createElement('span'), { className: 'lbl', id: hueLbl, textContent: 'Chip colour' }), hue.el);
2072
+ el.append(field('New element label', label), iconField, hueField, tags.field());
2073
+ return { el, focus: label, read: () => {
2074
+ if (!label.value.trim() && !icon.value) throw new UserError('Give the new element a label or an icon.');
2075
+ return { kind: 'add', label: label.value.trim(), icon: icon.value, tags: tags.read(), hue: hue.value };
2076
+ } };
2077
+ }
2078
+ case 'remove': case 'split': case 'clone': {
2079
+ const [legend, note] = {
2080
+ remove: ['Remove', 'Removes the target, or every element the query matches when the message arrives (e.g. a tag of $env). Their connections go with them.'],
2081
+ split: ['Split out', 'The target, or every element the query matches, leaves its bubble, carried on away from the sender.'],
2082
+ clone: ['Clone', 'A copy of the target, or of every element the query matches (label, icon, image, tags, colour), appears beside it in the same bubble. Connections are not copied.'],
2083
+ }[a.kind];
2084
+ const which = selectorControl(legend, a.which ?? { kind: 'target' }, [['target', 'Target'], ['query', 'Query']]);
2085
+ el.append(Object.assign(document.createElement('p'), { className: 'note', textContent: note }), which.el);
2086
+ return { el, focus: null, read: () => { const w = which.read(); return w.kind === 'target' ? { kind: a.kind } : { kind: a.kind, which: w }; } };
2087
+ }
2088
+ case 'connect': {
2089
+ const from = selectorControl('From', a.from), to = selectorControl('To', a.to);
2090
+ const label = textInput(a.label, 'optional', 60);
2091
+ const head = segmented([['end', 'End'], ['both', 'Both'], ['none', 'None']], a.head, 'Arrow');
2092
+ const dash = segmented([['solid', 'Solid'], ['dashed', 'Dashed'], ['flow', 'Flowing']], a.dash, 'Line');
2093
+ // Elasticity: same controls as the connection panel (a switch, then how loose).
2094
+ const elasticField = document.createElement('div');
2095
+ elasticField.className = 'field';
2096
+ const on = Object.assign(document.createElement('input'), { type: 'checkbox', id: uid('c'), checked: a.elasticity > 0 });
2097
+ const onLabel = Object.assign(document.createElement('label'), { className: 'check', htmlFor: on.id });
2098
+ onLabel.append(on, 'Rubber band');
2099
+ const amount = Object.assign(document.createElement('input'), { type: 'range', id: uid('r'), min: '0.05', max: '1', step: '0.05', value: String(a.elasticity > 0 ? a.elasticity : 0.5), disabled: !(a.elasticity > 0) });
2100
+ amount.setAttribute('aria-label', 'Elasticity amount');
2101
+ const out = Object.assign(document.createElement('output'), { textContent: a.elasticity > 0 ? a.elasticity.toFixed(2) : 'off' });
2102
+ const sync = () => { amount.disabled = !on.checked; out.textContent = on.checked ? Number(amount.value).toFixed(2) : 'off'; };
2103
+ on.addEventListener('change', sync);
2104
+ amount.addEventListener('input', sync);
2105
+ const rangeRow = Object.assign(document.createElement('div'), { className: 'range' });
2106
+ rangeRow.append(amount, out);
2107
+ elasticField.append(Object.assign(document.createElement('span'), { className: 'lbl', textContent: 'Elasticity' }), onLabel, rangeRow);
2108
+ const conn = Object.assign(document.createElement('div'), { className: 'sub' });
2109
+ conn.append(field('New line label', label), labelled('Arrow', head), labelled('Line', dash), elasticField);
2110
+ const lineSummary = () => [label.value.trim() && `“${label.value.trim()}”`, { solid: 'solid', dashed: 'dashed', flow: 'flowing' }[dash.value], on.checked && 'rubber band'].filter(Boolean).join(', ');
2111
+ const steps = stepper([
2112
+ { title: 'From', el: from.el, summary: () => selSummary(from.read(false)) },
2113
+ { title: 'To', el: to.el, summary: () => selSummary(to.read(false)) },
2114
+ { title: 'Connection', el: conn, summary: lineSummary },
2115
+ ]);
2116
+ from.onChange(steps.refresh); to.onChange(steps.refresh);
2117
+ for (const x of [label, on, amount]) x.addEventListener('input', steps.refresh);
2118
+ for (const x of [head.el, dash.el]) x.addEventListener('click', steps.refresh);
2119
+ el.append(steps.el);
2120
+ return { el, focus: null, read: () => ({ kind: 'connect', from: from.read(), to: to.read(), label: label.value.trim(), head: head.value, dash: dash.value, elasticity: on.checked ? Number(amount.value) : 0 }) };
2121
+ }
2122
+ case 'send': {
2123
+ const from = selectorControl('Senders', a.from);
2124
+ const find = Object.assign(document.createElement('button'), { type: 'button', className: 'btn', textContent: 'Find senders' });
2125
+ const found = Object.assign(document.createElement('div'), { className: 'found' });
2126
+ found.setAttribute('aria-live', 'polite');
2127
+ const pickLbl = uid('lbl');
2128
+ const picks = Object.assign(document.createElement('div'), { className: 'fchips' });
2129
+ picks.setAttribute('role', 'group'); picks.setAttribute('aria-labelledby', pickLbl);
2130
+ const pickField = document.createElement('div'); pickField.className = 'field';
2131
+ pickField.append(Object.assign(document.createElement('span'), { className: 'lbl', id: pickLbl, textContent: 'Message to send' }), picks);
2132
+ let chosen = a.message;
2133
+ const args = { ...(a.args ?? {}) };
2134
+ // Fields the chosen message asks for: map each to text that may use this message's own $fields.
2135
+ const mapField = document.createElement('div'); mapField.className = 'field';
2136
+ let chosenFields = [];
2137
+ const renderMapping = () => {
2138
+ mapField.hidden = !chosenFields.length;
2139
+ mapField.replaceChildren(Object.assign(document.createElement('span'), { className: 'lbl', textContent: `Fill in “${chosen}”` }), ...chosenFields.map((f) => {
2140
+ const inp = textInput(args[f] ?? '', 'e.g. $name, or fixed text', 60);
2141
+ inp.addEventListener('input', () => { args[f] = inp.value; });
2142
+ const row = Object.assign(document.createElement('div'), { className: 'maprow' });
2143
+ const lab = Object.assign(document.createElement('label'), { htmlFor: inp.id, textContent: f });
2144
+ row.append(lab, inp);
2145
+ return row;
2146
+ }));
2147
+ };
2148
+ // Run the selector against the stage as it is now, and offer the messages those elements can send.
2149
+ const runSelector = () => {
2150
+ const sel = from.read(false);
2151
+ const ids = sel.kind === 'query' && !filterActive({ q: sel.q, tags: sel.tags, icons: sel.icons }) ? [] : resolveSelector(app.scene, sel, link);
2152
+ const ix = indexOf(app.scene);
2153
+ const names = ids.filter((x) => ix.elements.has(x)).map((x) => ix.elements.get(x).label || 'unnamed');
2154
+ const opts = sendableMessages(app.scene, ids);
2155
+ const all = chosen && !opts.some((o) => o.label === chosen) ? [{ label: chosen, senders: [] }, ...opts] : opts;
2156
+ picks.replaceChildren(...all.map((o) => {
2157
+ const b = document.createElement('button');
2158
+ b.type = 'button'; b.className = 'fchip';
2159
+ b.setAttribute('aria-pressed', String(o.label === chosen));
2160
+ b.append(Object.assign(document.createElement('b'), { textContent: o.label }), Object.assign(document.createElement('span'), { className: 'from', textContent: o.senders.length ? ` from ${o.senders.join(', ')}` : ' not available from these elements now' }));
2161
+ b.addEventListener('click', () => { chosen = o.label; runSelector(); });
2162
+ return b;
2163
+ }));
2164
+ found.replaceChildren();
2165
+ if (!names.length) found.append('No elements match yet.');
2166
+ else {
2167
+ found.append(`${names.length} match: `, Object.assign(document.createElement('b'), { textContent: names.slice(0, 8).join(', ') + (names.length > 8 ? ` +${names.length - 8}` : '') }), '. ');
2168
+ found.append(opts.length ? `${opts.length} message${opts.length === 1 ? '' : 's'} available.` : 'None of them can send a message yet: add messages to their outgoing connections first.');
2169
+ }
2170
+ pickField.hidden = all.length === 0;
2171
+ chosenFields = all.find((o) => o.label === chosen)?.fields ?? Object.keys(args);
2172
+ renderMapping();
2173
+ };
2174
+ find.addEventListener('click', runSelector);
2175
+ from.onChange(runSelector);
2176
+ el.append(from.el, find, found, pickField, mapField);
2177
+ runSelector();
2178
+ return { el, focus: null, read: () => {
2179
+ const sel = from.read();
2180
+ if (!chosen) throw new UserError('Pick which message the senders should send. Use Find senders to see what they can send.');
2181
+ const mapped = Object.fromEntries(chosenFields.filter((f) => (args[f] ?? '').trim()).map((f) => [f, args[f].trim()]));
2182
+ return { kind: 'send', from: sel, message: chosen, ...(Object.keys(mapped).length ? { args: mapped } : {}) };
2183
+ } };
2184
+ }
2185
+ default: throw new Error(`bug: no editor for action ${a.kind}`);
2186
+ }
2187
+ }
2188
+
2189
+ // ---- message editor: label + reorderable step list; each step edits in a dialog ----
2190
+ // The message's input fields: chips over the hidden #mFields list (which the rest of the editor reads).
2191
+ // Fields a step uses are added automatically and can't be removed while a step uses them.
2192
+ const draftFields = () => { try { return parseFields($('mFields').value); } catch { return []; } };
2193
+ function renderFieldChips() {
2194
+ const d = app.msgDraft;
2195
+ if (!d) return;
2196
+ const used = new Set(d.actions.flatMap((a) => actionTexts(a).filter(Boolean).flatMap(fieldRefs)));
2197
+ const fields = [...new Set([...draftFields(), ...used])];
2198
+ $('mFields').value = fields.join(', ');
2199
+ renderTagChips($('mFieldTags'), fields.map((f) => `$${f}`), (t) => { $('mFields').value = draftFields().filter((f) => `$${f}` !== t).join(', '); renderFieldChips(); }, new Set([...used].map((f) => `$${f}`)));
2200
+ }
2201
+ /** Turn the half-typed field into a chip; false (after reporting) when it can't be a field. */
2202
+ function commitFieldInput() {
2203
+ const raw = $('mFieldIn').value.trim();
2204
+ if (!raw) return true;
2205
+ try { $('mFields').value = parseFields([...draftFields(), ...raw.split(/[\s,]+/)].join(', ')).join(', '); } catch (err) { showError(err); return false; }
2206
+ $('mFieldIn').value = '';
2207
+ renderFieldChips();
2208
+ return true;
2209
+ }
2210
+ $('mFieldIn').addEventListener('keydown', (ev) => { if (ev.key === 'Enter' || ev.key === ',') { ev.preventDefault(); commitFieldInput(); } });
2211
+
2212
+ function renderSteps() {
2213
+ const d = app.msgDraft;
2214
+ const list = $('mActs');
2215
+ if (!d) { list.replaceChildren(); return; }
2216
+ renderFieldChips();
2217
+ list.replaceChildren(...d.actions.map((a, i) => {
2218
+ const li = document.createElement('li');
2219
+ li.dataset.i = String(i);
2220
+ const handle = Object.assign(document.createElement('button'), { type: 'button', className: 'grip' });
2221
+ handle.setAttribute('aria-label', `Step ${i + 1}: drag, or use the up and down arrow keys, to reorder`);
2222
+ handle.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="9" cy="6" r="1.6"/><circle cx="15" cy="6" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="18" r="1.6"/><circle cx="15" cy="18" r="1.6"/></svg>';
2223
+ handle.addEventListener('pointerdown', (ev) => startStepDrag(ev, li));
2224
+ handle.addEventListener('keydown', (ev) => {
2225
+ if (ev.key !== 'ArrowUp' && ev.key !== 'ArrowDown') return;
2226
+ ev.preventDefault();
2227
+ const j = i + (ev.key === 'ArrowUp' ? -1 : 1);
2228
+ if (j < 0 || j >= d.actions.length) return;
2229
+ moveStep(i, j);
2230
+ $('mActs').children[j].querySelector('.grip').focus();
2231
+ });
2232
+ const open = Object.assign(document.createElement('button'), { type: 'button', className: 'sopen' });
2233
+ open.innerHTML = glyph(a.kind);
2234
+ open.append(Object.assign(document.createElement('span'), { textContent: describeAction(a, app.scene) }));
2235
+ open.setAttribute('aria-label', `Edit step ${i + 1}: ${describeAction(a, app.scene)}`);
2236
+ open.addEventListener('click', () => openStepDialog(i));
2237
+ const del = Object.assign(document.createElement('button'), { type: 'button', className: 'sdel', textContent: '✕' });
2238
+ del.setAttribute('aria-label', `Delete step ${i + 1}`);
2239
+ del.disabled = d.actions.length === 1;
2240
+ del.title = d.actions.length === 1 ? 'A message needs at least one step' : 'Delete step';
2241
+ del.addEventListener('click', () => { app.msgDraft = { ...d, actions: d.actions.filter((_, k) => k !== i) }; renderSteps(); });
2242
+ li.append(handle, open, del);
2243
+ return li;
2244
+ }));
2245
+ $('mActAdd').disabled = d.actions.length >= LIMIT_ACTIONS;
2246
+ }
2247
+ function moveStep(i, j) {
2248
+ const d = app.msgDraft;
2249
+ const actions = [...d.actions];
2250
+ const [x] = actions.splice(i, 1);
2251
+ actions.splice(j, 0, x);
2252
+ app.msgDraft = { ...d, actions };
2253
+ renderSteps();
2254
+ }
2255
+ /** Pointer drag on a step's grip: the row follows the pointer and the list reorders where it is dropped. */
2256
+ /** Drag a view chip sideways to reorder; a press that moves less than a few pixels stays a click. */
2257
+ function startViewDrag(ev, chip, id) {
2258
+ if (ev.button !== 0 || app.mode !== 'edit') return;
2259
+ const list = $('chips');
2260
+ const from = Number(chip.dataset.i);
2261
+ const rows = [...list.querySelectorAll('.chip')];
2262
+ const mids = rows.map((r) => { const b = r.getBoundingClientRect(); return b.left + b.width / 2; });
2263
+ const x0 = ev.clientX;
2264
+ let to = from, dragging = false;
2265
+ const move = (e) => {
2266
+ if (!dragging) {
2267
+ if (Math.abs(e.clientX - x0) < 5) return;
2268
+ dragging = true; chip.dataset.dragged = '1';
2269
+ chip.classList.add('dragging'); chip.setPointerCapture(e.pointerId);
2270
+ }
2271
+ chip.style.transform = `translateX(${e.clientX - x0}px)`;
2272
+ to = mids.filter((m, k) => k !== from && e.clientX > m).length;
2273
+ rows.forEach((r, k) => r.classList.toggle('drop-before', to !== from && k !== from && k === (to >= from ? to + 1 : to)));
2274
+ list.classList.toggle('drop-end', to === rows.length - 1 && to !== from);
2275
+ };
2276
+ const up = () => {
2277
+ chip.removeEventListener('pointermove', move);
2278
+ chip.removeEventListener('pointerup', up);
2279
+ chip.removeEventListener('pointercancel', up);
2280
+ if (!dragging) return;
2281
+ chip.classList.remove('dragging'); chip.style.transform = '';
2282
+ rows.forEach((r) => r.classList.remove('drop-before'));
2283
+ list.classList.remove('drop-end');
2284
+ setTimeout(() => delete chip.dataset.dragged, 0); // swallow the click that ends the drag
2285
+ if (to !== from) storeWrite('reorder', () => app.store.moveViewTo(id, to));
2286
+ };
2287
+ chip.addEventListener('pointermove', move);
2288
+ chip.addEventListener('pointerup', up);
2289
+ chip.addEventListener('pointercancel', up);
2290
+ }
2291
+
2292
+ function startStepDrag(ev, li) {
2293
+ ev.preventDefault();
2294
+ const list = $('mActs');
2295
+ const from = Number(li.dataset.i);
2296
+ const rows = [...list.children];
2297
+ const mids = rows.map((r) => { const b = r.getBoundingClientRect(); return b.top + b.height / 2; });
2298
+ const y0 = ev.clientY;
2299
+ let to = from;
2300
+ li.classList.add('dragging');
2301
+ li.setPointerCapture(ev.pointerId);
2302
+ const move = (e) => {
2303
+ li.style.transform = `translateY(${e.clientY - y0}px)`;
2304
+ to = mids.filter((m, k) => k !== from && e.clientY > m).length;
2305
+ rows.forEach((r, k) => r.classList.toggle('drop-before', k !== from && k === (to >= from ? to + 1 : to)));
2306
+ list.classList.toggle('drop-end', to === rows.length - 1 && to !== from);
2307
+ };
2308
+ const up = () => {
2309
+ li.removeEventListener('pointermove', move);
2310
+ li.removeEventListener('pointerup', up);
2311
+ li.removeEventListener('pointercancel', up);
2312
+ li.classList.remove('dragging'); li.style.transform = '';
2313
+ rows.forEach((r) => r.classList.remove('drop-before'));
2314
+ list.classList.remove('drop-end');
2315
+ if (to !== from) moveStep(from, to);
2316
+ };
2317
+ li.addEventListener('pointermove', move);
2318
+ li.addEventListener('pointerup', up);
2319
+ li.addEventListener('pointercancel', up);
2320
+ }
2321
+
2322
+ let stepEdit = null; // { index | null (new), kind, body, original, quick }
2323
+ /** quick: a brand-new message in one go: its label sits at the top and Save adds the message too. */
2324
+ function openStepDialog(index, quick = false) {
2325
+ const d = app.msgDraft;
2326
+ if (!d) throw new Error('bug: step dialog without a message draft');
2327
+ const link = indexOf(app.scene).links.get(d.linkId);
2328
+ const original = index === null ? DEFAULT_ACTION.add() : d.actions[index];
2329
+ stepEdit = { index, original, kind: original.kind, body: null, quick, saved: false };
2330
+ $('stepDlgTitle').textContent = quick ? 'New message' : index === null ? `Step ${d.actions.length + 1}` : `Step ${index + 1}`;
2331
+ $('stepMsgField').hidden = !quick;
2332
+ $('stepMsgLabel').value = '';
2333
+ $('stepSave').textContent = quick ? 'Save' : 'Save step';
2334
+ stepProblem(null); syncStepSave();
2335
+ const kinds = $('stepKinds');
2336
+ kinds.replaceChildren(...ACTION_KINDS.map(([k, name]) => {
2337
+ const b = document.createElement('button');
2338
+ b.type = 'button'; b.dataset.kind = k;
2339
+ b.innerHTML = glyph(k);
2340
+ b.append(Object.assign(document.createElement('span'), { textContent: name }));
2341
+ b.addEventListener('click', () => setStepKind(k, link));
2342
+ return b;
2343
+ }));
2344
+ setStepKind(original.kind, link);
2345
+ $('stepDlg').showModal();
2346
+ (quick ? $('stepMsgLabel') : stepEdit.body.focus ?? kinds.querySelector('[aria-pressed="true"]')).focus();
2347
+ }
2348
+ function setStepKind(kind, link) {
2349
+ stepEdit.kind = kind;
2350
+ for (const b of $('stepKinds').children) b.setAttribute('aria-pressed', String(b.dataset.kind === kind));
2351
+ const seed = kind === stepEdit.original.kind ? stepEdit.original : DEFAULT_ACTION[kind]();
2352
+ stepEdit.body = actionBody(seed, link);
2353
+ let fields = [];
2354
+ try { fields = parseFields($('mFields').value); } catch { /* reported when the message is saved */ }
2355
+ const hint = fields.length && ['add', 'connect', 'send'].includes(kind)
2356
+ ? [Object.assign(document.createElement('p'), { className: 'note', textContent: `This message's fields: ${fields.map((f) => `$${f}`).join(', ')}. Use them in the text boxes and tags below.` })] : [];
2357
+ $('stepBody').replaceChildren(...hint, stepEdit.body.el);
2358
+ }
2359
+ // Problems are shown in the dialog, not in the app bar behind it.
2360
+ const stepProblem = (err) => { $('stepErr').hidden = !err; $('stepErr').textContent = err ? err.message ?? String(err) : ''; };
2361
+ const needsLabel = () => !!stepEdit?.quick && !$('stepMsgLabel').value.trim();
2362
+ function syncStepSave() {
2363
+ $('stepSave').setAttribute('aria-disabled', String(needsLabel()));
2364
+ if (!needsLabel()) $('stepMsgErr').hidden = true;
2365
+ }
2366
+ $('stepMsgLabel').addEventListener('input', syncStepSave);
2367
+ $('stepForm').addEventListener('input', () => stepProblem(null));
2368
+ $('stepForm').addEventListener('submit', (ev) => {
2369
+ ev.preventDefault();
2370
+ const quick = stepEdit.quick;
2371
+ if (needsLabel()) { $('stepMsgErr').hidden = false; $('stepMsgLabel').focus(); return; }
2372
+ let action;
2373
+ try { action = parseOrThrow(ActionSchema, stepEdit.body.read(), 'Step'); } catch (err) { stepProblem(err); return; }
2374
+ const d = app.msgDraft;
2375
+ const actions = stepEdit.index === null ? [...d.actions, action] : d.actions.map((x, k) => (k === stepEdit.index ? action : x));
2376
+ app.msgDraft = { ...d, actions };
2377
+ stepEdit.saved = true;
2378
+ $('stepDlg').close();
2379
+ renderSteps();
2380
+ if (quick) { $('mLabel').value = $('stepMsgLabel').value.trim(); $('msgEd').requestSubmit(); } // save the message too (fields fill in from the step)
2381
+ });
2382
+ $('stepCancel').addEventListener('click', () => $('stepDlg').close());
2383
+ $('stepClose').addEventListener('click', () => $('stepDlg').close());
2384
+
2385
+ // ---------- open dialog ----------
2386
+ function openError(msg) { $('openErr').textContent = msg; $('openErr').hidden = !msg; }
2387
+ async function openFrom(load, handle = null) {
2388
+ openError('');
2389
+ try { if (openDeck(await load())) { setFileHandle(handle); $('openDlg').close(); } }
2390
+ catch (err) { openError(err?.message ?? String(err)); }
2391
+ }
2392
+ const openFileDeck = (file, handle = null) => openFrom(async () => {
2393
+ if (!file) throw new Error('Drop or choose a .json deck file.');
2394
+ let json;
2395
+ try { json = JSON.parse(await file.text()); } catch { throw new Error(`"${file.name}" is not JSON.`); }
2396
+ return parseDeck(json, `"${file.name}"`);
2397
+ }, handle);
2398
+ // Choose file… goes through the picker where it exists, so the deck can be saved back to the same file.
2399
+ if ('showOpenFilePicker' in window) $('openFileLbl').addEventListener('click', async (ev) => {
2400
+ ev.preventDefault();
2401
+ let h;
2402
+ try { [h] = await showOpenFilePicker({ types: JSON_TYPES }); } catch (err) { if (err?.name !== 'AbortError') openError(err.message); return; }
2403
+ openFileDeck(await h.getFile(), h);
2404
+ });
2405
+ $('saveAsBtn').addEventListener('click', () => downloadDeck(true));
2406
+ $('openBtn').addEventListener('click', () => { openError(''); $('openDlg').showModal(); });
2407
+ $('downloadBtn').addEventListener('click', () => downloadDeck());
2408
+ $('newBtn').addEventListener('click', () => { if (openDeck({ ...EMPTY_DECK, scene: { ...EMPTY_DECK.scene, bubbles: [], elements: [], links: [] } })) { setFileHandle(null); app.downloadName = 'deck.json'; } });
2409
+ // Popovers sit in the top layer, so place the menu under its button; any click inside closes it.
2410
+ $('fileMenu').addEventListener('toggle', (ev) => {
2411
+ if (ev.newState !== 'open') return;
2412
+ const r = $('menuBtn').getBoundingClientRect();
2413
+ Object.assign($('fileMenu').style, { top: `${r.bottom + 6}px`, left: `${r.left}px` });
2414
+ prepareLink();
2415
+ });
2416
+ // Copy link: the whole deck in #deck=, so anyone can open it without a hosted deck.json. Built when the menu opens,
2417
+ // so the click can write the clipboard straight away and the item can be disabled when the deck is too big.
2418
+ let deckLink = null;
2419
+ async function prepareLink() {
2420
+ deckLink = null; $('linkBtn').disabled = $('linkPresentBtn').disabled = true; $('linkTxt').textContent = 'Copy edit link';
2421
+ if (app.mode === 'edit') saveWorking();
2422
+ const hash = `#deck=${await encodeDeckLink(app.store.get())}`;
2423
+ const ok = location.origin.length + location.pathname.length + '?present'.length + hash.length <= LIMIT_LINK;
2424
+ deckLink = ok ? hash : null; $('linkBtn').disabled = $('linkPresentBtn').disabled = !ok;
2425
+ if (!ok) $('linkTxt').textContent = `Too big for a link (${Math.ceil(hash.length / 1000)}k) · Download instead`;
2426
+ }
2427
+ /** ?present opens the linked deck straight into present mode (boot handles it like any ?present link). */
2428
+ async function copyDeckLink(present) {
2429
+ if (!deckLink) return;
2430
+ const url = `${location.origin}${location.pathname}${present ? '?present' : ''}${deckLink}`;
2431
+ try { await navigator.clipboard.writeText(url); } catch { prompt('Copy this link:', url); return; }
2432
+ $('status').textContent = present ? 'Present link copied' : 'Edit link copied';
2433
+ setTimeout(setStatus, 2000);
2434
+ }
2435
+ $('linkBtn').addEventListener('click', () => copyDeckLink(false));
2436
+ $('linkPresentBtn').addEventListener('click', () => copyDeckLink(true));
2437
+ $('fileMenu').addEventListener('click', (ev) => { if (ev.target.closest('button')) $('fileMenu').hidePopover(); });
2438
+ $('openClose').addEventListener('click', () => $('openDlg').close());
2439
+ $('openFile').addEventListener('change', (ev) => { openFileDeck(ev.target.files[0]); ev.target.value = ''; });
2440
+ $('openForm').addEventListener('submit', async (ev) => {
2441
+ ev.preventDefault();
2442
+ const u = $('openUrl').value.trim();
2443
+ if (!u) return;
2444
+ $('openGo').disabled = true;
2445
+ await openFrom(async () => (await fetchDeck(u)).deck);
2446
+ $('openGo').disabled = false;
2447
+ });
2448
+ const drop = $('openDrop');
2449
+ drop.addEventListener('dragover', (ev) => { ev.preventDefault(); drop.classList.add('on'); });
2450
+ drop.addEventListener('dragleave', () => drop.classList.remove('on'));
2451
+ drop.addEventListener('drop', async (ev) => {
2452
+ ev.preventDefault(); drop.classList.remove('on');
2453
+ const file = ev.dataTransfer?.files[0];
2454
+ // The handle must be requested synchronously inside the drop event.
2455
+ const pending = ev.dataTransfer?.items[0]?.getAsFileSystemHandle?.();
2456
+ const h = await pending?.catch(() => null);
2457
+ openFileDeck(file, h?.kind === 'file' ? h : null);
2458
+ });
2459
+ $('stepDlg').addEventListener('close', () => {
2460
+ const dropDraft = stepEdit?.quick && !stepEdit.saved; // cancelled a new message: nothing to keep
2461
+ stepEdit = null; $('stepBody').replaceChildren();
2462
+ if (dropDraft) closeMessageEditor();
2463
+ });
2464
+ $('mActAdd').addEventListener('click', () => openStepDialog(null));
2465
+
2466
+ function openMessageEditor(linkId, messageId) {
2467
+ const l = indexOf(app.scene).links.get(linkId);
2468
+ if (!l) throw new Error(`bug: editor for missing connection ${linkId}`);
2469
+ const existing = messageId === null ? null : l.messages.find((m) => m.id === messageId);
2470
+ if (messageId !== null && !existing) throw new Error(`bug: editor for missing message ${messageId}`);
2471
+ if (!existing && l.messages.length >= LIMIT_MESSAGES) { showError(`A connection holds up to ${LIMIT_MESSAGES} messages.`); return; }
2472
+ app.msgDraft = { linkId, messageId, actions: existing ? existing.actions : [] };
2473
+ $('msgEdTitle').textContent = existing ? `Edit “${existing.label}”` : 'New message';
2474
+ $('mLabel').value = existing?.label ?? '';
2475
+ $('mFields').value = (existing?.fields ?? []).join(', ');
2476
+ $('mFieldIn').value = '';
2477
+ renderUI();
2478
+ if (existing) $('mLabel').focus();
2479
+ else openStepDialog(null, true);
2480
+ }
2481
+ function closeMessageEditor() { app.msgDraft = null; renderUI(); }
2482
+
2483
+ $('msgEd').addEventListener('submit', (ev) => {
2484
+ ev.preventDefault();
2485
+ const d = app.msgDraft;
2486
+ if (!d) throw new Error('bug: message form submitted with no draft');
2487
+ let msg;
2488
+ try {
2489
+ const label = $('mLabel').value.trim();
2490
+ if (!label) throw new UserError('Give the message a label; it appears on the send button and on the packet.');
2491
+ if (!d.actions.length) throw new UserError('Add at least one step.');
2492
+ if (!commitFieldInput()) return;
2493
+ const fields = parseFields($('mFields').value);
2494
+ d.actions.forEach((a, i) => {
2495
+ const unknown = [...new Set(actionTexts(a).flatMap(fieldRefs))].filter((f) => !fields.includes(f));
2496
+ if (unknown.length) throw new UserError(`Step ${i + 1} uses ${unknown.map((f) => `$${f}`).join(', ')}, which ${unknown.length > 1 ? 'are not fields' : 'is not a field'} of this message. Add ${unknown.length > 1 ? 'them' : 'it'} to Input fields, or write $$ for a plain $.`);
2497
+ });
2498
+ msg = parseOrThrow(MessageSchema, { id: d.messageId ?? newId('msg'), label, ...(fields.length ? { fields } : {}), actions: d.actions }, 'Message');
2499
+ } catch (err) { showError(err); return; }
2500
+ const l = indexOf(app.scene).links.get(d.linkId);
2501
+ const messages = d.messageId === null ? [...l.messages, msg] : l.messages.map((m) => (m.id === d.messageId ? msg : m));
2502
+ if (dispatch({ type: 'updateLink', id: d.linkId, patch: { messages } })) closeMessageEditor();
2503
+ });
2504
+ $('mCancel').addEventListener('click', closeMessageEditor);
2505
+ $('lMsgAdd').addEventListener('click', () => openMessageEditor(selectedLinkId(), null));
2506
+
2507
+ let msgDeleteArmed = null;
2508
+ function renderMessages() {
2509
+ // Connection panel: its messages, and the editor if it belongs to this connection.
2510
+ const sel = app.selection;
2511
+ const l = sel?.kind === 'link' ? indexOf(app.scene).links.get(sel.id) : null;
2512
+ if (app.msgDraft && (!l || app.msgDraft.linkId !== l.id)) app.msgDraft = null;
2513
+ $('msgEd').hidden = !app.msgDraft;
2514
+ renderSteps();
2515
+ $('lMsgAdd').hidden = !!app.msgDraft;
2516
+ if (l) {
2517
+ const ix = indexOf(app.scene);
2518
+ const from = ix.elements.get(l.from), to = ix.elements.get(l.to);
2519
+ $('lMsgs').replaceChildren(...l.messages.map((m) => {
2520
+ const li = document.createElement('li');
2521
+ const txt = document.createElement('div'); txt.className = 'mtxt';
2522
+ txt.append(Object.assign(document.createElement('b'), { textContent: m.label }), Object.assign(document.createElement('span'), { textContent: `${describeMessage(m, app.scene)} · ${from.label || 'start'} → ${to.label || 'end'}` }));
2523
+ const send = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Send' });
2524
+ send.addEventListener('click', () => requestSend(l.id, m.id));
2525
+ const edit = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Edit' });
2526
+ edit.addEventListener('click', () => openMessageEditor(l.id, m.id));
2527
+ const armed = msgDeleteArmed === m.id;
2528
+ const del = Object.assign(document.createElement('button'), { type: 'button', textContent: armed ? 'Confirm' : 'Delete', className: armed ? 'armed' : '' });
2529
+ del.setAttribute('aria-label', armed ? `Confirm deleting message ${m.label}` : `Delete message ${m.label}`);
2530
+ del.addEventListener('click', () => {
2531
+ if (msgDeleteArmed !== m.id) {
2532
+ msgDeleteArmed = m.id; renderMessages();
2533
+ setTimeout(() => { if (msgDeleteArmed === m.id) { msgDeleteArmed = null; renderMessages(); } }, 3000);
2534
+ return;
2535
+ }
2536
+ msgDeleteArmed = null;
2537
+ dispatch({ type: 'updateLink', id: l.id, patch: { messages: l.messages.filter((x) => x.id !== m.id) } });
2538
+ });
2539
+ li.append(txt, send, edit, del);
2540
+ return li;
2541
+ }));
2542
+ }
2543
+
2544
+ // Element panel: chip colour.
2545
+ if (sel?.kind === 'element') {
2546
+ const e = indexOf(app.scene).elements.get(sel.id);
2547
+ if (e) for (const b of $('eHues').children) b.setAttribute('aria-pressed', String(b.id === 'eFill' ? !!e.fill : (b.dataset.hue || null) === e.hue));
2548
+ if (e) for (const b of $('eText').children) b.setAttribute('aria-pressed', String(b.id === 'eStrike' ? !!e.strike : (b.dataset.hue || null) === (e.textHue ?? null)));
2549
+ }
2550
+
2551
+ // Message bar for the selected element (edit and present).
2552
+ const avail = availableMessages();
2553
+ const bar = $('msgbar');
2554
+ const wasHidden = bar.hidden;
2555
+ bar.hidden = avail.length === 0;
2556
+ if (!avail.length) return;
2557
+ const src = indexOf(app.scene).elements.get(app.selection.id);
2558
+ const head = document.createElement('span');
2559
+ head.className = 'from';
2560
+ head.append('From ', Object.assign(document.createElement('b'), { textContent: src.label || 'this element' }));
2561
+ bar.replaceChildren(head, ...avail.map(({ link, msg, target }, i) => {
2562
+ const b = document.createElement('button');
2563
+ b.type = 'button'; b.className = 'mbtn';
2564
+ b.title = `${describeMessage(msg, app.scene)}${i < 9 ? ` (key ${i + 1})` : ''}`;
2565
+ if (i < 9) b.append(Object.assign(document.createElement('span'), { className: 'k', textContent: String(i + 1) }));
2566
+ b.insertAdjacentHTML('beforeend', glyph(msg.actions[0].kind));
2567
+ b.append(Object.assign(document.createElement('span'), { textContent: msg.label }), Object.assign(document.createElement('span'), { className: 'to', textContent: `→ ${target.label || 'target'}` }));
2568
+ b.addEventListener('click', () => requestSend(link.id, msg.id));
2569
+ return b;
2570
+ }));
2571
+ if (wasHidden) { bar.style.animation = 'none'; void bar.offsetWidth; bar.style.animation = ''; }
2572
+ }
2573
+
2574
+ (function buildElementHues() {
2575
+ const box = $('eHues');
2576
+ const auto = document.createElement('button');
2577
+ auto.type = 'button'; auto.className = 'swatch auto'; auto.dataset.hue = ''; auto.setAttribute('aria-label', 'Same as the bubble'); auto.title = 'Same as the bubble';
2578
+ auto.addEventListener('click', () => app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch: { hue: null } }));
2579
+ const fill = document.createElement('button');
2580
+ fill.type = 'button'; fill.className = 'btn'; fill.id = 'eFill'; fill.textContent = 'Fill'; fill.title = 'Fill the chip with its colour';
2581
+ fill.addEventListener('click', () => app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch: { fill: !indexOf(app.scene).elements.get(app.selection.id)?.fill } }));
2582
+ box.append(fill, auto);
2583
+ for (const h of HUES) {
2584
+ const b = document.createElement('button');
2585
+ b.type = 'button'; b.className = 'swatch'; b.style.setProperty('--c', `var(--cell-${h})`); b.dataset.hue = h; b.setAttribute('aria-label', h);
2586
+ b.addEventListener('click', () => app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch: { hue: h } }));
2587
+ box.append(b);
2588
+ }
2589
+ })();
2590
+
2591
+ (function buildLabelStyle() {
2592
+ const box = $('eText');
2593
+ const set = (patch) => app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch });
2594
+ const strike = document.createElement('button');
2595
+ strike.type = 'button'; strike.className = 'btn icon'; strike.id = 'eStrike'; strike.title = 'Strikethrough'; strike.setAttribute('aria-label', 'Strikethrough');
2596
+ strike.innerHTML = '<s aria-hidden="true">S</s>';
2597
+ strike.addEventListener('click', () => set({ strike: !indexOf(app.scene).elements.get(app.selection.id)?.strike }));
2598
+ const auto = document.createElement('button');
2599
+ auto.type = 'button'; auto.className = 'swatch auto'; auto.dataset.hue = ''; auto.setAttribute('aria-label', 'Default text colour'); auto.title = 'Default text colour';
2600
+ auto.addEventListener('click', () => set({ textHue: null }));
2601
+ box.append(strike, auto);
2602
+ for (const h of HUES) {
2603
+ const b = document.createElement('button');
2604
+ b.type = 'button'; b.className = 'swatch'; b.style.setProperty('--c', `var(--cell-${h})`); b.dataset.hue = h; b.setAttribute('aria-label', `${h} text`); b.title = `${h} text`;
2605
+ b.addEventListener('click', () => set({ textHue: h }));
2606
+ box.append(b);
2607
+ }
2608
+ })();
2609
+
2610
+ // ---------- background ----------
2611
+ function renderStageControls() {
2612
+ const st = app.scene.stage;
2613
+ syncRich('stDesc', `stage:${app.activeViewId}`, st);
2614
+ $('stGrid').checked = st.grid;
2615
+ $('stOpacity').disabled = st.color === null;
2616
+ if (document.activeElement !== $('stColor')) $('stColor').value = st.color ?? themeBg();
2617
+ if (document.activeElement !== $('stOpacity')) $('stOpacity').value = String(Math.round(st.opacity * 100));
2618
+ $('stOpacityOut').textContent = st.color === null ? 'theme' : `${Math.round(st.opacity * 100)}%`;
2619
+ }
2620
+ $('stGrid').addEventListener('change', (ev) => dispatch({ type: 'setStage', patch: { grid: ev.target.checked } }));
2621
+ // The picker shows the theme background when the stage has no colour; picking that colour back means none again.
2622
+ const themeBg = () => getComputedStyle(document.documentElement).getPropertyValue('--bg').trim().toLowerCase();
2623
+ $('stColor').addEventListener('input', (ev) => { const c = ev.target.value.toLowerCase(); dispatch({ type: 'setStage', patch: { color: c === themeBg() ? null : c } }); });
2624
+ $('stOpacity').addEventListener('input', (ev) => dispatch({ type: 'setStage', patch: { opacity: Number(ev.target.value) / 100 } }));
2625
+
2626
+ // Overlay ink for light and dark backdrops; the same values as the page's light and dark theme tokens.
2627
+ const INK = Object.freeze({
2628
+ onLight: { fg: '#17202a', muted: '#566170', surface: '#ffffff', accent: '#2550b8' },
2629
+ onDark: { fg: '#e6ecf2', muted: '#98a5b3', surface: '#151c24', accent: '#7fa5ff' },
2630
+ cellsOnLight: { teal: '#0e9f8e', violet: '#6d4df2', amber: '#d98a0b', rose: '#db3a62', blue: '#2672e8', green: '#2f9a41', orange: '#e8590c', pink: '#d6409f', cyan: '#0b8fb8', lime: '#5f9a0a', slate: '#5c6b7a' },
2631
+ cellsOnDark: { teal: '#2cd3bd', violet: '#a48dff', amber: '#f4b23f', rose: '#ff6e92', blue: '#5e9dff', green: '#5fcb6c', orange: '#ff8a4c', pink: '#f783c7', cyan: '#3bc9ee', lime: '#a9e34b', slate: '#a3b1bf' },
2632
+ });
2633
+
2634
+ // In present mode on a custom-coloured slide, the floating controls (notes, HUD, view strip, share/exit, messages)
2635
+ // take the slide's backdrop and matching ink instead of the theme's panel colours.
2636
+ let chromeKey = '';
2637
+ function paintPresentChrome(look) {
2638
+ const vars = look ? (() => {
2639
+ const rgb = `rgb(${look.bg.map((v) => Math.round(v * 255)).join(' ')})`;
2640
+ return { '--surface': rgb, '--surface-2': `color-mix(in srgb, ${rgb} 88%, ${look.ink.fg})`, '--fg': look.ink.fg, '--muted': look.ink.muted, '--accent': look.ink.accent, '--line': `color-mix(in srgb, ${look.ink.fg} 22%, ${rgb})` };
2641
+ })() : {};
2642
+ const key = JSON.stringify(vars);
2643
+ if (key === chromeKey) return;
2644
+ chromeKey = key;
2645
+ const el = $('stage');
2646
+ for (const k of ['--surface', '--surface-2', '--fg', '--muted', '--accent', '--line']) el.style.removeProperty(k);
2647
+ for (const [k, v] of Object.entries(vars)) el.style.setProperty(k, v);
2648
+ }
2649
+
2650
+ // Save button: "Save*" in primary style while the stage differs from the selected view. Runs every frame, so it
2651
+ // only re-compares when the scene, the view or the camera actually changed.
2652
+ // Orbiting bubbles' x/y are ignored: they sit on their ring, and freezing the scene on save rewrites them.
2653
+ const sceneSig = (scene) => JSON.stringify({ ...scene, bubbles: scene.bubbles.map((b) => (b.orbit ? { ...b, x: 0, y: 0 } : b)) });
2654
+ let saveMemo = [];
2655
+ function renderSaveState() {
2656
+ const active = app.mode === 'edit' ? app.views.find((v) => v.id === app.activeViewId) : null;
2657
+ const memo = [app.scene, active, app.cam.x, app.cam.y, app.cam.zoom];
2658
+ if (memo.every((v, i) => v === saveMemo[i])) return;
2659
+ saveMemo = memo;
2660
+ const cam = roundCam(app.cam), saved = active && roundCam(active.camera); // hand-written files may hold unrounded cameras
2661
+ const dirty = !!active && (cam.x !== saved.x || cam.y !== saved.y || cam.zoom !== saved.zoom || sceneSig(app.scene) !== sceneSig(presentedScene(app.views, active.id)));
2662
+ const b = $('vUpdate');
2663
+ b.textContent = dirty ? 'Save*' : 'Save';
2664
+ b.classList.toggle('primary', dirty);
2665
+ b.setAttribute('aria-label', dirty ? 'Save (unsaved changes)' : 'Save');
2666
+ $('vSave').classList.toggle('primary', !active); // one primary at a time: Save as new only leads when no view is selected
2667
+ }
2668
+
2669
+ // ---------- presenter views strip ----------
2670
+ function renderPresentStrip() {
2671
+ const on = app.mode === 'present' && app.views.length > 0;
2672
+ $('pstrip').hidden = !on;
2673
+ if (!on) return;
2674
+ $('pstrip').replaceChildren(...app.views.map((v, i) => {
2675
+ const b = document.createElement('button');
2676
+ b.type = 'button'; b.className = 'chip';
2677
+ b.setAttribute('aria-current', String(v.id === app.activeViewId));
2678
+ const n = document.createElement('span'); n.className = 'n'; n.textContent = String(i + 1);
2679
+ const t = document.createElement('span'); t.textContent = v.name;
2680
+ b.append(n, t);
2681
+ b.addEventListener('click', () => goToView(v.id));
2682
+ return b;
2683
+ }));
2684
+ $('pstrip').querySelector('[aria-current="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
2685
+ }
2686
+
2687
+ // Label and icon that new bubbles start with; set from the Add bubble drop-down. Only the icon is remembered in this browser.
2688
+ let newLook = (() => { try { const v = JSON.parse(localStorage.getItem('celldeck.newLook')); if (v && (v.icon === null || ICON_KEYS.includes(v.icon))) return { label: '', icon: v.icon }; } catch {} return { label: '', icon: null }; })();
2689
+ // Icon last picked in the element panel; Add element (⌘L) starts new elements with it.
2690
+ let lastIcon = null;
2691
+ const iconLabel = (icon) => icon ? ICONS[icon][0] : 'New';
2692
+ const newElementLook = () => ({ label: newLook.label.trim() || iconLabel(newLook.icon), icon: newLook.icon });
2693
+ function setNewLook(patch) {
2694
+ newLook = { ...newLook, ...patch };
2695
+ try { localStorage.setItem('celldeck.newLook', JSON.stringify({ icon: newLook.icon })); } catch {}
2696
+ for (const b of $('nbIcons').children) b.setAttribute('aria-pressed', String((b.dataset.icon || null) === newLook.icon));
2697
+ }
2698
+ (function buildAddMenu() {
2699
+ const grid = $('nbIcons');
2700
+ for (const k of [null, ...ICON_KEYS]) {
2701
+ const b = document.createElement('button');
2702
+ b.type = 'button'; b.dataset.icon = k ?? '';
2703
+ b.setAttribute('aria-label', k ? ICONS[k][0] : 'No icon'); b.title = k ? ICONS[k][0] : 'No icon';
2704
+ b.innerHTML = k ? iconSvg(k) : '<span class="none">None</span>';
2705
+ b.addEventListener('click', () => setNewLook({ icon: k }));
2706
+ grid.append(b);
2707
+ }
2708
+ $('nbLabel').value = newLook.label;
2709
+ $('nbLabel').addEventListener('input', (ev) => setNewLook({ label: ev.target.value }));
2710
+ $('nbLabel').addEventListener('keydown', (ev) => { if (ev.key === 'Enter') $('nbAdd').click(); });
2711
+ setNewLook({});
2712
+ $('addMenu').addEventListener('toggle', (ev) => {
2713
+ if (ev.newState !== 'open') return;
2714
+ const r = $('addBubble').getBoundingClientRect();
2715
+ Object.assign($('addMenu').style, { top: `${r.bottom + 6}px`, left: `${Math.max(16, Math.min(r.left, innerWidth - $('addMenu').offsetWidth - 16))}px` });
2716
+ $('nbLabel').focus(); $('nbLabel').select();
2717
+ });
2718
+ $('nbAdd').addEventListener('click', () => { $('addMenu').hidePopover(); $('addBubble').click(); });
2719
+ })();
2720
+
2721
+ function centreWorld() { return { x: app.cam.x, y: app.cam.y }; }
2722
+ function addBubbleAt(x, y) {
2723
+ const bid = newId('bb'), eid = newId('el');
2724
+ if (dispatch({ type: 'addBubble', bubble: { id: bid, title: '', hue: nextHue(app.scene), x: Math.round(x), y: Math.round(y), orbit: null, tags: [] }, elements: [{ id: eid, ...newElementLook(), imageId: null, tags: [], hue: null }] })) {
2725
+ app.selection = { kind: 'element', id: eid };
2726
+ renderUI();
2727
+ $('eLabel').focus(); $('eLabel').select();
2728
+ }
2729
+ }
2730
+ function addAround(hubId) {
2731
+ const th = gapAngle(app.scene, app.rt, hubId);
2732
+ const hub = app.rt.bubbles[hubId];
2733
+ const ring = ringRadius(app.scene, hubId);
2734
+ const bid = newId('bb'), eid = newId('el');
2735
+ if (dispatch({ type: 'addBubble', bubble: { id: bid, title: '', hue: nextHue(app.scene), x: Math.round(hub.x + ring * Math.cos(th)), y: Math.round(hub.y + ring * Math.sin(th)), orbit: { hubId }, tags: [] }, elements: [{ id: eid, ...newElementLook(), imageId: null, tags: [], hue: null }] })) {
2736
+ app.selection = { kind: 'element', id: eid };
2737
+ renderUI();
2738
+ $('eLabel').focus(); $('eLabel').select();
2739
+ }
2740
+ }
2741
+
2742
+ /** Nearest spot to (x, y), spiralling out, where a one-element bubble clears every bubble on the stage. */
2743
+ function freeSpot(x, y) {
2744
+ const r = slotLayout(1).R, live = Object.values(app.rt.bubbles).filter((b) => !b.dying);
2745
+ // ponytail: O(tries × bubbles) spiral scan; fine for the bubble limit.
2746
+ for (let i = 0; i < 2000; i++) {
2747
+ const d = 12 * Math.sqrt(i), th = i * 2.39996; // golden-angle spiral
2748
+ const p = { x: x + d * Math.cos(th), y: y + d * Math.sin(th) };
2749
+ if (live.every((b) => Math.hypot(p.x - b.x, p.y - b.y) >= bubbleRadius(app.scene, b.id) + r + 24)) return p; // target radius: b.r may still be growing
2750
+ }
2751
+ return { x, y };
2752
+ }
2753
+ $('addBubble').addEventListener('click', () => { const c = centreWorld(), p = freeSpot(c.x, c.y); addBubbleAt(p.x, p.y); });
2754
+ // Inspector drawer: hide it to give the stage the room (remembered per browser). The stage canvas follows via its ResizeObserver.
2755
+ function setInspector(on) {
2756
+ $('app').classList.toggle('insp-off', !on);
2757
+ $('inspToggle').setAttribute('aria-pressed', String(on));
2758
+ $('inspToggle').ariaLabel = $('inspToggle').title = $('inspHide').ariaLabel = $('inspHide').title = on ? 'Hide inspector (⌘.)' : 'Show inspector (⌘.)';
2759
+ $('inspHide').setAttribute('aria-expanded', String(on));
2760
+ try { localStorage.setItem('celldeck.insp', on ? 'on' : 'off'); } catch {}
2761
+ }
2762
+ setInspector((() => { try { return localStorage.getItem('celldeck.insp') !== 'off'; } catch { return true; } })());
2763
+ $('inspHide').addEventListener('click', () => setInspector($('app').classList.contains('insp-off')));
2764
+ $('inspToggle').addEventListener('click', () => setInspector($('app').classList.contains('insp-off')));
2765
+ $('undo').addEventListener('click', undo);
2766
+ $('redo').addEventListener('click', redo);
2767
+ $('present').addEventListener('click', enterPresent);
2768
+ $('exit').addEventListener('click', exitPresent);
2769
+ // The address bar already tracks ?src, ?view and ?present, so the current URL is the share link.
2770
+ $('share').addEventListener('click', async () => {
2771
+ const url = location.href;
2772
+ // Without ?src the deck lives in this browser only, so the link reopens it here but not for anyone else.
2773
+ const note = new URLSearchParams(location.search).has('src') || location.hash.startsWith('#deck=') ? 'Link copied' : 'Copied · this browser only';
2774
+ try { await navigator.clipboard.writeText(url); } catch { prompt('Copy this link:', url); return; }
2775
+ $('shareTxt').textContent = note;
2776
+ clearTimeout($('share').t); $('share').t = setTimeout(() => { $('shareTxt').textContent = 'Share'; }, 2000);
2777
+ });
2778
+ $('prev').addEventListener('click', () => stepView(-1));
2779
+ $('navMode').addEventListener('click', toggleNavMode);
2780
+ $('next').addEventListener('click', () => stepView(1));
2781
+ $('vSave').addEventListener('click', saveView);
2782
+ $('vUpdate').addEventListener('click', () => updateView({ scene: ownedScene(app.views, app.activeViewId, freezeScene(app.scene, app.rt)), camera: roundCam(app.cam) }));
2783
+ $('vLeft').addEventListener('click', () => moveView(-1));
2784
+ $('vRight').addEventListener('click', () => moveView(1));
2785
+ $('vDel').addEventListener('click', deleteView);
2786
+ $('vName').addEventListener('change', (ev) => updateView({ name: ev.target.value.trim().slice(0, 60) || 'Untitled view' }));
2787
+
2788
+ $('bTitle').addEventListener('input', (ev) => app.selection && dispatch({ type: 'updateBubble', id: app.selection.id, patch: { title: ev.target.value.slice(0, 40) } }));
2789
+ $('bAddEl').addEventListener('click', () => {
2790
+ const eid = newId('el');
2791
+ if (dispatch({ type: 'addElement', bubbleId: app.selection.id, element: { id: eid, label: iconLabel(lastIcon), icon: lastIcon, imageId: null, tags: [], hue: null } })) {
2792
+ app.selection = { kind: 'element', id: eid }; renderUI(); $('eLabel').focus(); $('eLabel').select();
2793
+ }
2794
+ });
2795
+ $('bAround').addEventListener('click', () => addAround(app.selection.id));
2796
+ $('bOrbit').addEventListener('click', () => { app.pick = 'orbit'; renderUI(); });
2797
+ $('bUnorbit').addEventListener('click', () => dispatch({ type: 'setOrbit', id: app.selection.id, hubId: null }));
2798
+ $('bDel').addEventListener('click', () => dispatch({ type: 'deleteBubble', id: app.selection.id }));
2799
+ // ---------- rich-text description ----------
2800
+ // Descriptions are stored as HTML and can arrive from any ?src deck, so every render goes through this allowlist.
2801
+ const RT_TAGS = new Set(['B', 'STRONG', 'I', 'EM', 'U', 'UL', 'OL', 'LI', 'A', 'BR', 'P', 'DIV']);
2802
+ const RT_DROP = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'IFRAME', 'OBJECT', 'EMBED', 'SVG', 'MATH', 'NOSCRIPT', 'TITLE', 'HEAD']);
2803
+ const safeUrl = (u) => /^(https?:|mailto:)/i.test(String(u).trim()) ? String(u).trim() : null;
2804
+ /** Sanitised DocumentFragment for stored description HTML: allowlisted tags only, no attributes but a safe link href. */
2805
+ function safeHtml(html) {
2806
+ const src = new DOMParser().parseFromString(`<body>${html}`, 'text/html').body; // inert: nothing runs or loads
2807
+ const copy = (from, to) => {
2808
+ for (const n of from.childNodes) {
2809
+ if (n.nodeType === Node.TEXT_NODE) { to.append(n.data); continue; }
2810
+ if (n.nodeType !== Node.ELEMENT_NODE) continue;
2811
+ const tag = n.tagName.toUpperCase(); // SVG/MathML children keep lower-case names
2812
+ if (RT_DROP.has(tag)) continue;
2813
+ if (!RT_TAGS.has(tag) || n.namespaceURI !== 'http://www.w3.org/1999/xhtml') { copy(n, to); continue; } // anything else: keep its text only
2814
+ const el = document.createElement(tag.toLowerCase());
2815
+ if (tag === 'A') {
2816
+ const href = safeUrl(n.getAttribute('href'));
2817
+ if (!href) { copy(n, to); continue; }
2818
+ Object.assign(el, { href, target: '_blank', rel: 'noopener noreferrer' });
2819
+ }
2820
+ copy(n, el); to.append(el);
2821
+ }
2822
+ return to;
2823
+ };
2824
+ return copy(src, document.createDocumentFragment());
2825
+ }
2826
+ function cleanDescription(root) {
2827
+ if (!root.textContent.trim()) return '';
2828
+ const box = document.createElement('div');
2829
+ box.append(safeHtml(root.innerHTML));
2830
+ for (const a of box.querySelectorAll('a')) { a.removeAttribute('target'); a.removeAttribute('rel'); }
2831
+ return box.innerHTML;
2832
+ }
2833
+ /** Show a stored description in its editor unless the user is typing there; `key` names what is being edited. */
2834
+ function syncRich(prefix, key, obj) {
2835
+ const ed = $(prefix), tag = `${key}\n${obj.description ?? ''}`;
2836
+ if (document.activeElement !== ed && ed.dataset.of !== tag) { ed.replaceChildren(safeHtml(obj.description ?? '')); ed.dataset.of = tag; }
2837
+ $(`${prefix}Show`).checked = !!obj.showDescription;
2838
+ }
2839
+ /** Wire one rich-text field (editor, toolbar, show toggle); `update(patch)` writes description/showDescription. */
2840
+ function wireRich(prefix, update) {
2841
+ const ed = $(prefix);
2842
+ ed.addEventListener('input', () => {
2843
+ const description = cleanDescription(ed);
2844
+ if (description.length > 4000) { showError(new UserError('The description is too long (4000 characters of formatted text at most).')); return; }
2845
+ if (update({ description })) ed.dataset.of = (ed.dataset.of ?? '').split('\n')[0] + `\n${description}`;
2846
+ });
2847
+ ed.addEventListener('keydown', (ev) => ev.stopPropagation()); // typing here is not a stage shortcut
2848
+ $(`${prefix}Show`).addEventListener('change', (ev) => update({ showDescription: ev.target.checked }));
2849
+ for (const b of $(`${prefix}Bar`).children) {
2850
+ b.addEventListener('mousedown', (ev) => ev.preventDefault()); // keep the editor's selection
2851
+ b.addEventListener('click', () => {
2852
+ const sel = getSelection();
2853
+ const range = sel.rangeCount && ed.contains(sel.anchorNode) ? sel.getRangeAt(0) : null;
2854
+ ed.focus();
2855
+ if (b.dataset.cmd !== 'link') { document.execCommand(b.dataset.cmd); return; }
2856
+ const raw = prompt('Link to (https://…)', 'https://');
2857
+ if (!raw || raw.trim() === 'https://') return;
2858
+ const href = safeUrl(raw) ?? safeUrl(`https://${raw.trim()}`);
2859
+ if (range) { sel.removeAllRanges(); sel.addRange(range); }
2860
+ if (sel.isCollapsed || !range) {
2861
+ const a = Object.assign(document.createElement('a'), { href, textContent: href });
2862
+ document.execCommand('insertHTML', false, a.outerHTML);
2863
+ } else document.execCommand('createLink', false, href);
2864
+ });
2865
+ }
2866
+ }
2867
+ wireRich('eDesc', (patch) => app.selection?.kind === 'element' && dispatch({ type: 'updateElement', id: app.selection.id, patch }));
2868
+ wireRich('stDesc', (patch) => dispatch({ type: 'setStage', patch }));
2869
+
2870
+ $('eLabel').addEventListener('input', (ev) => app.selection && dispatch({ type: 'updateElement', id: app.selection.id, patch: { label: ev.target.value.slice(0, 60) } }));
2871
+ // Enter on an element's label hands selection back to its bubble, ready for ⌘L to add the next one.
2872
+ // Icon filter: the magnifier opens a search box that hides icons whose name doesn't match.
2873
+ function filterIcons(q) {
2874
+ q = q.trim().toLowerCase();
2875
+ for (const b of $('eIcons').children) b.hidden = !!q && !(b.dataset.icon && (ICONS[b.dataset.icon][0].toLowerCase().includes(q) || b.dataset.icon.includes(q)));
2876
+ }
2877
+ function openIconFilter(open) {
2878
+ $('eIconQ').hidden = !open; $('eIconFind').setAttribute('aria-expanded', String(open));
2879
+ if (open) $('eIconQ').focus(); else { $('eIconQ').value = ''; filterIcons(''); }
2880
+ }
2881
+ $('eIconFind').addEventListener('click', () => openIconFilter($('eIconQ').hidden));
2882
+ $('eIconQ').addEventListener('input', (ev) => filterIcons(ev.target.value));
2883
+ $('eIconQ').addEventListener('keydown', (ev) => {
2884
+ if (ev.key === 'Escape') { ev.stopPropagation(); openIconFilter(false); $('eIconFind').focus(); }
2885
+ else if (ev.key === 'Enter') { ev.preventDefault(); [...$('eIcons').children].find((b) => !b.hidden && b.dataset.icon)?.click(); }
2886
+ });
2887
+ $('eLabel').addEventListener('keydown', (ev) => {
2888
+ if (ev.key !== 'Enter' || ev.isComposing || app.selection?.kind !== 'element') return;
2889
+ ev.preventDefault(); ev.target.blur();
2890
+ app.selection = { kind: 'bubble', id: app.rt.elements[app.selection.id].bubbleId }; renderUI();
2891
+ });
2892
+ $('eDel').addEventListener('click', deleteSelectedElements);
2893
+ function deleteSelectedElements() { dispatch({ type: 'batch', cmds: selIds().map((id) => ({ type: 'deleteElement', id })) }); app.multi = []; }
2894
+ function duplicateSelected() {
2895
+ if (app.selection?.kind !== 'element') throw new Error('bug: duplicate without a selected element');
2896
+ const src = app.selection.id;
2897
+ const id = newId('el');
2898
+ if (dispatch({ type: 'duplicateElement', id: src, newId: id }, { spawnFrom: { [id]: src } })) {
2899
+ app.selection = { kind: 'element', id };
2900
+ renderUI();
2901
+ }
2902
+ }
2903
+ $('eDup').addEventListener('click', duplicateSelected);
2904
+ /** Copy the selected bubble and its elements (not their connections) beside it; an orbiting bubble joins the same ring. */
2905
+ function duplicateBubble() {
2906
+ const ix = indexOf(app.scene);
2907
+ const b = ix.bubbles.get(app.selection.id);
2908
+ const bid = newId('bb');
2909
+ const els = ix.members.get(b.id).map((eid) => [newId('el'), ix.elements.get(eid)]);
2910
+ const dx = bubbleRadius(app.scene, b.id) * 2 + 40;
2911
+ const cmd = { type: 'addBubble', bubble: { ...b, id: bid, x: Math.round(b.x + dx), y: b.y }, elements: els.map(([id, e]) => ({ ...e, id })) };
2912
+ if (dispatch(cmd, { spawnFrom: Object.fromEntries(els.map(([id, e]) => [id, e.id])) })) {
2913
+ app.selection = { kind: 'bubble', id: bid };
2914
+ renderUI();
2915
+ }
2916
+ }
2917
+ $('bDup').addEventListener('click', duplicateBubble);
2918
+
2919
+ // ---------- breadcrumbs: hub / … / bubble / element, with quick bubble actions on hover ----------
2920
+ const QA_ICON = (d) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${d}"/></svg>`;
2921
+ const BUBBLE_ACTIONS = [
2922
+ ['Add element', 'M12 5v14M5 12h14', (id) => $('bAddEl').click(), () => true],
2923
+ ['Add around', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M12 8v8M8 12h8', (id) => addAround(id), () => true],
2924
+ ['Orbit…', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z M12 12h.01', () => { app.pick = 'orbit'; renderUI(); }, (b) => !b.orbit],
2925
+ ['Duplicate', 'M9 9h11v11H9z M5 15H4V4h11v1', () => duplicateBubble(), () => true],
2926
+ ];
2927
+ function renderCrumbs(selB, selE) {
2928
+ const nav = $('crumbs');
2929
+ const ix = indexOf(app.scene);
2930
+ const leaf = selB ?? (selE && ix.bubbles.get(selE.bubbleId));
2931
+ nav.hidden = !leaf || app.mode !== 'edit';
2932
+ if (nav.hidden) return;
2933
+ const chain = [];
2934
+ for (let b = leaf; b && !chain.includes(b); b = b.orbit && ix.bubbles.get(b.orbit.hubId)) chain.unshift(b);
2935
+ const crumb = (text, current, onGo, bubble) => {
2936
+ const c = document.createElement('span'); c.className = 'crumb';
2937
+ const go = document.createElement('button');
2938
+ go.type = 'button'; go.className = 'go'; go.textContent = text; go.title = text;
2939
+ go.setAttribute('aria-current', String(current));
2940
+ go.addEventListener('click', onGo);
2941
+ c.append(go);
2942
+ if (bubble) {
2943
+ const qa = document.createElement('div'); qa.className = 'qa';
2944
+ const row = document.createElement('div'); row.className = 'qa-in'; row.setAttribute('role', 'toolbar'); row.setAttribute('aria-label', `Actions for ${text}`);
2945
+ for (const [label, d, run, show] of BUBBLE_ACTIONS) {
2946
+ if (!show(bubble)) continue;
2947
+ const b = document.createElement('button');
2948
+ b.type = 'button'; b.title = label; b.setAttribute('aria-label', `${label}: ${text}`); b.innerHTML = QA_ICON(d);
2949
+ b.addEventListener('click', () => { app.selection = { kind: 'bubble', id: bubble.id }; run(bubble.id); renderUI(); });
2950
+ row.append(b);
2951
+ }
2952
+ qa.append(row); c.append(qa);
2953
+ }
2954
+ return c;
2955
+ };
2956
+ const sep = () => Object.assign(document.createElement('span'), { className: 'sep', textContent: '/' });
2957
+ const parts = chain.map((b) => crumb(b.title || 'Untitled bubble', !selE && b === leaf, () => { app.selection = { kind: 'bubble', id: b.id }; renderUI(); }, b));
2958
+ if (selE) parts.push(crumb(selE.label || 'Element', true, () => {}, null));
2959
+ nav.replaceChildren(...parts.flatMap((p, i) => (i ? [sep(), p] : [p])));
2960
+ }
2961
+
2962
+ const toggleConnect = () => { app.pick = app.pick === 'connect' ? null : 'connect'; renderUI(); };
2963
+ $('connect').addEventListener('click', toggleConnect);
2964
+ const selectedLinkId = () => {
2965
+ if (app.selection?.kind !== 'link') throw new Error('bug: connection control used without a selected connection');
2966
+ return app.selection.id;
2967
+ };
2968
+ $('lLabel').addEventListener('input', (ev) => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { label: ev.target.value.slice(0, 60) } }));
2969
+ for (const b of $('lHead').children) b.addEventListener('click', () => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { head: b.dataset.v } }));
2970
+ for (const b of $('lDash').children) b.addEventListener('click', () => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { dash: b.dataset.v } }));
2971
+ $('lElastic').addEventListener('change', (ev) => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { elasticity: ev.target.checked ? Number($('lElasticity').value) : 0 } }));
2972
+ $('lOpacity').addEventListener('input', (ev) => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { opacity: Number(ev.target.value) / 100 } }));
2973
+ $('lElasticity').addEventListener('input', (ev) => dispatch({ type: 'updateLink', id: selectedLinkId(), patch: { elasticity: Number(ev.target.value) } }));
2974
+ $('lReverse').addEventListener('click', () => {
2975
+ const l = indexOf(app.scene).links.get(selectedLinkId());
2976
+ dispatch({ type: 'updateLink', id: l.id, patch: { from: l.to, to: l.from } });
2977
+ });
2978
+ $('lDel').addEventListener('click', () => dispatch({ type: 'deleteLink', id: selectedLinkId() }));
2979
+ $('eNoImg').addEventListener('click', () => dispatch({ type: 'updateElement', id: app.selection.id, patch: { imageId: null } }));
2980
+ $('ePull').addEventListener('click', () => {
2981
+ const id = app.selection.id;
2982
+ const e = app.rt.elements[id];
2983
+ const b = app.rt.bubbles[e.bubbleId];
2984
+ const dx = e.x - b.x, dy = e.y - b.y, d = Math.hypot(dx, dy) || 1;
2985
+ const u = d < 1 ? { x: 1, y: 0 } : { x: dx / d, y: dy / d };
2986
+ const dist = bubbleRadius(app.scene, e.bubbleId) + K.SINGLE_R + 90;
2987
+ dispatch({ type: 'detachElement', id, newBubbleId: newId('bb'), x: Math.round(b.x + u.x * dist), y: Math.round(b.y + u.y * dist), hue: nextHue(app.scene) });
2988
+ });
2989
+ async function uploadImage(file) {
2990
+ if (!app.assets) { showError('Image upload is not supported yet.'); return; }
2991
+ const target = app.selection;
2992
+ if (target?.kind !== 'element') return;
2993
+ $('eImgNote').textContent = 'Uploading…';
2994
+ try {
2995
+ const res = await app.assets.upload(file);
2996
+ dispatch({ type: 'updateElement', id: target.id, patch: { imageId: res.id } });
2997
+ $('eImgNote').textContent = '';
2998
+ } catch (err) {
2999
+ $('eImgNote').textContent = '';
3000
+ const why = { too_large: 'The image is over the size limit (20 MB, or 2 MB for SVG).', unsupported_type: 'Use a PNG, JPEG, WebP, GIF or SVG image.', rate_limited: 'Too many uploads at once. Wait a moment and try again.' }[err?.code];
3001
+ showError(why ?? `Upload failed (${err?.code ?? err}).`);
3002
+ }
3003
+ }
3004
+ $('eUpload').addEventListener('change', (ev) => { const f = ev.target.files?.[0]; ev.target.value = ''; if (f) uploadImage(f); });
3005
+ document.addEventListener('paste', (ev) => {
3006
+ if (app.selection?.kind !== 'element') return;
3007
+ const f = [...(ev.clipboardData?.files ?? [])].find((x) => x.type.startsWith('image/'));
3008
+ if (f) { ev.preventDefault(); uploadImage(f); }
3009
+ });
3010
+
3011
+ // ---------- pointer input ----------
3012
+ const ov = $('ov');
3013
+ const glc = $('gl');
3014
+ const ctx = ov.getContext('2d');
3015
+ let renderer = null;
3016
+ try { renderer = createMembraneRenderer(glc); } catch (err) { showError(err); }
3017
+ let size = { W: 1, H: 1, dpr: 1 };
3018
+ function resize() {
3019
+ const r = $('stage').getBoundingClientRect();
3020
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
3021
+ size = { W: Math.max(1, r.width), H: Math.max(1, r.height), dpr };
3022
+ for (const c of [ov, glc]) { c.width = Math.round(size.W * dpr); c.height = Math.round(size.H * dpr); }
3023
+ }
3024
+ new ResizeObserver(resize).observe($('stage'));
3025
+ resize();
3026
+
3027
+ const toWorld = (ev) => {
3028
+ const r = ov.getBoundingClientRect();
3029
+ const c = app.rt.camera;
3030
+ return { x: (ev.clientX - r.left - size.W / 2) / c.zoom + c.x, y: (ev.clientY - r.top - size.H / 2) / c.zoom + c.y };
3031
+ };
3032
+
3033
+ ov.addEventListener('pointerdown', (ev) => {
3034
+ if (ev.button !== 0) return;
3035
+ ov.setPointerCapture(ev.pointerId);
3036
+ const w = toWorld(ev);
3037
+ const hit = hitTest(app.rt, app.scene, w.x, w.y);
3038
+ const ix = indexOf(app.scene);
3039
+ if (app.pick === 'orbit') {
3040
+ const target = hit?.kind === 'element' ? { kind: 'bubble', id: ix.elements.get(hit.id).bubbleId } : hit;
3041
+ app.pick = null;
3042
+ if (target && app.selection?.kind === 'bubble' && target.id !== app.selection.id) dispatch({ type: 'setOrbit', id: app.selection.id, hubId: target.id });
3043
+ renderUI();
3044
+ return;
3045
+ }
3046
+ const base = { startX: ev.clientX, startY: ev.clientY, moved: false, hit };
3047
+ if (app.pick === 'connect' && hit?.kind === 'element') {
3048
+ app.drag = { ...base, kind: 'link', fromId: hit.id, x: w.x, y: w.y, targetId: null };
3049
+ return;
3050
+ }
3051
+ if (ev.shiftKey && app.mode === 'edit' && hit?.kind === 'element') {
3052
+ const ids = selIds();
3053
+ app.multi = ids.includes(hit.id) ? ids.filter((id) => id !== hit.id) : [...ids, hit.id];
3054
+ app.selection = app.multi.length ? { kind: 'element', id: app.multi.includes(hit.id) ? hit.id : app.multi.at(-1) } : null;
3055
+ renderUI();
3056
+ return;
3057
+ }
3058
+ if (ev.shiftKey && app.mode === 'edit' && !app.pick) {
3059
+ app.drag = { ...base, kind: 'marquee', x0: w.x, y0: w.y, x: w.x, y: w.y };
3060
+ return;
3061
+ }
3062
+ const group = hit?.kind === 'element' && selIds().length > 1 && selIds().includes(hit.id);
3063
+ if (!hit) {
3064
+ app.drag = { ...base, kind: 'pan', cam0: { ...app.cam } };
3065
+ } else if (group) {
3066
+ const body = app.rt.elements[hit.id];
3067
+ app.drag = { ...base, kind: 'element', id: hit.id, offX: body.x - w.x, offY: body.y - w.y, x: body.x, y: body.y, tether: false, group: selIds(), offsets: Object.fromEntries(selIds().filter((id) => id !== hit.id).map((id) => [id, { x: app.rt.elements[id].x - body.x, y: app.rt.elements[id].y - body.y }])) };
3068
+ } else if (hit.kind === 'element') {
3069
+ const e = ix.elements.get(hit.id);
3070
+ const b = ix.bubbles.get(e.bubbleId);
3071
+ if (ix.members.get(b.id).length === 1 && !b.title) {
3072
+ const body = app.rt.bubbles[b.id];
3073
+ app.drag = { ...base, kind: 'bubble', id: b.id, offX: body.x - w.x, offY: body.y - w.y, x: body.x, y: body.y };
3074
+ } else {
3075
+ const body = app.rt.elements[hit.id];
3076
+ app.drag = { ...base, kind: 'element', id: hit.id, offX: body.x - w.x, offY: body.y - w.y, x: body.x, y: body.y, tether: true };
3077
+ }
3078
+ } else if (hit.kind === 'link') {
3079
+ const l = ix.links.get(hit.id);
3080
+ const rest = {};
3081
+ for (const eid of [l.from, l.to]) {
3082
+ const b = app.rt.bubbles[ix.elements.get(eid).bubbleId];
3083
+ rest[eid] = Math.hypot(w.x - b.x, w.y - b.y);
3084
+ }
3085
+ app.drag = { ...base, kind: 'rope', id: hit.id, x: w.x, y: w.y, rest };
3086
+ } else if (hit.kind === 'bubble') {
3087
+ const body = app.rt.bubbles[hit.id];
3088
+ app.drag = { ...base, kind: 'bubble', id: hit.id, offX: body.x - w.x, offY: body.y - w.y, x: body.x, y: body.y };
3089
+ } else {
3090
+ throw new Error(`bug: unhandled hit kind ${hit.kind}`);
3091
+ }
3092
+ });
3093
+
3094
+ ov.addEventListener('pointermove', (ev) => {
3095
+ const d = app.drag;
3096
+ const w = toWorld(ev);
3097
+ if (!d) {
3098
+ const hit = hitTest(app.rt, app.scene, w.x, w.y);
3099
+ ov.style.cursor = app.pick ? 'crosshair' : hit ? 'grab' : 'default';
3100
+ return;
3101
+ }
3102
+ if (!d.moved && Math.hypot(ev.clientX - d.startX, ev.clientY - d.startY) > 4) d.moved = true;
3103
+ if (!d.moved) return;
3104
+ ov.style.cursor = d.kind === 'marquee' ? 'crosshair' : 'grabbing';
3105
+ if (d.kind === 'pan') {
3106
+ const z = app.cam.zoom;
3107
+ app.cam = { ...d.cam0, x: d.cam0.x - (ev.clientX - d.startX) / z, y: d.cam0.y - (ev.clientY - d.startY) / z };
3108
+ app.rt = { ...app.rt, camera: { ...app.cam } };
3109
+ return;
3110
+ }
3111
+ if (d.kind === 'link') {
3112
+ d.x = w.x; d.y = w.y;
3113
+ d.targetId = elementAt(app.rt, app.scene, w.x, w.y, d.fromId);
3114
+ return;
3115
+ }
3116
+ if (d.kind === 'rope' || d.kind === 'marquee') { d.x = w.x; d.y = w.y; return; }
3117
+ d.x = w.x + d.offX; d.y = w.y + d.offY;
3118
+ const mod = ev.metaKey || ev.ctrlKey;
3119
+ if (d.kind === 'element' && d.tether) {
3120
+ if (detachGap(app.scene, app.rt, d.id, d.x, d.y) > K.DETACH_GAP) {
3121
+ const nb = newId('bb');
3122
+ if (dispatch({ type: 'detachElement', id: d.id, newBubbleId: nb, x: Math.round(d.x), y: Math.round(d.y), hue: nextHue(app.scene) })) {
3123
+ app.drag = { ...d, kind: 'bubble', id: nb, tether: false, detachedFrom: d.id };
3124
+ return;
3125
+ }
3126
+ d.tether = false;
3127
+ }
3128
+ const e = indexOf(app.scene).elements.get(d.id);
3129
+ const own = app.rt.bubbles[e.bubbleId];
3130
+ // Within its own bubble an element can only change cell: into another cell, or (⌘/Ctrl) a new one.
3131
+ const inOwn = (mod || bubbleLayout(app.scene, e.bubbleId).cells.length > 0) && Math.hypot(w.x - own.x, w.y - own.y) < own.r;
3132
+ setDrop(bubbleAt(app.rt, app.scene, w.x, w.y, e.bubbleId)?.id ?? (inOwn ? e.bubbleId : null), w, mod);
3133
+ } else if (d.kind === 'element' && d.group) {
3134
+ setDrop(bubbleAt(app.rt, app.scene, w.x, w.y)?.id ?? null, w, mod);
3135
+ } else if (d.kind === 'bubble') {
3136
+ setDrop(bubbleAt(app.rt, app.scene, w.x, w.y, d.id)?.id ?? null, w, mod);
3137
+ }
3138
+ });
3139
+ function setDrop(id, w, mod) {
3140
+ app.dropTargetId = id;
3141
+ app.dropCell = id === null ? null : mod ? 'new' : cellAt(app.rt, app.scene, id, w.x, w.y);
3142
+ }
3143
+
3144
+ function endDrag(ev) {
3145
+ const d = app.drag;
3146
+ if (!d) return;
3147
+ app.drag = null;
3148
+ const target = app.dropTargetId;
3149
+ const cell = target && (app.dropCell === 'new' ? nextCell(app.scene, target) : app.dropCell);
3150
+ app.dropTargetId = null; app.dropCell = null;
3151
+ ov.style.cursor = 'default';
3152
+ if (d.kind === 'marquee') {
3153
+ // Shift-drag box: adds every element inside it to the selection.
3154
+ const [x0, x1] = [d.x0, d.x].sort((a, b) => a - b), [y0, y1] = [d.y0, d.y].sort((a, b) => a - b);
3155
+ const inside = Object.values(app.rt.elements).filter((e) => !e.dying && e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1).map((e) => e.id);
3156
+ const ids = [...new Set([...selIds(), ...inside])];
3157
+ if (ids.length) { app.multi = ids; app.selection = { kind: 'element', id: app.selection?.kind === 'element' && ids.includes(app.selection.id) ? app.selection.id : ids.at(-1) }; }
3158
+ renderUI();
3159
+ return;
3160
+ }
3161
+ if (!d.moved) {
3162
+ app.multi = [];
3163
+ if (d.kind === 'pan') app.selection = null;
3164
+ else app.selection = app.mode === 'edit' ? d.hit : d.hit?.kind === 'element' ? d.hit : null;
3165
+ renderUI();
3166
+ return;
3167
+ }
3168
+ if (d.kind === 'pan') { scheduleSave(); return; }
3169
+ if (d.kind === 'rope') {
3170
+ // Keep the connected bubbles where the pull left them (bubbles in a ring return to it).
3171
+ const ix = indexOf(app.scene);
3172
+ const l = ix.links.get(d.id);
3173
+ if (!l) return;
3174
+ const ids = [...new Set([l.from, l.to].map((eid) => ix.elements.get(eid).bubbleId))];
3175
+ const cmds = ids.filter((bid) => !ix.bubbles.get(bid).orbit).map((bid) => ({ type: 'setHome', id: bid, x: Math.round(app.rt.bubbles[bid].x), y: Math.round(app.rt.bubbles[bid].y) }));
3176
+ if (app.mode === 'edit') app.selection = { kind: 'link', id: d.id };
3177
+ if (cmds.length) dispatch({ type: 'batch', cmds });
3178
+ renderUI();
3179
+ return;
3180
+ }
3181
+ if (d.kind === 'link') {
3182
+ if (!d.targetId) return;
3183
+ const id = newId('ln');
3184
+ if (dispatch({ type: 'addLink', link: { id, from: d.fromId, to: d.targetId, label: '', head: 'end', dash: 'solid', elasticity: 0, tags: [], messages: [] } })) {
3185
+ app.selection = { kind: 'link', id };
3186
+ renderUI();
3187
+ }
3188
+ return;
3189
+ }
3190
+ if (d.kind === 'element' && d.group) {
3191
+ const ix = indexOf(app.scene);
3192
+ const ids = d.group.filter((id) => ix.elements.has(id));
3193
+ if (target) {
3194
+ dispatch({ type: 'batch', cmds: ids.map((id) => ({ type: 'moveElement', id, toBubbleId: target, cell })) });
3195
+ } else {
3196
+ // Dropped on empty canvas: the group becomes a new bubble there.
3197
+ const nb = newId('bb');
3198
+ dispatch({ type: 'batch', cmds: [
3199
+ { type: 'detachElement', id: d.id, newBubbleId: nb, x: Math.round(d.x), y: Math.round(d.y), hue: nextHue(app.scene) },
3200
+ ...ids.filter((id) => id !== d.id).map((id) => ({ type: 'moveElement', id, toBubbleId: nb, cell: 0 })),
3201
+ ] });
3202
+ }
3203
+ return;
3204
+ }
3205
+ if (d.kind === 'element') {
3206
+ const e = indexOf(app.scene).elements.get(d.id);
3207
+ if (target && !(target === e.bubbleId && (e.cell ?? 0) === cell)) dispatch({ type: 'moveElement', id: d.id, toBubbleId: target, cell });
3208
+ return;
3209
+ }
3210
+ if (d.kind === 'bubble') {
3211
+ if (target) {
3212
+ dispatch({ type: 'mergeBubble', fromId: d.id, intoId: target, titleElementId: newId('el'), cell });
3213
+ return;
3214
+ }
3215
+ const sb = indexOf(app.scene).bubbles.get(d.id);
3216
+ const cmds = [{ type: 'setHome', id: d.id, x: Math.round(d.x), y: Math.round(d.y) }];
3217
+ if (sb.orbit) {
3218
+ const hub = app.rt.bubbles[sb.orbit.hubId];
3219
+ if (Math.hypot(d.x - hub.x, d.y - hub.y) > ringRadius(app.scene, sb.orbit.hubId) * 1.6) cmds.push({ type: 'setOrbit', id: d.id, hubId: null });
3220
+ }
3221
+ dispatch({ type: 'batch', cmds });
3222
+ }
3223
+ }
3224
+ ov.addEventListener('pointerup', endDrag);
3225
+ ov.addEventListener('pointercancel', endDrag);
3226
+ ov.addEventListener('dblclick', (ev) => {
3227
+ if (app.mode !== 'edit') return;
3228
+ const w = toWorld(ev);
3229
+ const hit = hitTest(app.rt, app.scene, w.x, w.y);
3230
+ if (!hit) addBubbleAt(w.x, w.y);
3231
+ else if (hit.kind === 'element') { app.selection = hit; renderUI(); $('eLabel').focus(); $('eLabel').select(); }
3232
+ else if (hit.kind === 'link') { app.selection = hit; renderUI(); $('lLabel').focus(); }
3233
+ else { app.selection = hit; renderUI(); $('bTitle').focus(); }
3234
+ });
3235
+ ov.addEventListener('wheel', (ev) => {
3236
+ ev.preventDefault();
3237
+ const r = ov.getBoundingClientRect();
3238
+ const before = toWorld(ev);
3239
+ const zoom = clamp(app.cam.zoom * Math.exp(-ev.deltaY * 0.0015), 0.3, 2.5);
3240
+ const mx = ev.clientX - r.left - size.W / 2, my = ev.clientY - r.top - size.H / 2;
3241
+ app.cam = { x: before.x - mx / zoom, y: before.y - my / zoom, zoom };
3242
+ app.rt = { ...app.rt, camera: { ...app.cam } };
3243
+ scheduleSave();
3244
+ }, { passive: false });
3245
+
3246
+ document.addEventListener('keydown', (ev) => {
3247
+ if ($('stepDlg').open || $('openDlg').open) return; // the dialog handles its own keys (Esc closes it)
3248
+ const typing = ev.target instanceof HTMLInputElement || ev.target instanceof HTMLTextAreaElement;
3249
+ if (app.mode === 'present') {
3250
+ if (/^[1-9]$/.test(ev.key) && availableMessages()[Number(ev.key) - 1]) { ev.preventDefault(); const m = availableMessages()[Number(ev.key) - 1]; requestSend(m.link.id, m.msg.id); }
3251
+ // ponytail: single digit only, so views 10+ are reached by arrows or the strip; add a typed-number buffer if decks grow that long.
3252
+ else if (/^[1-9]$/.test(ev.key) && app.views[Number(ev.key) - 1]) { ev.preventDefault(); goToView(app.views[Number(ev.key) - 1].id); }
3253
+ else if (['ArrowRight', 'PageDown', ' ', 'Enter'].includes(ev.key)) { ev.preventDefault(); stepView(1); }
3254
+ else if (['ArrowLeft', 'PageUp'].includes(ev.key)) { ev.preventDefault(); stepView(-1); }
3255
+ else if (ev.key === 'Escape') exitPresent();
3256
+ else if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'z') { ev.preventDefault(); ev.shiftKey ? redo() : undo(); }
3257
+ else if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'y') { ev.preventDefault(); redo(); }
3258
+ else if ((ev.key === 'Delete' || ev.key === 'Backspace') && app.selection?.kind === 'element') {
3259
+ ev.preventDefault();
3260
+ if (dispatch({ type: 'deleteElement', id: app.selection.id })) { app.selection = null; renderUI(); }
3261
+ }
3262
+ return;
3263
+ }
3264
+ if ((ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 's') {
3265
+ ev.preventDefault();
3266
+ if (app.mode === 'edit') {
3267
+ if (app.views.some((v) => v.id === app.activeViewId)) updateView({ scene: ownedScene(app.views, app.activeViewId, freezeScene(app.scene, app.rt)), camera: roundCam(app.cam) });
3268
+ else saveView();
3269
+ }
3270
+ return;
3271
+ }
3272
+ // ⌘B / ⌘E work from text fields too (the rich-text editor keeps its own ⌘B for bold: it stops propagation).
3273
+ if (app.mode === 'edit' && (ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'b') { ev.preventDefault(); $('addBubble').click(); return; }
3274
+ if (app.mode === 'edit' && (ev.metaKey || ev.ctrlKey) && ev.key.toLowerCase() === 'e') { ev.preventDefault(); toggleConnect(); return; }
3275
+ if (app.mode === 'edit' && (ev.metaKey || ev.ctrlKey) && ev.key === '.') { ev.preventDefault(); setInspector($('app').classList.contains('insp-off')); return; }
3276
+ if (typing) {
3277
+ if (ev.key === 'Escape') { ev.target.blur(); if (app.filterOpen) { app.filterOpen = false; renderFilter(); } }
3278
+ return;
3279
+ }
3280
+ if (ev.key === '/') { ev.preventDefault(); $('fQuery').focus(); return; }
3281
+ if (ev.key === 'Escape' && app.filterOpen) { app.filterOpen = false; renderFilter(); return; }
3282
+ const mod = ev.metaKey || ev.ctrlKey;
3283
+ if (mod && ev.key.toLowerCase() === 'z') { ev.preventDefault(); ev.shiftKey ? redo() : undo(); }
3284
+ else if (mod && ev.key.toLowerCase() === 'y') { ev.preventDefault(); redo(); }
3285
+ else if (mod && ev.key.toLowerCase() === 'd' && app.selection?.kind === 'element') { ev.preventDefault(); duplicateSelected(); }
3286
+ else if (mod && ev.key.toLowerCase() === 'd' && app.selection?.kind === 'bubble') { ev.preventDefault(); duplicateBubble(); }
3287
+ else if (mod && ev.key.toLowerCase() === 'p' && app.selection?.kind === 'element') { ev.preventDefault(); if (!$('ePull').disabled) $('ePull').click(); }
3288
+ else if (mod && ev.key.toLowerCase() === 'l' && app.selection?.kind === 'bubble') { ev.preventDefault(); $('bAddEl').click(); }
3289
+ else if (mod && ev.key.toLowerCase() === 'u' && app.selection?.kind === 'bubble') { ev.preventDefault(); addAround(app.selection.id); }
3290
+ else if (ev.key === 'Escape') { app.pick = null; app.selection = null; app.multi = []; renderUI(); }
3291
+ else if ((ev.key === 'Delete' || ev.key === 'Backspace') && app.selection) {
3292
+ ev.preventDefault();
3293
+ if (app.selection.kind === 'element') { deleteSelectedElements(); return; }
3294
+ const type = { bubble: 'deleteBubble', link: 'deleteLink' }[app.selection.kind];
3295
+ if (!type) throw new Error(`bug: cannot delete selection kind ${app.selection.kind}`);
3296
+ dispatch({ type, id: app.selection.id });
3297
+ }
3298
+ else if (!mod && ev.key.toLowerCase() === 'c') toggleConnect();
3299
+ });
3300
+
3301
+ // Holding ⌘/Ctrl alone (not mid-drag, where it means "new cell") underlines the ⌘B / ⌘E / ⌘L / ⌘U / ⌘D letters.
3302
+ const cmdHint = (on) => document.body.classList.toggle('cmd-held', on);
3303
+ document.addEventListener('keydown', (ev) => cmdHint((ev.key === 'Meta' || ev.key === 'Control') && !app.drag && app.mode === 'edit'));
3304
+ document.addEventListener('keyup', (ev) => { if (ev.key === 'Meta' || ev.key === 'Control') cmdHint(false); });
3305
+ document.addEventListener('pointerdown', () => cmdHint(false));
3306
+ window.addEventListener('blur', () => cmdHint(false));
3307
+
3308
+ // ---------- theme tracking ----------
3309
+ const refreshTheme = () => { app.theme = readTheme(); };
3310
+ matchMedia('(prefers-color-scheme: dark)').addEventListener('change', refreshTheme);
3311
+ new MutationObserver(refreshTheme).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
3312
+
3313
+ // ---------- loop ----------
3314
+ const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
3315
+ let last = performance.now();
3316
+ let acc = 0;
3317
+ let loopFailed = false;
3318
+ function frame(now) {
3319
+ if (loopFailed) return;
3320
+ try {
3321
+ acc = Math.min(acc + (now - last) / 1000, 0.1);
3322
+ last = now;
3323
+ const input = {
3324
+ drag: !app.drag || !app.drag.moved ? null
3325
+ : app.drag.kind === 'element' || app.drag.kind === 'bubble' ? { kind: app.drag.kind, id: app.drag.id, x: app.drag.x, y: app.drag.y, tether: !!app.drag.tether, offsets: app.drag.offsets }
3326
+ : app.drag.kind === 'rope' ? { kind: 'rope', id: app.drag.id, x: app.drag.x, y: app.drag.y, rest: app.drag.rest }
3327
+ : null,
3328
+ cameraTarget: app.cam,
3329
+ match: filterMatch(app.scene, app.filter),
3330
+ };
3331
+ while (acc >= K.DT) {
3332
+ app.rt = step(app.rt, app.scene, input, K.DT);
3333
+ if (reduced) app.rt = { ...app.rt, bubbles: Object.fromEntries(Object.entries(app.rt.bubbles).map(([k, b]) => [k, { ...b, w2: b.w2 * 0.3, w3: b.w3 * 0.3 }])) };
3334
+ acc -= K.DT;
3335
+ }
3336
+ deliverArrivedPackets();
3337
+ const st = app.rt.stage;
3338
+ const bg = app.theme.bg.map((v, i) => v + (st.rgb[i] - v) * st.a);
3339
+ const darkBg = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] < 0.45;
3340
+ // Ink follows the actual backdrop, not the theme, so a dark custom colour in light mode (or the reverse) stays readable.
3341
+ const ink = darkBg ? INK.onDark : INK.onLight;
3342
+ // Named hues follow the backdrop; custom #rrggbb membranes (including fading ones) are used as is.
3343
+ const cellInk = { ...(darkBg ? INK.cellsOnDark : INK.cellsOnLight), ...Object.fromEntries(Object.values(app.rt.bubbles).filter((b) => b.hue.startsWith('#')).map((b) => [b.hue, b.hue])) };
3344
+ const backdrop = { ...app.theme, bg, grid: hexRgb(ink.fg), gridA: (darkBg ? 0.09 : 0.13) * st.grid, dark: darkBg ? 1 : 0 };
3345
+ paintPresentChrome(app.mode === 'present' && st.a > 0.001 ? { bg, ink } : null);
3346
+ renderSaveState();
3347
+ if (renderer) renderer.draw(buildFrame(app.rt, app.scene, { ...size, theme: { ...app.theme, cells: Object.fromEntries(Object.entries(cellInk).map(([h, v]) => [h, hexRgb(v)])) }, dragBubbleId: input.drag?.kind === 'bubble' ? input.drag.id : null }), backdrop);
3348
+ drawOverlay(ctx, app.rt, app.scene, { ...size, theme: { ...app.theme, css: { ...app.theme.css, ...ink, cells: cellInk } }, mode: app.mode, selection: app.selection, selectedIds: selIds(), marquee: app.drag?.kind === 'marquee' && app.drag.moved ? app.drag : null, dropTargetId: app.dropTargetId, dropCell: app.dropCell, dragElementId: app.drag?.kind === 'element' ? app.drag.id : null, pickMode: app.pick === 'orbit', packets: app.packets, pendingLink: app.drag?.kind === 'link' && app.drag.moved ? { fromId: app.drag.fromId, x: app.drag.x, y: app.drag.y, targetId: app.drag.targetId } : null });
3349
+ } catch (err) {
3350
+ loopFailed = true;
3351
+ showError(err);
3352
+ return;
3353
+ }
3354
+ requestAnimationFrame(frame);
3355
+ }
3356
+ renderUI();
3357
+ setStatus();
3358
+ requestAnimationFrame(frame);
3359
+ boot().catch(showError);
3360
+ </script>
3361
+
3362
+ </body></html>