AI-native design editor. Open-source Figma alternative.
test(app): cover Tauri file actions
Danila Poyarkov020b55a8ae3b
diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.tsindex a94459e68..7e7720091 100644--- a/src/app/document/export/files.ts+++ b/src/app/document/export/files.ts@@ -1,4 +1,4 @@-import { IS_TAURI } from '@/constants'+import { isTauri } from '@/app/tauri/env'import { renderNodesToImage } from '@open-pencil/core/io/formats/raster'import type { Editor, EditorState } from '@open-pencil/core/editor'@@ -86,6 +86,19 @@ export function createExportTargetActions(editor: Editor, state: EditorState, ioreturn { renderExportImage, getSelectionExportTarget, listSelectionExportFormats }}+export async function chooseTauriExportPath(fileName: string, format: string, ext: string) {+ const { save } = await import('@tauri-apps/plugin-dialog')+ return save({+ defaultPath: fileName,+ filters: [{ name: format, extensions: [ext.slice(1)] }]+ })+}++export async function writeTauriExportFile(path: string, data: Uint8Array) {+ const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')+ await tauriWrite(path, data)+}+export async function saveExportedFile(data: Uint8Array,fileName: string,@@ -94,15 +107,10 @@ export async function saveExportedFile(mime: string,downloadBlob: DownloadBlob) {- if (IS_TAURI) {- const { save } = await import('@tauri-apps/plugin-dialog')- const path = await save({- defaultPath: fileName,- filters: [{ name: format, extensions: [ext.slice(1)] }]- })+ if (isTauri()) {+ const path = await chooseTauriExportPath(fileName, format, ext)if (!path) return- const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')- await tauriWrite(path, data)+ await writeTauriExportFile(path, data)return}diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex a37f0ec3e..754367edf 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -1,7 +1,8 @@import { useFileDialog } from '@vueuse/core'import { openFileInNewTab } from '@/app/tabs'-import { IS_BROWSER, IS_TAURI } from '@/constants'+import { isTauri } from '@/app/tauri/env'+import { IS_BROWSER } from '@/constants'const fileDialog = useFileDialog({ accept: '.fig,.pen', multiple: false, reset: true })@@ -22,21 +23,30 @@ if (IS_BROWSER) {}}-export async function openFileFromPath(path: string) {- if (!IS_TAURI) return+export async function readTauriDesignFile(path: string): Promise<File> {const { readFile } = await import('@tauri-apps/plugin-fs')const bytes = await readFile(path)- const file = new File([bytes], path.split('/').pop() ?? 'file.fig')+ return new File([bytes], path.split('/').pop() ?? 'file.fig')+}++export async function chooseTauriOpenPath(): Promise<string | null> {+ const { open } = await import('@tauri-apps/plugin-dialog')+ const path = await open({+ filters: [{ name: 'Design file', extensions: ['fig', 'pen'] }],+ multiple: false+ })+ return typeof path === 'string' ? path : null+}++export async function openFileFromPath(path: string) {+ if (!isTauri()) return+ const file = await readTauriDesignFile(path)await openFileInNewTab(file, undefined, path)}export async function openFileDialog() {- if (IS_TAURI) {- const { open } = await import('@tauri-apps/plugin-dialog')- const path = await open({- filters: [{ name: 'Design file', extensions: ['fig', 'pen'] }],- multiple: false- })+ if (isTauri()) {+ const path = await chooseTauriOpenPath()if (!path) returnawait openFileFromPath(path)returndiff --git a/src/app/shell/menu/use.ts b/src/app/shell/menu/use.tsindex 970ea092a..d851ce5e7 100644--- a/src/app/shell/menu/use.ts+++ b/src/app/shell/menu/use.ts@@ -4,8 +4,8 @@ import { useEditorStore } from '@/app/editor/active-store'import { importFileDialog, openFileDialog } from '@/app/shell/menu/files'import { useAppTheme } from '@/app/shell/theme'import { checkForAppUpdate } from '@/app/shell/updater'+import { isTauri } from '@/app/tauri/env'import { createTab, closeTab, activeTab } from '@/app/tabs'-import { IS_TAURI } from '@/constants'import { useEditorCommands, useI18n } from '@open-pencil/vue'import type { EditorCommandId } from '@open-pencil/vue'@@ -52,7 +52,7 @@ function updateSelectedText(updates: {}export function useMenu() {- if (!IS_TAURI) return+ if (!isTauri()) returnlet unlisten: (() => void) | undefinedconst { setTheme } = useAppTheme()diff --git a/src/components/FontSettings/FontSettingsPopover.vue b/src/components/FontSettings/FontSettingsPopover.vuenew file mode 100644index 000000000..5f81640e6--- /dev/null+++ b/src/components/FontSettings/FontSettingsPopover.vue@@ -0,0 +1,154 @@+<script setup lang="ts">+import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'+import { onMounted } from 'vue'++import { useFontSettings } from '@/components/FontSettings/use'+import { useButtonUI } from '@/components/ui/button'+import { usePopoverUI } from '@/components/ui/popover'++const cls = usePopoverUI({ content: 'isolate z-[51] w-80 p-3' })+const trigger = useButtonUI({ tone: 'ghost', size: 'iconSm', ui: { base: 'shrink-0 border border-border bg-input' } })+const secondaryButton = useButtonUI({+ tone: 'ghost',+ size: 'sm',+ ui: { base: 'w-full bg-input px-2 py-1.5 text-[10px] font-medium text-surface hover:bg-hover disabled:opacity-50' }+})+const primaryButton = useButtonUI({+ tone: 'accent',+ size: 'sm',+ ui: { base: 'w-full px-2 py-1.5 text-[10px] font-medium disabled:opacity-50' }+})+const {+ accessState,+ accessStateLabel,+ busyAction,+ cacheCount,+ cacheSize,+ cacheUpdatedLabel,+ canRequestLocalFonts,+ status,+ clearCache,+ downloadFallbacks,+ refreshSummary,+ requestAccess+} = useFontSettings()++onMounted(() => {+ void refreshSummary()+})+</script>++<template>+ <PopoverRoot @update:open="$event && refreshSummary()">+ <PopoverTrigger data-test-id="font-settings-trigger" :class="trigger.base" title="Font settings">+ <icon-lucide-settings class="size-3.5" />+ </PopoverTrigger>++ <PopoverPortal>+ <PopoverContent+ side="left"+ :side-offset="8"+ align="start"+ :collision-padding="16"+ :avoid-collisions="true"+ :class="cls.content"+ >+ <div class="flex flex-col gap-3">+ <div class="flex items-start gap-2">+ <div class="flex size-8 shrink-0 items-center justify-center rounded bg-input text-muted">+ <icon-lucide-type class="size-4" />+ </div>+ <div>+ <h3 class="text-[11px] font-semibold text-surface">Font settings</h3>+ <p class="mt-0.5 text-[10px] leading-relaxed text-muted">+ Access system fonts, predownload fallback packs, and manage cached downloads.+ </p>+ </div>+ </div>++ <div class="grid gap-1.5 rounded border border-border bg-input/40 p-2 text-[10px]">+ <div class="flex justify-between gap-3 text-muted">+ <span>Local fonts</span>+ <span class="text-surface">{{ accessStateLabel }}</span>+ </div>+ <div class="flex justify-between gap-3 text-muted">+ <span>Downloaded cache</span>+ <span class="text-surface">{{ cacheCount }} fonts · {{ cacheSize }}</span>+ </div>+ <div class="flex justify-between gap-3 text-muted">+ <span>Last updated</span>+ <span class="text-surface">{{ cacheUpdatedLabel }}</span>+ </div>+ </div>++ <div class="space-y-1.5">+ <div class="grid grid-cols-[1fr_auto] gap-2 rounded border border-border p-2">+ <div>+ <p class="text-[10px] font-medium text-surface">System font access</p>+ <p class="mt-0.5 text-[10px] leading-relaxed text-muted">+ {{+ accessState === 'granted'+ ? 'System fonts are available.'+ : 'Allow browser font access when system fonts are missing.'+ }}+ </p>+ </div>+ <button+ type="button"+ data-test-id="font-settings-request-access"+ :class="secondaryButton.base"+ :disabled="busyAction !== null || !canRequestLocalFonts"+ @click="requestAccess"+ >+ {{ busyAction === 'access' ? 'Requesting…' : 'Allow' }}+ </button>+ </div>++ <div class="grid grid-cols-[1fr_auto] gap-2 rounded border border-border p-2">+ <div>+ <p class="text-[10px] font-medium text-surface">Fallback packs</p>+ <p class="mt-0.5 text-[10px] leading-relaxed text-muted">+ Download CJK and Arabic fallbacks before opening files that need them.+ </p>+ </div>+ <button+ type="button"+ data-test-id="font-settings-download-fallbacks"+ :class="primaryButton.base"+ :disabled="busyAction !== null"+ @click="downloadFallbacks"+ >+ {{ busyAction === 'download' ? 'Downloading…' : 'Download' }}+ </button>+ </div>+ </div>++ <div class="grid grid-cols-2 gap-1.5">+ <button+ type="button"+ data-test-id="font-settings-refresh-cache"+ :class="secondaryButton.base"+ :disabled="busyAction !== null"+ @click="refreshSummary"+ >+ Refresh+ </button>+ <button+ type="button"+ data-test-id="font-settings-clear-cache"+ :class="secondaryButton.base"+ :disabled="busyAction !== null || cacheCount === 0"+ @click="clearCache"+ >+ Clear cache+ </button>+ </div>++ <p v-if="status" class="rounded bg-input px-2 py-1.5 text-[10px] leading-relaxed text-muted">+ {{ status }}+ </p>+ </div>+ </PopoverContent>+ </PopoverPortal>+ </PopoverRoot>+</template>diff --git a/src/components/FontSettings/use.ts b/src/components/FontSettings/use.tsindex d352c031a..207c503eb 100644--- a/src/components/FontSettings/use.ts+++ b/src/components/FontSettings/use.ts@@ -42,6 +42,13 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {const busyAction = ref<FontSettingsBusyAction | null>(null)const status = ref('')+ const accessStateLabel = computed(() => {+ if (accessState.value === 'granted') return 'Enabled'+ if (accessState.value === 'denied') return 'Denied'+ if (accessState.value === 'unsupported') return 'Unavailable'+ return 'Not requested'+ })+const cacheSize = computed(() => {if (cacheByteLength.value === 0) return '0 MB'return `${(cacheByteLength.value / 1024 / 1024).toFixed(1)} MB`@@ -52,6 +59,10 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {return new Date(cacheUpdatedAt.value).toLocaleDateString()})+ const canRequestLocalFonts = computed(() =>+ accessState.value === 'prompt' || accessState.value === 'denied'+ )+async function refreshSummary() {busyAction.value = busyAction.value ?? 'refresh'try {@@ -110,7 +121,9 @@ export function useFontSettings(actions: FontSettingsActions = defaultActions) {return {accessState,+ accessStateLabel,busyAction,+ canRequestLocalFonts,cacheCount,cacheSize,cacheUpdatedLabel,diff --git a/src/components/FontSettingsPopover.vue b/src/components/FontSettingsPopover.vuedeleted file mode 100644index a3ccc5975..000000000--- a/src/components/FontSettingsPopover.vue+++ /dev/null@@ -1,113 +0,0 @@-<script setup lang="ts">-import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'-import { onMounted } from 'vue'--import { useFontSettings } from '@/components/FontSettings/use'-import { usePopoverUI } from '@/components/ui/popover'--const cls = usePopoverUI({ content: 'isolate z-[51] w-72 p-3' })-const {- accessState,- busyAction,- cacheCount,- cacheSize,- cacheUpdatedLabel,- status,- clearCache,- downloadFallbacks,- refreshSummary,- requestAccess-} = useFontSettings()--onMounted(() => {- void refreshSummary()-})-</script>--<template>- <PopoverRoot @update:open="$event && refreshSummary()">- <PopoverTrigger- data-test-id="font-settings-trigger"- class="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded border border-border bg-input text-muted hover:bg-hover hover:text-surface"- title="Font settings"- >- <icon-lucide-settings class="size-3.5" />- </PopoverTrigger>-- <PopoverPortal>- <PopoverContent- side="left"- :side-offset="8"- align="start"- :collision-padding="16"- :avoid-collisions="true"- :class="cls.content"- >- <div class="flex flex-col gap-3">- <div>- <h3 class="text-[11px] font-semibold text-surface">Fonts</h3>- <p class="mt-1 text-[10px] leading-relaxed text-muted">- Manage local font access and OpenPencil's downloaded fallback font cache.- </p>- </div>-- <div class="rounded border border-border bg-input/40 p-2 text-[10px] text-muted">- <div class="flex justify-between gap-3">- <span>Local access</span>- <span class="text-surface">{{ accessState }}</span>- </div>- <div class="mt-1 flex justify-between gap-3">- <span>Downloaded cache</span>- <span class="text-surface">{{ cacheCount }} fonts · {{ cacheSize }}</span>- </div>- <div class="mt-1 flex justify-between gap-3">- <span>Updated</span>- <span class="text-surface">{{ cacheUpdatedLabel }}</span>- </div>- </div>-- <div class="grid grid-cols-2 gap-1.5">- <button- type="button"- data-test-id="font-settings-request-access"- class="rounded bg-input px-2 py-1.5 text-[10px] font-medium text-surface hover:bg-hover disabled:opacity-50"- :disabled="busyAction !== null"- @click="requestAccess"- >- {{ busyAction === 'access' ? 'Requesting…' : 'Local fonts' }}- </button>- <button- type="button"- data-test-id="font-settings-download-fallbacks"- class="rounded bg-accent px-2 py-1.5 text-[10px] font-medium text-white hover:bg-accent/90 disabled:opacity-50"- :disabled="busyAction !== null"- @click="downloadFallbacks"- >- {{ busyAction === 'download' ? 'Downloading…' : 'Download fallbacks' }}- </button>- <button- type="button"- data-test-id="font-settings-refresh-cache"- class="rounded bg-input px-2 py-1.5 text-[10px] font-medium text-surface hover:bg-hover disabled:opacity-50"- :disabled="busyAction !== null"- @click="refreshSummary"- >- Refresh- </button>- <button- type="button"- data-test-id="font-settings-clear-cache"- class="rounded bg-input px-2 py-1.5 text-[10px] font-medium text-surface hover:bg-hover disabled:opacity-50"- :disabled="busyAction !== null || cacheCount === 0"- @click="clearCache"- >- Clear cache- </button>- </div>-- <p v-if="status" class="text-[10px] leading-relaxed text-muted">{{ status }}</p>- </div>- </PopoverContent>- </PopoverPortal>- </PopoverRoot>-</template>diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vueindex 733ea88c7..6792110d1 100644--- a/src/components/properties/TypographySection.vue+++ b/src/components/properties/TypographySection.vue@@ -4,7 +4,7 @@ import { ToggleGroupItem, ToggleGroupRoot } from 'reka-ui'import { TypographyControlsRoot, useI18n } from '@open-pencil/vue'import FontPicker from '@/components/FontPicker.vue'-import FontSettingsPopover from '@/components/FontSettingsPopover.vue'+import FontSettingsPopover from '@/components/FontSettings/FontSettingsPopover.vue'import ScrubInput from '@/components/ScrubInput.vue'import VariableScrubInput from '@/components/properties/VariableScrubInput.vue'import AppSelect from '@/components/ui/AppSelect.vue'diff --git a/tests/e2e/font-settings.spec.ts b/tests/e2e/font-settings.spec.tsindex 63bc248df..c9f82b5cb 100644--- a/tests/e2e/font-settings.spec.ts+++ b/tests/e2e/font-settings.spec.ts@@ -17,7 +17,7 @@ test('font settings popover is available from typography panel', async ({ page }await expect(page.locator('[data-test-id="typography-section"]')).toBeVisible()await page.locator('[data-test-id="font-settings-trigger"]').click()- await expect(page.getByText('Manage local font access')).toBeVisible()+ await expect(page.getByText('Access system fonts')).toBeVisible()await expect(page.locator('[data-test-id="font-settings-request-access"]')).toBeVisible()await expect(page.locator('[data-test-id="font-settings-download-fallbacks"]')).toBeVisible()await expect(page.locator('[data-test-id="font-settings-refresh-cache"]')).toBeVisible()diff --git a/tests/engine/font-settings.test.ts b/tests/engine/font-settings.test.tsindex 1e20bab5b..1661ab024 100644--- a/tests/engine/font-settings.test.ts+++ b/tests/engine/font-settings.test.ts@@ -28,6 +28,8 @@ describe('useFontSettings', () => {await settings.refreshSummary()expect(settings.cacheCount.value).toBe(2)+ expect(settings.accessStateLabel.value).toBe('Not requested')+ expect(settings.canRequestLocalFonts.value).toBe(true)expect(settings.cacheSize.value).toBe('1.5 MB')expect(settings.cacheUpdatedLabel.value).not.toBe('Never')expect(settings.busyAction.value).toBeNull()@@ -39,6 +41,8 @@ describe('useFontSettings', () => {await settings.requestAccess()expect(settings.accessState.value).toBe('granted')+ expect(settings.accessStateLabel.value).toBe('Enabled')+ expect(settings.canRequestLocalFonts.value).toBe(false)expect(settings.status.value).toBe('Local font access enabled.')expect(settings.busyAction.value).toBeNull()})diff --git a/tests/engine/tauri-file-actions.test.ts b/tests/engine/tauri-file-actions.test.tsnew file mode 100644index 000000000..b84fa8690--- /dev/null+++ b/tests/engine/tauri-file-actions.test.ts@@ -0,0 +1,123 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { saveExportedFile } from '@/app/document/export/files'+import { watchTauriFile } from '@/app/document/io/watch-targets'+import { chooseTauriOpenPath, readTauriDesignFile } from '@/app/shell/menu/files'+import { clearTauriMocks, mockTauriIPC } from '../helpers/tauri-mocks'++afterEach(async () => {+ await clearTauriMocks()+ // @ts-expect-error test cleanup+ delete globalThis.window+})++describe('Tauri file actions', () => {+ test('chooses a design file through plugin-dialog', async () => {+ await mockTauriIPC((cmd, args) => {+ expect(cmd).toBe('plugin:dialog|open')+ expect(args).toEqual({+ options: {+ filters: [{ name: 'Design file', extensions: ['fig', 'pen'] }],+ multiple: false+ }+ })+ return '/tmp/design.fig'+ })++ await expect(chooseTauriOpenPath()).resolves.toBe('/tmp/design.fig')+ })++ test('reads a Tauri design file into a File object', async () => {+ await mockTauriIPC((cmd, args) => {+ expect(cmd).toBe('plugin:fs|read_file')+ expect(args).toEqual({ path: '/tmp/design.pen', options: undefined })+ return [123, 34, 97, 34, 58, 49, 125]+ })++ const file = await readTauriDesignFile('/tmp/design.pen')++ expect(file.name).toBe('design.pen')+ await expect(file.text()).resolves.toBe('{"a":1}')+ })++ test('saves exports through Tauri dialog and fs APIs', async () => {+ const calls: Array<{ cmd: string; args: unknown; options: unknown }> = []+ await mockTauriIPC((cmd, args, options) => {+ calls.push({ cmd, args, options })+ if (cmd === 'plugin:dialog|save') return '/tmp/export.png'+ return null+ })++ await saveExportedFile(+ new Uint8Array([1, 2, 3]),+ '[email protected]',+ 'PNG',+ '.png',+ 'image/png',+ () => {+ throw new Error('browser download should not run in Tauri')+ }+ )++ expect(calls[0]).toEqual({+ cmd: 'plugin:dialog|save',+ args: {+ options: {+ defaultPath: '[email protected]',+ filters: [{ name: 'PNG', extensions: ['png'] }]+ }+ },+ options: undefined+ })+ expect(calls[1]?.cmd).toBe('plugin:fs|write_file')+ expect([...new Uint8Array(calls[1]?.args as ArrayBuffer)]).toEqual([1, 2, 3])+ expect(calls[1]?.options).toEqual({+ headers: { path: '%2Ftmp%2Fexport.png', options: undefined }+ })+ })++ test('watches Tauri files and ignores recent local writes', async () => {+ let onEvent: ((event: unknown) => void) | null = null+ const calls: string[] = []+ await mockTauriIPC((cmd, args) => {+ if (cmd === 'plugin:fs|watch') {+ expect(args).toMatchObject({+ paths: ['/tmp/design.fig'],+ options: { delayMs: 500 }+ })+ onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent.onmessage+ return 7+ }+ calls.push(cmd)+ return null+ })++ const unwatch = await watchTauriFile(+ '/tmp/design.fig',+ () => 0,+ () => calls.push('reload')+ )+ onEvent?.({ type: { modify: { kind: 'data' } } })+ expect(calls).toEqual(['reload'])++ await clearTauriMocks()+ await mockTauriIPC((cmd, args) => {+ if (cmd === 'plugin:fs|watch') {+ onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent.onmessage+ return 8+ }+ calls.push(cmd)+ return null+ })+ calls.length = 0+ await watchTauriFile(+ '/tmp/design.fig',+ () => Date.now(),+ () => calls.push('reload')+ )+ onEvent?.({ type: { modify: { kind: 'data' } } })+ expect(calls).toEqual([])++ unwatch()+ })+})