Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

v0.9.3: first-class table element (both phases)

nyblnet970a06fea849
diff --git a/CLAUDE.md b/CLAUDE.md
index 14d7d18a..d46ed715 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -101,6 +101,21 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.
glyphs, image cutouts); panel offers presets (subtle/soft/elevated/glow),
non-matching values show as 'custom'. Present-mode Reveal CONTROLS (corner
arrows) default OFF (doc.present.controls re-enables).
+- **Tables (v0.9.3)**: `table` element — a real HTML `<table>` (table-layout
+ fixed) rendered by the shared render.ts (`renderTableHtml`), identical in
+ editor/thumb/present/print. Model: `columns` fractional weights, `rows` of
+ `{cells:[{html,align?,color?,bg?,bold?}]}`, `header` bool, `style` object
+ (headerBg/Color, zebra, borderColor/Width, cellPad X/Y, fontSize, color,
+ radius). Cells edit on canvas via contentEditable (canvas.ts editCellAt/
+ commitCellEdit, mirroring text edit; Tab/Enter navigate, Tab off the end
+ appends a row). Column widths drag via `.bento-col-handle` overlays
+ (updateTableHandles/startColResize — live DOM update during drag, commit on
+ release; needs real-mouse QA like Moveable). Panel: row/col steppers, header
+ toggle, style presets (Lined/Zebra/Boxed/Minimal), colours, and a
+ table→chart bridge (buildTableProps/tableToChart: first column = labels,
+ first numeric column = series). Morphs as a BOX (cell content does not
+ morph); under collab `rows` is a whole-value LWW register (concurrent
+ different-cell edits are last-writer-wins — documented limitation).
- **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/docs/agents.md b/docs/agents.md
index a0602980..d96169ea 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -39,7 +39,8 @@ each kind of content to the feature built for it:
| When the material is… | Reach for | Why |
|---|---|---|
-| numbers, %, quantities, "A vs B", **any table** | a **chart** element | data as bars/lines reads instantly; as bullets it doesn't |
+| numbers to **compare visually** (trend, magnitude, share) | a **chart** element | bars/lines read instantly |
+| a **comparison / spec / pricing / feature grid** (rows × columns of labels + values) | a **table** element | structured cells beat 20 hand-placed text boxes; it styles cohesively |
| consecutive slides about the **same thing changing** (before/after, process steps, a metric across stages) | **morph**: same element `id` on both slides + `transition:"morph"` on the later one | the shared elements glide; this is Bento's signature and is *almost always missed* |
| a point to **drill into** (a definition, "click to see how", a sub-topic) | a **state slide** (`stateOf` + element `link`) | keeps the linear story clean; the detail is one click away |
| a **hero / full-slide image** | full-bleed image + scrim rect + text, with **ken-burns** | static photos feel dead; a slow drift feels intentional |
@@ -72,6 +73,20 @@ each kind of content to the feature built for it:
"fx":{"enter":"fade-up"} }
```
+**A comparison table** — a real HTML table; cells are the same inline-html subset as text:
+```json
+{ "id":"tbl1","type":"table","x":240,"y":220,"w":800,"h":260,"rotation":0,"opacity":1,
+ "header":true,
+ "columns":[{"w":1.4},{"w":1},{"w":1}],
+ "rows":[
+ { "cells":[{"html":"Plan"},{"html":"Price","align":"right"},{"html":"Seats","align":"right"}] },
+ { "cells":[{"html":"Team"},{"html":"$29"},{"html":"5"}] },
+ { "cells":[{"html":"Business"},{"html":"$79"},{"html":"25"}] } ],
+ "style":{"headerBg":"#1E2A3A","headerColor":"#fff","zebra":"rgba(30,42,58,0.05)",
+ "borderColor":"rgba(30,42,58,0.14)","borderWidth":1,"cellPadX":16,"cellPadY":11,
+ "fontSize":18,"color":"#1E2A3A","radius":10} }
+```
+
**A state slide reached by clicking a node** — parent slide has the clickable element, the state lives adjacent:
```json
// on the parent slide, an element the viewer clicks:
@@ -140,6 +155,12 @@ each kind of content to the feature built for it:
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.
+- **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?`,
+ `borderColor`, `borderWidth`, `cellPadX`, `cellPadY`, `fontSize`, `color`,
+ `radius`). Renders as a real HTML table. Use for comparison/spec/pricing
+ grids — NOT for numeric trends (use a chart).
- **svg**: `asset` or `markup` for static artwork. Prefer composing rects/
texts/paths — those stay editable and can morph.
diff --git a/scripts/postbuild-compress.mjs b/scripts/postbuild-compress.mjs
index 7ad21483..c334053d 100644
--- a/scripts/postbuild-compress.mjs
+++ b/scripts/postbuild-compress.mjs
@@ -86,8 +86,10 @@ const TOOLING_COMMENT = `<!--
MAKE A GREAT DECK, NOT JUST A CORRECT ONE
Bento's whole point is motion + interactivity. A wall of text slides wastes
it. When the source material contains ↓, reach for the feature:
- · numbers / %, quantities, "A vs B", any table → a CHART element
- (preset bar|line|pie|scatter). Never list data as bullet text.
+ · numbers to compare visually (trend, magnitude, share) → a CHART
+ element (preset bar|line|pie|scatter). Never list data as bullet text.
+ · a comparison / spec / pricing / feature grid → a TABLE element
+ (columns[] + rows[] of cells + a style object). Not a pile of textboxes.
· consecutive slides about the SAME thing changing (before/after, process
steps, a metric across stages) → give the shared elements the SAME id
on both slides and set the later slide's transition to "morph". This is
diff --git a/skills/bento-deck/SKILL.md b/skills/bento-deck/SKILL.md
index c4af32f3..310707ab 100644
--- a/skills/bento-deck/SKILL.md
+++ b/skills/bento-deck/SKILL.md
@@ -34,7 +34,9 @@ the console.
is it a stat? a table? a process? a definition to expand? a photo?
3. **Map material → feature (do NOT default to bullet text).** This is the
step that makes it a Bento deck rather than a slideshow of paragraphs:
- - numbers / %, quantities, "A vs B", **any table** → a **chart** element
+ - numbers to compare visually (trend, magnitude, share) → a **chart** element
+ - a comparison / spec / pricing / feature grid → a **table** element
+ (`columns` weights + `rows` of `cells` + a `style` object)
- consecutive slides about the **same thing changing** → **morph**: give
shared elements the same `id` on both slides + `transition:"morph"` on
the later one (Bento's signature move — reach for it liberally)
diff --git a/slides/package.json b/slides/package.json
index a35cb0ac..8289e622 100644
--- a/slides/package.json
+++ b/slides/package.json
@@ -1,7 +1,7 @@
{
"name": "bento-slides",
"private": true,
- "version": "0.9.2",
+ "version": "0.9.3",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.ts
index f99e5c28..dcb00a38 100644
--- a/slides/src/editor/canvas.ts
+++ b/slides/src/editor/canvas.ts
@@ -6,7 +6,7 @@ import Moveable from 'moveable'
import Selecto from 'selecto'
import type { Store } from '../store'
import { t } from '../i18n'
-import { uid, type SlideElement } from '../model'
+import { uid, type SlideElement, type TableElement } from '../model'
import { renderSlide, sanitizeHtml } from '../render'
import { autoformatAtCaret, clearAutoformat, markdownToHtml, undoAutoformat } from './markdown'
import { PathEditor } from './patheditor'
@@ -26,6 +26,8 @@ export class SlideCanvas {
private zoom = 1
private zoomLabel: HTMLElement | null = null
private editing: HTMLElement | null = null
+ /** when editing a table cell, which cell (else null → text element edit) */
+ private editingCell: { r: number; c: number } | null = null
private pathEditor!: PathEditor
private comments!: CommentsUI
@@ -109,8 +111,10 @@ export class SlideCanvas {
}, true)
this.stage.addEventListener('dblclick', (ev) => {
- const el = (ev.target as HTMLElement).closest<HTMLElement>('.bento-el-text')
- if (el) this.startTextEdit(el)
+ const textEl = (ev.target as HTMLElement).closest<HTMLElement>('.bento-el-text')
+ if (textEl) { this.startTextEdit(textEl); return }
+ const td = (ev.target as HTMLElement).closest<HTMLElement>('.bento-el-table td[data-c]')
+ if (td) this.editCellFromTd(td)
})
new ResizeObserver(() => this.relayout()).observe(wrap)
@@ -501,6 +505,79 @@ export class SlideCanvas {
// Keep Selecto's continue-select memory in lockstep with the store —
// otherwise shift-click resurrects targets from a previously shown slide.
this.selecto.setSelectedTargets(targets)
+ this.updateTableHandles()
+ }
+
+ // --- column resize handles (single selected table) --------------------------
+
+ /** Show draggable dividers on the boundaries of a lone selected table. */
+ private updateTableHandles() {
+ this.surface?.querySelectorAll('.bento-col-handle').forEach((h) => h.remove())
+ if (this.editing) return
+ const ids = this.store.selection
+ if (ids.length !== 1) return
+ const el = this.store.element(ids[0])
+ if (!el || el.type !== 'table' || el.columns.length < 2) return
+ const node = this.surface?.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
+ if (!node) return
+ const total = el.columns.reduce((s, c) => s + (c.w || 0), 0) || 1
+ let acc = 0
+ for (let i = 0; i < el.columns.length - 1; i++) {
+ acc += el.columns[i].w || 0
+ const handle = document.createElement('div')
+ handle.className = 'bento-col-handle'
+ handle.style.cssText =
+ `position:absolute;top:0;height:${el.h}px;width:11px;` +
+ `left:${(acc / total) * el.w - 5.5}px;cursor:col-resize;z-index:5;`
+ handle.addEventListener('pointerdown', (ev) => this.startColResize(ev, el.id, i))
+ node.appendChild(handle)
+ }
+ }
+
+ /** Drag a column divider: adjust the two adjacent weights, commit on release. */
+ private startColResize(ev: PointerEvent, id: string, i: number) {
+ ev.preventDefault()
+ ev.stopPropagation()
+ const el = this.store.element(id)
+ if (!el || el.type !== 'table') return
+ const node = this.surface?.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(id)}"]`)
+ if (!node) return
+ const startX = ev.clientX
+ const w0 = el.columns[i].w || 0
+ const w1 = el.columns[i + 1].w || 0
+ const pair = w0 + w1
+ const min = pair * 0.12
+ const cols = node.querySelectorAll<HTMLElement>('col')
+ const handles = [...node.querySelectorAll<HTMLElement>('.bento-col-handle')]
+ const total = el.columns.reduce((s, c) => s + (c.w || 0), 0) || 1
+ let live0 = w0
+ let live1 = w1
+ const onMove = (e: PointerEvent) => {
+ const dFrac = ((e.clientX - startX) / this.scale / el.w) * total
+ live0 = Math.min(Math.max(w0 + dFrac, min), pair - min)
+ live1 = pair - live0
+ // live DOM update only — no store write until release
+ if (cols[i]) cols[i].style.width = `${(live0 / total) * 100}%`
+ if (cols[i + 1]) cols[i + 1].style.width = `${(live1 / total) * 100}%`
+ let a = 0
+ for (let k = 0; k < el.columns.length - 1; k++) {
+ a += k === i ? live0 : k === i + 1 ? live1 : el.columns[k].w || 0
+ if (handles[k]) handles[k].style.left = `${(a / total) * el.w - 5.5}px`
+ }
+ }
+ const onUp = () => {
+ window.removeEventListener('pointermove', onMove)
+ window.removeEventListener('pointerup', onUp)
+ this.store.commit(() => {
+ const tb = this.store.element(id) as TableElement
+ if (tb?.columns[i] && tb.columns[i + 1]) {
+ tb.columns[i].w = live0
+ tb.columns[i + 1].w = live1
+ }
+ })
+ }
+ window.addEventListener('pointermove', onMove)
+ window.addEventListener('pointerup', onUp)
}
// --- moveable -------------------------------------------------------------
@@ -689,6 +766,15 @@ export class SlideCanvas {
return
}
if (this.editing) {
+ // editing a table cell: clicking a DIFFERENT cell switches to it
+ if (this.editingCell) {
+ const td = (target as HTMLElement)?.closest?.<HTMLElement>('td[data-c]')
+ if (td && this.editing.contains(td)) {
+ const already = Number(td.dataset.r) === this.editingCell.r && Number(td.dataset.c) === this.editingCell.c
+ if (!already) { this.editCellFromTd(td); e.stop(); return }
+ return // same cell: let contentEditable place the caret
+ }
+ }
// clicking outside the text being edited commits it; inside, do nothing
if (!this.editing.contains(target)) this.commitTextEdit()
e.stop()
@@ -776,6 +862,7 @@ export class SlideCanvas {
commitTextEdit() {
const node = this.editing
if (!node) return
+ if (this.editingCell) { this.commitCellEdit(node); return }
this.editing = null
this.onTextEditChange?.(undefined)
const inner = node.querySelector<HTMLElement>('.bento-text-inner')
@@ -797,6 +884,110 @@ export class SlideCanvas {
}
}
+ // --- table cell editing -----------------------------------------------------
+
+ /** Enter cell editing from a clicked/dbl-clicked <td> (re-queries fresh). */
+ private editCellFromTd(td: HTMLElement) {
+ const tableNode = td.closest<HTMLElement>('.bento-el-table')
+ const id = tableNode?.dataset.elId
+ if (!id) return
+ this.editCellAt(id, Number(td.dataset.r), Number(td.dataset.c))
+ }
+
+ /** Commit any current edit, then edit cell (r,c) of table `id`. */
+ private editCellAt(id: string, r: number, c: number) {
+ this.commitTextEdit()
+ const td = this.surface?.querySelector<HTMLElement>(
+ `[data-el-id="${CSS.escape(id)}"] td[data-r="${r}"][data-c="${c}"]`)
+ if (!td) return
+ const node = td.closest<HTMLElement>('.bento-el-table')
+ const inner = td.querySelector<HTMLElement>('.bento-cell-inner')
+ if (!node || !inner) return
+ this.editing = node
+ this.editingCell = { r, c }
+ node.classList.add('bento-editing')
+ inner.contentEditable = 'true'
+ inner.focus()
+ document.getSelection()?.selectAllChildren(inner)
+ this.syncTargets()
+ this.onTextEditChange?.(id)
+
+ inner.addEventListener('keydown', (ev) => {
+ ev.stopPropagation()
+ if (ev.key === 'Escape') { ev.preventDefault(); this.commitTextEdit(); return }
+ if (ev.key === 'Tab') { ev.preventDefault(); this.moveCell(ev.shiftKey ? -1 : 1, 'cell'); return }
+ if (ev.key === 'Enter' && !ev.shiftKey) { ev.preventDefault(); this.moveCell(1, 'row'); return }
+ if (ev.metaKey || ev.ctrlKey) {
+ if (ev.key.toLowerCase() === 'z' && !ev.shiftKey) { if (undoAutoformat()) ev.preventDefault(); return }
+ const cmd = { b: 'bold', i: 'italic', u: 'underline' }[ev.key.toLowerCase()]
+ if (cmd) { ev.preventDefault(); document.execCommand(cmd) }
+ }
+ })
+ inner.addEventListener('input', () => { if (!autoformatAtCaret()) clearAutoformat() })
+ inner.addEventListener('paste', (ev) => {
+ const text = ev.clipboardData?.getData('text/plain')
+ if (!text) return
+ ev.preventDefault()
+ document.execCommand('insertHTML', false, sanitizeHtml(markdownToHtml(text)))
+ })
+ inner.addEventListener('blur', () => this.commitTextEdit(), { once: true })
+ }
+
+ private commitCellEdit(node: HTMLElement) {
+ const cell = this.editingCell!
+ const id = node.dataset.elId
+ this.editing = null
+ this.editingCell = null
+ this.onTextEditChange?.(undefined)
+ node.classList.remove('bento-editing')
+ const inner = node.querySelector<HTMLElement>(
+ `td[data-r="${cell.r}"][data-c="${cell.c}"] .bento-cell-inner`)
+ if (!inner || !id) return
+ inner.contentEditable = 'false'
+ const html = sanitizeHtml(inner.innerHTML.replace(/\u200B/g, '').replace(/\\([*_~`-])/g, '$1'))
+ const el = this.store.element(id)
+ if (el && el.type === 'table' && el.rows[cell.r]?.cells[cell.c] && el.rows[cell.r].cells[cell.c].html !== html) {
+ this.store.commit(() => {
+ const tb = this.store.element(id) as TableElement
+ if (tb.rows[cell.r]?.cells[cell.c]) tb.rows[cell.r].cells[cell.c].html = html
+ })
+ } else {
+ this.syncTargets()
+ }
+ }
+
+ /** Tab/Enter navigation between cells; Tab off the last cell appends a row. */
+ private moveCell(dir: 1 | -1, mode: 'cell' | 'row') {
+ const cur = this.editingCell
+ const id = this.editing?.dataset.elId
+ if (!cur || !id) return
+ const el = this.store.element(id)
+ if (!el || el.type !== 'table') return
+ const nCols = el.columns.length
+ const nRows = el.rows.length
+ let r = cur.r
+ let c = cur.c
+ if (mode === 'row') {
+ if (r + dir < 0 || r + dir >= nRows) { this.commitTextEdit(); return }
+ r += dir
+ } else {
+ const idx = r * nCols + c + dir
+ if (idx < 0) { this.commitTextEdit(); return }
+ if (idx >= nRows * nCols) {
+ this.commitTextEdit()
+ this.store.commit(() => {
+ const tb = this.store.element(id) as TableElement
+ tb.rows.push({ cells: tb.columns.map(() => ({ html: '' })) })
+ })
+ this.editCellAt(id, nRows, 0)
+ return
+ }
+ r = Math.floor(idx / nCols)
+ c = idx % nCols
+ }
+ this.editCellAt(id, r, c)
+ }
+
get isEditingText() {
return !!this.editing
}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index fa1f68ec..092201cd 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -4,7 +4,7 @@
import type { Store } from '../store'
import {
FORMAT_VERSION,
- applyLayout, builtinLayouts, defaultChart, defaultImage, defaultShape, defaultText,
+ applyLayout, builtinLayouts, defaultChart, defaultImage, defaultShape, defaultTable, defaultText,
instantiateLayout, layoutElementIds, newDocId, uid,
type ShapeKind, type Slide, type SlideElement,
} from '../model'
@@ -181,6 +181,7 @@ export class Editor {
btn(ICONS.text, t('Text'), () => this.canvas.insert(defaultText({ y: 120 + Math.random() * 200 }), true)),
this.shapeDropdown(),
btn(ICONS.image, t('Image'), () => this.pickImage()),
+ btn(ICONS.table, t('Table'), () => this.canvas.insert(defaultTable())),
btn(ICONS.chart, t('Chart'), () => this.canvas.insert(defaultChart(CHART_PRESETS.bar()))),
)
const commentB = btn(ICONS.comment, t('Comment'), () => this.canvas.toggleCommentMode(),
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 0e739b2d..7a36583e 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -3,7 +3,7 @@
// into a single undo checkpoint.
import type { Store } from '../store'
-import { uid, type ChartElement, type LineEnding, type ShapeElement, type Slide, type SlideElement, type TextElement, type TransitionKind } from '../model'
+import { defaultChart, uid, type ChartElement, type LineEnding, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind } from '../model'
import { CHART_PRESETS } from '../charts'
import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'
import { ICONS } from '../icons'
@@ -286,7 +286,7 @@ export class PropsPanel {
}
private buildElementPanel(el: SlideElement) {
- this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram', chart: 'Chart' }[el.type])
+ this.section({ text: 'Text', shape: 'Shape', image: 'Image', svg: 'Diagram', chart: 'Chart', table: 'Table' }[el.type])
this.opsRow([el])
this.section(t('Arrange'))
@@ -355,6 +355,7 @@ export class PropsPanel {
if (el.type === 'shape') this.buildShapeProps(el)
if (el.type === 'image') this.buildImageProps(el)
if (el.type === 'chart') this.buildChartProps(el)
+ if (el.type === 'table') this.buildTableProps(el)
this.buildPresentingProps(el)
@@ -802,6 +803,116 @@ export class PropsPanel {
this.host.appendChild(ta)
}
+ private buildTableProps(el: TableElement) {
+ const stepper = (label: string, count: number, onDelta: (d: number) => void) => {
+ const wrap = document.createElement('div')
+ wrap.className = 'ed-stepper'
+ const minus = this.opBtn('−', t('Remove'), () => onDelta(-1))
+ const val = document.createElement('span')
+ val.className = 'ed-stepper-val'
+ val.textContent = String(count)
+ const plus = this.opBtn('+', t('Add'), () => onDelta(1))
+ wrap.append(minus, val, plus)
+ this.row(label, wrap)
+ }
+ const cols = el.columns.length
+ const rows = el.rows.length
+ stepper(t('Columns'), cols, (d) => this.mutate(el.id, (e) => {
+ const tb = e as TableElement
+ if (d > 0) { tb.columns.push({ w: 1 }); tb.rows.forEach((r) => r.cells.push({ html: '' })) }
+ else if (tb.columns.length > 1) { tb.columns.pop(); tb.rows.forEach((r) => r.cells.pop()) }
+ }, true))
+ stepper(t('Rows'), rows, (d) => this.mutate(el.id, (e) => {
+ const tb = e as TableElement
+ const minRows = tb.header ? 2 : 1
+ if (d > 0) tb.rows.push({ cells: tb.columns.map(() => ({ html: '' })) })
+ else if (tb.rows.length > minRows) tb.rows.pop()
+ }, true))
+
+ this.row(t('Header row'), this.toggle(el.header, (v) => this.mutate(el.id, (e) => {
+ (e as TableElement).header = v
+ }, true)))
+
+ // one-tap looks that all work within the fixed-grid renderer
+ const st = el.style
+ const preset = st.borderWidth && st.zebra ? 'Boxed'
+ : st.borderWidth ? 'Lined'
+ : st.zebra ? 'Zebra'
+ : 'Minimal'
+ this.section(t('Style'))
+ this.row(t('Preset'), this.select(['Lined', 'Zebra', 'Boxed', 'Minimal'], preset, (v) =>
+ this.mutate(el.id, (e) => {
+ const s = (e as TableElement).style
+ s.borderWidth = v === 'Lined' || v === 'Boxed' ? 1 : 0
+ s.zebra = v === 'Zebra' || v === 'Boxed' ? 'rgba(30,42,58,0.05)' : undefined
+ if (v === 'Minimal') { s.headerBg = 'transparent'; s.headerColor = s.color }
+ else if (s.headerBg === 'transparent') { s.headerBg = '#1E2A3A'; s.headerColor = '#FFFFFF' }
+ }, true)))
+
+ this.row(t('Header fill'), this.colorAlpha(st.headerBg, (v, fin) =>
+ this.mutate(el.id, (e) => { (e as TableElement).style.headerBg = v }, fin)))
+ this.row(t('Header text'), this.colorAlpha(st.headerColor, (v, fin) =>
+ this.mutate(el.id, (e) => { (e as TableElement).style.headerColor = v }, fin)))
+ this.row(t('Text'), this.colorAlpha(st.color, (v, fin) =>
+ this.mutate(el.id, (e) => { (e as TableElement).style.color = v }, fin)))
+ this.row(t('Grid lines'), this.colorAlpha(st.borderColor, (v, fin) =>
+ this.mutate(el.id, (e) => { (e as TableElement).style.borderColor = v }, fin)))
+
+ const grid = document.createElement('div')
+ grid.className = 'ed-grid2'
+ grid.append(
+ this.mini(t('Font'), st.fontSize, (v) => this.mutate(el.id, (e) =>
+ { (e as TableElement).style.fontSize = Math.max(v, 6) }, true)),
+ this.mini(t('Radius'), st.radius, (v) => this.mutate(el.id, (e) =>
+ { (e as TableElement).style.radius = Math.max(v, 0) }, true)),
+ this.mini(t('Pad X'), st.cellPadX, (v) => this.mutate(el.id, (e) =>
+ { (e as TableElement).style.cellPadX = Math.max(v, 0) }, true)),
+ this.mini(t('Pad Y'), st.cellPadY, (v) => this.mutate(el.id, (e) =>
+ { (e as TableElement).style.cellPadY = Math.max(v, 0) }, true)),
+ )
+ this.host.appendChild(grid)
+
+ const hint = document.createElement('p')
+ hint.className = 'ed-hint'
+ hint.textContent = t('Double-click a cell to edit. Tab moves across, Enter down.')
+ this.host.appendChild(hint)
+
+ const toChart = document.createElement('button')
+ toChart.className = 'ed-btn ed-btn-block'
+ toChart.textContent = t('Make a chart from this table →')
+ toChart.title = t('Create a bar chart from the numbers in this table (first column = labels)')
+ toChart.addEventListener('click', () => this.tableToChart(el))
+ this.host.appendChild(toChart)
+ }
+
+ /** Bridge: build a bar chart from a table's numeric columns and insert it. */
+ private tableToChart(el: TableElement) {
+ const bodyRows = el.header ? el.rows.slice(1) : el.rows
+ const strip = (html: string) => html.replace(/<[^>]*>/g, '').replace(/&[a-z]+;/gi, '').trim()
+ const labels = bodyRows.map((r) => strip(r.cells[0]?.html ?? ''))
+ // find the first body column (after labels) that parses as numbers
+ let dataCol = -1
+ for (let c = 1; c < el.columns.length; c++) {
+ if (bodyRows.some((r) => !Number.isNaN(parseFloat(strip(r.cells[c]?.html ?? ''))))) { dataCol = c; break }
+ }
+ if (dataCol < 0) { this.toast(t('No numeric column found to chart')); return }
+ const nums = bodyRows.map((r) => parseFloat(strip(r.cells[dataCol]?.html ?? '')) || 0)
+ const headerRow = el.header ? el.rows[0] : null
+ const seriesName = headerRow ? strip(headerRow.cells[dataCol]?.html ?? '') : ''
+ const option = {
+ xAxis: { type: 'category', data: labels },
+ yAxis: { type: 'value' },
+ series: [{ type: 'bar', name: seriesName, data: nums, itemStyle: { color: '#5E7699' } }],
+ tooltip: { trigger: 'item', formatter: '{b}: {c}' },
+ }
+ 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',
+ })
+ this.store.commit(() => this.store.slide.elements.push(chart))
+ this.store.select([chart.id])
+ this.toast(t('Chart created from table'))
+ }
+
private buildImageProps(el: SlideElement) {
this.section(t('Image'))
this.row(t('Fit'), this.select(['contain', 'cover', 'fill'], (el as any).fit, (v) =>
@@ -1129,6 +1240,15 @@ export class PropsPanel {
return sel
}
+ private toggle(value: boolean, onChange: (v: boolean) => void): HTMLElement {
+ const cb = document.createElement('input')
+ cb.type = 'checkbox'
+ cb.className = 'ed-toggle'
+ cb.checked = value
+ cb.addEventListener('change', () => onChange(cb.checked))
+ return cb
+ }
+
private opBtn(icon: string, title: string, onClick: () => void): HTMLElement {
const btn = document.createElement('button')
btn.className = 'ed-btn ed-btn-icon'
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index abbbe489..759c89ae 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -318,4 +318,22 @@ export const de: Catalog = {
"Passwords do not match": "Passwörter stimmen nicht überein",
"Cancel": "Abbrechen",
"Set password": "Passwort festlegen",
+ "Table": "Tabelle",
+ "Columns": "Spalten",
+ "Rows": "Zeilen",
+ "Header row": "Kopfzeile",
+ "Style": "Stil",
+ "Header fill": "Kopf-Füllung",
+ "Header text": "Kopf-Text",
+ "Grid lines": "Gitterlinien",
+ "Radius": "Radius",
+ "Pad X": "Abst. X",
+ "Pad Y": "Abst. Y",
+ "Remove": "Entfernen",
+ "Add": "Hinzufügen",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "Zum Bearbeiten Zelle doppelklicken. Tab wechselt seitwärts, Enter nach unten.",
+ "Make a chart from this table →": "Diagramm aus dieser Tabelle erstellen →",
+ "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",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index 56a82da7..fbb6573a 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -318,4 +318,22 @@ export const es: Catalog = {
"Passwords do not match": "Las contraseñas no coinciden",
"Cancel": "Cancelar",
"Set password": "Establecer contraseña",
+ "Table": "Tabla",
+ "Columns": "Columnas",
+ "Rows": "Filas",
+ "Header row": "Fila de encabezado",
+ "Style": "Estilo",
+ "Header fill": "Relleno de encabezado",
+ "Header text": "Texto de encabezado",
+ "Grid lines": "Líneas de cuadrícula",
+ "Radius": "Radio",
+ "Pad X": "Margen X",
+ "Pad Y": "Margen Y",
+ "Remove": "Quitar",
+ "Add": "Añadir",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "Haz doble clic en una celda para editar. Tab avanza, Intro baja.",
+ "Make a chart from this table →": "Crear un gráfico con esta tabla →",
+ "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",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 283bb2fb..d9fe427e 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -318,4 +318,22 @@ export const fr: Catalog = {
"Passwords do not match": "Les mots de passe ne correspondent pas",
"Cancel": "Annuler",
"Set password": "Définir le mot de passe",
+ "Table": "Tableau",
+ "Columns": "Colonnes",
+ "Rows": "Lignes",
+ "Header row": "Ligne d’en-tête",
+ "Style": "Style",
+ "Header fill": "Fond d’en-tête",
+ "Header text": "Texte d’en-tête",
+ "Grid lines": "Lignes de grille",
+ "Radius": "Rayon",
+ "Pad X": "Marge X",
+ "Pad Y": "Marge Y",
+ "Remove": "Retirer",
+ "Add": "Ajouter",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "Double-cliquez sur une cellule pour l’éditer. Tab avance, Entrée descend.",
+ "Make a chart from this table →": "Créer un graphique à partir de ce tableau →",
+ "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",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index d8ba3f6c..c5f1d4d8 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -318,4 +318,22 @@ export const it: Catalog = {
"Passwords do not match": "Le password non coincidono",
"Cancel": "Annulla",
"Set password": "Imposta password",
+ "Table": "Tabella",
+ "Columns": "Colonne",
+ "Rows": "Righe",
+ "Header row": "Riga d’intestazione",
+ "Style": "Stile",
+ "Header fill": "Sfondo intestazione",
+ "Header text": "Testo intestazione",
+ "Grid lines": "Linee griglia",
+ "Radius": "Raggio",
+ "Pad X": "Spazio X",
+ "Pad Y": "Spazio Y",
+ "Remove": "Rimuovi",
+ "Add": "Aggiungi",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "Doppio clic su una cella per modificarla. Tab si sposta, Invio scende.",
+ "Make a chart from this table →": "Crea un grafico da questa tabella →",
+ "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",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index b787d928..bfd4ac92 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -318,4 +318,22 @@ export const ja: Catalog = {
"Passwords do not match": "パスワードが一致しません",
"Cancel": "キャンセル",
"Set password": "パスワードを設定",
+ "Table": "表",
+ "Columns": "列",
+ "Rows": "行",
+ "Header row": "見出し行",
+ "Style": "スタイル",
+ "Header fill": "見出しの塗り",
+ "Header text": "見出しの文字",
+ "Grid lines": "罫線",
+ "Radius": "角丸",
+ "Pad X": "余白 X",
+ "Pad Y": "余白 Y",
+ "Remove": "削除",
+ "Add": "追加",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "セルをダブルクリックで編集。Tab で横、Enter で下に移動。",
+ "Make a chart from this table →": "この表からグラフを作成 →",
+ "Create a bar chart from the numbers in this table (first column = labels)": "この表の数値から棒グラフを作成します(最初の列 = ラベル)",
+ "No numeric column found to chart": "グラフ化できる数値列が見つかりません",
+ "Chart created from table": "表からグラフを作成しました",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index d57057b9..de764ea2 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -318,4 +318,22 @@ export const zhHans: Catalog = {
"Passwords do not match": "两次输入的密码不一致",
"Cancel": "取消",
"Set password": "设置密码",
+ "Table": "表格",
+ "Columns": "列",
+ "Rows": "行",
+ "Header row": "标题行",
+ "Style": "样式",
+ "Header fill": "标题填充",
+ "Header text": "标题文字",
+ "Grid lines": "网格线",
+ "Radius": "圆角",
+ "Pad X": "内边距 X",
+ "Pad Y": "内边距 Y",
+ "Remove": "移除",
+ "Add": "添加",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "双击单元格编辑。Tab 右移,Enter 下移。",
+ "Make a chart from this table →": "用此表格生成图表 →",
+ "Create a bar chart from the numbers in this table (first column = labels)": "用此表格中的数字生成柱状图(第一列为标签)",
+ "No numeric column found to chart": "未找到可制图的数值列",
+ "Chart created from table": "已用表格生成图表",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index 38485a4a..ebb39be0 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -318,4 +318,22 @@ export const zhHant: Catalog = {
"Passwords do not match": "兩次輸入的密碼不一致",
"Cancel": "取消",
"Set password": "設定密碼",
+ "Table": "表格",
+ "Columns": "欄",
+ "Rows": "列",
+ "Header row": "標題列",
+ "Style": "樣式",
+ "Header fill": "標題填色",
+ "Header text": "標題文字",
+ "Grid lines": "格線",
+ "Radius": "圓角",
+ "Pad X": "內距 X",
+ "Pad Y": "內距 Y",
+ "Remove": "移除",
+ "Add": "新增",
+ "Double-click a cell to edit. Tab moves across, Enter down.": "雙擊儲存格編輯。Tab 右移,Enter 下移。",
+ "Make a chart from this table →": "用此表格產生圖表 →",
+ "Create a bar chart from the numbers in this table (first column = labels)": "用此表格中的數字產生長條圖(第一欄為標籤)",
+ "No numeric column found to chart": "找不到可製圖的數值欄",
+ "Chart created from table": "已用表格產生圖表",
}
diff --git a/slides/src/icons.ts b/slides/src/icons.ts
index 27542a55..eb93465a 100644
--- a/slides/src/icons.ts
+++ b/slides/src/icons.ts
@@ -25,6 +25,7 @@ export const ICONS = {
sync: svg('<path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/>'),
window: svg('<rect x="3" y="5" width="18" height="14" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/>'),
share: svg('<circle cx="9" cy="8" r="3.2"/><path d="M3.5 20c.6-3.2 2.8-5 5.5-5s4.9 1.8 5.5 5"/><circle cx="17.5" cy="10.5" r="2.4"/><path d="M15.8 15.6c1.9.3 3.6 1.6 4.4 3.9"/>'),
+ table: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="14.5" x2="21" y2="14.5"/><line x1="9" y1="4" x2="9" y2="20"/><line x1="15" y1="4" x2="15" y2="20"/>'),
// shape menu entries
rect: svg('<rect x="3" y="5" width="18" height="14" rx="2"/>'),
ellipse: svg('<ellipse cx="12" cy="12" rx="9" ry="7"/>'),
diff --git a/slides/src/model.ts b/slides/src/model.ts
index fc665d3a..bd6fb3c7 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -168,7 +168,56 @@ export interface ChartElement extends ElementBase {
option: Record<string, unknown>
}
-export type SlideElement = TextElement | ShapeElement | ImageElement | SvgElement | ChartElement
+/** One cell of a table. `html` is the same sanitized inline subset as text. */
+export interface TableCell {
+ html: string
+ align?: 'left' | 'center' | 'right'
+ /** per-cell overrides (default from the table's style) */
+ color?: string
+ bg?: string
+ bold?: boolean
+}
+
+export interface TableRow {
+ cells: TableCell[]
+}
+
+/** Table-wide look. Cohesion lives here; cells carry only overrides. */
+export interface TableStyle {
+ headerBg: string
+ headerColor: string
+ /** stripe colour for alternate body rows; absent = no zebra */
+ zebra?: string
+ borderColor: string
+ borderWidth: number
+ cellPadX: number
+ cellPadY: number
+ fontSize: number
+ fontFamily?: string
+ /** default body-cell text colour */
+ color: string
+ /** outer corner radius (px) */
+ radius: number
+}
+
+/**
+ * A data table rendered as a real HTML <table> (table-layout: fixed) by the
+ * shared renderer — identical on the editor canvas, thumbnails, present and
+ * print. Column widths are fractional weights, normalised at render. Morphs
+ * as a box (position/size + style colours); cell CONTENT does not morph.
+ */
+export interface TableElement extends ElementBase {
+ type: 'table'
+ /** fractional column weights; length = column count */
+ columns: Array<{ w: number }>
+ rows: TableRow[]
+ /** treat row 0 as a styled header row */
+ header: boolean
+ style: TableStyle
+}
+
+export type SlideElement =
+ | TextElement | ShapeElement | ImageElement | SvgElement | ChartElement | TableElement
/**
* A review comment thread. Editor-only metadata: never rendered while
@@ -329,6 +378,36 @@ export function defaultChart(option: Record<string, unknown>, partial: Partial<C
}
}
+export function defaultTable(partial: Partial<TableElement> = {}): TableElement {
+ const cell = (html: string): TableCell => ({ html })
+ return {
+ id: uid('tbl'),
+ type: 'table',
+ x: 240, y: 220, w: 800, h: 260,
+ rotation: 0, opacity: 1,
+ header: true,
+ columns: [{ w: 1 }, { w: 1 }, { w: 1 }],
+ rows: [
+ { cells: [cell('Column A'), cell('Column B'), cell('Column C')] },
+ { cells: [cell('Row 1'), cell('—'), cell('—')] },
+ { cells: [cell('Row 2'), cell('—'), cell('—')] },
+ ],
+ style: {
+ headerBg: '#1E2A3A',
+ headerColor: '#FFFFFF',
+ zebra: 'rgba(30,42,58,0.05)',
+ borderColor: 'rgba(30,42,58,0.14)',
+ borderWidth: 1,
+ cellPadX: 16,
+ cellPadY: 11,
+ fontSize: 18,
+ color: '#1E2A3A',
+ radius: 10,
+ },
+ ...partial,
+ }
+}
+
export function defaultShape(shape: ShapeKind, partial: Partial<ShapeElement> = {}): ShapeElement {
return {
id: uid('s'),
diff --git a/slides/src/render.ts b/slides/src/render.ts
index 2fb1bfb8..a9ea57d6 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -1,7 +1,7 @@
// Shared model → DOM renderer. One code path draws slides everywhere:
// editor canvas, sidebar thumbnails, and Reveal.js sections.
-import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement } from './model'
+import type { BentoDoc, ShapeElement, Slide, SlideElement, SvgElement, TableElement } from './model'
import { chartSnapshotSvg } from './charts'
const SVG_NS = 'http://www.w3.org/2000/svg'
@@ -281,6 +281,51 @@ export function sanitizeHtml(html: string): string {
const VALIGN: Record<string, string> = { top: 'flex-start', middle: 'center', bottom: 'flex-end' }
+/**
+ * Render a table element as a real HTML <table> string (table-layout: fixed).
+ * Column widths are fractional weights normalised to %. Cells carry data-r /
+ * data-c so the editor can target them for in-cell editing.
+ */
+export function renderTableHtml(el: TableElement, doc: BentoDoc): string {
+ const st = el.style
+ const esc = (s: string) => s.replace(/"/g, '&quot;')
+ const totalW = el.columns.reduce((s, c) => s + (c.w || 0), 0) || 1
+ const cols = el.columns
+ .map((c) => `<col style="width:${(((c.w || 0) / totalW) * 100).toFixed(4)}%">`)
+ .join('')
+ const font = esc(st.fontFamily || doc.theme.fontFamily)
+ const border = st.borderWidth ? `border:${st.borderWidth}px solid ${st.borderColor};` : ''
+ const rowsHtml = el.rows
+ .map((row, r) => {
+ const isHeader = el.header && r === 0
+ const bodyIndex = el.header ? r - 1 : r
+ const stripe = !isHeader && st.zebra && bodyIndex % 2 === 1 ? st.zebra : ''
+ const cells = row.cells
+ .map((cell, c) => {
+ const align = cell.align || 'left'
+ const bg = cell.bg || (isHeader ? st.headerBg : stripe || 'transparent')
+ const color = cell.color || (isHeader ? st.headerColor : st.color)
+ const weight = cell.bold || isHeader ? 700 : 400
+ return (
+ `<td data-r="${r}" data-c="${c}" style="${border}padding:${st.cellPadY}px ${st.cellPadX}px;` +
+ `text-align:${align};vertical-align:middle;color:${color};background:${bg};` +
+ `font-weight:${weight};overflow:hidden;word-break:break-word;">` +
+ `<div class="bento-cell-inner">${sanitizeHtml(cell.html || '') || '<br>'}</div></td>`
+ )
+ })
+ .join('')
+ return `<tr data-r="${r}">${cells}</tr>`
+ })
+ .join('')
+ const radius = st.radius ? `border-radius:${st.radius}px;overflow:hidden;` : ''
+ return (
+ `<div class="bento-table-wrap" style="width:100%;height:100%;${radius}">` +
+ `<table class="bento-table" style="width:100%;height:100%;border-collapse:collapse;` +
+ `table-layout:fixed;font-family:${font};font-size:${st.fontSize}px;line-height:1.3;">` +
+ `<colgroup>${cols}</colgroup>${rowsHtml}</table></div>`
+ )
+}
+
/**
* Render one element. The wrapper carries data-el-id (edit-time selection)
* and data-flip-id (GSAP Flip morph matching across slides).
@@ -327,6 +372,10 @@ export function renderElement(el: SlideElement, doc: BentoDoc, opts: RenderOpts
case 'shape':
node.appendChild(shapeSvg(el))
break
+ case 'table':
+ node.dataset.table = '1'
+ node.innerHTML = renderTableHtml(el, doc)
+ break
case 'image': {
const img = document.createElement('img')
img.src = resolveAsset(doc, el.src)
diff --git a/slides/src/styles.css b/slides/src/styles.css
index ec67a37f..9e91980d 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -1383,3 +1383,18 @@ dialog.ed-pwdialog .ed-pwerr { color: #C33; }
color: #0D1B2E;
background: linear-gradient(180deg, #FFB29B, #ED8266);
}
+
+/* ————— tables ————— */
+.bento-el-table { overflow: visible; }
+.bento-el-table .bento-cell-inner { min-height: 1em; }
+/* editor-only affordances */
+.ed-root .bento-el-table td { cursor: text; }
+.bento-col-handle { border-radius: 3px; }
+.bento-col-handle:hover { background: rgba(94, 118, 153, 0.35); }
+.bento-el-table.bento-editing td { cursor: text; }
+
+/* table properties: steppers + toggle */
+.ed-stepper { display: inline-flex; align-items: center; gap: 6px; }
+.ed-stepper .ed-btn-icon { width: 24px; height: 24px; line-height: 1; font-size: 15px; padding: 0; }
+.ed-stepper-val { min-width: 20px; text-align: center; font-variant-numeric: tabular-nums; font-size: 13px; }
+input.ed-toggle { width: 16px; height: 16px; accent-color: #5E7699; cursor: pointer; }