Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

v0.9.6: dual y-axis charts + a visual chart editor

nyblnetc1ba368a8e73
diff --git a/CLAUDE.md b/CLAUDE.md
index 479ea416..37e4afc3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -97,7 +97,19 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
(optional format field; the starter deck declares peach/steel) or, absent that,
`deriveChartPalette(accent)` (accent + a cool HSL counterpart, each tinted).
tableToChart makes ONE series per numeric column (commas/`%` stripped, blanks→0,
- first column = x labels). Shapes:
+ first column = x labels) — and when two columns sit on very different scales
+ (or one reads as `%`) it auto-splits them onto a DUAL axis: bars on the left,
+ the odd column as a line on a right-hand axis. **Dual y-axis (v0.9.6)**:
+ `option.yAxis` may be an ARRAY of two value axes; a series picks one via
+ `yAxisIndex` (0/1). renderCartesian computes a range per axis, shares gridline
+ rows (2nd axis labels on the right, its own nice scale via `fixedTicks`), and
+ honours per-axis `min`/`max` + `axisLabel.formatter` ('{value}%'). **Visual
+ chart editor** (panels.ts buildChartProps): structured UI over the option —
+ Type, Legend + Second-axis toggles, a Series list (name · bar/line · left/right
+ axis · colour · remove), per-axis min/max, and an editable categories×series
+ data grid (add/remove rows keep xAxis.data + every series.data in lockstep);
+ pie gets a slices grid. The raw-JSON textarea stays as the 'Advanced (JSON)'
+ escape hatch. Shapes:
`strokeStyle` solid/dashed/dotted (legacy `strokeDash` still honoured);
line shapes have `lineStart`/`lineEnd` tips (arrow/dot/bar) rendered as
per-instance svg markers (sized in strokeWidth units, endpoints inset);
diff --git a/docs/agents.md b/docs/agents.md
index d96169ea..f6f12825 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -154,7 +154,10 @@ each kind of content to the feature built for it:
JSON. **Bar/line series data must be plain numbers** (`{value,itemStyle}`
objects coerce to 0 — only pie takes `{name,value}`); per-item bar colors
are unsupported, color by series; template formatters only (`{b}`, `{c}`,
- `{d}`), never functions.
+ `{d}`), never functions. **Dual axis**: for two series on very different
+ scales (e.g. volume + a %), make `yAxis` an ARRAY of two `{type:"value"}`
+ axes (give the 2nd `axisLabel:{formatter:"{value}%"}`) and point the odd
+ series at it with `"yAxisIndex":1` — render it as a `line` over the bars.
- **table**: `columns` (array of `{w}` fractional weights), `rows` (array of
`{cells:[{html, align?, color?, bg?, bold?}]}`), `header` (bool — row 0 is
the header), and a `style` object (`headerBg`, `headerColor`, `zebra?`,
diff --git a/slides/package.json b/slides/package.json
index ff5672d0..ae5e72e2 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -1,7 +1,7 @@
{
"name": "bento-slides",
"private": true,
- "version": "0.9.5",
+ "version": "0.9.6",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/slides/src/charts.ts b/slides/src/charts.ts
index 70b52414..ea829d9f 100644
--- a/slides/src/charts.ts
+++ b/slides/src/charts.ts
@@ -72,6 +72,8 @@ const SVG_NS = 'http://www.w3.org/2000/svg'
// --- option digestion -------------------------------------------------------
+interface YAxisCfg { name?: string; min?: number; max?: number; formatter?: string }
+
interface Digest {
w: number; h: number
font: string
@@ -82,6 +84,7 @@ interface Digest {
grid: { x: number; y: number; w: number; h: number }
legend: null | { color: string }
axisLabel: string; axisLine: string; splitLine: string
+ yAxes: YAxisCfg[] // 1 or 2 value axes; series pick one via yAxisIndex
tooltipTrigger: 'axis' | 'item' | null
zoomable: boolean
labelColor: string
@@ -93,12 +96,21 @@ function digest(option: Opt, w: number, h: number): Digest {
const g = option?.grid ?? {}
const legend = option?.legend ? { color: option.legend?.textStyle?.color ?? '#6B7280' } : null
const legendH = legend ? 24 : 0
+ const yRaw: Opt[] = Array.isArray(option?.yAxis) ? option.yAxis : option?.yAxis ? [option.yAxis] : [{}]
+ const yAxes: YAxisCfg[] = yRaw.slice(0, 2).map((a: Opt) => ({
+ name: typeof a?.name === 'string' ? a.name : undefined,
+ min: typeof a?.min === 'number' ? a.min : undefined,
+ max: typeof a?.max === 'number' ? a.max : undefined,
+ formatter: typeof a?.axisLabel?.formatter === 'string' ? a.axisLabel.formatter : undefined,
+ }))
+ if (!yAxes.length) yAxes.push({})
+ const twoAxes = !isPie && yAxes.length > 1
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),
+ w: w - num(g.left, 48) - num(g.right, twoAxes ? 56 : 16),
h: h - num(g.top, 24) - num(g.bottom, 44),
}
return {
@@ -109,9 +121,10 @@ function digest(option: Opt, w: number, h: number): Digest {
categories: (option?.xAxis?.data ?? []).map(String),
grid,
legend,
- axisLabel: option?.xAxis?.axisLabel?.color ?? option?.yAxis?.axisLabel?.color ?? '#6B7280',
+ axisLabel: option?.xAxis?.axisLabel?.color ?? yRaw[0]?.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)',
+ splitLine: yRaw[0]?.splitLine?.lineStyle?.color ?? 'rgba(110,120,135,0.15)',
+ yAxes,
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',
@@ -135,7 +148,42 @@ function niceTicks(min: number, max: number, target = 5): number[] {
}
const fmt = (v: number): string =>
- Math.abs(v) >= 1000 ? String(v).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : String(Math.round(v * 100) / 100)
+ Math.abs(v) >= 1000 ? String(Math.round(v * 100) / 100).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : String(Math.round(v * 100) / 100)
+
+/** Nearest "nice" number (1/2/5 × 10^n) to x. */
+function niceNum(x: number, round: boolean): number {
+ if (!(x > 0)) return 1
+ const exp = Math.floor(Math.log10(x))
+ const f = x / Math.pow(10, exp)
+ const nf = round ? (f < 1.5 ? 1 : f < 3 ? 2 : f < 7 ? 5 : 10) : (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10)
+ return nf * Math.pow(10, exp)
+}
+
+const linspace = (a: number, b: number, n: number): number[] =>
+ Array.from({ length: n }, (_, i) => a + (b - a) * (i / (n - 1)))
+
+/** Exactly `intervals`+1 evenly spaced nice ticks covering lo0..hi0 (lo0 kept as base). */
+function fixedTicks(lo0: number, hi0: number, intervals: number): number[] {
+ const iv = Math.max(1, intervals)
+ let step = niceNum((hi0 - lo0) / iv, false) || 1
+ let guard = 0
+ while (lo0 + step * iv < hi0 && guard++ < 20) step = niceNum(step * 1.5, false)
+ return Array.from({ length: iv + 1 }, (_, i) => Math.round((lo0 + step * i) * 1e6) / 1e6)
+}
+
+/** Range + tick labels for one value axis. `forceCount` aligns a 2nd axis to the 1st. */
+function axisRange(values: number[], cfg: YAxisCfg, forceCount?: number): { lo: number; hi: number; labels: string[] } {
+ let minV = 0, maxV = 0
+ for (const v of values) { if (v > maxV) maxV = v; if (v < minV) minV = v }
+ const loBase = cfg.min != null ? cfg.min : Math.min(0, minV)
+ const hiBase = cfg.max != null ? cfg.max : (maxV || 1)
+ const overridden = cfg.min != null || cfg.max != null
+ let ticks: number[]
+ if (forceCount) ticks = overridden ? linspace(loBase, hiBase, forceCount) : fixedTicks(loBase, hiBase, forceCount - 1)
+ else ticks = overridden ? linspace(loBase, hiBase, 6) : niceTicks(loBase, hiBase)
+ const apply = (v: number) => (cfg.formatter ? cfg.formatter.replace('{value}', fmt(v)) : fmt(v))
+ return { lo: ticks[0], hi: ticks[ticks.length - 1], labels: ticks.map(apply) }
+}
// --- svg helpers ------------------------------------------------------------
@@ -222,12 +270,13 @@ function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: Vie
const { cats, i0 } = catWindow(d, view)
const nCat = Math.max(1, cats.length)
- // y extent across visible data
- let maxY = 0
- let minY = 0
+ // ----- value axes (1 or 2); gridlines align, labels on left & right --------
+ const nAxes = d.yAxes.length
+ const axisOf = (s: Opt) => Math.min(nAxes - 1, Math.max(0, Math.round(num(s?.yAxisIndex, 0))))
+ const perAxis: number[][] = Array.from({ length: nAxes }, () => [])
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 }
+ perAxis[axisOf(s)].push(...data)
}
let sMinX = Infinity, sMaxX = -Infinity
for (const s of scatters) {
@@ -235,20 +284,28 @@ function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: Vie
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
+ perAxis[0].push(py)
}
}
- 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
+ const r0 = axisRange(perAxis[0], d.yAxes[0])
+ const k = r0.labels.length
+ const ranges: Array<ReturnType<typeof axisRange> | null> = [r0, nAxes > 1 ? axisRange(perAxis[1], d.yAxes[1], k) : null]
+ const yOf = (v: number, a = 0) => {
+ const r = ranges[a] ?? r0
+ return G.y + G.h - ((v - r.lo) / (r.hi - r.lo || 1)) * G.h
+ }
+ const baseOf = (a = 0) => yOf((ranges[a] ?? r0).lo, a)
- // gridlines + y labels
- for (const tv of ticks) {
- const y = yOf(tv)
+ // shared gridlines at k evenly spaced rows; labels on the matching side(s)
+ for (let j = 0; j < k; j++) {
+ const y = G.y + G.h - (j / Math.max(1, k - 1)) * G.h
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'))
+ svg.appendChild(text(G.x - 8, y + 4, r0.labels[j], d.axisLabel, d.font, 12, 'end'))
+ if (ranges[1]) svg.appendChild(text(G.x + G.w + 8, y + 4, ranges[1].labels[j], d.axisLabel, d.font, 12, 'start'))
}
+ if (d.yAxes[0]?.name) svg.appendChild(text(G.x - 8, G.y - 9, d.yAxes[0].name, d.axisLabel, d.font, 11, 'end'))
+ if (ranges[1] && d.yAxes[1]?.name) svg.appendChild(text(G.x + G.w + 8, G.y - 9, d.yAxes[1].name, d.axisLabel, d.font, 11, 'start'))
+
// 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 }))
@@ -292,14 +349,16 @@ function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: Vie
const groupW = band * 0.62
const barW = groupW / m
bars.forEach((s, si) => {
+ const ax = axisOf(s)
+ const base = baseOf(ax)
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 hv = (base - yOf(v, ax)) * sweep
const r = elNS('rect', {
- x: x + 1, y: yOf(yLo) - hv, width: Math.max(1, barW - 2), height: Math.max(0, hv),
+ x: x + 1, y: base - 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
@@ -312,10 +371,11 @@ function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: Vie
// lines
lines.forEach((s) => {
const si = d.series.indexOf(s)
+ const ax = axisOf(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])
+ const pts = data.map((v, i) => [G.x + band * (i + 0.5), yOf(v, ax)] as [number, number])
if (pts.length < 2) return
let path = `M ${pts[0][0]} ${pts[0][1]}`
if (s.smooth) {
@@ -331,7 +391,7 @@ function renderCartesian(svg: SVGSVGElement, d: Digest, sweep: number, view: Vie
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`,
+ d: `${path} L ${pts[pts.length - 1][0]} ${baseOf(ax)} L ${pts[0][0]} ${baseOf(ax)} Z`,
fill, opacity: s.areaStyle.color ? 1 : 0.25,
})
svg.appendChild(area)
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 0b0cf10c..3472b135 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -77,7 +77,7 @@ export class PropsPanel {
}
/** Collapsed by default until the user opens them (persisted per title). */
- private static CLOSED_BY_DEFAULT = new Set(['Presenting', 'Interactivity', 'Layout'])
+ private static CLOSED_BY_DEFAULT = new Set(['Presenting', 'Interactivity', 'Layout', 'Advanced (JSON)'])
/**
* Retrofit the flat panel into an accordion: every .ed-section header
@@ -772,23 +772,50 @@ export class PropsPanel {
}
}
+ /** Edit the live chart option in place; final=false while typing. */
+ private editOption(id: string, fn: (o: Record<string, any>) => void, final = true) {
+ this.mutate(id, (e) => { fn((e as ChartElement).option as Record<string, any>) }, final)
+ }
+
+ /** Native <select> with distinct value/label pairs (for model-word values). */
+ private labeledSelect(pairs: Array<[string, string]>, value: string, onChange: (v: string) => void): HTMLSelectElement {
+ const sel = document.createElement('select')
+ for (const [v, label] of pairs) {
+ const o = document.createElement('option')
+ o.value = v; o.textContent = label
+ if (v === value) o.selected = true
+ sel.appendChild(o)
+ }
+ sel.addEventListener('change', () => onChange(sel.value))
+ return sel
+ }
+
private buildChartProps(el: ChartElement) {
- this.section(t('Data'))
- this.row(t('Preset'), this.select(Object.keys(CHART_PRESETS), el.preset ?? 'bar', (v) =>
+ const opt = el.option as Record<string, any>
+ const series: any[] = Array.isArray(opt.series) ? opt.series : opt.series ? [opt.series] : []
+ const isPie = series.some((s) => s?.type === 'pie')
+ const isScatter = series.some((s) => s?.type === 'scatter')
+
+ this.section(t('Chart'))
+ this.row(t('Type'), 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 = applyChartPalette(CHART_PRESETS[v](), this.store.doc.theme)
}, true)))
+ if (!isPie && !isScatter) this.buildChartCartesian(el, opt, series)
+ else if (isPie) this.buildChartPie(el, series)
+
+ // The escape hatch: the full option as JSON, for anything the UI omits.
+ this.section(t('Advanced (JSON)'))
const hint = document.createElement('p')
hint.className = 'ed-hint'
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')
ta.className = 'ed-chart-json'
- ta.rows = 14
+ ta.rows = 12
ta.spellcheck = false
ta.value = JSON.stringify(el.option, null, 2)
ta.addEventListener('change', () => {
@@ -796,13 +823,232 @@ export class PropsPanel {
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')
- }
+ } catch { ta.classList.add('ed-invalid') }
})
this.host.appendChild(ta)
}
+ private static seriesColor(s: any, palette: string[] | undefined, i: number): string {
+ const c = s?.type === 'line' ? s?.lineStyle?.color : s?.itemStyle?.color
+ if (typeof c === 'string') return c
+ const p = palette && palette.length ? palette : ['#5470c6', '#91cc75', '#fac858', '#ee6666']
+ return p[i % p.length]
+ }
+
+ private static setSeriesColor(s: any, v: string) {
+ if (s?.type === 'line') s.lineStyle = { ...(s.lineStyle ?? {}), color: v }
+ else s.itemStyle = { ...(s.itemStyle ?? {}), color: v }
+ }
+
+ private buildChartCartesian(el: ChartElement, opt: Record<string, any>, series: any[]) {
+ const yAxis: any[] = Array.isArray(opt.yAxis) ? opt.yAxis : opt.yAxis ? [opt.yAxis] : [{ type: 'value' }]
+ const twoAxes = yAxis.length > 1
+
+ this.row(t('Legend'), this.toggle(!!opt.legend, (on) =>
+ this.editOption(el.id, (o) => { if (on) o.legend = { bottom: 0 }; else delete o.legend })))
+
+ this.row(t('Second axis'), this.toggle(twoAxes, (on) => this.editOption(el.id, (o) => {
+ const ss: any[] = Array.isArray(o.series) ? o.series : o.series ? [o.series] : []
+ if (on) {
+ const first = Array.isArray(o.yAxis) ? (o.yAxis[0] ?? {}) : (o.yAxis ?? {})
+ o.yAxis = [{ type: 'value', ...first }, { type: 'value', name: t('Axis {n}', { n: 2 }) }]
+ ss.forEach((s, i) => { if (s) s.yAxisIndex = i === 0 ? 0 : 1 })
+ } else {
+ o.yAxis = { type: 'value', ...(Array.isArray(o.yAxis) ? o.yAxis[0] : o.yAxis) }
+ ss.forEach((s) => { if (s) delete s.yAxisIndex })
+ }
+ })))
+
+ // --- series list --------------------------------------------------------
+ this.section(t('Series'))
+ const palette: string[] | undefined = Array.isArray(opt.color) ? opt.color : undefined
+ series.forEach((s, i) => {
+ const row = document.createElement('div')
+ row.className = 'ed-series-row'
+ const name = document.createElement('input')
+ name.type = 'text'; name.className = 'ed-series-name'; name.value = s?.name ?? ''
+ name.placeholder = t('Series {n}', { n: i + 1 })
+ name.addEventListener('input', () => this.editOption(el.id, (o) => { o.series[i].name = name.value }, false))
+ name.addEventListener('change', () => this.editOption(el.id, (o) => { o.series[i].name = name.value }, true))
+ const type = this.labeledSelect([['bar', t('Bar')], ['line', t('Line')]], s?.type === 'line' ? 'line' : 'bar',
+ (v) => this.editOption(el.id, (o) => { o.series[i].type = v }))
+ row.append(name, type)
+ if (twoAxes) {
+ row.append(this.labeledSelect([['0', t('Left')], ['1', t('Right')]], String(Math.round(s?.yAxisIndex ?? 0)),
+ (v) => this.editOption(el.id, (o) => { o.series[i].yAxisIndex = parseInt(v) })))
+ }
+ row.append(this.color(PropsPanel.seriesColor(s, palette, i), (v, final) =>
+ this.editOption(el.id, (o) => PropsPanel.setSeriesColor(o.series[i], v), final)))
+ const rm = this.opBtn('✕', t('Remove'), () => this.editOption(el.id, (o) => {
+ o.series.splice(i, 1)
+ if (o.series.length <= 1) { o.series.forEach((x: any) => x && delete x.yAxisIndex); if (Array.isArray(o.yAxis)) o.yAxis = o.yAxis[0] ?? { type: 'value' } }
+ }))
+ rm.classList.add('ed-series-rm')
+ row.append(rm)
+ this.host.appendChild(row)
+ })
+ const addRow = document.createElement('div')
+ addRow.className = 'ed-chart-add'
+ const addBtn = document.createElement('button')
+ addBtn.className = 'ed-btn'
+ addBtn.textContent = t('+ Add series')
+ addBtn.addEventListener('click', () => this.editOption(el.id, (o) => {
+ const ss: any[] = Array.isArray(o.series) ? o.series : o.series ? [o.series] : []
+ const n = (o.xAxis?.data?.length) || 4
+ ss.push({ type: 'bar', name: t('Series {n}', { n: ss.length + 1 }), data: Array(n).fill(0) })
+ o.series = ss
+ }))
+ addRow.appendChild(addBtn)
+ this.host.appendChild(addRow)
+
+ // --- per-axis min/max ---------------------------------------------------
+ yAxis.forEach((ax, ai) => {
+ const label = twoAxes ? (ai === 0 ? t('Left axis') : t('Right axis')) : t('Y axis')
+ const wrap = document.createElement('div')
+ wrap.className = 'ed-axis-range'
+ const mk = (key: 'min' | 'max', ph: string) => {
+ const inp = document.createElement('input')
+ inp.type = 'number'; inp.placeholder = ph
+ inp.value = typeof ax?.[key] === 'number' ? String(ax[key]) : ''
+ const commit = (final: boolean) => this.editOption(el.id, (o) => {
+ const a = Array.isArray(o.yAxis) ? o.yAxis[ai] : o.yAxis
+ const raw = inp.value.trim()
+ if (raw === '' || Number.isNaN(parseFloat(raw))) delete a[key]
+ else a[key] = parseFloat(raw)
+ }, final)
+ inp.addEventListener('input', () => commit(false))
+ inp.addEventListener('change', () => commit(true))
+ return inp
+ }
+ wrap.append(mk('min', t('min')), mk('max', t('max')))
+ this.row(label, wrap)
+ })
+
+ // --- data grid ----------------------------------------------------------
+ this.buildChartGrid(el, opt, series)
+ }
+
+ /** Editable categories × series grid. Adding/removing rows keeps every
+ * series data array and the x-axis categories in lockstep. */
+ private buildChartGrid(el: ChartElement, opt: Record<string, any>, series: any[]) {
+ const cats: any[] = opt.xAxis?.data ?? []
+ this.section(t('Data'))
+ const scroll = document.createElement('div')
+ scroll.className = 'ed-chart-grid-wrap'
+ const table = document.createElement('table')
+ table.className = 'ed-chart-grid'
+ const thead = document.createElement('tr')
+ const corner = document.createElement('th'); corner.textContent = ''
+ thead.appendChild(corner)
+ series.forEach((s, i) => {
+ const th = document.createElement('th')
+ th.textContent = s?.name || t('Series {n}', { n: i + 1 })
+ thead.appendChild(th)
+ })
+ thead.appendChild(document.createElement('th'))
+ table.appendChild(thead)
+
+ const cellInput = (value: string, onCommit: (v: string, final: boolean) => void, numeric: boolean) => {
+ const inp = document.createElement('input')
+ inp.type = numeric ? 'number' : 'text'
+ inp.value = value
+ inp.addEventListener('input', () => onCommit(inp.value, false))
+ inp.addEventListener('change', () => onCommit(inp.value, true))
+ return inp
+ }
+
+ const rowCount = Math.max(cats.length, ...series.map((s) => (s?.data?.length ?? 0)))
+ for (let r = 0; r < rowCount; r++) {
+ const tr = document.createElement('tr')
+ const cat = document.createElement('td')
+ cat.appendChild(cellInput(String(cats[r] ?? ''), (v, final) => this.editOption(el.id, (o) => {
+ if (!Array.isArray(o.xAxis?.data)) { o.xAxis = { ...(o.xAxis ?? { type: 'category' }), data: [] } }
+ o.xAxis.data[r] = v
+ }, final), false))
+ tr.appendChild(cat)
+ series.forEach((s, i) => {
+ const td = document.createElement('td')
+ td.appendChild(cellInput(String(s?.data?.[r] ?? ''), (v, final) => this.editOption(el.id, (o) => {
+ const arr = o.series[i].data ?? (o.series[i].data = [])
+ const n = parseFloat(v)
+ arr[r] = Number.isNaN(n) ? 0 : n
+ }, final), true))
+ tr.appendChild(td)
+ })
+ const rmTd = document.createElement('td')
+ rmTd.appendChild(this.opBtn('✕', t('Remove row'), () => this.editOption(el.id, (o) => {
+ if (Array.isArray(o.xAxis?.data)) o.xAxis.data.splice(r, 1)
+ o.series.forEach((s: any) => { if (Array.isArray(s?.data)) s.data.splice(r, 1) })
+ })))
+ tr.appendChild(rmTd)
+ table.appendChild(tr)
+ }
+ scroll.appendChild(table)
+ this.host.appendChild(scroll)
+
+ const addRow = document.createElement('div')
+ addRow.className = 'ed-chart-add'
+ const addBtn = document.createElement('button')
+ addBtn.className = 'ed-btn'
+ addBtn.textContent = t('+ Add row')
+ addBtn.addEventListener('click', () => this.editOption(el.id, (o) => {
+ if (!Array.isArray(o.xAxis?.data)) o.xAxis = { ...(o.xAxis ?? { type: 'category' }), data: [] }
+ o.xAxis.data.push(t('Item {n}', { n: o.xAxis.data.length + 1 }))
+ const ss: any[] = Array.isArray(o.series) ? o.series : [o.series]
+ ss.forEach((s) => { if (s) (s.data ?? (s.data = [])).push(0) })
+ }))
+ addRow.appendChild(addBtn)
+ this.host.appendChild(addRow)
+ }
+
+ /** Pie: one row per slice (name · value · colour · remove) + add. */
+ private buildChartPie(el: ChartElement, series: any[]) {
+ const s = series.find((x) => x?.type === 'pie') ?? series[0]
+ const data: any[] = s?.data ?? []
+ const palette: string[] | undefined = Array.isArray((el.option as any).color) ? (el.option as any).color : undefined
+ this.section(t('Slices'))
+ data.forEach((d, i) => {
+ const row = document.createElement('div')
+ row.className = 'ed-series-row'
+ const name = document.createElement('input')
+ name.type = 'text'; name.className = 'ed-series-name'; name.value = d?.name ?? ''
+ name.addEventListener('input', () => this.editPieDatum(el.id, i, (x) => { x.name = name.value }, false))
+ name.addEventListener('change', () => this.editPieDatum(el.id, i, (x) => { x.name = name.value }, true))
+ const val = document.createElement('input')
+ val.type = 'number'; val.className = 'ed-pie-val'; val.value = String(d?.value ?? 0)
+ const commitVal = (final: boolean) => this.editPieDatum(el.id, i, (x) => { const n = parseFloat(val.value); x.value = Number.isNaN(n) ? 0 : n }, final)
+ val.addEventListener('input', () => commitVal(false))
+ val.addEventListener('change', () => commitVal(true))
+ const swatch = this.color((palette && palette[i]) || PropsPanel.seriesColor({ type: 'pie' }, palette, i), (v, final) =>
+ this.editOption(el.id, (o) => { if (!Array.isArray(o.color)) o.color = []; o.color[i] = v }, final))
+ const rm = this.opBtn('✕', t('Remove'), () => this.editPieDatum(el.id, i, null, true))
+ rm.classList.add('ed-series-rm')
+ row.append(name, val, swatch, rm)
+ this.host.appendChild(row)
+ })
+ const addRow = document.createElement('div')
+ addRow.className = 'ed-chart-add'
+ const addBtn = document.createElement('button')
+ addBtn.className = 'ed-btn'
+ addBtn.textContent = t('+ Add slice')
+ addBtn.addEventListener('click', () => this.editOption(el.id, (o) => {
+ const ps = (Array.isArray(o.series) ? o.series : [o.series]).find((x: any) => x?.type === 'pie') ?? o.series[0]
+ ps.data = ps.data ?? []
+ ps.data.push({ name: t('Item {n}', { n: ps.data.length + 1 }), value: 0 })
+ }))
+ addRow.appendChild(addBtn)
+ this.host.appendChild(addRow)
+ }
+
+ private editPieDatum(id: string, i: number, fn: ((d: any) => void) | null, final: boolean) {
+ this.editOption(id, (o) => {
+ const ps = (Array.isArray(o.series) ? o.series : [o.series]).find((x: any) => x?.type === 'pie') ?? o.series[0]
+ if (!ps?.data) return
+ if (fn === null) ps.data.splice(i, 1)
+ else fn(ps.data[i])
+ }, final)
+ }
+
private buildTableProps(el: TableElement) {
const stepper = (label: string, count: number, onDelta: (d: number) => void) => {
const wrap = document.createElement('div')
@@ -894,24 +1140,55 @@ export class PropsPanel {
const labels = bodyRows.map((r) => strip(r.cells[0]?.html ?? ''))
const headerRow = el.header ? el.rows[0] : null
// every column after the labels that is mostly numeric becomes its own series
- const cols: number[] = []
+ const cols: Array<{ name: string; data: number[]; isPct: boolean; maxAbs: number }> = []
for (let c = 1; c < el.columns.length; c++) {
- const parsed = bodyRows.map((r) => num(r.cells[c]?.html ?? '')).filter((n) => !Number.isNaN(n))
- if (parsed.length >= Math.ceil(bodyRows.length / 2)) cols.push(c)
+ const raw = bodyRows.map((r) => r.cells[c]?.html ?? '')
+ const parsed = raw.map(num)
+ const good = parsed.filter((n) => !Number.isNaN(n))
+ if (good.length < Math.ceil(bodyRows.length / 2)) continue
+ const isPct = /%/.test(headerRow ? strip(headerRow.cells[c]?.html ?? '') : '') ||
+ raw.filter((h) => /%/.test(h)).length >= Math.ceil(bodyRows.length / 2)
+ cols.push({
+ name: headerRow ? strip(headerRow.cells[c]?.html ?? '') : '',
+ data: parsed.map((n) => (Number.isNaN(n) ? 0 : n)),
+ isPct,
+ maxAbs: Math.max(1, ...good.map((n) => Math.abs(n))),
+ })
}
if (!cols.length) { this.toast(t('No numeric column found to chart')); return }
- const series = cols.map((c) => ({
- type: 'bar',
- name: headerRow ? strip(headerRow.cells[c]?.html ?? '') : '',
- data: bodyRows.map((r) => { const n = num(r.cells[c]?.html ?? ''); return Number.isNaN(n) ? 0 : n }),
- }))
+
+ // two columns on very different scales (or one is a %) → dual axis: bars
+ // on the left, the odd one as a line on a right-hand axis
+ let secondary = -1
+ if (cols.length === 2) {
+ const pct = cols.filter((c) => c.isPct)
+ if (pct.length === 1) secondary = cols.indexOf(pct[0])
+ else {
+ const big = cols[0].maxAbs >= cols[1].maxAbs ? 0 : 1
+ if (cols[big].maxAbs / cols[1 - big].maxAbs >= 12) secondary = 1 - big
+ }
+ }
+
const option: Record<string, unknown> = {
xAxis: { type: 'category', data: labels },
- yAxis: { type: 'value' },
- series,
tooltip: { trigger: 'axis' },
}
- if (series.length > 1) option.legend = { bottom: 0 }
+ if (secondary >= 0) {
+ const prim = cols[1 - secondary], sec = cols[secondary]
+ option.yAxis = [
+ { type: 'value', name: prim.name || undefined },
+ { type: 'value', name: sec.name || undefined, axisLabel: sec.isPct ? { formatter: '{value}%' } : undefined },
+ ]
+ option.series = [
+ { type: 'bar', name: prim.name, data: prim.data, yAxisIndex: 0 },
+ { type: 'line', name: sec.name, data: sec.data, yAxisIndex: 1, smooth: true },
+ ]
+ option.legend = { bottom: 0 }
+ } else {
+ option.yAxis = { type: 'value' }
+ option.series = cols.map((c) => ({ type: 'bar', name: c.name, data: c.data }))
+ if (cols.length > 1) option.legend = { bottom: 0 }
+ }
applyChartPalette(option, this.store.doc.theme)
const chart = defaultChart(option, {
x: el.x, y: Math.min(el.y + el.h + 24, 480), w: Math.max(el.w, 640), h: 300, preset: 'bar',
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 759c89ae..f4717ee7 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -336,4 +336,25 @@ export const de: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "Ein Balkendiagramm aus den Zahlen dieser Tabelle erstellen (erste Spalte = Beschriftungen)",
"No numeric column found to chart": "Keine numerische Spalte zum Darstellen gefunden",
"Chart created from table": "Diagramm aus Tabelle erstellt",
+ "Type": "Typ",
+ "Legend": "Legende",
+ "Second axis": "Zweite Achse",
+ "Axis {n}": "Achse {n}",
+ "Series": "Datenreihe",
+ "Bar": "Balken",
+ "Left": "Links",
+ "Right": "Rechts",
+ "+ Add series": "+ Datenreihe",
+ "Series {n}": "Reihe {n}",
+ "Left axis": "Linke Achse",
+ "Right axis": "Rechte Achse",
+ "Y axis": "Y-Achse",
+ "min": "Min",
+ "max": "Max",
+ "Remove row": "Zeile entfernen",
+ "+ Add row": "+ Zeile",
+ "Item {n}": "Element {n}",
+ "Advanced (JSON)": "Erweitert (JSON)",
+ "Slices": "Segmente",
+ "+ Add slice": "+ Segment",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index fbb6573a..f5018a2a 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -336,4 +336,25 @@ export const es: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "Crea un gráfico de barras con los números de esta tabla (primera columna = etiquetas)",
"No numeric column found to chart": "No se encontró ninguna columna numérica para el gráfico",
"Chart created from table": "Gráfico creado a partir de la tabla",
+ "Type": "Tipo",
+ "Legend": "Leyenda",
+ "Second axis": "Segundo eje",
+ "Axis {n}": "Eje {n}",
+ "Series": "Serie",
+ "Bar": "Barras",
+ "Left": "Izquierda",
+ "Right": "Derecha",
+ "+ Add series": "+ Añadir serie",
+ "Series {n}": "Serie {n}",
+ "Left axis": "Eje izquierdo",
+ "Right axis": "Eje derecho",
+ "Y axis": "Eje Y",
+ "min": "Mín",
+ "max": "Máx",
+ "Remove row": "Quitar fila",
+ "+ Add row": "+ Añadir fila",
+ "Item {n}": "Elemento {n}",
+ "Advanced (JSON)": "Avanzado (JSON)",
+ "Slices": "Segmentos",
+ "+ Add slice": "+ Añadir segmento",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index d9fe427e..80d93369 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -336,4 +336,25 @@ export const fr: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "Créer un histogramme à partir des nombres de ce tableau (première colonne = étiquettes)",
"No numeric column found to chart": "Aucune colonne numérique à représenter",
"Chart created from table": "Graphique créé à partir du tableau",
+ "Type": "Type",
+ "Legend": "Légende",
+ "Second axis": "Second axe",
+ "Axis {n}": "Axe {n}",
+ "Series": "Série",
+ "Bar": "Barres",
+ "Left": "Gauche",
+ "Right": "Droite",
+ "+ Add series": "+ Ajouter une série",
+ "Series {n}": "Série {n}",
+ "Left axis": "Axe gauche",
+ "Right axis": "Axe droit",
+ "Y axis": "Axe Y",
+ "min": "Min",
+ "max": "Max",
+ "Remove row": "Supprimer la ligne",
+ "+ Add row": "+ Ajouter une ligne",
+ "Item {n}": "Élément {n}",
+ "Advanced (JSON)": "Avancé (JSON)",
+ "Slices": "Secteurs",
+ "+ Add slice": "+ Ajouter un secteur",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index c5f1d4d8..b80902b2 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -336,4 +336,25 @@ export const it: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "Crea un istogramma dai numeri di questa tabella (prima colonna = etichette)",
"No numeric column found to chart": "Nessuna colonna numerica da rappresentare",
"Chart created from table": "Grafico creato dalla tabella",
+ "Type": "Tipo",
+ "Legend": "Legenda",
+ "Second axis": "Secondo asse",
+ "Axis {n}": "Asse {n}",
+ "Series": "Serie",
+ "Bar": "Barre",
+ "Left": "Sinistra",
+ "Right": "Destra",
+ "+ Add series": "+ Aggiungi serie",
+ "Series {n}": "Serie {n}",
+ "Left axis": "Asse sinistro",
+ "Right axis": "Asse destro",
+ "Y axis": "Asse Y",
+ "min": "Min",
+ "max": "Max",
+ "Remove row": "Rimuovi riga",
+ "+ Add row": "+ Aggiungi riga",
+ "Item {n}": "Elemento {n}",
+ "Advanced (JSON)": "Avanzato (JSON)",
+ "Slices": "Segmenti",
+ "+ Add slice": "+ Aggiungi segmento",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index bfd4ac92..c3656ff2 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -336,4 +336,25 @@ export const ja: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "この表の数値から棒グラフを作成します(最初の列 = ラベル)",
"No numeric column found to chart": "グラフ化できる数値列が見つかりません",
"Chart created from table": "表からグラフを作成しました",
+ "Type": "種類",
+ "Legend": "凡例",
+ "Second axis": "第2軸",
+ "Axis {n}": "軸 {n}",
+ "Series": "系列",
+ "Bar": "棒",
+ "Left": "左",
+ "Right": "右",
+ "+ Add series": "+ 系列を追加",
+ "Series {n}": "系列 {n}",
+ "Left axis": "左軸",
+ "Right axis": "右軸",
+ "Y axis": "Y軸",
+ "min": "最小",
+ "max": "最大",
+ "Remove row": "行を削除",
+ "+ Add row": "+ 行を追加",
+ "Item {n}": "項目 {n}",
+ "Advanced (JSON)": "詳細 (JSON)",
+ "Slices": "スライス",
+ "+ Add slice": "+ スライスを追加",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index de764ea2..86d465de 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -336,4 +336,25 @@ export const zhHans: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "用此表格中的数字生成柱状图(第一列为标签)",
"No numeric column found to chart": "未找到可制图的数值列",
"Chart created from table": "已用表格生成图表",
+ "Type": "类型",
+ "Legend": "图例",
+ "Second axis": "第二轴",
+ "Axis {n}": "轴 {n}",
+ "Series": "系列",
+ "Bar": "柱状",
+ "Left": "左",
+ "Right": "右",
+ "+ Add series": "+ 添加系列",
+ "Series {n}": "系列 {n}",
+ "Left axis": "左轴",
+ "Right axis": "右轴",
+ "Y axis": "Y 轴",
+ "min": "最小",
+ "max": "最大",
+ "Remove row": "删除行",
+ "+ Add row": "+ 添加行",
+ "Item {n}": "项目 {n}",
+ "Advanced (JSON)": "高级 (JSON)",
+ "Slices": "扇区",
+ "+ Add slice": "+ 添加扇区",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index ebb39be0..c531b139 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -336,4 +336,25 @@ export const zhHant: Catalog = {
"Create a bar chart from the numbers in this table (first column = labels)": "用此表格中的數字產生長條圖(第一欄為標籤)",
"No numeric column found to chart": "找不到可製圖的數值欄",
"Chart created from table": "已用表格產生圖表",
+ "Type": "類型",
+ "Legend": "圖例",
+ "Second axis": "第二軸",
+ "Axis {n}": "軸 {n}",
+ "Series": "系列",
+ "Bar": "長條",
+ "Left": "左",
+ "Right": "右",
+ "+ Add series": "+ 新增系列",
+ "Series {n}": "系列 {n}",
+ "Left axis": "左軸",
+ "Right axis": "右軸",
+ "Y axis": "Y 軸",
+ "min": "最小",
+ "max": "最大",
+ "Remove row": "刪除列",
+ "+ Add row": "+ 新增列",
+ "Item {n}": "項目 {n}",
+ "Advanced (JSON)": "進階 (JSON)",
+ "Slices": "扇區",
+ "+ Add slice": "+ 新增扇區",
}
diff --git a/slides/src/styles.css b/slides/src/styles.css
index 9e91980d..5375803e 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -582,6 +582,61 @@ html, body {
}
.ed-chart-json.ed-invalid { border-color: #c9302c; outline: 1px solid #c9302c; }
+/* --- visual chart editor -------------------------------------------------- */
+.ed-series-row {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 3px 0;
+}
+.ed-series-row .ed-series-name { flex: 1 1 auto; min-width: 0; }
+.ed-series-row select { flex: 0 0 auto; }
+.ed-series-row input[type='text'],
+.ed-series-row select {
+ height: 26px;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ padding: 0 6px;
+ font-size: 12px;
+ background: #fff;
+ color: var(--ink, #1e2a3a);
+}
+.ed-series-row input[type='color'] { flex: 0 0 auto; width: 26px; height: 26px; padding: 0; border: 1px solid var(--line); border-radius: 6px; background: none; }
+.ed-series-row .ed-pie-val { width: 62px; height: 26px; border: 1px solid var(--line); border-radius: 6px; padding: 0 6px; font-size: 12px; }
+.ed-series-rm { flex: 0 0 auto; color: #9aa4b2; }
+.ed-series-rm:hover { color: #c9302c; }
+.ed-chart-add { margin: 4px 0 2px; }
+.ed-chart-add .ed-btn { width: 100%; justify-content: center; font-size: 12px; }
+.ed-axis-range { display: flex; gap: 6px; }
+.ed-axis-range input { width: 100%; height: 26px; border: 1px solid var(--line); border-radius: 6px; padding: 0 6px; font-size: 12px; }
+.ed-chart-grid-wrap { overflow-x: auto; margin: 2px 0; }
+.ed-chart-grid { border-collapse: collapse; width: 100%; }
+.ed-chart-grid th {
+ font-size: 10px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: #7a8494;
+ text-align: left;
+ padding: 2px 4px;
+ white-space: nowrap;
+}
+.ed-chart-grid td { padding: 1px 2px; }
+.ed-chart-grid input {
+ width: 100%;
+ min-width: 52px;
+ height: 24px;
+ border: 1px solid var(--line);
+ border-radius: 5px;
+ padding: 0 5px;
+ font-size: 12px;
+ background: #fff;
+ color: var(--ink, #1e2a3a);
+}
+.ed-chart-grid td:first-child input { font-weight: 600; }
+.ed-chart-grid .ed-btn-icon { padding: 2px; color: #9aa4b2; }
+.ed-chart-grid .ed-btn-icon:hover { color: #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;