Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/om/allen-panes/panes.om # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / om / allen-panes / panes.om` 326 lines ยท 100353 bytes Raw Blame History 1 note Allen glass panes generator: emits public/js/allen-panes.js on fd 1. 2 note ~N~ tokens in the js texts expand single definitions. 0 to 4 and 6 to 12 3 note come from contract.om, the canonical pane contract owned by the science 4 note protocol: 0 panekind, 1 paneevt, 2 PANEVER, 3 PANE_MAX, 4 TEXT_MAX, 5 note 6 TITLEMAX, 7 LISTMAX, 8 SERIESMX, 9 POINTSMX, 10 REVMAX, 11 PANESMAX, 6 note 12 URLMAX. The rest are the fields of pcfg below, in order: 5 statuses, 7 note 13 reopenable closed panes, 14 saved projects, 15 project bytes, 16 IndexedDB 8 note name, 17 file format, 18 frame sandbox, 19 frame CSP, 20 sheet media query, 9 note 21 minimum width, 22 minimum height, 23 largest plot magnitude, and 24 is 10 note contract SYNC_MAX, the project summary bytes. 11 note Field 23 is the decimal form of contract PLOTMAX; main traps if they differ. 12 note 5 repeats the contract status sentence. A pcfg field cannot contain a pipe or 13 note a newline. Composed with contract.om by check.sh, never compiled on its own. 14 note Source language checked at omega-mv `55f9b0af47de70a3d06357985cf99ae3e45c016f`. 15 text pcfg "computed,unsupported,unverified,input-data|8|50|`4194304`|allen-panes|allen-panes-project|allow-scripts|default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; form-action 'none'; base-uri 'none'|(max-width: 720px)|260|160|1e100|" 16 global output uchar 65536 17 global used ulong 1 18 global marker ulong 2 19 20 fn flush to void 21 p = ulong 0 22 while lt p get used 0 bound 65536 23 n = write 1 output p sub get used 0 p 24 if le n 0 25 trap 3 26 end 27 p = add p ulong n 28 end 29 put used 0 0 30 end 31 32 fn raw c uchar to void 33 if eq get used 0 len output 34 flush 35 end 36 put output get used 0 c 37 put used 0 add get used 0 1 38 end 39 40 note field: the k-th pipe-terminated field of pcfg; a missing field traps. 41 fn field k ulong to void 42 p = ulong 0 43 i = ulong 0 44 while lt p len pcfg 45 c = get pcfg p 46 if eq c 124 47 if eq i k 48 ret 49 end 50 i = add i 1 51 else 52 if eq i k 53 raw c 54 end 55 end 56 p = add p 1 57 end 58 trap 3 59 end 60 61 note kinds and events: a contract list with its pipes as commas, no trailing one. 62 fn kinds to void 63 p = ulong 0 64 while lt p len panekind 65 c = get panekind p 66 if eq c 124 67 if lt add p 1 len panekind 68 raw 44 69 end 70 else 71 raw c 72 end 73 p = add p 1 74 end 75 end 76 77 fn events to void 78 p = ulong 0 79 while lt p len paneevt 80 c = get paneevt p 81 if eq c 124 82 if lt add p 1 len paneevt 83 raw 44 84 end 85 else 86 raw c 87 end 88 p = add p 1 89 end 90 end 91 92 note num: v in decimal; a ulong has at most 20 digits. 93 fn num v ulong to void 94 d = new uchar 20 0 95 x = v 96 put d 0 uchar add 48 rem x 10 97 n = ulong 1 98 x = div x 10 99 while gt x 0 bound 20 100 put d n uchar add 48 rem x 10 101 n = add n 1 102 x = div x 10 103 end 104 while gt n 0 bound 20 105 n = sub n 1 106 raw get d n 107 end 108 end 109 110 fn slot k ulong to void 111 if eq k 0 112 kinds 113 ret 114 end 115 if eq k 1 116 events 117 ret 118 end 119 if eq k 2 120 num ulong PANEVER 121 ret 122 end 123 if eq k 3 124 num PANE_MAX 125 ret 126 end 127 if eq k 4 128 num TEXT_MAX 129 ret 130 end 131 slot2 k 132 end 133 134 note slot2: the contract limits 6 to 12, then pcfg field 0 for 5 and k - 12 above 12. 135 fn slot2 k ulong to void 136 if eq k 5 137 field 0 138 ret 139 end 140 if eq k 6 141 num TITLEMAX 142 ret 143 end 144 if eq k 7 145 num LISTMAX 146 ret 147 end 148 if eq k 8 149 num SERIESMX 150 ret 151 end 152 if eq k 9 153 num POINTSMX 154 ret 155 end 156 if eq k 10 157 num REVMAX 158 ret 159 end 160 if eq k 11 161 num PANESMAX 162 ret 163 end 164 if eq k 12 165 num URLMAX 166 ret 167 end 168 if eq k 24 169 num SYNC_MAX 170 ret 171 end 172 field sub k 12 173 end 174 175 note byteput: ~N~ expands slot N; any other byte is copied. 176 fn byteput c uchar to void 177 if eq c 126 178 if eq get marker 0 0 179 put marker 0 1 180 put marker 1 0 181 else 182 slot get marker 1 183 put marker 0 0 184 end 185 else 186 if eq get marker 0 1 187 if or lt c 48 gt c 57 188 trap 3 189 end 190 put marker 1 add mul get marker 1 10 ulong sub c 48 191 else 192 raw c 193 end 194 end 195 end 196 197 note JavaScript KINDS 198 text js0 "/* Allen glass panes.\n *\n * Generated by om/allen-panes/panes.om; never hand-edit. Event names, kinds,\n * the protocol version and the byte limits come from the canonical pane\n * contract om/allen-panes/contract.om; the remaining bounds come from the\n * table in panes.om.\n *\n * Renders the v1 pane events (pane.open, pane.update, pane.close) as movable,\n * resizable, stackable glass panes over the scene. Every network or model\n * string reaches only textContent, an attribute value this file checks, or the\n * srcdoc of a frame sandboxed to allow-scripts alone after an explicit Run\n * click. Nothing from the network is parsed as markup in this document: plots\n * are drawn here from numbers and TeX is typeset here by a small subset\n * renderer, or shown as source when it uses anything outside that subset.\n * Projects reach IndexedDB only on an explicit Save project.\n */\n(() => {\n 'use strict';\n if (window.AllenPanes) return;\n const KINDS = '~0~'.split(',');\n const EVENTS = '~1~'.split(',');\n const VERSION = ~2~;\n const MAX_EVENT = ~3~;\n const MAX_TEXT = ~4~;\n const STATUSES = '~5~'.split(',');\n const MAX_TITLE = ~6~;\n const MAX_LIST = ~7~;\n const MAX_SERIES = ~8~;\n const MAX_POINTS = ~9~;\n const MAX_REVISION = ~10~;\n const MAX_PANES = ~11~;\n const MAX_URL = ~12~;\n const MAX_CLOSED = ~13~;\n const MAX_PROJECTS = ~14~;\n const MAX_PROJECT_BYTES = ~15~;\n const DB_NAME = '~16~';\n const FORMAT = '~17~';\n const SANDBOX = '~18~';\n const CSP = \"~19~\";\n const SHEET = '~20~';\n const MIN_W = ~21~;\n const MIN_H = ~22~;\n const MAX_ABS = ~23~;\n const SYNC_MAX = ~24~;\n const ID = /^[A-Za-z0-9_-]{1,64}$/;\n const DB_PROJECTS = 'projects';\n const DB_INDEX = 'index';\n const STEP = 16;\n const BIG_STEP = 64;\n const MAX_NAME = 80;\n const ACADEMY = 'https://interplane.io/drakestapleton/sovereign-intelligence/blob/main/docs/academy/README.md';\n const SVG_NS = 'http://www.w3.org/2000/svg';\n const MATH_NS = 'http://www.w3.org/1998/Math/MathML';\n const NAMES = { math: 'Math', plot: 'Plot', doc: 'Document', code: 'Code', app: 'App', research: 'Research', data: 'Data', omega: 'Omega', card: 'Aien', projects: 'Projects' };\n const STATUS_NAMES = { computed: 'Computed', unsupported: 'Not supported', unverified: 'Not verified', 'input-data': 'Given data' };\n const CAVEATS = {\n computed: 'The math engine produced this result. That is not an independent check that it is correct.',\n unsupported: 'The engine does not support this request, so nothing here was computed.',\n unverified: 'Written by the model and not checked by any engine.',\n 'input-data': 'These are the numbers as given. Showing them does not measure or prove them.'\n };\n const PALETTE = ['#2d7ff9', '#00e599', '#f59e0b', '#6e82ff', '#f87171', '#c4b5fd', '#94a3b8', '#f1f5f9'];\n 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' };\n const encoder = new TextEncoder();\n let serial = 0;\n\n function el(tag, className, text) {\n const node = document.createElement(tag);\n if (className) node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n }\n function button(className, label, text, handler) {\n const node = el('button', className, text);\n node.type = 'button';\n if (label) node.setAttribute('aria-label', label);\n if (handler) node.addEventListener('click', handler);\n return node;\n }\n function uid(prefix) {\n serial += 1;\n return `${prefix}-${serial}`;\n }\n /* Display text for titles and names: no control or bidirectional override\n characters, one line, bounded. */\n function clean(text, max) {\n return String(text).replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, max);\n }\n function slug(text) {\n return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 48).replace(/-+$/, '');\n }\n function copy(value) {\n return JSON.parse(JSON.stringify(value));\n }\n function utf8(text) {\n return encoder.encode(text).length;\n }\n\n" 199 200 note JavaScript own 201 text js1 " /* The v1 contract, checked exactly as the gateway checks it: unknown or\n missing fields, a wrong kind, a nonfinite number or an excess size refuse\n the whole event. */\n const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);\n function plain(o) {\n if (o === null || typeof o !== 'object' || Array.isArray(o)) return false;\n const proto = Object.getPrototypeOf(o);\n return proto === Object.prototype || proto === null;\n }\n function shape(o, required, optional) {\n if (!plain(o)) return false;\n const allowed = optional ? required.concat(optional) : required;\n for (const k of Object.keys(o)) if (!allowed.includes(k)) return false;\n return required.every(k => own(o, k));\n }\n function isText(v, max, filled) {\n if (typeof v !== 'string' || v.length > max || v.includes('\\u0000')) return false;\n if (filled && !v.trim()) return false;\n return v.length * 3 <= max || utf8(v) <= max;\n }\n function texts(v) {\n return Array.isArray(v) && v.length <= MAX_LIST && v.every(s => isText(s, MAX_TEXT));\n }\n function finite(n) {\n return typeof n === 'number' && Number.isFinite(n) && Math.abs(n) <= MAX_ABS;\n }\n function httpsUrl(url) {\n if (typeof url !== 'string' || !isText(url, MAX_URL) || /[\\u0000-\\u0020\\u007f]/.test(url)) return null;\n try {\n const parsed = new URL(url);\n return parsed.protocol === 'https:' && parsed.hostname && !parsed.username && !parsed.password ? parsed : null;\n } catch (_) {\n return null;\n }\n }\n function refs(v) {\n 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);\n }\n function fns(v) {\n 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)\n && 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)));\n }\n function code(c) {\n return shape(c, ['source', 'language'], ['wasm', 'functions']) && isText(c.source, MAX_TEXT) && isText(c.language, MAX_TEXT)\n && (!own(c, 'wasm') || isText(c.wasm, MAX_TEXT)) && (!own(c, 'functions') || fns(c.functions));\n }\n function series(s) {\n return shape(s, ['label', 'points']) && isText(s.label, MAX_TITLE) && Array.isArray(s.points) && s.points.length >= 1 && s.points.length <= MAX_POINTS\n && s.points.every(p => Array.isArray(p) && p.length === 2 && finite(p[0]) && finite(p[1]));\n }\n const CONTENT = {\n math: c => shape(c, ['text'], ['tex']) && isText(c.text, MAX_TEXT) && (!own(c, 'tex') || isText(c.tex, MAX_TEXT)),\n plot: c => shape(c, ['series', 'x_label', 'y_label']) && isText(c.x_label, MAX_TITLE) && isText(c.y_label, MAX_TITLE)\n && Array.isArray(c.series) && c.series.length >= 1 && c.series.length <= MAX_SERIES && c.series.every(series),\n doc: c => shape(c, ['markdown', 'citations']) && isText(c.markdown, MAX_TEXT) && refs(c.citations),\n code,\n omega: code,\n app: c => shape(c, ['html']) && isText(c.html, MAX_TEXT),\n research: c => shape(c, ['notes', 'hypotheses', 'derivations', 'sources']) && isText(c.notes, MAX_TEXT) && texts(c.hypotheses) && texts(c.derivations) && refs(c.sources),\n data: c => shape(c, ['columns', 'rows']) && texts(c.columns) && c.columns.length >= 1\n && Array.isArray(c.rows) && c.rows.length <= MAX_LIST && c.rows.every(texts)\n };\n const PROVENANCE = ['status', 'engine', 'expression', 'result', 'source', 'commit'];\n function provenance(p) {\n return shape(p, PROVENANCE) && STATUSES.includes(p.status) && PROVENANCE.every(k => isText(p[k], MAX_TEXT));\n }\n function sized(value) {\n try {\n return utf8(JSON.stringify(value)) <= MAX_EVENT;\n } catch (_) {\n return false;\n }\n }\n /* Returns '' for a valid event, else the reason. An update is checked\n against the kind its pane was opened with. */\n function check(name, p, kind) {\n if (!EVENTS.includes(name)) return 'unknown pane event';\n if (!plain(p)) return 'the event is not a JSON object';\n const fields = name === 'pane.open' ? ['v', 'id', 'kind', 'title'] : name === 'pane.update' ? ['v', 'id', 'revision', 'content', 'provenance'] : ['v', 'id'];\n if (!shape(p, fields)) return 'unexpected or missing fields';\n if (p.v !== VERSION || typeof p.id !== 'string' || !ID.test(p.id)) return 'invalid pane identity';\n if (!sized(p)) return 'the event is over the size limit';\n if (name === 'pane.open') {\n if (!KINDS.includes(p.kind)) return 'invalid pane kind';\n return isText(p.title, MAX_TITLE, true) ? '' : 'invalid title';\n }\n if (name === 'pane.update') {\n if (!Number.isInteger(p.revision) || p.revision < 1 || p.revision > MAX_REVISION) return 'invalid revision';\n if (!KINDS.includes(kind)) return 'the pane is not open';\n if (!CONTENT[kind](p.content)) return `the content does not match ${kind === 'app' || kind === 'omega' ? 'an' : 'a'} ${kind} pane`;\n return provenance(p.provenance) ? '' : 'invalid provenance';\n }\n return '';\n }\n\n" 202 203 note JavaScript link 204 text js2 " /* Links: HTTPS only, shown with their host, never fetched by this page. */\n function link(label, url) {\n const safe = httpsUrl(url);\n const shown = clean(label, MAX_TITLE) || url;\n if (!safe) {\n const span = el('span', 'allen-link-off', shown);\n if (url && url !== shown) span.append(document.createTextNode(` (${url})`));\n return span;\n }\n const frag = document.createDocumentFragment();\n const a = el('a', 'allen-link', shown);\n a.href = safe.href;\n a.target = '_blank';\n a.rel = 'noopener noreferrer nofollow';\n a.referrerPolicy = 'no-referrer';\n frag.append(a, el('span', 'allen-link-host', ` ${safe.host}`));\n return frag;\n }\n\n /* A small first-party TeX subset typeset as MathML Core built element by\n element. Anything outside the subset throws, and the caller shows the\n TeX as source and says so. */\n 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' };\n const IDENT = { infty: '\\u221e', partial: '\\u2202', nabla: '\\u2207', ell: '\\u2113', hbar: '\\u210f', emptyset: '\\u2205', aleph: '\\u2135' };\n 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: '}' };\n const LARGE = { sum: '\\u2211', prod: '\\u220f', coprod: '\\u2210', int: '\\u222b', iint: '\\u222c', iiint: '\\u222d', oint: '\\u222e', bigcup: '\\u22c3', bigcap: '\\u22c2' };\n 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(' ');\n const LIMITS = ['sum', 'prod', 'coprod', 'bigcup', 'bigcap', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'inf'];\n const SPACES = { ',': '0.1667em', ':': '0.2222em', ';': '0.2778em', '!': '-0.1667em', ' ': '0.25em', quad: '1em', qquad: '2em' };\n const BB = { C: '\\u2102', H: '\\u210d', N: '\\u2115', P: '\\u2119', Q: '\\u211a', R: '\\u211d', Z: '\\u2124' };\n const FENCES = { '(': '(', ')': ')', '[': '[', ']': ']', '|': '|', '.': '', '\\\\{': '{', '\\\\}': '}', '\\\\langle': '\\u27e8', '\\\\rangle': '\\u27e9', '\\\\lvert': '|', '\\\\rvert': '|', '\\\\|': '\\u2016', '\\\\lfloor': '\\u230a', '\\\\rfloor': '\\u230b', '\\\\lceil': '\\u2308', '\\\\rceil': '\\u2309' };\n function mml(tag, children, attrs) {\n const node = document.createElementNS(MATH_NS, tag);\n if (attrs) for (const k of Object.keys(attrs)) node.setAttribute(k, attrs[k]);\n if (typeof children === 'string') node.textContent = children;\n else if (children) node.append(...children);\n return node;\n }\n function texTokens(src) {\n const out = [];\n const re = /\\\\([A-Za-z]+|.)|(\\d+(?:\\.\\d+)?)|(\\s+)|([\\s\\S])/g;\n let m;\n while ((m = re.exec(src)) !== null) {\n if (out.length > 4096) throw new Error('too long');\n if (m[3]) continue;\n out.push(m[1] !== undefined ? { t: 'cmd', v: m[1] } : m[2] !== undefined ? { t: 'num', v: m[2] } : { t: 'chr', v: m[4] });\n }\n return out;\n }\n function texParse(src) {\n const toks = texTokens(src);\n let at = 0;\n let depth = 0;\n const peek = () => toks[at];\n const take = () => toks[at++];\n const fail = what => { throw new Error(what); };\n function group() {\n const t = peek();\n if (!t) fail('missing argument');\n if (t.t === 'chr' && t.v === '{') {\n take();\n const row = seq('}');\n if (!peek() || peek().v !== '}') fail('unclosed brace');\n take();\n return row;\n }\n return atom(true);\n }\n function raw() {\n const t = take();\n if (!t || t.t !== 'chr' || t.v !== '{') fail('expected a braced argument');\n let text = '';\n let level = 1;\n for (;;) {\n const n = take();\n if (!n) fail('unclosed brace');\n if (n.t === 'chr' && n.v === '{') level += 1;\n if (n.t === 'chr' && n.v === '}') {\n level -= 1;\n if (level === 0) return text;\n }\n text += n.t === 'cmd' ? (n.v.length === 1 ? n.v : `\\\\${n.v} `) : n.v;\n }\n }\n function fence() {\n const t = take();\n if (!t) fail('missing delimiter');\n const key = t.t === 'cmd' ? `\\\\${t.v}` : t.v;\n if (!own(FENCES, key)) fail(`delimiter ${key}`);\n return FENCES[key];\n }\n function atom(single) {\n const t = take();\n if (!t) fail('missing argument');\n if (t.t === 'num') {\n if (single && t.v.length > 1) {\n at -= 1;\n toks[at] = { t: 'num', v: t.v.slice(1) };\n return mml('mn', t.v[0]);\n }\n return mml('mn', t.v);\n }\n if (t.t === 'chr') {\n if (/[A-Za-z]/.test(t.v)) return mml('mi', t.v);\n if (t.v === '{' && !single) {\n at -= 1;\n return group();\n }\n if (t.v === \"'\") return mml('mo', '\\u2032');\n if (t.v === '-') return mml('mo', '\\u2212');\n if ('+=<>()[]|,;:!/*.?'.includes(t.v)) return mml('mo', t.v, '()[]|'.includes(t.v) ? { stretchy: 'false' } : undefined);\n fail(`character ${t.v}`);\n }\n const c = t.v;\n if (own(GREEK, c)) return mml('mi', GREEK[c], /^[A-Z]/.test(c) ? { mathvariant: 'normal' } : undefined);\n if (own(IDENT, c)) return mml('mi', IDENT[c]);\n if (own(OPS, c)) return mml('mo', OPS[c]);\n if (own(LARGE, c)) return mml('mo', LARGE[c], LIMITS.includes(c) ? { largeop: 'true', movablelimits: 'true' } : { largeop: 'true' });\n if (FUNCS.includes(c)) return mml('mi', c, { mathvariant: 'normal' });\n if (own(SPACES, c)) return mml('mspace', null, { width: SPACES[c] });\n if (c === '{' || c === '}' || c === '%' || c === '$' || c === '#' || c === '_' || c === '&') return mml('mo', c);\n if (c === 'frac' || c === 'dfrac' || c === 'tfrac') return mml('mfrac', [group(), group()]);\n if (c === 'binom') return mml('mrow', [mml('mo', '('), mml('mfrac', [group(), group()], { linethickness: '0' }), mml('mo', ')')]);\n if (c === 'sqrt') {\n if (peek() && peek().t === 'chr' && peek().v === '[') {\n take();\n const index = seq(']');\n if (!peek() || peek().v !== ']') fail('unclosed root index');\n take();\n return mml('mroot', [group(), index]);\n }\n return mml('msqrt', [group()]);\n }\n if (c === 'text' || c === 'textrm' || c === 'mathrm' || c === 'operatorname') {\n const text = raw();\n return c === 'text' || c === 'textrm' ? mml('mtext', text) : mml('mi', text, { mathvariant: 'normal' });\n }\n if (c === 'mathbb') {\n const letter = raw().trim();\n if (!own(BB, letter)) fail(`mathbb ${letter}`);\n return mml('mi', BB[letter]);\n }\n if (c === 'left') {\n const open = fence();\n const inner = seq('right');\n const close = peek();\n if (!close || close.t !== 'cmd' || close.v !== 'right') fail('left without right');\n take();\n const shut = fence();\n return mml('mrow', [mml('mo', open, { fence: 'true', stretchy: 'true' }), inner, mml('mo', shut, { fence: 'true', stretchy: 'true' })]);\n }\n return fail(`\\\\${c}`);\n }\n function scripted(base) {\n let sub = null;\n let sup = null;\n for (let i = 0; i < 2; i++) {\n const t = peek();\n if (!t || t.t !== 'chr' || (t.v !== '_' && t.v !== '^')) break;\n take();\n if (t.v === '_') {\n if (sub) fail('double subscript');\n sub = group();\n } else {\n if (sup) fail('double superscript');\n sup = group();\n }\n }\n if (!sub && !sup) return base;\n const under = (base.localName === 'mo' && base.getAttribute('movablelimits') === 'true') || (base.localName === 'mi' && LIMITS.includes(base.textContent));\n if (sub && sup) return mml(under ? 'munderover' : 'msubsup', [base, sub, sup]);\n if (sub) return mml(under ? 'munder' : 'msub', [base, sub]);\n return mml(under ? 'mover' : 'msup', [base, sup]);\n }\n function seq(stop) {\n depth += 1;\n if (depth > 32) fail('nested too deeply');\n const items = [];\n while (at < toks.length) {\n const t = peek();\n if (stop === 'right' ? t.t === 'cmd' && t.v === 'right' : t.t === 'chr' && t.v === stop) break;\n if (t.t === 'chr' && (t.v === '}' || t.v === ']') && stop === null) fail('unbalanced');\n if (t.t === 'chr' && (t.v === '^' || t.v === '_')) {\n items.push(scripted(mml('mrow', [])));\n continue;\n }\n items.push(scripted(atom(false)));\n }\n depth -= 1;\n return items.length === 1 ? items[0] : mml('mrow', items);\n }\n const tree = seq(null);\n if (at !== toks.length) fail('trailing input');\n return tree;\n }\n /* Returns a math element, or null with the reason when the TeX is outside\n the subset or the browser has no MathML. */\n function typeset(src, display) {\n if (typeof window.MathMLElement !== 'function') return { node: null, reason: 'this browser does not lay out MathML' };\n try {\n const tree = texParse(src);\n const semantics = mml('semantics', [tree, mml('annotation', src, { encoding: 'application/x-tex' })]);\n return { node: mml('math', [semantics], { display: display ? 'block' : 'inline' }), reason: '' };\n } catch (error) {\n return { node: null, reason: `it uses ${String(error && error.message).slice(0, 80)}, which this renderer does not typeset` };\n }\n }\n function texBlock(src, label) {\n const box = el('div', 'allen-tex');\n const done = typeset(src, true);\n if (done.node) {\n 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.`));\n } else {\n box.append(el('p', 'allen-pane-label', `${label} as TeX source, not typeset: ${done.reason}.`));\n }\n const pre = el('pre', 'allen-pane-pre', src);\n pre.setAttribute('aria-label', 'TeX source');\n box.append(pre);\n return box;\n }\n\n" 205 206 note JavaScript inline 207 text js3 " /* Markdown subset rendered to DOM nodes only: headings, paragraphs, lists,\n quotes, rules, fenced code, pipe tables, inline code, strong, emphasis,\n HTTPS links and $ TeX. Raw HTML stays text. */\n function inline(node, text) {\n const re = /(`+)([^`][\\s\\S]*?)\\1|\\*\\*([^*\\n]+)\\*\\*|\\*([^*\\s][^*\\n]*)\\*|\\[([^\\]\\n]{1,500})\\]\\(([^)\\s]{1,2048})\\)|\\$([^$\\n]{1,500})\\$|(https:\\/\\/[^\\s<>()]{1,2048})/g;\n let last = 0;\n let m;\n while ((m = re.exec(text)) !== null) {\n if (m.index > last) node.append(document.createTextNode(text.slice(last, m.index)));\n if (m[1]) node.append(el('code', 'allen-md-code', m[2]));\n else if (m[3] !== undefined) node.append(el('strong', '', m[3]));\n else if (m[4] !== undefined) node.append(el('em', '', m[4]));\n else if (m[5] !== undefined) node.append(link(m[5], m[6]));\n else if (m[7] !== undefined) {\n const done = typeset(m[7], false);\n if (done.node) node.append(done.node);\n else {\n const raw = el('code', 'allen-md-tex', `$${m[7]}$`);\n raw.title = 'TeX source, not typeset';\n node.append(raw);\n }\n } else {\n const url = m[8].replace(/[.,;:!?]+$/, '');\n node.append(link(url, url));\n if (url.length < m[8].length) node.append(document.createTextNode(m[8].slice(url.length)));\n }\n last = re.lastIndex;\n }\n if (last < text.length) node.append(document.createTextNode(text.slice(last)));\n return node;\n }\n function cells(line) {\n return line.trim().replace(/^\\|/, '').replace(/\\|$/, '').split('|').map(s => s.trim());\n }\n /* A repo report's files, found by the same parser that renders the pane,\n so a fence the reader saw is exactly a fence that is saved. */\n const REPORT = /^Repo report: ([A-Za-z0-9_.-]{1,100})\\/([A-Za-z0-9_.-]{1,100})$/;\n function reportFiles(source) {\n const files = [{ path: 'README.md', content: source }];\n const patches = [];\n let port = 0;\n let harness = 0;\n markdown(source, document.createElement('div'), (lang, text) => {\n const kind = lang.toLowerCase();\n if (kind === 'omega' || kind === 'om') files.push({ path: `allen-port-${(port += 1)}.om`, content: `${text}\\n` });\n else if (kind === 'diff' || kind === 'patch') patches.push(`${text}\\n`);\n else if (kind === 'text' || kind === 'txt') files.push({ path: `parity-harness-${(harness += 1)}.txt`, content: `${text}\\n` });\n return null;\n });\n if (patches.length) files.push({ path: 'allen-ports.patch', content: patches.join('') });\n return files;\n }\n function markdown(source, box, fenceTool) {\n const lines = source.split(/\\r?\\n/);\n let para = [];\n let list = null;\n const flush = () => {\n if (para.length) box.append(inline(el('p', 'allen-md-p'), para.join(' ')));\n para = [];\n };\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const fence = /^\\s*(```+)\\s*([A-Za-z0-9_+-]{0,32})\\s*$/.exec(line);\n if (fence) {\n flush();\n list = null;\n const body = [];\n for (i += 1; i < lines.length && !lines[i].trim().startsWith(fence[1]); i++) body.push(lines[i]);\n const pre = el('pre', 'allen-md-pre');\n if (fence[2]) pre.dataset.lang = fence[2];\n pre.append(el('code', '', body.join('\\n')));\n box.append(pre);\n const tool = fenceTool ? fenceTool(fence[2], body.join('\\n')) : null;\n if (tool) box.append(tool);\n continue;\n }\n if (/^\\s*\\$\\$/.test(line)) {\n flush();\n list = null;\n const body = [line.replace(/^\\s*\\$\\$/, '')];\n let closed = /\\$\\$\\s*$/.test(body[0]) && body[0].trim().length > 2;\n if (closed) body[0] = body[0].replace(/\\$\\$\\s*$/, '');\n if (!closed) for (i += 1; i < lines.length; i++) {\n if (/\\$\\$\\s*$/.test(lines[i])) {\n body.push(lines[i].replace(/\\$\\$\\s*$/, ''));\n closed = true;\n break;\n }\n body.push(lines[i]);\n }\n box.append(texBlock(body.join('\\n').trim(), 'Formula'));\n continue;\n }\n if (!line.trim()) {\n flush();\n list = null;\n continue;\n }\n const heading = /^\\s*(#{1,6})\\s+(.*?)\\s*#*\\s*$/.exec(line);\n if (heading) {\n flush();\n list = null;\n box.append(inline(el(`h${Math.min(6, heading[1].length + 2)}`, 'allen-md-h'), heading[2]));\n continue;\n }\n if (/^\\s*([-*_])(\\s*\\1){2,}\\s*$/.test(line)) {\n flush();\n list = null;\n box.append(el('hr', 'allen-md-hr'));\n continue;\n }\n if (/^\\s*\\|.*\\|\\s*$/.test(line) && i + 1 < lines.length && /^\\s*\\|?\\s*:?-+:?\\s*(\\|\\s*:?-+:?\\s*)*\\|?\\s*$/.test(lines[i + 1])) {\n flush();\n list = null;\n const table = el('table', 'allen-md-table');\n const head = el('tr');\n for (const c of cells(line)) head.append(inline(el('th'), c));\n const thead = el('thead');\n thead.append(head);\n const tbody = el('tbody');\n for (i += 2; i < lines.length && /^\\s*\\|.*\\|\\s*$/.test(lines[i]); i++) {\n const row = el('tr');\n for (const c of cells(lines[i])) row.append(inline(el('td'), c));\n tbody.append(row);\n }\n i -= 1;\n table.append(thead, tbody);\n const wrap = el('div', 'allen-pane-table');\n wrap.append(table);\n box.append(wrap);\n continue;\n }\n const quote = /^\\s*>\\s?(.*)$/.exec(line);\n if (quote) {\n flush();\n list = null;\n const parts = [quote[1]];\n while (i + 1 < lines.length && /^\\s*>/.test(lines[i + 1])) parts.push(lines[++i].replace(/^\\s*>\\s?/, ''));\n const block = el('blockquote', 'allen-md-quote');\n block.append(inline(el('p', 'allen-md-p'), parts.join(' ')));\n box.append(block);\n continue;\n }\n const item = /^\\s*([-*+]|\\d{1,9}[.)])\\s+(.*)$/.exec(line);\n if (item) {\n flush();\n const ordered = /\\d/.test(item[1]);\n if (!list || (list.localName === 'ol') !== ordered) {\n list = el(ordered ? 'ol' : 'ul', 'allen-md-list');\n box.append(list);\n }\n list.append(inline(el('li'), item[2]));\n continue;\n }\n if (list && /^\\s{2,}\\S/.test(line)) {\n inline(list.lastElementChild, ` ${line.trim()}`);\n continue;\n }\n list = null;\n para.push(line.trim());\n }\n flush();\n return box;\n }\n\n" 208 209 note JavaScript svg 210 text js4 " /* Plots are drawn here from validated numbers; no SVG from the network is\n ever parsed. Colours are attributes so an exported file keeps them. */\n function svg(tag, attrs, text) {\n const node = document.createElementNS(SVG_NS, tag);\n for (const k of Object.keys(attrs)) node.setAttribute(k, String(attrs[k]));\n if (text !== undefined) node.textContent = text;\n return node;\n }\n function fmt(n) {\n const v = Number(n.toPrecision(5));\n return Object.is(v, -0) ? '0' : String(v);\n }\n function ticks(lo, hi) {\n const raw = (hi - lo) / 5;\n if (!Number.isFinite(raw) || raw <= 0) return [lo, hi];\n const mag = Math.pow(10, Math.floor(Math.log10(raw)));\n const unit = [1, 2, 5, 10].map(f => f * mag).find(s => s >= raw) || raw;\n const first = Math.ceil(lo / unit);\n const out = [];\n for (let n = 0; n < 12; n++) {\n const t = (first + n) * unit;\n if (t > hi + unit * 1e-9) break;\n out.push(t);\n }\n return out.length ? out : [lo, hi];\n }\n function extent(c) {\n let x0 = Infinity;\n let x1 = -Infinity;\n let y0 = Infinity;\n let y1 = -Infinity;\n for (const s of c.series) for (const p of s.points) {\n x0 = Math.min(x0, p[0]);\n x1 = Math.max(x1, p[0]);\n y0 = Math.min(y0, p[1]);\n y1 = Math.max(y1, p[1]);\n }\n if (x0 === x1) {\n x0 -= 1;\n x1 += 1;\n }\n if (y0 === y1) {\n y0 -= 1;\n y1 += 1;\n }\n return { x0, x1, y0, y1 };\n }\n function plot(c, title) {\n const W = 640;\n const H = 400;\n const L = 64;\n const R = 20;\n const T = 20;\n const B = 52;\n const e = extent(c);\n const sx = v => L + (v - e.x0) / (e.x1 - e.x0) * (W - L - R);\n const sy = v => H - B - (v - e.y0) / (e.y1 - e.y0) * (H - T - B);\n const titleId = uid('allen-plot-title');\n const descId = uid('allen-plot-desc');\n const root = svg('svg', { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: 'img', 'aria-labelledby': `${titleId} ${descId}`, class: 'allen-plot-svg' });\n const xl = c.x_label ? ` (${c.x_label})` : '';\n const yl = c.y_label ? ` (${c.y_label})` : '';\n 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)}.`));\n const grid = svg('g', { stroke: '#1c2536', 'stroke-width': 1 });\n const labels = svg('g', { fill: '#94a3b8', 'font-size': 12, 'font-family': 'ui-sans-serif, system-ui, sans-serif' });\n for (const t of ticks(e.x0, e.x1)) {\n const x = sx(t).toFixed(2);\n grid.append(svg('line', { x1: x, y1: T, x2: x, y2: H - B }));\n labels.append(svg('text', { x, y: H - B + 18, 'text-anchor': 'middle' }, fmt(t)));\n }\n for (const t of ticks(e.y0, e.y1)) {\n const y = sy(t).toFixed(2);\n grid.append(svg('line', { x1: L, y1: y, x2: W - R, y2: y }));\n labels.append(svg('text', { x: L - 8, y: (Number(y) + 4).toFixed(2), 'text-anchor': 'end' }, fmt(t)));\n }\n const axes = svg('g', { stroke: '#3b4a63', 'stroke-width': 1 });\n 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 }));\n if (c.x_label) labels.append(svg('text', { x: (L + W - R) / 2, y: H - 12, 'text-anchor': 'middle' }, c.x_label));\n if (c.y_label) {\n const mid = (T + H - B) / 2;\n labels.append(svg('text', { x: 16, y: mid, 'text-anchor': 'middle', transform: `rotate(-90 16 ${mid})` }, c.y_label));\n }\n const lines = svg('g', { fill: 'none', 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' });\n c.series.forEach((s, i) => {\n const colour = PALETTE[i % PALETTE.length];\n const group = svg('g', { stroke: colour });\n group.append(svg('title', {}, s.label || `Series ${i + 1}`));\n 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(' ') }));\n 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' }));\n lines.append(group);\n });\n root.append(grid, axes, lines, labels);\n const figure = el('figure', 'allen-plot');\n figure.append(root);\n const legend = el('ul', 'allen-plot-legend');\n c.series.forEach((s, i) => {\n const item = el('li', 'allen-plot-key');\n const swatch = el('span', 'allen-plot-swatch');\n swatch.style.background = PALETTE[i % PALETTE.length];\n swatch.setAttribute('aria-hidden', 'true');\n item.append(swatch, document.createTextNode(`${s.label || `Series ${i + 1}`}, ${s.points.length} point${s.points.length === 1 ? '' : 's'}`));\n legend.append(item);\n });\n figure.append(legend);\n const data = el('details', 'allen-plot-data');\n data.append(el('summary', 'allen-pane-summary', 'Plot data as a table'));\n data.addEventListener('toggle', () => {\n if (!data.open || data.dataset.built) return;\n data.dataset.built = 'yes';\n 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])]))));\n });\n figure.append(data);\n return { figure, svg: root };\n }\n function table(columns, rows) {\n const wrap = el('div', 'allen-pane-table');\n wrap.tabIndex = 0;\n const node = el('table', 'allen-data');\n const head = el('tr');\n for (const c of columns) {\n const th = el('th', '', c);\n th.scope = 'col';\n head.append(th);\n }\n const thead = el('thead');\n thead.append(head);\n const tbody = el('tbody');\n for (const r of rows) {\n const tr = el('tr');\n for (let i = 0; i < Math.max(r.length, columns.length); i++) tr.append(el('td', '', i < r.length ? r[i] : ''));\n tbody.append(tr);\n }\n node.append(thead, tbody);\n wrap.append(node);\n return wrap;\n }\n\n" 211 212 note JavaScript csv 213 text js5 " /* Files. Every download is application/octet-stream, so no browser renders\n a generated file in this origin. */\n function csv(columns, rows) {\n const cell = v => {\n let s = String(v);\n if (/^[=+@\\t\\r]/.test(s) || /^-(?![\\d.])/.test(s)) s = `'${s}`;\n return /[\",\\r\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n };\n return `${[columns, ...rows].map(r => r.map(cell).join(',')).join('\\r\\n')}\\r\\n`;\n }\n function refText(items) {\n return items.map((r, i) => `${i + 1}. [${r.title}](${r.url})`).join('\\n');\n }\n function artefact(rec) {\n const c = rec.content;\n const base = slug(rec.title) || rec.kind;\n switch (rec.kind) {\n case 'math': {\n const text = own(c, 'tex') ? `${c.text}\\n\\nTeX source:\\n${c.tex}\\n` : `${c.text}\\n`;\n return { name: `${base}.txt`, what: 'result', data: () => text, copy: c.text };\n }\n case 'plot': {\n const rows = c.series.flatMap((s, i) => s.points.map(p => [s.label || `Series ${i + 1}`, String(p[0]), String(p[1])]));\n return { name: `${base}.svg`, what: 'data as CSV', data: () => `\\n${new XMLSerializer().serializeToString(rec.svg)}\\n`, copy: csv(['series', c.x_label || 'x', c.y_label || 'y'], rows) };\n }\n case 'doc': {\n const text = c.citations.length ? `${c.markdown}\\n\\n## Citations\\n\\n${refText(c.citations)}\\n` : `${c.markdown}\\n`;\n return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };\n }\n case 'code':\n case 'omega': {\n const ext = rec.kind === 'omega' ? 'om' : EXT[c.language.toLowerCase()] || 'txt';\n return { name: `${base}.${ext}`, what: 'source', data: () => c.source, copy: c.source };\n }\n case 'app':\n return { name: `${base}.html`, what: 'HTML', data: () => c.html, copy: c.html };\n case 'research': {\n const parts = [`# ${rec.title}`, '## Notes', c.notes];\n if (c.hypotheses.length) parts.push('## Hypotheses', c.hypotheses.map(h => `- ${h}`).join('\\n'));\n if (c.derivations.length) parts.push('## Derivations', c.derivations.map(d => `\\`\\`\\`\\n${d}\\n\\`\\`\\``).join('\\n\\n'));\n if (c.sources.length) parts.push('## Sources', refText(c.sources));\n const text = `${parts.join('\\n\\n')}\\n`;\n return { name: `${base}.md`, what: 'Markdown', data: () => text, copy: text };\n }\n case 'data': {\n const text = csv(c.columns, c.rows);\n return { name: `${base}.csv`, what: 'CSV', data: () => text, copy: text };\n }\n default:\n return null;\n }\n }\n function wasmBytes(text) {\n try {\n const bin = atob(text.replace(/\\s+/g, ''));\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out.length >= 8 && out[0] === 0 && out[1] === 97 && out[2] === 115 && out[3] === 109 ? out : null;\n } catch (_) {\n return null;\n }\n }\n async function copyText(source, node) {\n if (node.dataset.label === undefined) node.dataset.label = node.textContent;\n try {\n await navigator.clipboard.writeText(source);\n node.textContent = 'Copied';\n } catch (_) {\n node.textContent = 'Copy blocked';\n }\n setTimeout(() => {\n node.textContent = node.dataset.label;\n }, 1500);\n }\n /* The policy becomes the first element of the program's head, as in the\n chat client: after an existing head tag, else in a head of its own. The\n prefix (doctype, comments, html tag) is skipped one sticky token at a\n time and a comment body never holds its closing marker, so the scan is\n linear in the source. */\n function sandboxed(source) {\n const meta = ``;\n const prefix = /\\s*(?:]*>||]*)?>)/iy;\n let at = 0;\n while (prefix.exec(source)) at = prefix.lastIndex;\n const head = /\\s*]*)?>/iy;\n head.lastIndex = at;\n if (head.exec(source)) return source.slice(0, head.lastIndex) + meta + source.slice(head.lastIndex);\n const lead = /^\\s*(?:]*>\\s*)?(?:]*)?>)?/i.exec(source)[0];\n return `${lead}${meta}${source.slice(lead.length)}`;\n }\n\n" 214 215 note JavaScript checkEntry 216 text js6 " /* Project files and IndexedDB records share one format. */\n function checkEntry(p) {\n if (!shape(p, ['id', 'kind', 'title', 'revision', 'content', 'provenance'], ['geom', 'minimized'])) return 'unexpected or missing fields';\n let reason = check('pane.open', { v: VERSION, id: p.id, kind: p.kind, title: p.title });\n if (!reason) reason = check('pane.update', { v: VERSION, id: p.id, revision: p.revision, content: p.content, provenance: p.provenance }, p.kind);\n if (reason) return reason;\n if (own(p, 'geom') && !(shape(p.geom, ['x', 'y', 'w', 'h']) && ['x', 'y', 'w', 'h'].every(k => finite(p.geom[k])))) return 'invalid geometry';\n if (own(p, 'minimized') && typeof p.minimized !== 'boolean') return 'invalid minimized flag';\n return '';\n }\n function checkFile(data) {\n if (!shape(data, ['format', 'v', 'panes'], ['id', 'name', 'saved', 'exported']) || data.format !== FORMAT || data.v !== VERSION) return 'this is not an Aien panes file';\n for (const k of ['id', 'name', 'saved', 'exported']) if (own(data, k) && !isText(data[k], MAX_TITLE)) return `invalid ${k}`;\n if (!Array.isArray(data.panes) || data.panes.length > MAX_PANES) return `a file holds at most ${MAX_PANES} panes`;\n for (let i = 0; i < data.panes.length; i++) {\n const reason = checkEntry(data.panes[i]);\n if (reason) return `pane ${i + 1}: ${reason}`;\n }\n return '';\n }\n function limit(message) {\n const error = new Error(message);\n error.name = 'AllenLimit';\n return error;\n }\n function storageError(error) {\n const name = error && error.name;\n if (name === 'AllenLimit') return error.message;\n if (name === 'QuotaExceededError') return 'This browser refused: it has no storage space left for this site. Export the panes as a file instead.';\n 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.';\n const detail = error && error.message ? ` (${clean(error.message, 160)})` : '';\n return `This browser refused to store the project${detail}. Export the panes as a file instead.`;\n }\n function openDb() {\n return new Promise((resolve, reject) => {\n let request;\n try {\n if (!window.indexedDB) throw Object.assign(new Error('no IndexedDB'), { name: 'AllenNoStore' });\n request = window.indexedDB.open(DB_NAME, 1);\n } catch (error) {\n reject(error);\n return;\n }\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(DB_PROJECTS)) db.createObjectStore(DB_PROJECTS, { keyPath: 'id' });\n if (!db.objectStoreNames.contains(DB_INDEX)) db.createObjectStore(DB_INDEX, { keyPath: 'id' });\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error || new Error('IndexedDB refused'));\n request.onblocked = () => reject(new Error('another tab holds the project store open'));\n });\n }\n function ask(request) {\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n async function store(mode, work) {\n const db = await openDb();\n try {\n const tx = db.transaction([DB_PROJECTS, DB_INDEX], mode);\n const done = new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onabort = () => reject(tx.error || new Error('the storage transaction was aborted'));\n });\n let value;\n try {\n value = await work(tx.objectStore(DB_PROJECTS), tx.objectStore(DB_INDEX));\n } catch (error) {\n try {\n tx.abort();\n } catch (_) {}\n await done.catch(() => {});\n throw error;\n }\n await done;\n return value;\n } finally {\n db.close();\n }\n }\n function stamp(iso) {\n const when = new Date(iso);\n return Number.isNaN(when.getTime()) ? String(iso) : when.toLocaleString();\n }\n\n" 217 218 note JavaScript mount 219 text js7 " function mount(host, options) {\n if (!(host instanceof Element)) throw new TypeError('AllenPanes.mount needs an element');\n const opts = options && typeof options === 'object' ? options : {};\n const panes = new Map();\n const closedIds = new Set();\n const closed = [];\n let order = [];\n let cascade = 0;\n let current = null;\n let alive = true;\n let fitting = 0;\n const root = el('div', 'allen-panes');\n const layer = el('div', 'allen-panes-layer');\n const dock = el('nav', 'allen-panes-dock');\n dock.setAttribute('aria-label', 'Aien panes');\n const chips = el('ul', 'allen-panes-chips');\n const projectsButton = button('allen-panes-tool', 'Projects: save, open, export or import panes', 'Projects', () => projectsPane());\n const exportButton = button('allen-panes-tool', 'Export the open panes as a JSON file', 'Export', () => exportOpen());\n const reopenButton = button('allen-panes-tool', '', 'Reopen', () => reopen());\n reopenButton.hidden = true;\n dock.append(chips, projectsButton, exportButton, reopenButton);\n const live = el('p', 'allen-panes-live');\n live.setAttribute('role', 'status');\n live.setAttribute('aria-live', 'polite');\n root.append(layer, dock, live);\n host.append(root);\n const media = typeof window.matchMedia === 'function' ? window.matchMedia(SHEET) : null;\n\n function say(message) {\n live.textContent = '';\n setTimeout(() => {\n if (alive) live.textContent = message;\n }, 60);\n if (typeof opts.announce === 'function') {\n try {\n opts.announce(message);\n } catch (_) {}\n }\n }\n function refuse(name, reason) {\n if (typeof opts.onRefuse === 'function') {\n try {\n opts.onRefuse(name, reason);\n } catch (_) {}\n }\n return { ok: false, reason };\n }\n function sheet() {\n return root.dataset.layout === 'sheet';\n }\n function layout() {\n root.dataset.layout = media && media.matches ? 'sheet' : 'float';\n refit();\n }\n function bounds() {\n return { w: Math.max(root.clientWidth, MIN_W), h: Math.max(root.clientHeight, MIN_H) };\n }\n function place(rec, x, y, w, h) {\n const b = bounds();\n const nw = Math.round(Math.min(Math.max(w, MIN_W), b.w));\n const nh = Math.round(Math.min(Math.max(h, MIN_H), b.h));\n const nx = Math.round(Math.min(Math.max(x, 0), b.w - nw));\n const ny = Math.round(Math.min(Math.max(y, 0), b.h - nh));\n rec.geom = { x: nx, y: ny, w: nw, h: nh };\n rec.el.style.transform = `translate(${nx}px, ${ny}px)`;\n rec.el.style.width = `${nw}px`;\n rec.el.style.height = `${nh}px`;\n }\n function refit() {\n for (const rec of panes.values()) place(rec, rec.geom.x, rec.geom.y, rec.geom.w, rec.geom.h);\n }\n function onResize() {\n if (!fitting) fitting = requestAnimationFrame(() => {\n fitting = 0;\n if (alive) refit();\n });\n }\n function initial(rec) {\n const b = bounds();\n const w = Math.min(560, b.w - 32);\n const h = Math.min(460, b.h - 160);\n const step = (cascade % 6) * 28;\n cascade += 1;\n place(rec, b.w - w - 32 - step, 76 + step, w, h);\n }\n function topmost() {\n for (let i = order.length - 1; i >= 0; i--) if (!order[i].minimized) return order[i];\n return null;\n }\n function chipState(rec) {\n rec.chipTitle.textContent = rec.title;\n rec.chip.setAttribute('aria-label', `${rec.title}, ${NAMES[rec.kind]} pane, ${rec.minimized ? 'minimized' : 'open'}`);\n rec.chip.dataset.state = rec.minimized ? 'minimized' : 'open';\n }\n function stack() {\n const top = topmost();\n order.forEach((rec, i) => {\n rec.el.style.zIndex = String(i + 1);\n rec.el.toggleAttribute('data-top', rec === top);\n rec.chip.toggleAttribute('data-top', rec === top);\n });\n dock.dataset.empty = panes.size ? 'no' : 'yes';\n }\n function raise(rec) {\n if (order[order.length - 1] !== rec) {\n order = order.filter(r => r !== rec);\n order.push(rec);\n }\n stack();\n }\n function owner(node) {\n for (const rec of panes.values()) if (rec.el.contains(node)) return rec;\n return null;\n }\n function label(rec) {\n rec.heading.textContent = rec.title;\n rec.move.setAttribute('aria-label', `Move ${rec.title}. Drag, or use the arrow keys; Shift moves farther.`);\n rec.size.setAttribute('aria-label', `Resize ${rec.title}. Drag, or use the arrow keys; Shift resizes farther.`);\n rec.min.setAttribute('aria-label', `Minimize ${rec.title}`);\n rec.max.setAttribute('aria-label', `Maximize ${rec.title}`);\n rec.max.setAttribute('aria-pressed', String(rec.maximized));\n rec.shut.setAttribute('aria-label', `Close ${rec.title}`);\n 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.`);\n chipState(rec);\n }\n function create(key, kind, title) {\n 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 };\n const pane = el('section', 'allen-pane');\n pane.dataset.kind = kind;\n pane.tabIndex = -1;\n pane.setAttribute('role', 'region');\n pane.setAttribute('aria-roledescription', 'pane');\n const head = el('header', 'allen-pane-head');\n const heading = el('h2', 'allen-pane-title');\n heading.id = uid('allen-pane-title');\n pane.setAttribute('aria-labelledby', heading.id);\n const move = button('allen-pane-move', '', '', null);\n const badge = el('span', 'allen-pane-badge');\n badge.hidden = true;\n const controls = el('div', 'allen-pane-controls');\n const min = button('allen-pane-ctl allen-pane-min', '', '\\u2212', () => minimize(rec));\n const max = button('allen-pane-ctl allen-pane-max', '', '\\u25a1', () => maximize(rec));\n const shut = button('allen-pane-ctl allen-pane-close', '', '\\u00d7', () => close(rec, true));\n controls.append(min, max, shut);\n head.append(move, el('span', 'allen-pane-kind', NAMES[kind]), heading, badge, controls);\n const notice = el('p', 'allen-pane-notice');\n notice.setAttribute('role', 'alert');\n notice.hidden = true;\n const body = el('div', 'allen-pane-body');\n body.tabIndex = 0;\n const source = el('details', 'allen-pane-source');\n source.hidden = true;\n const foot = el('div', 'allen-pane-foot');\n foot.hidden = true;\n const size = button('allen-pane-size', '', '', null);\n const grab = button('allen-pane-grab', '', '', () => minimize(rec));\n pane.append(grab, head, notice, body, source, foot, size);\n const item = el('li', 'allen-panes-item');\n const chip = button('allen-panes-chip', '', '', () => chipClick(rec));\n const chipTitle = el('span', 'allen-panes-chip-title');\n chip.append(el('span', 'allen-panes-chip-kind', NAMES[kind]), chipTitle);\n item.append(chip);\n Object.assign(rec, { el: pane, heading, badge, notice, body, source, foot, move, size, grab, min, max, shut, item, chip, chipTitle, swallow: 0 });\n label(rec);\n pane.addEventListener('pointerdown', () => raise(rec), true);\n pane.addEventListener('focusin', () => raise(rec));\n drag(rec, head, 'move');\n swipe(rec, head);\n swipe(rec, grab);\n pane.addEventListener('click', event => {\n if (event.timeStamp > rec.swallow) return;\n rec.swallow = 0;\n event.preventDefault();\n event.stopPropagation();\n }, true);\n drag(rec, size, 'size');\n keyed(rec, move, 'move');\n keyed(rec, size, 'size');\n layer.append(pane);\n chips.append(item);\n panes.set(key, rec);\n order.push(rec);\n initial(rec);\n stack();\n return rec;\n }\n /* Bottom sheet gestures, only on the grab strip and the title bar, so the\n content keeps its own scrolling, selection and editing. Down past a\n quarter of the sheet (or a quick flick) minimizes; sideways shows the\n neighbouring pane. A swipe never reaches the button it started on. */\n function swipe(rec, zone) {\n zone.addEventListener('pointerdown', event => {\n if (!sheet() || !event.isPrimary || event.button !== 0) return;\n const start = { x: event.clientX, y: event.clientY, t: event.timeStamp };\n const height = Math.max(1, rec.el.getBoundingClientRect().height);\n let mode = '';\n let last = event;\n let frame = 0;\n const paint = () => {\n frame = 0;\n if (!alive || !mode) return;\n const dx = last.clientX - start.x;\n const dy = last.clientY - start.y;\n rec.el.style.setProperty('--allen-pane-swipe-x', mode === 'side' ? `${Math.round(dx / 2)}px` : '0px');\n rec.el.style.setProperty('--allen-pane-swipe-y', mode === 'down' ? `${Math.round(Math.max(0, dy))}px` : '0px');\n };\n const settle = () => {\n rec.el.classList.remove('is-swiping');\n rec.el.style.removeProperty('--allen-pane-swipe-x');\n rec.el.style.removeProperty('--allen-pane-swipe-y');\n };\n const onMove = e => {\n if (e.pointerId !== event.pointerId) return;\n last = e;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n if (!mode) {\n if (Math.abs(dx) < 10 && Math.abs(dy) < 10) return;\n mode = Math.abs(dy) >= Math.abs(dx) ? (dy > 0 ? 'down' : 'up') : 'side';\n try {\n zone.setPointerCapture(e.pointerId);\n } catch (_) {}\n rec.el.classList.add('is-swiping');\n }\n if (mode !== 'up' && !frame) frame = requestAnimationFrame(paint);\n };\n const onEnd = e => {\n if (e.pointerId !== event.pointerId) return;\n zone.removeEventListener('pointermove', onMove);\n zone.removeEventListener('pointerup', onEnd);\n zone.removeEventListener('pointercancel', onEnd);\n if (frame) cancelAnimationFrame(frame);\n frame = 0;\n settle();\n if (!mode) return;\n rec.swallow = e.timeStamp + 500;\n if (e.type === 'pointercancel' || !alive) return;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n const speed = Math.max(Math.abs(dx), Math.abs(dy)) / Math.max(1, e.timeStamp - start.t);\n if (mode === 'down' && (dy > height / 4 || (dy > 24 && speed > 0.6))) minimize(rec);\n else if (mode === 'side' && (Math.abs(dx) > 72 || (Math.abs(dx) > 24 && speed > 0.6))) neighbour(rec, dx < 0 ? 1 : -1);\n };\n zone.addEventListener('pointermove', onMove);\n zone.addEventListener('pointerup', onEnd);\n zone.addEventListener('pointercancel', onEnd);\n });\n }\n function neighbour(rec, dir) {\n const all = [...panes.values()];\n if (all.length < 2) return;\n const next = all[(all.indexOf(rec) + dir + all.length) % all.length];\n const had = rec.el.contains(document.activeElement);\n restore(next, had);\n say(`${next.title}, pane ${all.indexOf(next) + 1} of ${all.length}.`);\n }\n function drag(rec, handle, mode) {\n handle.addEventListener('pointerdown', event => {\n if (event.button !== 0 || sheet() || rec.maximized) return;\n const hit = event.target.closest('button');\n if (mode === 'move' && hit && hit !== rec.move) return;\n event.preventDefault();\n raise(rec);\n const start = { x: event.clientX, y: event.clientY, g: { ...rec.geom } };\n let frame = 0;\n let last = null;\n try {\n handle.setPointerCapture(event.pointerId);\n } catch (_) {}\n rec.el.classList.add(mode === 'move' ? 'is-moving' : 'is-sizing');\n const apply = () => {\n frame = 0;\n if (!last || !alive) return;\n const dx = last.clientX - start.x;\n const dy = last.clientY - start.y;\n if (mode === 'move') place(rec, start.g.x + dx, start.g.y + dy, start.g.w, start.g.h);\n else place(rec, start.g.x, start.g.y, start.g.w + dx, start.g.h + dy);\n };\n const onMove = e => {\n if (e.pointerId !== event.pointerId) return;\n last = e;\n if (!frame) frame = requestAnimationFrame(apply);\n };\n const onUp = e => {\n if (e.pointerId !== event.pointerId) return;\n handle.removeEventListener('pointermove', onMove);\n handle.removeEventListener('pointerup', onUp);\n handle.removeEventListener('pointercancel', onUp);\n if (frame) cancelAnimationFrame(frame);\n apply();\n rec.el.classList.remove('is-moving', 'is-sizing');\n };\n handle.addEventListener('pointermove', onMove);\n handle.addEventListener('pointerup', onUp);\n handle.addEventListener('pointercancel', onUp);\n });\n }\n function keyed(rec, handle, mode) {\n handle.addEventListener('keydown', event => {\n const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[event.key];\n if (!d || event.altKey || event.ctrlKey || event.metaKey || sheet() || rec.maximized) return;\n event.preventDefault();\n const s = event.shiftKey ? BIG_STEP : STEP;\n const g = rec.geom;\n if (mode === 'move') place(rec, g.x + d[0] * s, g.y + d[1] * s, g.w, g.h);\n else place(rec, g.x, g.y, g.w + d[0] * s, g.h + d[1] * s);\n });\n handle.addEventListener('keyup', event => {\n if (!event.key.startsWith('Arrow') || sheet() || rec.maximized) return;\n const g = rec.geom;\n say(mode === 'move' ? `${rec.title} at ${g.x}, ${g.y}.` : `${rec.title} is ${g.w} by ${g.h}.`);\n });\n }\n function minimize(rec) {\n if (rec.minimized) return;\n const had = rec.el.contains(document.activeElement);\n rec.minimized = true;\n rec.el.hidden = true;\n chipState(rec);\n stack();\n if (had) rec.chip.focus();\n say(`${rec.title} minimized; it stays in the pane list.`);\n }\n function restore(rec, focus) {\n if (rec.minimized) {\n rec.minimized = false;\n rec.el.hidden = false;\n chipState(rec);\n }\n raise(rec);\n if (focus) rec.el.focus({ preventScroll: true });\n }\n function maximize(rec) {\n rec.maximized = !rec.maximized;\n rec.el.classList.toggle('is-max', rec.maximized);\n label(rec);\n raise(rec);\n }\n function chipClick(rec) {\n if (rec.minimized) restore(rec, true);\n else if (topmost() === rec) minimize(rec);\n else restore(rec, true);\n }\n function dataPane(rec) {\n return KINDS.includes(rec.kind) && rec.revision > 0;\n }\n function entry(rec) {\n 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 };\n }\n function reopenState() {\n const last = closed[closed.length - 1];\n reopenButton.hidden = !last;\n if (last) reopenButton.setAttribute('aria-label', `Reopen ${last.title}`);\n }\n function close(rec, byPerson, quiet) {\n if (panes.get(rec.id) !== rec) return;\n const had = rec.el.contains(document.activeElement);\n stopApp(rec);\n rec.el.remove();\n rec.item.remove();\n panes.delete(rec.id);\n order = order.filter(r => r !== rec);\n const kept = dataPane(rec);\n if (kept) {\n closed.push(entry(rec));\n while (closed.length > MAX_CLOSED) closed.shift();\n }\n reopenState();\n stack();\n if (had) {\n const next = topmost();\n if (next) next.el.focus({ preventScroll: true });\n else if (opts.returnFocus instanceof HTMLElement && opts.returnFocus.isConnected) opts.returnFocus.focus();\n else projectsButton.focus();\n }\n if (!quiet) say(byPerson ? `${rec.title} closed.${kept ? ' Reopen brings it back.' : ''}` : `Aien closed ${rec.title}.`);\n if (typeof opts.onClose === 'function') {\n try {\n opts.onClose(rec.kind === 'card' ? rec.id.slice(5) : rec.id, rec.kind, byPerson);\n } catch (_) {}\n }\n }\n function reopen() {\n const last = closed.pop();\n reopenState();\n if (!last) return;\n const rec = restoreEntry(last);\n if (rec) {\n rec.el.focus({ preventScroll: true });\n say(`${rec.title} reopened.`);\n } else {\n closed.push(last);\n reopenState();\n say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);\n }\n }\n function notify(rec, message) {\n rec.notice.textContent = message;\n rec.notice.hidden = false;\n }\n function waiting(rec) {\n rec.el.setAttribute('aria-busy', 'true');\n rec.body.replaceChildren(el('p', 'allen-pane-note', 'Aien is preparing this pane.'));\n }\n\n" 220 221 note JavaScript apply 222 text js8 " function apply(rec, revision, content, prov) {\n stopApp(rec);\n rec.revision = revision;\n rec.content = copy(content);\n rec.provenance = copy(prov);\n rec.svg = null;\n rec.notice.hidden = true;\n rec.el.removeAttribute('aria-busy');\n rec.body.replaceChildren();\n render(rec);\n rec.badge.textContent = STATUS_NAMES[rec.provenance.status];\n rec.badge.dataset.status = rec.provenance.status;\n rec.badge.hidden = false;\n sourceBlock(rec);\n footBlock(rec);\n }\n function section(heading) {\n const box = el('section', 'allen-pane-section');\n box.append(el('h3', 'allen-pane-h3', heading));\n return box;\n }\n function refList(heading, items) {\n const box = section(heading);\n const list = el('ol', 'allen-pane-refs');\n for (const r of items) {\n const li = el('li');\n li.append(link(r.title, r.url));\n list.append(li);\n }\n box.append(list, el('p', 'allen-pane-label', 'Links are shown as given; this page never fetched or checked them.'));\n return box;\n }\n /* A diff or patch fence gets its own Copy and Download patch. The patch\n is only ever a downloaded file; nothing here applies it. */\n function patchTool(rec) {\n let n = 0;\n return (lang, text) => {\n if (!/^(diff|patch)$/i.test(lang) || !text.trim()) return null;\n n += 1;\n const name = `${slug(rec.title) || 'allen'}${n > 1 ? `-${n}` : ''}.patch`;\n const bar = el('div', 'allen-pane-bar allen-md-tools');\n const copyButton = button('allen-pane-act', `Copy patch ${n} of ${rec.title}`, 'Copy patch', () => copyText(`${text}\\n`, copyButton));\n 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`)));\n return bar;\n };\n }\n function render(rec) {\n const c = rec.content;\n const body = rec.body;\n body.append(el('p', 'allen-pane-caveat', CAVEATS[rec.provenance.status]));\n if (rec.kind === 'math') {\n const result = el('p', 'allen-pane-math', c.text);\n result.setAttribute('aria-label', `Result: ${c.text}`);\n body.append(result);\n if (own(c, 'tex')) body.append(texBlock(c.tex, 'The engine\\u2019s formula'));\n } else if (rec.kind === 'plot') {\n const drawn = plot(c, rec.title);\n rec.svg = drawn.svg;\n body.append(drawn.figure);\n } else if (rec.kind === 'doc') {\n body.append(markdown(c.markdown, el('div', 'allen-md'), patchTool(rec)));\n if (c.citations.length) body.append(refList('Citations', c.citations));\n } else if (rec.kind === 'code' || rec.kind === 'omega') {\n body.append(el('p', 'allen-pane-label', rec.kind === 'omega' ? 'Omega source' : `${clean(c.language, 40) || 'Code'} source`));\n const pre = el('pre', 'allen-pane-code');\n pre.append(el('code', '', c.source));\n body.append(pre);\n if (own(c, 'functions') && c.functions.length) {\n const box = section('Functions');\n const list = el('ul', 'allen-pane-fns');\n 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}`));\n box.append(list);\n body.append(box);\n }\n if (own(c, 'wasm')) {\n const bytes = wasmBytes(c.wasm);\n const box = section('WebAssembly');\n if (bytes) {\n 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)));\n } else {\n box.append(el('p', 'allen-pane-note', 'WebAssembly was attached, but it is not a valid base64 WebAssembly module.'));\n }\n body.append(box);\n }\n } else if (rec.kind === 'app') {\n 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.'));\n const bar = el('div', 'allen-pane-bar');\n const stage = el('div', 'allen-pane-stage');\n const run = button('allen-pane-act allen-pane-run', `Run ${rec.title} in a sandbox`, 'Run', () => runApp(rec, stage, run, stop));\n const stop = button('allen-pane-act', `Stop ${rec.title}`, 'Stop', () => stopApp(rec));\n stop.hidden = true;\n bar.append(run, stop);\n body.append(bar, stage);\n rec.app = { frame: null, run, stop };\n } else if (rec.kind === 'research') {\n const notes = section('Notes');\n notes.append(markdown(c.notes, el('div', 'allen-md'), patchTool(rec)));\n body.append(notes);\n if (c.hypotheses.length) {\n const box = section('Hypotheses');\n const list = el('ul', 'allen-md-list');\n for (const h of c.hypotheses) list.append(inline(el('li'), h));\n box.append(list);\n body.append(box);\n }\n if (c.derivations.length) {\n const box = section('Derivations');\n const list = el('ol', 'allen-pane-derivations');\n for (const d of c.derivations) {\n const li = el('li');\n li.append(el('pre', 'allen-pane-pre', d));\n list.append(li);\n }\n box.append(list);\n body.append(box);\n }\n if (c.sources.length) body.append(refList('Sources', c.sources));\n } else if (rec.kind === 'data') {\n const grid = table(c.columns, c.rows);\n grid.firstChild.setAttribute('aria-labelledby', rec.heading.id);\n body.append(grid);\n }\n }\n function runApp(rec, stage, run, stop) {\n stopApp(rec);\n const frame = document.createElement('iframe');\n frame.setAttribute('sandbox', SANDBOX);\n frame.setAttribute('referrerpolicy', 'no-referrer');\n 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'\");\n frame.setAttribute('title', `${rec.title}, an app written by Aien, sandboxed`);\n frame.className = 'allen-pane-frame';\n /* A srcdoc frame would inherit the page policy, which forbids inline\n scripts; /aien/run.html writes what this page posts, sandboxed. */\n const html = sandboxed(rec.content.html);\n frame.addEventListener('load', () => frame.contentWindow.postMessage(html, '*'), { once: true });\n frame.src = '/aien/run.html';\n stage.replaceChildren(frame);\n rec.app = { frame, run, stop };\n run.hidden = true;\n stop.hidden = false;\n stop.focus();\n }\n function stopApp(rec) {\n if (!rec.app || !rec.app.frame) return;\n const hadFocus = rec.el.contains(document.activeElement);\n rec.app.frame.remove();\n rec.app.frame = null;\n rec.app.run.hidden = false;\n rec.app.stop.hidden = true;\n if (hadFocus && rec.app.run.isConnected) rec.app.run.focus();\n }\n function sourceBlock(rec) {\n const list = el('dl', 'allen-pane-prov');\n const row = (key, value, mono) => {\n if (value === '') return;\n list.append(el('dt', '', key), el('dd', mono ? 'allen-pane-mono' : '', value));\n };\n const p = rec.provenance;\n row('Status', STATUS_NAMES[p.status]);\n row('Engine', p.engine);\n row('Expression', p.expression, true);\n row('Result', p.result, true);\n row('Source', p.source);\n row('Commit', p.commit, true);\n row('Pane', rec.id, true);\n row('Revision', String(rec.revision));\n const raw = el('pre', 'allen-pane-raw', JSON.stringify({ content: rec.content, provenance: rec.provenance }, null, 2));\n raw.setAttribute('aria-label', `Everything Aien sent for ${rec.title}, as JSON`);\n raw.tabIndex = 0;\n rec.source.replaceChildren(el('summary', 'allen-pane-summary', 'Source and provenance'), list, el('p', 'allen-pane-label', 'As received'), raw);\n rec.source.hidden = false;\n }\n function footBlock(rec) {\n const out = artefact(rec);\n if (!out) return;\n const base = slug(rec.title) || rec.kind;\n const ext = out.name.slice(out.name.lastIndexOf('.'));\n const copyButton = button('allen-pane-act', `Copy the ${out.what} of ${rec.title}`, 'Copy', () => copyText(out.copy, copyButton));\n const save = button('allen-pane-act', `Download ${rec.title} as ${ext}`, `Download ${ext}`, () => download(out.name, out.data()));\n 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)));\n rec.foot.replaceChildren(copyButton, save, json);\n const keep = reportSave(rec);\n if (keep) rec.foot.append(...keep);\n rec.foot.hidden = false;\n }\n /* A repo report can become the visitor's own Omega project, only when the\n page supplies saveProject and only after the visitor has seen the file\n list and pressed Save. The page owns the request and the visitor's\n handle; this file never touches the network. */\n function reportSave(rec) {\n if (rec.kind !== 'doc' || typeof opts.saveProject !== 'function') return null;\n const named = REPORT.exec(rec.title);\n if (!named) return null;\n const files = reportFiles(rec.content.markdown);\n const repo = `${named[1]}/${named[2]}`;\n const ports = files.filter(f => f.path.endsWith('.om')).length;\n const box = el('div', 'allen-pane-save');\n box.hidden = true;\n const state = el('p', 'allen-projects-state');\n state.setAttribute('role', 'status');\n const open = button('allen-pane-act allen-pane-run', `Save ${rec.title} to my Omega projects`, 'Save to my Omega projects', () => {\n box.hidden = !box.hidden;\n open.setAttribute('aria-expanded', String(!box.hidden));\n if (!box.hidden) confirm.focus();\n });\n open.setAttribute('aria-expanded', 'false');\n const list = el('ul', 'allen-pane-files');\n for (const f of files) list.append(el('li', 'allen-pane-mono', `${f.path}, ${utf8(f.content)} bytes`));\n 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 () => {\n confirm.disabled = true;\n state.replaceChildren(document.createTextNode('Saving.'));\n let r;\n try {\n 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 })) });\n } catch (_) {\n r = null;\n }\n confirm.disabled = false;\n if (r && r.ok === true) {\n state.replaceChildren(document.createTextNode('Saved. Status: '), statusLink(r.url));\n } else {\n state.replaceChildren(document.createTextNode(r && typeof r.reason === 'string' ? clean(r.reason, 300) : 'The project could not be saved; nothing was stored.'));\n }\n });\n const cancel = button('allen-pane-act', 'Do not save the report', 'Cancel', () => {\n box.hidden = true;\n open.setAttribute('aria-expanded', 'false');\n open.focus();\n });\n const bar = el('div', 'allen-pane-bar');\n bar.append(confirm, cancel);\n 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);\n return [open, box, state];\n }\n function statusLink(url) {\n if (typeof url !== 'string' || !url) return document.createTextNode('no status address was returned.');\n if (/^\\/(?!\\/)/.test(url)) {\n try {\n const here = new URL(url, window.location.href);\n if (here.origin === window.location.origin) {\n const a = el('a', 'allen-link', here.pathname + here.search);\n a.href = here.href;\n return a;\n }\n } catch (_) {}\n }\n return link(url, url);\n }\n function download(name, data) {\n const blob = new Blob([data], { type: 'application/octet-stream' });\n const url = URL.createObjectURL(blob);\n const a = document.createElement('a');\n a.href = url;\n a.download = name;\n a.hidden = true;\n root.append(a);\n a.click();\n a.remove();\n setTimeout(() => URL.revokeObjectURL(url), 30000);\n }\n function file(entries, name) {\n return { format: FORMAT, v: VERSION, name: clean(name || 'Aien panes', MAX_NAME), exported: new Date().toISOString(), panes: entries };\n }\n function snapshot() {\n return order.filter(dataPane).map(entry);\n }\n function exportOpen() {\n const entries = snapshot();\n if (!entries.length) {\n say('There are no panes with content to export yet.');\n return { ok: false, reason: 'nothing to export' };\n }\n download('aien-panes.json', JSON.stringify(file(entries, current ? current.name : 'Aien panes'), null, 2));\n say(`Exported ${entries.length} pane${entries.length === 1 ? '' : 's'} as a JSON file.`);\n return { ok: true, count: entries.length };\n }\n function restoreEntry(p) {\n if (panes.size >= MAX_PANES) return null;\n let key = p.id;\n for (let n = 2; panes.has(key) && n < 100; n++) key = `${p.id.slice(0, 58)}-${n}`;\n if (panes.has(key)) return null;\n const rec = create(key, p.kind, p.title);\n apply(rec, p.revision, p.content, p.provenance);\n if (p.geom) place(rec, p.geom.x, p.geom.y, p.geom.w, p.geom.h);\n if (p.minimized) {\n rec.minimized = true;\n rec.el.hidden = true;\n chipState(rec);\n }\n stack();\n return rec;\n }\n function restoreAll(data) {\n const room = MAX_PANES - panes.size;\n if (data.panes.length > room) return { ok: false, reason: `Only ${room} more pane${room === 1 ? '' : 's'} fit; close some panes first.` };\n for (const p of data.panes) restoreEntry(p);\n return { ok: true, count: data.panes.length };\n }\n\n" 223 224 note JavaScript list 225 text js9 " /* Projects: IndexedDB only after an explicit save; an index store keeps\n the list cheap to read. */\n async function list() {\n try {\n const items = await store('readonly', (_, index) => ask(index.getAll()));\n items.sort((a, b) => String(b.saved).localeCompare(String(a.saved)));\n return { ok: true, projects: items.map(i => ({ id: i.id, name: i.name, saved: i.saved, count: i.count })) };\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n }\n async function save(name) {\n const entries = snapshot();\n if (!entries.length) return { ok: false, reason: 'There are no panes with content to save yet.' };\n const title = clean(name || '', MAX_NAME) || (current ? current.name : `Project ${new Date().toLocaleString()}`);\n const id = current && current.name === title ? current.id : `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n const record = { format: FORMAT, v: VERSION, id, name: title, saved: new Date().toISOString(), panes: entries };\n const bytes = utf8(JSON.stringify(record));\n 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.` };\n try {\n await store('readwrite', async (projects, index) => {\n const existing = await ask(index.get(id));\n const count = await ask(index.count());\n if (!existing && count >= MAX_PROJECTS) throw limit(`${MAX_PROJECTS} projects are saved in this browser; delete one first, or export instead.`);\n await ask(projects.put(record));\n await ask(index.put({ id, name: title, saved: record.saved, count: entries.length }));\n });\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n current = { id, name: title };\n return { ok: true, id, name: title, count: entries.length };\n }\n async function load(id) {\n let record;\n try {\n record = await store('readonly', projects => ask(projects.get(String(id))));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };\n const reason = checkFile(record);\n if (reason) return { ok: false, reason: `The saved project could not be read: ${reason}.` };\n const done = restoreAll(record);\n if (done.ok) current = { id: record.id, name: record.name };\n return done.ok ? { ok: true, id: record.id, name: record.name, count: done.count } : done;\n }\n async function remove(id) {\n try {\n await store('readwrite', (projects, index) => Promise.all([ask(projects.delete(String(id))), ask(index.delete(String(id)))]));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (current && current.id === id) current = null;\n return { ok: true, id };\n }\n async function exportSaved(id) {\n let record;\n try {\n record = await store('readonly', projects => ask(projects.get(String(id))));\n } catch (error) {\n return { ok: false, reason: storageError(error) };\n }\n if (!record) return { ok: false, reason: 'That project is no longer saved in this browser.' };\n download(`${slug(record.name) || 'allen-project'}.json`, JSON.stringify(record, null, 2));\n return { ok: true, id };\n }\n async function importFile(source) {\n let text;\n if (typeof source === 'string') text = source;\n else if (source && typeof source.text === 'function' && typeof source.size === 'number') {\n if (source.size > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };\n try {\n text = await source.text();\n } catch (_) {\n return { ok: false, reason: 'This browser could not read the file.' };\n }\n } else return { ok: false, reason: 'Import takes a project file or its JSON text.' };\n if (utf8(text) > MAX_PROJECT_BYTES) return { ok: false, reason: `A project file holds at most ${MAX_PROJECT_BYTES} bytes.` };\n let data;\n try {\n data = JSON.parse(text);\n } catch (_) {\n return { ok: false, reason: 'That file is not JSON.' };\n }\n const reason = checkFile(data);\n if (reason) return { ok: false, reason: `That file was refused: ${reason}.` };\n return restoreAll(data);\n }\n function project(command, arg) {\n if (!alive) return Promise.resolve({ ok: false, reason: 'unmounted' });\n if (command === 'save') return save(arg);\n if (command === 'list') return list();\n if (command === 'open') return load(arg);\n if (command === 'remove') return remove(arg);\n if (command === 'export') return arg === undefined ? Promise.resolve(exportOpen()) : exportSaved(arg);\n if (command === 'import') return importFile(arg);\n if (command === undefined || command === 'panel') {\n projectsPane();\n return Promise.resolve({ ok: true });\n }\n return Promise.resolve({ ok: false, reason: 'unknown project command' });\n }\n function projectsPane() {\n let rec = panes.get('#projects');\n if (rec) {\n restore(rec, true);\n refreshProjects(rec);\n return;\n }\n if (panes.size >= MAX_PANES) {\n say(`At most ${MAX_PANES} panes can be open. Close one to make room.`);\n return;\n }\n rec = create('#projects', 'projects', 'Projects');\n const body = rec.body;\n const status = el('p', 'allen-projects-state');\n status.setAttribute('role', 'status');\n const show = r => {\n status.textContent = r.ok ? r.message : r.reason;\n };\n const form = el('form', 'allen-projects-form');\n const nameId = uid('allen-project-name');\n const nameLabel = el('label', 'allen-pane-label', 'Project name');\n nameLabel.htmlFor = nameId;\n const input = el('input', 'allen-projects-name');\n input.id = nameId;\n input.type = 'text';\n input.maxLength = MAX_NAME;\n input.autocomplete = 'off';\n input.value = current ? current.name : '';\n const submit = el('button', 'allen-pane-act allen-pane-run', 'Save project');\n submit.type = 'submit';\n form.append(nameLabel, input, submit);\n form.addEventListener('submit', async event => {\n event.preventDefault();\n submit.disabled = true;\n const r = await save(input.value);\n submit.disabled = false;\n show(r.ok ? { ok: true, message: `Saved ${r.name} with ${r.count} pane${r.count === 1 ? '' : 's'} in this browser.` } : r);\n if (r.ok) {\n input.value = r.name;\n refreshProjects(rec);\n }\n });\n const saved = el('ul', 'allen-projects-list');\n const fileId = uid('allen-project-file');\n const fileLabel = el('label', 'allen-pane-label', 'Import a project file (.json)');\n fileLabel.htmlFor = fileId;\n const picker = el('input', 'allen-projects-file');\n picker.id = fileId;\n picker.type = 'file';\n picker.accept = 'application/json,.json';\n picker.addEventListener('change', async () => {\n const chosen = picker.files && picker.files[0];\n picker.value = '';\n if (!chosen) return;\n const r = await importFile(chosen);\n show(r.ok ? { ok: true, message: `Imported ${r.count} pane${r.count === 1 ? '' : 's'}. Nothing is stored until you press Save project.` } : r);\n });\n const exporter = button('allen-pane-act', 'Export the open panes as a JSON file', 'Export open panes', () => {\n const r = exportOpen();\n 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.' });\n });\n const tools = el('div', 'allen-pane-bar');\n tools.append(exporter);\n const academy = el('p', 'allen-pane-note allen-projects-academy');\n academy.append(link('Train your agent', ACADEMY));\n 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);\n if (typeof opts.syncSummary === 'function') body.append(summaryBox(show));\n rec.projects = { saved, show };\n refreshProjects(rec);\n rec.el.focus({ preventScroll: true });\n }\n /* Only when the page supplies syncSummary (a visitor with a remember key):\n a short summary the visitor reads and edits first, sent on one explicit\n click. Panes, code and data never leave the browser this way. */\n function draft() {\n const parts = snapshot().map(p => `${NAMES[p.kind]}: ${p.title}`);\n let text = `${current ? current.name : 'Project'}: ${parts.join('; ')}`;\n while (utf8(text) > SYNC_MAX) text = text.slice(0, -1);\n return text;\n }\n function summaryBox(show) {\n const box = section('Sync a short summary');\n const areaId = uid('allen-project-summary');\n 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.`);\n const areaLabel = el('label', 'allen-pane-label', 'Summary to sync');\n areaLabel.htmlFor = areaId;\n const area = el('textarea', 'allen-projects-summary');\n area.id = areaId;\n area.rows = 3;\n area.value = draft();\n const count = el('p', 'allen-pane-label');\n const recount = () => {\n const n = utf8(area.value);\n count.textContent = `${n} of ${SYNC_MAX} bytes`;\n count.dataset.over = n > SYNC_MAX ? 'yes' : 'no';\n };\n area.addEventListener('input', recount);\n recount();\n const refresh = button('allen-pane-act', 'Write the summary again from the open panes', 'Draft again', () => {\n area.value = draft();\n recount();\n });\n const send = button('allen-pane-act allen-pane-run', 'Sync this short summary to Aien\\u2019s memory of you', 'Sync short summary', async () => {\n const text = area.value.trim();\n if (!text) return show({ ok: false, reason: 'The summary is empty.' });\n if (utf8(text) > SYNC_MAX) return show({ ok: false, reason: `The summary is over ${SYNC_MAX} bytes.` });\n send.disabled = true;\n let r;\n try {\n r = await opts.syncSummary(text);\n } catch (_) {\n r = null;\n }\n send.disabled = false;\n 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.' });\n });\n const bar = el('div', 'allen-pane-bar');\n bar.append(refresh, send);\n box.append(note, areaLabel, area, count, bar);\n return box;\n }\n async function refreshProjects(rec) {\n const ui = rec.projects;\n if (!ui) return;\n const r = await list();\n if (!r.ok) {\n ui.saved.replaceChildren(el('li', 'allen-pane-note', r.reason));\n return;\n }\n if (!r.projects.length) {\n ui.saved.replaceChildren(el('li', 'allen-pane-note', 'No projects are saved in this browser.'));\n return;\n }\n ui.saved.replaceChildren(...r.projects.map(p => projectRow(rec, p)));\n }\n function projectRow(rec, p) {\n const name = clean(p.name, MAX_NAME) || 'Untitled';\n const li = el('li', 'allen-projects-item');\n const text = el('div', 'allen-projects-text');\n text.append(el('span', 'allen-projects-title', name), el('span', 'allen-projects-meta', `${p.count} pane${p.count === 1 ? '' : 's'}, saved ${stamp(p.saved)}`));\n const acts = el('div', 'allen-pane-bar');\n const open = button('allen-pane-act', `Open project ${name}`, 'Open', async () => {\n const r = await load(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Opened ${r.name}.` } : r);\n });\n const out = button('allen-pane-act', `Export project ${name} as a JSON file`, 'Export', async () => {\n const r = await exportSaved(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Exported ${name}.` } : r);\n });\n const del = button('allen-pane-act allen-pane-danger', `Delete project ${name} from this browser`, 'Delete', async () => {\n if (del.dataset.armed !== 'yes') {\n del.dataset.armed = 'yes';\n del.textContent = 'Confirm delete';\n del.setAttribute('aria-label', `Confirm: delete project ${name} from this browser`);\n setTimeout(() => {\n if (!del.isConnected) return;\n del.dataset.armed = '';\n del.textContent = 'Delete';\n del.setAttribute('aria-label', `Delete project ${name} from this browser`);\n }, 5000);\n return;\n }\n const r = await remove(p.id);\n rec.projects.show(r.ok ? { ok: true, message: `Deleted ${name} from this browser.` } : r);\n refreshProjects(rec);\n if (rec.el.contains(document.activeElement) || !document.activeElement || document.activeElement === document.body) rec.el.focus({ preventScroll: true });\n });\n acts.append(open, out, del);\n li.append(text, acts);\n return li;\n }\n\n" 226 227 note JavaScript event 228 text js10 " /* The stream and the page call these. */\n function event(name, payload) {\n if (!alive) return { ok: false, reason: 'unmounted' };\n const id = plain(payload) && typeof payload.id === 'string' ? payload.id : '';\n const rec = ID.test(id) ? panes.get(id) : undefined;\n if (name === 'pane.close' && plain(payload) && !rec) {\n const bad = check(name, payload, '');\n if (bad) return refuse(name, bad);\n closedIds.add(id);\n return { ok: true, id };\n }\n if (name === 'pane.update' && !rec) return refuse(name, 'the pane is not open');\n const reason = check(name, payload, rec ? rec.kind : '');\n if (reason) {\n if (rec && name === 'pane.update') notify(rec, `Aien sent an update this page could not show (${reason}). The last good version stays.`);\n return refuse(name, reason);\n }\n if (name === 'pane.open') {\n if (rec || closedIds.has(id)) return refuse(name, 'that pane id was already opened');\n if (panes.size >= MAX_PANES) {\n say(`Aien tried to open another pane, but at most ${MAX_PANES} can be open. Close one to make room.`);\n return refuse(name, 'too many panes');\n }\n const made = create(id, payload.kind, payload.title);\n waiting(made);\n say(`Aien opened a ${NAMES[made.kind]} pane: ${made.title}.`);\n return { ok: true, id };\n }\n if (name === 'pane.update') {\n if (payload.revision <= rec.revision) return refuse(name, 'the revision is not newer');\n apply(rec, payload.revision, payload.content, payload.provenance);\n return { ok: true, id, revision: payload.revision };\n }\n closedIds.add(id);\n close(rec, false);\n return { ok: true, id };\n }\n function open(payload) {\n if (!plain(payload)) return refuse('open', 'open takes an object');\n const id = own(payload, 'id') ? payload.id : `local-${Date.now().toString(36)}${(serial += 1)}`;\n const opened = event('pane.open', { v: VERSION, id, kind: payload.kind, title: payload.title });\n if (!opened.ok || !own(payload, 'content')) return opened;\n const rec = panes.get(id);\n const prov = own(payload, 'provenance') ? payload.provenance : { status: 'unverified', engine: '', expression: '', result: '', source: 'this page', commit: '' };\n const updated = event('pane.update', { v: VERSION, id, revision: own(payload, 'revision') ? payload.revision : rec.revision + 1, content: payload.content, provenance: prov });\n if (!updated.ok) close(rec, false, true);\n return updated;\n }\n function openNode(spec) {\n if (!alive) return { ok: false, reason: 'unmounted' };\n const node = spec && spec.node;\n if (!(node instanceof Node) || node.nodeType === Node.DOCUMENT_NODE) return refuse('openNode', 'openNode takes a node built by this page');\n const id = spec && typeof spec.id === 'string' && ID.test(spec.id) ? spec.id : `card${(serial += 1)}`;\n const key = `card:${id}`;\n let rec = panes.get(key);\n if (!rec) {\n if (panes.size >= MAX_PANES) return refuse('openNode', 'too many panes');\n rec = create(key, 'card', typeof spec.title === 'string' ? spec.title : 'Aien');\n } else if (typeof spec.title === 'string') {\n rec.title = clean(spec.title, MAX_TITLE) || rec.title;\n label(rec);\n }\n rec.body.replaceChildren(node);\n restore(rec, spec.focus === true);\n return { ok: true, id, close: () => close(rec, false) };\n }\n function cycle(dir, from) {\n const stops = [...panes.values()].filter(r => !r.minimized).map(r => r.el);\n stops.push(dock);\n const at = stops.findIndex(s => s.contains(from));\n const next = stops[(at + dir + stops.length) % stops.length];\n if (next === dock) (chips.querySelector('button') || projectsButton).focus();\n else next.focus({ preventScroll: true });\n }\n function onKey(e) {\n if (e.defaultPrevented || !alive) return;\n if (e.key === 'Escape') {\n const inside = root.contains(e.target);\n const loose = e.target === document.body || e.target === document.documentElement || e.target === document;\n if (!inside && !loose) return;\n const rec = inside ? owner(e.target) : null;\n const target = rec && !rec.minimized ? rec : topmost();\n if (!target) return;\n e.preventDefault();\n minimize(target);\n return;\n }\n if (e.key === 'F6' && root.contains(e.target)) {\n e.preventDefault();\n cycle(e.shiftKey ? -1 : 1, e.target);\n }\n }\n function destroy() {\n if (!alive) return;\n for (const rec of panes.values()) stopApp(rec);\n alive = false;\n document.removeEventListener('keydown', onKey);\n window.removeEventListener('resize', onResize);\n if (media) {\n if (typeof media.removeEventListener === 'function') media.removeEventListener('change', layout);\n else if (typeof media.removeListener === 'function') media.removeListener(layout);\n }\n if (fitting) cancelAnimationFrame(fitting);\n root.remove();\n panes.clear();\n order = [];\n closed.length = 0;\n }\n\n" 229 230 note JavaScript prelude 231 text js11 " document.addEventListener('keydown', onKey);\n window.addEventListener('resize', onResize);\n if (media) {\n if (typeof media.addEventListener === 'function') media.addEventListener('change', layout);\n else if (typeof media.addListener === 'function') media.addListener(layout);\n }\n layout();\n stack();\n return { event, open, openNode, project, destroy };\n }\n\n window.AllenPanes = Object.freeze({ version: VERSION, mount, check });\n window.dispatchEvent(new CustomEvent('allen-panes-ready', { detail: { version: VERSION } }));\n})();\n" 232 233 fn main to int 234 if ne PLOTMAX 1.`0e100f64` 235 trap 3 236 end 237 js_0 238 js_1 239 js_2 240 js_3 241 js_4 242 js_5 243 js_6 244 js_7 245 js_8 246 js_9 247 js_10 248 js_11 249 if eq get marker 0 1 250 trap 3 251 end 252 flush 253 ret 0 254 end 255 256 fn js_0 to void 257 for b ulong len js0 258 byteput get js0 b 259 end 260 end 261 262 fn js_1 to void 263 for b ulong len js1 264 byteput get js1 b 265 end 266 end 267 268 fn js_2 to void 269 for b ulong len js2 270 byteput get js2 b 271 end 272 end 273 274 fn js_3 to void 275 for b ulong len js3 276 byteput get js3 b 277 end 278 end 279 280 fn js_4 to void 281 for b ulong len js4 282 byteput get js4 b 283 end 284 end 285 286 fn js_5 to void 287 for b ulong len js5 288 byteput get js5 b 289 end 290 end 291 292 fn js_6 to void 293 for b ulong len js6 294 byteput get js6 b 295 end 296 end 297 298 fn js_7 to void 299 for b ulong len js7 300 byteput get js7 b 301 end 302 end 303 304 fn js_8 to void 305 for b ulong len js8 306 byteput get js8 b 307 end 308 end 309 310 fn js_9 to void 311 for b ulong len js9 312 byteput get js9 b 313 end 314 end 315 316 fn js_10 to void 317 for b ulong len js10 318 byteput get js10 b 319 end 320 end 321 322 fn js_11 to void 323 for b ulong len js11 324 byteput get js11 b 325 end 326 end