AI-native design editor. Open-source Figma alternative.
fix: lay text out only in its own prepared fonts (#1677)
Danila Poyarkov9c5e19dbf48e
diff --git a/changes/1677/fixed.md b/changes/1677/fixed.mdnew file mode 100644index 000000000..6b8c384fb--- /dev/null+++ b/changes/1677/fixed.md@@ -0,0 +1 @@+- Text is always laid out in its own fonts: text whose font, script fallback, or emoji font is still loading no longer takes the size of another face and keeps it, which left titles, sticky notes, and imported text narrower or wider than they drew.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 9e763ccfe..1b27a2ab3 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -92,6 +92,7 @@ Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.- Set fill types on the detached `Path`, never on a `PathBuilder`: in CanvasKit 0.41 `PathBuilder.setFillType` returns an undeleted copy of the builder (`packages/core/src/vector/index.ts`).- Paragraph construction is typed against `packages/core/src/canvas/text/paragraph/inputs.ts`; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction.- Text lays out through `buildParagraph` into a `TextLayout` (`packages/core/src/canvas/text/layout/`): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (`shapeText`), and text outlines all read that layout rather than laying text out again (`packages/core/tests/canvas/text/lists.test.ts`).+- Text is laid out only in its own prepared fonts. `prepareTextFonts` and `prepareGraphFonts` (`packages/core/src/text/prepare.ts`) are the one way text gets its faces, script fallbacks, and emoji; readers and design JSX call them before `layoutAuthoredNodes`, and the canvas loads the faces its tools create text in. Edits apply at once: text layout reaches before its fonts are prepared keeps its stored size and stays hidden while the editor prepares them, then is laid out once (`packages/core/src/editor/text/pending-layout.ts`, `packages/core/tests/editor/text/pending-layout.test.ts`).- Emoji are 1 em squares with their image drawn over, once per text and apart from the fills, as Figma does: `drawSavedEmoji` over a saved glyph's placeholder square (`emojiCodePoints`), `drawLaidOutEmoji` over the blank square the layout gives a character it falls back to `OpenPencil Emoji Metrics` for, the last fallback family, generated by `bun run generate:emoji-metrics`. The image comes from the browser's emoji font through a 2D canvas, or from Noto Color Emoji that `prepareGraphFonts` loads where nothing draws platform emoji (`tests/e2e/canvas/saved-glyph-visual.spec.ts`).- A keycap mark (U+20E3) is laid out as a zero-width space (`laidOutText`), since CanvasKit shapes it with the key's font, which lacks it; its frame, Noto Sans Symbols' outline that Figma draws, is drawn in the text's paint and saved apart (`packages/core/src/text/keycap.ts`, whose frame `bun run generate:emoji-metrics` writes to `packages/core/src/text/font/keycap.ts`; `packages/core/tests/canvas/text/shape.test.ts`).diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.tsindex 75386737d..9cc031887 100644--- a/packages/core/src/canvas/renderer.ts+++ b/packages/core/src/canvas/renderer.ts@@ -1,4 +1,4 @@-import { isEqual } from 'es-toolkit'+import { isEqual, noop } from 'es-toolkit'import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graph'import type { RenderColorSpace, ResolvedRenderColor } from '@open-pencil/scene-graph/color'@@ -376,6 +376,20 @@ export class SkiaRenderer {async loadFonts(onFallbackFontsLoaded?: () => void): Promise<void> {await RendererFonts.loadFonts(this, onFallbackFontsLoaded)+ if (this.fontsLoaded) this.resolveFontsLoaded()+ }++ private resolveFontsLoaded: () => void = noop+ private readonly fontsLoadedPromise = new Promise<void>((resolve) => {+ this.resolveFontsLoaded = resolve+ })++ /**+ * Settles once the canvas has the faces it draws and creates text with, or once it is destroyed+ * without them, so nothing waits on a canvas that is gone.+ */+ whenFontsLoaded(): Promise<void> {+ return this.fontsLoaded ? Promise.resolve() : this.fontsLoadedPromise}syncFontGeneration(): void {@@ -653,6 +667,10 @@ export class SkiaRenderer {return RenderText.measureTextNode(this, node, maxWidth)}+ measureTextAsDrawn(node: SceneNode, maxWidth?: number): { width: number; height: number } | null {+ return RenderText.measureTextAsDrawn(this, node, maxWidth)+ }+nodeFontReadiness(node: SceneNode): RenderText.NodeFontReadiness {if (node.type !== 'TEXT') return 'ready'const cached = this.textFonts.readiness.get(node.id)@@ -872,5 +890,6 @@ export class SkiaRenderer {destroy(): void {destroyRenderer(this)+ this.resolveFontsLoaded()}}diff --git a/packages/core/src/canvas/renderer/fonts.ts b/packages/core/src/canvas/renderer/fonts.tsindex c69ac5ed4..8af23ffb8 100644--- a/packages/core/src/canvas/renderer/fonts.ts+++ b/packages/core/src/canvas/renderer/fonts.ts@@ -1,6 +1,11 @@import type { Font } from 'canvaskit-wasm'+import { uniqBy } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { CONNECTOR_LABEL_FONT } from '@open-pencil/scene-graph/connectors'+import { FIGJAM_TYPEFACES } from '@open-pencil/scene-graph/figjam'+import { faceLoadKey } from '@open-pencil/scene-graph/font-style'+import { STICKY_FONT_FAMILY, STICKY_FONT_WEIGHT } from '@open-pencil/scene-graph/generated'import type { SkiaRenderer } from '#core/canvas/renderer'import type { NodeFontReadiness } from '#core/canvas/text'@@ -153,6 +158,21 @@ function registerSectionTitleFont(r: SkiaRenderer, data: ArrayBuffer) {}}+/**+ * The faces the editor creates text in: the text tool's, and FigJam's for sticky notes, shape+ * labels and connector labels. They load with the canvas, so new text is laid out in its own face+ * from the first click.+ */+const CREATED_TEXT_FACES = uniqBy(+ [+ { family: DEFAULT_FONT_FAMILY, weight: 400 },+ { family: STICKY_FONT_FAMILY, weight: STICKY_FONT_WEIGHT },+ { family: FIGJAM_TYPEFACES.simple.fontFamily, weight: FIGJAM_TYPEFACES.simple.fontWeight },+ { family: CONNECTOR_LABEL_FONT.family, weight: CONNECTOR_LABEL_FONT.weight }+ ].map(({ family, weight }) => ({ family, style: faceLoadKey(weight) })),+ ({ family, style }) => `${family}\u0000${style}`+)+export async function loadFonts(r: SkiaRenderer,onFallbackFontsLoaded?: () => void@@ -173,7 +193,8 @@ export async function loadFonts(fontManager.loadFont(DEFAULT_FONT_FAMILY, 'Regular'),fontManager.fetchBundledFont(SECTION_TITLE_FONT_URL).catch(() => null),// Without it emoji only take the text font's missing-glyph width; text still draws.- fontManager.loadFont(EMOJI_METRICS_FAMILY, 'Regular').catch(() => null)+ fontManager.loadFont(EMOJI_METRICS_FAMILY, 'Regular').catch(() => null),+ ...CREATED_TEXT_FACES.map(({ family, style }) => fontManager.loadFont(family, style))])if (r.isDestroyed()) returnif (titleData) registerSectionTitleFont(r, titleData)diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 512cde3f0..c9ef2ac50 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -155,6 +155,8 @@ function renderMaskNodeContent(absY: number,frame: Mat3 | null): void {+ // A mask whose fonts are still prepared masks nothing in yet, so what it masks stays hidden too.+ if (fontManager.isNodeBlocked(graph, node.id)) returncanvas.save()canvas.translate(node.x, node.y)// As in Figma, a mask's opacity and layer blur reach what it masks; its blend mode does not.@@ -265,7 +267,7 @@ export function renderNodeSelf(node.internalOnly ||!node.visible ||node.isMask ||- fontManager.isNodeBlocked(nodeId)+ fontManager.isNodeBlocked(graph, nodeId)) {return}@@ -317,8 +319,13 @@ function nodeIsolationLayerBounds(* Whether the canvas draws a node itself: not hidden, a mask, blocked on fonts, drawn live by* node-edit mode, or left to a live island while the canvas previews.*/-function drawsNode(node: SceneNode, overlays: RenderOverlays): boolean {- if (node.internalOnly || !node.visible || node.isMask || fontManager.isNodeBlocked(node.id))+function drawsNode(graph: SceneGraph, node: SceneNode, overlays: RenderOverlays): boolean {+ if (+ node.internalOnly ||+ !node.visible ||+ node.isMask ||+ fontManager.isNodeBlocked(graph, node.id)+ )return falsereturn overlays.nodeEditState?.nodeId !== node.id && !overlays.playIslands?.has(node.id)}@@ -339,7 +346,7 @@ export function renderNode(frame: Mat3 | null = null): void {const found = graph.getNode(nodeId)- if (!found || !drawsNode(found, overlays)) return+ if (!found || !drawsNode(graph, found, overlays)) returnconst node = stickyPlaceholderNode(graph, found, r.stickyPlaceholder) ?? foundr.drawCounts.nodes++diff --git a/packages/core/src/canvas/text/index.ts b/packages/core/src/canvas/text/index.tsindex b4e8402bd..0e06235f8 100644--- a/packages/core/src/canvas/text/index.ts+++ b/packages/core/src/canvas/text/index.ts@@ -67,6 +67,11 @@ function requiredFacesReadiness(r: FontReadinessRenderer, node: SceneNode): Nodelet exhausted = falsefor (const { family, style } of requiredNodeFaces(node)) {if (fontManager.isStyleLoaded(family, style)) continue+ // A face a load found nowhere draws in another face of the family, or the substitute.+ if (fontManager.isFaceMissing(family, style)) {+ if (!fontManager.isLoaded(family)) exhausted = true+ continue+ }const demand = fontFaceDemand(family, style, node.text)const state = fontResolver.state(demand).statedemandFace(r, node, family, style)@@ -191,6 +196,19 @@ export function measureTextNode(maxWidth?: number): { width: number; height: number } | null {if (!r.fontsLoaded || !r.fontProvider || !isNodeFontLoaded(r, node)) return null+ return measureTextAsDrawn(r, node, maxWidth)+}++/**+ * `node`'s size in the fonts the canvas draws it with now, ready or not: what a text being typed+ * shows, which its edit draws from the same fonts.+ */+export function measureTextAsDrawn(+ r: TextRenderer,+ node: SceneNode,+ maxWidth?: number+): { width: number; height: number } | null {+ if (!r.fontsLoaded || !r.fontProvider) return nullif (node.type !== 'TEXT' || !node.text) return nullconst layoutWidth = resolveParagraphLayoutWidth(node, maxWidth)diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.tsindex 49b71fc21..be5724150 100644--- a/packages/core/src/design-jsx/renderer.ts+++ b/packages/core/src/design-jsx/renderer.ts@@ -5,6 +5,7 @@ import { extractPaths, extractPathsFromElements, scalePathInfos } from '#core/icimport type { IconData } from '#core/icons/types'import { layoutAuthoredNodes } from '#core/layout'import { markdownText } from '#core/text/markdown'+import { prepareGraphFonts } from '#core/text/prepare'import { computeAccurateBounds } from '#core/vector/curve-math'function parseViewBox(viewBox: string | undefined): { w: number; h: number } {@@ -54,6 +55,7 @@ function createRenderer(icons: IconProvider) {// Inline SVG is artwork, not an icon from a set.identity: icon.prefix !== INLINE_SVG}),+ prepareFonts: prepareGraphFonts,layout: layoutAuthoredNodes,vectorBounds: computeAccurateBounds,markdown: markdownTextdiff --git a/packages/core/src/editor/clipboard/fonts.ts b/packages/core/src/editor/clipboard/fonts.tsindex 15b48a654..73d43983b 100644--- a/packages/core/src/editor/clipboard/fonts.ts+++ b/packages/core/src/editor/clipboard/fonts.ts@@ -1,34 +1,23 @@import type { EditorContext } from '#core/editor/types'import { computeAllLayouts } from '#core/layout'-import { fontManager } from '#core/text/font/manager'-import { collectGraphFontRequirements } from '#core/text/requirements/collect'-import { missingGraphFontScripts } from '#core/text/requirements/resolved'+import { prepareGraphFonts } from '#core/text/prepare'export function createClipboardFontActions(ctx: EditorContext) {+ /**+ * Prepares the fonts of pasted layers, hiding them meanwhile, and lays the page out in them;+ * resolves to the faces that could not load.+ */async function loadFontsForNodes(nodeIds: string[]) {- fontManager.blockNodesUntilFontsResolve(nodeIds)try {- const requirements = collectGraphFontRequirements(ctx.graph, nodeIds)- const toLoad = fontManager.collectFontKeys(ctx.graph, nodeIds)- const results = await Promise.all(- toLoad.map(([family, style]) => ctx.loadFont(family, style, requirements.characters))- )- const failed = toLoad.filter((_, index) => results[index] === null)- const requiredFallbacks = missingGraphFontScripts(requirements)- const fallbacks = await fontManager.ensureFallbackPack(- requiredFallbacks,- requirements.characters- )- const missingFallback = requiredFallbacks.some(- (script) => (fallbacks[script]?.length ?? 0) === 0- )- if (failed.length === 0 && !missingFallback) {- for (const node of requirements.nodes) if (node.type === 'TEXT') node.textPicture = null- }+ const status = await prepareGraphFonts(ctx.graph, nodeIds, {+ loadFont: ctx.loadFont,+ hide: true+ })computeAllLayouts(ctx.graph, ctx.state.currentPageId)- return failed+ return status.issues+ .filter((issue) => issue.status === 'unresolved')+ .map((issue) => [issue.family, issue.style] as [string, string])} finally {- fontManager.unblockNodes(nodeIds)ctx.getRenderer()?.invalidateAllPictures()ctx.requestRender()}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 6a2965eac..95c84867b 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -21,6 +21,7 @@ import { createLayoutRunner } from '#core/layout/mutations'import { emitNavigationTrace } from '#core/profiler'import { TextEditor } from '#core/text/editor'import { fontManager } from '#core/text/font/manager'+import { prepareTextFonts } from '#core/text/prepare'import { fontResolver } from '#core/text/resolver'import { createAlignmentActions } from './alignment'@@ -98,10 +99,9 @@ export function createEditor(options?: EditorOptions) {const interactiveEdits = new Set<symbol>()let _textEditor: TextEditor | null = nullconst events: Emitter<EditorEvents> = createNanoEvents()- const stopFontResolutionEvents = fontResolver.subscribe((event, snapshot) => {- if (event === 'settled') pendingTextLayout.relayoutReady(_renderer)+ const stopFontResolutionEvents = fontResolver.subscribe((event, snapshot) =>events.emit('font:resolution-changed', event, snapshot)- })+ )const stopFontLoadEvents = fontManager.onFaceLoaded((family, style) =>events.emit('font:loaded', family, style))@@ -227,8 +227,11 @@ export function createEditor(options?: EditorOptions) {const { runLayoutForNode, runMutationWithLayout } = createLayoutRunner(() => _graph)const pendingTextLayout = createPendingTextLayout({getGraph: () => _graph,+ getRenderer: () => _renderer,+ prepareFonts: (texts) => prepareTextFonts(texts, { loadFont: _loadFont }),runLayoutForNode,- requestRender+ requestRender,+ onEditorEvent})const { scheduleComponentSync } = createComponentSyncScheduler(() => _graph, requestRender)@@ -362,10 +365,11 @@ export function createEditor(options?: EditorOptions) {_renderers.add(renderer)_textEditor ??= new TextEditor(ck)uninstallTextMeasurer?.()+ // Measures with the editor's current renderer, which removing this one falls back from.uninstallTextMeasurer =typeof renderer.measureTextNode === 'function'? installTextMeasurer((node, maxWidth) =>- pendingTextLayout.measure(renderer, node, maxWidth)+ _renderer ? pendingTextLayout.measure(_renderer, node, maxWidth) : null): null}@@ -386,10 +390,10 @@ export function createEditor(options?: EditorOptions) {function replaceGraph(newGraph: SceneGraph) {nodes.cancelNodePreviews()undo.discardBatches()+ pendingTextLayout.clear()_graph = newGraphstate.documentKind = _graph.documentKindsetActiveTool(offeredTool(state, state.activeTool))- pendingTextLayout.clear()subscribeToGraph()const previousPageId = state.currentPageIdstate.currentPageId = _graph.getPages()[0]?.id ?? _graph.rootIddiff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.tsindex 4c4c69ee7..d7abb6fc0 100644--- a/packages/core/src/editor/pages.ts+++ b/packages/core/src/editor/pages.ts@@ -1,5 +1,3 @@-import { limitAsync } from 'es-toolkit/promise'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { instanceMainComponent } from '@open-pencil/scene-graph/instances'import type { Color } from '@open-pencil/scene-graph/primitives'@@ -15,9 +13,7 @@ import {} from '#core/kiwi/fig/population/client'import { isReaderPagePending, recoverReaderPage } from '#core/kiwi/fig/session/document-state'import { computeAllLayouts } from '#core/layout'-import { fontManager } from '#core/text/font/manager'-import { collectGraphFontRequirements } from '#core/text/requirements/collect'-import { missingGraphFontScripts } from '#core/text/requirements/resolved'+import { prepareGraphFonts } from '#core/text/prepare'import { createPageLayouts } from './pages/layouts'import { createPageViewportStore } from './pages/viewports'@@ -139,60 +135,16 @@ export function createPageActions(ctx: EditorContext, drawing?: PageDrawing) {options: PreparePageOptions): Promise<void> {const childIds = ctx.graph.getChildren(pageId).map((node) => node.id)- const toLoad = fontManager.collectFontKeys(ctx.graph, childIds)- const requirements = collectGraphFontRequirements(ctx.graph, childIds)- options.onProgress?.({- phase: 'resolving-fonts',- detail: pageName,- completed: 0,- total: toLoad.length- })- fontManager.blockNodesUntilFontsResolve(childIds)try {- let completedFaces = 0- const loadFace = limitAsync(async ([family, style]: [string, string]) => {- throwIfAborted(options.signal)- const result = await ctx.loadFont(family, style, requirements.characters, options.signal)- throwIfAborted(options.signal)- completedFaces++- options.onProgress?.({- phase: 'resolving-fonts',- detail: `${family} ${style}`,- completed: completedFaces,- total: toLoad.length- })- return result- }, MAX_CONCURRENT_FONT_LOADS)- const results = await Promise.all(toLoad.map(loadFace))- throwIfAborted(options.signal)- const requiredFallbacks = missingGraphFontScripts(requirements)- options.onProgress?.({- phase: 'resolving-fallbacks',- detail: pageName,- completed: 0,- total: requiredFallbacks.length+ await prepareGraphFonts(ctx.graph, childIds, {+ loadFont: ctx.loadFont,+ hide: true,+ signal: options.signal,+ concurrency: MAX_CONCURRENT_FONT_LOADS,+ label: pageName,+ onProgress: options.onProgress})- const fallbacks = await fontManager.ensureFallbackPack(- requiredFallbacks,- requirements.characters,- options.signal- )- throwIfAborted(options.signal)- options.onProgress?.({- phase: 'resolving-fallbacks',- detail: pageName,- completed: requiredFallbacks.length,- total: requiredFallbacks.length- })- const facesReady = results.every((result) => result !== null)- const fallbacksReady = requiredFallbacks.every(- (script) => (fallbacks[script]?.length ?? 0) > 0- )- if (facesReady && fallbacksReady) {- for (const node of requirements.nodes) if (node.type === 'TEXT') node.textPicture = null- }} finally {- fontManager.unblockNodes(childIds)ctx.getRenderer()?.invalidateAllPictures()}}diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.tsindex 5973ee41c..c4b8404cf 100644--- a/packages/core/src/editor/text.ts+++ b/packages/core/src/editor/text.ts@@ -7,9 +7,12 @@ import {type InstanceOverrideState} from '@open-pencil/scene-graph/instances/overrides'+import { isNodeFontLoaded } from '#core/canvas/text'import { textAutoResizeChanges } from '#core/layout/text-auto-resize'+import { getTextMeasurer, withTextMeasurer } from '#core/layout/text-measurement'import type { TextEditorState } from '#core/text/editor'import { hasGlyphOutlines } from '#core/text/font/glyphs'+import { prepareTextFonts } from '#core/text/prepare'import { applyBoundTextEdit } from './components/authoring/text-edit'import { fitEmptyLabelToPlaceholder } from './connectors/label-edit'@@ -122,12 +125,60 @@ export function createTextActions(ctx: EditorContext) {const node = ctx.graph.getNode(nodeId)if (!node) returnconst { width, height } = node- ctx.graph.updateNode(nodeId, {- ...textAutoResizeChanges(node, changes),- ...changes,- ...pathTextEditChanges(node, changes)+ measuringEditedText(nodeId, () => {+ ctx.graph.updateNode(nodeId, {+ ...textAutoResizeChanges(node, changes),+ ...changes,+ ...pathTextEditChanges(node, changes)+ })+ if (node.width !== width || node.height !== height) ctx.runLayoutForNode(nodeId)+ })+ if ('text' in changes || 'styleRuns' in changes) prepareEditedText(nodeId)+ }++ /**+ * Runs `fn` with the text being typed measured in the fonts it is drawn with now, as its edit+ * draws it, so its size and its glyphs agree while it waits for fonts it newly needs. Other text+ * is measured as layout measures it.+ */+ function measuringEditedText(nodeId: string, fn: () => void) {+ const renderer = ctx.getRenderer()+ const measure = getTextMeasurer()+ if (!renderer || !measure) return fn()+ withTextMeasurer(+ (node, maxWidth) =>+ node.id === nodeId ? renderer.measureTextAsDrawn(node, maxWidth) : measure(node, maxWidth),+ fn+ )+ }++ /**+ * Prepares the fonts the typed text newly needs, such as a script's fallback, through the one+ * gate, and once they are in, redraws the edit and sizes the text in them.+ */+ function prepareEditedText(nodeId: string) {+ const renderer = ctx.getRenderer()+ const node = ctx.graph.getNode(nodeId)+ if (!renderer?.fontsLoaded || !node || isNodeFontLoaded(renderer, node)) return+ void sizeInPreparedFonts(nodeId, node)+ }++ async function sizeInPreparedFonts(nodeId: string, node: SceneNode) {+ const graph = ctx.graph+ await prepareTextFonts([node], { loadFont: ctx.loadFont })+ // A replaced document has its own text, whatever its ids.+ if (ctx.graph !== graph) return+ const te = ctx.getTextEditor()+ const current = ctx.graph.getNode(nodeId)+ if (!current) return+ if (te?.isActive && te.nodeId === nodeId) te.rebuildParagraph(current)+ measuringEditedText(nodeId, () => {+ const sized = textAutoResizeChanges(current, { text: current.text })+ const { width, height } = current+ ctx.graph.updateNode(nodeId, sized)+ if (current.width !== width || current.height !== height) ctx.runLayoutForNode(nodeId)})- if (node.width !== width || node.height !== height) ctx.runLayoutForNode(nodeId)+ ctx.requestRender()}/** A text draws from its live layout while edited, so it is drawn afresh as the edit starts and ends. */diff --git a/packages/core/src/editor/text/pending-layout.ts b/packages/core/src/editor/text/pending-layout.tsindex bf7971c6d..15891d12b 100644--- a/packages/core/src/editor/text/pending-layout.ts+++ b/packages/core/src/editor/text/pending-layout.ts@@ -1,66 +1,153 @@+import { compact } from 'es-toolkit'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { generatedFrameOwner } from '@open-pencil/scene-graph/generated'import type { SkiaRenderer } from '#core/canvas/renderer'-import { isNodeFontLoaded } from '#core/canvas/text'+import type { EditorContext } from '#core/editor/types'import { sizeAutoResizingText } from '#core/layout/text-auto-resize'+import { fontManager } from '#core/text/font/manager'-export type PendingLayoutRenderer = Pick<SkiaRenderer, 'measureTextNode' | 'fontsLoaded'> &- Parameters<typeof isNodeFontLoaded>[0]+export type PendingLayoutRenderer = Pick<+ SkiaRenderer,+ 'measureTextNode' | 'fontsLoaded' | 'whenFontsLoaded' | 'syncFontGeneration'+>interface PendingTextLayoutContext {getGraph: () => SceneGraph+ getRenderer: () => PendingLayoutRenderer | null+ /** Prepares the fonts of `texts`: `prepareTextFonts` with the editor's loader. */+ prepareFonts: (texts: SceneNode[]) => Promise<unknown>runLayoutForNode: (id: string) => voidrequestRender: () => void- /** Whether the renderer can measure this layer with its own faces. */- isReady?: (renderer: PendingLayoutRenderer, node: SceneNode) => boolean-}--function facesLoaded(renderer: PendingLayoutRenderer, node: SceneNode): boolean {- return renderer.fontsLoaded && isNodeFontLoaded(renderer, node)+ onEditorEvent: EditorContext['onEditorEvent']}/**- * Text measured before its face loaded is laid out with an estimate. Remember those layers and,- * once their faces settle, measure them again and lay out the frames around them, so auto-sized- * text takes its real size wherever it sits, without adding an undo step. Layout of the- * document's own state stays derived.+ * Text that layout reaches before its fonts are prepared keeps the size it has and stays off the+ * canvas while `prepareFonts` prepares them. Then it is measured, the frames around it are laid+ * out, and it draws, once, in its own fonts. Edits apply at once and never wait for fonts, so+ * nothing lands late over a newer edit, an undo, or another document. Laying text out again adds+ * no undo step, and layout of the document's own state stays derived.*/export function createPendingTextLayout(ctx: PendingTextLayoutContext) {- /** Layer id → whether it was measured while laying out the document's own state. */- const pending = new Map<string, boolean>()- const ready = ctx.isReady ?? facesLoaded+ /** Layer id → whether it was measured only while laying out the document's own state. */+ const queued = new Map<string, boolean>()+ /** Text its fonts could not measure, prepared or failed, tried again once fonts settle. */+ const stalled = new Map<string, boolean>()+ /** The text being laid out after its fonts were prepared, which measuring does not queue again. */+ let layingOut: ReadonlySet<string> = new Set()+ /** Queued text kept off the canvas, each holding one block its preparation releases. */+ const hidden = new Set<string>()+ let scheduled = false+ /** Counts replaced documents, whose text a preparation still running no longer lays out. */+ let documents = 0function measure(renderer: PendingLayoutRenderer, node: SceneNode, maxWidth?: number) {const size = renderer.measureTextNode(node, maxWidth)- if (!size && node.type === 'TEXT' && node.text && !ready(renderer, node)) {- const graph = ctx.getGraph()- pending.set(node.id, (pending.get(node.id) ?? true) && graph.isApplyingDerivedLayout)- }+ if (!size && node.type === 'TEXT' && node.text) defer(node.id)return size}- function relayoutReady(renderer: PendingLayoutRenderer | null) {- if (!renderer || pending.size === 0) return+ function note(into: Map<string, boolean>, id: string, derived: boolean) {+ into.set(id, (into.get(id) ?? true) && derived)+ }++ function defer(id: string) {+ const derived = ctx.getGraph().isApplyingDerivedLayout+ if (layingOut.has(id)) {+ note(stalled, id, derived)+ return+ }+ if (!hidden.has(id)) {+ fontManager.blockNodesUntilFontsResolve(ctx.getGraph(), [id])+ hidden.add(id)+ }+ note(queued, id, derived)+ schedule()+ }++ function schedule() {+ if (scheduled) return+ scheduled = true+ queueMicrotask(() => void prepareQueued())+ }++ async function prepareQueued() {+ scheduled = false+ if (queued.size === 0) return+ const batch = new Map(queued)+ queued.clear()const graph = ctx.getGraph()+ const opened = documents+ const ids = [...batch.keys()]+ const held = ids.filter((id) => hidden.delete(id))+ try {+ const renderer = ctx.getRenderer()+ if (renderer && !renderer.fontsLoaded) await renderer.whenFontsLoaded()+ await ctx.prepareFonts(compact(ids.map((id) => graph.getNode(id))))+ } catch (error) {+ // Text in faces that did load is still laid out; text in faces that failed stalls there.+ console.warn('Text fonts could not be prepared:', error)+ } finally {+ // Text queued again meanwhile holds a block of its own until it is prepared in turn.+ fontManager.unblockNodes(graph, held)+ }+ if (opened !== documents || ctx.getGraph() !== graph) return+ layOut(graph, batch)+ }++ function layOut(graph: SceneGraph, batch: ReadonlyMap<string, boolean>) {+ ctx.getRenderer()?.syncFontGeneration()const edited: string[] = []const derived: string[] = []- for (const [id, isDerived] of pending) {- const node = graph.getNode(id)- if (node && !ready(renderer, node)) continue- pending.delete(id)- if (node) (isDerived ? derived : edited).push(id)+ for (const [id, isDerived] of batch) {+ if (graph.getNode(id)) (isDerived ? derived : edited).push(id)}- if (edited.length === 0 && derived.length === 0) return// Layout measures text only in auto layout; text that sizes itself is measured here,// unless it keeps the glyphs its file saved, whose size is the file's.const relayout = (id: string) => {- if (!graph.getNode(id)?.derivedTextGlyphs?.length) sizeAutoResizingText(graph, id)+ const node = graph.getNode(id)+ if (!node) return+ if (!node.derivedTextGlyphs?.length) sizeAutoResizingText(graph, id)ctx.runLayoutForNode(id)+ // A sticky note, shape, or connector fits itself to the text it is named by.+ const owner = generatedFrameOwner(graph, node)+ if (owner) ctx.runLayoutForNode(owner.id)+ }+ layingOut = new Set(batch.keys())+ try {+ if (derived.length > 0) graph.applyDerivedLayoutDuring(() => derived.forEach(relayout))+ edited.forEach(relayout)+ } finally {+ layingOut = new Set()}- if (derived.length > 0) graph.applyDerivedLayoutDuring(() => derived.forEach(relayout))- edited.forEach(relayout)ctx.requestRender()}- return { measure, relayoutReady, clear: () => pending.clear() }+ /** Tries the text again that its prepared fonts could not measure, once fonts have settled. */+ function retryStalled() {+ if (stalled.size === 0) return+ // It shows already, in the faces it has, and keeps showing while it is tried again.+ for (const [id, derived] of stalled) note(queued, id, derived)+ stalled.clear()+ schedule()+ }++ /** Drops the text of the document about to be replaced, before the editor replaces it. */+ function clear() {+ fontManager.unblockNodes(ctx.getGraph(), [...hidden])+ hidden.clear()+ queued.clear()+ stalled.clear()+ documents+++ }++ ctx.onEditorEvent('font:resolution-changed', (event) => {+ if (event === 'settled') retryStalled()+ })+ // A face loaded outside the resolver can be the one stalled text was missing.+ ctx.onEditorEvent('font:loaded', retryStalled)++ return { measure, retryStalled, clear }}diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex 9078e1d6e..4ee062caa 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -15,6 +15,7 @@ import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'import { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'import { layoutAuthoredNodes } from '#core/layout'+import { prepareGraphFonts } from '#core/text/prepare'import type { DrawIOExportTarget } from './formats/drawio/export'import { exportFigFile, parseFigFile } from './formats/fig'@@ -320,6 +321,13 @@ export const penFormat: IOFormatAdapter<'pen'> = {loadPenImages(assets.images, input),loadPenIcons(assets.icons, context?.icons ?? defaultIcons)])+ // Its text takes fonts from variables and components too, so the fonts it uses are read+ // from a build without layout and prepared before the build that lays it out.+ const unlaid = buildPenGraph(doc, { images, icons })+ await prepareGraphFonts(+ unlaid,+ unlaid.getPages(true).map((page) => page.id)+ )// A .pen file stores its layout intent, not the sizes and positions it implies.const graph = buildPenGraph(doc, {images,@@ -370,6 +378,10 @@ export const drawioFormat: IOFormatAdapter<'drawio'> = {throw new Error(`Could not read the draw.io pages ${file.unreadable.join(', ')}`)}const graph = drawioToSceneGraph(file)+ await prepareGraphFonts(+ graph,+ graph.getPages().map((page) => page.id)+ )// draw.io stores label text, not the sizes it lays out to.layoutAuthoredNodes(graph,diff --git a/packages/core/src/io/formats/html/import.ts b/packages/core/src/io/formats/html/import.tsindex 3d5796618..bd6838fd0 100644--- a/packages/core/src/io/formats/html/import.ts+++ b/packages/core/src/io/formats/html/import.ts@@ -36,7 +36,7 @@ export async function readHTMLDocument(const styled = options.tailwind? await tailwindHTMLToDesignDocument(html, options.tailwind, { css: options.cssText, runtime }): await htmlToDesignDocument(html, { cssText: options.cssText, runtime })- return { styled, graph: sceneGraphFromStyledHTML(styled, { pageName: options.pageName }) }+ return { styled, graph: await sceneGraphFromStyledHTML(styled, { pageName: options.pageName }) }}/** Reads HTML files where the headless CSS runtime is available, as in the CLI. */diff --git a/packages/core/src/io/formats/html/layers.ts b/packages/core/src/io/formats/html/layers.tsindex 616faa6ee..641889f9a 100644--- a/packages/core/src/io/formats/html/layers.ts+++ b/packages/core/src/io/formats/html/layers.ts@@ -3,17 +3,23 @@ import { designDocumentToSceneGraph } from '@open-pencil/dom-css/scene-graph'import type { SceneGraph } from '@open-pencil/scene-graph'import { layoutAuthoredNodes } from '#core/layout'+import { prepareGraphFonts } from '#core/text/prepare'/**- * The layers a styled DOM describes, with the sizes and positions its layout implies. Styling- * belongs to whoever has a CSS runtime, such as a browser or the headless runtime; building and- * laying out the layers happens here for every caller. Safe to bundle for the browser.+ * The layers a styled DOM describes, with the sizes and positions its layout implies, laid out+ * once their text's fonts are prepared. Styling belongs to whoever has a CSS runtime, such as a+ * browser or the headless runtime; building and laying out the layers happens here for every+ * caller. Safe to bundle for the browser.*/-export function sceneGraphFromStyledHTML(+export async function sceneGraphFromStyledHTML(styled: DesignDocument,options: { pageName?: string } = {}-): SceneGraph {+): Promise<SceneGraph> {const graph = designDocumentToSceneGraph(styled, { pageName: options.pageName })+ await prepareGraphFonts(+ graph,+ graph.getPages().map((page) => page.id)+ )layoutAuthoredNodes(graph,graph.getPages().map((page) => page.id)diff --git a/packages/core/src/io/formats/pdf/prepare.ts b/packages/core/src/io/formats/pdf/prepare.tsindex 77fb2c12e..4147cc42d 100644--- a/packages/core/src/io/formats/pdf/prepare.ts+++ b/packages/core/src/io/formats/pdf/prepare.ts@@ -30,7 +30,9 @@ export async function preparePDFFonts(specs: readonly PDFPageSpec[]): Promise<DocumentFontStatus> {const nodeIds = specs.flatMap((spec) => spec.nodeIds)- return prepareGraphFonts(graph, nodeIds, await pdfWrittenCharacters(graph, nodeIds))+ return prepareGraphFonts(graph, nodeIds, {+ extraCharacters: await pdfWrittenCharacters(graph, nodeIds)+ })}/**diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.tsindex 8c3ebf172..e7f22cace 100644--- a/packages/core/src/layout/text-measurement.ts+++ b/packages/core/src/layout/text-measurement.ts@@ -46,12 +46,22 @@ 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. */+/**+ * The size of `node`'s text. With a measurer installed, that is its size in its own fonts; text+ * whose fonts are not prepared keeps the size it has, never one guessed in another face, until+ * the measurer's host prepares them and lays it out again (the editor's `createPendingTextLayout`).+ * With none, as in a host without fonts, it is estimated.+ */export function measureTextForLayout(node: SceneNode,maxWidth?: number): { width: number; height: number } {- return globalTextMeasurer?.(node, maxWidth) ?? estimateTextSize(node, maxWidth)+ if (!globalTextMeasurer) return estimateTextSize(node, maxWidth)+ const measured = globalTextMeasurer(node, maxWidth)+ if (measured) return measured+ // Empty text measures nothing but its line, which needs no fonts beyond the default.+ if (node.type !== 'TEXT' || !node.text) return estimateTextSize(node, maxWidth)+ return { width: node.width, height: node.height }}const installedMeasurers: TextMeasurer[] = []diff --git a/packages/core/src/text/font/manager.ts b/packages/core/src/text/font/manager.tsindex 5bcb82244..8ea8839ea 100644--- a/packages/core/src/text/font/manager.ts+++ b/packages/core/src/text/font/manager.ts@@ -52,6 +52,8 @@ export class FontManager {private loadedFamilies = new Map<string, ArrayBuffer>()private loadedFamilySources = new Map<string, FontLoadedSource>()private unavailableFaces = new Map<string, FontUnavailableReason>()+ /** Faces a load looked for everywhere and found nowhere, until one of them loads after all. */+ private missingFaces = new Set<string>()private supplementalFamilyData = new Map<string, ArrayBuffer[]>()/** The name each file of a family loaded from several files is registered under. */private fileFamilies = new Map<ArrayBuffer, string>()@@ -73,7 +75,8 @@ export class FontManager {ArrayBuffer,{ axes: FontAxis[]; instances: NamedInstance[] } | null>()- private blockedNodeIds = new Set<string>()+ /** Layers kept off the canvas while their fonts are prepared, by graph, with how many hold each. */+ private blockedNodes = new WeakMap<SceneGraph, Map<string, number>>()private fontProvider: TypefaceFontProvider | null = nullprivate fontProviders = new Set<TypefaceFontProvider>()private providerCanvasKits = new WeakMap<TypefaceFontProvider, CanvasKit>()@@ -138,16 +141,31 @@ export class FontManager {return this.registrationGeneration}- blockNodesUntilFontsResolve(nodeIds: readonly string[]): void {- for (const nodeId of nodeIds) this.blockedNodeIds.add(nodeId)+ /**+ * Keeps `nodeIds` of `graph` off the canvas until each is unblocked as many times as it was+ * blocked, so one preparation that ends does not show text another still prepares.+ */+ blockNodesUntilFontsResolve(graph: SceneGraph, nodeIds: readonly string[]): void {+ let blocked = this.blockedNodes.get(graph)+ if (!blocked) {+ blocked = new Map()+ this.blockedNodes.set(graph, blocked)+ }+ for (const nodeId of nodeIds) blocked.set(nodeId, (blocked.get(nodeId) ?? 0) + 1)}- unblockNodes(nodeIds: readonly string[]): void {- for (const nodeId of nodeIds) this.blockedNodeIds.delete(nodeId)+ unblockNodes(graph: SceneGraph, nodeIds: readonly string[]): void {+ const blocked = this.blockedNodes.get(graph)+ if (!blocked) return+ for (const nodeId of nodeIds) {+ const holds = blocked.get(nodeId) ?? 0+ if (holds > 1) blocked.set(nodeId, holds - 1)+ else blocked.delete(nodeId)+ }}- isNodeBlocked(nodeId: string): boolean {- return this.blockedNodeIds.has(nodeId)+ isNodeBlocked(graph: SceneGraph, nodeId: string): boolean {+ return this.blockedNodes.get(graph)?.has(nodeId) ?? false}localAccessState(): LocalFontAccessState {@@ -404,12 +422,21 @@ export class FontManager {const shared = this.sharedVariableFace(family, style)if (shared) return this.withRemoteCoverage(family, style, shared, characters, signal)- return (+ const found =(await this.loadBundledFont(family, style)) ??(await this.loadCachedFont(family, style, characters)) ??(await this.loadRemoteFont(family, style, characters, signal)) ??(await this.loadStandIn(family, style))- )+ if (!found) this.missingFaces.add(`${family}|${style}`)+ return found+ }++ /**+ * Whether a load looked for this face and found it nowhere, so text in it draws in another face,+ * as Figma draws a missing font, rather than waiting for it.+ */+ isFaceMissing(family: string, style: string): boolean {+ return this.missingFaces.has(`${family}|${style}`)}/**@@ -812,6 +839,7 @@ export class FontManager {source?: FontLoadedSource): ArrayBuffer | null {const key = `${family}|${style}`+ this.missingFaces.delete(key)const existing = this.loadedFamilies.get(key)if (existing && sameFontFile(existing, buffer)) {if (source) this.loadedFamilySources.set(key, source)diff --git a/packages/core/src/text/prepare.ts b/packages/core/src/text/prepare.tsindex 2003d4a59..47b452a34 100644--- a/packages/core/src/text/prepare.ts+++ b/packages/core/src/text/prepare.ts@@ -1,4 +1,5 @@-import { uniq } from 'es-toolkit'+import { uniq, uniqBy } from 'es-toolkit'+import { limitAsync } from 'es-toolkit/promise'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'@@ -11,7 +12,11 @@ import {} from '#core/text/emoji'import { fontGlyphCoverageSync } from '#core/text/font/glyphs'import { fontManager } from '#core/text/font/manager'-import { collectGraphFontRequirements, collectNodeFontFaces } from '#core/text/requirements/collect'+import {+ collectFontRequirements,+ collectGraphFontRequirements,+ collectNodeFontFaces+} from '#core/text/requirements/collect'import { missingGraphFontScripts } from '#core/text/requirements/resolved'import { documentFontStatus, type DocumentFontStatus } from './font/status'@@ -41,27 +46,104 @@ function laidOutEmojiCharacters(node: SceneNode): string {return characters}-export async function prepareGraphFonts(- graph: SceneGraph,- nodeIds: readonly string[],+/** How far preparing a page's or a selection's fonts has got, for a loading indicator. */+export interface FontPreparationProgress {+ phase: 'resolving-fonts' | 'resolving-fallbacks'+ detail: string+ completed: number+ total: number+}++export interface PrepareGraphFontsOptions {/** Characters a writer draws besides the text's own, which the fonts must map too. */- extraCharacters = ''-): Promise<DocumentFontStatus> {- const collected = collectGraphFontRequirements(graph, nodeIds)- const requirements = extraCharacters+ extraCharacters?: string+ /**+ * Loads one face for these characters, `null` when it cannot; the host's loader, which knows+ * its local and cached fonts, or the font manager's.+ */+ loadFont?: (+ family: string,+ style: string,+ characters: string,+ signal?: AbortSignal+ ) => Promise<unknown>+ /** Keeps the layers off the canvas until their fonts are in, so they draw once, in them. */+ hide?: boolean+ signal?: AbortSignal+ /** How many faces load at once; all of them without a limit. */+ concurrency?: number+ /** Names the layers for progress reports. */+ label?: string+ onProgress?: (progress: FontPreparationProgress) => void+ /**+ * Whether a script whose coverage the loaded faces cannot tell needs its fallback pack, as on a+ * desktop where faces load without their coverage.+ */+ treatUnknownCoverageAsMissing?: boolean+}++export interface PreparedGraphFonts extends DocumentFontStatus {+ /** Whether loading changed any face the text draws with, so it draws and measures anew. */+ changed: boolean+}++/**+ * The one way text gets its fonts before it is laid out or drawn: every face its runs name, for+ * the characters they show, the fallback packs for scripts those faces lack, and the emoji font+ * when the platform draws none. Layout measures text only once this has run for it. `nodes` is+ * the text as it is, or as a write is about to make it. Resolves to whether that changed any face+ * the text draws with.+ */+export async function prepareTextFonts(+ nodes: readonly SceneNode[],+ options: PrepareGraphFontsOptions = {}+): Promise<boolean> {+ const { signal, label = '', onProgress } = options+ const load =+ options.loadFont ??+ ((family: string, style: string, characters: string) =>+ fontManager.loadFont(family, style, characters))+ const collected = collectFontRequirements(nodes)+ const requirements = options.extraCharacters? {...collected,- characters: uniq(Array.from(collected.characters + extraCharacters)).join('')+ characters: uniq(Array.from(collected.characters + options.extraCharacters)).join('')}: collected- const faces = requirements.nodes.flatMap(collectNodeFontFaces)- await Promise.all(- faces.map(({ family, style }) => fontManager.loadFont(family, style, requirements.characters))+ const faces = uniqBy(+ requirements.nodes.flatMap(collectNodeFontFaces),+ ({ family, style }) => `${family}\u0000${style}`)- await fontManager.ensureFallbackPack(- missingGraphFontScripts(requirements),- requirements.characters+ const generationBefore = fontManager.generation()+ let completed = 0+ onProgress?.({ phase: 'resolving-fonts', detail: label, completed, total: faces.length })+ const loadFace = async ({ family, style }: { family: string; style: string }) => {+ signal?.throwIfAborted()+ await load(family, style, requirements.characters, signal)+ signal?.throwIfAborted()+ completed+++ onProgress?.({+ phase: 'resolving-fonts',+ detail: `${family} ${style}`,+ completed,+ total: faces.length+ })+ }+ await Promise.all(+ faces.map(options.concurrency ? limitAsync(loadFace, options.concurrency) : loadFace))+ const scripts = missingGraphFontScripts(requirements, {+ treatUnknownCoverageAsMissing: options.treatUnknownCoverageAsMissing+ })+ onProgress?.({ phase: 'resolving-fallbacks', detail: label, completed: 0, total: scripts.length })+ const fallbacks = await fontManager.ensureFallbackPack(scripts, requirements.characters, signal)+ signal?.throwIfAborted()+ onProgress?.({+ phase: 'resolving-fallbacks',+ detail: label,+ completed: scripts.length,+ total: scripts.length+ })// Without a platform that draws emoji, emoji are drawn with Noto, loaded for just these: the// saved ones, and the ones the layout leaves to the emoji metrics font.const emoji =@@ -69,5 +151,27 @@ export async function prepareGraphFonts(requirements.nodes.map(laidOutEmojiCharacters).join('')if (emoji && !canDrawPlatformEmoji())await fontManager.loadRemoteFont(NOTO_COLOR_EMOJI_FAMILY, 'Regular', emoji)- return documentFontStatus(graph, nodeIds)+ const changed =+ fontManager.generation() !== generationBefore ||+ Object.values(fallbacks).some((families) => families.length > 0)+ // Text drawn before these fonts came in draws again with them.+ if (changed)+ for (const node of requirements.nodes) if (node.type === 'TEXT') node.textPicture = null+ return changed+}++/** Prepares the fonts of the text in `nodeIds` and the layers inside them; see `prepareTextFonts`. */+export async function prepareGraphFonts(+ graph: SceneGraph,+ nodeIds: readonly string[],+ options: PrepareGraphFontsOptions = {}+): Promise<PreparedGraphFonts> {+ const { nodes } = collectGraphFontRequirements(graph, nodeIds)+ if (options.hide) fontManager.blockNodesUntilFontsResolve(graph, nodeIds)+ try {+ const changed = await prepareTextFonts(nodes, options)+ return { ...documentFontStatus(graph, nodeIds), changed }+ } finally {+ if (options.hide) fontManager.unblockNodes(graph, nodeIds)+ }}diff --git a/packages/core/src/text/requirements/collect.ts b/packages/core/src/text/requirements/collect.tsindex b6136e0bc..b52820d95 100644--- a/packages/core/src/text/requirements/collect.ts+++ b/packages/core/src/text/requirements/collect.ts@@ -66,26 +66,37 @@ export interface GraphFontRequirements {scripts: FontFallbackScript[]}+/** What the text of `nodes` needs to measure and draw: its characters and the scripts among them. */+export function collectFontRequirements(nodes: readonly SceneNode[]): GraphFontRequirements {+ const characters = new Set<string>()+ const scripts = new Set<FontFallbackScript>()+ for (const node of nodes) {+ if (node.type !== 'TEXT') continue+ for (const { character, sourceIndex } of shownCharacters(node)) {+ characters.add(character)+ const script = fontFallbackScriptForCharacter(character, textLanguageAt(node, sourceIndex))+ if (script) scripts.add(script)+ }+ }+ return {+ characters: Array.from(characters).join(''),+ nodes: [...nodes],+ scripts: Array.from(scripts)+ }+}++/** What the text of `nodeIds` and the layers inside them needs. */export function collectGraphFontRequirements(graph: SceneGraph,nodeIds: readonly string[]): GraphFontRequirements {- const characters = new Set<string>()const nodes: SceneNode[] = []- const scripts = new Set<FontFallbackScript>()const collect = (nodeId: string) => {const node = graph.getNode(nodeId)if (!node) returnnodes.push(node)- if (node.type === 'TEXT') {- for (const { character, sourceIndex } of shownCharacters(node)) {- characters.add(character)- const script = fontFallbackScriptForCharacter(character, textLanguageAt(node, sourceIndex))- if (script) scripts.add(script)- }- }for (const childId of node.childIds) collect(childId)}for (const nodeId of nodeIds) collect(nodeId)- return { characters: Array.from(characters).join(''), nodes, scripts: Array.from(scripts) }+ return collectFontRequirements(nodes)}diff --git a/packages/core/tests/editor/text/pending-layout.test.ts b/packages/core/tests/editor/text/pending-layout.test.tsindex 17e27dd29..244ca88c6 100644--- a/packages/core/tests/editor/text/pending-layout.test.ts+++ b/packages/core/tests/editor/text/pending-layout.test.ts@@ -1,25 +1,37 @@-import { afterEach, expect, test } from 'bun:test'+import { afterEach, expect, spyOn, test } from 'bun:test'+import { noop } from 'es-toolkit'import { createEditor } from '@open-pencil/core'-import { setTextMeasurer } from '@open-pencil/core/layout'+import type { SkiaRenderer } from '@open-pencil/core/canvas'+import { setTextMeasurer, sizeAutoResizingText } from '@open-pencil/core/layout'import type { SceneNode } from '@open-pencil/scene-graph'+import { expectDefined } from '#core-tests/helpers/assert'import {createPendingTextLayout,type PendingLayoutRenderer} from '#core/editor/text/pending-layout'import { createLayoutRunner } from '#core/layout/mutations'import { textAutoResizeChanges } from '#core/layout/text-auto-resize'+import { fontManager } from '#core/text/font/manager'+import { fontResolver } from '#core/text/resolver'afterEach(() => {setTextMeasurer(null)})+/** Lets the pending preparation and the layout after it run. */+const settle = () => Bun.sleep(0)+/**- * A Hug row around auto-width text whose face loads after the first layout; `outside` puts the- * text on the page instead, where only its own measurement sizes it.+ * A Hug row around auto-width text whose fonts are prepared after the first layout; `outside` puts+ * the text on the page instead, where only its own measurement sizes it.*/-function setup({ outside = false, text: values = {} }: { outside?: boolean; text?: Partial<SceneNode> } = {}) {+function setup({+ outside = false,+ text: values = {},+ canvasFontsLoaded = true+}: { outside?: boolean; text?: Partial<SceneNode>; canvasFontsLoaded?: boolean } = {}) {const editor = createEditor()const graph = editor.graphconst frame = graph.createNode('FRAME', editor.state.currentPageId, {@@ -35,75 +47,114 @@ function setup({ outside = false, text: values = {} }: { outside?: boolean; texttext: 'Weighted label',fontWeight: 900,textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 100,+ height: 20,...values})let loaded = false+ let canvasLoaded: () => void = noopconst renderer: PendingLayoutRenderer = {- fontsLoaded: true,- measureTextNode: () => (loaded ? { width: 234, height: 29 } : null)+ fontsLoaded: canvasFontsLoaded,+ measureTextNode: () => (loaded ? { width: 234, height: 29 } : null),+ whenFontsLoaded: () =>+ new Promise((resolve) => {+ canvasLoaded = () => {+ renderer.fontsLoaded = true+ resolve()+ }+ }),+ syncFontGeneration: noop}- const { runLayoutForNode } = createLayoutRunner(() => graph)+ let currentGraph = graph+ const { runLayoutForNode } = createLayoutRunner(() => currentGraph)let renders = 0+ /** The text each preparation was asked for. */+ const prepared: string[][] = []+ /** Whether a preparation makes the fonts measure the text. */+ let preparing = true+ /** Holds each preparation until the test lets it finish, when set. */+ let gate: Promise<void> | null = null+ /** Whether the next preparation fails, as a font that cannot be fetched does. */+ let failing = false/** Whether each layout the pending text ran was the document's own. */const relayouts: boolean[] = []const pending = createPendingTextLayout({- getGraph: () => graph,+ getGraph: () => currentGraph,+ getRenderer: () => renderer,+ prepareFonts: async (texts) => {+ prepared.push(texts.map((node) => node.id))+ await (gate ?? Promise.resolve())+ if (failing) {+ failing = false+ throw new Error('font unavailable')+ }+ if (preparing) loaded = true+ },runLayoutForNode: (id) => {- relayouts.push(graph.isApplyingDerivedLayout)+ relayouts.push(currentGraph.isApplyingDerivedLayout)runLayoutForNode(id)},requestRender: () => renders++,- isReady: () => loaded+ onEditorEvent: editor.onEditorEvent})setTextMeasurer((node, maxWidth) => pending.measure(renderer, node, maxWidth))- const load = () => {- loaded = true- pending.relayoutReady(renderer)- }return {editor,graph,frame,text,- renderer,pending,+ prepared,runLayoutForNode,- load,relayouts,- renders: () => renders+ renders: () => renders,+ canvasLoaded: () => canvasLoaded(),+ stopPreparing: () => (preparing = false),+ loadElsewhere: () => (loaded = true),+ failNextPreparation: () => (failing = true),+ /** Replaces the document, as opening another one does, and returns the new one. */+ replaceDocument: () => {+ pending.clear()+ currentGraph = createEditor().graph+ return currentGraph+ },+ /** Holds preparations until the returned function lets them finish. */+ holdPreparation: () => {+ let release: () => void = noop+ const held = new Promise<void>((resolve) => {+ release = resolve+ })+ gate = held+ return () => {+ if (gate === held) gate = null+ release()+ }+ }}}-test('text laid out before its face loads takes its size, and its Hug frame follows', () => {- const { editor, frame, text, runLayoutForNode, load, relayouts, renders } = setup()+test('text laid out before its fonts are prepared stays hidden at its size, then takes its own', async () => {+ const { editor, graph, frame, text, prepared, runLayoutForNode, relayouts, renders } = setup()runLayoutForNode(text.id)- const estimated = text.width- expect(estimated).not.toBe(234)+ expect([text.width, text.height]).toEqual([100, 20])+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(true)- load()+ await settle()+ expect(prepared).toEqual([[text.id]])+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)expect([text.width, text.height]).toEqual([234, 29])expect([frame.width, frame.height]).toEqual([266, 53])expect(renders()).toBe(1)- expect(relayouts).toEqual([false])+ expect(relayouts.every((derived) => !derived)).toBe(true)expect(editor.undo.canUndo).toBe(false)})-test('a face that loads keeps the layout of the document’s own state derived', () => {- const { graph, text, runLayoutForNode, load, relayouts } = setup()+test('the layout of the document’s own state stays derived', async () => {+ const { graph, text, runLayoutForNode, relayouts } = setup()graph.applyDerivedLayoutDuring(() => runLayoutForNode(text.id))- load()+ await settle()expect(text.width).toBe(234)- expect(relayouts).toEqual([true])-})--test('layers whose faces are still loading or that were removed are left alone', () => {- const { graph, text, pending, renderer, runLayoutForNode, renders } = setup()- runLayoutForNode(text.id)- pending.relayoutReady(renderer)- expect(renders()).toBe(0)- graph.deleteNode(text.id)- pending.relayoutReady(renderer)- expect(renders()).toBe(0)+ expect(relayouts.every(Boolean)).toBe(true)})/** Edits the text as the editor and the plugin API do, measuring it as it changes. */@@ -111,25 +162,122 @@ function edit(graph: ReturnType<typeof setup>['graph'], text: SceneNode, changesgraph.updateNode(text.id, { ...changes, ...textAutoResizeChanges(text, changes) })}-test('text outside auto layout edited before its face loads takes its size when it loads', () => {- const { graph, text, load, editor } = setup({ outside: true })+test('an edit applies at once, and its text takes its size once its fonts are in', async () => {+ const { graph, text, editor } = setup({ outside: true })edit(graph, text, { text: 'Heavier label' })- expect(text.width).not.toBe(234)+ expect(text.text).toBe('Heavier label')+ expect([text.width, text.height]).toEqual([100, 20])- load()+ await settle()expect([text.width, text.height]).toEqual([234, 29])expect(editor.undo.canUndo).toBe(false)})-test('wrapping text outside auto layout takes its height when its face loads', () => {- const { graph, text, load } = setup({ outside: true, text: { textAutoResize: 'HEIGHT', width: 200 } })+test('wrapping text takes its height once its fonts are in', async () => {+ const { graph, text } = setup({ outside: true, text: { textAutoResize: 'HEIGHT', width: 200 } })edit(graph, text, { text: 'Heavier label' })- load()+ await settle()expect([text.width, text.height]).toEqual([200, 29])})-test('text that keeps the glyphs its file saved keeps the size the file gave it', () => {- const { graph, text, runLayoutForNode, load } = setup({+test('text waits for the canvas’s own fonts before its fonts are prepared', async () => {+ const { graph, text, prepared, runLayoutForNode, canvasLoaded } = setup({+ canvasFontsLoaded: false+ })+ runLayoutForNode(text.id)+ await settle()+ expect(prepared).toEqual([])+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(true)++ canvasLoaded()+ await settle()+ expect(prepared).toEqual([[text.id]])+ expect(text.width).toBe(234)+})++test('a document replaced before its text is prepared keeps its text as it is', async () => {+ const { graph, text, runLayoutForNode, replaceDocument, renders } = setup()+ runLayoutForNode(text.id)+ replaceDocument()+ await settle()+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)+ expect(text.width).toBe(100)+ expect(renders()).toBe(0)+})++test('a document replaced while its text is prepared keeps its text as it is', async () => {+ const { graph, text, prepared, runLayoutForNode, replaceDocument, renders, holdPreparation } =+ setup()+ const release = holdPreparation()+ runLayoutForNode(text.id)+ await settle()+ expect(prepared).toEqual([[text.id]])+ replaceDocument()+ release()+ await settle()+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)+ expect(text.width).toBe(100)+ expect(renders()).toBe(0)+})++test('text of the document that replaced another is laid out once its fonts are prepared', async () => {+ const { prepared, replaceDocument, renders } = setup()+ const opened = replaceDocument()+ const next = opened.createNode('TEXT', opened.getPages()[0].id, {+ text: 'Weighted label',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 100,+ height: 20+ })+ sizeAutoResizingText(opened, next.id)+ expect(fontManager.isNodeBlocked(opened, next.id)).toBe(true)++ await settle()+ expect(prepared).toEqual([[next.id]])+ expect(fontManager.isNodeBlocked(opened, next.id)).toBe(false)+ expect([next.width, next.height]).toEqual([234, 29])+ expect(renders()).toBe(1)+})++test('text an edit queues again while it is prepared stays hidden until it is prepared again', async () => {+ const { graph, text, prepared, runLayoutForNode, holdPreparation, stopPreparing } = setup()+ stopPreparing()+ const releaseFirst = holdPreparation()+ runLayoutForNode(text.id)+ await settle()+ const releaseSecond = holdPreparation()+ edit(graph, text, { text: 'Heavier label' })+ await settle()+ expect(prepared).toEqual([[text.id], [text.id]])++ releaseFirst()+ await settle()+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(true)++ releaseSecond()+ await settle()+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)+})++test('text its prepared fonts still cannot measure shows, and is laid out once fonts settle', async () => {+ const { graph, text, prepared, pending, runLayoutForNode, stopPreparing, loadElsewhere } =+ setup()+ stopPreparing()+ runLayoutForNode(text.id)+ await settle()+ expect(prepared).toEqual([[text.id]])+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)+ expect(text.width).toBe(100)++ loadElsewhere()+ pending.retryStalled()+ await settle()+ expect(prepared).toEqual([[text.id], [text.id]])+ expect(text.width).toBe(234)+})++test('text that keeps the glyphs its file saved keeps the size the file gave it', async () => {+ const { graph, text, runLayoutForNode } = setup({outside: true,text: {width: 120,@@ -140,6 +288,135 @@ test('text that keeps the glyphs its file saved keeps the size the file gave it'graph.applyDerivedLayoutDuring(() => runLayoutForNode(text.id))// Measured while it loads, as layout measures text in a flow, without changing it.graph.applyDerivedLayoutDuring(() => textAutoResizeChanges(text, { text: text.text }))- load()+ await settle()expect([text.width, text.height]).toEqual([120, 20])})++/**+ * An editor with a renderer whose fonts measure its auto-sizing text only once `measure` is called;+ * the rest of the renderer stays absent, past what the editor's graph events and text layout reach.+ */+function editorSetup() {+ let measurable = false+ const editor = createEditor({ loadFont: () => Promise.resolve(null) })+ const tiledScene: Partial<SkiaRenderer['tiledScene']> = {+ invalidateNode: noop,+ invalidateStructure: noop+ }+ const renderer: Partial<SkiaRenderer> = {+ tiledScene: tiledScene as SkiaRenderer['tiledScene'],+ forgetNode: noop,+ invalidateVectorPath: noop,+ fontsLoaded: true,+ measureTextNode: () => (measurable ? { width: 234, height: 29 } : null),+ whenFontsLoaded: () => Promise.resolve(),+ syncFontGeneration: noop,+ invalidateNodePicture: noop+ }+ editor.setCanvasKit({} as Parameters<typeof editor.setCanvasKit>[0], renderer as SkiaRenderer)+ const text = editor.graph.createNode('TEXT', editor.state.currentPageId, {+ text: 'Weighted label',+ textAutoResize: 'WIDTH_AND_HEIGHT',+ width: 100,+ height: 20+ })+ /** Settles when the pending text layout next asks for a render, once it has laid text out. */+ const laidOut = () =>+ new Promise<void>((resolve) => {+ const stop = editor.onEditorEvent('render:requested', () => {+ stop()+ resolve()+ })+ })+ return {+ editor,+ text,+ measure: () => (measurable = true),+ laidOut,+ /** Lays the text out before its fonts measure it, which stalls it. */+ stall: async () => {+ const first = laidOut()+ sizeAutoResizingText(editor.graph, text.id)+ await first+ },+ dispose: () => editor.removeCanvasRenderer(renderer as SkiaRenderer)+ }+}++test('the editor lays out text its fonts could not measure once font resolution settles', async () => {+ const { text, measure, laidOut, stall, dispose } = editorSetup()+ try {+ await stall()+ expect(text.width).toBe(100)++ measure()+ const relaid = laidOut()+ await fontResolver.demand({ key: 'pending-layout-test', candidates: [] })+ await relaid+ expect([text.width, text.height]).toEqual([234, 29])+ } finally {+ fontResolver.reset('pending-layout-test')+ dispose()+ }+})++test('the editor lays out text its fonts could not measure once a face loads', async () => {+ const inter = expectDefined(+ await fontManager.fetchBundledFont('/InterVariable.ttf'),+ 'bundled Inter font'+ )+ const { text, measure, laidOut, stall, dispose } = editorSetup()+ try {+ await stall()+ expect(text.width).toBe(100)++ measure()+ // The face listener runs inside markLoaded, so the render it leads to is awaited after it.+ const relaid = laidOut()+ await fontManager.markLoaded('Pending Layout Test', 'Regular', inter)+ await relaid+ expect([text.width, text.height]).toEqual([234, 29])+ } finally {+ dispose()+ }+})++test('text whose fonts fail to load shows at its size, and is laid out once fonts settle', async () => {+ const { graph, text, pending, runLayoutForNode, renders, failNextPreparation } = setup()+ failNextPreparation()+ const warn = spyOn(console, 'warn').mockImplementation(noop)+ try {+ runLayoutForNode(text.id)+ await settle()+ expect(warn).toHaveBeenCalledTimes(1)+ } finally {+ warn.mockRestore()+ }+ expect(fontManager.isNodeBlocked(graph, text.id)).toBe(false)+ expect([text.width, text.height]).toEqual([100, 20])+ expect(renders()).toBe(1)++ pending.retryStalled()+ await settle()+ expect([text.width, text.height]).toEqual([234, 29])+})++test('text whose face loads while a failing preparation runs is laid out in it', async () => {+ const { text, runLayoutForNode, renders, failNextPreparation, holdPreparation, loadElsewhere } =+ setup()+ failNextPreparation()+ const release = holdPreparation()+ const warn = spyOn(console, 'warn').mockImplementation(noop)+ try {+ runLayoutForNode(text.id)+ await settle()+ loadElsewhere()+ release()+ await settle()+ expect(warn).toHaveBeenCalledTimes(1)+ } finally {+ warn.mockRestore()+ }+ expect([text.width, text.height]).toEqual([234, 29])+ expect(renders()).toBe(1)+})diff --git a/packages/core/tests/layout/text-measurement.test.ts b/packages/core/tests/layout/text-measurement.test.tsindex 6efed67fe..207261920 100644--- a/packages/core/tests/layout/text-measurement.test.ts+++ b/packages/core/tests/layout/text-measurement.test.ts@@ -54,10 +54,12 @@ describe('measureTextForLayout', () => {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)+ test('estimates without a measurer, as a host without fonts has none', () => {+ expect(measureTextForLayout(node, 100)).toEqual(estimateTextSize(node, 100))+ })++ test('keeps the size of text whose fonts are not prepared', () => {setTextMeasurer(() => null)- expect(measureTextForLayout(node, 100)).toEqual(estimate)+ expect(measureTextForLayout(node, 100)).toEqual({ width: node.width, height: node.height })})})diff --git a/packages/design-jsx/src/render/roots.ts b/packages/design-jsx/src/render/roots.tsindex d11582e57..f9cc196e5 100644--- a/packages/design-jsx/src/render/roots.ts+++ b/packages/design-jsx/src/render/roots.ts@@ -149,6 +149,7 @@ async function renderInto<Artwork>(...context.warnings,...resolveConnectorEnds(graph, rootIds, connectors, refs)]+ await services.prepareFonts?.(graph, rootIds)if (!options.deferLayout) services.layout(graph, rootIds)return nodes.map((node) => ({diff --git a/packages/design-jsx/src/services.ts b/packages/design-jsx/src/services.tsindex 24ff9e612..5300fae27 100644--- a/packages/design-jsx/src/services.ts+++ b/packages/design-jsx/src/services.ts@@ -29,7 +29,12 @@ export interface DesignJSXServices<Artwork> {svg(source: SVGSource, size: number): Artwork | null/** Vector nodes for the artwork, created under the placement's parent. */createArtwork(graph: SceneGraph, artwork: Artwork, placement: ArtworkPlacement): SceneNode- /** Size and lay out the rendered roots once they are in place. */+ /**+ * Prepare the fonts the rendered roots' text uses, before they are laid out, so layout measures+ * that text in its own fonts. An engine without fonts leaves it out.+ */+ prepareFonts?(graph: SceneGraph, rootIds: readonly string[]): Promise<unknown>+ /** Size and lay out the rendered roots once they are in place and their fonts prepared. */layout(graph: SceneGraph, rootIds: readonly string[]): void/** The tight bounds of a vector network, its curves included, which size a `<Vector>`. */vectorBounds(network: VectorNetwork): Rectdiff --git a/src/app/code/dom-preview.ts b/src/app/code/dom-preview.tsindex 8cf49072c..a04b16630 100644--- a/src/app/code/dom-preview.ts+++ b/src/app/code/dom-preview.ts@@ -50,7 +50,7 @@ export async function previewDOMCode(styling: ComponentStyling): Promise<{ ok: true } | { ok: false; error: string }> {try {- const graph = sceneGraphFromStyledHTML(await designDocument(source, styling), {+ const graph = await sceneGraphFromStyledHTML(await designDocument(source, styling), {pageName: 'Code preview'})const pageId = graph.getPages()[0]?.id ?? graph.rootIddiff --git a/src/app/document/io/dom.ts b/src/app/document/io/dom.tsindex ea6ec1436..a5539896b 100644--- a/src/app/document/io/dom.ts+++ b/src/app/document/io/dom.ts@@ -69,7 +69,7 @@ export function createDOMOpenActions({signal: load.signal})load.signal.throwIfAborted()- const graph = sceneGraphFromStyledHTML(styled, { pageName })+ const graph = await sceneGraphFromStyledHTML(styled, { pageName })await yieldToUI()await applyImportedDocument(editor, graph, load)// Into a reused tab too, the document opens with the panels its kind starts with.diff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.tsindex c93077a25..231f6c8c8 100644--- a/src/app/editor/fonts/index.ts+++ b/src/app/editor/fonts/index.ts@@ -5,9 +5,8 @@ import { watch } from 'vue'import {DEFAULT_WEB_FONT_PROVIDER_SETTINGS,WEB_FONT_PROVIDER_IDS,- collectGraphFontRequirements,fontManager,- missingGraphFontScripts,+ prepareGraphFonts,type FontFamilyOption,type HostFontFamily,type LocalFontAccessState,@@ -156,46 +155,27 @@ interface FontRenderInvalidator {invalidateNodesForFonts(graph: SceneGraph, nodeIds: readonly string[]): void}+/**+ * Prepares the fonts of `nodeIds` with the app's loader, keeping them off the canvas meanwhile;+ * resolves to whether that changed any face their text draws with.+ */export async function ensureGraphFonts(graph: SceneGraph,nodeIds: string[],renderer?: FontRenderInvalidator | null): Promise<boolean> {- fontManager.blockNodesUntilFontsResolve(nodeIds)try {- const generationBefore = fontManager.generation()- const fontKeys = fontManager.collectFontKeys(graph, nodeIds)- const requirements = collectGraphFontRequirements(graph, nodeIds)- const { characters } = requirements- await Promise.all(fontKeys.map(([family, style]) => loadFont(family, style, characters)))- const fallbackScripts = missingGraphFontScripts(requirements, {+ const prepared = await prepareGraphFonts(graph, nodeIds, {+ loadFont,+ hide: true,treatUnknownCoverageAsMissing: IS_TAURI})- if (fallbackScripts.length > 0) {- const fallbacks = await fontManager.ensureFallbackPack(fallbackScripts, characters)- if (Object.values(fallbacks).some((families) => families.length > 0)) {- clearTextPictures(graph, nodeIds)- }- } else if (fontManager.generation() !== generationBefore) {- clearTextPictures(graph, nodeIds)- }- return fontManager.generation() !== generationBefore || fallbackScripts.length > 0+ return prepared.changed} finally {- fontManager.unblockNodes(nodeIds)renderer?.invalidateNodesForFonts(graph, nodeIds)}}-function clearTextPictures(graph: SceneGraph, nodeIds: string[]): void {- const clear = (id: string) => {- const node = graph.getNode(id)- if (!node) return- if (node.type === 'TEXT') node.textPicture = null- for (const childId of node.childIds) clear(childId)- }- for (const id of nodeIds) clear(id)-}-type NativeFontLoadError = { code?: 'not-found' | 'unsupported-format' | 'failed' }async function loadSystemFont(family: string, style = 'Regular'): Promise<ArrayBuffer | null> {diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 9b8f368d6..a4404a24b 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -6,6 +6,7 @@ import { createDocumentGraph } from '@open-pencil/core'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { figThumbnailPageId, populateFigPage } from '@open-pencil/core/io/formats/fig'import { computeAllLayouts } from '@open-pencil/core/layout'+import { prepareGraphFonts } from '@open-pencil/core/text'import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'import { setOpenPencilStore } from '@/app/browser-bridge'@@ -22,6 +23,7 @@ import type { DocumentSourceIdentity } from '@/app/document/io/types'import { getRecoveryStore, type RecoverySnapshotMeta } from '@/app/document/recovery'import { recoverySessionId } from '@/app/document/recovery/session'import { setActiveEditorStore } from '@/app/editor/active-store'+import { loadFont } from '@/app/editor/fonts'import { appIcons } from '@/app/editor/icons/provider'import type { EditorPreparationHandle as DocumentLoadSession } from '@/app/editor/preparation/types'import { createEditorStore } from '@/app/editor/session'@@ -331,13 +333,16 @@ async function discardFailedRecovery(store: EditorStore): Promise<void> {async function readFigForTab(file: File, signal?: AbortSignal): Promise<SceneGraph> {const imported = await readFigDocument(file, signal)const firstPageId = imported.getPages()[0]?.id- const layOut = (pageId: string) =>+ // Each page is laid out once its text's fonts are prepared, never in a face it would lose.+ const layOut = async (pageId: string) => {+ await prepareGraphFonts(imported, [pageId], { loadFont, signal })imported.applyDerivedLayoutDuring(() => computeAllLayouts(imported, pageId))- if (firstPageId) layOut(firstPageId)+ }+ if (firstPageId) await layOut(firstPageId)const thumbnailPageId = figThumbnailPageId(imported.getPages())if (thumbnailPageId && thumbnailPageId !== firstPageId) {populateFigPage(imported, thumbnailPageId)- layOut(thumbnailPageId)+ await layOut(thumbnailPageId)}return imported}diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts b/tests/e2e/fonts/cjk-rendering-visual.spec.tsindex 73f3a23dd..2f4617eea 100644--- a/tests/e2e/fonts/cjk-rendering-visual.spec.ts+++ b/tests/e2e/fonts/cjk-rendering-visual.spec.ts@@ -132,8 +132,8 @@ test('international text is correct on its first visible paint', async ({ page }}).id})- fontManager.blockNodesUntilFontsResolve(sampleIds)- const blockedBeforeFonts = sampleIds.every((id) => fontManager.isNodeBlocked(id))+ fontManager.blockNodesUntilFontsResolve(store.graph, sampleIds)+ const blockedBeforeFonts = sampleIds.every((id) => fontManager.isNodeBlocked(store.graph, id))const [cjk, arabic] = await Promise.all([fetch('/tests/fixtures/fonts/NotoSansCJK-Test.otf').then((response) =>response.arrayBuffer()@@ -148,7 +148,7 @@ test('international text is correct on its first visible paint', async ({ page }fontManager.setArabicFallbackFamily('Noto Naskh Arabic')await store.loadFontsForNodes(sampleIds)- fontManager.unblockNodes(sampleIds)+ fontManager.unblockNodes(store.graph, sampleIds)for (const id of sampleIds) {const node = store.graph.getNode(id)if (node?.type === 'TEXT') store.graph.updateNode(id, { text: node.text })@@ -178,7 +178,7 @@ test('international text is correct on its first visible paint', async ({ page }state: node ? store.renderer?.nodeFontReadiness(node) : 'missing'}}),- unblockedAfterFonts: sampleIds.every((id) => !fontManager.isNodeBlocked(id))+ unblockedAfterFonts: sampleIds.every((id) => !fontManager.isNodeBlocked(store.graph, id))}})@@ -263,7 +263,7 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyconst { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {fontManager: FontManager}- fontManager.blockNodesUntilFontsResolve(nodeIds)+ fontManager.blockNodesUntilFontsResolve(store.graph, nodeIds)store.select([typed.id])store.startTextEditing(typed.id)store.requestRender()@@ -287,6 +287,8 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asy})await canvas.waitForRender()const pending = await page.evaluate(async (nodeIds) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not found')const fontModuleURL = performance.getEntriesByType('resource').map((entry) => entry.name)@@ -295,7 +297,7 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyconst { fontManager } = (await import(/* @vite-ignore */ fontModuleURL)) as {fontManager: FontManager}- return nodeIds.every((id) => fontManager.isNodeBlocked(id))+ return nodeIds.every((id) => fontManager.isNodeBlocked(store.graph, id))}, ids.nodeIds)expect(pending).toBe(true)await expectCanvas(canvas, 'interactive-font-fallback-pending')@@ -325,10 +327,11 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyfontManager.setArabicFallbackFamily('Noto Naskh Arabic')store.commitTextEdit()await store.loadFontsForNodes(nodeIds)- fontManager.unblockNodes(nodeIds)+ fontManager.unblockNodes(store.graph, nodeIds)+ // Both texts are laid out as the editor lays out an edit, measuring them in their fonts.for (const id of nodeIds) {const node = store.graph.getNode(id)- if (node?.type === 'TEXT') store.graph.updateNode(id, { text: node.text })+ if (node?.type === 'TEXT') store.updateNode(id, { text: node.text })}store.clearSelection()store.renderer.invalidateAllPictures()@@ -351,14 +354,21 @@ test('typed and tool-created text repaint with the same resolved fallbacks', asyreturn {image: Array.from(image),textsMatch: tool?.type === 'TEXT' && typed?.type === 'TEXT' && tool.text === typed.text,+ sameHeights: tool?.derivedTextHeight === typed?.derivedTextHeight,toolReady: tool ? store.renderer.isNodeFontLoaded(tool) : false,typedReady: typed ? store.renderer.isNodeFontLoaded(typed) : false,- unblocked: nodeIds.every((id) => !fontManager.isNodeBlocked(id))+ unblocked: nodeIds.every((id) => !fontManager.isNodeBlocked(store.graph, id))}}, ids)const { image, ...state } = resolved- expect(state).toEqual({ textsMatch: true, toolReady: true, typedReady: true, unblocked: true })+ expect(state).toEqual({+ textsMatch: true,+ sameHeights: true,+ toolReady: true,+ typedReady: true,+ unblocked: true+ })expect(Buffer.from(image)).toMatchSnapshot('interactive-font-fallback-resolved.png')})diff --git a/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/interactive-font-fallback-resolved-openpencil-darwin.png b/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/interactive-font-fallback-resolved-openpencil-darwin.pngindex 15cc8cf67..af3d83e30 100644Binary files a/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/interactive-font-fallback-resolved-openpencil-darwin.png and b/tests/e2e/fonts/cjk-rendering-visual.spec.ts-snapshots/interactive-font-fallback-resolved-openpencil-darwin.png differdiff --git a/tests/engine/text/fonts/lifecycle.test.ts b/tests/engine/text/fonts/lifecycle.test.tsindex 41cb51980..22835532e 100644--- a/tests/engine/text/fonts/lifecycle.test.ts+++ b/tests/engine/text/fonts/lifecycle.test.ts@@ -65,12 +65,19 @@ describe('font lifecycle', () => {test('tracks nodes gated by pre-render font resolution', () => {const manager = new FontManager()- manager.blockNodesUntilFontsResolve(['first', 'second'])- expect(manager.isNodeBlocked('first')).toBe(true)- expect(manager.isNodeBlocked('second')).toBe(true)- manager.unblockNodes(['first'])- expect(manager.isNodeBlocked('first')).toBe(false)- expect(manager.isNodeBlocked('second')).toBe(true)+ const graph = new SceneGraph()+ const other = new SceneGraph()+ manager.blockNodesUntilFontsResolve(graph, ['first', 'second'])+ manager.blockNodesUntilFontsResolve(graph, ['second'])+ expect(manager.isNodeBlocked(graph, 'first')).toBe(true)+ expect(manager.isNodeBlocked(other, 'first')).toBe(false)+ manager.unblockNodes(other, ['first'])+ manager.unblockNodes(graph, ['first', 'second'])+ expect(manager.isNodeBlocked(graph, 'first')).toBe(false)+ // Another preparation still holds it.+ expect(manager.isNodeBlocked(graph, 'second')).toBe(true)+ manager.unblockNodes(graph, ['second'])+ expect(manager.isNodeBlocked(graph, 'second')).toBe(false)})test('rejects a text picture observed before the font generation changed', () => {