AI-native design editor. Open-source Figma alternative.
feat(app): prepare documents atomically per tab (#592)
Danila Poyarkov6f5638380a26
diff --git a/knip.json b/knip.jsonindex 59a0d24c1..809f7da63 100644--- a/knip.json+++ b/knip.json@@ -9,6 +9,7 @@"ignoreUnresolved": ["~icons/*","/src/app/editor/fonts/index.ts",+ "/src/app/tabs/index.ts","#core/*"],"ignoreBinaries": ["figma-use", "identify", "magick", "open", "osascript"]diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.tsindex 0085e2a5b..2208836bb 100644--- a/packages/core/src/editor/pages.ts+++ b/packages/core/src/editor/pages.ts@@ -1,3 +1,5 @@+import { limitAsync } from 'es-toolkit/promise'+import type { Color } from '@open-pencil/scene-graph/primitives'import { populateLazyFigImportRoots } from '#core/kiwi/fig/lazy-import'@@ -13,6 +15,31 @@ import { missingGraphFontScripts } from '#core/text/resolved-requirements'import { createPageViewportStore } from './page-viewports'import type { EditorContext } from './types'+export interface PageSwitchProgress {+ phase: 'populating-page' | 'resolving-fonts' | 'resolving-fallbacks' | 'layout'+ detail?: string+ completed?: number+ total?: number+}++export interface PreparePageOptions {+ onProgress?: (progress: PageSwitchProgress) => void+ signal?: AbortSignal+}++export interface PreparedPage {+ pageId: string+ generation: number+}++export type SwitchPageOptions = PreparePageOptions++function throwIfAborted(signal?: AbortSignal): void {+ signal?.throwIfAborted()+}++const MAX_CONCURRENT_FONT_LOADS = 4+export function createPageActions(ctx: EditorContext) {const pageViewportStore = createPageViewportStore(ctx)let populationWorkerInstance: ReturnType<typeof createFigPopulationWorker> | undefined@@ -25,53 +52,79 @@ export function createPageActions(ctx: EditorContext) {return populationWorkerInstance}- async function switchPage(pageId: string) {- const page = ctx.graph.getNode(pageId)- if (page?.type !== 'CANVAS') return- const switchGeneration = ++pageSwitchGeneration-- pageViewportStore.saveCurrentPageViewport()-- const previousPageId = ctx.state.currentPageId- ctx.state.currentPageId = pageId- ctx.state.enteredContainerId = null- ctx.setSelectedIds(new Set())- if (previousPageId !== pageId) ctx.emitEditorEvent('page:changed', pageId, previousPageId)-- pageViewportStore.restorePageViewport(pageId)-- ctx.state.loading = true- let populated: boolean- try {- const worker = populationWorker()- const workerGeneration = populationWorkerGeneration- const workerResult = worker ? await worker.populate(pageId) : null- if (workerGeneration !== populationWorkerGeneration) return- if (workerResult === null) {- worker?.terminate()- populationWorkerInstance = undefined- populated = populateLazyFigImportRoots(ctx.graph, [pageId])- } else {- populated = workerResult- }- } finally {- if (switchGeneration === pageSwitchGeneration) ctx.state.loading = false+ async function populatePage(+ pageId: string,+ switchGeneration: number,+ signal?: AbortSignal+ ): Promise<boolean | null> {+ throwIfAborted(signal)+ const worker = populationWorker()+ const workerGeneration = populationWorkerGeneration+ const workerResult = worker ? await worker.populate(pageId, signal) : null+ throwIfAborted(signal)+ if (+ workerGeneration !== populationWorkerGeneration ||+ switchGeneration !== pageSwitchGeneration+ ) {+ return null}- if (switchGeneration !== pageSwitchGeneration) return+ if (workerResult !== null) return workerResult+ worker?.terminate()+ populationWorkerInstance = undefined+ return populateLazyFigImportRoots(ctx.graph, [pageId])+ }+ async function resolvePageFonts(+ pageId: string,+ pageName: string,+ 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 {- const results = await Promise.all(- toLoad.map(([family, style]) => ctx.loadFont(family, style, requirements.characters))- )+ 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+ })const fallbacks = await fontManager.ensureFallbackPack(requiredFallbacks,- requirements.characters+ 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@@ -83,16 +136,58 @@ export function createPageActions(ctx: EditorContext) {fontManager.unblockNodes(childIds)ctx.getRenderer()?.invalidateAllPictures()}+ }++ async function preparePage(+ pageId: string,+ options: PreparePageOptions = {}+ ): Promise<PreparedPage | null> {+ const page = ctx.graph.getNode(pageId)+ if (page?.type !== 'CANVAS') return null+ const generation = ++pageSwitchGeneration+ throwIfAborted(options.signal)++ options.onProgress?.({ phase: 'populating-page', detail: page.name })+ const populated = await populatePage(pageId, generation, options.signal)+ if (populated === null || generation !== pageSwitchGeneration) return null++ await resolvePageFonts(pageId, page.name, options)+ throwIfAborted(options.signal)+ if (generation !== pageSwitchGeneration) return nullif (ctx.getRenderer() || populated) {+ options.onProgress?.({ phase: 'layout', detail: page.name })computeAllLayouts(ctx.graph, pageId)}+ throwIfAborted(options.signal)+ return generation === pageSwitchGeneration ? { pageId, generation } : null+ }++ function commitPageSwitch(prepared: PreparedPage): boolean {+ if (prepared.generation !== pageSwitchGeneration) return false+ const page = ctx.graph.getNode(prepared.pageId)+ if (page?.type !== 'CANVAS') return false++ pageViewportStore.saveCurrentPageViewport()+ const previousPageId = ctx.state.currentPageId+ ctx.state.currentPageId = prepared.pageId+ ctx.state.enteredContainerId = null+ ctx.setSelectedIds(new Set())+ pageViewportStore.restorePageViewport(prepared.pageId)+ if (previousPageId !== prepared.pageId) {+ ctx.emitEditorEvent('page:changed', prepared.pageId, previousPageId)+ }ctx.requestRender()+ return true+ }++ async function switchPage(pageId: string, options: SwitchPageOptions = {}): Promise<void> {+ const prepared = await preparePage(pageId, options)+ if (prepared) commitPageSwitch(prepared)}function clearPageViewports() {populationWorkerGeneration++pageSwitchGeneration++- ctx.state.loading = falsepopulationWorkerInstance?.terminate()populationWorkerInstance = undefinedpageViewportStore.clearPageViewports()@@ -140,6 +235,8 @@ export function createPageActions(ctx: EditorContext) {}return {+ preparePage,+ commitPageSwitch,switchPage,addPage,deletePage,diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.tsindex d049f8aed..b8d13e7c8 100644--- a/packages/core/src/editor/state/shared.ts+++ b/packages/core/src/editor/state/shared.ts@@ -8,7 +8,6 @@ export function createDefaultEditorSharedState(): EditorSharedState {remoteCursors: [],documentName: 'Untitled',rulerTheme: undefined,- sceneVersion: 0,- loading: false+ sceneVersion: 0}}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 962b4097f..458487461 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -45,7 +45,6 @@ export interface EditorSharedState {documentName: stringrulerTheme?: RulerThemesceneVersion: number- loading: boolean}export interface EditorViewState {@@ -131,7 +130,12 @@ export type EditorEventName = keyof EditorEventsexport interface EditorOptions {graph?: SceneGraphstate?: EditorState- loadFont?: (family: string, style: string, characters?: string) => Promise<ArrayBuffer | null>+ loadFont?: (+ family: string,+ style: string,+ characters?: string,+ signal?: AbortSignal+ ) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages?: FigmaClipboardImageResolvergetViewportSize?: () => { width: number; height: number }skipInitialGraphSetup?: boolean@@ -142,7 +146,12 @@ export interface EditorContext {set graph(g: SceneGraph)undo: UndoManagerstate: EditorState- loadFont: (family: string, style: string, characters?: string) => Promise<ArrayBuffer | null>+ loadFont: (+ family: string,+ style: string,+ characters?: string,+ signal?: AbortSignal+ ) => Promise<ArrayBuffer | null>resolveFigmaClipboardImages: FigmaClipboardImageResolver | nullgetViewportSize: () => { width: number; height: number }getCk: () => CanvasKit | nulldiff --git a/packages/core/src/io/formats/fig/read.ts b/packages/core/src/io/formats/fig/read.tsindex 75a883552..a58079872 100644--- a/packages/core/src/io/formats/fig/read.ts+++ b/packages/core/src/io/formats/fig/read.ts@@ -12,6 +12,7 @@ import { registerFigPopulationWorker } from '#core/kiwi/fig/population/client'export interface ParseFigFileOptions {populate?: 'all' | 'first-page' | 'none'onPages?: (pages: readonly FigPageManifestEntry[]) => void+ signal?: AbortSignal}function parseFigFileSync(buffer: ArrayBuffer, options: ParseFigFileOptions = {}): SceneGraph {@@ -43,7 +44,14 @@ type WorkerParseResult = WorkerGraphResult | WorkerPageManifestResultfunction parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Promise<SceneGraph> {return new Promise((resolve, reject) => {+ options.signal?.throwIfAborted()const worker = createFigParseWorker()+ const abort = () => {+ worker.terminate()+ reject(new DOMException('Aborted', 'AbortError'))+ }+ options.signal?.addEventListener('abort', abort, { once: true })+ const cleanupAbort = () => options.signal?.removeEventListener('abort', abort)worker.onmessage = (e: MessageEvent<WorkerParseResult>) => {if (e.data.type === 'page-manifest') {@@ -51,6 +59,7 @@ function parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Promreturn}if (e.data.error || !e.data.graph) {+ cleanupAbort()worker.terminate()reject(new Error(e.data.error ?? 'Worker failed to parse .fig file'))return@@ -58,18 +67,24 @@ function parseViaWorker(buffer: ArrayBuffer, options: ParseFigFileOptions): Promtry {const graph = deserializeSceneGraph(e.data.graph)if (options.populate === 'first-page') {+ cleanupAbort()worker.onmessage = nullworker.onerror = nullregisterFigPopulationWorker(graph, worker)- } else worker.terminate()+ } else {+ cleanupAbort()+ worker.terminate()+ }resolve(graph)} catch (error) {+ cleanupAbort()worker.terminate()reject(error instanceof Error ? error : new Error(String(error)))}}worker.onerror = (err) => {+ cleanupAbort()worker.terminate()reject(new Error(err.message || 'Worker failed to parse .fig file'))}@@ -82,15 +97,18 @@ export async function parseFigFile(buffer: ArrayBuffer,options: ParseFigFileOptions = {}): Promise<SceneGraph> {+ options.signal?.throwIfAborted()if (typeof Worker !== 'undefined' && IS_BROWSER) {const copy = buffer.slice(0)try {return await parseViaWorker(buffer, options)} catch (error) {+ if (options.signal?.aborted) throw errorconsole.warn('Worker parsing failed, falling back to main thread:', error)return parseFigFileSync(copy, options)}}+ options.signal?.throwIfAborted()return parseFigFileSync(buffer, options)}@@ -98,5 +116,8 @@ export async function readFigFile(file: File,options: ParseFigFileOptions = {}): Promise<SceneGraph> {- return parseFigFile(await file.arrayBuffer(), options)+ options.signal?.throwIfAborted()+ const buffer = await file.arrayBuffer()+ options.signal?.throwIfAborted()+ return parseFigFile(buffer, options)}diff --git a/packages/core/src/kiwi/fig/population/client.ts b/packages/core/src/kiwi/fig/population/client.tsindex 459a709aa..e62afa330 100644--- a/packages/core/src/kiwi/fig/population/client.ts+++ b/packages/core/src/kiwi/fig/population/client.ts@@ -57,7 +57,7 @@ export function canUseFigPopulationWorker(graph: SceneGraph): boolean {}export interface FigPopulationWorker {- populate: (pageId: string) => Promise<boolean | null>+ populate: (pageId: string, signal?: AbortSignal) => Promise<boolean | null>terminate: () => void}@@ -71,6 +71,7 @@ function createPopulationWorkerClient(graph: SceneGraph, worker: Worker): FigPopstring,{resolve: (value: boolean | null) => void+ abort?: () => voidrevision: numberstartedAt: numbertimeout: ReturnType<typeof setTimeout>@@ -99,6 +100,7 @@ function createPopulationWorkerClient(graph: SceneGraph, worker: Worker): FigPopif (emit) emitTelemetry({ event: 'fallback', reason: 'worker-error' })for (const request of pending.values()) {clearTimeout(request.timeout)+ request.abort?.()request.resolve(null)}pending.clear()@@ -119,6 +121,7 @@ function createPopulationWorkerClient(graph: SceneGraph, worker: Worker): FigPopconst request = pending.get(result.requestId)if (!request) returnclearTimeout(request.timeout)+ request.abort?.()pending.delete(result.requestId)if (stale || revision !== request.revision || result.baseRevision !== request.revision) {emitTelemetry({ event: 'stale', reason: 'graph-mutation' })@@ -149,14 +152,25 @@ function createPopulationWorkerClient(graph: SceneGraph, worker: Worker): FigPop}worker.onerror = () => fail()return {- populate(pageId) {+ populate(pageId, signal) {+ signal?.throwIfAborted()if (stale) return Promise.resolve(null)const requestId = randomHex()const baseRevision = revision- return new Promise((resolve) => {+ return new Promise((resolve, reject) => {+ const abort = () => {+ const request = pending.get(requestId)+ if (!request) return+ clearTimeout(request.timeout)+ pending.delete(requestId)+ fail(false)+ reject(new DOMException('Aborted', 'AbortError'))+ }+ signal?.addEventListener('abort', abort, { once: true })const timeout = setTimeout(() => fail(), FIG_POPULATION_WORKER_TIMEOUT_MS)pending.set(requestId, {resolve,+ abort: () => signal?.removeEventListener('abort', abort),revision: baseRevision,startedAt: performance.now(),timeoutdiff --git a/packages/core/src/text/fonts.ts b/packages/core/src/text/fonts.tsindex d3c551d5a..5f33c73bf 100644--- a/packages/core/src/text/fonts.ts+++ b/packages/core/src/text/fonts.ts@@ -249,8 +249,10 @@ export class FontManager {async loadRemoteFont(family: string,style = 'Regular',- characters = ''+ characters = '',+ signal?: AbortSignal): Promise<ArrayBuffer | null> {+ signal?.throwIfAborted()if (typeof fetch === 'undefined') return nullconst coverage = this.remoteCoverage.get(`${family}|${style}`)if (@@ -266,7 +268,7 @@ export class FontManager {)const normalized = normalizeFontFamily(family)const families = normalized === family ? [family] : [family, normalized]- const resolved = await this.webFonts.fetchFont(families, style, requestedCharacters)+ const resolved = await this.webFonts.fetchFont(families, style, requestedCharacters, signal)if (!resolved || resolved.buffers.length === 0) return nullconst primary = resolved.buffers[0]await this.writeDownloadedFont(family, style, primary, requestedCharacters)@@ -279,12 +281,19 @@ export class FontManager {}return registered} catch (e) {+ if (signal?.aborted) throw econsole.warn(`Web font fetch failed for "${family}" ${style}:`, e)return null}}- async loadFont(family: string, style = 'Regular', characters = ''): Promise<ArrayBuffer | null> {+ async loadFont(+ family: string,+ style = 'Regular',+ characters = '',+ signal?: AbortSignal+ ): Promise<ArrayBuffer | null> {+ signal?.throwIfAborted()const loaded = this.loadedData(family, style)if (loaded) {this.registerFontInCanvasKit(family, loaded)@@ -295,14 +304,14 @@ export class FontManager {Array.from(characters).some((character) => !remoteCoverage.has(character)))return missingRemoteCoverage- ? ((await this.loadRemoteFont(family, style, characters)) ?? loaded)+ ? ((await this.loadRemoteFont(family, style, characters, signal)) ?? loaded): loaded}return ((await this.loadLocalFont(family, style)) ??(await this.loadCachedFont(family, style, characters)) ??- (await this.loadRemoteFont(family, style, characters))+ (await this.loadRemoteFont(family, style, characters, signal)))}@@ -381,20 +390,33 @@ export class FontManager {async ensureFallbackPack(scripts: FontFallbackScript[] = ['cjk', 'arabic'],- characters = ''+ characters = '',+ signal?: AbortSignal): Promise<Partial<Record<FontFallbackScript, string[]>>> {+ signal?.throwIfAborted()const result: Partial<Record<FontFallbackScript, string[]>> = {}await Promise.all(scripts.map(async (script) => {- if (script === 'arabic' && !characters) result[script] = await this.ensureArabicFallback()- else if (script === 'cjk' && !characters) result[script] = await this.ensureCJKFallback()- else {- const target =- script === 'arabic' ? this.arabicFallbackFamilies : this.cjkFallbackFamilies+ signal?.throwIfAborted()+ const target = script === 'arabic' ? this.arabicFallbackFamilies : this.cjkFallbackFamilies+ if (signal) {+ result[script] = await this.ensureFallbackFamilies(+ script,+ target,+ { allowVariableLocalFonts: script === 'cjk' },+ characters,+ signal+ )+ } else if (script === 'arabic' && !characters) {+ result[script] = await this.ensureArabicFallback()+ } else if (script === 'cjk' && !characters) {+ result[script] = await this.ensureCJKFallback()+ } else {result[script] = await this.ensureFallbackFamilies(script, target, {}, characters)}}))+ signal?.throwIfAborted()return result}@@ -412,11 +434,14 @@ export class FontManager {script: FontFallbackScript,targetFamilies: string[],options: { allowVariableLocalFonts?: boolean } = {},- characters = ''+ characters = '',+ signal?: AbortSignal): Promise<string[]> {+ signal?.throwIfAborted()const manifest = fontFallbackEntry(script, this.fallbackUserAgent)for (const family of manifest.localFamilies) {+ signal?.throwIfAborted()const buffer =(await this.loadHostFont(family, 'Regular')) ??(await this.findLocalFont(family, undefined, {@@ -434,7 +459,9 @@ export class FontManager {if (targetFamilies.length === 0 || characters) {const results = await Promise.allSettled(manifest.remoteFamilies.map(async (family) => {- const data = await this.loadRemoteFont(family, 'Regular', characters)+ signal?.throwIfAborted()+ const data = await this.loadRemoteFont(family, 'Regular', characters, signal)+ signal?.throwIfAborted()return data ? family : null}))diff --git a/packages/core/src/text/web-fonts.ts b/packages/core/src/text/web-fonts.tsindex 1f243a284..4d946e887 100644--- a/packages/core/src/text/web-fonts.ts+++ b/packages/core/src/text/web-fonts.ts@@ -143,14 +143,17 @@ export class WebFontResolver {async fetchFont(families: string[],style: string,- characters = ''+ characters = '',+ signal?: AbortSignal): Promise<ResolvedWebFont | null> {+ signal?.throwIfAborted()const providers = this.enabledProviders()if (providers.length === 0 || (IS_BROWSER && !this.remoteFetch)) return nullfor (const family of families) {for (const provider of providers) {- const buffers = await this.fetchFromProvider(family, style, provider, characters)+ signal?.throwIfAborted()+ const buffers = await this.fetchFromProvider(family, style, provider, characters, signal)if (buffers.length > 0) return { buffers, provider }}}@@ -222,31 +225,43 @@ export class WebFontResolver {family: string,style: string,provider: WebFontProviderId,- characters: string+ characters: string,+ signal?: AbortSignal): Promise<ArrayBuffer[]> {const coverage = normalizedCoverageText(characters)const key = `${provider}|${family}|${style}|${coverage}`if (this.failedFonts.has(key)) return []+ if (signal) {+ const result = await this.loadFromProvider(family, style, provider, coverage, signal)+ if (result.length === 0 && !signal.aborted) this.failedFonts.add(key)+ return result+ }+let promise = this.fontPromises.get(key)if (!promise) {- promise = this.loadFromProvider(family, style, provider, coverage)+ promise = this.loadFromProvider(family, style, provider, coverage, signal)this.fontPromises.set(key, promise)}- const result = await promise- this.fontPromises.delete(key)- if (result.length === 0) this.failedFonts.add(key)- return result+ try {+ const result = await promise+ if (result.length === 0) this.failedFonts.add(key)+ return result+ } finally {+ this.fontPromises.delete(key)+ }}private async loadFromProvider(family: string,style: string,provider: WebFontProviderId,- characters: string+ characters: string,+ signal?: AbortSignal): Promise<ArrayBuffer[]> {try {+ signal?.throwIfAborted()const parsed = parseFontStyle(style)const unifont = await this.unifont(provider)const options = {@@ -264,12 +279,13 @@ export class WebFontResolver {const faces = resolvedRemoteFaces(result)const buffers = await Promise.all(faces.map(async ({ source, init }) => {- const response = await this.fetchRemote(source.url, init)+ const response = await this.fetchRemote(source.url, { ...init, signal })return response.ok ? response.arrayBuffer() : null}))return buffers.filter(isArrayBuffer)- } catch {+ } catch (error) {+ if (signal?.aborted) throw errorreturn []}}diff --git a/packages/dom-css/src/browser.ts b/packages/dom-css/src/browser.tsindex 90d31f5f4..f35f73441 100644--- a/packages/dom-css/src/browser.ts+++ b/packages/dom-css/src/browser.ts@@ -13,6 +13,7 @@ export type { JSXChild, JSXElementProps, JSXStyleInput, JSXTag } from './jsx/corexport interface BrowserToDesignDocumentOptions extends BrowserCSSRuntimeOptions {cssText?: stringcompute?: CSSComputeOptions+ signal?: AbortSignal}export type BrowserHTMLToDesignDocumentOptions = BrowserToDesignDocumentOptions@@ -69,6 +70,7 @@ export async function browserHTMLToDesignDocument(html: string,options: BrowserHTMLToDesignDocumentOptions = {}): Promise<DesignDocument> {+ options.signal?.throwIfAborted()const browserDocument = resolveBrowserDocument(options.document)const runtime = createRuntime({ ...options, document: browserDocument })const document = runtime.parseHTML(html)@@ -81,7 +83,10 @@ export async function browserHTMLToSceneGraph(options: BrowserHTMLToSceneGraphOptions = {}): Promise<SceneGraph> {const document = await browserHTMLToDesignDocument(html, options)- return designDocumentToSceneGraph(document, options)+ options.signal?.throwIfAborted()+ const graph = designDocumentToSceneGraph(document, options)+ options.signal?.throwIfAborted()+ return graph}export async function browserTailwindHTMLToDesignDocument(@@ -99,7 +104,10 @@ export async function browserTailwindHTMLToSceneGraph(options: BrowserTailwindHTMLToSceneGraphOptions = {}): Promise<SceneGraph> {const document = await browserTailwindHTMLToDesignDocument(html, candidates, options)- return designDocumentToSceneGraph(document, options)+ options.signal?.throwIfAborted()+ const graph = designDocumentToSceneGraph(document, options)+ options.signal?.throwIfAborted()+ return graph}export async function browserJSXToDesignDocument(diff --git a/packages/dom-css/tests/conversion.test.ts b/packages/dom-css/tests/conversion.test.tsindex f4c3b3bb7..997494054 100644--- a/packages/dom-css/tests/conversion.test.ts+++ b/packages/dom-css/tests/conversion.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'bun:test'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { browserHTMLToSceneGraph } from '../src/browser'import type { DesignElement, DesignNode } from '../src/index'import {createHeadlessCSSRuntime,@@ -157,6 +158,15 @@ function expectStyleRoundTripHTML(graph: SceneGraph) {}describe('@open-pencil/dom-css conversion', () => {+ it('rejects pre-aborted browser conversion before runtime work', async () => {+ const abort = new AbortController()+ abort.abort()++ await expect(+ browserHTMLToSceneGraph('<main>Cancelled</main>', { signal: abort.signal })+ ).rejects.toHaveProperty('name', 'AbortError')+ })+it('converts HTML and CSS to DesignDOM with one API call', async () => {const document = await htmlToDesignDocument(cardHTML, {cssText: cardCSS,diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.tsindex c27b3232c..101f06c4f 100644--- a/packages/vue/src/canvas/surface/lifecycle.ts+++ b/packages/vue/src/canvas/surface/lifecycle.ts@@ -79,6 +79,14 @@ export function createCanvasSurfaceManager({}}+ function acknowledgePresentation() {+ const renderedState = options?.getRenderState?.() ?? editor.state+ options?.onPresented?.({+ renderVersion: renderedState.renderVersion,+ sceneVersion: renderedState.sceneVersion+ })+ }+function renderNow() {if (!state.renderer || isDestroyed()) returnstate.renderer.renderFromEditorState(@@ -91,6 +99,7 @@ export function createCanvasSurfaceManager({options?.layer ?? 'full')renderLoop.markRendered()+ acknowledgePresentation()clearSceneBackingRenderTimer()if (options?.layer === 'scene' && state.renderer.sceneBackingNeedsCrispRender) {const delay = Math.max(0, state.renderer.sceneBackingPreviewUntil - performance.now())@@ -100,7 +109,8 @@ export function createCanvasSurfaceManager({const renderLoop = createCanvasRenderLoop(editor, renderNow, {layer: options?.layer,- getRenderState: options?.getRenderState+ getRenderState: options?.getRenderState,+ shouldSuspendRender: options?.shouldSuspendRender})function resizeCanvas(canvas: HTMLCanvasElement) {diff --git a/packages/vue/src/canvas/surface/render-loop.ts b/packages/vue/src/canvas/surface/render-loop.tsindex 457d85bed..cb23ea6ec 100644--- a/packages/vue/src/canvas/surface/render-loop.ts+++ b/packages/vue/src/canvas/surface/render-loop.ts@@ -5,6 +5,7 @@ import type { CanvasRenderLayer } from './types'type RenderLoopOptions = {layer?: CanvasRenderLayergetRenderState?: () => EditorState+ shouldSuspendRender?: () => boolean}type EditorRenderScheduler = {@@ -67,7 +68,7 @@ export function createCanvasRenderLoop(function renderFrame() {frameScheduled = falseconst state = getRenderState()- if (state.loading) {+ if (options.shouldSuspendRender?.() === true) {dirty = truescheduleFrame()returndiff --git a/packages/vue/src/canvas/surface/types.ts b/packages/vue/src/canvas/surface/types.tsindex 8577543f0..cd4d00f7b 100644--- a/packages/vue/src/canvas/surface/types.ts+++ b/packages/vue/src/canvas/surface/types.ts@@ -6,6 +6,8 @@ import type { EditorState } from '@open-pencil/core/editor'export type CanvasRenderLayer = 'full' | 'scene' | 'overlays'export interface UseCanvasOptions {+ shouldSuspendRender?: () => boolean+ onPresented?: (versions: { renderVersion: number; sceneVersion: number }) => void/*** Selects which render layer this canvas owns.*/diff --git a/src/app/diagnostics/events/index.ts b/src/app/diagnostics/events/index.tsindex a071987f6..3f7d87ea7 100644--- a/src/app/diagnostics/events/index.ts+++ b/src/app/diagnostics/events/index.ts@@ -1,5 +1,6 @@export { recordChatCompleted, recordChatFailed, recordModelStepCompleted } from './ai'export { recordDocumentFailure } from './document'+export { preparationDurationBucket, recordPreparationOutcome } from './preparation'export { recordStorageFailure } from './storage'export { recordACPTransportFailure, recordMCPConnectionFailure } from './transport'export { storageOperationForJob } from './storage-operation'diff --git a/src/app/diagnostics/events/preparation.ts b/src/app/diagnostics/events/preparation.tsnew file mode 100644index 000000000..7e5168e53--- /dev/null+++ b/src/app/diagnostics/events/preparation.ts@@ -0,0 +1,72 @@+import * as v from 'valibot'++import type {+ EditorPreparationCancelReason,+ EditorPreparationFailure,+ EditorPreparationKind,+ EditorPreparationPhase+} from '@/app/editor/preparation/types'++import { recordDiagnostic } from '../recorder'+import type { DiagnosticEvent } from '../types'++const durationBuckets = ['under-100ms', '100ms-1s', '1s-5s', '5s-30s', 'over-30s'] as const++const preparationSchema = v.object({+ kind: v.picklist([+ 'document-open',+ 'document-reload',+ 'recovery-restore',+ 'storage-open',+ 'page-switch',+ 'font-retry',+ 'dom-import'+ ]),+ outcome: v.picklist(['completed', 'cancelled', 'failed']),+ cancellationReason: v.nullable(v.picklist(['superseded', 'tab-closed', 'user'])),+ failureCode: v.nullable(+ v.picklist(['read-failed', 'decode-failed', 'font-failed', 'layout-failed', 'render-failed'])+ ),+ terminalPhase: v.picklist([+ 'reading',+ 'decoding',+ 'materializing',+ 'populating-page',+ 'resolving-fonts',+ 'resolving-fallbacks',+ 'layout',+ 'preparing-render'+ ]),+ durationBucket: v.picklist(durationBuckets)+})++export interface PreparationDiagnosticInput {+ kind: EditorPreparationKind+ outcome: 'completed' | 'cancelled' | 'failed'+ cancellationReason: EditorPreparationCancelReason | null+ failureCode: EditorPreparationFailure['code'] | null+ terminalPhase: EditorPreparationPhase+ durationMs: number+}++export function preparationDurationBucket(durationMs: number): (typeof durationBuckets)[number] {+ if (durationMs < 100) return 'under-100ms'+ if (durationMs < 1_000) return '100ms-1s'+ if (durationMs < 5_000) return '1s-5s'+ if (durationMs < 30_000) return '5s-30s'+ return 'over-30s'+}++export function recordPreparationOutcome(input: PreparationDiagnosticInput): void {+ const parsed = v.safeParse(preparationSchema, {+ ...input,+ durationBucket: preparationDurationBucket(input.durationMs)+ })+ if (!parsed.success) return+ recordDiagnostic({+ category: 'document',+ level: input.outcome === 'failed' ? 'error' : 'info',+ name: 'editor.preparation.finished',+ attributes: parsed.output+ } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+}diff --git a/src/app/diagnostics/index.ts b/src/app/diagnostics/index.tsindex cda666825..3ec3c7a23 100644--- a/src/app/diagnostics/index.ts+++ b/src/app/diagnostics/index.ts@@ -5,6 +5,8 @@ export {recordDocumentFailure,recordMCPConnectionFailure,recordModelStepCompleted,+ preparationDurationBucket,+ recordPreparationOutcome,recordStorageFailure,storageOperationForJob} from './events'diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsindex 4b28a9d4d..fad2baf70 100644--- a/src/app/document/io/create.ts+++ b/src/app/document/io/create.ts@@ -7,17 +7,18 @@ import { createOpenActions, createReloadActions } from '@/app/document/io/read'import { createDocumentSourceActions, createDocumentSourceState } from '@/app/document/io/source'import type { ViewportSize } from '@/app/document/io/types'import { createFileWatcher } from '@/app/document/io/watch'+import type { EditorPreparationController } from '@/app/editor/preparation/controller'type DocumentIOState = EditorState & {documentName: string- loading: booleanautosaveEnabled: boolean}export function createDocumentIOActions(editor: Editor,state: DocumentIOState,- viewportSize: ViewportSize+ viewportSize: ViewportSize,+ preparationController: EditorPreparationController) {const sourceState = createDocumentSourceState()@@ -28,7 +29,8 @@ export function createDocumentIOActions(state,getFilePath: sourceState.getFilePath,getFileHandle: sourceState.getFileHandle,- setSavedVersion: sourceState.setSavedVersion+ setSavedVersion: sourceState.setSavedVersion,+ preparationController})const { startWatchingFile, stopWatchingFile } = createFileWatcher({getFilePath: sourceState.getFilePath,@@ -54,13 +56,15 @@ export function createDocumentIOActions(editor,state,setDocumentSource: sourceActions.setDocumentSource,- fitCurrentPageToViewport+ fitCurrentPageToViewport,+ preparationController})const { openDOMFile, importDOMText } = createDOMOpenActions({editor,state,setDocumentSource: sourceActions.setDocumentSource,- fitCurrentPageToViewport+ fitCurrentPageToViewport,+ preparationController})return {diff --git a/src/app/document/io/dom.ts b/src/app/document/io/dom.tsindex 9786c5342..07aa67602 100644--- a/src/app/document/io/dom.ts+++ b/src/app/document/io/dom.ts@@ -4,12 +4,13 @@ import { browserHTMLToSceneGraph } from '@open-pencil/dom-css/browser'import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'import { yieldToUI } from '@/app/document/io/browser'import { applyImportedDocument } from '@/app/document/io/imported-document'+import type { EditorPreparationController } from '@/app/editor/preparation/controller'+import type { EditorPreparationHandle } from '@/app/editor/preparation/types'import { notificationMessages } from '@/app/i18n/notifications'import { toast } from '@/app/shell/ui'type OpenDOMDocumentState = EditorState & {documentName: string- loading: boolean}type OpenDOMFileOptions = {@@ -22,12 +23,14 @@ type OpenDOMFileOptions = {path?: string) => voidfitCurrentPageToViewport: () => Promise<void>+ preparationController: EditorPreparationController}type DOMImportOptions = {cssText?: stringhandle?: FileSystemFileHandlepath?: string+ preparation?: EditorPreparationHandle}type DOMTextImportOptions = {@@ -47,14 +50,25 @@ export function createDOMOpenActions({editor,state,setDocumentSource,- fitCurrentPageToViewport+ fitCurrentPageToViewport,+ preparationController}: OpenDOMFileOptions) {- async function applyDOMText(html: string, options: DOMTextImportOptions) {+ async function applyDOMText(+ html: string,+ options: DOMTextImportOptions,+ load: ReturnType<EditorPreparationController['begin']>+ ) {await yieldToUI()const pageName = options.documentName ?? 'DOM Import'- const graph = await browserHTMLToSceneGraph(html, { cssText: options.cssText, pageName })+ load.update({ phase: 'decoding', detail: pageName })+ const graph = await browserHTMLToSceneGraph(html, {+ cssText: options.cssText,+ pageName,+ signal: load.signal+ })+ load.signal.throwIfAborted()await yieldToUI()- await applyImportedDocument(editor, graph)+ await applyImportedDocument(editor, graph, load)state.documentName = pageNameawait fitCurrentPageToViewport()editor.requestRender()@@ -62,44 +76,73 @@ export function createDOMOpenActions({}async function importDOMText(html: string, options: DOMTextImportOptions = {}) {+ const load = preparationController.begin({+ kind: 'dom-import',+ subject: options.documentName ?? 'DOM Import'+ })+ let succeeded = falsetry {- state.loading = true- const pageName = await applyDOMText(html, options)+ const pageName = await applyDOMText(html, options, load)setDocumentSource(`${pageName}.html`, 'html')toast.info(notificationMessages.get().importedDOMCSS)+ succeeded = true} catch (e) {+ if (load.signal.aborted) throw e+ const diagnostic = describeDiagnosticError(e)+ load.fail({+ code: 'decode-failed',+ message: errorDetail(e),+ retryable: diagnostic.retryable ?? true+ })recordDocumentFailure({operation: 'import',format: 'dom-css',- ...describeDiagnosticError(e),- retryable: describeDiagnosticError(e).retryable+ ...diagnostic,+ retryable: diagnostic.retryable})+ console.error('Failed to import DOM/CSS:', e)toast.error(notificationMessages.get().importDOMCSSFailed({ error: errorDetail(e) }))throw e} finally {- state.loading = false+ if (succeeded) load.complete()}}async function openDOMFile(file: File, options: DOMImportOptions = {}) {+ const load =+ options.preparation ?? preparationController.begin({ kind: 'dom-import', subject: file.name })+ const ownsLoad = options.preparation === undefined+ let succeeded = falsetry {- state.loading = trueconst html = await file.text()- await applyDOMText(html, {- cssText: options.cssText,- documentName: documentNameFor(file)- })+ await applyDOMText(+ html,+ {+ cssText: options.cssText,+ documentName: documentNameFor(file)+ },+ load+ )setDocumentSource(file.name, 'html', options.handle, options.path)+ succeeded = true} catch (e) {+ if (load.signal.aborted || !ownsLoad) throw e+ const diagnostic = describeDiagnosticError(e)+ load.fail({+ code: 'decode-failed',+ message: errorDetail(e),+ retryable: diagnostic.retryable ?? true+ })recordDocumentFailure({operation: 'open',format: 'dom-css',- ...describeDiagnosticError(e),- retryable: describeDiagnosticError(e).retryable+ ...diagnostic,+ retryable: diagnostic.retryable})+ console.error('Failed to open DOM/CSS file:', e)toast.error(notificationMessages.get().openDOMCSSFailed({ error: errorDetail(e) }))} finally {- state.loading = false+ if (ownsLoad && succeeded) load.complete()}}diff --git a/src/app/document/io/fig.ts b/src/app/document/io/fig.tsindex 79e5a59a2..88ff5c5a0 100644--- a/src/app/document/io/fig.ts+++ b/src/app/document/io/fig.ts@@ -1,29 +1,8 @@-import type { Editor } from '@open-pencil/core/editor'import { readFigFile } from '@open-pencil/core/io/formats/fig'-import type { FigPageManifestEntry } from '@open-pencil/kiwi/fig'-import { SceneGraph } from '@open-pencil/scene-graph'-/** Show lightweight page shells while the FIG worker continues decoding the full document. */-function showFigPageManifest(editor: Editor, pages: readonly FigPageManifestEntry[]): void {- if (pages.length === 0) return-- const graph = new SceneGraph()- for (const page of graph.getPages(true)) graph.deleteNode(page.id)- for (const entry of pages) {- const page = graph.addPage(entry.name)- page.internalOnly = entry.internalOnly- page.source.format = 'fig'- page.source.id = entry.sourceId- page.source.orderKey = entry.position- }-- editor.replaceGraph(graph)- editor.state.loading = true-}--export function readFigDocument(file: File, editor: Editor) {+export function readFigDocument(file: File, signal?: AbortSignal) {return readFigFile(file, {populate: 'first-page',- onPages: (pages) => showFigPageManifest(editor, pages)+ signal})}diff --git a/src/app/document/io/imported-document.ts b/src/app/document/io/imported-document.tsindex 09f734963..39472b046 100644--- a/src/app/document/io/imported-document.ts+++ b/src/app/document/io/imported-document.ts@@ -1,13 +1,34 @@-import type { Editor } from '@open-pencil/core/editor'-import { computeAllLayouts } from '@open-pencil/core/layout'+import { createEditor, type Editor } from '@open-pencil/core/editor'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-export async function applyImportedDocument(editor: Editor, imported: SceneGraph) {+import { loadFont } from '@/app/editor/fonts'+import type { EditorPreparationHandle as DocumentLoadSession } from '@/app/editor/preparation/types'++export async function applyImportedDocument(+ editor: Editor,+ imported: SceneGraph,+ load?: DocumentLoadSession+) {const firstPage = imported.getPages()[0] as SceneNode | undefined- if (firstPage) computeAllLayouts(imported, firstPage.id)- editor.replaceGraph(imported)- editor.undo.clear()- editor.clearSelection()- const pageId = firstPage?.id ?? editor.graph.rootId- await editor.switchPage(pageId)+ const pageId = firstPage?.id ?? imported.rootId+ const stagingEditor = createEditor({+ graph: imported,+ loadFont,+ skipInitialGraphSetup: true+ })+ try {+ load?.update({ phase: 'populating-page', detail: firstPage?.name ?? null })+ const prepared = await stagingEditor.preparePage(pageId, {+ signal: load?.signal,+ onProgress: (progress) => load?.update(progress)+ })+ load?.signal.throwIfAborted()+ if (!prepared) throw new Error('Imported page preparation was superseded')++ editor.replaceGraph(imported)+ editor.undo.clear()+ editor.clearSelection()+ } finally {+ stagingEditor.dispose()+ }}diff --git a/src/app/document/io/read.ts b/src/app/document/io/read.tsindex 87e7bb5ad..d7b3a8458 100644--- a/src/app/document/io/read.ts+++ b/src/app/document/io/read.ts@@ -1,5 +1,4 @@import type { Editor, EditorState } from '@open-pencil/core/editor'-import { computeAllLayouts } from '@open-pencil/core/layout'import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'import { yieldToUI } from '@/app/document/io/browser'@@ -7,12 +6,12 @@ import { readFigDocument } from '@/app/document/io/fig'import { applyImportedDocument } from '@/app/document/io/imported-document'import { readReloadSource } from '@/app/document/io/reload-source'import { captureReloadState, restoreReloadState } from '@/app/document/io/reload-state'+import type { EditorPreparationController } from '@/app/editor/preparation/controller'import { notificationMessages } from '@/app/i18n/notifications'import { toast } from '@/app/shell/ui'type OpenDocumentState = EditorState & {documentName: string- loading: boolean}type ReloadDocumentState = EditorState & { documentName: string }@@ -27,6 +26,7 @@ type OpenFigFileOptions = {path?: string) => voidfitCurrentPageToViewport: () => Promise<void>+ preparationController: EditorPreparationController}type ReloadActionsOptions = {@@ -35,32 +35,48 @@ type ReloadActionsOptions = {getFilePath: () => string | nullgetFileHandle: () => FileSystemFileHandle | nullsetSavedVersion: (version: number) => void+ preparationController: EditorPreparationController}export function createOpenActions({editor,state,setDocumentSource,- fitCurrentPageToViewport+ fitCurrentPageToViewport,+ preparationController}: OpenFigFileOptions) {async function openFigFile(file: File, handle?: FileSystemFileHandle, path?: string) {+ const load = preparationController.begin({ kind: 'document-open', subject: file.name })+ let succeeded = falsetry {- state.loading = true+ load.update({ phase: 'reading', detail: file.name })await yieldToUI()- const imported = await readFigDocument(file, editor)+ load.update({ phase: 'decoding', detail: file.name })+ const imported = await readFigDocument(file, load.signal)await yieldToUI()- await applyImportedDocument(editor, imported)+ load.update({ phase: 'materializing', detail: file.name })+ await applyImportedDocument(editor, imported, load)state.documentName = file.name.replace(/\.fig$/i, '')setDocumentSource(file.name, 'fig', handle, path)await fitCurrentPageToViewport()+ load.update({ phase: 'preparing-render', detail: state.documentName })editor.requestRender()+ succeeded = true} catch (e) {+ if (load.signal.aborted) return+ const diagnostic = describeDiagnosticError(e)+ load.fail({+ code: 'decode-failed',+ message: e instanceof Error ? e.message : String(e),+ retryable: diagnostic.retryable ?? true+ })recordDocumentFailure({operation: 'open',format: 'fig',- ...describeDiagnosticError(e),- retryable: describeDiagnosticError(e).retryable+ ...diagnostic,+ retryable: diagnostic.retryable})+ console.error('Failed to open .fig file:', e)toast.error(notificationMessages.get().openFileFailed({name: file.name,@@ -68,7 +84,7 @@ export function createOpenActions({}))} finally {- state.loading = false+ if (succeeded) load.complete()}}@@ -80,27 +96,56 @@ export function createReloadActions({state,getFilePath,getFileHandle,- setSavedVersion+ setSavedVersion,+ preparationController}: ReloadActionsOptions) {async function reloadFromDisk() {- const snapshot = captureReloadState(state)- const filePath = getFilePath()- const fileHandle = getFileHandle()-- const imported = await readReloadSource({- documentName: state.documentName,- filePath,- fileHandle+ const load = preparationController.begin({+ kind: 'document-reload',+ subject: state.documentName})- if (!imported) return- const pageId = imported.getNode(snapshot.pageId) ? snapshot.pageId : imported.getPages()[0]?.id- if (pageId) computeAllLayouts(imported, pageId)- editor.replaceGraph(imported)-- editor.undo.clear()- restoreReloadState(editor, state, snapshot)- editor.requestRender()- setSavedVersion(state.sceneVersion)+ let succeeded = false+ try {+ const snapshot = captureReloadState(state)+ load.update({ phase: 'reading', detail: state.documentName })+ const imported = await readReloadSource({+ documentName: state.documentName,+ filePath: getFilePath(),+ fileHandle: getFileHandle(),+ signal: load.signal+ })+ if (!imported) {+ succeeded = true+ return+ }+ await applyImportedDocument(editor, imported, load)+ restoreReloadState(editor, state, snapshot)+ editor.requestRender()+ setSavedVersion(state.sceneVersion)+ succeeded = true+ } catch (error) {+ if (load.signal.aborted) return+ const diagnostic = describeDiagnosticError(error)+ load.fail({+ code: 'decode-failed',+ message: error instanceof Error ? error.message : String(error),+ retryable: diagnostic.retryable ?? true+ })+ recordDocumentFailure({+ operation: 'open',+ format: 'fig',+ ...diagnostic,+ retryable: diagnostic.retryable+ })+ toast.error(+ notificationMessages.get().openFileFailed({+ name: state.documentName,+ error: error instanceof Error ? error.message : String(error)+ })+ )+ } finally {+ if (succeeded) load.complete()+ }}return { reloadFromDisk }diff --git a/src/app/document/io/reload-source.ts b/src/app/document/io/reload-source.tsindex 0191d0438..f79f2d9d9 100644--- a/src/app/document/io/reload-source.ts+++ b/src/app/document/io/reload-source.ts@@ -6,24 +6,29 @@ export type ReloadSourceOptions = {documentName: stringfilePath: string | nullfileHandle: FileSystemFileHandle | null+ signal?: AbortSignal}export async function readReloadSource({documentName,filePath,- fileHandle+ fileHandle,+ signal}: ReloadSourceOptions) {+ signal?.throwIfAborted()if (filePath && isTauri()) {const { readFile: tauriRead } = await import('@tauri-apps/plugin-fs')const bytes = await tauriRead(filePath)+ signal?.throwIfAborted()const blob = new Blob([bytes])const file = new File([blob], `${documentName}.fig`)- return readFigFile(file, { populate: 'first-page' })+ return readFigFile(file, { populate: 'first-page', signal })}if (fileHandle) {const file = await fileHandle.getFile()- return readFigFile(file, { populate: 'first-page' })+ signal?.throwIfAborted()+ return readFigFile(file, { populate: 'first-page', signal })}return nulldiff --git a/src/app/editor/fonts/index.ts b/src/app/editor/fonts/index.tsindex 1fc3371b9..1266dbab3 100644--- a/src/app/editor/fonts/index.ts+++ b/src/app/editor/fonts/index.ts@@ -221,10 +221,11 @@ async function loadSystemFont(family: string, style = 'Regular'): Promise<ArrayBexport async function loadFont(family: string,style = 'Regular',- characters = ''+ characters = '',+ signal?: AbortSignal): Promise<ArrayBuffer | null> {configureTauriFontCache()- const loaded = await fontManager.loadFont(family, style, characters)+ const loaded = await fontManager.loadFont(family, style, characters, signal)if (!loaded) showWebFontUnavailableToast()return loaded}diff --git a/src/app/editor/fonts/status.ts b/src/app/editor/fonts/status.tsindex a4ca3345c..b50501db3 100644--- a/src/app/editor/fonts/status.ts+++ b/src/app/editor/fonts/status.ts@@ -1,12 +1,14 @@import { computed, ref } from 'vue'+import { computeAllLayouts } from '@open-pencil/core/layout'import { documentFontStatus, fontManager, fontResolver } from '@open-pencil/core/text'-import { useEditor, useEditorEvent } from '@open-pencil/vue'+import { useEditorEvent } from '@open-pencil/vue'+import { useEditorStore } from '@/app/editor/active-store'import { loadFont, requestLocalFontAccess } from '@/app/editor/fonts'export function useDocumentFontStatus() {- const editor = useEditor()+ const editor = useEditorStore()const revision = ref(0)const retrying = ref(false)@@ -29,6 +31,8 @@ export function useDocumentFontStatus() {async function retry() {if (retrying.value) returnretrying.value = true+ const preparation = editor.preparationController.begin({ kind: 'font-retry' })+ let succeeded = falsetry {if (fontManager.localAccessState() === 'prompt') {await requestLocalFontAccess().catch(() => [])@@ -39,12 +43,31 @@ export function useDocumentFontStatus() {fontResolver.reset(`face:${family.trim().toLocaleLowerCase()}:${style.toLocaleLowerCase()}`)- await loadFont(family, style)+ await loadFont(family, style, '', preparation.signal)}))+ editor.renderer?.invalidateAllPictures()+ computeAllLayouts(editor.graph, editor.state.currentPageId)+ preparation.update({ phase: 'preparing-render' })editor.requestRender()+ if (editor.renderer) {+ await editor.preparationController.waitForPresentation(+ preparation.id,+ editor.state.sceneVersion+ )+ }refresh()+ succeeded = true+ } catch (error) {+ if (!preparation.signal.aborted) {+ preparation.fail({+ code: 'font-failed',+ message: error instanceof Error ? error.message : String(error),+ retryable: true+ })+ }} finally {+ if (succeeded) preparation.complete()retrying.value = false}}diff --git a/src/app/editor/preparation/controller.ts b/src/app/editor/preparation/controller.tsnew file mode 100644index 000000000..337b1683d--- /dev/null+++ b/src/app/editor/preparation/controller.ts@@ -0,0 +1,148 @@+import { withTimeout } from 'es-toolkit/promise'++import type { EditorPreparationEventEmitter } from '@/app/editor/preparation/events'+import type {+ BeginEditorPreparation,+ EditorPreparationCancelReason,+ EditorPreparationFailure,+ EditorPreparationHandle,+ EditorPreparationUpdate+} from '@/app/editor/preparation/types'+import type { AppEditorState } from '@/app/editor/session/types'++const PRESENTATION_TIMEOUT_MS = 10_000++interface PresentationWaiter {+ sceneVersion: number+ resolve: () => void+}++export interface EditorPreparationControllerOptions {+ presentationTimeoutMs?: number+}++export interface EditorPreparationController {+ begin(options: BeginEditorPreparation): EditorPreparationHandle+ acknowledgePresentation(sceneVersion: number): void+ waitForPresentation(id: number, sceneVersion: number): Promise<void>+ dispose(): void+}++export function createEditorPreparationController(+ state: AppEditorState,+ events?: EditorPreparationEventEmitter,+ options: EditorPreparationControllerOptions = {}+): EditorPreparationController {+ const presentationTimeoutMs = options.presentationTimeoutMs ?? PRESENTATION_TIMEOUT_MS+ let nextId = 0+ let activeAbort: AbortController | null = null+ let activeCancel: ((reason: EditorPreparationCancelReason) => void) | null = null+ let presentedSceneVersion = -1+ const presentationWaiters = new Map<number, PresentationWaiter>()++ const isActive = (id: number) => state.preparation?.id === id++ return {+ begin(options) {+ activeCancel?.('superseded')+ const abort = new AbortController()+ activeAbort = abort+ const id = ++nextId+ const kind = options.kind+ state.preparation = {+ id,+ kind,+ phase: options.phase ?? 'reading',+ subject: options.subject ?? null,+ detail: null,+ progress: null,+ startedAt: performance.now()+ }+ events?.emit('preparation:started', state.preparation)++ const clear = () => {+ presentationWaiters.get(id)?.resolve()+ presentationWaiters.delete(id)+ if (isActive(id)) state.preparation = null+ if (activeAbort === abort) activeAbort = null+ if (activeCancel === cancel) activeCancel = null+ }++ const cancel = (reason: EditorPreparationCancelReason = 'user') => {+ if (!isActive(id)) return+ abort.abort()+ clear()+ events?.emit('preparation:finished', { id, kind, status: 'cancelled', reason })+ }+ activeCancel = cancel++ return {+ id,+ signal: abort.signal,+ update(update: EditorPreparationUpdate) {+ if (!isActive(id) || abort.signal.aborted) return+ const hasProgress =+ update.completed !== undefined &&+ update.completed !== null &&+ update.total !== undefined &&+ update.total !== null &&+ update.total > 0+ const previous = state.preparation+ if (!previous) return+ state.preparation = {+ ...previous,+ phase: update.phase,+ detail: update.detail ?? null,+ progress: hasProgress+ ? {+ completed: update.completed ?? 0,+ total: update.total ?? 0,+ unit: update.unit ?? 'fonts'+ }+ : null+ }+ events?.emit('preparation:updated', state.preparation, previous)+ },+ complete() {+ if (!isActive(id)) return+ clear()+ events?.emit('preparation:finished', { id, kind, status: 'completed' })+ },+ fail(failure) {+ if (!isActive(id)) return+ const event: EditorPreparationFailure = { id, kind, ...failure }+ clear()+ events?.emit('preparation:failed', event)+ },+ cancel+ }+ },+ acknowledgePresentation(sceneVersion) {+ presentedSceneVersion = Math.max(presentedSceneVersion, sceneVersion)+ for (const [id, waiter] of presentationWaiters) {+ if (waiter.sceneVersion > presentedSceneVersion) continue+ waiter.resolve()+ presentationWaiters.delete(id)+ }+ },+ waitForPresentation(id, sceneVersion) {+ if (!isActive(id) || presentedSceneVersion >= sceneVersion) return Promise.resolve()+ return withTimeout(+ () =>+ new Promise<void>((resolve) => {+ presentationWaiters.set(id, { sceneVersion, resolve })+ }),+ presentationTimeoutMs+ ).finally(() => presentationWaiters.delete(id))+ },+ dispose() {+ activeCancel?.('tab-closed')+ activeAbort?.abort()+ activeAbort = null+ activeCancel = null+ for (const waiter of presentationWaiters.values()) waiter.resolve()+ presentationWaiters.clear()+ state.preparation = null+ }+ }+}diff --git a/src/app/editor/preparation/events.ts b/src/app/editor/preparation/events.tsnew file mode 100644index 000000000..2e4c5e801--- /dev/null+++ b/src/app/editor/preparation/events.ts@@ -0,0 +1,70 @@+import type {+ EditorPreparation,+ EditorPreparationFailure,+ EditorPreparationResult+} from '@/app/editor/preparation/types'++export interface EditorPreparationEvents {+ 'preparation:started': (preparation: EditorPreparation) => void+ 'preparation:updated': (preparation: EditorPreparation, previous: EditorPreparation) => void+ 'preparation:finished': (result: EditorPreparationResult) => void+ 'preparation:failed': (failure: EditorPreparationFailure) => void+}++export type EditorPreparationEventName = keyof EditorPreparationEvents++export interface EditorPreparationEventEmitter {+ emit<Event extends EditorPreparationEventName>(+ event: Event,+ ...args: Parameters<EditorPreparationEvents[Event]>+ ): void+ on<Event extends EditorPreparationEventName>(+ event: Event,+ handler: EditorPreparationEvents[Event]+ ): () => void+}++export function createEditorPreparationEvents(): EditorPreparationEventEmitter {+ const started = new Set<EditorPreparationEvents['preparation:started']>()+ const updated = new Set<EditorPreparationEvents['preparation:updated']>()+ const finished = new Set<EditorPreparationEvents['preparation:finished']>()+ const failed = new Set<EditorPreparationEvents['preparation:failed']>()++ return {+ emit(event, ...args) {+ switch (event) {+ case 'preparation:started':+ for (const listener of started) listener(args[0] as EditorPreparation)+ break+ case 'preparation:updated':+ for (const listener of updated) {+ listener(args[0] as EditorPreparation, args[1] as EditorPreparation)+ }+ break+ case 'preparation:finished':+ for (const listener of finished) listener(args[0] as EditorPreparationResult)+ break+ case 'preparation:failed':+ for (const listener of failed) listener(args[0] as EditorPreparationFailure)+ }+ },+ on(event, handler) {+ switch (event) {+ case 'preparation:started':+ started.add(handler as EditorPreparationEvents['preparation:started'])+ return () => started.delete(handler as EditorPreparationEvents['preparation:started'])+ case 'preparation:updated':+ updated.add(handler as EditorPreparationEvents['preparation:updated'])+ return () => updated.delete(handler as EditorPreparationEvents['preparation:updated'])+ case 'preparation:finished':+ finished.add(handler as EditorPreparationEvents['preparation:finished'])+ return () => finished.delete(handler as EditorPreparationEvents['preparation:finished'])+ case 'preparation:failed':+ failed.add(handler as EditorPreparationEvents['preparation:failed'])+ return () => failed.delete(handler as EditorPreparationEvents['preparation:failed'])+ default:+ return () => undefined+ }+ }+ }+}diff --git a/src/app/editor/preparation/types.ts b/src/app/editor/preparation/types.tsnew file mode 100644index 000000000..bc69a41cc--- /dev/null+++ b/src/app/editor/preparation/types.ts@@ -0,0 +1,76 @@+export type EditorPreparationKind =+ | 'document-open'+ | 'document-reload'+ | 'recovery-restore'+ | 'storage-open'+ | 'page-switch'+ | 'font-retry'+ | 'dom-import'++export type EditorPreparationPhase =+ | 'reading'+ | 'decoding'+ | 'materializing'+ | 'populating-page'+ | 'resolving-fonts'+ | 'resolving-fallbacks'+ | 'layout'+ | 'preparing-render'++export interface EditorPreparationProgress {+ completed: number+ total: number+ unit: 'bytes' | 'nodes' | 'fonts' | 'pages'+}++export interface EditorPreparation {+ id: number+ kind: EditorPreparationKind+ phase: EditorPreparationPhase+ subject: string | null+ detail: string | null+ progress: EditorPreparationProgress | null+ startedAt: number+}++export interface BeginEditorPreparation {+ kind: EditorPreparationKind+ phase?: EditorPreparationPhase+ subject?: string | null+}++export interface EditorPreparationUpdate {+ phase: EditorPreparationPhase+ detail?: string | null+ completed?: number | null+ total?: number | null+ unit?: EditorPreparationProgress['unit']+}++export type EditorPreparationCancelReason = 'superseded' | 'tab-closed' | 'user'++export interface EditorPreparationFailure {+ id: number+ kind: EditorPreparationKind+ code: 'read-failed' | 'decode-failed' | 'font-failed' | 'layout-failed' | 'render-failed'+ message: string+ retryable: boolean+}++export type EditorPreparationResult =+ | { id: number; kind: EditorPreparationKind; status: 'completed' }+ | {+ id: number+ kind: EditorPreparationKind+ status: 'cancelled'+ reason: EditorPreparationCancelReason+ }++export interface EditorPreparationHandle {+ readonly id: number+ readonly signal: AbortSignal+ update(update: EditorPreparationUpdate): void+ complete(): void+ fail(failure: Omit<EditorPreparationFailure, 'id' | 'kind'>): void+ cancel(reason?: EditorPreparationCancelReason): void+}diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.tsindex 75f65f5d0..c67f4c2aa 100644--- a/src/app/editor/session/create.ts+++ b/src/app/editor/session/create.ts@@ -4,6 +4,7 @@ import { createEditor } from '@open-pencil/core/editor'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { SceneGraph } from '@open-pencil/scene-graph'+import { recordPreparationOutcome } from '@/app/diagnostics'import {getActiveEditorStore,setActiveEditorStore,@@ -13,12 +14,21 @@ import { resolveFigmaClipboardImages } from '@/app/editor/clipboard/figma-imagesimport { bindClipboardNotifications } from '@/app/editor/clipboard/notifications'import { loadFont } from '@/app/editor/fonts'import { createCanvasPaneRegistry } from '@/app/editor/panes/registry'+import { createEditorPreparationController } from '@/app/editor/preparation/controller'+import {+ createEditorPreparationEvents,+ type EditorPreparationEventName,+ type EditorPreparationEvents+} from '@/app/editor/preparation/events'+import type { EditorPreparationHandle } from '@/app/editor/preparation/types'import {createEditorComputedRefs,createEditorStoreModules,defineEditorStoreAccessors} from '@/app/editor/session/modules'import { createInitialAppEditorState, type AppEditorState } from '@/app/editor/session/types'+import { notificationMessages } from '@/app/i18n/notifications'+import { toast } from '@/app/shell/ui'import { IS_BROWSER, IS_TAURI } from '@/constants'export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/editor'@@ -52,17 +62,140 @@ export function createEditorStore(initialGraph?: SceneGraph) {}const { selectedNodes, selectedNode, layerTree } = createEditorComputedRefs(editor, state)-- const modules = createEditorStoreModules(editor, state, io, viewportSize)+ const preparationEvents = createEditorPreparationEvents()+ const preparationLifecycle = new Map<+ number,+ {+ kind: NonNullable<AppEditorState['preparation']>['kind']+ phase: NonNullable<AppEditorState['preparation']>['phase']+ startedAt: number+ }+ >()+ preparationEvents.on('preparation:started', (preparation) => {+ preparationLifecycle.set(preparation.id, {+ kind: preparation.kind,+ phase: preparation.phase,+ startedAt: preparation.startedAt+ })+ })+ preparationEvents.on('preparation:updated', (preparation) => {+ const lifecycle = preparationLifecycle.get(preparation.id)+ if (lifecycle) lifecycle.phase = preparation.phase+ })+ preparationEvents.on('preparation:finished', (result) => {+ const lifecycle = preparationLifecycle.get(result.id)+ if (!lifecycle) return+ recordPreparationOutcome({+ kind: result.kind,+ outcome: result.status,+ cancellationReason: result.status === 'cancelled' ? result.reason : null,+ failureCode: null,+ terminalPhase: lifecycle.phase,+ durationMs: performance.now() - lifecycle.startedAt+ })+ preparationLifecycle.delete(result.id)+ })+ preparationEvents.on('preparation:failed', (failure) => {+ const lifecycle = preparationLifecycle.get(failure.id)+ if (!lifecycle) return+ recordPreparationOutcome({+ kind: failure.kind,+ outcome: 'failed',+ cancellationReason: null,+ failureCode: failure.code,+ terminalPhase: lifecycle.phase,+ durationMs: performance.now() - lifecycle.startedAt+ })+ preparationLifecycle.delete(failure.id)+ })+ const preparationController = createEditorPreparationController(state, preparationEvents)+ const modules = createEditorStoreModules(editor, state, io, viewportSize, preparationController)// ─── Public API ───────────────────────────────────────────────// Spread all core Editor methods, then override getters and add app-specific.const panes = createCanvasPaneRegistry(state)+ function progressUnit(phase: string): 'fonts' | 'pages' | undefined {+ if (phase === 'resolving-fonts') return 'fonts'+ if (phase === 'populating-page') return 'pages'+ return undefined+ }++ async function switchPage(+ pageId: string,+ options: {+ preparation?: EditorPreparationHandle+ onProgress?: Parameters<typeof editor.switchPage>[1] extends infer Options+ ? Options extends { onProgress?: infer Progress }+ ? Progress+ : never+ : never+ } = {}+ ) {+ const page = editor.graph.getNode(pageId)+ const preparation =+ options.preparation ??+ preparationController.begin({+ kind: 'page-switch',+ phase: 'populating-page',+ subject: page?.name ?? null+ })+ const ownsPreparation = options.preparation === undefined+ let succeeded = false+ try {+ const prepared = await editor.preparePage(pageId, {+ signal: preparation.signal,+ onProgress: (progress) => {+ options.onProgress?.(progress)+ preparation.update({+ ...progress,+ unit: progressUnit(progress.phase)+ })+ }+ })+ preparation.signal.throwIfAborted()+ if (prepared) {+ editor.commitPageSwitch(prepared)+ preparation.update({ phase: 'preparing-render', detail: page?.name ?? null })+ await preparationController.waitForPresentation(preparation.id, editor.state.sceneVersion)+ preparation.signal.throwIfAborted()+ }+ succeeded = true+ } catch (error) {+ if (preparation.signal.aborted) throw error+ if (ownsPreparation) {+ const presentationTimedOut =+ error instanceof Error && error.message === 'The operation was timed out'+ preparation.fail({+ code: presentationTimedOut ? 'render-failed' : 'layout-failed',+ message: error instanceof Error ? error.message : String(error),+ retryable: true+ })+ if (presentationTimedOut) {+ toast.error(+ notificationMessages.get().operationFailed({+ error: error instanceof Error ? error.message : String(error)+ })+ )+ }+ }+ throw error+ } finally {+ if (ownsPreparation && succeeded) preparation.complete()+ }+ }+const store = {...editor,state,+ preparationController,+ onPreparationEvent<Event extends EditorPreparationEventName>(+ event: Event,+ handler: EditorPreparationEvents[Event]+ ) {+ return preparationEvents.on(event, handler)+ },panes,selectedNodes,selectedNode,@@ -72,6 +205,7 @@ export function createEditorStore(initialGraph?: SceneGraph) {visiblePaneCount: panes.visiblePaneCount,getPaneRenderState: panes.getPaneRenderState,setActivePane: panes.setActivePane,+ switchPage,splitPane: panes.splitPane,closePane: panes.closePane,resizePane: panes.resizePane,diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex e17f70d8c..bb4b0cde6 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -9,6 +9,7 @@ import type { ViewportSize } from '@/app/document/io/types'import { createFlashActions } from '@/app/editor/flash'import { createMobileClipboardActions } from '@/app/editor/mobile-clipboard'import { createPenActions } from '@/app/editor/pen'+import type { EditorPreparationController } from '@/app/editor/preparation/controller'import { createProfilerActions } from '@/app/editor/profiler'import type { AppEditorState } from '@/app/editor/session/types'import { createVectorEditActions } from '@/app/editor/vector'@@ -52,12 +53,13 @@ export function createEditorStoreModules(editor: Editor,state: AppEditorState,io: IORegistry,- viewportSize: ViewportSize+ viewportSize: ViewportSize,+ preparationController: EditorPreparationController) {const flash = createFlashActions(editor, state)const pen = createPenActions(editor, state)const vectorEdit = createVectorEditActions(editor, state)- const documentIO = createDocumentIOActions(editor, state, viewportSize)+ const documentIO = createDocumentIOActions(editor, state, viewportSize, preparationController)const documentExport = createDocumentExportActions(editor, state, io, documentIO.downloadBlob)const mobileClipboard = createMobileClipboardActions(editor, state)const profiler = createProfilerActions(editor)@@ -88,6 +90,7 @@ export function createEditorStoreModules(editor.dispose()editor.clearPageViewports()documentIO.disposeDocumentIO()+ preparationController.dispose()},...documentExport,...mobileClipboard,diff --git a/src/app/editor/session/types.ts b/src/app/editor/session/types.tsindex f54d721b8..7a5560916 100644--- a/src/app/editor/session/types.ts+++ b/src/app/editor/session/types.ts@@ -1,5 +1,6 @@import { createDefaultEditorState, type EditorState } from '@open-pencil/core/editor'+import type { EditorPreparation } from '@/app/editor/preparation/types'import type { NodeEditState } from '@/app/editor/vector/types'import { appPreferences } from '@/app/settings/preferences/store'@@ -21,7 +22,8 @@ export function createInitialAppEditorState(pageId: string): AppEditorState {nodeEditState: null,renameSelectionOpen: false,renameNodeId: null,- numberFieldFocused: false+ numberFieldFocused: false,+ preparation: null}}@@ -41,4 +43,5 @@ export type AppEditorState = EditorState & {renameSelectionOpen: booleanrenameNodeId: string | nullnumberFieldFocused: boolean+ preparation: EditorPreparation | null}diff --git a/src/app/integrations/storage/s3/adapter.ts b/src/app/integrations/storage/s3/adapter.tsindex 25b5b0bc1..e65a08fcf 100644--- a/src/app/integrations/storage/s3/adapter.ts+++ b/src/app/integrations/storage/s3/adapter.ts@@ -172,8 +172,10 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3Storareturn documents.sort((first, second) => second.updatedAt.localeCompare(first.updatedAt))},- async getDocument(id, onProgress) {+ async getDocument(id, onProgress, signal) {+ signal?.throwIfAborted()const config = await resolveConfig(runtime)+ signal?.throwIfAborted()const bytes = await getObject(config,documentFigKey(id),@@ -183,7 +185,8 @@ export function createS3StorageAdapter(runtime: StorageProviderRuntime): S3StoratransferredBytes: progress.receivedBytes,totalBytes: progress.totalBytes})- : undefined+ : undefined,+ signal)if (!bytes) throw new Error(`Document not found: ${id}`)return bytesdiff --git a/src/app/integrations/storage/s3/client.ts b/src/app/integrations/storage/s3/client.tsindex cf426d7ce..0d9fb7fec 100644--- a/src/app/integrations/storage/s3/client.ts+++ b/src/app/integrations/storage/s3/client.ts@@ -142,7 +142,8 @@ export async function s3Request(method: signed.method,headers: signed.headers,body: init.body ?? undefined,- credentials: 'omit'+ credentials: 'omit',+ signal: init.signal})}} catch (error) {@@ -247,29 +248,31 @@ export async function getObjectValue(export type DownloadProgress = { receivedBytes: number; totalBytes: number | null }-export async function getObject(- config: S3CompatibleConfig,- key: string,- onProgress?: (progress: DownloadProgress) => void-): Promise<Uint8Array | null> {- const res = await s3Request(config, objectURL(config, key), { method: 'GET' })- if (res.status === 404) return null- if (!onProgress || !res.body) {- return new Uint8Array(await res.arrayBuffer())- }+export async function readDownloadResponse(+ res: Response,+ onProgress?: (progress: DownloadProgress) => void,+ signal?: AbortSignal+): Promise<Uint8Array> {+ signal?.throwIfAborted()+ if (!onProgress || !res.body) return new Uint8Array(await res.arrayBuffer())- // Stream so large figs can report download progressconst contentLength = Number(res.headers.get('content-length'))const totalBytes = Number.isFinite(contentLength) && contentLength > 0 ? contentLength : nullconst reader = res.body.getReader()const chunks: Uint8Array[] = []let receivedBytes = 0- for (;;) {- const { done, value } = await reader.read()- if (done) break- chunks.push(value)- receivedBytes += value.byteLength- onProgress({ receivedBytes, totalBytes })+ try {+ for (;;) {+ const { done, value } = await reader.read()+ signal?.throwIfAborted()+ if (done) break+ chunks.push(value)+ receivedBytes += value.byteLength+ onProgress({ receivedBytes, totalBytes })+ }+ } catch (error) {+ await reader.cancel().catch(() => undefined)+ throw error}const out = new Uint8Array(receivedBytes)let offset = 0@@ -280,6 +283,18 @@ export async function getObject(return out}+export async function getObject(+ config: S3CompatibleConfig,+ key: string,+ onProgress?: (progress: DownloadProgress) => void,+ signal?: AbortSignal+): Promise<Uint8Array | null> {+ signal?.throwIfAborted()+ const res = await s3Request(config, objectURL(config, key), { method: 'GET', signal })+ if (res.status === 404) return null+ return readDownloadResponse(res, onProgress, signal)+}+export async function deleteObject(config: S3CompatibleConfig, key: string): Promise<void> {const res = await s3Request(config, objectURL(config, key), { method: 'DELETE' })if (!res.ok && res.status !== 404) {diff --git a/src/app/integrations/storage/s3/fetch.ts b/src/app/integrations/storage/s3/fetch.tsindex 912b14aae..1f1cbda55 100644--- a/src/app/integrations/storage/s3/fetch.ts+++ b/src/app/integrations/storage/s3/fetch.ts@@ -3,20 +3,16 @@ import { isTauri } from '@/app/tauri/env'/** Avoid hung “Test connection” when CORS/network never resolves. */const STORAGE_FETCH_TIMEOUT_MS = 20_000-function withTimeoutSignal(init?: RequestInit): {+interface StorageFetchSignal {signal: AbortSignal- cleanup: () => void-} {- const controller = new AbortController()- const timer = setTimeout(() => controller.abort(), STORAGE_FETCH_TIMEOUT_MS)- const external = init?.signal- if (external) {- if (external.aborted) controller.abort()- else external.addEventListener('abort', () => controller.abort(), { once: true })- }+ timedOut: () => boolean+}++function storageFetchSignal(external?: AbortSignal | null): StorageFetchSignal {+ const timeout = AbortSignal.timeout(STORAGE_FETCH_TIMEOUT_MS)return {- signal: controller.signal,- cleanup: () => clearTimeout(timer)+ signal: external ? AbortSignal.any([external, timeout]) : timeout,+ timedOut: () => timeout.aborted}}@@ -25,7 +21,7 @@ export async function storageFetch(input: RequestInfo | URL,init?: RequestInit): Promise<Response> {- const { signal, cleanup } = withTimeoutSignal(init)+ const { signal, timedOut } = storageFetchSignal(init?.signal)try {if (isTauri()) {const { tauriFetch } = await import('@/app/tauri/http')@@ -37,13 +33,11 @@ export async function storageFetch(}return await fetch(input, { ...init, signal })} catch (error) {- if (signal.aborted) {+ if (timedOut()) {throw new Error('Storage request timed out. Check the endpoint URL, network, and bucket CORS settings.')}throw error- } finally {- cleanup()}}diff --git a/src/app/integrations/storage/types.ts b/src/app/integrations/storage/types.tsindex 9e1584510..9872952be 100644--- a/src/app/integrations/storage/types.ts+++ b/src/app/integrations/storage/types.ts@@ -68,7 +68,8 @@ export interface StorageAdapter {listDocuments(): Promise<StorageDocument[]>getDocument(id: string,- onProgress?: (progress: StorageTransferProgress) => void+ onProgress?: (progress: StorageTransferProgress) => void,+ signal?: AbortSignal): Promise<Uint8Array>putDocument(id: string,diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex b797ece12..61ccc7b4b 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -9,12 +9,16 @@ import { computeAllLayouts } from '@open-pencil/core/layout'import type { SceneGraph } from '@open-pencil/scene-graph'import { setOpenPencilStore } from '@/app/browser-bridge'+import { describeDiagnosticError, recordStorageFailure } from '@/app/diagnostics'import { readFigDocument } from '@/app/document/io/fig'+import { applyImportedDocument } from '@/app/document/io/imported-document'import type { DocumentSourceIdentity } from '@/app/document/io/types'import { getRecoveryStore, type RecoverySnapshotMeta } from '@/app/document/recovery'import { setActiveEditorStore } from '@/app/editor/active-store'+import type { EditorPreparationHandle as DocumentLoadSession } from '@/app/editor/preparation/types'import { createEditorStore } from '@/app/editor/session'import type { EditorStore } from '@/app/editor/session'+import { notificationMessages } from '@/app/i18n/notifications'import {activeStorageProviderID,createActiveStorageAdapter,@@ -25,6 +29,7 @@ import {loadCachedRecentFileThumbnail,rememberRecentStorageDocument} from '@/app/recent-files'+import { toast } from '@/app/shell/ui'import { getLocalCanvasStore } from '@/app/storage/local-store'import { seedStorageCanvasFromRemote } from '@/app/storage/sync/persist'import { createFileOpenCoordinator } from '@/app/tabs/open/coordinator'@@ -59,6 +64,8 @@ export const allTabs = computed(() =>id: t.id,name: t.store.state.documentName,isHome: t.kind === 'home',+ isPreparing: t.store.state.preparation !== null,+ preparationProgress: t.store.state.preparation?.progress ?? null,isActive: t.id === activeTabId.value})))@@ -190,8 +197,8 @@ function reusableTabStore(): { store: EditorStore; created: boolean } {return { store: createTab().store, created: true }}-async function readFigForTab(file: File, store: EditorStore): Promise<SceneGraph> {- const imported = await readFigDocument(file, store)+async function readFigForTab(file: File, signal?: AbortSignal): Promise<SceneGraph> {+ const imported = await readFigDocument(file, signal)const firstPageId = imported.getPages()[0]?.idif (firstPageId) computeAllLayouts(imported, firstPageId)const coverPageId = findFigThumbnailPageId(imported.getPages())@@ -205,14 +212,19 @@ async function readFigForTab(file: File, store: EditorStore): Promise<SceneGraphasync function showImportedGraph(store: EditorStore,graph: SceneGraph,- prepare?: () => void | Promise<void>+ prepare?: () => void | Promise<void>,+ load?: DocumentLoadSession): Promise<void> {- store.replaceGraph(graph)- store.undo.clear()+ load?.update({ phase: 'materializing', detail: store.state.documentName })+ await applyImportedDocument(store, graph, load)+ load?.signal.throwIfAborted()await prepare?.()- store.clearSelection()+ load?.signal.throwIfAborted()const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId- await store.switchPage(pageId)+ load?.update({ phase: 'populating-page', detail: store.graph.getNode(pageId)?.name ?? null })+ await store.switchPage(pageId, { preparation: load })+ load?.signal.throwIfAborted()+ load?.update({ phase: 'preparing-render', detail: store.state.documentName })await store.fitCurrentPageToViewport()}@@ -265,6 +277,19 @@ function findStorageTab(providerId: string, documentId: string): Tab | undefined})}+function failPreparation(+ load: DocumentLoadSession,+ code: 'read-failed' | 'decode-failed',+ error: unknown+): void {+ if (load.signal.aborted) return+ load.fail({+ code,+ message: error instanceof Error ? error.message : String(error),+ retryable: true+ })+}+export async function openStorageDocumentInNewTab(document: StorageDocument): Promise<void> {const providerId = activeStorageProviderID.valueconst existing = findStorageTab(providerId, document.id)@@ -276,11 +301,18 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): Prconst { store, created } = reusableTabStore()store.state.documentName = document.name- store.state.loading = true+ const load = store.preparationController.begin({+ kind: 'storage-open',+ subject: document.name+ })+ let succeeded = falsetry {+ load.update({ phase: 'reading', detail: document.name })const local = getLocalCanvasStore()const localMetadata = await local.getMeta(document.id)+ load.signal.throwIfAborted()const localBytes = localMetadata?.hasFig ? await local.readFig(document.id) : null+ load.signal.throwIfAborted()const localIsAuthoritative =localMetadata?.syncStatus !== 'synced' ||!document.metadataAuthoritative ||@@ -288,7 +320,18 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): Prlet bytes = localBytes && localIsAuthoritative ? localBytes : nullif (!bytes) {- bytes = await createActiveStorageAdapter(providerId).getDocument(document.id)+ bytes = await createActiveStorageAdapter(providerId).getDocument(+ document.id,+ (progress) =>+ load.update({+ phase: 'reading',+ detail: document.name,+ completed: progress.transferredBytes,+ total: progress.totalBytes,+ unit: 'bytes'+ }),+ load.signal+ )await seedStorageCanvasFromRemote({providerId,canvasId: document.id,@@ -296,6 +339,7 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): PrupdatedAt: document.updatedAt,figBytes: bytes})+ load.signal.throwIfAborted()}const fileBytes = new Uint8Array(bytes.byteLength)@@ -303,19 +347,39 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): Prconst file = new File([fileBytes.buffer], `${document.name}.fig`, {type: 'application/octet-stream'})- const imported = await readFigForTab(file, store)- await showImportedGraph(store, imported, () =>- store.setStorageDocumentSource({ providerId, documentId: document.id }, document.name)+ load.update({ phase: 'decoding', detail: document.name })+ const imported = await readFigForTab(file, load.signal)+ await showImportedGraph(+ store,+ imported,+ () => store.setStorageDocumentSource({ providerId, documentId: document.id }, document.name),+ load)rememberRecentStorageDocument(providerId, document.id, document.name)+ succeeded = true} catch (error) {+ if (!load.signal.aborted) {+ const diagnostic = describeDiagnosticError(error)+ load.fail({+ code: 'read-failed',+ message: error instanceof Error ? error.message : String(error),+ retryable: diagnostic.retryable ?? true+ })+ recordStorageFailure({ operation: 'download', ...diagnostic })+ toast.error(+ notificationMessages.get().openFileFailed({+ name: document.name,+ error: error instanceof Error ? error.message : String(error)+ })+ )+ }if (created) {const tab = getTabForStore(store)if (tab) await closeTab(tab.id)}throw error} finally {- store.state.loading = false+ if (succeeded) load.complete()}}@@ -350,13 +414,16 @@ export async function openFileInNewTab(const { store, created } = reusableTabStore()store.state.documentName = file.name.replace(/\.[^.]+$/i, '')- store.state.loading = true+ const load = store.preparationController.begin({+ kind: isDOMImportFile(file) ? 'dom-import' : 'document-open',+ subject: file.name+ })const completion = Promise.withResolvers<undefined>()void completion.promise.catch(() => undefined)const pendingOpen = { completion: completion.promise, identity, store }fileOpenCoordinator.add(pendingOpen)- return { kind: 'owner' as const, completion, pendingOpen, store, created }+ return { kind: 'owner' as const, completion, pendingOpen, store, created, load }})if (decision.kind === 'existing') return@@ -365,40 +432,55 @@ export async function openFileInNewTab(return}- const { completion, pendingOpen, store, created } = decision+ const { completion, pendingOpen, store, created, load } = decision+ let succeeded = falsetry {if (isDOMImportFile(file)) {- await store.openDOMFile(file, { handle, path })+ await store.openDOMFile(file, { handle, path, preparation: load })completion.resolve(undefined)+ succeeded = truereturn}await yieldToUI()+ load.update({ phase: 'reading', detail: file.name })const isFig = file.name.toLowerCase().endsWith('.fig')- const { graph: imported, sourceFormat } = isFig- ? {- graph: await readFigForTab(file, store),- sourceFormat: 'fig'- }- : await io.readDocument({- name: file.name,- mimeType: file.type || undefined,- data: new Uint8Array(await file.arrayBuffer())- })+ let imported: SceneGraph+ let sourceFormat: string+ if (isFig) {+ load.update({ phase: 'decoding', detail: file.name })+ imported = await readFigForTab(file, load.signal)+ sourceFormat = 'fig'+ } else {+ const result = await io.readDocument({+ name: file.name,+ mimeType: file.type || undefined,+ data: new Uint8Array(await file.arrayBuffer())+ })+ imported = result.graph+ sourceFormat = result.sourceFormat+ }const firstPageId = imported.getPages()[0]?.idif (!isFig && firstPageId) computeAllLayouts(imported, firstPageId)- await showImportedGraph(store, imported, () => {- store.setDocumentSource(file.name, sourceFormat, handle, path)- if (isFig && path) watchOpenedFigCover(path, store)- })+ await showImportedGraph(+ store,+ imported,+ () => {+ store.setDocumentSource(file.name, sourceFormat, handle, path)+ if (isFig && path) watchOpenedFigCover(path, store)+ },+ load+ )if (isFig && path) {void cacheOpenedFigCover(path, store).catch((error) => {console.warn('[Recent files] Failed to cache the Cover thumbnail', error)})}completion.resolve(undefined)+ succeeded = true} catch (error) {+ failPreparation(load, 'decode-failed', error)completion.reject(error)if (created) {const tab = getTabForStore(store)@@ -406,7 +488,7 @@ export async function openFileInNewTab(}throw error} finally {- store.state.loading = false+ if (succeeded) load.complete()fileOpenCoordinator.remove(pendingOpen)}}@@ -424,20 +506,35 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {if (!snapshot) throw new Error('Recovery snapshot is no longer available')const { store } = reusableTabStore()- store.state.loading = true+ const load = store.preparationController.begin({+ kind: 'recovery-restore',+ subject: snapshot.documentName+ })+ let succeeded = falsetry {+ load.update({ phase: 'reading', detail: snapshot.documentName })const fileBytes = new Uint8Array(snapshot.figBytes)const file = new File([fileBytes.buffer], `${snapshot.documentName}.fig`, {type: 'application/octet-stream'})- const imported = await readFigForTab(file, store)-- await showImportedGraph(store, imported, async () => {- store.state.documentName = snapshot.documentName- await store.adoptRecoverySnapshot(id, snapshot.sceneVersion)- })+ load.update({ phase: 'decoding', detail: snapshot.documentName })+ const imported = await readFigForTab(file, load.signal)++ await showImportedGraph(+ store,+ imported,+ async () => {+ store.state.documentName = snapshot.documentName+ await store.adoptRecoverySnapshot(id, snapshot.sceneVersion)+ },+ load+ )+ succeeded = true+ } catch (error) {+ failPreparation(load, 'decode-failed', error)+ throw error} finally {- store.state.loading = false+ if (succeeded) load.complete()}}diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 5ae1b3888..dd661b786 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -30,6 +30,7 @@ import IconLucidePanelLeft from '~icons/lucide/panel-left'import IconLucidePanelRight from '~icons/lucide/panel-right'import IconLucidePanelTop from '~icons/lucide/panel-top'import CanvasMenu from './canvas/CanvasMenu.vue'+import PreparationOverlay from '@/components/preparation/canvas/Overlay.vue'import NumberField from './inputs/NumberField.vue'const { paneId } = defineProps<{@@ -59,17 +60,26 @@ const onViewportResize = paneIdconst { updateCursor } = useCanvasCollaborationAwareness(store, collab)const { selectAtContextPoint } = createCanvasContextSelection(canvasRef, store)+const shouldSuspendRender = () =>+ store.state.preparation !== null &&+ store.state.preparation.kind !== 'font-retry' &&+ store.state.preparation.phase !== 'preparing-render'+useCanvas(sceneCanvasRef, store, {layer: 'scene',+ shouldSuspendRender,showRulers: false,getRenderState,- onViewportResize+ onViewportResize,+ onPresented: ({ sceneVersion }) =>+ store.preparationController.acknowledgePresentation(sceneVersion)})const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle } = useCanvas(canvasRef,store,{layer: 'overlays',+ shouldSuspendRender,getRenderState,onViewportResize}@@ -204,22 +214,10 @@ const cursor = computed(() => toolCursor(store.state.activeTool, cursorOverride.</PopoverContent></PopoverPortal></PopoverRoot>- <Transition leave-active-class="transition-opacity duration-300" leave-to-class="opacity-0">- <div- v-if="store.state.loading"- data-test-id="canvas-loading"- class="absolute inset-0 z-50 flex items-center justify-center bg-canvas"- >- <icon-lucide-pencil-line class="size-8 text-surface opacity-45" />- <div- class="absolute bottom-1/2 left-1/2 h-0.5 w-25 -translate-x-1/2 translate-y-10 overflow-hidden rounded-full bg-surface/8"- >- <div- class="h-full w-2/5 animate-[slide_1s_ease-in-out_infinite] rounded-full bg-surface/25"- />- </div>- </div>- </Transition>+ <PreparationOverlay+ v-if="store.state.preparation && store.state.preparation.kind !== 'font-retry'"+ :preparation="store.state.preparation"+ /></div></ContextMenuTrigger>diff --git a/src/components/TabBar.vue b/src/components/TabBar.vueindex 0e42a9123..25cd67132 100644--- a/src/components/TabBar.vue+++ b/src/components/TabBar.vue@@ -3,6 +3,7 @@ import { computed } from 'vue'import { TabsList, TabsRoot, TabsTrigger } from 'reka-ui'import { tv } from 'tailwind-variants'+import PreparationIndicator from '@/components/preparation/tab/Indicator.vue'import Tip from '@/components/ui/Tip.vue'import tabBarTheme from '@/theme/tab-bar'import { useTabsStore, createHomeTab } from '@/app/tabs'@@ -56,6 +57,7 @@ function onClose(e: MouseEvent, tabId: string) {@mousedown="onMiddleClick($event, tab.id, tab.isHome)"><icon-lucide-house v-if="tab.isHome" :class="baseStyles.icon()" />+ <PreparationIndicator v-else-if="tab.isPreparing" :progress="tab.preparationProgress" /><icon-lucide-file v-else :class="baseStyles.icon()" /><span :class="baseStyles.label()">{{ tab.isHome ? dialogs.newTab : tab.name }}</span><Tipdiff --git a/src/components/preparation/canvas/Overlay.vue b/src/components/preparation/canvas/Overlay.vuenew file mode 100644index 000000000..91d921aaf--- /dev/null+++ b/src/components/preparation/canvas/Overlay.vue@@ -0,0 +1,57 @@+<script setup lang="ts">+import { ProgressIndicator, ProgressRoot } from 'reka-ui'+import { computed } from 'vue'++import type { EditorPreparation } from '@/app/editor/preparation/types'+import { preparationLabel, preparationPercent } from '@/components/preparation/presentation'++const { preparation } = defineProps<{+ preparation: EditorPreparation+}>()++const label = computed(() => preparationLabel(preparation))+const progressValue = computed(() => preparationPercent(preparation.progress))+const progressSteps = computed(() => Math.round(progressValue.value ?? 0))+</script>++<template>+ <Transition leave-active-class="transition-opacity duration-300" leave-to-class="opacity-0">+ <div+ data-test-id="canvas-loading"+ role="status"+ aria-live="polite"+ :aria-label="label"+ class="absolute inset-0 z-50 flex items-center justify-center bg-canvas"+ >+ <div class="flex w-72 flex-col items-center gap-3 text-center">+ <icon-lucide-pencil-line class="size-8 text-surface opacity-45" />+ <div class="space-y-1">+ <p class="text-sm font-medium text-surface/80">{{ label }}</p>+ <p v-if="preparation.detail" class="truncate text-xs text-surface/45">+ {{ preparation.detail }}+ </p>+ </div>+ <ProgressRoot+ :model-value="progressValue"+ class="h-0.5 w-25 overflow-hidden rounded-full bg-surface/8"+ >+ <ProgressIndicator+ v-if="progressValue === null"+ class="h-full w-2/5 animate-[slide_1s_ease-in-out_infinite] rounded-full bg-surface/25"+ />+ <div v-else class="flex h-full w-full">+ <span+ v-for="step in 100"+ :key="step"+ :data-complete="step <= progressSteps"+ class="h-full flex-1 bg-transparent transition-colors duration-150 data-[complete=true]:bg-surface/35"+ />+ </div>+ </ProgressRoot>+ <p v-if="progressValue !== null" class="text-xs tabular-nums text-surface/45">+ {{ preparation.progress?.completed }} of {{ preparation.progress?.total }}+ </p>+ </div>+ </div>+ </Transition>+</template>diff --git a/src/components/preparation/presentation.ts b/src/components/preparation/presentation.tsnew file mode 100644index 000000000..0c8e4bbd5--- /dev/null+++ b/src/components/preparation/presentation.ts@@ -0,0 +1,21 @@+import type { EditorPreparation, EditorPreparationProgress } from '@/app/editor/preparation/types'++export const preparationPhaseLabels = {+ reading: 'Reading document',+ decoding: 'Decoding Figma document',+ materializing: 'Preparing layers',+ 'populating-page': 'Preparing page',+ 'resolving-fonts': 'Resolving fonts',+ 'resolving-fallbacks': 'Finalizing typography',+ layout: 'Computing layout',+ 'preparing-render': 'Preparing canvas'+} satisfies Record<EditorPreparation['phase'], string>++export function preparationLabel(preparation: EditorPreparation | null): string {+ return preparation ? preparationPhaseLabels[preparation.phase] : 'Loading…'+}++export function preparationPercent(progress: EditorPreparationProgress | null): number | null {+ if (!progress || progress.total <= 0) return null+ return Math.min(100, Math.max(0, Math.round((progress.completed / progress.total) * 100)))+}diff --git a/src/components/preparation/tab/Indicator.vue b/src/components/preparation/tab/Indicator.vuenew file mode 100644index 000000000..f9879683c--- /dev/null+++ b/src/components/preparation/tab/Indicator.vue@@ -0,0 +1,25 @@+<script setup lang="ts">+import { computed } from 'vue'++import type { EditorPreparationProgress } from '@/app/editor/preparation/types'+import { preparationPercent } from '@/components/preparation/presentation'++const { progress } = defineProps<{+ progress: EditorPreparationProgress | null+}>()++const percent = computed(() => preparationPercent(progress))+</script>++<template>+ <span+ role="progressbar"+ :aria-valuenow="percent ?? undefined"+ :aria-valuemin="percent === null ? undefined : 0"+ :aria-valuemax="percent === null ? undefined : 100"+ aria-label="Preparing document"+ class="relative flex size-3 shrink-0 items-center justify-center text-accent"+ >+ <icon-lucide-loader-circle class="size-3 animate-spin" />+ </span>+</template>diff --git a/src/components/recovery/RecoveryDialog.vue b/src/components/recovery/RecoveryDialog.vueindex 1011cfea3..6ff675563 100644--- a/src/components/recovery/RecoveryDialog.vue+++ b/src/components/recovery/RecoveryDialog.vue@@ -1,5 +1,5 @@<script setup lang="ts">-import { AlertDialogCancel } from 'reka-ui'+import { AlertDialogCancel, AlertDialogDescription, AlertDialogTitle } from 'reka-ui'import { onMounted, ref } from 'vue'import { useRoute } from 'vue-router'import { useI18n } from '@open-pencil/vue'diff --git a/tests/e2e/app/tab-preparation.spec.ts b/tests/e2e/app/tab-preparation.spec.tsnew file mode 100644index 000000000..f0282841a--- /dev/null+++ b/tests/e2e/app/tab-preparation.spec.ts@@ -0,0 +1,22 @@+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'++const editor = useEditorSetup('/?test')++test('shows preparation status in an inactive tab without covering the active canvas', async () => {+ await editor.page.evaluate(async () => {+ const tabs = await import('/src/app/tabs/index.ts')+ const first = tabs.getActiveStore()+ first.state.documentName = 'Preparing file'+ tabs.createTab()+ first.preparationController+ .begin({ kind: 'document-open', phase: 'resolving-fonts', subject: 'preparing.fig' })+ .update({ phase: 'resolving-fonts', completed: 3, total: 4, unit: 'fonts' })+ })++ const tab = editor.page.getByTestId('tabbar-tab').filter({ hasText: 'Preparing file' })+ await expect(tab.getByRole('progressbar', { name: 'Preparing document' })).toHaveAttribute(+ 'aria-valuenow',+ '75'+ )+ await expect(editor.page.getByTestId('canvas-loading')).toBeHidden()+})diff --git a/tests/e2e/canvas/document-loading.spec.ts b/tests/e2e/canvas/document-loading.spec.tsnew file mode 100644index 000000000..a54d87133--- /dev/null+++ b/tests/e2e/canvas/document-loading.spec.ts@@ -0,0 +1,37 @@+import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'++const editor = useEditorSetup('/?test&no-chrome&no-rulers')++test('shows staged and determinate document loading progress in the existing canvas overlay', async () => {+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const load = store.preparationController.begin({+ kind: 'document-open',+ phase: 'resolving-fonts',+ subject: 'example.fig'+ })+ load.update({+ phase: 'resolving-fonts',+ detail: 'Geist SemiBold',+ completed: 7,+ total: 12,+ unit: 'fonts'+ })+ })++ const loader = editor.page.getByTestId('canvas-loading')+ await expect(loader).toBeVisible()+ await expect(loader).toHaveAttribute('role', 'status')+ await expect(loader).toContainText('Resolving fonts')+ await expect(loader).toContainText('Geist SemiBold')+ await expect(loader).toContainText('7 of 12')+ await expect(loader.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '58')++ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) return+ store.preparationController.dispose()+ })+ await expect(loader).toBeHidden()+})diff --git a/tests/engine/app/diagnostics/events.test.ts b/tests/engine/app/diagnostics/events.test.tsindex b921cd997..68e65e4ec 100644--- a/tests/engine/app/diagnostics/events.test.ts+++ b/tests/engine/app/diagnostics/events.test.ts@@ -2,6 +2,33 @@ import { describe, expect, test } from 'bun:test'import { describeDiagnosticError } from '@/app/diagnostics'import { storageOperationForJob } from '@/app/diagnostics/events'+import {+ preparationDurationBucket,+ recordPreparationOutcome+} from '@/app/diagnostics/events/preparation'++test('preparation diagnostics bucket durations without sensitive subjects', () => {+ expect(+ [99, 100, 999, 1_000, 4_999, 5_000, 29_999, 30_000].map(preparationDurationBucket)+ ).toEqual([+ 'under-100ms',+ '100ms-1s',+ '100ms-1s',+ '1s-5s',+ '1s-5s',+ '5s-30s',+ '5s-30s',+ 'over-30s'+ ])+ recordPreparationOutcome({+ kind: 'document-open',+ outcome: 'failed',+ cancellationReason: null,+ failureCode: 'decode-failed',+ terminalPhase: 'decoding',+ durationMs: 1_234+ })+})describe('diagnostic error metadata', () => {test('keeps only safe error metadata', () => {diff --git a/tests/engine/app/document/io/imported-document.test.ts b/tests/engine/app/document/io/imported-document.test.tsnew file mode 100644index 000000000..f75be5e97--- /dev/null+++ b/tests/engine/app/document/io/imported-document.test.ts@@ -0,0 +1,44 @@+import { expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { SceneGraph } from '@open-pencil/scene-graph'++import { applyImportedDocument } from '@/app/document/io/imported-document'+import { createEditorPreparationController } from '@/app/editor/preparation/controller'+import { createInitialAppEditorState } from '@/app/editor/session/types'++test('cancelled imported-document staging preserves the live graph', async () => {+ const liveGraph = new SceneGraph()+ const liveEditor = createEditor({ graph: liveGraph, skipInitialGraphSetup: true })+ const imported = new SceneGraph()+ const importedPage = imported.getPages()[0]+ if (!importedPage) throw new Error('Expected imported page')+ imported.updateNode(importedPage.id, { name: 'Imported' })+ const controller = createEditorPreparationController(+ createInitialAppEditorState(liveGraph.rootId)+ )+ const preparation = controller.begin({ kind: 'document-open' })+ preparation.cancel()++ await expect(applyImportedDocument(liveEditor, imported, preparation)).rejects.toHaveProperty(+ 'name',+ 'AbortError'+ )+ expect(liveEditor.graph).toBe(liveGraph)+ liveEditor.dispose()+})++test('prepared imported documents replace the live graph only after staging', async () => {+ const liveGraph = new SceneGraph()+ const liveEditor = createEditor({ graph: liveGraph, skipInitialGraphSetup: true })+ const imported = new SceneGraph()+ const page = imported.getPages()[0]+ if (!page) throw new Error('Expected imported page')+ imported.updateNode(page.id, { name: 'Imported' })++ await applyImportedDocument(liveEditor, imported)++ expect(liveEditor.graph).toBe(imported)+ expect(liveEditor.state.currentPageId).toBe(page.id)+ liveEditor.dispose()+})diff --git a/tests/engine/app/editor/preparation/controller.test.ts b/tests/engine/app/editor/preparation/controller.test.tsnew file mode 100644index 000000000..bce79ae22--- /dev/null+++ b/tests/engine/app/editor/preparation/controller.test.ts@@ -0,0 +1,119 @@+import { describe, expect, test } from 'bun:test'++import { createEditorPreparationController } from '@/app/editor/preparation/controller'+import { createEditorPreparationEvents } from '@/app/editor/preparation/events'+import type { EditorPreparationResult } from '@/app/editor/preparation/types'+import { createInitialAppEditorState } from '@/app/editor/session/types'++describe('editor preparation controller', () => {+ test('keeps one reactive preparation snapshot until its owner finishes', () => {+ const state = createInitialAppEditorState('page')+ const controller = createEditorPreparationController(state)+ const load = controller.begin({ kind: 'document-open', subject: 'example.fig' })+ load.update({+ phase: 'resolving-fonts',+ detail: 'Geist Regular',+ completed: 2,+ total: 7,+ unit: 'fonts'+ })++ expect(state.preparation).toEqual({+ id: load.id,+ kind: 'document-open',+ phase: 'resolving-fonts',+ subject: 'example.fig',+ detail: 'Geist Regular',+ progress: { completed: 2, total: 7, unit: 'fonts' },+ startedAt: expect.any(Number)+ })++ load.complete()+ expect(state.preparation).toBeNull()+ })++ test('aborts and ignores an obsolete preparation handle', () => {+ const state = createInitialAppEditorState('page')+ const events = createEditorPreparationEvents()+ const results: EditorPreparationResult[] = []+ events.on('preparation:finished', (result) => results.push(result))+ const controller = createEditorPreparationController(state, events)+ const first = controller.begin({ kind: 'document-open' })+ const second = controller.begin({ kind: 'page-switch', phase: 'populating-page' })++ expect(first.signal.aborted).toBe(true)+ expect(results).toContainEqual({+ id: first.id,+ kind: 'document-open',+ status: 'cancelled',+ reason: 'superseded'+ })+ first.update({ phase: 'layout', detail: 'obsolete' })+ first.complete()+ expect(state.preparation?.id).toBe(second.id)+ second.complete()+ expect(state.preparation).toBeNull()+ })++ test('waits for the prepared scene to be presented before finishing', async () => {+ const state = createInitialAppEditorState('page')+ const controller = createEditorPreparationController(state)+ const handle = controller.begin({ kind: 'page-switch' })++ let presented = false+ const waiting = controller.waitForPresentation(handle.id, 7).then(() => {+ presented = true+ return presented+ })+ await Promise.resolve()+ expect(presented).toBe(false)++ controller.acknowledgePresentation(6)+ await Promise.resolve()+ expect(presented).toBe(false)++ controller.acknowledgePresentation(7)+ await waiting+ expect(presented).toBe(true)+ handle.complete()+ })+ test('times out when a committed scene is never presented', async () => {+ const state = createInitialAppEditorState('page')+ const controller = createEditorPreparationController(state, undefined, {+ presentationTimeoutMs: 1+ })+ const handle = controller.begin({ kind: 'page-switch' })++ await expect(controller.waitForPresentation(handle.id, 7)).rejects.toHaveProperty(+ 'message',+ 'The operation was timed out'+ )+ handle.fail({ code: 'render-failed', message: 'Timed out', retryable: true })+ expect(state.preparation).toBeNull()+ })+ test('emits exactly one terminal outcome', () => {+ const state = createInitialAppEditorState('page')+ const events = createEditorPreparationEvents()+ const outcomes: string[] = []+ events.on('preparation:finished', (result) => outcomes.push(result.status))+ events.on('preparation:failed', () => outcomes.push('failed'))+ const controller = createEditorPreparationController(state, events)++ const failed = controller.begin({ kind: 'document-open' })+ failed.fail({ code: 'decode-failed', message: 'Invalid', retryable: false })+ failed.complete()+ failed.cancel()++ expect(outcomes).toEqual(['failed'])+ })+ test('dispose aborts the active tab-local preparation', () => {+ const state = createInitialAppEditorState('page')+ const controller = createEditorPreparationController(state)+ const load = controller.begin({ kind: 'storage-open' })++ controller.dispose()++ expect(load.signal.aborted).toBe(true)+ expect(state.preparation).toBeNull()+ })+})diff --git a/tests/engine/app/editor/preparation/multi-tab.test.ts b/tests/engine/app/editor/preparation/multi-tab.test.tsnew file mode 100644index 000000000..8634e7bfc--- /dev/null+++ b/tests/engine/app/editor/preparation/multi-tab.test.ts@@ -0,0 +1,53 @@+import { describe, expect, test } from 'bun:test'++import { createEditorStore } from '@/app/editor/session/create'++describe('multi-tab editor preparation', () => {+ test('keeps preparation snapshots isolated per editor store', () => {+ const first = createEditorStore()+ const second = createEditorStore()+ const events: string[] = []+ const offStarted = first.onPreparationEvent('preparation:started', () => events.push('started'))+ const offUpdated = first.onPreparationEvent('preparation:updated', () => events.push('updated'))+ const offFinished = first.onPreparationEvent('preparation:finished', (result) =>+ events.push(result.status)+ )+ const firstLoad = first.preparationController.begin({+ kind: 'document-open',+ subject: 'first.fig'+ })+ const secondLoad = second.preparationController.begin({+ kind: 'storage-open',+ subject: 'second.fig'+ })++ expect(first.state.preparation?.subject).toBe('first.fig')+ expect(second.state.preparation?.subject).toBe('second.fig')+ firstLoad.update({ phase: 'layout' })+ firstLoad.complete()+ expect(events).toEqual(['started', 'updated', 'completed'])+ offStarted()+ offUpdated()+ offFinished()+ expect(first.state.preparation).toBeNull()+ expect(second.state.preparation?.id).toBe(secondLoad.id)++ first.dispose()+ second.dispose()+ })++ test('disposing one editor aborts only its own active preparation', () => {+ const first = createEditorStore()+ const second = createEditorStore()+ const firstLoad = first.preparationController.begin({ kind: 'page-switch' })+ const secondLoad = second.preparationController.begin({ kind: 'font-retry' })++ first.dispose()++ expect(firstLoad.signal.aborted).toBe(true)+ expect(first.state.preparation).toBeNull()+ expect(secondLoad.signal.aborted).toBe(false)+ expect(second.state.preparation).not.toBeNull()+ second.dispose()+ })+})diff --git a/tests/engine/app/integrations/storage/cancellation.test.ts b/tests/engine/app/integrations/storage/cancellation.test.tsnew file mode 100644index 000000000..698f0c762--- /dev/null+++ b/tests/engine/app/integrations/storage/cancellation.test.ts@@ -0,0 +1,78 @@+import { expect, test } from 'bun:test'++import { createS3StorageAdapter } from '@/app/integrations/storage/s3/adapter'+import { readDownloadResponse } from '@/app/integrations/storage/s3/client'+import { storageFetch } from '@/app/integrations/storage/s3/fetch'++test('mid-stream cancellation discards partial bytes and stops progress', async () => {+ const abort = new AbortController()+ const progress: number[] = []+ let cancelled = false+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new Uint8Array([1, 2]))+ queueMicrotask(() => controller.enqueue(new Uint8Array([3, 4])))+ },+ cancel() {+ cancelled = true+ }+ })+ const response = new Response(stream, { headers: { 'content-length': '4' } })+ const reading = readDownloadResponse(+ response,+ ({ receivedBytes }) => {+ progress.push(receivedBytes)+ abort.abort()+ },+ abort.signal+ )++ await expect(reading).rejects.toHaveProperty('name', 'AbortError')+ expect(progress).toEqual([2])+ expect(cancelled).toBe(true)+})++test('external storage cancellation remains an AbortError rather than a timeout', async () => {+ const originalFetch = globalThis.fetch+ globalThis.fetch = ((_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener(+ 'abort',+ () => reject(new DOMException('Aborted', 'AbortError')),+ { once: true }+ )+ })) as typeof fetch+ const abort = new AbortController()+ const pending = storageFetch('https://storage.example.com/document.fig', {+ signal: abort.signal+ })+ abort.abort()+ try {+ await expect(pending).rejects.toHaveProperty('name', 'AbortError')+ } finally {+ globalThis.fetch = originalFetch+ }+})++test('pre-aborted storage downloads do not resolve credentials or start network work', async () => {+ let credentialResolutions = 0+ const adapter = createS3StorageAdapter({+ preferences: {+ endpoint: 'https://storage.example.com',+ bucket: 'designs',+ region: 'auto'+ },+ async resolveCredential() {+ credentialResolutions+++ return 'secret'+ }+ })+ const abort = new AbortController()+ abort.abort()++ await expect(adapter.getDocument('document', undefined, abort.signal)).rejects.toHaveProperty(+ 'name',+ 'AbortError'+ )+ expect(credentialResolutions).toBe(0)+})diff --git a/tests/engine/app/tabs/open-file-dedup.test.ts b/tests/engine/app/tabs/open-file-dedup.test.tsindex ee52963db..1ef76e417 100644--- a/tests/engine/app/tabs/open-file-dedup.test.ts+++ b/tests/engine/app/tabs/open-file-dedup.test.ts@@ -39,6 +39,36 @@ function setupGlobals() {globalThis.cancelAnimationFrame = window.cancelAnimationFrame}+function acknowledgePendingPresentation(): void {+ for (const tab of getTabsSnapshot()) {+ if (tab.store.state.preparation?.phase !== 'preparing-render') continue+ tab.store.preparationController.acknowledgePresentation(tab.store.state.sceneVersion)+ }+}++type FileOpenOutcome = { status: 'fulfilled' } | { status: 'rejected'; reason: unknown }++async function settleFileOpen(opening: Promise<void>): Promise<void> {+ const outcome: Promise<FileOpenOutcome> = opening.then(+ () => ({ status: 'fulfilled' }),+ (reason: unknown) => ({ status: 'rejected', reason })+ )++ const awaitOutcome = async (): Promise<FileOpenOutcome> => {+ acknowledgePendingPresentation()+ const result = await Promise.race([+ outcome,+ new Promise<null>((resolve) => {+ setTimeout(resolve, 0)+ })+ ])+ return result ?? awaitOutcome()+ }++ const result = await awaitOutcome()+ if (result.status === 'rejected') throw result.reason+}+function makeHandle(name: string,isSameEntry: (other: FileSystemFileHandle) => Promise<boolean>@@ -152,7 +182,9 @@ describe('openFileInNewTab deduplication', () => {const home = getTabsSnapshot().at(-1)const count = tabCount()- await openFileInNewTab(new File([], 'design.fig'), undefined, '/tmp/from-home.fig')+ await settleFileOpen(+ openFileInNewTab(new File([], 'design.fig'), undefined, '/tmp/from-home.fig')+ )expect(tabCount()).toBe(count)expect(getTabsSnapshot().at(-1)?.id).toBe(home?.id)@@ -163,9 +195,9 @@ describe('openFileInNewTab deduplication', () => {const initialCount = tabCount()const file = new File([], 'design.fig')- await openFileInNewTab(file, undefined, '/tmp/design.fig')+ await settleFileOpen(openFileInNewTab(file, undefined, '/tmp/design.fig'))const openedStore = getActiveStore()- await openFileInNewTab(file, undefined, '/tmp/design.fig')+ await settleFileOpen(openFileInNewTab(file, undefined, '/tmp/design.fig'))expect(tabCount()).toBe(initialCount)expect(getActiveStore()).toBe(openedStore)@@ -189,7 +221,7 @@ describe('openFileInNewTab deduplication', () => {expect(figModule.readFigFile).toHaveBeenCalledTimes(1)read.resolve(new SceneGraph())- await Promise.all([first, second])+ await Promise.all([settleFileOpen(first), settleFileOpen(second)])expect(tabCount()).toBe(initialCount)})@@ -211,7 +243,7 @@ describe('openFileInNewTab deduplication', () => {expect(figModule.readFigFile).toHaveBeenCalledTimes(2)reads[0].resolve(new SceneGraph())reads[1].resolve(new SceneGraph())- await Promise.all([first, second])+ await Promise.all([settleFileOpen(first), settleFileOpen(second)])expect(tabCount()).toBe(initialCount + 1)})@@ -221,10 +253,10 @@ describe('openFileInNewTab deduplication', () => {.mockResolvedValueOnce(new SceneGraph())await expect(- openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig')+ settleFileOpen(openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig'))).rejects.toThrow('read failed')await expect(- openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig')+ settleFileOpen(openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig'))).resolves.toBeUndefined()expect(figModule.readFigFile).toHaveBeenCalledTimes(2)@@ -235,8 +267,8 @@ describe('openFileInNewTab deduplication', () => {const initialCount = tabCount()const file = new File([], 'same-name.fig')- await openFileInNewTab(file)- await openFileInNewTab(file)+ await settleFileOpen(openFileInNewTab(file))+ await settleFileOpen(openFileInNewTab(file))expect(tabCount()).toBe(initialCount + 1)expect(figModule.readFigFile).toHaveBeenCalledTimes(2)diff --git a/tests/engine/editor/pages/loading.test.ts b/tests/engine/editor/pages/loading.test.tsnew file mode 100644index 000000000..de25d7dda--- /dev/null+++ b/tests/engine/editor/pages/loading.test.ts@@ -0,0 +1,138 @@+import { expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { createEditor, type PageSwitchProgress } from '#core/editor'++test('core page preparation only reports progress and never owns app suspension', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ if (!page) throw new Error('Expected default page')+ graph.createNode('TEXT', page.id, {+ text: 'Loading',+ fontFamily: 'Loader Test',+ fontWeight: 400+ })+ const progress: PageSwitchProgress[] = []+ let release: (() => void) | null = null+ const fontReady = new Promise<void>((resolve) => {+ release = resolve+ })+ const editor = createEditor({+ graph,+ skipInitialGraphSetup: true,+ loadFont: async () => {+ await fontReady+ return null+ }+ })+ const switching = editor.switchPage(page.id, {+ onProgress: (next) => progress.push(next)+ })+ await Promise.resolve()++ expect(progress.some((entry) => entry.phase === 'resolving-fonts')).toBe(true)+ release?.()+ await switching+ expect(progress).toContainEqual(+ expect.objectContaining({ phase: 'resolving-fonts', completed: 1, total: 1 })+ )+})++test('prepares a target page without exposing it before commit', async () => {+ const graph = new SceneGraph()+ const firstPage = graph.getPages()[0]+ if (!firstPage) throw new Error('Expected default page')+ const secondPage = graph.addPage('Prepared page')+ graph.createNode('TEXT', secondPage.id, {+ text: 'Loading',+ fontFamily: 'Loader Test',+ fontWeight: 400+ })+ let release: (() => void) | null = null+ const fontReady = new Promise<void>((resolve) => {+ release = resolve+ })+ const editor = createEditor({+ graph,+ skipInitialGraphSetup: true,+ loadFont: async () => {+ await fontReady+ return null+ }+ })+ const pageChanges: string[] = []+ editor.onEditorEvent('page:changed', (pageId) => pageChanges.push(pageId))++ const preparing = editor.preparePage(secondPage.id)+ await Promise.resolve()+ expect(editor.state.currentPageId).toBe(firstPage.id)+ expect(pageChanges).toEqual([])++ release?.()+ const prepared = await preparing+ expect(editor.state.currentPageId).toBe(firstPage.id)+ expect(prepared).not.toBeNull()+ if (!prepared) throw new Error('Expected prepared page')++ expect(editor.commitPageSwitch(prepared)).toBe(true)+ expect(editor.state.currentPageId).toBe(secondPage.id)+ expect(pageChanges).toEqual([secondPage.id])+})++test('aborted page preparation preserves the visible page', async () => {+ const graph = new SceneGraph()+ const firstPage = graph.getPages()[0]+ if (!firstPage) throw new Error('Expected default page')+ const secondPage = graph.addPage('Cancelled page')+ graph.createNode('TEXT', secondPage.id, {+ text: 'Loading',+ fontFamily: 'Loader Test',+ fontWeight: 400+ })+ let release: (() => void) | null = null+ const fontReady = new Promise<void>((resolve) => {+ release = resolve+ })+ const editor = createEditor({+ graph,+ skipInitialGraphSetup: true,+ loadFont: async () => {+ await fontReady+ return null+ }+ })+ const abort = new AbortController()+ const preparing = editor.preparePage(secondPage.id, { signal: abort.signal })+ await Promise.resolve()+ abort.abort()+ release?.()++ await expect(preparing).rejects.toHaveProperty('name', 'AbortError')+ expect(editor.state.currentPageId).toBe(firstPage.id)+})++test('obsolete prepared pages cannot commit after a newer preparation', async () => {+ const graph = new SceneGraph()+ const firstPage = graph.getPages()[0]+ if (!firstPage) throw new Error('Expected default page')+ const secondPage = graph.addPage('Second')+ const thirdPage = graph.addPage('Third')+ const editor = createEditor({ graph, skipInitialGraphSetup: true })++ const second = await editor.preparePage(secondPage.id)+ const third = await editor.preparePage(thirdPage.id)+ expect(second).not.toBeNull()+ expect(third).not.toBeNull()+ if (!second || !third) throw new Error('Expected prepared pages')++ expect(editor.commitPageSwitch(second)).toBe(false)+ expect(editor.state.currentPageId).toBe(firstPage.id)+ expect(editor.commitPageSwitch(third)).toBe(true)+ expect(editor.state.currentPageId).toBe(thirdPage.id)+})+test('page viewport cleanup remains independent from app preparation state', () => {+ const editor = createEditor()++ expect(() => editor.clearPageViewports()).not.toThrow()+})diff --git a/tests/engine/io/fig/import/cancellation.test.ts b/tests/engine/io/fig/import/cancellation.test.tsnew file mode 100644index 000000000..0fa8e5216--- /dev/null+++ b/tests/engine/io/fig/import/cancellation.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from 'bun:test'++import { parseFigFile } from '#core/io/formats/fig/read'++describe('FIG parsing cancellation', () => {+ test('rejects before synchronous parsing when already aborted', async () => {+ const abort = new AbortController()+ abort.abort()++ await expect(parseFigFile(new ArrayBuffer(0), { signal: abort.signal })).rejects.toHaveProperty(+ 'name',+ 'AbortError'+ )+ })+})diff --git a/tests/engine/tauri/fonts.test.ts b/tests/engine/tauri/fonts.test.tsindex 12ab3e739..a2837675d 100644--- a/tests/engine/tauri/fonts.test.ts+++ b/tests/engine/tauri/fonts.test.ts@@ -50,6 +50,6 @@ describe('Tauri font helpers', () => {const { loadFont } = await import('@/app/editor/fonts')await expect(loadFont('Missing Family', 'Regular')).resolves.toBe(fallback)- expect(loadFontSpy).toHaveBeenCalledWith('Missing Family', 'Regular', '')+ expect(loadFontSpy).toHaveBeenCalledWith('Missing Family', 'Regular', '', undefined)})})diff --git a/tests/engine/text/fonts/loading.test.ts b/tests/engine/text/fonts/loading.test.tsindex 0c5a23c38..ecf2c92fb 100644--- a/tests/engine/text/fonts/loading.test.ts+++ b/tests/engine/text/fonts/loading.test.ts@@ -212,6 +212,34 @@ describe('FontManager loaded font cache', () => {expect(writes).toBe(0)})+ test('forwards cancellation to fallback web-font requests', async () => {+ const manager = new FontManager()+ let remoteRequestStarted: (() => void) | null = null+ const started = new Promise<void>((resolve) => {+ remoteRequestStarted = resolve+ })+ const originalLoadRemoteFont = manager.loadRemoteFont.bind(manager)+ manager.loadRemoteFont = async (_family, _style, _characters, signal) => {+ remoteRequestStarted?.()+ return new Promise<ArrayBuffer | null>((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), {+ once: true+ })+ })+ }+ const abort = new AbortController()+ const loading = manager.ensureFallbackPack(['cjk'], '字', abort.signal)++ await started+ abort.abort()++ try {+ await expect(loading).rejects.toHaveProperty('name', 'AbortError')+ } finally {+ manager.loadRemoteFont = originalLoadRemoteFont+ }+ })+test('loads bundled Inter ExtraBold without network access', async () => {const manager = new FontManager()const recording = createRecordingProvider()diff --git a/tests/engine/vue/canvas/render-loop.test.ts b/tests/engine/vue/canvas/render-loop.test.tsindex 0cec79ac3..762e692a9 100644--- a/tests/engine/vue/canvas/render-loop.test.ts+++ b/tests/engine/vue/canvas/render-loop.test.ts@@ -43,7 +43,6 @@ function createEditor() {const handlers = new Map<EditorEventName, Set<(...args: never[]) => void>>()const editor: TestEditor = {state: {- loading: false,renderVersion: 0,selectedIds: new Set<string>()} as Editor['state'],@@ -253,29 +252,33 @@ describe('canvas render loop', () => {}})- test('renders after supplied view state finishes loading without a version change', () => {+ test('renders after an injected suspension finishes without a version change', () => {const scheduler = createFrameScheduler()try {const { editor, emit } = createEditor()- const viewState = { ...editor.state, loading: false }+ const viewState = { ...editor.state }+ let suspended = falselet renders = 0const loop = createCanvasRenderLoop(editor,() => {renders++},- { getRenderState: () => viewState }+ {+ getRenderState: () => viewState,+ shouldSuspendRender: () => suspended+ })emit('repaint:requested')scheduler.flush()loop.markRendered()- viewState.loading = true+ suspended = trueemit('repaint:requested')scheduler.flush()expect(renders).toBe(1)- viewState.loading = false+ suspended = falsescheduler.flush()expect(renders).toBe(2)} finally {