AI-native design editor. Open-source Figma alternative.
fix(fig): harden background page loading
Victor Wadsa53d90d50b73
diff --git a/packages/kiwi/src/schema-runtime/bb.ts b/packages/kiwi/src/schema-runtime/bb.tsindex 0c02d9153..5ad4d2345 100644--- a/packages/kiwi/src/schema-runtime/bb.ts+++ b/packages/kiwi/src/schema-runtime/bb.ts@@ -128,18 +128,22 @@ export class ByteBuffer {}readString(): string {- const data = this._dataconst start = this._index- let i = start- while (data[i] !== 0) i+++ const i = this.findStringTerminator(start)this._index = i + 1- return textDecoder.decode(data.subarray(start, i))+ return textDecoder.decode(this._data.subarray(start, i))}skipString(): void {- while (this._data[this._index++] !== 0) {- // Strings are null-terminated in Kiwi messages.- }+ this._index = this.findStringTerminator(this._index) + 1+ }++ private findStringTerminator(start: number): number {+ const data = this._data+ let index = start+ while (index < data.length && data[index] !== 0) index+++ if (index >= data.length) throw new Error('Unterminated string in Kiwi message')+ return index}private _growBy(amount: number): void {diff --git a/src/app/shell/menu/recent-files.ts b/src/app/shell/menu/recent-files.tsindex 66a1afcd7..b6e102dd9 100644--- a/src/app/shell/menu/recent-files.ts+++ b/src/app/shell/menu/recent-files.ts@@ -57,7 +57,12 @@ export async function syncRecentFilesMenu(): Promise<void> {}function updateRecentFiles(paths: string[]): void {- recentFilePaths.value = paths.slice(0, MAX_RECENT_FILES)+ const nextPaths = paths.slice(0, MAX_RECENT_FILES)+ const retainedPaths = new Set(nextPaths)+ recentFilePaths.value = nextPaths+ recentFileOpenedAt.value = Object.fromEntries(+ Object.entries(recentFileOpenedAt.value).filter(([path]) => retainedPaths.has(path))+ )void syncRecentFilesMenu().catch((error) => {console.warn('[Recent files] Failed to update the native menu', error)})@@ -123,12 +128,25 @@ export async function loadRecentFileThumbnail(path: string): Promise<Uint8Arrayif (!isTauri() || !path.toLowerCase().endsWith('.fig')) return nullconst cached = await loadCachedRecentFileThumbnail(path)if (cached) return cached- const { readFile } = await import('@tauri-apps/plugin-fs')- const bytes = await readFile(path)- return extractFigThumbnailFromReader({- size: bytes.byteLength,- async read(start, endExclusive) {- return bytes.subarray(start, endExclusive)- }- })+ const { open, SeekMode } = await import('@tauri-apps/plugin-fs')+ const file = await open(path, { read: true })+ try {+ const info = await file.stat()+ return await extractFigThumbnailFromReader({+ size: info.size,+ async read(start, endExclusive) {+ await file.seek(start, SeekMode.Start)+ const bytes = new Uint8Array(endExclusive - start)+ let offset = 0+ while (offset < bytes.byteLength) {+ const count = await file.read(bytes.subarray(offset))+ if (count === null) break+ offset += count+ }+ return offset === bytes.byteLength ? bytes : bytes.subarray(0, offset)+ }+ })+ } finally {+ await file.close()+ }}diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 15b9e7e33..776ca3c23 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -178,6 +178,20 @@ async function readFigForTab(file: File, store: EditorStore): Promise<SceneGraphreturn imported}+async function showImportedGraph(+ store: EditorStore,+ graph: SceneGraph,+ prepare?: () => void | Promise<void>+): Promise<void> {+ store.replaceGraph(graph)+ store.undo.clear()+ await prepare?.()+ store.clearSelection()+ const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId+ await store.switchPage(pageId)+ await store.fitCurrentPageToViewport()+}+async function cacheOpenedFigCover(path: string, store: EditorStore): Promise<void> {if (await loadCachedRecentFileThumbnail(path)) returnconst coverPageId = findFigThumbnailPageId(store.graph.getPages())@@ -265,13 +279,9 @@ export async function openStorageDocumentInNewTab(document: StorageDocument): Prtype: 'application/octet-stream'})const imported = await readFigForTab(file, store)- store.replaceGraph(imported)- store.undo.clear()- store.setStorageDocumentSource({ providerId, documentId: document.id }, document.name)- store.clearSelection()- const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId- await store.switchPage(pageId)- await store.fitCurrentPageToViewport()+ await showImportedGraph(store, imported, () =>+ store.setStorageDocumentSource({ providerId, documentId: document.id }, document.name)+ )} finally {store.state.loading = false}@@ -346,14 +356,10 @@ export async function openFileInNewTab(const firstPageId = imported.getPages()[0]?.idif (!isFig && firstPageId) computeAllLayouts(imported, firstPageId)- store.replaceGraph(imported)- store.undo.clear()- store.setDocumentSource(file.name, sourceFormat, handle, path)- if (isFig && path) watchOpenedFigCover(path, store)- store.clearSelection()- const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId- await store.switchPage(pageId)- await store.fitCurrentPageToViewport()+ await showImportedGraph(store, imported, () => {+ store.setDocumentSource(file.name, sourceFormat, handle, path)+ if (isFig && path) watchOpenedFigCover(path, store)+ })if (isFig && path) {void cacheOpenedFigCover(path, store).catch((error) => {console.warn('[Recent files] Failed to cache the Cover thumbnail', error)@@ -382,20 +388,21 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {if (!snapshot) throw new Error('Recovery snapshot is no longer available')const store = reusableTabStore()- 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)+ store.state.loading = true+ try {+ 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)- store.replaceGraph(imported)- store.undo.clear()- store.state.documentName = snapshot.documentName- await store.adoptRecoverySnapshot(id, snapshot.sceneVersion)- store.clearSelection()- const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId- await store.switchPage(pageId)- await store.fitCurrentPageToViewport()+ await showImportedGraph(store, imported, async () => {+ store.state.documentName = snapshot.documentName+ await store.adoptRecoverySnapshot(id, snapshot.sceneVersion)+ })+ } finally {+ store.state.loading = false+ }}export async function prepareForReload(): Promise<void> {diff --git a/tests/engine/io/fig/page-manifest.test.ts b/tests/engine/io/fig/page-manifest.test.tsindex 479214771..790cfbc31 100644--- a/tests/engine/io/fig/page-manifest.test.ts+++ b/tests/engine/io/fig/page-manifest.test.ts@@ -9,18 +9,18 @@ const fixturePath = resolve(import.meta.dir, '../../../fixtures/gold-preview.figtest('reports FIG pages before materializing NodeChange objects', () => {const bytes = readFileSync(fixturePath)- let parseCompleted = false+ let callbackCount = 0let manifest: FigPageManifestEntry[] = []const parsed = parseFigBuffer(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),(pages) => {- expect(parseCompleted).toBe(false)+ callbackCount++manifest = pages})- parseCompleted = true+ expect(callbackCount).toBe(1)expect(parsed.nodeChanges.length).toBeGreaterThan(0)expect(manifest).toEqual([{