Skip to content

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

feat: pin one Home tab first that never closes (#1493)

Danila Poyarkovb45526406e5d
diff --git a/changes/1493/changed.md b/changes/1493/changed.md
new file mode 100644
index 000000000..ff66f31a6
--- /dev/null
+++ b/changes/1493/changed.md
@@ -0,0 +1 @@
+- Home is one tab pinned first that never closes; designs open in tabs of their own, + starts a new design, and ⌘T shows Home.
diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.json
index 8557648d9..69d8d0f9b 100644
--- a/packages/vue/src/i18n/locales/de/files.json
+++ b/packages/vue/src/i18n/locales/de/files.json
@@ -11,6 +11,7 @@
"importing": "Wird importiert…",
"importToCanvas": "Auf die Arbeitsfläche importieren",
"newTab": "Neuer Tab",
+ "home": "Startseite",
"closeTab": "{name} schließen",
"clipboardImageUnavailableWeb": "Das eingefügte Design enthält 1 Bild, das in der Web-App nicht geladen werden kann. Verwende die Desktop-App, um es einzuschließen.",
"clipboardImagesUnavailableWeb": "Das eingefügte Design enthält {count} Bilder, die in der Web-App nicht geladen werden können. Verwende die Desktop-App, um sie einzuschließen.",
diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.json
index 3fc286f86..e935880b2 100644
--- a/packages/vue/src/i18n/locales/es/files.json
+++ b/packages/vue/src/i18n/locales/es/files.json
@@ -11,6 +11,7 @@
"importing": "Importando…",
"importToCanvas": "Importar al lienzo",
"newTab": "Nueva pestaña",
+ "home": "Inicio",
"closeTab": "Cerrar {name}",
"clipboardImageUnavailableWeb": "El diseño pegado contiene 1 imagen que no se puede cargar en la aplicación web. Usa la aplicación de escritorio para incluirla.",
"clipboardImagesUnavailableWeb": "El diseño pegado contiene {count} imágenes que no se pueden cargar en la aplicación web. Usa la aplicación de escritorio para incluirlas.",
diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.json
index 5313f0be1..fa67c6f4f 100644
--- a/packages/vue/src/i18n/locales/fr/files.json
+++ b/packages/vue/src/i18n/locales/fr/files.json
@@ -11,6 +11,7 @@
"importing": "Importation…",
"importToCanvas": "Importer dans le canevas",
"newTab": "Nouvel onglet",
+ "home": "Accueil",
"closeTab": "Fermer {name}",
"clipboardImageUnavailableWeb": "Le design collé contient 1 image qui ne peut pas être chargée dans l’application web. Utilisez l’application de bureau pour l’inclure.",
"clipboardImagesUnavailableWeb": "Le design collé contient {count} images qui ne peuvent pas être chargées dans l’application web. Utilisez l’application de bureau pour les inclure.",
diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.json
index 317d3096b..94f449c39 100644
--- a/packages/vue/src/i18n/locales/it/files.json
+++ b/packages/vue/src/i18n/locales/it/files.json
@@ -11,6 +11,7 @@
"importing": "Importazione…",
"importToCanvas": "Importa nell’area di lavoro",
"newTab": "Nuova scheda",
+ "home": "Pagina iniziale",
"closeTab": "Chiudi {name}",
"clipboardImageUnavailableWeb": "Il design incollato contiene 1 immagine che non può essere caricata nell’app web. Usa l’app desktop per includerla.",
"clipboardImagesUnavailableWeb": "Il design incollato contiene {count} immagini che non possono essere caricate nell’app web. Usa l’app desktop per includerle.",
diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.json
index 7d4e6093a..0234d7081 100644
--- a/packages/vue/src/i18n/locales/ja/files.json
+++ b/packages/vue/src/i18n/locales/ja/files.json
@@ -11,6 +11,7 @@
"importing": "インポート中…",
"importToCanvas": "キャンバスにインポート",
"newTab": "新しいタブ",
+ "home": "ホーム",
"closeTab": "{name} を閉じる",
"clipboardImageUnavailableWeb": "貼り付けたデザインには、ウェブアプリで読み込めない画像が1件含まれています。その画像を含めるにはデスクトップアプリを使用してください。",
"clipboardImagesUnavailableWeb": "貼り付けたデザインには、ウェブアプリで読み込めない画像が{count}件含まれています。それらの画像を含めるにはデスクトップアプリを使用してください。",
diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.json
index d5aa1ae4b..952397aec 100644
--- a/packages/vue/src/i18n/locales/pl/files.json
+++ b/packages/vue/src/i18n/locales/pl/files.json
@@ -11,6 +11,7 @@
"importing": "Importowanie…",
"importToCanvas": "Importuj na obszar roboczy",
"newTab": "Nowa karta",
+ "home": "Strona główna",
"closeTab": "Zamknij {name}",
"clipboardImageUnavailableWeb": "Wklejony projekt zawiera 1 obraz, którego nie można wczytać w aplikacji internetowej. Użyj aplikacji komputerowej, aby go dołączyć.",
"clipboardImagesUnavailableWeb": "Wklejony projekt zawiera {count} obrazy, których nie można wczytać w aplikacji internetowej. Użyj aplikacji komputerowej, aby je dołączyć.",
diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.json
index d28475a15..06000b666 100644
--- a/packages/vue/src/i18n/locales/ru/files.json
+++ b/packages/vue/src/i18n/locales/ru/files.json
@@ -11,6 +11,7 @@
"importing": "Импорт…",
"importToCanvas": "Импортировать на холст",
"newTab": "Новая вкладка",
+ "home": "Главная",
"closeTab": "Закрыть {name}",
"clipboardImageUnavailableWeb": "Вставленный дизайн содержит 1 изображение, которое нельзя загрузить в веб-приложении. Используйте настольное приложение, чтобы включить его.",
"clipboardImagesUnavailableWeb": "Вставленный дизайн содержит {count} изображений, которые нельзя загрузить в веб-приложении. Используйте настольное приложение, чтобы включить их.",
diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.json
index 3056836c6..72210265a 100644
--- a/packages/vue/src/i18n/locales/zh-cn/files.json
+++ b/packages/vue/src/i18n/locales/zh-cn/files.json
@@ -11,6 +11,7 @@
"importing": "正在导入…",
"importToCanvas": "导入到画布",
"newTab": "新标签页",
+ "home": "主页",
"closeTab": "关闭 {name}",
"clipboardImageUnavailableWeb": "粘贴的设计包含 1 张无法在网页应用中加载的图片。请使用桌面应用以包含该图片。",
"clipboardImagesUnavailableWeb": "粘贴的设计包含 {count} 张无法在网页应用中加载的图片。请使用桌面应用以包含这些图片。",
diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.ts
index 33e8d8918..0cca590b5 100644
--- a/packages/vue/src/i18n/messages/files.ts
+++ b/packages/vue/src/i18n/messages/files.ts
@@ -11,6 +11,7 @@ export const filesMessageDefaults = {
importing: 'Importing…',
importToCanvas: 'Import to canvas',
newTab: 'New tab',
+ home: 'Home',
closeTab: params('Close {name}'),
unsavedChanges: 'Unsaved changes',
saveBeforeClosing: params('Save changes to “{name}”?'),
diff --git a/src/app/recent-files/workspace.ts b/src/app/recent-files/workspace.ts
new file mode 100644
index 000000000..09869cd65
--- /dev/null
+++ b/src/app/recent-files/workspace.ts
@@ -0,0 +1,90 @@
+import { watch } from 'vue'
+
+import { useDocumentWorkspace } from '@open-pencil/vue/document/workspace'
+
+import {
+ createStorageAdapter,
+ sameStorageLocation,
+ storageLocationOf,
+ type StorageDocument
+} from '@/app/integrations/storage'
+import { openFileFromPath } from '@/app/shell/menu/use'
+import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'
+import { openStorageDocumentInNewTab } from '@/app/tabs'
+
+import { forgetRecentDocument, recentFiles, type RecentDocument } from './store'
+import { loadRecentFileThumbnail } from './thumbnails'
+
+/** The recent files with their previews, as Home and a New file tab list them. */
+export function useRecentFilesWorkspace() {
+ const workspace = useDocumentWorkspace<RecentDocument>({
+ source: {
+ async refresh() {
+ return recentFiles.value
+ },
+ loadPreview(documentId) {
+ const document = recentFiles.value.find((candidate) => candidate.id === documentId)
+ if (!document) return Promise.resolve(null)
+ if (document.kind === 'local') return loadRecentFileThumbnail(document.path)
+ return createStorageWorkspaceSource(
+ () => undefined,
+ () => storageLocationOf(document)
+ ).loadPreview(document.documentId)
+ }
+ },
+ refreshOnFocus: false,
+ refreshOnReconnect: false,
+ previewConcurrency: 2
+ })
+ watch(recentFiles, () => void workspace.invalidate())
+ return workspace
+}
+
+export type RecentFilesWorkspace = ReturnType<typeof useRecentFilesWorkspace>
+
+/** The recent files whose name, path, or stored id holds `query`, already lowercased in `locale`. */
+export function matchingRecentFiles(
+ documents: readonly RecentDocument[],
+ query: string,
+ locale: string
+): readonly RecentDocument[] {
+ if (!query) return documents
+ return documents.filter((document) =>
+ `${document.name}\n${document.kind === 'local' ? document.path : document.documentId}`
+ .toLocaleLowerCase(locale)
+ .includes(query)
+ )
+}
+
+/**
+ * Opens a recent file. A stored one opens with the revision its storage lists, so a stale copy on
+ * this device is not taken for current: `listed` is the active storage's listing when the caller
+ * has it, and other places are listed here; offline, the copy opens as it is. A file that cannot
+ * open is forgotten, and its error thrown.
+ */
+export async function openRecentDocument(
+ document: RecentDocument,
+ listed?: readonly StorageDocument[]
+): Promise<void> {
+ try {
+ if (document.kind === 'local') {
+ await openFileFromPath(document.path)
+ return
+ }
+ const location = storageLocationOf(document)
+ const listing =
+ listed && sameStorageLocation(location, activeStorageLocation())
+ ? listed
+ : await createStorageAdapter(location)
+ .listDocuments()
+ .catch(() => [])
+ const found = listing.find((candidate) => candidate.id === document.documentId)
+ await openStorageDocumentInNewTab(
+ found ?? { id: document.documentId, name: document.name, updatedAt: document.updatedAt },
+ location
+ )
+ } catch (error) {
+ forgetRecentDocument(document.id)
+ throw error
+ }
+}
diff --git a/src/app/storage/workspace/create.ts b/src/app/storage/workspace/create.ts
index 2d3d89589..bbdba43bf 100644
--- a/src/app/storage/workspace/create.ts
+++ b/src/app/storage/workspace/create.ts
@@ -1,10 +1,10 @@
import type { StorageLocation } from '@/app/integrations/storage'
import { rememberRecentStorageDocument } from '@/app/recent-files'
-import { createDocumentInCurrentTab } from '@/app/tabs'
+import { createTab } from '@/app/tabs'
/** Starts a design that lives in a Cloud workspace or the storage bucket from its first edit. */
export async function createStoredDocument(location: StorageLocation): Promise<void> {
- const { store } = createDocumentInCurrentTab()
+ const { store } = createTab()
if (!(await store.saveFigFileToStorage(location))) return
const binding = store.getStorageBinding()
if (binding) rememberRecentStorageDocument(binding, store.state.documentName)
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index fb9241d5e..bc7a32b45 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -109,35 +109,41 @@ export function createTab(store?: EditorStore, initialGraph?: SceneGraph): Tab {
return tab
}
+/**
+ * Shows Home, the one tab pinned first that never closes and never turns into a design, as in
+ * Figma's desktop app; it is made the first time it is asked for.
+ */
export function createHomeTab(): Tab {
+ const existing = tabsRef.value.find((tab) => tab.kind === 'home')
+ if (existing) {
+ activateTab(existing)
+ return existing
+ }
const tab: Tab = { id: generateTabId(), store: createEditorStore(), kind: 'home' }
- tabsRef.value = [...tabsRef.value, tab]
+ tabsRef.value = [tab, ...tabsRef.value]
activateTab(tab)
return tab
}
-export function leaveHome(tabId: string): void {
- const tabIndex = tabsRef.value.findIndex((candidate) => candidate.id === tabId)
- if (tabIndex === -1) return
- const tab = tabsRef.value[tabIndex]
- if (tab.kind !== 'home') return
- tabsRef.value = tabsRef.value.with(tabIndex, { ...tab, kind: 'document' })
+export function showNewTab(): void {
+ createHomeTab()
}
-export function createDocumentInCurrentTab(): Tab {
- const current = activeTab.value
- if (current?.kind !== 'home') return createTab()
- leaveHome(current.id)
- return getTabById(current.id) ?? current
+/** `tabs` with Home first: as they are when it is, with their Home moved there, or `home()` added. */
+export function withHomePinned(tabs: readonly Tab[], home: () => Tab): readonly Tab[] {
+ if (tabs[0]?.kind === 'home') return tabs
+ const existing = tabs.find((tab) => tab.kind === 'home')
+ return existing ? [existing, ...tabs.filter((tab) => tab !== existing)] : [home(), ...tabs]
}
-export function showNewTab(): void {
- const homeTab = tabsRef.value.find((tab) => tab.kind === 'home')
- if (homeTab) {
- switchTab(homeTab.id)
- return
- }
- createHomeTab()
+/** Pins Home first when it is missing, leaving the tab in front where it is. */
+export function ensureHomeTab(): void {
+ const pinned = withHomePinned(tabsRef.value, () => ({
+ id: generateTabId(),
+ store: createEditorStore(),
+ kind: 'home'
+ }))
+ if (pinned !== tabsRef.value) tabsRef.value = [...pinned]
}
function activateTab(tab: Tab) {
@@ -175,7 +181,7 @@ export async function closeTab(tabId: string, unsaved?: 'save' | 'discard'): Pro
if (idx === -1) return
const closingTab = tabsRef.value[idx]
- if (closingTab.kind === 'home' && tabsRef.value.length === 1) return
+ if (closingTab.kind === 'home') return
const choice = unsaved
? await confirmDocumentClose(closingTab.store, async () => unsaved)
: await requestDocumentClose(closingTab.store, closingTab.store.state.documentName)
@@ -216,53 +222,53 @@ function isDOMImportFile(file: File): boolean {
return /\.(html?|xhtml)$/i.test(file.name)
}
-/** A tab a document opens in: a new one, Home, or an untouched empty document. */
-type OpeningTab = { store: EditorStore; created: boolean; fromHome: boolean }
+/**
+ * A tab a document opens in: a new one, or an untouched empty design in front; never Home. `from`
+ * is the tab in front when the open began, which comes back to the front if the open fails.
+ */
+type OpeningTab = { store: EditorStore; created: boolean; from: Tab | undefined }
function reusableTabStore(): OpeningTab {
const current = activeTab.value
- if (current?.kind === 'home') {
- leaveHome(current.id)
- return { store: current.store, created: false, fromHome: true }
- }
+ const source = current?.store.getSourceIdentity()
const isUntouched =
- current?.store.state.documentName === 'Untitled' && !current.store.undo.canUndo
- if (isUntouched) {
- leaveHome(current.id)
- return { store: current.store, created: false, fromHome: false }
- }
- return { store: createTab().store, created: true, fromHome: false }
+ current?.kind === 'document' &&
+ current.store.state.documentName === 'Untitled' &&
+ !current.store.undo.canUndo &&
+ current.store.getStorageBinding() === null &&
+ source?.path === null &&
+ source.handle === null
+ if (current && isUntouched) return { store: current.store, created: false, from: current }
+ return { store: createTab().store, created: true, from: current }
}
/**
- * After a document failed to open: a tab opened for it closes, and Home is Home again, with a
- * fresh store, so nothing of the failed document stays for the next one opened there.
+ * After a document failed to open, a tab opened for it closes and the tab in front before it, such
+ * as Home, comes back; an empty design it reused stays. `keepRecovery` leaves the recovery copy,
+ * as a failed restore must: that copy is the work being restored.
*/
-async function releaseOpeningTab(opening: OpeningTab): Promise<void> {
+async function releaseOpeningTab(
+ opening: OpeningTab,
+ { keepRecovery = false }: { keepRecovery?: boolean } = {}
+): Promise<void> {
+ if (!opening.created) return
const tab = getTabForStore(opening.store)
if (!tab) return
- if (!opening.created && !opening.fromHome) return
- // The tab goes, or Home comes back, even when the recovery copy stays behind, which the next
- // start offers again; the open's own error is the one to report.
- await tab.store.discardRecovery().catch((error: unknown) => {
+ // The tab goes even when the recovery copy stays behind, which the next start offers again;
+ // the open's own error is the one to report.
+ if (!keepRecovery) await discardFailedRecovery(tab.store)
+ const wasActive = activeTabId.value === tab.id
+ removeTab(tab)
+ if (wasActive && opening.from && tabsRef.value.includes(opening.from)) activateTab(opening.from)
+}
+
+async function discardFailedRecovery(store: EditorStore): Promise<void> {
+ await store.discardRecovery().catch((error: unknown) => {
console.warn(
'[Tabs] Failed to discard the recovery copy of a document that failed to open',
error
)
})
- if (opening.created) {
- removeTab(tab)
- return
- }
- // Tabs may have closed meanwhile, so the tab is found again, and only while it still holds this store.
- const tabIndex = tabsRef.value.findIndex(
- (candidate) => candidate.id === tab.id && candidate.store === tab.store
- )
- if (tabIndex === -1) return
- const home: Tab = { ...tab, kind: 'home', store: createEditorStore() }
- tabsRef.value = tabsRef.value.with(tabIndex, home)
- if (activeTabId.value === tab.id) activateTab(home)
- disposeTabStore(tab.store)
}
async function readFigForTab(file: File, signal?: AbortSignal): Promise<SceneGraph> {
@@ -599,7 +605,8 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {
const snapshot = await getRecoveryStore().read(id)
if (!snapshot) throw new Error('Recovery snapshot is no longer available')
- const { store } = reusableTabStore()
+ const opening = reusableTabStore()
+ const { store } = opening
const load = store.preparationController.begin({
kind: 'recovery-restore',
subject: snapshot.documentName
@@ -626,6 +633,7 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {
succeeded = true
} catch (error) {
failPreparation(load, 'decode-failed', error)
+ await releaseOpeningTab(opening, { keepRecovery: true })
throw error
} finally {
if (succeeded) load.complete()
@@ -651,9 +659,7 @@ export function useTabsStore() {
tabs: allTabs,
activeTabId,
createHomeTab,
- createDocumentInCurrentTab,
createTab,
- leaveHome,
switchTab,
closeTab,
getActiveTabId,
diff --git a/src/components/TabBar.vue b/src/components/TabBar.vue
index 6e821c5f1..3f2677c92 100644
--- a/src/components/TabBar.vue
+++ b/src/components/TabBar.vue
@@ -6,7 +6,7 @@ import { computed, useTemplateRef, watch } from 'vue'
import { useI18n } from '@open-pencil/vue/i18n'
import { animationsEnabled } from '@/app/shell/motion'
-import { useTabsStore, createHomeTab } from '@/app/tabs'
+import { useTabsStore, createTab } from '@/app/tabs'
import PreparationIndicator from '@/components/preparation/tab/Indicator.vue'
import { useScrollOverflow } from '@/components/shell/useScrollOverflow'
import Tip from '@/components/ui/overlay/Tip.vue'
@@ -41,14 +41,15 @@ const modelValue = computed({
set: (id: string) => switchTab(id)
})
+/** A new design in a tab of its own, as Figma's + does; Home stays pinned first. */
function createNewTab(event: MouseEvent): void {
event.preventDefault()
if (event.currentTarget instanceof HTMLElement) event.currentTarget.blur()
- createHomeTab()
+ createTab()
}
function onMiddleClick(e: MouseEvent, tabId: string, isHome: boolean) {
- if (e.button === 1 && (!isHome || tabs.value.length > 1)) {
+ if (e.button === 1 && !isHome) {
e.preventDefault()
void closeTab(tabId)
}
@@ -80,35 +81,32 @@ function onClose(e: MouseEvent, tabId: string) {
:key="tab.id"
data-slot="tab-item"
:data-active="tab.isActive || undefined"
- :class="tabBarStyles({ active: tab.isActive }).item()"
+ :class="tabBarStyles({ active: tab.isActive, home: tab.isHome }).item()"
@mousedown="onMiddleClick($event, tab.id, tab.isHome)"
>
<TabsTrigger
:value="tab.id"
data-test-id="tabbar-tab"
- :class="tabBarStyles({ active: tab.isActive }).trigger()"
+ :class="tabBarStyles({ active: tab.isActive, home: tab.isHome }).trigger()"
+ :aria-label="tab.isHome ? files.home : undefined"
:data-active="tab.isActive || undefined"
:data-dirty="tab.isDirty || undefined"
>
<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 ? files.newTab : tab.name }}</span>
+ <span v-if="!tab.isHome" :class="baseStyles.label()">{{ tab.name }}</span>
<Tip v-if="tab.isDirty" :label="files.unsavedChanges" side="bottom">
<span role="img" :aria-label="files.unsavedChanges" :class="baseStyles.dirtyDot()" />
</Tip>
</TabsTrigger>
- <Tip
- v-if="!tab.isHome || tabs.length > 1"
- :label="files.closeTab({ name: tab.isHome ? files.newTab : tab.name })"
- side="bottom"
- >
+ <Tip v-if="!tab.isHome" :label="files.closeTab({ name: tab.name })" side="bottom">
<button
type="button"
data-test-id="tabbar-close"
:class="tabBarStyles({ active: tab.isActive }).close()"
:data-active="tab.isActive || undefined"
- :aria-label="files.closeTab({ name: tab.isHome ? files.newTab : tab.name })"
+ :aria-label="files.closeTab({ name: tab.name })"
tabindex="-1"
@click="onClose($event, tab.id)"
>
@@ -133,11 +131,11 @@ function onClose(e: MouseEvent, tabId: string) {
<icon-lucide-chevron-right v-if="overflowEnd" :class="baseStyles.scrollIcon()" />
<icon-lucide-chevron-left v-else :class="baseStyles.scrollIcon()" />
</button>
- <Tip :label="files.newTab" side="bottom">
+ <Tip :label="files.newDesign" side="bottom">
<button
type="button"
data-test-id="tabbar-new"
- :aria-label="files.newTab"
+ :aria-label="files.newDesign"
:class="baseStyles.newTab()"
@click="createNewTab"
>
diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vue
index d317c0eee..0adb24ff7 100644
--- a/src/components/home/HomeWorkspace.vue
+++ b/src/components/home/HomeWorkspace.vue
@@ -1,9 +1,8 @@
<script setup lang="ts">
import { useLocalStorage } from '@vueuse/core'
-import { computed, ref, watch } from 'vue'
+import { computed, ref } from 'vue'
import { useDocumentWorkspace } from '@open-pencil/vue/document/workspace'
-import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'
import { useI18n } from '@open-pencil/vue/i18n'
import { CLOUD_INCLUDED, CLOUD_STORAGE_PROVIDER_ID } from '@/app/cloud/integration'
@@ -11,41 +10,35 @@ import { useHomeLocations } from '@/app/home/locations'
import { useDateFormat } from '@/app/i18n/date'
import {
activeStorageProviderID,
- createStorageAdapter,
readStoragePreferences,
storagePreferencesComplete,
- sameStorageLocation,
- storageLocationOf,
storageProviderRegistry,
type StorageDocument,
type StorageLocation
} from '@/app/integrations/storage'
+import type { RecentDocument } from '@/app/recent-files'
import {
- clearRecentFiles,
- forgetRecentDocument,
- loadRecentFileThumbnail,
- recentFiles,
- type RecentDocument
-} from '@/app/recent-files'
+ matchingRecentFiles,
+ openRecentDocument,
+ useRecentFilesWorkspace
+} from '@/app/recent-files/workspace'
import { useCredentialSettings } from '@/app/settings/credentials/preferences/use'
import { openSettingsDialog } from '@/app/settings/dialog'
-import { openFileFromPath } from '@/app/shell/menu/use'
import { createStoredDocument } from '@/app/storage/workspace/create'
-import { activeStorageLocation, createStorageWorkspaceSource } from '@/app/storage/workspace/source'
+import { createStorageWorkspaceSource } from '@/app/storage/workspace/source'
import { openStorageDocumentInNewTab } from '@/app/tabs'
import { CloudSharedSection, CloudWorkspaceSection } from '@/components/cloud/integration'
import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
import HomeLayout from '@/components/home/HomeLayout.vue'
+import RecentFilesSection from '@/components/home/recent/RecentFilesSection.vue'
import HomeSearchActions from '@/components/home/search/HomeSearchActions.vue'
import HomeLocationMenu from '@/components/home/sidebar/HomeLocationMenu.vue'
import HomeSidebar from '@/components/home/sidebar/HomeSidebar.vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
-import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
const emit = defineEmits<{ 'new-document': [] }>()
-const { panels, locale, storage, files, common, settings, credentials } = useI18n()
-const { isMobile } = useViewportKind()
+const { locale, storage, files, common, settings, credentials } = useI18n()
const view = useLocalStorage<'grid' | 'list'>('open-pencil:home-files-view', 'grid')
const query = ref('')
const openError = ref<string | null>(null)
@@ -59,29 +52,9 @@ function newDocument() {
else emit('new-document')
}
-const workspace = useDocumentWorkspace<RecentDocument>({
- source: {
- async refresh() {
- return recentFiles.value
- },
- loadPreview(documentId) {
- const document = recentFiles.value.find((candidate) => candidate.id === documentId)
- if (!document) return Promise.resolve(null)
- if (document.kind === 'local') return loadRecentFileThumbnail(document.path)
- return createStorageWorkspaceSource(
- () => undefined,
- () => storageLocationOf(document)
- ).loadPreview(document.documentId)
- }
- },
- refreshOnFocus: false,
- refreshOnReconnect: false,
- previewConcurrency: 2
-})
+const workspace = useRecentFilesWorkspace()
const documents = workspace.documents
-const previewURL = workspace.previewURL
-const vWorkspacePreview = workspace.previewDirective
const storageWorkspace = useDocumentWorkspace<StorageDocument>({
source: createStorageWorkspaceSource((snapshot) => {
@@ -162,21 +135,15 @@ const newDesignTarget = computed<{ location: StorageLocation; label: string } |
const storagePreviewURL = storageWorkspace.previewURL
const vStoragePreview = storageWorkspace.previewDirective
const normalizedQuery = computed(() => query.value.trim().toLocaleLowerCase(locale.value))
-const filteredRecentFiles = computed(() => {
- if (!normalizedQuery.value) return documents.value
- return documents.value.filter((document) =>
- `${document.name}\n${document.kind === 'local' ? document.path : document.documentId}`
- .toLocaleLowerCase(locale.value)
- .includes(normalizedQuery.value)
- )
-})
+const filteredRecentFiles = computed(() =>
+ matchingRecentFiles(documents.value, normalizedQuery.value, locale.value)
+)
const filteredStorageDocuments = computed(() => {
if (!normalizedQuery.value) return storageDocuments.value
return storageDocuments.value.filter((document) =>
document.name.toLocaleLowerCase(locale.value).includes(normalizedQuery.value)
)
})
-const hasRecentFiles = computed(() => documents.value.length > 0)
const noSearchMatches = computed(
() =>
Boolean(normalizedQuery.value) &&
@@ -184,30 +151,13 @@ const noSearchMatches = computed(
filteredStorageDocuments.value.length === 0
)
-watch(recentFiles, () => void workspace.invalidate())
-
async function openRecent(document: RecentDocument): Promise<void> {
openError.value = null
try {
- if (document.kind === 'local') {
- await openFileFromPath(document.path)
- return
- }
- const location = storageLocationOf(document)
- // The listing carries the revision that tells whether this device's copy is still current;
- // offline, the copy opens as it is.
- const listing = sameStorageLocation(location, activeStorageLocation())
- ? storageDocuments.value
- : await createStorageAdapter(location)
- .listDocuments()
- .catch(() => [])
- const listed = listing.find((candidate) => candidate.id === document.documentId)
- await openStorageDocumentInNewTab(
- listed ?? { id: document.documentId, name: document.name, updatedAt: document.updatedAt },
- location
- )
+ // Before the storage list first loads, an empty list would hide the revision to check.
+ const listed = storageWorkspace.lastRefreshedAt.value ? storageDocuments.value : undefined
+ await openRecentDocument(document, listed)
} catch (error) {
- forgetRecentDocument(document.id)
openError.value = error instanceof Error ? error.message : String(error)
}
}
@@ -286,77 +236,14 @@ function formattedDate(updatedAt: string): string {
{{ files.noMatchingFiles({ query: query.trim() }) }}
</p>
- <section v-if="!noSearchMatches && places.location.value.kind === 'recent'">
- <div class="mb-3 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-2">
- <div class="col-span-2 min-w-0 sm:col-span-1">
- <h1 class="text-base font-semibold">{{ files.recentFiles }}</h1>
- <p class="mt-0.5 text-pretty text-xs text-muted">{{ files.recentFilesDescription }}</p>
- </div>
- <div class="col-span-2 flex items-center justify-end gap-1 sm:col-span-1">
- <IconButton
- v-if="hasRecentFiles"
- :label="common.clear"
- class="size-10 sm:size-7"
- data-test-id="recent-files-clear"
- @click="clearRecentFiles"
- >
- <icon-lucide-trash-2 class="size-3.5" />
- </IconButton>
- <SegmentedControl
- v-model="view"
- required
- :label="files.recentFiles"
- :size="isMobile ? 'touch' : 'md'"
- :options="[
- { value: 'grid', label: panels.gridView },
- { value: 'list', label: panels.listView }
- ]"
- >
- <template #option="{ option }">
- <icon-lucide-layout-grid v-if="option.value === 'grid'" class="size-3.5" />
- <icon-lucide-list v-else class="size-3.5" />
- </template>
- </SegmentedControl>
- </div>
- </div>
-
- <div
- v-if="filteredRecentFiles.length && view === 'grid'"
- class="grid grid-cols-1 gap-x-5 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(200px,1fr))]"
- >
- <DocumentEntry
- v-for="document in filteredRecentFiles"
- :key="document.id"
- v-workspace-preview="document.id"
- :name="document.name"
- :metadata="formattedDate(document.updatedAt)"
- :previewURL="previewURL(document.id)"
- @open="openRecent(document)"
- />
- </div>
-
- <div
- v-else-if="filteredRecentFiles.length"
- class="overflow-hidden rounded-lg border border-border"
- >
- <DocumentEntry
- v-for="document in filteredRecentFiles"
- :key="document.id"
- view="list"
- :name="document.name"
- :metadata="formattedDate(document.updatedAt)"
- @open="openRecent(document)"
- />
- </div>
-
- <div
- v-else-if="!normalizedQuery"
- class="rounded-lg border border-dashed border-border px-4 py-4 text-center sm:py-6"
- >
- <p class="text-xs font-medium">{{ files.noRecentFiles }}</p>
- <p class="mt-1 text-xs text-muted">{{ files.noRecentFilesDescription }}</p>
- </div>
- </section>
+ <RecentFilesSection
+ v-if="!noSearchMatches && places.location.value.kind === 'recent'"
+ v-model:view="view"
+ :workspace="workspace"
+ :documents="filteredRecentFiles"
+ :query="normalizedQuery"
+ @open="openRecent"
+ />
<section v-if="places.location.value.kind === 'storage'">
<div class="mb-3 flex items-start gap-3">
diff --git a/src/components/home/recent/RecentFilesSection.vue b/src/components/home/recent/RecentFilesSection.vue
new file mode 100644
index 000000000..5e909eda8
--- /dev/null
+++ b/src/components/home/recent/RecentFilesSection.vue
@@ -0,0 +1,104 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'
+import { useI18n } from '@open-pencil/vue/i18n'
+
+import { useDateFormat } from '@/app/i18n/date'
+import { clearRecentFiles, type RecentDocument } from '@/app/recent-files'
+import type { RecentFilesWorkspace } from '@/app/recent-files/workspace'
+import DocumentEntry from '@/components/home/document/DocumentEntry.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
+
+/** The recent files, as a grid or a list, with the files `documents` keeps of them. */
+const { workspace, documents, query } = defineProps<{
+ workspace: RecentFilesWorkspace
+ documents: readonly RecentDocument[]
+ query: string
+}>()
+const emit = defineEmits<{ open: [document: RecentDocument] }>()
+const view = defineModel<'grid' | 'list'>('view', { required: true })
+const { panels, files, common } = useI18n()
+const { isMobile } = useViewportKind()
+const dates = useDateFormat()
+const previewURL = workspace.previewURL
+const vWorkspacePreview = workspace.previewDirective
+const hasRecentFiles = computed(() => workspace.documents.value.length > 0)
+
+/** A file's last change; a file that never reported one shows nothing. */
+function formattedDate(updatedAt: string): string {
+ return Date.parse(updatedAt) === 0 ? '' : dates.format(updatedAt, 'dateTime')
+}
+</script>
+
+<template>
+ <section>
+ <div class="mb-3 grid grid-cols-[minmax(0,1fr)_auto] items-start gap-x-3 gap-y-2">
+ <div class="col-span-2 min-w-0 sm:col-span-1">
+ <h1 class="text-base font-semibold">{{ files.recentFiles }}</h1>
+ <p class="mt-0.5 text-pretty text-xs text-muted">{{ files.recentFilesDescription }}</p>
+ </div>
+ <div class="col-span-2 flex items-center justify-end gap-1 sm:col-span-1">
+ <IconButton
+ v-if="hasRecentFiles"
+ :label="common.clear"
+ class="size-10 sm:size-7"
+ data-test-id="recent-files-clear"
+ @click="clearRecentFiles"
+ >
+ <icon-lucide-trash-2 class="size-3.5" />
+ </IconButton>
+ <SegmentedControl
+ v-model="view"
+ required
+ :label="files.recentFiles"
+ :size="isMobile ? 'touch' : 'md'"
+ :options="[
+ { value: 'grid', label: panels.gridView },
+ { value: 'list', label: panels.listView }
+ ]"
+ >
+ <template #option="{ option }">
+ <icon-lucide-layout-grid v-if="option.value === 'grid'" class="size-3.5" />
+ <icon-lucide-list v-else class="size-3.5" />
+ </template>
+ </SegmentedControl>
+ </div>
+ </div>
+
+ <div
+ v-if="documents.length && view === 'grid'"
+ class="grid grid-cols-1 gap-x-5 gap-y-6 sm:grid-cols-[repeat(auto-fill,minmax(200px,1fr))]"
+ >
+ <DocumentEntry
+ v-for="document in documents"
+ :key="document.id"
+ v-workspace-preview="document.id"
+ :name="document.name"
+ :metadata="formattedDate(document.updatedAt)"
+ :previewURL="previewURL(document.id)"
+ @open="emit('open', document)"
+ />
+ </div>
+
+ <div v-else-if="documents.length" class="overflow-hidden rounded-lg border border-border">
+ <DocumentEntry
+ v-for="document in documents"
+ :key="document.id"
+ view="list"
+ :name="document.name"
+ :metadata="formattedDate(document.updatedAt)"
+ @open="emit('open', document)"
+ />
+ </div>
+
+ <div
+ v-else-if="!query"
+ class="rounded-lg border border-dashed border-border px-4 py-4 text-center sm:py-6"
+ >
+ <p class="text-xs font-medium">{{ files.noRecentFiles }}</p>
+ <p class="mt-1 text-xs text-muted">{{ files.noRecentFilesDescription }}</p>
+ </div>
+ </section>
+</template>
diff --git a/src/theme/tab-bar.ts b/src/theme/tab-bar.ts
index 4d358c9d8..1b22db29a 100644
--- a/src/theme/tab-bar.ts
+++ b/src/theme/tab-bar.ts
@@ -22,6 +22,13 @@ const tabBarTheme = {
scrollIcon: 'size-3.5'
},
variants: {
+ // Home is pinned first as an icon, the way Figma's desktop app shows it.
+ home: {
+ true: {
+ item: 'max-w-none min-w-0 pr-0',
+ trigger: 'px-3.5'
+ }
+ },
active: {
true: {
item: 'bg-panel text-surface',
@@ -36,7 +43,8 @@ const tabBarTheme = {
}
},
defaultVariants: {
- active: false
+ active: false,
+ home: false
}
}
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index 6ccf4220b..16c28586c 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -33,8 +33,8 @@ import { useEditorMenu } from '@/app/shell/menu/use'
import { toast } from '@/app/shell/ui'
import {
activeTab,
- createDocumentInCurrentTab,
createHomeTab,
+ ensureHomeTab,
createTab,
getActiveStore,
getTabsSnapshot,
@@ -78,16 +78,20 @@ watch(
)
const router = useRouter()
const createdInitialTab = tabCount() === 0
-// Home opens first where it lists something: recent files, or the workspaces of the Cloud server
-// that serves the editor.
-const shouldCreateHome =
- route.path === '/' &&
- !appRuntimeConfig.test &&
- !route.meta.demo &&
- (recentFilesAvailable() || IS_CLOUD_SITE)
+// Home is pinned first everywhere but tests and the demo, and opens in front where it lists
+// something: recent files, or the workspaces of the Cloud server that serves the editor.
+const pinHome = !appRuntimeConfig.test && !route.meta.demo
+const showHomeFirst = route.path === '/' && pinHome && (recentFilesAvailable() || IS_CLOUD_SITE)
+// The view stays mounted from /demo to /, so Home is pinned once a route that has it is reached.
+watch(
+ () => !appRuntimeConfig.test && !route.meta.demo,
+ (pins) => {
+ if (pins) ensureHomeTab()
+ }
+)
/**
- * A Cloud link's first tab is Home, which the document it opens takes over; Home is also where a
- * link that fails or waits for a sign-in leaves the person, never an empty document.
+ * A Cloud link's first tab is Home, beside which the document it opens gets its own tab; Home is
+ * also where a link that fails or waits for a sign-in leaves the person, never an empty document.
*/
const opensCloudLink = ['documentId', 'shareId', 'invitationId'].some(
(param) => typeof route.params[param] === 'string'
@@ -95,14 +99,20 @@ const opensCloudLink = ['documentId', 'shareId', 'invitationId'].some(
const { collaboration } = useI18n()
const joinRoomFromInput = useJoinRoom()
-/** A share link opens its room in a tab of its own, so nothing editable shows before it. */
+/**
+ * A share link opens its room in a tab of its own, so nothing editable shows before it. Home, where
+ * the app has one, is pinned first behind it.
+ */
function openFirstTab(): Tab {
const roomId = typeof route.params.roomId === 'string' ? route.params.roomId : null
+ if (pinHome) createHomeTab()
if (roomId) {
if (joinRoomFromInput(roomId) && activeTab.value) return activeTab.value
toast.error(collaboration.value.invalidRoomLink)
+ // A link that fails leaves the person on Home, not in an empty design.
+ if (pinHome) return createHomeTab()
}
- return shouldCreateHome || opensCloudLink ? createHomeTab() : createTab()
+ return showHomeFirst || opensCloudLink ? createHomeTab() : createTab()
}
// Block-scoped so the view does not keep the first tab's store after that tab closes.
@@ -291,7 +301,7 @@ onUnmounted(() => {
<RenameSelectionDialog />
<CommandPalette />
<TabBar />
- <HomeWorkspace v-show="activeTab?.kind === 'home'" @new-document="createDocumentInCurrentTab" />
+ <HomeWorkspace v-show="activeTab?.kind === 'home'" @new-document="createTab()" />
<CloudVersionDialog />
<EditorWorkspace v-if="shown && shown.tab.kind !== 'home'" :key="shown.key" :tab="shown.tab" />
<LoadingScreen v-if="openingCloudLink" />
diff --git a/tests/engine/app/tabs/open-file-dedup.test.ts b/tests/engine/app/tabs/open-file-dedup.test.ts
index 01e9ad496..fbd2be60f 100644
--- a/tests/engine/app/tabs/open-file-dedup.test.ts
+++ b/tests/engine/app/tabs/open-file-dedup.test.ts
@@ -6,15 +6,20 @@ import { SceneGraph } from '@open-pencil/scene-graph'
import { resolveBrowserFileURL } from '@/app/document/io/browser'
import type { DocumentSourceIdentity } from '@/app/document/io/types'
+import { getRecoveryStore, resetRecoveryStoreForTests } from '@/app/document/recovery'
+import { createMemoryRecoveryStore } from '@/app/document/recovery/memory'
import {
- createDocumentInCurrentTab,
+ closeTab,
createHomeTab,
createTab,
getActiveStore,
getTabsSnapshot,
openFileInNewTab,
showNewTab,
- tabCount
+ restoreRecoverySnapshot,
+ tabCount,
+ withHomePinned,
+ type Tab
} from '@/app/tabs'
import { fileIdentitiesMatch, findTabByFileIdentity } from '@/app/tabs/open/identity'
@@ -173,72 +178,84 @@ describe('openFileInNewTab deduplication', () => {
expect(getTabsSnapshot().filter((tab) => tab.kind === 'home')).toHaveLength(1)
})
- test('converts the current New tab into a blank document', () => {
- createHomeTab()
- const home = getTabsSnapshot().at(-1)
+ test('keeps one Home pinned first, which never closes', async () => {
+ createTab()
+ const home = createHomeTab()
+ expect(createHomeTab().id).toBe(home.id)
+ expect(getTabsSnapshot()[0]?.id).toBe(home.id)
+ await closeTab(home.id)
+ expect(getTabsSnapshot().filter((tab) => tab.kind === 'home')).toEqual([home])
+ })
+
+ test('pins Home first, moving it there or adding it when the tabs have none', () => {
+ const design = createTab()
+ const home = createHomeTab()
+ const ids = (tabs: readonly Tab[]) => tabs.map((tab) => tab.id)
+ expect(ids(withHomePinned([design], () => home))).toEqual([home.id, design.id])
+ const pinned = [home, design]
+ expect(withHomePinned(pinned, () => createTab())).toBe(pinned)
+ expect(ids(withHomePinned([design, home], () => createTab()))).toEqual([home.id, design.id])
+ })
+
+ test('a failed recovery restore closes its tab and keeps the snapshot', async () => {
+ resetRecoveryStoreForTests(createMemoryRecoveryStore())
+ await getRecoveryStore().write({
+ id: 'broken',
+ documentName: 'Broken',
+ figBytes: new Uint8Array([1])
+ })
+ ;(figModule.readFigFile as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
+ new Error('read failed')
+ )
+ const home = createHomeTab()
const count = tabCount()
- const document = createDocumentInCurrentTab()
+ await expect(restoreRecoverySnapshot('broken')).rejects.toThrow('read failed')
expect(tabCount()).toBe(count)
- expect(document.id).toBe(expectDefined(home, 'home tab').id)
- expect(document.kind).toBe('document')
+ expect(getActiveStore()).toBe(home.store)
+ expect(await getRecoveryStore().read('broken')).not.toBeNull()
+ resetRecoveryStoreForTests()
})
- test('opens a file in the current New tab', async () => {
- createHomeTab()
- const home = getTabsSnapshot().at(-1)
+ test('opens a file from Home in a tab of its own, leaving Home as it is', async () => {
+ const home = createHomeTab()
const count = tabCount()
await settleFileOpen(
openFileInNewTab(new File([], 'design.fig'), undefined, '/tmp/from-home.fig')
)
- expect(tabCount()).toBe(count)
- expect(getTabsSnapshot().at(-1)?.id).toBe(home?.id)
+ expect(tabCount()).toBe(count + 1)
expect(getTabsSnapshot().at(-1)?.kind).toBe('document')
+ expect(
+ expectDefined(
+ getTabsSnapshot().find((tab) => tab.id === home.id),
+ 'home'
+ ).kind
+ ).toBe('home')
})
- test('leaves Home as it was when a file opened from it fails', async () => {
+ test('closes the tab a file opened from Home got when it fails, leaving Home as it was', async () => {
;(figModule.readFigFile as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
new Error('read failed')
)
- createHomeTab()
- const home = expectDefined(getTabsSnapshot().at(-1), 'home tab')
+ createTab()
+ const home = createHomeTab()
const count = tabCount()
await expect(
settleFileOpen(openFileInNewTab(new File([], 'broken.fig'), undefined, '/tmp/broken.fig'))
).rejects.toThrow('read failed')
- const after = expectDefined(getTabsSnapshot().at(-1), 'home tab')
expect(tabCount()).toBe(count)
- expect(after.id).toBe(home.id)
- expect(after.kind).toBe('home')
- expect(after.store).not.toBe(home.store)
- expect(after.store.state.documentName).toBe('Untitled')
- expect(getActiveStore()).toBe(after.store)
- })
-
- test('brings Home back and reports the open failure when its recovery copy stays', async () => {
- ;(figModule.readFigFile as ReturnType<typeof vi.fn>).mockRejectedValueOnce(
- new Error('read failed')
+ const after = expectDefined(
+ getTabsSnapshot().find((tab) => tab.id === home.id),
+ 'home tab'
)
- createHomeTab()
- const home = expectDefined(getTabsSnapshot().at(-1), 'home tab')
- vi.spyOn(home.store, 'discardRecovery').mockRejectedValueOnce(new Error('disk full'))
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
-
- await expect(
- settleFileOpen(openFileInNewTab(new File([], 'broken.fig'), undefined, '/tmp/broken.fig'))
- ).rejects.toThrow('read failed')
-
- const after = expectDefined(getTabsSnapshot().at(-1), 'home tab')
- expect(after.id).toBe(home.id)
- expect(after.kind).toBe('home')
- expect(after.store).not.toBe(home.store)
- expect(warn).toHaveBeenCalled()
- warn.mockRestore()
+ expect([after.kind, after.store]).toEqual(['home', home.store])
+ // Home was in front when the open began, so it is again, not the other design.
+ expect(getActiveStore()).toBe(home.store)
})
test('activates the existing tab when the same path is opened again', async () => {