@iasiv5/dsh-skills 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/locale/en.json +6 -0
  2. package/locale/zh.json +6 -0
  3. package/package.json +4 -2
  4. package/skills/answer-me-with-html/SKILL.md +4 -2
  5. package/skills/answer-me-with-html/scripts/am.mjs +627 -192
  6. package/skills/guizang-ppt-skill/README.en.md +10 -8
  7. package/skills/guizang-ppt-skill/README.md +10 -8
  8. package/skills/guizang-ppt-skill/SKILL.md +20 -16
  9. package/skills/guizang-ppt-skill/assets/template-swiss.html +1068 -456
  10. package/skills/guizang-ppt-skill/assets/template.html +991 -225
  11. package/skills/guizang-ppt-skill/references/checklist.md +5 -4
  12. package/skills/guizang-ppt-skill/references/components.md +9 -5
  13. package/skills/guizang-ppt-skill/references/gz-components.md +289 -0
  14. package/skills/guizang-ppt-skill/references/layouts-swiss.md +17 -17
  15. package/skills/guizang-ppt-skill/references/layouts.md +1 -1
  16. package/skills/guizang-ppt-skill/references/themes-swiss.md +57 -86
  17. package/skills/guizang-ppt-skill/references/themes.md +65 -63
  18. package/skills/guizang-ppt-skill/scripts/gz-theme.mjs +434 -0
  19. package/skills/guizang-social-card-skill/HANDOFF.md +19 -1
  20. package/skills/guizang-social-card-skill/README.en.md +20 -7
  21. package/skills/guizang-social-card-skill/README.md +20 -7
  22. package/skills/guizang-social-card-skill/SKILL.md +7 -5
  23. package/skills/guizang-social-card-skill/assets/template-editorial-card.html +954 -126
  24. package/skills/guizang-social-card-skill/assets/template-swiss-card.html +588 -84
  25. package/skills/guizang-social-card-skill/package-lock.json +90 -1
  26. package/skills/guizang-social-card-skill/package.json +7 -4
  27. package/skills/guizang-social-card-skill/references/background-systems.md +7 -15
  28. package/skills/guizang-social-card-skill/references/components.md +16 -10
  29. package/skills/guizang-social-card-skill/references/gz-components.md +289 -0
  30. package/skills/guizang-social-card-skill/references/layout-recipes.md +1 -1
  31. package/skills/guizang-social-card-skill/references/production-workflow.md +10 -12
  32. package/skills/guizang-social-card-skill/references/style-system.md +1 -1
  33. package/skills/guizang-social-card-skill/references/theme-presets.md +59 -111
  34. package/skills/guizang-social-card-skill/scripts/gz-fonts.mjs +654 -0
  35. package/skills/guizang-social-card-skill/scripts/gz-theme.mjs +434 -0
  36. package/skills/guizang-social-card-skill/scripts/render.mjs +92 -0
  37. package/skills/guizang-social-card-skill/validate-social-deck.mjs +11 -6
