Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
v0.7.0: charts-lite (all-MIT), compressed self-extracting shell, AI round-trip
nyblnet9c407893addd
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9f9712a4..3aeb3796 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -63,18 +63,17 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.translate at render time); keys must match source EXACTLY (validate with theextraction/diff script pattern in git history); setLocale('x-pseudo') auditsunswept strings. New UI strings must be added to ALL catalogs.-- `src/charts.ts` — ECharts (Apache-2.0, svg renderer only, tree-shaken:- bar/line/pie/scatter + grid/tooltip/legend/dataZoom/title/dataset). A `chart`- element stores a PURE-JSON option (template-string formatters, never- functions — the doc must serialize). Editor canvas/thumbnails/print show- cached SSR SVG snapshots (chartSnapshotSvg); present mode mounts live- instances (tooltips + dataZoom work), disposed back to snapshots on slide- exit. Live node exposes `__bentoChart` for scripting. Panel: preset select- re-seeds the option; JSON textarea is the escape hatch. NOTICE block in- index.html carries MIT + Apache/BSD notices into every saved document.- Charts on morph/state transitions data-morph: the incoming chart paints the- outgoing side's option first, then setOption's to its own with- universalTransition (values tween in place, bar⇄pie works). Shapes:+- `src/charts.ts` — charts-lite, OUR OWN engine (ECharts removed for size:+ it was 630KB = 47% of the shell; git history has the integration). Same+ 3-function API (CHART_PRESETS/mountChart/chartSnapshotSvg) interpreting the+ ECharts option SHAPE (format unchanged): bar/line/pie/scatter, nice-tick+ axes, legend, axis/item tooltips, inside wheel-zoom+drag-pan, transitions+ (same series types = numeric-leaf lerp of the whole option per frame;+ type change bar⇄pie = staged fade+sweep). Pure SVG on anim.ts. Options stay+ PURE JSON (template formatters {b}/{c}/{d}, never functions). Editor+ canvas/thumbs/print use chartSnapshotSvg (cached); present mounts live+ (host exposes `__bentoChart`). Unknown option keys are ignored gracefully —+ exotic ECharts configs degrade, don't crash. Shapes:`strokeStyle` solid/dashed/dotted (legacy `strokeDash` still honoured);line shapes have `lineStart`/`lineEnd` tips (arrow/dot/bar) rendered asper-instance svg markers (sized in strokeWidth units, endpoints inset);@@ -176,6 +175,20 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.7. Tiny text labels make unusable click targets when scaled down — interactivecontrols get padded transparent `link` overlay rects, not links on the text itself.+- **Compressed shell (Phase 1)**: `scripts/postbuild-compress.mjs` (runs in+ build:single) deflates runtime JS+CSS into base64 `bento/deflate-b64` script+ blocks + ~1KB loader (DecompressionStream → blob import; pre-2023 browsers+ get a plain-HTML message). Byte order: chrome → NOTICE → tooling comment →+ PLAINTEXT #bento-doc → splash → payloads last. Shell ~373KB (was 1.33MB).+ SPLICE CONTRACT (old updaters are frozen code): #bento-doc stays plaintext/+ same id, file survives DOMParser→splice→outerHTML, no stray script-close —+ release.mjs runs a conformance GATE before signing every release.+- **AI round-trip**: the DOCUMENT is the interchange unit (chat AIs can't emit+ 1MB+ files). About → "Copy document JSON" / "Replace document from JSON…"+ (store.replaceDoc, undoable); `window.bento.loadDoc(json)` for scripts; the+ shell carries a Tooling-note comment pointing AIs at #bento-doc + the API.+ Agent harnesses edit files in place; chat AIs round-trip the JSON.+## Commands- `npm run dev` (in slides/) — dev server; `.claude/launch.json` has `slides-dev` (:5199)diff --git a/docs/architecture.md b/docs/architecture.mdindex 115122ef..e10dfdf3 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -13,6 +13,14 @@ trick, modernized with the File System Access API).---+> **v0.7.0 update**: the runtime now ships DEFLATE-compressed (shell ≈373KB,+> was 1.33MB) — byte order: chrome → NOTICE → tooling comment → **plaintext+> `#bento-doc`** → splash → compressed payloads + 1KB loader last. The+> document block stays plaintext forever (AI/tooling + old-updater splice+> contract; release.mjs gates every release on it). Charts are now in-house+> (`charts-lite`, MIT) — ECharts/zrender removed. Diagrams below describe the+> uncompressed layout; sizes predate compression.+## 1. On-disk anatomyA `.bento.html` file is ordinary, valid HTML. Its compartments, drawndiff --git a/scripts/postbuild-compress.mjs b/scripts/postbuild-compress.mjsnew file mode 100644index 00000000..3e9aa392--- /dev/null+++ b/scripts/postbuild-compress.mjs@@ -0,0 +1,152 @@+#!/usr/bin/env node+// Self-extracting shell: compress the built runtime so the file on disk is+// ~half the size, with zero feature loss.+//+// node scripts/postbuild-compress.mjs slides/dist-single/Bento_Slides.bento.html+//+// Takes the vite single-file build, extracts the big inline module script and+// stylesheet, deflates them (raw) into base64 payload blocks, and restructures+// the document into the canonical byte order:+//+// head chrome → NOTICE → tooling comment → #bento-doc (PLAINTEXT, always)+// → splash (paints while the payload parses) → payloads + 1KB loader last+//+// The loader inflates via the native DecompressionStream and boots the module+// from a blob URL. Browsers without DecompressionStream (pre-2023 Safari) get+// a plain-HTML message instead of a blank page.+//+// COMPATIBILITY CONTRACT (老 updaters are frozen code — we conform to them):+// - #bento-doc stays plaintext with the same id.+// - The whole file survives DOMParser → splice → outerHTML round-trips.+// - No literal "</script>" anywhere (base64 alphabet can't produce one;+// the loader is checked below).+// release.mjs runs a frozen v0.1.0-style splice against the output as a gate.++import { readFileSync, writeFileSync } from 'node:fs'+import { deflateRawSync } from 'node:zlib'++const path = process.argv[2]+if (!path) {+ console.error('usage: node scripts/postbuild-compress.mjs <shell.html>')+ process.exit(1)+}++const html = readFileSync(path, 'utf8')+if (html.includes('id="bento-rt"')) {+ console.log('already compressed — skipping')+ process.exit(0)+}++// --- extract the runtime pieces --------------------------------------------+const modRe = /<script type="module"[^>]*>([\s\S]*?)<\/script>/+const mod = html.match(modRe)+if (!mod) throw new Error('module script not found')++// the FIRST big <style> is the app css; the splash <style> lives in body+const styleRe = /<style[^>]*>([\s\S]*?)<\/style>/+const headPart = html.slice(0, html.indexOf('</head>'))+const styleM = headPart.match(styleRe)+if (!styleM) throw new Error('app stylesheet not found in head')++const js = mod[1]+const css = styleM[1]++const b64 = (s) => deflateRawSync(Buffer.from(s, 'utf8'), { level: 9 }).toString('base64')+const jsB64 = b64(js)+const cssB64 = b64(css)++// --- other parts ------------------------------------------------------------+const notice = html.match(/<!--\s*NOTICE[\s\S]*?-->/)?.[0] ?? ''+const docBlock = html.match(/<script type="application\/bento\+json" id="bento-doc">[\s\S]*?<\/script>/)?.[0]+if (!docBlock) throw new Error('#bento-doc not found')+const favicon = html.match(/<link rel="icon"[^>]*\/?>/)?.[0] ?? ''+const title = html.match(/<title>[\s\S]*?<\/title>/)?.[0] ?? '<title>Bento Slides</title>'+const splashDiv = html.match(/<div id="bento-splash"[\s\S]*?<\/div>\s*<\/div>/)?.[0] ?? ''+const splashCss = (() => {+ const bodyPart = html.slice(html.indexOf('<body'))+ const m = bodyPart.match(/<style[^>]*>([\s\S]*?)<\/style>/)+ return m ? m[1] : ''+})()++const TOOLING_COMMENT = `<!--+ Tooling note (for AI assistants and scripts):+ - The DOCUMENT lives in the script block of type "application/bento+json"+ with id "bento-doc" below, as plain readable JSON. That block is the only part that changes+ between saves; everything else is the fixed application shell.+ - To modify this deck programmatically or with an AI: edit that JSON (or+ replace the block's text), never regenerate the whole file. In the app:+ About dialog → "Copy document JSON" / "Replace document from JSON".+ - The base64 blocks near the end are the DEFLATE-compressed application+ runtime (open source: https://bento.page) — no user content inside.+ - In a running file, window.bento exposes { doc, serialize(), comments(),+ loadDoc(json), updates, i18n } for automation.+ -->`++// --- loader (plain script, runs at end of body; no "</script>" literal) -----+const loader = `+(async () => {+ var fail = function (msg) {+ var d = document.createElement('div')+ d.style.cssText = 'position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:#0D1B2E;color:#F2F0EA;font:16px/1.6 sans-serif;text-align:center;padding:40px;z-index:99999'+ d.innerHTML = msg+ document.body.appendChild(d)+ var s = document.getElementById('bento-splash'); if (s) s.remove()+ }+ if (typeof DecompressionStream === 'undefined') {+ fail('This file needs a browser from 2023 or later (Chrome 80+, Edge, Firefox 113+, Safari 16.4+).<br>The document itself is intact \\u2014 open this file in a newer browser.')+ return+ }+ var inflate = async function (id) {+ var b64 = document.getElementById(id).textContent.trim()+ var bytes = Uint8Array.from(atob(b64), function (c) { return c.charCodeAt(0) })+ var ds = new DecompressionStream('deflate-raw')+ var stream = new Blob([bytes]).stream().pipeThrough(ds)+ return await new Response(stream).text()+ }+ try {+ var css = await inflate('bento-rt-css')+ var st = document.createElement('style')+ st.textContent = css+ document.head.appendChild(st)+ var js = await inflate('bento-rt')+ var url = URL.createObjectURL(new Blob([js], { type: 'text/javascript' }))+ await import(url)+ } catch (e) {+ fail('This file could not start: ' + (e && e.message ? e.message : e))+ }+})()+`+if (loader.includes('</scr' + 'ipt>')) throw new Error('loader contains script-close')++// --- assemble ----------------------------------------------------------------+const out = `<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="generator" content="bento-slides" />+ ${favicon}+ ${title}+ ${notice}+ ${TOOLING_COMMENT}+ ${docBlock}+ <style>${splashCss}</style>+ </head>+ <body>+ ${splashDiv}+ <div id="app"></div>+ <script id="bento-rt-css" type="bento/deflate-b64">${cssB64}</script>+ <script id="bento-rt" type="bento/deflate-b64">${jsB64}</script>+ <script>${loader}</script>+ </body>+</html>+`++// sanity: script-close count must equal script tag count (splice invariant)+const closes = out.split('</scr' + 'ipt>').length - 1+const opens = (out.match(/<script[\s>]/g) ?? []).length+if (closes !== opens) throw new Error(`script tag imbalance: ${opens} opens, ${closes} closes`)++writeFileSync(path, out)+const kb = (n) => `${Math.round(n / 1024)}KB`+console.log(`compressed shell: ${kb(html.length)} → ${kb(out.length)} (js ${kb(js.length)}→${kb(jsB64.length)}, css ${kb(css.length)}→${kb(cssB64.length)})`)diff --git a/scripts/release.mjs b/scripts/release.mjsindex 11b2ec14..44b51e6a 100644--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -47,6 +47,26 @@ cpSync(shellSrc, join(site, 'releases/slides/Bento_Slides.bento.html'))// The live demo IS the shell — opening it boots the editor with the starter deck.cpSync(shellSrc, join(site, 'slides/index.html'))+// CONFORMANCE GATE — old updaters are frozen code; every release must+// satisfy the splice contract they rely on (see postbuild-compress.mjs):+// plaintext #bento-doc, regex-extractable, balanced script tags, and a+// v0.1.0-style text splice must produce a well-formed document.+{+ const shell = readFileSync(join(site, 'releases/slides/Bento_Slides.bento.html'), 'utf8')+ const blockRe = /<script type="application\/bento\+json" id="bento-doc">[\s\S]*?<\/script>/+ if (!blockRe.test(shell)) throw new Error('GATE: #bento-doc block not found/extractable')+ const opens = (shell.match(/<script[\s>]/g) ?? []).length+ const closes = shell.split('</scr' + 'ipt>').length - 1+ if (opens !== closes) throw new Error(`GATE: script tag imbalance (${opens}/${closes})`)+ const fakeDoc = JSON.stringify({ format: 'bento/slides', probe: '<tag> & </close>' }).replace(/</g, '\\u003c')+ const spliced = shell.replace(blockRe, `<script type="application/bento+json" id="bento-doc">\n${fakeDoc}\n</scr` + 'ipt>')+ if (!spliced.includes(fakeDoc)) throw new Error('GATE: splice failed')+ const opens2 = (spliced.match(/<script[\s>]/g) ?? []).length+ const closes2 = spliced.split('</scr' + 'ipt>').length - 1+ if (opens2 !== closes2) throw new Error('GATE: spliced document imbalanced')+ console.log('conformance gate: old-updater splice contract OK')+}+// Sign the manifest against the staged bytes.const signArgs = [join(root, 'scripts/sign-release.mjs'),diff --git a/slides/index.html b/slides/index.htmlindex ffb9a68a..3b2ceb3b 100644--- a/slides/index.html+++ b/slides/index.html@@ -14,15 +14,12 @@reveal.js — Copyright (C) Hakim El Hattab and contributors — MIT Licensemoveable, selecto and their @daybrush/@scena/@egjs/@cfcs modules —Copyright (c) Daybrush (Younkue Choi) — MIT License- Apache ECharts — Copyright Apache Software Foundation — Apache License- 2.0 (http://www.apache.org/licenses/LICENSE-2.0). Provided on an- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. This- distribution bundles ECharts unmodified.- zrender — Copyright (c) 2017 Baidu Inc. — BSD-3-Clause LicenseFraunces typeface — Copyright 2020 The Fraunces Project Authors(github.com/undercasetype/Fraunces) — SIL Open Font License 1.1- (openfontlicense.org). Embedded as a document asset in decks that- use it; the font is licensed under the OFL and remains under it.+ Instrument Sans typeface — Copyright 2022 The Instrument Sans Project+ Authors (github.com/Instrument/instrument-sans) — SIL Open Font+ License 1.1 (openfontlicense.org). Both fonts are embedded as+ document assets in decks that use them and remain under the OFL.MIT License: Permission is hereby granted, free of charge, to any personobtaining a copy of this software and associated documentation files (thediff --git a/slides/package.json b/slides/package.jsonindex 53ae1670..5e014fbe 100644--- a/slides/package.json+++ b/slides/package.json@@ -1,16 +1,15 @@{"name": "bento-slides","private": true,- "version": "0.6.2",+ "version": "0.7.0","type": "module","scripts": {"dev": "vite","build": "tsc -b && vite build",- "build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Slides.bento.html",+ "build:single": "tsc -b && SINGLEFILE=1 vite build --outDir dist-single && mv dist-single/index.html dist-single/Bento_Slides.bento.html && node ../scripts/postbuild-compress.mjs dist-single/Bento_Slides.bento.html","preview": "vite preview"},"dependencies": {- "echarts": "^6.1.0","moveable": "^0.53.0","reveal.js": "^5.2.1","selecto": "^1.26.3"diff --git a/slides/src/charts.ts b/slides/src/charts.tsindex 3a1c1489..9bcdd15a 100644--- a/slides/src/charts.ts+++ b/slides/src/charts.ts@@ -1,33 +1,23 @@-// ECharts integration. A `chart` element stores a plain-JSON ECharts option in-// the document; this module renders it two ways:-// - chartSnapshotSvg(el): a static SVG string (SSR mode) — used by the-// editor canvas, sidebar thumbnails and print, so those surfaces stay-// cheap, crisp at any scale, and drag-friendly.-// - mountChart(el, host): a live instance — used in present mode, where-// tooltips, dataZoom and legend interactivity actually run.-// Only the SVG renderer and a curated set of charts/components are bundled;-// options must stay pure JSON (template-string formatters, no functions).--import * as echarts from 'echarts/core'-import { BarChart, LineChart, PieChart, ScatterChart } from 'echarts/charts'-import {- DatasetComponent,- DataZoomComponent,- GridComponent,- LegendComponent,- TitleComponent,- TooltipComponent,-} from 'echarts/components'-import { SVGRenderer } from 'echarts/renderers'-import { UniversalTransition } from 'echarts/features'+// charts-lite: Bento's own chart engine (replaces ECharts — see git history).+//+// A `chart` element stores a plain-JSON option in the ECharts option SHAPE —+// the format is unchanged; this module interprets the subset Bento uses:+// bar / line / pie / scatter · category+value axes with nice ticks ·+// legend · axis/item tooltips · inside wheel-zoom + drag-pan · transitions+// between options (same-type data tweens; cross-type staged sweep).+// Unknown option keys are ignored gracefully. Rendering is pure SVG on the+// same substrate as the rest of Bento (anim.ts drives all motion), so the+// whole engine is ~one file and every byte of it is ours (MIT).+//+// Two render paths, same API as always:+// - chartSnapshotSvg(el): static SVG string — editor canvas, thumbs, print.+// - mountChart(el, host, fromOption?): live instance — present mode+// (tooltips, zoom); with fromOption, animates from that option to its own.++import { anim } from './anim'import type { ChartElement } from './model'-echarts.use([- BarChart, LineChart, PieChart, ScatterChart,- DatasetComponent, DataZoomComponent, GridComponent,- LegendComponent, TitleComponent, TooltipComponent,- SVGRenderer, UniversalTransition,-])+type Opt = Record<string, any>/** Presets seed new charts and let the panel swap types without data loss. */export const CHART_PRESETS: Record<string, () => Record<string, unknown>> = {@@ -69,7 +59,7 @@ export const CHART_PRESETS: Record<string, () => Record<string, unknown>> = {grid: { left: 56, right: 20, top: 24, bottom: 40 },xAxis: { type: 'value' },yAxis: { type: 'value' },- dataZoom: [{ type: 'inside' }, { type: 'inside', orient: 'vertical' }],+ dataZoom: [{ type: 'inside' }],series: [{type: 'scatter', symbolSize: 14,data: [[10, 8], [15, 12], [22, 10], [28, 19], [34, 15], [41, 25], [48, 22]],@@ -77,68 +67,541 @@ export const CHART_PRESETS: Record<string, () => Record<string, unknown>> = {}),}-/** Enable smooth data/type transitions on every series of an option. */-const withTransition = (option: Record<string, unknown>, animate: boolean): Record<string, unknown> => ({- ...option,- animation: animate,- animationDurationUpdate: 650,- animationEasingUpdate: 'quadraticInOut',- series: Array.isArray(option.series)- ? (option.series as Array<Record<string, unknown>>).map((s) => ({ ...s, universalTransition: true }))- : option.series,-})+const PALETTE = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']+const SVG_NS = 'http://www.w3.org/2000/svg'++// --- option digestion -------------------------------------------------------++interface Digest {+ w: number; h: number+ font: string+ colors: string[]+ series: Array<Opt>+ categories: string[]+ isPie: boolean+ grid: { x: number; y: number; w: number; h: number }+ legend: null | { color: string }+ axisLabel: string; axisLine: string; splitLine: string+ tooltipTrigger: 'axis' | 'item' | null+ zoomable: boolean+ labelColor: string+}++function digest(option: Opt, w: number, h: number): Digest {+ const series: Opt[] = Array.isArray(option?.series) ? option.series : option?.series ? [option.series] : []+ const isPie = series.some((s) => s?.type === 'pie')+ const g = option?.grid ?? {}+ const legend = option?.legend ? { color: option.legend?.textStyle?.color ?? '#6B7280' } : null+ const legendH = legend ? 24 : 0+ const grid = isPie+ ? { x: 0, y: 0, w, h: h - legendH }+ : {+ x: num(g.left, 48),+ y: num(g.top, 24),+ w: w - num(g.left, 48) - num(g.right, 16),+ h: h - num(g.top, 24) - num(g.bottom, 44),+ }+ return {+ w, h,+ font: option?.textStyle?.fontFamily ?? 'sans-serif',+ colors: Array.isArray(option?.color) && option.color.length ? option.color : PALETTE,+ series, isPie,+ categories: (option?.xAxis?.data ?? []).map(String),+ grid,+ legend,+ axisLabel: option?.xAxis?.axisLabel?.color ?? option?.yAxis?.axisLabel?.color ?? '#6B7280',+ axisLine: option?.xAxis?.axisLine?.lineStyle?.color ?? 'rgba(110,120,135,0.45)',+ splitLine: option?.yAxis?.splitLine?.lineStyle?.color ?? 'rgba(110,120,135,0.15)',+ tooltipTrigger: option?.tooltip ? (option.tooltip.trigger === 'item' ? 'item' : 'axis') : null,+ zoomable: Array.isArray(option?.dataZoom) && option.dataZoom.length > 0,+ labelColor: series.find((s) => s?.type === 'pie')?.label?.color ?? '#6B7280',+ }+}++const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d)++/** Nice tick values for a 0..max (or min..max) range. */+function niceTicks(min: number, max: number, target = 5): number[] {+ if (max === min) max = min + 1+ const span = max - min+ const step0 = Math.pow(10, Math.floor(Math.log10(span / target)))+ const err = span / target / step0+ const step = step0 * (err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1)+ const lo = Math.floor(min / step) * step+ const hi = Math.ceil(max / step) * step+ const out: number[] = []+ for (let v = lo; v <= hi + step / 2; v += step) out.push(Math.round(v * 1e6) / 1e6)+ return out+}++const fmt = (v: number): string =>+ Math.abs(v) >= 1000 ? String(v).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : String(Math.round(v * 100) / 100)++// --- svg helpers ------------------------------------------------------------++function elNS<K extends keyof SVGElementTagNameMap>(tag: K, attrs: Record<string, string | number>): SVGElementTagNameMap[K] {+ const n = document.createElementNS(SVG_NS, tag)+ for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, String(v))+ return n+}++function text(x: number, y: number, s: string, fill: string, font: string, size = 12, anchor = 'middle'): SVGTextElement {+ const t = elNS('text', { x, y, fill, 'font-size': size, 'text-anchor': anchor, 'font-family': font })+ t.textContent = s+ return t+}++let gradSeq = 0+function seriesFill(svg: SVGSVGElement, s: Opt, fallback: string): string {+ const c = s?.areaStyle?.color ?? s?.itemStyle?.color+ if (c && typeof c === 'object' && Array.isArray(c.colorStops)) {+ const id = `bc-g${++gradSeq}`+ const lg = elNS('linearGradient', {+ id, x1: num(c.x, 0), y1: num(c.y, 0), x2: num(c.x2, 0), y2: num(c.y2, 1),+ })+ for (const st of c.colorStops) {+ lg.appendChild(elNS('stop', { offset: num(st.offset, 0), 'stop-color': st.color ?? fallback }))+ }+ let defs = svg.querySelector('defs')+ if (!defs) { defs = elNS('defs', {}); svg.prepend(defs) }+ defs.appendChild(lg)+ return `url(#${id})`+ }+ return typeof c === 'string' ? c : fallback+}++// --- core renderer ----------------------------------------------------------++interface View { start: number; end: number } // x-domain window, 0..1/**- * Live instance for present mode. Returns a dispose handle. When `fromOption`- * is given (morph/state transition with a matching chart on the other side),- * the chart first paints that state and then ANIMATES to its own — value- * changes tween in place, and universalTransition even morphs across series- * types (bar → pie).+ * Render `option` into a fresh <svg>. `sweep` (0..1) grows series in — used+ * by entrance/cross-type transitions. `view` is the zoom window.*/-export function mountChart(el: ChartElement, host: HTMLElement, fromOption?: Record<string, unknown>): () => void {- host.innerHTML = ''- const inst = echarts.init(host, undefined, { renderer: 'svg', width: el.w, height: el.h })- try {- if (fromOption && JSON.stringify(fromOption) !== JSON.stringify(el.option)) {- inst.setOption(withTransition(fromOption, false) as never)- setTimeout(() => {- if (!inst.isDisposed()) inst.setOption(withTransition(el.option, true) as never, { notMerge: true })- }, 60)- } else {- inst.setOption(el.option as never)+function renderChart(option: Opt, w: number, h: number, sweep = 1, view: View = { start: 0, end: 1 }): SVGSVGElement {+ const d = digest(option, w, h)+ const svg = elNS('svg', { xmlns: SVG_NS, viewBox: `0 0 ${w} ${h}`, width: w, height: h })+ svg.style.cssText = 'width:100%;height:100%;display:block'++ if (d.isPie) renderPie(svg, d, option, sweep)+ else renderCartesian(svg, d, sweep, view)++ if (d.legend && d.series.some((s) => s?.name || s?.type === 'pie')) renderLegend(svg, d)+ return svg+}++function renderLegend(svg: SVGSVGElement, d: Digest) {+ const pie = d.series.find((s) => s?.type === 'pie')+ const items: Array<{ name: string; color: string }> = pie+ ? (pie.data ?? []).map((p: Opt, i: number) => ({ name: String(p?.name ?? i), color: d.colors[i % d.colors.length] }))+ : d.series.map((s, i) => ({ name: String(s?.name ?? `Series ${i + 1}`), color: typeof s?.itemStyle?.color === 'string' ? s.itemStyle.color : typeof s?.lineStyle?.color === 'string' ? s.lineStyle.color : d.colors[i % d.colors.length] }))+ const iw = items.map((it) => 14 + 5 + it.name.length * 6.6 + 16)+ const total = iw.reduce((a, b) => a + b, 0)+ let x = Math.max(8, (d.w - total) / 2)+ const y = d.h - 12+ for (let i = 0; i < items.length; i++) {+ svg.appendChild(elNS('rect', { x, y: y - 9, width: 14, height: 10, rx: 3, fill: items[i].color }))+ svg.appendChild(text(x + 19, y, items[i].name, d.legend!.color, d.font, 12, 'start'))+ x += iw[i]+ }+}++function catWindow(d: Digest, view: View): { cats: string[]; i0: number } {+ const n = Math.max(1, d.categories.length)+ const i0 = Math.min(n - 1, Math.floor(view.start * n))+ const i1 = Math.max(i0 + 1, Math.ceil(view.end * n))+ return { cats: d.categories.slice(i0, i1), i0 }+}++function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: View) {+ const G = d.grid+ const bars = d.series.filter((s) => s?.type === 'bar')+ const lines = d.series.filter((s) => s?.type === 'line')+ const scatters = d.series.filter((s) => s?.type === 'scatter')++ const { cats, i0 } = catWindow(d, view)+ const nCat = Math.max(1, cats.length)++ // y extent across visible data+ let maxY = 0+ let minY = 0+ for (const s of [...bars, ...lines]) {+ const data: number[] = (s.data ?? []).slice(i0, i0 + nCat).map((v: unknown) => num(v, 0))+ for (const v of data) { if (v > maxY) maxY = v; if (v < minY) minY = v }+ }+ let sMinX = Infinity, sMaxX = -Infinity+ for (const s of scatters) {+ for (const p of s.data ?? []) {+ const [px, py] = Array.isArray(p) ? p : [0, 0]+ if (px < sMinX) sMinX = px+ if (px > sMaxX) sMaxX = px+ if (py > maxY) maxY = py+ if (py < minY) minY = py}- } catch {- host.textContent = '⚠ invalid chart option'}- // scripting/diagnostics hook, like window.bento.anim- ;(host as HTMLElement & { __bentoChart?: unknown }).__bentoChart = inst- return () => {- delete (host as HTMLElement & { __bentoChart?: unknown }).__bentoChart- inst.dispose()+ const ticks = niceTicks(Math.min(0, minY), maxY || 1)+ const yLo = ticks[0], yHi = ticks[ticks.length - 1]+ const yOf = (v: number) => G.y + G.h - ((v - yLo) / (yHi - yLo)) * G.h++ // gridlines + y labels+ for (const tv of ticks) {+ const y = yOf(tv)+ svg.appendChild(elNS('line', { x1: G.x, y1: y, x2: G.x + G.w, y2: y, stroke: d.splitLine, 'stroke-width': 1 }))+ svg.appendChild(text(G.x - 8, y + 4, fmt(tv), d.axisLabel, d.font, 12, 'end'))+ }+ // x axis line+ svg.appendChild(elNS('line', { x1: G.x, y1: G.y + G.h, x2: G.x + G.w, y2: G.y + G.h, stroke: d.axisLine, 'stroke-width': 1 }))++ if (scatters.length && !d.categories.length) {+ // value x-axis (scatter)+ const xt = niceTicks(sMinX === Infinity ? 0 : Math.min(0, sMinX), sMaxX === -Infinity ? 1 : sMaxX)+ const span = xt[xt.length - 1] - xt[0]+ const vx0 = xt[0] + span * view.start+ const vx1 = xt[0] + span * view.end+ const xOf = (v: number) => G.x + ((v - vx0) / (vx1 - vx0)) * G.w+ for (const tv of xt) {+ if (tv < vx0 || tv > vx1) continue+ svg.appendChild(text(xOf(tv), G.y + G.h + 18, fmt(tv), d.axisLabel, d.font, 12))+ }+ scatters.forEach((s, si) => {+ const color = typeof s?.itemStyle?.color === 'string' ? s.itemStyle.color : d.colors[si % d.colors.length]+ const r = num(s.symbolSize, 10) / 2+ for (const p of s.data ?? []) {+ const [px, py] = Array.isArray(p) ? p : [0, 0]+ const cx = xOf(px)+ if (cx < G.x - r || cx > G.x + G.w + r) continue+ const c = elNS('circle', { cx, cy: yOf(py), r: r * sweep, fill: color, opacity: 0.85 })+ ;(c as any).__tip = { title: '', rows: [{ name: `${fmt(px)}, ${fmt(py)}`, color }] }+ svg.appendChild(c)+ }+ })+ return+ }++ // category x labels (thinned)+ const band = G.w / nCat+ const step = Math.ceil(nCat / Math.max(1, Math.floor(G.w / 56)))+ cats.forEach((c, i) => {+ if (i % step) return+ svg.appendChild(text(G.x + band * (i + 0.5), G.y + G.h + 18, c, d.axisLabel, d.font, 12))+ })++ // bars+ const m = bars.length+ if (m) {+ const groupW = band * 0.62+ const barW = groupW / m+ bars.forEach((s, si) => {+ const color = typeof s?.itemStyle?.color === 'string' ? s.itemStyle.color : d.colors[d.series.indexOf(s) % d.colors.length]+ const radius = Array.isArray(s?.itemStyle?.borderRadius) ? num(s.itemStyle.borderRadius[0], 0) : num(s?.itemStyle?.borderRadius, 0)+ const data: number[] = (s.data ?? []).slice(i0, i0 + nCat).map((v: unknown) => num(v, 0))+ data.forEach((v, i) => {+ const x = G.x + band * i + (band - groupW) / 2 + barW * si+ const hv = (yOf(yLo) - yOf(v)) * sweep+ const r = elNS('rect', {+ x: x + 1, y: yOf(yLo) - hv, width: Math.max(1, barW - 2), height: Math.max(0, hv),+ rx: Math.min(radius, barW / 2), fill: color,+ })+ ;(r as any).__cat = i+ ;(r as any).__tip = { title: cats[i], rows: [{ name: String(s.name ?? ''), value: fmt(v), color }] }+ svg.appendChild(r)+ })+ })}++ // lines+ lines.forEach((s) => {+ const si = d.series.indexOf(s)+ const stroke = typeof s?.lineStyle?.color === 'string' ? s.lineStyle.color : d.colors[si % d.colors.length]+ const width = num(s?.lineStyle?.width, 2)+ const data: number[] = (s.data ?? []).slice(i0, i0 + nCat).map((v: unknown) => num(v, 0))+ const pts = data.map((v, i) => [G.x + band * (i + 0.5), yOf(v)] as [number, number])+ if (pts.length < 2) return+ let path = `M ${pts[0][0]} ${pts[0][1]}`+ if (s.smooth) {+ for (let i = 0; i < pts.length - 1; i++) {+ const p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)]+ const c1x = p1[0] + (p2[0] - p0[0]) / 6, c1y = p1[1] + (p2[1] - p0[1]) / 6+ const c2x = p2[0] - (p3[0] - p1[0]) / 6, c2y = p2[1] - (p3[1] - p1[1]) / 6+ path += ` C ${c1x} ${c1y} ${c2x} ${c2y} ${p2[0]} ${p2[1]}`+ }+ } else {+ for (let i = 1; i < pts.length; i++) path += ` L ${pts[i][0]} ${pts[i][1]}`+ }+ if (s.areaStyle) {+ const fill = seriesFill(svg, s, stroke)+ const area = elNS('path', {+ d: `${path} L ${pts[pts.length - 1][0]} ${yOf(yLo)} L ${pts[0][0]} ${yOf(yLo)} Z`,+ fill, opacity: s.areaStyle.color ? 1 : 0.25,+ })+ svg.appendChild(area)+ }+ const line = elNS('path', { d: path, fill: 'none', stroke, 'stroke-width': width, 'stroke-linecap': 'round' })+ if (sweep < 1) {+ const len = 2000+ line.setAttribute('stroke-dasharray', String(len))+ line.setAttribute('stroke-dashoffset', String(len * (1 - sweep)))+ }+ svg.appendChild(line)+ if (s.symbol !== 'none') {+ pts.forEach(([cx, cy], i) => {+ const c = elNS('circle', { cx, cy, r: 3.5, fill: stroke, opacity: sweep })+ ;(c as any).__cat = i+ ;(c as any).__tip = { title: cats[i], rows: [{ name: String(s.name ?? ''), value: fmt(data[i]), color: stroke }] }+ svg.appendChild(c)+ })+ }+ })++ // invisible per-category hit bands for axis tooltips+ if (d.tooltipTrigger === 'axis') {+ for (let i = 0; i < nCat; i++) {+ const band_ = elNS('rect', { x: G.x + band * i, y: G.y, width: band, height: G.h, fill: 'transparent' })+ ;(band_ as any).__cat = i+ svg.appendChild(band_)+ }+ }+}++function renderPie(svg: SVGSVGElement, d: Digest, _option: Opt, sweep: number) {+ const s = d.series.find((x) => x?.type === 'pie')!+ const data: Array<{ name: string; value: number }> = (s.data ?? []).map((p: Opt, i: number) => ({+ name: String(p?.name ?? i), value: Math.max(0, num(p?.value, 0)),+ }))+ const total = data.reduce((a, b) => a + b.value, 0) || 1+ const cx = d.grid.w / 2+ const cy = d.grid.h / 2+ const R = Math.min(d.grid.w, d.grid.h) / 2+ const [ri, ro] = (Array.isArray(s.radius) ? s.radius : ['0%', s.radius ?? '70%']).map(+ (r: string | number) => (typeof r === 'string' ? (parseFloat(r) / 100) * R : r),+ )+ const border = s?.itemStyle?.borderColor+ const bw = num(s?.itemStyle?.borderWidth, 0)+ const labelFmt: string | null = s?.label === false ? null : (s?.label?.formatter ?? '{b}')++ let a0 = -Math.PI / 2+ const sweepEnd = -Math.PI / 2 + Math.PI * 2 * sweep+ data.forEach((p, i) => {+ const frac = p.value / total+ let a1 = a0 + frac * Math.PI * 2+ const clip0 = Math.min(a0, sweepEnd)+ const clip1 = Math.min(a1, sweepEnd)+ const color = d.colors[i % d.colors.length]+ if (clip1 > clip0 + 0.0001) {+ svg.appendChild(arcPath(cx, cy, ri, ro, clip0, clip1, color, border, bw, {+ title: '', rows: [{ name: p.name, value: `${fmt(p.value)} (${Math.round((frac) * 1000) / 10}%)`, color }],+ }))+ }+ // labels only at full sweep+ if (sweep >= 1 && labelFmt) {+ const mid = (a0 + a1) / 2+ const lx = cx + Math.cos(mid) * (ro + 12)+ const ly = cy + Math.sin(mid) * (ro + 12)+ const right = Math.cos(mid) >= 0+ const label = labelFmt+ .replaceAll('{b}', p.name)+ .replaceAll('{c}', fmt(p.value))+ .replaceAll('{d}', String(Math.round(frac * 1000) / 10))+ svg.appendChild(elNS('line', {+ x1: cx + Math.cos(mid) * ro, y1: cy + Math.sin(mid) * ro, x2: lx, y2: ly,+ stroke: color, 'stroke-width': 1,+ }))+ svg.appendChild(text(lx + (right ? 4 : -4), ly + 4, label, d.labelColor, d.font, 12, right ? 'start' : 'end'))+ }+ a0 = a1+ })+}++function arcPath(+ cx: number, cy: number, ri: number, ro: number, a0: number, a1: number,+ fill: string, border: string | undefined, bw: number, tip: unknown,+): SVGPathElement {+ const large = a1 - a0 > Math.PI ? 1 : 0+ const p = (r: number, a: number) => `${cx + Math.cos(a) * r} ${cy + Math.sin(a) * r}`+ const dstr =+ `M ${p(ro, a0)} A ${ro} ${ro} 0 ${large} 1 ${p(ro, a1)} ` ++ (ri > 0 ? `L ${p(ri, a1)} A ${ri} ${ri} 0 ${large} 0 ${p(ri, a0)} Z` : `L ${cx} ${cy} Z`)+ const path = elNS('path', { d: dstr, fill })+ if (border && bw) { path.setAttribute('stroke', border); path.setAttribute('stroke-width', String(bw)) }+ ;(path as any).__tip = tip+ return path}-// Snapshots are pure functions of (option, w, h) — cache across re-renders-// (thumbnails re-render often). Keep the cache bounded.-const snapCache = new Map<string, string>()+// --- public API -------------------------------------------------------------++const snapshotCache = new Map<string, string>()-/** Static SVG markup for editor canvas / thumbnails / print. */+/** Static SVG snapshot (string) for canvas/thumbnails/print. */export function chartSnapshotSvg(el: ChartElement): string {const key = `${el.w}x${el.h}:${JSON.stringify(el.option)}`- const hit = snapCache.get(key)+ const hit = snapshotCache.get(key)if (hit) return hit- let svg = ''+ let out: stringtry {- const inst = echarts.init(null as never, undefined, {- renderer: 'svg', ssr: true, width: el.w, height: el.h,- })- inst.setOption({ ...(el.option as object), animation: false } as never)- svg = inst.renderToSVGString()- inst.dispose()+ out = new XMLSerializer().serializeToString(renderChart(el.option as Opt, el.w, el.h))} catch {- svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${el.w}" height="${el.h}"><text x="12" y="24" fill="#c9302c" font-size="14">⚠ invalid chart option</text></svg>`+ out = `<svg xmlns="${SVG_NS}"></svg>`+ }+ if (snapshotCache.size > 60) snapshotCache.clear()+ snapshotCache.set(key, out)+ return out+}++/** Numeric-leaf interpolation between two same-shape options. */+function lerpOption(a: any, b: any, t: number): any {+ if (typeof a === 'number' && typeof b === 'number') return a + (b - a) * t+ if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) return b.map((v, i) => lerpOption(a[i], v, t))+ if (a && b && typeof a === 'object' && typeof b === 'object' && !Array.isArray(a) && !Array.isArray(b)) {+ const out: Opt = { ...b }+ for (const k of Object.keys(b)) if (k in a) out[k] = lerpOption(a[k], b[k], t)+ return out+ }+ return t < 1 ? a ?? b : b+}++const sameShape = (a: Opt, b: Opt): boolean => {+ const ta = (a?.series ?? []).map((s: Opt) => s?.type).join()+ const tb = (b?.series ?? []).map((s: Opt) => s?.type).join()+ return ta === tb+}++/**+ * Live chart for present mode. Returns a dispose handle. With `fromOption`,+ * the chart animates from that state to its own: same series types tween+ * their values in place; a type change (bar⇄pie) plays a staged sweep.+ */+export function mountChart(el: ChartElement, host: HTMLElement, fromOption?: Record<string, unknown>): () => void {+ host.innerHTML = ''+ if (getComputedStyle(host).position === 'static') host.style.position = 'relative'+ const w = el.w, h = el.h+ const option = el.option as Opt+ const view: View = { start: 0, end: 1 }+ let disposed = false+ const clock = { t: 0 } // tween target — killed via killTweensOf(clock)++ const draw = (opt: Opt, sweep = 1) => {+ if (disposed) return+ host.querySelector('svg')?.remove()+ const svg = renderChart(opt, w, h, sweep, view)+ host.prepend(svg)+ wireTooltips(svg, opt)+ }++ // tooltip overlay+ const tipEl = document.createElement('div')+ tipEl.style.cssText =+ 'position:absolute;pointer-events:none;z-index:5;display:none;background:rgba(18,26,40,0.92);color:#fff;' ++ 'font-size:12px;line-height:1.5;padding:6px 10px;border-radius:6px;white-space:nowrap;transform:translate(-50%,-110%)'+ host.appendChild(tipEl)++ const digestNow = () => digest(option, w, h)++ function wireTooltips(svg: SVGSVGElement, opt: Opt) {+ const d = digest(opt, w, h)+ if (!d.tooltipTrigger) return+ svg.addEventListener('mousemove', (ev) => {+ const target = ev.target as Element & { __tip?: any; __cat?: number }+ const rect = host.getBoundingClientRect()+ const sx = rect.width / w+ if (d.tooltipTrigger === 'axis' && typeof target.__cat === 'number') {+ const { cats, i0 } = catWindow(d, view)+ const i = target.__cat+ const rows = d.series+ .filter((s) => s.type !== 'pie')+ .map((s, si) => ({+ name: String(s.name ?? `#${si + 1}`),+ value: fmt(num((s.data ?? [])[i0 + i], 0)),+ color: typeof s?.itemStyle?.color === 'string' ? s.itemStyle.color : d.colors[si % d.colors.length],+ }))+ showTip(cats[i] ?? '', rows, ev.clientX - rect.left, ev.clientY - rect.top, sx)+ } else if (target.__tip) {+ showTip(target.__tip.title, target.__tip.rows, ev.clientX - rect.left, ev.clientY - rect.top, sx)+ } else if (d.tooltipTrigger === 'item') {+ tipEl.style.display = 'none'+ }+ })+ svg.addEventListener('mouseleave', () => { tipEl.style.display = 'none' })+ }++ function showTip(title: string, rows: Array<{ name: string; value?: string; color: string }>, x: number, y: number, _sx: number) {+ tipEl.innerHTML =+ (title ? `<b>${escapeHtml(title)}</b><br>` : '') ++ rows.map((r) =>+ `<span style="display:inline-block;width:8px;height:8px;border-radius:2px;background:${r.color};margin-right:5px"></span>` ++ `${escapeHtml(r.name)}${r.value !== undefined ? `: <b>${escapeHtml(r.value)}</b>` : ''}`,+ ).join('<br>')+ tipEl.style.left = `${x}px`+ tipEl.style.top = `${y - 6}px`+ tipEl.style.display = 'block'+ }++ // inside dataZoom: wheel to zoom, drag to pan+ if (digestNow().zoomable && !digestNow().isPie) {+ host.addEventListener('wheel', (ev) => {+ ev.preventDefault()+ const span = view.end - view.start+ const rect = host.getBoundingClientRect()+ const fx = Math.min(1, Math.max(0, (ev.clientX - rect.left) / rect.width))+ const factor = ev.deltaY > 0 ? 1.18 : 1 / 1.18+ const newSpan = Math.min(1, Math.max(0.1, span * factor))+ const anchor = view.start + span * fx+ view.start = Math.max(0, anchor - newSpan * fx)+ view.end = Math.min(1, view.start + newSpan)+ view.start = Math.max(0, view.end - newSpan)+ draw(option)+ }, { passive: false })+ let panFrom: { x: number; s: number; e: number } | null = null+ host.addEventListener('mousedown', (ev) => { panFrom = { x: ev.clientX, s: view.start, e: view.end } })+ window.addEventListener('mousemove', (ev) => {+ if (!panFrom || disposed) return+ const rect = host.getBoundingClientRect()+ const dx = (ev.clientX - panFrom.x) / rect.width+ const span = panFrom.e - panFrom.s+ let s = panFrom.s - dx * span+ s = Math.max(0, Math.min(1 - span, s))+ view.start = s+ view.end = s + span+ draw(option)+ })+ window.addEventListener('mouseup', () => { panFrom = null })+ }++ // entrance / transition+ if (fromOption && JSON.stringify(fromOption) !== JSON.stringify(option)) {+ if (sameShape(fromOption as Opt, option)) {+ anim.to(clock, {+ t: 1, duration: 0.65, ease: 'power2.inOut',+ onUpdate: () => draw(lerpOption(fromOption, option, clock.t)),+ } as any)+ } else {+ // staged: hold old frame briefly, then sweep the new type in+ draw(fromOption as Opt)+ anim.to(clock, {+ t: 1, duration: 0.8, delay: 0.05, ease: 'power2.inOut',+ onUpdate: () => {+ const t = clock.t+ if (t < 0.3) {+ const s = host.querySelector('svg')+ if (s) (s as SVGElement).style.opacity = String(1 - t / 0.3)+ } else {+ draw(option, (t - 0.3) / 0.7)+ }+ },+ } as any)+ }+ } else {+ draw(option)+ }++ ;(host as HTMLElement & { __bentoChart?: unknown }).__bentoChart = { option, redraw: () => draw(option), view }++ return () => {+ disposed = true+ anim.killTweensOf(clock)+ delete (host as HTMLElement & { __bentoChart?: unknown }).__bentoChart+ host.innerHTML = ''}- if (snapCache.size > 100) snapCache.clear()- snapCache.set(key, svg)- return svg}++const escapeHtml = (s: string): string =>+ s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 03642c20..f1a3a9b3 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -865,10 +865,57 @@ export class Editor {langRow.append(document.createTextNode(t('Language') + ' '), langSel)box.appendChild(langRow)+ // AI round-trip: the document is the interchange unit+ const aiRow = div('ed-about-row')+ const copyB = document.createElement('button')+ copyB.className = 'ed-btn'+ copyB.textContent = t('Copy document JSON')+ copyB.title = t('Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.')+ copyB.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(JSON.stringify(this.store.doc))+ copyB.textContent = t('Copied ✓')+ setTimeout(() => { copyB.textContent = t('Copy document JSON') }, 1600)+ } catch {+ this.toast(t('Couldn’t access the clipboard'))+ }+ })+ const replB = document.createElement('button')+ replB.className = 'ed-btn'+ replB.textContent = t('Replace document from JSON…')+ replB.addEventListener('click', () => {+ if (box.querySelector('.ed-about-json')) return+ const ta = document.createElement('textarea')+ ta.className = 'ed-about-json'+ ta.rows = 5+ ta.placeholder = t('Paste document JSON here…')+ const applyB = document.createElement('button')+ applyB.className = 'ed-btn ed-btn-primary'+ applyB.textContent = t('Apply')+ applyB.addEventListener('click', () => {+ const ok = (window as any).bento?.loadDoc+ ? (window as any).bento.loadDoc(ta.value)+ : false+ if (ok) {+ this.toast(t('Document replaced — ⌘Z undoes'))+ close()+ } else {+ ta.style.borderColor = '#C0392B'+ applyB.textContent = t('Invalid document JSON')+ setTimeout(() => { applyB.textContent = t('Apply') }, 1800)+ }+ })+ box.insertBefore(ta, fine)+ box.insertBefore(applyB, fine)+ ta.focus()+ })+ aiRow.append(copyB, replB)+ box.appendChild(aiRow)+const fine = div('ed-about-fine')fine.innerHTML =`${t('Checks contact the release server and send nothing about you or this document — no ids, no telemetry.')}<br>` +- t('Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.')+ t('Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.')box.appendChild(fine)overlay.appendChild(box)diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.tsindex 3ec23f3e..cf689e9e 100644--- a/slides/src/editor/panels.ts+++ b/slides/src/editor/panels.ts@@ -753,7 +753,7 @@ export class PropsPanel {const hint = document.createElement('p')hint.className = 'ed-hint'- hint.innerHTML = t('The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.')+ hint.innerHTML = t('The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.')this.host.appendChild(hint)const ta = document.createElement('textarea')diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.tsindex 86d61abb..6efda2c0 100644--- a/slides/src/i18n/de.ts+++ b/slides/src/i18n/de.ts@@ -9,6 +9,7 @@ export const de: Catalog = {"Align": "Ausrichten","Ambient": "Ambiente","Angle": "Winkel",+ "Apply": "Anwenden","Arrange": "Anordnen","Arrow": "Pfeil","Background": "Hintergrund",@@ -26,14 +27,18 @@ export const de: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "Prüfungen kontaktieren nur den Release-Server und senden nichts über Sie oder dieses Dokument — keine IDs, keine Telemetrie.","Click to reset": "Klicken zum Zurücksetzen","Color": "Farbe",+ "Comment": "Kommentar","Comment (C) — click an element or a spot on the slide": "Kommentar (C) — Element oder Stelle auf der Folie anklicken","Comment · element": "Kommentar · Element","Comment · point ({x}, {y})": "Kommentar · Punkt ({x}, {y})","Comment · slide": "Kommentar · Folie",- "Comment": "Kommentar","Comment:": "Kommentar:",+ "Copied ✓": "Kopiert ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "Kopiert diese Präsentation als reines JSON — in einen KI-Chat oder ein beliebiges Tool einfügen und das bearbeitete JSON hierher zurückbringen.",+ "Copy document JSON": "Dokument-JSON kopieren","Corner radius": "Eckenradius","Couldn't check: {m}": "Prüfung fehlgeschlagen: {m}",+ "Couldn’t access the clipboard": "Zugriff auf die Zwischenablage nicht möglich","Count up": "Hochzählen","Custom ({n})": "Benutzerdefiniert ({n})","Data": "Daten",@@ -43,6 +48,7 @@ export const de: Catalog = {"Delete this layout": "Dieses Layout löschen","Delete this slide? {parts}.": "Diese Folie löschen? {parts}.","Dissolve the group (⇧⌘G)": "Gruppe auflösen (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "Dokument ersetzt — ⌘Z macht rückgängig","Download updated copy": "Aktualisierte Kopie herunterladen","Downloaded ✓": "Heruntergeladen ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "Lädt ein Backup der aktuellen Version herunter und schreibt diese Datei dann als neue Version — das Dokument bleibt unverändert.",@@ -72,9 +78,10 @@ export const de: Catalog = {"Hover dim": "Hover-Abdunkelung","Hover set:": "Hover-Gruppe:","Image": "Bild",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "Enthält reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces-Schrift (OFL-1.1) — vollständige Hinweise stehen im Quelltext dieser Datei.",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "Enthält reveal.js, Moveable, Selecto (MIT) · Schriften Fraunces + Instrument Sans (OFL-1.1) — vollständige Hinweise stehen im Quelltext dieser Datei.","Insert slide here": "Folie hier einfügen","Interactivity": "Interaktivität",+ "Invalid document JSON": "Ungültiges Dokument-JSON","Language": "Sprache","Launch check couldn't reach the release server ({m}). Check manually below.": "Startprüfung konnte den Release-Server nicht erreichen ({m}). Unten manuell prüfen.","Layout": "Layout",@@ -96,6 +103,7 @@ export const de: Catalog = {"Opacity": "Deckkraft","Opacity %": "Deckkraft %","Open comment(s)": "Kommentar(e) öffnen",+ "Paste document JSON here…": "Dokument-JSON hier einfügen…","Path": "Pfad","Position %": "Position %","Position & size": "Position und Größe",@@ -113,6 +121,7 @@ export const de: Catalog = {"Reload into new version": "Neu laden in die neue Version","Remove stop": "Stopp entfernen","Reopen": "Wieder öffnen",+ "Replace document from JSON…": "Dokument aus JSON ersetzen…","Reply": "Antworten","Reply…": "Antworten…","Reset zoom to fit (⌘0)": "Zoom zurücksetzen (⌘0)",@@ -138,7 +147,7 @@ export const de: Catalog = {"Stroke width": "Konturstärke","Sync from parent slide": "Von der Elternfolie synchronisieren","Text": "Text",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "Die vollständige <b>ECharts-Option</b> als JSON (reine Daten — Vorlagen wie <code>{b}: {c}</code>, niemals Funktionen). Tooltips und Zoom laufen beim Präsentieren.",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "Die vollständige <b>Diagramm-Option</b> als JSON (reine Daten — Vorlagen wie <code>{b}: {c}</code>, niemals Funktionen). Tooltips und Zoom laufen beim Präsentieren.","Thin": "Dünn","This browser can’t rewrite files in place — a fresh copy went to Downloads": "Dieser Browser kann Dateien nicht direkt überschreiben — eine neue Kopie liegt in Downloads","This document": "Dieses Dokument",diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.tsindex feca353b..c1260684 100644--- a/slides/src/i18n/es.ts+++ b/slides/src/i18n/es.ts@@ -9,6 +9,7 @@ export const es: Catalog = {"Align": "Alinear","Ambient": "Ambiente","Angle": "Ángulo",+ "Apply": "Aplicar","Arrange": "Organizar","Arrow": "Flecha","Background": "Fondo",@@ -26,14 +27,18 @@ export const es: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "Las comprobaciones contactan el servidor de versiones sin enviar nada sobre ti ni este documento — sin IDs, sin telemetría.","Click to reset": "Clic para reiniciar","Color": "Color",+ "Comment": "Comentario","Comment (C) — click an element or a spot on the slide": "Comentario (C) — haz clic en un elemento o un punto de la diapositiva","Comment · element": "Comentario · elemento","Comment · point ({x}, {y})": "Comentario · punto ({x}, {y})","Comment · slide": "Comentario · diapositiva",- "Comment": "Comentario","Comment:": "Comentario:",+ "Copied ✓": "Copiado ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "Copia esta presentación como JSON plano — pégalo en un chat de IA o cualquier herramienta y trae aquí el JSON editado.",+ "Copy document JSON": "Copiar JSON del documento","Corner radius": "Radio de esquina","Couldn't check: {m}": "No se pudo comprobar: {m}",+ "Couldn’t access the clipboard": "No se pudo acceder al portapapeles","Count up": "Contador","Custom ({n})": "Personalizado ({n})","Data": "Datos",@@ -43,6 +48,7 @@ export const es: Catalog = {"Delete this layout": "Eliminar este diseño","Delete this slide? {parts}.": "¿Eliminar esta diapositiva? {parts}.","Dissolve the group (⇧⌘G)": "Deshacer el grupo (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "Documento reemplazado — ⌘Z deshace","Download updated copy": "Descargar copia actualizada","Downloaded ✓": "Descargado ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "Descarga una copia de seguridad de la versión actual y reescribe este archivo con la nueva versión — el documento no cambia.",@@ -72,9 +78,10 @@ export const es: Catalog = {"Hover dim": "Atenuación hover","Hover set:": "Grupo hover:","Image": "Imagen",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "Incluye reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · tipografía Fraunces (OFL-1.1) — los avisos completos viajan en el código de este archivo.",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "Incluye reveal.js, Moveable, Selecto (MIT) · tipografías Fraunces + Instrument Sans (OFL-1.1) — los avisos completos viajan en el código de este archivo.","Insert slide here": "Insertar diapositiva aquí","Interactivity": "Interactividad",+ "Invalid document JSON": "JSON de documento no válido","Language": "Idioma","Launch check couldn't reach the release server ({m}). Check manually below.": "La comprobación inicial no alcanzó el servidor ({m}). Comprueba manualmente abajo.","Layout": "Diseño",@@ -96,6 +103,7 @@ export const es: Catalog = {"Opacity": "Opacidad","Opacity %": "Opacidad %","Open comment(s)": "Abrir comentario(s)",+ "Paste document JSON here…": "Pega aquí el JSON del documento…","Path": "Trazado","Position %": "Posición %","Position & size": "Posición y tamaño",@@ -113,6 +121,7 @@ export const es: Catalog = {"Reload into new version": "Recargar en la nueva versión","Remove stop": "Quitar parada","Reopen": "Reabrir",+ "Replace document from JSON…": "Reemplazar documento desde JSON…","Reply": "Responder","Reply…": "Responder…","Reset zoom to fit (⌘0)": "Restablecer zoom para ajustar (⌘0)",@@ -138,7 +147,7 @@ export const es: Catalog = {"Stroke width": "Grosor de trazo","Sync from parent slide": "Sincronizar desde la diapositiva padre","Text": "Texto",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "La <b>opción de ECharts</b> completa como JSON (datos puros — usa plantillas como <code>{b}: {c}</code>, nunca funciones). Los tooltips y el zoom funcionan al presentar.",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "La <b>opción del gráfico</b> completa como JSON (datos puros — usa plantillas como <code>{b}: {c}</code>, nunca funciones). Los tooltips y el zoom funcionan al presentar.","Thin": "Muy fina","This browser can’t rewrite files in place — a fresh copy went to Downloads": "Este navegador no puede reescribir archivos en el sitio — una copia nueva fue a Descargas","This document": "Este documento",diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.tsindex 5d3cf161..7752f9ba 100644--- a/slides/src/i18n/fr.ts+++ b/slides/src/i18n/fr.ts@@ -9,6 +9,7 @@ export const fr: Catalog = {"Align": "Aligner","Ambient": "Ambiance","Angle": "Angle",+ "Apply": "Appliquer","Arrange": "Disposition","Arrow": "Flèche","Background": "Arrière-plan",@@ -26,14 +27,18 @@ export const fr: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "Les vérifications contactent le serveur de versions sans rien envoyer sur vous ni ce document — pas d'ID, pas de télémétrie.","Click to reset": "Cliquer pour réinitialiser","Color": "Couleur",+ "Comment": "Commentaire","Comment (C) — click an element or a spot on the slide": "Commentaire (C) — cliquez sur un élément ou un point de la diapositive","Comment · element": "Commentaire · élément","Comment · point ({x}, {y})": "Commentaire · point ({x}, {y})","Comment · slide": "Commentaire · diapositive",- "Comment": "Commentaire","Comment:": "Commentaire :",+ "Copied ✓": "Copié ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "Copie cette présentation en JSON brut — collez-le dans un chat IA ou tout autre outil, puis rapportez ici le JSON modifié.",+ "Copy document JSON": "Copier le JSON du document","Corner radius": "Rayon d'angle","Couldn't check: {m}": "Vérification impossible : {m}",+ "Couldn’t access the clipboard": "Impossible d'accéder au presse-papiers","Count up": "Compteur","Custom ({n})": "Personnalisé ({n})","Data": "Données",@@ -43,6 +48,7 @@ export const fr: Catalog = {"Delete this layout": "Supprimer cette disposition","Delete this slide? {parts}.": "Supprimer cette diapositive ? {parts}.","Dissolve the group (⇧⌘G)": "Dissoudre le groupe (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "Document remplacé — ⌘Z annule","Download updated copy": "Télécharger la copie à jour","Downloaded ✓": "Téléchargé ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "Télécharge une sauvegarde de la version actuelle, puis réécrit ce fichier avec la nouvelle version — document intact.",@@ -72,9 +78,10 @@ export const fr: Catalog = {"Hover dim": "Atténuation au survol","Hover set:": "Groupe de survol :","Image": "Image",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "Inclut reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · police Fraunces (OFL-1.1) — les mentions complètes voyagent dans la source de ce fichier.",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "Inclut reveal.js, Moveable, Selecto (MIT) · polices Fraunces + Instrument Sans (OFL-1.1) — les mentions complètes voyagent dans la source de ce fichier.","Insert slide here": "Insérer une diapositive ici","Interactivity": "Interactivité",+ "Invalid document JSON": "JSON de document invalide","Language": "Langue","Launch check couldn't reach the release server ({m}). Check manually below.": "La vérification au démarrage n'a pas atteint le serveur ({m}). Vérifiez manuellement ci-dessous.","Layout": "Disposition",@@ -96,6 +103,7 @@ export const fr: Catalog = {"Opacity": "Opacité","Opacity %": "Opacité %","Open comment(s)": "Ouvrir le(s) commentaire(s)",+ "Paste document JSON here…": "Collez le JSON du document ici…","Path": "Tracé","Position %": "Position %","Position & size": "Position et taille",@@ -113,6 +121,7 @@ export const fr: Catalog = {"Reload into new version": "Recharger dans la nouvelle version","Remove stop": "Retirer l'étape","Reopen": "Rouvrir",+ "Replace document from JSON…": "Remplacer le document depuis JSON…","Reply": "Répondre","Reply…": "Répondre…","Reset zoom to fit (⌘0)": "Réinitialiser le zoom (⌘0)",@@ -138,7 +147,7 @@ export const fr: Catalog = {"Stroke width": "Épaisseur de contour","Sync from parent slide": "Synchroniser depuis la diapositive parente","Text": "Texte",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "L'<b>option ECharts</b> complète en JSON (données pures — modèles comme <code>{b}: {c}</code>, jamais de fonctions). Infobulles et zoom actifs en présentation.",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "L'<b>option du graphique</b> complète en JSON (données pures — modèles comme <code>{b}: {c}</code>, jamais de fonctions). Infobulles et zoom actifs en présentation.","Thin": "Très fin","This browser can’t rewrite files in place — a fresh copy went to Downloads": "Ce navigateur ne peut pas réécrire les fichiers sur place — une copie est allée dans Téléchargements","This document": "Ce document",diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.tsindex b77a6c7f..f08d0dd4 100644--- a/slides/src/i18n/it.ts+++ b/slides/src/i18n/it.ts@@ -9,6 +9,7 @@ export const it: Catalog = {"Align": "Allinea","Ambient": "Ambiente","Angle": "Angolo",+ "Apply": "Applica","Arrange": "Disponi","Arrow": "Freccia","Background": "Sfondo",@@ -26,14 +27,18 @@ export const it: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "Le verifiche contattano il server delle versioni senza inviare nulla su di te o su questo documento — niente ID, niente telemetria.","Click to reset": "Clic per azzerare","Color": "Colore",+ "Comment": "Commento","Comment (C) — click an element or a spot on the slide": "Commento (C) — fai clic su un elemento o un punto della diapositiva","Comment · element": "Commento · elemento","Comment · point ({x}, {y})": "Commento · punto ({x}, {y})","Comment · slide": "Commento · diapositiva",- "Comment": "Commento","Comment:": "Commento:",+ "Copied ✓": "Copiato ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "Copia questa presentazione come JSON puro — incollalo in una chat IA o in qualsiasi strumento, poi riporta qui il JSON modificato.",+ "Copy document JSON": "Copia JSON del documento","Corner radius": "Raggio angoli","Couldn't check: {m}": "Verifica non riuscita: {m}",+ "Couldn’t access the clipboard": "Impossibile accedere agli appunti","Count up": "Conteggio","Custom ({n})": "Personalizzato ({n})","Data": "Dati",@@ -43,6 +48,7 @@ export const it: Catalog = {"Delete this layout": "Elimina questo layout","Delete this slide? {parts}.": "Eliminare questa diapositiva? {parts}.","Dissolve the group (⇧⌘G)": "Sciogli il gruppo (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "Documento sostituito — ⌘Z annulla","Download updated copy": "Scarica copia aggiornata","Downloaded ✓": "Scaricato ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "Scarica un backup della versione attuale, poi riscrive questo file come nuova versione — documento intatto.",@@ -72,9 +78,10 @@ export const it: Catalog = {"Hover dim": "Attenuazione hover","Hover set:": "Gruppo hover:","Image": "Immagine",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "Include reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · carattere Fraunces (OFL-1.1) — le note complete viaggiano nel sorgente di questo file.",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "Include reveal.js, Moveable, Selecto (MIT) · caratteri Fraunces + Instrument Sans (OFL-1.1) — le note complete viaggiano nel sorgente di questo file.","Insert slide here": "Inserisci diapositiva qui","Interactivity": "Interattività",+ "Invalid document JSON": "JSON del documento non valido","Language": "Lingua","Launch check couldn't reach the release server ({m}). Check manually below.": "La verifica all'avvio non ha raggiunto il server ({m}). Verifica manualmente qui sotto.","Layout": "Layout",@@ -96,6 +103,7 @@ export const it: Catalog = {"Opacity": "Opacità","Opacity %": "Opacità %","Open comment(s)": "Apri commento/i",+ "Paste document JSON here…": "Incolla qui il JSON del documento…","Path": "Tracciato","Position %": "Posizione %","Position & size": "Posizione e dimensioni",@@ -113,6 +121,7 @@ export const it: Catalog = {"Reload into new version": "Ricarica nella nuova versione","Remove stop": "Rimuovi stop","Reopen": "Riapri",+ "Replace document from JSON…": "Sostituisci documento da JSON…","Reply": "Rispondi","Reply…": "Rispondi…","Reset zoom to fit (⌘0)": "Azzera lo zoom (⌘0)",@@ -138,7 +147,7 @@ export const it: Catalog = {"Stroke width": "Spessore tratto","Sync from parent slide": "Sincronizza dalla diapositiva padre","Text": "Testo",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "L'<b>opzione ECharts</b> completa in JSON (dati puri — usa template come <code>{b}: {c}</code>, mai funzioni). Tooltip e zoom attivi durante la presentazione.",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "L'<b>opzione del grafico</b> completa in JSON (dati puri — usa template come <code>{b}: {c}</code>, mai funzioni). Tooltip e zoom attivi durante la presentazione.","Thin": "Sottile","This browser can’t rewrite files in place — a fresh copy went to Downloads": "Questo browser non può riscrivere i file sul posto — una nuova copia è in Download","This document": "Questo documento",diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.tsindex d4a11790..09094618 100644--- a/slides/src/i18n/ja.ts+++ b/slides/src/i18n/ja.ts@@ -9,6 +9,7 @@ export const ja: Catalog = {"Align": "整列","Ambient": "アンビエント","Angle": "角度",+ "Apply": "適用","Arrange": "配置","Arrow": "矢印","Background": "背景",@@ -26,14 +27,18 @@ export const ja: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "確認はリリースサーバーへの接続のみで、あなたやこのドキュメントの情報は一切送信しません — ID もテレメトリーもなし。","Click to reset": "クリックでリセット","Color": "色",+ "Comment": "コメント","Comment (C) — click an element or a spot on the slide": "コメント (C) — 要素またはスライド上の位置をクリック","Comment · element": "コメント · 要素","Comment · point ({x}, {y})": "コメント · 位置 ({x}, {y})","Comment · slide": "コメント · スライド",- "Comment": "コメント","Comment:": "コメント:",+ "Copied ✓": "コピーしました ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "このデッキをプレーン JSON としてコピーします — AI チャットや任意のツールに貼り付け、編集した JSON をここに戻してください。",+ "Copy document JSON": "ドキュメント JSON をコピー","Corner radius": "角丸","Couldn't check: {m}": "確認できませんでした: {m}",+ "Couldn’t access the clipboard": "クリップボードにアクセスできませんでした","Count up": "カウントアップ","Custom ({n})": "カスタム ({n})","Data": "データ",@@ -43,6 +48,7 @@ export const ja: Catalog = {"Delete this layout": "このレイアウトを削除","Delete this slide? {parts}.": "このスライドを削除しますか? {parts}。","Dissolve the group (⇧⌘G)": "グループを解除 (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "ドキュメントを置き換えました — ⌘Z で元に戻せます","Download updated copy": "更新版をダウンロード","Downloaded ✓": "ダウンロード完了 ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "現在のバージョンのバックアップをダウンロードしてから、このファイルを新バージョンに書き換えます — ドキュメントはそのまま。",@@ -72,9 +78,10 @@ export const ja: Catalog = {"Hover dim": "ホバー減光","Hover set:": "ホバーセット:","Image": "画像",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "reveal.js・Moveable・Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces 書体 (OFL-1.1) を含みます — 完全な表記はこのファイルのソース内にあります。",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "reveal.js・Moveable・Selecto (MIT) · Fraunces + Instrument Sans 書体 (OFL-1.1) を含みます — 完全な表記はこのファイルのソース内にあります。","Insert slide here": "ここにスライドを挿入","Interactivity": "インタラクティブ",+ "Invalid document JSON": "無効なドキュメント JSON","Language": "言語","Launch check couldn't reach the release server ({m}). Check manually below.": "起動時の確認でリリースサーバーに接続できませんでした ({m})。下から手動で確認してください。","Layout": "レイアウト",@@ -96,6 +103,7 @@ export const ja: Catalog = {"Opacity": "不透明度","Opacity %": "不透明度 %","Open comment(s)": "コメントを開く",+ "Paste document JSON here…": "ここにドキュメント JSON を貼り付け…","Path": "パス","Position %": "位置 %","Position & size": "位置とサイズ",@@ -113,6 +121,7 @@ export const ja: Catalog = {"Reload into new version": "再読込して新バージョンへ","Remove stop": "ストップを削除","Reopen": "再オープン",+ "Replace document from JSON…": "JSON からドキュメントを置き換え…","Reply": "返信","Reply…": "返信…","Reset zoom to fit (⌘0)": "ズームをフィットに戻す (⌘0)",@@ -138,7 +147,7 @@ export const ja: Catalog = {"Stroke width": "線幅","Sync from parent slide": "親スライドから同期","Text": "テキスト",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "<b>ECharts オプション</b>全体を JSON で(純データ — <code>{b}: {c}</code> のようなテンプレート文字列を使用、関数は不可)。ツールチップとズームはプレゼン中に動作。",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "<b>チャートオプション</b>全体を JSON で(純データ — <code>{b}: {c}</code> のようなテンプレート文字列を使用、関数は不可)。ツールチップとズームはプレゼン中に動作。","Thin": "シン","This browser can’t rewrite files in place — a fresh copy went to Downloads": "このブラウザはファイルの直接書き換えに未対応 — 新しいコピーをダウンロードしました","This document": "このドキュメント",diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.tsindex c939151a..e043497c 100644--- a/slides/src/i18n/zh-Hans.ts+++ b/slides/src/i18n/zh-Hans.ts@@ -9,6 +9,7 @@ export const zhHans: Catalog = {"Align": "对齐","Ambient": "氛围","Angle": "角度",+ "Apply": "应用","Arrange": "排列","Arrow": "箭头","Background": "背景",@@ -26,14 +27,18 @@ export const zhHans: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "检查仅连接发布服务器,不发送任何关于您或此文档的信息 — 无 ID,无遥测。","Click to reset": "点击重置","Color": "颜色",+ "Comment": "评论","Comment (C) — click an element or a spot on the slide": "评论 (C) — 点击元素或幻灯片上的位置","Comment · element": "评论 · 元素","Comment · point ({x}, {y})": "评论 · 位置 ({x}, {y})","Comment · slide": "评论 · 幻灯片",- "Comment": "评论","Comment:": "评论:",+ "Copied ✓": "已复制 ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "将此演示文稿复制为纯 JSON — 粘贴到 AI 聊天或任何工具中,再把编辑后的 JSON 带回这里。",+ "Copy document JSON": "复制文档 JSON","Corner radius": "圆角","Couldn't check: {m}": "无法检查:{m}",+ "Couldn’t access the clipboard": "无法访问剪贴板","Count up": "数字递增","Custom ({n})": "自定义 ({n})","Data": "数据",@@ -43,6 +48,7 @@ export const zhHans: Catalog = {"Delete this layout": "删除此版式","Delete this slide? {parts}.": "删除此幻灯片?{parts}。","Dissolve the group (⇧⌘G)": "取消编组 (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "文档已替换 — ⌘Z 可撤销","Download updated copy": "下载更新副本","Downloaded ✓": "已下载 ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "先下载当前版本的备份,然后将此文件改写为新版本 — 文档内容不变。",@@ -72,9 +78,10 @@ export const zhHans: Catalog = {"Hover dim": "悬停变暗","Hover set:": "悬停组:","Image": "图片",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "包含 reveal.js、Moveable、Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces 字体 (OFL-1.1) — 完整声明位于此文件源码中。",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "包含 reveal.js、Moveable、Selecto (MIT) · Fraunces + Instrument Sans 字体 (OFL-1.1) — 完整声明位于此文件源码中。","Insert slide here": "在此插入幻灯片","Interactivity": "交互",+ "Invalid document JSON": "无效的文档 JSON","Language": "语言","Launch check couldn't reach the release server ({m}). Check manually below.": "启动检查无法连接发布服务器 ({m})。请在下方手动检查。","Layout": "版式",@@ -96,6 +103,7 @@ export const zhHans: Catalog = {"Opacity": "不透明度","Opacity %": "不透明度 %","Open comment(s)": "打开评论",+ "Paste document JSON here…": "在此粘贴文档 JSON…","Path": "路径","Position %": "位置 %","Position & size": "位置与大小",@@ -113,6 +121,7 @@ export const zhHans: Catalog = {"Reload into new version": "重新加载进入新版本","Remove stop": "删除色标","Reopen": "重新打开",+ "Replace document from JSON…": "从 JSON 替换文档…","Reply": "回复","Reply…": "回复…","Reset zoom to fit (⌘0)": "重置缩放以适应 (⌘0)",@@ -138,7 +147,7 @@ export const zhHans: Catalog = {"Stroke width": "描边宽度","Sync from parent slide": "从父幻灯片同步","Text": "文本",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "完整的 <b>ECharts 配置</b>(纯数据 JSON — 使用 <code>{b}: {c}</code> 这样的模板字符串,不能用函数)。提示框和缩放在演示时生效。",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "完整的<b>图表配置</b>(纯数据 JSON — 使用 <code>{b}: {c}</code> 这样的模板字符串,不能用函数)。提示框和缩放在演示时生效。","Thin": "极细","This browser can’t rewrite files in place — a fresh copy went to Downloads": "此浏览器无法就地改写文件 — 新副本已存入下载","This document": "此文档",diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.tsindex 8103fddf..5e63fe0c 100644--- a/slides/src/i18n/zh-Hant.ts+++ b/slides/src/i18n/zh-Hant.ts@@ -9,6 +9,7 @@ export const zhHant: Catalog = {"Align": "對齊","Ambient": "氛圍","Angle": "角度",+ "Apply": "套用","Arrange": "排列","Arrow": "箭頭","Background": "背景",@@ -26,14 +27,18 @@ export const zhHant: Catalog = {"Checks contact the release server and send nothing about you or this document — no ids, no telemetry.": "檢查僅連線發佈伺服器,不會傳送任何關於您或此文件的資訊 — 無 ID,無遙測。","Click to reset": "點按以重設","Color": "顏色",+ "Comment": "註解","Comment (C) — click an element or a spot on the slide": "註解 (C) — 點按元素或投影片上的位置","Comment · element": "註解 · 元素","Comment · point ({x}, {y})": "註解 · 位置 ({x}, {y})","Comment · slide": "註解 · 投影片",- "Comment": "註解","Comment:": "註解:",+ "Copied ✓": "已複製 ✓",+ "Copies this deck as plain JSON — paste it into an AI chat or any tool, then bring the edited JSON back here.": "將此簡報複製為純 JSON — 貼到 AI 聊天或任何工具中,再把編輯後的 JSON 帶回這裡。",+ "Copy document JSON": "複製文件 JSON","Corner radius": "圓角","Couldn't check: {m}": "無法檢查:{m}",+ "Couldn’t access the clipboard": "無法存取剪貼簿","Count up": "數字遞增","Custom ({n})": "自訂 ({n})","Data": "資料",@@ -43,6 +48,7 @@ export const zhHant: Catalog = {"Delete this layout": "刪除此版面配置","Delete this slide? {parts}.": "刪除此投影片?{parts}。","Dissolve the group (⇧⌘G)": "解散群組 (⇧⌘G)",+ "Document replaced — ⌘Z undoes": "文件已取代 — ⌘Z 可還原","Download updated copy": "下載更新副本","Downloaded ✓": "已下載 ✓","Downloads a backup of the current version, then rewrites this file on disk as the new version — document untouched.": "先下載目前版本的備份,再將此檔案改寫為新版本 — 文件內容不變。",@@ -72,9 +78,10 @@ export const zhHant: Catalog = {"Hover dim": "懸停變暗","Hover set:": "懸停組:","Image": "影像",- "Includes reveal.js, Moveable, Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces typeface (OFL-1.1) — full notices travel in this file’s source.": "包含 reveal.js、Moveable、Selecto (MIT) · Apache ECharts (Apache-2.0) · zrender (BSD-3) · Fraunces 字型 (OFL-1.1) — 完整聲明位於此檔案原始碼中。",+ "Includes reveal.js, Moveable, Selecto (MIT) · Fraunces + Instrument Sans typefaces (OFL-1.1) — full notices travel in this file’s source.": "包含 reveal.js、Moveable、Selecto (MIT) · Fraunces + Instrument Sans 字型 (OFL-1.1) — 完整聲明位於此檔案原始碼中。","Insert slide here": "在此插入投影片","Interactivity": "互動",+ "Invalid document JSON": "無效的文件 JSON","Language": "語言","Launch check couldn't reach the release server ({m}). Check manually below.": "啟動檢查無法連線發佈伺服器 ({m})。請在下方手動檢查。","Layout": "版面配置",@@ -96,6 +103,7 @@ export const zhHant: Catalog = {"Opacity": "不透明度","Opacity %": "不透明度 %","Open comment(s)": "開啟註解",+ "Paste document JSON here…": "在此貼上文件 JSON…","Path": "路徑","Position %": "位置 %","Position & size": "位置與大小",@@ -113,6 +121,7 @@ export const zhHant: Catalog = {"Reload into new version": "重新載入進入新版本","Remove stop": "移除色標","Reopen": "重新開啟",+ "Replace document from JSON…": "從 JSON 取代文件…","Reply": "回覆","Reply…": "回覆…","Reset zoom to fit (⌘0)": "重設縮放以符合 (⌘0)",@@ -138,7 +147,7 @@ export const zhHant: Catalog = {"Stroke width": "筆畫寬度","Sync from parent slide": "從父投影片同步","Text": "文字",- "The full <b>ECharts option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "完整的 <b>ECharts 選項</b>(純資料 JSON — 使用 <code>{b}: {c}</code> 這類樣板字串,不能用函式)。提示框與縮放在簡報時生效。",+ "The full <b>chart option</b> as JSON (pure data — use template-string formatters like <code>{b}: {c}</code>, never functions). Tooltips and zoom run while presenting.": "完整的<b>圖表選項</b>(純資料 JSON — 使用 <code>{b}: {c}</code> 這類樣板字串,不能用函式)。提示框與縮放在簡報時生效。","Thin": "極細","This browser can’t rewrite files in place — a fresh copy went to Downloads": "此瀏覽器無法就地改寫檔案 — 新副本已存入下載項目","This document": "此文件",diff --git a/slides/src/main.ts b/slides/src/main.tsindex 4a14fa95..cfc394e5 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -63,6 +63,17 @@ if (location.hash === '#present') {anim,/** i18n: t/locale/setLocale/choices — setLocale('x-pseudo') audits the sweep */i18n: i18nApi,+ /**+ * AI/tooling round-trip: replace the whole document from a JSON string+ * (the contents of #bento-doc). Validates via parseDoc; returns false and+ * changes nothing on invalid input. Undoable in the editor.+ */+ loadDoc(json: string): boolean {+ const next = parseDoc(json)+ if (!next) return false+ store.replaceDoc(next)+ return true+ },/*** Self-update surface (all user/tooling-initiated, never automatic):* check() fetches + signature-verifies the release manifest; build()diff --git a/slides/src/store.ts b/slides/src/store.tsindex 820db4dc..b4063fc0 100644--- a/slides/src/store.ts+++ b/slides/src/store.ts@@ -52,6 +52,22 @@ export class Store {.filter((e): e is SlideElement => !!e)}+ /**+ * Replace the whole document (AI/JSON round-trip import). Undoable —+ * ⌘Z restores the previous document wholesale.+ */+ replaceDoc(next: BentoDoc) {+ this.checkpoint()+ this.doc = next+ this.currentIndex = 0+ this.selection = []+ this.setDirty(true)+ this.emit('slides')+ this.emit('current')+ this.emit('selection')+ this.emit('doc')+ }+// --- history ------------------------------------------------------------/** Snapshot current doc state onto the undo stack. Call BEFORE a mutation. */diff --git a/slides/src/styles.css b/slides/src/styles.cssindex ff413e8f..1bf55957 100644--- a/slides/src/styles.css+++ b/slides/src/styles.css@@ -496,6 +496,14 @@ html, body {max-height: 140px;overflow: auto;}+.ed-about-json {+ width: 100%;+ font: 11px/1.4 ui-monospace, Menlo, monospace;+ border: 1px solid var(--line);+ border-radius: 8px;+ padding: 8px;+ resize: vertical;+}.ed-about-fine {font-size: 10.5px;line-height: 1.5;