AI-native design editor. Open-source Figma alternative.
feat: draw sharper previews of recent files on Home (#1662)
Valery Komarov70c3f70ba3b4
diff --git a/changes/1662/changed.md b/changes/1662/changed.mdnew file mode 100644index 000000000..7abb87bff--- /dev/null+++ b/changes/1662/changed.md@@ -0,0 +1 @@+- Recent files on Home show sharp previews of their whole cover page, centred on the page colour as in Figma's file browser, and keep them after the file is saved.diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.tsindex f137aa9d1..ef887e36e 100644--- a/packages/core/src/io/formats/raster/index.ts+++ b/packages/core/src/io/formats/raster/index.ts@@ -4,6 +4,7 @@ export {renderThumbnail,thumbnailFrame,type RasterExportFormat,+ type ThumbnailFit,type ThumbnailFrame,type ExportFormat} from './render'diff --git a/packages/core/src/io/formats/raster/render.ts b/packages/core/src/io/formats/raster/render.tsindex 36f3c96fd..21f375389 100644--- a/packages/core/src/io/formats/raster/render.ts+++ b/packages/core/src/io/formats/raster/render.ts@@ -298,12 +298,20 @@ export interface ThumbnailFrame {height: number}-/** The page region a thumbnail fitted into `width` by `height` pixels shows, and its size. */+/**+ * How a thumbnail frames its page's content, always whole: `contain` is as large as the content+ * fits in `width` by `height`, and `letterbox` is exactly that size with the content centred on+ * the page colour, as Figma's file browser shows a file in its card.+ */+export type ThumbnailFit = 'contain' | 'letterbox'++/** The page region a thumbnail of `width` by `height` pixels shows, and its size. */export function thumbnailFrame(graph: SceneGraph,pageId: string,width: number,- height: number+ height: number,+ fit: ThumbnailFit = 'contain'): ThumbnailFrame | null {const page = graph.getNode(pageId)if (!page || page.childIds.length === 0) return null@@ -316,6 +324,24 @@ export function thumbnailFrame(if (contentW <= 0 || contentH <= 0) return nullconst scale = Math.min(width / contentW, height / contentH)+ if (fit === 'letterbox') {+ const centerX = (bounds.minX + bounds.maxX) / 2+ const centerY = (bounds.minY + bounds.maxY) / 2+ const halfW = width / scale / 2+ const halfH = height / scale / 2+ return {+ bounds: {+ minX: centerX - halfW,+ minY: centerY - halfH,+ maxX: centerX + halfW,+ maxY: centerY + halfH+ },+ scale,+ width,+ height+ }+ }+return {bounds,scale,@@ -330,9 +356,10 @@ export function renderThumbnail(graph: SceneGraph,pageId: string,width: number,- height: number+ height: number,+ fit: ThumbnailFit = 'contain'): Uint8Array<ArrayBuffer> | null {- const frame = thumbnailFrame(graph, pageId, width, height)+ const frame = thumbnailFrame(graph, pageId, width, height, fit)if (!frame) return nullconst { bounds, scale, width: pixelW, height: pixelH } = frame// The page's own background, which the editor's page colour matches only while it is open.diff --git a/packages/core/tests/io/formats/raster/thumbnail.test.ts b/packages/core/tests/io/formats/raster/thumbnail.test.tsindex beb8364e6..c07987198 100644--- a/packages/core/tests/io/formats/raster/thumbnail.test.ts+++ b/packages/core/tests/io/formats/raster/thumbnail.test.ts@@ -6,7 +6,8 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'import {createCanvasKitRasterCodec,headlessRenderThumbnail,- initCanvasKit+ initCanvasKit,+ thumbnailFrame} from '@open-pencil/core/io/formats/raster'import { SceneGraph } from '@open-pencil/scene-graph'@@ -48,3 +49,19 @@ test('a thumbnail loads the faces its text is set in before drawing it', async (expect(inked).toBeGreaterThan(0)})++test('a letterboxed thumbnail fills its size with the whole content centred', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ graph.createNode('RECTANGLE', page.id, { x: 0, y: 0, width: 1000, height: 1000 })++ const contained = expectDefined(thumbnailFrame(graph, page.id, 160, 90), 'contained frame')+ expect([contained.width, contained.height]).toEqual([90, 90])++ const boxed = expectDefined(thumbnailFrame(graph, page.id, 160, 90, 'letterbox'), 'boxed frame')+ expect([boxed.width, boxed.height, boxed.scale]).toEqual([160, 90, 0.09])+ expect(boxed.bounds.minY).toBe(0)+ expect(boxed.bounds.maxY).toBe(1000)+ expect(boxed.bounds.minX).toBeCloseTo(-388.89, 2)+ expect(boxed.bounds.maxX).toBeCloseTo(1388.89, 2)+})diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.tsindex bb798d4ea..54e293830 100644--- a/src/app/document/io/source/actions.ts+++ b/src/app/document/io/source/actions.ts@@ -9,7 +9,8 @@ import {documentFileName,documentNameFromFigPath,downloadNameFromPath,- figDownloadName+ figDownloadName,+ isFigArchiveName} from '@/app/document/io/names'import { createSaveActions } from '@/app/document/io/save/actions'import { createDocumentSourceState } from '@/app/document/io/source/state'@@ -18,6 +19,7 @@ import { createDocumentRecovery } from '@/app/document/recovery'import { recoveryEnabled } from '@/app/document/recovery/preferences'import { storageLocationOf } from '@/app/integrations/storage/location'import type { StorageDocumentBinding, StorageLocation } from '@/app/integrations/storage/types'+import { cacheRecentFileCover } from '@/app/recent-files'import { createCanvasId } from '@/app/storage/id'import { isTauri } from '@/app/tauri/env'import { trackDocumentFormat } from '@/app/telemetry'@@ -76,6 +78,21 @@ export function createDocumentSourceActions({})}+ /**+ * A write changes the file's time, which keys its Home preview, so the sharp cover is drawn+ * again for it; without it Home falls back to the small cover inside the file. An edit made+ * while `version` was being written is not in the file, so the cover is left to the next save.+ */+ function recacheRecentCover(version: number) {+ const path = getFilePath()+ const renderer = getRenderer()+ if (!path || !renderer || !isFigArchiveName(path)) return+ if (changes.capture() !== version) return+ void cacheRecentFileCover(path, editor.graph, renderer).catch((error: unknown) => {+ console.warn('[Recent files] Could not cache the preview after saving', error)+ })+ }+function buildRecoveryFigFile() {return exportFigFile(editor.graph, {pageId: state.currentPageId,@@ -110,7 +127,10 @@ export function createDocumentSourceActions({startWatchingFile: () => {void startWatchingFile()},- onWriteSuccess: (version) => recovery.markProtectedVersion(version),+ onWriteSuccess: (version) => {+ recacheRecentCover(version)+ return recovery.markProtectedVersion(version)+ },onDownloadSuccess: (version) => recovery.markProtectedVersion(version)})diff --git a/src/app/recent-files/index.ts b/src/app/recent-files/index.tsindex 36a71e02c..ee94cd31f 100644--- a/src/app/recent-files/index.ts+++ b/src/app/recent-files/index.ts@@ -15,6 +15,7 @@ export {type RecentStorageDocument} from './store'export {+ cacheRecentFileCover,cacheRecentFileThumbnail,loadCachedRecentFileThumbnail,loadRecentFileThumbnaildiff --git a/src/app/recent-files/thumbnails.ts b/src/app/recent-files/thumbnails.tsindex 4359ea794..39ea20728 100644--- a/src/app/recent-files/thumbnails.ts+++ b/src/app/recent-files/thumbnails.ts@@ -1,42 +1,124 @@import { stat, open, SeekMode } from '@tauri-apps/plugin-fs'+import { isEqual } from 'es-toolkit'+import * as v from 'valibot'+import type { Editor } from '@open-pencil/core'+import { figThumbnailPageId } from '@open-pencil/core/io/formats/fig'+import { renderThumbnail } from '@open-pencil/core/io/formats/raster'import { extractFigThumbnailFromReader } from '@open-pencil/fig'+import type { SceneGraph } from '@open-pencil/scene-graph'-import { readCacheBytes, removeCachePrefix, writeCacheBytes } from '@/app/cache'+import {+ readCacheBytes,+ readCacheJSON,+ removeCachePrefix,+ writeCacheBytes,+ writeCacheJSON+} from '@/app/cache'import { isFigArchiveName } from '@/app/document/io/names'import { isTauri } from '@/app/tauri/env'-const RECENT_FILE_THUMBNAIL_CACHE_DIR = 'recent-file-thumbnails/v2'+// One entry per file: its cover and the size and time of the file it was drawn for. v4 holds+// 800×450 covers; older ones are drawn again when a file next opens.+const RECENT_FILE_THUMBNAIL_CACHE_DIR = 'recent-file-thumbnails/v4'-async function recentFileThumbnailCacheKey(path: string): Promise<string> {- let fingerprint = path+const coverFingerprintSchema = v.strictObject({ size: v.number(), mtime: v.number() })+type CoverFingerprint = v.InferOutput<typeof coverFingerprintSchema>++/** The file's size and time now; null when they cannot be read, so nothing cached matches. */+async function fileFingerprint(path: string): Promise<CoverFingerprint | null> {try {const info = await stat(path)- fingerprint = `${path}\0${info.size}\0${info.mtime?.getTime() ?? 0}`+ return { size: info.size, mtime: info.mtime?.getTime() ?? 0 }} catch (error) {- // A path-only key still permits a preview when metadata is unavailable.console.warn('[Recent files] Could not stat the file for thumbnail caching', error)+ return null}- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(fingerprint))+}++async function coverEntry(path: string): Promise<{ image: string; fingerprint: string }> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(path))const hash = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')- return `${RECENT_FILE_THUMBNAIL_CACHE_DIR}/${hash}.png`+ const base = `${RECENT_FILE_THUMBNAIL_CACHE_DIR}/${hash}`+ return { image: `${base}.png`, fingerprint: `${base}.json` }}export async function loadCachedRecentFileThumbnail(path: string): Promise<Uint8Array | null> {if (!isTauri()) return null- const bytes = await readCacheBytes(await recentFileThumbnailCacheKey(path))+ const [entry, current] = await Promise.all([coverEntry(path), fileFingerprint(path)])+ if (!current) return null+ const cached = await readCacheJSON(entry.fingerprint, coverFingerprintSchema)+ if (!cached || !isEqual(cached, current)) return null+ const bytes = await readCacheBytes(entry.image)return bytes ? new Uint8Array(bytes) : null}+/** Caches `bytes` as the file's cover, drawn for the file as `fingerprint` describes it. */+async function writeCover(+ path: string,+ bytes: Uint8Array,+ fingerprint: CoverFingerprint+): Promise<void> {+ const entry = await coverEntry(path)+ await writeCacheBytes(entry.image, Uint8Array.from(bytes).buffer)+ await writeCacheJSON(entry.fingerprint, fingerprint)+}+export async function cacheRecentFileThumbnail(path: string, bytes: Uint8Array): Promise<void> {if (!isTauri()) return- await writeCacheBytes(await recentFileThumbnailCacheKey(path), Uint8Array.from(bytes).buffer)+ const fingerprint = await fileFingerprint(path)+ if (fingerprint) await writeCover(path, bytes, fingerprint)+}++/**+ * A Home card's preview: the whole cover page centred on its colour in the card's 16:9, as Figma's+ * file browser shows it, 800 px wide like Figma's previews so a card stays sharp at 2×.+ */+const RECENT_FILE_COVER = { width: 800, height: 450 }++/** Cover writes still running, by file, so each file's covers are cached in the order drawn. */+const coverWrites = new Map<string, Promise<void>>()++/**+ * Draws the cover page of the document at `path` for its Home card and caches it for the file+ * as it is now, so call it once the file is written. The file is read and the cover drawn and+ * queued at once; caching waits for the file's earlier covers, so the last one drawn is kept.+ * False when there is no page to draw.+ */+export async function cacheRecentFileCover(+ path: string,+ graph: SceneGraph,+ renderer: NonNullable<Editor['renderer']>+): Promise<boolean> {+ if (!isTauri()) return false+ const pageId = figThumbnailPageId(graph.getPages())+ if (!pageId) return false+ const { width, height } = RECENT_FILE_COVER+ const bytes = renderThumbnail(renderer.ck, renderer, graph, pageId, width, height, 'letterbox')+ if (!bytes) return false+ // Read now, for the file this cover was drawn from, but queued at once, so covers keep the+ // order they were drawn in however their reads finish.+ const fingerprint = fileFingerprint(path)+ const previous = coverWrites.get(path) ?? Promise.resolve()+ const write = previous+ .catch(() => undefined)+ .then(() => fingerprint)+ .then((drawnFor) => (drawnFor ? writeCover(path, bytes, drawnFor) : undefined))+ coverWrites.set(path, write)+ try {+ await write+ } finally {+ if (coverWrites.get(path) === write) coverWrites.delete(path)+ }+ return true}-export function clearRecentFileThumbnails(): Promise<void> {- return removeCachePrefix(RECENT_FILE_THUMBNAIL_CACHE_DIR)+/** Clears every cover once the writes already queued have landed, so none comes back. */+export async function clearRecentFileThumbnails(): Promise<void> {+ await Promise.allSettled(coverWrites.values())+ await removeCachePrefix(RECENT_FILE_THUMBNAIL_CACHE_DIR)}export async function loadRecentFileThumbnail(path: string): Promise<Uint8Array | null> {diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 984e0506c..bb2e51a95 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -5,7 +5,6 @@ import { shallowRef, computed, triggerRef } from 'vue'import { createDocumentGraph } from '@open-pencil/core'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { figThumbnailPageId, populateFigPage } from '@open-pencil/core/io/formats/fig'-import { renderThumbnail } from '@open-pencil/core/io/formats/raster'import { computeAllLayouts } from '@open-pencil/core/layout'import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'@@ -36,7 +35,7 @@ import {type StorageLocation} from '@/app/integrations/storage'import {- cacheRecentFileThumbnail,+ cacheRecentFileCover,loadCachedRecentFileThumbnail,rememberRecentStorageDocument} from '@/app/recent-files'@@ -61,7 +60,6 @@ export interface Tab {const io = new IORegistry(BUILTIN_IO_FORMATS)const fileOpenCoordinator = createFileOpenCoordinator()-const RECENT_FILE_THUMBNAIL_SIZE = 512const coverThumbnailListeners = new WeakMap<EditorStore, () => void>()let nextTabId = 1@@ -359,8 +357,8 @@ async function showImportedGraph(async function cacheOpenedFigCover(path: string, store: EditorStore): Promise<void> {if (await loadCachedRecentFileThumbnail(path)) return- const thumbnailPageId = figThumbnailPageId(store.graph.getPages())- if (!thumbnailPageId) return+ // A document without a page has no cover, so it never waits for a renderer.+ if (!figThumbnailPageId(store.graph.getPages())) returnfor (let attempt = 0; attempt < 240 && !store.renderer; attempt++) {await promiseTimeout(250)}@@ -369,19 +367,9 @@ async function cacheOpenedFigCover(path: string, store: EditorStore): Promise<voconsole.warn('[Recent files] Thumbnail skipped because the renderer was unavailable')return}- const bytes = renderThumbnail(- renderer.ck,- renderer,- store.graph,- thumbnailPageId,- RECENT_FILE_THUMBNAIL_SIZE,- RECENT_FILE_THUMBNAIL_SIZE- )- if (!bytes) {+ if (!(await cacheRecentFileCover(path, store.graph, renderer))) {console.warn('[Recent files] Thumbnail skipped because its page was empty')- return}- await cacheRecentFileThumbnail(path, bytes)}function watchOpenedFigCover(path: string, store: EditorStore): void {diff --git a/src/theme/home/document-entry.ts b/src/theme/home/document-entry.tsindex 9f402d171..6476bd0d6 100644--- a/src/theme/home/document-entry.ts+++ b/src/theme/home/document-entry.ts@@ -7,7 +7,7 @@ export default {'min-w-0 w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 disabled:opacity-50',preview:'flex aspect-video items-center justify-center overflow-hidden rounded-lg border border-border bg-panel-field transition-colors group-hover:border-panel-focus',- image: 'size-full object-cover transition-transform duration-200 group-hover:scale-[1.015]',+ image: 'size-full object-contain transition-transform duration-200 group-hover:scale-[1.015]',fallback: 'size-8 text-muted/40',icon: 'size-4 shrink-0 text-primary',kind: 'size-3.5 shrink-0',