AI-native design editor. Open-source Figma alternative.
perf(core): measure each distinct text once per layout (#1264)
Sergi Gonzalez6a6e2c44039d
diff --git a/changes/1264/performance.md b/changes/1264/performance.mdnew file mode 100644index 000000000..a4637176e--- /dev/null+++ b/changes/1264/performance.md@@ -0,0 +1 @@+- Laying out a document with many repeated text layers measures each distinct text once, instead of shaping it again for every copy.diff --git a/packages/core/src/canvas/text/preparation/cache.ts b/packages/core/src/canvas/text/preparation/cache.tsindex 41c5fc241..668aaee95 100644--- a/packages/core/src/canvas/text/preparation/cache.ts+++ b/packages/core/src/canvas/text/preparation/cache.ts@@ -12,6 +12,9 @@ const MAX_PREPARED_PARAGRAPHS = 1024const MAX_PREPARED_TEXT_UNITS = 262_144// Layout measures a text at a few widths; more than this means the widths are not repeating.const MAX_MEASURED_WIDTHS = 16+// Bound the shapings layers share by their key length, which holds the text.+const MAX_SHARED_SHAPINGS = 8192+const MAX_SHARED_SHAPING_UNITS = 1_048_576import type { TextDecorationRect } from '#core/canvas/text/decorations'import type { TextLayout } from '#core/canvas/text/layout'@@ -26,13 +29,22 @@ export interface PreparedText {decorations?: { y: number; rects: TextDecorationRect[] }}-/** What shaping a node's text showed, valid while its `shapingInputs` stay the same. */-interface Shaping {- inputs: PreparationInput[]+/** What shaping a text showed: whether its faces cover it, and its size at each layout width. */+interface ShapingResult {covered: booleansizes: Map<number, Size>}+/**+ * A node's view of the shaping its text shows, valid while its `shapingInputs` stay the same. The+ * result is shared by every layer whose text shapes the same, such as an instance's copies.+ */+interface Shaping {+ inputs: PreparationInput[]+ key: string+ result: ShapingResult+}+interface Entry extends PreparedText {nodeId: stringinputs: PreparationInput[]@@ -43,8 +55,14 @@ export class TextPreparationCache {private readonly entries: ResourceCache<string, Entry>private readonly nodeKeys = new Map<string, Set<string>>()// Coverage and measured sizes contain no native resources. Keep them independently of- // paragraph LRU eviction, weakly owned by the source node.+ // paragraph LRU eviction: each node's view weakly owned by the node, the results it shares with+ // identical text bounded by their keys.private shaping = new WeakMap<SceneNode, Shaping>()+ private readonly results = new ResourceCache<string, ShapingResult>({+ maxEntries: MAX_SHARED_SHAPINGS,+ maxWeight: MAX_SHARED_SHAPING_UNITS,+ weight: (_result, key) => key.length+ })private readonly invalidatedShaping = new Set<string>()private generation = -1private provider: TypefaceFontProvider | null = null@@ -111,12 +129,13 @@ export class TextPreparationCache {hasGlyphCoverage(node: SceneNode, generation: number, provider: TypefaceFontProvider): boolean {if (this.generation !== generation || this.provider !== provider) return false- return this.currentShaping(node)?.covered === true+ // A copy that has not shaped yet still finds what its source's identical text showed.+ return this.shapingFor(node).result.covered}/** Call only after observing complete coverage with this cache's current font scope. */recordGlyphCoverage(node: SceneNode): void {- this.shapingFor(node).covered = true+ this.shapingFor(node).result.covered = true}/** The size of `node`'s text laid out at `layoutWidth`, measured once per shaping. */@@ -128,7 +147,7 @@ export class TextPreparationCache {compute: () => Size): Size {this.useScope(generation, provider)- const sizes = this.shapingFor(node).sizes+ const sizes = this.shapingFor(node).result.sizesconst cached = sizes.get(layoutWidth)if (cached) return cachedconst size = compute()@@ -148,6 +167,7 @@ export class TextPreparationCache {if (this.invalidatedShaping.size > this.maxEntries) {this.shaping = new WeakMap()this.invalidatedShaping.clear()+ this.results.clear()}const keys = this.nodeKeys.get(id)if (keys) for (const key of keys) this.entries.delete(key)@@ -162,6 +182,9 @@ export class TextPreparationCache {private currentShaping(node: SceneNode): Shaping | null {if (this.invalidatedShaping.delete(node.id)) {+ // An explicit invalidation covers what the inputs cannot show, so the shared result goes too.+ const invalidated = this.shaping.get(node)+ if (invalidated) this.results.delete(invalidated.key)this.shaping.delete(node)return null}@@ -180,7 +203,14 @@ export class TextPreparationCache {private shapingFor(node: SceneNode): Shaping {const existing = this.currentShaping(node)if (existing) return existing- const created: Shaping = { inputs: shapingInputs(node), covered: false, sizes: new Map() }+ const inputs = shapingInputs(node)+ const key = JSON.stringify(inputs)+ let result = this.results.get(key)+ if (!result) {+ result = { covered: false, sizes: new Map() }+ this.results.set(key, result)+ }+ const created: Shaping = { inputs, key, result }this.shaping.set(node, created)return created}@@ -189,6 +219,7 @@ export class TextPreparationCache {this.nodeKeys.clear()this.shaping = new WeakMap()this.invalidatedShaping.clear()+ this.results.clear()this.entries.clear()}}diff --git a/packages/core/src/io/formats/svg/text.ts b/packages/core/src/io/formats/svg/text.tsindex 9c75d02fb..23833a921 100644--- a/packages/core/src/io/formats/svg/text.ts+++ b/packages/core/src/io/formats/svg/text.ts@@ -10,7 +10,7 @@ import {import Matrix from '@open-pencil/scene-graph/matrix'import type { SVGElementLayer } from '#core/icons/types'-import { estimateTextSize, getTextMeasurer } from '#core/layout/text-measurement'+import { measureTextForLayout } from '#core/layout/text-measurement'import { weightToStyle } from '#core/text/font/style'import type {SVGVectorizeResult,@@ -95,7 +95,7 @@ function createTextPiece(lineHeight: null,width: 0})- const size = getTextMeasurer()?.(node) ?? estimateTextSize(node)+ const size = measureTextForLayout(node)const width = size.width / scaleconst left = width * ANCHOR_OFFSET[piece.anchor]const world = Matrix.multiply(diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsindex 7bab5b7c3..01425bff3 100644--- a/packages/core/src/layout.ts+++ b/packages/core/src/layout.ts@@ -42,7 +42,7 @@ import {type SceneNode} from '@open-pencil/scene-graph'-import { estimateTextSize, getTextMeasurer } from './layout/text-measurement'+import { estimateTextSize, getTextMeasurer, measureTextForLayout } from './layout/text-measurement'import {applyMinMaxConstraints,applyLockedAspectRatio,@@ -558,8 +558,7 @@ function configureTextLeaf(const cached = cache.get(cacheKey)if (cached) return cached- const measured = getTextMeasurer()?.(child, maxW)- const result = measured ?? estimateTextSize(child, maxW)+ const result = measureTextForLayout(child, maxW)cache.set(cacheKey, result)return result})@@ -589,11 +588,7 @@ function configureTextLeaf(if (constraintW === child.width && (child.derivedTextGlyphs?.length ?? 0) > 0) {return { width: constraintW, height: child.height }}- const measured = getTextMeasurer()?.(child, constraintW)- const result = {- width: constraintW,- height: measured?.height ?? estimateTextSize(child, constraintW).height- }+ const result = { width: constraintW, height: measureTextForLayout(child, constraintW).height }cache.set(cacheKey, result)return result})diff --git a/packages/core/src/layout/text-auto-resize.ts b/packages/core/src/layout/text-auto-resize.tsindex acc72cbd3..0785f2328 100644--- a/packages/core/src/layout/text-auto-resize.ts+++ b/packages/core/src/layout/text-auto-resize.ts@@ -1,6 +1,6 @@import { TEXT_METRIC_FIELDS, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'-import { estimateTextSize, getTextMeasurer } from './text-measurement'+import { measureTextForLayout } from './text-measurement'export const TEXT_AUTO_RESIZE_KEYS = new Set<keyof SceneNode>([...TEXT_METRIC_FIELDS,@@ -38,7 +38,7 @@ export function textAutoResizeChanges(if (mode !== 'HEIGHT' && mode !== 'WIDTH_AND_HEIGHT') return {}const maxWidth = mode === 'HEIGHT' ? next.width : undefined- const measured = getTextMeasurer()?.(next, maxWidth) ?? estimateTextSize(next, maxWidth)+ const measured = measureTextForLayout(next, maxWidth)const resized: Partial<Pick<SceneNode, 'width' | 'height' | 'derivedLayout' | 'derivedTextGlyphs'>> = { derivedLayout: null, derivedTextGlyphs: null }diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.tsindex bc9e47af7..77ca427a3 100644--- a/packages/core/src/layout/text-measurement.ts+++ b/packages/core/src/layout/text-measurement.ts@@ -44,6 +44,14 @@ export function setTextMeasurer(measurer: TextMeasurer | null): void {globalTextMeasurer = measurer}+/** The size of `node`'s text: measured when a measurer is installed and can, estimated otherwise. */+export function measureTextForLayout(+ node: SceneNode,+ maxWidth?: number+): { width: number; height: number } {+ return globalTextMeasurer?.(node, maxWidth) ?? estimateTextSize(node, maxWidth)+}+const installedMeasurers: TextMeasurer[] = []/**diff --git a/packages/core/tests/layout/text-measurement.test.ts b/packages/core/tests/layout/text-measurement.test.tsindex 28d4653da..6efed67fe 100644--- a/packages/core/tests/layout/text-measurement.test.ts+++ b/packages/core/tests/layout/text-measurement.test.ts@@ -1,8 +1,12 @@import { afterEach, describe, expect, test } from 'bun:test'+import { SceneGraph } from '@open-pencil/scene-graph'+import {+ estimateTextSize,getTextMeasurer,installTextMeasurer,+ measureTextForLayout,setTextMeasurer,type TextMeasurer} from '#core/layout/text-measurement'@@ -38,3 +42,22 @@ describe('installTextMeasurer', () => {expect(getTextMeasurer()).toBeNull()})})++describe('measureTextForLayout', () => {+ afterEach(() => setTextMeasurer(null))++ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { text: 'Label', fontSize: 14 })++ test('uses the installed measurer', () => {+ setTextMeasurer(measurer(42))+ expect(measureTextForLayout(node, 100)).toEqual({ width: 42, height: 10 })+ })++ test('estimates what the measurer cannot measure, or without one', () => {+ const estimate = estimateTextSize(node, 100)+ expect(measureTextForLayout(node, 100)).toEqual(estimate)+ setTextMeasurer(() => null)+ expect(measureTextForLayout(node, 100)).toEqual(estimate)+ })+})diff --git a/tests/engine/render/canvas/text/preparation-cache.test.ts b/tests/engine/render/canvas/text/preparation-cache.test.tsindex 27d962c3e..03250ef01 100644--- a/tests/engine/render/canvas/text/preparation-cache.test.ts+++ b/tests/engine/render/canvas/text/preparation-cache.test.ts@@ -204,6 +204,34 @@ describe('text preparation cache', () => {}})+ test('shares measured sizes between layers whose text shapes the same', async () => {+ const f = await fixture()+ let measured = 0+ const measure = (node: typeof f.node, width = 200) =>+ f.cache.measure(node, width, 1, f.provider, () => {+ measured+++ return { width, height: node.text.length }+ })+ const parentId = expectDefined(f.node.parentId, 'text node parent')+ // An instance's copies repeat the source text, whatever box each one sits in.+ const copy = f.graph.createNode('TEXT', parentId, { text: f.node.text, width: 80 })+ const other = f.graph.createNode('TEXT', parentId, { text: 'Other text' })+ try {+ measure(f.node)+ measure(copy)+ expect(measured).toBe(1)+ measure(copy, 120)+ measure(other)+ expect(measured).toBe(3)+ // An explicit invalidation drops the sizes the layer shares instead of reading them back.+ f.cache.deleteNode(f.node.id)+ measure(f.node)+ expect(measured).toBe(4)+ } finally {+ f.dispose()+ }+ })+test('reuses native paragraphs during movement and invalidates text layout inputs', async () => {const f = await fixture()try {