Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: compact input places by layout and role — four more built-in layouts (#491)

nyblnet44ed9a234b6f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2d8d9bb8..d64fd6f9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1404,6 +1404,14 @@ jobs:
slides/node_modules/.bin/esbuild scripts/test-slides-agent-decks.ts --bundle --platform=node --format=esm --outfile="$RUNNER_TEMP/test-slides-agent-decks.mjs"
node "$RUNNER_TEMP/test-slides-agent-decks.mjs"
+ - name: Compact layouts and roles rig
+ # A compact slide names a layout and its elements carry roles: the
+ # layout's frames through model.ts applyLayout (the editor's own
+ # path), ids kept so same-layout slides morph, unknown roles fall
+ # back and are reported, explicit geometry wins, bodies stack, and
+ # AGENTS.md's layout table is checked against the code.
+ run: node scripts/test-slides-compact-layouts.ts
+
- name: Gate parity rig (the load-report collector changes no decision)
# main's untrusted.ts frozen from git at rig time and bundled beside
# the branch's; every checked-in deck plus a hostile corpus goes
diff --git a/AGENTS.md b/AGENTS.md
index dc5c926d..0e0a5adc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -119,6 +119,44 @@ instead of `html` and it converts exactly as pasted markdown does: `**bold**`,
`*italic*`, `` `code` ``, `~~strike~~`, `- bullets` (indent two spaces for a
sub-bullet), `[caption](https://…)`; when both are present `html` wins.
+You need not place anything. Give a slide a `layout` and its elements a
+`role`, leave out geometry and typography, and the layout's frames and type
+are used — the same matching the editor's *Apply layout* does, and slides born
+from the same layout share element ids, so their titles morph. An element that
+DOES carry `x y w h` is placed as given, on top. More `body` elements than the
+layout has body slots stack into the slot top-to-bottom, each sized to its
+text. A role the layout lacks falls back to the body slot and the load report
+says so (`dropped` carries a note with the path). An `image` role takes an
+image element and puts the picture in the slot.
+
+```json
+{ "compact": true, "slides": [
+ { "layout": "title-body", "elements": [
+ { "role": "title", "md": "Three things went right" },
+ { "role": "body", "md": "**Latency** fell 40%." },
+ { "role": "body", "md": "**Uptime** held at 99.97%." } ] },
+ { "layout": "image-right", "elements": [
+ { "role": "title", "md": "The tile" },
+ { "role": "body", "md": "It stays put." },
+ { "type": "image", "role": "image", "src": "data:image/png;base64,…" } ] } ] }
+```
+
+The built-in layouts and their roles (this list is generated from the code by
+`scripts/test-slides-compact-layouts.ts`, so it cannot drift):
+
+- `title` — title, subtitle
+- `title-content` — title, body (also answers to `title-body`)
+- `two-col` — title, body, left, right (also `two-column`; `left`/`right` are
+ the two body slots)
+- `section` — title, kicker
+- `three-cards` — title, card1, card2, card3 (also `cards`)
+- `quote` — quote, attribution
+- `image-left` — image, title, body
+- `image-right` — title, body, image
+
+A deck's own `layouts` (full Slide objects, the shape *Save slide as layout*
+writes) may be named the same way.
+
Load it with `window.bento.loadDoc(json)` or *Save ▾ Replace from JSON…*;
`window.bento.compact()` (or *Save ▾ Copy compact JSON*) gives a deck back in
this shape. A compact document passes the untrusted shape gate on the way in,
@@ -130,6 +168,7 @@ const r = window.bento.loadDoc(json)
// r.dropped → [{ path: '/slides/0/elements/2/fontSze', reason: 'unknown key for a text element' }, …]
// r.expanded → fields filled from the editor's defaults
// r.fitted → text boxes sized to their text
+// r.laidOut → slides placed by layout + role
// r.findings → window.bento.validate() on the loaded deck (overflow, off-canvas, dead links …)
```
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50ba14ff..0c57a542 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,18 @@ pre-1.0.
## [Unreleased]
+- **An agent can place a slide by layout and role.** In the compact form a
+ slide may say `"layout": "title-body"` and its elements carry a `role`
+ (`title`, `body`, `subtitle`, `kicker`, `quote`, `attribution`, `image`,
+ `card1`…) instead of coordinates and typography: the layout's frames and
+ type are used, the same way *Apply layout* fills a slide in the editor, and
+ slides born from the same layout still morph their chrome. Several `body`
+ paragraphs stack into the slot, each sized to its text; an element that
+ carries its own `x y w h` is placed as given. Four new built-in layouts —
+ *Three cards*, *Quote*, *Image left*, *Image right* — appear in the layout
+ picker for everyone, next to the five that were there. The file on disk is
+ unchanged: the layout is applied on load, and what is saved is the placed
+ slide.
- **The format has a schema, and every file says where it is.** A JSON
Schema for the bento/slides document is generated from the same tables the
app uses to check what it loads, so it cannot describe a deck the app would
diff --git a/scripts/fixtures/agent-decks/layouts-and-roles.json b/scripts/fixtures/agent-decks/layouts-and-roles.json
new file mode 100644
index 00000000..69a3af15
--- /dev/null
+++ b/scripts/fixtures/agent-decks/layouts-and-roles.json
@@ -0,0 +1,40 @@
+{
+ "compact": true,
+ "title": "Platform roadmap",
+ "slides": [
+ { "layout": "title", "elements": [
+ { "role": "title", "md": "Platform roadmap" },
+ { "role": "subtitle", "md": "What ships in Q4, and why" }
+ ] },
+ { "layout": "section", "elements": [
+ { "role": "kicker", "md": "PART 1" },
+ { "role": "title", "md": "Where we are" }
+ ] },
+ { "layout": "title-body", "elements": [
+ { "role": "title", "md": "Three things went right" },
+ { "role": "body", "md": "**Latency** fell 40% after the cache rewrite." },
+ { "role": "body", "md": "**Uptime** held at 99.97% through two migrations." },
+ { "role": "body", "md": "**Onboarding** dropped from six screens to two." }
+ ] },
+ { "layout": "two-column", "elements": [
+ { "role": "title", "md": "Before and after" },
+ { "role": "left", "md": "- six screens\n- two passwords\n- a PDF to print" },
+ { "role": "right", "md": "- two screens\n- one passkey\n- nothing to print" }
+ ] },
+ { "layout": "three-cards", "elements": [
+ { "role": "title", "md": "Q4 in three cards" },
+ { "role": "card1", "md": "**Sync**\n\nOffline edits merge without conflicts." },
+ { "role": "card2", "md": "**Broadcast**\n\nA deck follows its presenter live." },
+ { "role": "card3", "md": "**Agents**\n\nA deck can be written from a schema." }
+ ] },
+ { "layout": "quote", "elements": [
+ { "role": "quote", "md": "The file is the software." },
+ { "role": "attribution", "md": "README, line one" }
+ ] },
+ { "layout": "image-right", "elements": [
+ { "role": "title", "md": "The tile" },
+ { "role": "body", "md": "Four tiles morph through every slide of the starter deck; this one stays put." },
+ { "type": "image", "role": "image", "src": "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 3'%3E%3Crect width='4' height='3' fill='%23F7A600'/%3E%3C/svg%3E" }
+ ] }
+ ]
+}
diff --git a/scripts/test-slides-compact-layouts.ts b/scripts/test-slides-compact-layouts.ts
new file mode 100644
index 00000000..69383829
--- /dev/null
+++ b/scripts/test-slides-compact-layouts.ts
@@ -0,0 +1,150 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Compact input, round three: placement by layout and role (compact.ts).
+//
+// node scripts/test-slides-compact-layouts.ts
+//
+// WHAT THIS PROVES. A compact slide that names a layout and gives its
+// elements roles expands to EXACTLY the layout's frames with the content
+// applied (through model.ts applyLayout — the same matching the editor's
+// "Apply layout" uses), slides born from the same layout share element ids
+// (so their chrome morphs), an unknown role falls back to the body slot with
+// a load-report note, explicit geometry always wins, more bodies than slots
+// stack into the slot without overlapping (equal shares here; compactload.ts
+// restacks by measured height — source-asserted), the four added built-in
+// layouts carry the roles AGENTS.md says they do, and AGENTS.md's table of
+// layouts and roles is generated from the code so it cannot drift.
+
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, join } from 'node:path'
+import { expandDocWithStats, layoutRoles, findLayout, LAYOUT_ALIASES, STACK_GAP } from '../slides/src/compact.ts'
+import { builtinLayouts, applyLayout, type Slide, type SlideElement, type TextElement, type ImageElement } from '../slides/src/model.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+const root = join(dirname(fileURLToPath(import.meta.url)), '..')
+const read = (f: string) => readFileSync(join(root, f), 'utf8')
+type Obj = Record<string, unknown>
+const els = (s: Slide) => s.elements as unknown as Obj[]
+const text = (s: Slide, id: string) => s.elements.find((e) => e.id === id) as TextElement | undefined
+const frame = (e: SlideElement | undefined) => e ? `${e.x},${e.y},${e.w}x${e.h}` : 'none'
+
+console.log('the built-in layouts and their roles\n')
+const layouts = builtinLayouts()
+const byId = Object.fromEntries(layouts.map((l) => [l.id, l]))
+const expectRoles: Record<string, string[]> = {
+ 'layout-title': ['title', 'subtitle'],
+ 'layout-title-content': ['title', 'body'],
+ 'layout-two-col': ['title', 'body', 'left', 'right'],
+ 'layout-section': ['title', 'kicker'],
+ 'layout-three-cards': ['title', 'card1', 'card2', 'card3'],
+ 'layout-quote': ['quote', 'attribution'],
+ 'layout-image-left': ['image', 'title', 'body'],
+ 'layout-image-right': ['title', 'body', 'image'],
+ 'layout-blank': [],
+}
+ok(layouts.map((l) => l.id).sort().join() === Object.keys(expectRoles).sort().join(), `nine built-in layouts (${layouts.length})`)
+for (const [id, roles] of Object.entries(expectRoles)) {
+ ok(Object.keys(layoutRoles(byId[id])).sort().join() === [...roles].sort().join(), `${id}: roles ${roles.join(', ') || '(none)'}`)
+}
+ok(layoutRoles(byId['layout-two-col']).left === 'l2c-left' && layoutRoles(byId['layout-two-col']).right === 'l2c-right', 'left/right are the first and second body slot of the two-column layout')
+const ids = layouts.flatMap((l) => l.elements.map((e) => e.id))
+ok(new Set(ids).size === ids.length, 'every layout element id is unique across the built-ins (lineage cannot collide)')
+const cards = byId['layout-three-cards']
+ok(['l3c-bg1', 'l3c-card1'].every((id) => cards.elements.find((e) => e.id === id)?.groupId === 'l3c-g1'), 'a card and its backdrop share a groupId (they move as one)')
+ok(['title-body', 'two-column', 'cards'].every((a) => findLayout(a, {})?.id === LAYOUT_ALIASES[a]) && findLayout('quote', {})?.id === 'layout-quote' && findLayout('layout-section', {})?.id === 'layout-section', 'a layout is found by alias, by short name and by id')
+const scaled = findLayout('title-body', { size: { width: 1280, height: 720 } })!
+ok(text(scaled, 'ltc-title')!.w === 1088, 'the layout is scaled to the deck size (1088 wide on a 1280 deck)')
+
+console.log('\nexpansion by role\n')
+const one = expandDocWithStats({ compact: true, slides: [
+ { id: 'a', layout: 'title-body', elements: [{ role: 'title', md: 'Hi' }, { role: 'body', md: '- a\n- b' }] },
+ { id: 'b', layout: 'title-body', elements: [{ role: 'title', md: 'Second' }, { role: 'body', md: 'Text' }] },
+] })
+const a = one.doc.slides[0], b = one.doc.slides[1]
+const ref = findLayout('title-body', { size: { width: 1280, height: 720 } })!
+ok(els(a).map((e) => e.id).join() === ref.elements.map((e) => e.id).join(), 'the slide has exactly the layout\'s elements, in order, with the layout\'s ids')
+ok(frame(text(a, 'ltc-title')) === frame(text(ref, 'ltc-title')) && frame(text(a, 'ltc-body')) === frame(text(ref, 'ltc-body')), 'title and body sit exactly on the layout\'s frames')
+ok(text(a, 'ltc-title')!.html === 'Hi' && /• a<br>• b|<li>a/.test(text(a, 'ltc-body')!.html), 'content applied: the title, and the markdown body as the editor converts it')
+ok(text(a, 'ltc-title')!.fontSize === text(ref, 'ltc-title')!.fontSize && text(a, 'ltc-title')!.fontWeight === 700, 'typography is the layout\'s (44→scaled, weight 700), not the compact default')
+ok(els(a).every((e) => !(e.placeholder && !(e.html as string))), 'no leftover placeholder prompt: every text slot was filled')
+ok(text(b, 'ltc-title')!.id === text(a, 'ltc-title')!.id, 'two slides from the same layout share element ids — their titles morph')
+ok(!('layout' in (a as unknown as Obj)), 'the compact `layout` key never reaches the document')
+ok(one.stats.laidOut === 2 && one.stats.notes.length === 0, 'stats: two slides laid out, no notes')
+
+console.log('\nfallbacks, explicit geometry, images\n')
+const two = expandDocWithStats({ compact: true, slides: [
+ { id: 'c', layout: 'title-body', elements: [
+ { role: 'title', md: 'T' }, { role: 'quote', md: 'Q' },
+ { type: 'shape', shape: 'rect', x: 10, y: 20, w: 30, h: 40, role: 'title' },
+ { type: 'text', role: 'title', x: 700, y: 600, w: 200, h: 50, html: 'Explicit' },
+ ] },
+ { id: 'd', layout: 'section', elements: [{ role: 'body', md: 'No body slot here' }] },
+ { id: 'e', layout: 'no-such-layout', elements: [{ type: 'text', x: 1, y: 2, w: 3, h: 4, html: 'x' }] },
+ { id: 'f', layout: 'image-left', elements: [{ type: 'image', role: 'image', src: 'data:,', fit: 'cover' }, { role: 'title', md: 'Pic' }] },
+ { id: 'g', layout: 'two-column', elements: [{ role: 'left', md: 'L' }, { role: 'right', md: 'R' }] },
+] })
+const c = two.doc.slides[0]
+ok(text(c, 'ltc-body')!.html === 'Q', 'a role the layout has no slot for lands in the body slot')
+ok(two.stats.notes.some((n) => n.path === '/slides/0/elements/1/role' && /no `quote` slot in layout `layout-title-content`; placed as body/.test(n.reason)), 'and the load report says so, with the path')
+const shape = els(c).find((e) => e.type === 'shape' && e.x === 10)
+ok(!!shape && shape.w === 30 && shape.h === 40, 'explicit geometry wins: the shape sits where the author put it, role or not')
+const explicit = els(c).find((e) => e.html === 'Explicit')
+ok(!!explicit && explicit.x === 700 && explicit.y === 600, 'a text with a frame and a role is placed as given, not into the slot')
+ok(text(c, 'ltc-title')!.html === 'T', '…and the slot took the frameless title')
+const d = two.doc.slides[1]
+ok(two.stats.notes.some((n) => n.path === '/slides/1/elements/0/role' && /no body slot; placed at the default frame/.test(n.reason)) && els(d).some((e) => e.html === 'No body slot here'), 'no body slot at all: placed at the default frame, reported')
+const e = two.doc.slides[2]
+ok(two.stats.notes.some((n) => n.path === '/slides/2/layout' && /unknown layout/.test(n.reason)) && els(e).length === 1 && els(e)[0].x === 1, 'an unknown layout: elements placed as given, reported')
+const f = two.doc.slides[3]
+const pic = f.elements.find((x) => x.id === 'lil-image') as ImageElement | undefined
+ok(!!pic && pic.type === 'image' && pic.src === 'data:,' && pic.fit === 'cover' && frame(pic) === frame(text(findLayout('image-left', { size: { width: 1280, height: 720 } })!, 'lil-image')), 'an image donor REPLACES the image slot: picture, fit kept, slot frame and id')
+ok(text(f, 'lil-title')!.html === 'Pic', 'the title beside it is filled')
+const g = two.doc.slides[4]
+ok(text(g, 'l2c-left')!.html === 'L' && text(g, 'l2c-right')!.html === 'R', 'left/right fill the two-column layout\'s columns')
+
+console.log('\nstacking bodies\n')
+const three = expandDocWithStats({ compact: true, slides: [
+ { id: 'h', layout: 'title-body', elements: [{ role: 'title', md: 'T' }, { role: 'body', md: 'p1' }, { role: 'body', md: 'p2' }, { role: 'body', md: 'p3' }] },
+] })
+const h = three.doc.slides[0]
+const slot = text(findLayout('title-body', { size: { width: 1280, height: 720 } })!, 'ltc-body')!
+const bodies = ['ltc-body', 'ltc-body-2', 'ltc-body-3'].map((id) => text(h, id)!)
+ok(bodies.every(Boolean) && bodies.map((x) => x.html).join() === 'p1,p2,p3', 'three bodies → the slot and two more, ids derived from the slot')
+const share = Math.floor((slot.h - STACK_GAP * 2) / 3)
+ok(bodies.every((x) => x.h === share) && bodies.every((x, i) => x.y === slot.y + i * (share + STACK_GAP)), `equal shares of the slot (${share} px) with a ${STACK_GAP} px gap`)
+ok(bodies.every((x, i) => i === 0 || x.y >= bodies[i - 1].y + bodies[i - 1].h), 'no overlap')
+ok(bodies[2].y + bodies[2].h <= slot.y + slot.h, 'the stack stays inside the slot')
+ok(bodies.every((x) => x.x === slot.x && x.w === slot.w && x.fontSize === slot.fontSize), 'each keeps the slot\'s x, width and typography')
+ok(three.stats.stacks.length === 1 && three.stats.stacks[0].ids.join() === 'ltc-body,ltc-body-2,ltc-body-3' && three.stats.autoHeight.length === 3, 'stats name the stack and mark each for measuring')
+const load = read('slides/src/compactload.ts')
+ok(/export function restack\(/.test(load) && /fitAutoHeights\(doc, stats\)\n\s*restack\(doc, stats\)/.test(load), 'compactload restacks by measured height after fitting (browser side)')
+ok(/y \+= el\.h \+ STACK_GAP/.test(load), 'restack lays them top-to-bottom with the same gap')
+ok(/restack\(store\.doc, \{ stacks: parsed\.report\.stacks \}\)/.test(read('slides/src/main.ts')), 'the fonts-ready re-fit restacks too')
+
+console.log('\nthe editor path is the same one\n')
+const donorSlide = { id: 'x', elements: [{ id: 'q', type: 'text', role: 'title', html: 'Hi', x: 0, y: 0, w: 1, h: 1 }] } as unknown as Slide
+const applied = applyLayout(donorSlide, byId['layout-title-content'], new Set(ids))
+ok((applied.find((x) => x.id === 'ltc-title') as TextElement).html === 'Hi', 'applyLayout (the editor\'s "Apply layout") fills a slot by role the same way')
+ok(/applyLayout\(slideForApply, layout, known\)/.test(read('slides/src/compact.ts')), 'compact.ts calls that function, not a copy of it')
+ok(!/layout\?:/.test(read('slides/src/model.ts').slice(read('slides/src/model.ts').indexOf('export interface Slide '))), 'the Slide model gains no `layout` field — input only')
+
+console.log('\nAGENTS.md cannot drift\n')
+const agents = read('AGENTS.md')
+for (const l of layouts) {
+ if (l.id === 'layout-blank') continue
+ const roles = Object.keys(layoutRoles(l))
+ const line = `\`${l.id.replace(/^layout-/, '')}\` — ${roles.join(', ')}`
+ ok(agents.includes(line), `AGENTS.md lists ${line}`)
+}
+ok(/"layout": "title-body"/.test(agents) && /"role": "title"/.test(agents), 'AGENTS.md shows the layout + role example')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/slides/src/compact.ts b/slides/src/compact.ts
index 60d6336c..133b4f3c 100644
--- a/slides/src/compact.ts
+++ b/slides/src/compact.ts
@@ -42,6 +42,26 @@
* and indented sub-bullets, [caption](url)). When both are present `html`
* wins and `md` is dropped; `md` never reaches the document.
*
+ * Round three — placement by layout and role, so an agent never writes a
+ * coordinate it did not choose:
+ *
+ * - A compact slide may say `"layout": "<layout id>"` (a built-in, or one
+ * of the compact document's own `layouts`). Its elements may then omit
+ * geometry and typography and carry a `role` instead — `title`, `body`,
+ * `subtitle`, `kicker`, `quote`, `attribution`, `image`, `card1`…: the
+ * layout is instantiated the way the picker does it (element ids KEPT, so
+ * slides born from the same layout still morph their chrome) and each
+ * role'd element's content is laid onto the layout's slot with that role
+ * through model.ts applyLayout — the same matching "Apply layout" in the
+ * editor uses. An element WITH explicit `x y w h` is placed as given, on
+ * top, role or not. A role the layout has no slot for falls back to the
+ * body slot (or, with no body either, to the editor's default frame) and
+ * the load report says so. `left`/`right` name the first and second
+ * `body` slot of a two-column layout. More `body` elements than body slots
+ * STACK into the slot top-to-bottom: an equal share of the slot's height
+ * each here (pure); compactload.ts then measures each and restacks with a
+ * gap so a title and three paragraphs lay out as a reader expects.
+ *
* Defaults come from the SAME functions model.ts's editor paths use
* (defaultText, defaultShape, …), never a second table — a second table is
* what drifts. Where the editor derives a value from the deck (text colour
@@ -59,7 +79,7 @@ import { markdownToHtml } from './editor/markdown.ts'
import {
FORMAT, FORMAT_VERSION, FONT_STACK,
defaultText, defaultShape, defaultImage, defaultChart, defaultCode, defaultTable, defaultMedia,
- readableInk, isLightBg, newDoc,
+ readableInk, isLightBg, newDoc, builtinLayouts, applyLayout,
type BentoDoc, type Slide, type SlideElement, type ShapeKind,
} from './model.ts'
@@ -198,6 +218,111 @@ export interface ExpandStats {
fromMarkdown: number
/** text elements whose h is provisional — the browser measures these */
autoHeight: Array<{ slide: string; id: string }>
+ /** slides laid out from a layout by role */
+ laidOut: number
+ /** role'd elements the layout had no slot for, and where they went */
+ notes: Array<{ path: string; reason: string }>
+ /** body elements stacked into one slot; compactload.ts restacks these by
+ * measured height (ids in stacking order, the slot's frame) */
+ stacks: Array<{ slide: string; ids: string[]; slot: { x: number; y: number; w: number; h: number } }>
+}
+
+/** The gap between stacked body elements, in slide px. */
+export const STACK_GAP = 16
+
+/** A layout's role → slot map (first slot per role wins; `left`/`right` are
+ * the first and second `body` slot). Exported for AGENTS.md's table rig. */
+export function layoutRoles(layout: Slide): Record<string, string> {
+ const roles: Record<string, string> = {}
+ const bodies: string[] = []
+ for (const el of layout.elements) {
+ if (!el.role) continue
+ if (!(el.role in roles)) roles[el.role] = el.id
+ if (el.role === 'body') bodies.push(el.id)
+ }
+ if (bodies.length >= 2) { roles.left = bodies[0]; roles.right = bodies[1] }
+ return roles
+}
+
+/** The compact `layout` name resolved to a layout for this deck: a built-in
+ * (by id, with or without the `layout-` prefix) or one of the document's. */
+export function findLayout(name: string, doc: Obj): Slide | undefined {
+ const size = doc.size as { width: number; height: number } | undefined
+ const own = Array.isArray(doc.layouts) ? (doc.layouts as Slide[]) : []
+ const all = [...builtinLayouts(size), ...own]
+ const key = LAYOUT_ALIASES[name] ?? name
+ return all.find((l) => l.id === key) ?? all.find((l) => l.id === `layout-${key}`) ?? all.find((l) => l.name?.toLowerCase() === name.toLowerCase())
+}
+
+/** The names an agent says for a built-in, beside the ids themselves. */
+export const LAYOUT_ALIASES: Record<string, string> = {
+ 'title-body': 'layout-title-content',
+ 'two-column': 'layout-two-col',
+ 'cards': 'layout-three-cards',
+}
+
+const hasFrame = (el: Obj) => ['x', 'y', 'w', 'h'].every((k) => typeof el[k] === 'number')
+
+/**
+ * Lay a compact slide's elements onto a layout. `els` are the expanded
+ * elements (full defaults, md converted); `raw` the author's originals, to
+ * know which carried a frame. Returns the slide's element list.
+ */
+function layOut(layout: Slide, els: Obj[], raw: Obj[], slideId: string, si: number, stats: ExpandStats): Obj[] {
+ const roles = layoutRoles(layout)
+ const donors: Obj[] = []
+ const extras: Obj[] = []
+ const bySlot = new Map<string, Obj[]>() // slot id → donors wanting it, in order
+ els.forEach((el, i) => {
+ const role = typeof el.role === 'string' ? el.role : ''
+ if (!role || hasFrame(raw[i])) { extras.push(el); return }
+ let slot = roles[role]
+ if (!slot) {
+ if (roles.body) {
+ slot = roles.body
+ stats.notes.push({ path: `/slides/${si}/elements/${i}/role`, reason: `no \`${role}\` slot in layout \`${layout.id}\`; placed as body` })
+ } else {
+ stats.notes.push({ path: `/slides/${si}/elements/${i}/role`, reason: `no \`${role}\` slot in layout \`${layout.id}\` and no body slot; placed at the default frame` })
+ extras.push(el); return
+ }
+ }
+ // the slot's own role is what applyLayout matches on
+ const slotEl = layout.elements.find((e) => e.id === slot)!
+ const d = { ...el, role: slotEl.role }
+ const list = bySlot.get(slot) ?? []
+ list.push(d); bySlot.set(slot, list)
+ donors.push(d)
+ })
+ // applyLayout consumes donors in document order, one per slot
+ const known = new Set(layout.elements.map((e) => e.id))
+ const slideForApply = { id: slideId, elements: donors as unknown as SlideElement[] } as unknown as Slide
+ const placed = applyLayout(slideForApply, layout, known) as unknown as Obj[]
+ // an image donor that applyLayout turned into the slot keeps the slot id;
+ // a text donor's content is now in the slot copy. Anything unconsumed of
+ // ours is a SECOND body for its slot → stack. (applyLayout appends
+ // unconsumed donors as extras; we take them back out.)
+ const donorIds = new Set(donors.map((d) => d.id))
+ const out: Obj[] = placed.filter((e) => !donorIds.has(e.id as string))
+ for (const [slot, list] of bySlot) {
+ if (list.length < 2) continue
+ const slotEl = out.find((e) => e.id === slot)
+ if (!slotEl || slotEl.type !== 'text') continue
+ const n = list.length
+ const frame = { x: slotEl.x as number, y: slotEl.y as number, w: slotEl.w as number, h: slotEl.h as number }
+ const share = Math.floor((frame.h - STACK_GAP * (n - 1)) / n)
+ const ids: string[] = []
+ list.forEach((d, k) => {
+ const id = k === 0 ? slot : `${slot}-${k + 1}`
+ const copy: Obj = { ...slotEl, id, y: frame.y + k * (share + STACK_GAP), h: Math.max(1, share), html: d.html }
+ if (k === 0) Object.assign(slotEl, copy)
+ else out.splice(out.indexOf(slotEl) + k, 0, copy)
+ ids.push(id)
+ stats.autoHeight.push({ slide: slideId, id })
+ })
+ stats.stacks.push({ slide: slideId, ids, slot: frame })
+ }
+ stats.laidOut++
+ return [...out, ...extras]
}
/**
@@ -217,7 +342,7 @@ export const provisionalHeight = (fontSize: number, lineHeight: number): number
/** expandDoc, and what it did. */
export function expandDocWithStats(input: unknown): { doc: BentoDoc; stats: ExpandStats } {
- const stats: ExpandStats = { expanded: 0, minted: 0, fromMarkdown: 0, autoHeight: [] }
+ const stats: ExpandStats = { expanded: 0, minted: 0, fromMarkdown: 0, autoHeight: [], laidOut: 0, notes: [], stacks: [] }
if (!isCompact(input)) return { doc: input as BentoDoc, stats }
const src = input as Obj
const dd = docDefaults()
@@ -239,16 +364,22 @@ export function expandDocWithStats(input: unknown): { doc: BentoDoc; stats: Expa
doc.slides = slidesIn.map((raw, si) => {
const s0 = isObj(raw) ? raw : {}
const sd = slideDefaults(doc)
- const slide: Obj = { ...sd, ...s0 }
+ // a layout supplies the slide's background/transition unless the author set them
+ const layout = typeof s0.layout === 'string' ? findLayout(s0.layout, doc) : undefined
+ if (typeof s0.layout === 'string' && !layout) stats.notes.push({ path: `/slides/${si}/layout`, reason: `unknown layout \`${s0.layout}\`; elements placed as given` })
+ const slide: Obj = { ...sd, ...(layout ? { background: layout.background, transition: layout.transition } : {}), ...s0 }
+ delete slide.layout
stats.expanded += Object.keys(sd).filter((k) => !(k in s0)).length
if (typeof slide.id !== 'string' || !slide.id) slide.id = `s${si + 1}`
const flat: Obj[] = []
const walk = (v: unknown) => { if (Array.isArray(v)) v.forEach(walk); else if (isObj(v)) flat.push(v) }
walk(s0.elements)
- slide.elements = flat.map((el, i) => {
+ slide.elements = flat.map((el0, i) => {
+ // a role'd or text-bearing element with no `type` is a text box
+ const el: Obj = (!el0.type && (typeof el0.role === 'string' || typeof el0.md === 'string' || typeof el0.html === 'string')) ? { type: 'text', ...el0 } : el0
const defaults = elementDefaults(el, slide, doc) ?? {}
const out: Obj = { ...defaults, ...el }
- stats.expanded += Object.keys(defaults).filter((k) => !(k in el)).length
+ stats.expanded += Object.keys(defaults).filter((k) => !(k in el)).length + (el === el0 ? 0 : 1)
if (typeof out.id !== 'string' || !out.id) { out.id = mintId(slide, el, i); stats.minted++ }
if (el.type === 'text') {
// md → html by the editor's own paste conversion; html wins when both
@@ -264,6 +395,15 @@ export function expandDocWithStats(input: unknown): { doc: BentoDoc; stats: Expa
}
return out as unknown as SlideElement
})
+ if (layout) {
+ const before = new Set(stats.autoHeight.filter((a) => a.slide === slide.id).map((a) => a.id))
+ const laid = layOut(layout, slide.elements as unknown as Obj[], flat, slide.id as string, si, stats)
+ // donors that became slot content no longer exist under their own id:
+ // their provisional heights are the slot's, not to be measured
+ const ids = new Set(laid.map((e) => e.id as string))
+ stats.autoHeight = stats.autoHeight.filter((a) => a.slide !== slide.id || !before.has(a.id) || ids.has(a.id))
+ slide.elements = laid as unknown as SlideElement[]
+ }
return slide as unknown as Slide
})
return { doc: doc as unknown as BentoDoc, stats }
diff --git a/slides/src/compactload.ts b/slides/src/compactload.ts
index 213ff183..e63707b0 100644
--- a/slides/src/compactload.ts
+++ b/slides/src/compactload.ts
@@ -23,7 +23,7 @@
import { parseDoc, type BentoDoc, type Slide, type TextElement } from './model'
import { sanitizeSlide, withDropReport, withPathSegment, type Dropped } from './untrusted'
-import { expandDocWithStats, isCompact, type ExpandStats } from './compact'
+import { expandDocWithStats, isCompact, STACK_GAP, type ExpandStats } from './compact'
import { measureElement } from './measure'
import { validateDoc, type ValidateResult } from './validate'
@@ -42,6 +42,10 @@ export interface LoadReport {
/** the elements still to re-fit once document.fonts settles (heights were
* measured against fallback fonts); empty when fonts were ready */
refit: ExpandStats['autoHeight']
+ /** slides placed by layout + role (compact.ts round three) */
+ laidOut: number
+ /** bodies stacked into one slot — restacked again after a fonts-ready re-fit */
+ stacks: ExpandStats['stacks']
}
/**
@@ -61,7 +65,7 @@ export function parseDocInputReport(json: string, fit = typeof document !== 'und
if (!isCompact(raw)) {
const doc = parseDoc(json)
if (!doc) return null
- return { doc, report: { ok: true, compact: false, dropped: [], expanded: 0, fitted: 0, findings: validateDoc(doc), refit: [] } }
+ return { doc, report: { ok: true, compact: false, dropped: [], expanded: 0, fitted: 0, findings: validateDoc(doc), refit: [], laidOut: 0, stacks: [] } }
}
const { doc: expanded, stats } = expandDocWithStats(raw)
const ex = expanded as unknown as Record<string, unknown>
@@ -77,9 +81,13 @@ export function parseDocInputReport(json: string, fit = typeof document !== 'und
let refit: ExpandStats['autoHeight'] = []
if (fit && stats.autoHeight.length) {
fitted = fitAutoHeights(doc, stats)
+ restack(doc, stats)
if (document.fonts?.status === 'loading') refit = stats.autoHeight
}
- return { doc, report: { ok: true, compact: true, dropped, expanded: stats.expanded, fitted, findings: validateDoc(doc), refit } }
+ // a role the layout had no slot for is reported beside the gate's drops:
+ // same shape, same loop for the agent (path → reason)
+ const all = [...dropped, ...stats.notes.map((n) => ({ path: n.path, reason: n.reason } as Dropped))]
+ return { doc, report: { ok: true, compact: true, dropped: all, expanded: stats.expanded, fitted, findings: validateDoc(doc), refit, laidOut: stats.laidOut, stacks: stats.stacks } }
}
/**
@@ -100,3 +108,25 @@ export function fitAutoHeights(doc: BentoDoc, stats: Pick<ExpandStats, 'autoHeig
}
return n
}
+
+/**
+ * Bodies stacked into one layout slot got an equal share of its height in
+ * compact.ts; now that each has its measured height, lay them top-to-bottom
+ * with STACK_GAP between. If they do not fit the slot they still stack (the
+ * validator's overflow finding says so) — never scaled or clipped here.
+ * Exported for the fonts-ready re-fit.
+ */
+export function restack(doc: BentoDoc, stats: Pick<ExpandStats, 'stacks'>): void {
+ for (const st of stats.stacks) {
+ const slide = doc.slides.find((s) => s.id === st.slide)
+ if (!slide) continue
+ let y = st.slot.y
+ for (const id of st.ids) {
+ const el = slide.elements.find((e) => e.id === id)
+ if (!el) continue
+ el.y = y
+ y += el.h + STACK_GAP
+ }
+ }
+}
+
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 0f18ce27..17727471 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -19,7 +19,7 @@ import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './u
import { i18nApi, t, applyDirection } from './i18n'
import { parseDoc, type BentoDoc, type TextElement } from './model'
import { compactJson } from './compact'
-import { parseDocInputReport, fitAutoHeights, type LoadReport } from './compactload'
+import { parseDocInputReport, fitAutoHeights, restack, type LoadReport } from './compactload'
import { validateDoc, type ValidateOpts } from './validate'
import { buildSchema } from './schema'
import { resolveThemeRefs } from './palette'
@@ -341,7 +341,7 @@ if (location.hash === '#present') {
void document.fonts.ready.then(() => {
if (store.doc !== parsed.doc) return // the deck moved on
const n = fitAutoHeights(store.doc, { autoHeight: parsed.report.refit })
- if (n) store.commit(() => {})
+ if (n) { restack(store.doc, { stacks: parsed.report.stacks }); store.commit(() => {}) }
})
}
return parsed.report
diff --git a/slides/src/model.ts b/slides/src/model.ts
index a2be2628..602cec65 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -1091,6 +1091,13 @@ const bar = (id: string, frame: { x: number; y: number; w: number; h: number }):
rotation: 0, opacity: 1, fill: '#F7A600', stroke: 'transparent', strokeWidth: 0, radius: 2,
})
+/** A card backdrop: a soft panel grouped with the text that sits on it. */
+const card = (id: string, frame: { x: number; y: number; w: number; h: number }, role: string): ShapeElement => ({
+ id, type: 'shape', shape: 'rect', ...frame,
+ rotation: 0, opacity: 1, fill: '#F3F0EA', stroke: 'transparent', strokeWidth: 0, radius: 16,
+ groupId: `l3c-g${role.slice(-1)}`,
+})
+
/**
* The canvas the built-in layout geometry below is authored against.
*
@@ -1171,6 +1178,53 @@ export function builtinLayouts(size?: { width: number; height: number }): Slide[
{ fontSize: 18, fontWeight: 600, color: '#F7A600', letterSpacing: 3, valign: 'middle', role: 'kicker' }),
],
},
+ // Four layouts an agent reaches for (compact input: `layout` + `role`,
+ // compact.ts). Roles are the slot names; the card backdrops share a
+ // groupId per card so a card moves as one in the editor.
+ {
+ id: 'layout-three-cards', name: 'Three cards', background: '#FFFFFF', transition: 'fade', notes: '', elements: [
+ ph('l3c-title', 'Click to add title', { x: 120, y: 72, w: 1360, h: 84 },
+ { fontSize: 44, fontWeight: 700, valign: 'middle', role: 'title' }),
+ card('l3c-bg1', { x: 120, y: 220, w: 426, h: 560 }, 'card1'),
+ ph('l3c-card1', 'First card', { x: 152, y: 252, w: 362, h: 496 },
+ { fontSize: 24, valign: 'top', lineHeight: 1.5, role: 'card1', groupId: 'l3c-g1' }),
+ card('l3c-bg2', { x: 587, y: 220, w: 426, h: 560 }, 'card2'),
+ ph('l3c-card2', 'Second card', { x: 619, y: 252, w: 362, h: 496 },
+ { fontSize: 24, valign: 'top', lineHeight: 1.5, role: 'card2', groupId: 'l3c-g2' }),
+ card('l3c-bg3', { x: 1054, y: 220, w: 426, h: 560 }, 'card3'),
+ ph('l3c-card3', 'Third card', { x: 1086, y: 252, w: 362, h: 496 },
+ { fontSize: 24, valign: 'top', lineHeight: 1.5, role: 'card3', groupId: 'l3c-g3' }),
+ ],
+ },
+ {
+ id: 'layout-quote', name: 'Quote', background: '#FFFFFF', transition: 'fade', notes: '', elements: [
+ bar('lq-bar', { x: 160, y: 300, w: 8, h: 300 }),
+ ph('lq-quote', 'Click to add a quote', { x: 208, y: 300, w: 1232, h: 300 },
+ { fontSize: 48, fontWeight: 500, valign: 'middle', lineHeight: 1.3, role: 'quote' }),
+ ph('lq-attr', 'Who said it', { x: 208, y: 620, w: 1232, h: 44 },
+ { fontSize: 24, color: '#586A80', valign: 'middle', role: 'attribution' }),
+ ],
+ },
+ {
+ id: 'layout-image-left', name: 'Image left', background: '#FFFFFF', transition: 'fade', notes: '', elements: [
+ ph('lil-image', 'Add an image', { x: 120, y: 120, w: 640, h: 660 },
+ { fontSize: 24, color: '#8A98AB', align: 'center', valign: 'middle', role: 'image' }),
+ ph('lil-title', 'Click to add title', { x: 820, y: 120, w: 660, h: 120 },
+ { fontSize: 44, fontWeight: 700, valign: 'middle', role: 'title' }),
+ ph('lil-body', 'Click to add content', { x: 820, y: 264, w: 660, h: 516 },
+ { fontSize: 24, color: '#586A80', valign: 'top', lineHeight: 1.5, role: 'body' }),
+ ],
+ },
+ {
+ id: 'layout-image-right', name: 'Image right', background: '#FFFFFF', transition: 'fade', notes: '', elements: [
+ ph('lir-title', 'Click to add title', { x: 120, y: 120, w: 660, h: 120 },
+ { fontSize: 44, fontWeight: 700, valign: 'middle', role: 'title' }),
+ ph('lir-body', 'Click to add content', { x: 120, y: 264, w: 660, h: 516 },
+ { fontSize: 24, color: '#586A80', valign: 'top', lineHeight: 1.5, role: 'body' }),
+ ph('lir-image', 'Add an image', { x: 840, y: 120, w: 640, h: 660 },
+ { fontSize: 24, color: '#8A98AB', align: 'center', valign: 'middle', role: 'image' }),
+ ],
+ },
{ id: 'layout-blank', name: 'Blank', background: '#FFFFFF', transition: 'fade', notes: '', elements: [] },
]
if (!size || (size.width === LAYOUT_BASE.width && size.height === LAYOUT_BASE.height)) return base
@@ -1207,12 +1261,17 @@ export function applyLayout(
): SlideElement[] {
const donors = slide.elements
const consumed = new Set<SlideElement>()
+ // An `image` slot is a text placeholder ("Add an image") that an IMAGE
+ // donor replaces outright — the picture takes the slot's frame and id, so
+ // slides from the same layout still morph their pictures.
+ const imageSlot = (lel: SlideElement) => lel.role === 'image' && lel.type === 'text'
const findDonor = (lel: SlideElement): SlideElement | undefined => {
const byId = donors.find((e) => !consumed.has(e) && e.id === lel.id)
if (byId) return byId
if (!lel.role) return undefined
return donors.find(
- (e) => !consumed.has(e) && e.role === lel.role && e.type === lel.type && textHasContent(e),
+ (e) => !consumed.has(e) && e.role === lel.role &&
+ ((e.type === lel.type && textHasContent(e)) || (imageSlot(lel) && e.type === 'image')),
)
}
const out: SlideElement[] = layout.elements.map((lel) => {
@@ -1220,7 +1279,16 @@ export function applyLayout(
const d = findDonor(lel)
if (d) {
consumed.add(d)
+ if (imageSlot(lel) && d.type === 'image') {
+ const pic = JSON.parse(JSON.stringify(d)) as SlideElement
+ return { ...pic, id: lel.id, x: lel.x, y: lel.y, w: lel.w, h: lel.h, rotation: lel.rotation, role: 'image' }
+ }
if (copy.type === 'text' && d.type === 'text' && textHasContent(d)) copy.html = d.html
+ if (copy.type === 'image' && d.type === 'image') {
+ copy.src = d.src
+ if (d.fit) copy.fit = d.fit
+ if (d.crop) copy.crop = d.crop
+ }
if (d.link) copy.link = d.link
}
return copy