AI-native design editor. Open-source Figma alternative.
perf(text): measure each text once per shaping and layout width (#959)
Danila Poyarkov6a06b31dd8de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex acd582aee..4ed9e9c98 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -224,7 +224,7 @@- Open the `/demo` document like any `.fig` file, built ahead of time, instead of generating it in the browser, which froze the page for several seconds.- Open large `.fig` files with less memory in the macOS desktop app and Safari: imported layers now share one object layout in JavaScriptCore instead of each being stored as a slower, larger dictionary.- Open multi-page `.fig` documents faster: the archive is indexed once rather than once for every page, each page resolves only the layers it adds instead of rescanning the whole document, placing an instance no longer re-synchronises every other instance of its component, and archive records are copied directly rather than through `structuredClone`. A 33-page file loads about a fifth quicker, and a page of repeated components opens three to four times faster once a document is already open.-- Lay out documents with many text layers and component instances without long freezes: text checks whether its fonts cover every glyph once rather than on every layout pass, and layout updating sizes no longer re-synchronises the components it touched. Building the demo document takes less than half as long.+- Lay out documents with many text layers and component instances without long freezes: text checks whether its fonts cover every glyph and measures itself at each width once rather than on every layout pass, and layout updating sizes no longer re-synchronises the components it touched. Building the demo document takes less than half as long.### Securitydiff --git a/packages/core/src/canvas/renderer/state.ts b/packages/core/src/canvas/renderer/state.tsindex ca0d986c6..15909be98 100644--- a/packages/core/src/canvas/renderer/state.ts+++ b/packages/core/src/canvas/renderer/state.ts@@ -1,7 +1,7 @@import type { SceneNode } from '@open-pencil/scene-graph'import type { SkiaRenderer } from '#core/canvas/renderer'-import { changesGlyphCoverage } from '#core/canvas/text/paragraph-inputs'+import { changesShaping } from '#core/canvas/text/paragraph-inputs'export function invalidateScenePicture(r: SkiaRenderer): void {r.scenePicture?.delete()@@ -41,7 +41,7 @@ export function invalidateNodePicture(changedKeys?: readonly (keyof SceneNode)[]): void {r.textPreparationCache.deleteNode(nodeId, {- keepGlyphCoverage: changedKeys !== undefined && !changesGlyphCoverage(changedKeys)+ keepShaping: changedKeys !== undefined && !changesShaping(changedKeys)})r.effectRasterCache.delete(nodeId)r.effectRasterCache.deleteDependencies(nodeId)diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.tsindex 09af213d9..f4818ef78 100644--- a/packages/core/src/canvas/text/index.ts+++ b/packages/core/src/canvas/text/index.ts@@ -225,12 +225,25 @@ export function measureTextNode(if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return nullif (node.type !== 'TEXT' || !node.text) return null- const paragraph = buildParagraph(r, node)- paragraph.layout(resolveParagraphLayoutWidth(node, maxWidth))- const width = paragraph.getLongestLine()- const height = paragraph.getHeight()- paragraph.delete()- return { width: Math.ceil(width), height: Math.ceil(height) }+ const layoutWidth = resolveParagraphLayoutWidth(node, maxWidth)+ const measure = () => {+ const paragraph = buildParagraph(r, node)+ paragraph.layout(layoutWidth)+ const width = paragraph.getLongestLine()+ const height = paragraph.getHeight()+ paragraph.delete()+ return { width: Math.ceil(width), height: Math.ceil(height) }+ }+ // Layout asks for the same text at the same width many times per pass.+ return r.textPreparationCache+ ? r.textPreparationCache.measure(+ node,+ layoutWidth,+ fontManager.generation(),+ r.fontProvider,+ measure+ )+ : measure()}export function buildTextPicture(r: TextRenderer, node: SceneNode): Uint8Array | null {diff --git a/packages/core/src/canvas/text/paragraph-inputs.ts b/packages/core/src/canvas/text/paragraph-inputs.tsindex 88fdf6a63..bd4f644e8 100644--- a/packages/core/src/canvas/text/paragraph-inputs.ts+++ b/packages/core/src/canvas/text/paragraph-inputs.ts@@ -33,19 +33,19 @@ export type ParagraphNode = Pick<SceneNode, (typeof PARAGRAPH_INPUT_KEYS)[numberconst BOX_SIZE_KEYS = new Set<keyof SceneNode>(['width', 'height'])/**- * The paragraph inputs that decide which glyphs are shaped. The box size only matters when the- * text is truncated, since it decides which characters are shown; otherwise layout resizing the- * box leaves coverage as it was.+ * The paragraph inputs that decide how text shapes: which glyphs it needs and how big it is at a+ * given layout width. The box size only matters when the text is truncated, since it decides+ * which characters are shown; otherwise layout resizing the box leaves both as they were.*/-export function glyphCoverageInputs(node: ParagraphNode): ParagraphNode[keyof ParagraphNode][] {+export function shapingInputs(node: ParagraphNode): ParagraphNode[keyof ParagraphNode][] {const truncated = node.textTruncation === 'ENDING'return PARAGRAPH_INPUT_KEYS.filter((key) => truncated || !BOX_SIZE_KEYS.has(key)).map((key) => node[key])}-/** Whether a change to `keys` can change glyph coverage beyond what `glyphCoverageInputs` sees. */-export function changesGlyphCoverage(keys: readonly (keyof SceneNode)[]): boolean {+/** Whether a change to `keys` can change shaping beyond what `shapingInputs` sees. */+export function changesShaping(keys: readonly (keyof SceneNode)[]): boolean {return keys.some((key) => !BOX_SIZE_KEYS.has(key) && (PARAGRAPH_INPUT_KEYS as readonly string[]).includes(key))diff --git a/packages/core/src/canvas/text/preparation-cache.ts b/packages/core/src/canvas/text/preparation-cache.tsindex 03f04fec1..527e4f121 100644--- a/packages/core/src/canvas/text/preparation-cache.ts+++ b/packages/core/src/canvas/text/preparation-cache.ts@@ -1,6 +1,7 @@import type { Paragraph, TypefaceFontProvider } from 'canvaskit-wasm'import type { SceneNode } from '@open-pencil/scene-graph'+import type { Size } from '@open-pencil/scene-graph/primitives'import { ResourceCache } from '#core/cache/resource'import type { missingGlyphOccurrences } from '#core/text/resolver'@@ -9,8 +10,10 @@ import type { missingGlyphOccurrences } from '#core/text/resolver'// Source UTF-16 units are a workload bound, not an estimate of native bytes.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-import { glyphCoverageInputs, PARAGRAPH_INPUT_KEYS } from './paragraph-inputs'+import { PARAGRAPH_INPUT_KEYS, shapingInputs } from './paragraph-inputs'type PreparationInput = SceneNode[(typeof PARAGRAPH_INPUT_KEYS)[number]]@@ -19,6 +22,13 @@ export interface PreparedText {missingGlyphs?: ReturnType<typeof missingGlyphOccurrences>}+/** What shaping a node's text showed, valid while its `shapingInputs` stay the same. */+interface Shaping {+ inputs: PreparationInput[]+ covered: boolean+ sizes: Map<number, Size>+}+interface Entry extends PreparedText {nodeId: stringinputs: PreparationInput[]@@ -28,10 +38,10 @@ interface Entry extends PreparedText {export class TextPreparationCache {private readonly entries: ResourceCache<string, Entry>private readonly nodeKeys = new Map<string, Set<string>>()- // A successful coverage check contains no native resources. Keep that result- // independently of paragraph LRU eviction, weakly owned by the source node.- private glyphCoverage = new WeakMap<SceneNode, PreparationInput[]>()- private readonly invalidatedCoverage = new Set<string>()+ // Coverage and measured sizes contain no native resources. Keep them independently of+ // paragraph LRU eviction, weakly owned by the source node.+ private shaping = new WeakMap<SceneNode, Shaping>()+ private readonly invalidatedShaping = new Set<string>()private generation = -1private provider: TypefaceFontProvider | null = null@@ -61,11 +71,7 @@ export class TextPreparationCache {build: () => Paragraph,consume: (prepared: PreparedText) => T): T {- if (this.generation !== generation || this.provider !== provider) {- this.clear()- this.generation = generation- this.provider = provider- }+ this.useScope(generation, provider)if (node.text.length > this.maxTextUnits || this.maxEntries <= 0) {const paragraph = build()try {@@ -80,7 +86,8 @@ export class TextPreparationCache {entry &&!PARAGRAPH_INPUT_KEYS.every((prop, index) => entry?.inputs[index] === node[prop])) {- this.deleteNode(node.id)+ // Shaping compares its own inputs, so a change it doesn't see, such as a resize, keeps it.+ this.deleteNode(node.id, { keepShaping: true })entry = undefined}if (!entry) {@@ -100,48 +107,84 @@ export class TextPreparationCache {hasGlyphCoverage(node: SceneNode, generation: number, provider: TypefaceFontProvider): boolean {if (this.generation !== generation || this.provider !== provider) return false- if (this.invalidatedCoverage.delete(node.id)) {- this.glyphCoverage.delete(node)- return false- }- const inputs = this.glyphCoverage.get(node)- if (!inputs) return false- const current = glyphCoverageInputs(node)- if (- current.length === inputs.length &&- current.every((input, index) => input === inputs[index])- )- return true- this.glyphCoverage.delete(node)- return false+ return this.currentShaping(node)?.covered === true}/** Call only after observing complete coverage with this cache's current font scope. */recordGlyphCoverage(node: SceneNode): void {- this.invalidatedCoverage.delete(node.id)- this.glyphCoverage.set(node, glyphCoverageInputs(node))+ this.shapingFor(node).covered = true+ }++ /** The size of `node`'s text laid out at `layoutWidth`, measured once per shaping. */+ measure(+ node: SceneNode,+ layoutWidth: number,+ generation: number,+ provider: TypefaceFontProvider,+ compute: () => Size+ ): Size {+ this.useScope(generation, provider)+ const sizes = this.shapingFor(node).sizes+ const cached = sizes.get(layoutWidth)+ if (cached) return cached+ const size = compute()+ if (sizes.size >= MAX_MEASURED_WIDTHS) sizes.clear()+ sizes.set(layoutWidth, size)+ return size}/**- * Drops `id`'s paragraphs and, unless `keepGlyphCoverage`, its coverage. Keep coverage only for- * changes `glyphCoverageInputs` compares, such as layout resizing the box.+ * Drops `id`'s paragraphs and, unless `keepShaping`, its coverage and measured sizes. Keep+ * them only for changes `shapingInputs` compares, such as layout resizing the box.*/- deleteNode(id: string, { keepGlyphCoverage = false } = {}): void {+ deleteNode(id: string, { keepShaping = false } = {}): void {// Invalidation arrives by ID; don't add strong node ownership just to find// weak observations. Bound pending IDs and conservatively reset on overflow.- if (!keepGlyphCoverage) this.invalidatedCoverage.add(id)- if (this.invalidatedCoverage.size > this.maxEntries) {- this.glyphCoverage = new WeakMap()- this.invalidatedCoverage.clear()+ if (!keepShaping) this.invalidatedShaping.add(id)+ if (this.invalidatedShaping.size > this.maxEntries) {+ this.shaping = new WeakMap()+ this.invalidatedShaping.clear()}const keys = this.nodeKeys.get(id)if (keys) for (const key of keys) this.entries.delete(key)}+ private useScope(generation: number, provider: TypefaceFontProvider): void {+ if (this.generation === generation && this.provider === provider) return+ this.clear()+ this.generation = generation+ this.provider = provider+ }++ private currentShaping(node: SceneNode): Shaping | null {+ if (this.invalidatedShaping.delete(node.id)) {+ this.shaping.delete(node)+ return null+ }+ const shaping = this.shaping.get(node)+ if (!shaping) return null+ const current = shapingInputs(node)+ if (+ current.length === shaping.inputs.length &&+ current.every((input, index) => input === shaping.inputs[index])+ )+ return shaping+ this.shaping.delete(node)+ return null+ }++ 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() }+ this.shaping.set(node, created)+ return created+ }+clear(): void {this.nodeKeys.clear()- this.glyphCoverage = new WeakMap()- this.invalidatedCoverage.clear()+ this.shaping = new WeakMap()+ this.invalidatedShaping.clear()this.entries.clear()}}diff --git a/tests/engine/render/canvas/picture-invalidation.test.ts b/tests/engine/render/canvas/picture-invalidation.test.tsindex 07081fc26..1a748db7b 100644--- a/tests/engine/render/canvas/picture-invalidation.test.ts+++ b/tests/engine/render/canvas/picture-invalidation.test.ts@@ -72,7 +72,7 @@ test('node picture invalidation removes pictures that depend on a changed child'invalidateNodePicture(renderer, 'child')expect(textPreparationCache.deleteNode).toHaveBeenCalledWith('child', {- keepGlyphCoverage: false+ keepShaping: false})expect(parentPicture.delete).toHaveBeenCalledTimes(1)expect(childPicture.delete).toHaveBeenCalledTimes(1)@@ -80,10 +80,10 @@ test('node picture invalidation removes pictures that depend on a changed child'invalidateNodePicture(renderer, 'child', ['width', 'height', 'x'])expect(textPreparationCache.deleteNode).toHaveBeenLastCalledWith('child', {- keepGlyphCoverage: true+ keepShaping: true})invalidateNodePicture(renderer, 'child', ['width', 'text'])expect(textPreparationCache.deleteNode).toHaveBeenLastCalledWith('child', {- keepGlyphCoverage: false+ keepShaping: false})})diff --git a/tests/engine/render/canvas/text-preparation-cache.test.ts b/tests/engine/render/canvas/text-preparation-cache.test.tsindex d337997ee..a23b7bb64 100644--- a/tests/engine/render/canvas/text-preparation-cache.test.ts+++ b/tests/engine/render/canvas/text-preparation-cache.test.ts@@ -138,7 +138,7 @@ describe('text preparation cache', () => {// Layout resizing the box shapes the same glyphs, unless truncation hides some of them.f.graph.updateNodePreview(f.node.id, { width: 80 })expect(f.cache.hasGlyphCoverage(f.node, 1, f.provider)).toBe(true)- f.cache.deleteNode(f.node.id, { keepGlyphCoverage: true })+ f.cache.deleteNode(f.node.id, { keepShaping: true })expect(f.cache.hasGlyphCoverage(f.node, 1, f.provider)).toBe(true)f.graph.updateNodePreview(f.node.id, { textTruncation: 'ENDING' })expect(f.cache.hasGlyphCoverage(f.node, 1, f.provider)).toBe(false)@@ -165,6 +165,44 @@ describe('text preparation cache', () => {}})+ test('measures a text once per shaping and layout width', async () => {+ const f = await fixture()+ let measured = 0+ const measure = (width: number, generation = 1) =>+ f.cache.measure(f.node, width, generation, f.provider, () => {+ measured+++ return { width, height: f.node.text.length }+ })+ try {+ measure(200)+ measure(200)+ measure(120)+ expect(measured).toBe(2)+ // Layout resizing the box changes neither the shaping nor the sizes at a given width.+ f.graph.updateNodePreview(f.node.id, { width: 80, height: 30 })+ f.cache.deleteNode(f.node.id, { keepShaping: true })+ measure(200)+ expect(measured).toBe(2)+ // Drawing rebuilds its paragraph for the new box without dropping the measurements.+ f.use()+ f.graph.updateNodePreview(f.node.id, { width: 90 })+ f.use()+ expect(f.built).toHaveLength(2)+ measure(200)+ expect(measured).toBe(2)+ f.graph.updateNodePreview(f.node.id, { text: 'Edited text' })+ expect(measure(200).height).toBe('Edited text'.length)+ expect(measured).toBe(3)+ f.cache.deleteNode(f.node.id)+ measure(200)+ expect(measured).toBe(4)+ measure(200, 2)+ expect(measured).toBe(5)+ } finally {+ f.dispose()+ }+ })+test('reuses native paragraphs during movement and invalidates text layout inputs', async () => {const f = await fixture()try {