Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

window.bento.measure(): answer the question the format cannot (#198)

nyblnet6a2ade138ba4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c210261..5f421e37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,18 @@ pre-1.0.
## [Unreleased]
+- **Fit height to text.** A text box that is too short lets its content spill
+ over whatever sits below it, and one that is too tall throws off its
+ alignment against everything beside it — neither is visible in the numbers.
+ The Typography panel now has a button that sets the box to exactly the height
+ its text needs, and says what that is before you press it.
+
+ Underneath is `window.bento.measure()`, which answers the question the format
+ could not: how tall is this string at this width, in this font? Ask it with a
+ spec and you can size a box *before* creating the element, which is what
+ turns generating a deck from guess-then-correct into laying it out right the
+ first time. Requested by thinkbig1979 in #194.
+
- **Entrance animations work on morph slides.** Setting an element to sweep in
from the right on a morph slide gave you a small upward nudge instead: the
morph supplied one fixed entrance for everything new on the slide, and
diff --git a/docs/agents.md b/docs/agents.md
index 9606cb61..ecbe7693 100644
--- a/docs/agents.md
+++ b/docs/agents.md
@@ -168,6 +168,29 @@ each kind of content to the feature built for it:
obvious on screen. This is the only check that catches what the others
cannot; a deck nobody rendered is not finished.
+### `window.bento.measure()` — size text before you place it
+
+The format is absolute pixels, which is what lets morph, the drag handles and
+the renderer work from one representation. The cost falls on you: the height of
+a string at a given width and font is not knowable from the JSON. Stop guessing
+and ask:
+
+```js
+window.bento.measure({ html: 'Long paragraph…', w: 600, fontSize: 28, lineHeight: 1.4 })
+// → { height: 236, width: 600, lines: 6 }
+```
+
+Pass a spec to size text **before** the element exists — which is the point, as
+it lets you lay a slide out correctly the first time. Pass an element id to
+measure one already in the deck, and include `h` in a spec to get `fits` and
+`overflow` back too. It renders through the real renderer, so the answer is
+what the slide will actually do, not an estimate.
+
+Use it for the arithmetic that used to be guesswork: stacking cards in a
+column, deciding whether a heading needs two lines or three, sizing a caption
+under a photo. In the editor, the same thing is a **Fit height to text** button
+in the Typography panel.
+
### `window.bento.validate()`
Open the deck and run it in the browser console. It reports, in one pass, the
diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.ts
index 659cd6c8..88b37ea5 100644
--- a/slides/src/editor/panels.ts
+++ b/slides/src/editor/panels.ts
@@ -7,6 +7,7 @@
import type { Store } from '../store'
import { MEDIA_EMBED_BUDGET, applyChartPalette, defaultChart, internAsset, morphKey, tableStyleFor, uid, type ChartElement, type LineEnding, type MediaElement, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind } from '../model'
import { resolveAsset } from '../render'
+import { measureElement } from '../measure'
import { isMacOS } from '../screens'
import { CHART_PRESETS } from '../charts'
import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'
@@ -864,12 +865,40 @@ export class PropsPanel {
return `slide ${linear}${s.name ? ` — ${s.name}` : ''}`
}
+ /**
+ * "Fit height to text" — set `h` to exactly what the content needs.
+ *
+ * A box that is too short lets its text spill over whatever sits below, and
+ * one that is too tall throws off vertical alignment against its neighbours;
+ * neither is visible in the numbers. The button reports the delta so it is
+ * obvious whether anything was wrong before you press it.
+ */
+ private buildFitHeight(el: TextElement) {
+ if (!el.html?.trim()) return // nothing to measure yet
+ const m = measureElement(el, this.store.doc)
+ const delta = m.height - el.h
+ const fit = document.createElement('button')
+ fit.className = 'ed-btn ed-btn-block'
+ fit.textContent = t('Fit height to text')
+ fit.title = t('The text needs {need}px and the box is {have}px',
+ { need: String(m.height), have: String(el.h) })
+ if (delta === 0) fit.setAttribute('disabled', '')
+ fit.addEventListener('click', () => {
+ // measure again at click time — the text may have been edited since the
+ // panel was built, and a stale height is worse than no button
+ const fresh = measureElement(this.store.element(el.id) as TextElement, this.store.doc)
+ this.mutate(el.id, (e) => { e.h = fresh.height }, true)
+ })
+ this.host.appendChild(fit)
+ }
+
private buildTextProps(el: TextElement) {
this.section(t('Typography'))
const hint = document.createElement('p')
hint.className = 'ed-hint'
hint.innerHTML = t('While editing: <b>⌘B</b>/<b>⌘I</b>/<b>⌘U</b> · markdown auto-converts — **bold*&#8203;* *italic*&#8203; `code` ~~strike~~ and "- " bullets; pasting markdown converts too. Escape with \\ or press ⌘Z right after to keep the literal characters.')
this.host.appendChild(hint)
+ this.buildFitHeight(el)
this.row('Font', this.fontSelect(el))
// Shown in POINTS (the unit office users know); the model stores slide-space
// px. 1pt = 4/3 px at the slide's 96dpi space, so 32px = 24pt exactly.
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index 843a90c1..1bbd6342 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -728,4 +728,6 @@ export const de: Catalog = {
"Opened {name} — ⌘S will save a copy": "{name} geöffnet — ⌘S speichert eine Kopie",
"⌘S asks where to save, then rewrites that file in place": "⌘S fragt nach dem Speicherort und überschreibt diese Datei dann direkt",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} ist eine leere Kopie von Bento, keine gespeicherte Präsentation. Öffnen Sie die Datei einzeln, um eine zu beginnen.",
+ "Fit height to text": "Höhe an Text anpassen",
+ "The text needs {need}px and the box is {have}px": "Der Text braucht {need}px, das Feld ist {have}px hoch",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index 2067dea3..1224f934 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -728,4 +728,6 @@ export const es: Catalog = {
"Opened {name} — ⌘S will save a copy": "{name} abierto: ⌘S guardará una copia",
"⌘S asks where to save, then rewrites that file in place": "⌘S pregunta dónde guardar y luego reescribe ese archivo en el sitio",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} es una copia vacía de Bento, no una presentación guardada. Ábrela por su cuenta para empezar una.",
+ "Fit height to text": "Ajustar alto al texto",
+ "The text needs {need}px and the box is {have}px": "El texto necesita {need}px y la caja mide {have}px",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index 60736cd0..cfe894d2 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -728,4 +728,6 @@ export const fr: Catalog = {
"Opened {name} — ⌘S will save a copy": "{name} ouvert — ⌘S enregistrera une copie",
"⌘S asks where to save, then rewrites that file in place": "⌘S demande où enregistrer, puis réécrit ce fichier sur place",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} est une copie vierge de Bento, pas une présentation enregistrée. Ouvrez-la seule pour en commencer une.",
+ "Fit height to text": "Ajuster la hauteur au texte",
+ "The text needs {need}px and the box is {have}px": "Le texte nécessite {need}px et la boîte fait {have}px",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index 2a7ee2ba..595e506e 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -728,4 +728,6 @@ export const it: Catalog = {
"Opened {name} — ⌘S will save a copy": "{name} aperto — ⌘S salverà una copia",
"⌘S asks where to save, then rewrites that file in place": "⌘S chiede dove salvare, poi riscrive quel file sul posto",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} è una copia vuota di Bento, non una presentazione salvata. Aprila da sola per iniziarne una.",
+ "Fit height to text": "Adatta altezza al testo",
+ "The text needs {need}px and the box is {have}px": "Il testo richiede {need}px e la casella è di {have}px",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index b2198f06..531e2cc0 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -728,4 +728,6 @@ export const ja: Catalog = {
"Opened {name} — ⌘S will save a copy": "{name} を開きました — ⌘S はコピーを保存します",
"⌘S asks where to save, then rewrites that file in place": "⌘S は保存先を尋ねてから、そのファイルを上書き保存します",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} は保存済みのデッキではなく、空の Bento です。単独で開いて作成してください。",
+ "Fit height to text": "高さをテキストに合わせる",
+ "The text needs {need}px and the box is {have}px": "テキストには {need}px 必要で、ボックスは {have}px です",
}
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index 4189cfad..5016d56d 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -734,4 +734,6 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Opened {name} — ⌘S will save a copy": ["{name} を開きました — ⌘S はコピーを保存します","已打开 {name} — ⌘S 将保存副本","已開啟 {name} — ⌘S 將儲存副本","{name} abierto: ⌘S guardará una copia","{name} ouvert — ⌘S enregistrera une copie","{name} geöffnet — ⌘S speichert eine Kopie","{name} aperto — ⌘S salverà una copia","{name} aberto — ⌘S guardará uma cópia"],
"⌘S asks where to save, then rewrites that file in place": ["⌘S は保存先を尋ねてから、そのファイルを上書き保存します","⌘S 会先询问保存位置,然后直接覆写该文件","⌘S 會先詢問儲存位置,然後直接覆寫該檔案","⌘S pregunta dónde guardar y luego reescribe ese archivo en el sitio","⌘S demande où enregistrer, puis réécrit ce fichier sur place","⌘S fragt nach dem Speicherort und überschreibt diese Datei dann direkt","⌘S chiede dove salvare, poi riscrive quel file sul posto","⌘S pergunta onde guardar e depois reescreve esse ficheiro no local"],
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": ["{name} は保存済みのデッキではなく、空の Bento です。単独で開いて作成してください。","{name} 是一个空的 Bento 副本,不是已保存的演示文稿。请单独打开它以创建。","{name} 是一個空的 Bento 副本,不是已儲存的簡報。請單獨開啟它以建立。","{name} es una copia vacía de Bento, no una presentación guardada. Ábrela por su cuenta para empezar una.","{name} est une copie vierge de Bento, pas une présentation enregistrée. Ouvrez-la seule pour en commencer une.","{name} ist eine leere Kopie von Bento, keine gespeicherte Präsentation. Öffnen Sie die Datei einzeln, um eine zu beginnen.","{name} è una copia vuota di Bento, non una presentazione salvata. Aprila da sola per iniziarne una.","{name} é uma cópia vazia do Bento, não uma apresentação guardada. Abra-a sozinha para começar uma."],
+ "Fit height to text": ["高さをテキストに合わせる","高度适应文本","高度符合文字","Ajustar alto al texto","Ajuster la hauteur au texte","Höhe an Text anpassen","Adatta altezza al testo","Ajustar altura ao texto"],
+ "The text needs {need}px and the box is {have}px": ["テキストには {need}px 必要で、ボックスは {have}px です","文本需要 {need}px,文本框为 {have}px","文字需要 {need}px,文字方塊為 {have}px","El texto necesita {need}px y la caja mide {have}px","Le texte nécessite {need}px et la boîte fait {have}px","Der Text braucht {need}px, das Feld ist {have}px hoch","Il testo richiede {need}px e la casella è di {have}px","O texto precisa de {need}px e a caixa tem {have}px"],
}
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index 3d76a4df..eb0e9a76 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -726,4 +726,6 @@ export const pt: Catalog = {
"Slide number": "Número do slide",
"Progress bar": "Barra de progresso",
"Corner arrows": "Setas de canto",
+ "Fit height to text": "Ajustar altura ao texto",
+ "The text needs {need}px and the box is {have}px": "O texto precisa de {need}px e a caixa tem {have}px",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 0c95c138..849c9935 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -728,4 +728,6 @@ export const zhHans: Catalog = {
"Opened {name} — ⌘S will save a copy": "已打开 {name} — ⌘S 将保存副本",
"⌘S asks where to save, then rewrites that file in place": "⌘S 会先询问保存位置,然后直接覆写该文件",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} 是一个空的 Bento 副本,不是已保存的演示文稿。请单独打开它以创建。",
+ "Fit height to text": "高度适应文本",
+ "The text needs {need}px and the box is {have}px": "文本需要 {need}px,文本框为 {have}px",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index e4f839b5..3299e70e 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -728,4 +728,6 @@ export const zhHant: Catalog = {
"Opened {name} — ⌘S will save a copy": "已開啟 {name} — ⌘S 將儲存副本",
"⌘S asks where to save, then rewrites that file in place": "⌘S 會先詢問儲存位置,然後直接覆寫該檔案",
"{name} is an empty copy of Bento, not a saved deck. Open it on its own to start one.": "{name} 是一個空的 Bento 副本,不是已儲存的簡報。請單獨開啟它以建立。",
+ "Fit height to text": "高度符合文字",
+ "The text needs {need}px and the box is {have}px": "文字需要 {need}px,文字方塊為 {have}px",
}
diff --git a/slides/src/main.ts b/slides/src/main.ts
index a72dc7f8..3eef5374 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -14,8 +14,9 @@ import {
import { buildSlidePreview } from './preview'
import { APP_VERSION, checkForUpdates, buildUpdatedFile, applyUpdate } from './update'
import { i18nApi, t, applyDirection } from './i18n'
-import { parseDoc, type BentoDoc } from './model'
+import { parseDoc, type BentoDoc, type TextElement } from './model'
import { validateDoc, type ValidateOpts } from './validate'
+import { measureText, measureElement, type TextMeasureSpec } from './measure'
import { starterDoc } from './starterdeck'
import { injectFonts } from './fonts'
import { Store } from './store'
@@ -227,6 +228,27 @@ if (location.hash === '#present') {
validate(target?: BentoDoc, opts?: ValidateOpts) {
return validateDoc(target ?? store.doc, opts)
},
+ /**
+ * How tall does this text need to be? The format is absolute pixels, so
+ * without a screen the height of a string is a guess — this answers it by
+ * rendering through the real renderer.
+ *
+ * Pass an element id to measure one that exists, or a spec
+ * ({html, w, fontSize, …}) to size text BEFORE creating the element, which
+ * is the point: an agent can lay a slide out correctly the first time
+ * instead of writing it, checking, and correcting.
+ *
+ * Returns {height, width, lines} — plus {fits, overflow} when you supply `h`.
+ */
+ measure(target: string | TextMeasureSpec, opts?: { doc?: BentoDoc }) {
+ const doc = opts?.doc ?? store.doc
+ if (typeof target !== 'string') return measureText(target, doc)
+ for (const s of doc.slides) {
+ const el = s.elements.find((e) => e.id === target && e.type === 'text')
+ if (el) return measureElement(el as TextElement, doc)
+ }
+ return null
+ },
/**
* Self-update surface (all user/tooling-initiated, never automatic):
* check() fetches + signature-verifies the release manifest; build()
diff --git a/slides/src/measure.ts b/slides/src/measure.ts
new file mode 100644
index 00000000..e4222675
--- /dev/null
+++ b/slides/src/measure.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Text measurement — `window.bento.measure()`.
+//
+// WHY THIS EXISTS. The format is absolute pixels, which is what lets morph, the
+// editor's drag handles and the renderer all work from one representation. The
+// cost lands on whoever is generating a deck without a screen: the rendered
+// height of a string, for a given font, size, weight and lineHeight, is
+// unknowable without a render. So every card, caption and two-line heading is a
+// guess, and overflow and collisions are downstream of that one gap.
+//
+// This closes it. Give it text and a width, get back the height that text needs
+// — before the element exists, so an agent can size a box rather than guess it
+// and correct later.
+//
+// It measures by RENDERING, through `renderElement`, the same path the editor,
+// present mode and thumbnails use. A reimplementation — canvas measureText, a
+// line-count estimate — would drift from the renderer the moment anything about
+// text layout changed, and drift in a measuring tool is worse than no tool: it
+// reads as authoritative and is quietly wrong.
+
+import type { BentoDoc, TextElement } from './model.ts'
+import { defaultText } from './model.ts'
+import { renderElement } from './render.ts'
+
+/** What to measure. Anything omitted falls back to the deck's text defaults. */
+export interface TextMeasureSpec {
+ html: string
+ /** box width in slide px — the thing that decides where lines wrap */
+ w: number
+ /** box height, if you have one and want `fits`/`overflow` computed */
+ h?: number
+ fontSize?: number
+ fontFamily?: string
+ fontWeight?: number
+ lineHeight?: number
+ letterSpacing?: number
+}
+
+export interface TextMeasurement {
+ /** height this content needs at this width, in slide px, rounded up */
+ height: number
+ /** the width it was measured at, echoed back */
+ width: number
+ /** how many lines it wrapped to */
+ lines: number
+ /** only when `h` was supplied: does the content fit the box? */
+ fits?: boolean
+ /** only when `h` was supplied: px of overflow (0 when it fits) */
+ overflow?: number
+}
+
+/**
+ * A hidden host that is in the document (so layout runs) but paints nothing.
+ *
+ * visibility:hidden rather than display:none — a display:none subtree has no
+ * layout at all and every height would read 0. Marked transient so
+ * `serializeBody` strips it if a save ever races a measurement.
+ */
+function withHost<T>(fn: (host: HTMLElement) => T): T {
+ const host = document.createElement('div')
+ host.setAttribute('data-bento-transient', '')
+ host.style.cssText =
+ 'position:fixed;left:-10000px;top:0;visibility:hidden;pointer-events:none;contain:strict;'
+ document.body.appendChild(host)
+ try {
+ return fn(host)
+ } finally {
+ host.remove()
+ }
+}
+
+/**
+ * Measure one text element as the renderer would lay it out.
+ *
+ * `doc` supplies the theme font and the embedded faces, so measuring against
+ * the deck the text will live in is the whole point — the same string in
+ * Fraunces and in a system stack are different heights.
+ */
+export function measureText(spec: TextMeasureSpec, doc: BentoDoc): TextMeasurement {
+ return withHost((host) => measureInto(host, spec, doc))
+}
+
+/** One measurement inside an already-open host. */
+function measureInto(host: HTMLElement, spec: TextMeasureSpec, doc: BentoDoc): TextMeasurement {
+ const el = defaultText({
+ ...spec,
+ id: 'bento-measure',
+ x: 0,
+ y: 0,
+ w: spec.w,
+ h: spec.h ?? 10,
+ })
+ const node = renderElement(el, doc)
+ // The box height is what we are trying to find, so it must not constrain the
+ // measurement — let the inner text take whatever height it needs.
+ node.style.height = 'auto'
+ host.appendChild(node)
+ const inner = node.querySelector<HTMLElement>('.bento-text-inner') ?? node
+ const height = Math.ceil(inner.getBoundingClientRect().height)
+ // lineHeight is unitless in the model, so one line is fontSize * lineHeight
+ const per = (el.fontSize ?? 16) * (el.lineHeight ?? 1.2)
+ const lines = Math.max(1, Math.round(height / Math.max(per, 1)))
+ node.remove()
+ const out: TextMeasurement = { height, width: spec.w, lines }
+ if (typeof spec.h === 'number') {
+ out.fits = height <= spec.h
+ out.overflow = Math.max(0, height - spec.h)
+ }
+ return out
+}
+
+/**
+ * Measure many elements through ONE host — what `validate()` uses to check a
+ * whole deck. Opening a host per element would be the same answer and a lot
+ * more DOM churn on a long deck.
+ */
+export function measureElements(els: TextElement[], doc: BentoDoc): TextMeasurement[] {
+ if (!els.length) return []
+ return withHost((host) => els.map((el) => measureInto(host, specOf(el), doc)))
+}
+
+const specOf = (el: TextElement): TextMeasureSpec => ({
+ html: el.html,
+ w: el.w,
+ h: el.h,
+ fontSize: el.fontSize,
+ fontFamily: el.fontFamily,
+ fontWeight: el.fontWeight,
+ lineHeight: el.lineHeight,
+ letterSpacing: el.letterSpacing,
+})
+
+/**
+ * The height an existing element's content needs — the number to write into
+ * `h` so the box fits its text exactly.
+ */
+export function measureElement(el: TextElement, doc: BentoDoc): TextMeasurement {
+ return measureText(specOf(el), doc)
+}
diff --git a/slides/src/validate.ts b/slides/src/validate.ts
index f6a8c2ca..f55caea1 100644
--- a/slides/src/validate.ts
+++ b/slides/src/validate.ts
@@ -15,15 +15,16 @@
// finding is advice, not a refusal. `parseDoc` remains the thing that decides
// whether a document is loadable at all.
//
-// Text overflow needs real layout, so it renders each slide off-screen with the
-// SAME renderer the editor and present mode use (`renderSlide`) and measures
-// what comes out. Anything else would measure a different deck than the one the
-// audience sees. Without a DOM (node tooling) the measured checks are skipped
-// and `measured` reports false, rather than guessing.
+// Text overflow needs real layout, so it goes through measure.ts — the same
+// path `window.bento.measure()` uses, which renders off-screen with the SAME
+// renderer the editor and present mode use. One path means the validator and
+// the measuring tool cannot disagree about whether a box fits its text. Without
+// a DOM (node tooling) the measured checks are skipped and `measured` reports
+// false, rather than guessing.
-import type { BentoDoc, Slide, SlideElement } from './model.ts'
+import type { BentoDoc, Slide, SlideElement, TextElement } from './model.ts'
import { MODEL_KEYS } from './modelkeys.generated.ts'
-import { renderSlide } from './render.ts'
+import { measureElements } from './measure.ts'
export type Severity = 'error' | 'warning' | 'info'
@@ -306,42 +307,28 @@ function validateChart(
}
/**
- * Render every slide off-screen and measure what the text actually does.
+ * Measure every text element and report the ones that do not fit.
*
- * Uses the shared renderer so the measurement is of the same DOM the audience
- * gets — a reimplementation here would drift from render.ts and start lying.
- * The host is visibility:hidden rather than display:none, because a
- * display:none subtree has no layout at all and every height would read 0.
+ * Goes through measure.ts, the same path `window.bento.measure()` uses, so the
+ * validator and the measuring tool can never disagree about whether a given
+ * box fits its text — which they would within a release if each had its own
+ * copy of the arithmetic.
*/
function measureOverflow(doc: BentoDoc, add: (f: Finding) => void) {
- const host = document.createElement('div')
- host.setAttribute('data-bento-transient', '') // never captured into a save
- host.style.cssText =
- 'position:fixed;left:-10000px;top:0;visibility:hidden;pointer-events:none;contain:strict;'
- document.body.appendChild(host)
- try {
- for (const slide of doc.slides) {
- const surface = renderSlide(slide, doc)
- host.appendChild(surface)
- for (const el of slide.elements) {
- if (el.type !== 'text') continue
- const node = surface.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(el.id)}"]`)
- const inner = node?.querySelector<HTMLElement>('.bento-text-inner')
- if (!inner) continue
- const need = inner.scrollHeight
- // a placeholder with no content measures as one empty line — not overflow
- if (!el.html?.trim()) continue
- if (need > el.h + 1) {
- add({
- slide: slide.id, element: el.id, code: 'text-overflow', severity: 'warning',
- path: 'h',
- message: `Text needs ${Math.ceil(need)}px but the box is ${el.h}px tall — it overflows by ${Math.ceil(need - el.h)}px and will collide with whatever is below it.`,
- })
- }
- }
- surface.remove()
+ // a placeholder with no content measures as one empty line — not overflow
+ const targets: Array<{ slide: string; el: TextElement }> = []
+ for (const slide of doc.slides) {
+ for (const el of slide.elements) {
+ if (el.type === 'text' && el.html?.trim()) targets.push({ slide: slide.id, el })
}
- } finally {
- host.remove()
}
+ const measured = measureElements(targets.map((t) => t.el), doc)
+ measured.forEach((m, i) => {
+ const { slide, el } = targets[i]
+ if (m.fits !== false || m.overflow! <= 1) return
+ add({
+ slide, element: el.id, code: 'text-overflow', severity: 'warning', path: 'h',
+ message: `Text needs ${m.height}px but the box is ${el.h}px tall — it overflows by ${m.overflow}px (${m.lines} lines) and will collide with whatever is below it.`,
+ })
+ })
}