@@ -30,7 +30,7 @@ var init_temml = __esm({
30
30
 
31
31
  // src/cli.js
32
32
  import { parseArgs } from "node:util";
33
- import { readFileSync as readFileSync9, writeFileSync as writeFileSync7, mkdirSync as mkdirSync4, existsSync as existsSync7, rmSync as rmSync7, statSync as statSync4 } from "node:fs";
33
+ import { readFileSync as readFileSync10, writeFileSync as writeFileSync8, mkdirSync as mkdirSync6, existsSync as existsSync8, rmSync as rmSync7, statSync as statSync5 } from "node:fs";
34
34
 
35
35
  // src/assets.js
36
36
  var VERSION = "0.5.10";
@@ -636,7 +636,7 @@ table.am-mark { background: none; }
636
636
  .am-remark-kind::before { content: attr(data-n); margin-inline-end: 5px; color: var(--ink-3); font-family: var(--font-mono); font-size: var(--am-fs-label); }
637
637
  @media print { .am-remark-pop { display: none !important; } }
638
638
  `;
639
- var RUNTIME_JS = "(() => {\n// How a formula reads in a quote. MathML has no plain text, so src/math.js writes the formula as the draft wrote it, delimiters included, in\n// data-am-tex on the <math> element, and the Remark and Reply scripts read page text through this file. On a page without math there is no\n// such element, so formulaOf is null and every text comes out as it did before.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n\nconst TEX = 'data-am-tex';\n\n// The formula that holds a node, or null.\nconst formulaOf = (node) => node.parentElement?.closest(`[${TEX}]`) ?? null;\n\nconst firstText = (el) => {\n for (const child of el.childNodes) {\n const found = child.nodeType === 3 ? child : firstText(child);\n if (found) return found;\n }\n return null;\n};\n\n// What a text node adds to a quote: its data. The first text node of a formula adds the formula, and the others add nothing.\n// (A formula in an error style is plain text with its delimiters, not a <math>, so it comes out once.)\nfunction nodeText(node) {\n const math = formulaOf(node);\n if (!math) return node.data;\n return firstText(math) === node ? math.getAttribute(TEX) : '';\n}\n\n// The text of a node as textContent reads it, but with each formula as written.\nconst textWithMath = (node) => (node.nodeType === 3 ? nodeText(node) : [...node.childNodes].map(textWithMath).join(''));\n\n(() => {\n const root = document.documentElement;\n // A host that serves this page inside its own document leaves the real root without the page's settings. The toolbar keeps a copy;\n // set back what the root lacks, before anything below reads the root. A root's own value, even an empty one, is never replaced.\n const carrier = document.querySelector('.am-toolbar');\n for (const [attr, key] of [['lang', 'data-am-root-lang'], ['dir', 'data-am-root-dir'], ['data-theme', 'data-am-root-theme'], ['data-mode', 'data-am-root-mode'], ['data-style', 'data-am-root-style']]) {\n if (root.getAttribute(attr) === null && carrier?.getAttribute(key) != null) root.setAttribute(attr, carrier.getAttribute(key));\n }\n // Each toolbar list sets one root attribute; its options name the values, so the runtime names no theme or mode.\n for (const [name, attr] of [['theme', 'data-theme'], ['mode', 'data-mode']]) {\n const select = document.querySelector(`select[data-am=\"${name}\"]`);\n if (!select) continue;\n select.value = root.getAttribute(attr);\n select.addEventListener('change', () => root.setAttribute(attr, select.value));\n }\n\n // \u2500\u2500 Text size \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // A\u2212 / A+ set --am-scale on the root; every page size and line (src/themes/type-scale.js) follows it, and the drawing boxes grow\n // with it while their viewBox keeps the units Node measured. The buttons carry the range from SCALE, so this script keeps no\n // second copy of the numbers. A reader's choice is remembered in this browser and wins over the page's own scale; where storage\n // is off (am serve, file://) it lasts for this tab, and the click still works.\n const scaleDown = document.querySelector('[data-am=\"scale-down\"]');\n const scaleUp = document.querySelector('[data-am=\"scale-up\"]');\n if (scaleDown && scaleUp) {\n const min = Number(scaleDown.dataset.min);\n const max = Number(scaleDown.dataset.max);\n const step = Number(scaleDown.dataset.step);\n const storeKey = 'am-scale';\n let value;\n\n const inRange = (n) => Number.isFinite(n) && n >= min && n <= max;\n const savedScale = () => {\n try {\n return Number(localStorage.getItem(storeKey));\n } catch {\n return NaN;\n }\n };\n const saveScale = (n) => {\n try {\n localStorage.setItem(storeKey, String(n));\n } catch {\n // Storage may be off (am serve, file://); the size then lasts until the tab closes.\n }\n };\n\n const updateButtons = () => {\n const setUnavailable = (btn, unavailable) => {\n if (unavailable) btn.setAttribute('aria-disabled', 'true');\n else btn.removeAttribute('aria-disabled');\n };\n setUnavailable(scaleDown, value <= min);\n setUnavailable(scaleUp, value >= max);\n };\n\n // One step is a multiple of `step`: Math.round first, then two decimals, so 1.1500000000000001 becomes 1.15.\n const setScale = (next, remember = false) => {\n value = Math.min(max, Math.max(min, Number((Math.round(next / step) * step).toFixed(2))));\n root.style.setProperty('--am-scale', String(value));\n for (const svg of document.querySelectorAll('.am-diagram:not(.am-lightbox-canvas) > svg[role=\"img\"]')) {\n const box = svg.viewBox?.baseVal;\n if (!box || !(box.width > 0) || !(box.height > 0)) continue;\n svg.setAttribute('width', String(Math.ceil(box.width * value)));\n svg.setAttribute('height', String(Math.ceil(box.height * value)));\n }\n updateButtons();\n if (remember) saveScale(value);\n window.dispatchEvent(new Event('am-scale'));\n };\n\n // A page with no stored choice is left exactly as it was rendered: no inline variable, no svg rewrite, no extra layout pass.\n value = parseFloat(getComputedStyle(root).getPropertyValue('--am-scale')) || 1;\n updateButtons();\n const saved = savedScale();\n if (inRange(saved) && saved !== value) setScale(saved);\n scaleDown.hidden = false;\n scaleUp.hidden = false;\n scaleDown.addEventListener('click', () => {\n if (scaleDown.getAttribute('aria-disabled') === 'true') return;\n setScale(value - step, true);\n });\n scaleUp.addEventListener('click', () => {\n if (scaleUp.getAttribute('aria-disabled') === 'true') return;\n setScale(value + step, true);\n });\n }\n\n // A phone cannot show the whole toolbar. Its end (Reply, Remark, Copy source) is what a phone showed before the text-size\n // buttons, so open at that end: Theme, Mode and A\u2212 / A+ are reached by scrolling toward the start. A reader scroll leaves the\n // position we set, so a later resize does not pull the toolbar back.\n if (carrier) {\n const rtl = getComputedStyle(carrier).direction === 'rtl';\n let lastProgrammatic = null;\n let readerScrolled = false;\n const scrollToEnd = () => {\n if (carrier.scrollWidth <= carrier.clientWidth) return;\n // Chrome keeps a right-to-left box's scrollLeft negative; the browser clamps either value to the real end.\n carrier.scrollTo({ left: rtl ? -carrier.scrollWidth : carrier.scrollWidth });\n lastProgrammatic = carrier.scrollLeft;\n };\n carrier.addEventListener('scroll', () => {\n if (Math.abs(carrier.scrollLeft - lastProgrammatic) > 1) readerScrolled = true;\n });\n scrollToEnd();\n addEventListener('resize', () => {\n if (!readerScrolled) scrollToEnd();\n });\n }\n\n const copyText = async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n } catch {\n const ta = Object.assign(document.createElement('textarea'), { value: text });\n document.body.append(ta);\n ta.select();\n document.execCommand('copy');\n ta.remove();\n }\n };\n // A button reads its label from data-done for a moment after a copy, then comes back to the label it started from. That label is\n // read once, here: a second click inside the moment would otherwise read the copied label off the button and restore that instead,\n // and the label would never come back. The moment starts again on each click: the timer of the previous one is left to fire and\n // does nothing (a token, so this needs no timer bookkeeping the page scripts do not already have).\n const flasher = (btn) => {\n const idle = btn.textContent;\n let clicks = 0;\n return () => {\n btn.textContent = btn.dataset.done;\n const mine = ++clicks;\n setTimeout(() => { if (mine === clicks) btn.textContent = idle; }, 1400);\n };\n };\n\n const copyBtn = document.querySelector('[data-am=\"copy\"]');\n if (copyBtn) {\n const flash = flasher(copyBtn);\n copyBtn.addEventListener('click', async () => {\n const nodes = document.querySelectorAll('#am-source');\n await copyText(nodes[nodes.length - 1]?.value ?? '');\n flash();\n });\n }\n\n // Each code block copies its own lines, without the line numbers.\n for (const btn of document.querySelectorAll('[data-am=\"copy-code\"]')) {\n const flash = flasher(btn);\n btn.addEventListener('click', async () => {\n const lines = btn.closest('.am-codeblock')?.querySelectorAll('.am-ln') ?? [];\n await copyText([...lines].map((l) => l.textContent).join('\\n'));\n flash();\n });\n }\n\n // \u2500\u2500 Diagram Lightbox & Pan-Zoom Viewer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const diagrams = document.querySelectorAll('.am-diagram:not(.am-lightbox-canvas)');\n const lb = document.querySelector('.am-lightbox');\n if (diagrams.length && lb) {\n const backdrop = lb.querySelector('.am-lightbox-backdrop');\n const titleText = lb.querySelector('.am-lightbox-title-text');\n const stage = lb.querySelector('.am-lightbox-stage');\n const canvas = lb.querySelector('.am-lightbox-canvas');\n const closeBtn = lb.querySelector('.am-lightbox-close');\n const expandLabel = lb.getAttribute('data-expand') || 'Expand diagram';\n\n let scale = 1, x = 0, y = 0, fitScale = 1, curVw = 800, curVh = 600;\n let isDragging = false, activePointerId = null, startX = 0, startY = 0, origX = 0, origY = 0;\n let lastTrigger = null;\n\n const apply = () => {\n canvas.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0) scale(${scale.toFixed(4)})`;\n };\n\n const zoomTo = (newScale, pivotX, pivotY) => {\n newScale = Math.max(0.2, Math.min(6.0, newScale));\n if (Math.abs(newScale - scale) < 0.0001) return;\n const r = newScale / scale;\n x = pivotX - (pivotX - x) * r;\n y = pivotY - (pivotY - y) * r;\n scale = newScale;\n apply();\n };\n\n const open = (diag, trigger) => {\n const svg = [...diag.children].find((el) => el.tagName.toLowerCase() === 'svg');\n if (!svg) return;\n lastTrigger = trigger;\n\n const panel = diag.closest('.am-panel');\n const panelTitle = panel?.querySelector('.am-panel-head h2')?.textContent?.trim() || panel?.querySelector('h2')?.textContent?.trim() || lb.getAttribute('aria-label') || 'Diagram viewer';\n if (titleText) titleText.textContent = panelTitle;\n\n const clone = svg.cloneNode(true);\n const defElements = clone.querySelectorAll('[id]');\n if (defElements.length) {\n const idMap = new Map();\n defElements.forEach((el, i) => {\n const oldId = el.id;\n const newId = `${oldId}-lb-${i}`;\n idMap.set(oldId, newId);\n el.id = newId;\n });\n const urlAttrs = ['marker-start', 'marker-mid', 'marker-end', 'fill', 'stroke', 'filter', 'clip-path', 'mask'];\n clone.querySelectorAll('*').forEach((el) => {\n for (const attr of urlAttrs) {\n const val = el.getAttribute(attr);\n if (val && val.startsWith('url(#')) {\n const id = val.slice(5, -1);\n if (idMap.has(id)) el.setAttribute(attr, `url(#${idMap.get(id)})`);\n }\n }\n const href = el.getAttribute('href') || el.getAttribute('xlink:href');\n if (href && href.startsWith('#')) {\n const id = href.slice(1);\n if (idMap.has(id)) {\n if (el.hasAttribute('href')) el.setAttribute('href', `#${idMap.get(id)}`);\n if (el.hasAttribute('xlink:href')) el.setAttribute('xlink:href', `#${idMap.get(id)}`);\n }\n }\n });\n }\n\n const vb = svg.viewBox?.baseVal;\n curVw = (vb && vb.width > 0) ? vb.width : (parseFloat(svg.getAttribute('width')) || svg.clientWidth || 800);\n curVh = (vb && vb.height > 0) ? vb.height : (parseFloat(svg.getAttribute('height')) || svg.clientHeight || 600);\n clone.style.width = `${curVw}px`;\n clone.style.height = `${curVh}px`;\n canvas.innerHTML = '';\n canvas.append(clone);\n lb.removeAttribute('hidden');\n document.body.style.overflow = 'hidden';\n\n const rect = stage.getBoundingClientRect();\n const pad = 48;\n const availW = Math.max(100, rect.width - pad * 2);\n const availH = Math.max(100, rect.height - pad * 2);\n fitScale = Math.min(availW / curVw, availH / curVh, 1.0);\n scale = fitScale;\n x = (rect.width - curVw * scale) / 2;\n y = (rect.height - curVh * scale) / 2;\n apply();\n closeBtn.focus();\n };\n\n const close = () => {\n if (lb.hasAttribute('hidden')) return;\n lb.setAttribute('hidden', '');\n canvas.innerHTML = '';\n document.body.style.overflow = '';\n lastTrigger?.focus();\n };\n\n stage.addEventListener('wheel', (e) => {\n e.preventDefault();\n const rect = stage.getBoundingClientRect();\n const dy = e.deltaMode === 1 ? e.deltaY * 16 : (e.deltaMode === 2 ? e.deltaY * 400 : e.deltaY);\n const factor = Math.exp(-Math.max(-200, Math.min(200, dy)) * 0.0015);\n zoomTo(scale * factor, e.clientX - rect.left, e.clientY - rect.top);\n }, { passive: false });\n\n stage.addEventListener('pointerdown', (e) => {\n if (e.button !== 0 || isDragging) return;\n isDragging = true;\n activePointerId = e.pointerId;\n startX = e.clientX;\n startY = e.clientY;\n origX = x;\n origY = y;\n stage.setPointerCapture(e.pointerId);\n stage.classList.add('am-panning');\n });\n\n stage.addEventListener('pointermove', (e) => {\n if (!isDragging || e.pointerId !== activePointerId) return;\n x = origX + (e.clientX - startX);\n y = origY + (e.clientY - startY);\n apply();\n });\n\n const endDrag = (e) => {\n if (!isDragging || e.pointerId !== activePointerId) return;\n isDragging = false;\n activePointerId = null;\n stage.classList.remove('am-panning');\n try { stage.releasePointerCapture(e.pointerId); } catch {}\n };\n stage.addEventListener('pointerup', endDrag);\n stage.addEventListener('pointercancel', endDrag);\n\n stage.addEventListener('dblclick', () => {\n const rect = stage.getBoundingClientRect();\n scale = fitScale;\n x = (rect.width - curVw * scale) / 2;\n y = (rect.height - curVh * scale) / 2;\n apply();\n });\n\n closeBtn.addEventListener('click', close);\n backdrop.addEventListener('click', close);\n window.addEventListener('keydown', (e) => {\n if (e.key === 'Escape' && !lb.hasAttribute('hidden')) close();\n });\n\n lb.addEventListener('keydown', (e) => {\n if (e.key !== 'Tab') return;\n const focusables = lb.querySelectorAll('button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])');\n if (!focusables.length) return;\n const first = focusables[0];\n const last = focusables[focusables.length - 1];\n if (e.shiftKey && document.activeElement === first) {\n e.preventDefault();\n last.focus();\n } else if (!e.shiftKey && document.activeElement === last) {\n e.preventDefault();\n first.focus();\n }\n });\n\n const expandSvg = '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><polyline points=\"15 3 21 3 21 9\"></polyline><polyline points=\"9 21 3 21 3 15\"></polyline><line x1=\"21\" y1=\"3\" x2=\"14\" y2=\"10\"></line><line x1=\"3\" y1=\"21\" x2=\"10\" y2=\"14\"></line></svg>';\n diagrams.forEach((diag) => {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'am-diagram-expand';\n btn.title = expandLabel;\n btn.setAttribute('aria-label', expandLabel);\n btn.innerHTML = expandSvg;\n btn.addEventListener('click', () => open(diag, btn));\n diag.prepend(btn);\n });\n }\n})();\n(() => {\n// The reply a reader copies from the page: one Markdown text with the decisions, the panel comments and the block remarks.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n// decisions: [{ panel, question, picked: [label], suggested: [label], touched }]; comments: [{ panel, title, text }];\n// remarks: [{ panel, quote, kind, note }], where quote is the start of the marked block and kind is a key of ui.kinds.\n// Comment and remark text is quoted line by line, so text the reader typed cannot pass as part of the structure.\n// rtl: the page reads right to left, so the arrow before each answer points left, the way the text runs.\nfunction replyText({ title, decisions, comments, remarks = [], ui, rtl = false }) {\n const arrow = rtl ? '\u2190' : '\u2192';\n const out = [`# Re: ${title}`];\n if (decisions.length) {\n out.push('', `## ${ui.decisions}`);\n decisions.forEach((d, i) => {\n const answer = d.picked.length ? d.picked.map((l) => `**${l}**`).join(', ') : '**\u2014**';\n // Every option starts unselected, so an ask the reader never clicked has no answer: the reply names the suggestion\n // instead of passing it off as the reader's choice.\n const same = d.picked.length === d.suggested.length && d.picked.every((l) => d.suggested.includes(l));\n const suggested = d.suggested.join(', ') || '\u2014';\n const why = !d.touched ? `${ui.untouched}: ${suggested}` : same ? ui.confirmed : `${ui.was}: ${suggested}`;\n out.push(`${i + 1}. [${d.panel}] ${d.question}`, ` ${arrow} ${answer} _(${why})_`);\n });\n }\n const written = comments.filter((c) => c.text.trim());\n const quoted = (text) => (text.trim() ? text.trim().split('\\n').map((l) => ` > ${l}`) : []);\n if (written.length) {\n out.push('', `## ${ui.comments}`);\n for (const c of written) out.push(`- **${c.panel} \xB7 ${c.title}**`, ...quoted(c.text));\n }\n if (remarks.length) {\n out.push('', `## ${ui.remarks}`);\n for (const r of remarks) {\n const label = [r.panel, ui.kinds?.[r.kind] ?? r.kind].filter(Boolean).join(' \xB7 ');\n out.push(`- **${label}** \"${r.quote}\"`, ...quoted(r.note));\n }\n }\n if (written.length || remarks.some((r) => r.note.trim())) out.push('', `_${ui.typed}_`);\n return `${out.join('\\n')}\\n`;\n}\n\n// A letter of a right-to-left script. One definition for the page builder (src/bidi.js) and for the right-to-left page script\n// (src/runtime/reply-view.js), so the two cannot drift apart. A plain ES module; the page script gets this file in front of\n// reply-view.js, with its `export` keyword dropped and reply-view.js's import of it removed (src/runtime/compose.js).\nconst RTL_LETTER = /[\\p{Script=Hebrew}\\p{Script=Arabic}\\p{Script=Syriac}\\p{Script=Thaana}\\p{Script=Nko}\\p{Script=Samaritan}\\p{Script=Mandaic}]/u;\n\n// The reply as the reader sees it in the Reply sheet (src/runtime/reply.js): the Markdown that Copy copies, drawn as headings, bold answers\n// and quoted comments instead of raw \"# Re: ...\", \"1. [E] ...\" and \"- **A \xB7 ...**\" lines. Each line gets its own direction, so a\n// Hebrew reader sees Latin answers and paths in place; a line with no right-to-left letter reads left to right, as on any other page.\n// The raw Markdown stays in the sheet under a fold, so the copied text does not change.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped and rtl-letter.js in front of it in place of the\n// import (src/runtime/compose.js).\n\nconst escHtml = (s) => s.replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c]);\n// A line with a right-to-left letter reads right to left; a line without one (an English comment, a path) reads left to right.\nconst dirOf = (s) => (RTL_LETTER.test(s) ? 'rtl' : 'ltr');\n\n// The only inline Markdown src/runtime/reply-text.js writes: **answer**, _(note)_ and the \"quote\" of a remark. Each piece is isolated in its own direction,\n// so a Latin answer inside a Hebrew line keeps its place, and \"A \xB7 title\" still starts with the panel letter.\nconst piece = (tag, text) => `<${tag}><bdi dir=\"${dirOf(text)}\">${text}</bdi></${tag}>`;\nfunction inline(s) {\n return escHtml(s)\n .replace(/\\*\\*(.+?)\\*\\*/g, (_, t) => piece('strong', t))\n .replace(/(^|\\s)_(.+?)_(?=\\s|$)/g, (_, pre, t) => pre + piece('em', t))\n // The quoted start of a marked block (\"- **A \xB7 concern** \"text\"\"): isolated, so Latin text in a Hebrew line keeps its place.\n .replace(/&quot;(.+)&quot;$/, (_, t) => `&quot;<bdi dir=\"${dirOf(t)}\">${t}</bdi>&quot;`);\n}\n\n// The reply text (src/runtime/reply-text.js) as HTML, one block per line.\nfunction replyViewHtml(text) {\n return text\n .replace(/\\n$/, '')\n .split('\\n')\n .map((line) => {\n const dir = dirOf(line);\n let m;\n if (!line.trim()) return '<div class=\"am-rv-gap\"></div>';\n if ((m = line.match(/^(#{1,2}) (.*)$/))) return `<div class=\"am-rv-h${m[1].length}\" dir=\"${dir}\">${inline(m[2])}</div>`;\n if ((m = line.match(/^(\\d+)\\. \\[([^\\]]*)\\] (.*)$/))) {\n return `<div class=\"am-rv-q\" dir=\"${dir}\"><bdi>${m[1]}.</bdi> <bdi class=\"am-rv-tag\">${escHtml(m[2])}</bdi> ${inline(m[3])}</div>`;\n }\n if ((m = line.match(/^ {3}([\u2190\u2192]) (.*)$/))) return `<div class=\"am-rv-a\" dir=\"${dir}\">${m[1]} ${inline(m[2])}</div>`;\n if ((m = line.match(/^- (.*)$/))) return `<div class=\"am-rv-c\" dir=\"${dir}\">${inline(m[1])}</div>`;\n // A comment line is shown exactly as the reader typed it.\n if ((m = line.match(/^ {2}> ?(.*)$/))) return `<div class=\"am-rv-quote\" dir=\"${dirOf(m[1])}\">${escHtml(m[1]) || '&nbsp;'}</div>`;\n return `<div dir=\"${dir}\">${inline(line)}</div>`;\n })\n .join('');\n}\n\n// Answer on the page: every panel gets a Comment box, and the Reply button collects the ask answers, the comments and the remarks\n// into one Markdown reply (replyText) to copy back to the agent. Answers and comments stay in localStorage across reloads.\n// The remark script (remark.js) adds the blocks the reader marked, through window.__amRemarkData, and tells this script about a change\n// with an \"am-remark-change\" event on the document.\n// The Reply sheet shows the reply drawn (replyViewHtml) with the Markdown that Copy copies under a fold. Once the reader has given any\n// input, a bar at the bottom of the page shows the counts and copies the reply in one click, so there is no trip to the top-right button.\nconst replyBtn = document.querySelector('[data-am=\"reply\"]');\nconst COMMENT_ICON = '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path></svg>';\nif (replyBtn) {\n const ui = JSON.parse(replyBtn.dataset.ui);\n const storeKey = `am-reply:${location.pathname}`;\n const panels = [...document.querySelectorAll('.am-panel')];\n const asks = [...document.querySelectorAll('.am-ask')];\n // Answers are saved by question text, so they still match after am patch has renumbered the asks.\n // Page text without the word joiners a right-to-left page puts after a Hebrew prefix hyphen (src/bidi.js): the reply and the saved\n // answers hold the text as the draft wrote it, a formula too (src/runtime/math-text.js).\n const WJ = new RegExp(String.fromCharCode(0x2060), 'g');\n const textOf = (el) => el && textWithMath(el).replace(WJ, '').trim();\n const keyOf = (ask) => textOf(ask.querySelector('legend')) ?? ask.dataset.ask;\n const touched = new Set();\n const boxes = new Map();\n // The bar is built below with the sheet; the handlers that change the counts only call this.\n let refreshBar = () => {};\n // The textarea a failed copy keeps selected, so the reader can still use the keyboard shortcut.\n let stuck = null;\n\n const load = () => {\n try {\n return JSON.parse(localStorage.getItem(storeKey)) || {};\n } catch {\n return {};\n }\n };\n const save = () => {\n const state = {\n asks: Object.fromEntries(asks.map((a) => [keyOf(a), { picked: picked(a), touched: touched.has(a) }])),\n comments: Object.fromEntries([...boxes].map(([id, box]) => [id, box.value]).filter(([, text]) => text.trim())),\n };\n try {\n localStorage.setItem(storeKey, JSON.stringify(state));\n } catch {\n // Storage may be off (private window, file:// policy); answers then last until the page closes.\n }\n };\n const picked = (ask) => [...ask.querySelectorAll('input')].filter((i) => i.checked).map((i) => i.value);\n const panelOf = (el) => {\n const panel = el.closest('.am-panel');\n return { id: panel?.id.replace(/^panel-/, '') ?? '', title: textOf(panel?.querySelector('.am-panel-head h2')) ?? '' };\n };\n\n const saved = load();\n for (const ask of asks) {\n const inputs = [...ask.querySelectorAll('input')];\n const state = saved.asks?.[keyOf(ask)];\n // A saved answer applies only while every picked option still exists on the page, and only if the reader clicked: older versions started\n // with the suggestion selected and saved it untouched, and that state must come back unselected.\n if (state?.touched && state.picked.every((v) => inputs.some((i) => i.value === v))) {\n for (const input of inputs) input.checked = state.picked.includes(input.value);\n touched.add(ask);\n }\n // A click counts even on the option that is already picked: the reader confirms the suggestion.\n const answer = () => {\n touched.add(ask);\n save();\n refreshBar();\n };\n ask.addEventListener('change', answer);\n ask.addEventListener('click', (e) => { if (e.target.matches('input')) answer(); });\n }\n\n for (const panel of panels) {\n const id = panel.id.replace(/^panel-/, '');\n // An icon only: narrow panels have no room for a word next to the title.\n const btn = Object.assign(document.createElement('button'), { type: 'button', className: 'am-comment-btn', title: ui.comment, innerHTML: COMMENT_ICON });\n btn.setAttribute('aria-label', `${ui.comment} ${id}`);\n btn.setAttribute('aria-expanded', 'false');\n const wrap = Object.assign(document.createElement('div'), { className: 'am-comment', hidden: true });\n const box = Object.assign(document.createElement('textarea'), { rows: 3, placeholder: ui.commentHint, value: saved.comments?.[id] ?? '' });\n box.setAttribute('aria-label', `${ui.comment} ${id}`);\n wrap.append(box);\n const show = (open) => {\n wrap.hidden = !open;\n btn.setAttribute('aria-expanded', String(open));\n };\n btn.addEventListener('click', () => {\n show(wrap.hidden);\n if (!wrap.hidden) box.focus();\n });\n box.addEventListener('input', () => {\n btn.classList.toggle('am-comment-btn--on', Boolean(box.value.trim()));\n save();\n refreshBar();\n });\n btn.classList.toggle('am-comment-btn--on', Boolean(box.value.trim()));\n if (box.value.trim()) show(true);\n (panel.querySelector('.am-panel-head') ?? panel).append(btn);\n panel.append(wrap);\n boxes.set(id, box);\n }\n\n const sheet = document.createElement('dialog');\n sheet.className = 'am-reply';\n sheet.setAttribute('aria-label', ui.title);\n sheet.innerHTML = '<div class=\"am-reply-head\"><strong></strong><span></span></div><div class=\"am-reply-view\" tabindex=\"0\"></div><details class=\"am-reply-raw\"><summary></summary><textarea readonly rows=\"10\"></textarea></details><div class=\"am-reply-actions\"><button type=\"button\" class=\"am-btn\" data-act=\"copy\"></button><button type=\"button\" class=\"am-btn\" data-act=\"close\"></button></div>';\n sheet.querySelector('strong').textContent = ui.title;\n sheet.querySelector('span').textContent = ui.hint;\n sheet.querySelector('summary').textContent = ui.raw;\n const view = sheet.querySelector('.am-reply-view');\n const raw = sheet.querySelector('details');\n const text = sheet.querySelector('textarea');\n const copy = sheet.querySelector('[data-act=\"copy\"]');\n const close = sheet.querySelector('[data-act=\"close\"]');\n copy.textContent = ui.copy;\n close.textContent = ui.close;\n document.body.append(sheet);\n\n const compose = () => {\n const decisions = asks.map((ask) => ({\n panel: panelOf(ask).id,\n question: textOf(ask.querySelector('legend')) ?? '',\n picked: picked(ask),\n suggested: [...ask.querySelectorAll('input[data-suggested]')].map((i) => i.value),\n touched: touched.has(ask),\n }));\n const comments = [...boxes].map(([id, box]) => ({ panel: id, title: panelOf(box).title, text: box.value }));\n const remarks = window.__amRemarkData?.() ?? [];\n const empty = !decisions.length && !comments.some((c) => c.text.trim()) && !remarks.length;\n const title = textOf(document.querySelector('.am-head h1')) ?? document.title;\n return empty ? '' : replyText({ title, decisions, comments, remarks, ui, rtl: document.documentElement.dir === 'rtl' });\n };\n\n // The text goes through the clipboard API; a page the browser treats as insecure (file://) falls back to selecting a temporary\n // textarea, because the sheet's own textarea can sit inside a closed fold, where it cannot be selected.\n // That fallback reports whether it worked. When it does not, the text stays selected (so Cmd/Ctrl+C still copies it) and the\n // button says what to do instead of showing the \"Copied \u2713\" label the reader cannot trust.\n const copyText = async (str, btn) => {\n stuck?.remove();\n stuck = null;\n try {\n await navigator.clipboard.writeText(str);\n // The close_after_reply script (close-after-reply.js) closes the tab once the reply is on the clipboard.\n document.dispatchEvent(new Event('am-reply-copied'));\n } catch {\n const tmp = Object.assign(document.createElement('textarea'), { value: str });\n tmp.style.cssText = 'position:fixed;top:-100px;opacity:0';\n // Inside the sheet while it is open: while a modal dialog is open the rest of the document cannot take focus, so a textarea\n // in the body can be selected but not focused, and the keyboard shortcut the reader is told to press would copy nothing.\n // The bottom bar copies while the sheet is closed, and a closed dialog is not rendered, so there the textarea goes in the body.\n (sheet.open ? sheet : document.body).append(tmp);\n tmp.select();\n let copied = false;\n try {\n copied = document.execCommand('copy');\n } catch {\n copied = false;\n }\n if (!copied) {\n stuck = tmp;\n btn.textContent = ui.copyFailed;\n setTimeout(() => { btn.textContent = ui.copy; }, 3000);\n return;\n }\n tmp.remove();\n }\n btn.textContent = ui.done;\n setTimeout(() => { btn.textContent = ui.copy; }, 1400);\n };\n\n const open = () => {\n const reply = compose();\n if (reply) view.innerHTML = replyViewHtml(reply);\n else view.textContent = ui.empty;\n view.scrollTop = 0;\n text.value = reply;\n raw.open = false;\n raw.hidden = !reply;\n copy.disabled = !reply;\n if (sheet.showModal) sheet.showModal();\n else sheet.setAttribute('open', '');\n (reply ? copy : close).focus();\n };\n replyBtn.addEventListener('click', open);\n close.addEventListener('click', () => (sheet.close ? sheet.close() : sheet.removeAttribute('open')));\n // A failed copy leaves the text selected for Cmd/Ctrl+C; closing the sheet drops that textarea.\n sheet.addEventListener('close', () => { stuck?.remove(); stuck = null; });\n copy.addEventListener('click', () => copyText(text.value, copy));\n\n const bar = Object.assign(document.createElement('div'), { className: 'am-reply-bar', hidden: true });\n bar.setAttribute('role', 'region');\n bar.setAttribute('aria-label', ui.title);\n const summary = Object.assign(document.createElement('span'), { className: 'am-reply-bar-count' });\n summary.setAttribute('aria-live', 'polite');\n const preview = Object.assign(document.createElement('button'), { type: 'button', className: 'am-btn', textContent: ui.preview });\n const barCopy = Object.assign(document.createElement('button'), { type: 'button', className: 'am-btn am-btn--reply', textContent: ui.copy });\n preview.addEventListener('click', open);\n barCopy.addEventListener('click', () => copyText(compose(), barCopy));\n bar.append(summary, preview, barCopy);\n document.body.append(bar);\n\n // The bar shows only the counts that are above zero, and only once there is any input at all.\n refreshBar = () => {\n const counts = {\n answered: touched.size,\n comments: [...boxes.values()].filter((box) => box.value.trim()).length,\n remarks: (window.__amRemarkData?.() ?? []).length,\n };\n const parts = Object.entries(counts).filter(([, n]) => n > 0).map(([kind, n]) => ui.count[kind].replace('{n}', n));\n summary.textContent = parts.join(' \xB7 ');\n bar.hidden = !parts.length;\n document.body.classList.toggle('am-has-reply-bar', parts.length > 0);\n };\n document.addEventListener('am-remark-change', () => refreshBar());\n // Saved remarks are restored by remark.js, which runs after this script in the same <script> element: its data is not there yet.\n // A microtask runs when that whole element has finished, so the first count includes them.\n queueMicrotask(() => refreshBar());\n}\n})();\n(() => {\n// Text helpers for remark mode (src/runtime/remark.js): how a marked block is named and quoted.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n// A block keeps its mark across `am patch` because the key is its panel, its tag and the start of its text, not its position.\n\nconst collapse = (text) => String(text).replace(/\\s+/g, ' ').trim();\n\n// The start of a block's text with whitespace collapsed: the readable identity of the block.\nfunction fingerprint(text, len = 80) {\n return collapse(text).slice(0, len);\n}\n\n// What the reply quotes of a block: the start of its text, with an ellipsis when it is cut.\nfunction quote(text, len = 60) {\n const t = collapse(text);\n return t.length > len ? `${t.slice(0, len).trimEnd()}\u2026` : t;\n}\n\n// Two blocks with the same text (two identical list items) get the same base key. The n-th one in the page gets \"\\t<n>\" added;\n// a tab cannot be in a fingerprint, which has its whitespace collapsed, so the new key never meets another base key.\nfunction occurrenceKeys(bases) {\n const seen = new Map();\n return bases.map((base) => {\n const n = seen.get(base) ?? 0;\n seen.set(base, n + 1);\n return n ? `${base}\\t${n}` : base;\n });\n}\n\n// Remark mode: the reader turns it on, clicks a block, tags it (suggestion, keep, question, concern) and may add a note.\n// A mark shows as a bar and a note chip inside the block, lives in localStorage like panel comments, and the Reply button carries it\n// back to the agent: reply.js calls window.__amRemarkData, and replyText (reply-text.js) writes the Remarks section.\n(() => {\n const btn = document.querySelector('[data-am=\"remark\"]');\n if (!btn) return;\n const ui = JSON.parse(btn.dataset.ui);\n const KINDS = ['suggestion', 'keep', 'question', 'concern'];\n const storeKey = `am-remark:${location.pathname}`;\n // The one definition of a block a reader can mark: the content under <main>. The page and panel titles are left out, because the\n // reply reads them as text; a panel has its Comment button.\n // A $$ block on its own is a div; a $$ formula inside a sentence is a span of its paragraph.\n const BLOCK = 'main :is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,dd,dt,figure,div.am-math-block):not(.am-head *, .am-panel-head *, .am-toc *)';\n // A click on these does what it always did.\n const LIVE = '.am-remark-pop, .am-toolbar, a, button, input, textarea, select, label';\n const blockAt = (target) => (target.closest(LIVE) ? null : target.closest(BLOCK));\n\n const WJ = new RegExp(String.fromCharCode(0x2060), 'g'); // word joiners of a right-to-left page (src/bidi.js); not part of the draft's text\n // A narrow horizontal timeline shows its date and title inline (src/themes/base.css). They stay parts of their own, so a block key\n // does not change with the width of the window (#194).\n const OWN_BOX = '.am-timeline--h .am-tl-when, .am-timeline--h .am-tl-title';\n const inlineBox = new WeakMap();\n const isInline = (el) => {\n if (!inlineBox.has(el)) inlineBox.set(el, !el.matches(OWN_BOX) && getComputedStyle(el).display.startsWith('inline'));\n return inlineBox.get(el);\n };\n // The text of a block as the reader sees it: separate lines, cells and timeline parts are joined by a space (textContent would run\n // \"2026\" and \"Ship\" together), and the note chip is not part of it. A formula is one box and reads as the TeX the draft wrote\n // (src/runtime/math-text.js), not as the MathML tokens.\n const blockText = (el) => {\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n let text = '';\n let last = null;\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (node.parentElement.closest('.am-mark-note')) continue;\n let box = formulaOf(node) ?? node.parentElement;\n while (box !== el && isInline(box)) box = box.parentElement;\n if (last && box !== last) text += ' ';\n text += nodeText(node).replace(WJ, '');\n last = box;\n }\n return text;\n };\n\n const panelOf = (el) => el.closest('.am-panel')?.id.replace(/^panel-/, '') ?? '';\n // Block keys, in page order. Built when first needed: a page nobody marked pays nothing.\n let keys = null;\n const keyMap = () => {\n if (!keys) {\n const blocks = [...document.querySelectorAll(BLOCK)];\n const ids = occurrenceKeys(blocks.map((el) => `${panelOf(el)}|${el.localName}|${fingerprint(blockText(el))}`));\n keys = new Map(blocks.map((el, i) => [el, ids[i]]));\n }\n return keys;\n };\n\n const load = () => {\n try {\n const saved = JSON.parse(localStorage.getItem(storeKey));\n return Array.isArray(saved) ? saved.filter((m) => typeof m?.key === 'string' && KINDS.includes(m.kind)) : [];\n } catch {\n return [];\n }\n };\n // A mark whose block is gone from the page stays stored (it may return with `am patch`); it is neither painted nor sent.\n const marks = new Map(load().map((m) => [m.key, { key: m.key, kind: m.kind, note: String(m.note ?? '') }]));\n // Kind and note of a popover closed without Save, by block key, until the page reloads (see open below).\n const drafts = new Map();\n const clearBtn = document.createElement('button');\n clearBtn.type = 'button';\n clearBtn.className = 'am-btn am-btn--remark-clear';\n clearBtn.textContent = ui.clear;\n // Clear all drops saved marks and drafts, so it shows while either exists.\n const toClear = () => marks.size + drafts.size;\n const showClear = () => { clearBtn.hidden = toClear() === 0; };\n btn.insertAdjacentElement('afterend', clearBtn);\n let clearTimer = null;\n let clearArmed = false;\n const resetClear = () => {\n if (clearTimer !== null) clearTimeout(clearTimer);\n clearTimer = null;\n clearArmed = false;\n clearBtn.classList.remove('is-armed');\n clearBtn.textContent = ui.clear;\n showClear();\n };\n const armClear = () => {\n clearArmed = true;\n clearBtn.classList.add('is-armed');\n clearBtn.textContent = ui.clearConfirm.replace('{n}', toClear());\n clearTimer = setTimeout(resetClear, 4000);\n };\n clearBtn.addEventListener('click', () => {\n if (!clearArmed) {\n armClear();\n return;\n }\n for (const el of document.querySelectorAll('.am-mark')) unpaint(el);\n marks.clear();\n // A draft is a remark the reader has not saved yet; Clear all drops it too, so no block reopens with an old kind.\n drafts.clear();\n try {\n localStorage.removeItem(storeKey);\n } catch {\n // Storage may be off (private window, a sandboxed page); the in-memory marks still clear.\n }\n resetClear();\n document.dispatchEvent(new Event('am-remark-change'));\n });\n const save = () => {\n try {\n localStorage.setItem(storeKey, JSON.stringify([...marks.values()]));\n } catch {\n // Storage may be off (private window, a sandboxed page); marks then last until the page closes.\n }\n // The reply bar (reply.js) shows the number of marks.\n document.dispatchEvent(new Event('am-remark-change'));\n showClear();\n };\n\n const chip = (el, mark) => {\n const note = document.createElement(el.localName === 'table' ? 'caption' : 'span');\n note.className = 'am-mark-note';\n const kind = document.createElement('b');\n kind.textContent = ui.kinds[mark.kind];\n note.append(kind, mark.note ? ` ${mark.note}` : '');\n return note;\n };\n const clearChip = (el) => el.querySelector(':scope > .am-mark-note')?.remove();\n const paint = (el, mark) => {\n clearChip(el);\n el.classList.add('am-mark');\n el.dataset.kind = mark.kind;\n // Inside the block, so a list item stays a child of its list. A table takes it as its caption; a list item with a sub-list shows\n // it under its own text, before the sub-list.\n const sub = el.querySelector(':scope > ul, :scope > ol');\n if (el.localName === 'table') el.prepend(chip(el, mark));\n else if (sub) sub.before(chip(el, mark));\n else el.append(chip(el, mark));\n };\n const unpaint = (el) => {\n clearChip(el);\n el.classList.remove('am-mark');\n delete el.dataset.kind;\n };\n showClear();\n if (marks.size) for (const [el, key] of keyMap()) if (marks.has(key)) paint(el, marks.get(key));\n\n // The popover edits one block. Save stays off until a kind is picked, and a hint says so. 1\u20134 pick a kind from the keyboard and\n // move to the note; Ctrl / Cmd + Enter saves. A popover closed without Save keeps its kind and note as a draft for that block until the page reloads.\n const pop = document.createElement('div');\n pop.className = 'am-remark-pop';\n pop.hidden = true;\n pop.setAttribute('role', 'dialog');\n pop.setAttribute('aria-label', ui.button);\n document.body.append(pop);\n let opener = null;\n let anchor = null;\n let keepDraft = null;\n const close = (restoreFocus) => {\n if (pop.hidden) return;\n keepDraft?.();\n keepDraft = null;\n pop.hidden = true;\n if (restoreFocus) (opener?.isConnected && opener !== document.body ? opener : btn).focus();\n };\n const place = () => {\n const rect = anchor.getBoundingClientRect();\n const rtl = getComputedStyle(document.documentElement).direction === 'rtl';\n const x = rtl ? rect.right - pop.offsetWidth : rect.left;\n // Under the block; a block taller than the window gets the popover at the bottom of the window instead.\n const y = Math.min(rect.bottom + 6, window.innerHeight - pop.offsetHeight - 8);\n pop.style.left = `${window.scrollX + Math.min(Math.max(8, x), window.innerWidth - pop.offsetWidth - 8)}px`;\n pop.style.top = `${window.scrollY + Math.max(8, y)}px`;\n };\n const make = (tag, props) => Object.assign(document.createElement(tag), props);\n const open = (el) => {\n const key = keyMap().get(el);\n const mark = marks.get(key);\n const draft = drafts.get(key);\n let kind = draft?.kind ?? mark?.kind ?? '';\n opener = document.activeElement;\n anchor = el;\n\n const note = make('textarea', { rows: 2, placeholder: ui.hint, value: draft?.note ?? mark?.note ?? '' });\n note.setAttribute('aria-label', ui.hint);\n const keep = make('button', { type: 'button', className: 'am-btn', textContent: ui.save, disabled: !kind });\n const need = make('span', { className: 'am-remark-need', textContent: ui.need, hidden: Boolean(kind) });\n keepDraft = () => {\n if (kind || note.value.trim()) drafts.set(key, { kind, note: note.value });\n else drafts.delete(key);\n showClear();\n };\n const done = () => { drafts.delete(key); keepDraft = null; showClear(); };\n keep.addEventListener('click', () => {\n done();\n const saved = { key, kind, note: note.value.trim() };\n marks.set(key, saved);\n save();\n paint(el, saved);\n close(true);\n });\n const actions = make('div', { className: 'am-remark-actions' });\n actions.append(keep);\n if (mark) {\n const drop = make('button', { type: 'button', className: 'am-btn', textContent: ui.remove });\n drop.addEventListener('click', () => {\n done();\n marks.delete(key);\n save();\n unpaint(el);\n close(true);\n });\n actions.append(drop);\n }\n const choose = (k) => {\n kind = k;\n for (const other of kindBtns) other.setAttribute('aria-pressed', String(other.dataset.kind === k));\n keep.disabled = false;\n need.hidden = true;\n };\n const kindBtns = KINDS.map((k, i) => {\n const kb = make('button', { type: 'button', className: 'am-remark-kind', textContent: ui.kinds[k] });\n kb.dataset.kind = k;\n kb.dataset.n = i + 1;\n kb.setAttribute('aria-pressed', String(k === kind));\n kb.addEventListener('click', () => choose(k));\n return kb;\n });\n // Ctrl / Cmd + Enter presses Save (nothing while Save waits for a kind). A digit types into the note, so it picks a kind\n // only while the focus is outside the note.\n pop.onkeydown = (e) => {\n if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !e.isComposing) {\n e.preventDefault();\n if (!keep.disabled) keep.click();\n return;\n }\n if (e.target === note || e.ctrlKey || e.metaKey || e.altKey || !/^[1-4]$/.test(e.key)) return;\n e.preventDefault();\n choose(KINDS[Number(e.key) - 1]);\n note.focus();\n };\n actions.append(need);\n pop.replaceChildren(make('div', { className: 'am-remark-kinds' }), note, actions);\n pop.firstChild.append(...kindBtns);\n pop.hidden = false;\n place();\n (kindBtns.find((b) => b.dataset.kind === kind) ?? kindBtns[0]).focus({ preventScroll: true });\n };\n\n // Picking works only while remark mode is on. A click on a marked block edits its mark, on a plain block starts one.\n // The block under the pointer gets an outline: the same blockAt decides what is outlined and what a click picks.\n let hover = null;\n const track = (e) => {\n const el = e.type === 'mouseout' && e.relatedTarget === null ? null : blockAt(e.target);\n if (el === hover) return;\n hover?.classList.remove('am-remark-hover');\n hover = el;\n hover?.classList.add('am-remark-hover');\n };\n const pick = (e) => {\n const el = blockAt(e.target);\n if (el) open(el);\n };\n // The keyboard picks too: while the mode is on, every block takes focus with Tab, and Enter or Space opens its popover. A block\n // that already had a tabindex keeps it; only the ones the mode added lose it again.\n const pickKey = (e) => {\n if ((e.key !== 'Enter' && e.key !== ' ') || e.ctrlKey || e.metaKey || e.altKey || !e.target.hasAttribute?.('data-am-pick')) return;\n e.preventDefault();\n open(e.target);\n };\n const focusable = (on) => {\n if (!on && !keys) return; // the mode starts off: a page nobody marked builds no block keys\n for (const el of keyMap().keys()) {\n if (on && !el.hasAttribute('tabindex')) {\n el.tabIndex = 0;\n el.setAttribute('data-am-pick', '');\n } else if (!on && el.hasAttribute('data-am-pick')) {\n el.removeAttribute('tabindex');\n el.removeAttribute('data-am-pick');\n }\n }\n };\n const setMode = (on) => {\n btn.classList.toggle('is-on', on);\n btn.setAttribute('aria-pressed', String(on));\n const toggle = on ? 'addEventListener' : 'removeEventListener';\n document.body[toggle]('click', pick);\n document.body[toggle]('mouseover', track);\n document.body[toggle]('mouseout', track);\n document.body[toggle]('keydown', pickKey);\n focusable(on);\n if (!on) {\n track({ type: 'mouseout', relatedTarget: null });\n close(false);\n }\n };\n btn.addEventListener('click', () => setMode(btn.getAttribute('aria-pressed') !== 'true'));\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') close(true);\n });\n // A click outside the popover closes it; the same click may then start another mark.\n document.addEventListener('click', (e) => {\n if (!pop.hidden && !pop.contains(e.target)) close(false);\n }, true);\n setMode(false);\n\n // What the Reply button reads: the marked blocks that are on the page, in page order.\n window.__amRemarkData = () => {\n if (!marks.size) return [];\n const live = [];\n for (const [el, key] of keyMap()) {\n const mark = marks.get(key);\n if (mark) live.push({ panel: panelOf(el), quote: quote(blockText(el)), kind: mark.kind, note: mark.note });\n }\n return live;\n };\n})();\n})();\n(() => {\n// Pure planner for justified (\"photo wall\") rows on sheet pages. No DOM access.\n//\n// This file must stay inlinable into the page script: top-level declarations only, no imports, and the exports are\n// `planLayout` and the constants the DOM adapter shares (STEP, MAX_SCALE, MIN_SCALE). The page build strips the `export ` keyword,\n// and test/layout-plan.test.js checks that this still works.\n//\n// planLayout({ width, gap, cols, panels }) -> { rows: [{ columns: [{ panels: [index, ...], width }], height }] }\n//\n// Input (all lengths in px):\n// width container width\n// gap space between columns, and between two panels stacked in one column\n// cols most columns in one row (the planner never uses more than MAX_COLUMNS, but spans stay shares of `cols`)\n// panels one entry per panel, in reading order:\n// samples [{ w, h }] panel height at sampled widths, ascending by w (heights between samples are interpolated)\n// minWidth narrowest feasible width (clamped to `width`)\n// maxWidth widest useful width; beyond it the panel only gains empty space (default: no limit)\n// natural natural diagram width for a diagram-only panel (default: none)\n// pad panel width not used by the diagram (padding and border; default 0)\n// span the author's width hint in grid columns (default 1); span >= cols keeps the panel alone in its row\n//\n// Output: { rows, maxScale }. Rows are in reading order; a row is a list of columns (at most `cols`); a column holds one panel or two\n// consecutive panels, stacked. For integer inputs the column widths plus the gaps between them equal `width`.\n// Rows are chosen by dynamic programming over break points; widths by a search in STEP px steps. Cost per row:\n// H = tallest column; waste = sum((H - columnHeight) * columnWidth) + sum over diagrams wider than maxWidth of (w - maxWidth) * h\n// dev = sum(((w - preferred) / oneColumn)^2) + SCALE_WEIGHT * sum over diagrams of (ln(scale) / ln(MAX_SCALE))^2\n// cost = waste / 1000 + PREF_WEIGHT * dev * H\n// Scale band: diagrams on one page stay at similar sizes. With the result's `maxScale` as the diagram size limit, a diagram is\n// shown at scale min(maxScale, (width - pad) / natural). The planner tries a few bands [lo, lo * BAND_RATIO] (lo in BAND_LOS) and\n// keeps the cheapest plan in which no diagram is narrower than scale lo and none is shown above the band's top, so the largest and\n// smallest diagram scale on the page differ by at most BAND_RATIO. A panel wider than its diagram's top size keeps the diagram at\n// that size, and the page script must set the diagram's max-width to natural * maxScale. The band starts no higher than the\n// largest scale the page allows the least roomy diagram, so one wide diagram lowers the band for the others.\n// If no band is feasible the plan is made without a band (maxScale = MAX_SCALE); if no plan fits (or the input is unusable) the\n// result is a single column: one panel per row at the full width.\n\nconst STEP = 10;\nconst MAX_SCALE = 1.25;\nconst MIN_SCALE = 0.75; // the narrowest a diagram is shown, as a share of its natural width\nconst MAX_COLUMNS = 6; // rows with more columns are unreadable, and the search grows steeply with the column count\nconst BAND_RATIO = 1.25; // the largest and smallest diagram scale on a page differ by at most this\nconst BAND_LOS = [MIN_SCALE, 0.85, 0.95, 1]; // lower ends tried for the band; lo * BAND_RATIO is the upper end (1.25 means no upper limit)\nconst SCALE_WEIGHT = 3;\nconst PREF_WEIGHT = 0.15;\n\nfunction heightAt(samples, w) {\n const i = samples.findIndex((s) => s.w >= w);\n if (i === -1) return samples[samples.length - 1].h;\n if (i === 0) return samples[0].h;\n const a = samples[i - 1];\n const b = samples[i];\n return a.h + ((b.h - a.h) * (w - a.w)) / (b.w - a.w);\n}\n\n// Every way to split `len` consecutive panels into columns of 1 or 2 panels, as lists of column sizes.\nfunction splits(len) {\n if (len === 0) return [[]];\n return [1, 2].filter((k) => k <= len).flatMap((k) => splits(len - k).map((rest) => [k, ...rest]));\n}\n\nfunction singleColumn(width, panels) {\n return { rows: panels.map((_, i) => ({ columns: [{ panels: [i], width }], height: 0 })) };\n}\n\nfunction planLayout({ width, gap = 0, cols = 3, panels }) {\n const usable = Number.isFinite(width) && width > 0 && panels.every((p) => Array.isArray(p.samples) && p.samples.length > 0);\n if (!usable) return singleColumn(width, panels);\n\n // `cols` stays the unit of the author's spans; no row gets more than MAX_COLUMNS columns however large `cols` is.\n const maxColumns = Math.min(cols, MAX_COLUMNS);\n const oneColumn = Math.max(1, (width - gap * (cols - 1)) / cols);\n // Per-panel limits. With a band [lo, lo * BAND_RATIO], a diagram is no narrower than scale lo and shown at most at the top of the\n // band: a wider panel keeps it at that size and gains empty space, which the cost counts as waste.\n const prepare = (lo) => panels.map((p) => {\n const pad = p.pad ?? 0;\n const diagram = lo > 0 && p.natural > 0;\n const scaleCap = diagram ? Math.min(MAX_SCALE, lo * BAND_RATIO) : MAX_SCALE;\n return {\n ...p,\n minWidth: Math.min(width, Math.max(Math.ceil(p.minWidth || 0), diagram ? Math.ceil(p.natural * lo + pad) : 0)),\n maxWidth: Math.min(p.maxWidth ?? Infinity, diagram ? p.natural * scaleCap + pad : Infinity),\n scaleCap,\n pad,\n preferred: Math.min(width, (p.span ?? 1) * oneColumn + ((p.span ?? 1) - 1) * gap),\n alone: (p.span ?? 1) >= cols,\n };\n });\n let info = prepare(0);\n // Beyond its maxWidth a panel only gains empty space, so its height stops changing there (matters when a band lowers maxWidth).\n const heightOf = (p, w) => heightAt(p.samples, Math.min(w, p.maxWidth));\n const columnHeight = (col, w) => col.reduce((h, k) => h + heightOf(info[k], w), 0) + gap * (col.length - 1);\n\n function bestColumns(columns) {\n const avail = width - gap * (columns.length - 1);\n const mins = columns.map((c) => Math.max(...c.map((k) => info[k].minWidth)));\n const minsFrom = mins.map((_, n) => mins.slice(n).reduce((s, w) => s + w, 0));\n if (minsFrom[0] > avail) return null;\n let best = null;\n const evaluate = (ws) => {\n const hs = ws.map((w, n) => columnHeight(columns[n], w));\n const H = Math.max(...hs);\n let waste = 0;\n let dev = 0;\n ws.forEach((w, n) => {\n waste += (H - hs[n]) * w;\n for (const k of columns[n]) {\n const p = info[k];\n if (w > p.maxWidth) waste += (w - p.maxWidth) * heightOf(p, w);\n dev += ((w - p.preferred) / oneColumn) ** 2;\n if (p.natural > 0) {\n const scale = Math.min(p.scaleCap, Math.max(w - p.pad, 1) / p.natural);\n dev += SCALE_WEIGHT * (Math.log(scale) / Math.log(MAX_SCALE)) ** 2;\n }\n }\n });\n const cost = waste / 1000 + PREF_WEIGHT * dev * H;\n if (!best || cost < best.cost) best = { cost, ws, height: H, columns };\n };\n const choose = (n, used, ws) => {\n if (n === columns.length - 1) {\n const w = avail - used;\n if (w >= mins[n]) evaluate([...ws, w]);\n return;\n }\n for (let w = mins[n]; used + w + minsFrom[n + 1] <= avail; w += STEP) choose(n + 1, used + w, [...ws, w]);\n };\n choose(0, 0, []);\n return best;\n }\n\n // Best columns for one row of panels i..j.\n function bestRow(i, j) {\n if (j > i && info.slice(i, j + 1).some((p) => p.alone)) return null;\n let best = null;\n for (const split of splits(j - i + 1)) {\n if (split.length > maxColumns) continue;\n let next = i;\n const columns = split.map((size) => Array.from({ length: size }, () => next++));\n const r = bestColumns(columns);\n if (r && (!best || r.cost < best.cost)) best = r;\n }\n return best;\n }\n\n // Row breaks in reading order, for the band set up in `info`. A row holds at most 2 * maxColumns panels. Null if nothing fits.\n function solve() {\n const n = panels.length;\n const total = Array(n + 1).fill(Infinity);\n const from = Array(n + 1).fill(-1);\n const chosen = Array(n + 1).fill(null);\n total[0] = 0;\n for (let j = 1; j <= n; j++) {\n for (let i = Math.max(0, j - 2 * maxColumns); i < j; i++) {\n if (total[i] === Infinity) continue;\n const r = bestRow(i, j - 1);\n if (r && total[i] + r.cost < total[j]) {\n total[j] = total[i] + r.cost;\n from[j] = i;\n chosen[j] = r;\n }\n }\n }\n if (total[n] === Infinity) return null;\n const rows = [];\n for (let j = n; j > 0; j = from[j]) {\n const r = chosen[j];\n rows.unshift({ columns: r.columns.map((panelsInColumn, c) => ({ panels: panelsInColumn, width: r.ws[c] })), height: r.height });\n }\n return { rows, cost: total[n] };\n }\n\n let best = null;\n const diagrams = panels.filter((p) => p.natural > 0);\n if (diagrams.length > 1) {\n // No diagram can be shown larger than the page allows, so the band cannot start above the smallest of those limits.\n const reach = Math.min(...diagrams.map((p) => Math.min(MAX_SCALE, Math.max(width - (p.pad ?? 0), 1) / p.natural)));\n for (const lo of new Set([...BAND_LOS.filter((x) => x < reach), reach])) {\n info = prepare(lo);\n const r = solve();\n if (r && (!best || r.cost < best.cost)) best = { ...r, maxScale: Math.min(MAX_SCALE, lo * BAND_RATIO) };\n }\n info = prepare(0);\n }\n best ??= solve();\n return best ? { rows: best.rows, maxScale: best.maxScale ?? MAX_SCALE } : singleColumn(width, panels);\n}\n\n// DOM adapter for the sheet's justified (\"photo wall\") layout. Not a module: compose.js puts it after src/runtime/layout-plan.js\n// (which defines planLayout and the shared STEP, MAX_SCALE, MIN_SCALE) inside one function scope of the page script.\n//\n// It measures every panel at sampled widths, asks planLayout for rows and column widths, and applies them with flexbox.\n// The rendered HTML keeps the plain CSS grid: with JavaScript off, at the single-column breakpoint, or while printing, the grid is what\n// shows (the planned widths belong to the screen width, so print never gets a mix of the two); after printing the layout comes back.\n\nconst grid = document.querySelector('.am-grid');\nconst panels = grid ? [...grid.children].filter((el) => el.classList.contains('am-panel')) : [];\n\nif (panels.length > 1) {\n const SINGLE_COLUMN = '(max-width: 760px)'; // the single-column breakpoint in src/themes/base.css\n const TWO_COLUMNS = '(max-width: 1100px)'; // below this the CSS grid has two columns\n const SAMPLE_STEP = 20; // width sampling step, px; the planner interpolates between samples\n // The width floors are text sizes (px at scale 1). They take the page scale on every pass, so a runtime change of --am-scale re-plans.\n const TEXT_MIN = 260; // text keeps at least about 16 CJK characters per line\n const TABLE_COL_MIN = 96; // per table column, px\n const TABLE_COL_COMFORT = 220; // a table column this wide reads three or four words per line\n const KV_COL_MIN = 120; // per key-value column, px: a value of two short words stays on one line\n const DIAGRAM_MIN = 160;\n const RESIZE_DELAY = 150;\n const pageScale = () => {\n const scale = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--am-scale'));\n return Number.isFinite(scale) && scale > 0 ? scale : 1;\n };\n const OVERFLOWING = '.am-table-wrap, .am-diagram, .am-annot-scroll, pre';\n\n // The first-row cells of each table carry the column widths fitTables() sets, so restore() resets them too.\n const tables = [...grid.querySelectorAll('.am-table-wrap > table')];\n const headCells = (table) => [...(table.rows[0]?.cells ?? [])];\n const original = new Map([grid, ...panels, ...grid.querySelectorAll('.am-diagram > svg'), ...tables.flatMap(headCells)].map((el) => [el, el.getAttribute('style')]));\n const restoreStyle = (el) => (original.get(el) === null ? el.removeAttribute('style') : el.setAttribute('style', original.get(el)));\n\n // Back to the plain grid markup and styles.\n const restore = () => {\n for (const box of grid.querySelectorAll(':scope > .am-col')) box.replaceWith(...box.children);\n for (const el of original.keys()) restoreStyle(el);\n };\n\n // The author's width hint, rendered as data-span only when the author wrote one. The inline grid-column is the no-JavaScript fallback\n // and may hold spans the server added, so it is never read here.\n const spanHint = (el) => Number(el.dataset.span) || 1;\n const diagramOnly = (el) => {\n const body = el.querySelector(':scope > .am-panel-body');\n return body && body.children.length === 1 ? body.querySelector(':scope > .am-diagram > svg') : null;\n };\n const naturalWidth = (svg) => Number(svg.getAttribute('width')) || 0;\n\n // The width each column of a table reads well at: its natural width, but no wider than TABLE_COL_COMFORT unless its longest word\n // needs more. Below it the cells wrap one word per line, so a panel with a table is not planned narrower than the sum, and\n // fitTables() keeps each column at its share (the browser would otherwise give the room to the longest column).\n const columnWidths = new Map();\n function comfortableWidth(table, scale) {\n const saved = table.getAttribute('style');\n const columns = (width) => {\n table.style.width = width;\n return headCells(table).map((cell) => cell.getBoundingClientRect().width);\n };\n const most = columns('max-content');\n const least = columns('min-content');\n if (saved === null) table.removeAttribute('style');\n else table.setAttribute('style', saved);\n // A max-content column comes out a fraction under its text in Chrome, enough to wrap the last word, so it gets one pixel more.\n const want = most.map((w, i) => Math.min(Math.ceil(w) + 1, Math.max(least[i], TABLE_COL_COMFORT * scale)));\n columnWidths.set(table, { least, want });\n return want.reduce((sum, w) => sum + w, 0);\n }\n\n // After the layout: each column gets at least its comfortable width, scaled down toward its longest word when the panel came out\n // narrower than planned (a page narrower than the table), so a table scrolls sideways only when even its longest words do not fit.\n function fitTables() {\n for (const [table, { least, want }] of columnWidths) {\n // Each width is rounded up to a whole pixel (a column a fraction too narrow wraps its last word), so keep a pixel per column spare.\n const room = table.parentElement.clientWidth - want.length;\n const low = least.reduce((s, w) => s + w, 0);\n const high = want.reduce((s, w) => s + w, 0);\n const k = high > room ? Math.max(0, (room - low) / (high - low || 1)) : 1;\n headCells(table).forEach((cell, i) => { cell.style.minWidth = `${Math.ceil(least[i] + (want[i] - least[i]) * k)}px`; });\n }\n }\n\n // Height (and, for panels with tables or code, the narrowest width without sideways scrolling) at sampled widths.\n // Only one panel is displayed while it is measured, so each width change lays out that panel alone.\n function measure(width) {\n const scale = pageScale();\n grid.style.display = 'block';\n for (const el of panels) {\n el.style.display = 'none';\n el.style.boxSizing = 'border-box';\n for (const svg of el.querySelectorAll('.am-diagram > svg')) {\n svg.style.width = '100%';\n svg.style.maxWidth = `${naturalWidth(svg) * MAX_SCALE}px`;\n }\n }\n const info = panels.map((el) => {\n const svg = diagramOnly(el);\n const svgs = [...el.querySelectorAll('.am-diagram > svg')];\n const scrollers = el.querySelectorAll(OVERFLOWING);\n const tableCols = Math.max(0, ...[...el.querySelectorAll('table tr:first-child')].map((tr) => tr.children.length));\n el.style.display = '';\n el.style.width = `${width}px`;\n const pad = svg ? el.offsetWidth - svg.parentElement.clientWidth : 0;\n const natural = svg ? naturalWidth(svg) : 0;\n const shrunk = Math.max(0, ...svgs.map((s) => naturalWidth(s) * MIN_SCALE)) + (svg ? pad : 34);\n const tableFloors = [...el.querySelectorAll('.am-table-wrap > table')].map((t) => comfortableWidth(t, scale) + el.offsetWidth - t.parentElement.clientWidth);\n // A key-value grid gets the same care: the room a table gains must not squeeze a neighbouring grid to one word per line.\n const kvs = [...el.querySelectorAll('.am-kv')].map((kv) => (Number(kv.style.getPropertyValue('--kv-cols')) || 1) * KV_COL_MIN * scale + el.offsetWidth - kv.clientWidth);\n const floor = svg ? Math.max(DIAGRAM_MIN * scale, natural * MIN_SCALE + pad) : Math.max(TEXT_MIN * scale, shrunk, tableCols * TABLE_COL_MIN * scale + 34, ...tableFloors, ...kvs);\n const from = Math.min(width, Math.floor(floor / STEP) * STEP);\n const samples = [];\n let fits = null;\n for (let w = from; ; w += SAMPLE_STEP) {\n w = Math.min(w, width);\n el.style.width = `${w}px`;\n if (fits === null && !svg && scrollers.length && ![...scrollers].some((s) => s.scrollWidth > s.clientWidth + 1)) fits = w;\n samples.push({ w, h: el.offsetHeight });\n if (w === width) break;\n }\n el.style.display = 'none';\n return {\n samples,\n minWidth: svg ? floor : Math.max(floor, fits ?? (scrollers.length ? width : 0)),\n maxWidth: svg ? natural * MAX_SCALE + pad : Infinity,\n natural,\n pad,\n span: spanHint(el),\n };\n });\n for (const el of panels) {\n el.style.display = '';\n el.style.width = '';\n }\n return info;\n }\n\n // Each column gets a fixed width. A row adds up to the full width, so flex-wrap breaks rows by itself.\n // Stacked panels go into a column wrapper whose last panel absorbs the extra height.\n function apply(plan, gap) {\n grid.style.display = 'flex';\n grid.style.flexWrap = 'wrap';\n grid.style.alignItems = 'stretch';\n grid.style.gap = `${gap}px`;\n for (const el of panels) {\n el.style.gridColumn = '';\n el.style.gridRow = '';\n el.style.flex = '0 0 auto';\n }\n for (const row of plan.rows) {\n for (const col of row.columns) {\n const width = `${col.width}px`;\n if (col.panels.length === 1) {\n panels[col.panels[0]].style.width = width;\n continue;\n }\n const box = document.createElement('div');\n box.className = 'am-col';\n box.style.cssText = `width:${width};flex:0 0 auto;display:flex;flex-direction:column;gap:${gap}px`;\n panels[col.panels[0]].before(box);\n for (const k of col.panels) {\n panels[k].style.width = '';\n box.append(panels[k]);\n }\n panels[col.panels[col.panels.length - 1]].style.flex = '1 1 auto';\n }\n }\n }\n\n // Diagram-only panels show their diagram at most at the top of the page's scale band; a wider panel gains empty space instead.\n function capDiagrams(maxScale) {\n for (const el of panels) {\n const svg = diagramOnly(el);\n if (svg) svg.style.maxWidth = `${naturalWidth(svg) * maxScale}px`;\n }\n }\n\n const containerWidth = () => Math.floor(grid.getBoundingClientRect().width);\n\n function justify() {\n if (printing || printQuery.matches) return;\n try {\n // A vertical scrollbar can appear or vanish once the rows change height; plan again if the width moved.\n let planned = -1;\n for (let pass = 0; pass < 3 && planned !== containerWidth(); pass++) {\n restore();\n if (matchMedia(SINGLE_COLUMN).matches) return;\n planned = containerWidth();\n const gap = parseFloat(getComputedStyle(grid).columnGap) || 0;\n const cols = Math.max(1, Number(getComputedStyle(grid).getPropertyValue('--cols')) || 3);\n const plan = planLayout({ width: planned, gap, cols: matchMedia(TWO_COLUMNS).matches ? Math.min(cols, 2) : cols, panels: measure(planned) });\n apply(plan, gap);\n capDiagrams(plan.maxScale);\n fitTables();\n }\n // The width never settled: columns planned for another width would overflow or leave gaps, so show the plain grid.\n if (planned !== containerWidth()) restore();\n } catch {\n restore();\n }\n }\n\n // Printing: back to the plain grid (spans and all), and the layout again afterwards. Browsers disagree on which of the\n // `beforeprint` event and the print media query change fires first, or at all, so listen to both; both are idempotent.\n // While `printing` is set (beforeprint to afterprint) justify() does nothing, so a late resize cannot bring flex widths into the print layout.\n let printing = false;\n const printQuery = matchMedia('print');\n let timer = 0;\n const later = () => {\n clearTimeout(timer);\n timer = setTimeout(justify, RESIZE_DELAY);\n };\n const toPrint = () => {\n clearTimeout(timer);\n restore();\n };\n justify();\n addEventListener('resize', later);\n // A reader's text size changes every panel's text widths and heights, so the sheet is planned again like a resize.\n addEventListener('am-scale', later);\n addEventListener('beforeprint', () => {\n printing = true;\n toPrint();\n });\n addEventListener('afterprint', () => {\n printing = false;\n later();\n });\n printQuery.addEventListener('change', (e) => (e.matches ? toPrint() : later()));\n // Late changes to panel heights: web fonts arriving, and images inside the grid finishing their load (load does not bubble, so capture it).\n document.fonts?.ready.then(later);\n grid.addEventListener('load', later, true);\n // Switching theme changes paddings and fonts, hence panel heights.\n document.querySelector('[data-am=\"theme\"]')?.addEventListener('click', later);\n}\n})();\n// The outline rail of a doc page (src/templates/doc.js): the markup already works without a script, <details> opens the list and the\n// links jump. This adds the hover dwell, the open direction, the keys, the tap outside and the marking of the current section.\n(() => {\n const nav = document.querySelector('nav.am-toc');\n const box = nav && nav.querySelector('details.am-outline');\n if (!box) return;\n const sum = box.querySelector('summary');\n const links = Array.from(box.querySelectorAll('.am-outline-list a'));\n const ticks = Array.from(box.querySelectorAll('.am-tick'));\n const LIST_W = 240; // keep in step with .am-outline-list in src/themes/base.css\n const EDGE = 10; // the 6px gap to the rail plus a margin to the viewport edge\n let current = '';\n let byHover = false;\n let dwell = 0;\n let leave = 0;\n\n // Open away from the body when the room outside the rail fits the list; otherwise over the body. Never past the viewport.\n const place = () => {\n const r = sum.getBoundingClientRect();\n const right = r.left + r.width / 2 > innerWidth / 2;\n const room = right ? innerWidth - r.right : r.left;\n nav.dataset.flow = room >= Math.min(LIST_W, innerWidth - 48) + EDGE ? 'out' : 'in';\n };\n const setOpen = (open) => {\n if (open) place();\n box.open = open;\n if (!open) byHover = false;\n };\n const peek = (tick) => ticks.forEach((t) => t.classList.toggle('is-peek', t === tick));\n const currentLink = () => links.find((a) => a.getAttribute('aria-current') === 'true') || links[0];\n\n const mark = (id) => {\n current = id;\n ticks.forEach((t) => t.classList.toggle('is-current', t.dataset.id === id));\n links.forEach((a) => {\n if (a.getAttribute('href') === `#panel-${id}`) a.setAttribute('aria-current', 'true');\n else a.removeAttribute('aria-current');\n });\n };\n const sections = ticks.map((t) => document.getElementById(`panel-${t.dataset.id}`)).filter(Boolean);\n if (sections.length) mark(sections[0].id.slice(6));\n if (sections.length && 'IntersectionObserver' in window) {\n // A thin band a third of the way down the viewport: the section across it is the one being read.\n const seen = new Set();\n const io = new IntersectionObserver((entries) => {\n entries.forEach((e) => (e.isIntersecting ? seen.add(e.target) : seen.delete(e.target)));\n const hit = sections.filter((s) => seen.has(s)).pop();\n if (hit && hit.id.slice(6) !== current) mark(hit.id.slice(6));\n }, { rootMargin: '-30% 0px -65% 0px' });\n sections.forEach((s) => io.observe(s));\n }\n\n place();\n addEventListener('resize', place);\n\n // Mouse: dwelling on the rail opens the list, leaving it closes a list opened that way. A tap or click opens it for good.\n box.addEventListener('pointerenter', (e) => {\n clearTimeout(leave);\n if (e.pointerType !== 'mouse' || box.open) return;\n dwell = setTimeout(() => { setOpen(true); byHover = true; }, 300);\n });\n box.addEventListener('pointerleave', () => {\n clearTimeout(dwell);\n // A link the keyboard moved into keeps the list open; focusout closes it once the focus leaves the nav.\n if (byHover) leave = setTimeout(() => { if (!nav.contains(document.activeElement)) setOpen(false); }, 250);\n });\n sum.addEventListener('click', (e) => {\n clearTimeout(dwell);\n if (box.open && byHover) { e.preventDefault(); byHover = false; return; }\n place();\n });\n box.addEventListener('toggle', () => { if (box.open) peek(null); });\n\n // Keyboard: the summary opens with Enter or Space (native); arrows move through the links; Esc closes and returns to the rail.\n sum.addEventListener('focus', () => {\n if (sum.matches(':focus-visible')) peek(ticks.find((t) => t.dataset.id === current));\n });\n sum.addEventListener('blur', () => peek(null));\n nav.addEventListener('keydown', (e) => {\n if (e.key === 'Escape' && box.open) {\n e.preventDefault();\n setOpen(false);\n sum.focus();\n return;\n }\n if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) return;\n const at = links.indexOf(document.activeElement);\n if (at < 0 && e.target !== sum) return;\n e.preventDefault();\n if (!box.open) setOpen(true);\n let next;\n if (e.key === 'Home') next = links[0];\n else if (e.key === 'End') next = links[links.length - 1];\n else if (at < 0) next = e.key === 'ArrowDown' ? currentLink() : links[links.length - 1];\n else next = links[Math.min(links.length - 1, Math.max(0, at + (e.key === 'ArrowDown' ? 1 : -1)))];\n next.focus();\n });\n nav.addEventListener('focusout', (e) => {\n if (box.open && e.relatedTarget && !nav.contains(e.relatedTarget)) setOpen(false);\n });\n\n // Choosing a section or tapping outside closes the list.\n links.forEach((a) => a.addEventListener('click', () => setOpen(false)));\n document.addEventListener('pointerdown', (e) => { if (box.open && !nav.contains(e.target)) setOpen(false); });\n document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && box.open && !nav.contains(e.target)) setOpen(false); });\n})();\n})();\n";
639
+ var RUNTIME_JS = "(() => {\n// How a formula reads in a quote. MathML has no plain text, so src/math.js writes the formula as the draft wrote it, delimiters included, in\n// data-am-tex on the <math> element, and the Remark and Reply scripts read page text through this file. On a page without math there is no\n// such element, so formulaOf is null and every text comes out as it did before.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n\nconst TEX = 'data-am-tex';\n\n// The formula that holds a node, or null.\nconst formulaOf = (node) => node.parentElement?.closest(`[${TEX}]`) ?? null;\n\nconst firstText = (el) => {\n for (const child of el.childNodes) {\n const found = child.nodeType === 3 ? child : firstText(child);\n if (found) return found;\n }\n return null;\n};\n\n// What a text node adds to a quote: its data. The first text node of a formula adds the formula, and the others add nothing.\n// (A formula in an error style is plain text with its delimiters, not a <math>, so it comes out once.)\nfunction nodeText(node) {\n const math = formulaOf(node);\n if (!math) return node.data;\n return firstText(math) === node ? math.getAttribute(TEX) : '';\n}\n\n// The text of a node as textContent reads it, but with each formula as written.\nconst textWithMath = (node) => (node.nodeType === 3 ? nodeText(node) : [...node.childNodes].map(textWithMath).join(''));\n\n(() => {\n const root = document.documentElement;\n // A host that serves this page inside its own document leaves the real root without the page's settings. The toolbar keeps a copy;\n // set back what the root lacks, before anything below reads the root. A root's own value, even an empty one, is never replaced.\n const carrier = document.querySelector('.am-toolbar');\n for (const [attr, key] of [['lang', 'data-am-root-lang'], ['dir', 'data-am-root-dir'], ['data-theme', 'data-am-root-theme'], ['data-mode', 'data-am-root-mode'], ['data-style', 'data-am-root-style']]) {\n if (root.getAttribute(attr) === null && carrier?.getAttribute(key) != null) root.setAttribute(attr, carrier.getAttribute(key));\n }\n // Each toolbar list sets one root attribute; its options name the values, so the runtime names no theme or mode.\n for (const [name, attr] of [['theme', 'data-theme'], ['mode', 'data-mode']]) {\n const select = document.querySelector(`select[data-am=\"${name}\"]`);\n if (!select) continue;\n select.value = root.getAttribute(attr);\n select.addEventListener('change', () => root.setAttribute(attr, select.value));\n }\n\n // \u2500\u2500 Text size \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // A\u2212 / A+ set --am-scale on the root; every page size and line (src/themes/type-scale.js) follows it, and the drawing boxes grow\n // with it while their viewBox keeps the units Node measured. The buttons carry the range from SCALE, so this script keeps no\n // second copy of the numbers. A reader's choice is remembered in this browser and wins over the page's own scale; where storage\n // is off (am serve, file://) it lasts for this tab, and the click still works.\n const scaleDown = document.querySelector('[data-am=\"scale-down\"]');\n const scaleUp = document.querySelector('[data-am=\"scale-up\"]');\n if (scaleDown && scaleUp) {\n const min = Number(scaleDown.dataset.min);\n const max = Number(scaleDown.dataset.max);\n const step = Number(scaleDown.dataset.step);\n const storeKey = 'am-scale';\n let value;\n\n const inRange = (n) => Number.isFinite(n) && n >= min && n <= max;\n const savedScale = () => {\n try {\n return Number(localStorage.getItem(storeKey));\n } catch {\n return NaN;\n }\n };\n const saveScale = (n) => {\n try {\n localStorage.setItem(storeKey, String(n));\n } catch {\n // Storage may be off (am serve, file://); the size then lasts until the tab closes.\n }\n };\n\n const updateButtons = () => {\n const setUnavailable = (btn, unavailable) => {\n if (unavailable) btn.setAttribute('aria-disabled', 'true');\n else btn.removeAttribute('aria-disabled');\n };\n setUnavailable(scaleDown, value <= min);\n setUnavailable(scaleUp, value >= max);\n };\n\n // One step is a multiple of `step`: Math.round first, then two decimals, so 1.1500000000000001 becomes 1.15.\n const setScale = (next, remember = false) => {\n value = Math.min(max, Math.max(min, Number((Math.round(next / step) * step).toFixed(2))));\n root.style.setProperty('--am-scale', String(value));\n for (const svg of document.querySelectorAll('.am-diagram:not(.am-lightbox-canvas) > svg[role=\"img\"]')) {\n const box = svg.viewBox?.baseVal;\n if (!box || !(box.width > 0) || !(box.height > 0)) continue;\n svg.setAttribute('width', String(Math.ceil(box.width * value)));\n svg.setAttribute('height', String(Math.ceil(box.height * value)));\n }\n updateButtons();\n if (remember) saveScale(value);\n window.dispatchEvent(new Event('am-scale'));\n };\n\n // A page with no stored choice is left exactly as it was rendered: no inline variable, no svg rewrite, no extra layout pass.\n value = parseFloat(getComputedStyle(root).getPropertyValue('--am-scale')) || 1;\n updateButtons();\n const saved = savedScale();\n if (inRange(saved) && saved !== value) setScale(saved);\n scaleDown.hidden = false;\n scaleUp.hidden = false;\n scaleDown.addEventListener('click', () => {\n if (scaleDown.getAttribute('aria-disabled') === 'true') return;\n setScale(value - step, true);\n });\n scaleUp.addEventListener('click', () => {\n if (scaleUp.getAttribute('aria-disabled') === 'true') return;\n setScale(value + step, true);\n });\n }\n\n // A phone cannot show the whole toolbar. Its end (Reply, Remark, Copy source) is what a phone showed before the text-size\n // buttons, so open at that end: Theme, Mode and A\u2212 / A+ are reached by scrolling toward the start. A reader scroll leaves the\n // position we set, so a later resize does not pull the toolbar back.\n if (carrier) {\n const rtl = getComputedStyle(carrier).direction === 'rtl';\n let lastProgrammatic = null;\n let readerScrolled = false;\n const scrollToEnd = () => {\n if (carrier.scrollWidth <= carrier.clientWidth) return;\n // Chrome keeps a right-to-left box's scrollLeft negative; the browser clamps either value to the real end.\n carrier.scrollTo({ left: rtl ? -carrier.scrollWidth : carrier.scrollWidth });\n lastProgrammatic = carrier.scrollLeft;\n };\n carrier.addEventListener('scroll', () => {\n if (Math.abs(carrier.scrollLeft - lastProgrammatic) > 1) readerScrolled = true;\n });\n scrollToEnd();\n addEventListener('resize', () => {\n if (!readerScrolled) scrollToEnd();\n });\n }\n\n const copyText = async (text) => {\n try {\n await navigator.clipboard.writeText(text);\n } catch {\n const ta = Object.assign(document.createElement('textarea'), { value: text });\n document.body.append(ta);\n ta.select();\n document.execCommand('copy');\n ta.remove();\n }\n };\n // A button reads its label from data-done for a moment after a copy, then comes back to the label it started from. That label is\n // read once, here: a second click inside the moment would otherwise read the copied label off the button and restore that instead,\n // and the label would never come back. The moment starts again on each click: the timer of the previous one is left to fire and\n // does nothing (a token, so this needs no timer bookkeeping the page scripts do not already have).\n const flasher = (btn) => {\n const idle = btn.textContent;\n let clicks = 0;\n return () => {\n btn.textContent = btn.dataset.done;\n const mine = ++clicks;\n setTimeout(() => { if (mine === clicks) btn.textContent = idle; }, 1400);\n };\n };\n\n const copyBtn = document.querySelector('[data-am=\"copy\"]');\n if (copyBtn) {\n const flash = flasher(copyBtn);\n copyBtn.addEventListener('click', async () => {\n const nodes = document.querySelectorAll('#am-source');\n await copyText(nodes[nodes.length - 1]?.value ?? '');\n flash();\n });\n }\n\n // Each code block copies its own lines, without the line numbers.\n for (const btn of document.querySelectorAll('[data-am=\"copy-code\"]')) {\n const flash = flasher(btn);\n btn.addEventListener('click', async () => {\n const lines = btn.closest('.am-codeblock')?.querySelectorAll('.am-ln') ?? [];\n await copyText([...lines].map((l) => l.textContent).join('\\n'));\n flash();\n });\n }\n\n // \u2500\u2500 Diagram Lightbox & Pan-Zoom Viewer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const diagrams = document.querySelectorAll('.am-diagram:not(.am-lightbox-canvas)');\n const lb = document.querySelector('.am-lightbox');\n if (diagrams.length && lb) {\n const backdrop = lb.querySelector('.am-lightbox-backdrop');\n const titleText = lb.querySelector('.am-lightbox-title-text');\n const stage = lb.querySelector('.am-lightbox-stage');\n const canvas = lb.querySelector('.am-lightbox-canvas');\n const closeBtn = lb.querySelector('.am-lightbox-close');\n const expandLabel = lb.getAttribute('data-expand') || 'Expand diagram';\n\n let scale = 1, x = 0, y = 0, fitScale = 1, curVw = 800, curVh = 600;\n let isDragging = false, activePointerId = null, startX = 0, startY = 0, origX = 0, origY = 0;\n let lastTrigger = null;\n\n const apply = () => {\n canvas.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0) scale(${scale.toFixed(4)})`;\n };\n\n const zoomTo = (newScale, pivotX, pivotY) => {\n newScale = Math.max(0.2, Math.min(6.0, newScale));\n if (Math.abs(newScale - scale) < 0.0001) return;\n const r = newScale / scale;\n x = pivotX - (pivotX - x) * r;\n y = pivotY - (pivotY - y) * r;\n scale = newScale;\n apply();\n };\n\n const open = (diag, trigger) => {\n const svg = [...diag.children].find((el) => el.tagName.toLowerCase() === 'svg');\n if (!svg) return;\n lastTrigger = trigger;\n\n const panel = diag.closest('.am-panel');\n const panelTitle = panel?.querySelector('.am-panel-head h2')?.textContent?.trim() || panel?.querySelector('h2')?.textContent?.trim() || lb.getAttribute('aria-label') || 'Diagram viewer';\n if (titleText) titleText.textContent = panelTitle;\n\n const clone = svg.cloneNode(true);\n const defElements = clone.querySelectorAll('[id]');\n if (defElements.length) {\n const idMap = new Map();\n defElements.forEach((el, i) => {\n const oldId = el.id;\n const newId = `${oldId}-lb-${i}`;\n idMap.set(oldId, newId);\n el.id = newId;\n });\n const urlAttrs = ['marker-start', 'marker-mid', 'marker-end', 'fill', 'stroke', 'filter', 'clip-path', 'mask'];\n clone.querySelectorAll('*').forEach((el) => {\n for (const attr of urlAttrs) {\n const val = el.getAttribute(attr);\n if (val && val.startsWith('url(#')) {\n const id = val.slice(5, -1);\n if (idMap.has(id)) el.setAttribute(attr, `url(#${idMap.get(id)})`);\n }\n }\n const href = el.getAttribute('href') || el.getAttribute('xlink:href');\n if (href && href.startsWith('#')) {\n const id = href.slice(1);\n if (idMap.has(id)) {\n if (el.hasAttribute('href')) el.setAttribute('href', `#${idMap.get(id)}`);\n if (el.hasAttribute('xlink:href')) el.setAttribute('xlink:href', `#${idMap.get(id)}`);\n }\n }\n });\n }\n\n const vb = svg.viewBox?.baseVal;\n curVw = (vb && vb.width > 0) ? vb.width : (parseFloat(svg.getAttribute('width')) || svg.clientWidth || 800);\n curVh = (vb && vb.height > 0) ? vb.height : (parseFloat(svg.getAttribute('height')) || svg.clientHeight || 600);\n clone.style.width = `${curVw}px`;\n clone.style.height = `${curVh}px`;\n canvas.innerHTML = '';\n canvas.append(clone);\n lb.removeAttribute('hidden');\n document.body.style.overflow = 'hidden';\n\n const rect = stage.getBoundingClientRect();\n const pad = 48;\n const availW = Math.max(100, rect.width - pad * 2);\n const availH = Math.max(100, rect.height - pad * 2);\n fitScale = Math.min(availW / curVw, availH / curVh, 1.0);\n scale = fitScale;\n x = (rect.width - curVw * scale) / 2;\n y = (rect.height - curVh * scale) / 2;\n apply();\n closeBtn.focus();\n };\n\n const close = () => {\n if (lb.hasAttribute('hidden')) return;\n lb.setAttribute('hidden', '');\n canvas.innerHTML = '';\n document.body.style.overflow = '';\n lastTrigger?.focus();\n };\n\n stage.addEventListener('wheel', (e) => {\n e.preventDefault();\n const rect = stage.getBoundingClientRect();\n const dy = e.deltaMode === 1 ? e.deltaY * 16 : (e.deltaMode === 2 ? e.deltaY * 400 : e.deltaY);\n const factor = Math.exp(-Math.max(-200, Math.min(200, dy)) * 0.0015);\n zoomTo(scale * factor, e.clientX - rect.left, e.clientY - rect.top);\n }, { passive: false });\n\n stage.addEventListener('pointerdown', (e) => {\n if (e.button !== 0 || isDragging) return;\n isDragging = true;\n activePointerId = e.pointerId;\n startX = e.clientX;\n startY = e.clientY;\n origX = x;\n origY = y;\n stage.setPointerCapture(e.pointerId);\n stage.classList.add('am-panning');\n });\n\n stage.addEventListener('pointermove', (e) => {\n if (!isDragging || e.pointerId !== activePointerId) return;\n x = origX + (e.clientX - startX);\n y = origY + (e.clientY - startY);\n apply();\n });\n\n const endDrag = (e) => {\n if (!isDragging || e.pointerId !== activePointerId) return;\n isDragging = false;\n activePointerId = null;\n stage.classList.remove('am-panning');\n try { stage.releasePointerCapture(e.pointerId); } catch {}\n };\n stage.addEventListener('pointerup', endDrag);\n stage.addEventListener('pointercancel', endDrag);\n\n stage.addEventListener('dblclick', () => {\n const rect = stage.getBoundingClientRect();\n scale = fitScale;\n x = (rect.width - curVw * scale) / 2;\n y = (rect.height - curVh * scale) / 2;\n apply();\n });\n\n closeBtn.addEventListener('click', close);\n backdrop.addEventListener('click', close);\n window.addEventListener('keydown', (e) => {\n if (e.key === 'Escape' && !lb.hasAttribute('hidden')) close();\n });\n\n lb.addEventListener('keydown', (e) => {\n if (e.key !== 'Tab') return;\n const focusables = lb.querySelectorAll('button:not([disabled]), [tabindex]:not([tabindex=\"-1\"])');\n if (!focusables.length) return;\n const first = focusables[0];\n const last = focusables[focusables.length - 1];\n if (e.shiftKey && document.activeElement === first) {\n e.preventDefault();\n last.focus();\n } else if (!e.shiftKey && document.activeElement === last) {\n e.preventDefault();\n first.focus();\n }\n });\n\n const expandSvg = '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><polyline points=\"15 3 21 3 21 9\"></polyline><polyline points=\"9 21 3 21 3 15\"></polyline><line x1=\"21\" y1=\"3\" x2=\"14\" y2=\"10\"></line><line x1=\"3\" y1=\"21\" x2=\"10\" y2=\"14\"></line></svg>';\n diagrams.forEach((diag) => {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'am-diagram-expand';\n btn.title = expandLabel;\n btn.setAttribute('aria-label', expandLabel);\n btn.innerHTML = expandSvg;\n btn.addEventListener('click', () => open(diag, btn));\n diag.prepend(btn);\n });\n }\n})();\n(() => {\n// The reply a reader copies from the page: one Markdown text with the decisions, the panel comments and the block remarks.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n// decisions: [{ panel, question, picked: [label], suggested: [label], touched }]; comments: [{ panel, title, text }];\n// remarks: [{ panel, quote, kind, note }], where quote is the start of the marked block and kind is a key of ui.kinds.\n// Comment and remark text is quoted line by line, so text the reader typed cannot pass as part of the structure.\n// rtl: the page reads right to left, so the arrow before each answer points left, the way the text runs.\nfunction replyText({ title, decisions, comments, remarks = [], ui, rtl = false }) {\n const arrow = rtl ? '\u2190' : '\u2192';\n const out = [`# Re: ${title}`];\n if (decisions.length) {\n out.push('', `## ${ui.decisions}`);\n decisions.forEach((d, i) => {\n const answer = d.picked.length ? d.picked.map((l) => `**${l}**`).join(', ') : '**\u2014**';\n // Every option starts unselected, so an ask the reader never clicked has no answer: the reply names the suggestion\n // instead of passing it off as the reader's choice.\n const same = d.picked.length === d.suggested.length && d.picked.every((l) => d.suggested.includes(l));\n const suggested = d.suggested.join(', ') || '\u2014';\n const why = !d.touched ? `${ui.untouched}: ${suggested}` : same ? ui.confirmed : `${ui.was}: ${suggested}`;\n out.push(`${i + 1}. [${d.panel}] ${d.question}`, ` ${arrow} ${answer} _(${why})_`);\n });\n }\n const written = comments.filter((c) => c.text.trim());\n const quoted = (text) => (text.trim() ? text.trim().split('\\n').map((l) => ` > ${l}`) : []);\n if (written.length) {\n out.push('', `## ${ui.comments}`);\n for (const c of written) out.push(`- **${c.panel} \xB7 ${c.title}**`, ...quoted(c.text));\n }\n if (remarks.length) {\n out.push('', `## ${ui.remarks}`);\n for (const r of remarks) {\n const label = [r.panel, ui.kinds?.[r.kind] ?? r.kind].filter(Boolean).join(' \xB7 ');\n out.push(`- **${label}** \"${r.quote}\"`, ...quoted(r.note));\n }\n }\n if (written.length || remarks.some((r) => r.note.trim())) out.push('', `_${ui.typed}_`);\n return `${out.join('\\n')}\\n`;\n}\n\n// A letter of a right-to-left script. One definition for the page builder (src/bidi.js) and for the right-to-left page script\n// (src/runtime/reply-view.js), so the two cannot drift apart. A plain ES module; the page script gets this file in front of\n// reply-view.js, with its `export` keyword dropped and reply-view.js's import of it removed (src/runtime/compose.js).\nconst RTL_LETTER = /[\\p{Script=Hebrew}\\p{Script=Arabic}\\p{Script=Syriac}\\p{Script=Thaana}\\p{Script=Nko}\\p{Script=Samaritan}\\p{Script=Mandaic}]/u;\n\n// The reply as the reader sees it in the Reply sheet (src/runtime/reply.js): the Markdown that Copy copies, drawn as headings, bold answers\n// and quoted comments instead of raw \"# Re: ...\", \"1. [E] ...\" and \"- **A \xB7 ...**\" lines. Each line gets its own direction, so a\n// Hebrew reader sees Latin answers and paths in place; a line with no right-to-left letter reads left to right, as on any other page.\n// The raw Markdown stays in the sheet under a fold, so the copied text does not change.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped and rtl-letter.js in front of it in place of the\n// import (src/runtime/compose.js).\n\nconst escHtml = (s) => s.replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c]);\n// A line with a right-to-left letter reads right to left; a line without one (an English comment, a path) reads left to right.\nconst dirOf = (s) => (RTL_LETTER.test(s) ? 'rtl' : 'ltr');\n\n// The only inline Markdown src/runtime/reply-text.js writes: **answer**, _(note)_ and the \"quote\" of a remark. Each piece is isolated in its own direction,\n// so a Latin answer inside a Hebrew line keeps its place, and \"A \xB7 title\" still starts with the panel letter.\nconst piece = (tag, text) => `<${tag}><bdi dir=\"${dirOf(text)}\">${text}</bdi></${tag}>`;\nfunction inline(s) {\n return escHtml(s)\n .replace(/\\*\\*(.+?)\\*\\*/g, (_, t) => piece('strong', t))\n .replace(/(^|\\s)_(.+?)_(?=\\s|$)/g, (_, pre, t) => pre + piece('em', t))\n // The quoted start of a marked block (\"- **A \xB7 concern** \"text\"\"): isolated, so Latin text in a Hebrew line keeps its place.\n .replace(/&quot;(.+)&quot;$/, (_, t) => `&quot;<bdi dir=\"${dirOf(t)}\">${t}</bdi>&quot;`);\n}\n\n// The reply text (src/runtime/reply-text.js) as HTML, one block per line.\nfunction replyViewHtml(text) {\n return text\n .replace(/\\n$/, '')\n .split('\\n')\n .map((line) => {\n const dir = dirOf(line);\n let m;\n if (!line.trim()) return '<div class=\"am-rv-gap\"></div>';\n if ((m = line.match(/^(#{1,2}) (.*)$/))) return `<div class=\"am-rv-h${m[1].length}\" dir=\"${dir}\">${inline(m[2])}</div>`;\n if ((m = line.match(/^(\\d+)\\. \\[([^\\]]*)\\] (.*)$/))) {\n return `<div class=\"am-rv-q\" dir=\"${dir}\"><bdi>${m[1]}.</bdi> <bdi class=\"am-rv-tag\">${escHtml(m[2])}</bdi> ${inline(m[3])}</div>`;\n }\n if ((m = line.match(/^ {3}([\u2190\u2192]) (.*)$/))) return `<div class=\"am-rv-a\" dir=\"${dir}\">${m[1]} ${inline(m[2])}</div>`;\n if ((m = line.match(/^- (.*)$/))) return `<div class=\"am-rv-c\" dir=\"${dir}\">${inline(m[1])}</div>`;\n // A comment line is shown exactly as the reader typed it.\n if ((m = line.match(/^ {2}> ?(.*)$/))) return `<div class=\"am-rv-quote\" dir=\"${dirOf(m[1])}\">${escHtml(m[1]) || '&nbsp;'}</div>`;\n return `<div dir=\"${dir}\">${inline(line)}</div>`;\n })\n .join('');\n}\n\n// Answer on the page: every panel gets a Comment box, and the Reply button collects the ask answers, the comments and the remarks\n// into one Markdown reply (replyText) to copy back to the agent. Answers and comments stay in localStorage across reloads.\n// The remark script (remark.js) adds the blocks the reader marked, through window.__amRemarkData, and tells this script about a change\n// with an \"am-remark-change\" event on the document.\n// The Reply sheet shows the reply drawn (replyViewHtml) with the Markdown that Copy copies under a fold. Once the reader has given any\n// input, a bar at the bottom of the page shows the counts and copies the reply in one click, so there is no trip to the top-right button.\nconst replyBtn = document.querySelector('[data-am=\"reply\"]');\nconst COMMENT_ICON = '<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z\"></path></svg>';\nif (replyBtn) {\n const ui = JSON.parse(replyBtn.dataset.ui);\n const storeKey = `am-reply:${location.pathname}`;\n // A page served by `am serve` runs without localStorage and the phone may discard its tab, so it keeps the answers on the\n // server: data-am-save names the write route and data-am-state carries what the server already holds for this page version.\n const serve = (() => {\n const { amSave: save, amState: state } = document.body?.dataset ?? {};\n if (!save) return null;\n try {\n return { save, restored: state ? JSON.parse(state) : null };\n } catch {\n return { save, restored: null };\n }\n })();\n let saveTimer = null;\n let pendingPatch = null;\n const sendSave = (patch) => {\n fetch(serve.save, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch), keepalive: true })\n .catch(() => {}); // a page that cannot reach the server keeps its state until it closes, as before\n };\n // Typing must not put one request per keystroke on the server; localStorage is written at once, the network follows.\n const saveSoon = (patch) => {\n clearTimeout(saveTimer);\n pendingPatch = patch;\n saveTimer = setTimeout(() => {\n pendingPatch = null;\n sendSave(patch);\n }, 400);\n };\n // A hidden or closing page sends the change it still holds, before the timer can run.\n const flushSave = () => {\n if (!pendingPatch) return;\n clearTimeout(saveTimer);\n sendSave(pendingPatch);\n pendingPatch = null;\n };\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flushSave();\n });\n window.addEventListener('pagehide', flushSave);\n const panels = [...document.querySelectorAll('.am-panel')];\n const asks = [...document.querySelectorAll('.am-ask')];\n // Answers are saved by question text, so they still match after am patch has renumbered the asks.\n // Page text without the word joiners a right-to-left page puts after a Hebrew prefix hyphen (src/bidi.js): the reply and the saved\n // answers hold the text as the draft wrote it, a formula too (src/runtime/math-text.js).\n const WJ = new RegExp(String.fromCharCode(0x2060), 'g');\n const textOf = (el) => el && textWithMath(el).replace(WJ, '').trim();\n const keyOf = (ask) => textOf(ask.querySelector('legend')) ?? ask.dataset.ask;\n const touched = new Set();\n const boxes = new Map();\n // The bar is built below with the sheet; the handlers that change the counts only call this.\n let refreshBar = () => {};\n // The textarea a failed copy keeps selected, so the reader can still use the keyboard shortcut.\n let stuck = null;\n\n const load = () => {\n if (serve?.restored?.reply) return serve.restored.reply;\n try {\n return JSON.parse(localStorage.getItem(storeKey)) || {};\n } catch {\n return {};\n }\n };\n const save = () => {\n const state = {\n asks: Object.fromEntries(asks.map((a) => [keyOf(a), { picked: picked(a), touched: touched.has(a) }])),\n comments: Object.fromEntries([...boxes].map(([id, box]) => [id, box.value]).filter(([, text]) => text.trim())),\n };\n try {\n localStorage.setItem(storeKey, JSON.stringify(state));\n } catch {\n // Storage may be off (private window, file:// policy); answers then last until the page closes.\n }\n if (serve) saveSoon({ reply: state });\n };\n const picked = (ask) => [...ask.querySelectorAll('input')].filter((i) => i.checked).map((i) => i.value);\n const panelOf = (el) => {\n const panel = el.closest('.am-panel');\n return { id: panel?.id.replace(/^panel-/, '') ?? '', title: textOf(panel?.querySelector('.am-panel-head h2')) ?? '' };\n };\n\n const saved = load();\n for (const ask of asks) {\n const inputs = [...ask.querySelectorAll('input')];\n const state = saved.asks?.[keyOf(ask)];\n // A saved answer applies only while every picked option still exists on the page, and only if the reader clicked: older versions started\n // with the suggestion selected and saved it untouched, and that state must come back unselected.\n if (state?.touched && Array.isArray(state.picked) && state.picked.every((v) => inputs.some((i) => i.value === v))) {\n for (const input of inputs) input.checked = state.picked.includes(input.value);\n touched.add(ask);\n }\n // A click counts even on the option that is already picked: the reader confirms the suggestion.\n const answer = () => {\n touched.add(ask);\n save();\n refreshBar();\n };\n ask.addEventListener('change', answer);\n ask.addEventListener('click', (e) => { if (e.target.matches('input')) answer(); });\n }\n\n for (const panel of panels) {\n const id = panel.id.replace(/^panel-/, '');\n // An icon only: narrow panels have no room for a word next to the title.\n const btn = Object.assign(document.createElement('button'), { type: 'button', className: 'am-comment-btn', title: ui.comment, innerHTML: COMMENT_ICON });\n btn.setAttribute('aria-label', `${ui.comment} ${id}`);\n btn.setAttribute('aria-expanded', 'false');\n const wrap = Object.assign(document.createElement('div'), { className: 'am-comment', hidden: true });\n const box = Object.assign(document.createElement('textarea'), { rows: 3, placeholder: ui.commentHint, value: saved.comments?.[id] ?? '' });\n box.setAttribute('aria-label', `${ui.comment} ${id}`);\n wrap.append(box);\n const show = (open) => {\n wrap.hidden = !open;\n btn.setAttribute('aria-expanded', String(open));\n };\n btn.addEventListener('click', () => {\n show(wrap.hidden);\n if (!wrap.hidden) box.focus();\n });\n box.addEventListener('input', () => {\n btn.classList.toggle('am-comment-btn--on', Boolean(box.value.trim()));\n save();\n refreshBar();\n });\n btn.classList.toggle('am-comment-btn--on', Boolean(box.value.trim()));\n if (box.value.trim()) show(true);\n (panel.querySelector('.am-panel-head') ?? panel).append(btn);\n panel.append(wrap);\n boxes.set(id, box);\n }\n\n const sheet = document.createElement('dialog');\n sheet.className = 'am-reply';\n sheet.setAttribute('aria-label', ui.title);\n sheet.innerHTML = '<div class=\"am-reply-head\"><strong></strong><span></span></div><div class=\"am-reply-view\" tabindex=\"0\"></div><details class=\"am-reply-raw\"><summary></summary><textarea readonly rows=\"10\"></textarea></details><div class=\"am-reply-actions\"><button type=\"button\" class=\"am-btn\" data-act=\"copy\"></button><button type=\"button\" class=\"am-btn\" data-act=\"close\"></button></div>';\n sheet.querySelector('strong').textContent = ui.title;\n sheet.querySelector('span').textContent = ui.hint;\n sheet.querySelector('summary').textContent = ui.raw;\n const view = sheet.querySelector('.am-reply-view');\n const raw = sheet.querySelector('details');\n const text = sheet.querySelector('textarea');\n const copy = sheet.querySelector('[data-act=\"copy\"]');\n const close = sheet.querySelector('[data-act=\"close\"]');\n copy.textContent = ui.copy;\n close.textContent = ui.close;\n document.body.append(sheet);\n\n const compose = () => {\n const decisions = asks.map((ask) => ({\n panel: panelOf(ask).id,\n question: textOf(ask.querySelector('legend')) ?? '',\n picked: picked(ask),\n suggested: [...ask.querySelectorAll('input[data-suggested]')].map((i) => i.value),\n touched: touched.has(ask),\n }));\n const comments = [...boxes].map(([id, box]) => ({ panel: id, title: panelOf(box).title, text: box.value }));\n const remarks = window.__amRemarkData?.() ?? [];\n const empty = !decisions.length && !comments.some((c) => c.text.trim()) && !remarks.length;\n const title = textOf(document.querySelector('.am-head h1')) ?? document.title;\n return empty ? '' : replyText({ title, decisions, comments, remarks, ui, rtl: document.documentElement.dir === 'rtl' });\n };\n\n // The text goes through the clipboard API; a page the browser treats as insecure (file://) falls back to selecting a temporary\n // textarea, because the sheet's own textarea can sit inside a closed fold, where it cannot be selected.\n // That fallback reports whether it worked. When it does not, the text stays selected (so Cmd/Ctrl+C still copies it) and the\n // button says what to do instead of showing the \"Copied \u2713\" label the reader cannot trust.\n const copyText = async (str, btn) => {\n stuck?.remove();\n stuck = null;\n try {\n await navigator.clipboard.writeText(str);\n // The close_after_reply script (close-after-reply.js) closes the tab once the reply is on the clipboard.\n document.dispatchEvent(new Event('am-reply-copied'));\n } catch {\n const tmp = Object.assign(document.createElement('textarea'), { value: str });\n tmp.style.cssText = 'position:fixed;top:-100px;opacity:0';\n // Inside the sheet while it is open: while a modal dialog is open the rest of the document cannot take focus, so a textarea\n // in the body can be selected but not focused, and the keyboard shortcut the reader is told to press would copy nothing.\n // The bottom bar copies while the sheet is closed, and a closed dialog is not rendered, so there the textarea goes in the body.\n (sheet.open ? sheet : document.body).append(tmp);\n tmp.select();\n let copied = false;\n try {\n copied = document.execCommand('copy');\n } catch {\n copied = false;\n }\n if (!copied) {\n stuck = tmp;\n btn.textContent = ui.copyFailed;\n setTimeout(() => { btn.textContent = ui.copy; }, 3000);\n return;\n }\n tmp.remove();\n }\n btn.textContent = ui.done;\n setTimeout(() => { btn.textContent = ui.copy; }, 1400);\n };\n\n const open = () => {\n const reply = compose();\n if (reply) view.innerHTML = replyViewHtml(reply);\n else view.textContent = ui.empty;\n view.scrollTop = 0;\n text.value = reply;\n raw.open = false;\n raw.hidden = !reply;\n copy.disabled = !reply;\n if (sheet.showModal) sheet.showModal();\n else sheet.setAttribute('open', '');\n (reply ? copy : close).focus();\n };\n replyBtn.addEventListener('click', open);\n close.addEventListener('click', () => (sheet.close ? sheet.close() : sheet.removeAttribute('open')));\n // A failed copy leaves the text selected for Cmd/Ctrl+C; closing the sheet drops that textarea.\n sheet.addEventListener('close', () => { stuck?.remove(); stuck = null; });\n copy.addEventListener('click', () => copyText(text.value, copy));\n\n const bar = Object.assign(document.createElement('div'), { className: 'am-reply-bar', hidden: true });\n bar.setAttribute('role', 'region');\n bar.setAttribute('aria-label', ui.title);\n const summary = Object.assign(document.createElement('span'), { className: 'am-reply-bar-count' });\n summary.setAttribute('aria-live', 'polite');\n const preview = Object.assign(document.createElement('button'), { type: 'button', className: 'am-btn', textContent: ui.preview });\n const barCopy = Object.assign(document.createElement('button'), { type: 'button', className: 'am-btn am-btn--reply', textContent: ui.copy });\n preview.addEventListener('click', open);\n barCopy.addEventListener('click', () => copyText(compose(), barCopy));\n bar.append(summary, preview, barCopy);\n document.body.append(bar);\n\n // The bar shows only the counts that are above zero, and only once there is any input at all.\n refreshBar = () => {\n const counts = {\n answered: touched.size,\n comments: [...boxes.values()].filter((box) => box.value.trim()).length,\n remarks: (window.__amRemarkData?.() ?? []).length,\n };\n const parts = Object.entries(counts).filter(([, n]) => n > 0).map(([kind, n]) => ui.count[kind].replace('{n}', n));\n summary.textContent = parts.join(' \xB7 ');\n bar.hidden = !parts.length;\n document.body.classList.toggle('am-has-reply-bar', parts.length > 0);\n };\n document.addEventListener('am-remark-change', () => refreshBar());\n // Saved remarks are restored by remark.js, which runs after this script in the same <script> element: its data is not there yet.\n // A microtask runs when that whole element has finished, so the first count includes them.\n queueMicrotask(() => refreshBar());\n}\n})();\n(() => {\n// Text helpers for remark mode (src/runtime/remark.js): how a marked block is named and quoted.\n// A plain ES module for tests; the page gets it with its `export` keyword dropped (src/runtime/compose.js).\n// A block keeps its mark across `am patch` because the key is its panel, its tag and the start of its text, not its position.\n\nconst collapse = (text) => String(text).replace(/\\s+/g, ' ').trim();\n\n// The start of a block's text with whitespace collapsed: the readable identity of the block.\nfunction fingerprint(text, len = 80) {\n return collapse(text).slice(0, len);\n}\n\n// What the reply quotes of a block: the start of its text, with an ellipsis when it is cut.\nfunction quote(text, len = 60) {\n const t = collapse(text);\n return t.length > len ? `${t.slice(0, len).trimEnd()}\u2026` : t;\n}\n\n// Two blocks with the same text (two identical list items) get the same base key. The n-th one in the page gets \"\\t<n>\" added;\n// a tab cannot be in a fingerprint, which has its whitespace collapsed, so the new key never meets another base key.\nfunction occurrenceKeys(bases) {\n const seen = new Map();\n return bases.map((base) => {\n const n = seen.get(base) ?? 0;\n seen.set(base, n + 1);\n return n ? `${base}\\t${n}` : base;\n });\n}\n\n// Remark mode: the reader turns it on, clicks a block, tags it (suggestion, keep, question, concern) and may add a note.\n// A mark shows as a bar and a note chip inside the block, lives in localStorage like panel comments, and the Reply button carries it\n// back to the agent: reply.js calls window.__amRemarkData, and replyText (reply-text.js) writes the Remarks section.\n(() => {\n const btn = document.querySelector('[data-am=\"remark\"]');\n if (!btn) return;\n const ui = JSON.parse(btn.dataset.ui);\n const KINDS = ['suggestion', 'keep', 'question', 'concern'];\n const storeKey = `am-remark:${location.pathname}`;\n // A page served by `am serve` has no localStorage and the phone may discard its tab; it keeps the marks on the server, in the\n // same record as the answers (reply.js), so a re-opened page finds them again.\n const serve = (() => {\n const { amSave: save, amState: state } = document.body?.dataset ?? {};\n if (!save) return null;\n try {\n return { save, restored: state ? JSON.parse(state) : null };\n } catch {\n return { save, restored: null };\n }\n })();\n let saveTimer = null;\n let pendingPatch = null;\n const sendSave = (patch) => {\n fetch(serve.save, { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch), keepalive: true })\n .catch(() => {});\n };\n const saveSoon = (patch) => {\n clearTimeout(saveTimer);\n pendingPatch = patch;\n saveTimer = setTimeout(() => {\n pendingPatch = null;\n sendSave(patch);\n }, 400);\n };\n // A hidden or closing page sends the change it still holds, before the timer can run.\n const flushSave = () => {\n if (!pendingPatch) return;\n clearTimeout(saveTimer);\n sendSave(pendingPatch);\n pendingPatch = null;\n };\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flushSave();\n });\n window.addEventListener('pagehide', flushSave);\n // The one definition of a block a reader can mark: the content under <main>. The page and panel titles are left out, because the\n // reply reads them as text; a panel has its Comment button.\n // A $$ block on its own is a div; a $$ formula inside a sentence is a span of its paragraph.\n const BLOCK = 'main :is(h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,dd,dt,figure,div.am-math-block):not(.am-head *, .am-panel-head *, .am-toc *)';\n // A click on these does what it always did.\n const LIVE = '.am-remark-pop, .am-toolbar, a, button, input, textarea, select, label';\n const blockAt = (target) => (target.closest(LIVE) ? null : target.closest(BLOCK));\n\n const WJ = new RegExp(String.fromCharCode(0x2060), 'g'); // word joiners of a right-to-left page (src/bidi.js); not part of the draft's text\n // A narrow horizontal timeline shows its date and title inline (src/themes/base.css). They stay parts of their own, so a block key\n // does not change with the width of the window (#194).\n const OWN_BOX = '.am-timeline--h .am-tl-when, .am-timeline--h .am-tl-title';\n const inlineBox = new WeakMap();\n const isInline = (el) => {\n if (!inlineBox.has(el)) inlineBox.set(el, !el.matches(OWN_BOX) && getComputedStyle(el).display.startsWith('inline'));\n return inlineBox.get(el);\n };\n // The text of a block as the reader sees it: separate lines, cells and timeline parts are joined by a space (textContent would run\n // \"2026\" and \"Ship\" together), and the note chip is not part of it. A formula is one box and reads as the TeX the draft wrote\n // (src/runtime/math-text.js), not as the MathML tokens.\n const blockText = (el) => {\n const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);\n let text = '';\n let last = null;\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (node.parentElement.closest('.am-mark-note')) continue;\n let box = formulaOf(node) ?? node.parentElement;\n while (box !== el && isInline(box)) box = box.parentElement;\n if (last && box !== last) text += ' ';\n text += nodeText(node).replace(WJ, '');\n last = box;\n }\n return text;\n };\n\n const panelOf = (el) => el.closest('.am-panel')?.id.replace(/^panel-/, '') ?? '';\n // Block keys, in page order. Built when first needed: a page nobody marked pays nothing.\n let keys = null;\n const keyMap = () => {\n if (!keys) {\n const blocks = [...document.querySelectorAll(BLOCK)];\n const ids = occurrenceKeys(blocks.map((el) => `${panelOf(el)}|${el.localName}|${fingerprint(blockText(el))}`));\n keys = new Map(blocks.map((el, i) => [el, ids[i]]));\n }\n return keys;\n };\n\n const load = () => {\n const restored = serve?.restored?.remark;\n if (Array.isArray(restored)) return restored.filter((m) => typeof m?.key === 'string' && KINDS.includes(m.kind));\n try {\n const saved = JSON.parse(localStorage.getItem(storeKey));\n return Array.isArray(saved) ? saved.filter((m) => typeof m?.key === 'string' && KINDS.includes(m.kind)) : [];\n } catch {\n return [];\n }\n };\n // A mark whose block is gone from the page stays stored (it may return with `am patch`); it is neither painted nor sent.\n const marks = new Map(load().map((m) => [m.key, { key: m.key, kind: m.kind, note: String(m.note ?? '') }]));\n // Kind and note of a popover closed without Save, by block key, until the page reloads (see open below).\n const drafts = new Map();\n const clearBtn = document.createElement('button');\n clearBtn.type = 'button';\n clearBtn.className = 'am-btn am-btn--remark-clear';\n clearBtn.textContent = ui.clear;\n // Clear all drops saved marks and drafts, so it shows while either exists.\n const toClear = () => marks.size + drafts.size;\n const showClear = () => { clearBtn.hidden = toClear() === 0; };\n btn.insertAdjacentElement('afterend', clearBtn);\n let clearTimer = null;\n let clearArmed = false;\n const resetClear = () => {\n if (clearTimer !== null) clearTimeout(clearTimer);\n clearTimer = null;\n clearArmed = false;\n clearBtn.classList.remove('is-armed');\n clearBtn.textContent = ui.clear;\n showClear();\n };\n const armClear = () => {\n clearArmed = true;\n clearBtn.classList.add('is-armed');\n clearBtn.textContent = ui.clearConfirm.replace('{n}', toClear());\n clearTimer = setTimeout(resetClear, 4000);\n };\n clearBtn.addEventListener('click', () => {\n if (!clearArmed) {\n armClear();\n return;\n }\n for (const el of document.querySelectorAll('.am-mark')) unpaint(el);\n marks.clear();\n // A draft is a remark the reader has not saved yet; Clear all drops it too, so no block reopens with an old kind.\n drafts.clear();\n try {\n localStorage.removeItem(storeKey);\n } catch {\n // Storage may be off (private window, a sandboxed page); the in-memory marks still clear.\n }\n if (serve) saveSoon({ remark: [] });\n resetClear();\n document.dispatchEvent(new Event('am-remark-change'));\n });\n const save = () => {\n try {\n localStorage.setItem(storeKey, JSON.stringify([...marks.values()]));\n } catch {\n // Storage may be off (private window, a sandboxed page); marks then last until the page closes.\n }\n if (serve) saveSoon({ remark: [...marks.values()] });\n // The reply bar (reply.js) shows the number of marks.\n document.dispatchEvent(new Event('am-remark-change'));\n showClear();\n };\n\n const chip = (el, mark) => {\n const note = document.createElement(el.localName === 'table' ? 'caption' : 'span');\n note.className = 'am-mark-note';\n const kind = document.createElement('b');\n kind.textContent = ui.kinds[mark.kind];\n note.append(kind, mark.note ? ` ${mark.note}` : '');\n return note;\n };\n const clearChip = (el) => el.querySelector(':scope > .am-mark-note')?.remove();\n const paint = (el, mark) => {\n clearChip(el);\n el.classList.add('am-mark');\n el.dataset.kind = mark.kind;\n // Inside the block, so a list item stays a child of its list. A table takes it as its caption; a list item with a sub-list shows\n // it under its own text, before the sub-list.\n const sub = el.querySelector(':scope > ul, :scope > ol');\n if (el.localName === 'table') el.prepend(chip(el, mark));\n else if (sub) sub.before(chip(el, mark));\n else el.append(chip(el, mark));\n };\n const unpaint = (el) => {\n clearChip(el);\n el.classList.remove('am-mark');\n delete el.dataset.kind;\n };\n showClear();\n if (marks.size) for (const [el, key] of keyMap()) if (marks.has(key)) paint(el, marks.get(key));\n\n // The popover edits one block. Save stays off until a kind is picked, and a hint says so. 1\u20134 pick a kind from the keyboard and\n // move to the note; Ctrl / Cmd + Enter saves. A popover closed without Save keeps its kind and note as a draft for that block until the page reloads.\n const pop = document.createElement('div');\n pop.className = 'am-remark-pop';\n pop.hidden = true;\n pop.setAttribute('role', 'dialog');\n pop.setAttribute('aria-label', ui.button);\n document.body.append(pop);\n let opener = null;\n let anchor = null;\n let keepDraft = null;\n const close = (restoreFocus) => {\n if (pop.hidden) return;\n keepDraft?.();\n keepDraft = null;\n pop.hidden = true;\n if (restoreFocus) (opener?.isConnected && opener !== document.body ? opener : btn).focus();\n };\n const place = () => {\n const rect = anchor.getBoundingClientRect();\n const rtl = getComputedStyle(document.documentElement).direction === 'rtl';\n const x = rtl ? rect.right - pop.offsetWidth : rect.left;\n // Under the block; a block taller than the window gets the popover at the bottom of the window instead.\n const y = Math.min(rect.bottom + 6, window.innerHeight - pop.offsetHeight - 8);\n pop.style.left = `${window.scrollX + Math.min(Math.max(8, x), window.innerWidth - pop.offsetWidth - 8)}px`;\n pop.style.top = `${window.scrollY + Math.max(8, y)}px`;\n };\n const make = (tag, props) => Object.assign(document.createElement(tag), props);\n const open = (el) => {\n const key = keyMap().get(el);\n const mark = marks.get(key);\n const draft = drafts.get(key);\n let kind = draft?.kind ?? mark?.kind ?? '';\n opener = document.activeElement;\n anchor = el;\n\n const note = make('textarea', { rows: 2, placeholder: ui.hint, value: draft?.note ?? mark?.note ?? '' });\n note.setAttribute('aria-label', ui.hint);\n const keep = make('button', { type: 'button', className: 'am-btn', textContent: ui.save, disabled: !kind });\n const need = make('span', { className: 'am-remark-need', textContent: ui.need, hidden: Boolean(kind) });\n keepDraft = () => {\n if (kind || note.value.trim()) drafts.set(key, { kind, note: note.value });\n else drafts.delete(key);\n showClear();\n };\n const done = () => { drafts.delete(key); keepDraft = null; showClear(); };\n keep.addEventListener('click', () => {\n done();\n const saved = { key, kind, note: note.value.trim() };\n marks.set(key, saved);\n save();\n paint(el, saved);\n close(true);\n });\n const actions = make('div', { className: 'am-remark-actions' });\n actions.append(keep);\n if (mark) {\n const drop = make('button', { type: 'button', className: 'am-btn', textContent: ui.remove });\n drop.addEventListener('click', () => {\n done();\n marks.delete(key);\n save();\n unpaint(el);\n close(true);\n });\n actions.append(drop);\n }\n const choose = (k) => {\n kind = k;\n for (const other of kindBtns) other.setAttribute('aria-pressed', String(other.dataset.kind === k));\n keep.disabled = false;\n need.hidden = true;\n };\n const kindBtns = KINDS.map((k, i) => {\n const kb = make('button', { type: 'button', className: 'am-remark-kind', textContent: ui.kinds[k] });\n kb.dataset.kind = k;\n kb.dataset.n = i + 1;\n kb.setAttribute('aria-pressed', String(k === kind));\n kb.addEventListener('click', () => choose(k));\n return kb;\n });\n // Ctrl / Cmd + Enter presses Save (nothing while Save waits for a kind). A digit types into the note, so it picks a kind\n // only while the focus is outside the note.\n pop.onkeydown = (e) => {\n if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && !e.isComposing) {\n e.preventDefault();\n if (!keep.disabled) keep.click();\n return;\n }\n if (e.target === note || e.ctrlKey || e.metaKey || e.altKey || !/^[1-4]$/.test(e.key)) return;\n e.preventDefault();\n choose(KINDS[Number(e.key) - 1]);\n note.focus();\n };\n actions.append(need);\n pop.replaceChildren(make('div', { className: 'am-remark-kinds' }), note, actions);\n pop.firstChild.append(...kindBtns);\n pop.hidden = false;\n place();\n (kindBtns.find((b) => b.dataset.kind === kind) ?? kindBtns[0]).focus({ preventScroll: true });\n };\n\n // Picking works only while remark mode is on. A click on a marked block edits its mark, on a plain block starts one.\n // The block under the pointer gets an outline: the same blockAt decides what is outlined and what a click picks.\n let hover = null;\n const track = (e) => {\n const el = e.type === 'mouseout' && e.relatedTarget === null ? null : blockAt(e.target);\n if (el === hover) return;\n hover?.classList.remove('am-remark-hover');\n hover = el;\n hover?.classList.add('am-remark-hover');\n };\n const pick = (e) => {\n const el = blockAt(e.target);\n if (el) open(el);\n };\n // The keyboard picks too: while the mode is on, every block takes focus with Tab, and Enter or Space opens its popover. A block\n // that already had a tabindex keeps it; only the ones the mode added lose it again.\n const pickKey = (e) => {\n if ((e.key !== 'Enter' && e.key !== ' ') || e.ctrlKey || e.metaKey || e.altKey || !e.target.hasAttribute?.('data-am-pick')) return;\n e.preventDefault();\n open(e.target);\n };\n const focusable = (on) => {\n if (!on && !keys) return; // the mode starts off: a page nobody marked builds no block keys\n for (const el of keyMap().keys()) {\n if (on && !el.hasAttribute('tabindex')) {\n el.tabIndex = 0;\n el.setAttribute('data-am-pick', '');\n } else if (!on && el.hasAttribute('data-am-pick')) {\n el.removeAttribute('tabindex');\n el.removeAttribute('data-am-pick');\n }\n }\n };\n const setMode = (on) => {\n btn.classList.toggle('is-on', on);\n btn.setAttribute('aria-pressed', String(on));\n const toggle = on ? 'addEventListener' : 'removeEventListener';\n document.body[toggle]('click', pick);\n document.body[toggle]('mouseover', track);\n document.body[toggle]('mouseout', track);\n document.body[toggle]('keydown', pickKey);\n focusable(on);\n if (!on) {\n track({ type: 'mouseout', relatedTarget: null });\n close(false);\n }\n };\n btn.addEventListener('click', () => setMode(btn.getAttribute('aria-pressed') !== 'true'));\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') close(true);\n });\n // A click outside the popover closes it; the same click may then start another mark.\n document.addEventListener('click', (e) => {\n if (!pop.hidden && !pop.contains(e.target)) close(false);\n }, true);\n setMode(false);\n\n // What the Reply button reads: the marked blocks that are on the page, in page order.\n window.__amRemarkData = () => {\n if (!marks.size) return [];\n const live = [];\n for (const [el, key] of keyMap()) {\n const mark = marks.get(key);\n if (mark) live.push({ panel: panelOf(el), quote: quote(blockText(el)), kind: mark.kind, note: mark.note });\n }\n return live;\n };\n})();\n})();\n(() => {\n// Pure planner for justified (\"photo wall\") rows on sheet pages. No DOM access.\n//\n// This file must stay inlinable into the page script: top-level declarations only, no imports, and the exports are\n// `planLayout` and the constants the DOM adapter shares (STEP, MAX_SCALE, MIN_SCALE). The page build strips the `export ` keyword,\n// and test/layout-plan.test.js checks that this still works.\n//\n// planLayout({ width, gap, cols, panels }) -> { rows: [{ columns: [{ panels: [index, ...], width }], height }] }\n//\n// Input (all lengths in px):\n// width container width\n// gap space between columns, and between two panels stacked in one column\n// cols most columns in one row (the planner never uses more than MAX_COLUMNS, but spans stay shares of `cols`)\n// panels one entry per panel, in reading order:\n// samples [{ w, h }] panel height at sampled widths, ascending by w (heights between samples are interpolated)\n// minWidth narrowest feasible width (clamped to `width`)\n// maxWidth widest useful width; beyond it the panel only gains empty space (default: no limit)\n// natural natural diagram width for a diagram-only panel (default: none)\n// pad panel width not used by the diagram (padding and border; default 0)\n// span the author's width hint in grid columns (default 1); span >= cols keeps the panel alone in its row\n//\n// Output: { rows, maxScale }. Rows are in reading order; a row is a list of columns (at most `cols`); a column holds one panel or two\n// consecutive panels, stacked. For integer inputs the column widths plus the gaps between them equal `width`.\n// Rows are chosen by dynamic programming over break points; widths by a search in STEP px steps. Cost per row:\n// H = tallest column; waste = sum((H - columnHeight) * columnWidth) + sum over diagrams wider than maxWidth of (w - maxWidth) * h\n// dev = sum(((w - preferred) / oneColumn)^2) + SCALE_WEIGHT * sum over diagrams of (ln(scale) / ln(MAX_SCALE))^2\n// cost = waste / 1000 + PREF_WEIGHT * dev * H\n// Scale band: diagrams on one page stay at similar sizes. With the result's `maxScale` as the diagram size limit, a diagram is\n// shown at scale min(maxScale, (width - pad) / natural). The planner tries a few bands [lo, lo * BAND_RATIO] (lo in BAND_LOS) and\n// keeps the cheapest plan in which no diagram is narrower than scale lo and none is shown above the band's top, so the largest and\n// smallest diagram scale on the page differ by at most BAND_RATIO. A panel wider than its diagram's top size keeps the diagram at\n// that size, and the page script must set the diagram's max-width to natural * maxScale. The band starts no higher than the\n// largest scale the page allows the least roomy diagram, so one wide diagram lowers the band for the others.\n// If no band is feasible the plan is made without a band (maxScale = MAX_SCALE); if no plan fits (or the input is unusable) the\n// result is a single column: one panel per row at the full width.\n\nconst STEP = 10;\nconst MAX_SCALE = 1.25;\nconst MIN_SCALE = 0.75; // the narrowest a diagram is shown, as a share of its natural width\nconst MAX_COLUMNS = 6; // rows with more columns are unreadable, and the search grows steeply with the column count\nconst BAND_RATIO = 1.25; // the largest and smallest diagram scale on a page differ by at most this\nconst BAND_LOS = [MIN_SCALE, 0.85, 0.95, 1]; // lower ends tried for the band; lo * BAND_RATIO is the upper end (1.25 means no upper limit)\nconst SCALE_WEIGHT = 3;\nconst PREF_WEIGHT = 0.15;\n\nfunction heightAt(samples, w) {\n const i = samples.findIndex((s) => s.w >= w);\n if (i === -1) return samples[samples.length - 1].h;\n if (i === 0) return samples[0].h;\n const a = samples[i - 1];\n const b = samples[i];\n return a.h + ((b.h - a.h) * (w - a.w)) / (b.w - a.w);\n}\n\n// Every way to split `len` consecutive panels into columns of 1 or 2 panels, as lists of column sizes.\nfunction splits(len) {\n if (len === 0) return [[]];\n return [1, 2].filter((k) => k <= len).flatMap((k) => splits(len - k).map((rest) => [k, ...rest]));\n}\n\nfunction singleColumn(width, panels) {\n return { rows: panels.map((_, i) => ({ columns: [{ panels: [i], width }], height: 0 })) };\n}\n\nfunction planLayout({ width, gap = 0, cols = 3, panels }) {\n const usable = Number.isFinite(width) && width > 0 && panels.every((p) => Array.isArray(p.samples) && p.samples.length > 0);\n if (!usable) return singleColumn(width, panels);\n\n // `cols` stays the unit of the author's spans; no row gets more than MAX_COLUMNS columns however large `cols` is.\n const maxColumns = Math.min(cols, MAX_COLUMNS);\n const oneColumn = Math.max(1, (width - gap * (cols - 1)) / cols);\n // Per-panel limits. With a band [lo, lo * BAND_RATIO], a diagram is no narrower than scale lo and shown at most at the top of the\n // band: a wider panel keeps it at that size and gains empty space, which the cost counts as waste.\n const prepare = (lo) => panels.map((p) => {\n const pad = p.pad ?? 0;\n const diagram = lo > 0 && p.natural > 0;\n const scaleCap = diagram ? Math.min(MAX_SCALE, lo * BAND_RATIO) : MAX_SCALE;\n return {\n ...p,\n minWidth: Math.min(width, Math.max(Math.ceil(p.minWidth || 0), diagram ? Math.ceil(p.natural * lo + pad) : 0)),\n maxWidth: Math.min(p.maxWidth ?? Infinity, diagram ? p.natural * scaleCap + pad : Infinity),\n scaleCap,\n pad,\n preferred: Math.min(width, (p.span ?? 1) * oneColumn + ((p.span ?? 1) - 1) * gap),\n alone: (p.span ?? 1) >= cols,\n };\n });\n let info = prepare(0);\n // Beyond its maxWidth a panel only gains empty space, so its height stops changing there (matters when a band lowers maxWidth).\n const heightOf = (p, w) => heightAt(p.samples, Math.min(w, p.maxWidth));\n const columnHeight = (col, w) => col.reduce((h, k) => h + heightOf(info[k], w), 0) + gap * (col.length - 1);\n\n function bestColumns(columns) {\n const avail = width - gap * (columns.length - 1);\n const mins = columns.map((c) => Math.max(...c.map((k) => info[k].minWidth)));\n const minsFrom = mins.map((_, n) => mins.slice(n).reduce((s, w) => s + w, 0));\n if (minsFrom[0] > avail) return null;\n let best = null;\n const evaluate = (ws) => {\n const hs = ws.map((w, n) => columnHeight(columns[n], w));\n const H = Math.max(...hs);\n let waste = 0;\n let dev = 0;\n ws.forEach((w, n) => {\n waste += (H - hs[n]) * w;\n for (const k of columns[n]) {\n const p = info[k];\n if (w > p.maxWidth) waste += (w - p.maxWidth) * heightOf(p, w);\n dev += ((w - p.preferred) / oneColumn) ** 2;\n if (p.natural > 0) {\n const scale = Math.min(p.scaleCap, Math.max(w - p.pad, 1) / p.natural);\n dev += SCALE_WEIGHT * (Math.log(scale) / Math.log(MAX_SCALE)) ** 2;\n }\n }\n });\n const cost = waste / 1000 + PREF_WEIGHT * dev * H;\n if (!best || cost < best.cost) best = { cost, ws, height: H, columns };\n };\n const choose = (n, used, ws) => {\n if (n === columns.length - 1) {\n const w = avail - used;\n if (w >= mins[n]) evaluate([...ws, w]);\n return;\n }\n for (let w = mins[n]; used + w + minsFrom[n + 1] <= avail; w += STEP) choose(n + 1, used + w, [...ws, w]);\n };\n choose(0, 0, []);\n return best;\n }\n\n // Best columns for one row of panels i..j.\n function bestRow(i, j) {\n if (j > i && info.slice(i, j + 1).some((p) => p.alone)) return null;\n let best = null;\n for (const split of splits(j - i + 1)) {\n if (split.length > maxColumns) continue;\n let next = i;\n const columns = split.map((size) => Array.from({ length: size }, () => next++));\n const r = bestColumns(columns);\n if (r && (!best || r.cost < best.cost)) best = r;\n }\n return best;\n }\n\n // Row breaks in reading order, for the band set up in `info`. A row holds at most 2 * maxColumns panels. Null if nothing fits.\n function solve() {\n const n = panels.length;\n const total = Array(n + 1).fill(Infinity);\n const from = Array(n + 1).fill(-1);\n const chosen = Array(n + 1).fill(null);\n total[0] = 0;\n for (let j = 1; j <= n; j++) {\n for (let i = Math.max(0, j - 2 * maxColumns); i < j; i++) {\n if (total[i] === Infinity) continue;\n const r = bestRow(i, j - 1);\n if (r && total[i] + r.cost < total[j]) {\n total[j] = total[i] + r.cost;\n from[j] = i;\n chosen[j] = r;\n }\n }\n }\n if (total[n] === Infinity) return null;\n const rows = [];\n for (let j = n; j > 0; j = from[j]) {\n const r = chosen[j];\n rows.unshift({ columns: r.columns.map((panelsInColumn, c) => ({ panels: panelsInColumn, width: r.ws[c] })), height: r.height });\n }\n return { rows, cost: total[n] };\n }\n\n let best = null;\n const diagrams = panels.filter((p) => p.natural > 0);\n if (diagrams.length > 1) {\n // No diagram can be shown larger than the page allows, so the band cannot start above the smallest of those limits.\n const reach = Math.min(...diagrams.map((p) => Math.min(MAX_SCALE, Math.max(width - (p.pad ?? 0), 1) / p.natural)));\n for (const lo of new Set([...BAND_LOS.filter((x) => x < reach), reach])) {\n info = prepare(lo);\n const r = solve();\n if (r && (!best || r.cost < best.cost)) best = { ...r, maxScale: Math.min(MAX_SCALE, lo * BAND_RATIO) };\n }\n info = prepare(0);\n }\n best ??= solve();\n return best ? { rows: best.rows, maxScale: best.maxScale ?? MAX_SCALE } : singleColumn(width, panels);\n}\n\n// DOM adapter for the sheet's justified (\"photo wall\") layout. Not a module: compose.js puts it after src/runtime/layout-plan.js\n// (which defines planLayout and the shared STEP, MAX_SCALE, MIN_SCALE) inside one function scope of the page script.\n//\n// It measures every panel at sampled widths, asks planLayout for rows and column widths, and applies them with flexbox.\n// The rendered HTML keeps the plain CSS grid: with JavaScript off, at the single-column breakpoint, or while printing, the grid is what\n// shows (the planned widths belong to the screen width, so print never gets a mix of the two); after printing the layout comes back.\n\nconst grid = document.querySelector('.am-grid');\nconst panels = grid ? [...grid.children].filter((el) => el.classList.contains('am-panel')) : [];\n\nif (panels.length > 1) {\n const SINGLE_COLUMN = '(max-width: 760px)'; // the single-column breakpoint in src/themes/base.css\n const TWO_COLUMNS = '(max-width: 1100px)'; // below this the CSS grid has two columns\n const SAMPLE_STEP = 20; // width sampling step, px; the planner interpolates between samples\n // The width floors are text sizes (px at scale 1). They take the page scale on every pass, so a runtime change of --am-scale re-plans.\n const TEXT_MIN = 260; // text keeps at least about 16 CJK characters per line\n const TABLE_COL_MIN = 96; // per table column, px\n const TABLE_COL_COMFORT = 220; // a table column this wide reads three or four words per line\n const KV_COL_MIN = 120; // per key-value column, px: a value of two short words stays on one line\n const DIAGRAM_MIN = 160;\n const RESIZE_DELAY = 150;\n const pageScale = () => {\n const scale = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--am-scale'));\n return Number.isFinite(scale) && scale > 0 ? scale : 1;\n };\n const OVERFLOWING = '.am-table-wrap, .am-diagram, .am-annot-scroll, pre';\n\n // The first-row cells of each table carry the column widths fitTables() sets, so restore() resets them too.\n const tables = [...grid.querySelectorAll('.am-table-wrap > table')];\n const headCells = (table) => [...(table.rows[0]?.cells ?? [])];\n const original = new Map([grid, ...panels, ...grid.querySelectorAll('.am-diagram > svg'), ...tables.flatMap(headCells)].map((el) => [el, el.getAttribute('style')]));\n const restoreStyle = (el) => (original.get(el) === null ? el.removeAttribute('style') : el.setAttribute('style', original.get(el)));\n\n // Back to the plain grid markup and styles.\n const restore = () => {\n for (const box of grid.querySelectorAll(':scope > .am-col')) box.replaceWith(...box.children);\n for (const el of original.keys()) restoreStyle(el);\n };\n\n // The author's width hint, rendered as data-span only when the author wrote one. The inline grid-column is the no-JavaScript fallback\n // and may hold spans the server added, so it is never read here.\n const spanHint = (el) => Number(el.dataset.span) || 1;\n const diagramOnly = (el) => {\n const body = el.querySelector(':scope > .am-panel-body');\n return body && body.children.length === 1 ? body.querySelector(':scope > .am-diagram > svg') : null;\n };\n const naturalWidth = (svg) => Number(svg.getAttribute('width')) || 0;\n\n // The width each column of a table reads well at: its natural width, but no wider than TABLE_COL_COMFORT unless its longest word\n // needs more. Below it the cells wrap one word per line, so a panel with a table is not planned narrower than the sum, and\n // fitTables() keeps each column at its share (the browser would otherwise give the room to the longest column).\n const columnWidths = new Map();\n function comfortableWidth(table, scale) {\n const saved = table.getAttribute('style');\n const columns = (width) => {\n table.style.width = width;\n return headCells(table).map((cell) => cell.getBoundingClientRect().width);\n };\n const most = columns('max-content');\n const least = columns('min-content');\n if (saved === null) table.removeAttribute('style');\n else table.setAttribute('style', saved);\n // A max-content column comes out a fraction under its text in Chrome, enough to wrap the last word, so it gets one pixel more.\n const want = most.map((w, i) => Math.min(Math.ceil(w) + 1, Math.max(least[i], TABLE_COL_COMFORT * scale)));\n columnWidths.set(table, { least, want });\n return want.reduce((sum, w) => sum + w, 0);\n }\n\n // After the layout: each column gets at least its comfortable width, scaled down toward its longest word when the panel came out\n // narrower than planned (a page narrower than the table), so a table scrolls sideways only when even its longest words do not fit.\n function fitTables() {\n for (const [table, { least, want }] of columnWidths) {\n // Each width is rounded up to a whole pixel (a column a fraction too narrow wraps its last word), so keep a pixel per column spare.\n const room = table.parentElement.clientWidth - want.length;\n const low = least.reduce((s, w) => s + w, 0);\n const high = want.reduce((s, w) => s + w, 0);\n const k = high > room ? Math.max(0, (room - low) / (high - low || 1)) : 1;\n headCells(table).forEach((cell, i) => { cell.style.minWidth = `${Math.ceil(least[i] + (want[i] - least[i]) * k)}px`; });\n }\n }\n\n // Height (and, for panels with tables or code, the narrowest width without sideways scrolling) at sampled widths.\n // Only one panel is displayed while it is measured, so each width change lays out that panel alone.\n function measure(width) {\n const scale = pageScale();\n grid.style.display = 'block';\n for (const el of panels) {\n el.style.display = 'none';\n el.style.boxSizing = 'border-box';\n for (const svg of el.querySelectorAll('.am-diagram > svg')) {\n svg.style.width = '100%';\n svg.style.maxWidth = `${naturalWidth(svg) * MAX_SCALE}px`;\n }\n }\n const info = panels.map((el) => {\n const svg = diagramOnly(el);\n const svgs = [...el.querySelectorAll('.am-diagram > svg')];\n const scrollers = el.querySelectorAll(OVERFLOWING);\n const tableCols = Math.max(0, ...[...el.querySelectorAll('table tr:first-child')].map((tr) => tr.children.length));\n el.style.display = '';\n el.style.width = `${width}px`;\n const pad = svg ? el.offsetWidth - svg.parentElement.clientWidth : 0;\n const natural = svg ? naturalWidth(svg) : 0;\n const shrunk = Math.max(0, ...svgs.map((s) => naturalWidth(s) * MIN_SCALE)) + (svg ? pad : 34);\n const tableFloors = [...el.querySelectorAll('.am-table-wrap > table')].map((t) => comfortableWidth(t, scale) + el.offsetWidth - t.parentElement.clientWidth);\n // A key-value grid gets the same care: the room a table gains must not squeeze a neighbouring grid to one word per line.\n const kvs = [...el.querySelectorAll('.am-kv')].map((kv) => (Number(kv.style.getPropertyValue('--kv-cols')) || 1) * KV_COL_MIN * scale + el.offsetWidth - kv.clientWidth);\n const floor = svg ? Math.max(DIAGRAM_MIN * scale, natural * MIN_SCALE + pad) : Math.max(TEXT_MIN * scale, shrunk, tableCols * TABLE_COL_MIN * scale + 34, ...tableFloors, ...kvs);\n const from = Math.min(width, Math.floor(floor / STEP) * STEP);\n const samples = [];\n let fits = null;\n for (let w = from; ; w += SAMPLE_STEP) {\n w = Math.min(w, width);\n el.style.width = `${w}px`;\n if (fits === null && !svg && scrollers.length && ![...scrollers].some((s) => s.scrollWidth > s.clientWidth + 1)) fits = w;\n samples.push({ w, h: el.offsetHeight });\n if (w === width) break;\n }\n el.style.display = 'none';\n return {\n samples,\n minWidth: svg ? floor : Math.max(floor, fits ?? (scrollers.length ? width : 0)),\n maxWidth: svg ? natural * MAX_SCALE + pad : Infinity,\n natural,\n pad,\n span: spanHint(el),\n };\n });\n for (const el of panels) {\n el.style.display = '';\n el.style.width = '';\n }\n return info;\n }\n\n // Each column gets a fixed width. A row adds up to the full width, so flex-wrap breaks rows by itself.\n // Stacked panels go into a column wrapper whose last panel absorbs the extra height.\n function apply(plan, gap) {\n grid.style.display = 'flex';\n grid.style.flexWrap = 'wrap';\n grid.style.alignItems = 'stretch';\n grid.style.gap = `${gap}px`;\n for (const el of panels) {\n el.style.gridColumn = '';\n el.style.gridRow = '';\n el.style.flex = '0 0 auto';\n }\n for (const row of plan.rows) {\n for (const col of row.columns) {\n const width = `${col.width}px`;\n if (col.panels.length === 1) {\n panels[col.panels[0]].style.width = width;\n continue;\n }\n const box = document.createElement('div');\n box.className = 'am-col';\n box.style.cssText = `width:${width};flex:0 0 auto;display:flex;flex-direction:column;gap:${gap}px`;\n panels[col.panels[0]].before(box);\n for (const k of col.panels) {\n panels[k].style.width = '';\n box.append(panels[k]);\n }\n panels[col.panels[col.panels.length - 1]].style.flex = '1 1 auto';\n }\n }\n }\n\n // Diagram-only panels show their diagram at most at the top of the page's scale band; a wider panel gains empty space instead.\n function capDiagrams(maxScale) {\n for (const el of panels) {\n const svg = diagramOnly(el);\n if (svg) svg.style.maxWidth = `${naturalWidth(svg) * maxScale}px`;\n }\n }\n\n const containerWidth = () => Math.floor(grid.getBoundingClientRect().width);\n\n function justify() {\n if (printing || printQuery.matches) return;\n try {\n // A vertical scrollbar can appear or vanish once the rows change height; plan again if the width moved.\n let planned = -1;\n for (let pass = 0; pass < 3 && planned !== containerWidth(); pass++) {\n restore();\n if (matchMedia(SINGLE_COLUMN).matches) return;\n planned = containerWidth();\n const gap = parseFloat(getComputedStyle(grid).columnGap) || 0;\n const cols = Math.max(1, Number(getComputedStyle(grid).getPropertyValue('--cols')) || 3);\n const plan = planLayout({ width: planned, gap, cols: matchMedia(TWO_COLUMNS).matches ? Math.min(cols, 2) : cols, panels: measure(planned) });\n apply(plan, gap);\n capDiagrams(plan.maxScale);\n fitTables();\n }\n // The width never settled: columns planned for another width would overflow or leave gaps, so show the plain grid.\n if (planned !== containerWidth()) restore();\n } catch {\n restore();\n }\n }\n\n // Printing: back to the plain grid (spans and all), and the layout again afterwards. Browsers disagree on which of the\n // `beforeprint` event and the print media query change fires first, or at all, so listen to both; both are idempotent.\n // While `printing` is set (beforeprint to afterprint) justify() does nothing, so a late resize cannot bring flex widths into the print layout.\n let printing = false;\n const printQuery = matchMedia('print');\n let timer = 0;\n const later = () => {\n clearTimeout(timer);\n timer = setTimeout(justify, RESIZE_DELAY);\n };\n const toPrint = () => {\n clearTimeout(timer);\n restore();\n };\n justify();\n addEventListener('resize', later);\n // A reader's text size changes every panel's text widths and heights, so the sheet is planned again like a resize.\n addEventListener('am-scale', later);\n addEventListener('beforeprint', () => {\n printing = true;\n toPrint();\n });\n addEventListener('afterprint', () => {\n printing = false;\n later();\n });\n printQuery.addEventListener('change', (e) => (e.matches ? toPrint() : later()));\n // Late changes to panel heights: web fonts arriving, and images inside the grid finishing their load (load does not bubble, so capture it).\n document.fonts?.ready.then(later);\n grid.addEventListener('load', later, true);\n // Switching theme changes paddings and fonts, hence panel heights.\n document.querySelector('[data-am=\"theme\"]')?.addEventListener('click', later);\n}\n})();\n// The outline rail of a doc page (src/templates/doc.js): the markup already works without a script, <details> opens the list and the\n// links jump. This adds the hover dwell, the open direction, the keys, the tap outside and the marking of the current section.\n(() => {\n const nav = document.querySelector('nav.am-toc');\n const box = nav && nav.querySelector('details.am-outline');\n if (!box) return;\n const sum = box.querySelector('summary');\n const links = Array.from(box.querySelectorAll('.am-outline-list a'));\n const ticks = Array.from(box.querySelectorAll('.am-tick'));\n const LIST_W = 240; // keep in step with .am-outline-list in src/themes/base.css\n const EDGE = 10; // the 6px gap to the rail plus a margin to the viewport edge\n let current = '';\n let byHover = false;\n let dwell = 0;\n let leave = 0;\n\n // Open away from the body when the room outside the rail fits the list; otherwise over the body. Never past the viewport.\n const place = () => {\n const r = sum.getBoundingClientRect();\n const right = r.left + r.width / 2 > innerWidth / 2;\n const room = right ? innerWidth - r.right : r.left;\n nav.dataset.flow = room >= Math.min(LIST_W, innerWidth - 48) + EDGE ? 'out' : 'in';\n };\n const setOpen = (open) => {\n if (open) place();\n box.open = open;\n if (!open) byHover = false;\n };\n const peek = (tick) => ticks.forEach((t) => t.classList.toggle('is-peek', t === tick));\n const currentLink = () => links.find((a) => a.getAttribute('aria-current') === 'true') || links[0];\n\n const mark = (id) => {\n current = id;\n ticks.forEach((t) => t.classList.toggle('is-current', t.dataset.id === id));\n links.forEach((a) => {\n if (a.getAttribute('href') === `#panel-${id}`) a.setAttribute('aria-current', 'true');\n else a.removeAttribute('aria-current');\n });\n };\n const sections = ticks.map((t) => document.getElementById(`panel-${t.dataset.id}`)).filter(Boolean);\n if (sections.length) mark(sections[0].id.slice(6));\n if (sections.length && 'IntersectionObserver' in window) {\n // A thin band a third of the way down the viewport: the section across it is the one being read.\n const seen = new Set();\n const io = new IntersectionObserver((entries) => {\n entries.forEach((e) => (e.isIntersecting ? seen.add(e.target) : seen.delete(e.target)));\n const hit = sections.filter((s) => seen.has(s)).pop();\n if (hit && hit.id.slice(6) !== current) mark(hit.id.slice(6));\n }, { rootMargin: '-30% 0px -65% 0px' });\n sections.forEach((s) => io.observe(s));\n }\n\n place();\n addEventListener('resize', place);\n\n // Mouse: dwelling on the rail opens the list, leaving it closes a list opened that way. A tap or click opens it for good.\n box.addEventListener('pointerenter', (e) => {\n clearTimeout(leave);\n if (e.pointerType !== 'mouse' || box.open) return;\n dwell = setTimeout(() => { setOpen(true); byHover = true; }, 300);\n });\n box.addEventListener('pointerleave', () => {\n clearTimeout(dwell);\n // A link the keyboard moved into keeps the list open; focusout closes it once the focus leaves the nav.\n if (byHover) leave = setTimeout(() => { if (!nav.contains(document.activeElement)) setOpen(false); }, 250);\n });\n sum.addEventListener('click', (e) => {\n clearTimeout(dwell);\n if (box.open && byHover) { e.preventDefault(); byHover = false; return; }\n place();\n });\n box.addEventListener('toggle', () => { if (box.open) peek(null); });\n\n // Keyboard: the summary opens with Enter or Space (native); arrows move through the links; Esc closes and returns to the rail.\n sum.addEventListener('focus', () => {\n if (sum.matches(':focus-visible')) peek(ticks.find((t) => t.dataset.id === current));\n });\n sum.addEventListener('blur', () => peek(null));\n nav.addEventListener('keydown', (e) => {\n if (e.key === 'Escape' && box.open) {\n e.preventDefault();\n setOpen(false);\n sum.focus();\n return;\n }\n if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) return;\n const at = links.indexOf(document.activeElement);\n if (at < 0 && e.target !== sum) return;\n e.preventDefault();\n if (!box.open) setOpen(true);\n let next;\n if (e.key === 'Home') next = links[0];\n else if (e.key === 'End') next = links[links.length - 1];\n else if (at < 0) next = e.key === 'ArrowDown' ? currentLink() : links[links.length - 1];\n else next = links[Math.min(links.length - 1, Math.max(0, at + (e.key === 'ArrowDown' ? 1 : -1)))];\n next.focus();\n });\n nav.addEventListener('focusout', (e) => {\n if (box.open && e.relatedTarget && !nav.contains(e.relatedTarget)) setOpen(false);\n });\n\n // Choosing a section or tapping outside closes the list.\n links.forEach((a) => a.addEventListener('click', () => setOpen(false)));\n document.addEventListener('pointerdown', (e) => { if (box.open && !nav.contains(e.target)) setOpen(false); });\n document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && box.open && !nav.contains(e.target)) setOpen(false); });\n})();\n})();\n";
640
640
  var DIFF_CSS = "/* Diff block (only on pages that have one): red and green lines, a hunk row, and two gutters, old and new, drawn from data-o / data-n.\n The hues are fixed and mixed into the theme's own --fill and --ink, so they read as green and red in every theme, light and dark. */\n.am-codeblock--diff { --diff-add: #1f9d4d; --diff-del: #d1344a; }\n.am-code-stat { display: inline-flex; gap: 6px; flex: none; font: var(--am-fs-small)/1.3 var(--font-mono); }\n.am-code-stat-add { color: color-mix(in srgb, var(--diff-add) 75%, var(--ink)); }\n.am-code-stat-del { color: color-mix(in srgb, var(--diff-del) 75%, var(--ink)); }\n.am-code--diff .am-ln { display: flex; padding: 0 14px 0 0; }\n.am-code--diff:not(.am-code--dnum) .am-ln { padding-left: 14px; }\n.am-code--dnum .am-ln::before, .am-code--dnum .am-ln::after {\n flex: none; box-sizing: content-box; width: 3.5ch; padding: 0 6px; text-align: right; color: var(--ink-3);\n user-select: none; -webkit-user-select: none;\n}\n.am-code--dnum .am-ln::before { content: attr(data-o); order: -2; }\n.am-code--dnum .am-ln::after { content: attr(data-n); order: -1; margin-right: 10px; }\n.am-ln--add { background: color-mix(in srgb, var(--diff-add) 14%, var(--fill)); }\n.am-ln--del { background: color-mix(in srgb, var(--diff-del) 14%, var(--fill)); }\n.am-ln--add::before, .am-ln--add::after { background: color-mix(in srgb, var(--diff-add) 28%, var(--fill)); }\n.am-ln--del::before, .am-ln--del::after { background: color-mix(in srgb, var(--diff-del) 28%, var(--fill)); }\n.am-code--diff .am-ln--hl { box-shadow: none; }\n.am-code--diff .am-ln--hl::before { box-shadow: inset 3px 0 0 var(--accent); }\n.am-code--diff .am-ln--ctx.am-ln--hl { background: var(--accent-bg); }\n.am-code--diff .am-ln--hunk { display: block; min-height: 0; padding: 1px 14px; font-size: var(--am-fs-fine); color: var(--ink-3); background: color-mix(in srgb, var(--accent) 8%, var(--fill)); }\n.am-code--dnum .am-ln--hunk::before, .am-code--dnum .am-ln--hunk::after { content: none; }\n.am-code--diff .am-ln--meta { display: none; }\n";
641
641
  var DELTA_CSS = `/* Change markers (only on pages that have one). Only the Changes view (.am-view-changes) draws change styling: colors, strike-through, faded items
642
642
  and badges. Before and After look like a plain diagram, and the items that do not exist in the view are hidden.
@@ -1357,8 +1357,8 @@ var VIDEO_EXPORT_JS = "// The export engine for the path that has no ffmpeg: the
1357
1357
  var VIDEO_MUX_JS = "// Minimal WebM (Matroska) writer for the export path that has no ffmpeg: the browser encodes the frames (WebCodecs,\n// see src/runtime/video.js) and this module writes the container. One VP8/VP9 video track and an optional Opus audio\n// track. The blocks are buffered, sorted by time and cut into clusters of about a second, so the sound and the\n// picture of a moment sit next to each other in the file. The Segment and the Clusters carry the unknown size, which\n// is how a stream is written: nothing needs to be measured first and nothing is patched afterwards.\n// Plain bytes only (no Buffer, no imports), so the same source runs in Node and inside a page (scripts/inline-assets.mjs\n// turns it into a script for the player page).\nconst APP = 'answer-me-with-html'; // MuxingApp / WritingApp\nconst CLUSTER_MS = 1000; // how much time one cluster holds\nconst SEEK_PRE_ROLL_NS = 80_000_000; // what the Opus specification asks for\n\nconst ID = {\n EBML: [0x1a, 0x45, 0xdf, 0xa3],\n EBMLVersion: [0x42, 0x86], EBMLReadVersion: [0x42, 0xf7], EBMLMaxIDLength: [0x42, 0xf2], EBMLMaxSizeLength: [0x42, 0xf3],\n DocType: [0x42, 0x82], DocTypeVersion: [0x42, 0x87], DocTypeReadVersion: [0x42, 0x85],\n Segment: [0x18, 0x53, 0x80, 0x67], Info: [0x15, 0x49, 0xa9, 0x66], TimecodeScale: [0x2a, 0xd7, 0xb1],\n MuxingApp: [0x4d, 0x80], WritingApp: [0x57, 0x41], Duration: [0x44, 0x89],\n Tracks: [0x16, 0x54, 0xae, 0x6b], TrackEntry: [0xae], TrackNumber: [0xd7], TrackUID: [0x73, 0xc5], FlagLacing: [0x9c],\n CodecID: [0x86], TrackType: [0x83], Video: [0xe0], PixelWidth: [0xb0], PixelHeight: [0xba],\n Audio: [0xe1], SamplingFrequency: [0xb5], Channels: [0x9f], CodecPrivate: [0x63, 0xa2],\n CodecDelay: [0x56, 0xaa], SeekPreRoll: [0x56, 0xbb],\n Cluster: [0x1f, 0x43, 0xb6, 0x75], Timecode: [0xe7], SimpleBlock: [0xa3],\n};\nconst UNKNOWN_SIZE = new Uint8Array([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);\n\nconst concat = (parts) => {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let at = 0;\n for (const p of parts) { out.set(p, at); at += p.length; }\n return out;\n};\nconst bytes = (id) => new Uint8Array(id);\nconst text = (s) => new TextEncoder().encode(s);\n\n// Element size as a variable-size integer, in the shortest length that fits; the all-ones value is reserved.\nfunction size(n) {\n for (let len = 1; len <= 8; len++) {\n if (len === 8 || n < 2 ** (7 * len) - 1) {\n const out = new Uint8Array(len);\n let v = n;\n for (let i = len - 1; i >= 0; i--) {\n out[i] = v & 0xff;\n v = Math.floor(v / 256);\n }\n out[0] |= 0x80 >> (len - 1);\n return out;\n }\n }\n}\n\n// Unsigned integer, big endian, as short as it can be (a Matroska integer drops leading zero bytes).\nfunction uint(n) {\n const out = [];\n let v = Math.round(n);\n do {\n out.unshift(v & 0xff);\n v = Math.floor(v / 256);\n } while (v > 0);\n return new Uint8Array(out);\n}\n\nfunction f64(x) {\n const out = new Uint8Array(8);\n new DataView(out.buffer).setFloat64(0, x);\n return out;\n}\n\nconst elem = (id, payload) => concat([bytes(id), size(payload.length), payload]);\n\n// WebM writer. video: { width, height, codec } with codec 'V_VP9' or 'V_VP8'; audio: null or\n// { channels, codecPrivate, preSkipSamples }. Duration is written up front, so a player knows the length at once.\nclass WebmWriter {\n constructor({ width, height, durationMs, videoCodec = 'V_VP9', audio = null }) {\n this.width = width;\n this.height = height;\n this.durationMs = durationMs;\n this.videoCodec = videoCodec;\n this.audio = audio;\n this.blocks = [];\n }\n\n // track 1 is the picture, track 2 the sound. key marks a key frame; tsUs is the time in microseconds.\n block({ track, key, tsUs, data }) {\n this.blocks.push({ track, key: Boolean(key), ms: Math.round(tsUs / 1000), data });\n }\n\n count(track) {\n return this.blocks.reduce((n, b) => n + (b.track === track ? 1 : 0), 0);\n }\n\n build() {\n const parts = [\n elem(ID.EBML, concat([\n elem(ID.EBMLVersion, uint(1)),\n elem(ID.EBMLReadVersion, uint(1)),\n elem(ID.EBMLMaxIDLength, uint(4)),\n elem(ID.EBMLMaxSizeLength, uint(8)),\n elem(ID.DocType, text('webm')),\n elem(ID.DocTypeVersion, uint(4)),\n elem(ID.DocTypeReadVersion, uint(2)),\n ])),\n concat([bytes(ID.Segment), UNKNOWN_SIZE]),\n elem(ID.Info, concat([\n elem(ID.TimecodeScale, uint(1_000_000)),\n elem(ID.MuxingApp, text(APP)),\n elem(ID.WritingApp, text(APP)),\n elem(ID.Duration, f64(this.durationMs)),\n ])),\n elem(ID.Tracks, concat([this.#videoTrack(), ...(this.audio ? [this.#audioTrack()] : [])])),\n ];\n for (const cluster of this.#clusters()) parts.push(cluster);\n return concat(parts);\n }\n\n #track(num, type, codecId, extra) {\n return elem(ID.TrackEntry, concat([\n elem(ID.TrackNumber, uint(num)),\n elem(ID.TrackUID, uint(num)),\n elem(ID.FlagLacing, uint(0)),\n elem(ID.CodecID, text(codecId)),\n elem(ID.TrackType, uint(type)),\n ...extra,\n ]));\n }\n\n #videoTrack() {\n return this.#track(1, 1, this.videoCodec, [\n elem(ID.Video, concat([elem(ID.PixelWidth, uint(this.width)), elem(ID.PixelHeight, uint(this.height))])),\n ]);\n }\n\n #audioTrack() {\n const { channels, codecPrivate, preSkipSamples } = this.audio;\n const extra = [elem(ID.Audio, concat([elem(ID.SamplingFrequency, f64(48000)), elem(ID.Channels, uint(channels))]))];\n if (codecPrivate) extra.unshift(elem(ID.CodecPrivate, codecPrivate));\n // The encoder adds pre-skip samples of silence; CodecDelay tells the player to drop them again.\n extra.push(elem(ID.CodecDelay, uint((preSkipSamples / 48000) * 1e9)), elem(ID.SeekPreRoll, uint(SEEK_PRE_ROLL_NS)));\n return this.#track(2, 2, 'A_OPUS', extra);\n }\n\n #clusters() {\n const blocks = [...this.blocks].sort((a, b) => a.ms - b.ms || a.track - b.track);\n const out = [];\n for (let i = 0; i < blocks.length; ) {\n const start = blocks[i].ms;\n const body = [elem(ID.Timecode, uint(start))];\n while (i < blocks.length && blocks[i].ms - start <= CLUSTER_MS) {\n body.push(this.#block(blocks[i], start));\n i++;\n }\n out.push(concat([bytes(ID.Cluster), UNKNOWN_SIZE, ...body]));\n }\n return out;\n }\n\n #block(b, clusterStart) {\n const head = new Uint8Array(4);\n head[0] = 0x80 | b.track; // the track number as a variable-size integer\n new DataView(head.buffer).setInt16(1, b.ms - clusterStart);\n head[3] = b.key ? 0x80 : 0x00;\n return elem(ID.SimpleBlock, concat([head, b.data]));\n }\n}\n\nwindow.__amvWebm = { WebmWriter };\n";
1358
1358
 
1359
1359
  // src/cli.js
1360
- import { join as join11, resolve as resolve4, dirname as dirname3, basename as basename4, extname as extname3, sep as sep4 } from "node:path";
1361
- import { spawn as spawn4 } from "node:child_process";
1360
+ import { join as join13, resolve as resolve5, dirname as dirname4, basename as basename5, extname as extname3, sep as sep4 } from "node:path";
1361
+ import { spawn as spawn5 } from "node:child_process";
1362
1362
 
1363
1363
  // src/languages/zh.js
1364
1364
  var zh_default = {
@@ -2462,8 +2462,15 @@ function themeSet(user = [], broken = /* @__PURE__ */ new Map(), folderWarning)
2462
2462
  if (bad) return `Theme "${name}" cannot be used: ${bad[1].reason} (${bad[1].file})`;
2463
2463
  return `Theme "${name}" is not installed. Choose one of: ${names2(scope).join(" | ")}`;
2464
2464
  },
2465
- // The themes a page carries: the built-in ones for its scope, plus its own theme when that is a user theme.
2466
- embedFor: (name, scope) => [...themes(scope), ...user.filter((t) => t.name === name && t.scope.includes(scope))],
2465
+ // The themes a page carries: the built-in ones for its scope, then every installed user theme for that scope, sorted by name,
2466
+ // so the toolbar picker lists them all and every one can be selected. A video has no picker, so it carries only its own theme
2467
+ // (when that is a user theme). The page's own theme is in the user list already.
2468
+ embedFor: (name, scope) => {
2469
+ const builtins = themes(scope);
2470
+ const own = user.filter((t) => t.name === name && t.scope.includes(scope));
2471
+ if (scope !== "page") return [...builtins, ...own];
2472
+ return [...builtins, ...user.filter((t) => t.scope.includes(scope)).sort((a, b) => a.name.localeCompare(b.name))];
2473
+ },
2467
2474
  warnings: [...folderWarning ? [folderWarning] : [], ...[...broken.values()].map(({ file, reason: reason2 }) => `${file} skipped: ${reason2}`)]
2468
2475
  });
2469
2476
  }
@@ -6933,10 +6940,12 @@ var $o = kr;
6933
6940
  var FS2 = DRAWING.node;
6934
6941
  var LH2 = 17;
6935
6942
  var TEXT_MAX = 150;
6943
+ var EDGE_MAX = 240;
6936
6944
  var EDGE_FS = DRAWING.edge;
6937
6945
  var CLUSTER_FS = DRAWING.cluster;
6938
6946
  var CLUSTER_LABEL_H = 15;
6939
6947
  var DIRS = /* @__PURE__ */ new Set(["TB", "LR", "BT", "RL"]);
6948
+ var FORCED_BREAK = /\\n/;
6940
6949
  var BRACKETS = [
6941
6950
  { open: "[(", close: ")]", shape: "db" },
6942
6951
  { open: "[", close: "]", shape: "rect" },
@@ -6962,6 +6971,7 @@ var flow_default = {
6962
6971
  summary: "Flowchart / architecture diagram (automatic layout)",
6963
6972
  syntax: `\`\`\`flow [TB|LR|BT|RL]
6964
6973
  A -> B: label \u2190 solid line; text after the colon is the edge label
6974
+ A -> B: first\\nsecond line \u2190 a literal \\n in a node or edge label forces a line break
6965
6975
  A --> C \u2190 dashed line
6966
6976
  A -> B -> C \u2190 chain
6967
6977
  A -> B & C \u2190 fan-out
@@ -7135,8 +7145,20 @@ function parseNode(t, start, line) {
7135
7145
  if (!label) throw new ComponentError(`flow has an empty node: "${t}"`, line);
7136
7146
  return { node: { id: label, label, shape: bracket?.shape ?? "rect", explicit: Boolean(bracket), hi }, end };
7137
7147
  }
7148
+ function labelLines(label, maxWidth, size) {
7149
+ return String(label).split(FORCED_BREAK).flatMap((part) => wrap(part, maxWidth, size));
7150
+ }
7151
+ function edgeText(label) {
7152
+ const parts = String(label).split(FORCED_BREAK);
7153
+ const lines = parts.length > 1 ? parts.flatMap((part) => wrap(part, EDGE_MAX, EDGE_FS)) : [String(label)];
7154
+ return {
7155
+ lines,
7156
+ width: Math.max(...lines.map((line) => measure(line, EDGE_FS))) + 10,
7157
+ height: lines.length === 1 ? 18 : lines.length * LH2
7158
+ };
7159
+ }
7138
7160
  function nodeSize(node) {
7139
- const lines = wrap(node.label, TEXT_MAX, FS2);
7161
+ const lines = labelLines(node.label, TEXT_MAX, FS2);
7140
7162
  const tw = Math.max(...lines.map((l3) => measure(l3, FS2)));
7141
7163
  const th = lines.length * LH2;
7142
7164
  const w = Math.max(tw + 28, 64);
@@ -7182,7 +7204,8 @@ function runLayout({ nodes, edges, groups }, rankdir, rtl, widths, reserve) {
7182
7204
  });
7183
7205
  });
7184
7206
  edges.forEach((e, i) => {
7185
- const label = e.label ? { label: e.label, width: measure(e.label, EDGE_FS) + 12, height: 18, labelpos: "c" } : {};
7207
+ const size = e.label ? edgeText(e.label) : null;
7208
+ const label = size ? { label: e.label, width: size.width + 2, height: size.height, labelpos: "c" } : {};
7186
7209
  g.setEdge(key.get(e.from), key.get(e.to), label, `e${i}`);
7187
7210
  });
7188
7211
  $o.layout(g);
@@ -7247,8 +7270,8 @@ function placeLabels({ g, key, sizes }, { nodes, edges, groups }, widths, rtl, r
7247
7270
  const pts = data.points;
7248
7271
  for (let k2 = 1; k2 < pts.length; k2++) segments.push([pts[k2 - 1], pts[k2]]);
7249
7272
  if (e.label) {
7250
- const w = measure(e.label, EDGE_FS) + 10;
7251
- boxes.push([data.x - w / 2, data.y - 9, data.x + w / 2, data.y + 9]);
7273
+ const { width: w, height: h2 } = edgeText(e.label);
7274
+ boxes.push([data.x - w / 2, data.y - h2 / 2, data.x + w / 2, data.y + h2 / 2]);
7252
7275
  }
7253
7276
  });
7254
7277
  return groups.map((grp, i) => {
@@ -7332,8 +7355,8 @@ function layout2(model, rankdir, id, ui, pageDir = "ltr") {
7332
7355
  const path = `<path class="am-edge${e.dashed ? " am-edge--dashed" : ""}" d="${smoothPath(pts)}" marker-end="url(#${head})"/>`;
7333
7356
  const open = `<g data-step="${stepOf.get(e.line)}"${deltaAttr(e.state)}>`;
7334
7357
  if (!e.label) return `${open}${path}</g>`;
7335
- const w = measure(e.label, EDGE_FS) + 10;
7336
- return `${open}${path}<g class="am-edge-label"><rect x="${f(data.x - w / 2)}" y="${f(data.y - 9)}" width="${f(w)}" height="18" rx="3"/>${textLines([e.label], data.x, data.y, LH2, "", pageDir)}</g></g>`;
7358
+ const { lines, width: w, height: h2 } = edgeText(e.label);
7359
+ return `${open}${path}<g class="am-edge-label"><rect x="${f(data.x - w / 2)}" y="${f(data.y - h2 / 2)}" width="${f(w)}" height="${f(h2)}" rx="3"/>${textLines(lines, data.x, data.y, LH2, "", pageDir)}</g></g>`;
7337
7360
  });
7338
7361
  const nodeSvg = [...nodes.values()].map((n) => {
7339
7362
  const { x: x2, y: y2 } = g.node(key.get(n.id));
@@ -8770,11 +8793,11 @@ var videoSel = (t) => `html[data-video][data-theme="${t.name}"]`;
8770
8793
  var scoped = (css, sel) => css.replace(/&/g, sel);
8771
8794
  var languageFontCss = () => fontLanguages().map((l3) => block(langSelector(l3, "html", "[data-theme][data-mode]"), { "--font-sans": l3.fonts.sans }));
8772
8795
  var ownLanguageFont = (t) => fontLanguages().map((l3) => block(langSelector(l3, "html", `[data-theme="${t.name}"][data-mode]`), { "--font-sans": t.tokens.common["--font-sans"] }));
8773
- function pageCss(list2 = themes("page"), { diff = false, delta = false, rtl = false, math: math2 = false, chart = false, update: update2 = false, closeAfter = false, theme, scale = 1 } = {}) {
8796
+ function pageCss(list2 = themes("page"), { diff = false, delta = false, rtl = false, math: math2 = false, chart = false, update: update2 = false, closeAfter = false, fonts = true, scale = 1 } = {}) {
8774
8797
  const decorations = list2.filter((t) => t.css).map((t) => scoped(t.css, pageSel(t)));
8775
- const fontFace = FONT_CSS[list2.find((t) => t.name === theme)?.font];
8798
+ const fontFaces = fonts ? [...new Set(list2.map((t) => t.font).filter((f2) => f2 && FONT_CSS[f2]))].map((f2) => FONT_CSS[f2]) : [];
8776
8799
  const ownFonts = list2.filter((t) => t.ownFont).flatMap(ownLanguageFont);
8777
- return [list2.map((t) => tokenCss(pageSel(t), t.tokens)).join("\n\n"), ...languageFontCss(), ...ownFonts, typeScaleCss(), ...scale === 1 ? [] : [`html { --am-scale: ${scale}; }`], BASE_CSS, ...math2 ? [MATH_CSS] : [], ...chart ? [CHART_CSS] : [], ...diff ? [DIFF_CSS] : [], ...delta ? [DELTA_CSS] : [], ...update2 ? [UPDATE_CSS] : [], ...closeAfter ? [CLOSE_AFTER_CSS] : [], ...rtl ? [RTL_CSS] : [], ...fontFace ? [fontFace] : [], ...decorations].join("\n\n");
8800
+ return [list2.map((t) => tokenCss(pageSel(t), t.tokens)).join("\n\n"), ...languageFontCss(), ...ownFonts, typeScaleCss(), ...scale === 1 ? [] : [`html { --am-scale: ${scale}; }`], BASE_CSS, ...math2 ? [MATH_CSS] : [], ...chart ? [CHART_CSS] : [], ...diff ? [DIFF_CSS] : [], ...delta ? [DELTA_CSS] : [], ...update2 ? [UPDATE_CSS] : [], ...closeAfter ? [CLOSE_AFTER_CSS] : [], ...rtl ? [RTL_CSS] : [], ...fontFaces, ...decorations].join("\n\n");
8778
8801
  }
8779
8802
  function videoCss(list2 = themes("video"), { diff = false, delta = false, rtl = false, chart = false } = {}) {
8780
8803
  const parts = list2.filter((t) => t.video).flatMap((t) => [
@@ -8782,7 +8805,7 @@ function videoCss(list2 = themes("video"), { diff = false, delta = false, rtl =
8782
8805
  t.video.css ? scoped(t.video.css, videoSel(t)) : "",
8783
8806
  rtl && t.video.rtlCss ? scoped(t.video.rtlCss, videoSel(t)) : ""
8784
8807
  ]).filter(Boolean);
8785
- return [pageCss(list2.filter((t) => t.scope.includes("page")), { diff, delta, rtl, chart }), VIDEO_CSS, ...parts].join("\n\n");
8808
+ return [pageCss(list2.filter((t) => t.scope.includes("page")), { diff, delta, rtl, chart, fonts: false }), VIDEO_CSS, ...parts].join("\n\n");
8786
8809
  }
8787
8810
 
8788
8811
  // src/lint/wordlist.en.js
@@ -9820,7 +9843,7 @@ ${cspMeta([script], { live: true })}
9820
9843
  <meta name="generator" content="Answer me with HTML ${VERSION}">
9821
9844
  <title>${esc(meta.title || "Answer me with HTML")}</title>
9822
9845
  <style>
9823
- ${pageCss(embedded, { diff: body.includes('class="am-codeblock am-codeblock--diff"'), delta: hasDelta(body), rtl: language.dir === "rtl", math: hasMath(body), chart: hasChart(body), update: Boolean(update2), closeAfter, theme: meta.theme, scale })}
9846
+ ${pageCss(embedded, { diff: body.includes('class="am-codeblock am-codeblock--diff"'), delta: hasDelta(body), rtl: language.dir === "rtl", math: hasMath(body), chart: hasChart(body), update: Boolean(update2), closeAfter, scale })}
9824
9847
  </style>
9825
9848
  </head>
9826
9849
  <body>
@@ -10268,7 +10291,7 @@ async function add(name, opts, { print, fail, env }, net) {
10268
10291
  return 1;
10269
10292
  }
10270
10293
  } else if (status !== "same") {
10271
- print(` Use it: theme: ${name} in a draft, --theme ${name}, or am config set theme ${name}`);
10294
+ print(` It now appears in every new page's theme picker. Make it the default: am theme add ${name} --use, or am config set theme ${name}`);
10272
10295
  }
10273
10296
  return 0;
10274
10297
  }
@@ -10383,7 +10406,7 @@ function removeTheme(name, { print, fail, env }) {
10383
10406
  resetConfig("theme", env);
10384
10407
  print(`! ${name} was the default theme; the default is auto again`);
10385
10408
  }
10386
- print(" Pages already made keep their look: a page carries its own theme.");
10409
+ print(" Pages already made keep their look: a page embeds the themes it was made with.");
10387
10410
  return 0;
10388
10411
  }
