Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

ECharts chart elements: interactive data charts in the format

nyblnetd2220ee89ef5
diff --git a/CLAUDE.md b/CLAUDE.md
index c540e861..8d1c79bc 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,6 +31,15 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
visually on canvas (`editor/patheditor.ts`): draggable anchors auto-smoothed
Catmull-Rom→cubic bezier; the stored path is RELATIVE to the element's rest
position (first anchor = rest position; committing moves the element there).
+- `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.
- **Diagram philosophy**: complex diagrams are ordinary Bento elements (rects, texts,
`path` shapes) with groups — interactivity = linked state slides + morph (filters,
era sequences), hover = focus-group, motion = fx.loop. Opaque `svg` elements are
diff --git a/slides/index.html b/slides/index.html
index 7ae72503..2f6a897f 100644
--- a/slides/index.html
+++ b/slides/index.html
@@ -14,6 +14,11 @@
reveal.js — Copyright (C) Hakim El Hattab and contributors — MIT License
moveable, 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 License
MIT License: Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files (the
diff --git a/slides/package-lock.json b/slides/package-lock.json
index fba6b2d4..ac861c54 100644
--- a/slides/package-lock.json
+++ b/slides/package-lock.json
@@ -8,6 +8,7 @@
"name": "bento-slides",
"version": "0.1.0",
"dependencies": {
+ "echarts": "^6.1.0",
"moveable": "^0.53.0",
"reveal.js": "^5.2.1",
"selecto": "^1.26.3"
@@ -1023,6 +1024,16 @@
"@scena/matrix": "^1.0.0"
}
},
+ "node_modules/echarts": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz",
+ "integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "tslib": "2.3.0",
+ "zrender": "6.1.0"
+ }
+ },
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
@@ -1424,6 +1435,12 @@
"node": ">=8.0"
}
},
+ "node_modules/tslib": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
+ "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==",
+ "license": "0BSD"
+ },
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
@@ -1541,6 +1558,15 @@
"optional": true
}
}
+ },
+ "node_modules/zrender": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz",
+ "integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tslib": "2.3.0"
+ }
}
}
}
diff --git a/slides/package.json b/slides/package.json
index f76ee764..87dbb24d 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -10,6 +10,7 @@
"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.ts
new file mode 100644
index 00000000..53e06000
--- /dev/null
+++ b/slides/src/charts.ts
@@ -0,0 +1,119 @@
+// 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 type { ChartElement } from './model'
+
+echarts.use([
+ BarChart, LineChart, PieChart, ScatterChart,
+ DatasetComponent, DataZoomComponent, GridComponent,
+ LegendComponent, TitleComponent, TooltipComponent,
+ SVGRenderer,
+])
+
+/** Presets seed new charts and let the panel swap types without data loss. */
+export const CHART_PRESETS: Record<string, () => Record<string, unknown>> = {
+ bar: () => ({
+ tooltip: { trigger: 'axis' },
+ legend: { bottom: 0 },
+ grid: { left: 56, right: 20, top: 24, bottom: 56 },
+ xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] },
+ yAxis: { type: 'value' },
+ dataZoom: [{ type: 'inside' }],
+ series: [
+ { type: 'bar', name: 'Series A', data: [12, 20, 15, 28] },
+ { type: 'bar', name: 'Series B', data: [8, 14, 19, 21] },
+ ],
+ }),
+ line: () => ({
+ tooltip: { trigger: 'axis' },
+ legend: { bottom: 0 },
+ grid: { left: 56, right: 20, top: 24, bottom: 56 },
+ xAxis: { type: 'category', data: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] },
+ yAxis: { type: 'value' },
+ dataZoom: [{ type: 'inside' }],
+ series: [{ type: 'line', name: 'Trend', smooth: true, areaStyle: {}, data: [4, 7, 6, 11, 14, 18] }],
+ }),
+ pie: () => ({
+ tooltip: { trigger: 'item' },
+ legend: { bottom: 0 },
+ series: [{
+ type: 'pie', radius: ['38%', '68%'],
+ label: { formatter: '{b}: {d}%' },
+ data: [
+ { name: 'Alpha', value: 42 }, { name: 'Beta', value: 28 },
+ { name: 'Gamma', value: 18 }, { name: 'Delta', value: 12 },
+ ],
+ }],
+ }),
+ scatter: () => ({
+ tooltip: { trigger: 'item' },
+ grid: { left: 56, right: 20, top: 24, bottom: 40 },
+ xAxis: { type: 'value' },
+ yAxis: { type: 'value' },
+ dataZoom: [{ type: 'inside' }, { type: 'inside', orient: 'vertical' }],
+ series: [{
+ type: 'scatter', symbolSize: 14,
+ data: [[10, 8], [15, 12], [22, 10], [28, 19], [34, 15], [41, 25], [48, 22]],
+ }],
+ }),
+}
+
+/** Live instance for present mode. Returns a dispose handle. */
+export function mountChart(el: ChartElement, host: HTMLElement): () => void {
+ host.innerHTML = ''
+ const inst = echarts.init(host, undefined, { renderer: 'svg', width: el.w, height: el.h })
+ try {
+ inst.setOption(el.option as never)
+ } 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()
+ }
+}
+
+// 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>()
+
+/** Static SVG markup for editor 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)
+ if (hit) return hit
+ let svg = ''
+ try {
+ 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()
+ } 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>`
+ }
+ if (snapCache.size > 100) snapCache.clear()
+ snapCache.set(key, svg)
+ return svg
+}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index c77fc57a..f7e1bd35 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -3,9 +3,10 @@
import type { Store } from '../store'
import {
- defaultImage, defaultShape, defaultText, emptySlide, uid,
+ defaultChart, defaultImage, defaultShape, defaultText, emptySlide, uid,
type ShapeKind, type SlideElement,
} from '../model'
+import { CHART_PRESETS } from '../charts'
import { renderSlide, renderThumbnail } from '../render'
import { SlideCanvas } from './canvas'
import { PropsPanel } from './panels'
@@ -83,6 +84,7 @@ export class Editor {
btn(ICONS.text, 'Text', () => this.canvas.insert(defaultText({ y: 120 + Math.random() * 200 }), true)),
this.shapeDropdown(),
btn(ICONS.image, 'Image', () => this.pickImage()),
+ btn('📊', 'Chart', () => this.canvas.insert(defaultChart(CHART_PRESETS.bar()))),
)
const actions = div('ed-group ed-group-right')
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 0dc880d2..5d9193b7 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -3,7 +3,8 @@
// into a single undo checkpoint.
import type { Store } from '../store'
-import { uid, type ShapeElement, type SlideElement, type TextElement, type TransitionKind } from '../model'
+import { uid, type ChartElement, type ShapeElement, type SlideElement, type TextElement, type TransitionKind } from '../model'
+import { CHART_PRESETS } from '../charts'
import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'
import { ICONS } from '../icons'
@@ -165,7 +166,7 @@ export class PropsPanel {
}
private buildElementPanel(el: SlideElement) {
- this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram' }[el.type])
+ this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram', chart: 'Chart' }[el.type])
this.opsRow([el])
// geometry
@@ -185,6 +186,7 @@ export class PropsPanel {
if (el.type === 'text') this.buildTextProps(el)
if (el.type === 'shape') this.buildShapeProps(el)
if (el.type === 'image') this.buildImageProps(el)
+ if (el.type === 'chart') this.buildChartProps(el)
this.buildPresentingProps(el)
@@ -583,6 +585,37 @@ export class PropsPanel {
}
}
+ private buildChartProps(el: ChartElement) {
+ this.section('Data')
+ this.row('Preset', this.select(Object.keys(CHART_PRESETS), el.preset ?? 'bar', (v) =>
+ this.mutate(el.id, (e) => {
+ const c = e as ChartElement
+ c.preset = v
+ c.option = CHART_PRESETS[v]()
+ }, true)))
+
+ const hint = document.createElement('p')
+ hint.className = 'ed-hint'
+ hint.innerHTML = '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.'
+ this.host.appendChild(hint)
+
+ const ta = document.createElement('textarea')
+ ta.className = 'ed-chart-json'
+ ta.rows = 14
+ ta.spellcheck = false
+ ta.value = JSON.stringify(el.option, null, 2)
+ ta.addEventListener('change', () => {
+ try {
+ const parsed = JSON.parse(ta.value)
+ ta.classList.remove('ed-invalid')
+ this.mutate(el.id, (e) => { (e as ChartElement).option = parsed }, true)
+ } catch {
+ ta.classList.add('ed-invalid')
+ }
+ })
+ this.host.appendChild(ta)
+ }
+
private buildImageProps(el: SlideElement) {
this.section('Image')
this.row('Fit', this.select(['contain', 'cover', 'fill'], (el as any).fit, (v) =>
diff --git a/slides/src/model.ts b/slides/src/model.ts
index f73765f8..a6745289 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -120,7 +120,20 @@ export interface SvgElement extends ElementBase {
css?: string
}
-export type SlideElement = TextElement | ShapeElement | ImageElement | SvgElement
+/**
+ * Data chart rendered by ECharts. `option` is a PURE-JSON ECharts option
+ * (template-string formatters only — never functions): static SVG snapshots
+ * on the editor canvas/thumbnails/print, a live interactive instance
+ * (tooltips, dataZoom) while presenting.
+ */
+export interface ChartElement extends ElementBase {
+ type: 'chart'
+ /** preset key the panel offers to re-seed from (bar/line/pie/scatter) */
+ preset?: string
+ option: Record<string, unknown>
+}
+
+export type SlideElement = TextElement | ShapeElement | ImageElement | SvgElement | ChartElement
export interface Slide {
id: string
@@ -201,6 +214,18 @@ export function defaultText(partial: Partial<TextElement> = {}): TextElement {
}
}
+export function defaultChart(option: Record<string, unknown>, partial: Partial<ChartElement> = {}): ChartElement {
+ return {
+ id: uid('c'),
+ type: 'chart',
+ x: 400, y: 190, w: 800, h: 520,
+ rotation: 0, opacity: 1,
+ preset: 'bar',
+ option,
+ ...partial,
+ }
+}
+
export function defaultShape(shape: ShapeKind, partial: Partial<ShapeElement> = {}): ShapeElement {
return {
id: uid('s'),
diff --git a/slides/src/present.ts b/slides/src/present.ts
index 5616c9b6..1413948e 100644
--- a/slides/src/present.ts
+++ b/slides/src/present.ts
@@ -6,6 +6,7 @@ import Reveal from 'reveal.js'
import RevealNotes from 'reveal.js/plugin/notes/notes'
import 'reveal.js/dist/reveal.css'
import { anim, resetXform } from './anim'
+import { chartSnapshotSvg, mountChart } from './charts'
import type { BentoDoc, GradientFill, ShapeElement, Slide, SlideElement } from './model'
import { applyElementFrame, gradientLineCoords, renderSlide } from './render'
@@ -183,6 +184,8 @@ export function startPresentation(
runAmbientFx(doc.slides[toIdx], to)
restartSvgAnimations(to)
wireHoverFocus(doc.slides[toIdx], to)
+ if (from) disposeLiveCharts(doc.slides[fromIdx], from)
+ mountLiveCharts(doc.slides[toIdx], to)
}) as any)
// Clicking an element with a link jumps to its target slide.
@@ -210,12 +213,45 @@ export function startPresentation(
runAmbientFx(doc.slides[startIndex], first)
restartSvgAnimations(first)
wireHoverFocus(doc.slides[startIndex], first)
+ mountLiveCharts(doc.slides[startIndex], first)
}
})
return { exit }
}
+// --- live charts --------------------------------------------------------------
+
+// Present mode swaps chart snapshots for live ECharts instances (tooltips,
+// dataZoom). Leaving the slide disposes the instance and restores the
+// snapshot so the section stays presentable in Reveal's viewDistance cache.
+const chartHandles = new WeakMap<HTMLElement, Array<() => void>>()
+
+function mountLiveCharts(slide: Slide, section: HTMLElement) {
+ const handles: Array<() => void> = []
+ for (const el of slide?.elements ?? []) {
+ if (el.type !== 'chart') continue
+ const node = section.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
+ if (!node) continue
+ const dispose = mountChart(el, node)
+ handles.push(() => {
+ dispose()
+ node.innerHTML = chartSnapshotSvg(el)
+ const csvg = node.querySelector('svg')
+ if (csvg) {
+ csvg.setAttribute('preserveAspectRatio', 'none')
+ ;(csvg as SVGElement).style.cssText = 'width:100%;height:100%;display:block'
+ }
+ })
+ }
+ if (handles.length) chartHandles.set(section, handles)
+}
+
+function disposeLiveCharts(_slide: Slide, section: HTMLElement) {
+ for (const h of chartHandles.get(section) ?? []) h()
+ chartHandles.delete(section)
+}
+
// --- element fx -------------------------------------------------------------
function fxNodes(slide: Slide, section: HTMLElement): Array<[SlideElement, HTMLElement]> {
diff --git a/slides/src/render.ts b/slides/src/render.ts
index c0f06ab7..4f663ab3 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -2,6 +2,7 @@
// editor canvas, sidebar thumbnails, and Reveal.js sections.
import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement } from './model'
+import { chartSnapshotSvg } from './charts'
const SVG_NS = 'http://www.w3.org/2000/svg'
@@ -255,6 +256,19 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOpts
node.appendChild(img)
break
}
+ case 'chart': {
+ // Static SVG snapshot everywhere; present mode swaps in a live ECharts
+ // instance (mountLiveCharts) for tooltips/zoom. Kept as innerHTML so
+ // print and thumbnails need no chart runtime at render time.
+ node.dataset.chart = '1'
+ node.innerHTML = chartSnapshotSvg(el)
+ const csvg = node.querySelector('svg')
+ if (csvg) {
+ csvg.setAttribute('preserveAspectRatio', 'none')
+ csvg.style.cssText = 'width:100%;height:100%;display:block'
+ }
+ break
+ }
case 'svg': {
const markup = svgMarkup(el, doc)
if (opts.svgAsImage) {
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 67452a07..9f2b1481 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -464,6 +464,20 @@ html, body {
border-radius: 999px;
}
+/* chart option JSON editor */
+.ed-chart-json {
+ width: 100%;
+ resize: vertical;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ padding: 8px;
+ color: var(--ink, #1e2a3a);
+}
+.ed-chart-json.ed-invalid { border-color: #c9302c; outline: 1px solid #c9302c; }
+
/* inline code spans inside text elements — editor, present and print alike */
.bento-el-text code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;