Skip to content

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

refactor: handle file names and paths with pathe (#1491)

Danila Poyarkovd5fc0804f7a8
diff --git a/bun.lock b/bun.lock
index a24ae98a8..af52b166a 100644
--- a/bun.lock
+++ b/bun.lock
@@ -80,6 +80,7 @@
"nanostores": "^1.5.4",
"opentype.js": "^2.0.0",
"partial-json": "^0.1.7",
+ "pathe": "^2.0.3",
"qrcode": "1.5.4",
"reka-ui": "^2.10.5",
"svg2pdf.js": "^2.8.1",
@@ -286,6 +287,7 @@
"ofetch": "^1.5.1",
"opentype.js": "^2.0.0",
"parse5": "^8.0.1",
+ "pathe": "^2.0.3",
"pixelmatch": "^7.2.0",
"pptxgenjs": "^4.0.1",
"rbush": "^4.0.1",
diff --git a/changes/1491/fixed.md b/changes/1491/fixed.md
new file mode 100644
index 000000000..752a36071
--- /dev/null
+++ b/changes/1491/fixed.md
@@ -0,0 +1 @@
+- Documents opened from disk in the Windows desktop app are named by their file, not by their whole path.
diff --git a/package.json b/package.json
index 60a35f26b..16f943d8e 100644
--- a/package.json
+++ b/package.json
@@ -195,6 +195,7 @@
"nanostores": "^1.5.4",
"opentype.js": "^2.0.0",
"partial-json": "^0.1.7",
+ "pathe": "^2.0.3",
"qrcode": "1.5.4",
"reka-ui": "^2.10.5",
"svg2pdf.js": "^2.8.1",
diff --git a/packages/core/package.json b/packages/core/package.json
index 28e3c3c56..44261f781 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -204,6 +204,7 @@
"ofetch": "^1.5.1",
"opentype.js": "^2.0.0",
"parse5": "^8.0.1",
+ "pathe": "^2.0.3",
"pixelmatch": "^7.2.0",
"pptxgenjs": "^4.0.1",
"rbush": "^4.0.1",
diff --git a/packages/core/src/editor/clipboard/assets.ts b/packages/core/src/editor/clipboard/assets.ts
index 5c2be5c95..e7e628996 100644
--- a/packages/core/src/editor/clipboard/assets.ts
+++ b/packages/core/src/editor/clipboard/assets.ts
@@ -1,4 +1,5 @@
import { sumBy } from 'es-toolkit'
+import { filename } from 'pathe/utils'
import type { Fill } from '@open-pencil/scene-graph'
import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
@@ -82,7 +83,7 @@ export function createClipboardAssetActions(
? {
kind: 'svg',
data,
- name: file.name.replace(/\.svg$/i, '') || undefined,
+ name: filename(file.name) || undefined,
width: data.width,
height: data.height
}
@@ -117,7 +118,7 @@ export function createClipboardAssetActions(
visible: true
}
return ctx.graph.createNode('RECTANGLE', parentId, {
- name: asset.name.replace(/\.[^.]+$/, ''),
+ name: filename(asset.name) ?? asset.name,
x,
y,
width: asset.width,
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index e7b439506..a769bc6c4 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -1,4 +1,5 @@
import { groupBy } from 'es-toolkit'
+import { filename } from 'pathe/utils'
import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'
import { isDrawIOExportFileName } from '@open-pencil/drawio'
@@ -221,7 +222,7 @@ async function writeFig(
renderer: context?.renderer,
pageId,
renderHeadlessThumbnail: options?.renderThumbnail ?? false,
- documentName: options?.documentName ?? fileName?.replace(/\.fig$/i, '')
+ documentName: options?.documentName ?? (fileName && filename(fileName))
})
return { format: 'fig', mimeType: 'application/octet-stream', extension: 'fig', data }
}
diff --git a/packages/core/src/io/formats/design-tokens/read.ts b/packages/core/src/io/formats/design-tokens/read.ts
index 003ca051d..9d2118202 100644
--- a/packages/core/src/io/formats/design-tokens/read.ts
+++ b/packages/core/src/io/formats/design-tokens/read.ts
@@ -1,4 +1,5 @@
import { isPlainObject } from 'es-toolkit/predicate'
+import { basename, dirname, join, normalize } from 'pathe'
import * as v from 'valibot'
import { pathName } from './paths'
@@ -131,24 +132,29 @@ export function documentTokens(parsed: Record<string, unknown>): ReadToken[] {
/** `a/b/c.tokens.json` is `c`; `.tokens`, `.tokens.json`, and `.json` all go. */
function baseName(path: string): string {
- const file = path.split('/').at(-1) ?? path
- return file.replace(/\.tokens(\.json)?$|\.json$/i, '')
+ return basename(path).replace(/\.tokens(\.json)?$|\.json$/i, '')
}
+/** The folder a picked file sits in, or `''` for a file picked on its own. */
function folderOf(path: string): string {
- return path.split('/').slice(0, -1).join('/')
+ const folder = dirname(path)
+ return folder === '.' ? '' : folder
}
-/** A `$ref` as a path among the picked files, relative to the file it appears in. */
+/**
+ * `path` as the picked files spell theirs: forward slashes, and nothing above their top, since
+ * nothing was picked from outside them.
+ */
+function pickedPath(path: string): string {
+ return normalize(path).replace(/^(?:\.\.\/|\/)+/, '')
+}
+
+/**
+ * A `$ref` as a path among the picked files: from the top of the picked folders when it starts
+ * with `/`, otherwise relative to the file it appears in.
+ */
function resolveRef(from: string, ref: string): string {
- const segments = [...folderOf(from).split('/'), ...ref.split('/')]
- const resolved: string[] = []
- for (const segment of segments) {
- if (segment === '' || segment === '.') continue
- if (segment === '..') resolved.pop()
- else resolved.push(segment)
- }
- return resolved.join('/')
+ return pickedPath(ref.startsWith('/') ? ref : join(folderOf(from), ref))
}
/**
@@ -158,8 +164,8 @@ function resolveRef(from: string, ref: string): string {
function findRef(reader: Reader, from: string, ref: string): string {
const path = resolveRef(from, ref)
if (reader.documents.has(path)) return path
- const name = path.split('/').at(-1)
- const matches = [...reader.documents.keys()].filter((key) => key.split('/').at(-1) === name)
+ const name = basename(path)
+ const matches = [...reader.documents.keys()].filter((key) => basename(key) === name)
return matches.length === 1 ? matches[0] : path
}
@@ -291,7 +297,7 @@ function readModeFiles(paths: readonly string[], reader: Reader): ReadCollection
// collection they name, or into one.
const folder = folderOf(path)
const key = folder || info.collection || ''
- const name = info.collection ?? (folder.split('/').at(-1) || 'Tokens')
+ const name = info.collection ?? (basename(folder) || 'Tokens')
const collection = collections.get(key) ?? { name, modes: [], modeAttribute: undefined }
collection.modeAttribute ??= info.modeAttribute
collection.modes.push({
@@ -333,7 +339,7 @@ export function readDesignTokens(files: readonly DesignTokenSourceFile[]): Desig
const reader: Reader = { documents: new Map(), used: new Set(), issues: [] }
for (const file of files) {
const result = v.safeParse(documentSchema, file.text)
- if (result.success) reader.documents.set(file.path, result.output)
+ if (result.success) reader.documents.set(pickedPath(file.path), result.output)
else reader.issues.push({ kind: 'invalid-file', file: file.path })
}
const collections: ReadCollection[] = []
diff --git a/packages/core/src/io/formats/html/index.ts b/packages/core/src/io/formats/html/index.ts
index afd7b7fea..5d494b5de 100644
--- a/packages/core/src/io/formats/html/index.ts
+++ b/packages/core/src/io/formats/html/index.ts
@@ -1,3 +1,5 @@
+import { filename } from 'pathe/utils'
+
import {
exportHTMLBundle,
sceneNodeToDesignDocument,
@@ -22,10 +24,7 @@ function designDocument(graph: SceneGraph, nodeIds: string[]): DesignDocument {
/** `card.html` keeps its external files in `card.assets/` next to it, whatever the path style. */
function assetBasePath(fileName: string | undefined): string {
- const name = fileName
- ?.split(/[\\/]/)
- .pop()
- ?.replace(/\.[^.]*$/, '')
+ const name = fileName && filename(fileName)
return `${name || 'export'}.assets`
}
diff --git a/packages/core/tests/io/formats/design-tokens/import.test.ts b/packages/core/tests/io/formats/design-tokens/import.test.ts
index 4c70e8cf7..60aa0a4c0 100644
--- a/packages/core/tests/io/formats/design-tokens/import.test.ts
+++ b/packages/core/tests/io/formats/design-tokens/import.test.ts
@@ -81,6 +81,39 @@ describe('reading token files', () => {
expect(bundle.collections[0].modes[0].tokens.map((token) => token.name)).toEqual(['gap'])
})
+ test('a resolver ref is relative to its file, from the top with `/`, and never above the top', () => {
+ const tokens = (name: string) => ({ [name]: { $type: 'number', $value: 1 } })
+ const bundle = readDesignTokens(
+ files({
+ 'Theme\\Sub\\tokens.resolver.json': {
+ version: '2025-11-01',
+ sets: {
+ Nested: { sources: [{ $ref: 'shared.json' }] },
+ Sibling: { sources: [{ $ref: '../shared.json' }] },
+ Top: { sources: [{ $ref: '/shared.json' }] },
+ Above: { sources: [{ $ref: '../../../../shared.json' }] }
+ },
+ resolutionOrder: ['Nested', 'Sibling', 'Top', 'Above'].map((name) => ({
+ $ref: `#/sets/${name}`
+ }))
+ },
+ 'shared.json': tokens('top'),
+ 'Theme/shared.json': tokens('theme'),
+ 'Theme/Sub/shared.json': tokens('sub')
+ })
+ )
+
+ expect(bundle.issues).toEqual([])
+ expect(
+ bundle.collections.map((collection) => [collection.name, collection.modes[0].tokens[0].name])
+ ).toEqual([
+ ['Nested', 'sub'],
+ ['Sibling', 'theme'],
+ ['Top', 'top'],
+ ['Above', 'top']
+ ])
+ })
+
test('Tokens Studio themes become modes of their group, and the sets they refer to collections', () => {
const bundle = readDesignTokens(
files({
diff --git a/src/app/ai/attachment/image/prepare.ts b/src/app/ai/attachment/image/prepare.ts
index 815677a8c..b894bfd2f 100644
--- a/src/app/ai/attachment/image/prepare.ts
+++ b/src/app/ai/attachment/image/prepare.ts
@@ -1,3 +1,5 @@
+import { filename } from 'pathe/utils'
+
import { isSVGFile } from '@open-pencil/scene-graph/images'
import type {
@@ -90,7 +92,7 @@ export async function rasterizeSVGAttachment(
if (!context) throw new Error('Could not prepare the image.')
context.drawImage(image, 0, 0, canvas.width, canvas.height)
const blob = await canvasToBlob(canvas, 'image/png')
- const name = file.name.replace(/\.svg$/i, '') + '.png'
+ const name = `${filename(file.name) ?? file.name}.png`
return new File([blob], name, { type: 'image/png' })
} finally {
revokeImagePreviewURL(sourceURL)
diff --git a/src/app/cache/index.ts b/src/app/cache/index.ts
index 41e73e53b..6f394ff30 100644
--- a/src/app/cache/index.ts
+++ b/src/app/cache/index.ts
@@ -1,3 +1,4 @@
+import { dirname } from 'pathe'
import * as v from 'valibot'
import { IS_TAURI } from '@open-pencil/core/constants'
@@ -21,10 +22,7 @@ function cachePath(key: string) {
}
function cacheDirectoryPath(key: string) {
- const segments = key.split('/').slice(0, -1)
- return segments.length > 0
- ? `${APP_CACHE_DIR}/${segments.map(encodeURIComponent).join('/')}`
- : APP_CACHE_DIR
+ return dirname(cachePath(key))
}
function storageKey(key: string) {
diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.ts
index 2ae1191c7..55ef8c41f 100644
--- a/src/app/document/export/files.ts
+++ b/src/app/document/export/files.ts
@@ -1,4 +1,5 @@
import { zipSync, type Zippable } from 'fflate'
+import { extname } from 'pathe'
import type { Editor, EditorState } from '@open-pencil/core'
import {
@@ -52,9 +53,8 @@ export function bundleExportFiles(files: ExportedFile[]): Uint8Array {
for (const file of files) {
let name = sanitizeZipEntryName(file.fileName)
if (used.has(name)) {
- const dot = name.lastIndexOf('.')
- const stem = dot === -1 ? name : name.slice(0, dot)
- const tail = dot === -1 ? '' : name.slice(dot)
+ const tail = extname(name)
+ const stem = name.slice(0, name.length - tail.length)
let i = 2
while (used.has(`${stem} (${i})${tail}`)) i++
name = `${stem} (${i})${tail}`
diff --git a/src/app/document/io/names.ts b/src/app/document/io/names.ts
index ba7453a8f..40ab99a4a 100644
--- a/src/app/document/io/names.ts
+++ b/src/app/document/io/names.ts
@@ -1,16 +1,14 @@
+import { basename } from 'pathe'
+import { filename } from 'pathe/utils'
+
export function documentNameFromFigPath(path: string): string {
- return (
- path
- .split(/[\\/]/)
- .pop()
- ?.replace(/\.fig$/i, '') ?? 'Untitled'
- )
+ return filename(path) || 'Untitled'
}
export function downloadNameFromPath(path: string): string {
- return path.split(/[\\/]/).pop() ?? 'Untitled.fig'
+ return basename(path) || 'Untitled.fig'
}
export function figDownloadName(fileName: string, sourceFormat: string): string {
- return sourceFormat === 'fig' ? fileName : fileName.replace(/\.[^.]+$/i, '.fig')
+ return sourceFormat === 'fig' ? fileName : `${filename(fileName) ?? fileName}.fig`
}
diff --git a/src/app/document/io/pending-open.ts b/src/app/document/io/pending-open.ts
index dfd74a047..6f10d2732 100644
--- a/src/app/document/io/pending-open.ts
+++ b/src/app/document/io/pending-open.ts
@@ -1,3 +1,5 @@
+import { basename } from 'pathe'
+
// The queue the desktop shell fills before the editor exists: a double-clicked
// document, an `Open With`, an argv path, or an `openpencil://` link. Rust tags each
// entry with its producer because the frontend cannot tell them apart from the path
@@ -25,7 +27,7 @@ export interface PendingOpenIo {
const tauriIo: PendingOpenIo = { openPath: openFileFromPath, openLink: openDeepLink }
function displayName(file: PendingOpenFile): string {
- return file.path.split(/[/\\]/).pop() ?? file.path
+ return basename(file.path) || file.path
}
/**
diff --git a/src/app/document/io/read.ts b/src/app/document/io/read.ts
index 5e9924597..2cac6c5a6 100644
--- a/src/app/document/io/read.ts
+++ b/src/app/document/io/read.ts
@@ -1,3 +1,5 @@
+import { filename } from 'pathe/utils'
+
import type { Editor, EditorState } from '@open-pencil/core'
import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'
@@ -56,7 +58,7 @@ export function createOpenActions({
await yieldToUI()
load.update({ phase: 'materializing', detail: file.name })
await applyImportedDocument(editor, imported, load)
- state.documentName = file.name.replace(/\.fig$/i, '')
+ state.documentName = filename(file.name) ?? file.name
setDocumentSource(file.name, 'fig', handle, path)
await fitCurrentPageToViewport()
load.update({ phase: 'preparing-render', detail: state.documentName })
diff --git a/src/app/recent-files/store.ts b/src/app/recent-files/store.ts
index 0bc3c6f98..a2c2dbc5d 100644
--- a/src/app/recent-files/store.ts
+++ b/src/app/recent-files/store.ts
@@ -1,4 +1,5 @@
import { useLocalStorage } from '@vueuse/core'
+import { basename } from 'pathe'
import { computed } from 'vue'
import {
@@ -38,7 +39,7 @@ export type RecentDocument = RecentLocalDocument | RecentStorageDocument
export const recentDocuments = useLocalStorage<RecentDocument[]>(RECENT_DOCUMENTS_STORAGE_KEY, [])
function fileName(path: string): string {
- return path.split(/[\\/]/).pop() ?? path
+ return basename(path) || path
}
function localDocumentId(path: string): string {
diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.ts
index 8073bb050..5602b87fc 100644
--- a/src/app/shell/menu/files.ts
+++ b/src/app/shell/menu/files.ts
@@ -1,5 +1,6 @@
import { useFileDialog } from '@vueuse/core'
import { uniq } from 'es-toolkit/array'
+import { basename } from 'pathe'
import { decode } from 'ufo'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
@@ -63,7 +64,7 @@ if (IS_BROWSER && 'window' in globalThis) {
* escape stays as written.
*/
function fileNameFromURL(url: URL): string {
- return decode(url.pathname.split('/').pop() ?? '') || 'file.fig'
+ return decode(basename(url.pathname)) || 'file.fig'
}
/** Fetches a document over HTTP and opens it in a new tab. Browser builds only. */
@@ -124,7 +125,7 @@ export async function readTauriDesignFile(path: string): Promise<File> {
assertSupportedDesignFile(path)
const { readFile } = await import('@tauri-apps/plugin-fs')
const bytes = await readFile(path)
- return new File([bytes], path.split('/').pop() ?? 'file.fig')
+ return new File([bytes], basename(path) || 'file.fig')
}
export async function chooseTauriOpenPaths(): Promise<string[]> {
@@ -161,7 +162,7 @@ export async function activateTabForPath(path: string): Promise<boolean> {
export async function openFileDialog() {
if (isTauri()) {
const paths = await chooseTauriOpenPaths()
- await openDesignFileBatch(paths, (path) => path.split(/[/\\]/).pop() ?? path, openFileFromPath)
+ await openDesignFileBatch(paths, (path) => basename(path) || path, openFileFromPath)
return
}
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index a91cf20ed..fb9241d5e 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -1,4 +1,5 @@
import { promiseTimeout } from '@vueuse/core'
+import { filename } from 'pathe/utils'
import { shallowRef, computed, triggerRef } from 'vue'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
@@ -506,7 +507,7 @@ export async function openFileInNewTab(
const opening = reusableTabStore()
const { store } = opening
- store.state.documentName = file.name.replace(/\.[^.]+$/i, '')
+ store.state.documentName = filename(file.name) ?? file.name
const load = store.preparationController.begin({
kind: isDOMImportFile(file) ? 'dom-import' : 'document-open',
subject: file.name
diff --git a/tests/app/document/io/names.test.ts b/tests/app/document/io/names.test.ts
new file mode 100644
index 000000000..fc7b19592
--- /dev/null
+++ b/tests/app/document/io/names.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ documentNameFromFigPath,
+ downloadNameFromPath,
+ figDownloadName
+} from '@/app/document/io/names'
+
+describe('document names from paths', () => {
+ test('take the last segment of POSIX and Windows paths alike', () => {
+ expect(documentNameFromFigPath('/Users/me/Landing page.fig')).toBe('Landing page')
+ expect(documentNameFromFigPath('C:\\Users\\me\\Landing page.FIG')).toBe('Landing page')
+ expect(downloadNameFromPath('C:\\Users\\me\\Landing page.fig')).toBe('Landing page.fig')
+ })
+
+ test('fall back to Untitled for a path with no file name', () => {
+ expect(documentNameFromFigPath('')).toBe('Untitled')
+ expect(downloadNameFromPath('')).toBe('Untitled.fig')
+ })
+
+ test('save a document read from another format under a .fig name', () => {
+ expect(figDownloadName('Landing.fig', 'fig')).toBe('Landing.fig')
+ expect(figDownloadName('Landing.pen', 'pen')).toBe('Landing.fig')
+ expect(figDownloadName('Landing', 'html')).toBe('Landing.fig')
+ })
+})
diff --git a/tests/engine/tauri/file-actions.test.ts b/tests/engine/tauri/file-actions.test.ts
index 815c333b1..0cffb421b 100644
--- a/tests/engine/tauri/file-actions.test.ts
+++ b/tests/engine/tauri/file-actions.test.ts
@@ -51,6 +51,14 @@ describe('Tauri file actions', () => {
await expect(file.text()).resolves.toBe('{"a":1}')
})
+ test('names a file read from a Windows path by its last segment', async () => {
+ await mockTauriIPC(() => [123, 125])
+
+ const file = await readTauriDesignFile('C:\\Users\\me\\Design File.pen')
+
+ expect(file.name).toBe('Design File.pen')
+ })
+
test('saves exports through Tauri dialog and fs APIs', async () => {
const calls: Array<{ cmd: string; args: unknown; options: unknown }> = []
await mockTauriIPC((cmd, args, options) => {