10389
10412
 
@@ -10750,14 +10773,14 @@ function bestVoice(candidates, base) {
10750
10773
  }
10751
10774
  var stripName = (name) => name.replace(/\s*[((].*$/, "");
10752
10775
  function run(cmd, args) {
10753
- return new Promise((resolve5, reject) => {
10776
+ return new Promise((resolve6, reject) => {
10754
10777
  const p = spawn(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });
10755
10778
  let err = "";
10756
10779
  p.stderr.on("data", (d) => {
10757
10780
  err += d;
10758
10781
  });
10759
10782
  p.on("error", reject);
10760
- p.on("close", (code) => code === 0 ? resolve5() : reject(new TtsError(`${cmd} failed (${code}): ${err.slice(0, 200)}`)));
10783
+ p.on("close", (code) => code === 0 ? resolve6() : reject(new TtsError(`${cmd} failed (${code}): ${err.slice(0, 200)}`)));
10761
10784
  });
10762
10785
  }
10763
10786
  function textFile(wavFile, text2) {
@@ -11053,21 +11076,21 @@ ${sourceTag(source)}
11053
11076
  }
11054
11077
 
11055
11078
  // src/video/export.js
11079
+ import { spawn as spawn3 } from "node:child_process";
11080
+ import { writeFileSync as writeFileSync5 } from "node:fs";
11081
+ import { join as join9 } from "node:path";
11082
+ import { pathToFileURL } from "node:url";
11083
+
11084
+ // src/chrome.js
11056
11085
  import { spawn as spawn2 } from "node:child_process";
11057
- import { existsSync as existsSync5, mkdtempSync as mkdtempSync2, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
11086
+ import { existsSync as existsSync5, mkdtempSync as mkdtempSync2, rmSync as rmSync4 } from "node:fs";
11058
11087
  import { tmpdir as tmpdir3 } from "node:os";
11059
11088
  import { join as join8 } from "node:path";
11060
- import { pathToFileURL } from "node:url";
11061
11089
  var ExportError = class extends Error {
11062
11090
  };
11063
11091
  var CDP_TIMEOUT_MS = 3e4;
11064
11092
  var CHROME_START_TIMEOUT_MS = 2e4;
11065
- var WIDTH = 1920;
11066
- var HEIGHT = 1080;
11067
- var QUALITY = 92;
11068
- var WEBM_BITRATE = 35e5;
11069
- var WEBM_SLICE = 1048572;
11070
- var WEBM_POLL_MS = 250;
11093
+ var LOAD_TIMEOUT_MS = 3e4;
11071
11094
  var CHROME_PATHS = {
11072
11095
  darwin: [
11073
11096
  "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
@@ -11081,16 +11104,29 @@ var CHROME_PATHS = {
11081
11104
  ],
11082
11105
  linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"]
11083
11106
  };
11107
+ function chromePaths(platform = process.platform, env = process.env) {
11108
+ const list2 = [...CHROME_PATHS[platform] ?? CHROME_PATHS.linux];
11109
+ if (platform === "win32" && env.LOCALAPPDATA) list2.push(`${env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`);
11110
+ return list2;
11111
+ }
11084
11112
  function findChrome(env = process.env, platform = process.platform) {
11085
11113
  const custom = env.AM_CHROME || env.CHROME_PATH;
11086
11114
  if (custom) return custom;
11087
- const list2 = CHROME_PATHS[platform] ?? CHROME_PATHS.linux;
11088
- return list2.find((p) => p.includes("/") || p.includes("\\") ? existsSync5(p) : hasCommand(p)) ?? null;
11089
- }
11090
- async function openPlayer(htmlFile, { env, startTimeoutMs }) {
11091
- const chromePath = findChrome(env);
11115
+ return chromePaths(platform, env).find((p) => p.includes("/") || p.includes("\\") ? existsSync5(p) : hasCommand(p)) ?? null;
11116
+ }
11117
+ async function openPage(url, {
11118
+ env = process.env,
11119
+ chromePath = findChrome(env),
11120
+ startTimeoutMs = CHROME_START_TIMEOUT_MS,
11121
+ width,
11122
+ height = 900,
11123
+ deviceScaleFactor = 1,
11124
+ media,
11125
+ flags = [],
11126
+ scriptError = "Page script error"
11127
+ } = {}) {
11092
11128
  if (!chromePath) throw new ExportError("No Chrome / Chromium / Edge found. Set the browser path with the AM_CHROME environment variable");
11093
- const tmp = mkdtempSync2(join8(tmpdir3(), "am-export-"));
11129
+ const tmp = mkdtempSync2(join8(tmpdir3(), "am-chrome-"));
11094
11130
  const chrome = spawn2(chromePath, [
11095
11131
  "--headless=new",
11096
11132
  "--remote-debugging-port=0",
@@ -11099,8 +11135,8 @@ async function openPlayer(htmlFile, { env, startTimeoutMs }) {
11099
11135
  "--no-default-browser-check",
11100
11136
  "--hide-scrollbars",
11101
11137
  "--mute-audio",
11102
- "--force-device-scale-factor=1",
11103
- `--window-size=${WIDTH},${HEIGHT}`,
11138
+ ...width ? [`--force-device-scale-factor=${deviceScaleFactor}`, `--window-size=${width},${height}`] : [],
11139
+ ...flags,
11104
11140
  "about:blank"
11105
11141
  ], { stdio: ["ignore", "ignore", "pipe"] });
11106
11142
  let cdp = null;
@@ -11128,16 +11164,116 @@ async function openPlayer(htmlFile, { env, startTimeoutMs }) {
11128
11164
  const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
11129
11165
  const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
11130
11166
  const page = (method, params) => cdp.send(method, params, sessionId);
11131
- await page("Emulation.setDeviceMetricsOverride", { width: WIDTH, height: HEIGHT, deviceScaleFactor: 1, mobile: false });
11167
+ if (width) await page("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor, mobile: false });
11168
+ if (media) await page("Emulation.setEmulatedMedia", { media });
11132
11169
  await page("Page.enable");
11133
11170
  const loaded = cdp.once("Page.loadEventFired");
11134
- await page("Page.navigate", { url: pathToFileURL(htmlFile).href });
11135
- await loaded;
11171
+ await page("Page.navigate", { url });
11172
+ await waitForLoad(loaded);
11136
11173
  const evaluate = async (expression) => {
11137
11174
  const r = await page("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
11138
- if (r.exceptionDetails) throw new ExportError(`Player page script error: ${r.exceptionDetails.exception?.description ?? r.exceptionDetails.text}`);
11175
+ if (r.exceptionDetails) throw new ExportError(`${scriptError}: ${r.exceptionDetails.exception?.description ?? r.exceptionDetails.text}`);
11139
11176
  return r.result.value;
11140
11177
  };
11178
+ return { page, evaluate, close, tmp, chrome };
11179
+ } catch (e) {
11180
+ await close();
11181
+ throw e;
11182
+ }
11183
+ }
11184
+ function waitForLoad(loaded, timeoutMs = LOAD_TIMEOUT_MS) {
11185
+ let timer;
11186
+ return Promise.race([
11187
+ loaded,
11188
+ new Promise((_2, reject) => {
11189
+ timer = setTimeout(() => reject(new ExportError(`The page did not finish loading within ${timeoutMs / 1e3} seconds`)), timeoutMs);
11190
+ })
11191
+ ]).finally(() => clearTimeout(timer));
11192
+ }
11193
+ function devtoolsUrl(chrome, timeoutMs = CHROME_START_TIMEOUT_MS) {
11194
+ return new Promise((resolve6, reject) => {
11195
+ let buf = "";
11196
+ const fail = (msg) => {
11197
+ clearTimeout(timer);
11198
+ const tail = buf.trim().split("\n").slice(-5).join("\n");
11199
+ reject(new ExportError(tail ? `${msg}. Chrome stderr:
11200
+ ${tail}` : msg));
11201
+ };
11202
+ const timer = setTimeout(() => fail(`Chrome did not start in time (${timeoutMs / 1e3} s)`), timeoutMs);
11203
+ chrome.on("error", (e) => fail(`Cannot start Chrome: ${e.message}`));
11204
+ chrome.on("close", (code, signal) => fail(`Chrome exited (${code ?? signal}) before it started`));
11205
+ chrome.stderr.on("data", (d) => {
11206
+ buf += d;
11207
+ const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
11208
+ if (m) {
11209
+ clearTimeout(timer);
11210
+ resolve6(m[1]);
11211
+ }
11212
+ });
11213
+ });
11214
+ }
11215
+ function connect(url) {
11216
+ return new Promise((resolve6, reject) => {
11217
+ const ws = new WebSocket(url);
11218
+ const pending = /* @__PURE__ */ new Map();
11219
+ const waiters = /* @__PURE__ */ new Map();
11220
+ let id = 0;
11221
+ ws.addEventListener("error", () => reject(new ExportError("Cannot connect to Chrome DevTools")));
11222
+ ws.addEventListener("message", (ev) => {
11223
+ const msg = JSON.parse(ev.data);
11224
+ if (msg.id && pending.has(msg.id)) {
11225
+ const { ok, fail } = pending.get(msg.id);
11226
+ pending.delete(msg.id);
11227
+ if (msg.error) fail(new ExportError(`CDP ${msg.error.message}`));
11228
+ else ok(msg.result);
11229
+ } else if (msg.method && waiters.has(msg.method)) {
11230
+ waiters.get(msg.method)(msg.params);
11231
+ waiters.delete(msg.method);
11232
+ }
11233
+ });
11234
+ ws.addEventListener("open", () => resolve6({
11235
+ send(method, params = {}, sessionId) {
11236
+ return new Promise((ok, fail) => {
11237
+ const msgId = ++id;
11238
+ const timer = setTimeout(() => {
11239
+ pending.delete(msgId);
11240
+ fail(new ExportError(`Chrome is not responding (${method} took more than ${CDP_TIMEOUT_MS / 1e3} seconds)`));
11241
+ }, CDP_TIMEOUT_MS);
11242
+ pending.set(msgId, { ok: (v) => {
11243
+ clearTimeout(timer);
11244
+ ok(v);
11245
+ }, fail: (e) => {
11246
+ clearTimeout(timer);
11247
+ fail(e);
11248
+ } });
11249
+ ws.send(JSON.stringify({ id: msgId, method, params, ...sessionId ? { sessionId } : {} }));
11250
+ });
11251
+ },
11252
+ once: (method) => new Promise((r) => waiters.set(method, r)),
11253
+ close: () => ws.close()
11254
+ }));
11255
+ });
11256
+ }
11257
+
11258
+ // src/video/export.js
11259
+ var CHROME_START_TIMEOUT_MS2 = 2e4;
11260
+ var WIDTH = 1920;
11261
+ var HEIGHT = 1080;
11262
+ var QUALITY = 92;
11263
+ var WEBM_BITRATE = 35e5;
11264
+ var WEBM_SLICE = 1048572;
11265
+ var WEBM_POLL_MS = 250;
11266
+ async function openPlayer(htmlFile, { env, startTimeoutMs }) {
11267
+ const player = await openPage(pathToFileURL(htmlFile).href, {
11268
+ env,
11269
+ startTimeoutMs,
11270
+ width: WIDTH,
11271
+ height: HEIGHT,
11272
+ deviceScaleFactor: 1,
11273
+ scriptError: "Player page script error"
11274
+ });
11275
+ const { page, evaluate, close, tmp } = player;
11276
+ try {
11141
11277
  const info = await evaluate("document.fonts.ready.then(() => { window.__amv.exportMode(); return { duration: window.__amv.duration, fps: window.__amv.fps }; })");
11142
11278
  const screenshot = async () => (await page("Page.captureScreenshot", { format: "jpeg", quality: QUALITY, clip: { x: 0, y: 0, width: WIDTH, height: HEIGHT, scale: 1 } })).data;
11143
11279
  return { info, evaluate, screenshot, close, tmp };
@@ -11147,15 +11283,15 @@ async function openPlayer(htmlFile, { env, startTimeoutMs }) {
11147
11283
  }
11148
11284
  }
11149
11285
  async function exportMp4(htmlFile, mp4File, { wav: wav2, env = process.env, onProgress = () => {
11150
- }, startTimeoutMs = CHROME_START_TIMEOUT_MS } = {}) {
11286
+ }, startTimeoutMs = CHROME_START_TIMEOUT_MS2 } = {}) {
11151
11287
  if (typeof WebSocket === "undefined") throw new ExportError("MP4 export needs Node.js 22 or later (built-in WebSocket)");
11152
11288
  if (!hasCommand("ffmpeg")) throw new ExportError("MP4 export needs ffmpeg: on macOS run brew install ffmpeg; on Linux install it with the package manager");
11153
11289
  const player = await openPlayer(htmlFile, { env, startTimeoutMs });
11154
11290
  try {
11155
11291
  const { info, evaluate, screenshot, tmp } = player;
11156
- const wavFile = wav2 ? join8(tmp, "voice.wav") : null;
11292
+ const wavFile = wav2 ? join9(tmp, "voice.wav") : null;
11157
11293
  if (wav2) writeFileSync5(wavFile, wav2);
11158
- const ffmpeg = spawn2("ffmpeg", [
11294
+ const ffmpeg = spawn3("ffmpeg", [
11159
11295
  "-y",
11160
11296
  "-loglevel",
11161
11297
  "error",
@@ -11188,14 +11324,14 @@ async function exportMp4(htmlFile, mp4File, { wav: wav2, env = process.env, onPr
11188
11324
  });
11189
11325
  ffmpeg.stdin.on("error", () => {
11190
11326
  });
11191
- const done = new Promise((resolve5, reject) => {
11327
+ const done = new Promise((resolve6, reject) => {
11192
11328
  ffmpeg.on("error", (e) => {
11193
11329
  exited = true;
11194
11330
  reject(new ExportError(`Cannot run ffmpeg: ${e.message}`));
11195
11331
  });
11196
11332
  ffmpeg.on("close", (code) => {
11197
11333
  exited = true;
11198
- if (code === 0) resolve5();
11334
+ if (code === 0) resolve6();
11199
11335
  else reject(new ExportError(`ffmpeg failed (${code}): ${ffErr.slice(0, 300)}`));
11200
11336
  });
11201
11337
  });
@@ -11220,7 +11356,7 @@ async function exportMp4(htmlFile, mp4File, { wav: wav2, env = process.env, onPr
11220
11356
  }
11221
11357
  }
11222
11358
  async function exportWebm(htmlFile, webmFile, { env = process.env, onProgress = () => {
11223
- }, startTimeoutMs = CHROME_START_TIMEOUT_MS, bitrate = WEBM_BITRATE } = {}) {
11359
+ }, startTimeoutMs = CHROME_START_TIMEOUT_MS2, bitrate = WEBM_BITRATE } = {}) {
11224
11360
  if (typeof WebSocket === "undefined") throw new ExportError("The built-in encoder needs Node.js 22 or later (built-in WebSocket)");
11225
11361
  const player = await openPlayer(htmlFile, { env, startTimeoutMs });
11226
11362
  try {
@@ -11250,77 +11386,184 @@ async function exportWebm(htmlFile, webmFile, { env = process.env, onProgress =
11250
11386
  await player.close();
11251
11387
  }
11252
11388
  }
11253
- function devtoolsUrl(chrome, timeoutMs = CHROME_START_TIMEOUT_MS) {
11254
- return new Promise((resolve5, reject) => {
11255
- let buf = "";
11256
- const fail = (msg) => {
11257
- clearTimeout(timer);
11258
- const tail = buf.trim().split("\n").slice(-5).join("\n");
11259
- reject(new ExportError(tail ? `${msg}. Chrome stderr:
11260
- ${tail}` : msg));
11261
- };
11262
- const timer = setTimeout(() => fail(`Chrome did not start in time (${timeoutMs / 1e3} s)`), timeoutMs);
11263
- chrome.on("error", (e) => fail(`Cannot start Chrome: ${e.message}`));
11264
- chrome.on("close", (code, signal) => fail(`Chrome exited (${code ?? signal}) before it started`));
11265
- chrome.stderr.on("data", (d) => {
11266
- buf += d;
11267
- const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
11268
- if (m) {
11269
- clearTimeout(timer);
11270
- resolve5(m[1]);
11271
- }
11272
- });
11389
+
11390
+ // src/export.js
11391
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, statSync as statSync4, writeFileSync as writeFileSync6 } from "node:fs";
11392
+ import { basename as basename3, dirname as dirname2, join as join10, resolve as resolve3 } from "node:path";
11393
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
11394
+ var VIEWPORT = 1200;
11395
+ var DEVICE_SCALE = 2;
11396
+ var MAX_SLICE = 1800;
11397
+ var SETTLE_MS = 400;
11398
+ var CHROME_CSS = `.am-toolbar, .am-reply, .am-reply-bar, .am-comment, .am-comment-btn, .am-remark-pop,
11399
+ .am-update, .am-btn--update, .am-lightbox, .am-code-copy, .am-diagram-expand, .am-toc, .am-delta-switch {
11400
+ display: none !important;
11401
+ }`;
11402
+ function slicePoints(pageHeight, boxes = [], maxHeight = MAX_SLICE) {
11403
+ const limit = Math.floor(maxHeight);
11404
+ if (!(limit > 0)) throw new RangeError("maxHeight must be greater than 0");
11405
+ if (!(pageHeight > 0)) return [];
11406
+ const cuts = [];
11407
+ let start = 0;
11408
+ while (pageHeight - start > limit) {
11409
+ const target = start + limit;
11410
+ const cut = Math.floor(gapCut(start, target, boxes) ?? target);
11411
+ cuts.push(cut > start ? cut : target);
11412
+ start = cuts[cuts.length - 1];
11413
+ }
11414
+ return cuts;
11415
+ }
11416
+ function gapCut(start, target, boxes) {
11417
+ let y2 = target;
11418
+ for (; ; ) {
11419
+ const box = boxes.find((b) => y2 > b.top && y2 < b.bottom);
11420
+ if (!box) return y2 > start ? y2 : null;
11421
+ if (!(box.top > start)) return null;
11422
+ y2 = box.top;
11423
+ }
11424
+ }
11425
+ async function exportPage(file, { pdf, png, env = process.env, onFile = () => {
11426
+ } } = {}) {
11427
+ if (typeof WebSocket === "undefined") throw new ExportError("Export needs Node.js 22 or later (built-in WebSocket)");
11428
+ if (pdf && existsSync6(pdf) && sameFile(pdf, file)) {
11429
+ throw new ExportError(`The PDF ${pdf} is the input page: choose another file name`);
11430
+ }
11431
+ if (pdf && png && resolve3(dirname2(pdf)) === resolve3(png) && isSliceOf(basename3(pdf), sliceName(file))) {
11432
+ throw new ExportError(`The PDF ${pdf} has the name of a PNG slice in ${png}: choose another file name`);
11433
+ }
11434
+ const chrome = findChrome(env);
11435
+ if (!chrome) throw new ExportError("No Chrome / Chromium / Edge found. Set the browser path with the AM_CHROME environment variable");
11436
+ if (isPath(chrome) && !existsSync6(chrome)) {
11437
+ const from = env.AM_CHROME ? "AM_CHROME" : env.CHROME_PATH ? "CHROME_PATH" : "the built-in path";
11438
+ throw new ExportError(`No browser at ${chrome} (from ${from}). Set AM_CHROME to the Chrome / Chromium / Edge binary`);
11439
+ }
11440
+ const page = await openPage(pathToFileURL2(file).href, {
11441
+ env,
11442
+ chromePath: chrome,
11443
+ width: VIEWPORT,
11444
+ height: 900,
11445
+ deviceScaleFactor: DEVICE_SCALE,
11446
+ media: "screen"
11273
11447
  });
11274
- }
11275
- function connect(url) {
11276
- return new Promise((resolve5, reject) => {
11277
- const ws = new WebSocket(url);
11278
- const pending = /* @__PURE__ */ new Map();
11279
- const waiters = /* @__PURE__ */ new Map();
11280
- let id = 0;
11281
- ws.addEventListener("error", () => reject(new ExportError("Cannot connect to Chrome DevTools")));
11282
- ws.addEventListener("message", (ev) => {
11283
- const msg = JSON.parse(ev.data);
11284
- if (msg.id && pending.has(msg.id)) {
11285
- const { ok, fail } = pending.get(msg.id);
11286
- pending.delete(msg.id);
11287
- if (msg.error) fail(new ExportError(`CDP ${msg.error.message}`));
11288
- else ok(msg.result);
11289
- } else if (msg.method && waiters.has(msg.method)) {
11290
- waiters.get(msg.method)(msg.params);
11291
- waiters.delete(msg.method);
11292
- }
11293
- });
11294
- ws.addEventListener("open", () => resolve5({
11295
- send(method, params = {}, sessionId) {
11296
- return new Promise((ok, fail) => {
11297
- const msgId = ++id;
11298
- const timer = setTimeout(() => {
11299
- pending.delete(msgId);
11300
- fail(new ExportError(`Chrome is not responding (${method} took more than ${CDP_TIMEOUT_MS / 1e3} seconds)`));
11301
- }, CDP_TIMEOUT_MS);
11302
- pending.set(msgId, { ok: (v) => {
11303
- clearTimeout(timer);
11304
- ok(v);
11305
- }, fail: (e) => {
11306
- clearTimeout(timer);
11307
- fail(e);
11308
- } });
11309
- ws.send(JSON.stringify({ id: msgId, method, params, ...sessionId ? { sessionId } : {} }));
11310
- });
11311
- },
11312
- once: (method) => new Promise((r) => waiters.set(method, r)),
11313
- close: () => ws.close()
11314
- }));
11448
+ const written = [];
11449
+ try {
11450
+ if (pdf) {
11451
+ const writtenPdf = await writePdf(page, pdf);
11452
+ written.push(writtenPdf);
11453
+ onFile(writtenPdf);
11454
+ }
11455
+ if (png) {
11456
+ const writtenPngs = await writePngSlices(page, file, png);
11457
+ written.push(...writtenPngs);
11458
+ writtenPngs.forEach(onFile);
11459
+ }
11460
+ } finally {
11461
+ await page.close();
11462
+ }
11463
+ return written;
11464
+ }
11465
+ async function writePdf(page, file) {
11466
+ await page.page("Emulation.setEmulatedMedia", { media: "print" });
11467
+ await settle2(page);
11468
+ const { data } = await page.page("Page.printToPDF", {
11469
+ printBackground: true,
11470
+ // Part of the agreed contract: a page's own @page rules win. A page written by am has no @page size, so it prints
11471
+ // on the A4 paper below; an html fence that sets @page is the author's explicit choice.
11472
+ preferCSSPageSize: true,
11473
+ displayHeaderFooter: false,
11474
+ paperWidth: 8.27,
11475
+ // A4, 210 x 297 mm
11476
+ paperHeight: 11.69
11315
11477
  });
11478
+ try {
11479
+ mkdirSync4(dirname2(file), { recursive: true });
11480
+ writeFileSync6(file, Buffer.from(data, "base64"));
11481
+ } catch (e) {
11482
+ throw new ExportError(`Cannot write the PDF ${file}: ${e.message}`);
11483
+ }
11484
+ return file;
11485
+ }
11486
+ async function writePngSlices(page, htmlFile, folder) {
11487
+ await page.page("Emulation.setEmulatedMedia", { media: "screen" });
11488
+ await settle2(page);
11489
+ const layout4 = await page.evaluate(`(async () => {
11490
+ await document.fonts.ready;
11491
+ await new Promise((r) => setTimeout(r, ${SETTLE_MS}));
11492
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
11493
+ const style = document.createElement('style');
11494
+ style.textContent = ${JSON.stringify(CHROME_CSS)};
11495
+ document.head.append(style);
11496
+ const box = (el) => {
11497
+ const r = el.getBoundingClientRect();
11498
+ return { top: r.top + window.scrollY, bottom: r.bottom + window.scrollY };
11499
+ };
11500
+ return {
11501
+ empty: document.body.children.length === 0 && !document.body.textContent.trim(),
11502
+ height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)),
11503
+ boxes: [...document.querySelectorAll('.am-head, .am-panel')]
11504
+ .filter((el) => el.getClientRects().length)
11505
+ .map(box),
11506
+ };
11507
+ })()`);
11508
+ if (layout4.empty) throw new ExportError("The page is empty: there is nothing to export");
11509
+ try {
11510
+ mkdirSync4(folder, { recursive: true });
11511
+ if (!statSync4(folder).isDirectory()) throw new Error("not a folder");
11512
+ } catch (e) {
11513
+ throw new ExportError(`Cannot use the PNG folder ${folder}: ${e.message}`);
11514
+ }
11515
+ const cuts = slicePoints(layout4.height, layout4.boxes, MAX_SLICE);
11516
+ const name = sliceName(htmlFile);
11517
+ const bounds = [0, ...cuts, layout4.height];
11518
+ const written = [];
11519
+ for (let i = 1; i < bounds.length; i++) {
11520
+ const top2 = bounds[i - 1];
11521
+ const height = bounds[i] - top2;
11522
+ if (height <= 0) continue;
11523
+ const { data } = await page.page("Page.captureScreenshot", {
11524
+ format: "png",
11525
+ // Capture each slice of the full page, not just the part inside a 900px viewport.
11526
+ captureBeyondViewport: true,
11527
+ clip: { x: 0, y: top2, width: VIEWPORT, height, scale: 1 }
11528
+ });
11529
+ const file = join10(folder, `${name}-${i}.png`);
11530
+ if (existsSync6(file) && sameFile(file, htmlFile)) throw new ExportError(`The PNG ${file} is the input page: choose another folder`);
11531
+ try {
11532
+ writeFileSync6(file, Buffer.from(data, "base64"));
11533
+ } catch (e) {
11534
+ throw new ExportError(`Cannot write the PNG ${file}: ${e.message}`);
11535
+ }
11536
+ written.push(file);
11537
+ }
11538
+ return written;
11316
11539
  }
11540
+ var settle2 = (page) => page.evaluate(`(async () => {
11541
+ await document.fonts.ready;
11542
+ await new Promise((r) => setTimeout(r, ${SETTLE_MS}));
11543
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
11544
+ return true;
11545
+ })()`);
11546
+ function isHtmlPage(file) {
11547
+ return /\.html?$/i.test(file) && statSync4(file, { throwIfNoEntry: false })?.isFile() === true;
11548
+ }
11549
+ var sliceName = (htmlFile) => basename3(htmlFile).replace(/\.html?$/i, "") || "page";
11550
+ var isSliceOf = (fileName, name) => {
11551
+ if (!fileName.startsWith(`${name}-`) || !fileName.endsWith(".png")) return false;
11552
+ return /^[1-9]\d*$/.test(fileName.slice(name.length + 1, -".png".length));
11553
+ };
11554
+ var sameFile = (a, b) => {
11555
+ const x2 = statSync4(a);
11556
+ const y2 = statSync4(b);
11557
+ return x2.dev === y2.dev && x2.ino === y2.ino;
11558
+ };
11559
+ var isPath = (value) => value.includes("/") || value.includes("\\");
11317
11560
 
11318
11561
  // src/housekeeping.js
11319
- import { readdirSync as readdirSync2, lstatSync as lstatSync2, rmSync as rmSync5 } from "node:fs";
11320
- import { join as join9 } from "node:path";
11562
+ import { readdirSync as readdirSync2, lstatSync as lstatSync2, rmSync as rmSync5, readFileSync as readFileSync8 } from "node:fs";
11563
+ import { join as join11 } from "node:path";
11321
11564
 
11322
11565
  // src/update.js
11323
- import { spawn as spawn3 } from "node:child_process";
11566
+ import { spawn as spawn4 } from "node:child_process";
11324
11567
  var UPDATE = Object.freeze({
11325
11568
  checkEveryDays: 1,
11326
11569
  hintEveryDays: 3,
@@ -11388,7 +11631,7 @@ function shouldCheckUpdate(state, env, config, now = Date.now()) {
11388
11631
  function spawnUpdateCheck(home, scriptPath) {
11389
11632
  writeState(home, { lastUpdateCheck: Date.now() });
11390
11633
  try {
11391
- spawn3(process.execPath, [scriptPath, "__update-check"], { detached: true, stdio: "ignore", env: { ...process.env, AM_HOME: home } }).on("error", () => {
11634
+ spawn4(process.execPath, [scriptPath, "__update-check"], { detached: true, stdio: "ignore", env: { ...process.env, AM_HOME: home } }).on("error", () => {
11392
11635
  }).unref();
11393
11636
  } catch {
11394
11637
  }
@@ -11425,6 +11668,7 @@ var CLEAN = Object.freeze({
11425
11668
  // the same notice at most once every 7 days
11426
11669
  });
11427
11670
  var DIRS3 = ["pages", "videos", "cache"];
11671
+ var HOUR = DAY / 24;
11428
11672
  function walk(dir) {
11429
11673
  let entries;
11430
11674
  try {
@@ -11434,7 +11678,7 @@ function walk(dir) {
11434
11678
  return [];
11435
11679
  }
11436
11680
  return entries.flatMap((e) => {
11437
- const p = join9(dir, e.name);
11681
+ const p = join11(dir, e.name);
11438
11682
  if (e.isDirectory()) return walk(p);
11439
11683
  try {
11440
11684
  const s = lstatSync2(p);
@@ -11447,7 +11691,7 @@ function walk(dir) {
11447
11691
  var sum = (files) => files.reduce((n, f2) => n + f2.bytes, 0);
11448
11692
  function usage2(home) {
11449
11693
  const parts = Object.fromEntries(DIRS3.map((d) => {
11450
- const files = walk(join9(home, d));
11694
+ const files = walk(join11(home, d));
11451
11695
  return [d, { count: files.length, bytes: sum(files) }];
11452
11696
  }));
11453
11697
  return { ...parts, total: DIRS3.reduce((n, d) => n + parts[d].bytes, 0) };
@@ -11455,14 +11699,25 @@ function usage2(home) {
11455
11699
  function clean2(home, { days = CLEAN.days, all = false, dryRun = false, now = Date.now(), temp } = {}) {
11456
11700
  const cutoff = now - days * DAY;
11457
11701
  const victims = [
11458
- ...[home, temp].filter(Boolean).flatMap((dir) => ["pages", "videos", "drafts"].flatMap((d) => walk(join9(dir, d)).filter((f2) => all || f2.mtime < cutoff))),
11459
- ...walk(join9(home, "cache"))
11702
+ ...[home, temp].filter(Boolean).flatMap((dir) => ["pages", "videos", "drafts"].flatMap((d) => walk(join11(dir, d)).filter((f2) => all || f2.mtime < cutoff))),
11703
+ ...walk(join11(home, "cache"))
11460
11704
  ];
11705
+ const gone = new Set(walk(join11(home, "pages")).filter((f2) => all || f2.mtime < cutoff).map((f2) => f2.path));
11706
+ const states = walk(join11(home, "serve-state")).filter((f2) => {
11707
+ if (!f2.path.endsWith(".json")) return f2.mtime < now - HOUR;
11708
+ if (all || f2.mtime < cutoff) return true;
11709
+ try {
11710
+ const file = JSON.parse(readFileSync8(f2.path, "utf8"))?.file;
11711
+ return typeof file !== "string" || gone.has(join11(home, "pages", file)) || !lstatSync2(join11(home, "pages", file)).isFile();
11712
+ } catch {
11713
+ return true;
11714
+ }
11715
+ });
11461
11716
  if (!dryRun) {
11462
- for (const f2 of victims) rmSync5(f2.path, { force: true });
11717
+ for (const f2 of [...victims, ...states]) rmSync5(f2.path, { force: true });
11463
11718
  writeState(home, { lastClean: now, lastCleanHint: null });
11464
11719
  }
11465
- return { files: victims.length, bytes: sum(victims) };
11720
+ return { files: victims.length + states.length, bytes: sum(victims) + sum(states) };
11466
11721
  }
11467
11722
  var mb = (bytes) => bytes < 2 ** 20 ? `${Math.ceil(bytes / 1024)} KB` : `${(bytes / 2 ** 20).toFixed(bytes < 10 * 2 ** 20 ? 1 : 0)} MB`;
11468
11723
  function cleanHint(state, use, now = Date.now()) {
@@ -11561,10 +11816,10 @@ import { createServer } from "node:http";
11561
11816
  import { connect as connect2, isIP } from "node:net";
11562
11817
  import { spawnSync as spawnSync3 } from "node:child_process";
11563
11818
  import { networkInterfaces, uptime } from "node:os";
11564
- import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
11565
- import { readFileSync as readFileSync8, writeFileSync as writeFileSync6, renameSync as renameSync5, rmSync as rmSync6, watch, lstatSync as lstatSync3, existsSync as existsSync6, openSync, fstatSync, closeSync, linkSync, constants as fsConstants } from "node:fs";
11819
+ import { createHmac, createHash as createHash3, randomBytes, timingSafeEqual } from "node:crypto";
11820
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync7, renameSync as renameSync5, rmSync as rmSync6, mkdirSync as mkdirSync5, watch, lstatSync as lstatSync3, existsSync as existsSync7, openSync, fstatSync, closeSync, linkSync, constants as fsConstants } from "node:fs";
11566
11821
  import { lstat, realpath, readFile, stat } from "node:fs/promises";
11567
- import { join as join10, resolve as resolve3, dirname as dirname2, basename as basename3, sep as sep3 } from "node:path";
11822
+ import { join as join12, resolve as resolve4, dirname as dirname3, basename as basename4, sep as sep3 } from "node:path";
11568
11823
  var DEFAULT_PORT = 8765;
11569
11824
  var HOST = "127.0.0.1";
11570
11825
  var LAN_BIND = "0.0.0.0";
@@ -11572,7 +11827,8 @@ var TOKEN_LENGTH = 22;
11572
11827
  var PREFIX2 = Object.freeze({ p: "pages", v: "videos" });
11573
11828
  var PREFIX_OF = Object.freeze({ pages: "p", videos: "v" });
11574
11829
  var EVENTS = "e";
11575
- var SETTLE_MS = 150;
11830
+ var SAVE = "r";
11831
+ var SETTLE_MS2 = 150;
11576
11832
  var LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])(:\d{1,5})?$/i;
11577
11833
  function lanRank(address) {
11578
11834
  const [a, b] = address.split(".").map(Number);
@@ -11604,7 +11860,7 @@ function publicUrlOrigin(input) {
11604
11860
  var TAILSCALE_APP = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
11605
11861
  function readTailscaleStatus(run2 = (cmd) => spawnSync3(cmd, ["status", "--json"], { encoding: "utf8", timeout: 5e3, env: { ...process.env, TAILSCALE_BE_CLI: "1" } })) {
11606
11862
  let result = run2("tailscale");
11607
- if (result.error?.code === "ENOENT" && process.platform === "darwin" && existsSync6(TAILSCALE_APP)) result = run2(TAILSCALE_APP);
11863
+ if (result.error?.code === "ENOENT" && process.platform === "darwin" && existsSync7(TAILSCALE_APP)) result = run2(TAILSCALE_APP);
11608
11864
  if (result.error?.code === "ENOENT") {
11609
11865
  throw new ServeError("--tailscale needs the tailscale CLI: install Tailscale (https://tailscale.com/download) and make sure `tailscale` is on PATH");
11610
11866
  }
@@ -11667,7 +11923,7 @@ function loadSecret(secretFile) {
11667
11923
  const mode = fstatSync(fd);
11668
11924
  if (!mode.isFile()) throw new ServeError("--secret-file must be a regular file");
11669
11925
  if (process.platform !== "win32" && mode.mode & 36) throw new ServeError("--secret-file must not be readable by group or others");
11670
- const secret = readFileSync8(fd, "utf8");
11926
+ const secret = readFileSync9(fd, "utf8");
11671
11927
  if (!SECRET_PATTERN.test(secret)) throw new ServeError("--secret-file must contain exactly 64 lowercase hex characters");
11672
11928
  return secret;
11673
11929
  } finally {
@@ -11679,7 +11935,7 @@ function loadSecret(secretFile) {
11679
11935
  const secret = randomBytes(32).toString("hex");
11680
11936
  const tmp = `${secretFile}.${process.pid}.${randomBytes(16).toString("hex")}.tmp`;
11681
11937
  try {
11682
- writeFileSync6(tmp, secret, { mode: 384, flag: "wx" });
11938
+ writeFileSync7(tmp, secret, { mode: 384, flag: "wx" });
11683
11939
  try {
11684
11940
  linkSync(tmp, secretFile);
11685
11941
  } catch (publishError) {
@@ -11695,7 +11951,7 @@ function loadSecret(secretFile) {
11695
11951
  }
11696
11952
  }
11697
11953
  }
11698
- var infoPath = (home) => join10(home, "serve.json");
11954
+ var infoPath = (home) => join12(home, "serve.json");
11699
11955
  function pageToken(secret, dir, file) {
11700
11956
  return createHmac("sha256", secret).update(`${dir}/${file}`).digest("base64url").slice(0, TOKEN_LENGTH);
11701
11957
  }
@@ -11727,7 +11983,7 @@ var BOOT_SLACK_MS = 5e3;
11727
11983
  var bootedBefore = (startedAt) => startedAt < Date.now() - uptime() * 1e3 - BOOT_SLACK_MS;
11728
11984
  function readServeInfo(home) {
11729
11985
  try {
11730
- const info = JSON.parse(readFileSync8(infoPath(home), "utf8"));
11986
+ const info = JSON.parse(readFileSync9(infoPath(home), "utf8"));
11731
11987
  const validBase = info?.baseUrl === void 0 || typeof info.baseUrl === "string" && publicUrlOrigin(info.baseUrl) === info.baseUrl;
11732
11988
  const ok = info && Number.isInteger(info.port) && typeof info.secret === "string" && info.secret.length > 0 && Number.isFinite(info.startedAt) && !bootedBefore(info.startedAt) && alive(info.pid) && validBase;
11733
11989
  const host = isIP(info.host) ? info.host : void 0;
@@ -11740,9 +11996,9 @@ function serveLink(home, file) {
11740
11996
  try {
11741
11997
  const info = readServeInfo(home);
11742
11998
  if (!info) return null;
11743
- const path = resolve3(file);
11744
- const dir = ["pages", "videos"].find((d) => dirname2(path) === resolve3(home, d));
11745
- const name = basename3(path);
11999
+ const path = resolve4(file);
12000
+ const dir = ["pages", "videos"].find((d) => dirname3(path) === resolve4(home, d));
12001
+ const name = basename4(path);
11746
12002
  return dir && validFileName(name) ? pageLink(info, dir, name) : null;
11747
12003
  } catch {
11748
12004
  return null;
@@ -11753,7 +12009,7 @@ function writeInfo(home, info) {
11753
12009
  const tmp = `${infoPath(home)}.${process.pid}.tmp`;
11754
12010
  try {
11755
12011
  rmSync6(tmp, { force: true });
11756
- writeFileSync6(tmp, `${JSON.stringify(info)}
12012
+ writeFileSync7(tmp, `${JSON.stringify(info)}
11757
12013
  `, { mode: 384, flag: "wx" });
11758
12014
  renameSync5(tmp, infoPath(home));
11759
12015
  } finally {
@@ -11762,7 +12018,7 @@ function writeInfo(home, info) {
11762
12018
  }
11763
12019
  function removeInfo(home, secret, port) {
11764
12020
  try {
11765
- const info = JSON.parse(readFileSync8(infoPath(home), "utf8"));
12021
+ const info = JSON.parse(readFileSync9(infoPath(home), "utf8"));
11766
12022
  if (info.secret === secret && info.port === port) rmSync6(infoPath(home), { force: true });
11767
12023
  } catch {
11768
12024
  }
@@ -11772,10 +12028,106 @@ function reply(req, res, status, type, body = "") {
11772
12028
  res.end(req.method === "HEAD" ? void 0 : body);
11773
12029
  }
11774
12030
  var notFound = (req, res) => reply(req, res, 404, "text/plain; charset=utf-8", "Not found\n");
12031
+ var STATE_DIR = "serve-state";
12032
+ var MAX_STATE_BYTES = 64 * 1024;
12033
+ var STATE_KEYS = Object.freeze(["reply", "remark"]);
12034
+ async function pageVersion(home, file) {
12035
+ try {
12036
+ const s = await stat(await resolvePage(home, "pages", file));
12037
+ return `${s.mtimeMs}:${s.size}:${s.ino}`;
12038
+ } catch {
12039
+ return null;
12040
+ }
12041
+ }
12042
+ var stateFile = (home, token) => join12(home, STATE_DIR, `${createHash3("sha256").update(token).digest("hex")}.json`);
12043
+ function readState2(home, token) {
12044
+ try {
12045
+ const record2 = JSON.parse(readFileSync9(stateFile(home, token), "utf8"));
12046
+ return record2 && typeof record2 === "object" ? record2 : null;
12047
+ } catch {
12048
+ return null;
12049
+ }
12050
+ }
12051
+ function writeState2(home, token, record2) {
12052
+ const dir = join12(home, STATE_DIR);
12053
+ mkdirSync5(dir, { recursive: true, mode: 448 });
12054
+ const path = stateFile(home, token);
12055
+ const tmp = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
12056
+ try {
12057
+ writeFileSync7(tmp, `${JSON.stringify(record2)}
12058
+ `, { mode: 384, flag: "wx" });
12059
+ renameSync5(tmp, path);
12060
+ } finally {
12061
+ rmSync6(tmp, { force: true });
12062
+ }
12063
+ }
12064
+ function restorable(record2, version) {
12065
+ if (!record2 || version === null || record2.version !== version) return null;
12066
+ const state = Object.fromEntries(STATE_KEYS.filter((k2) => record2[k2] !== void 0).map((k2) => [k2, record2[k2]]));
12067
+ return Object.keys(state).length ? state : null;
12068
+ }
12069
+ async function saveState(req, res, home, secret, file, token, version) {
12070
+ const allow = "PUT, OPTIONS";
12071
+ const cors = {
12072
+ "Access-Control-Allow-Origin": "null",
12073
+ "Access-Control-Allow-Methods": allow,
12074
+ "Access-Control-Allow-Headers": "content-type",
12075
+ "Access-Control-Max-Age": "600"
12076
+ };
12077
+ if (req.method === "OPTIONS") {
12078
+ res.writeHead(204, { ...HEADERS, ...cors, Allow: allow });
12079
+ return res.end();
12080
+ }
12081
+ if (req.method !== "PUT") {
12082
+ res.setHeader("Allow", allow);
12083
+ return reply(req, res, 405, "text/plain; charset=utf-8", "Method not allowed\n");
12084
+ }
12085
+ const { origin, "sec-fetch-dest": dest } = req.headers;
12086
+ if (origin !== void 0 && origin !== "null" || dest !== void 0 && dest !== "empty") return notFound(req, res);
12087
+ if (!tokenMatches(secret, "pages", file, token) || version === null) return notFound(req, res);
12088
+ const type = (req.headers["content-type"] ?? "").toLowerCase();
12089
+ if (!type.startsWith("application/json")) return reply(req, res, 415, "text/plain; charset=utf-8", "Unsupported media type\n");
12090
+ const chunks = [];
12091
+ let size = 0;
12092
+ for await (const chunk of req) {
12093
+ size += chunk.length;
12094
+ chunks.push(chunk);
12095
+ if (size > MAX_STATE_BYTES) {
12096
+ res.setHeader("Connection", "close");
12097
+ return reply(req, res, 413, "text/plain; charset=utf-8", "State too large\n");
12098
+ }
12099
+ }
12100
+ const body = Buffer.concat(chunks).toString("utf8");
12101
+ let patch;
12102
+ try {
12103
+ patch = JSON.parse(body);
12104
+ } catch {
12105
+ return reply(req, res, 400, "text/plain; charset=utf-8", "Invalid JSON\n");
12106
+ }
12107
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
12108
+ return reply(req, res, 400, "text/plain; charset=utf-8", "Invalid JSON\n");
12109
+ }
12110
+ const part = Object.fromEntries(STATE_KEYS.filter((k2) => patch[k2] !== void 0).map((k2) => [k2, patch[k2]]));
12111
+ if (!Object.keys(part).length) return reply(req, res, 400, "text/plain; charset=utf-8", "Nothing to save\n");
12112
+ const previous = readState2(home, token);
12113
+ const base = previous && previous.version === version ? previous : {};
12114
+ const next = { ...base, ...part, version, file };
12115
+ if (Buffer.byteLength(`${JSON.stringify(next)}
12116
+ `) > MAX_STATE_BYTES) {
12117
+ return reply(req, res, 413, "text/plain; charset=utf-8", "State too large\n");
12118
+ }
12119
+ try {
12120
+ writeState2(home, token, next);
12121
+ } catch {
12122
+ return reply(req, res, 500, "text/plain; charset=utf-8", "Cannot save the state\n");
12123
+ }
12124
+ res.writeHead(204, { ...HEADERS, ...cors });
12125
+ return res.end();
12126
+ }
11775
12127
  async function resolvePage(home, dir, file) {
11776
12128
  try {
11777
- const root = await realpath(join10(home, dir));
11778
- const path = join10(root, file);
12129
+ const root = await realpath(join12(home, dir));
12130
+ const path = join12(root, file);
11779
12131
  if (!(await lstat(path)).isFile()) return null;
11780
12132
  const real = await realpath(path);
11781
12133
  return real.startsWith(root + sep3) ? real : null;
@@ -11783,12 +12135,14 @@ async function resolvePage(home, dir, file) {
11783
12135
  return null;
11784
12136
  }
11785
12137
  }
11786
- function withLiveReload(html, eventPath) {
12138
+ function withLiveReload(html, eventPath, serve) {
11787
12139
  const { ui } = resolveLanguage({ declared: readPage(html).lang });
11788
12140
  const script = `<script data-live="${esc(JSON.stringify({ url: eventPath, ui: ui.live }))}">${LIVE_SCRIPT_BODY}</script>
11789
12141
  `;
11790
- const at3 = html.lastIndexOf("</body>");
11791
- return at3 === -1 ? html + script : html.slice(0, at3) + script + html.slice(at3);
12142
+ const attrs = serve ? ` data-am-save="${esc(serve.save)}"${serve.state ? ` data-am-state="${esc(JSON.stringify(serve.state))}"` : ""}` : "";
12143
+ const withState = attrs && /<body\b[^>]*>/i.test(html) ? html.replace(/(<body\b)([^>]*)>/i, (_m, tag, own) => `${tag}${own}${attrs}>`) : html;
12144
+ const at3 = withState.search(/<\/body>(?![\s\S]*<\/body>)/i);
12145
+ return at3 === -1 ? withState + script : withState.slice(0, at3) + script + withState.slice(at3);
11792
12146
  }
11793
12147
  function liveStreams(home) {
11794
12148
  const streams = /* @__PURE__ */ new Map();
@@ -11834,14 +12188,14 @@ function liveStreams(home) {
11834
12188
  running = false;
11835
12189
  }
11836
12190
  };
11837
- const settle2 = () => {
12191
+ const settle3 = () => {
11838
12192
  clearTimeout(timer);
11839
- timer = setTimeout(run2, SETTLE_MS);
12193
+ timer = setTimeout(run2, SETTLE_MS2);
11840
12194
  };
11841
12195
  const startWatching = () => {
11842
12196
  if (watcher) return;
11843
12197
  try {
11844
- watcher = watch(join10(home, "pages"), settle2);
12198
+ watcher = watch(join12(home, "pages"), settle3);
11845
12199
  } catch {
11846
12200
  return;
11847
12201
  }
@@ -11903,23 +12257,29 @@ function handler(home, secret, allowedHosts, live) {
11903
12257
  return async (req, res) => {
11904
12258
  try {
11905
12259
  if (!hostAllowed(req.headers.host, allowedHosts)) return notFound(req, res);
11906
- if (req.method !== "GET" && req.method !== "HEAD") {
11907
- res.setHeader("Allow", "GET, HEAD");
11908
- return reply(req, res, 405, "text/plain; charset=utf-8", "Method not allowed\n");
11909
- }
11910
12260
  const parts = req.url.split(/[?#]/)[0].split("/");
11911
12261
  if (parts.length !== 4 || parts[0] !== "") return notFound(req, res);
11912
12262
  const [, prefix, token, raw] = parts;
11913
- const events = prefix === EVENTS;
11914
- const dir = events ? "pages" : Object.hasOwn(PREFIX2, prefix) ? PREFIX2[prefix] : void 0;
11915
- if (!dir || !token || !raw) return notFound(req, res);
11916
12263
  let file;
11917
12264
  try {
11918
12265
  file = decodeURIComponent(raw);
11919
12266
  } catch {
11920
12267
  return notFound(req, res);
11921
12268
  }
11922
- if (!validFileName(file) || !tokenMatches(secret, dir, file, token)) return notFound(req, res);
12269
+ if (!validFileName(file)) return notFound(req, res);
12270
+ if (prefix === SAVE) {
12271
+ const version = await pageVersion(home, file);
12272
+ if (!token) return notFound(req, res);
12273
+ return await saveState(req, res, home, secret, file, token, version);
12274
+ }
12275
+ if (req.method !== "GET" && req.method !== "HEAD") {
12276
+ res.setHeader("Allow", "GET, HEAD");
12277
+ return reply(req, res, 405, "text/plain; charset=utf-8", "Method not allowed\n");
12278
+ }
12279
+ const events = prefix === EVENTS;
12280
+ const dir = events ? "pages" : Object.hasOwn(PREFIX2, prefix) ? PREFIX2[prefix] : void 0;
12281
+ if (!dir || !token) return notFound(req, res);
12282
+ if (!tokenMatches(secret, dir, file, token)) return notFound(req, res);
11923
12283
  if (events) return await openEvents(req, res, home, file, live);
11924
12284
  const dest = req.headers["sec-fetch-dest"];
11925
12285
  if (dest !== void 0 && dest !== "document") return notFound(req, res);
@@ -11927,7 +12287,10 @@ function handler(home, secret, allowedHosts, live) {
11927
12287
  if (!real) return notFound(req, res);
11928
12288
  const html = await readFile(real);
11929
12289
  const page = LOOPBACK_HOST.test(req.headers.host) ? html.toString("utf8") : withoutUpdateNotice(html.toString("utf8"));
11930
- const body = dir === "pages" ? withLiveReload(page, eventLink({ secret }, file)) : page;
12290
+ const body = dir === "pages" ? withLiveReload(page, eventLink({ secret }, file), {
12291
+ save: `/${SAVE}/${token}/${encodeURIComponent(file)}`,
12292
+ state: restorable(readState2(home, token), await pageVersion(home, file)) ?? void 0
12293
+ }) : page;
11931
12294
  return reply(req, res, 200, "text/html; charset=utf-8", body);
11932
12295
  } catch {
11933
12296
  return notFound(req, res);
@@ -11959,7 +12322,7 @@ async function startServer({ home, port = DEFAULT_PORT, lan = false, publicUrl,
11959
12322
  const running = readServeInfo(home);
11960
12323
  if (running && await listening(running.port, running.host)) throw new ServeError(`am serve is already running on ${running.baseUrl ?? `http://${HOST}:${running.port}`} (pid ${running.pid}); stop it first`);
11961
12324
  if (tail && !secretFile) ensureHome(home);
11962
- const secret = loadSecret(secretFile ?? (tail ? join10(home, "serve-secret") : void 0));
12325
+ const secret = loadSecret(secretFile ?? (tail ? join12(home, "serve-secret") : void 0));
11963
12326
  const live = liveStreams(home);
11964
12327
  const server = createServer(handler(home, secret, allowedHosts, live));
11965
12328
  await new Promise((done, fail) => {
@@ -11986,7 +12349,7 @@ async function startServer({ home, port = DEFAULT_PORT, lan = false, publicUrl,
11986
12349
  });
11987
12350
  return closed;
11988
12351
  };
11989
- return { port: actual, secret, close, baseUrl, addresses, lan, tailscale: !!tail, secretPath: tail && !secretFile ? join10(home, "serve-secret") : secretFile };
12352
+ return { port: actual, secret, close, baseUrl, addresses, lan, tailscale: !!tail, secretPath: tail && !secretFile ? join12(home, "serve-secret") : secretFile };
11990
12353
  }
11991
12354
  async function runServe({ home, port, lan = false, publicUrl, secretFile, tailscale = false, print, fail }) {
11992
12355
  let srv;
@@ -12033,6 +12396,8 @@ Usage:
12033
12396
  am video <file|-> [-o <file>] [--voice auto|elevenlabs|local|system|off] [--mp4] [--webm] [--no-open]
12034
12397
  [--theme ${["auto", ...themeNames("video")].join("|")}] [--mode light|dark]
12035
12398
  render a video draft into a 3b1b-style explainer video player page (--mp4 / --webm also save a video file)
12399
+ am export <page.html> [--pdf <file.pdf>] [--png <dir>]
12400
+ export a rendered page as an A4 PDF and/or as PNG slices for a chat app (needs Chrome)
12036
12401
  am lint <file|-> [--style off|80|strict] run only the STE controlled-writing check
12037
12402
  am config [set <key> <value> | get <key> | reset [key]] show or change settings
12038
12403
  am serve [--port 8765] [--lan | --tailscale | --public-url <origin>] [--secret-file <path>] serve pages over http on 127.0.0.1 (--lan: on the local network; --tailscale: on your tailnet only); am render then prints a link:
@@ -12041,7 +12406,7 @@ Usage:
12041
12406
  am theme add <name> [--use] [--force] install a theme from the catalog (answer-me-with-html.com/themes/); --use makes it the default
12042
12407
  am theme list [--remote] | update [name] | remove <name> show, update or delete the themes in your themes folder
12043
12408
  am list list templates, themes and components
12044
- am help [component|format|code|image|video|patch|theme] show component syntax / page draft format / code block / image syntax / video draft format / patch / theme usage
12409
+ am help [component|format|code|image|video|patch|theme|export] show component syntax / page draft format / code block / image syntax / video draft format / patch / theme / export usage
12045
12410
 
12046
12411
  - A file argument of - reads from stdin (good for heredoc: am render - <<'EOF' ... EOF).
12047
12412
  - -o names an output file, for example -o page.html; it does not name a folder.
@@ -12210,6 +12575,8 @@ async function main(argv, io = {}) {
12210
12575
  voice: { type: "string" },
12211
12576
  mp4: { type: "boolean" },
12212
12577
  webm: { type: "boolean" },
12578
+ pdf: { type: "string" },
12579
+ png: { type: "string" },
12213
12580
  panel: { type: "string" },
12214
12581
  from: { type: "string" },
12215
12582
  days: { type: "string" },
@@ -12245,6 +12612,8 @@ ${USAGE}`);
12245
12612
  return cmdPatch(arg, rest[0], opts, ctx);
12246
12613
  case "video":
12247
12614
  return withSource(arg, io, fail, (src, _baseDir, from) => cmdVideo(src, opts, ctx, from));
12615
+ case "export":
12616
+ return cmdExport(arg, opts, ctx);
12248
12617
  case "lint":
12249
12618
  return withSource(arg, io, fail, (src) => cmdLint(src, opts, { print, fail }));
12250
12619
  case "config":
@@ -12276,7 +12645,7 @@ async function withSource(arg, io, fail, fn3) {
12276
12645
  const cwd = io.cwd ?? process.cwd();
12277
12646
  let src;
12278
12647
  try {
12279
- src = arg === "-" ? await readStream(io.stdin ?? process.stdin) : readFileSync9(resolve4(cwd, arg), "utf8");
12648
+ src = arg === "-" ? await readStream(io.stdin ?? process.stdin) : readFileSync10(resolve5(cwd, arg), "utf8");
12280
12649
  } catch (e) {
12281
12650
  fail(`\u2717 Cannot read the draft: ${e.message}`);
12282
12651
  return 2;
@@ -12285,7 +12654,7 @@ async function withSource(arg, io, fail, fn3) {
12285
12654
  fail("\u2717 The draft is empty");
12286
12655
  return 2;
12287
12656
  }
12288
- return fn3(src, arg === "-" ? cwd : dirname3(resolve4(cwd, arg)), arg === "-" ? { stdin: true } : { file: resolve4(cwd, arg) });
12657
+ return fn3(src, arg === "-" ? cwd : dirname4(resolve5(cwd, arg)), arg === "-" ? { stdin: true } : { file: resolve5(cwd, arg) });
12289
12658
  }
12290
12659
  async function readStream(stream) {
12291
12660
  const chunks = [];
@@ -12307,7 +12676,7 @@ async function cmdRender(src, opts, ctx, baseDir, from) {
12307
12676
  const { fail, print } = ctx;
12308
12677
  const replaced = opts.replace === void 0 ? null : pagePath(opts.replace, ctx);
12309
12678
  if (replaced === false) {
12310
- fail(`\u2717 --replace takes a page that am render wrote (a .html file in ${join11(amHome(ctx.env), "pages")} or ${join11(tempHome(), "pages")})`);
12679
+ fail(`\u2717 --replace takes a page that am render wrote (a .html file in ${join13(amHome(ctx.env), "pages")} or ${join13(tempHome(), "pages")})`);
12311
12680
  return 2;
12312
12681
  }
12313
12682
  const config = loadConfig(ctx);
@@ -12324,7 +12693,7 @@ async function cmdRender(src, opts, ctx, baseDir, from) {
12324
12693
  const written = emit(result, file, ctx, { fallback: opts.out ? void 0 : "pages" });
12325
12694
  if (!written) return 1;
12326
12695
  if (opts.out && !extname3(file)) print("! -o names a file without an extension; use .html for an HTML page");
12327
- if (replaced && replaced !== resolve4(written)) removeEarlier(replaced, ctx);
12696
+ if (replaced && replaced !== resolve5(written)) removeEarlier(replaced, ctx);
12328
12697
  keepDraft(result, src, from, ctx);
12329
12698
  const held = !opts.open && hasRetryWarnings(result) && shouldOpen(opts, ctx.env, config.values);
12330
12699
  if (held) print(` Not opened because of the warnings; to render again, add --replace ${written}`);
@@ -12332,7 +12701,7 @@ async function cmdRender(src, opts, ctx, baseDir, from) {
12332
12701
  }
12333
12702
  var updateFor = (config, { env, io }) => pageUpdate(readState(amHome(env)), VERSION, io.scriptPath, env, config.values);
12334
12703
  var hasWarnings = (result) => hasRetryWarnings(result) || (result.stats.componentWarnings ?? []).length > 0 || (result.stats.htmlWarnings ?? []).length > 0;
12335
- var draftsDir = (home) => join11(resolve4(home), "drafts");
12704
+ var draftsDir = (home) => join13(resolve5(home), "drafts");
12336
12705
  function draftTitle(src) {
12337
12706
  const m = src.match(/^title:\s*["']?(.+?)["']?\s*$/m) ?? src.match(/^#\s+(.+)$/m);
12338
12707
  return m?.[1] ?? "";
@@ -12347,7 +12716,7 @@ function saveDraft(src, { env, io }) {
12347
12716
  for (const folder of folders) {
12348
12717
  try {
12349
12718
  const dir = folder();
12350
- mkdirSync4(dir, { recursive: true });
12719
+ mkdirSync6(dir, { recursive: true });
12351
12720
  return writeNew(dir, name, src);
12352
12721
  } catch {
12353
12722
  }
@@ -12356,9 +12725,9 @@ function saveDraft(src, { env, io }) {
12356
12725
  }
12357
12726
  function writeNew(dir, name, text2) {
12358
12727
  for (let n = 1; ; n++) {
12359
- const file = join11(dir, n === 1 ? name : name.replace(/\.md$/, `-${n}.md`));
12728
+ const file = join13(dir, n === 1 ? name : name.replace(/\.md$/, `-${n}.md`));
12360
12729
  try {
12361
- writeFileSync7(file, text2, { flag: "wx" });
12730
+ writeFileSync8(file, text2, { flag: "wx" });
12362
12731
  return file;
12363
12732
  } catch (e) {
12364
12733
  if (e.code !== "EEXIST") throw e;
@@ -12379,7 +12748,7 @@ function keepDraft(result, src, from, ctx) {
12379
12748
  }
12380
12749
  }
12381
12750
  function isKeptDraft(path, { env }) {
12382
- return [draftsDir(amHome(env)), draftsDir(tempHome())].includes(dirname3(path)) && basename4(path).endsWith(".md");
12751
+ return [draftsDir(amHome(env)), draftsDir(tempHome())].includes(dirname4(path)) && basename5(path).endsWith(".md");
12383
12752
  }
12384
12753
  var isDraftError = (e) => e instanceof DraftErrors || e instanceof RenderError || e instanceof LintError || e instanceof ParseError && e.line > 0;
12385
12754
  function reportDraftError(e, src, from, ctx) {
@@ -12392,10 +12761,25 @@ function reportDraftError(e, src, from, ctx) {
12392
12761
  }
12393
12762
  var hasRetryWarnings = (result) => result.warnings.length > 0 || (result.stats.codeWarnings ?? []).length > 0 || (result.stats.mathWarnings ?? []).length > 0;
12394
12763
  function pagePath(arg, { env, io }) {
12395
- const path = resolve4(io.cwd ?? process.cwd(), arg);
12396
- const folders = [resolve4(amHome(env), "pages"), resolve4(tempHome(), "pages")];
12397
- return folders.includes(dirname3(path)) && basename4(path).endsWith(".html") ? path : false;
12764
+ const path = resolve5(io.cwd ?? process.cwd(), arg);
12765
+ const folders = [resolve5(amHome(env), "pages"), resolve5(tempHome(), "pages")];
12766
+ return folders.includes(dirname4(path)) && basename5(path).endsWith(".html") ? path : false;
12398
12767
  }
12768
+ var EXPORT_HELP = `Export a rendered page as an A4 PDF and/or PNG slices for a chat app
12769
+
12770
+ Usage:
12771
+ am export <page.html> --pdf <file.pdf>
12772
+ am export <page.html> --png <dir>
12773
+ am export <page.html> --pdf <file.pdf> --png <dir>
12774
+
12775
+ - The page must be an existing .html file, opened as a file:// URL; am export does not change it.
12776
+ - --pdf writes an A4 PDF with the page's own print rules (@media print), background colors, no header and no footer.
12777
+ - --png writes <dir>/<page-name>-1.png, -2.png ... at 1200 CSS px wide and 2x (2400 px), in slices no taller than 1800 CSS px.
12778
+ A cut falls in a gap between panels; a panel taller than 1800 CSS px is cut at the limit, so its text can span two PNG files.
12779
+ The toolbar, the reply and remark controls and the new-version notice are left out.
12780
+ - Give both flags to write both; at least one is required. The folder for --png is created when missing.
12781
+ - Needs Chrome / Chromium / Edge, like am video --mp4 / --webm. Set AM_CHROME when it is not in a usual place.
12782
+ - A PDF or PNG is a picture: reply, remarks, the theme switch and the Before/After switches do not work in it.`;
12399
12783
  var PATCH_HELP = `Replace one panel of a rendered page in place
12400
12784
 
12401
12785
  Usage:
@@ -12413,7 +12797,7 @@ var THEME_HELP = `Install a ready-made theme from the catalog at answer-me-with-
12413
12797
 
12414
12798
  am theme add <name> [--use] [--force]
12415
12799
  - Reads the catalog, downloads themes/<name>.json, checks its size, sha256, colors and links, and saves it to ~/.answer-me-with-html/themes/<name>.json.
12416
- Only catalog names work, not URLs or paths. --use also makes it the default theme (the same as am config set theme <name>).
12800
+ Only catalog names work, not URLs or paths. --use also makes it the default theme (the same as am config set theme <name>); without it, the theme is still in every new page's theme picker.
12417
12801
  - A file of that name that is not the catalog's is never overwritten (it may be your own theme): add --force to replace it.
12418
12802
  - It asks nothing else. The catalog address can be moved with the AM_CATALOG_URL environment variable (an https URL of an index.json; http only for localhost).
12419
12803
  am theme list [--remote] built-in themes, then your themes with version and source (catalog, catalog edited, local) and files that cannot be used; --remote also reads the catalog and marks updates and themes you do not have
@@ -12441,7 +12825,7 @@ Pick it like a built-in theme: theme: notes in the draft, --theme notes, or am c
12441
12825
  - tokens: light and dark must each set every color: ${COLOR_TOKENS.join(" ")}.
12442
12826
  common holds values shared by both; --radius --shadow --bw --head-font --font-sans --font-mono are optional.
12443
12827
  - Fonts: name installed fonts only; the default font stack is added as the fallback.
12444
- - font (optional): a font this tool ships, embedded in a page rendered with the theme: ${FONT_NAMES.join(" | ")}. Use it in css, for example & .am-head h1 { font-family: "Bangers", Impact, sans-serif; }.
12828
+ - font (optional): a font this tool ships, embedded once in every page that carries the theme: ${FONT_NAMES.join(" | ")}. Use it in css, for example & .am-head h1 { font-family: "Bangers", Impact, sans-serif; }.
12445
12829
  An older version ignores the field and shows the fallback font.
12446
12830
  - requires (optional): the oldest version of this tool the theme supports, as x.y.z. A newer requirement makes this tool skip the theme.
12447
12831
  - css (optional): start every selector with &, which stands for the theme's root, so the rules apply only under this theme.
@@ -12452,7 +12836,7 @@ Pick it like a built-in theme: theme: notes in the draft, --theme notes, or am c
12452
12836
  They restyle what is inside flow, sequence and er diagrams and tree boxes, and each defaults to today's look. The series tokens color the bars, lines and slices of a chart: a fixed palette is the default (a light set and a dark set); a series color below 3:1 against --paper in light or dark gives a warning. Widths and radii are a number or px / em (a bare number is px);
12453
12837
  --node-shadow is none or drop-shadow(...), like drop-shadow(3px 3px 0 #111). Do not write diagram selectors in css. There is no token for fonts: diagram text is measured for the sans font.
12454
12838
  - video (optional): video-only variables (--v-stage, --v-title-font, --v-cap-fg, --v-cap-bg, --v-glow) and & css for am video.
12455
- - A page carries the built-in themes plus its own theme, so it opens anywhere; readers without your fonts see the fallback.
12839
+ - A page carries the built-in themes plus every installed user theme, so the toolbar can switch to any of them and the page opens anywhere; readers without your fonts see the fallback.
12456
12840
  - A file with problems is skipped with a warning; am theme check <name|file.json> tells you why.
12457
12841
 
12458
12842
  am theme check <name|file.json> [--no-open]
@@ -12471,10 +12855,10 @@ async function cmdPatch(htmlArg, fromArg, opts, ctx) {
12471
12855
  return 2;
12472
12856
  }
12473
12857
  const cwd = io.cwd ?? process.cwd();
12474
- const file = resolve4(cwd, htmlArg);
12858
+ const file = resolve5(cwd, htmlArg);
12475
12859
  let html;
12476
12860
  try {
12477
- html = readFileSync9(file, "utf8");
12861
+ html = readFileSync10(file, "utf8");
12478
12862
  } catch (e) {
12479
12863
  fail(`\u2717 Cannot read the HTML: ${e.message}`);
12480
12864
  return 2;
@@ -12488,7 +12872,7 @@ async function cmdPatch(htmlArg, fromArg, opts, ctx) {
12488
12872
  const from = opts.from ?? fromArg;
12489
12873
  let replacement;
12490
12874
  try {
12491
- replacement = !from || from === "-" ? await readStream(io.stdin ?? process.stdin) : readFileSync9(resolve4(cwd, from), "utf8");
12875
+ replacement = !from || from === "-" ? await readStream(io.stdin ?? process.stdin) : readFileSync10(resolve5(cwd, from), "utf8");
12492
12876
  } catch (e) {
12493
12877
  fail(`\u2717 Cannot read the new panel draft: ${e.message}`);
12494
12878
  return 2;
@@ -12534,6 +12918,45 @@ async function cmdPatch(htmlArg, fromArg, opts, ctx) {
12534
12918
  if (!emit(result, file, ctx, { note: video ? " (an MP4 or WebM with the same name is not updated; run am video --mp4 or --webm again if you need it)" : "", inPlace: true })) return 1;
12535
12919
  return finish(file, opts, config, ctx);
12536
12920
  }
12921
+ async function cmdExport(arg, opts, ctx) {
12922
+ const { fail, print, env, io } = ctx;
12923
+ const empty = opts.pdf === "" ? "--pdf" : opts.png === "" ? "--png" : null;
12924
+ if (empty) {
12925
+ fail(`\u2717 ${empty} needs a path`);
12926
+ return 2;
12927
+ }
12928
+ if (opts.pdf === void 0 && opts.png === void 0) {
12929
+ fail("\u2717 export needs --pdf <file.pdf> or --png <dir>\n\n am export <page.html> --pdf <file.pdf> | --png <dir>");
12930
+ return 2;
12931
+ }
12932
+ if (!arg) {
12933
+ fail("\u2717 Missing the page argument: pass the .html file am render wrote");
12934
+ return 2;
12935
+ }
12936
+ const cwd = io.cwd ?? process.cwd();
12937
+ const file = resolve5(cwd, arg);
12938
+ let isPage;
12939
+ try {
12940
+ isPage = isHtmlPage(file);
12941
+ } catch (e) {
12942
+ fail(`\u2717 Cannot read the page ${arg}: ${e.message}`);
12943
+ return 2;
12944
+ }
12945
+ if (!isPage) {
12946
+ fail(`\u2717 ${arg} is not an existing .html file: am export takes a page am render wrote`);
12947
+ return 2;
12948
+ }
12949
+ const pdf = opts.pdf === void 0 ? void 0 : resolve5(cwd, opts.pdf);
12950
+ const png = opts.png === void 0 ? void 0 : resolve5(cwd, opts.png);
12951
+ try {
12952
+ await exportPage(file, { pdf, png, env, onFile: (f2) => print(`\u2713 ${f2}`) });
12953
+ return 0;
12954
+ } catch (e) {
12955
+ if (!(e instanceof ExportError)) throw e;
12956
+ fail(`\u2717 Export failed: ${e.message}`);
12957
+ return 1;
12958
+ }
12959
+ }
12537
12960
  async function cmdVideo(src, opts, ctx, from) {
12538
12961
  const { fail, print } = ctx;
12539
12962
  const config = loadConfig(ctx);
@@ -12585,7 +13008,7 @@ function narrationCache(home) {
12585
13008
  if (!isDenied(e)) throw e;
12586
13009
  return void 0;
12587
13010
  }
12588
- return join11(home, "cache", "tts");
13011
+ return join13(home, "cache", "tts");
12589
13012
  }
12590
13013
  function voiceSummary(provider, captionsOnly = []) {
12591
13014
  if (!provider) return "none (captions only)";
@@ -12618,24 +13041,31 @@ function themeWarnings({ fail, themes: themes2 }) {
12618
13041
  }
12619
13042
  function outputPath(dir, title, opts, { env, io, fail }) {
12620
13043
  if (opts.out) {
12621
- const file = resolve4(io.cwd ?? process.cwd(), opts.out);
12622
- if (statSync4(file, { throwIfNoEntry: false })?.isDirectory()) {
13044
+ const file2 = resolve5(io.cwd ?? process.cwd(), opts.out);
13045
+ if (statSync5(file2, { throwIfNoEntry: false })?.isDirectory()) {
12623
13046
  fail("\u2717 -o names a folder; give a file path, for example -o page.html");
12624
13047
  return null;
12625
13048
  }
12626
- return file;
13049
+ return file2;
13050
+ }
13051
+ const file = join13(amHome(env), dir, `${slug(title)}-${stamp(new Date(io.now?.() ?? Date.now()))}.html`);
13052
+ return opts.replace === void 0 ? unusedPagePath(file) : file;
13053
+ }
13054
+ function unusedPagePath(file) {
13055
+ for (let n = 1; ; n++) {
13056
+ const candidate = n === 1 ? file : file.replace(/\.html$/, `-${n}.html`);
13057
+ if (!existsSync8(candidate)) return candidate;
12627
13058
  }
12628
- return join11(amHome(env), dir, `${slug(title)}-${stamp(new Date(io.now?.() ?? Date.now()))}.html`);
12629
13059
  }
12630
13060
  function writePage(file, html, env) {
12631
- const home = resolve4(amHome(env));
12632
- const path = resolve4(file);
13061
+ const home = resolve5(amHome(env));
13062
+ const path = resolve5(file);
12633
13063
  if (path.startsWith(home + sep4)) ensureHome(home);
12634
- mkdirSync4(dirname3(file), { recursive: true });
12635
- if (!path.startsWith(join11(home, "pages") + sep4)) return writeFileSync7(file, html);
12636
- const tmp = join11(dirname3(file), `.${basename4(file)}.${process.pid}.tmp`);
13064
+ mkdirSync6(dirname4(file), { recursive: true });
13065
+ if (!path.startsWith(join13(home, "pages") + sep4)) return writeFileSync8(file, html);
13066
+ const tmp = join13(dirname4(file), `.${basename5(file)}.${process.pid}.tmp`);
12637
13067
  try {
12638
- writeFileSync7(tmp, html);
13068
+ writeFileSync8(tmp, html);
12639
13069
  renameOver(tmp, file);
12640
13070
  } finally {
12641
13071
  rmSync7(tmp, { force: true });
@@ -12643,10 +13073,10 @@ function writePage(file, html, env) {
12643
13073
  }
12644
13074
  function savePage(html, file, { fallback, inPlace }, { fail, env }) {
12645
13075
  const home = amHome(env);
12646
- const inHome = resolve4(file).startsWith(resolve4(home) + sep4);
13076
+ const inHome = resolve5(file).startsWith(resolve5(home) + sep4);
12647
13077
  const hint = (path) => {
12648
13078
  if (inPlace) return "Copy the page to a folder this session can write to and patch the copy";
12649
- return inHome ? `If this session can write only inside the workspace, run the command again with -o "<workspace>/.tmp/answers/${basename4(path)}"` : "Give -o a file in a folder this session can write to";
13079
+ return inHome ? `If this session can write only inside the workspace, run the command again with -o "<workspace>/.tmp/answers/${basename5(path)}"` : "Give -o a file in a folder this session can write to";
12650
13080
  };
12651
13081
  const refuse = (path, e) => fail(`\u2717 Cannot write the page: permission denied (${e.code}) ${path}. ${hint(path)}`);
12652
13082
  try {
@@ -12655,7 +13085,7 @@ function savePage(html, file, { fallback, inPlace }, { fail, env }) {
12655
13085
  } catch (e) {
12656
13086
  if (!isDenied(e)) throw e;
12657
13087
  if (!(fallback && inHome)) return refuse(file, e), null;
12658
- const spare = join11(tempHome(), fallback, basename4(file));
13088
+ const spare = join13(tempHome(), fallback, basename5(file));
12659
13089
  try {
12660
13090
  checkedTempHome({ create: true });
12661
13091
  writePage(spare, html, env);
@@ -12780,7 +13210,7 @@ function cmdServe(opts, { print, fail, env, io }) {
12780
13210
  return 2;
12781
13211
  }
12782
13212
  const port = opts.port === void 0 ? DEFAULT_PORT : Number(opts.port);
12783
- const secretFile = opts["secret-file"] === void 0 ? void 0 : resolve4(io?.cwd ?? process.cwd(), opts["secret-file"]);
13213
+ const secretFile = opts["secret-file"] === void 0 ? void 0 : resolve5(io?.cwd ?? process.cwd(), opts["secret-file"]);
12784
13214
  return runServe({ home: amHome(env), port, lan: !!opts.lan, tailscale: !!opts.tailscale, publicUrl: opts["public-url"], secretFile, print, fail });
12785
13215
  }
12786
13216
  function cmdLint(src, opts, { print, fail }) {
@@ -12910,13 +13340,13 @@ function cmdTheme(action, target, opts, ctx) {
12910
13340
  return 2;
12911
13341
  }
12912
13342
  const isFile = /\.json$/i.test(target) || /[\\/]/.test(target);
12913
- const path = isFile ? resolve4(io.cwd ?? process.cwd(), target) : join11(amHome(env), "themes", `${target}.json`);
12914
- const name = isFile ? basename4(path).replace(/\.json$/i, "") : target;
13343
+ const path = isFile ? resolve5(io.cwd ?? process.cwd(), target) : join13(amHome(env), "themes", `${target}.json`);
13344
+ const name = isFile ? basename5(path).replace(/\.json$/i, "") : target;
12915
13345
  let theme;
12916
13346
  let errors = [];
12917
13347
  if (!isFile && getTheme(name)) {
12918
13348
  theme = getTheme(name);
12919
- } else if (existsSync7(path)) {
13349
+ } else if (existsSync8(path)) {
12920
13350
  ({ theme, errors } = readThemeFile(path, themeNames("video")));
12921
13351
  } else {
12922
13352
  fail(`\u2717 No theme named "${target}": ${path} does not exist`);
@@ -12949,12 +13379,13 @@ function cmdHelp(name, { print, fail }) {
12949
13379
  if (name === "image") return print(IMAGE_HELP), 0;
12950
13380
  if (name === "code") return print(CODE_HELP), 0;
12951
13381
  if (name === "video") return print(VIDEO_FORMAT), 0;
13382
+ if (name === "export") return print(EXPORT_HELP), 0;
12952
13383
  if (name === "patch") return print(PATCH_HELP), 0;
12953
13384
  if (name === "theme") return print(THEME_HELP), 0;
12954
13385
  if (name === "html" || name === "svg") return print(RAW_HELP.replace(/LANG/g, name)), 0;
12955
13386
  const comp = COMPONENTS.get(name);
12956
13387
  if (!comp) {
12957
- fail(`\u2717 No component named "${name}". Available: ${[...COMPONENTS.keys()].join(", ")}, html, svg, format, code, image, video, patch, theme`);
13388
+ fail(`\u2717 No component named "${name}". Available: ${[...COMPONENTS.keys()].join(", ")}, html, svg, format, code, image, video, export, patch, theme`);
12958
13389
  return 2;
12959
13390
  }
12960
13391
  print(`${comp.name} \u2014 ${comp.summary}
@@ -12966,8 +13397,12 @@ ${comp.example}`);
12966
13397
  return 0;
12967
13398
  }
12968
13399
  function slug(title) {
12969
- const s = String(title || "page").trim().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 40);
12970
- return s || "page";
13400
+ const s = String(title || "").replace(/[^A-Za-z0-9]+/g, "-").toLowerCase().replace(/^-+|-+$/g, "");
13401
+ if (!s) return "page";
13402
+ if (s.length <= 24) return s;
13403
+ const cut = s.slice(0, 24);
13404
+ const at3 = cut.lastIndexOf("-");
13405
+ return at3 > 0 ? cut.slice(0, at3) : cut;
12971
13406
  }
12972
13407
  function stamp(d) {
12973
13408
  const p = (n) => String(n).padStart(2, "0");
@@ -12976,7 +13411,7 @@ function stamp(d) {
12976
13411
  function openFile(file) {
12977
13412
  const [cmd, args] = process.platform === "darwin" ? ["open", [file]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", file]] : ["xdg-open", [file]];
12978
13413
  try {
12979
- spawn4(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {
13414
+ spawn5(cmd, args, { detached: true, stdio: "ignore" }).on("error", () => {
12980
13415
  }).unref();
12981
13416
  } catch {
12982
13417
  }