interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / public / js / allen-panes.js

2001 lines · 93354 bytes Raw Blame History
1/* Allen glass panes.
2 *
3 * Generated by om/allen-panes/panes.om; never hand-edit. Event names, kinds,
4 * the protocol version and the byte limits come from the canonical pane
5 * contract om/allen-panes/contract.om; the remaining bounds come from the
6 * table in panes.om.
7 *
8 * Renders the v1 pane events (pane.open, pane.update, pane.close) as movable,
9 * resizable, stackable glass panes over the scene. Every network or model
10 * string reaches only textContent, an attribute value this file checks, or the
11 * srcdoc of a frame sandboxed to allow-scripts alone after an explicit Run
12 * click. Nothing from the network is parsed as markup in this document: plots
13 * are drawn here from numbers and TeX is typeset here by a small subset
14 * renderer, or shown as source when it uses anything outside that subset.
15 * Projects reach IndexedDB only on an explicit Save project.
16 */
17(() => {
18 'use strict';
19 if (window.AllenPanes) return;
20 const KINDS = 'math,plot,doc,code,app,research,data,omega'.split(',');
21 const EVENTS = 'pane.open,pane.update,pane.close'.split(',');
22 const VERSION = 1;
23 const MAX_EVENT = 65536;
24 const MAX_TEXT = 32768;
25 const STATUSES = 'computed,unsupported,unverified,input-data'.split(',');
26 const MAX_TITLE = 200;
27 const MAX_LIST = 64;
28 const MAX_SERIES = 8;
29 const MAX_POINTS = 512;
30 const MAX_REVISION = 1000000;
31 const MAX_PANES = 32;
32 const MAX_URL = 2048;
33 const MAX_CLOSED = 8;
34 const MAX_PROJECTS = 50;
35 const MAX_PROJECT_BYTES = 4194304;
36 const DB_NAME = 'allen-panes';
37 const FORMAT = 'allen-panes-project';
38 const SANDBOX = 'allow-scripts';
39 const CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'";
40 const SHEET = '(max-width: 720px)';
41 const MIN_W = 260;
42 const MIN_H = 160;
43 const MAX_ABS = 1e100;
44 const SYNC_MAX = 1000;
45 const ID = /^[A-Za-z0-9_-]{1,64}$/;
46 const DB_PROJECTS = 'projects';
47 const DB_INDEX = 'index';
48 const STEP = 16;
49 const BIG_STEP = 64;
50 const MAX_NAME = 80;
51 const ACADEMY = 'https://interplane.io/drakestapleton/sovereign-intelligence/blob/main/docs/academy/README.md';
52 const SVG_NS = 'http://www.w3.org/2000/svg';
53 const MATH_NS = 'http://www.w3.org/1998/Math/MathML';
54 const NAMES = { math: 'Math', plot: 'Plot', doc: 'Document', code: 'Code', app: 'App', research: 'Research', data: 'Data', omega: 'Omega', card: 'Aien', projects: 'Projects' };
55 const STATUS_NAMES = { computed: 'Computed', unsupported: 'Not supported', unverified: 'Not verified', 'input-data': 'Given data' };
56 const CAVEATS = {
57 computed: 'The math engine produced this result. That is not an independent check that it is correct.',
58 unsupported: 'The engine does not support this request, so nothing here was computed.',
59 unverified: 'Written by the model and not checked by any engine.',
60 'input-data': 'These are the numbers as given. Showing them does not measure or prove them.'
61 };
62 const PALETTE = ['#2d7ff9', '#00e599', '#f59e0b', '#6e82ff', '#f87171', '#c4b5fd', '#94a3b8', '#f1f5f9'];
63 const EXT = { javascript: 'js', js: 'js', typescript: 'ts', ts: 'ts', python: 'py', py: 'py', rust: 'rs', rs: 'rs', c: 'c', cpp: 'cpp', 'c++': 'cpp', go: 'go', java: 'java', html: 'html', css: 'css', json: 'json', shell: 'sh', sh: 'sh', bash: 'sh', sql: 'sql', mojo: 'mojo', wat: 'wat', omega: 'om', om: 'om', markdown: 'md', md: 'md', text: 'txt' };
64 const encoder = new TextEncoder();
65 let serial = 0;
66
67 function el(tag, className, text) {
68 const node = document.createElement(tag);
69 if (className) node.className = className;
70 if (text !== undefined) node.textContent = text;
71 return node;
72 }
73 function button(className, label, text, handler) {
74 const node = el('button', className, text);
75 node.type = 'button';
76 if (label) node.setAttribute('aria-label', label);
77 if (handler) node.addEventListener('click', handler);
78 return node;
79 }
80 function uid(prefix) {
81 serial += 1;
82 return `${prefix}-${serial}`;
83 }
84 /* Display text for titles and names: no control or bidirectional override
85 characters, one line, bounded. */
86 function clean(text, max) {
87 return String(text).replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
88 }
89 function slug(text) {
90 return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 48).replace(/-+$/, '');
91 }
92 function copy(value) {
93 return JSON.parse(JSON.stringify(value));
94 }
95 function utf8(text) {
96 return encoder.encode(text).length;
97 }
98
99 /* The v1 contract, checked exactly as the gateway checks it: unknown or
100 missing fields, a wrong kind, a nonfinite number or an excess size refuse
101 the whole event. */
102 const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
103 function plain(o) {
104 if (o === null || typeof o !== 'object' || Array.isArray(o)) return false;
105 const proto = Object.getPrototypeOf(o);
106 return proto === Object.prototype || proto === null;
107 }
108 function shape(o, required, optional) {
109 if (!plain(o)) return false;
110 const allowed = optional ? required.concat(optional) : required;
111 for (const k of Object.keys(o)) if (!allowed.includes(k)) return false;
112 return required.every(k => own(o, k));
113 }
114 function isText(v, max, filled) {
115 if (typeof v !== 'string' || v.length > max || v.includes('\u0000')) return false;
116 if (filled && !v.trim()) return false;
117 return v.length * 3 <= max || utf8(v) <= max;
118 }
119 function texts(v) {
120 return Array.isArray(v) && v.length <= MAX_LIST && v.every(s => isText(s, MAX_TEXT));
121 }
122 function finite(n) {
123 return typeof n === 'number' && Number.isFinite(n) && Math.abs(n) <= MAX_ABS;
124 }
125 function httpsUrl(url) {
126 if (typeof url !== 'string' || !isText(url, MAX_URL) || /[\u0000-\u0020\u007f]/.test(url)) return null;
127 try {
128 const parsed = new URL(url);
129 return parsed.protocol === 'https:' && parsed.hostname && !parsed.username && !parsed.password ? parsed : null;
130 } catch (_) {
131 return null;
132 }
133 }
134 function refs(v) {
135 return Array.isArray(v) && v.length <= MAX_LIST && v.every(r => shape(r, ['title', 'url']) && isText(r.title, MAX_TITLE, true) && httpsUrl(r.url) !== null);
136 }
137 function fns(v) {
138 return Array.isArray(v) && v.length <= MAX_LIST && v.every(f => shape(f, ['name', 'params', 'ret']) && isText(f.name, MAX_TEXT) && isText(f.ret, MAX_TEXT)
139 && Array.isArray(f.params) && f.params.length <= MAX_LIST && f.params.every(p => shape(p, ['name', 'type']) && isText(p.name, MAX_TEXT) && isText(p.type, MAX_TEXT)));
140 }
141 function code(c) {
142 return shape(c, ['source', 'language'], ['wasm', 'functions']) && isText(c.source, MAX_TEXT) && isText(c.language, MAX_TEXT)
143 && (!own(c, 'wasm') || isText(c.wasm, MAX_TEXT)) && (!own(c, 'functions') || fns(c.functions));
144 }
145 function series(s) {
146 return shape(s, ['label', 'points']) && isText(s.label, MAX_TITLE) && Array.isArray(s.points) && s.points.length >= 1 && s.points.length <= MAX_POINTS
147 && s.points.every(p => Array.isArray(p) && p.length === 2 && finite(p[0]) && finite(p[1]));
148 }
149 const CONTENT = {
150 math: c => shape(c, ['text'], ['tex']) && isText(c.text, MAX_TEXT) && (!own(c, 'tex') || isText(c.tex, MAX_TEXT)),
151 plot: c => shape(c, ['series', 'x_label', 'y_label']) && isText(c.x_label, MAX_TITLE) && isText(c.y_label, MAX_TITLE)
152 && Array.isArray(c.series) && c.series.length >= 1 && c.series.length <= MAX_SERIES && c.series.every(series),
153 doc: c => shape(c, ['markdown', 'citations']) && isText(c.markdown, MAX_TEXT) && refs(c.citations),
154 code,
155 omega: code,
156 app: c => shape(c, ['html']) && isText(c.html, MAX_TEXT),
157 research: c => shape(c, ['notes', 'hypotheses', 'derivations', 'sources']) && isText(c.notes, MAX_TEXT) && texts(c.hypotheses) && texts(c.derivations) && refs(c.sources),
158 data: c => shape(c, ['columns', 'rows']) && texts(c.columns) && c.columns.length >= 1
159 && Array.isArray(c.rows) && c.rows.length <= MAX_LIST && c.rows.every(texts)
160 };
161 const PROVENANCE = ['status', 'engine', 'expression', 'result', 'source', 'commit'];
162 function provenance(p) {
163 return shape(p, PROVENANCE) && STATUSES.includes(p.status) && PROVENANCE.every(k => isText(p[k], MAX_TEXT));
164 }
165 function sized(value) {
166 try {
167 return utf8(JSON.stringify(value)) <= MAX_EVENT;
168 } catch (_) {
169 return false;
170 }
171 }
172 /* Returns '' for a valid event, else the reason. An update is checked
173 against the kind its pane was opened with. */
174 function check(name, p, kind) {
175 if (!EVENTS.includes(name)) return 'unknown pane event';
176 if (!plain(p)) return 'the event is not a JSON object';
177 const fields = name === 'pane.open' ? ['v', 'id', 'kind', 'title'] : name === 'pane.update' ? ['v', 'id', 'revision', 'content', 'provenance'] : ['v', 'id'];
178 if (!shape(p, fields)) return 'unexpected or missing fields';
179 if (p.v !== VERSION || typeof p.id !== 'string' || !ID.test(p.id)) return 'invalid pane identity';
180 if (!sized(p)) return 'the event is over the size limit';
181 if (name === 'pane.open') {
182 if (!KINDS.includes(p.kind)) return 'invalid pane kind';
183 return isText(p.title, MAX_TITLE, true) ? '' : 'invalid title';
184 }
185 if (name === 'pane.update') {
186 if (!Number.isInteger(p.revision) || p.revision < 1 || p.revision > MAX_REVISION) return 'invalid revision';
187 if (!KINDS.includes(kind)) return 'the pane is not open';
188 if (!CONTENT[kind](p.content)) return `the content does not match ${kind === 'app' || kind === 'omega' ? 'an' : 'a'} ${kind} pane`;
189 return provenance(p.provenance) ? '' : 'invalid provenance';
190 }
191 return '';
192 }
193
194 /* Links: HTTPS only, shown with their host, never fetched by this page. */
195 function link(label, url) {
196 const safe = httpsUrl(url);
197 const shown = clean(label, MAX_TITLE) || url;
198 if (!safe) {
199 const span = el('span', 'allen-link-off', shown);
200 if (url && url !== shown) span.append(document.createTextNode(` (${url})`));
201 return span;
202 }
203 const frag = document.createDocumentFragment();
204 const a = el('a', 'allen-link', shown);
205 a.href = safe.href;
206 a.target = '_blank';
207 a.rel = 'noopener noreferrer nofollow';
208 a.referrerPolicy = 'no-referrer';
209 frag.append(a, el('span', 'allen-link-host', ` ${safe.host}`));
210 return frag;
211 }
212
213 /* A small first-party TeX subset typeset as MathML Core built element by
214 element. Anything outside the subset throws, and the caller shows the
215 TeX as source and says so. */
216 const GREEK = { alpha: '\u03b1', beta: '\u03b2', gamma: '\u03b3', delta: '\u03b4', epsilon: '\u03f5', varepsilon: '\u03b5', zeta: '\u03b6', eta: '\u03b7', theta: '\u03b8', vartheta: '\u03d1', iota: '\u03b9', kappa: '\u03ba', lambda: '\u03bb', mu: '\u03bc', nu: '\u03bd', xi: '\u03be', pi: '\u03c0', varpi: '\u03d6', rho: '\u03c1', varrho: '\u03f1', sigma: '\u03c3', varsigma: '\u03c2', tau: '\u03c4', upsilon: '\u03c5', phi: '\u03d5', varphi: '\u03c6', chi: '\u03c7', psi: '\u03c8', omega: '\u03c9', Gamma: '\u0393', Delta: '\u0394', Theta: '\u0398', Lambda: '\u039b', Xi: '\u039e', Pi: '\u03a0', Sigma: '\u03a3', Upsilon: '\u03a5', Phi: '\u03a6', Psi: '\u03a8', Omega: '\u03a9' };
217 const IDENT = { infty: '\u221e', partial: '\u2202', nabla: '\u2207', ell: '\u2113', hbar: '\u210f', emptyset: '\u2205', aleph: '\u2135' };
218 const OPS = { pm: '\u00b1', mp: '\u2213', times: '\u00d7', cdot: '\u22c5', div: '\u00f7', ast: '\u2217', star: '\u22c6', circ: '\u2218', bullet: '\u2219', leq: '\u2264', le: '\u2264', geq: '\u2265', ge: '\u2265', neq: '\u2260', ne: '\u2260', approx: '\u2248', equiv: '\u2261', sim: '\u223c', simeq: '\u2243', cong: '\u2245', propto: '\u221d', ll: '\u226a', gg: '\u226b', to: '\u2192', rightarrow: '\u2192', leftarrow: '\u2190', Rightarrow: '\u21d2', Leftarrow: '\u21d0', leftrightarrow: '\u2194', Leftrightarrow: '\u21d4', iff: '\u21d4', implies: '\u21d2', mapsto: '\u21a6', in: '\u2208', notin: '\u2209', ni: '\u220b', subset: '\u2282', supset: '\u2283', subseteq: '\u2286', supseteq: '\u2287', cup: '\u222a', cap: '\u2229', setminus: '\u2216', wedge: '\u2227', land: '\u2227', vee: '\u2228', lor: '\u2228', neg: '\u00ac', lnot: '\u00ac', forall: '\u2200', exists: '\u2203', ldots: '\u2026', cdots: '\u22ef', vdots: '\u22ee', ddots: '\u22f1', dots: '\u2026', prime: '\u2032', perp: '\u22a5', parallel: '\u2225', angle: '\u2220', oplus: '\u2295', otimes: '\u2297', langle: '\u27e8', rangle: '\u27e9', lfloor: '\u230a', rfloor: '\u230b', lceil: '\u2308', rceil: '\u2309', vert: '|', mid: '|', lbrace: '{', rbrace: '}' };
219 const LARGE = { sum: '\u2211', prod: '\u220f', coprod: '\u2210', int: '\u222b', iint: '\u222c', iiint: '\u222d', oint: '\u222e', bigcup: '\u22c3', bigcap: '\u22c2' };
220 const FUNCS = 'sin cos tan cot sec csc arcsin arccos arctan sinh cosh tanh coth log ln lg exp det dim ker deg gcd lcm max min sup inf lim liminf limsup arg Pr mod'.split(' ');
221 const LIMITS = ['sum', 'prod', 'coprod', 'bigcup', 'bigcap', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'inf'];
222 const SPACES = { ',': '0.1667em', ':': '0.2222em', ';': '0.2778em', '!': '-0.1667em', ' ': '0.25em', quad: '1em', qquad: '2em' };
223 const BB = { C: '\u2102', H: '\u210d', N: '\u2115', P: '\u2119', Q: '\u211a', R: '\u211d', Z: '\u2124' };
224 const FENCES = { '(': '(', ')': ')', '[': '[', ']': ']', '|': '|', '.': '', '\\{': '{', '\\}': '}', '\\langle': '\u27e8', '\\rangle': '\u27e9', '\\lvert': '|', '\\rvert': '|', '\\|': '\u2016', '\\lfloor': '\u230a', '\\rfloor': '\u230b', '\\lceil': '\u2308', '\\rceil': '\u2309' };
225 function mml(tag, children, attrs) {
226 const node = document.createElementNS(MATH_NS, tag);
227 if (attrs) for (const k of Object.keys(attrs)) node.setAttribute(k, attrs[k]);
228 if (typeof children === 'string') node.textContent = children;
229 else if (children) node.append(...children);
230 return node;
231 }
232 function texTokens(src) {
233 const out = [];
234 const re = /\\([A-Za-z]+|.)|(\d+(?:\.\d+)?)|(\s+)|([\s\S])/g;
235 let m;
236 while ((m = re.exec(src)) !== null) {
237 if (out.length > 4096) throw new Error('too long');
238 if (m[3]) continue;
239 out.push(m[1] !== undefined ? { t: 'cmd', v: m[1] } : m[2] !== undefined ? { t: 'num', v: m[2] } : { t: 'chr', v: m[4] });
240 }
241 return out;
242 }
243 function texParse(src) {
244 const toks = texTokens(src);
245 let at = 0;
246 let depth = 0;
247 const peek = () => toks[at];
248 const take = () => toks[at++];
249 const fail = what => { throw new Error(what); };
250 function group() {
251 const t = peek();
252 if (!t) fail('missing argument');
253 if (t.t === 'chr' && t.v === '{') {
254 take();
255 const row = seq('}');
256 if (!peek() || peek().v !== '}') fail('unclosed brace');
257 take();
258 return row;
259 }
260 return atom(true);
261 }
262 function raw() {
263 const t = take();
264 if (!t || t.t !== 'chr' || t.v !== '{') fail('expected a braced argument');
265 let text = '';
266 let level = 1;
267 for (;;) {
268 const n = take();
269 if (!n) fail('unclosed brace');
270 if (n.t === 'chr' && n.v === '{') level += 1;
271 if (n.t === 'chr' && n.v === '}') {
272 level -= 1;
273 if (level === 0) return text;
274 }
275 text += n.t === 'cmd' ? (n.v.length === 1 ? n.v : `\\${n.v} `) : n.v;
276 }
277 }
278 function fence() {
279 const t = take();
280 if (!t) fail('missing delimiter');
281 const key = t.t === 'cmd' ? `\\${t.v}` : t.v;
282 if (!own(FENCES, key)) fail(`delimiter ${key}`);
283 return FENCES[key];
284 }
285 function atom(single) {
286 const t = take();
287 if (!t) fail('missing argument');
288 if (t.t === 'num') {
289 if (single && t.v.length > 1) {
290 at -= 1;
291 toks[at] = { t: 'num', v: t.v.slice(1) };
292 return mml('mn', t.v[0]);
293 }
294 return mml('mn', t.v);
295 }
296 if (t.t === 'chr') {
297 if (/[A-Za-z]/.test(t.v)) return mml('mi', t.v);
298 if (t.v === '{' && !single) {
299 at -= 1;
300 return group();
301 }
302 if (t.v === "'") return mml('mo', '\u2032');
303 if (t.v === '-') return mml('mo', '\u2212');
304 if ('+=<>()[]|,;:!/*.?'.includes(t.v)) return mml('mo', t.v, '()[]|'.includes(t.v) ? { stretchy: 'false' } : undefined);
305 fail(`character ${t.v}`);
306 }
307 const c = t.v;
308 if (own(GREEK, c)) return mml('mi', GREEK[c], /^[A-Z]/.test(c) ? { mathvariant: 'normal' } : undefined);
309 if (own(IDENT, c)) return mml('mi', IDENT[c]);
310 if (own(OPS, c)) return mml('mo', OPS[c]);
311 if (own(LARGE, c)) return mml('mo', LARGE[c], LIMITS.includes(c) ? { largeop: 'true', movablelimits: 'true' } : { largeop: 'true' });
312 if (FUNCS.includes(c)) return mml('mi', c, { mathvariant: 'normal' });
313 if (own(SPACES, c)) return mml('mspace', null, { width: SPACES[c] });
314 if (c === '{' || c === '}' || c === '%' || c === '$' || c === '#' || c === '_' || c === '&') return mml('mo', c);
315 if (c === 'frac' || c === 'dfrac' || c === 'tfrac') return mml('mfrac', [group(), group()]);
316 if (c === 'binom') return mml('mrow', [mml('mo', '('), mml('mfrac', [group(), group()], { linethickness: '0' }), mml('mo', ')')]);
317 if (c === 'sqrt') {
318 if (peek() && peek().t === 'chr' && peek().v === '[') {
319 take();
320 const index = seq(']');
321 if (!peek() || peek().v !== ']') fail('unclosed root index');
322 take();
323 return mml('mroot', [group(), index]);
324 }
325 return mml('msqrt', [group()]);
326 }
327 if (c === 'text' || c === 'textrm' || c === 'mathrm' || c === 'operatorname') {
328 const text = raw();
329 return c === 'text' || c === 'textrm' ? mml('mtext', text) : mml('mi', text, { mathvariant: 'normal' });
330 }
331 if (c === 'mathbb') {
332 const letter = raw().trim();
333 if (!own(BB, letter)) fail(`mathbb ${letter}`);
334 return mml('mi', BB[letter]);
335 }
336 if (c === 'left') {
337 const open = fence();
338 const inner = seq('right');
339 const close = peek();
340 if (!close || close.t !== 'cmd' || close.v !== 'right') fail('left without right');
341 take();
342 const shut = fence();
343 return mml('mrow', [mml('mo', open, { fence: 'true', stretchy: 'true' }), inner, mml('mo', shut, { fence: 'true', stretchy: 'true' })]);
344 }
345 return fail(`\\${c}`);
346 }
347 function scripted(base) {
348 let sub = null;
349 let sup = null;
350 for (let i = 0; i < 2; i++) {
351 const t = peek();
352 if (!t || t.t !== 'chr' || (t.v !== '_' && t.v !== '^')) break;
353 take();
354 if (t.v === '_') {
355 if (sub) fail('double subscript');
356 sub = group();
357 } else {
358 if (sup) fail('double superscript');
359 sup = group();
360 }
361 }
362 if (!sub && !sup) return base;
363 const under = (base.localName === 'mo' && base.getAttribute('movablelimits') === 'true') || (base.localName === 'mi' && LIMITS.includes(base.textContent));
364 if (sub && sup) return mml(under ? 'munderover' : 'msubsup', [base, sub, sup]);
365 if (sub) return mml(under ? 'munder' : 'msub', [base, sub]);
366 return mml(under ? 'mover' : 'msup', [base, sup]);
367 }
368 function seq(stop) {
369 depth += 1;
370 if (depth > 32) fail('nested too deeply');
371 const items = [];
372 while (at < toks.length) {
373 const t = peek();
374 if (stop === 'right' ? t.t === 'cmd' && t.v === 'right' : t.t === 'chr' && t.v === stop) break;
375 if (t.t === 'chr' && (t.v === '}' || t.v === ']') && stop === null) fail('unbalanced');
376 if (t.t === 'chr' && (t.v === '^' || t.v === '_')) {
377 items.push(scripted(mml('mrow', [])));
378 continue;
379 }
380 items.push(scripted(atom(false)));
381 }
382 depth -= 1;
383 return items.length === 1 ? items[0] : mml('mrow', items);
384 }
385 const tree = seq(null);
386 if (at !== toks.length) fail('trailing input');
387 return tree;
388 }
389 /* Returns a math element, or null with the reason when the TeX is outside
390 the subset or the browser has no MathML. */
391 function typeset(src, display) {
392 if (typeof window.MathMLElement !== 'function') return { node: null, reason: 'this browser does not lay out MathML' };
393 try {
394 const tree = texParse(src);
395 const semantics = mml('semantics', [tree, mml('annotation', src, { encoding: 'application/x-tex' })]);
396 return { node: mml('math', [semantics], { display: display ? 'block' : 'inline' }), reason: '' };
397 } catch (error) {
398 return { node: null, reason: `it uses ${String(error && error.message).slice(0, 80)}, which this renderer does not typeset` };
399 }
400 }
401 function texBlock(src, label) {
402 const box = el('div', 'allen-tex');
403 const done = typeset(src, true);
404 if (done.node) {
405 box.append(done.node, el('p', 'allen-pane-label', `${label} typeset in this page from TeX by a small first-party renderer; the source is below.`));
406 } else {
407 box.append(el('p', 'allen-pane-label', `${label} as TeX source, not typeset: ${done.reason}.`));
408 }
409 const pre = el('pre', 'allen-pane-pre', src);
410 pre.setAttribute('aria-label', 'TeX source');
411 box.append(pre);
412 return box;
413 }
414
415 /* Markdown subset rendered to DOM nodes only: headings, paragraphs, lists,
416 quotes, rules, fenced code, pipe tables, inline code, strong, emphasis,
417 HTTPS links and $ TeX. Raw HTML stays text. */
418 function inline(node, text) {
419 const re = /(`+)([^`][\s\S]*?)\1|\*\*([^*\n]+)\*\*|\*([^*\s][^*\n]*)\*|\[([^\]\n]{1,500})\]\(([^)\s]{1,2048})\)|\$([^$\n]{1,500})\$|(https:\/\/[^\s<>()]{1,2048})/g;
420 let last = 0;
421 let m;
422 while ((m = re.exec(text)) !== null) {
423 if (m.index > last) node.append(document.createTextNode(text.slice(last, m.index)));
424 if (m[1]) node.append(el('code', 'allen-md-code', m[2]));
425 else if (m[3] !== undefined) node.append(el('strong', '', m[3]));
426 else if (m[4] !== undefined) node.append(el('em', '', m[4]));
427 else if (m[5] !== undefined) node.append(link(m[5], m[6]));
428 else if (m[7] !== undefined) {
429 const done = typeset(m[7], false);
430 if (done.node) node.append(done.node);
431 else {
432 const raw = el('code', 'allen-md-tex', `$${m[7]}$`);
433 raw.title = 'TeX source, not typeset';
434 node.append(raw);
435 }
436 } else {
437 const url = m[8].replace(/[.,;:!?]+$/, '');
438 node.append(link(url, url));
439 if (url.length < m[8].length) node.append(document.createTextNode(m[8].slice(url.length)));
440 }
441 last = re.lastIndex;
442 }
443 if (last < text.length) node.append(document.createTextNode(text.slice(last)));
444 return node;
445 }
446 function cells(line) {
447 return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(s => s.trim());
448 }
449 /* A repo report's files, found by the same parser that renders the pane,
450 so a fence the reader saw is exactly a fence that is saved. */
451 const REPORT = /^Repo report: ([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/;
452 function reportFiles(source) {
453 const files = [{ path: 'README.md', content: source }];
454 const patches = [];
455 let port = 0;
456 let harness = 0;
457 markdown(source, document.createElement('div'), (lang, text) => {
458 const kind = lang.toLowerCase();
459 if (kind === 'omega' || kind === 'om') files.push({ path: `allen-port-${(port += 1)}.om`, content: `${text}\n` });
460 else if (kind === 'diff' || kind === 'patch') patches.push(`${text}\n`);
461 else if (kind === 'text' || kind === 'txt') files.push({ path: `parity-harness-${(harness += 1)}.txt`, content: `${text}\n` });
462 return null;
463 });
464 if (patches.length) files.push({ path: 'allen-ports.patch', content: patches.join('') });
465 return files;
466 }
467 function markdown(source, box, fenceTool) {
468 const lines = source.split(/\r?\n/);
469 let para = [];
470 let list = null;
471 const flush = () => {
472 if (para.length) box.append(inline(el('p', 'allen-md-p'), para.join(' ')));
473 para = [];
474 };
475 for (let i = 0; i < lines.length; i++) {
476 const line = lines[i];
477 const fence = /^\s*(```+)\s*([A-Za-z0-9_+-]{0,32})\s*$/.exec(line);
478 if (fence) {
479 flush();
480 list = null;
481 const body = [];
482 for (i += 1; i < lines.length && !lines[i].trim().startsWith(fence[1]); i++) body.push(lines[i]);
483 const pre = el('pre', 'allen-md-pre');
484 if (fence[2]) pre.dataset.lang = fence[2];
485 pre.append(el('code', '', body.join('\n')));
486 box.append(pre);
487 const tool = fenceTool ? fenceTool(fence[2], body.join('\n')) : null;
488 if (tool) box.append(tool);
489 continue;
490 }
491 if (/^\s*\$\$/.test(line)) {
492 flush();
493 list = null;
494 const body = [line.replace(/^\s*\$\$/, '')];
495 let closed = /\$\$\s*$/.test(body[0]) && body[0].trim().length > 2;
496 if (closed) body[0] = body[0].replace(/\$\$\s*$/, '');
497 if (!closed) for (i += 1; i < lines.length; i++) {
498 if (/\$\$\s*$/.test(lines[i])) {
499 body.push(lines[i].replace(/\$\$\s*$/, ''));
500 closed = true;
501 break;
502 }
503 body.push(lines[i]);
504 }
505 box.append(texBlock(body.join('\n').trim(), 'Formula'));
506 continue;
507 }
508 if (!line.trim()) {
509 flush();
510 list = null;
511 continue;
512 }
513 const heading = /^\s*(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
514 if (heading) {
515 flush();
516 list = null;
517 box.append(inline(el(`h${Math.min(6, heading[1].length + 2)}`, 'allen-md-h'), heading[2]));
518 continue;
519 }
520 if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) {
521 flush();
522 list = null;
523 box.append(el('hr', 'allen-md-hr'));
524 continue;
525 }
526 if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(lines[i + 1])) {
527 flush();
528 list = null;
529 const table = el('table', 'allen-md-table');
530 const head = el('tr');
531 for (const c of cells(line)) head.append(inline(el('th'), c));
532 const thead = el('thead');
533 thead.append(head);
534 const tbody = el('tbody');
535 for (i += 2; i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i]); i++) {
536 const row = el('tr');
537 for (const c of cells(lines[i])) row.append(inline(el('td'), c));
538 tbody.append(row);
539 }
540 i -= 1;
541 table.append(thead, tbody);
542 const wrap = el('div', 'allen-pane-table');
543 wrap.append(table);
544 box.append(wrap);
545 continue;
546 }
547 const quote = /^\s*>\s?(.*)$/.exec(line);
548 if (quote) {
549 flush();
550 list = null;
551 const parts = [quote[1]];
552 while (i + 1 < lines.length && /^\s*>/.test(lines[i + 1])) parts.push(lines[++i].replace(/^\s*>\s?/, ''));
553 const block = el('blockquote', 'allen-md-quote');
554 block.append(inline(el('p', 'allen-md-p'), parts.join(' ')));
555 box.append(block);
556 continue;
557 }
558 const item = /^\s*([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(line);
559 if (item) {
560 flush();
561 const ordered = /\d/.test(item[1]);
562 if (!list || (list.localName === 'ol') !== ordered) {
563 list = el(ordered ? 'ol' : 'ul', 'allen-md-list');
564 box.append(list);
565 }
566 list.append(inline(el('li'), item[2]));
567 continue;
568 }
569 if (list && /^\s{2,}\S/.test(line)) {
570 inline(list.lastElementChild, ` ${line.trim()}`);
571 continue;
572 }
573 list = null;
574 para.push(line.trim());
575 }
576 flush();
577 return box;
578 }
579
580 /* Plots are drawn here from validated numbers; no SVG from the network is
581 ever parsed. Colours are attributes so an exported file keeps them. */
582 function svg(tag, attrs, text) {
583 const node = document.createElementNS(SVG_NS, tag);
584 for (const k of Object.keys(attrs)) node.setAttribute(k, String(attrs[k]));
585 if (text !== undefined) node.textContent = text;
586 return node;
587 }
588 function fmt(n) {
589 const v = Number(n.toPrecision(5));
590 return Object.is(v, -0) ? '0' : String(v);
591 }
592 function ticks(lo, hi) {
593 const raw = (hi - lo) / 5;
594 if (!Number.isFinite(raw) || raw <= 0) return [lo, hi];
595 const mag = Math.pow(10, Math.floor(Math.log10(raw)));
596 const unit = [1, 2, 5, 10].map(f => f * mag).find(s => s >= raw) || raw;
597 const first = Math.ceil(lo / unit);
598 const out = [];
599 for (let n = 0; n < 12; n++) {
600 const t = (first + n) * unit;
601 if (t > hi + unit * 1e-9) break;
602 out.push(t);
603 }
604 return out.length ? out : [lo, hi];
605 }
606 function extent(c) {
607 let x0 = Infinity;
608 let x1 = -Infinity;
609 let y0 = Infinity;
610 let y1 = -Infinity;
611 for (const s of c.series) for (const p of s.points) {
612 x0 = Math.min(x0, p[0]);
613 x1 = Math.max(x1, p[0]);
614 y0 = Math.min(y0, p[1]);
615 y1 = Math.max(y1, p[1]);
616 }
617 if (x0 === x1) {
618 x0 -= 1;
619 x1 += 1;
620 }
621 if (y0 === y1) {
622 y0 -= 1;
623 y1 += 1;
624 }
625 return { x0, x1, y0, y1 };
626 }
627 function plot(c, title) {
628 const W = 640;
629 const H = 400;
630 const L = 64;
631 const R = 20;
632 const T = 20;
633 const B = 52;
634 const e = extent(c);
635 const sx = v => L + (v - e.x0) / (e.x1 - e.x0) * (W - L - R);
636 const sy = v => H - B - (v - e.y0) / (e.y1 - e.y0) * (H - T - B);
637 const titleId = uid('allen-plot-title');
638 const descId = uid('allen-plot-desc');
639 const root = svg('svg', { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: 'img', 'aria-labelledby': `${titleId} ${descId}`, class: 'allen-plot-svg' });
640 const xl = c.x_label ? ` (${c.x_label})` : '';
641 const yl = c.y_label ? ` (${c.y_label})` : '';
642 root.append(svg('title', { id: titleId }, title), svg('desc', { id: descId }, `${c.series.length} series; x${xl} from ${fmt(e.x0)} to ${fmt(e.x1)}; y${yl} from ${fmt(e.y0)} to ${fmt(e.y1)}.`));
643 const grid = svg('g', { stroke: '#1c2536', 'stroke-width': 1 });
644 const labels = svg('g', { fill: '#94a3b8', 'font-size': 12, 'font-family': 'ui-sans-serif, system-ui, sans-serif' });
645 for (const t of ticks(e.x0, e.x1)) {
646 const x = sx(t).toFixed(2);
647 grid.append(svg('line', { x1: x, y1: T, x2: x, y2: H - B }));
648 labels.append(svg('text', { x, y: H - B + 18, 'text-anchor': 'middle' }, fmt(t)));
649 }
650 for (const t of ticks(e.y0, e.y1)) {
651 const y = sy(t).toFixed(2);
652 grid.append(svg('line', { x1: L, y1: y, x2: W - R, y2: y }));
653 labels.append(svg('text', { x: L - 8, y: (Number(y) + 4).toFixed(2), 'text-anchor': 'end' }, fmt(t)));
654 }
655 const axes = svg('g', { stroke: '#3b4a63', 'stroke-width': 1 });
656 axes.append(svg('line', { x1: L, y1: H - B, x2: W - R, y2: H - B }), svg('line', { x1: L, y1: T, x2: L, y2: H - B }));
657 if (c.x_label) labels.append(svg('text', { x: (L + W - R) / 2, y: H - 12, 'text-anchor': 'middle' }, c.x_label));
658 if (c.y_label) {
659 const mid = (T + H - B) / 2;
660 labels.append(svg('text', { x: 16, y: mid, 'text-anchor': 'middle', transform: `rotate(-90 16 ${mid})` }, c.y_label));
661 }
662 const lines = svg('g', { fill: 'none', 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' });
663 c.series.forEach((s, i) => {
664 const colour = PALETTE[i % PALETTE.length];
665 const group = svg('g', { stroke: colour });
666 group.append(svg('title', {}, s.label || `Series ${i + 1}`));
667 if (s.points.length > 1) group.append(svg('polyline', { points: s.points.map(p => `${sx(p[0]).toFixed(2)},${sy(p[1]).toFixed(2)}`).join(' ') }));
668 if (s.points.length <= 64) for (const p of s.points) group.append(svg('circle', { cx: sx(p[0]).toFixed(2), cy: sy(p[1]).toFixed(2), r: 3, fill: colour, stroke: 'none' }));
669 lines.append(group);
670 });
671 root.append(grid, axes, lines, labels);
672 const figure = el('figure', 'allen-plot');
673 figure.append(root);
674 const legend = el('ul', 'allen-plot-legend');
675 c.series.forEach((s, i) => {
676 const item = el('li', 'allen-plot-key');
677 const swatch = el('span', 'allen-plot-swatch');
678 swatch.style.background = PALETTE[i % PALETTE.length];
679 swatch.setAttribute('aria-hidden', 'true');
680 item.append(swatch, document.createTextNode(`${s.label || `Series ${i + 1}`}, ${s.points.length} point${s.points.length === 1 ? '' : 's'}`));
681 legend.append(item);
682 });
683 figure.append(legend);
684 const data = el('details', 'allen-plot-data');
685 data.append(el('summary', 'allen-pane-summary', 'Plot data as a table'));
686 data.addEventListener('toggle', () => {
687 if (!data.open || data.dataset.built) return;
688 data.dataset.built = 'yes';
689 data.append(table(['Series', c.x_label || 'x', c.y_label || 'y'], c.series.flatMap((s, i) => s.points.map(p => [s.label || `Series ${i + 1}`, String(p[0]), String(p[1])]))));
690 });
691 figure.append(data);
692 return { figure, svg: root };
693 }
694 function table(columns, rows) {
695 const wrap = el('div', 'allen-pane-table');
696 wrap.tabIndex = 0;
697 const node = el('table', 'allen-data');
698 const head = el('tr');
699 for (const c of columns) {
700 const th = el('th', '', c);
701 th.scope = 'col';
702 head.append(th);
703 }
704 const thead = el('thead');
705 thead.append(head);
706 const tbody = el('tbody');
707 for (const r of rows) {
708 const tr = el('tr');
709 for (let i = 0; i < Math.max(r.length, columns.length); i++) tr.append(el('td', '', i < r.length ? r[i] : ''));
710 tbody.append(tr);
711 }
712 node.append(thead, tbody);
713 wrap.append(node);
714 return wrap;
715 }
716
717 /* Files. Every download is application/octet-stream, so no browser renders
718 a generated file in this origin. */
719 function csv(columns, rows) {
720 const cell = v => {
721 let s = String(v);
722 if (/^[=+@\t\r]/.test(s) || /^-(?![\d.])/.test(s)) s = `'${s}`;
723 return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
724 };
725 return `${[columns, ...rows].map(r => r.map(cell).join(',')).join('\r\n')}\r\n`;
726 }
727 function refText(items) {
728 return items.map((r, i) => `${i + 1}. [${r.title}](${r.url})`).join('\n');
729 }
730 function artefact(rec) {
731 const c = rec.content;
732 const base = slug(rec.title) || rec.kind;
733 switch (rec.kind) {
734 case 'math': {
735 const text = own(c, 'tex') ? `${c.text}\n\nTeX source:\n${c.tex}\n` : `${c.text}\n`;
736 return { name: `${base}.txt`, what: 'result', data: () => text, copy: c.text };
737 }
738 case 'plot': {
739 const rows = c.series.flatMap((s, i) => s.points.map(p => [s.label || `Series ${i + 1}`, String(p[0]), String(p[1])]));
740 return { name: `${base}.svg`, what: 'data as CSV', data: () => `<?xml version="1.0" encoding="UTF-8"?>\n${new XMLSerializer().serializeToString(rec.svg)}\n`, copy: csv(['series', c.x_label || 'x', c.y_label || 'y'], rows) };
741 }
742 case 'doc': {
743 const text = c.citations.length ? `${c.markdown}\n\n## Citations\n\n${refText(c.citations)}\n` : `${c.markdown}\n`;
744 return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };
745 }
746 case 'code':
747 case 'omega': {
748 const ext = rec.kind === 'omega' ? 'om' : EXT[c.language.toLowerCase()] || 'txt';
749 return { name: `${base}.${ext}`, what: 'source', data: () => c.source, copy: c.source };
750 }
751 case 'app':
752 return { name: `${base}.html`, what: 'HTML', data: () => c.html, copy: c.html };
753 case 'research': {
754 const parts = [`# ${rec.title}`, '## Notes', c.notes];
755 if (c.hypotheses.length) parts.push('## Hypotheses', c.hypotheses.map(h => `- ${h}`).join('\n'));
756 if (c.derivations.length) parts.push('## Derivations', c.derivations.map(d => `\`\`\`\n${d}\n\`\`\``).join('\n\n'));
757 if (c.sources.length) parts.push('## Sources', refText(c.sources));
758 const text = `${parts.join('\n\n')}\n`;
759 return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };
760 }
761 case 'data': {
762 const text = csv(c.columns, c.rows);
763 return { name: `${base}.csv`, what: 'CSV', data: () => text, copy: text };
764 }
765 default:
766 return null;
767 }
768 }
769 function wasmBytes(text) {
770 try {
771 const bin = atob(text.replace(/\s+/g, ''));
772 const out = new Uint8Array(bin.length);
773 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
774 return out.length >= 8 && out[0] === 0 && out[1] === 97 && out[2] === 115 && out[3] === 109 ? out : null;
775 } catch (_) {
776 return null;
777 }
778 }
779 async function copyText(source, node) {
780 if (node.dataset.label === undefined) node.dataset.label = node.textContent;
781 try {
782 await navigator.clipboard.writeText(source);
783 node.textContent = 'Copied';
784 } catch (_) {
785 node.textContent = 'Copy blocked';
786 }
787 setTimeout(() => {
788 node.textContent = node.dataset.label;
789 }, 1500);
790 }
791 /* The policy becomes the first element of the program's head, as in the
792 chat client: after an existing head tag, else in a head of its own. The
793 prefix (doctype, comments, html tag) is skipped one sticky token at a
794 time and a comment body never holds its closing marker, so the scan is
795 linear in the source. */
796 function sandboxed(source) {
797 const meta = `<meta http-equiv="Content-Security-Policy" content="${CSP}">`;
798 const prefix = /\s*(?:<!doctype[^>]*>|<!--(?:[^-]|-(?!->))*-->|<html(?:\s[^>]*)?>)/iy;
799 let at = 0;
800 while (prefix.exec(source)) at = prefix.lastIndex;
801 const head = /\s*<head(?:\s[^>]*)?>/iy;
802 head.lastIndex = at;
803 if (head.exec(source)) return source.slice(0, head.lastIndex) + meta + source.slice(head.lastIndex);
804 const lead = /^\s*(?:<!doctype[^>]*>\s*)?(?:<html(?:\s[^>]*)?>)?/i.exec(source)[0];
805 return `${lead}<head>${meta}</head>${source.slice(lead.length)}`;
806 }
807
808 /* Project files and IndexedDB records share one format. */
809 function checkEntry(p) {
810 if (!shape(p, ['id', 'kind', 'title', 'revision', 'content', 'provenance'], ['geom', 'minimized'])) return 'unexpected or missing fields';
811 let reason = check('pane.open', { v: VERSION, id: p.id, kind: p.kind, title: p.title });
812 if (!reason) reason = check('pane.update', { v: VERSION, id: p.id, revision: p.revision, content: p.content, provenance: p.provenance }, p.kind);
813 if (reason) return reason;
814 if (own(p, 'geom') && !(shape(p.geom, ['x', 'y', 'w', 'h']) && ['x', 'y', 'w', 'h'].every(k => finite(p.geom[k])))) return 'invalid geometry';
815 if (own(p, 'minimized') && typeof p.minimized !== 'boolean') return 'invalid minimized flag';
816 return '';
817 }
818 function checkFile(data) {
819 if (!shape(data, ['format', 'v', 'panes'], ['id', 'name', 'saved', 'exported']) || data.format !== FORMAT || data.v !== VERSION) return 'this is not an Aien panes file';
820 for (const k of ['id', 'name', 'saved', 'exported']) if (own(data, k) && !isText(data[k], MAX_TITLE)) return `invalid ${k}`;
821 if (!Array.isArray(data.panes) || data.panes.length > MAX_PANES) return `a file holds at most ${MAX_PANES} panes`;
822 for (let i = 0; i < data.panes.length; i++) {
823 const reason = checkEntry(data.panes[i]);
824 if (reason) return `pane ${i + 1}: ${reason}`;
825 }
826 return '';
827 }
828 function limit(message) {
829 const error = new Error(message);
830 error.name = 'AllenLimit';
831 return error;
832 }
833 function storageError(error) {
834 const name = error && error.name;
835 if (name === 'AllenLimit') return error.message;
836 if (name === 'QuotaExceededError') return 'This browser refused: it has no storage space left for this site. Export the panes as a file instead.';
837 if (name === 'SecurityError' || name === 'InvalidStateError' || name === 'AllenNoStore') return 'This browser does not allow storage here, for example in private browsing. Export the panes as a file instead.';
838 const detail = error && error.message ? ` (${clean(error.message, 160)})` : '';
839 return `This browser refused to store the project${detail}. Export the panes as a file instead.`;
840 }
841 function openDb() {
842 return new Promise((resolve, reject) => {
843 let request;
844 try {
845 if (!window.indexedDB) throw Object.assign(new Error('no IndexedDB'), { name: 'AllenNoStore' });
846 request = window.indexedDB.open(DB_NAME, 1);
847 } catch (error) {
848 reject(error);
849 return;
850 }
851 request.onupgradeneeded = () => {
852 const db = request.result;
853 if (!db.objectStoreNames.contains(DB_PROJECTS)) db.createObjectStore(DB_PROJECTS, { keyPath: 'id' });
854 if (!db.objectStoreNames.contains(DB_INDEX)) db.createObjectStore(DB_INDEX, { keyPath: 'id' });
855 };
856 request.onsuccess = () => {
857 const db = request.result;
858 db.onversionchange = () => db.close();
859 resolve(db);
860 };
861 request.onerror = () => reject(request.error || new Error('IndexedDB refused'));
862 request.onblocked = () => reject(new Error('another tab holds the project store open'));
863 });
864 }
865 function ask(request) {
866 return new Promise((resolve, reject) => {
867 request.onsuccess = () => resolve(request.result);
868 request.onerror = () => reject(request.error);
869 });
870 }
871 async function store(mode, work) {
872 const db = await openDb();
873 try {
874 const tx = db.transaction([DB_PROJECTS, DB_INDEX], mode);
875 const done = new Promise((resolve, reject) => {
876 tx.oncomplete = () => resolve();
877 tx.onabort = () => reject(tx.error || new Error('the storage transaction was aborted'));
878 });
879 let value;
880 try {
881 value = await work(tx.objectStore(DB_PROJECTS), tx.objectStore(DB_INDEX));
882 } catch (error) {
883 try {
884 tx.abort();
885 } catch (_) {}
886 await done.catch(() => {});
887 throw error;
888 }
889 await done;
890 return value;
891 } finally {
892 db.close();
893 }
894 }
895 function stamp(iso) {
896 const when = new Date(iso);
897 return Number.isNaN(when.getTime()) ? String(iso) : when.toLocaleString();
898 }
899
900 function mount(host, options) {
901 if (!(host instanceof Element)) throw new TypeError('AllenPanes.mount needs an element');
902 const opts = options && typeof options === 'object' ? options : {};
903 const panes = new Map();
904 const closedIds = new Set();
905 const closed = [];
906 let order = [];
907 let cascade = 0;
908 let current = null;
909 let alive = true;
910 let fitting = 0;
911 const root = el('div', 'allen-panes');
912 const layer = el('div', 'allen-panes-layer');
913 const dock = el('nav', 'allen-panes-dock');
914 dock.setAttribute('aria-label', 'Aien panes');
915 const chips = el('ul', 'allen-panes-chips');
916 const projectsButton = button('allen-panes-tool', 'Projects: save, open, export or import panes', 'Projects', () => projectsPane());
917 const exportButton = button('allen-panes-tool', 'Export the open panes as a JSON file', 'Export', () => exportOpen());
918 const reopenButton = button('allen-panes-tool', '', 'Reopen', () => reopen());
919 reopenButton.hidden = true;
920 dock.append(chips, projectsButton, exportButton, reopenButton);
921 const live = el('p', 'allen-panes-live');
922 live.setAttribute('role', 'status');
923 live.setAttribute('aria-live', 'polite');
924 root.append(layer, dock, live);
925 host.append(root);
926 const media = typeof window.matchMedia === 'function' ? window.matchMedia(SHEET) : null;
927
928 function say(message) {
929 live.textContent = '';
930 setTimeout(() => {
931 if (alive) live.textContent = message;
932 }, 60);
933 if (typeof opts.announce === 'function') {
934 try {
935 opts.announce(message);
936 } catch (_) {}
937 }
938 }
939 function refuse(name, reason) {
940 if (typeof opts.onRefuse === 'function') {
941 try {
942 opts.onRefuse(name, reason);
943 } catch (_) {}
944 }
945 return { ok: false, reason };
946 }
947 function sheet() {
948 return root.dataset.layout === 'sheet';
949 }
950 function layout() {
951 root.dataset.layout = media && media.matches ? 'sheet' : 'float';
952 refit();
953 }
954 function bounds() {
955 return { w: Math.max(root.clientWidth, MIN_W), h: Math.max(root.clientHeight, MIN_H) };
956 }
957 function place(rec, x, y, w, h) {
958 const b = bounds();
959 const nw = Math.round(Math.min(Math.max(w, MIN_W), b.w));
960 const nh = Math.round(Math.min(Math.max(h, MIN_H), b.h));
961 const nx = Math.round(Math.min(Math.max(x, 0), b.w - nw));
962 const ny = Math.round(Math.min(Math.max(y, 0), b.h - nh));
963 rec.geom = { x: nx, y: ny, w: nw, h: nh };
964 rec.el.style.transform = `translate(${nx}px, ${ny}px)`;
965 rec.el.style.width = `${nw}px`;
966 rec.el.style.height = `${nh}px`;
967 }
968 function refit() {
969 for (const rec of panes.values()) place(rec, rec.geom.x, rec.geom.y, rec.geom.w, rec.geom.h);
970 }
971 function onResize() {
972 if (!fitting) fitting = requestAnimationFrame(() => {
973 fitting = 0;
974 if (alive) refit();
975 });
976 }
977 function initial(rec) {
978 const b = bounds();
979 const w = Math.min(560, b.w - 32);
980 const h = Math.min(460, b.h - 160);
981 const step = (cascade % 6) * 28;
982 cascade += 1;
983 place(rec, b.w - w - 32 - step, 76 + step, w, h);
984 }
985 function topmost() {
986 for (let i = order.length - 1; i >= 0; i--) if (!order[i].minimized) return order[i];
987 return null;
988 }
989 function chipState(rec) {
990 rec.chipTitle.textContent = rec.title;
991 rec.chip.setAttribute('aria-label', `${rec.title}, ${NAMES[rec.kind]} pane, ${rec.minimized ? 'minimized' : 'open'}`);
992 rec.chip.dataset.state = rec.minimized ? 'minimized' : 'open';
993 }
994 function stack() {
995 const top = topmost();
996 order.forEach((rec, i) => {
997 rec.el.style.zIndex = String(i + 1);
998 rec.el.toggleAttribute('data-top', rec === top);
999 rec.chip.toggleAttribute('data-top', rec === top);
1000 });
1001 dock.dataset.empty = panes.size ? 'no' : 'yes';
1002 }
1003 function raise(rec) {
1004 if (order[order.length - 1] !== rec) {
1005 order = order.filter(r => r !== rec);
1006 order.push(rec);
1007 }
1008 stack();
1009 }
1010 function owner(node) {
1011 for (const rec of panes.values()) if (rec.el.contains(node)) return rec;
1012 return null;
1013 }
1014 function label(rec) {
1015 rec.heading.textContent = rec.title;
1016 rec.move.setAttribute('aria-label', `Move ${rec.title}. Drag, or use the arrow keys; Shift moves farther.`);
1017 rec.size.setAttribute('aria-label', `Resize ${rec.title}. Drag, or use the arrow keys; Shift resizes farther.`);
1018 rec.min.setAttribute('aria-label', `Minimize ${rec.title}`);
1019 rec.max.setAttribute('aria-label', `Maximize ${rec.title}`);
1020 rec.max.setAttribute('aria-pressed', String(rec.maximized));
1021 rec.shut.setAttribute('aria-label', `Close ${rec.title}`);
1022 rec.grab.setAttribute('aria-label', `Minimize ${rec.title}. On a touch screen, swipe the top of the sheet down to minimize, or sideways for the next pane.`);
1023 chipState(rec);
1024 }
1025 function create(key, kind, title) {
1026 const rec = { id: key, kind, title: clean(title, MAX_TITLE) || NAMES[kind], revision: 0, content: null, provenance: null, geom: null, minimized: false, maximized: false, svg: null, app: null, projects: null };
1027 const pane = el('section', 'allen-pane');
1028 pane.dataset.kind = kind;
1029 pane.tabIndex = -1;
1030 pane.setAttribute('role', 'region');
1031 pane.setAttribute('aria-roledescription', 'pane');
1032 const head = el('header', 'allen-pane-head');
1033 const heading = el('h2', 'allen-pane-title');
1034 heading.id = uid('allen-pane-title');
1035 pane.setAttribute('aria-labelledby', heading.id);
1036 const move = button('allen-pane-move', '', '', null);
1037 const badge = el('span', 'allen-pane-badge');
1038 badge.hidden = true;
1039 const controls = el('div', 'allen-pane-controls');
1040 const min = button('allen-pane-ctl allen-pane-min', '', '\u2212', () => minimize(rec));
1041 const max = button('allen-pane-ctl allen-pane-max', '', '\u25a1', () => maximize(rec));
1042 const shut = button('allen-pane-ctl allen-pane-close', '', '\u00d7', () => close(rec, true));
1043 controls.append(min, max, shut);
1044 head.append(move, el('span', 'allen-pane-kind', NAMES[kind]), heading, badge, controls);
1045 const notice = el('p', 'allen-pane-notice');
1046 notice.setAttribute('role', 'alert');
1047 notice.hidden = true;
1048 const body = el('div', 'allen-pane-body');
1049 body.tabIndex = 0;
1050 const source = el('details', 'allen-pane-source');
1051 source.hidden = true;
1052 const foot = el('div', 'allen-pane-foot');
1053 foot.hidden = true;
1054 const size = button('allen-pane-size', '', '', null);
1055 const grab = button('allen-pane-grab', '', '', () => minimize(rec));
1056 pane.append(grab, head, notice, body, source, foot, size);
1057 const item = el('li', 'allen-panes-item');
1058 const chip = button('allen-panes-chip', '', '', () => chipClick(rec));
1059 const chipTitle = el('span', 'allen-panes-chip-title');
1060 chip.append(el('span', 'allen-panes-chip-kind', NAMES[kind]), chipTitle);
1061 item.append(chip);
1062 Object.assign(rec, { el: pane, heading, badge, notice, body, source, foot, move, size, grab, min, max, shut, item, chip, chipTitle, swallow: 0 });
1063 label(rec);
1064 pane.addEventListener('pointerdown', () => raise(rec), true);
1065 pane.addEventListener('focusin', () => raise(rec));
1066 drag(rec, head, 'move');
1067 swipe(rec, head);
1068 swipe(rec, grab);
1069 pane.addEventListener('click', event => {
1070 if (event.timeStamp > rec.swallow) return;
1071 rec.swallow = 0;
1072 event.preventDefault();
1073 event.stopPropagation();
1074 }, true);
1075 drag(rec, size, 'size');
1076 keyed(rec, move, 'move');
1077 keyed(rec, size, 'size');
1078 layer.append(pane);
1079 chips.append(item);
1080 panes.set(key, rec);
1081 order.push(rec);
1082 initial(rec);
1083 stack();
1084 return rec;
1085 }
1086 /* Bottom sheet gestures, only on the grab strip and the title bar, so the
1087 content keeps its own scrolling, selection and editing. Down past a
1088 quarter of the sheet (or a quick flick) minimizes; sideways shows the
1089 neighbouring pane. A swipe never reaches the button it started on. */
1090 function swipe(rec, zone) {
1091 zone.addEventListener('pointerdown', event => {
1092 if (!sheet() || !event.isPrimary || event.button !== 0) return;
1093 const start = { x: event.clientX, y: event.clientY, t: event.timeStamp };
1094 const height = Math.max(1, rec.el.getBoundingClientRect().height);
1095 let mode = '';
1096 let last = event;
1097 let frame = 0;
1098 const paint = () => {
1099 frame = 0;
1100 if (!alive || !mode) return;
1101 const dx = last.clientX - start.x;
1102 const dy = last.clientY - start.y;
1103 rec.el.style.setProperty('--allen-pane-swipe-x', mode === 'side' ? `${Math.round(dx / 2)}px` : '0px');
1104 rec.el.style.setProperty('--allen-pane-swipe-y', mode === 'down' ? `${Math.round(Math.max(0, dy))}px` : '0px');
1105 };
1106 const settle = () => {
1107 rec.el.classList.remove('is-swiping');
1108 rec.el.style.removeProperty('--allen-pane-swipe-x');
1109 rec.el.style.removeProperty('--allen-pane-swipe-y');
1110 };
1111 const onMove = e => {
1112 if (e.pointerId !== event.pointerId) return;
1113 last = e;
1114 const dx = e.clientX - start.x;
1115 const dy = e.clientY - start.y;
1116 if (!mode) {
1117 if (Math.abs(dx) < 10 && Math.abs(dy) < 10) return;
1118 mode = Math.abs(dy) >= Math.abs(dx) ? (dy > 0 ? 'down' : 'up') : 'side';
1119 try {
1120 zone.setPointerCapture(e.pointerId);
1121 } catch (_) {}
1122 rec.el.classList.add('is-swiping');
1123 }
1124 if (mode !== 'up' && !frame) frame = requestAnimationFrame(paint);
1125 };
1126 const onEnd = e => {
1127 if (e.pointerId !== event.pointerId) return;
1128 zone.removeEventListener('pointermove', onMove);
1129 zone.removeEventListener('pointerup', onEnd);
1130 zone.removeEventListener('pointercancel', onEnd);
1131 if (frame) cancelAnimationFrame(frame);
1132 frame = 0;
1133 settle();
1134 if (!mode) return;
1135 rec.swallow = e.timeStamp + 500;
1136 if (e.type === 'pointercancel' || !alive) return;
1137 const dx = e.clientX - start.x;
1138 const dy = e.clientY - start.y;
1139 const speed = Math.max(Math.abs(dx), Math.abs(dy)) / Math.max(1, e.timeStamp - start.t);
1140 if (mode === 'down' && (dy > height / 4 || (dy > 24 && speed > 0.6))) minimize(rec);
1141 else if (mode === 'side' && (Math.abs(dx) > 72 || (Math.abs(dx) > 24 && speed > 0.6))) neighbour(rec, dx < 0 ? 1 : -1);
1142 };
1143 zone.addEventListener('pointermove', onMove);
1144 zone.addEventListener('pointerup', onEnd);
1145 zone.addEventListener('pointercancel', onEnd);
1146 });
1147 }
1148 function neighbour(rec, dir) {
1149 const all = [...panes.values()];
1150 if (all.length < 2) return;
1151 const next = all[(all.indexOf(rec) + dir + all.length) % all.length];
1152 const had = rec.el.contains(document.activeElement);
1153 restore(next, had);
1154 say(`${next.title}, pane ${all.indexOf(next) + 1} of ${all.length}.`);
1155 }
1156 function drag(rec, handle, mode) {
1157 handle.addEventListener('pointerdown', event => {
1158 if (event.button !== 0 || sheet() || rec.maximized) return;
1159 const hit = event.target.closest('button');
1160 if (mode === 'move' && hit && hit !== rec.move) return;
1161 event.preventDefault();
1162 raise(rec);
1163 const start = { x: event.clientX, y: event.clientY, g: { ...rec.geom } };
1164 let frame = 0;
1165 let last = null;
1166 try {
1167 handle.setPointerCapture(event.pointerId);
1168 } catch (_) {}
1169 rec.el.classList.add(mode === 'move' ? 'is-moving' : 'is-sizing');
1170 const apply = () => {
1171 frame = 0;
1172 if (!last || !alive) return;
1173 const dx = last.clientX - start.x;
1174 const dy = last.clientY - start.y;
1175 if (mode === 'move') place(rec, start.g.x + dx, start.g.y + dy, start.g.w, start.g.h);
1176 else place(rec, start.g.x, start.g.y, start.g.w + dx, start.g.h + dy);
1177 };
1178 const onMove = e => {
1179 if (e.pointerId !== event.pointerId) return;
1180 last = e;
1181 if (!frame) frame = requestAnimationFrame(apply);
1182 };
1183 const onUp = e => {
1184 if (e.pointerId !== event.pointerId) return;
1185 handle.removeEventListener('pointermove', onMove);
1186 handle.removeEventListener('pointerup', onUp);
1187 handle.removeEventListener('pointercancel', onUp);
1188 if (frame) cancelAnimationFrame(frame);
1189 apply();
1190 rec.el.classList.remove('is-moving', 'is-sizing');
1191 };
1192 handle.addEventListener('pointermove', onMove);
1193 handle.addEventListener('pointerup', onUp);
1194 handle.addEventListener('pointercancel', onUp);
1195 });
1196 }
1197 function keyed(rec, handle, mode) {
1198 handle.addEventListener('keydown', event => {
1199 const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];
1200 if (!d || event.altKey || event.ctrlKey || event.metaKey || sheet() || rec.maximized) return;
1201 event.preventDefault();
1202 const s = event.shiftKey ? BIG_STEP : STEP;
1203 const g = rec.geom;
1204 if (mode === 'move') place(rec, g.x + d[0] * s, g.y + d[1] * s, g.w, g.h);
1205 else place(rec, g.x, g.y, g.w + d[0] * s, g.h + d[1] * s);
1206 });
1207 handle.addEventListener('keyup', event => {
1208 if (!event.key.startsWith('Arrow') || sheet() || rec.maximized) return;
1209 const g = rec.geom;
1210 say(mode === 'move' ? `${rec.title} at ${g.x}, ${g.y}.` : `${rec.title} is ${g.w} by ${g.h}.`);
1211 });
1212 }
1213 function minimize(rec) {
1214 if (rec.minimized) return;
1215 const had = rec.el.contains(document.activeElement);
1216 rec.minimized = true;
1217 rec.el.hidden = true;
1218 chipState(rec);
1219 stack();
1220 if (had) rec.chip.focus();
1221 say(`${rec.title} minimized; it stays in the pane list.`);
1222 }
1223 function restore(rec, focus) {
1224 if (rec.minimized) {
1225 rec.minimized = false;
1226 rec.el.hidden = false;
1227 chipState(rec);
1228 }
1229 raise(rec);
1230 if (focus) rec.el.focus({ preventScroll: true });
1231 }
1232 function maximize(rec) {
1233 rec.maximized = !rec.maximized;
1234 rec.el.classList.toggle('is-max', rec.maximized);
1235 label(rec);
1236 raise(rec);
1237 }
1238 function chipClick(rec) {
1239 if (rec.minimized) restore(rec, true);
1240 else if (topmost() === rec) minimize(rec);
1241 else restore(rec, true);
1242 }
1243 function dataPane(rec) {
1244 return KINDS.includes(rec.kind) && rec.revision > 0;
1245 }
1246 function entry(rec) {
1247 return { id: rec.id, kind: rec.kind, title: rec.title, revision: rec.revision, content: copy(rec.content), provenance: copy(rec.provenance), geom: { ...rec.geom }, minimized: rec.minimized };
1248 }
1249 function reopenState() {
1250 const last = closed[closed.length - 1];
1251 reopenButton.hidden = !last;
1252 if (last) reopenButton.setAttribute('aria-label', `Reopen ${last.title}`);
1253 }
1254 function close(rec, byPerson, quiet) {
1255 if (panes.get(rec.id) !== rec) return;
1256 const had = rec.el.contains(document.activeElement);
1257 stopApp(rec);
1258 rec.el.remove();
1259 rec.item.remove();
1260 panes.delete(rec.id);
1261 order = order.filter(r => r !== rec);
1262 const kept = dataPane(rec);
1263 if (kept) {
1264 closed.push(entry(rec));
1265 while (closed.length > MAX_CLOSED) closed.shift();
1266 }
1267 reopenState();
1268 stack();
1269 if (had) {
1270 const next = topmost();
1271 if (next) next.el.focus({ preventScroll: true });
1272 else if (opts.returnFocus instanceof HTMLElement && opts.returnFocus.isConnected) opts.returnFocus.focus();
1273 else projectsButton.focus();
1274 }
1275 if (!quiet) say(byPerson ? `${rec.title} closed.${kept ? ' Reopen brings it back.' : ''}` : `Aien closed ${rec.title}.`);
1276 if (typeof opts.onClose === 'function') {
1277 try {
1278 opts.onClose(rec.kind === 'card' ? rec.id.slice(5) : rec.id, rec.kind, byPerson);
1279 } catch (_) {}
1280 }
1281 }
1282 function reopen() {
1283 const last = closed.pop();
1284 reopenState();
1285 if (!last) return;
1286 const rec = restoreEntry(last);
1287 if (rec) {
1288 rec.el.focus({ preventScroll: true });
1289 say(`${rec.title} reopened.`);
1290 } else {
1291 closed.push(last);
1292 reopenState();
1293 say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);
1294 }
1295 }
1296 function notify(rec, message) {
1297 rec.notice.textContent = message;
1298 rec.notice.hidden = false;
1299 }
1300 function waiting(rec) {
1301 rec.el.setAttribute('aria-busy', 'true');
1302 rec.body.replaceChildren(el('p', 'allen-pane-note', 'Aien is preparing this pane.'));
1303 }
1304
1305 function apply(rec, revision, content, prov) {
1306 stopApp(rec);
1307 rec.revision = revision;
1308 rec.content = copy(content);
1309 rec.provenance = copy(prov);
1310 rec.svg = null;
1311 rec.notice.hidden = true;
1312 rec.el.removeAttribute('aria-busy');
1313 rec.body.replaceChildren();
1314 render(rec);
1315 rec.badge.textContent = STATUS_NAMES[rec.provenance.status];
1316 rec.badge.dataset.status = rec.provenance.status;
1317 rec.badge.hidden = false;
1318 sourceBlock(rec);
1319 footBlock(rec);
1320 }
1321 function section(heading) {
1322 const box = el('section', 'allen-pane-section');
1323 box.append(el('h3', 'allen-pane-h3', heading));
1324 return box;
1325 }
1326 function refList(heading, items) {
1327 const box = section(heading);
1328 const list = el('ol', 'allen-pane-refs');
1329 for (const r of items) {
1330 const li = el('li');
1331 li.append(link(r.title, r.url));
1332 list.append(li);
1333 }
1334 box.append(list, el('p', 'allen-pane-label', 'Links are shown as given; this page never fetched or checked them.'));
1335 return box;
1336 }
1337 /* A diff or patch fence gets its own Copy and Download patch. The patch
1338 is only ever a downloaded file; nothing here applies it. */
1339 function patchTool(rec) {
1340 let n = 0;
1341 return (lang, text) => {
1342 if (!/^(diff|patch)$/i.test(lang) || !text.trim()) return null;
1343 n += 1;
1344 const name = `${slug(rec.title) || 'allen'}${n > 1 ? `-${n}` : ''}.patch`;
1345 const bar = el('div', 'allen-pane-bar allen-md-tools');
1346 const copyButton = button('allen-pane-act', `Copy patch ${n} of ${rec.title}`, 'Copy patch', () => copyText(`${text}\n`, copyButton));
1347 bar.append(copyButton, button('allen-pane-act', `Download patch ${n} of ${rec.title} as ${name}; it is not applied anywhere`, 'Download patch', () => download(name, `${text}\n`)));
1348 return bar;
1349 };
1350 }
1351 function render(rec) {
1352 const c = rec.content;
1353 const body = rec.body;
1354 body.append(el('p', 'allen-pane-caveat', CAVEATS[rec.provenance.status]));
1355 if (rec.kind === 'math') {
1356 const result = el('p', 'allen-pane-math', c.text);
1357 result.setAttribute('aria-label', `Result: ${c.text}`);
1358 body.append(result);
1359 if (own(c, 'tex')) body.append(texBlock(c.tex, 'The engine\u2019s formula'));
1360 } else if (rec.kind === 'plot') {
1361 const drawn = plot(c, rec.title);
1362 rec.svg = drawn.svg;
1363 body.append(drawn.figure);
1364 } else if (rec.kind === 'doc') {
1365 body.append(markdown(c.markdown, el('div', 'allen-md'), patchTool(rec)));
1366 if (c.citations.length) body.append(refList('Citations', c.citations));
1367 } else if (rec.kind === 'code' || rec.kind === 'omega') {
1368 body.append(el('p', 'allen-pane-label', rec.kind === 'omega' ? 'Omega source' : `${clean(c.language, 40) || 'Code'} source`));
1369 const pre = el('pre', 'allen-pane-code');
1370 pre.append(el('code', '', c.source));
1371 body.append(pre);
1372 if (own(c, 'functions') && c.functions.length) {
1373 const box = section('Functions');
1374 const list = el('ul', 'allen-pane-fns');
1375 for (const f of c.functions) list.append(el('li', 'allen-pane-mono', `${f.name}(${f.params.map(p => `${p.name} ${p.type}`).join(', ')}) to ${f.ret}`));
1376 box.append(list);
1377 body.append(box);
1378 }
1379 if (own(c, 'wasm')) {
1380 const bytes = wasmBytes(c.wasm);
1381 const box = section('WebAssembly');
1382 if (bytes) {
1383 box.append(el('p', 'allen-pane-note', `${bytes.length} bytes. Offered as a file only; this page does not run it.`), button('allen-pane-act', `Download the WebAssembly of ${rec.title}`, 'Download .wasm', () => download(`${slug(rec.title) || 'omega'}.wasm`, bytes)));
1384 } else {
1385 box.append(el('p', 'allen-pane-note', 'WebAssembly was attached, but it is not a valid base64 WebAssembly module.'));
1386 }
1387 body.append(box);
1388 }
1389 } else if (rec.kind === 'app') {
1390 body.append(el('p', 'allen-pane-note', 'Aien wrote this app. It runs only when you press Run, in a sandbox with no access to this page, your cookies or the network.'));
1391 const bar = el('div', 'allen-pane-bar');
1392 const stage = el('div', 'allen-pane-stage');
1393 const run = button('allen-pane-act allen-pane-run', `Run ${rec.title} in a sandbox`, 'Run', () => runApp(rec, stage, run, stop));
1394 const stop = button('allen-pane-act', `Stop ${rec.title}`, 'Stop', () => stopApp(rec));
1395 stop.hidden = true;
1396 bar.append(run, stop);
1397 body.append(bar, stage);
1398 rec.app = { frame: null, run, stop };
1399 } else if (rec.kind === 'research') {
1400 const notes = section('Notes');
1401 notes.append(markdown(c.notes, el('div', 'allen-md'), patchTool(rec)));
1402 body.append(notes);
1403 if (c.hypotheses.length) {
1404 const box = section('Hypotheses');
1405 const list = el('ul', 'allen-md-list');
1406 for (const h of c.hypotheses) list.append(inline(el('li'), h));
1407 box.append(list);
1408 body.append(box);
1409 }
1410 if (c.derivations.length) {
1411 const box = section('Derivations');
1412 const list = el('ol', 'allen-pane-derivations');
1413 for (const d of c.derivations) {
1414 const li = el('li');
1415 li.append(el('pre', 'allen-pane-pre', d));
1416 list.append(li);
1417 }
1418 box.append(list);
1419 body.append(box);
1420 }
1421 if (c.sources.length) body.append(refList('Sources', c.sources));
1422 } else if (rec.kind === 'data') {
1423 const grid = table(c.columns, c.rows);
1424 grid.firstChild.setAttribute('aria-labelledby', rec.heading.id);
1425 body.append(grid);
1426 }
1427 }
1428 function runApp(rec, stage, run, stop) {
1429 stopApp(rec);
1430 const frame = document.createElement('iframe');
1431 frame.setAttribute('sandbox', SANDBOX);
1432 frame.setAttribute('referrerpolicy', 'no-referrer');
1433 frame.setAttribute('allow', "camera 'none'; microphone 'none'; geolocation 'none'; usb 'none'; serial 'none'; bluetooth 'none'; payment 'none'; display-capture 'none'; clipboard-read 'none'; clipboard-write 'none'; fullscreen 'none'");
1434 frame.setAttribute('title', `${rec.title}, an app written by Aien, sandboxed`);
1435 frame.className = 'allen-pane-frame';
1436 /* A srcdoc frame would inherit the page policy, which forbids inline
1437 scripts; /aien/run.html writes what this page posts, sandboxed. */
1438 const html = sandboxed(rec.content.html);
1439 frame.addEventListener('load', () => frame.contentWindow.postMessage(html, '*'), { once: true });
1440 frame.src = '/aien/run.html';
1441 stage.replaceChildren(frame);
1442 rec.app = { frame, run, stop };
1443 run.hidden = true;
1444 stop.hidden = false;
1445 stop.focus();
1446 }
1447 function stopApp(rec) {
1448 if (!rec.app || !rec.app.frame) return;
1449 const hadFocus = rec.el.contains(document.activeElement);
1450 rec.app.frame.remove();
1451 rec.app.frame = null;
1452 rec.app.run.hidden = false;
1453 rec.app.stop.hidden = true;
1454 if (hadFocus && rec.app.run.isConnected) rec.app.run.focus();
1455 }
1456 function sourceBlock(rec) {
1457 const list = el('dl', 'allen-pane-prov');
1458 const row = (key, value, mono) => {
1459 if (value === '') return;
1460 list.append(el('dt', '', key), el('dd', mono ? 'allen-pane-mono' : '', value));
1461 };
1462 const p = rec.provenance;
1463 row('Status', STATUS_NAMES[p.status]);
1464 row('Engine', p.engine);
1465 row('Expression', p.expression, true);
1466 row('Result', p.result, true);
1467 row('Source', p.source);
1468 row('Commit', p.commit, true);
1469 row('Pane', rec.id, true);
1470 row('Revision', String(rec.revision));
1471 const raw = el('pre', 'allen-pane-raw', JSON.stringify({ content: rec.content, provenance: rec.provenance }, null, 2));
1472 raw.setAttribute('aria-label', `Everything Aien sent for ${rec.title}, as JSON`);
1473 raw.tabIndex = 0;
1474 rec.source.replaceChildren(el('summary', 'allen-pane-summary', 'Source and provenance'), list, el('p', 'allen-pane-label', 'As received'), raw);
1475 rec.source.hidden = false;
1476 }
1477 function footBlock(rec) {
1478 const out = artefact(rec);
1479 if (!out) return;
1480 const base = slug(rec.title) || rec.kind;
1481 const ext = out.name.slice(out.name.lastIndexOf('.'));
1482 const copyButton = button('allen-pane-act', `Copy the ${out.what} of ${rec.title}`, 'Copy', () => copyText(out.copy, copyButton));
1483 const save = button('allen-pane-act', `Download ${rec.title} as ${ext}`, `Download ${ext}`, () => download(out.name, out.data()));
1484 const json = button('allen-pane-act', `Download ${rec.title} with its provenance as JSON`, 'Download .json', () => download(`${base}.json`, JSON.stringify(file([entry(rec)], rec.title), null, 2)));
1485 rec.foot.replaceChildren(copyButton, save, json);
1486 const keep = reportSave(rec);
1487 if (keep) rec.foot.append(...keep);
1488 rec.foot.hidden = false;
1489 }
1490 /* A repo report can become the visitor's own Omega project, only when the
1491 page supplies saveProject and only after the visitor has seen the file
1492 list and pressed Save. The page owns the request and the visitor's
1493 handle; this file never touches the network. */
1494 function reportSave(rec) {
1495 if (rec.kind !== 'doc' || typeof opts.saveProject !== 'function') return null;
1496 const named = REPORT.exec(rec.title);
1497 if (!named) return null;
1498 const files = reportFiles(rec.content.markdown);
1499 const repo = `${named[1]}/${named[2]}`;
1500 const ports = files.filter(f => f.path.endsWith('.om')).length;
1501 const box = el('div', 'allen-pane-save');
1502 box.hidden = true;
1503 const state = el('p', 'allen-projects-state');
1504 state.setAttribute('role', 'status');
1505 const open = button('allen-pane-act allen-pane-run', `Save ${rec.title} to my Omega projects`, 'Save to my Omega projects', () => {
1506 box.hidden = !box.hidden;
1507 open.setAttribute('aria-expanded', String(!box.hidden));
1508 if (!box.hidden) confirm.focus();
1509 });
1510 open.setAttribute('aria-expanded', 'false');
1511 const list = el('ul', 'allen-pane-files');
1512 for (const f of files) list.append(el('li', 'allen-pane-mono', `${f.path}, ${utf8(f.content)} bytes`));
1513 const confirm = button('allen-pane-act allen-pane-run', `Save these ${files.length} files as an Omega project`, `Save ${files.length} file${files.length === 1 ? '' : 's'}`, async () => {
1514 confirm.disabled = true;
1515 state.replaceChildren(document.createTextNode('Saving.'));
1516 let r;
1517 try {
1518 r = await opts.saveProject({ project: slug(`${named[1]}-${named[2]}`) || 'allen-report', title: `Omega path for ${repo}`, description: `Aien's report on ${repo}${ports ? `, with ${ports} Omega port${ports === 1 ? '' : 's'}` : ''}.`, files: files.map(f => ({ path: f.path, content: f.content })) });
1519 } catch (_) {
1520 r = null;
1521 }
1522 confirm.disabled = false;
1523 if (r && r.ok === true) {
1524 state.replaceChildren(document.createTextNode('Saved. Status: '), statusLink(r.url));
1525 } else {
1526 state.replaceChildren(document.createTextNode(r && typeof r.reason === 'string' ? clean(r.reason, 300) : 'The project could not be saved; nothing was stored.'));
1527 }
1528 });
1529 const cancel = button('allen-pane-act', 'Do not save the report', 'Cancel', () => {
1530 box.hidden = true;
1531 open.setAttribute('aria-expanded', 'false');
1532 open.focus();
1533 });
1534 const bar = el('div', 'allen-pane-bar');
1535 bar.append(confirm, cancel);
1536 box.append(el('p', 'allen-pane-note', `These files become a project under your handle in Omega projects, for Drake to review before anything is published:`), list, bar);
1537 return [open, box, state];
1538 }
1539 function statusLink(url) {
1540 if (typeof url !== 'string' || !url) return document.createTextNode('no status address was returned.');
1541 if (/^\/(?!\/)/.test(url)) {
1542 try {
1543 const here = new URL(url, window.location.href);
1544 if (here.origin === window.location.origin) {
1545 const a = el('a', 'allen-link', here.pathname + here.search);
1546 a.href = here.href;
1547 return a;
1548 }
1549 } catch (_) {}
1550 }
1551 return link(url, url);
1552 }
1553 function download(name, data) {
1554 const blob = new Blob([data], { type: 'application/octet-stream' });
1555 const url = URL.createObjectURL(blob);
1556 const a = document.createElement('a');
1557 a.href = url;
1558 a.download = name;
1559 a.hidden = true;
1560 root.append(a);
1561 a.click();
1562 a.remove();
1563 setTimeout(() => URL.revokeObjectURL(url), 30000);
1564 }
1565 function file(entries, name) {
1566 return { format: FORMAT, v: VERSION, name: clean(name || 'Aien panes', MAX_NAME), exported: new Date().toISOString(), panes: entries };
1567 }
1568 function snapshot() {
1569 return order.filter(dataPane).map(entry);
1570 }
1571 function exportOpen() {
1572 const entries = snapshot();
1573 if (!entries.length) {
1574 say('There are no panes with content to export yet.');
1575 return { ok: false, reason: 'nothing to export' };
1576 }
1577 download('aien-panes.json', JSON.stringify(file(entries, current ? current.name : 'Aien panes'), null, 2));
1578 say(`Exported ${entries.length} pane${entries.length === 1 ? '' : 's'} as a JSON file.`);
1579 return { ok: true, count: entries.length };
1580 }
1581 function restoreEntry(p) {
1582 if (panes.size >= MAX_PANES) return null;
1583 let key = p.id;
1584 for (let n = 2; panes.has(key) && n < 100; n++) key = `${p.id.slice(0, 58)}-${n}`;
1585 if (panes.has(key)) return null;
1586 const rec = create(key, p.kind, p.title);
1587 apply(rec, p.revision, p.content, p.provenance);
1588 if (p.geom) place(rec, p.geom.x, p.geom.y, p.geom.w, p.geom.h);
1589 if (p.minimized) {
1590 rec.minimized = true;
1591 rec.el.hidden = true;
1592 chipState(rec);
1593 }
1594 stack();
1595 return rec;
1596 }
1597 function restoreAll(data) {
1598 const room = MAX_PANES - panes.size;
1599 if (data.panes.length > room) return { ok: false, reason: `Only ${room} more pane${room === 1 ? '' : 's'} fit; close some panes first.` };
1600 for (const p of data.panes) restoreEntry(p);
1601 return { ok: true, count: data.panes.length };
1602 }
1603
1604 /* Projects: IndexedDB only after an explicit save; an index store keeps
1605 the list cheap to read. */
1606 async function list() {
1607 try {
1608 const items = await store('readonly', (_, index) => ask(index.getAll()));
1609 items.sort((a, b) => String(b.saved).localeCompare(String(a.saved)));
1610 return { ok: true, projects: items.map(i => ({ id: i.id, name: i.name, saved: i.saved, count: i.count })) };
1611 } catch (error) {
1612 return { ok: false, reason: storageError(error) };
1613 }
1614 }
1615 async function save(name) {
1616 const entries = snapshot();
1617 if (!entries.length) return { ok: false, reason: 'There are no panes with content to save yet.' };
1618 const title = clean(name || '', MAX_NAME) || (current ? current.name : `Project ${new Date().toLocaleString()}`);
1619 const id = current && current.name === title ? current.id : `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
1620 const record = { format: FORMAT, v: VERSION, id, name: title, saved: new Date().toISOString(), panes: entries };
1621 const bytes = utf8(JSON.stringify(record));
1622 if (bytes > MAX_PROJECT_BYTES) return { ok: false, reason: `This project is ${bytes} bytes; one project holds at most ${MAX_PROJECT_BYTES}. Export it as a file instead.` };
1623 try {
1624 await store('readwrite', async (projects, index) => {
1625 const existing = await ask(index.get(id));
1626 const count = await ask(index.count());
1627 if (!existing && count >= MAX_PROJECTS) throw limit(`${MAX_PROJECTS} projects are saved in this browser; delete one first, or export instead.`);
1628 await ask(projects.put(record));
1629 await ask(index.put({ id, name: title, saved: record.saved, count: entries.length }));
1630 });
1631 } catch (error) {
1632 return { ok: false, reason: storageError(error) };
1633 }
1634 current = { id, name: title };
1635 return { ok: true, id, name: title, count: entries.length };
1636 }
1637 async function load(id) {
1638 let record;
1639 try {
1640 record = await store('readonly', projects => ask(projects.get(String(id))));
1641 } catch (error) {
1642 return { ok: false, reason: storageError(error) };
1643 }
1644 if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };
1645 const reason = checkFile(record);
1646 if (reason) return { ok: false, reason: `The saved project could not be read: ${reason}.` };
1647 const done = restoreAll(record);
1648 if (done.ok) current = { id: record.id, name: record.name };
1649 return done.ok ? { ok: true, id: record.id, name: record.name, count: done.count } : done;
1650 }
1651 async function remove(id) {
1652 try {
1653 await store('readwrite', (projects, index) => Promise.all([ask(projects.delete(String(id))), ask(index.delete(String(id)))]));
1654 } catch (error) {
1655 return { ok: false, reason: storageError(error) };
1656 }
1657 if (current && current.id === id) current = null;
1658 return { ok: true, id };
1659 }
1660 async function exportSaved(id) {
1661 let record;
1662 try {
1663 record = await store('readonly', projects => ask(projects.get(String(id))));
1664 } catch (error) {
1665 return { ok: false, reason: storageError(error) };
1666 }
1667 if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };
1668 download(`${slug(record.name) || 'allen-project'}.json`, JSON.stringify(record, null, 2));
1669 return { ok: true, id };
1670 }
1671 async function importFile(source) {
1672 let text;
1673 if (typeof source === 'string') text = source;
1674 else if (source && typeof source.text === 'function' && typeof source.size === 'number') {
1675 if (source.size > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };
1676 try {
1677 text = await source.text();
1678 } catch (_) {
1679 return { ok: false, reason: 'This browser could not read the file.' };
1680 }
1681 } else return { ok: false, reason: 'Import takes a project file or its JSON text.' };
1682 if (utf8(text) > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };
1683 let data;
1684 try {
1685 data = JSON.parse(text);
1686 } catch (_) {
1687 return { ok: false, reason: 'That file is not JSON.' };
1688 }
1689 const reason = checkFile(data);
1690 if (reason) return { ok: false, reason: `That file was refused: ${reason}.` };
1691 return restoreAll(data);
1692 }
1693 function project(command, arg) {
1694 if (!alive) return Promise.resolve({ ok: false, reason: 'unmounted' });
1695 if (command === 'save') return save(arg);
1696 if (command === 'list') return list();
1697 if (command === 'open') return load(arg);
1698 if (command === 'remove') return remove(arg);
1699 if (command === 'export') return arg === undefined ? Promise.resolve(exportOpen()) : exportSaved(arg);
1700 if (command === 'import') return importFile(arg);
1701 if (command === undefined || command === 'panel') {
1702 projectsPane();
1703 return Promise.resolve({ ok: true });
1704 }
1705 return Promise.resolve({ ok: false, reason: 'unknown project command' });
1706 }
1707 function projectsPane() {
1708 let rec = panes.get('#projects');
1709 if (rec) {
1710 restore(rec, true);
1711 refreshProjects(rec);
1712 return;
1713 }
1714 if (panes.size >= MAX_PANES) {
1715 say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);
1716 return;
1717 }
1718 rec = create('#projects', 'projects', 'Projects');
1719 const body = rec.body;
1720 const status = el('p', 'allen-projects-state');
1721 status.setAttribute('role', 'status');
1722 const show = r => {
1723 status.textContent = r.ok ? r.message : r.reason;
1724 };
1725 const form = el('form', 'allen-projects-form');
1726 const nameId = uid('allen-project-name');
1727 const nameLabel = el('label', 'allen-pane-label', 'Project name');
1728 nameLabel.htmlFor = nameId;
1729 const input = el('input', 'allen-projects-name');
1730 input.id = nameId;
1731 input.type = 'text';
1732 input.maxLength = MAX_NAME;
1733 input.autocomplete = 'off';
1734 input.value = current ? current.name : '';
1735 const submit = el('button', 'allen-pane-act allen-pane-run', 'Save project');
1736 submit.type = 'submit';
1737 form.append(nameLabel, input, submit);
1738 form.addEventListener('submit', async event => {
1739 event.preventDefault();
1740 submit.disabled = true;
1741 const r = await save(input.value);
1742 submit.disabled = false;
1743 show(r.ok ? { ok: true, message: `Saved ${r.name} with ${r.count} pane${r.count === 1 ? '' : 's'} in this browser.` } : r);
1744 if (r.ok) {
1745 input.value = r.name;
1746 refreshProjects(rec);
1747 }
1748 });
1749 const saved = el('ul', 'allen-projects-list');
1750 const fileId = uid('allen-project-file');
1751 const fileLabel = el('label', 'allen-pane-label', 'Import a project file (.json)');
1752 fileLabel.htmlFor = fileId;
1753 const picker = el('input', 'allen-projects-file');
1754 picker.id = fileId;
1755 picker.type = 'file';
1756 picker.accept = 'application/json,.json';
1757 picker.addEventListener('change', async () => {
1758 const chosen = picker.files && picker.files[0];
1759 picker.value = '';
1760 if (!chosen) return;
1761 const r = await importFile(chosen);
1762 show(r.ok ? { ok: true, message: `Imported ${r.count} pane${r.count === 1 ? '' : 's'}. Nothing is stored until you press Save project.` } : r);
1763 });
1764 const exporter = button('allen-pane-act', 'Export the open panes as a JSON file', 'Export open panes', () => {
1765 const r = exportOpen();
1766 show(r.ok ? { ok: true, message: `Exported ${r.count} pane${r.count === 1 ? '' : 's'}.` } : { ok: false, reason: 'There are no panes with content to export yet.' });
1767 });
1768 const tools = el('div', 'allen-pane-bar');
1769 tools.append(exporter);
1770 const academy = el('p', 'allen-pane-note allen-projects-academy');
1771 academy.append(link('Train your agent', ACADEMY));
1772 body.append(el('p', 'allen-pane-note', 'Nothing is stored until you press Save project. A project keeps the open panes, their provenance and where they sit, in this browser only. Conversations are not part of a project.'), form, status, section('Saved in this browser'), saved, fileLabel, picker, tools, academy);
1773 if (typeof opts.syncSummary === 'function') body.append(summaryBox(show));
1774 rec.projects = { saved, show };
1775 refreshProjects(rec);
1776 rec.el.focus({ preventScroll: true });
1777 }
1778 /* Only when the page supplies syncSummary (a visitor with a remember key):
1779 a short summary the visitor reads and edits first, sent on one explicit
1780 click. Panes, code and data never leave the browser this way. */
1781 function draft() {
1782 const parts = snapshot().map(p => `${NAMES[p.kind]}: ${p.title}`);
1783 let text = `${current ? current.name : 'Project'}: ${parts.join('; ')}`;
1784 while (utf8(text) > SYNC_MAX) text = text.slice(0, -1);
1785 return text;
1786 }
1787 function summaryBox(show) {
1788 const box = section('Sync a short summary');
1789 const areaId = uid('allen-project-summary');
1790 const note = el('p', 'allen-pane-note', `Only this summary is sent, at most ${SYNC_MAX} bytes, never the panes, code or data. Aien keeps one project summary for you and replaces it each time. Edit it first if you like.`);
1791 const areaLabel = el('label', 'allen-pane-label', 'Summary to sync');
1792 areaLabel.htmlFor = areaId;
1793 const area = el('textarea', 'allen-projects-summary');
1794 area.id = areaId;
1795 area.rows = 3;
1796 area.value = draft();
1797 const count = el('p', 'allen-pane-label');
1798 const recount = () => {
1799 const n = utf8(area.value);
1800 count.textContent = `${n} of ${SYNC_MAX} bytes`;
1801 count.dataset.over = n > SYNC_MAX ? 'yes' : 'no';
1802 };
1803 area.addEventListener('input', recount);
1804 recount();
1805 const refresh = button('allen-pane-act', 'Write the summary again from the open panes', 'Draft again', () => {
1806 area.value = draft();
1807 recount();
1808 });
1809 const send = button('allen-pane-act allen-pane-run', 'Sync this short summary to Aien\u2019s memory of you', 'Sync short summary', async () => {
1810 const text = area.value.trim();
1811 if (!text) return show({ ok: false, reason: 'The summary is empty.' });
1812 if (utf8(text) > SYNC_MAX) return show({ ok: false, reason: `The summary is over ${SYNC_MAX} bytes.` });
1813 send.disabled = true;
1814 let r;
1815 try {
1816 r = await opts.syncSummary(text);
1817 } catch (_) {
1818 r = null;
1819 }
1820 send.disabled = false;
1821 show(r && r.ok === true ? { ok: true, message: 'Synced the summary. Aien replaced the previous one.' } : { ok: false, reason: r && typeof r.reason === 'string' ? clean(r.reason, 300) : 'Aien could not sync the summary; nothing was stored.' });
1822 });
1823 const bar = el('div', 'allen-pane-bar');
1824 bar.append(refresh, send);
1825 box.append(note, areaLabel, area, count, bar);
1826 return box;
1827 }
1828 async function refreshProjects(rec) {
1829 const ui = rec.projects;
1830 if (!ui) return;
1831 const r = await list();
1832 if (!r.ok) {
1833 ui.saved.replaceChildren(el('li', 'allen-pane-note', r.reason));
1834 return;
1835 }
1836 if (!r.projects.length) {
1837 ui.saved.replaceChildren(el('li', 'allen-pane-note', 'No projects are saved in this browser.'));
1838 return;
1839 }
1840 ui.saved.replaceChildren(...r.projects.map(p => projectRow(rec, p)));
1841 }
1842 function projectRow(rec, p) {
1843 const name = clean(p.name, MAX_NAME) || 'Untitled';
1844 const li = el('li', 'allen-projects-item');
1845 const text = el('div', 'allen-projects-text');
1846 text.append(el('span', 'allen-projects-title', name), el('span', 'allen-projects-meta', `${p.count} pane${p.count === 1 ? '' : 's'}, saved ${stamp(p.saved)}`));
1847 const acts = el('div', 'allen-pane-bar');
1848 const open = button('allen-pane-act', `Open project ${name}`, 'Open', async () => {
1849 const r = await load(p.id);
1850 rec.projects.show(r.ok ? { ok: true, message: `Opened ${r.name}.` } : r);
1851 });
1852 const out = button('allen-pane-act', `Export project ${name} as a JSON file`, 'Export', async () => {
1853 const r = await exportSaved(p.id);
1854 rec.projects.show(r.ok ? { ok: true, message: `Exported ${name}.` } : r);
1855 });
1856 const del = button('allen-pane-act allen-pane-danger', `Delete project ${name} from this browser`, 'Delete', async () => {
1857 if (del.dataset.armed !== 'yes') {
1858 del.dataset.armed = 'yes';
1859 del.textContent = 'Confirm delete';
1860 del.setAttribute('aria-label', `Confirm: delete project ${name} from this browser`);
1861 setTimeout(() => {
1862 if (!del.isConnected) return;
1863 del.dataset.armed = '';
1864 del.textContent = 'Delete';
1865 del.setAttribute('aria-label', `Delete project ${name} from this browser`);
1866 }, 5000);
1867 return;
1868 }
1869 const r = await remove(p.id);
1870 rec.projects.show(r.ok ? { ok: true, message: `Deleted ${name} from this browser.` } : r);
1871 refreshProjects(rec);
1872 if (rec.el.contains(document.activeElement) || !document.activeElement || document.activeElement === document.body) rec.el.focus({ preventScroll: true });
1873 });
1874 acts.append(open, out, del);
1875 li.append(text, acts);
1876 return li;
1877 }
1878
1879 /* The stream and the page call these. */
1880 function event(name, payload) {
1881 if (!alive) return { ok: false, reason: 'unmounted' };
1882 const id = plain(payload) && typeof payload.id === 'string' ? payload.id : '';
1883 const rec = ID.test(id) ? panes.get(id) : undefined;
1884 if (name === 'pane.close' && plain(payload) && !rec) {
1885 const bad = check(name, payload, '');
1886 if (bad) return refuse(name, bad);
1887 closedIds.add(id);
1888 return { ok: true, id };
1889 }
1890 if (name === 'pane.update' && !rec) return refuse(name, 'the pane is not open');
1891 const reason = check(name, payload, rec ? rec.kind : '');
1892 if (reason) {
1893 if (rec && name === 'pane.update') notify(rec, `Aien sent an update this page could not show (${reason}). The last good version stays.`);
1894 return refuse(name, reason);
1895 }
1896 if (name === 'pane.open') {
1897 if (rec || closedIds.has(id)) return refuse(name, 'that pane id was already opened');
1898 if (panes.size >= MAX_PANES) {
1899 say(`Aien tried to open another pane, but at most ${MAX_PANES} can be open. Close one to make room.`);
1900 return refuse(name, 'too many panes');
1901 }
1902 const made = create(id, payload.kind, payload.title);
1903 waiting(made);
1904 say(`Aien opened a ${NAMES[made.kind]} pane: ${made.title}.`);
1905 return { ok: true, id };
1906 }
1907 if (name === 'pane.update') {
1908 if (payload.revision <= rec.revision) return refuse(name, 'the revision is not newer');
1909 apply(rec, payload.revision, payload.content, payload.provenance);
1910 return { ok: true, id, revision: payload.revision };
1911 }
1912 closedIds.add(id);
1913 close(rec, false);
1914 return { ok: true, id };
1915 }
1916 function open(payload) {
1917 if (!plain(payload)) return refuse('open', 'open takes an object');
1918 const id = own(payload, 'id') ? payload.id : `local-${Date.now().toString(36)}${(serial += 1)}`;
1919 const opened = event('pane.open', { v: VERSION, id, kind: payload.kind, title: payload.title });
1920 if (!opened.ok || !own(payload, 'content')) return opened;
1921 const rec = panes.get(id);
1922 const prov = own(payload, 'provenance') ? payload.provenance : { status: 'unverified', engine: '', expression: '', result: '', source: 'this page', commit: '' };
1923 const updated = event('pane.update', { v: VERSION, id, revision: own(payload, 'revision') ? payload.revision : rec.revision + 1, content: payload.content, provenance: prov });
1924 if (!updated.ok) close(rec, false, true);
1925 return updated;
1926 }
1927 function openNode(spec) {
1928 if (!alive) return { ok: false, reason: 'unmounted' };
1929 const node = spec && spec.node;
1930 if (!(node instanceof Node) || node.nodeType === Node.DOCUMENT_NODE) return refuse('openNode', 'openNode takes a node built by this page');
1931 const id = spec && typeof spec.id === 'string' && ID.test(spec.id) ? spec.id : `card${(serial += 1)}`;
1932 const key = `card:${id}`;
1933 let rec = panes.get(key);
1934 if (!rec) {
1935 if (panes.size >= MAX_PANES) return refuse('openNode', 'too many panes');
1936 rec = create(key, 'card', typeof spec.title === 'string' ? spec.title : 'Aien');
1937 } else if (typeof spec.title === 'string') {
1938 rec.title = clean(spec.title, MAX_TITLE) || rec.title;
1939 label(rec);
1940 }
1941 rec.body.replaceChildren(node);
1942 restore(rec, spec.focus === true);
1943 return { ok: true, id, close: () => close(rec, false) };
1944 }
1945 function cycle(dir, from) {
1946 const stops = [...panes.values()].filter(r => !r.minimized).map(r => r.el);
1947 stops.push(dock);
1948 const at = stops.findIndex(s => s.contains(from));
1949 const next = stops[(at + dir + stops.length) % stops.length];
1950 if (next === dock) (chips.querySelector('button') || projectsButton).focus();
1951 else next.focus({ preventScroll: true });
1952 }
1953 function onKey(e) {
1954 if (e.defaultPrevented || !alive) return;
1955 if (e.key === 'Escape') {
1956 const inside = root.contains(e.target);
1957 const loose = e.target === document.body || e.target === document.documentElement || e.target === document;
1958 if (!inside && !loose) return;
1959 const rec = inside ? owner(e.target) : null;
1960 const target = rec && !rec.minimized ? rec : topmost();
1961 if (!target) return;
1962 e.preventDefault();
1963 minimize(target);
1964 return;
1965 }
1966 if (e.key === 'F6' && root.contains(e.target)) {
1967 e.preventDefault();
1968 cycle(e.shiftKey ? -1 : 1, e.target);
1969 }
1970 }
1971 function destroy() {
1972 if (!alive) return;
1973 for (const rec of panes.values()) stopApp(rec);
1974 alive = false;
1975 document.removeEventListener('keydown', onKey);
1976 window.removeEventListener('resize', onResize);
1977 if (media) {
1978 if (typeof media.removeEventListener === 'function') media.removeEventListener('change', layout);
1979 else if (typeof media.removeListener === 'function') media.removeListener(layout);
1980 }
1981 if (fitting) cancelAnimationFrame(fitting);
1982 root.remove();
1983 panes.clear();
1984 order = [];
1985 closed.length = 0;
1986 }
1987
1988 document.addEventListener('keydown', onKey);
1989 window.addEventListener('resize', onResize);
1990 if (media) {
1991 if (typeof media.addEventListener === 'function') media.addEventListener('change', layout);
1992 else if (typeof media.addListener === 'function') media.addListener(layout);
1993 }
1994 layout();
1995 stack();
1996 return { event, open, openNode, project, destroy };
1997 }
1998
1999 window.AllenPanes = Object.freeze({ version: VERSION, mount, check });
2000 window.dispatchEvent(new CustomEvent('allen-panes-ready', { detail: { version: VERSION } }));
2001})();