Skip to content

AI-native design editor. Open-source Figma alternative.

feat(app): add recent files workspace

Victor Wads52a8e5da6258
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a837b94fd..c17614e6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Added
+- Open to a recent-files home screen with embedded `.fig` previews and grid or list layouts.
- Add deterministic two-browser collaboration coverage for bidirectional edits, awareness, departure cleanup, partitioned-peer convergence, and reconnect synchronization without public network dependencies. (#530)
- Import, render, edit, resize, select, and export Figma text-on-path layers while preserving their curved glyph layout.
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index 85f7b4fbf..a37c87abe 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -12,6 +12,10 @@
"label": "Open…",
"accelerator": "CmdOrCtrl+O"
},
+ {
+ "id": "open-recent",
+ "label": "Open Recent"
+ },
{
"id": "open-storage-workspace",
"label": "Open Storage Workspace…"
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index 4a88c8e0a..0de23f00f 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -41,6 +41,11 @@ fn take_pending_open(state: tauri::State<PendingOpen>) -> Vec<PendingOpenFile> {
.unwrap_or_default()
}
+#[tauri::command]
+fn set_recent_files(app: tauri::AppHandle, paths: Vec<String>) -> Result<(), String> {
+ install_app_menu(&app, &paths).map_err(|error| error.to_string())
+}
+
#[tauri::command]
fn mcp_executable_available() -> bool {
which::which("openpencil-mcp-http").is_ok()
@@ -145,6 +150,7 @@ pub fn run() {
list_system_fonts,
load_system_font,
proxy_http_request,
+ set_recent_files,
take_pending_open
])
.plugin(tauri_plugin_opener::init())
@@ -159,7 +165,7 @@ pub fn run() {
})
.setup(|app| {
queue_open_paths(app.handle(), startup_open_paths());
- Ok(install_app_menu(app)?)
+ Ok(install_app_menu(app.handle(), &[])?)
})
.build(tauri::generate_context!())
.expect("error while building tauri application")
diff --git a/desktop/src/menu.rs b/desktop/src/menu.rs
index 0f3b05f31..d05f909c7 100644
--- a/desktop/src/menu.rs
+++ b/desktop/src/menu.rs
@@ -1,4 +1,5 @@
use serde::Deserialize;
+use std::path::Path;
use tauri::menu::{MenuBuilder, MenuItemBuilder, Submenu, SubmenuBuilder};
#[cfg(any(target_os = "macos", target_os = "windows"))]
@@ -25,6 +26,7 @@ fn build_submenu<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
label: &str,
items: &[MenuEntry],
+ recent_files: &[String],
) -> tauri::Result<Submenu<R>> {
let mut builder = SubmenuBuilder::new(app, label);
@@ -35,8 +37,13 @@ fn build_submenu<R: tauri::Runtime>(
}
let label = entry.label.as_deref().unwrap_or_default();
+ if entry.id.as_deref() == Some("open-recent") {
+ let submenu = build_recent_files_submenu(app, label, recent_files)?;
+ builder = builder.item(&submenu);
+ continue;
+ }
if !entry.sub.is_empty() {
- let submenu = build_submenu(app, label, &entry.sub)?;
+ let submenu = build_submenu(app, label, &entry.sub, recent_files)?;
builder = builder.item(&submenu);
continue;
}
@@ -80,17 +87,58 @@ fn build_submenu<R: tauri::Runtime>(
builder.build()
}
+fn recent_file_label(path: &str) -> String {
+ let path = Path::new(path);
+ let name = path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .map(str::to_owned)
+ .unwrap_or_else(|| path.as_os_str().to_string_lossy().into_owned());
+ let parent = path
+ .parent()
+ .and_then(Path::file_name)
+ .and_then(|name| name.to_str());
+ parent.map_or(name.clone(), |parent| format!("{name} — {parent}"))
+}
+
+fn build_recent_files_submenu<R: tauri::Runtime>(
+ app: &tauri::AppHandle<R>,
+ label: &str,
+ recent_files: &[String],
+) -> tauri::Result<Submenu<R>> {
+ let mut builder =
+ SubmenuBuilder::with_id(app, "open-recent", label).enabled(!recent_files.is_empty());
+ for (index, path) in recent_files.iter().enumerate() {
+ let item = MenuItemBuilder::new(recent_file_label(path))
+ .id(format!("open-recent:{index}"))
+ .build(app)?;
+ builder = builder.item(&item);
+ }
+ if !recent_files.is_empty() {
+ builder = builder.separator().item(
+ &MenuItemBuilder::new("Clear Menu")
+ .id("clear-recent-files")
+ .build(app)?,
+ );
+ }
+ builder.build()
+}
+
fn build_schema_menus<R: tauri::Runtime>(
app: &tauri::AppHandle<R>,
+ recent_files: &[String],
) -> tauri::Result<Vec<Submenu<R>>> {
let groups: Vec<MenuGroup> = serde_json::from_str(include_str!("../generated/menu.json"))?;
groups
.iter()
- .map(|group| build_submenu(app, &group.label, &group.items))
+ .map(|group| build_submenu(app, &group.label, &group.items, recent_files))
.collect()
}
-pub fn install_app_menu<R: tauri::Runtime>(app: &mut tauri::App<R>) -> tauri::Result<()> {
+pub fn install_app_menu<R: tauri::Runtime>(
+ app: &tauri::AppHandle<R>,
+ recent_files: &[String],
+) -> tauri::Result<()> {
#[cfg(target_os = "macos")]
let app_menu = SubmenuBuilder::new(app, "OpenPencil")
.item(&PredefinedMenuItem::about(
@@ -113,8 +161,7 @@ pub fn install_app_menu<R: tauri::Runtime>(app: &mut tauri::App<R>) -> tauri::Re
.item(&PredefinedMenuItem::quit(app, None)?)
.build()?;
- let handle = app.handle().clone();
- let schema_menus = build_schema_menus(&handle)?;
+ let schema_menus = build_schema_menus(app, recent_files)?;
let mut builder = MenuBuilder::new(app);
#[cfg(target_os = "macos")]
diff --git a/packages/vue/src/i18n/locales/de/dialogs.json b/packages/vue/src/i18n/locales/de/dialogs.json
index 21d32a02b..b50066c50 100644
--- a/packages/vue/src/i18n/locales/de/dialogs.json
+++ b/packages/vue/src/i18n/locales/de/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Noch keine gespeicherten Dokumente.",
"loadingDocuments": "Dokumente werden geladen…",
"storageNotConfigured": "Konfiguriere den Speicher, bevor du diesen Arbeitsbereich verwendest.",
+ "recentFiles": "Zuletzt verwendete Dateien",
+ "recentFilesDescription": "Arbeite an einem Entwurf weiter oder beginne einen neuen.",
+ "noRecentFiles": "Noch keine zuletzt verwendeten Dateien",
+ "noRecentFilesDescription": "Dateien, die du in der Desktop-App öffnest, werden hier angezeigt.",
"copyStorageCors": "CORS-JSON kopieren",
"storageEndpoint": "Endpunkt",
"storageBucket": "Bucket",
diff --git a/packages/vue/src/i18n/locales/es/dialogs.json b/packages/vue/src/i18n/locales/es/dialogs.json
index c311578a6..a8857669e 100644
--- a/packages/vue/src/i18n/locales/es/dialogs.json
+++ b/packages/vue/src/i18n/locales/es/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Aún no hay documentos guardados.",
"loadingDocuments": "Cargando documentos…",
"storageNotConfigured": "Configura el almacenamiento antes de usar este espacio.",
+ "recentFiles": "Archivos recientes",
+ "recentFilesDescription": "Continúa trabajando en un diseño o crea uno nuevo.",
+ "noRecentFiles": "Aún no hay archivos recientes",
+ "noRecentFilesDescription": "Los archivos que abras en la aplicación de escritorio aparecerán aquí.",
"copyStorageCors": "Copiar JSON de CORS",
"storageEndpoint": "Punto de conexión",
"storageBucket": "Bucket",
diff --git a/packages/vue/src/i18n/locales/fr/dialogs.json b/packages/vue/src/i18n/locales/fr/dialogs.json
index 2cf51869f..4da5f9d2f 100644
--- a/packages/vue/src/i18n/locales/fr/dialogs.json
+++ b/packages/vue/src/i18n/locales/fr/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Aucun document stocké pour le moment.",
"loadingDocuments": "Chargement des documents…",
"storageNotConfigured": "Configurez le stockage avant d’utiliser cet espace.",
+ "recentFiles": "Fichiers récents",
+ "recentFilesDescription": "Continuez un design ou commencez-en un nouveau.",
+ "noRecentFiles": "Aucun fichier récent",
+ "noRecentFilesDescription": "Les fichiers ouverts dans l’application de bureau apparaîtront ici.",
"copyStorageCors": "Copier le JSON CORS",
"storageEndpoint": "Point de terminaison",
"storageBucket": "Bucket",
diff --git a/packages/vue/src/i18n/locales/it/dialogs.json b/packages/vue/src/i18n/locales/it/dialogs.json
index bcc990b36..da549cb68 100644
--- a/packages/vue/src/i18n/locales/it/dialogs.json
+++ b/packages/vue/src/i18n/locales/it/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Nessun documento archiviato.",
"loadingDocuments": "Caricamento documenti…",
"storageNotConfigured": "Configura l’archiviazione prima di usare quest’area.",
+ "recentFiles": "File recenti",
+ "recentFilesDescription": "Continua a lavorare su un progetto o iniziane uno nuovo.",
+ "noRecentFiles": "Nessun file recente",
+ "noRecentFilesDescription": "I file aperti nell’app desktop appariranno qui.",
"copyStorageCors": "Copia JSON CORS",
"storageEndpoint": "Endpoint",
"storageBucket": "Bucket",
diff --git a/packages/vue/src/i18n/locales/ja/dialogs.json b/packages/vue/src/i18n/locales/ja/dialogs.json
index 501f9667e..e124a68da 100644
--- a/packages/vue/src/i18n/locales/ja/dialogs.json
+++ b/packages/vue/src/i18n/locales/ja/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "保存されたドキュメントはまだありません。",
"loadingDocuments": "ドキュメントを読み込み中…",
"storageNotConfigured": "このワークスペースを使用する前にストレージを設定してください。",
+ "recentFiles": "最近使用したファイル",
+ "recentFilesDescription": "デザインの作業を続けるか、新しく始めます。",
+ "noRecentFiles": "最近使用したファイルはありません",
+ "noRecentFilesDescription": "デスクトップアプリで開いたファイルがここに表示されます。",
"copyStorageCors": "CORS JSONをコピー",
"storageEndpoint": "エンドポイント",
"storageBucket": "バケット",
diff --git a/packages/vue/src/i18n/locales/pl/dialogs.json b/packages/vue/src/i18n/locales/pl/dialogs.json
index 86a8ba051..1cb9a0fcd 100644
--- a/packages/vue/src/i18n/locales/pl/dialogs.json
+++ b/packages/vue/src/i18n/locales/pl/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Brak zapisanych dokumentów.",
"loadingDocuments": "Ładowanie dokumentów…",
"storageNotConfigured": "Skonfiguruj przechowywanie przed użyciem tego obszaru.",
+ "recentFiles": "Ostatnie pliki",
+ "recentFilesDescription": "Kontynuuj pracę nad projektem lub rozpocznij nowy.",
+ "noRecentFiles": "Brak ostatnich plików",
+ "noRecentFilesDescription": "Pliki otwarte w aplikacji komputerowej pojawią się tutaj.",
"copyStorageCors": "Kopiuj JSON CORS",
"storageEndpoint": "Punkt końcowy",
"storageBucket": "Zasobnik",
diff --git a/packages/vue/src/i18n/locales/ru/dialogs.json b/packages/vue/src/i18n/locales/ru/dialogs.json
index 151abc177..4dd9065e6 100644
--- a/packages/vue/src/i18n/locales/ru/dialogs.json
+++ b/packages/vue/src/i18n/locales/ru/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "Сохранённых документов пока нет.",
"loadingDocuments": "Загрузка документов…",
"storageNotConfigured": "Настройте хранилище перед использованием этой области.",
+ "recentFiles": "Недавние файлы",
+ "recentFilesDescription": "Продолжите работу над дизайном или начните новый.",
+ "noRecentFiles": "Недавних файлов пока нет",
+ "noRecentFilesDescription": "Файлы, открытые в приложении для компьютера, появятся здесь.",
"copyStorageCors": "Скопировать JSON CORS",
"storageEndpoint": "Конечная точка",
"storageBucket": "Бакет",
diff --git a/packages/vue/src/i18n/locales/zh-cn/dialogs.json b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
index defa84e2c..3b9f075a5 100644
--- a/packages/vue/src/i18n/locales/zh-cn/dialogs.json
+++ b/packages/vue/src/i18n/locales/zh-cn/dialogs.json
@@ -145,6 +145,10 @@
"emptyStorageWorkspace": "暂无已存储的文档。",
"loadingDocuments": "正在加载文档…",
"storageNotConfigured": "请先配置存储,再使用此工作区。",
+ "recentFiles": "最近使用的文件",
+ "recentFilesDescription": "继续编辑设计或新建设计。",
+ "noRecentFiles": "暂无最近使用的文件",
+ "noRecentFilesDescription": "在桌面应用中打开的文件会显示在这里。",
"copyStorageCors": "复制 CORS JSON",
"storageEndpoint": "端点",
"storageBucket": "存储桶",
diff --git a/packages/vue/src/i18n/messages/dialogs.ts b/packages/vue/src/i18n/messages/dialogs.ts
index 29d463dce..bf904f7b9 100644
--- a/packages/vue/src/i18n/messages/dialogs.ts
+++ b/packages/vue/src/i18n/messages/dialogs.ts
@@ -234,6 +234,10 @@ export const dialogMessageDefaults = {
emptyStorageWorkspace: 'No stored documents yet.',
loadingDocuments: 'Loading documents…',
storageNotConfigured: 'Configure storage before using this workspace.',
+ recentFiles: 'Recent files',
+ recentFilesDescription: 'Continue working on a design or start a new one.',
+ noRecentFiles: 'No recent files yet',
+ noRecentFilesDescription: 'Files you open in the desktop app will appear here.',
copyStorageCors: 'Copy CORS JSON',
storageEndpoint: 'Endpoint',
storageBucket: 'Bucket',
diff --git a/src/app/shell/menu/editor.ts b/src/app/shell/menu/editor.ts
index 7e2c7697b..d9fef1e58 100644
--- a/src/app/shell/menu/editor.ts
+++ b/src/app/shell/menu/editor.ts
@@ -3,8 +3,15 @@ import type { EditorCommandId } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { createSharedEditorMenuActions } from '@/app/shell/menu/editor-actions'
-import { openFileDialog } from '@/app/shell/menu/files'
+import { openFileDialog, openFileFromPath } from '@/app/shell/menu/files'
import { useNativeMenuEvents } from '@/app/shell/menu/native-events'
+import {
+ clearRecentFiles,
+ forgetRecentFile,
+ OPEN_RECENT_EVENT_PREFIX,
+ recentFileAt,
+ syncRecentFilesMenu
+} from '@/app/shell/menu/recent-files'
import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'
import { createSelectionMenuActions } from '@/app/shell/menu/selection-actions'
import { SHELL_MENU_IDS } from '@/app/shell/menu/shell'
@@ -27,6 +34,10 @@ const COMMAND_MENU_IDS = new Set<EditorCommandId>(
export function useEditorMenu() {
if (!isTauri()) return
+ void syncRecentFilesMenu().catch((error) => {
+ console.warn('[Recent files] Failed to initialize the native menu', error)
+ })
+
const { setTheme } = useAppTheme()
const { runCommand } = useEditorCommands()
@@ -61,6 +72,21 @@ export function useEditorMenu() {
}
useNativeMenuEvents((id) => {
+ if (id === 'clear-recent-files') {
+ clearRecentFiles()
+ return
+ }
+ if (id.startsWith(OPEN_RECENT_EVENT_PREFIX)) {
+ const index = Number(id.slice(OPEN_RECENT_EVENT_PREFIX.length))
+ const path = Number.isInteger(index) ? recentFileAt(index) : null
+ if (path) {
+ void openFileFromPath(path).catch((error) => {
+ forgetRecentFile(path)
+ console.warn('[Recent files] Failed to open file', error)
+ })
+ }
+ return
+ }
if (SHELL_MENU_IDS.has(id)) return
if (COMMAND_MENU_IDS.has(id as EditorCommandId)) {
runCommand(id as EditorCommandId)
diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.ts
index c3c2e1a2a..42ec0446d 100644
--- a/src/app/shell/menu/files.ts
+++ b/src/app/shell/menu/files.ts
@@ -2,6 +2,7 @@ import { useFileDialog } from '@vueuse/core'
import { setOpenPencilOpenFileHandler } from '@/app/browser-bridge'
import { resolveBrowserFileURL } from '@/app/document/io/browser'
+import { rememberRecentFile } from '@/app/shell/menu/recent-files'
import { openFileInNewTab } from '@/app/tabs'
import { isTauri } from '@/app/tauri/env'
import { IS_BROWSER } from '@/constants'
@@ -47,6 +48,7 @@ export async function openFileFromPath(path: string) {
if (!isTauri()) return
const file = await readTauriDesignFile(path)
await openFileInNewTab(file, undefined, path)
+ rememberRecentFile(path)
}
export async function openFileDialog() {
diff --git a/src/app/shell/menu/recent-files.ts b/src/app/shell/menu/recent-files.ts
new file mode 100644
index 000000000..35427178a
--- /dev/null
+++ b/src/app/shell/menu/recent-files.ts
@@ -0,0 +1,92 @@
+import { useLocalStorage } from '@vueuse/core'
+import { computed } from 'vue'
+
+import { extractFigThumbnailFromReader } from '@open-pencil/fig'
+
+import { isTauri } from '@/app/tauri/env'
+
+const MAX_RECENT_FILES = 10
+const RECENT_FILES_STORAGE_KEY = 'open-pencil:recent-files'
+const RECENT_FILE_OPENED_AT_STORAGE_KEY = 'open-pencil:recent-file-opened-at'
+
+export type RecentFile = {
+ id: string
+ path: string
+ name: string
+ updatedAt: string
+}
+
+export const OPEN_RECENT_EVENT_PREFIX = 'open-recent:'
+export const recentFilePaths = useLocalStorage<string[]>(RECENT_FILES_STORAGE_KEY, [])
+const recentFileOpenedAt = useLocalStorage<Record<string, string>>(
+ RECENT_FILE_OPENED_AT_STORAGE_KEY,
+ {}
+)
+
+function fileName(path: string): string {
+ return path.split(/[\\/]/).pop() ?? path
+}
+
+export const recentFiles = computed<RecentFile[]>(() =>
+ normalizedRecentFiles().map((path) => ({
+ id: path,
+ path,
+ name: fileName(path),
+ updatedAt: recentFileOpenedAt.value[path] ?? new Date(0).toISOString()
+ }))
+)
+
+function normalizedRecentFiles(): string[] {
+ return recentFilePaths.value
+ .filter((path): path is string => typeof path === 'string' && path.length > 0)
+ .slice(0, MAX_RECENT_FILES)
+}
+
+export async function syncRecentFilesMenu(): Promise<void> {
+ if (!isTauri()) return
+ const { invoke } = await import('@tauri-apps/api/core')
+ await invoke('set_recent_files', { paths: normalizedRecentFiles() })
+}
+
+function updateRecentFiles(paths: string[]): void {
+ recentFilePaths.value = paths.slice(0, MAX_RECENT_FILES)
+ void syncRecentFilesMenu().catch((error) => {
+ console.warn('[Recent files] Failed to update the native menu', error)
+ })
+}
+
+export function rememberRecentFile(path: string): void {
+ recentFileOpenedAt.value = {
+ ...recentFileOpenedAt.value,
+ [path]: new Date().toISOString()
+ }
+ updateRecentFiles([path, ...normalizedRecentFiles().filter((recent) => recent !== path)])
+}
+
+export function forgetRecentFile(path: string): void {
+ recentFileOpenedAt.value = Object.fromEntries(
+ Object.entries(recentFileOpenedAt.value).filter(([recent]) => recent !== path)
+ )
+ updateRecentFiles(normalizedRecentFiles().filter((recent) => recent !== path))
+}
+
+export function clearRecentFiles(): void {
+ recentFileOpenedAt.value = {}
+ updateRecentFiles([])
+}
+
+export function recentFileAt(index: number): string | null {
+ return normalizedRecentFiles()[index] ?? null
+}
+
+export async function loadRecentFileThumbnail(path: string): Promise<Uint8Array | null> {
+ if (!isTauri() || !path.toLowerCase().endsWith('.fig')) return null
+ 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)
+ }
+ })
+}
diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.ts
index 2eb06c0b7..dc07f90d6 100644
--- a/src/app/shell/menu/schema.ts
+++ b/src/app/shell/menu/schema.ts
@@ -35,6 +35,7 @@ export const APP_MENU_SCHEMA = [
items: [
{ id: 'new', label: 'New', shortcut: 'MOD+N' },
{ id: 'open', label: 'Open…', shortcut: 'MOD+O' },
+ { id: 'open-recent', label: 'Open Recent', target: 'native' },
{ id: 'open-storage-workspace', label: 'Open Storage Workspace…', handler: 'shell' },
{ type: 'separator' },
{ id: 'save', label: 'Save', shortcut: 'MOD+S' },
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index fc3cd23e1..b66b3f30d 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -24,6 +24,7 @@ import { findTabByFileIdentity } from '@/app/tabs/open/identity'
export interface Tab {
id: string
store: EditorStore
+ showHome: boolean
}
const io = new IORegistry(BUILTIN_IO_FORMATS)
@@ -70,14 +71,21 @@ export function getTabsSnapshot(): Tab[] {
return [...tabsRef.value]
}
-export function createTab(store?: EditorStore, initialGraph?: SceneGraph): Tab {
+export function createTab(store?: EditorStore, initialGraph?: SceneGraph, showHome = false): Tab {
const s = store ?? createEditorStore(initialGraph)
- const tab: Tab = { id: generateTabId(), store: s }
+ const tab: Tab = { id: generateTabId(), store: s, showHome }
tabsRef.value = [...tabsRef.value, tab]
activateTab(tab)
return tab
}
+export function leaveHome(tabId: string): void {
+ const tabIndex = tabsRef.value.findIndex((candidate) => candidate.id === tabId)
+ const tab = tabsRef.value[tabIndex]
+ if (!tab?.showHome) return
+ tabsRef.value = tabsRef.value.with(tabIndex, { ...tab, showHome: false })
+}
+
function activateTab(tab: Tab) {
activeTabId.value = tab.id
setActiveEditorStore(tab.store)
@@ -102,7 +110,7 @@ export async function closeTab(tabId: string): Promise<void> {
tabsRef.value = tabsRef.value.filter((t) => t.id !== tabId)
if (tabsRef.value.length === 0) {
- createTab()
+ createTab(undefined, undefined, true)
return
}
@@ -126,7 +134,11 @@ function reusableTabStore(): EditorStore {
const current = activeTab.value
const isUntouched =
current?.store.state.documentName === 'Untitled' && !current.store.undo.canUndo
- return isUntouched ? current.store : createTab().store
+ if (isUntouched) {
+ leaveHome(current.id)
+ return current.store
+ }
+ return createTab().store
}
async function readFigForTab(file: File, store: EditorStore): Promise<SceneGraph> {
@@ -315,6 +327,7 @@ export function useTabsStore() {
tabs: allTabs,
activeTabId,
createTab,
+ leaveHome,
switchTab,
closeTab,
getActiveTabId,
diff --git a/src/components/recent-files/RecentFilesHome.vue b/src/components/recent-files/RecentFilesHome.vue
new file mode 100644
index 000000000..e27e9e52b
--- /dev/null
+++ b/src/components/recent-files/RecentFilesHome.vue
@@ -0,0 +1,179 @@
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useLocalStorage } from '@vueuse/core'
+
+import { useDocumentWorkspace, useI18n } from '@open-pencil/vue'
+
+import {
+ forgetRecentFile,
+ loadRecentFileThumbnail,
+ recentFiles,
+ type RecentFile
+} from '@/app/shell/menu/recent-files'
+import { openFileDialog, openFileFromPath } from '@/app/shell/menu/use'
+
+const emit = defineEmits<{ 'new-document': [] }>()
+const { dialogs, menu, panels, locale } = useI18n()
+const view = useLocalStorage<'grid' | 'list'>('open-pencil:recent-files-view', 'grid')
+const openError = ref<string | null>(null)
+
+const workspace = useDocumentWorkspace<RecentFile>({
+ source: {
+ async refresh() {
+ return recentFiles.value
+ },
+ loadPreview: loadRecentFileThumbnail
+ },
+ refreshOnFocus: false,
+ refreshOnReconnect: false,
+ previewConcurrency: 2
+})
+
+const documents = workspace.documents
+const previewURL = workspace.previewURL
+const vWorkspacePreview = workspace.previewDirective
+const hasRecentFiles = computed(() => documents.value.length > 0)
+
+watch(recentFiles, () => void workspace.invalidate())
+
+async function openRecent(document: RecentFile): Promise<void> {
+ openError.value = null
+ try {
+ await openFileFromPath(document.path)
+ } catch (error) {
+ forgetRecentFile(document.path)
+ openError.value = error instanceof Error ? error.message : String(error)
+ }
+}
+
+function formattedDate(updatedAt: string): string {
+ const date = new Date(updatedAt)
+ if (date.getTime() === 0) return ''
+ return date.toLocaleString(locale.value)
+}
+</script>
+
+<template>
+ <main class="flex min-h-0 flex-1 flex-col bg-app text-surface" data-test-id="recent-files-home">
+ <header class="flex h-14 shrink-0 items-center border-b border-border px-6">
+ <div class="flex items-center gap-2.5">
+ <img src="/favicon-32.png" class="size-5" alt="" />
+ <span class="text-sm font-semibold">OpenPencil</span>
+ </div>
+ <div class="ml-auto flex items-center gap-2">
+ <button
+ type="button"
+ class="rounded px-3 py-1.5 text-xs text-muted hover:bg-hover hover:text-surface"
+ data-test-id="home-open-file"
+ @click="openFileDialog"
+ >
+ <icon-lucide-folder-open class="mr-1.5 inline size-3.5" />
+ {{ menu.open }}
+ </button>
+ <button
+ type="button"
+ class="rounded bg-accent px-3 py-1.5 text-xs font-medium text-white hover:bg-accent/90"
+ data-test-id="home-new-document"
+ @click="emit('new-document')"
+ >
+ <icon-lucide-plus class="mr-1 inline size-3.5" />
+ {{ menu.new }}
+ </button>
+ </div>
+ </header>
+
+ <section class="mx-auto flex min-h-0 w-full max-w-7xl flex-1 flex-col px-8 py-10">
+ <div class="mb-6 flex items-center">
+ <div>
+ <h1 class="text-xl font-semibold">{{ dialogs.recentFiles }}</h1>
+ <p class="mt-1 text-xs text-muted">{{ dialogs.recentFilesDescription }}</p>
+ </div>
+ <div v-if="hasRecentFiles" class="ml-auto flex rounded border border-border p-0.5">
+ <button
+ type="button"
+ class="flex size-7 items-center justify-center rounded-sm text-muted hover:text-surface"
+ :class="{ 'bg-hover text-surface': view === 'grid' }"
+ :aria-label="panels.gridView"
+ @click="view = 'grid'"
+ >
+ <icon-lucide-layout-grid class="size-3.5" />
+ </button>
+ <button
+ type="button"
+ class="flex size-7 items-center justify-center rounded-sm text-muted hover:text-surface"
+ :class="{ 'bg-hover text-surface': view === 'list' }"
+ :aria-label="panels.listView"
+ @click="view = 'list'"
+ >
+ <icon-lucide-list class="size-3.5" />
+ </button>
+ </div>
+ </div>
+
+ <p v-if="openError" class="mb-4 text-xs text-danger" role="alert">{{ openError }}</p>
+
+ <div
+ v-if="hasRecentFiles && view === 'grid'"
+ class="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-5"
+ >
+ <button
+ v-for="document in documents"
+ :key="document.path"
+ type="button"
+ class="group overflow-hidden rounded-lg border border-border bg-panel text-left transition-colors hover:border-panel-focus hover:bg-hover"
+ @click="openRecent(document)"
+ >
+ <div
+ v-workspace-preview="document.path"
+ class="flex aspect-[4/3] items-center justify-center overflow-hidden bg-panel-field"
+ >
+ <img
+ v-if="previewURL(document.path)"
+ :src="previewURL(document.path) ?? undefined"
+ alt=""
+ class="size-full object-cover transition-transform duration-200 group-hover:scale-[1.015]"
+ />
+ <icon-lucide-file-image v-else class="size-8 text-muted/40" />
+ </div>
+ <div class="border-t border-border p-3">
+ <p class="truncate text-xs font-medium">{{ document.name }}</p>
+ <p class="mt-1 truncate text-[10px] text-muted">
+ {{ formattedDate(document.updatedAt) }}
+ </p>
+ </div>
+ </button>
+ </div>
+
+ <div v-else-if="hasRecentFiles" class="overflow-hidden rounded-lg border border-border">
+ <button
+ v-for="document in documents"
+ :key="document.path"
+ type="button"
+ class="flex w-full items-center gap-3 border-b border-border px-4 py-3 text-left last:border-b-0 hover:bg-hover"
+ @click="openRecent(document)"
+ >
+ <icon-lucide-file-image class="size-4 shrink-0 text-accent" />
+ <span class="min-w-0 flex-1 truncate text-xs font-medium">{{ document.name }}</span>
+ <span class="shrink-0 text-[10px] text-muted">{{
+ formattedDate(document.updatedAt)
+ }}</span>
+ </button>
+ </div>
+
+ <div v-else class="flex flex-1 flex-col items-center justify-center pb-20 text-center">
+ <div class="mb-4 flex size-12 items-center justify-center rounded-xl bg-panel-field">
+ <icon-lucide-files class="size-5 text-muted" />
+ </div>
+ <p class="text-sm font-medium">{{ dialogs.noRecentFiles }}</p>
+ <p class="mt-1 max-w-sm text-xs text-muted">{{ dialogs.noRecentFilesDescription }}</p>
+ <button
+ type="button"
+ class="mt-5 rounded border border-border px-3 py-1.5 text-xs hover:bg-hover"
+ @click="openFileDialog"
+ >
+ {{ menu.open }}
+ </button>
+ </div>
+ </section>
+ </main>
+</template>
diff --git a/src/views/EditorView.vue b/src/views/EditorView.vue
index 60dce7059..ba9b2cb6b 100644
--- a/src/views/EditorView.vue
+++ b/src/views/EditorView.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { onMounted, onUnmounted, provide, ref } from 'vue'
+import { computed, onMounted, onUnmounted, provide, ref } from 'vue'
import { tv } from 'tailwind-variants'
import { useEventListener, useUrlSearchParams } from '@vueuse/core'
import { useRoute } from 'vue-router'
@@ -18,7 +18,7 @@ import { isTauri } from '@/app/tauri/env'
import { appMenuShortcut } from '@/app/shell/menu/shortcut'
import { createDemoShapes } from '@/app/demo/document'
import { useEditorStore } from '@/app/editor/active-store'
-import { createTab, activeTab, getActiveStore, tabCount } from '@/app/tabs'
+import { createTab, activeTab, getActiveStore, leaveHome, tabCount } from '@/app/tabs'
import CollabPanel from '@/components/CollabPanel/CollabPanel.vue'
import EditorCanvas from '@/components/EditorCanvas.vue'
@@ -28,6 +28,7 @@ import LayersPanel from '@/components/LayersPanel.vue'
import MobileDrawer from '@/components/MobileDrawer.vue'
import MobileHud from '@/components/MobileHud/MobileHud.vue'
import PropertiesPanel from '@/components/PropertiesPanel.vue'
+import RecentFilesHome from '@/components/recent-files/RecentFilesHome.vue'
import RenameSelectionDialog from '@/components/selection/RenameSelectionDialog.vue'
import SafariBanner from '@/components/SafariBanner.vue'
import TabBar from '@/components/TabBar.vue'
@@ -40,7 +41,11 @@ const params = useUrlSearchParams('history')
const showChrome = !('no-chrome' in params)
const createdInitialTab = tabCount() === 0
-const firstTab = createdInitialTab ? createTab() : (activeTab.value ?? createTab())
+const showInitialHome =
+ route.path === '/' && !('test' in params) && (isTauri() || 'recent-files' in params)
+const firstTab = createdInitialTab
+ ? createTab(undefined, undefined, showInitialHome)
+ : (activeTab.value ?? createTab())
const store = useEditorStore()
const { dialogs } = useI18n()
const { isMobile } = useViewportKind()
@@ -71,6 +76,7 @@ const mcpCleanup = ref<(() => void) | null>(null)
const fileAssociationCleanup = ref<(() => void) | null>(null)
const initialEditorLayout = loadEditorLayout()
const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })
+const showingHome = computed(() => activeTab.value?.showHome === true)
type PendingOpenFile = {
path: string
@@ -120,11 +126,12 @@ onUnmounted(() => {
<SafariBanner />
<FontStatusBanner />
<RenameSelectionDialog />
- <TabBar />
+ <RecentFilesHome v-if="showingHome" @new-document="activeTab && leaveHome(activeTab.id)" />
+ <TabBar v-if="!showingHome" />
<!-- Desktop layout -->
<SplitterGroup
- v-if="!isMobile && showChrome && store.state.showUI"
+ v-if="!showingHome && !isMobile && showChrome && store.state.showUI"
:key="activeTab?.id"
direction="horizontal"
class="flex-1 overflow-hidden"
@@ -172,7 +179,7 @@ onUnmounted(() => {
<!-- Mobile layout -->
<div
- v-else-if="isMobile && showChrome && store.state.showUI"
+ v-else-if="!showingHome && isMobile && showChrome && store.state.showUI"
:key="'mobile-' + activeTab?.id"
class="flex flex-1 overflow-hidden"
>
@@ -186,7 +193,7 @@ onUnmounted(() => {
<!-- Collapsed UI (showUI=false) -->
<div
- v-else-if="showChrome"
+ v-else-if="!showingHome && showChrome"
:key="'collapsed-' + activeTab?.id"
class="flex flex-1 overflow-hidden"
>
@@ -218,7 +225,11 @@ onUnmounted(() => {
</div>
<!-- Bare canvas (no chrome, e.g. ?no-chrome) -->
- <div v-else :key="'bare-' + activeTab?.id" class="flex flex-1 overflow-hidden">
+ <div
+ v-else-if="!showingHome"
+ :key="'bare-' + activeTab?.id"
+ class="flex flex-1 overflow-hidden"
+ >
<div class="relative flex min-w-0 flex-1">
<EditorCanvas />
</div>
diff --git a/tests/e2e/app/recent-files.spec.ts b/tests/e2e/app/recent-files.spec.ts
new file mode 100644
index 000000000..624e7793c
--- /dev/null
+++ b/tests/e2e/app/recent-files.spec.ts
@@ -0,0 +1,13 @@
+import { expect, test } from '#tests/e2e/fixtures'
+
+test('opens to the recent-files home and starts a new document', async ({ page }) => {
+ await page.goto('/?recent-files')
+
+ await expect(page.getByTestId('recent-files-home')).toBeVisible()
+ await expect(page.getByText('No recent files yet')).toBeVisible()
+
+ await page.getByTestId('home-new-document').click()
+
+ await expect(page.getByTestId('recent-files-home')).toBeHidden()
+ await expect(page.getByRole('group', { name: 'Layers' })).toBeVisible()
+})
diff --git a/tests/engine/app/shell/menu/recent-files.test.ts b/tests/engine/app/shell/menu/recent-files.test.ts
new file mode 100644
index 000000000..3fd184b28
--- /dev/null
+++ b/tests/engine/app/shell/menu/recent-files.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import {
+ clearRecentFiles,
+ forgetRecentFile,
+ recentFileAt,
+ recentFilePaths,
+ recentFiles,
+ rememberRecentFile
+} from '@/app/shell/menu/recent-files'
+
+afterEach(() => clearRecentFiles())
+
+describe('recent files', () => {
+ test('keeps the latest file first without duplicates', () => {
+ recentFilePaths.value = []
+
+ rememberRecentFile('/tmp/first.fig')
+ rememberRecentFile('/tmp/second.fig')
+ rememberRecentFile('/tmp/first.fig')
+
+ expect(recentFilePaths.value).toEqual(['/tmp/first.fig', '/tmp/second.fig'])
+ expect(recentFiles.value.map(({ id, name }) => ({ id, name }))).toEqual([
+ { id: '/tmp/first.fig', name: 'first.fig' },
+ { id: '/tmp/second.fig', name: 'second.fig' }
+ ])
+ expect(recentFileAt(0)).toBe('/tmp/first.fig')
+ })
+
+ test('forgets missing files and clears the list', () => {
+ recentFilePaths.value = ['/tmp/first.fig', '/tmp/second.fig']
+
+ forgetRecentFile('/tmp/first.fig')
+ expect(recentFilePaths.value).toEqual(['/tmp/second.fig'])
+
+ clearRecentFiles()
+ expect(recentFilePaths.value).toEqual([])
+ expect(recentFileAt(0)).toBeNull()
+ })
+})
diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.ts
index 2c8f48bd3..df09e3364 100644
--- a/tests/engine/app/shell/menu/schema.test.ts
+++ b/tests/engine/app/shell/menu/schema.test.ts
@@ -66,6 +66,15 @@ describe('APP_MENU_SCHEMA', () => {
)
})
+ test('exposes recent files through the native File menu', () => {
+ const fileMenu = APP_MENU_SCHEMA.find((group) => group.label === 'File')
+ const entries = fileMenu ? actionItems(fileMenu.items) : []
+
+ expect(entries).toContainEqual(
+ expect.objectContaining({ id: 'open-recent', label: 'Open Recent', target: 'native' })
+ )
+ })
+
test('keeps move-to-page destination selection in the browser menu', () => {
const objectMenu = APP_MENU_SCHEMA.find((group) => group.label === 'Object')
const entries = objectMenu ? actionItems(objectMenu.items) : []