From a5d49a59c3776dd94bf43922a5ba8b3ee3b35f7e Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:23:18 +0800 Subject: [PATCH 01/19] feat(storage): begin browser project file adapter --- src/services/storage/browserProjectFile.ts | 73 ++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/services/storage/browserProjectFile.ts diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts new file mode 100644 index 0000000..f9d1701 --- /dev/null +++ b/src/services/storage/browserProjectFile.ts @@ -0,0 +1,73 @@ +import type { BasProjectData } from "@/types/storage"; +import { normalizeProjectData } from "./projectSchema"; + +type DirectoryPermission = FileSystemDirectoryHandle & { + queryPermission(descriptor: { mode: "read" | "readwrite" }): Promise; + requestPermission(descriptor: { mode: "read" | "readwrite" }): Promise; +}; + +type DirectoryPicker = Window & { + showDirectoryPicker(options?: { mode?: "read" | "readwrite" }): Promise; +}; + +export type BrowserProjectFile = { + directory: FileSystemDirectoryHandle; + fileName: string; + fingerprint: string; + project: BasProjectData; +}; + +/** 文件夹权限可能在页面重启或浏览器重启后失效。申请权限必须由用户操作触发。 */ +export async function ensureDirectoryPermission(directory: FileSystemDirectoryHandle, request = false): Promise { + const handle = directory as DirectoryPermission; + if (typeof handle.queryPermission !== "function") return false; + if ((await handle.queryPermission({ mode: "readwrite" })) === "granted") return true; + return request && typeof handle.requestPermission === "function" && + (await handle.requestPermission({ mode: "readwrite" })) === "granted"; +} + +export async function pickProjectDirectory(): Promise { + if (!("showDirectoryPicker" in window)) throw new Error("DIRECTORY_PICKER_UNSUPPORTED"); + return (window as DirectoryPicker).showDirectoryPicker({ mode: "readwrite" }); +} + +/** 只能访问选定目录中的直接子文件,不能使用路径分隔符或相对路径穿越。 */ +function validateFileName(fileName: string): void { + if (!fileName || fileName === "." || fileName === ".." || /[\\/\0]/.test(fileName) || !fileName.endsWith(".basproj")) { + throw new Error("INVALID_PROJECT_FILE_NAME"); + } +} + +async function digest(contents: string): Promise { + const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(contents)); + return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +export async function openBrowserProject(directory: FileSystemDirectoryHandle, fileName: string): Promise { + validateFileName(fileName); + if (!(await ensureDirectoryPermission(directory))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const file = await (await directory.getFileHandle(fileName)).getFile(); + const contents = await file.text(); + return { directory, fileName, project: normalizeProjectData(JSON.parse(contents)), fingerprint: await digest(contents) }; +} + +/** 检测外部更改后才写入;浏览器文件系统 API 不提供跨进程原子比较并交换。 */ +export async function saveBrowserProject(opened: BrowserProjectFile, project: BasProjectData): Promise { + validateFileName(opened.fileName); + if (!(await ensureDirectoryPermission(opened.directory))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const handle = await opened.directory.getFileHandle(opened.fileName); + const current = await (await handle.getFile()).text(); + if ((await digest(current)) !== opened.fingerprint) throw new Error("PROJECT_MODIFIED_EXTERNALLY"); + const normalized = normalizeProjectData(project); + if (normalized.id !== opened.project.id) throw new Error("PROJECT_ID_MISMATCH"); + const contents = JSON.stringify(normalized, null, 2); + const writable = await handle.createWritable(); + try { + await writable.write(contents); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => {}); + throw error; + } + return { ...opened, project: normalized, fingerprint: await digest(contents) }; +} From 522aff12468b96bc97c7dec481aa0cadb45c0be9 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:25:09 +0800 Subject: [PATCH 02/19] feat(storage): add browser directory project creation --- src/services/storage/browserProjectFile.ts | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index f9d1701..dd7d9de 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -1,4 +1,5 @@ import type { BasProjectData } from "@/types/storage"; +import { idbDelete, idbGet, idbSet, STORES } from "./indexedDB"; import { normalizeProjectData } from "./projectSchema"; type DirectoryPermission = FileSystemDirectoryHandle & { @@ -17,6 +18,29 @@ export type BrowserProjectFile = { project: BasProjectData; }; +/** 目录句柄只作为最近项目索引;项目内容以用户目录中的文件为准。 */ +export type BrowserProjectLocation = { + projectId: string; + directory: FileSystemDirectoryHandle; + fileName: string; +}; + +const LOCATION_PREFIX = "browser-project-location:"; + +export async function rememberBrowserProject(location: BrowserProjectLocation): Promise { + validateFileName(location.fileName); + await idbSet(STORES.PROJECTS, LOCATION_PREFIX + location.projectId, location); +} + +export async function findBrowserProjectLocation(projectId: string): Promise { + return idbGet(STORES.PROJECTS, LOCATION_PREFIX + projectId); +} + +/** 移除最近项目记录,不删除用户目录中的任何文件。 */ +export async function forgetBrowserProject(projectId: string): Promise { + await idbDelete(STORES.PROJECTS, LOCATION_PREFIX + projectId); +} + /** 文件夹权限可能在页面重启或浏览器重启后失效。申请权限必须由用户操作触发。 */ export async function ensureDirectoryPermission(directory: FileSystemDirectoryHandle, request = false): Promise { const handle = directory as DirectoryPermission; @@ -51,6 +75,30 @@ export async function openBrowserProject(directory: FileSystemDirectoryHandle, f return { directory, fileName, project: normalizeProjectData(JSON.parse(contents)), fingerprint: await digest(contents) }; } +/** 只在用户选定的空目录中初始化文件,已有文件或目录都不覆盖。 */ +export async function createBrowserProject( + directory: FileSystemDirectoryHandle, + fileName: string, + project: BasProjectData +): Promise { + validateFileName(fileName); + if (!(await ensureDirectoryPermission(directory))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const iterable = directory as FileSystemDirectoryHandle & { values(): AsyncIterable }; + for await (const _entry of iterable.values()) throw new Error("DIRECTORY_NOT_EMPTY"); + const normalized = normalizeProjectData(project); + const contents = JSON.stringify(normalized, null, 2); + const handle = await directory.getFileHandle(fileName, { create: true }); + const writable = await handle.createWritable(); + try { + await writable.write(contents); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => {}); + throw error; + } + return { directory, fileName, project: normalized, fingerprint: await digest(contents) }; +} + /** 检测外部更改后才写入;浏览器文件系统 API 不提供跨进程原子比较并交换。 */ export async function saveBrowserProject(opened: BrowserProjectFile, project: BasProjectData): Promise { validateFileName(opened.fileName); From f7f77e92c6f84a03d7fdf67cd420af768bbe8dc0 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:25:59 +0800 Subject: [PATCH 03/19] feat(storage): add browser media handle support --- src/services/storage/browserMediaFile.ts | 51 ++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/services/storage/browserMediaFile.ts diff --git a/src/services/storage/browserMediaFile.ts b/src/services/storage/browserMediaFile.ts new file mode 100644 index 0000000..557e0bf --- /dev/null +++ b/src/services/storage/browserMediaFile.ts @@ -0,0 +1,51 @@ +import { idbDelete, idbGet, idbSet, STORES } from "./indexedDB"; + +type ReadPermissionHandle = FileSystemFileHandle & { + queryPermission(descriptor: { mode: "read" }): Promise; + requestPermission(descriptor: { mode: "read" }): Promise; +}; + +type FilePicker = Window & { + showOpenFilePicker(options?: { multiple?: boolean; types?: { description: string; accept: Record }[] }): Promise; +}; + +const mediaKey = (projectId: string, mediaId: string): string => `browser-media-handle:${encodeURIComponent(projectId)}:${encodeURIComponent(mediaId)}`; + +/** 选择文件须由用户操作直接触发;浏览器不会暴露真实的本机绝对路径。 */ +export async function pickBrowserAudio(): Promise { + if (!("showOpenFilePicker" in window)) throw new Error("FILE_PICKER_UNSUPPORTED"); + const [handle] = await (window as FilePicker).showOpenFilePicker({ + multiple: false, + types: [{ description: "Audio", accept: { "audio/*": [".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac"] } }] + }); + return handle ?? null; +} + +/** 授权可能失效;只在用户交互中允许重新请求。 */ +export async function ensureBrowserMediaPermission(handle: FileSystemFileHandle, request = false): Promise { + const file = handle as ReadPermissionHandle; + if (typeof file.queryPermission !== "function") return false; + if ((await file.queryPermission({ mode: "read" })) === "granted") return true; + return request && typeof file.requestPermission === "function" && + (await file.requestPermission({ mode: "read" })) === "granted"; +} + +/** 仅保存浏览器授权句柄,不复制、不修改用户的原始媒体文件。 */ +export async function rememberBrowserMedia(projectId: string, mediaId: string, handle: FileSystemFileHandle): Promise { + if (!projectId || !mediaId) throw new Error("INVALID_MEDIA_ID"); + await idbSet(STORES.MEDIA_BLOBS, mediaKey(projectId, mediaId), handle); +} + +export async function getBrowserMediaHandle(projectId: string, mediaId: string): Promise { + return idbGet(STORES.MEDIA_BLOBS, mediaKey(projectId, mediaId)); +} + +export async function readBrowserMedia(handle: FileSystemFileHandle): Promise { + if (!(await ensureBrowserMediaPermission(handle))) throw new Error("MEDIA_PERMISSION_REQUIRED"); + return handle.getFile(); +} + +/** 删除索引,不删除原文件。 */ +export async function forgetBrowserMedia(projectId: string, mediaId: string): Promise { + await idbDelete(STORES.MEDIA_BLOBS, mediaKey(projectId, mediaId)); +} From ad4862c8363a32a514625280f70acae21bd01c9e Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:28:33 +0800 Subject: [PATCH 04/19] test(storage): cover browser project files --- package.json | 4 +- pnpm-lock.yaml | 341 ++++++++++++++++++++++++++--- tests/browser-project-file.test.ts | 62 ++++++ 3 files changed, 377 insertions(+), 30 deletions(-) create mode 100644 tests/browser-project-file.test.ts diff --git a/package.json b/package.json index 58a1e02..2dcb737 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "build:renderer": "run-p type-check \"build-only {@}\" --", "build-only": "vite build", "preview": "vite preview", - "type-check": "vue-tsc --build" + "type-check": "vue-tsc --build", + "test:storage": "node --import tsx --test tests/browser-project-file.test.ts" }, "dependencies": { "@dantheman827/taglib-ts": "^0.1.5", @@ -48,6 +49,7 @@ "@vitejs/plugin-vue-jsx": "^5.1.2", "@vue/tsconfig": "^0.8.1", "npm-run-all2": "^8.0.4", + "tsx": "^4.23.15", "tw-animate-css": "^1.4.0", "typescript": "~5.9.0", "vite": "^7.2.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d97008a..0a4c7e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,7 +13,7 @@ importers: version: 0.1.5 '@tailwindcss/vite': specifier: ^4.1.17 - version: 4.1.17(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) + version: 4.1.17(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) '@tauri-apps/api': specifier: ^2.12.4 version: 2.12.4 @@ -83,16 +83,19 @@ importers: version: 24.10.1 '@vitejs/plugin-vue': specifier: ^6.0.2 - version: 6.0.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) + version: 6.0.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) '@vitejs/plugin-vue-jsx': specifier: ^5.1.2 - version: 5.1.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) + version: 5.1.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) '@vue/tsconfig': specifier: ^0.8.1 version: 0.8.1(typescript@5.9.3)(vue@3.5.25(typescript@5.9.3)) npm-run-all2: specifier: ^8.0.4 version: 8.0.4 + tsx: + specifier: ^4.23.15 + version: 4.23.15 tw-animate-css: specifier: ^1.4.0 version: 1.4.0 @@ -101,10 +104,10 @@ importers: version: 5.9.3 vite: specifier: ^7.2.4 - version: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + version: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) vite-plugin-vue-devtools: specifier: ^8.0.5 - version: 8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) + version: 8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) vue-tsc: specifier: ^3.1.5 version: 3.1.5(typescript@5.9.3) @@ -500,156 +503,312 @@ packages: cpu: [ppc64] os: [aix] + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + '@esbuild/android-arm64@0.25.12': resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} engines: {node: '>=18'} cpu: [arm64] os: [android] + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + '@esbuild/android-arm@0.25.12': resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} engines: {node: '>=18'} cpu: [arm] os: [android] + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + '@esbuild/android-x64@0.25.12': resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} engines: {node: '>=18'} cpu: [x64] os: [android] + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + '@esbuild/darwin-arm64@0.25.12': resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + '@esbuild/darwin-x64@0.25.12': resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} engines: {node: '>=18'} cpu: [x64] os: [darwin] + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + '@esbuild/freebsd-arm64@0.25.12': resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + '@esbuild/freebsd-x64@0.25.12': resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + '@esbuild/linux-arm64@0.25.12': resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} engines: {node: '>=18'} cpu: [arm64] os: [linux] + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + '@esbuild/linux-arm@0.25.12': resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} engines: {node: '>=18'} cpu: [arm] os: [linux] + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + '@esbuild/linux-ia32@0.25.12': resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} engines: {node: '>=18'} cpu: [ia32] os: [linux] + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + '@esbuild/linux-loong64@0.25.12': resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} engines: {node: '>=18'} cpu: [loong64] os: [linux] + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + '@esbuild/linux-mips64el@0.25.12': resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + '@esbuild/linux-ppc64@0.25.12': resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + '@esbuild/linux-riscv64@0.25.12': resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + '@esbuild/linux-s390x@0.25.12': resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} engines: {node: '>=18'} cpu: [s390x] os: [linux] + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + '@esbuild/linux-x64@0.25.12': resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} engines: {node: '>=18'} cpu: [x64] os: [linux] + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + '@esbuild/netbsd-arm64@0.25.12': resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + '@esbuild/netbsd-x64@0.25.12': resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + '@esbuild/openbsd-arm64@0.25.12': resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + '@esbuild/openbsd-x64@0.25.12': resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + '@esbuild/openharmony-arm64@0.25.12': resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + '@esbuild/sunos-x64@0.25.12': resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} engines: {node: '>=18'} cpu: [x64] os: [sunos] + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + '@esbuild/win32-arm64@0.25.12': resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} engines: {node: '>=18'} cpu: [arm64] os: [win32] + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + '@esbuild/win32-ia32@0.25.12': resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} engines: {node: '>=18'} cpu: [ia32] os: [win32] + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + '@esbuild/win32-x64@0.25.12': resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} engines: {node: '>=18'} cpu: [x64] os: [win32] + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + '@floating-ui/core@1.7.3': resolution: {integrity: sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==} @@ -1401,6 +1560,11 @@ packages: engines: {node: '>=18'} hasBin: true + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -1817,6 +1981,11 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsx@4.23.15: + resolution: {integrity: sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==} + engines: {node: '>=18.0.0'} + hasBin: true + tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} @@ -2411,81 +2580,159 @@ snapshots: '@esbuild/aix-ppc64@0.25.12': optional: true + '@esbuild/aix-ppc64@0.28.2': + optional: true + '@esbuild/android-arm64@0.25.12': optional: true + '@esbuild/android-arm64@0.28.2': + optional: true + '@esbuild/android-arm@0.25.12': optional: true + '@esbuild/android-arm@0.28.2': + optional: true + '@esbuild/android-x64@0.25.12': optional: true + '@esbuild/android-x64@0.28.2': + optional: true + '@esbuild/darwin-arm64@0.25.12': optional: true + '@esbuild/darwin-arm64@0.28.2': + optional: true + '@esbuild/darwin-x64@0.25.12': optional: true + '@esbuild/darwin-x64@0.28.2': + optional: true + '@esbuild/freebsd-arm64@0.25.12': optional: true + '@esbuild/freebsd-arm64@0.28.2': + optional: true + '@esbuild/freebsd-x64@0.25.12': optional: true + '@esbuild/freebsd-x64@0.28.2': + optional: true + '@esbuild/linux-arm64@0.25.12': optional: true + '@esbuild/linux-arm64@0.28.2': + optional: true + '@esbuild/linux-arm@0.25.12': optional: true + '@esbuild/linux-arm@0.28.2': + optional: true + '@esbuild/linux-ia32@0.25.12': optional: true + '@esbuild/linux-ia32@0.28.2': + optional: true + '@esbuild/linux-loong64@0.25.12': optional: true + '@esbuild/linux-loong64@0.28.2': + optional: true + '@esbuild/linux-mips64el@0.25.12': optional: true + '@esbuild/linux-mips64el@0.28.2': + optional: true + '@esbuild/linux-ppc64@0.25.12': optional: true + '@esbuild/linux-ppc64@0.28.2': + optional: true + '@esbuild/linux-riscv64@0.25.12': optional: true + '@esbuild/linux-riscv64@0.28.2': + optional: true + '@esbuild/linux-s390x@0.25.12': optional: true + '@esbuild/linux-s390x@0.28.2': + optional: true + '@esbuild/linux-x64@0.25.12': optional: true + '@esbuild/linux-x64@0.28.2': + optional: true + '@esbuild/netbsd-arm64@0.25.12': optional: true + '@esbuild/netbsd-arm64@0.28.2': + optional: true + '@esbuild/netbsd-x64@0.25.12': optional: true + '@esbuild/netbsd-x64@0.28.2': + optional: true + '@esbuild/openbsd-arm64@0.25.12': optional: true + '@esbuild/openbsd-arm64@0.28.2': + optional: true + '@esbuild/openbsd-x64@0.25.12': optional: true + '@esbuild/openbsd-x64@0.28.2': + optional: true + '@esbuild/openharmony-arm64@0.25.12': optional: true + '@esbuild/openharmony-arm64@0.28.2': + optional: true + '@esbuild/sunos-x64@0.25.12': optional: true + '@esbuild/sunos-x64@0.28.2': + optional: true + '@esbuild/win32-arm64@0.25.12': optional: true + '@esbuild/win32-arm64@0.28.2': + optional: true + '@esbuild/win32-ia32@0.25.12': optional: true + '@esbuild/win32-ia32@0.28.2': + optional: true + '@esbuild/win32-x64@0.25.12': optional: true + '@esbuild/win32-x64@0.28.2': + optional: true + '@floating-ui/core@1.7.3': dependencies: '@floating-ui/utils': 0.2.10 @@ -2712,12 +2959,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.1.17 '@tailwindcss/oxide-win32-x64-msvc': 4.1.17 - '@tailwindcss/vite@4.1.17(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))': + '@tailwindcss/vite@4.1.17(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))': dependencies: '@tailwindcss/node': 4.1.17 '@tailwindcss/oxide': 4.1.17 tailwindcss: 4.1.17 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) '@tanstack/virtual-core@3.13.12': {} @@ -2793,22 +3040,22 @@ snapshots: '@types/web-bluetooth@0.0.21': {} - '@vitejs/plugin-vue-jsx@5.1.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': + '@vitejs/plugin-vue-jsx@5.1.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': dependencies: '@babel/core': 7.28.5 '@babel/plugin-syntax-typescript': 7.27.1(@babel/core@7.28.5) '@babel/plugin-transform-typescript': 7.28.5(@babel/core@7.28.5) '@rolldown/pluginutils': 1.0.0-beta.53 '@vue/babel-plugin-jsx': 2.0.1(@babel/core@7.28.5) - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) vue: 3.5.25(typescript@5.9.3) transitivePeerDependencies: - supports-color - '@vitejs/plugin-vue@6.0.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': + '@vitejs/plugin-vue@6.0.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': dependencies: '@rolldown/pluginutils': 1.0.0-beta.50 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) vue: 3.5.25(typescript@5.9.3) '@volar/language-core@2.4.23': @@ -2919,14 +3166,14 @@ snapshots: dependencies: '@vue/devtools-kit': 7.7.9 - '@vue/devtools-core@8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': + '@vue/devtools-core@8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3))': dependencies: '@vue/devtools-kit': 8.0.5 '@vue/devtools-shared': 8.0.5 mitt: 3.0.1 nanoid: 5.1.6 pathe: 2.0.3 - vite-hot-client: 2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) + vite-hot-client: 2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) vue: 3.5.25(typescript@5.9.3) transitivePeerDependencies: - vite @@ -3290,6 +3537,35 @@ snapshots: '@esbuild/win32-ia32': 0.25.12 '@esbuild/win32-x64': 0.25.12 + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escalade@3.2.0: {} esprima@4.0.1: {} @@ -3661,6 +3937,12 @@ snapshots: tslib@2.8.1: {} + tsx@4.23.15: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + tw-animate-css@1.4.0: {} typescript@5.9.3: {} @@ -3678,17 +3960,17 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 - vite-dev-rpc@1.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)): + vite-dev-rpc@1.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)): dependencies: birpc: 2.9.0 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) - vite-hot-client: 2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) + vite-hot-client: 2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) - vite-hot-client@2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)): + vite-hot-client@2.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)): dependencies: - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) - vite-plugin-inspect@11.3.3(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)): + vite-plugin-inspect@11.3.3(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)): dependencies: ansis: 4.2.0 debug: 4.4.3 @@ -3698,26 +3980,26 @@ snapshots: perfect-debounce: 2.0.0 sirv: 3.0.2 unplugin-utils: 0.3.1 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) - vite-dev-rpc: 1.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) + vite-dev-rpc: 1.1.0(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) transitivePeerDependencies: - supports-color - vite-plugin-vue-devtools@8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)): + vite-plugin-vue-devtools@8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)): dependencies: - '@vue/devtools-core': 8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) + '@vue/devtools-core': 8.0.5(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2))(vue@3.5.25(typescript@5.9.3)) '@vue/devtools-kit': 8.0.5 '@vue/devtools-shared': 8.0.5 sirv: 3.0.2 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) - vite-plugin-inspect: 11.3.3(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) - vite-plugin-vue-inspector: 5.3.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) + vite-plugin-inspect: 11.3.3(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) + vite-plugin-vue-inspector: 5.3.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)) vue: 3.5.25(typescript@5.9.3) transitivePeerDependencies: - '@nuxt/kit' - supports-color - vite-plugin-vue-inspector@5.3.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)): + vite-plugin-vue-inspector@5.3.2(vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2)): dependencies: '@babel/core': 7.28.5 '@babel/plugin-proposal-decorators': 7.28.0(@babel/core@7.28.5) @@ -3728,11 +4010,11 @@ snapshots: '@vue/compiler-dom': 3.5.25 kolorist: 1.8.0 magic-string: 0.30.21 - vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite: 7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2) transitivePeerDependencies: - supports-color - vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2): + vite@7.2.6(@types/node@24.10.1)(jiti@2.6.1)(lightningcss@1.30.2)(tsx@4.23.15)(yaml@2.8.2): dependencies: esbuild: 0.25.12 fdir: 6.5.0(picomatch@4.0.3) @@ -3745,6 +4027,7 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 lightningcss: 1.30.2 + tsx: 4.23.15 yaml: 2.8.2 vscode-languageserver-textdocument@1.0.12: {} diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts new file mode 100644 index 0000000..b7b86f4 --- /dev/null +++ b/tests/browser-project-file.test.ts @@ -0,0 +1,62 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createBrowserProject, openBrowserProject, saveBrowserProject } from "../src/services/storage/browserProjectFile"; +import { ensureBrowserMediaPermission, readBrowserMedia } from "../src/services/storage/browserMediaFile"; + +const project = { version: 2, id: "project-1", name: "Project", createdAt: 1, updatedAt: 1, + canvas: { width: 800, height: 450 }, timeline: { duration: 0 }, danmus: [], audioMeta: [], tracks: [] }; + +function directoryFixture(initial?: string) { + let contents = initial; + const fileHandle = { + kind: "file", name: "project.basproj", + getFile: async () => new File([contents ?? ""], "project.basproj"), + createWritable: async () => { + let next = ""; + return { write: async (data: string) => { next = data; }, close: async () => { contents = next; }, abort: async () => {} }; + } + }; + const directory = { + kind: "directory", name: "project", queryPermission: async () => "granted", + values: async function* () { if (contents !== undefined) yield fileHandle; }, + getFileHandle: async (_name: string, options?: { create?: boolean }) => { + if (contents === undefined && !options?.create) throw new DOMException("Missing", "NotFoundError"); + return fileHandle; + } + } as unknown as FileSystemDirectoryHandle; + return { directory, read: () => contents, modify: (value: string) => { contents = value; } }; +} + +test("creates a project only in an empty directory", async () => { + const fs = directoryFixture(); + const opened = await createBrowserProject(fs.directory, "project.basproj", project); + assert.equal(opened.project.id, "project-1"); + assert.equal(JSON.parse(fs.read()!).id, "project-1"); + await assert.rejects(createBrowserProject(fs.directory, "project.basproj", project), /DIRECTORY_NOT_EMPTY/); +}); + +test("saves a project and refuses externally modified files", async () => { + const fs = directoryFixture(JSON.stringify(project)); + const opened = await openBrowserProject(fs.directory, "project.basproj"); + const saved = await saveBrowserProject(opened, { ...project, name: "Changed" }); + assert.equal(JSON.parse(fs.read()!).name, "Changed"); + fs.modify(JSON.stringify({ ...project, name: "External" })); + await assert.rejects(saveBrowserProject(saved, project), /PROJECT_MODIFIED_EXTERNALLY/); + assert.equal(JSON.parse(fs.read()!).name, "External"); +}); + +test("rejects paths outside selected directory and mismatched project IDs", async () => { + const fs = directoryFixture(JSON.stringify(project)); + await assert.rejects(openBrowserProject(fs.directory, "../project.basproj"), /INVALID_PROJECT_FILE_NAME/); + const opened = await openBrowserProject(fs.directory, "project.basproj"); + await assert.rejects(saveBrowserProject(opened, { ...project, id: "another" }), /PROJECT_ID_MISMATCH/); +}); + +test("does not read a media file until permission is granted", async () => { + let permission: PermissionState = "prompt"; + const file = { queryPermission: async () => permission, requestPermission: async () => { permission = "granted"; return permission; }, getFile: async () => new File(["data"], "test.wav") } as unknown as FileSystemFileHandle; + assert.equal(await ensureBrowserMediaPermission(file), false); + await assert.rejects(readBrowserMedia(file), /MEDIA_PERMISSION_REQUIRED/); + assert.equal(await ensureBrowserMediaPermission(file, true), true); + assert.equal(await (await readBrowserMedia(file)).text(), "data"); +}); From 4475c07e81ee822cd30a1bd534b324963729ed3b Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:02:06 +0800 Subject: [PATCH 05/19] fix(storage): guard concurrent browser project saves --- src/services/storage/browserProjectFile.ts | 35 ++++++++++------- tests/browser-project-file.test.ts | 44 ++++++++++++++++++++++ 2 files changed, 65 insertions(+), 14 deletions(-) diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index dd7d9de..1091fff 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -103,19 +103,26 @@ export async function createBrowserProject( export async function saveBrowserProject(opened: BrowserProjectFile, project: BasProjectData): Promise { validateFileName(opened.fileName); if (!(await ensureDirectoryPermission(opened.directory))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); - const handle = await opened.directory.getFileHandle(opened.fileName); - const current = await (await handle.getFile()).text(); - if ((await digest(current)) !== opened.fingerprint) throw new Error("PROJECT_MODIFIED_EXTERNALLY"); - const normalized = normalizeProjectData(project); - if (normalized.id !== opened.project.id) throw new Error("PROJECT_ID_MISMATCH"); - const contents = JSON.stringify(normalized, null, 2); - const writable = await handle.createWritable(); - try { - await writable.write(contents); - await writable.close(); - } catch (error) { - await writable.abort().catch(() => {}); - throw error; + const save = async (): Promise => { + const handle = await opened.directory.getFileHandle(opened.fileName); + const current = await (await handle.getFile()).text(); + if ((await digest(current)) !== opened.fingerprint) throw new Error("PROJECT_MODIFIED_EXTERNALLY"); + const normalized = normalizeProjectData(project); + if (normalized.id !== opened.project.id) throw new Error("PROJECT_ID_MISMATCH"); + const contents = JSON.stringify(normalized, null, 2); + const writable = await handle.createWritable(); + try { + await writable.write(contents); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => {}); + throw error; + } + return { ...opened, project: normalized, fingerprint: await digest(contents) }; + }; + // 跨标签页串行化同一项目;外部程序仍可能在检查和写入之间更改文件。 + if (typeof navigator !== "undefined" && navigator.locks) { + return navigator.locks.request(`danmakucut-project:${opened.project.id}`, { mode: "exclusive" }, save); } - return { ...opened, project: normalized, fingerprint: await digest(contents) }; + return save(); } diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts index b7b86f4..2e922d3 100644 --- a/tests/browser-project-file.test.ts +++ b/tests/browser-project-file.test.ts @@ -60,3 +60,47 @@ test("does not read a media file until permission is granted", async () => { assert.equal(await ensureBrowserMediaPermission(file, true), true); assert.equal(await (await readBrowserMedia(file)).text(), "data"); }); + +test("does not write when directory permission is denied", async () => { + let wrote = false; + const directory = { + queryPermission: async () => "denied", + getFileHandle: async () => { wrote = true; throw new Error("unexpected write"); } + } as unknown as FileSystemDirectoryHandle; + await assert.rejects(openBrowserProject(directory, "project.basproj"), /DIRECTORY_PERMISSION_REQUIRED/); + assert.equal(wrote, false); +}); + +test("aborts the writable stream when writing fails", async () => { + let aborted = false; + const existing = JSON.stringify(project); + const fileHandle = { + getFile: async () => new File([existing], "project.basproj"), + createWritable: async () => ({ + write: async () => { throw new Error("disk full"); }, + close: async () => { throw new Error("unexpected close"); }, + abort: async () => { aborted = true; } + }) + }; + const directory = { queryPermission: async () => "granted", getFileHandle: async () => fileHandle } as unknown as FileSystemDirectoryHandle; + const opened = await openBrowserProject(directory, "project.basproj"); + await assert.rejects(saveBrowserProject(opened, project), /disk full/); + assert.equal(aborted, true); +}); + +test("serializes project saves with Web Locks when available", async () => { + const fs = directoryFixture(JSON.stringify(project)); + const opened = await openBrowserProject(fs.directory, "project.basproj"); + const original = Object.getOwnPropertyDescriptor(globalThis, "navigator"); + let lockName = ""; + Object.defineProperty(globalThis, "navigator", { configurable: true, value: { locks: { + request: async (name: string, _options: unknown, callback: () => Promise) => { lockName = name; return callback(); } + } } }); + try { + await saveBrowserProject(opened, project); + assert.equal(lockName, "danmakucut-project:project-1"); + } finally { + if (original) Object.defineProperty(globalThis, "navigator", original); + else Reflect.deleteProperty(globalThis, "navigator"); + } +}); From 9560fc57a65c10d39601f4adf0991554e0969e71 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:08:00 +0800 Subject: [PATCH 06/19] Connect browser project folders and referenced audio --- src/components/editor/EditorLayout.vue | 4 +- src/components/editor/ResourcesPanel.vue | 11 +++- .../editor/resources/ResourcesHeader.vue | 17 ++++-- src/composables/useProjectAutoSave.ts | 19 ++----- src/i18n/messages/projects.ts | 3 ++ src/services/storage/projectStorage.ts | 54 +++++++++++++++++-- src/views/ProjectsView.vue | 24 ++++++--- 7 files changed, 103 insertions(+), 29 deletions(-) diff --git a/src/components/editor/EditorLayout.vue b/src/components/editor/EditorLayout.vue index 8e56917..88db0f1 100644 --- a/src/components/editor/EditorLayout.vue +++ b/src/components/editor/EditorLayout.vue @@ -176,6 +176,8 @@ useEventListener("mouseleave", stopResize); {{ autoSave.saveStatus.value === 'saving' ? t('app.saving') + : autoSave.saveStatus.value === 'error' + ? t('projects.saveFailed') : autoSave.isDirty.value ? t('app.unsaved') : t('app.saved') @@ -233,7 +235,7 @@ useEventListener("mouseleave", stopResize);
- +
diff --git a/src/components/editor/ResourcesPanel.vue b/src/components/editor/ResourcesPanel.vue index 8d9cd02..a72113c 100644 --- a/src/components/editor/ResourcesPanel.vue +++ b/src/components/editor/ResourcesPanel.vue @@ -9,6 +9,10 @@ import type { AudioResource } from "@/types/resource"; import { getItemName } from "@/utils/resourceUtils"; import { extractAudioCover } from "@/utils/audio/audio-cover"; import { LayoutGrid, List } from "lucide-vue-next"; +import { hasBrowserProjectSession } from "@/services/storage/projectStorage"; +import { rememberBrowserMedia } from "@/services/storage/browserMediaFile"; + +const props = defineProps<{ projectId: string }>(); import ResourcesSidebar from "./resources/ResourcesSidebar.vue"; import ResourcesHeader from "./resources/ResourcesHeader.vue"; @@ -103,7 +107,7 @@ const getAudioDuration = (url: string): Promise => { }; // 点击选择和拖放音频均从这里创建资源,保证行为一致。 -const handleAudioUpload = async (file: File) => { +const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle) => { const url = URL.createObjectURL(file); const [duration, coverUrl] = await Promise.all([ getAudioDuration(url), @@ -118,6 +122,10 @@ const handleAudioUpload = async (file: File) => { file, duration, }; + if (handle) { + try { await rememberBrowserMedia(props.projectId, resource.id, handle); } + catch (error) { URL.revokeObjectURL(url); console.error("Failed to remember audio", error); return; } + } audioStore.add(resource); console.log( `[ResourcesPanel] 上传音频文件: ${file.name}, 时长: ${duration}ms` @@ -215,6 +223,7 @@ const toggleResourceLayout = () => {
(); const emit = defineEmits<{ (e: "update:searchQuery", value: string): void; (e: "add-danmu", type: DanmuType): void; - (e: "upload-audio", file: File): void; + (e: "upload-audio", file: File, handle?: FileSystemFileHandle): void; }>(); const audioInputRef = ref(null); const { t } = useI18n(); -const triggerAudioUpload = () => { +const triggerAudioUpload = async () => { + if (props.useFileReferences && "showOpenFilePicker" in window) { + try { + const handle = await pickBrowserAudio(); + if (handle) emit("upload-audio", await handle.getFile(), handle); + } catch (error) { + if (!(error instanceof DOMException && error.name === "AbortError")) console.error("Failed to select audio", error); + } + return; + } audioInputRef.value?.click(); }; diff --git a/src/composables/useProjectAutoSave.ts b/src/composables/useProjectAutoSave.ts index 52ac9be..0a86e3f 100644 --- a/src/composables/useProjectAutoSave.ts +++ b/src/composables/useProjectAutoSave.ts @@ -41,24 +41,12 @@ export function useProjectAutoSave(projectId: string) { /** * 构造当前工程需要持久化的音频元数据。 * - * 已加载的音频使用运行时资源信息;未加载但仍被任意嵌套时间轴引用的音频, + * 已加载的音频使用运行时资源信息;暂时未加载的音频, * 则沿用导入工程中的元数据,避免保存后产生悬空资源引用。 * * @returns 当前工程需要写入持久化数据的音频元数据列表 */ const getSerializedAudioMetadata = (): SerializedAudioMetadata[] => { - const resources = new Map(audioStore.audioResources.map((resource) => [resource.id, resource])); - const referencedIds = new Set(); - const collectReferencedIds = (tracks: typeof timelineStore.rootTracks) => { - for (const track of tracks) { - for (const clip of track.clips) { - if (clip.kind === "resource") referencedIds.add(clip.resourceId); - else collectReferencedIds(clip.tracks); - } - } - }; - collectReferencedIds(timelineStore.rootTracks); - const metadata: SerializedAudioMetadata[] = audioStore.audioResources.map((resource) => ({ id: resource.id, name: resource.name, @@ -69,7 +57,7 @@ export function useProjectAutoSave(projectId: string) { })); const knownIds = new Set(metadata.map((item) => item.id)); for (const item of importedAudioMeta.value) { - if (referencedIds.has(item.id) && !knownIds.has(item.id)) { + if (!knownIds.has(item.id)) { metadata.push(item); } } @@ -151,7 +139,8 @@ export function useProjectAutoSave(projectId: string) { const { project, audioResources } = draft; createdAt.value = project.createdAt; - importedAudioMeta.value = project.audioMeta ?? []; + const restoredIds = new Set(audioResources.map((resource) => resource.id)); + importedAudioMeta.value = (project.audioMeta ?? []).filter((meta) => !restoredIds.has(meta.id)); if (project.name) { projectName.value = project.name; diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index 21d604a..dda7567 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,4 +1,5 @@ const zhCN = { + selectFolder: "选择空文件夹", emptyFolder: "请选择已有的空文件夹", folderFailed: "无法选择文件夹,请重试。", openFailed: "无法打开项目,请检查文件夹权限和项目文件。", title: "项目", search: "搜索项目...", newProject: "新建项目", createFirst: "创建第一个项目", empty: "还没有项目", emptyDescription: "创建你的第一个项目,开始制作属于你的弹幕作品。", noResults: "没有找到项目", noResultsDescription: "换个关键词试试,或创建一个新项目。", @@ -9,6 +10,7 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + selectFolder: "Choose empty folder", emptyFolder: "Select an existing empty folder", folderFailed: "Unable to select folder.", openFailed: "Could not open project. Check the folder permission and project file.", title: "Projects", search: "Search projects...", newProject: "New project", createFirst: "Create your first project", empty: "No projects yet", emptyDescription: "Create your first project and start making danmaku.", noResults: "No projects found", noResultsDescription: "Try another search, or create a new project.", @@ -19,6 +21,7 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + selectFolder: "空のフォルダーを選択", emptyFolder: "既存の空フォルダーを選択", folderFailed: "フォルダーを選択できません。", openFailed: "プロジェクトを開けません。権限とファイルを確認してください。", title: "プロジェクト", search: "プロジェクトを検索...", newProject: "新規プロジェクト", createFirst: "最初のプロジェクトを作成", empty: "プロジェクトはまだありません", emptyDescription: "プロジェクトを作成して弾幕の制作を始めましょう。", noResults: "プロジェクトが見つかりません", noResultsDescription: "別のキーワードで検索するか、プロジェクトを作成してください。", diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index 5ef52c5..efb6f25 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -2,14 +2,21 @@ import type { AudioResource } from "@/types/resource"; import type { BasProjectData } from "@/types/storage"; import { idbGet, idbSet, idbDelete, idbGetAllKeys, STORES } from "./indexedDB"; import { mediaStorage } from "./mediaStorage"; +import { getBrowserMediaHandle, readBrowserMedia } from "./browserMediaFile"; import { normalizeProjectData, PROJECT_VERSION } from "./projectSchema"; import { saveTextFile } from "@/utils/desktop"; +import { createBrowserProject, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; const CURRENT_VERSION = PROJECT_VERSION; const ACTIVE_DRAFT_KEY = "active_draft"; const PROJECT_PREFIX = "project:"; const LEGACY_PROJECT_ID = "legacy-draft"; const projectMediaKey = (projectId: string, mediaId: string) => `${projectId}--${mediaId}`; +const browserSessions = new Map(); + +export function hasBrowserProjectSession(id: string): boolean { + return browserSessions.has(id); +} /** 旧草稿先完整复制,写入成功后才移除原键。媒体仍保留在原位置。 */ export async function migrateLegacyDraft(): Promise { @@ -44,8 +51,36 @@ export async function createProject(name: string, trackName: string): Promise { + const now = Date.now(); + const project: BasProjectData = { + version: CURRENT_VERSION, id: crypto.randomUUID(), name, createdAt: now, updatedAt: now, + canvas: { width: 800, height: 450 }, timeline: { duration: 0 }, danmus: [], audioMeta: [], + tracks: [{ id: "track_1", name: trackName, clips: [], visible: true, muted: false, locked: false }] + }; + const fileName = "project.basproj"; + const opened = await createBrowserProject(directory, fileName, project); + await rememberBrowserProject({ projectId: project.id, directory, fileName }); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + project.id, project); + browserSessions.set(project.id, opened); + return project; +} + +/** 在用户点击打开时恢复权限和文件内容;不允许静默使用过期缓存。 */ +export async function prepareProjectOpen(id: string): Promise { + const location = await findBrowserProjectLocation(id); + if (!location) return; + if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const opened = await openBrowserProject(location.directory, location.fileName); + if (opened.project.id !== id) throw new Error("PROJECT_ID_MISMATCH"); + browserSessions.set(id, opened); +} + /** 媒体可能被其他工程引用,不在删除工程时清空共享媒体。 */ export async function deleteProject(id: string): Promise { + await forgetBrowserProject(id); + browserSessions.delete(id); await idbDelete(STORES.PROJECTS, PROJECT_PREFIX + id); } @@ -75,7 +110,8 @@ export async function saveProjectDraft( // 1. 先保存所有媒体物理文件到 OPFS / IndexedDB const mediaSaves: Promise[] = []; for (const [id, file] of audioFiles.entries()) { - mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); + const reference = await getBrowserMediaHandle(projectData.id, id); + if (!reference) mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); } await Promise.all(mediaSaves); @@ -86,6 +122,14 @@ export async function saveProjectDraft( updatedAt: Date.now(), }; + const location = await findBrowserProjectLocation(projectData.id); + if (location) { + const opened = browserSessions.get(projectData.id); + if (!opened) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const next = await saveBrowserProject(opened, fullProject); + browserSessions.set(projectData.id, next); + } + // 3. 写入 IndexedDB await idbSet(STORES.PROJECTS, PROJECT_PREFIX + projectData.id, fullProject); } @@ -94,7 +138,10 @@ export async function loadProjectDraft(id: string): Promise<{ project: BasProjectData; audioResources: AudioResource[]; } | null> { - const storedProject = await idbGet(STORES.PROJECTS, PROJECT_PREFIX + id); + const location = await findBrowserProjectLocation(id); + const session = browserSessions.get(id); + if (location && !session) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const storedProject = session?.project ?? await idbGet(STORES.PROJECTS, PROJECT_PREFIX + id); if (!storedProject) return null; const project = normalizeProjectData(storedProject); @@ -103,7 +150,8 @@ export async function loadProjectDraft(id: string): Promise<{ if (Array.isArray(project.audioMeta)) { for (const meta of project.audioMeta) { try { - const file = await mediaStorage.get(projectMediaKey(id, meta.id)) ?? + const handle = await getBrowserMediaHandle(id, meta.id); + const file = handle ? await readBrowserMedia(handle) : await mediaStorage.get(projectMediaKey(id, meta.id)) ?? (id === LEGACY_PROJECT_ID ? await mediaStorage.get(meta.id) : null); if (file) { const url = URL.createObjectURL(file); diff --git a/src/views/ProjectsView.vue b/src/views/ProjectsView.vue index 0df374f..5523107 100644 --- a/src/views/ProjectsView.vue +++ b/src/views/ProjectsView.vue @@ -9,7 +9,8 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTitleBarDrag } from "@/composables/useTitleBarDrag"; -import { createProject, deleteProject, listProjects } from "@/services/storage/projectStorage"; +import { createProject, createFolderProject, deleteProject, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; +import { pickProjectDirectory } from "@/services/storage/browserProjectFile"; import type { BasProjectData } from "@/types/storage"; import { isDesktopApp, isMacOS } from "@/utils/desktop"; @@ -30,6 +31,8 @@ const isCreating = ref(false); const isCreateOpen = ref(false); const isSettingsOpen = ref(false); const name = ref(""); +const directory = ref(null); +const supportsFolder = !isDesktop && "showDirectoryPicker" in window; const filtered = computed(() => projects.value.filter((project) => project.name.toLowerCase().includes(search.value.trim().toLowerCase())) .sort((a, b) => descending.value ? b.updatedAt - a.updatedAt : a.updatedAt - b.updatedAt)); const allSelected = computed(() => filtered.value.length > 0 && filtered.value.every((p) => selected.value.includes(p.id))); @@ -42,13 +45,22 @@ const refresh = async () => { finally { isLoading.value = false; } }; onMounted(refresh); -const showCreate = () => { name.value = ""; isCreateOpen.value = true; }; +const showCreate = () => { name.value = ""; directory.value = null; isCreateOpen.value = true; }; +const selectDirectory = async () => { + try { directory.value = await pickProjectDirectory(); } + catch (cause) { if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.folderFailed")); } } +}; +const open = async (id: string) => { + try { await prepareProjectOpen(id); emit("open", id); } + catch (cause) { console.error("[Projects] Failed to open", cause); window.alert(t("projects.openFailed")); } +}; const create = async () => { const projectName = name.value.trim(); - if (!projectName || isCreating.value) return; + if (!projectName || isCreating.value || (supportsFolder && !directory.value)) return; isCreating.value = true; try { - const project = await createProject(projectName, t("timeline.defaultTrackName", { n: 1 })); + const trackName = t("timeline.defaultTrackName", { n: 1 }); + const project = directory.value ? await createFolderProject(projectName, trackName, directory.value) : await createProject(projectName, trackName); isCreateOpen.value = false; emit("open", project.id); } catch (cause) { console.error("[Projects] Failed to create", cause); window.alert(t("projects.createFailed")); } @@ -106,10 +118,10 @@ const removeSelected = async () => {
- + - {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}
+ {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}
{{ directory?.name || t("projects.emptyFolder") }}
From d4124ef75a30e5901965db4511dea0e302816ca7 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:23:40 +0800 Subject: [PATCH 07/19] Add initial desktop project files and removal choices --- src-tauri/src/lib.rs | 3 +- src-tauri/src/project_files.rs | 113 ++++++++++++++++++ src/components/editor/ResourcesPanel.vue | 6 +- .../editor/resources/ResourcesHeader.vue | 9 +- src/composables/useProjectAutoSave.ts | 1 + src/i18n/messages/projects.ts | 3 + src/services/storage/browserProjectFile.ts | 8 ++ src/services/storage/desktopProjectFile.ts | 49 ++++++++ src/services/storage/projectStorage.ts | 56 ++++++++- src/types/resource.ts | 1 + src/types/storage.ts | 1 + src/views/ProjectsView.vue | 44 +++++-- 12 files changed, 275 insertions(+), 19 deletions(-) create mode 100644 src-tauri/src/project_files.rs create mode 100644 src/services/storage/desktopProjectFile.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 79d5fbb..1ea9ead 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ mod commands; +mod project_files; use tauri::Manager; use tauri_plugin_window_state::StateFlags; @@ -28,7 +29,7 @@ pub fn run() { ) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) - .invoke_handler(tauri::generate_handler![commands::write_text_file]) + .invoke_handler(tauri::generate_handler![commands::write_text_file, project_files::create_disk_project, project_files::read_disk_project, project_files::save_disk_project, project_files::read_audio_reference, project_files::delete_disk_project_file]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs new file mode 100644 index 0000000..cbe0135 --- /dev/null +++ b/src-tauri/src/project_files.rs @@ -0,0 +1,113 @@ +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +// Serialize compare-and-replace operations from this application instance. +static PROJECT_IO: Mutex<()> = Mutex::new(()); +const PROJECT_FILE: &str = "project.basproj"; + +fn project_path(directory: &Path) -> Result { + if !directory.is_absolute() || !directory.is_dir() { + return Err("INVALID_PROJECT_DIRECTORY".into()); + } + Ok(directory.join(PROJECT_FILE)) +} + +#[tauri::command] +pub fn create_disk_project(directory: PathBuf, contents: String) -> Result<(), String> { + let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; + let path = project_path(&directory)?; + if fs::read_dir(&directory).map_err(|e| e.to_string())?.next().is_some() { + return Err("DIRECTORY_NOT_EMPTY".into()); + } + // create_new makes the project filename exclusive even if the directory changes. + let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; + if let Err(error) = file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()) { + drop(file); + let _ = fs::remove_file(path); + return Err(error.to_string()); + } + Ok(()) +} + +#[tauri::command] +pub fn read_disk_project(directory: PathBuf) -> Result { + let path = project_path(&directory)?; + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { + return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); + } + fs::read_to_string(path).map_err(|e| e.to_string()) +} + +#[tauri::command] +pub fn save_disk_project(directory: PathBuf, expected: String, contents: String) -> Result<(), String> { + let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; + let path = project_path(&directory)?; + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { + return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); + } + if fs::read_to_string(&path).map_err(|e| e.to_string())? != expected { + return Err("PROJECT_MODIFIED_EXTERNALLY".into()); + } + let temp = directory.join(format!(".project-{}-{}.tmp", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos())); + let result = (|| -> Result<(), String> { + let mut file = OpenOptions::new().write(true).create_new(true).open(&temp).map_err(|e| e.to_string())?; + file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()).map_err(|e| e.to_string())?; + drop(file); + if fs::read_to_string(&path).map_err(|e| e.to_string())? != expected { + return Err("PROJECT_MODIFIED_EXTERNALLY".into()); + } + fs::rename(&temp, &path).map_err(|e| e.to_string()) + })(); + if result.is_err() { let _ = fs::remove_file(&temp); } + result +} + +#[tauri::command] +pub fn read_audio_reference(path: PathBuf) -> Result, String> { + if !path.is_absolute() || !path.is_file() { + return Err("AUDIO_FILE_NOT_FOUND".into()); + } + let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase(); + if !["mp3", "wav", "ogg", "flac", "m4a", "aac", "opus"].contains(&extension.as_str()) { + return Err("UNSUPPORTED_AUDIO_FILE".into()); + } + let size = fs::metadata(&path).map_err(|e| e.to_string())?.len(); + if size > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + fs::read(path).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn create_save_and_reject_external_change() { + let directory = std::env::temp_dir().join(format!("danmakucut-test-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); + fs::create_dir(&directory).unwrap(); + create_disk_project(directory.clone(), "first".into()).unwrap(); + assert!(create_disk_project(directory.clone(), "other".into()).is_err()); + assert_eq!(read_disk_project(directory.clone()).unwrap(), "first"); + save_disk_project(directory.clone(), "first".into(), "second".into()).unwrap(); + assert!(save_disk_project(directory.clone(), "first".into(), "lost".into()).is_err()); + assert_eq!(read_disk_project(directory.clone()).unwrap(), "second"); + fs::remove_dir_all(directory).unwrap(); + } +} + +#[tauri::command] +pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Result<(), String> { + let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; + let path = project_path(&directory)?; + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { + return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); + } + let data: serde_json::Value = serde_json::from_str(&fs::read_to_string(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; + if data.get("id").and_then(|value| value.as_str()) != Some(project_id.as_str()) { + return Err("PROJECT_ID_MISMATCH".into()); + } + fs::remove_file(path).map_err(|e| e.to_string()) +} diff --git a/src/components/editor/ResourcesPanel.vue b/src/components/editor/ResourcesPanel.vue index a72113c..c054f0e 100644 --- a/src/components/editor/ResourcesPanel.vue +++ b/src/components/editor/ResourcesPanel.vue @@ -9,7 +9,7 @@ import type { AudioResource } from "@/types/resource"; import { getItemName } from "@/utils/resourceUtils"; import { extractAudioCover } from "@/utils/audio/audio-cover"; import { LayoutGrid, List } from "lucide-vue-next"; -import { hasBrowserProjectSession } from "@/services/storage/projectStorage"; +import { hasBrowserProjectSession, hasDesktopProjectSession } from "@/services/storage/projectStorage"; import { rememberBrowserMedia } from "@/services/storage/browserMediaFile"; const props = defineProps<{ projectId: string }>(); @@ -107,7 +107,7 @@ const getAudioDuration = (url: string): Promise => { }; // 点击选择和拖放音频均从这里创建资源,保证行为一致。 -const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle) => { +const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle, sourcePath?: string) => { const url = URL.createObjectURL(file); const [duration, coverUrl] = await Promise.all([ getAudioDuration(url), @@ -120,6 +120,7 @@ const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle) => { url, coverUrl: coverUrl ?? undefined, file, + sourcePath, duration, }; if (handle) { @@ -224,6 +225,7 @@ const toggleResourceLayout = () => { (); const emit = defineEmits<{ (e: "update:searchQuery", value: string): void; (e: "add-danmu", type: DanmuType): void; - (e: "upload-audio", file: File, handle?: FileSystemFileHandle): void; + (e: "upload-audio", file: File, handle?: FileSystemFileHandle, path?: string): void; }>(); const audioInputRef = ref(null); @@ -27,6 +29,11 @@ const audioInputRef = ref(null); const { t } = useI18n(); const triggerAudioUpload = async () => { + if (props.useDesktopReferences) { + try { const selected = await pickDesktopAudio(); if (selected) emit("upload-audio", selected.file, undefined, selected.path); } + catch (error) { console.error("Failed to select audio", error); } + return; + } if (props.useFileReferences && "showOpenFilePicker" in window) { try { const handle = await pickBrowserAudio(); diff --git a/src/composables/useProjectAutoSave.ts b/src/composables/useProjectAutoSave.ts index 0a86e3f..20db2c5 100644 --- a/src/composables/useProjectAutoSave.ts +++ b/src/composables/useProjectAutoSave.ts @@ -54,6 +54,7 @@ export function useProjectAutoSave(projectId: string) { coverUrl: resource.coverUrl, size: resource.file?.size, type: resource.file?.type, + sourcePath: resource.sourcePath, })); const knownIds = new Set(metadata.map((item) => item.id)); for (const item of importedAudioMeta.value) { diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index dda7567..dfd8255 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,4 +1,5 @@ const zhCN = { + removeTitle: "移除项目", removeDescription: "选择处理方式。引用的原始素材和项目文件夹不会被删除。", listOnly: "仅从列表移除", deleteFiles: "同时删除项目文件", confirmFileDelete: "确定永久删除显示的项目文件吗?此操作无法撤销。", storedInternally: "应用内存储", selectFolder: "选择空文件夹", emptyFolder: "请选择已有的空文件夹", folderFailed: "无法选择文件夹,请重试。", openFailed: "无法打开项目,请检查文件夹权限和项目文件。", title: "项目", search: "搜索项目...", newProject: "新建项目", createFirst: "创建第一个项目", empty: "还没有项目", emptyDescription: "创建你的第一个项目,开始制作属于你的弹幕作品。", @@ -10,6 +11,7 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + removeTitle: "Remove projects", removeDescription: "Choose what to remove. Original referenced media and folders will be kept.", listOnly: "Remove from list only", deleteFiles: "Also delete project files", confirmFileDelete: "Permanently delete the displayed project files? This cannot be undone.", storedInternally: "App storage", selectFolder: "Choose empty folder", emptyFolder: "Select an existing empty folder", folderFailed: "Unable to select folder.", openFailed: "Could not open project. Check the folder permission and project file.", title: "Projects", search: "Search projects...", newProject: "New project", createFirst: "Create your first project", empty: "No projects yet", emptyDescription: "Create your first project and start making danmaku.", @@ -21,6 +23,7 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + removeTitle: "プロジェクトを削除", removeDescription: "削除方法を選択してください。元の素材とフォルダーは削除されません。", listOnly: "一覧からのみ削除", deleteFiles: "プロジェクトファイルも削除", confirmFileDelete: "表示されたファイルを完全に削除しますか?元に戻せません。", storedInternally: "アプリ内ストレージ", selectFolder: "空のフォルダーを選択", emptyFolder: "既存の空フォルダーを選択", folderFailed: "フォルダーを選択できません。", openFailed: "プロジェクトを開けません。権限とファイルを確認してください。", title: "プロジェクト", search: "プロジェクトを検索...", newProject: "新規プロジェクト", createFirst: "最初のプロジェクトを作成", empty: "プロジェクトはまだありません", emptyDescription: "プロジェクトを作成して弾幕の制作を始めましょう。", diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index 1091fff..995453f 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -126,3 +126,11 @@ export async function saveBrowserProject(opened: BrowserProjectFile, project: Ba } return save(); } + +/** Removes only the matching project file, never the selected directory or referenced assets. */ +export async function deleteBrowserProjectFile(location: BrowserProjectLocation): Promise { + if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const opened = await openBrowserProject(location.directory, location.fileName); + if (opened.project.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); + await location.directory.removeEntry(location.fileName); +} diff --git a/src/services/storage/desktopProjectFile.ts b/src/services/storage/desktopProjectFile.ts new file mode 100644 index 0000000..28b8823 --- /dev/null +++ b/src/services/storage/desktopProjectFile.ts @@ -0,0 +1,49 @@ +import { invoke } from "@tauri-apps/api/core"; +import { open } from "@tauri-apps/plugin-dialog"; +import type { BasProjectData } from "@/types/storage"; +import { normalizeProjectData } from "./projectSchema"; +import { idbDelete, idbGet, idbSet, STORES } from "./indexedDB"; + +const prefix = "desktop-project-location:"; +export type DesktopProjectSession = { directory: string; contents: string; project: BasProjectData }; + +/** Must be called directly from the user's click. */ +export async function pickDesktopDirectory(): Promise { + return await open({ directory: true, multiple: false }); +} +export const findDesktopProjectLocation = (id: string) => idbGet(STORES.PROJECTS, prefix + id); +export const forgetDesktopProject = (id: string) => idbDelete(STORES.PROJECTS, prefix + id); + +export async function createDesktopProject(directory: string, project: BasProjectData): Promise { + const contents = JSON.stringify(normalizeProjectData(project), null, 2); + await invoke("create_disk_project", { directory, contents }); + await idbSet(STORES.PROJECTS, prefix + project.id, directory); + return { directory, contents, project }; +} +export async function openDesktopProject(directory: string, expectedId: string): Promise { + const contents = await invoke("read_disk_project", { directory }); + const project = normalizeProjectData(JSON.parse(contents)); + if (project.id !== expectedId) throw new Error("PROJECT_ID_MISMATCH"); + return { directory, contents, project }; +} +export async function saveDesktopProject(session: DesktopProjectSession, project: BasProjectData): Promise { + if (project.id !== session.project.id) throw new Error("PROJECT_ID_MISMATCH"); + const contents = JSON.stringify(normalizeProjectData(project), null, 2); + await invoke("save_disk_project", { directory: session.directory, expected: session.contents, contents }); + return { ...session, contents, project }; +} + +/** Returns a file backed by an explicitly selected path; the original is never modified. */ +export async function pickDesktopAudio(): Promise<{ file: File; path: string } | null> { + const path = await open({ multiple: false, filters: [{ name: "Audio", extensions: ["mp3", "wav", "ogg", "flac", "m4a", "aac", "opus"] }] }); + return path ? { file: await readDesktopAudio(path), path } : null; +} +export async function readDesktopAudio(path: string, mimeType = "audio/*"): Promise { + const bytes = await invoke("read_audio_reference", { path }); + const name = path.split(/[\\/]/).pop() || "audio"; + return new File([new Uint8Array(bytes)], name, { type: mimeType }); +} + +export async function deleteDesktopProjectFile(directory: string, projectId: string): Promise { + await invoke("delete_disk_project_file", { directory, projectId }); +} diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index efb6f25..64940d3 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -1,11 +1,12 @@ import type { AudioResource } from "@/types/resource"; import type { BasProjectData } from "@/types/storage"; import { idbGet, idbSet, idbDelete, idbGetAllKeys, STORES } from "./indexedDB"; +import { createDesktopProject, findDesktopProjectLocation, forgetDesktopProject, openDesktopProject, saveDesktopProject, readDesktopAudio, deleteDesktopProjectFile, type DesktopProjectSession } from "./desktopProjectFile"; import { mediaStorage } from "./mediaStorage"; import { getBrowserMediaHandle, readBrowserMedia } from "./browserMediaFile"; import { normalizeProjectData, PROJECT_VERSION } from "./projectSchema"; import { saveTextFile } from "@/utils/desktop"; -import { createBrowserProject, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; +import { createBrowserProject, deleteBrowserProjectFile, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; const CURRENT_VERSION = PROJECT_VERSION; const ACTIVE_DRAFT_KEY = "active_draft"; @@ -13,6 +14,9 @@ const PROJECT_PREFIX = "project:"; const LEGACY_PROJECT_ID = "legacy-draft"; const projectMediaKey = (projectId: string, mediaId: string) => `${projectId}--${mediaId}`; const browserSessions = new Map(); +const desktopSessions = new Map(); + +export function hasDesktopProjectSession(id: string): boolean { return desktopSessions.has(id); } export function hasBrowserProjectSession(id: string): boolean { return browserSessions.has(id); @@ -67,8 +71,24 @@ export async function createFolderProject(name: string, trackName: string, direc return project; } +/** 初始化桌面端用户选择的空目录。 */ +export async function createDesktopFolderProject(name: string, trackName: string, directory: string): Promise { + const now = Date.now(); + const project: BasProjectData = { + version: CURRENT_VERSION, id: crypto.randomUUID(), name, createdAt: now, updatedAt: now, + canvas: { width: 800, height: 450 }, timeline: { duration: 0 }, danmus: [], audioMeta: [], + tracks: [{ id: "track_1", name: trackName, clips: [], visible: true, muted: false, locked: false }] + }; + const session = await createDesktopProject(directory, project); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + project.id, project); + desktopSessions.set(project.id, session); + return project; +} + /** 在用户点击打开时恢复权限和文件内容;不允许静默使用过期缓存。 */ export async function prepareProjectOpen(id: string): Promise { + const desktopDirectory = await findDesktopProjectLocation(id); + if (desktopDirectory) { desktopSessions.set(id, await openDesktopProject(desktopDirectory, id)); return; } const location = await findBrowserProjectLocation(id); if (!location) return; if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); @@ -78,8 +98,23 @@ export async function prepareProjectOpen(id: string): Promise { } /** 媒体可能被其他工程引用,不在删除工程时清空共享媒体。 */ -export async function deleteProject(id: string): Promise { +export async function getProjectLocationLabel(id: string): Promise { + const desktop = await findDesktopProjectLocation(id); + if (desktop) return desktop + "/project.basproj"; + const browser = await findBrowserProjectLocation(id); + return browser ? browser.directory.name + "/" + browser.fileName : null; +} + +export async function deleteProject(id: string, deleteFile = false): Promise { + if (deleteFile) { + const desktop = await findDesktopProjectLocation(id); + const browser = await findBrowserProjectLocation(id); + if (desktop) await deleteDesktopProjectFile(desktop, id); + else if (browser) await deleteBrowserProjectFile(browser); + } await forgetBrowserProject(id); + await forgetDesktopProject(id); + desktopSessions.delete(id); browserSessions.delete(id); await idbDelete(STORES.PROJECTS, PROJECT_PREFIX + id); } @@ -111,7 +146,7 @@ export async function saveProjectDraft( const mediaSaves: Promise[] = []; for (const [id, file] of audioFiles.entries()) { const reference = await getBrowserMediaHandle(projectData.id, id); - if (!reference) mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); + if (!reference && !projectData.audioMeta.some((item) => item.id === id && item.sourcePath)) mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); } await Promise.all(mediaSaves); @@ -122,6 +157,13 @@ export async function saveProjectDraft( updatedAt: Date.now(), }; + const desktopDirectory = await findDesktopProjectLocation(projectData.id); + if (desktopDirectory) { + const session = desktopSessions.get(projectData.id); + if (!session) throw new Error("PROJECT_NOT_OPEN"); + desktopSessions.set(projectData.id, await saveDesktopProject(session, fullProject)); + } + const location = await findBrowserProjectLocation(projectData.id); if (location) { const opened = browserSessions.get(projectData.id); @@ -141,7 +183,10 @@ export async function loadProjectDraft(id: string): Promise<{ const location = await findBrowserProjectLocation(id); const session = browserSessions.get(id); if (location && !session) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); - const storedProject = session?.project ?? await idbGet(STORES.PROJECTS, PROJECT_PREFIX + id); + const desktopDirectory = await findDesktopProjectLocation(id); + const desktopSession = desktopSessions.get(id); + if (desktopDirectory && !desktopSession) throw new Error("PROJECT_NOT_OPEN"); + const storedProject = desktopSession?.project ?? session?.project ?? await idbGet(STORES.PROJECTS, PROJECT_PREFIX + id); if (!storedProject) return null; const project = normalizeProjectData(storedProject); @@ -151,7 +196,7 @@ export async function loadProjectDraft(id: string): Promise<{ for (const meta of project.audioMeta) { try { const handle = await getBrowserMediaHandle(id, meta.id); - const file = handle ? await readBrowserMedia(handle) : await mediaStorage.get(projectMediaKey(id, meta.id)) ?? + const file = meta.sourcePath && desktopSession ? await readDesktopAudio(meta.sourcePath, meta.type) : handle ? await readBrowserMedia(handle) : await mediaStorage.get(projectMediaKey(id, meta.id)) ?? (id === LEGACY_PROJECT_ID ? await mediaStorage.get(meta.id) : null); if (file) { const url = URL.createObjectURL(file); @@ -162,6 +207,7 @@ export async function loadProjectDraft(id: string): Promise<{ duration: meta.duration, coverUrl: meta.coverUrl, file, + sourcePath: meta.sourcePath, url, }); } diff --git a/src/types/resource.ts b/src/types/resource.ts index 9b52f70..99a18eb 100644 --- a/src/types/resource.ts +++ b/src/types/resource.ts @@ -6,4 +6,5 @@ export interface AudioResource { coverUrl?: string; // 内嵌封面的 Data URL file: File; duration?: number; + sourcePath?: string; } diff --git a/src/types/storage.ts b/src/types/storage.ts index b15f756..486e8ca 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -11,6 +11,7 @@ export interface SerializedAudioMetadata { coverUrl?: string; // Data URL 格式的封面 size?: number; type?: string; + sourcePath?: string; } /** diff --git a/src/views/ProjectsView.vue b/src/views/ProjectsView.vue index 5523107..73441a8 100644 --- a/src/views/ProjectsView.vue +++ b/src/views/ProjectsView.vue @@ -9,7 +9,8 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTitleBarDrag } from "@/composables/useTitleBarDrag"; -import { createProject, createFolderProject, deleteProject, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; +import { createProject, createFolderProject, createDesktopFolderProject, deleteProject, getProjectLocationLabel, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; +import { pickDesktopDirectory } from "@/services/storage/desktopProjectFile"; import { pickProjectDirectory } from "@/services/storage/browserProjectFile"; import type { BasProjectData } from "@/types/storage"; import { isDesktopApp, isMacOS } from "@/utils/desktop"; @@ -30,9 +31,13 @@ const error = ref(""); const isCreating = ref(false); const isCreateOpen = ref(false); const isSettingsOpen = ref(false); +const isRemoveOpen = ref(false); +const deleteDiskFiles = ref(false); +const removeLocations = ref>({}); const name = ref(""); const directory = ref(null); -const supportsFolder = !isDesktop && "showDirectoryPicker" in window; +const desktopDirectory = ref(null); +const supportsFolder = isDesktop || "showDirectoryPicker" in window; const filtered = computed(() => projects.value.filter((project) => project.name.toLowerCase().includes(search.value.trim().toLowerCase())) .sort((a, b) => descending.value ? b.updatedAt - a.updatedAt : a.updatedAt - b.updatedAt)); const allSelected = computed(() => filtered.value.length > 0 && filtered.value.every((p) => selected.value.includes(p.id))); @@ -45,9 +50,9 @@ const refresh = async () => { finally { isLoading.value = false; } }; onMounted(refresh); -const showCreate = () => { name.value = ""; directory.value = null; isCreateOpen.value = true; }; +const showCreate = () => { name.value = ""; directory.value = null; desktopDirectory.value = null; isCreateOpen.value = true; }; const selectDirectory = async () => { - try { directory.value = await pickProjectDirectory(); } + try { if (isDesktop) desktopDirectory.value = await pickDesktopDirectory(); else directory.value = await pickProjectDirectory(); } catch (cause) { if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.folderFailed")); } } }; const open = async (id: string) => { @@ -56,11 +61,11 @@ const open = async (id: string) => { }; const create = async () => { const projectName = name.value.trim(); - if (!projectName || isCreating.value || (supportsFolder && !directory.value)) return; + if (!projectName || isCreating.value || (supportsFolder && !(isDesktop ? desktopDirectory.value : directory.value))) return; isCreating.value = true; try { const trackName = t("timeline.defaultTrackName", { n: 1 }); - const project = directory.value ? await createFolderProject(projectName, trackName, directory.value) : await createProject(projectName, trackName); + const project = desktopDirectory.value ? await createDesktopFolderProject(projectName, trackName, desktopDirectory.value) : directory.value ? await createFolderProject(projectName, trackName, directory.value) : await createProject(projectName, trackName); isCreateOpen.value = false; emit("open", project.id); } catch (cause) { console.error("[Projects] Failed to create", cause); window.alert(t("projects.createFailed")); } @@ -71,9 +76,19 @@ const toggleAll = () => { selected.value = allSelected.value ? selected.value.filter((id) => !ids.has(id)) : Array.from(new Set([...selected.value, ...ids])); }; const removeSelected = async () => { - if (!selected.value.length || !window.confirm(t("projects.confirmDelete", { count: selected.value.length }))) return; - try { for (const id of selected.value) await deleteProject(id); selected.value = []; await refresh(); } - catch (cause) { console.error("[Projects] Failed to delete", cause); window.alert(t("projects.deleteFailed")); await refresh(); } + if (!selected.value.length) return; + const locations = await Promise.all(selected.value.map(async (id) => [id, await getProjectLocationLabel(id)] as const)); + removeLocations.value = Object.fromEntries(locations.map(([id, path]) => [id, path || t("projects.storedInternally")])); + deleteDiskFiles.value = false; + isRemoveOpen.value = true; +}; +const confirmRemove = async () => { + if (deleteDiskFiles.value && !window.confirm(t("projects.confirmFileDelete"))) return; + try { + for (const id of [...selected.value]) { await deleteProject(id, deleteDiskFiles.value); selected.value = selected.value.filter((item) => item !== id); } + isRemoveOpen.value = false; + await refresh(); + } catch (cause) { console.error("[Projects] Failed to delete", cause); window.alert(t("projects.deleteFailed")); await refresh(); } }; @@ -122,6 +137,15 @@ const removeSelected = async () => { - {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}
{{ directory?.name || t("projects.emptyFolder") }}
+ + + {{ t("projects.removeTitle") }}{{ t("projects.removeDescription") }} +
  • {{ projects.find(p => p.id === id)?.name }}
    {{ removeLocations[id] }}
+ + + +
+
+ {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}
{{ desktopDirectory || directory?.name || t("projects.emptyFolder") }}
From 6bf02161c23bee6e71bc2cfa756d3936b664c2c4 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:29:39 +0800 Subject: [PATCH 08/19] Add backups, local reopening and media relinking --- src-tauri/src/lib.rs | 11 +- src-tauri/src/project_files.rs | 178 +++++++++++++++++---- src/components/editor/EditorLayout.vue | 2 +- src/components/editor/ResourcesPanel.vue | 37 ++++- src/composables/useProjectAutoSave.ts | 1 + src/i18n/messages/projects.ts | 9 ++ src/services/storage/browserBackups.ts | 41 +++++ src/services/storage/browserProjectFile.ts | 3 + src/services/storage/desktopProjectFile.ts | 8 +- src/services/storage/projectStorage.ts | 57 ++++++- src/views/ProjectsView.vue | 25 ++- tests/browser-project-file.test.ts | 39 ++++- 12 files changed, 375 insertions(+), 36 deletions(-) create mode 100644 src/services/storage/browserBackups.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1ea9ead..da32835 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -29,7 +29,16 @@ pub fn run() { ) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_opener::init()) - .invoke_handler(tauri::generate_handler![commands::write_text_file, project_files::create_disk_project, project_files::read_disk_project, project_files::save_disk_project, project_files::read_audio_reference, project_files::delete_disk_project_file]) + .invoke_handler(tauri::generate_handler![ + commands::write_text_file, + project_files::create_disk_project, + project_files::read_disk_project, + project_files::save_disk_project, + project_files::read_audio_reference, + project_files::list_disk_backups, + project_files::read_disk_backup, + project_files::delete_disk_project_file + ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index cbe0135..0e18322 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -18,12 +18,23 @@ fn project_path(directory: &Path) -> Result { pub fn create_disk_project(directory: PathBuf, contents: String) -> Result<(), String> { let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; let path = project_path(&directory)?; - if fs::read_dir(&directory).map_err(|e| e.to_string())?.next().is_some() { + if fs::read_dir(&directory) + .map_err(|e| e.to_string())? + .next() + .is_some() + { return Err("DIRECTORY_NOT_EMPTY".into()); } // create_new makes the project filename exclusive even if the directory changes. - let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; - if let Err(error) = file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()) { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(|e| e.to_string())?; + if let Err(error) = file + .write_all(contents.as_bytes()) + .and_then(|()| file.sync_all()) + { drop(file); let _ = fs::remove_file(path); return Err(error.to_string()); @@ -34,34 +45,94 @@ pub fn create_disk_project(directory: PathBuf, contents: String) -> Result<(), S #[tauri::command] pub fn read_disk_project(directory: PathBuf) -> Result { let path = project_path(&directory)?; - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); } fs::read_to_string(path).map_err(|e| e.to_string()) } +fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { + let backup_dir = directory.join(".danmakucut-backups"); + if backup_dir.exists() { + if fs::symlink_metadata(&backup_dir).map_err(|e| e.to_string())?.file_type().is_symlink() { + return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); + } + } else { + fs::create_dir(&backup_dir).map_err(|e| e.to_string())?; + } + let mut backups = Vec::new(); + for entry in fs::read_dir(&backup_dir).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { continue; } + if let Some(name) = entry.file_name().to_str() { + if let Some(timestamp) = name.strip_prefix("backup-").and_then(|s| s.strip_suffix(".basproj")).and_then(|s| s.parse::().ok()) { + backups.push((timestamp, entry.path())); + } + } + } + backups.sort_by(|a, b| b.0.cmp(&a.0)); + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_millis(); + if backups.first().is_some_and(|(time, _)| now.saturating_sub(*time) < 300_000) { return Ok(()); } + let path = backup_dir.join(format!("backup-{now}.basproj")); + let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; + if let Err(error) = file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()) { + drop(file); + let _ = fs::remove_file(path); + return Err(error.to_string()); + } + for (_, path) in backups.into_iter().skip(9) { fs::remove_file(path).map_err(|e| e.to_string())?; } + Ok(()) +} + #[tauri::command] -pub fn save_disk_project(directory: PathBuf, expected: String, contents: String) -> Result<(), String> { +pub fn save_disk_project( + directory: PathBuf, + expected: String, + contents: String, +) -> Result<(), String> { let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; let path = project_path(&directory)?; - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); } if fs::read_to_string(&path).map_err(|e| e.to_string())? != expected { return Err("PROJECT_MODIFIED_EXTERNALLY".into()); } - let temp = directory.join(format!(".project-{}-{}.tmp", std::process::id(), - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos())); + backup_project(&directory, &expected)?; + let temp = directory.join(format!( + ".project-{}-{}.tmp", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_nanos() + )); let result = (|| -> Result<(), String> { - let mut file = OpenOptions::new().write(true).create_new(true).open(&temp).map_err(|e| e.to_string())?; - file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()).map_err(|e| e.to_string())?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&temp) + .map_err(|e| e.to_string())?; + file.write_all(contents.as_bytes()) + .and_then(|()| file.sync_all()) + .map_err(|e| e.to_string())?; drop(file); if fs::read_to_string(&path).map_err(|e| e.to_string())? != expected { return Err("PROJECT_MODIFIED_EXTERNALLY".into()); } fs::rename(&temp, &path).map_err(|e| e.to_string()) })(); - if result.is_err() { let _ = fs::remove_file(&temp); } + if result.is_err() { + let _ = fs::remove_file(&temp); + } result } @@ -70,23 +141,87 @@ pub fn read_audio_reference(path: PathBuf) -> Result, String> { if !path.is_absolute() || !path.is_file() { return Err("AUDIO_FILE_NOT_FOUND".into()); } - let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase(); + let extension = path + .extension() + .and_then(|value| value.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); if !["mp3", "wav", "ogg", "flac", "m4a", "aac", "opus"].contains(&extension.as_str()) { return Err("UNSUPPORTED_AUDIO_FILE".into()); } let size = fs::metadata(&path).map_err(|e| e.to_string())?.len(); - if size > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + if size > 512 * 1024 * 1024 { + return Err("AUDIO_FILE_TOO_LARGE".into()); + } fs::read(path).map_err(|e| e.to_string()) } +#[tauri::command] +pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Result<(), String> { + let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; + let path = project_path(&directory)?; + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); + } + let data: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&path).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + if data.get("id").and_then(|value| value.as_str()) != Some(project_id.as_str()) { + return Err("PROJECT_ID_MISMATCH".into()); + } + fs::remove_file(path).map_err(|e| e.to_string()) +} + +#[tauri::command] +pub fn list_disk_backups(directory: PathBuf) -> Result, String> { + let path = project_path(&directory)?.parent().ok_or("INVALID_PROJECT_DIRECTORY")?.join(".danmakucut-backups"); + if !path.exists() { return Ok(Vec::new()); } + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + let mut names = Vec::new(); + for entry in fs::read_dir(path).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { continue; } + if let Some(name) = entry.file_name().to_str() { + if valid_backup_name(name) { names.push(name.to_string()); } + } + } + names.sort(); + names.reverse(); + Ok(names) +} + +fn valid_backup_name(name: &str) -> bool { + name.strip_prefix("backup-").and_then(|s| s.strip_suffix(".basproj")).is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) +} + +#[tauri::command] +pub fn read_disk_backup(directory: PathBuf, name: String) -> Result { + if !valid_backup_name(&name) { return Err("INVALID_BACKUP_NAME".into()); } + let backup_dir = project_path(&directory)?.parent().ok_or("INVALID_PROJECT_DIRECTORY")?.join(".danmakucut-backups"); + if fs::symlink_metadata(&backup_dir).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + let path = backup_dir.join(name); + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + fs::read_to_string(path).map_err(|e| e.to_string()) +} + #[cfg(test)] mod tests { use super::*; #[test] fn create_save_and_reject_external_change() { - let directory = std::env::temp_dir().join(format!("danmakucut-test-{}-{}", std::process::id(), - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); + let directory = std::env::temp_dir().join(format!( + "danmakucut-test-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); fs::create_dir(&directory).unwrap(); create_disk_project(directory.clone(), "first".into()).unwrap(); assert!(create_disk_project(directory.clone(), "other".into()).is_err()); @@ -98,16 +233,3 @@ mod tests { } } -#[tauri::command] -pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Result<(), String> { - let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; - let path = project_path(&directory)?; - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { - return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); - } - let data: serde_json::Value = serde_json::from_str(&fs::read_to_string(&path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?; - if data.get("id").and_then(|value| value.as_str()) != Some(project_id.as_str()) { - return Err("PROJECT_ID_MISMATCH".into()); - } - fs::remove_file(path).map_err(|e| e.to_string()) -} diff --git a/src/components/editor/EditorLayout.vue b/src/components/editor/EditorLayout.vue index 88db0f1..d937a64 100644 --- a/src/components/editor/EditorLayout.vue +++ b/src/components/editor/EditorLayout.vue @@ -235,7 +235,7 @@ useEventListener("mouseleave", stopResize);
- +
diff --git a/src/components/editor/ResourcesPanel.vue b/src/components/editor/ResourcesPanel.vue index c054f0e..a4c9359 100644 --- a/src/components/editor/ResourcesPanel.vue +++ b/src/components/editor/ResourcesPanel.vue @@ -6,13 +6,17 @@ import { useTimelineStore } from "@/stores/timeline"; import { useAudioStore } from "@/stores/audio"; import type { DanmuType, AnyDanmu } from "@/types/danmu"; import type { AudioResource } from "@/types/resource"; +import type { SerializedAudioMetadata } from "@/types/storage"; +import { pickDesktopAudio } from "@/services/storage/desktopProjectFile"; +import { pickBrowserAudio } from "@/services/storage/browserMediaFile"; import { getItemName } from "@/utils/resourceUtils"; import { extractAudioCover } from "@/utils/audio/audio-cover"; import { LayoutGrid, List } from "lucide-vue-next"; import { hasBrowserProjectSession, hasDesktopProjectSession } from "@/services/storage/projectStorage"; import { rememberBrowserMedia } from "@/services/storage/browserMediaFile"; -const props = defineProps<{ projectId: string }>(); +const props = defineProps<{ projectId: string; offlineAudio?: SerializedAudioMetadata[] }>(); +const emit = defineEmits<{ (e: "relink-audio", id: string): void }>(); import ResourcesSidebar from "./resources/ResourcesSidebar.vue"; import ResourcesHeader from "./resources/ResourcesHeader.vue"; @@ -133,6 +137,32 @@ const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle, sour ); }; +const relinkAudio = async (meta: SerializedAudioMetadata) => { + try { + let file: File; + let sourcePath: string | undefined; + let handle: FileSystemFileHandle | undefined; + if (hasDesktopProjectSession(props.projectId)) { + const selection = await pickDesktopAudio(); + if (!selection) return; + file = selection.file; + sourcePath = selection.path; + } else { + const selection = await pickBrowserAudio(); + if (!selection) return; + handle = selection; + file = await selection.getFile(); + } + if (!window.confirm(t("projects.relinkConfirm", { name: file.name, size: file.size }))) return; + if (handle) await rememberBrowserMedia(props.projectId, meta.id, handle); + const url = URL.createObjectURL(file); + audioStore.add({ id: meta.id, type: "audio-file", name: meta.name, duration: meta.duration, coverUrl: meta.coverUrl, file, url, sourcePath }); + emit("relink-audio", meta.id); + } catch (error) { + if (!(error instanceof DOMException && error.name === "AbortError")) { console.error("Failed to relink audio", error); window.alert(t("projects.relinkFailed")); } + } +}; + const isAudioFile = (file: File) => file.type.startsWith("audio/"); const hasFiles = (event: DragEvent) => @@ -231,6 +261,11 @@ const toggleResourceLayout = () => { @upload-audio="handleAudioUpload" /> +
+
{{ t("projects.offlineMedia") }}
+
{{ audio.name }}
+
+ }; + +/** Preserve the previous version before replacing it; only manage our own backup names. */ +export async function backupBrowserProject(directory: FileSystemDirectoryHandle, contents: string, now = Date.now()): Promise { + const backups = await directory.getDirectoryHandle(".danmakucut-backups", { create: true }); + const entries: { name: string; time: number }[] = []; + for await (const entry of (backups as IterableDirectory).values()) { + const match = entry.kind === "file" ? BACKUP_NAME.exec(entry.name) : null; + if (match) entries.push({ name: entry.name, time: Number(match[1]) }); + } + entries.sort((a, b) => b.time - a.time || b.name.localeCompare(a.name)); + if (entries[0] && now - entries[0].time < BACKUP_INTERVAL_MS) return; + const name = `backup-${now}-${crypto.randomUUID()}.basproj`; + const handle = await backups.getFileHandle(name, { create: true }); + const writer = await handle.createWritable(); + try { await writer.write(contents); await writer.close(); } + catch (error) { await writer.abort().catch(() => {}); throw error; } + // Best effort: a pruning failure must not cause the save to be reported as successful. + for (const entry of entries.slice(MAX_BACKUPS - 1)) await backups.removeEntry(entry.name); +} + +export async function listBrowserBackups(directory: FileSystemDirectoryHandle): Promise { + let backups: FileSystemDirectoryHandle; + try { backups = await directory.getDirectoryHandle(".danmakucut-backups"); } + catch (error) { if (error instanceof DOMException && error.name === "NotFoundError") return []; throw error; } + const names: string[] = []; + for await (const entry of (backups as IterableDirectory).values()) { + if (entry.kind === "file" && BACKUP_NAME.test(entry.name)) names.push(entry.name); + } + return names.sort().reverse(); +} + +export async function readBrowserBackup(directory: FileSystemDirectoryHandle, name: string): Promise { + if (!BACKUP_NAME.test(name)) throw new Error("INVALID_BACKUP_NAME"); + const backups = await directory.getDirectoryHandle(".danmakucut-backups"); + return (await (await backups.getFileHandle(name)).getFile()).text(); +} diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index 995453f..bc389ed 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -1,3 +1,4 @@ +import { backupBrowserProject } from "./browserBackups"; import type { BasProjectData } from "@/types/storage"; import { idbDelete, idbGet, idbSet, STORES } from "./indexedDB"; import { normalizeProjectData } from "./projectSchema"; @@ -110,6 +111,8 @@ export async function saveBrowserProject(opened: BrowserProjectFile, project: Ba const normalized = normalizeProjectData(project); if (normalized.id !== opened.project.id) throw new Error("PROJECT_ID_MISMATCH"); const contents = JSON.stringify(normalized, null, 2); + await backupBrowserProject(opened.directory, current); + if ((await digest(await (await handle.getFile()).text())) !== opened.fingerprint) throw new Error("PROJECT_MODIFIED_EXTERNALLY"); const writable = await handle.createWritable(); try { await writable.write(contents); diff --git a/src/services/storage/desktopProjectFile.ts b/src/services/storage/desktopProjectFile.ts index 28b8823..6296cf2 100644 --- a/src/services/storage/desktopProjectFile.ts +++ b/src/services/storage/desktopProjectFile.ts @@ -20,10 +20,10 @@ export async function createDesktopProject(directory: string, project: BasProjec await idbSet(STORES.PROJECTS, prefix + project.id, directory); return { directory, contents, project }; } -export async function openDesktopProject(directory: string, expectedId: string): Promise { +export async function openDesktopProject(directory: string, expectedId?: string): Promise { const contents = await invoke("read_disk_project", { directory }); const project = normalizeProjectData(JSON.parse(contents)); - if (project.id !== expectedId) throw new Error("PROJECT_ID_MISMATCH"); + if (expectedId && project.id !== expectedId) throw new Error("PROJECT_ID_MISMATCH"); return { directory, contents, project }; } export async function saveDesktopProject(session: DesktopProjectSession, project: BasProjectData): Promise { @@ -47,3 +47,7 @@ export async function readDesktopAudio(path: string, mimeType = "audio/*"): Prom export async function deleteDesktopProjectFile(directory: string, projectId: string): Promise { await invoke("delete_disk_project_file", { directory, projectId }); } + +export async function rememberDesktopProject(id: string, directory: string): Promise { + await idbSet(STORES.PROJECTS, prefix + id, directory); +} diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index 64940d3..89c750f 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -1,7 +1,9 @@ +import { invoke } from "@tauri-apps/api/core"; +import { listBrowserBackups, readBrowserBackup } from "./browserBackups"; import type { AudioResource } from "@/types/resource"; import type { BasProjectData } from "@/types/storage"; import { idbGet, idbSet, idbDelete, idbGetAllKeys, STORES } from "./indexedDB"; -import { createDesktopProject, findDesktopProjectLocation, forgetDesktopProject, openDesktopProject, saveDesktopProject, readDesktopAudio, deleteDesktopProjectFile, type DesktopProjectSession } from "./desktopProjectFile"; +import { createDesktopProject, rememberDesktopProject, findDesktopProjectLocation, forgetDesktopProject, openDesktopProject, saveDesktopProject, readDesktopAudio, deleteDesktopProjectFile, type DesktopProjectSession } from "./desktopProjectFile"; import { mediaStorage } from "./mediaStorage"; import { getBrowserMediaHandle, readBrowserMedia } from "./browserMediaFile"; import { normalizeProjectData, PROJECT_VERSION } from "./projectSchema"; @@ -85,6 +87,25 @@ export async function createDesktopFolderProject(name: string, trackName: string return project; } +/** The user explicitly chose this directory, so it may also repair a moved project. */ +export async function openSelectedProjectDirectory(directory: string | FileSystemDirectoryHandle): Promise { + if (typeof directory === "string") { + const session = await openDesktopProject(directory); + if (!session.project.id) throw new Error("INVALID_PROJECT_ID"); + await rememberDesktopProject(session.project.id, directory); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + session.project.id, session.project); + desktopSessions.set(session.project.id, session); + return session.project; + } + if (!(await ensureDirectoryPermission(directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const session = await openBrowserProject(directory, "project.basproj"); + if (!session.project.id) throw new Error("INVALID_PROJECT_ID"); + await rememberBrowserProject({ projectId: session.project.id, directory, fileName: session.fileName }); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + session.project.id, session.project); + browserSessions.set(session.project.id, session); + return session.project; +} + /** 在用户点击打开时恢复权限和文件内容;不允许静默使用过期缓存。 */ export async function prepareProjectOpen(id: string): Promise { const desktopDirectory = await findDesktopProjectLocation(id); @@ -244,3 +265,37 @@ export async function parseProjectFile(file: File): Promise { const text = await file.text(); return normalizeProjectData(JSON.parse(text), file.name.replace(/\.[^/.]+$/, "")); } + +/** List backups without changing the current project. */ +export async function listProjectBackups(id: string): Promise { + const desktop = await findDesktopProjectLocation(id); + if (desktop) return invoke("list_disk_backups", { directory: desktop }); + const browser = await findBrowserProjectLocation(id); + if (!browser) return []; + if (!(await ensureDirectoryPermission(browser.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + return listBrowserBackups(browser.directory); +} + +/** Validate both project identity and current file before restoring a chosen snapshot. */ +export async function restoreProjectBackup(id: string, name: string): Promise { + const desktop = await findDesktopProjectLocation(id); + const browser = await findBrowserProjectLocation(id); + if (desktop) { + const contents = await invoke("read_disk_backup", { directory: desktop, name }); + const backup = normalizeProjectData(JSON.parse(contents)); + if (backup.id !== id) throw new Error("PROJECT_ID_MISMATCH"); + const current = await openDesktopProject(desktop, id); + const saved = await saveDesktopProject(current, backup); + desktopSessions.set(id, saved); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + id, saved.project); + } else if (browser) { + if (!(await ensureDirectoryPermission(browser.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + const backup = normalizeProjectData(JSON.parse(await readBrowserBackup(browser.directory, name))); + if (backup.id !== id) throw new Error("PROJECT_ID_MISMATCH"); + const current = await openBrowserProject(browser.directory, browser.fileName); + if (current.project.id !== id) throw new Error("PROJECT_ID_MISMATCH"); + const saved = await saveBrowserProject(current, backup); + browserSessions.set(id, saved); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + id, saved.project); + } else throw new Error("BACKUPS_UNAVAILABLE"); +} diff --git a/src/views/ProjectsView.vue b/src/views/ProjectsView.vue index 73441a8..27b0e7c 100644 --- a/src/views/ProjectsView.vue +++ b/src/views/ProjectsView.vue @@ -9,7 +9,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTitleBarDrag } from "@/composables/useTitleBarDrag"; -import { createProject, createFolderProject, createDesktopFolderProject, deleteProject, getProjectLocationLabel, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; +import { createProject, createFolderProject, createDesktopFolderProject, deleteProject, getProjectLocationLabel, listProjectBackups, restoreProjectBackup, openSelectedProjectDirectory, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; import { pickDesktopDirectory } from "@/services/storage/desktopProjectFile"; import { pickProjectDirectory } from "@/services/storage/browserProjectFile"; import type { BasProjectData } from "@/types/storage"; @@ -32,6 +32,9 @@ const isCreating = ref(false); const isCreateOpen = ref(false); const isSettingsOpen = ref(false); const isRemoveOpen = ref(false); +const backupProjectId = ref(""); +const backupNames = ref([]); +const isBackupOpen = ref(false); const deleteDiskFiles = ref(false); const removeLocations = ref>({}); const name = ref(""); @@ -55,6 +58,14 @@ const selectDirectory = async () => { try { if (isDesktop) desktopDirectory.value = await pickDesktopDirectory(); else directory.value = await pickProjectDirectory(); } catch (cause) { if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.folderFailed")); } } }; +const openExisting = async () => { + try { + const chosen = isDesktop ? await pickDesktopDirectory() : await pickProjectDirectory(); + if (!chosen) return; + const project = await openSelectedProjectDirectory(chosen); + emit("open", project.id); + } catch (cause) { if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.openFailed")); } } +}; const open = async (id: string) => { try { await prepareProjectOpen(id); emit("open", id); } catch (cause) { console.error("[Projects] Failed to open", cause); window.alert(t("projects.openFailed")); } @@ -71,6 +82,15 @@ const create = async () => { } catch (cause) { console.error("[Projects] Failed to create", cause); window.alert(t("projects.createFailed")); } finally { isCreating.value = false; } }; +const showBackups = async (id: string) => { + try { backupNames.value = await listProjectBackups(id); backupProjectId.value = id; isBackupOpen.value = true; } + catch (cause) { console.error(cause); window.alert(t("projects.backupFailed")); } +}; +const restoreBackup = async (name: string) => { + if (!window.confirm(t("projects.confirmRestore"))) return; + try { await restoreProjectBackup(backupProjectId.value, name); isBackupOpen.value = false; await refresh(); } + catch (cause) { console.error(cause); window.alert(t("projects.backupFailed")); } +}; const toggleAll = () => { const ids = new Set(filtered.value.map((p) => p.id)); selected.value = allSelected.value ? selected.value.filter((id) => !ids.has(id)) : Array.from(new Set([...selected.value, ...ids])); @@ -113,6 +133,7 @@ const confirmRemove = async () => {
+
@@ -133,10 +154,12 @@ const confirmRemove = async () => {
+ + {{ t("projects.backups") }}{{ t("projects.confirmRestore") }}

{{ t("projects.noBackups") }}

  • {{ name }}
{{ t("projects.removeTitle") }}{{ t("projects.removeDescription") }} diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts index 2e922d3..d0cd5bb 100644 --- a/tests/browser-project-file.test.ts +++ b/tests/browser-project-file.test.ts @@ -6,6 +6,10 @@ import { ensureBrowserMediaPermission, readBrowserMedia } from "../src/services/ const project = { version: 2, id: "project-1", name: "Project", createdAt: 1, updatedAt: 1, canvas: { width: 800, height: 450 }, timeline: { duration: 0 }, danmus: [], audioMeta: [], tracks: [] }; +function fakeBackupDirectory() { + return { values: async function* () {}, getFileHandle: async () => ({ createWritable: async () => ({ write: async () => {}, close: async () => {}, abort: async () => {} }) }), removeEntry: async () => {} }; +} + function directoryFixture(initial?: string) { let contents = initial; const fileHandle = { @@ -18,6 +22,7 @@ function directoryFixture(initial?: string) { }; const directory = { kind: "directory", name: "project", queryPermission: async () => "granted", + getDirectoryHandle: async () => fakeBackupDirectory(), values: async function* () { if (contents !== undefined) yield fileHandle; }, getFileHandle: async (_name: string, options?: { create?: boolean }) => { if (contents === undefined && !options?.create) throw new DOMException("Missing", "NotFoundError"); @@ -82,7 +87,7 @@ test("aborts the writable stream when writing fails", async () => { abort: async () => { aborted = true; } }) }; - const directory = { queryPermission: async () => "granted", getFileHandle: async () => fileHandle } as unknown as FileSystemDirectoryHandle; + const directory = { queryPermission: async () => "granted", getFileHandle: async () => fileHandle, getDirectoryHandle: async () => fakeBackupDirectory() } as unknown as FileSystemDirectoryHandle; const opened = await openBrowserProject(directory, "project.basproj"); await assert.rejects(saveBrowserProject(opened, project), /disk full/); assert.equal(aborted, true); @@ -104,3 +109,35 @@ test("serializes project saves with Web Locks when available", async () => { else Reflect.deleteProperty(globalThis, "navigator"); } }); + +test("disk removal validates project identity and removes only the project file", async () => { + const { deleteBrowserProjectFile } = await import("../src/services/storage/browserProjectFile"); + let removed = ""; + const contents = JSON.stringify(project); + const directory = { + queryPermission: async () => "granted", + getFileHandle: async () => ({ getFile: async () => new File([contents], "project.basproj") }), + removeEntry: async (name: string) => { removed = name; } + } as unknown as FileSystemDirectoryHandle; + await assert.rejects(deleteBrowserProjectFile({ projectId: "other", directory, fileName: "project.basproj" }), /PROJECT_ID_MISMATCH/); + assert.equal(removed, ""); + await deleteBrowserProjectFile({ projectId: project.id, directory, fileName: "project.basproj" }); + assert.equal(removed, "project.basproj"); +}); + + +test("backup copies previous content at most once per interval", async () => { + const { backupBrowserProject } = await import("../src/services/storage/browserBackups"); + const files = new Map(); + const backupDir = { + values: async function* () { for (const name of files.keys()) yield { kind: "file", name }; }, + getFileHandle: async (name: string) => ({ createWritable: async () => { let value = ""; return { write: async (text: string) => { value = text; }, close: async () => { files.set(name, value); }, abort: async () => {} }; } }), + removeEntry: async (name: string) => { files.delete(name); } + }; + const dir = { getDirectoryHandle: async () => backupDir } as unknown as FileSystemDirectoryHandle; + await backupBrowserProject(dir, "old", 1_000_000); + await backupBrowserProject(dir, "new", 1_000_001); + assert.deepEqual([...files.values()], ["old"]); + await backupBrowserProject(dir, "new", 1_300_001); + assert.deepEqual([...files.values()], ["old", "new"]); +}); From f615851c1adf27cd71caa7d20477cdef84b4056e Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:33:44 +0800 Subject: [PATCH 09/19] Migrate application projects with project-owned audio --- src-tauri/src/lib.rs | 2 + src-tauri/src/project_files.rs | 139 +++++++++++++++++++++---- src/composables/useProjectAutoSave.ts | 1 + src/i18n/messages/projects.ts | 3 + src/services/storage/projectAssets.ts | 31 ++++++ src/services/storage/projectStorage.ts | 32 +++++- src/types/resource.ts | 1 + src/types/storage.ts | 1 + src/views/ProjectsView.vue | 17 ++- tests/browser-project-file.test.ts | 21 ++++ 10 files changed, 224 insertions(+), 24 deletions(-) create mode 100644 src/services/storage/projectAssets.ts diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index da32835..a2abd49 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -37,6 +37,8 @@ pub fn run() { project_files::read_audio_reference, project_files::list_disk_backups, project_files::read_disk_backup, + project_files::write_project_audio, + project_files::read_project_audio, project_files::delete_disk_project_file ]) .run(tauri::generate_context!()) diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index 0e18322..c5d3b8d 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -58,7 +58,11 @@ pub fn read_disk_project(directory: PathBuf) -> Result { fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { let backup_dir = directory.join(".danmakucut-backups"); if backup_dir.exists() { - if fs::symlink_metadata(&backup_dir).map_err(|e| e.to_string())?.file_type().is_symlink() { + if fs::symlink_metadata(&backup_dir) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } } else { @@ -67,24 +71,47 @@ fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { let mut backups = Vec::new(); for entry in fs::read_dir(&backup_dir).map_err(|e| e.to_string())? { let entry = entry.map_err(|e| e.to_string())?; - if !entry.file_type().map_err(|e| e.to_string())?.is_file() { continue; } + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + continue; + } if let Some(name) = entry.file_name().to_str() { - if let Some(timestamp) = name.strip_prefix("backup-").and_then(|s| s.strip_suffix(".basproj")).and_then(|s| s.parse::().ok()) { + if let Some(timestamp) = name + .strip_prefix("backup-") + .and_then(|s| s.strip_suffix(".basproj")) + .and_then(|s| s.parse::().ok()) + { backups.push((timestamp, entry.path())); } } } - backups.sort_by(|a, b| b.0.cmp(&a.0)); - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|e| e.to_string())?.as_millis(); - if backups.first().is_some_and(|(time, _)| now.saturating_sub(*time) < 300_000) { return Ok(()); } + backups.sort_by_key(|item| std::cmp::Reverse(item.0)); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| e.to_string())? + .as_millis(); + if backups + .first() + .is_some_and(|(time, _)| now.saturating_sub(*time) < 300_000) + { + return Ok(()); + } let path = backup_dir.join(format!("backup-{now}.basproj")); - let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; - if let Err(error) = file.write_all(contents.as_bytes()).and_then(|()| file.sync_all()) { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(|e| e.to_string())?; + if let Err(error) = file + .write_all(contents.as_bytes()) + .and_then(|()| file.sync_all()) + { drop(file); let _ = fs::remove_file(path); return Err(error.to_string()); } - for (_, path) in backups.into_iter().skip(9) { fs::remove_file(path).map_err(|e| e.to_string())?; } + for (_, path) in backups.into_iter().skip(9) { + fs::remove_file(path).map_err(|e| e.to_string())?; + } Ok(()) } @@ -178,15 +205,30 @@ pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Resul #[tauri::command] pub fn list_disk_backups(directory: PathBuf) -> Result, String> { - let path = project_path(&directory)?.parent().ok_or("INVALID_PROJECT_DIRECTORY")?.join(".danmakucut-backups"); - if !path.exists() { return Ok(Vec::new()); } - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + let path = project_path(&directory)? + .parent() + .ok_or("INVALID_PROJECT_DIRECTORY")? + .join(".danmakucut-backups"); + if !path.exists() { + return Ok(Vec::new()); + } + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); + } let mut names = Vec::new(); for entry in fs::read_dir(path).map_err(|e| e.to_string())? { let entry = entry.map_err(|e| e.to_string())?; - if !entry.file_type().map_err(|e| e.to_string())?.is_file() { continue; } + if !entry.file_type().map_err(|e| e.to_string())?.is_file() { + continue; + } if let Some(name) = entry.file_name().to_str() { - if valid_backup_name(name) { names.push(name.to_string()); } + if valid_backup_name(name) { + names.push(name.to_string()); + } } } names.sort(); @@ -195,19 +237,77 @@ pub fn list_disk_backups(directory: PathBuf) -> Result, String> { } fn valid_backup_name(name: &str) -> bool { - name.strip_prefix("backup-").and_then(|s| s.strip_suffix(".basproj")).is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) + name.strip_prefix("backup-") + .and_then(|s| s.strip_suffix(".basproj")) + .is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) } #[tauri::command] pub fn read_disk_backup(directory: PathBuf, name: String) -> Result { - if !valid_backup_name(&name) { return Err("INVALID_BACKUP_NAME".into()); } - let backup_dir = project_path(&directory)?.parent().ok_or("INVALID_PROJECT_DIRECTORY")?.join(".danmakucut-backups"); - if fs::symlink_metadata(&backup_dir).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + if !valid_backup_name(&name) { + return Err("INVALID_BACKUP_NAME".into()); + } + let backup_dir = project_path(&directory)? + .parent() + .ok_or("INVALID_PROJECT_DIRECTORY")? + .join(".danmakucut-backups"); + if fs::symlink_metadata(&backup_dir) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); + } let path = backup_dir.join(name); - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); } + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("BACKUP_SYMLINK_NOT_ALLOWED".into()); + } fs::read_to_string(path).map_err(|e| e.to_string()) } +fn asset_path(directory: &Path, name: &str, create: bool) -> Result { + if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.') || name.starts_with('.') || name.contains("..") { + return Err("INVALID_ASSET_NAME".into()); + } + let _ = project_path(directory)?; + let assets = directory.join("assets"); + let audio = assets.join("audio"); + for dir in [&assets, &audio] { + if dir.exists() { + let metadata = fs::symlink_metadata(dir).map_err(|e| e.to_string())?; + if metadata.file_type().is_symlink() || !metadata.is_dir() { return Err("INVALID_ASSET_DIRECTORY".into()); } + } else if create { fs::create_dir(dir).map_err(|e| e.to_string())?; } + else { return Err("ASSET_NOT_FOUND".into()); } + } + Ok(audio.join(name)) +} + +#[tauri::command] +pub fn write_project_audio(directory: PathBuf, name: String, bytes: Vec) -> Result<(), String> { + if bytes.len() > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + let path = asset_path(&directory, &name, true)?; + let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; + if let Err(error) = file.write_all(&bytes).and_then(|()| file.sync_all()) { + drop(file); + let _ = fs::remove_file(path); + return Err(error.to_string()); + } + Ok(()) +} + +#[tauri::command] +pub fn read_project_audio(directory: PathBuf, name: String) -> Result, String> { + let path = asset_path(&directory, &name, false)?; + if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("ASSET_SYMLINK_NOT_ALLOWED".into()); } + let size = fs::metadata(&path).map_err(|e| e.to_string())?.len(); + if size > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + fs::read(path).map_err(|e| e.to_string()) +} + #[cfg(test)] mod tests { use super::*; @@ -232,4 +332,3 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } } - diff --git a/src/composables/useProjectAutoSave.ts b/src/composables/useProjectAutoSave.ts index a3749a8..e441a23 100644 --- a/src/composables/useProjectAutoSave.ts +++ b/src/composables/useProjectAutoSave.ts @@ -55,6 +55,7 @@ export function useProjectAutoSave(projectId: string) { size: resource.file?.size, type: resource.file?.type, sourcePath: resource.sourcePath, + relativePath: resource.relativePath, })); const knownIds = new Set(metadata.map((item) => item.id)); for (const item of importedAudioMeta.value) { diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index cc602f7..4f1fb64 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,4 +1,5 @@ const zhCN = { + migrate: "迁移到文件夹", migrationFailed: "迁移失败:请确认素材可读取、目标为空且有写入权限。原项目仍被保留,目标文件夹可能存在已创建的文件。", openExisting: "打开本地项目", backups: "历史备份", noBackups: "暂无历史备份。", restoreBackup: "恢复", confirmRestore: "恢复此版本会替换当前项目文件,确认继续?", backupFailed: "备份操作失败,请检查文件权限和项目状态。", offlineMedia: "素材离线", relink: "重新链接", relinkFailed: "重新链接失败,请检查文件和权限。", relinkConfirm: "选择的文件:{name}({size} 字节)。确认用于重新链接?", @@ -14,6 +15,7 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + migrate: "Migrate to folder", migrationFailed: "Migration failed. Check media, the empty destination and write access. The old project is retained; the destination may contain created files.", openExisting: "Open local project", backups: "Backups", noBackups: "No backups yet.", restoreBackup: "Restore", confirmRestore: "Replace the current project with this backup?", backupFailed: "Backup operation failed. Check the project and file permissions.", offlineMedia: "Offline media", relink: "Relink", relinkFailed: "Could not relink this file. Check file access and permissions.", relinkConfirm: "Use {name} ({size} bytes) for this media?", @@ -29,6 +31,7 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + migrate: "フォルダーへ移行", migrationFailed: "移行に失敗しました。素材、空のフォルダー、権限を確認してください。元のプロジェクトは保持されます。", openExisting: "ローカルプロジェクトを開く", backups: "バックアップ", noBackups: "バックアップはありません。", restoreBackup: "復元", confirmRestore: "現在のプロジェクトをこのバックアップで置き換えますか?", backupFailed: "バックアップ操作に失敗しました。", offlineMedia: "オフライン素材", relink: "再リンク", relinkFailed: "再リンクできません。権限とファイルを確認してください。", relinkConfirm: "{name}({size} バイト)を使用しますか?", diff --git a/src/services/storage/projectAssets.ts b/src/services/storage/projectAssets.ts new file mode 100644 index 0000000..37853b7 --- /dev/null +++ b/src/services/storage/projectAssets.ts @@ -0,0 +1,31 @@ +import { invoke } from "@tauri-apps/api/core"; + +function validate(name: string): void { + if (!/^[A-Za-z0-9][A-Za-z0-9.-]*$/.test(name) || name.includes("..")) throw new Error("INVALID_ASSET_NAME"); +} +async function webAudioDirectory(directory: FileSystemDirectoryHandle, create: boolean): Promise { + return (await directory.getDirectoryHandle("assets", { create })).getDirectoryHandle("audio", { create }); +} +export async function writeProjectAudio(directory: string | FileSystemDirectoryHandle, name: string, file: File): Promise { + validate(name); + if (typeof directory === "string") { + await invoke("write_project_audio", { directory, name, bytes: Array.from(new Uint8Array(await file.arrayBuffer())) }); + } else { + const audio = await webAudioDirectory(directory, true); + // Assets use fresh UUID-based names. Never overwrite a pre-existing file. + try { await audio.getFileHandle(name); throw new Error("ASSET_ALREADY_EXISTS"); } + catch (error) { if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; } + const handle = await audio.getFileHandle(name, { create: true }); + const writer = await handle.createWritable(); + try { await writer.write(file); await writer.close(); } + catch (error) { await writer.abort().catch(() => {}); throw error; } + } +} +export async function readProjectAudio(directory: string | FileSystemDirectoryHandle, name: string, type?: string): Promise { + validate(name); + if (typeof directory === "string") { + const bytes = await invoke("read_project_audio", { directory, name }); + return new File([new Uint8Array(bytes)], name, { type }); + } + return (await (await webAudioDirectory(directory, false)).getFileHandle(name)).getFile(); +} diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index 89c750f..1b38aa0 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -1,3 +1,4 @@ +import { writeProjectAudio, readProjectAudio } from "./projectAssets"; import { invoke } from "@tauri-apps/api/core"; import { listBrowserBackups, readBrowserBackup } from "./browserBackups"; import type { AudioResource } from "@/types/resource"; @@ -106,6 +107,31 @@ export async function openSelectedProjectDirectory(directory: string | FileSyste return session.project; } +/** Copies a legacy project and all available media into a new user-chosen directory. */ +export async function migrateProjectToDirectory(id: string, directory: string | FileSystemDirectoryHandle): Promise { + if (await findDesktopProjectLocation(id) || await findBrowserProjectLocation(id)) throw new Error("ALREADY_A_FOLDER_PROJECT"); + const old = await loadProjectDraft(id); + if (!old) throw new Error("PROJECT_NOT_FOUND"); + const byId = new Map(old.audioResources.map((resource) => [resource.id, resource])); + if (old.project.audioMeta.some((meta) => !byId.has(meta.id))) throw new Error("MEDIA_OFFLINE"); + const project: BasProjectData = { + ...old.project, id: crypto.randomUUID(), createdAt: Date.now(), updatedAt: Date.now(), + audioMeta: old.project.audioMeta.map((meta) => ({ ...meta, sourcePath: undefined, relativePath: `${crypto.randomUUID()}.audio` })) + }; + // The old project remains intact even if copying or registration fails. + const desktop = typeof directory === "string" ? await createDesktopProject(directory, project) : null; + const browser = typeof directory !== "string" ? await createBrowserProject(directory, "project.basproj", project) : null; + for (const meta of project.audioMeta) await writeProjectAudio(directory, meta.relativePath!, byId.get(meta.id)!.file); + if (browser && typeof directory !== "string") { + await rememberBrowserProject({ projectId: project.id, directory, fileName: "project.basproj" }); + browserSessions.set(project.id, browser); + } + if (desktop) desktopSessions.set(project.id, desktop); + await idbSet(STORES.PROJECTS, PROJECT_PREFIX + project.id, project); + for (const resource of old.audioResources) URL.revokeObjectURL(resource.url); + return project; +} + /** 在用户点击打开时恢复权限和文件内容;不允许静默使用过期缓存。 */ export async function prepareProjectOpen(id: string): Promise { const desktopDirectory = await findDesktopProjectLocation(id); @@ -167,7 +193,7 @@ export async function saveProjectDraft( const mediaSaves: Promise[] = []; for (const [id, file] of audioFiles.entries()) { const reference = await getBrowserMediaHandle(projectData.id, id); - if (!reference && !projectData.audioMeta.some((item) => item.id === id && item.sourcePath)) mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); + if (!reference && !projectData.audioMeta.some((item) => item.id === id && (item.sourcePath || item.relativePath))) mediaSaves.push(mediaStorage.save(projectMediaKey(projectData.id, id), file)); } await Promise.all(mediaSaves); @@ -217,7 +243,8 @@ export async function loadProjectDraft(id: string): Promise<{ for (const meta of project.audioMeta) { try { const handle = await getBrowserMediaHandle(id, meta.id); - const file = meta.sourcePath && desktopSession ? await readDesktopAudio(meta.sourcePath, meta.type) : handle ? await readBrowserMedia(handle) : await mediaStorage.get(projectMediaKey(id, meta.id)) ?? + const projectDirectory = desktopSession?.directory ?? session?.directory; + const file = meta.relativePath && projectDirectory ? await readProjectAudio(projectDirectory, meta.relativePath, meta.type) : meta.sourcePath && desktopSession ? await readDesktopAudio(meta.sourcePath, meta.type) : handle ? await readBrowserMedia(handle) : await mediaStorage.get(projectMediaKey(id, meta.id)) ?? (id === LEGACY_PROJECT_ID ? await mediaStorage.get(meta.id) : null); if (file) { const url = URL.createObjectURL(file); @@ -229,6 +256,7 @@ export async function loadProjectDraft(id: string): Promise<{ coverUrl: meta.coverUrl, file, sourcePath: meta.sourcePath, + relativePath: meta.relativePath, url, }); } diff --git a/src/types/resource.ts b/src/types/resource.ts index 99a18eb..0054660 100644 --- a/src/types/resource.ts +++ b/src/types/resource.ts @@ -7,4 +7,5 @@ export interface AudioResource { file: File; duration?: number; sourcePath?: string; + relativePath?: string; } diff --git a/src/types/storage.ts b/src/types/storage.ts index 486e8ca..3a06c68 100644 --- a/src/types/storage.ts +++ b/src/types/storage.ts @@ -12,6 +12,7 @@ export interface SerializedAudioMetadata { size?: number; type?: string; sourcePath?: string; + relativePath?: string; } /** diff --git a/src/views/ProjectsView.vue b/src/views/ProjectsView.vue index 27b0e7c..c8e7348 100644 --- a/src/views/ProjectsView.vue +++ b/src/views/ProjectsView.vue @@ -9,7 +9,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTitleBarDrag } from "@/composables/useTitleBarDrag"; -import { createProject, createFolderProject, createDesktopFolderProject, deleteProject, getProjectLocationLabel, listProjectBackups, restoreProjectBackup, openSelectedProjectDirectory, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; +import { createProject, createFolderProject, createDesktopFolderProject, deleteProject, getProjectLocationLabel, listProjectBackups, restoreProjectBackup, openSelectedProjectDirectory, migrateProjectToDirectory, listProjects, prepareProjectOpen } from "@/services/storage/projectStorage"; import { pickDesktopDirectory } from "@/services/storage/desktopProjectFile"; import { pickProjectDirectory } from "@/services/storage/browserProjectFile"; import type { BasProjectData } from "@/types/storage"; @@ -22,6 +22,7 @@ const isDesktop = isDesktopApp(); const hasControls = isDesktop && !isMacOS(); const titleBarListeners = isDesktop ? useTitleBarDrag() : {}; const projects = ref([]); +const projectLocations = ref>({}); const search = ref(""); const selected = ref([]); const view = ref<"grid" | "list">("grid"); @@ -48,7 +49,7 @@ const formatDate = (timestamp: number) => new Intl.DateTimeFormat(locale.value, const refresh = async () => { isLoading.value = true; error.value = ""; - try { projects.value = await listProjects(); } + try { projects.value = await listProjects(); projectLocations.value = Object.fromEntries(await Promise.all(projects.value.map(async (project) => [project.id, await getProjectLocationLabel(project.id)] as const))); } catch (cause) { console.error("[Projects] Failed to load", cause); error.value = t("projects.listFailed"); } finally { isLoading.value = false; } }; @@ -58,6 +59,17 @@ const selectDirectory = async () => { try { if (isDesktop) desktopDirectory.value = await pickDesktopDirectory(); else directory.value = await pickProjectDirectory(); } catch (cause) { if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.folderFailed")); } } }; +const migrateProject = async (id: string) => { + try { + const directory = isDesktop ? await pickDesktopDirectory() : await pickProjectDirectory(); + if (!directory) return; + const project = await migrateProjectToDirectory(id, directory); + await refresh(); + emit("open", project.id); + } catch (cause) { + if (!(cause instanceof DOMException && cause.name === "AbortError")) { console.error(cause); window.alert(t("projects.migrationFailed")); } + } +}; const openExisting = async () => { try { const chosen = isDesktop ? await pickDesktopDirectory() : await pickProjectDirectory(); @@ -154,6 +166,7 @@ const confirmRemove = async () => {
+ diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts index d0cd5bb..250204b 100644 --- a/tests/browser-project-file.test.ts +++ b/tests/browser-project-file.test.ts @@ -141,3 +141,24 @@ test("backup copies previous content at most once per interval", async () => { await backupBrowserProject(dir, "new", 1_300_001); assert.deepEqual([...files.values()], ["old", "new"]); }); + +test("project assets reject traversal and preserve copied audio", async () => { + const { writeProjectAudio, readProjectAudio } = await import("../src/services/storage/projectAssets"); + const files = new Map(); + const audio = { + getFileHandle: async (name: string, options?: { create?: boolean }) => { + if (!files.has(name) && !options?.create) throw new DOMException("Missing", "NotFoundError"); + return { + getFile: async () => files.get(name)!, + createWritable: async () => { let file: File; return { write: async (value: File) => { file = value; }, close: async () => { files.set(name, file); }, abort: async () => {} }; } + }; + } + }; + const assets = { getDirectoryHandle: async () => audio }; + const dir = { getDirectoryHandle: async () => assets } as unknown as FileSystemDirectoryHandle; + await assert.rejects(writeProjectAudio(dir, "../x", new File(["audio"], "source.wav")), /INVALID_ASSET_NAME/); + await writeProjectAudio(dir, "safe.audio", new File(["audio"], "source.wav")); + assert.equal(await (await readProjectAudio(dir, "safe.audio")).text(), "audio"); + await assert.rejects(writeProjectAudio(dir, "safe.audio", new File(["new"], "other.wav")), /ASSET_ALREADY_EXISTS/); + assert.equal(await (await readProjectAudio(dir, "safe.audio")).text(), "audio"); +}); From 1ccf73ac95942deaf9198544e4b2e39cac0e840c Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:36:31 +0800 Subject: [PATCH 10/19] Verify storage behavior and remove owned project data --- .github/workflows/ci.yml | 6 +++ src-tauri/src/project_files.rs | 60 +++++++++++++++++++--- src/components/editor/ResourcesPanel.vue | 4 ++ src/i18n/messages/projects.ts | 9 ++-- src/services/storage/browserProjectFile.ts | 16 +++++- tests/browser-project-file.test.ts | 1 + 6 files changed, 84 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 557064b..5c7a092 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,9 @@ jobs: - name: Type check and build renderer run: pnpm build:renderer + - name: Storage tests + run: pnpm test:storage + backend: name: Backend Checks (${{ matrix.os }}) runs-on: ${{ matrix.os }} @@ -88,3 +91,6 @@ jobs: - name: Clippy run: cargo clippy --manifest-path src-tauri/Cargo.toml -- -D warnings + + - name: Native storage tests + run: cargo test --manifest-path src-tauri/Cargo.toml --lib diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index c5d3b8d..5864afb 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -200,6 +200,26 @@ pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Resul if data.get("id").and_then(|value| value.as_str()) != Some(project_id.as_str()) { return Err("PROJECT_ID_MISMATCH".into()); } + if let Some(items) = data.get("audioMeta").and_then(|value| value.as_array()) { + for item in items { + if let Some(name) = item.get("relativePath").and_then(|value| value.as_str()) { + let asset = match asset_path(&directory, name, false) { + Ok(asset) => asset, + Err(error) if error == "ASSET_NOT_FOUND" => continue, + Err(error) => return Err(error), + }; + match fs::symlink_metadata(&asset) { + Ok(meta) if meta.file_type().is_symlink() => return Err("ASSET_SYMLINK_NOT_ALLOWED".into()), + Ok(_) => fs::remove_file(asset).map_err(|e| e.to_string())?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), + Err(error) => return Err(error.to_string()), + } + } + } + } + for name in list_disk_backups(directory.clone())? { + fs::remove_file(directory.join(".danmakucut-backups").join(name)).map_err(|e| e.to_string())?; + } fs::remove_file(path).map_err(|e| e.to_string()) } @@ -270,7 +290,12 @@ pub fn read_disk_backup(directory: PathBuf, name: String) -> Result Result { - if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.') || name.starts_with('.') || name.contains("..") { + if !name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'.') + || name.starts_with('.') + || name.contains("..") + { return Err("INVALID_ASSET_NAME".into()); } let _ = project_path(directory)?; @@ -279,18 +304,29 @@ fn asset_path(directory: &Path, name: &str, create: bool) -> Result) -> Result<(), String> { - if bytes.len() > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + if bytes.len() > 512 * 1024 * 1024 { + return Err("AUDIO_FILE_TOO_LARGE".into()); + } let path = asset_path(&directory, &name, true)?; - let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| e.to_string())?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(|e| e.to_string())?; if let Err(error) = file.write_all(&bytes).and_then(|()| file.sync_all()) { drop(file); let _ = fs::remove_file(path); @@ -302,9 +338,17 @@ pub fn write_project_audio(directory: PathBuf, name: String, bytes: Vec) -> #[tauri::command] pub fn read_project_audio(directory: PathBuf, name: String) -> Result, String> { let path = asset_path(&directory, &name, false)?; - if fs::symlink_metadata(&path).map_err(|e| e.to_string())?.file_type().is_symlink() { return Err("ASSET_SYMLINK_NOT_ALLOWED".into()); } + if fs::symlink_metadata(&path) + .map_err(|e| e.to_string())? + .file_type() + .is_symlink() + { + return Err("ASSET_SYMLINK_NOT_ALLOWED".into()); + } let size = fs::metadata(&path).map_err(|e| e.to_string())?.len(); - if size > 512 * 1024 * 1024 { return Err("AUDIO_FILE_TOO_LARGE".into()); } + if size > 512 * 1024 * 1024 { + return Err("AUDIO_FILE_TOO_LARGE".into()); + } fs::read(path).map_err(|e| e.to_string()) } diff --git a/src/components/editor/ResourcesPanel.vue b/src/components/editor/ResourcesPanel.vue index a4c9359..a313c59 100644 --- a/src/components/editor/ResourcesPanel.vue +++ b/src/components/editor/ResourcesPanel.vue @@ -192,6 +192,10 @@ const handleDrop = (event: DragEvent) => { audioDragDepth.value = 0; isAudioFileDrag.value = false; + if (hasBrowserProjectSession(props.projectId) || hasDesktopProjectSession(props.projectId)) { + window.alert(t("projects.selectAudioInstead")); + return; + } const audioFile = Array.from(event.dataTransfer?.files ?? []).find(isAudioFile); if (audioFile) { void handleAudioUpload(audioFile); diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index 4f1fb64..30595aa 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,9 +1,10 @@ const zhCN = { + selectAudioInstead: "请使用资源栏中的音频按钮选择原始文件,以便项目保留文件引用。", migrate: "迁移到文件夹", migrationFailed: "迁移失败:请确认素材可读取、目标为空且有写入权限。原项目仍被保留,目标文件夹可能存在已创建的文件。", openExisting: "打开本地项目", backups: "历史备份", noBackups: "暂无历史备份。", restoreBackup: "恢复", confirmRestore: "恢复此版本会替换当前项目文件,确认继续?", backupFailed: "备份操作失败,请检查文件权限和项目状态。", offlineMedia: "素材离线", relink: "重新链接", relinkFailed: "重新链接失败,请检查文件和权限。", relinkConfirm: "选择的文件:{name}({size} 字节)。确认用于重新链接?", - removeTitle: "移除项目", removeDescription: "选择处理方式。引用的原始素材和项目文件夹不会被删除。", listOnly: "仅从列表移除", deleteFiles: "同时删除项目文件", confirmFileDelete: "确定永久删除显示的项目文件吗?此操作无法撤销。", storedInternally: "应用内存储", + removeTitle: "移除项目", removeDescription: "选择处理方式。删除磁盘文件会删除项目文件、项目内素材和备份;引用的原始素材和文件夹会保留。", listOnly: "仅从列表移除", deleteFiles: "同时删除项目文件", confirmFileDelete: "确定永久删除显示的项目文件吗?此操作无法撤销。", storedInternally: "应用内存储", selectFolder: "选择空文件夹", emptyFolder: "请选择已有的空文件夹", folderFailed: "无法选择文件夹,请重试。", openFailed: "无法打开项目,请检查文件夹权限和项目文件。", title: "项目", search: "搜索项目...", newProject: "新建项目", createFirst: "创建第一个项目", empty: "还没有项目", emptyDescription: "创建你的第一个项目,开始制作属于你的弹幕作品。", @@ -15,11 +16,12 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + selectAudioInstead: "Use the audio button to select the original file and preserve its reference.", migrate: "Migrate to folder", migrationFailed: "Migration failed. Check media, the empty destination and write access. The old project is retained; the destination may contain created files.", openExisting: "Open local project", backups: "Backups", noBackups: "No backups yet.", restoreBackup: "Restore", confirmRestore: "Replace the current project with this backup?", backupFailed: "Backup operation failed. Check the project and file permissions.", offlineMedia: "Offline media", relink: "Relink", relinkFailed: "Could not relink this file. Check file access and permissions.", relinkConfirm: "Use {name} ({size} bytes) for this media?", - removeTitle: "Remove projects", removeDescription: "Choose what to remove. Original referenced media and folders will be kept.", listOnly: "Remove from list only", deleteFiles: "Also delete project files", confirmFileDelete: "Permanently delete the displayed project files? This cannot be undone.", storedInternally: "App storage", + removeTitle: "Remove projects", removeDescription: "Deleting disk files removes the project file, project assets and backups. Original referenced media and folders will be kept.", listOnly: "Remove from list only", deleteFiles: "Also delete project files", confirmFileDelete: "Permanently delete the displayed project files? This cannot be undone.", storedInternally: "App storage", selectFolder: "Choose empty folder", emptyFolder: "Select an existing empty folder", folderFailed: "Unable to select folder.", openFailed: "Could not open project. Check the folder permission and project file.", title: "Projects", search: "Search projects...", newProject: "New project", createFirst: "Create your first project", empty: "No projects yet", emptyDescription: "Create your first project and start making danmaku.", @@ -31,11 +33,12 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + selectAudioInstead: "音声ボタンから元のファイルを選択してください。", migrate: "フォルダーへ移行", migrationFailed: "移行に失敗しました。素材、空のフォルダー、権限を確認してください。元のプロジェクトは保持されます。", openExisting: "ローカルプロジェクトを開く", backups: "バックアップ", noBackups: "バックアップはありません。", restoreBackup: "復元", confirmRestore: "現在のプロジェクトをこのバックアップで置き換えますか?", backupFailed: "バックアップ操作に失敗しました。", offlineMedia: "オフライン素材", relink: "再リンク", relinkFailed: "再リンクできません。権限とファイルを確認してください。", relinkConfirm: "{name}({size} バイト)を使用しますか?", - removeTitle: "プロジェクトを削除", removeDescription: "削除方法を選択してください。元の素材とフォルダーは削除されません。", listOnly: "一覧からのみ削除", deleteFiles: "プロジェクトファイルも削除", confirmFileDelete: "表示されたファイルを完全に削除しますか?元に戻せません。", storedInternally: "アプリ内ストレージ", + removeTitle: "プロジェクトを削除", removeDescription: "ファイルを削除すると、プロジェクト、保存素材、バックアップが削除されます。元の素材とフォルダーは保持されます。", listOnly: "一覧からのみ削除", deleteFiles: "プロジェクトファイルも削除", confirmFileDelete: "表示されたファイルを完全に削除しますか?元に戻せません。", storedInternally: "アプリ内ストレージ", selectFolder: "空のフォルダーを選択", emptyFolder: "既存の空フォルダーを選択", folderFailed: "フォルダーを選択できません。", openFailed: "プロジェクトを開けません。権限とファイルを確認してください。", title: "プロジェクト", search: "プロジェクトを検索...", newProject: "新規プロジェクト", createFirst: "最初のプロジェクトを作成", empty: "プロジェクトはまだありません", emptyDescription: "プロジェクトを作成して弾幕の制作を始めましょう。", diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index bc389ed..bc4a3f2 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -1,4 +1,4 @@ -import { backupBrowserProject } from "./browserBackups"; +import { backupBrowserProject, listBrowserBackups } from "./browserBackups"; import type { BasProjectData } from "@/types/storage"; import { idbDelete, idbGet, idbSet, STORES } from "./indexedDB"; import { normalizeProjectData } from "./projectSchema"; @@ -135,5 +135,19 @@ export async function deleteBrowserProjectFile(location: BrowserProjectLocation) if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); const opened = await openBrowserProject(location.directory, location.fileName); if (opened.project.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); + const assets = opened.project.audioMeta.filter((item) => item.relativePath).map((item) => item.relativePath!); + for (const name of assets) if (!/^[A-Za-z0-9][A-Za-z0-9.-]*$/.test(name) || name.includes("..")) throw new Error("INVALID_ASSET_NAME"); + if (assets.length) { + const audio = await (await location.directory.getDirectoryHandle("assets")).getDirectoryHandle("audio"); + for (const name of assets) { + try { await audio.removeEntry(name); } + catch (error) { if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; } + } + } + const backups = await listBrowserBackups(location.directory); + if (backups.length) { + const backupDirectory = await location.directory.getDirectoryHandle(".danmakucut-backups"); + for (const name of backups) await backupDirectory.removeEntry(name); + } await location.directory.removeEntry(location.fileName); } diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts index 250204b..b1d007a 100644 --- a/tests/browser-project-file.test.ts +++ b/tests/browser-project-file.test.ts @@ -117,6 +117,7 @@ test("disk removal validates project identity and removes only the project file" const directory = { queryPermission: async () => "granted", getFileHandle: async () => ({ getFile: async () => new File([contents], "project.basproj") }), + getDirectoryHandle: async () => { throw new DOMException("Missing", "NotFoundError"); }, removeEntry: async (name: string) => { removed = name; } } as unknown as FileSystemDirectoryHandle; await assert.rejects(deleteBrowserProjectFile({ projectId: "other", directory, fileName: "project.basproj" }), /PROJECT_ID_MISMATCH/); From 94baaa34c803a2df5796883bdbf94d824b88f4f9 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:38:24 +0800 Subject: [PATCH 11/19] Offer project-owned audio imports --- src-tauri/src/project_files.rs | 7 +++++-- src/components/editor/ResourcesPanel.vue | 13 ++++++++++++- src/i18n/messages/projects.ts | 3 +++ src/services/storage/projectAssets.ts | 3 ++- src/services/storage/projectStorage.ts | 4 ++++ 5 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index 5864afb..78340b4 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -209,7 +209,9 @@ pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Resul Err(error) => return Err(error), }; match fs::symlink_metadata(&asset) { - Ok(meta) if meta.file_type().is_symlink() => return Err("ASSET_SYMLINK_NOT_ALLOWED".into()), + Ok(meta) if meta.file_type().is_symlink() => { + return Err("ASSET_SYMLINK_NOT_ALLOWED".into()) + } Ok(_) => fs::remove_file(asset).map_err(|e| e.to_string())?, Err(error) if error.kind() == std::io::ErrorKind::NotFound => (), Err(error) => return Err(error.to_string()), @@ -218,7 +220,8 @@ pub fn delete_disk_project_file(directory: PathBuf, project_id: String) -> Resul } } for name in list_disk_backups(directory.clone())? { - fs::remove_file(directory.join(".danmakucut-backups").join(name)).map_err(|e| e.to_string())?; + fs::remove_file(directory.join(".danmakucut-backups").join(name)) + .map_err(|e| e.to_string())?; } fs::remove_file(path).map_err(|e| e.to_string()) } diff --git a/src/components/editor/ResourcesPanel.vue b/src/components/editor/ResourcesPanel.vue index a313c59..28fa3f3 100644 --- a/src/components/editor/ResourcesPanel.vue +++ b/src/components/editor/ResourcesPanel.vue @@ -12,7 +12,8 @@ import { pickBrowserAudio } from "@/services/storage/browserMediaFile"; import { getItemName } from "@/utils/resourceUtils"; import { extractAudioCover } from "@/utils/audio/audio-cover"; import { LayoutGrid, List } from "lucide-vue-next"; -import { hasBrowserProjectSession, hasDesktopProjectSession } from "@/services/storage/projectStorage"; +import { hasBrowserProjectSession, hasDesktopProjectSession, projectSessionDirectory } from "@/services/storage/projectStorage"; +import { writeProjectAudio } from "@/services/storage/projectAssets"; import { rememberBrowserMedia } from "@/services/storage/browserMediaFile"; const props = defineProps<{ projectId: string; offlineAudio?: SerializedAudioMetadata[] }>(); @@ -127,6 +128,16 @@ const handleAudioUpload = async (file: File, handle?: FileSystemFileHandle, sour sourcePath, duration, }; + const directory = projectSessionDirectory(props.projectId); + if (directory && window.confirm(t("projects.copyAudio"))) { + try { + const name = `${crypto.randomUUID()}.audio`; + await writeProjectAudio(directory, name, file); + resource.relativePath = name; + resource.sourcePath = undefined; + handle = undefined; + } catch (error) { URL.revokeObjectURL(url); console.error(error); window.alert(t("projects.copyAudioFailed")); return; } + } if (handle) { try { await rememberBrowserMedia(props.projectId, resource.id, handle); } catch (error) { URL.revokeObjectURL(url); console.error("Failed to remember audio", error); return; } diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index 30595aa..529811f 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,4 +1,5 @@ const zhCN = { + copyAudio: "是否将音频复制到项目文件夹?选择取消将引用原文件。", copyAudioFailed: "音频复制失败,未添加素材。", selectAudioInstead: "请使用资源栏中的音频按钮选择原始文件,以便项目保留文件引用。", migrate: "迁移到文件夹", migrationFailed: "迁移失败:请确认素材可读取、目标为空且有写入权限。原项目仍被保留,目标文件夹可能存在已创建的文件。", openExisting: "打开本地项目", @@ -16,6 +17,7 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + copyAudio: "Copy this audio into the project? Choose Cancel to reference the original file.", copyAudioFailed: "Audio copy failed; the resource was not added.", selectAudioInstead: "Use the audio button to select the original file and preserve its reference.", migrate: "Migrate to folder", migrationFailed: "Migration failed. Check media, the empty destination and write access. The old project is retained; the destination may contain created files.", openExisting: "Open local project", @@ -33,6 +35,7 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + copyAudio: "音声をプロジェクトにコピーしますか?キャンセルすると元ファイルを参照します。", copyAudioFailed: "音声をコピーできませんでした。", selectAudioInstead: "音声ボタンから元のファイルを選択してください。", migrate: "フォルダーへ移行", migrationFailed: "移行に失敗しました。素材、空のフォルダー、権限を確認してください。元のプロジェクトは保持されます。", openExisting: "ローカルプロジェクトを開く", diff --git a/src/services/storage/projectAssets.ts b/src/services/storage/projectAssets.ts index 37853b7..7dab34c 100644 --- a/src/services/storage/projectAssets.ts +++ b/src/services/storage/projectAssets.ts @@ -27,5 +27,6 @@ export async function readProjectAudio(directory: string | FileSystemDirectoryHa const bytes = await invoke("read_project_audio", { directory, name }); return new File([new Uint8Array(bytes)], name, { type }); } - return (await (await webAudioDirectory(directory, false)).getFileHandle(name)).getFile(); + const file = await (await (await webAudioDirectory(directory, false)).getFileHandle(name)).getFile(); + return type && !file.type ? new File([file], name, { type, lastModified: file.lastModified }) : file; } diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index 1b38aa0..de37754 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -19,6 +19,10 @@ const projectMediaKey = (projectId: string, mediaId: string) => `${projectId}--$ const browserSessions = new Map(); const desktopSessions = new Map(); +export function projectSessionDirectory(id: string): string | FileSystemDirectoryHandle | null { + return desktopSessions.get(id)?.directory ?? browserSessions.get(id)?.directory ?? null; +} + export function hasDesktopProjectSession(id: string): boolean { return desktopSessions.has(id); } export function hasBrowserProjectSession(id: string): boolean { From c062e7dee0a9b6dac9d439cfde802f69a5cb4a78 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:41:35 +0800 Subject: [PATCH 12/19] Restore corrupt or missing project files from backup --- src-tauri/src/lib.rs | 1 + src-tauri/src/project_files.rs | 41 +++++++++++++++++++--- src/services/storage/browserProjectFile.ts | 15 ++++++++ src/services/storage/projectStorage.ts | 26 +++++++++----- tests/browser-project-file.test.ts | 27 ++++++++++++++ 5 files changed, 97 insertions(+), 13 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a2abd49..a53ae9e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -32,6 +32,7 @@ pub fn run() { .invoke_handler(tauri::generate_handler![ commands::write_text_file, project_files::create_disk_project, + project_files::restore_missing_disk_project, project_files::read_disk_project, project_files::save_disk_project, project_files::read_audio_reference, diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index 78340b4..500e075 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -45,16 +45,39 @@ pub fn create_disk_project(directory: PathBuf, contents: String) -> Result<(), S #[tauri::command] pub fn read_disk_project(directory: PathBuf) -> Result { let path = project_path(&directory)?; - if fs::symlink_metadata(&path) - .map_err(|e| e.to_string())? - .file_type() - .is_symlink() - { + let metadata = fs::symlink_metadata(&path).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + "PROJECT_FILE_NOT_FOUND".to_string() + } else { + e.to_string() + } + })?; + if metadata.file_type().is_symlink() { return Err("PROJECT_SYMLINK_NOT_ALLOWED".into()); } fs::read_to_string(path).map_err(|e| e.to_string()) } +#[tauri::command] +pub fn restore_missing_disk_project(directory: PathBuf, contents: String) -> Result<(), String> { + let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; + let path = project_path(&directory)?; + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(|e| e.to_string())?; + if let Err(error) = file + .write_all(contents.as_bytes()) + .and_then(|()| file.sync_all()) + { + drop(file); + let _ = fs::remove_file(path); + return Err(error.to_string()); + } + Ok(()) +} + fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { let backup_dir = directory.join(".danmakucut-backups"); if backup_dir.exists() { @@ -376,6 +399,14 @@ mod tests { save_disk_project(directory.clone(), "first".into(), "second".into()).unwrap(); assert!(save_disk_project(directory.clone(), "first".into(), "lost".into()).is_err()); assert_eq!(read_disk_project(directory.clone()).unwrap(), "second"); + assert!(restore_missing_disk_project(directory.clone(), "replacement".into()).is_err()); + fs::remove_file(directory.join(PROJECT_FILE)).unwrap(); + assert_eq!( + read_disk_project(directory.clone()).unwrap_err(), + "PROJECT_FILE_NOT_FOUND" + ); + restore_missing_disk_project(directory.clone(), "restored".into()).unwrap(); + assert_eq!(read_disk_project(directory.clone()).unwrap(), "restored"); fs::remove_dir_all(directory).unwrap(); } } diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index bc4a3f2..5cb0799 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -151,3 +151,18 @@ export async function deleteBrowserProjectFile(location: BrowserProjectLocation) } await location.directory.removeEntry(location.fileName); } + +/** Restore a validated backup even when the current project JSON is corrupt. */ +export async function restoreBrowserProjectFile(location: BrowserProjectLocation, backup: BasProjectData): Promise { + validateFileName(location.fileName); + if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); + if (backup.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); + const contents = await (await (await location.directory.getFileHandle(location.fileName)).getFile()).text(); + try { + const raw = JSON.parse(contents) as { id?: unknown }; + if (raw && typeof raw === "object" && typeof raw.id === "string" && raw.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + } + return saveBrowserProject({ directory: location.directory, fileName: location.fileName, project: backup, fingerprint: await digest(contents) }, backup); +} diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index de37754..1d53174 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -9,7 +9,7 @@ import { mediaStorage } from "./mediaStorage"; import { getBrowserMediaHandle, readBrowserMedia } from "./browserMediaFile"; import { normalizeProjectData, PROJECT_VERSION } from "./projectSchema"; import { saveTextFile } from "@/utils/desktop"; -import { createBrowserProject, deleteBrowserProjectFile, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; +import { createBrowserProject, deleteBrowserProjectFile, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, restoreBrowserProjectFile, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; const CURRENT_VERSION = PROJECT_VERSION; const ACTIVE_DRAFT_KEY = "active_draft"; @@ -313,20 +313,30 @@ export async function restoreProjectBackup(id: string, name: string): Promise("read_disk_backup", { directory: desktop, name }); - const backup = normalizeProjectData(JSON.parse(contents)); + const backupContents = await invoke("read_disk_backup", { directory: desktop, name }); + const backup = normalizeProjectData(JSON.parse(backupContents)); if (backup.id !== id) throw new Error("PROJECT_ID_MISMATCH"); - const current = await openDesktopProject(desktop, id); - const saved = await saveDesktopProject(current, backup); + let current: string | null; + try { current = await invoke("read_disk_project", { directory: desktop }); } + catch (error) { if (String(error).includes("PROJECT_FILE_NOT_FOUND")) current = null; else throw error; } + const contents = JSON.stringify(backup, null, 2); + if (current === null) { + await invoke("restore_missing_disk_project", { directory: desktop, contents }); + } else { + try { + const raw: unknown = JSON.parse(current); + if (raw && typeof raw === "object" && "id" in raw && typeof raw.id === "string" && raw.id !== id) throw new Error("PROJECT_ID_MISMATCH"); + } catch (error) { if (!(error instanceof SyntaxError)) throw error; } + await invoke("save_disk_project", { directory: desktop, expected: current, contents }); + } + const saved: DesktopProjectSession = { directory: desktop, contents, project: backup }; desktopSessions.set(id, saved); await idbSet(STORES.PROJECTS, PROJECT_PREFIX + id, saved.project); } else if (browser) { if (!(await ensureDirectoryPermission(browser.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); const backup = normalizeProjectData(JSON.parse(await readBrowserBackup(browser.directory, name))); if (backup.id !== id) throw new Error("PROJECT_ID_MISMATCH"); - const current = await openBrowserProject(browser.directory, browser.fileName); - if (current.project.id !== id) throw new Error("PROJECT_ID_MISMATCH"); - const saved = await saveBrowserProject(current, backup); + const saved = await restoreBrowserProjectFile(browser, backup); browserSessions.set(id, saved); await idbSet(STORES.PROJECTS, PROJECT_PREFIX + id, saved.project); } else throw new Error("BACKUPS_UNAVAILABLE"); diff --git a/tests/browser-project-file.test.ts b/tests/browser-project-file.test.ts index b1d007a..1d1c354 100644 --- a/tests/browser-project-file.test.ts +++ b/tests/browser-project-file.test.ts @@ -163,3 +163,30 @@ test("project assets reject traversal and preserve copied audio", async () => { await assert.rejects(writeProjectAudio(dir, "safe.audio", new File(["new"], "other.wav")), /ASSET_ALREADY_EXISTS/); assert.equal(await (await readProjectAudio(dir, "safe.audio")).text(), "audio"); }); + +test("disk removal deletes only project-owned assets and backups", async () => { + const { deleteBrowserProjectFile } = await import("../src/services/storage/browserProjectFile"); + const deleted: string[] = []; + const projectWithAsset = { ...project, audioMeta: [{ id: "audio-1", name: "sound", relativePath: "owned.audio" }] }; + const backups = { + values: async function* () { yield { kind: "file", name: "backup-1000-aaaaaaaa.basproj" }; yield { kind: "file", name: "unrelated.txt" }; }, + removeEntry: async (name: string) => { deleted.push(`backup/${name}`); } + }; + const audio = { removeEntry: async (name: string) => { deleted.push(`audio/${name}`); } }; + const root = { + queryPermission: async () => "granted", + getFileHandle: async () => ({ getFile: async () => new File([JSON.stringify(projectWithAsset)], "project.basproj") }), + getDirectoryHandle: async (name: string) => name === "assets" ? { getDirectoryHandle: async () => audio } : backups, + removeEntry: async (name: string) => { deleted.push(name); } + } as unknown as FileSystemDirectoryHandle; + await deleteBrowserProjectFile({ projectId: project.id, directory: root, fileName: "project.basproj" }); + assert.deepEqual(deleted, ["audio/owned.audio", "backup/backup-1000-aaaaaaaa.basproj", "project.basproj"]); +}); + +test("a validated backup can recover corrupted project JSON", async () => { + const { restoreBrowserProjectFile } = await import("../src/services/storage/browserProjectFile"); + const fs = directoryFixture("{corrupt"); + const restored = await restoreBrowserProjectFile({ projectId: project.id, directory: fs.directory, fileName: "project.basproj" }, project); + assert.equal(restored.project.id, project.id); + assert.equal(JSON.parse(fs.read()!).name, project.name); +}); From 6cde02ff34cb4f7c08ea2fcf60a2a060a98f39d2 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:43:40 +0800 Subject: [PATCH 13/19] Keep current version before restoring a backup --- src-tauri/src/project_files.rs | 16 +++++++++------- src/services/storage/browserBackups.ts | 4 ++-- src/services/storage/browserProjectFile.ts | 6 +++--- src/services/storage/desktopProjectFile.ts | 2 +- src/services/storage/projectStorage.ts | 2 +- tests/browser-project-file.test.ts | 2 ++ 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src-tauri/src/project_files.rs b/src-tauri/src/project_files.rs index 500e075..9aa87f2 100644 --- a/src-tauri/src/project_files.rs +++ b/src-tauri/src/project_files.rs @@ -78,7 +78,7 @@ pub fn restore_missing_disk_project(directory: PathBuf, contents: String) -> Res Ok(()) } -fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { +fn backup_project(directory: &Path, contents: &str, force: bool) -> Result<(), String> { let backup_dir = directory.join(".danmakucut-backups"); if backup_dir.exists() { if fs::symlink_metadata(&backup_dir) @@ -112,9 +112,10 @@ fn backup_project(directory: &Path, contents: &str) -> Result<(), String> { .duration_since(std::time::UNIX_EPOCH) .map_err(|e| e.to_string())? .as_millis(); - if backups - .first() - .is_some_and(|(time, _)| now.saturating_sub(*time) < 300_000) + if !force + && backups + .first() + .is_some_and(|(time, _)| now.saturating_sub(*time) < 300_000) { return Ok(()); } @@ -143,6 +144,7 @@ pub fn save_disk_project( directory: PathBuf, expected: String, contents: String, + force_backup: Option, ) -> Result<(), String> { let _guard = PROJECT_IO.lock().map_err(|e| e.to_string())?; let path = project_path(&directory)?; @@ -156,7 +158,7 @@ pub fn save_disk_project( if fs::read_to_string(&path).map_err(|e| e.to_string())? != expected { return Err("PROJECT_MODIFIED_EXTERNALLY".into()); } - backup_project(&directory, &expected)?; + backup_project(&directory, &expected, force_backup.unwrap_or(false))?; let temp = directory.join(format!( ".project-{}-{}.tmp", std::process::id(), @@ -396,8 +398,8 @@ mod tests { create_disk_project(directory.clone(), "first".into()).unwrap(); assert!(create_disk_project(directory.clone(), "other".into()).is_err()); assert_eq!(read_disk_project(directory.clone()).unwrap(), "first"); - save_disk_project(directory.clone(), "first".into(), "second".into()).unwrap(); - assert!(save_disk_project(directory.clone(), "first".into(), "lost".into()).is_err()); + save_disk_project(directory.clone(), "first".into(), "second".into(), None).unwrap(); + assert!(save_disk_project(directory.clone(), "first".into(), "lost".into(), None).is_err()); assert_eq!(read_disk_project(directory.clone()).unwrap(), "second"); assert!(restore_missing_disk_project(directory.clone(), "replacement".into()).is_err()); fs::remove_file(directory.join(PROJECT_FILE)).unwrap(); diff --git a/src/services/storage/browserBackups.ts b/src/services/storage/browserBackups.ts index 270adb9..6161270 100644 --- a/src/services/storage/browserBackups.ts +++ b/src/services/storage/browserBackups.ts @@ -5,7 +5,7 @@ const BACKUP_NAME = /^backup-(\d+)-[a-f0-9-]+\.basproj$/; type IterableDirectory = FileSystemDirectoryHandle & { values(): AsyncIterable }; /** Preserve the previous version before replacing it; only manage our own backup names. */ -export async function backupBrowserProject(directory: FileSystemDirectoryHandle, contents: string, now = Date.now()): Promise { +export async function backupBrowserProject(directory: FileSystemDirectoryHandle, contents: string, now = Date.now(), force = false): Promise { const backups = await directory.getDirectoryHandle(".danmakucut-backups", { create: true }); const entries: { name: string; time: number }[] = []; for await (const entry of (backups as IterableDirectory).values()) { @@ -13,7 +13,7 @@ export async function backupBrowserProject(directory: FileSystemDirectoryHandle, if (match) entries.push({ name: entry.name, time: Number(match[1]) }); } entries.sort((a, b) => b.time - a.time || b.name.localeCompare(a.name)); - if (entries[0] && now - entries[0].time < BACKUP_INTERVAL_MS) return; + if (!force && entries[0] && now - entries[0].time < BACKUP_INTERVAL_MS) return; const name = `backup-${now}-${crypto.randomUUID()}.basproj`; const handle = await backups.getFileHandle(name, { create: true }); const writer = await handle.createWritable(); diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index 5cb0799..2c671f0 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -101,7 +101,7 @@ export async function createBrowserProject( } /** 检测外部更改后才写入;浏览器文件系统 API 不提供跨进程原子比较并交换。 */ -export async function saveBrowserProject(opened: BrowserProjectFile, project: BasProjectData): Promise { +export async function saveBrowserProject(opened: BrowserProjectFile, project: BasProjectData, forceBackup = false): Promise { validateFileName(opened.fileName); if (!(await ensureDirectoryPermission(opened.directory))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); const save = async (): Promise => { @@ -111,7 +111,7 @@ export async function saveBrowserProject(opened: BrowserProjectFile, project: Ba const normalized = normalizeProjectData(project); if (normalized.id !== opened.project.id) throw new Error("PROJECT_ID_MISMATCH"); const contents = JSON.stringify(normalized, null, 2); - await backupBrowserProject(opened.directory, current); + await backupBrowserProject(opened.directory, current, Date.now(), forceBackup); if ((await digest(await (await handle.getFile()).text())) !== opened.fingerprint) throw new Error("PROJECT_MODIFIED_EXTERNALLY"); const writable = await handle.createWritable(); try { @@ -164,5 +164,5 @@ export async function restoreBrowserProjectFile(location: BrowserProjectLocation } catch (error) { if (!(error instanceof SyntaxError)) throw error; } - return saveBrowserProject({ directory: location.directory, fileName: location.fileName, project: backup, fingerprint: await digest(contents) }, backup); + return saveBrowserProject({ directory: location.directory, fileName: location.fileName, project: backup, fingerprint: await digest(contents) }, backup, true); } diff --git a/src/services/storage/desktopProjectFile.ts b/src/services/storage/desktopProjectFile.ts index 6296cf2..b1360ac 100644 --- a/src/services/storage/desktopProjectFile.ts +++ b/src/services/storage/desktopProjectFile.ts @@ -29,7 +29,7 @@ export async function openDesktopProject(directory: string, expectedId?: string) export async function saveDesktopProject(session: DesktopProjectSession, project: BasProjectData): Promise { if (project.id !== session.project.id) throw new Error("PROJECT_ID_MISMATCH"); const contents = JSON.stringify(normalizeProjectData(project), null, 2); - await invoke("save_disk_project", { directory: session.directory, expected: session.contents, contents }); + await invoke("save_disk_project", { directory: session.directory, expected: session.contents, contents, forceBackup: false }); return { ...session, contents, project }; } diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index 1d53174..fd23e43 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -327,7 +327,7 @@ export async function restoreProjectBackup(id: string, name: string): Promise { assert.deepEqual([...files.values()], ["old"]); await backupBrowserProject(dir, "new", 1_300_001); assert.deepEqual([...files.values()], ["old", "new"]); + await backupBrowserProject(dir, "before restore", 1_300_002, true); + assert.deepEqual([...files.values()], ["old", "new", "before restore"]); }); test("project assets reject traversal and preserve copied audio", async () => { From 48497f61f52f5ffa0776353ac942c378b27c1b1a Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:45:28 +0800 Subject: [PATCH 14/19] Recover missing browser projects without replacing existing files --- src/services/storage/browserProjectFile.ts | 28 +++++++++++++++++++++- src/services/storage/projectStorage.ts | 5 ++-- tests/browser-project-file.test.ts | 18 ++++++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/services/storage/browserProjectFile.ts b/src/services/storage/browserProjectFile.ts index 2c671f0..1acd7fb 100644 --- a/src/services/storage/browserProjectFile.ts +++ b/src/services/storage/browserProjectFile.ts @@ -157,7 +157,20 @@ export async function restoreBrowserProjectFile(location: BrowserProjectLocation validateFileName(location.fileName); if (!(await ensureDirectoryPermission(location.directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); if (backup.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); - const contents = await (await (await location.directory.getFileHandle(location.fileName)).getFile()).text(); + let contents: string; + try { + contents = await (await (await location.directory.getFileHandle(location.fileName)).getFile()).text(); + } catch (error) { + if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; + // Use a fresh name instead of risking overwrite of a concurrently recreated project file. + const fileName = `recovered-${crypto.randomUUID()}.basproj`; + const handle = await location.directory.getFileHandle(fileName, { create: true }); + const serialized = JSON.stringify(normalizeProjectData(backup), null, 2); + const writer = await handle.createWritable(); + try { await writer.write(serialized); await writer.close(); } + catch (cause) { await writer.abort().catch(() => {}); throw cause; } + return { directory: location.directory, fileName, project: backup, fingerprint: await digest(serialized) }; + } try { const raw = JSON.parse(contents) as { id?: unknown }; if (raw && typeof raw === "object" && typeof raw.id === "string" && raw.id !== location.projectId) throw new Error("PROJECT_ID_MISMATCH"); @@ -166,3 +179,16 @@ export async function restoreBrowserProjectFile(location: BrowserProjectLocation } return saveBrowserProject({ directory: location.directory, fileName: location.fileName, project: backup, fingerprint: await digest(contents) }, backup, true); } + +/** Find the canonical project file, or a single file created by recovery. */ +export async function findBrowserProjectFile(directory: FileSystemDirectoryHandle): Promise { + try { await directory.getFileHandle("project.basproj"); return "project.basproj"; } + catch (error) { if (!(error instanceof DOMException && error.name === "NotFoundError")) throw error; } + const names: string[] = []; + const iterable = directory as FileSystemDirectoryHandle & { values(): AsyncIterable }; + for await (const entry of iterable.values()) { + if (entry.kind === "file" && /^recovered-[a-f0-9-]+\.basproj$/.test(entry.name)) names.push(entry.name); + } + if (names.length !== 1) throw new Error("PROJECT_FILE_NOT_FOUND_OR_AMBIGUOUS"); + return names[0]!; +} diff --git a/src/services/storage/projectStorage.ts b/src/services/storage/projectStorage.ts index fd23e43..fb785a1 100644 --- a/src/services/storage/projectStorage.ts +++ b/src/services/storage/projectStorage.ts @@ -9,7 +9,7 @@ import { mediaStorage } from "./mediaStorage"; import { getBrowserMediaHandle, readBrowserMedia } from "./browserMediaFile"; import { normalizeProjectData, PROJECT_VERSION } from "./projectSchema"; import { saveTextFile } from "@/utils/desktop"; -import { createBrowserProject, deleteBrowserProjectFile, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, restoreBrowserProjectFile, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; +import { createBrowserProject, deleteBrowserProjectFile, findBrowserProjectFile, ensureDirectoryPermission, findBrowserProjectLocation, forgetBrowserProject, openBrowserProject, rememberBrowserProject, restoreBrowserProjectFile, saveBrowserProject, type BrowserProjectFile } from "./browserProjectFile"; const CURRENT_VERSION = PROJECT_VERSION; const ACTIVE_DRAFT_KEY = "active_draft"; @@ -103,7 +103,7 @@ export async function openSelectedProjectDirectory(directory: string | FileSyste return session.project; } if (!(await ensureDirectoryPermission(directory, true))) throw new Error("DIRECTORY_PERMISSION_REQUIRED"); - const session = await openBrowserProject(directory, "project.basproj"); + const session = await openBrowserProject(directory, await findBrowserProjectFile(directory)); if (!session.project.id) throw new Error("INVALID_PROJECT_ID"); await rememberBrowserProject({ projectId: session.project.id, directory, fileName: session.fileName }); await idbSet(STORES.PROJECTS, PROJECT_PREFIX + session.project.id, session.project); @@ -337,6 +337,7 @@ export async function restoreProjectBackup(id: string, name: string): Promise { assert.equal(restored.project.id, project.id); assert.equal(JSON.parse(fs.read()!).name, project.name); }); + +test("missing browser project is recovered under a fresh filename", async () => { + const { restoreBrowserProjectFile, findBrowserProjectFile } = await import("../src/services/storage/browserProjectFile"); + const files = new Map(); + const dir = { + queryPermission: async () => "granted", + values: async function* () { for (const name of files.keys()) yield { kind: "file", name }; }, + getFileHandle: async (name: string, options?: { create?: boolean }) => { + if (!files.has(name) && !options?.create) throw new DOMException("Missing", "NotFoundError"); + if (options?.create) files.set(name, ""); + return { getFile: async () => new File([files.get(name)!], name), createWritable: async () => { let text = ""; return { write: async (value: string) => { text = value; }, close: async () => { files.set(name, text); }, abort: async () => {} }; } }; + } + } as unknown as FileSystemDirectoryHandle; + const restored = await restoreBrowserProjectFile({ projectId: project.id, directory: dir, fileName: "project.basproj" }, project); + assert.match(restored.fileName, /^recovered-/); + assert.equal(await findBrowserProjectFile(dir), restored.fileName); + assert.equal(JSON.parse(files.get(restored.fileName)!).id, project.id); +}); From a831ad5ffb08199311da59f9ef8a6ff08fe03f82 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:46:26 +0800 Subject: [PATCH 15/19] Explain browser storage fallback --- src/i18n/messages/projects.ts | 3 +++ src/views/ProjectsView.vue | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/i18n/messages/projects.ts b/src/i18n/messages/projects.ts index 529811f..1ba48c1 100644 --- a/src/i18n/messages/projects.ts +++ b/src/i18n/messages/projects.ts @@ -1,4 +1,5 @@ const zhCN = { + browserStorageNotice: "当前浏览器不支持选择项目文件夹,项目将保存在浏览器的应用内存储中。", copyAudio: "是否将音频复制到项目文件夹?选择取消将引用原文件。", copyAudioFailed: "音频复制失败,未添加素材。", selectAudioInstead: "请使用资源栏中的音频按钮选择原始文件,以便项目保留文件引用。", migrate: "迁移到文件夹", migrationFailed: "迁移失败:请确认素材可读取、目标为空且有写入权限。原项目仍被保留,目标文件夹可能存在已创建的文件。", @@ -17,6 +18,7 @@ const zhCN = { listFailed: "项目列表加载失败,请刷新重试。", createFailed: "创建项目失败,请重试。", deleteFailed: "删除失败,请重试。" }; const en: typeof zhCN = { + browserStorageNotice: "This browser cannot select a project folder. Projects will be stored in browser app storage.", copyAudio: "Copy this audio into the project? Choose Cancel to reference the original file.", copyAudioFailed: "Audio copy failed; the resource was not added.", selectAudioInstead: "Use the audio button to select the original file and preserve its reference.", migrate: "Migrate to folder", migrationFailed: "Migration failed. Check media, the empty destination and write access. The old project is retained; the destination may contain created files.", @@ -35,6 +37,7 @@ const en: typeof zhCN = { listFailed: "Could not load projects. Refresh and try again.", createFailed: "Could not create project.", deleteFailed: "Could not delete projects." }; const ja: typeof zhCN = { + browserStorageNotice: "このブラウザーではフォルダーを選択できないため、アプリ内に保存されます。", copyAudio: "音声をプロジェクトにコピーしますか?キャンセルすると元ファイルを参照します。", copyAudioFailed: "音声をコピーできませんでした。", selectAudioInstead: "音声ボタンから元のファイルを選択してください。", migrate: "フォルダーへ移行", migrationFailed: "移行に失敗しました。素材、空のフォルダー、権限を確認してください。元のプロジェクトは保持されます。", diff --git a/src/views/ProjectsView.vue b/src/views/ProjectsView.vue index c8e7348..51a1b9b 100644 --- a/src/views/ProjectsView.vue +++ b/src/views/ProjectsView.vue @@ -182,6 +182,6 @@ const confirmRemove = async () => {
- {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}
{{ desktopDirectory || directory?.name || t("projects.emptyFolder") }}
+ {{ t("projects.createTitle") }}{{ t("projects.createDescription") }}

{{ t("projects.browserStorageNotice") }}

{{ desktopDirectory || directory?.name || t("projects.emptyFolder") }}
From f346c24a943355cb992e732338f9de23084dcb00 Mon Sep 17 00:00:00 2001 From: Kvxin <36565256+Kvxin@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:48:42 +0800 Subject: [PATCH 16/19] Flush pending changes before closing desktop windows --- src/components/editor/EditorLayout.vue | 50 +++++++++++++++++++------- src/i18n/messages/projects.ts | 3 ++ 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/src/components/editor/EditorLayout.vue b/src/components/editor/EditorLayout.vue index d937a64..2d22e6c 100644 --- a/src/components/editor/EditorLayout.vue +++ b/src/components/editor/EditorLayout.vue @@ -1,5 +1,6 @@ + + diff --git a/src/components/editor/EditorLayout.vue b/src/components/editor/EditorLayout.vue index 8bf3d83..dd54e5c 100644 --- a/src/components/editor/EditorLayout.vue +++ b/src/components/editor/EditorLayout.vue @@ -2,40 +2,45 @@ import { computed, onBeforeUnmount, onMounted, ref } from "vue"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { useEventListener, useDark } from "@vueuse/core"; -import { - MessageSquareText, - Check, - Cloud, - Loader2, - Settings, - ArrowLeft, -} from "lucide-vue-next"; +import { MessageSquareText, Check, Cloud, Loader2, Settings, ArrowLeft } from "lucide-vue-next"; import ResourcesPanel from "./ResourcesPanel.vue"; import PreviewPanel from "./PreviewPanel.vue"; import PropertiesPanel from "./PropertiesPanel.vue"; import TimelinePanel from "./TimelinePanel.vue"; import WindowControls from "./WindowControls.vue"; +import AssetBundleDialog from "./AssetBundleDialog.vue"; +import { bundleProject } from "@/services/storage/projectBundle"; import { useTitleBarDrag } from "@/composables/useTitleBarDrag"; import { useI18n } from "vue-i18n"; import SettingsView from "@/views/SettingsView.vue"; import { useProjectAutoSave } from "@/composables/useProjectAutoSave"; -import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useTimelineStore } from "@/stores/timeline"; import { useDanmuStore } from "@/stores/danmu"; -import { compileTimelineToBas } from "@/utils/compiler"; +import { compileTimelineToBas, formatBasParseError } from "@/utils/compiler"; +import { parseBasDSL } from "@/utils/bas"; import { isDesktopApp, isMacOS, saveTextFile } from "@/utils/desktop"; const props = defineProps<{ projectId: string }>(); const emit = defineEmits<{ close: [] }>(); -const { t } = useI18n(); +const { t, locale } = useI18n(); const autoSave = useProjectAutoSave(props.projectId); const saveErrorMessage = computed(() => { const message = autoSave.lastSaveError.value.toLowerCase(); if (message.includes("modified_externally")) return t("projects.saveConflict"); - if (message.includes("permission") || message.includes("denied") || message.includes("notallowed")) return t("projects.savePermission"); - if (message.includes("space") || message.includes("quota") || message.includes("disk full")) return t("projects.saveSpace"); + if (message.includes("permission") || message.includes("denied") || message.includes("notallowed")) + return t("projects.savePermission"); + if (message.includes("space") || message.includes("quota") || message.includes("disk full")) + return t("projects.saveSpace"); return t("projects.saveFailed"); }); const isReady = ref(false); @@ -44,27 +49,47 @@ const isLeaving = ref(false); const timelineStore = useTimelineStore(); const danmuStore = useDanmuStore(); const isExportDialogOpen = ref(false); +const isBundleDialogOpen = ref(false); +const collectProject = () => bundleProject(props.projectId, autoSave.getProjectSnapshot); const exportFileName = ref("bas-creater-timeline"); +const exportError = ref(""); const isSettingsOpen = ref(false); -// 桌面端隐藏系统标题栏,由顶部 header 充当可拖动的深色标题栏 +// 桌面端隐藏系统标题栏,由顶部 header 充当可拖动的标题栏 const isDesktop = isDesktopApp(); const hasCustomWindowControls = isDesktop && !isMacOS(); const hasTrafficLights = isDesktop && isMacOS(); const titleBarListeners = isDesktop ? useTitleBarDrag() : {}; const openExportDialog = () => { + exportError.value = ""; isExportDialogOpen.value = true; }; const exportTimelineAsTxt = async () => { - const content = compileTimelineToBas(timelineStore.rootTracks, danmuStore.danmus); - const safeName = exportFileName.value.trim().replace(/[\\/:*?"<>|]/g, "_") || "bas-creater-timeline"; - isExportDialogOpen.value = false; - await saveTextFile({ - fileName: `${safeName}.txt`, - content, - filters: [{ name: "Text", extensions: ["txt"] }] - }); + exportError.value = ""; + try { + const ranges: Array<{ clipId: string; startLine: number; endLine: number }> = []; + const content = compileTimelineToBas(timelineStore.rootTracks, danmuStore.danmus, { + audioResourceIds: autoSave.getProjectSnapshot().audioMeta.map((audio) => audio.id), + onRange: (clipId, startLine, endLine) => ranges.push({ clipId, startLine, endLine }) + }); + if (content.trim()) { + try { + await parseBasDSL(content); + } catch (error) { + throw new Error(formatBasParseError(error, content, ranges)); + } + } + const safeName = exportFileName.value.trim().replace(/[\\/:*?"<>|]/g, "_") || "bas-creater-timeline"; + const saved = await saveTextFile({ + fileName: `${safeName}.txt`, + content, + filters: [{ name: "Text", extensions: ["txt"] }] + }); + if (saved) isExportDialogOpen.value = false; + } catch (error) { + exportError.value = error instanceof Error ? error.message : String(error); + } }; let unlistenClose: (() => void) | undefined; @@ -75,7 +100,8 @@ const flushBeforeLeaving = async (): Promise => { if (!isReady.value && !loadFailed.value) return false; if (!loadFailed.value) { while (autoSave.isDirty.value || autoSave.saveStatus.value === "saving") { - if (!(await autoSave.saveNow())) return window.confirm(`${saveErrorMessage.value}\n\n${t("projects.discardAfterSaveFailed")}`); + if (!(await autoSave.saveNow())) + return window.confirm(`${saveErrorMessage.value}\n\n${t("projects.discardAfterSaveFailed")}`); } } return true; @@ -85,40 +111,67 @@ onMounted(async () => { if (isDesktop) { const appWindow = getCurrentWindow(); try { - const unlisten = await appWindow.onCloseRequested(async (event) => { + const unlisten = await appWindow.onCloseRequested(async event => { if (allowWindowClose) return; event.preventDefault(); if (isLeaving.value) return; isLeaving.value = true; try { - if (await flushBeforeLeaving()) { allowWindowClose = true; await appWindow.close(); } + if (await flushBeforeLeaving()) { + allowWindowClose = true; + await appWindow.close(); + } } catch (error) { allowWindowClose = false; console.error("[Editor] Failed to close window", error); - } finally { isLeaving.value = false; } + } finally { + isLeaving.value = false; + } }); - if (unmounted) unlisten(); else unlistenClose = unlisten; - } catch (error) { console.error("[Editor] Failed to register close handler", error); } + if (unmounted) unlisten(); + else unlistenClose = unlisten; + } catch (error) { + console.error("[Editor] Failed to register close handler", error); + } } isReady.value = await autoSave.restoreProject(); loadFailed.value = !isReady.value; }); -onBeforeUnmount(() => { unmounted = true; unlistenClose?.(); }); +onBeforeUnmount(() => { + unmounted = true; + unlistenClose?.(); + stopResize(); +}); const closeProject = async () => { if (isLeaving.value) return; isLeaving.value = true; - try { if (await flushBeforeLeaving()) emit("close"); } - finally { isLeaving.value = false; } + try { + if (await flushBeforeLeaving()) emit("close"); + } finally { + isLeaving.value = false; + } }; // Theme const isDark = useDark({ initialValue: "dark" }); // Layout State -const leftWidth = ref(450); -const rightWidth = ref(300); -const bottomHeight = ref(250); +const leftWidth = ref(300); +const rightWidth = ref(280); +const bottomHeight = ref(280); +const viewportWidth = ref(window.innerWidth); +const viewportHeight = ref(window.innerHeight); +// 缩小窗口时优先保留预览可用宽度,面板的拖动尺寸仍然独立保存。 +const visibleLeftWidth = computed(() => Math.min(leftWidth.value, Math.max(180, viewportWidth.value - 594))); +const visibleRightWidth = computed(() => + Math.min(rightWidth.value, Math.max(210, viewportWidth.value - visibleLeftWidth.value - 384)) +); +const visibleBottomHeight = computed(() => Math.min(bottomHeight.value, viewportHeight.value * 0.45)); +useEventListener("resize", () => { + viewportWidth.value = window.innerWidth; + viewportHeight.value = window.innerHeight; +}); // Drag State const isDraggingLeft = ref(false); @@ -128,12 +181,15 @@ const isDraggingBottom = ref(false); // Resizing Logic const startResizeLeft = () => { isDraggingLeft.value = true; + document.body.style.cursor = "col-resize"; }; const startResizeRight = () => { isDraggingRight.value = true; + document.body.style.cursor = "col-resize"; }; const startResizeBottom = () => { isDraggingBottom.value = true; + document.body.style.cursor = "row-resize"; }; const stopResize = () => { @@ -147,14 +203,14 @@ useEventListener("mousemove", (e: MouseEvent) => { if (isDraggingLeft.value) { e.preventDefault(); const newWidth = e.clientX; - if (newWidth > 150 && newWidth < 600) { + if (newWidth >= 180 && newWidth <= 600) { leftWidth.value = newWidth; } } if (isDraggingRight.value) { e.preventDefault(); const newWidth = window.innerWidth - e.clientX; - if (newWidth > 150 && newWidth < 600) { + if (newWidth >= 210 && newWidth <= 600) { rightWidth.value = newWidth; } } @@ -178,9 +234,8 @@ useEventListener("mouseleave", stopResize); >
- +
-

+

{{ autoSave.projectName.value }}

- + {{ - autoSave.saveStatus.value === 'saving' - ? t('app.saving') - : autoSave.saveStatus.value === 'error' - ? saveErrorMessage - : autoSave.isDirty.value - ? t('app.unsaved') - : t('app.saved') + autoSave.saveStatus.value === "saving" + ? t("app.saving") + : autoSave.saveStatus.value === "error" + ? saveErrorMessage + : autoSave.isDirty.value + ? t("app.unsaved") + : t("app.saved") }}
- + - + + + -
{{ t("projects.loadFailed") }}
+
+ {{ t("projects.loadFailed") }} +
-
+
-
+
-
- +
+
@@ -289,37 +384,46 @@ useEventListener("mouseleave", stopResize); -
+
-
+
diff --git a/src/components/editor/PreviewPanel.vue b/src/components/editor/PreviewPanel.vue index 5da1e39..4f57c7c 100644 --- a/src/components/editor/PreviewPanel.vue +++ b/src/components/editor/PreviewPanel.vue @@ -13,24 +13,23 @@ import { Plus, RotateCcw, Maximize, - Minimize, + Minimize } from "lucide-vue-next"; -import basService from "@/utils/bas"; +import basService, { parseBasDSL } from "@/utils/bas"; import { useTimelineStore } from "@/stores/timeline"; import { useDanmuStore } from "@/stores/danmu"; import { useAudioStore } from "@/stores/audio"; -import { compileTimelineToBas } from "@/utils/compiler"; +import { basNameForClip, compileTimelineToBas, formatBasParseError } from "@/utils/compiler"; import { getAudioEngine } from "@/utils/audio/audio-engine"; +import { measurePreviewPaint, startPreviewMeasurement } from "@/utils/previewPerformance"; import TransformControls from "./controls/TransformControls.vue"; import type { AnyDanmu } from "@/types/danmu"; import type { TimelineClip } from "@/types/timeline"; -import { flattenTimelineClips } from "@/utils/timelineGroups"; import { BASE_KEYFRAME_ID, clampKeyframeTime, getEffectiveDanmuAtTime, - normalizeKeyframes, - pickKeyframePropertiesForResource, + pickKeyframePropertiesForResource } from "@/utils/keyframes"; const { t } = useI18n(); @@ -50,29 +49,29 @@ const CANVAS_PRESETS = [ aspect: "16:9", previewClass: "h-3 w-5", width: 800, - height: 450, + height: 450 }, { label: "640×360", aspect: "16:9", previewClass: "h-3 w-5", width: 640, - height: 360, + height: 360 }, { label: "1080×1920", aspect: "9:16", previewClass: "h-5 w-3", width: 1080, - height: 1920, + height: 1920 }, { label: "1920×1080", aspect: "16:9", previewClass: "h-3 w-5", width: 1920, - height: 1080, - }, + height: 1080 + } ] as const; type CanvasPreset = (typeof CANVAS_PRESETS)[number]; @@ -96,46 +95,65 @@ const position = ref({ x: 0, y: 0 }); const isDragging = ref(false); const lastMousePos = { x: 0, y: 0 }; const containerRef = ref(null); +const viewportSize = ref({ width: 0, height: 0 }); +let viewportObserver: ResizeObserver | null = null; +let canvasObserver: ResizeObserver | null = null; const danmakuRef = ref(null); const isFullscreen = ref(false); const isZoomMenuOpen = ref(false); const isResolutionMenuOpen = ref(false); const zoomMenuRef = ref(null); +let measuredDefinitions: Array<{ name: string; type: string; attrs: Record }> = []; + +const refreshParentReferenceSizes = () => { + const canvas = danmakuRef.value; + const context = document.createElement("canvas").getContext("2d"); + const sizes: Record = {}; + if (canvas && context && canvas.offsetWidth > 0) { + const names = new Map(timelineStore.tracks.flatMap(track => track.clips) + .filter(clip => clip.kind === "resource").map(clip => [basNameForClip(clip.id), clip.id])); + const numeric = (value: unknown, proportion: number) => { + if (typeof value === "number") return value; + if (!value || typeof value !== "object" || !("value" in value)) return NaN; + const item = value as { value: number; numType?: string }; + return item.numType === "percent" ? item.value * proportion / 100 : item.value; + }; + for (const definition of measuredDefinitions) { + const id = names.get(definition.name); + if (!id || definition.type !== "DefText") continue; + const attrs = definition.attrs; + const fontSize = numeric(attrs.fontSize, canvas.offsetWidth); + let width = numeric(attrs.width, canvas.offsetWidth); + let height = numeric(attrs.height, canvas.offsetHeight); + if (!width || !height) { + context.font = `${numeric(attrs.bold, canvas.offsetWidth) ? "bold " : ""} ${fontSize}px ${attrs.fontFamily}`; + width = context.measureText(String(attrs.content)).width; + height = fontSize; + } + if (Number.isFinite(width) && width > 0 && Number.isFinite(height) && height > 0) sizes[id] = { width, height }; + } + } + timelineStore.parentReferenceSizes = sizes; +}; const resolutionMenuRef = ref(null); // 点击菜单外部时关闭 -onClickOutside(zoomMenuRef, () => { isZoomMenuOpen.value = false; }); -onClickOutside(resolutionMenuRef, () => { isResolutionMenuOpen.value = false; }); +onClickOutside(zoomMenuRef, () => { + isZoomMenuOpen.value = false; +}); +onClickOutside(resolutionMenuRef, () => { + isResolutionMenuOpen.value = false; +}); type CoordinateField = "x" | "y"; -const isUnsetCoordinate = (value: unknown) => - value === undefined || value === null || value === ""; - -const isPercentageCoordinate = (value: unknown) => - typeof value === "string" && value.trim().endsWith("%"); - -const getSelectedCoordinateSource = ( - danmu: AnyDanmu, - clip: TimelineClip, - selectedKeyframeId: string, - field: CoordinateField -) => { - let source = danmu[field]; - - for (const keyframe of normalizeKeyframes(clip.keyframes, clip.duration)) { - const value = keyframe.properties[field]; - if (!isUnsetCoordinate(value)) source = value; - if (keyframe.id === selectedKeyframeId) break; - } +const isUnsetCoordinate = (value: unknown) => value === undefined || value === null || value === ""; - return source; -}; +const isPercentageCoordinate = (value: unknown) => typeof value === "string" && value.trim().endsWith("%"); const usesPercentageCoordinate = ( danmu: AnyDanmu, clip: TimelineClip, - selectedKeyframeId: string | null, effectiveValue: unknown, field: CoordinateField ) => { @@ -143,20 +161,13 @@ const usesPercentageCoordinate = ( return true; } - if (selectedKeyframeId && selectedKeyframeId !== BASE_KEYFRAME_ID) { - const source = getSelectedCoordinateSource(danmu, clip, selectedKeyframeId, field); - return isUnsetCoordinate(source) || isPercentageCoordinate(source); - } - const rawValue = danmu[field]; const localTimeMs = timelineStore.currentTime - clip.startTime; - if (selectedKeyframeId === BASE_KEYFRAME_ID || localTimeMs <= 0) { + if (localTimeMs <= 0) { return isUnsetCoordinate(rawValue) || isPercentageCoordinate(rawValue); } - const hasAnimatedValue = clip.keyframes?.some( - keyframe => !isUnsetCoordinate(keyframe.properties[field]) - ); + const hasAnimatedValue = clip.keyframes?.some(keyframe => !isUnsetCoordinate(keyframe.properties[field])); if (hasAnimatedValue) return false; return isUnsetCoordinate(rawValue) || isPercentageCoordinate(rawValue); @@ -165,46 +176,39 @@ const usesPercentageCoordinate = ( const previewTransformItems = computed(() => { const items: Array<{ clipId: string; + parentClipId?: string; danmu: AnyDanmu; coordinatePercentageMode: { x: boolean; y: boolean }; }> = []; - const previewClips = timelineStore.tracks.flatMap((track) => - track.visible ? track.clips.filter((clip): clip is Extract => clip.kind === "resource") : [] + const previewClips = timelineStore.tracks.flatMap(track => + track.visible + ? track.clips.filter((clip): clip is Extract => clip.kind === "resource") + : [] ); for (const clip of previewClips) { - const danmu = danmuStore.danmus.find((item) => item.id === clip.resourceId); - if (!danmu) continue; - - const selectedKeyframeId = - clip.id === timelineStore.selectedClipId ? timelineStore.selectedKeyframeId : null; - const effectiveDanmu = getEffectiveDanmuAtTime( - danmu, - clip, - timelineStore.currentTime, - selectedKeyframeId - ); + const resource = danmuStore.danmus.find(item => item.id === clip.resourceId); + if (!resource) continue; + const danmu = { ...resource, ...clip.overrides } as AnyDanmu; + + // BAS 先以根画布归一化数值坐标,再在渲染时乘父定义尺寸。 + const reference = timelineStore.canvasReferenceSize ?? undefined; + let effectiveDanmu = danmu; + try { + effectiveDanmu = getEffectiveDanmuAtTime(danmu, clip, timelineStore.currentTime, null, reference); + } catch { + continue; + } items.push({ - clipId: clip.id, - danmu: effectiveDanmu, - coordinatePercentageMode: { - x: usesPercentageCoordinate( - danmu, - clip, - selectedKeyframeId, - effectiveDanmu.x, - "x" - ), - y: usesPercentageCoordinate( - danmu, - clip, - selectedKeyframeId, - effectiveDanmu.y, - "y" - ), - }, + clipId: clip.id, + parentClipId: clip.parentClipId, + danmu: effectiveDanmu, + coordinatePercentageMode: { + x: usesPercentageCoordinate(danmu, clip, effectiveDanmu.x, "x"), + y: usesPercentageCoordinate(danmu, clip, effectiveDanmu.y, "y") + } }); } @@ -215,10 +219,9 @@ const previewTransformItems = computed(() => { /** 自适应缩放:使画布完整适配视口 */ const fitScale = computed(() => { - if (!containerRef.value) return 1; - const rect = containerRef.value.getBoundingClientRect(); - const paddingW = rect.width > 0 ? Math.max(0, rect.width - 32) : 0; - const paddingH = rect.height > 0 ? Math.max(0, rect.height - 32) : 0; + if (!viewportSize.value.width || !viewportSize.value.height) return 1; + const paddingW = Math.max(0, viewportSize.value.width - 32); + const paddingH = Math.max(0, viewportSize.value.height - 32); const sx = paddingW / canvasWidth.value; const sy = paddingH / canvasHeight.value; return Math.min(sx, sy); @@ -228,14 +231,8 @@ const fitScale = computed(() => { const zoomPercent = computed(() => Math.round(scale.value * 100)); /** 当前是否处于 Fit 模式(误差 ≤ 1%) */ -const isAtFit = computed( - () => - Math.abs(scale.value - fitScale.value) / Math.max(0.01, fitScale.value) < - 0.01 -); -const zoomDisplayLabel = computed(() => - isAtFit.value ? t("preview.zoom.fit") : `${zoomPercent.value}%` -); +const isAtFit = computed(() => Math.abs(scale.value - fitScale.value) / Math.max(0.01, fitScale.value) < 0.01); +const zoomDisplayLabel = computed(() => (isAtFit.value ? t("preview.zoom.fit") : `${zoomPercent.value}%`)); /** 自适应:将画布居中缩放至完整适配视口 */ const fitToScreen = () => { @@ -251,10 +248,7 @@ const setViewportPercent = (percent: number) => { }; const nudgeViewportZoom = (direction: 1 | -1) => { - scale.value = Math.max( - MIN_SCALE, - Math.min(MAX_SCALE, scale.value + direction * fitScale.value * 0.25) - ); + scale.value = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale.value + direction * fitScale.value * 0.25)); centerStageView(scale.value); }; @@ -274,28 +268,20 @@ const toggleFullscreen = async () => { /** 当前分辨率是否匹配某个预设 */ const currentPresetLabel = computed(() => { - const match = CANVAS_PRESETS.find( - (p) => p.width === canvasWidth.value && p.height === canvasHeight.value - ); + const match = CANVAS_PRESETS.find(p => p.width === canvasWidth.value && p.height === canvasHeight.value); return match?.label ?? null; }); -const canvasSizeLabel = computed( - () => currentPresetLabel.value ?? `${canvasWidth.value}×${canvasHeight.value}` -); +const canvasSizeLabel = computed(() => currentPresetLabel.value ?? `${canvasWidth.value}×${canvasHeight.value}`); const isCanvasPresetSelected = (preset: CanvasPreset) => canvasWidth.value === preset.width && canvasHeight.value === preset.height; -const isZoomPresetSelected = (preset: number) => - !isAtFit.value && zoomPercent.value === preset; +const isZoomPresetSelected = (preset: number) => !isAtFit.value && zoomPercent.value === preset; const clampCanvasDimension = (value: number | string) => { const numericValue = typeof value === "number" ? value : Number(value); if (!Number.isFinite(numericValue)) return CANVAS_MIN_SIZE; - return Math.min( - CANVAS_MAX_SIZE, - Math.max(CANVAS_MIN_SIZE, Math.round(numericValue)) - ); + return Math.min(CANVAS_MAX_SIZE, Math.max(CANVAS_MIN_SIZE, Math.round(numericValue))); }; /** 设置画布分辨率 */ @@ -337,34 +323,13 @@ const handleTransformSelection = (payload: { danmuStore.select(payload.primaryDanmuId); }; -const findClipByResourceId = (resourceId: string): TimelineClip | null => { - if (timelineStore.selectedClipId) { - for (const track of timelineStore.tracks) { - const selectedClip = track.clips.find( - (clip) => - clip.id === timelineStore.selectedClipId && clip.resourceId === resourceId - ); - if (selectedClip) return selectedClip; - } - } - - for (const track of timelineStore.tracks) { - const clip = track.clips.find((item) => item.resourceId === resourceId); - if (clip) return clip; - } - - return null; -}; - -const handleTransformCommit = ( - updates: Array<{ id: string; changes: Partial }> -) => { +const handleTransformCommit = (updates: Array<{ clipId: string; changes: Partial }>) => { for (const update of updates) { - const resource = danmuStore.danmus.find((item) => item.id === update.id); - const clip = findClipByResourceId(update.id); - const keyframeProperties = resource - ? pickKeyframePropertiesForResource(resource, update.changes) - : {}; + const clip = timelineStore.tracks.flatMap(track => track.clips).find(item => item.id === update.clipId); + if (!clip || clip.kind !== "resource") continue; + const resource = danmuStore.danmus.find(item => item.id === clip.resourceId); + if (!resource) continue; + const keyframeProperties = pickKeyframePropertiesForResource(resource, update.changes); const hasAnimatableChanges = Object.keys(keyframeProperties).length > 0; const animatableKeys = new Set(Object.keys(keyframeProperties)); @@ -372,86 +337,68 @@ const handleTransformCommit = ( Object.entries(update.changes).filter(([key]) => !animatableKeys.has(key)) ) as Partial; if (Object.keys(resourceChanges).length > 0) { - danmuStore.updateDanmu(update.id, resourceChanges); - } - - if (!resource || !clip || !hasAnimatableChanges) { - if (hasAnimatableChanges) { - danmuStore.updateDanmu(update.id, keyframeProperties as Partial); - } - continue; + timelineStore.updateClip(clip.id, { overrides: { ...clip.overrides, ...resourceChanges } }); } + if (!hasAnimatableChanges) continue; - const selectedKeyframeId = - clip.id === timelineStore.selectedClipId ? timelineStore.selectedKeyframeId : null; + const selectedKeyframeId = clip.id === timelineStore.selectedClipId ? timelineStore.selectedKeyframeId : null; const rawLocalTimeMs = timelineStore.currentTime - clip.startTime; const localTimeMs = clampKeyframeTime(rawLocalTimeMs, clip.duration); - if ( - timelineStore.autoKeyframe && - rawLocalTimeMs > 0 && - rawLocalTimeMs <= clip.duration - ) { + if (timelineStore.autoKeyframe && rawLocalTimeMs > 0 && rawLocalTimeMs <= clip.duration) { timelineStore.upsertClipKeyframeAtTime(clip.id, localTimeMs, keyframeProperties); continue; } if (timelineStore.autoKeyframe) { - danmuStore.updateDanmu(update.id, keyframeProperties as Partial); + timelineStore.updateClip(clip.id, { overrides: { ...clip.overrides, ...keyframeProperties } }); continue; } if (selectedKeyframeId && selectedKeyframeId !== BASE_KEYFRAME_ID) { - const storedProperties = clip.keyframes?.find( - (keyframe) => keyframe.id === selectedKeyframeId - )?.properties ?? {}; + const storedProperties = clip.keyframes?.find(keyframe => keyframe.id === selectedKeyframeId)?.properties ?? {}; timelineStore.updateClipKeyframe(clip.id, selectedKeyframeId, { properties: { ...storedProperties, - ...keyframeProperties, - }, + ...keyframeProperties + } }); continue; } if (selectedKeyframeId === BASE_KEYFRAME_ID) { - danmuStore.updateDanmu(update.id, keyframeProperties as Partial); + timelineStore.updateClip(clip.id, { overrides: { ...clip.overrides, ...keyframeProperties } }); continue; } - danmuStore.updateDanmu(update.id, keyframeProperties as Partial); + timelineStore.updateClip(clip.id, { overrides: { ...clip.overrides, ...keyframeProperties } }); } }; -// Helper to find clip by BAS element class name -const findClipByElement = (element: Element): { clip: any; track: any } | null => { - const classList = Array.from(element.classList); - - // BAS generates class like: bas-danmaku-item--obj_clipId - for (const className of classList) { - if (className.startsWith('bas-danmaku-item--obj_')) { - const objName = className.replace('bas-danmaku-item--', ''); - - // Match against all clips - for (const track of timelineStore.tracks) { - for (const clip of track.clips) { - const expectedObjName = `obj_${clip.id.replace(/[^a-zA-Z0-9]/g, '_')}`; - if (objName === expectedObjName) { - return { clip, track }; - } - } - } - } - } - return null; -}; // Computed isPlaying synced with timelineStore const isPlaying = computed(() => timelineStore.isPlaying); const basInitialized = ref(false); let animationFrameId: number | null = null; -const needsRecompile = ref(false); +let publishingClock = false; +let playbackRequestId = 0; +const needsRecompile = ref(true); +const previewErrors = ref([]); +let previewRevision = 0; +let previewFrame: number | null = null; +let previewUnmounted = false; +let previewRequestedAt: number | undefined; +let loadedCode: string | undefined; + +const schedulePreview = () => { + if (previewFrame !== null || previewUnmounted) return; + if (import.meta.env.DEV && previewRequestedAt === undefined) previewRequestedAt = performance.now(); + previewFrame = requestAnimationFrame(() => { + previewFrame = null; + if (!timelineStore.isPlaying) void compileAndLoad(true); + }); +}; // ---- Audio Engine 播放 ---- @@ -460,10 +407,7 @@ const audioEngine = getAudioEngine(); let audioPlaybackRequestId = 0; const isAtTimelineEnd = (timeMs = timelineStore.currentTime) => { - return ( - timelineStore.duration > 0 && - timeMs >= timelineStore.duration - PLAYBACK_END_EPSILON_MS - ); + return timelineStore.duration > 0 && timeMs >= timelineStore.duration - PLAYBACK_END_EPSILON_MS; }; async function startAudioPlayback(startTimeMs: number) { @@ -475,50 +419,39 @@ async function startAudioPlayback(startTimeMs: number) { if (requestId !== audioPlaybackRequestId) return; - const now = audioEngine.getCurrentTime(); - const resourceById = new Map( - audioStore.audioResources.map((resource) => [resource.id, resource]), - ); - - for (const track of timelineStore.tracks) { - if (track.muted || (track.type !== "audio" && !track.visible)) continue; - - for (const clip of track.clips) { - if (clip.kind !== "resource") continue; - const resource = resourceById.get(clip.resourceId); - if (!resource) continue; - - const clipStart = clip.startTime; - const clipEnd = clip.startTime + clip.duration; - if (clipEnd <= startTimeMs) continue; - - // 计算调度参数 - const delaySec = Math.max(0, (clipStart - startTimeMs) / 1000); - const offsetSec = Math.max(0, (startTimeMs - clipStart) / 1000); - const durationSec = (clipEnd - Math.max(startTimeMs, clipStart)) / 1000; - - // 获取当前音量 - const volumeDb = timelineStore.getEffectiveVolume(clip); - const isMuted = timelineStore.isClipMuted(clip); - const effectiveVolumeDb = isMuted ? -60 : volumeDb; - - try { - const buffer = await audioEngine.loadAudioBuffer(resource.url); - if (requestId !== audioPlaybackRequestId) return; - - audioEngine.scheduleClip( - clip.id, - buffer, - now + delaySec, - offsetSec, - durationSec, - effectiveVolumeDb, - ); - } catch (err) { - console.warn(`[PreviewPanel] Failed to load audio for clip ${clip.id}:`, err); + const resourceById = new Map(audioStore.audioResources.map(resource => [resource.id, resource])); + const scheduleTracks = (tracks: typeof timelineStore.tracks, offsetMs = 0) => { + for (const track of tracks) { + if (track.muted || (track.type !== "audio" && !track.visible)) continue; + for (const clip of track.clips) { + const clipStart = offsetMs + clip.startTime; + if (clip.kind === "group") { + scheduleTracks(clip.tracks, clipStart); + continue; + } + const resource = resourceById.get(clip.resourceId); + if (!resource?.url || clipStart + clip.duration <= startTimeMs) continue; + if (timelineStore.isClipMuted(clip)) continue; + const volumeDb = timelineStore.getEffectiveVolume(clip); + void audioEngine.loadAudioBuffer(resource.url).then(buffer => { + if (requestId !== audioPlaybackRequestId || !timelineStore.isPlaying) return; + // Decoding may complete long after playback started. Align to the + // current BAS clock, not the stale time captured before loading. + const currentMs = basService.getCurrentTime(); + const elapsedMs = Math.max(0, currentMs - clipStart); + const remainingMs = clip.duration - elapsedMs; + const offsetSec = ((clip.sourceInMs ?? 0) + elapsedMs) / 1000; + const durationSec = Math.min(remainingMs / 1000, buffer.duration - offsetSec); + if (durationSec <= 0) return; + const when = audioEngine.getCurrentTime() + Math.max(0, clipStart - currentMs) / 1000; + audioEngine.scheduleClip(clip.id, buffer, when, offsetSec, durationSec, volumeDb); + }).catch(err => { + console.warn(`[PreviewPanel] Failed to load audio for clip ${clip.id}:`, err); + }); } } - } + }; + scheduleTracks(timelineStore.tracks); } function stopAudioPlayback() { @@ -538,7 +471,9 @@ const startSyncLoop = () => { return; } + publishingClock = true; timelineStore.setCurrentTime(currentTime); + publishingClock = false; animationFrameId = requestAnimationFrame(loop); } }; @@ -553,37 +488,36 @@ const stopSyncLoop = () => { }; function stopPlayback(seekTimeMs?: number) { + playbackRequestId++; stopAudioPlayback(); basService.pause(); - - if (seekTimeMs !== undefined) { - const clampedTime = Math.max(0, Math.min(seekTimeMs, timelineStore.duration)); - timelineStore.setCurrentTime(clampedTime); - basService.seek(clampedTime / 1000, true); - } - timelineStore.isPlaying = false; stopSyncLoop(); + + const targetTime = Math.max(0, Math.min(seekTimeMs ?? basService.getCurrentTime(), timelineStore.duration)); + seekTimeline(targetTime); } function finishPlaybackAtEnd() { stopPlayback(timelineStore.duration); } -// ... (handleWheel, startDrag, onDrag, stopDrag helpers remain same) - +function seekTimeline(timeMs: number) { + const previousTime = timelineStore.currentTime; + timelineStore.setCurrentTime(timeMs); + if (timelineStore.currentTime === previousTime && basInitialized.value) { + basService.seek(timelineStore.currentTime / 1000, true); + if (timelineStore.isPlaying) void startAudioPlayback(timelineStore.currentTime); + } +} +// ... (handleWheel, startDrag, onDrag, stopDrag helpers remain same) // Computed styles -const containerStyle = computed(() => ({ - backgroundPosition: `${position.value.x}px ${position.value.y}px`, - backgroundSize: `${20 * scale.value}px ${20 * scale.value}px`, - backgroundImage: `radial-gradient(circle, color-mix(in oklab, var(--border) 70%, transparent) 1px, transparent 1px)`, -})); const contentStyle = computed(() => ({ transform: `translate(${position.value.x}px, ${position.value.y}px) scale(${scale.value})`, - transformOrigin: "0 0", + transformOrigin: "0 0" })); const centerStageView = (nextScale = scale.value) => { @@ -610,10 +544,7 @@ const handleWheel = (e: WheelEvent) => { // New Scale const zoomDelta = -e.deltaY * ZOOM_SENSITIVITY; - const newScale = Math.min( - Math.max(MIN_SCALE, scale.value * (1 + zoomDelta)), - MAX_SCALE - ); + const newScale = Math.min(Math.max(MIN_SCALE, scale.value * (1 + zoomDelta)), MAX_SCALE); // Calculate new translation to keep the world point under the mouse position.value.x = mouseX - worldX * newScale; @@ -651,73 +582,146 @@ const stopDrag = () => { document.body.style.cursor = ""; }; -const compileAndLoad = (seekToCurrent = true) => { - if (!basInitialized.value || !basService.isReady()) return false; - const code = compileTimelineToBas(timelineStore.tracks, danmuStore.danmus); - basService.reset(); - basService.addRaw(code); - if (seekToCurrent) { - basService.seek(timelineStore.currentTime / 1000, true); +const compileAndLoad = async (seekToCurrent = true): Promise => { + if (previewFrame !== null) { + cancelAnimationFrame(previewFrame); + previewFrame = null; + } + const revision = ++previewRevision; + const measurement = startPreviewMeasurement(previewRequestedAt ?? performance.now()); + previewRequestedAt = undefined; + if (!basInitialized.value || !basService.isReady() || previewUnmounted) { + previewErrors.value = ["BAS preview is not initialized"]; + return false; + } + const errors: string[] = []; + const ranges: Array<{ clipId: string; startLine: number; endLine: number }> = []; + try { + const compileStart = measurement ? performance.now() : 0; + const code = compileTimelineToBas(timelineStore.tracks, danmuStore.danmus, { + audioResourceIds: audioStore.audioResources.map(resource => resource.id), + onError: message => errors.push(message), + onRange: (clipId, startLine, endLine) => ranges.push({ clipId, startLine, endLine }) + }); + if (measurement) measurement.compileMs = performance.now() - compileStart; + if (errors.length) throw new Error(errors.join("; ")); + if (code === loadedCode) { + refreshParentReferenceSizes(); + if (seekToCurrent) basService.seek(timelineStore.currentTime / 1000, true); + previewErrors.value = []; + needsRecompile.value = false; + if (measurement) measurement.outcome = "unchanged"; + measurePreviewPaint(measurement); + return true; + } + const parseStart = measurement ? performance.now() : 0; + let parsed; + try { + parsed = code.trim() ? await parseBasDSL(code) : { defs: [], sets: [] }; + } catch (error) { + throw new Error(formatBasParseError(error, code, ranges)); + } finally { + if (measurement) measurement.parseMs = performance.now() - parseStart; + } + if (revision !== previewRevision || previewUnmounted) { + if (measurement) measurement.outcome = "superseded"; + return false; + } + const definitions = parsed.defs.filter(definition => definition.type === "DefText").map(definition => ({ + name: definition.name as string, + type: definition.type as string, + attrs: { ...definition.attrs } + })); + const loadStart = measurement ? performance.now() : 0; + loadedCode = undefined; + try { + basService.reset(); + if (code.trim()) await basService.addParsedAsync({ ...parsed, stime: 0 }); + } finally { + if (measurement) measurement.loadMs = performance.now() - loadStart; + } + if (revision !== previewRevision || previewUnmounted) { + if (measurement) measurement.outcome = "superseded"; + return false; + } + measuredDefinitions = definitions; + refreshParentReferenceSizes(); + if (seekToCurrent) basService.seek(timelineStore.currentTime / 1000, true); + loadedCode = code; + previewErrors.value = []; + needsRecompile.value = false; + if (measurement) measurement.outcome = "loaded"; + measurePreviewPaint(measurement); + return true; + } catch (error) { + if (revision !== previewRevision || previewUnmounted) { + if (measurement) measurement.outcome = "superseded"; + return false; + } + if (measurement) measurement.outcome = "error"; + measurePreviewPaint(measurement); + previewErrors.value = [error instanceof Error ? error.message : String(error)]; + needsRecompile.value = true; + return false; } - needsRecompile.value = false; - return true; }; watch( () => timelineStore.activeGroupPath.join("/"), () => { - stopAudioPlayback(); - timelineStore.isPlaying = false; + stopPlayback(timelineStore.currentTime); + ++previewRevision; needsRecompile.value = true; - if (basInitialized.value && basService.isReady()) compileAndLoad(false); + if (basInitialized.value && basService.isReady()) schedulePreview(); } ); // 自动刷新预览(当资源或时间轴改变时) watch( - [() => danmuStore.danmus, () => timelineStore.tracks], + [() => danmuStore.danmus, () => timelineStore.tracks, () => audioStore.audioResources], () => { + ++previewRevision; + timelineStore.parentReferenceSizes = {}; needsRecompile.value = true; - // 只有在暂停状态下才自动刷新,避免播放时频繁重置 - if (!timelineStore.isPlaying && basInitialized.value && basService.isReady()) { - compileAndLoad(true); - } + if (!timelineStore.isPlaying && basInitialized.value && basService.isReady()) schedulePreview(); }, { deep: true } ); watch( - () => - timelineStore.tracks - .map((track) => `${track.id}:${track.type ?? "danmu"}:${track.visible ? 1 : 0}:${track.muted ? 1 : 0}`) - .join("|"), + [() => timelineStore.tracks, () => audioStore.audioResources], () => { - if (timelineStore.isPlaying) { - startAudioPlayback(timelineStore.currentTime); - } - } + if (timelineStore.isPlaying) void startAudioPlayback(timelineStore.currentTime); + }, + { deep: true } +); + +watch( + () => timelineStore.currentTime, + time => { + if (publishingClock || !basInitialized.value) return; + basService.seek(time / 1000, true); + if (timelineStore.isPlaying) void startAudioPlayback(time); + }, + { flush: "sync" } ); watch( () => timelineStore.isPlaying, - (isPlayingNow) => { + isPlayingNow => { // 播放时隐藏舞台溢出内容,暂停时恢复 if (danmakuRef.value) { danmakuRef.value.style.overflow = isPlayingNow ? "hidden" : ""; } - if (!isPlayingNow && needsRecompile.value) { - compileAndLoad(true); - } + if (!isPlayingNow && needsRecompile.value) schedulePreview(); } ); watch( () => basInitialized.value, - (ready) => { - if (ready && !timelineStore.isPlaying && needsRecompile.value) { - compileAndLoad(true); - } + ready => { + if (ready && !timelineStore.isPlaying && needsRecompile.value) schedulePreview(); } ); @@ -726,10 +730,38 @@ const onFullscreenChange = () => { isFullscreen.value = document.fullscreenElement !== null; }; +const onVisibilityChange = () => { + if (document.hidden) stopPlayback(); +}; + // Initial centering and BAS init onMounted(() => { + if (danmakuRef.value) { + const canvas = danmakuRef.value; + const updateCanvasSize = () => { + const width = canvas.offsetWidth; + const height = canvas.offsetHeight; + timelineStore.canvasReferenceSize = width > 0 && height > 0 ? { width, height } : null; + refreshParentReferenceSizes(); + }; + updateCanvasSize(); + canvasObserver = new ResizeObserver(updateCanvasSize); + canvasObserver.observe(canvas); + } if (containerRef.value) { - centerStageView(scale.value); + // 编辑器恢复项目时暂时隐藏;等到容器有实际尺寸后再居中。 + viewportObserver = new ResizeObserver(([entry]) => { + if (!entry || entry.contentRect.width <= 0 || entry.contentRect.height <= 0) return; + const previous = viewportSize.value; + const shouldFit = previous.width === 0 || isAtFit.value; + viewportSize.value = { width: entry.contentRect.width, height: entry.contentRect.height }; + if (shouldFit) fitToScreen(); + else { + position.value.x += (viewportSize.value.width - previous.width) / 2; + position.value.y += (viewportSize.value.height - previous.height) / 2; + } + }); + viewportObserver.observe(containerRef.value); } window.addEventListener("mousemove", onDrag); @@ -737,12 +769,16 @@ onMounted(() => { // 监听全屏状态变化 document.addEventListener("fullscreenchange", onFullscreenChange); + document.addEventListener("visibilitychange", onVisibilityChange); // 初始化 BAS 弹幕服务 nextTick(() => { const danmakuEl = document.getElementById("danmaku"); - if (danmakuEl && !basService.isReady()) { + if (danmakuEl) { try { + // 重新打开项目或热更新后,旧实例仍可能绑定到已移除的画布。 + basService.pause(); + basService.clear(); basService.init({ container: danmakuEl }); // 初始化时不自动播放,或者根据需要 basInitialized.value = true; @@ -755,9 +791,17 @@ onMounted(() => { }); onUnmounted(() => { + previewUnmounted = true; + ++previewRevision; + if (previewFrame !== null) cancelAnimationFrame(previewFrame); + viewportObserver?.disconnect(); + canvasObserver?.disconnect(); + timelineStore.canvasReferenceSize = null; + timelineStore.parentReferenceSizes = {}; window.removeEventListener("mousemove", onDrag); window.removeEventListener("mouseup", stopDrag); document.removeEventListener("fullscreenchange", onFullscreenChange); + document.removeEventListener("visibilitychange", onVisibilityChange); stopPlayback(); }); @@ -768,7 +812,7 @@ const resetView = () => { }; // 播放控制 -const togglePlay = () => { +const togglePlay = async () => { if (!basInitialized.value) return; if (timelineStore.isPlaying) { @@ -780,119 +824,98 @@ const togglePlay = () => { } if (isAtTimelineEnd()) { - timelineStore.setCurrentTime(0); - basService.seek(0); + seekTimeline(0); } + const requestId = ++playbackRequestId; if (needsRecompile.value) { - const compiled = compileAndLoad(true); - if (!compiled) return; + const compiled = await compileAndLoad(true); + if (!compiled || requestId !== playbackRequestId) return; } basService.play(); - startAudioPlayback(timelineStore.currentTime); timelineStore.isPlaying = true; + void startAudioPlayback(timelineStore.currentTime); startSyncLoop(); } }; -const playFromStart = () => { +const playFromStart = async () => { if (!basInitialized.value) return; if (timelineStore.duration <= 0) { stopPlayback(0); return; } + stopPlayback(); + const requestId = ++playbackRequestId; - timelineStore.setCurrentTime(0); + seekTimeline(0); if (needsRecompile.value) { - const compiled = compileAndLoad(true); - if (!compiled) return; - } else { - basService.seek(0); + const compiled = await compileAndLoad(true); + if (!compiled || requestId !== playbackRequestId) return; } - startAudioPlayback(0); - basService.play(); timelineStore.isPlaying = true; + void startAudioPlayback(timelineStore.currentTime); startSyncLoop(); }; const seekToStart = () => { if (!basInitialized.value) return; - timelineStore.setCurrentTime(0); - basService.seek(0); - - if (timelineStore.isPlaying) { - startAudioPlayback(0); - } + seekTimeline(0); }; const skipForward = () => { if (!basInitialized.value) return; - const targetTime = Math.min( - timelineStore.currentTime + SKIP_FORWARD_MS, - timelineStore.duration - ); + const targetTime = Math.min(timelineStore.currentTime + SKIP_FORWARD_MS, timelineStore.duration); if (isAtTimelineEnd(targetTime)) { finishPlaybackAtEnd(); return; } - timelineStore.setCurrentTime(targetTime); - basService.seek(targetTime / 1000); - - if (timelineStore.isPlaying) { - startAudioPlayback(targetTime); - } + seekTimeline(targetTime); };