Skip to content

Spot it. Save it. Free, local-first Chrome extension for images, videos and prompts. Explore 2,000+ curated cases and connect your library to AI Agents via MCP. 提示词导演

完善素材管理闭环并固化回归保护

MigenAI2d6802659f18
diff --git a/.gitignore b/.gitignore
index 0451122..a98d623 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,3 +20,4 @@ store/screenshots/*
!store/screenshots/01-library-1280x800.png
!store/screenshots/02-skills-1280x800.png
!store/screenshots/03-composer-1280x800.png
+store/promo-options/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b7d22ca..1ee15da 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,32 @@
# Changelog
+## 1.18.13
+
+- 项目排序时不再误选文字,案例选择期间排序入口保持原位并以禁用状态表达互斥关系。
+- 快速笔记、视频链接和导入确认的项目组合框会根据弹窗可用空间上下展开,不再被滚动区或底部操作栏裁切。
+- 案例排序与选择入口改为轻量工具条;案例删除入口移到来源信息旁,无来源案例仍在详情正文底部提供回收站操作。
+
+## 1.18.12
+
+- 项目排序改为显式管理态下整行拖动,支持触摸与键盘移动,并在保存失败时恢复原顺序;项目菜单同步缩短并去除省略文案。
+- 批量选择栏只保留一个已选计数,详情删除操作移到内容末尾,单图案例不再显示共享提示词编辑入口,标题保存改为同行操作。
+- 快速笔记、视频链接和导入确认复用同一可创建项目组合框;精选案例排序回归公共主题 Select,清除残留的系统白灰菜单。
+- “补全资料索引”明确说明本地分类、色卡和相似匹配用途,按检查、补全与完成状态显示真实文字,不再使用无反馈的常驻进度条。
+
+## 1.18.11
+
+- 统一 Chrome 134+ 下拉菜单视觉,保留原生键盘、表单与无障碍行为。
+- 详情、外部采集和导入确认统一使用多标签编辑器;界面术语收敛为“添加标签”和“AI 标签”,层级标签默认只显示叶子名称。
+- 批量栏恢复稳定居中,项目排序删除常驻下拉并改为按需上下移动,案例选择与排序完成使用不同图标。
+- 回收站新增真正的“全部恢复”,桌面项目侧栏支持拖动与键盘调整宽度并记住偏好。
+
+## 1.18.10
+
+- 案例详情改用紧凑的多项目下拉,自由标签与回收站操作直接可用,不再被冗余说明和异常复选框布局干扰。
+- 修复全选筛选结果后无法清空的问题;案例与项目排序改为显式进入管理态,完成后立即隐藏移动控件。
+- 侧栏只保留项目与回收站,回收站增加素材封面、完整标题和图标操作。
+- 更新提醒只在真实存在新版本时强调可执行动作,当前已是最新版时保持中性。
+
## 1.18.9
- 分享包把 Chrome Web Store 设为普通用户的主安装入口,并保留源码仓库作为次级入口。
diff --git a/asset-formats.js b/asset-formats.js
new file mode 100644
index 0000000..4dc8e44
--- /dev/null
+++ b/asset-formats.js
@@ -0,0 +1,162 @@
+const GENERIC_MIME_TYPES = new Set([
+ "application/octet-stream",
+ "application/x-unknown"
+]);
+
+const DEFINITIONS = [
+ format("png", "image", "image", ["png"], ["image/png"]),
+ format("jpeg", "image", "image", ["jpg", "jpeg"], ["image/jpeg", "image/jpg"]),
+ format("webp", "image", "image", ["webp"], ["image/webp"]),
+ format("gif", "image", "image", ["gif"], ["image/gif"]),
+ format("avif", "image", "image", ["avif"], ["image/avif"]),
+
+ format("mp4", "video", "video", ["mp4", "m4v"], ["video/mp4", "video/x-m4v"]),
+ format("webm", "video", "video", ["webm"], ["video/webm"]),
+ format("quicktime", "video", "video", ["mov"], ["video/quicktime"]),
+ format("matroska", "video", "video", ["mkv"], ["video/x-matroska", "video/matroska"]),
+ format("avi", "video", "video", ["avi"], ["video/x-msvideo", "video/avi"]),
+
+ format("mp3", "audio", "audio", ["mp3"], ["audio/mpeg", "audio/mp3"]),
+ format("wav", "audio", "audio", ["wav"], ["audio/wav", "audio/x-wav", "audio/wave"]),
+ format("m4a", "audio", "audio", ["m4a"], ["audio/mp4", "audio/x-m4a"]),
+ format("aac", "audio", "audio", ["aac"], ["audio/aac"]),
+ format("flac", "audio", "audio", ["flac"], ["audio/flac", "audio/x-flac"]),
+ format("ogg", "audio", "audio", ["ogg", "oga"], ["audio/ogg", "application/ogg"]),
+ format("opus", "audio", "audio", ["opus"], ["audio/opus", "audio/ogg"]),
+ format("aiff", "audio", "audio", ["aif", "aiff"], ["audio/aiff", "audio/x-aiff"]),
+ format("wma", "audio", "audio", ["wma"], ["audio/x-ms-wma"]),
+
+ format("pdf", "document", "document", ["pdf"], ["application/pdf"]),
+ format("txt", "document", "document", ["txt"], ["text/plain"]),
+ format("markdown", "document", "document", ["md", "markdown"], ["text/markdown", "text/plain"]),
+ format("html", "document", "document", ["html", "htm"], ["text/html"]),
+ format("rtf", "document", "document", ["rtf"], ["application/rtf", "text/rtf", "application/x-rtf"]),
+ format("srt", "document", "subtitle", ["srt"], ["application/x-subrip", "text/srt", "text/plain"], { plainText: true }),
+ format("webvtt", "document", "subtitle", ["vtt"], ["text/vtt", "text/plain"], { plainText: true }),
+ format("ass", "document", "subtitle", ["ass", "ssa"], ["text/x-ssa", "text/plain"], { plainText: true }),
+ format("sbv", "document", "subtitle", ["sbv"], ["text/plain"], { plainText: true }),
+ format("lrc", "document", "subtitle", ["lrc"], ["text/plain", "application/lrc"], { plainText: true }),
+
+ format("photoshop", "attachment", "design-source", ["psd", "psb"], ["image/vnd.adobe.photoshop", "application/x-photoshop"]),
+ format("illustrator", "attachment", "design-source", ["ai"], ["application/postscript", "application/illustrator"]),
+ format("eps", "attachment", "design-source", ["eps"], ["application/postscript", "image/x-eps", "application/eps"]),
+ format("indesign", "attachment", "design-source", ["indd", "idml"], ["application/x-indesign"]),
+ format("procreate", "attachment", "design-source", ["procreate"], ["application/x-procreate"]),
+ format("sketch", "attachment", "design-source", ["sketch"], ["application/x-sketch"]),
+ format("aseprite", "attachment", "design-source", ["ase", "aseprite"], ["application/x-aseprite"]),
+
+ format("after-effects", "attachment", "motion-project", ["aep", "aepx"], ["application/x-after-effects"]),
+ format("premiere", "attachment", "editing-project", ["prproj"], ["application/x-premiere"]),
+ format("audition", "attachment", "audio-project", ["sesx"], ["application/x-audition-session"]),
+ format("animate", "attachment", "motion-project", ["fla", "xfl"], ["application/x-adobe-animate"]),
+ format("lightroom", "attachment", "design-source", ["lrcat"], ["application/x-lightroom-catalog"]),
+ format("davinci-resolve", "attachment", "editing-project", ["drp", "dra"], ["application/x-davinci-resolve"]),
+
+ format("opentype", "attachment", "font", ["otf"], ["font/otf", "application/vnd.ms-opentype", "application/x-font-opentype"]),
+ format("truetype", "attachment", "font", ["ttf"], ["font/ttf", "application/x-font-ttf"]),
+ format("woff", "attachment", "font", ["woff"], ["font/woff", "application/font-woff"]),
+ format("woff2", "attachment", "font", ["woff2"], ["font/woff2"]),
+
+ format("blender", "attachment", "3d-vfx", ["blend"], ["application/x-blender"]),
+ format("cinema4d", "attachment", "3d-vfx", ["c4d"], ["application/x-cinema4d"]),
+ format("3ds-max", "attachment", "3d-vfx", ["max", "3ds"], ["application/x-3dsmax", "application/x-3ds"]),
+ format("maya", "attachment", "3d-vfx", ["ma", "mb"], ["application/x-maya"]),
+ format("houdini", "attachment", "3d-vfx", ["hip", "hiplc", "hipnc"], ["application/x-houdini"]),
+ format("fbx", "attachment", "3d-vfx", ["fbx"], ["application/x-fbx"]),
+ format("wavefront", "attachment", "3d-vfx", ["obj"], ["model/obj", "text/plain"]),
+ format("gltf", "attachment", "3d-vfx", ["gltf"], ["model/gltf+json", "application/json"]),
+ format("glb", "attachment", "3d-vfx", ["glb"], ["model/gltf-binary"]),
+ format("usd", "attachment", "3d-vfx", ["usd", "usda", "usdc", "usdz"], ["model/vnd.usd", "model/vnd.usdz+zip"]),
+ format("alembic", "attachment", "3d-vfx", ["abc"], ["application/x-alembic"]),
+ format("collada", "attachment", "3d-vfx", ["dae"], ["model/vnd.collada+xml"]),
+ format("stl", "attachment", "3d-vfx", ["stl"], ["model/stl", "application/sla"]),
+ format("zbrush", "attachment", "3d-vfx", ["ztl", "zbr"], ["application/x-zbrush"]),
+ format("nuke", "attachment", "3d-vfx", ["nk"], ["application/x-nuke", "text/plain"]),
+ format("substance", "attachment", "3d-vfx", ["sbs", "sbsar", "spp"], ["application/x-substance"])
+];
+
+export const ASSET_FORMAT_REGISTRY = Object.freeze(DEFINITIONS);
+export const SUPPORTED_ASSET_KINDS = Object.freeze(["image", "video", "audio", "document", "attachment"]);
+
+const BY_EXTENSION = new Map();
+const BY_MIME_TYPE = new Map();
+for (const definition of ASSET_FORMAT_REGISTRY) {
+ for (const extension of definition.extensions) {
+ if (BY_EXTENSION.has(extension)) throw new Error(`重复的资产扩展名:${extension}`);
+ BY_EXTENSION.set(extension, definition);
+ }
+ for (const mimeType of definition.mimeTypes) {
+ const values = BY_MIME_TYPE.get(mimeType) ?? [];
+ values.push(definition);
+ BY_MIME_TYPE.set(mimeType, values);
+ }
+}
+
+export function assetFormatForExtension(value) {
+ return BY_EXTENSION.get(normalizeExtension(value)) ?? null;
+}
+
+export function assetFormatsForMimeType(value) {
+ return Object.freeze([...(BY_MIME_TYPE.get(normalizeMimeType(value)) ?? [])]);
+}
+
+export function assetFormatForFile(file = {}) {
+ const extension = fileExtension(file.name);
+ const byExtension = assetFormatForExtension(extension);
+ if (byExtension) return byExtension;
+ const byMime = assetFormatsForMimeType(file.type);
+ return byMime.length === 1 ? byMime[0] : null;
+}
+
+export function assetKindFromFileMetadata(file = {}) {
+ const definition = assetFormatForFile(file);
+ return definition && isReportedMimeCompatible(definition, file.type) ? definition.kind : "";
+}
+
+export function isReportedMimeCompatible(definition, value) {
+ const mimeType = normalizeMimeType(value);
+ return !mimeType || GENERIC_MIME_TYPES.has(mimeType) || Boolean(definition?.mimeTypes?.includes(mimeType));
+}
+
+export function canonicalMimeType(definition, reportedMimeType = "") {
+ const mimeType = normalizeMimeType(reportedMimeType);
+ return mimeType && !GENERIC_MIME_TYPES.has(mimeType) ? mimeType : definition?.mimeTypes?.[0] ?? "";
+}
+
+export function assetFileAccept(options = {}) {
+ const kinds = new Set(Array.isArray(options.kinds) && options.kinds.length ? options.kinds : SUPPORTED_ASSET_KINDS);
+ return ASSET_FORMAT_REGISTRY
+ .filter((definition) => kinds.has(definition.kind))
+ .flatMap((definition) => definition.extensions.map((extension) => `.${extension}`))
+ .join(",");
+}
+
+export function extensionsForAssetKind(kind) {
+ return Object.freeze(ASSET_FORMAT_REGISTRY
+ .filter((definition) => definition.kind === kind)
+ .flatMap((definition) => definition.extensions));
+}
+
+export function fileExtension(value) {
+ return String(value ?? "").trim().toLocaleLowerCase("en-US").match(/\.([a-z0-9]+)$/u)?.[1] ?? "";
+}
+
+function normalizeExtension(value) {
+ return String(value ?? "").trim().toLocaleLowerCase("en-US").replace(/^\./u, "");
+}
+
+function normalizeMimeType(value) {
+ return String(value ?? "").split(";", 1)[0].trim().toLocaleLowerCase("en-US");
+}
+
+function format(id, kind, category, extensions, mimeTypes, options = {}) {
+ return Object.freeze({
+ id,
+ kind,
+ category,
+ extensions: Object.freeze(extensions),
+ mimeTypes: Object.freeze(mimeTypes),
+ preview: kind === "attachment" ? "inert" : options.plainText ? "text" : "native",
+ plainText: options.plainText === true
+ });
+}
diff --git a/assets/ui-icons.svg b/assets/ui-icons.svg
index 4d0767f..73facf2 100644
--- a/assets/ui-icons.svg
+++ b/assets/ui-icons.svg
@@ -1,9 +1,17 @@
<!-- Generated from lucide-static. ISC license: THIRD_PARTY_NOTICES.md -->
<svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
+ <symbol id="icon-arrow-down" viewBox="0 0 24 24">
+ <path d="M12 5v14" />
+ <path d="m19 12-7 7-7-7" />
+ </symbol>
<symbol id="icon-arrow-left" viewBox="0 0 24 24">
<path d="m12 19-7-7 7-7" />
<path d="M19 12H5" />
</symbol>
+ <symbol id="icon-arrow-up" viewBox="0 0 24 24">
+ <path d="m5 12 7-7 7 7" />
+ <path d="M12 19V5" />
+ </symbol>
<symbol id="icon-check" viewBox="0 0 24 24">
<path d="M20 6 9 17l-5-5" />
</symbol>
@@ -16,6 +24,10 @@
<symbol id="icon-chevron-right" viewBox="0 0 24 24">
<path d="m9 18 6-6-6-6" />
</symbol>
+ <symbol id="icon-circle-check-big" viewBox="0 0 24 24">
+ <path d="M21.801 10A10 10 0 1 1 17 3.335" />
+ <path d="m9 11 3 3L22 4" />
+ </symbol>
<symbol id="icon-copy" viewBox="0 0 24 24">
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
@@ -56,6 +68,13 @@
<path d="M8 8v12" />
<path d="M4 4v16" />
</symbol>
+ <symbol id="icon-list-checks" viewBox="0 0 24 24">
+ <path d="M13 5h8" />
+ <path d="M13 12h8" />
+ <path d="M13 19h8" />
+ <path d="m3 17 2 2 4-4" />
+ <path d="m3 7 2 2 4-4" />
+ </symbol>
<symbol id="icon-maximize-2" viewBox="0 0 24 24">
<path d="M15 3h6v6" />
<path d="m21 3-7 7" />
@@ -128,6 +147,10 @@
<path d="M22 4h-4" />
<circle cx="4" cy="20" r="2" />
</symbol>
+ <symbol id="icon-square-check-big" viewBox="0 0 24 24">
+ <path d="M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344" />
+ <path d="m9 11 3 3L22 4" />
+ </symbol>
<symbol id="icon-square" viewBox="0 0 24 24">
<rect width="18" height="18" x="3" y="3" rx="2" />
</symbol>
diff --git a/background.js b/background.js
index 48a9aca..22c991d 100644
--- a/background.js
+++ b/background.js
@@ -110,14 +110,20 @@ import {
saveDerivedMetadata,
saveMediaBlob
} from "./media-store.js";
-import { findExactMediaDuplicate, sha256Blob } from "./local-media.js";
+import { deleteLocalAssetHandle } from "./local-asset-store.js";
+import {
+ LOCAL_ASSET_REFERENCE_RECORD_TYPE,
+ findExactMediaDuplicate,
+ sha256Blob
+} from "./local-media.js";
import { tempReferenceAssetIds, unreadReferenceImageAssets } from "./temp-references.js";
import {
addStagedAsset,
collectRetainedLocalAssetIds,
normalizeImportStagingState,
removeStagedAsset,
- stagedAssetById
+ stagedAssetById,
+ stagedAssetMediaRecord
} from "./import-staging.js";
import {
cancelImportJob,
@@ -142,10 +148,10 @@ import {
addTimeNote,
entryMediaAssets,
normalizeEntryMedia,
- removeEntryMedia,
removeTimeNote,
setEntryMediaPrompt,
- setPrimaryMedia
+ setPrimaryMedia,
+ updateLocalAssetReferenceMetadata
} from "./media.js";
import {
cancelLibraryMaintenance,
@@ -173,14 +179,25 @@ import { mergeCuratedLibraryPackage } from "./curated-import.js";
import { prepareCuratedSubmissionState } from "./curated-submission.js";
import {
createCollection,
- deleteCollection,
normalizeOrganizerState,
- planCollectionAndEntriesDeletion,
removeEntriesFromOrganizer,
+ reorderCollections,
replaceCollectionEntries,
renameCollection,
+ setEntriesCollection,
setCollectionVisibility
} from "./organizer.js";
+import {
+ emptyTrash,
+ listTrashItems,
+ moveCollectionWithEntriesToTrash,
+ moveCollectionsToTrash,
+ moveEntriesToTrash,
+ moveMediaToTrash,
+ normalizeTrashState,
+ restoreTrashItems,
+ takeTrashItems
+} from "./trash.js";
import { normalizeUiPreferences, resolveLocale } from "./preferences.js";
import { CHROME_WEB_STORE_URL } from "./product-links.js";
import { PALETTE_VERSION } from "./palette.js";
@@ -277,7 +294,6 @@ import {
addEntryVisual,
normalizeEntryVisuals,
primaryVisual,
- removeEntryVisual,
setPrimaryVisual,
updateEntryVisual
} from "./visuals.js";
@@ -327,10 +343,15 @@ import {
getSyncDirectoryHandle,
saveSyncCryptoKey
} from "./sync-store.js";
+import {
+ createExtensionUpdateLifecycle,
+ EXTENSION_UPDATE_STATUS_CHANGED
+} from "./extension-update.js";
const STORAGE_KEYS = Object.freeze({
schemaVersion: "schemaVersion",
entries: "entries",
+ trashState: "trashState",
compoundCases: "compoundCases",
settings: "settings",
taxonomy: "taxonomy",
@@ -368,6 +389,7 @@ const STORAGE_KEYS = Object.freeze({
});
const SYNCED_STORAGE_KEYS = new Set([
STORAGE_KEYS.entries,
+ STORAGE_KEYS.trashState,
STORAGE_KEYS.compoundCases,
STORAGE_KEYS.settings,
STORAGE_KEYS.taxonomy,
@@ -388,6 +410,15 @@ let automaticSyncScheduled = false;
let creatingOffscreenDocument = null;
let visionAnalysisInFlight = false;
const aiProviderModule = createAiProviderModule();
+const extensionUpdateLifecycle = createExtensionUpdateLifecycle({
+ runtime: chrome.runtime,
+ storage: chrome.storage.local,
+ fetchFn: (...args) => fetch(...args),
+ notify: (status) => chrome.runtime.sendMessage({
+ type: EXTENSION_UPDATE_STATUS_CHANGED,
+ status
+ }).catch(() => undefined)
+});
const VIDEO_ANALYSIS_ADAPTERS = Object.freeze({
gemini: analyzeVideoWithGemini,
chat_completions: analyzeVideoWithChatCompletions,
@@ -416,7 +447,8 @@ const captureRuntime = createCaptureWorkspace({
resolveSourceContext: resolveCaptureSourceContext
});
-chrome.runtime.onInstalled.addListener(async () => {
+chrome.runtime.onInstalled.addListener(async (details) => {
+ await extensionUpdateLifecycle.handleInstalled(details);
await restrictLocalStorageAccess();
await syncContextMenus();
await chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false });
@@ -426,6 +458,16 @@ chrome.runtime.onInstalled.addListener(async () => {
await migrateLegacyScreenshots(state.entries);
});
+chrome.runtime.onUpdateAvailable.addListener((details) => {
+ extensionUpdateLifecycle.handleUpdateAvailable(details)
+ .catch((error) => console.error("PromptDirector update availability handling failed", error));
+});
+
+chrome.runtime.onStartup.addListener(() => {
+ extensionUpdateLifecycle.handleStartup()
+ .catch((error) => console.error("PromptDirector development update check failed", error));
+});
+
restrictLocalStorageAccess().catch((error) => console.error("PromptDirector storage access restriction failed", error));
syncContextMenus().catch((error) => console.error("PromptDirector context menu sync failed", error));
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: false }).catch((error) => console.error("PromptDirector side panel setup failed", error));
@@ -507,6 +549,18 @@ async function handleMessage(message, interaction = {}) {
return enqueueCapture(async () => captureWorkspace());
case "GET_DATA_SAFETY_STATUS":
return enqueue(async () => dataSafetyStatus(await readState()));
+ case "GET_EXTENSION_UPDATE_STATUS":
+ return extensionUpdateLifecycle.getStatus()
+ .then((status) => ({ ok: true, status }));
+ case "CHECK_EXTENSION_UPDATE":
+ return extensionUpdateLifecycle.check()
+ .then((status) => ({
+ ok: status.checkStatus !== "error",
+ status,
+ message: status.lastError
+ }));
+ case "APPLY_EXTENSION_UPDATE":
+ return extensionUpdateLifecycle.apply();
case "CONNECT_SYNC_FOLDER":
return enqueue(async () => connectSyncFolder(message.password));
case "UNLOCK_SYNC_VAULT":
@@ -573,7 +627,10 @@ async function handleMessage(message, interaction = {}) {
case "CANCEL_CAPTURE_DRAFT":
return enqueueCapture(async () => captureRuntime.dispatch("cancel"));
case "COMMIT_CAPTURE_DRAFT":
- return enqueueCapture(async () => enqueue(async () => commitCaptureDraft(message.duplicateAction)));
+ return enqueueCapture(async () => enqueue(async () => commitCaptureDraft(message.duplicateAction, {
+ collectionId: message.collectionId,
+ newCollectionName: message.newCollectionName
+ })));
case "START_CAPTURE_FOR_CASE":
return enqueueCapture(async () => startCaptureForCase(message.caseId, message.partEntryId));
case "CREATE_COMPOUND_CASE":
@@ -597,9 +654,9 @@ async function handleMessage(message, interaction = {}) {
case "CREATE_MEDIA_CASE":
return enqueue(async () => createMediaCase(message.asset, message.posterAsset, message.title, message.text));
case "CREATE_MEDIA_REFERENCE":
- return enqueue(async () => createMediaReferenceCase(message.asset, message.posterAsset, message.title));
+ return enqueue(async () => createMediaReferenceCase(message.asset, message.posterAsset, message.title, message));
case "CREATE_QUICK_NOTE":
- return enqueue(async () => createQuickNote(message.title, message.text));
+ return enqueue(async () => createQuickNote(message.title, message.text, message));
case "ADD_TIME_NOTE":
return enqueue(async () => addEntryTimeNote(message.entryId, message.note));
case "ADD_VIDEO_KEYFRAME":
@@ -748,14 +805,32 @@ async function handleMessage(message, interaction = {}) {
return enqueue(async () => applyEntryMediaPromptSuggestions(message));
case "UPDATE_ENTRY_TITLE":
return enqueue(async () => updateCaseTitle(message));
+ case "UPDATE_ENTRY_CUSTOM_LABELS":
+ return enqueue(async () => updateEntryCustomLabels(message));
+ case "UPDATE_LOCAL_ASSET_REFERENCE":
+ return enqueue(async () => updateLocalAssetReferenceAction(message));
+ case "BATCH_ADD_CUSTOM_LABELS":
+ return enqueue(async () => batchAddCustomLabels(message));
+ case "BATCH_SET_PROJECT":
+ return enqueue(async () => batchSetProject(message));
case "UNDO_VISION_ANALYSIS":
return enqueue(async () => undoEntryVisionAnalysis(message.entryId));
case "UNDO_LAST":
return enqueue(async () => undoLastSave());
case "DELETE_ENTRY":
return enqueue(async () => deleteEntry(message.entryId));
+ case "BATCH_MOVE_TO_TRASH":
+ return enqueue(async () => moveEntryBatchToTrash(message.entryIds));
case "DELETE_COLLECTION_WITH_ENTRIES":
return enqueue(async () => deleteCollectionWithEntries(message));
+ case "GET_TRASH_ITEMS":
+ return enqueue(async () => getTrashItems(message));
+ case "RESTORE_TRASH_ITEMS":
+ return enqueue(async () => restoreSelectedTrashItems(message));
+ case "PERMANENT_DELETE_TRASH_ITEMS":
+ return enqueue(async () => permanentlyDeleteTrashItems(message));
+ case "EMPTY_TRASH":
+ return enqueue(async () => emptyTrashAction());
case "CONFIRM_CLASSIFICATION":
return enqueue(async () => updateClassification(message));
case "RENAME_CONTENT_TYPE":
@@ -777,6 +852,7 @@ async function handleMessage(message, interaction = {}) {
case "CREATE_COLLECTION":
case "RENAME_COLLECTION":
case "DELETE_COLLECTION":
+ case "REORDER_COLLECTIONS":
case "REPLACE_COLLECTION_ENTRIES":
case "SET_COLLECTION_VISIBILITY":
return enqueue(async () => updateOrganizer(message));
@@ -872,6 +948,7 @@ async function captureWorkspace() {
STORAGE_KEYS.compoundCases,
STORAGE_KEYS.taxonomy,
STORAGE_KEYS.classificationRules,
+ STORAGE_KEYS.organizerState,
STORAGE_KEYS.activeCreativeResult,
STORAGE_KEYS.composerSessions
]);
@@ -879,6 +956,7 @@ async function captureWorkspace() {
entries: Array.isArray(stored[STORAGE_KEYS.entries]) ? stored[STORAGE_KEYS.entries] : [],
taxonomy: normalizeTaxonomy(stored[STORAGE_KEYS.taxonomy]),
classificationRules: Array.isArray(stored[STORAGE_KEYS.classificationRules]) ? stored[STORAGE_KEYS.classificationRules] : [],
+ organizerState: normalizeOrganizerState(stored[STORAGE_KEYS.organizerState]),
activeCreativeResult: normalizeActiveCreativeResult(stored[STORAGE_KEYS.activeCreativeResult]),
composerSessions: normalizeComposerSessions(stored[STORAGE_KEYS.composerSessions])
};
@@ -906,6 +984,7 @@ async function captureWorkspace() {
targetEntry,
suggestedContentTypeId: suggested?.pathIds?.[0] || "",
contentTypes: state.taxonomy.nodes.map((item) => ({ id: item.id, name: item.name })),
+ collections: state.organizerState.collections.map((item) => ({ id: item.id, name: item.name })),
partContentTypes,
activeCreativeResult: state.activeCreativeResult,
activeCreativePrompt: activeCreativePromptSummary(state.activeCreativeResult, state.composerSessions),
@@ -1876,25 +1955,18 @@ async function splitCompoundCaseAction(compoundCaseId) {
async function setEntryPrimaryVisual(entryId, visualId) {
const state = await readState();
const current = findEntry(state, entryId);
- const updated = setPrimaryVisual(current, visualId);
+ const next = setPrimaryVisual(current, visualId);
+ const updated = next.primaryVisualId === current.primaryVisualId ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: "主图已更新", entry: updated };
}
async function deleteEntryVisual(entryId, visualId) {
- const state = await readState();
- const current = normalizeEntryVisuals(findEntry(state, entryId));
- const visual = current.visuals.find((item) => item.id === String(visualId ?? ""));
- if (!visual) return { ok: false, message: "没有找到这张截图" };
- let updated = removeEntryVisual(current, visual.id);
- updated.facetAssignments = (updated.facetAssignments ?? []).filter((item) =>
- !(item.source === "vision_model" && (item.visualId === visual.id || (!item.visualId && visual.visionAnalysis)))
- );
- const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
- await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
- await deleteScreenshotBlob(visual.id).catch(() => undefined);
- return { ok: true, message: "这张截图已删除,案例文字和其他截图保持不变", entry: updated };
+ return moveEntryMediaToTrash(entryId, visualId, {
+ missingMessage: "没有找到这张截图",
+ successMessage: "截图已移入回收站,案例文字和其他截图保持不变"
+ });
}
async function addUploadedVisual(entryId, visualValue) {
@@ -1902,14 +1974,14 @@ async function addUploadedVisual(entryId, visualValue) {
const current = findEntry(state, entryId);
const visualId = String(visualValue?.id ?? "").trim();
if (!visualId || !await getScreenshotBlob(visualId)) throw new Error("没有读取到待添加的图片");
- const updated = addEntryVisual(current, {
+ const updated = touchEntry(addEntryVisual(current, {
...visualValue,
id: visualId,
sourceUrl: current.url,
sourceTitle: current.title,
capturedAt: new Date().toISOString(),
reviewStatus: "verified"
- });
+ }));
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
await queueAutomaticVisionAnalysis([updated.id]);
@@ -1919,26 +1991,64 @@ async function addUploadedVisual(entryId, visualValue) {
async function setEntryPrimaryMedia(entryId, assetId) {
const state = await readState();
const current = findEntry(state, entryId);
- const updated = setPrimaryMedia(current, assetId);
+ const next = setPrimaryMedia(current, assetId);
+ const updated = next.primaryMediaId === current.primaryMediaId ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: "主要媒体已更新", entry: updated };
}
async function deleteEntryMedia(entryId, assetId) {
+ return moveEntryMediaToTrash(entryId, assetId, {
+ missingMessage: "没有找到这个媒体",
+ successMessage: "媒体已移入回收站,案例文字和其他资料保持不变"
+ });
+}
+
+async function moveEntryMediaToTrash(entryId, assetId, messages) {
const state = await readState();
const current = normalizeEntryMedia(findEntry(state, entryId));
const asset = current.mediaAssets.find((item) => item.id === String(assetId ?? ""));
- if (!asset) return { ok: false, message: "没有找到这个媒体" };
- const updated = removeEntryMedia(current, asset.id);
- const removedAssets = current.mediaAssets.filter((item) => !updated.mediaAssets.some((next) => next.id === item.id));
- updated.facetAssignments = (updated.facetAssignments ?? []).filter((item) =>
- !(item.source === "vision_model" && item.visualId === asset.id)
- );
- const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
+ if (!asset) return { ok: false, message: messages.missingMessage };
+ const moved = moveMediaToTrash({
+ entries: state.entries,
+ trashState: state.trashState
+ }, current.id, [asset.id]);
+ const entries = touchEntries(moved.entries, [current.id]);
+ const updated = entries.find((entry) => entry.id === current.id);
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: entries,
+ [STORAGE_KEYS.trashState]: moved.trashState
+ });
+ return {
+ ok: true,
+ message: messages.successMessage,
+ movedItemIds: moved.movedItemIds,
+ entry: updated,
+ trashState: moved.trashState
+ };
+}
+
+async function updateLocalAssetReferenceAction(message = {}) {
+ const state = await readState();
+ const current = findEntry(state, String(message.entryId ?? "").trim());
+ const updated = updateLocalAssetReferenceMetadata(current, message.assetId, {
+ sourceTitle: message.sourceTitle,
+ relativePath: message.relativePath,
+ sourceFormat: message.sourceFormat,
+ mimeType: message.mimeType,
+ byteSize: message.byteSize,
+ sourceLastModified: message.sourceLastModified
+ });
+ const entry = touchEntry(updated.entry);
+ const entries = state.entries.map((item) => item.id === entry.id ? entry : item);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
- await Promise.allSettled(removedAssets.filter((item) => item.storageMode === "managed").map((item) => deleteMediaBlob(item.id)));
- return { ok: true, message: "媒体已删除,案例文字和其他资料保持不变", entry: updated };
+ return {
+ ok: true,
+ message: "本机源文件链接已更新",
+ entry,
+ asset: entry.mediaAssets.find((item) => item.id === updated.asset.id)
+ };
}
async function addUploadedMedia(entryId, assetValue, posterValue = null) {
@@ -1962,6 +2072,7 @@ async function addUploadedMedia(entryId, assetValue, posterValue = null) {
if (!await getMediaBlob(posterValue.id)) throw new Error("没有读取到视频封面");
updated = addEntryMedia(updated, { ...posterValue, usage: "poster", derivedFromAssetId: assetId, storageMode: "managed" });
}
+ updated = touchEntry(updated);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
if (assetValue?.kind === "image") await queueAutomaticVisionAnalysis([updated.id]);
@@ -2000,7 +2111,7 @@ async function createMediaCase(assetValue, posterValue, titleValue, textValue =
return { ok: true, message: "资料已保存", entry };
}
-async function createMediaReferenceCase(assetValue, posterValue, titleValue) {
+async function createMediaReferenceCase(assetValue, posterValue, titleValue, organization = {}) {
const state = await readState();
const sourceUrl = String(assetValue?.reference?.url || assetValue?.sourceUrl || "").trim();
const base = buildEntry({ text: "", title: titleValue, url: sourceUrl, allowEmptyText: true });
@@ -2015,24 +2126,31 @@ async function createMediaReferenceCase(assetValue, posterValue, titleValue) {
mediaAssets,
primaryMediaId: assetValue?.id,
classification: classifyContent({ ...base, mediaAssets }, state.classificationRules, state.taxonomy),
- customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
+ customLabels: uniqueNames(organization.customLabels), metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
});
const entries = [...state.entries, entry];
- await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
+ const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], organization);
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: entries,
+ [STORAGE_KEYS.organizerState]: organizerState
+ });
await notifySaved(entries.length);
return { ok: true, message: "视频来源已保存;不能嵌入的平台会打开原网页", entry };
}
-async function createQuickNote(titleValue, textValue) {
+async function createQuickNote(titleValue, textValue, organization = {}) {
const state = await readState();
const entry = buildEntry({ text: textValue, title: titleValue, url: "" });
entry.schemaVersion = SCHEMA_VERSION;
entry.classification = classifyImportedMedia({ ...entry, sourceKind: "quick_note" }, state.taxonomy);
+ entry.customLabels = uniqueNames(organization.customLabels);
const entries = [...state.entries, entry];
+ const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], organization);
await retireLastSaveUndo();
await commitLocalChanges({
[STORAGE_KEYS.entries]: entries,
+ [STORAGE_KEYS.organizerState]: organizerState,
[STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry.id)
});
await notifySaved(entries.length);
@@ -2042,7 +2160,7 @@ async function createQuickNote(titleValue, textValue) {
async function addEntryTimeNote(entryId, noteValue) {
const state = await readState();
const current = findEntry(state, entryId);
- const updated = addTimeNote(current, noteValue);
+ const updated = touchEntry(addTimeNote(current, noteValue));
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: "时间点笔记已保存", entry: updated };
@@ -2062,6 +2180,7 @@ async function addVideoKeyframe(entryId, assetValue, noteValue) {
reviewStatus: "verified"
});
updated = addTimeNote(updated, { ...noteValue, frameAssetId: frameId });
+ updated = touchEntry(updated);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: "当前画面和时间点笔记已保存", entry: updated };
@@ -2070,19 +2189,21 @@ async function addVideoKeyframe(entryId, assetValue, noteValue) {
async function deleteEntryTimeNote(entryId, noteId) {
const state = await readState();
const current = findEntry(state, entryId);
- const updated = removeTimeNote(current, noteId);
+ const next = removeTimeNote(current, noteId);
+ const updated = (next.timeNotes ?? []).length === (current.timeNotes ?? []).length ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: "时间点笔记已删除", entry: updated };
}
-async function commitCaptureDraft(duplicateAction = "") {
+async function commitCaptureDraft(duplicateAction = "", placementValue = {}) {
const draft = await captureRuntime.getDraft();
if (!draft.fragments.length && !draft.visuals.length) return { ok: false, message: "草稿里还没有可保存的文字或截图", draft };
const state = await readState();
const targetCompound = normalizeCompoundCases(state.compoundCases, state.entries)
.find((compound) => compound.id === draft.targetCaseId) ?? null;
- if (targetCompound) return commitCaptureIntoCompound(draft, draftParts(draft), state, targetCompound);
+ const placement = capturePlacement(draft, placementValue);
+ if (targetCompound) return commitCaptureIntoCompound(draft, draftParts(draft), state, targetCompound, placement);
const text = draftText(draft);
const sourcePages = mergeSourcePages(draftSourcePages(draft), draft.visuals.map((visual) => {
const context = sourceContextForUrl(draft, visual.sourceUrl);
@@ -2143,13 +2264,22 @@ async function commitCaptureDraft(duplicateAction = "") {
negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
});
}
- const entries = target
+ let entries = target
? state.entries.map((item) => item.id === entry.id ? entry : item)
: [...state.entries, entry];
+ const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, [entry.id], placement);
+ const existingEntryIds = new Set(state.entries.map((item) => item.id));
+ const touchedEntryIds = new Set([
+ ...(target ? [entry.id] : []),
+ ...changedProjectEntryIds(state.organizerState, organizerState).filter((id) => existingEntryIds.has(id))
+ ]);
+ entries = touchEntries(entries, [...touchedEntryIds]);
+ entry = entries.find((item) => item.id === entry.id) ?? entry;
const nextDraft = createCaptureDraft();
await retireLastSaveUndo();
await commitLocalChanges({
[STORAGE_KEYS.entries]: entries,
+ [STORAGE_KEYS.organizerState]: organizerState,
...captureCommitState(draft, nextDraft),
...(created ? { [STORAGE_KEYS.lastSaveUndo]: createEntrySaveUndo(entry.id) } : {})
});
@@ -2158,10 +2288,11 @@ async function commitCaptureDraft(duplicateAction = "") {
return { ok: true, message: target ? "内容已加入明确选择的案例" : "多段文字和截图已保存为新案例", entry, draft: nextDraft };
}
-async function commitCaptureIntoCompound(draft, parts, state, targetCompound) {
+async function commitCaptureIntoCompound(draft, parts, state, targetCompound, placement = {}) {
let entries = [...state.entries];
let compounds = normalizeCompoundCases(state.compoundCases, entries);
const memberIds = [...targetCompound.memberEntryIds];
+ const updatedExistingIds = new Set();
for (const [index, part] of parts.entries()) {
const partTarget = findCapturePartTarget({
entries,
@@ -2172,6 +2303,7 @@ async function commitCaptureIntoCompound(draft, parts, state, targetCompound) {
if (partTarget) {
const updated = mergeCapturePartIntoEntry(partTarget, part, draft, state);
entries = entries.map((entry) => entry.id === updated.id ? updated : entry);
+ updatedExistingIds.add(updated.id);
continue;
}
const created = createEntryFromCapturePart(part, draft, state, {
@@ -2184,12 +2316,19 @@ async function commitCaptureIntoCompound(draft, parts, state, targetCompound) {
const updated = updateCompoundCase(compounds, entries, targetCompound.id, { memberEntryIds: memberIds });
compounds = updated.compoundCases;
const compoundCase = updated.compoundCase;
+ const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, compoundCase.memberEntryIds, placement);
+ const existingEntryIds = new Set(state.entries.map((entry) => entry.id));
+ for (const entryId of changedProjectEntryIds(state.organizerState, organizerState)) {
+ if (existingEntryIds.has(entryId)) updatedExistingIds.add(entryId);
+ }
+ entries = touchEntries(entries, [...updatedExistingIds]);
const nextDraft = createCaptureDraft();
await retireLastSaveUndo();
await commitLocalChanges({
[STORAGE_KEYS.entries]: entries,
[STORAGE_KEYS.compoundCases]: compounds,
+ [STORAGE_KEYS.organizerState]: organizerState,
...captureCommitState(draft, nextDraft)
});
await notifySaved(entries.length);
@@ -2206,6 +2345,32 @@ async function commitCaptureIntoCompound(draft, parts, state, targetCompound) {
};
}
+function capturePlacement(draft, value = {}) {
+ const hasCollectionId = Object.hasOwn(value, "collectionId");
+ const hasNewCollectionName = Object.hasOwn(value, "newCollectionName");
+ return {
+ collectionId: String(hasCollectionId ? value.collectionId : draft.collectionId ?? "").trim(),
+ newCollectionName: String(hasNewCollectionName ? value.newCollectionName : draft.newCollectionName ?? "").trim()
+ };
+}
+
+function organizerAfterCapturePlacement(organizerValue, entries, entryIds, placement = {}) {
+ let organizerState = normalizeOrganizerState(organizerValue, entries.map((entry) => entry.id));
+ let collectionId = String(placement.collectionId ?? "").trim();
+ const newCollectionName = String(placement.newCollectionName ?? "").trim();
+ if (collectionId && newCollectionName) throw new Error("请选择已有项目或新建项目,不要同时填写");
+ if (newCollectionName) {
+ const created = createCollection(organizerState, newCollectionName);
+ organizerState = created.state;
+ collectionId = created.item.id;
+ }
+ if (!collectionId) return organizerState;
+ const target = organizerState.collections.find((collection) => collection.id === collectionId);
+ if (!target) throw new Error("保存目标项目已经不存在,请重新选择");
+ target.entryIds = [...new Set([...target.entryIds, ...entryIds])];
+ return normalizeOrganizerState(organizerState, entries.map((entry) => entry.id));
+}
+
function captureCommitState(_draft, nextDraft) {
return {
[STORAGE_KEYS.captureDraft]: nextDraft
@@ -2355,99 +2520,190 @@ async function undoLastSave() {
async function deleteEntry(entryId) {
const state = await readState();
- const entry = normalizeEntryMedia(findEntry(state, entryId));
- const creativeVisualIds = new Set(state.creativeRuns.flatMap((run) =>
- run.outputs.map((output) => output.visual.id)
- ));
- const removableVisualIds = entry.mediaAssets
- .filter((visual) => !creativeVisualIds.has(visual.id))
- .map((visual) => visual.id);
- const entries = state.entries.filter((item) => item.id !== entry.id);
- const organizerState = removeEntriesFromOrganizer(state.organizerState, [entry.id]);
- const compoundCases = removeEntriesFromCompoundCases(state.compoundCases, state.entries, [entry.id]);
- const visionAnalysisUndo = await visionUndoWithout(entry.id);
- await commitMetadataThenDeleteImages({
- imageIds: removableVisualIds,
- deleteImage: deleteMediaBlob,
- commitMetadata: () => commitLocalChanges({
- [STORAGE_KEYS.entries]: entries,
- [STORAGE_KEYS.compoundCases]: compoundCases,
- [STORAGE_KEYS.organizerState]: organizerState,
- [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
+ const entry = findEntry(state, entryId);
+ return moveEntryBatchToTrash([entry.id], state);
+}
+
+async function deleteCollectionWithEntries(message) {
+ const state = await readState();
+ const organizerState = normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id));
+ const collection = organizerState.collections.find((item) => item.id === String(message.collectionId ?? "").trim());
+ if (!collection) throw new Error("项目不存在");
+ if (String(message.confirmationName ?? "").trim() !== collection.name) throw new Error("项目名称不匹配,未执行删除");
+ if (!collection.entryIds.length) throw new Error("这个项目没有可删除的案例");
+ const moved = moveCollectionWithEntriesToTrash({
+ entries: state.entries,
+ trashState: state.trashState,
+ organizerState,
+ compoundCases: state.compoundCases
+ }, collection.id);
+ const visionAnalysisUndo = await visionUndoWithoutEntries(new Set(moved.movedEntryIds));
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: moved.entries,
+ [STORAGE_KEYS.trashState]: moved.trashState,
+ [STORAGE_KEYS.compoundCases]: moved.compoundCases,
+ [STORAGE_KEYS.organizerState]: moved.organizerState,
+ [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
+ });
+ return {
+ ok: true,
+ message: `项目“${collection.name}”及其中 ${moved.movedEntryIds.length} 个案例已移入回收站`,
+ movedEntryCount: moved.movedEntryIds.length,
+ movedItemIds: moved.movedItemIds,
+ ...publicDomainState({
+ ...state,
+ entries: moved.entries,
+ trashState: moved.trashState,
+ organizerState: moved.organizerState,
+ compoundCases: moved.compoundCases
})
+ };
+}
+
+async function moveEntryBatchToTrash(entryIdsValue, stateValue) {
+ const state = stateValue ?? await readState();
+ const activeIds = new Set(state.entries.map((entry) => entry.id));
+ const entryIds = uniqueNames(entryIdsValue).filter((entryId) => activeIds.has(entryId));
+ if (!entryIds.length) return { ok: false, message: "没有找到可移入回收站的案例" };
+ const moved = moveEntriesToTrash({
+ entries: state.entries,
+ trashState: state.trashState,
+ organizerState: state.organizerState,
+ compoundCases: state.compoundCases
+ }, entryIds);
+ const visionAnalysisUndo = await visionUndoWithoutEntries(new Set(entryIds));
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: moved.entries,
+ [STORAGE_KEYS.trashState]: moved.trashState,
+ [STORAGE_KEYS.organizerState]: moved.organizerState,
+ [STORAGE_KEYS.compoundCases]: moved.compoundCases,
+ [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
});
- await Promise.allSettled([
- clearLastSaveUndoForEntry(entry.id),
- chrome.storage.local.remove(screenshotStorageKey(entry.id))
- ]);
return {
ok: true,
- message: "案例已从本机删除",
- deletedEntryId: entry.id,
- entries,
- organizerState,
- compoundCases
+ message: moved.movedItemIds.length === 1
+ ? "案例已移入回收站"
+ : `${moved.movedItemIds.length} 个案例已移入回收站`,
+ movedEntryIds: entryIds,
+ movedItemIds: moved.movedItemIds,
+ ...publicDomainState({ ...state, ...moved })
};
}
-async function deleteCollectionWithEntries(message) {
+async function getTrashItems(message = {}) {
const state = await readState();
- const deletion = planCollectionAndEntriesDeletion(
- state.organizerState,
- state.entries,
- message.collectionId,
- message.confirmationName
- );
- if (!deletion.deletedEntryIds.length) throw new Error("这个项目没有可删除的案例");
-
- const deletedEntryIds = new Set(deletion.deletedEntryIds);
- const retainedMediaIds = new Set(deletion.entries.flatMap((entry) =>
- normalizeEntryMedia(entry).mediaAssets.map((asset) => asset.id)
- ));
- state.creativeRuns.forEach((run) => run.outputs.forEach((output) => retainedMediaIds.add(output.visual.id)));
- const removableMediaIds = deletion.deletedEntries.flatMap((entry) =>
- normalizeEntryMedia(entry).mediaAssets
- .map((asset) => asset.id)
- .filter((assetId) => !retainedMediaIds.has(assetId))
- );
- const compoundCases = removeEntriesFromCompoundCases(
- state.compoundCases,
- state.entries,
- deletion.deletedEntryIds
- );
- const visionAnalysisUndo = await visionUndoWithoutEntries(deletedEntryIds);
+ const items = listTrashItems(state.trashState, { kind: message.kind });
+ return { ok: true, items, count: items.length, trashState: normalizeTrashState(state.trashState) };
+}
+
+async function restoreSelectedTrashItems(message = {}) {
+ const state = await readState();
+ const restored = restoreTrashItems({
+ entries: state.entries,
+ trashState: state.trashState,
+ organizerState: state.organizerState,
+ compoundCases: state.compoundCases
+ }, message.itemIds, { collectionReplacements: message.collectionReplacements });
+ if (!restored.restoredItemIds.length) {
+ return {
+ ok: false,
+ message: restored.unresolved[0]?.reason || "没有找到可恢复的内容",
+ unresolved: restored.unresolved,
+ trashState: restored.trashState
+ };
+ }
+ await commitLocalChanges({
+ [STORAGE_KEYS.entries]: restored.entries,
+ [STORAGE_KEYS.trashState]: restored.trashState,
+ [STORAGE_KEYS.organizerState]: restored.organizerState,
+ [STORAGE_KEYS.compoundCases]: restored.compoundCases
+ });
+ const unresolvedMessage = restored.unresolved.length ? `;另有 ${restored.unresolved.length} 项因关系冲突未恢复` : "";
+ return {
+ ok: true,
+ message: `已恢复 ${restored.restoredItemIds.length} 项${unresolvedMessage}`,
+ restoredItemIds: restored.restoredItemIds,
+ unresolved: restored.unresolved,
+ ...publicDomainState({ ...state, ...restored })
+ };
+}
+
+async function permanentlyDeleteTrashItems(message = {}) {
+ const state = await readState();
+ const retainedMediaIds = collectRetainedLocalAssetIds(state);
+ const taken = takeTrashItems(state.trashState, message.itemIds, {
+ retainedMediaIds: [...retainedMediaIds],
+ retainedEntryIds: state.entries.map((entry) => entry.id)
+ });
+ return commitTrashCleanup(taken, { retainedLocalAssetIds: [...retainedMediaIds] });
+}
+
+async function emptyTrashAction() {
+ const state = await readState();
+ const retainedMediaIds = collectRetainedLocalAssetIds(state);
+ const taken = emptyTrash(state.trashState, {
+ retainedMediaIds: [...retainedMediaIds],
+ retainedEntryIds: state.entries.map((entry) => entry.id)
+ });
+ return commitTrashCleanup(taken, { retainedLocalAssetIds: [...retainedMediaIds] });
+}
+
+async function commitTrashCleanup(taken, options = {}) {
+ if (!taken.takenItems.length) return { ok: false, message: "回收站中没有可永久删除的内容" };
+ const retainedLocalAssetIds = new Set(Array.isArray(options.retainedLocalAssetIds) ? options.retainedLocalAssetIds : []);
+ const localReferenceIds = [...new Set(taken.takenItems.flatMap(localReferenceIdsInTrashItem))]
+ .filter((assetId) => !retainedLocalAssetIds.has(assetId));
const cleanup = await commitMetadataThenDeleteImages({
- imageIds: removableMediaIds,
+ imageIds: taken.cleanup.mediaIds,
deleteImages: deleteMediaBlobs,
- commitMetadata: () => commitLocalChanges({
- [STORAGE_KEYS.entries]: deletion.entries,
- [STORAGE_KEYS.compoundCases]: compoundCases,
- [STORAGE_KEYS.organizerState]: deletion.organizerState,
- [STORAGE_KEYS.visionAnalysisUndo]: visionAnalysisUndo
- })
+ commitMetadata: () => commitLocalChanges({ [STORAGE_KEYS.trashState]: taken.trashState })
});
- await Promise.allSettled([
- clearLastSaveUndoForEntries(deletedEntryIds),
- chrome.storage.local.remove(deletion.deletedEntryIds.map(screenshotStorageKey))
- ]);
- const cleanupWarning = cleanup.failedIds.length
- ? `;${cleanup.failedIds.length} 个已失去引用的媒体文件未能清理,可稍后重试`
- : "";
+ if (cleanup.failedIds.length) {
+ const retryableTrashState = normalizeTrashState({
+ items: [...taken.trashState.items, ...taken.takenItems]
+ });
+ await commitLocalChanges({ [STORAGE_KEYS.trashState]: retryableTrashState });
+ return {
+ ok: false,
+ message: "本机文件清理失败,内容仍保留在回收站,可稍后重试",
+ failedMediaCount: cleanup.failedIds.length,
+ trashState: retryableTrashState
+ };
+ }
+ const screenshotResults = await Promise.allSettled(
+ taken.cleanup.screenshotEntryIds.map((entryId) => chrome.storage.local.remove(screenshotStorageKey(entryId)))
+ );
+ const localReferenceResults = await Promise.allSettled(localReferenceIds.map((assetId) => deleteLocalAssetHandle(assetId)));
+ const failedScreenshotCount = screenshotResults.filter((result) => result.status === "rejected").length;
+ const failedLocalReferenceCount = localReferenceResults.filter((result) => result.status === "rejected").length;
+ const warningParts = [
+ failedScreenshotCount ? `${failedScreenshotCount} 个旧版截图缓存未能清理` : "",
+ failedLocalReferenceCount ? `${failedLocalReferenceCount} 个本机链接记录未能清理` : ""
+ ].filter(Boolean);
+ const warning = warningParts.length ? `;${warningParts.join(";")}` : "";
return {
ok: true,
- message: `已删除项目“${deletion.collection.name}”及其中 ${deletion.deletedEntryIds.length} 个案例${cleanupWarning}`,
- deletedEntryCount: deletion.deletedEntryIds.length,
+ message: `已永久删除 ${taken.takenItems.length} 项${warning}`,
+ permanentlyDeletedItemIds: taken.takenItems.map((item) => item.id),
deletedMediaCount: cleanup.deletedIds.length,
- failedMediaCount: cleanup.failedIds.length,
- ...publicDomainState({
- ...state,
- entries: deletion.entries,
- organizerState: deletion.organizerState,
- compoundCases
- })
+ deletedLocalReferenceCount: localReferenceIds.length - failedLocalReferenceCount,
+ failedMediaCount: 0,
+ failedLocalReferenceCount,
+ failedLegacyScreenshotCount: failedScreenshotCount,
+ trashState: taken.trashState
};
}
+function localReferenceIdsInTrashItem(item) {
+ if (!item || !["entry", "media"].includes(item.kind)) return [];
+ const assets = Array.isArray(item.snapshot?.mediaAssets)
+ ? item.snapshot.mediaAssets
+ : Array.isArray(item.snapshot?.visuals) ? item.snapshot.visuals : [];
+ return assets.flatMap((asset) => asset?.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE && asset?.id
+ ? [String(asset.id).trim()]
+ : []).filter(Boolean);
+}
+
function enqueue(task) {
const operation = writeQueue.then(task, task);
writeQueue = operation.catch(() => undefined);
@@ -2477,27 +2733,6 @@ async function retireLastSaveUndo(options = {}) {
await chrome.storage.local.remove(STORAGE_KEYS.lastSaveUndo);
}
-async function clearLastSaveUndoForEntry(entryId) {
- const stored = await chrome.storage.local.get(STORAGE_KEYS.lastSaveUndo);
- const undo = normalizeLastSaveUndo(stored[STORAGE_KEYS.lastSaveUndo]);
- if (undo?.entryId !== entryId) return;
- if (undo.type === "restore_replaced_screenshot") {
- await discardSaveUndoBackup(undo).catch(() => undefined);
- }
- await chrome.storage.local.remove(STORAGE_KEYS.lastSaveUndo);
-}
-
-async function clearLastSaveUndoForEntries(entryIds) {
- const ids = entryIds instanceof Set ? entryIds : new Set(entryIds);
- const stored = await chrome.storage.local.get(STORAGE_KEYS.lastSaveUndo);
- const undo = normalizeLastSaveUndo(stored[STORAGE_KEYS.lastSaveUndo]);
- if (!undo || !ids.has(undo.entryId)) return;
- if (undo.type === "restore_replaced_screenshot") {
- await discardSaveUndoBackup(undo).catch(() => undefined);
- }
- await chrome.storage.local.remove(STORAGE_KEYS.lastSaveUndo);
-}
-
async function discardSaveUndoBackup(undoValue) {
const undo = normalizeLastSaveUndo(undoValue);
if (undo?.type !== "restore_replaced_screenshot") return;
@@ -2530,6 +2765,7 @@ async function readState() {
let state = migration?.state ?? {
schemaVersion: SCHEMA_VERSION,
entries: stored[STORAGE_KEYS.entries],
+ trashState: stored[STORAGE_KEYS.trashState],
compoundCases: stored[STORAGE_KEYS.compoundCases],
taxonomy: stored[STORAGE_KEYS.taxonomy],
facetCatalog: stored[STORAGE_KEYS.facetCatalog],
@@ -3014,6 +3250,14 @@ async function startImportJobAction(message) {
for (const value of incoming) {
const assetId = String(value?.assetId ?? "").trim();
const name = String(value?.name ?? "").trim();
+ const isLocalReference = value?.storageMode === "reference" &&
+ value?.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE;
+ if (isLocalReference) {
+ const staged = addStagedAsset(staging, value);
+ staging = staged.state;
+ jobItems.push({ stagedAssetId: staged.asset.id, keepDuplicate: true });
+ continue;
+ }
const blob = assetId ? await getMediaBlob(assetId) : null;
if (!(blob instanceof Blob)) throw new Error(`没有读取到待导入文件:${name || assetId || "未命名"}`);
const file = new File([blob], name, { type: blob.type || value?.mimeType });
@@ -3047,7 +3291,8 @@ async function startImportJobAction(message) {
items: jobItems,
options: {
duplicateAction: "skip",
- autoAnalyze: message.options?.autoAnalyze === true
+ autoAnalyze: message.options?.autoAnalyze === true,
+ customLabels: uniqueNames(message.customLabels)
}
});
const skippedCleanupIds = [];
@@ -3083,18 +3328,25 @@ async function cancelImportJobAction(jobId) {
const canceled = cancelImportJob(stored[STORAGE_KEYS.importJobs], jobId);
let staging = normalizeImportStagingState(stored[STORAGE_KEYS.importStaging]);
const cleanupIds = [];
+ const localReferenceCleanupIds = [];
for (const item of canceled.job.items.filter((value) => value.status === "skipped" && value.skipReason === "canceled")) {
const staged = stagedAssetById(staging, item.stagedAssetId);
if (!staged) continue;
const removed = removeStagedAsset(staging, staged.id);
staging = removed.state;
cleanupIds.push(...removed.removedAssetIds);
+ if (staged.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE) localReferenceCleanupIds.push(staged.assetId);
}
await commitLocalChanges({
[STORAGE_KEYS.importJobs]: canceled.state,
[STORAGE_KEYS.importStaging]: staging
});
await deleteUnreferencedMedia(cleanupIds);
+ const committedState = await readState();
+ const retainedLocalAssetIds = collectRetainedLocalAssetIds({ ...committedState, importStaging: staging });
+ await Promise.allSettled(localReferenceCleanupIds
+ .filter((assetId) => !retainedLocalAssetIds.has(assetId))
+ .map((assetId) => deleteLocalAssetHandle(assetId)));
return { ok: true, message: "已取消剩余导入项", job: canceled.job };
}
@@ -3126,7 +3378,14 @@ async function undoImportJobAction(jobId) {
const assetIds = removedEntries.flatMap((entry) => normalizeEntryMedia(entry).mediaAssets
.filter((asset) => asset.storageMode !== "reference")
.map((asset) => asset.id));
+ const localReferenceIds = removedEntries.flatMap((entry) => normalizeEntryMedia(entry).mediaAssets
+ .filter((asset) => asset.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE)
+ .map((asset) => asset.id));
await deleteUnreferencedMedia(assetIds);
+ const retainedLocalAssetIds = collectRetainedLocalAssetIds({ ...state, entries });
+ await Promise.allSettled(localReferenceIds
+ .filter((assetId) => !retainedLocalAssetIds.has(assetId))
+ .map((assetId) => deleteLocalAssetHandle(assetId)));
return { ok: true, message: `已撤销本次导入的 ${removedEntries.length} 个案例`, job: undone.job };
}
@@ -3187,9 +3446,11 @@ async function importStagedItem(job, item) {
const state = await readState();
const staged = stagedAssetById(state.importStaging, item.stagedAssetId);
if (!staged) throw new Error("暂存文件已经丢失,无法继续导入");
- if (!await getMediaBlob(staged.assetId)) throw new Error(`本机媒体已经丢失:${staged.name}`);
+ if (staged.storageMode !== "reference" && !await getMediaBlob(staged.assetId)) {
+ throw new Error(`本机媒体已经丢失:${staged.name}`);
+ }
if (staged.posterAssetId && !await getMediaBlob(staged.posterAssetId)) throw new Error(`视频或 GIF 封面已经丢失:${staged.name}`);
- const entry = importedEntryFromStagedAsset(state, staged);
+ const entry = importedEntryFromStagedAsset(state, staged, job, item);
const entries = [...state.entries, entry];
let organizerState = normalizeOrganizerState(state.organizerState, entries.map((value) => value.id));
if (job.collectionId) {
@@ -3210,26 +3471,15 @@ async function importStagedItem(job, item) {
await queueImportJobAnalysis(finished.job);
}
-function importedEntryFromStagedAsset(state, staged) {
- const base = buildEntry({ text: staged.contentText || "", title: staged.name, url: "", allowEmptyText: true });
- const asset = {
- id: staged.assetId,
- kind: staged.kind,
- storageMode: "managed",
- mimeType: staged.mimeType,
- byteSize: staged.byteSize,
- sourceTitle: staged.name,
- relativePath: staged.relativePath,
- contentHash: staged.contentHash,
- capturedAt: new Date().toISOString(),
- reviewStatus: "verified",
- ...(staged.width ? { width: staged.width } : {}),
- ...(staged.height ? { height: staged.height } : {}),
- ...(staged.durationMs ? { durationMs: staged.durationMs } : {}),
- ...(staged.playbackCapability ? { playbackCapability: staged.playbackCapability } : {}),
- ...(staged.kind === "document" && staged.contentFormat ? { extractedTextFormat: staged.contentFormat } : {}),
- ...(staged.posterAssetId ? { posterAssetId: staged.posterAssetId } : {})
- };
+function importedEntryFromStagedAsset(state, staged, job, item) {
+ const base = buildEntry({
+ text: staged.contentText || "",
+ title: staged.name,
+ url: "",
+ libraryAddedAt: item.libraryAddedAt || job.libraryAddedAt,
+ allowEmptyText: true
+ });
+ const asset = stagedAssetMediaRecord(staged, { capturedAt: new Date().toISOString() });
const mediaAssets = [asset];
if (staged.posterAssetId) {
mediaAssets.push({
@@ -3245,11 +3495,12 @@ function importedEntryFromStagedAsset(state, staged) {
}
return normalizeEntryMedia({
...base,
+ importBatchId: item.importBatchId || job.importBatchId,
schemaVersion: SCHEMA_VERSION,
mediaAssets,
primaryMediaId: staged.assetId,
classification: classifyImportedMedia({ ...base, mediaAssets }, state.taxonomy),
- customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
+ customLabels: uniqueNames(job.options.customLabels), metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],
rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false
});
}
@@ -3986,7 +4237,7 @@ async function updateClassification(message) {
}
const current = findEntry(state, message.entryId);
const recovery = await recoverPaletteAfterClassification(confirmClassification(current, message.pathIds, state.taxonomy));
- const updated = recovery.entry;
+ const updated = touchEntry(recovery.entry);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
let classificationRules = state.classificationRules;
if (message.rememberSource) {
@@ -4110,11 +4361,13 @@ async function applyDetailTagOrganization(message) {
const state = await readState();
const before = domainState(state);
const applied = applyDetailOrganizationMappings(before, message.mappings);
- await persistDomainState(applied.state, before);
+ const changedIds = userVisibleEntryChanges(before.entries, applied.state.entries);
+ const nextState = { ...applied.state, entries: touchEntries(applied.state.entries, changedIds) };
+ await persistDomainState(nextState, before);
return {
ok: true,
message: `已整理 ${applied.changedCount} 个三级标签,其中合并 ${applied.mergedCount} 个;旧名称仍可搜索`,
- ...publicDomainState(applied.state),
+ ...publicDomainState(nextState),
canUndoFacetUpdate: true
};
}
@@ -4531,7 +4784,8 @@ async function updateVisionDescription(entryId, visualIdValue, description) {
async function updateEntryMediaPromptAction(message) {
const state = await readState();
const current = findEntry(state, message.entryId);
- const updated = setEntryMediaPrompt(current, message.assetId, message.text, "manual");
+ const next = setEntryMediaPrompt(current, message.assetId, message.text, "manual");
+ const updated = userVisibleEntryEqual(current, next) ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return {
@@ -4554,6 +4808,7 @@ async function applyEntryMediaPromptSuggestions(message) {
appliedCount += 1;
}
if (!appliedCount) return { ok: false, message: "没有需要保存的逐图提示词" };
+ updated = touchEntry(updated);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: `已确认并保存 ${appliedCount} 条逐图提示词`, entry: updated };
@@ -4602,7 +4857,8 @@ async function updateEntryFacet(message) {
const current = findEntry(state, message.entryId);
const node = state.facetCatalog.nodes.find((item) => item.id === message.nodeId && item.status === "active");
if (!node || node.facetId !== message.facetId) return { ok: false, message: "创作标签无效" };
- const updated = setManualAssignment(current, node.facetId, node.id, message.selected !== false);
+ const next = setManualAssignment(current, node.facetId, node.id, message.selected !== false);
+ const updated = userVisibleEntryEqual(current, next) ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: message.selected === false ? "标签已移除" : "创作标签已添加", entry: updated };
@@ -4611,7 +4867,8 @@ async function updateEntryFacet(message) {
async function updateCaseText(message) {
const state = await readState();
const current = findEntry(state, message.entryId);
- const updated = updateEntryText(current, message.text, message.textRevision);
+ const next = updateEntryText(current, message.text, message.textRevision);
+ const updated = next.text === current.text ? next : touchEntry(next);
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return {
@@ -4626,15 +4883,74 @@ async function updateCaseTitle(message) {
const current = findEntry(state, message.entryId);
const title = String(message.title ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
if (!title) return { ok: false, message: "案例标题不能为空" };
- const updated = { ...current, title };
+ const updated = title === current.title ? current : touchEntry({ ...current, title });
const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
return { ok: true, message: title === current.title ? "标题没有变化" : "标题已保存", entry: updated };
}
+async function updateEntryCustomLabels(message) {
+ const state = await readState();
+ const current = findEntry(state, message.entryId);
+ const customLabels = uniqueNames(message.customLabels);
+ const updated = stringListsEqual(customLabels, current.customLabels) ? current : touchEntry({ ...current, customLabels });
+ const entries = state.entries.map((entry) => entry.id === current.id ? updated : entry);
+ await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
+ return { ok: true, message: "标签已保存", entry: updated, entries };
+}
+
+async function batchAddCustomLabels(message) {
+ const state = await readState();
+ const requested = new Set(uniqueNames(message.entryIds));
+ const labels = uniqueNames(message.customLabels);
+ if (!labels.length) return { ok: false, message: "请输入要添加的标签" };
+ let updatedCount = 0;
+ const updatedAt = new Date().toISOString();
+ const entries = state.entries.map((entry) => {
+ if (!requested.has(entry.id)) return entry;
+ const customLabels = uniqueNames([...(entry.customLabels ?? []), ...labels]);
+ if (stringListsEqual(customLabels, entry.customLabels)) return entry;
+ updatedCount += 1;
+ return touchEntry({ ...entry, customLabels }, updatedAt);
+ });
+ if (!updatedCount) return { ok: true, message: "所选案例已经包含这些标签", updatedCount: 0, entries };
+ await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });
+ return { ok: true, message: `已为 ${updatedCount} 个案例添加标签`, updatedCount, entries };
+}
+
+async function batchSetProject(message) {
+ const state = await readState();
+ const validIds = new Set(state.entries.map((entry) => entry.id));
+ const entryIds = uniqueNames(message.entryIds).filter((entryId) => validIds.has(entryId));
+ if (!entryIds.length) return { ok: false, message: "没有找到可加入项目的案例" };
+ const mode = message.mode === "move" ? "move" : "add";
+ let organizerState = normalizeOrganizerState(state.organizerState, [...validIds]);
+ if (!organizerState.collections.some((collection) => collection.id === String(message.collectionId ?? "").trim())) {
+ return { ok: false, message: "项目不存在" };
+ }
+ const beforeOrganizer = organizerState;
+ if (mode === "move") organizerState = removeEntriesFromOrganizer(organizerState, entryIds);
+ organizerState = setEntriesCollection(organizerState, message.collectionId, entryIds, true);
+ const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);
+ const entries = touchEntries(state.entries, changedEntryIds);
+ await commitLocalChanges({
+ ...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),
+ [STORAGE_KEYS.organizerState]: organizerState
+ });
+ return {
+ ok: true,
+ message: mode === "move" ? `已将 ${entryIds.length} 个案例移动到项目` : `已将 ${entryIds.length} 个案例加入项目`,
+ updatedCount: entryIds.length,
+ entries,
+ organizerState
+ };
+}
+
async function updateOrganizer(message) {
const state = await readState();
let organizerState = normalizeOrganizerState(state.organizerState, state.entries.map((entry) => entry.id));
+ const beforeOrganizer = organizerState;
+ let trashState = normalizeTrashState(state.trashState);
let created = null;
if (message.type === "CREATE_COLLECTION") {
const result = createCollection(organizerState, message.name);
@@ -4643,7 +4959,12 @@ async function updateOrganizer(message) {
} else if (message.type === "RENAME_COLLECTION") {
organizerState = renameCollection(organizerState, message.collectionId, message.name);
} else if (message.type === "DELETE_COLLECTION") {
- organizerState = deleteCollection(organizerState, message.collectionId);
+ const moved = moveCollectionsToTrash({ organizerState, trashState }, [message.collectionId]);
+ if (!moved.movedItemIds.length) throw new Error("项目不存在");
+ organizerState = normalizeOrganizerState(moved.organizerState, state.entries.map((entry) => entry.id));
+ trashState = moved.trashState;
+ } else if (message.type === "REORDER_COLLECTIONS") {
+ organizerState = reorderCollections(organizerState, message.collectionIds);
} else if (message.type === "REPLACE_COLLECTION_ENTRIES") {
const validIds = new Set(state.entries.map((entry) => entry.id));
const entryIds = (Array.isArray(message.entryIds) ? message.entryIds : []).filter((id) => validIds.has(id));
@@ -4651,15 +4972,22 @@ async function updateOrganizer(message) {
} else if (message.type === "SET_COLLECTION_VISIBILITY") {
organizerState = setCollectionVisibility(organizerState, message.collectionId, message.visibility);
}
- await commitLocalChanges({ [STORAGE_KEYS.organizerState]: organizerState });
- return { ok: true, message: organizerMessage(message.type), organizerState, created };
+ const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);
+ const entries = touchEntries(state.entries, changedEntryIds);
+ await commitLocalChanges({
+ ...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),
+ [STORAGE_KEYS.organizerState]: organizerState,
+ ...(message.type === "DELETE_COLLECTION" ? { [STORAGE_KEYS.trashState]: trashState } : {})
+ });
+ return { ok: true, message: organizerMessage(message.type), entries, organizerState, trashState, created };
}
function organizerMessage(type) {
return ({
CREATE_COLLECTION: "项目已创建",
RENAME_COLLECTION: "项目名称已保存",
- DELETE_COLLECTION: "项目已删除,案例仍保留在资料库",
+ DELETE_COLLECTION: "项目已移入回收站,案例仍保留在资料库",
+ REORDER_COLLECTIONS: "项目顺序已保存",
REPLACE_COLLECTION_ENTRIES: "项目案例已更新",
SET_COLLECTION_VISIBILITY: "项目显示范围已更新"
})[type] || "项目已更新";
@@ -5585,6 +5913,69 @@ function findEntry(state, entryId) {
return entry;
}
+function touchEntry(entry, updatedAt = new Date().toISOString()) {
+ return { ...entry, libraryUpdatedAt: updatedAt };
+}
+
+function touchEntries(entriesValue, entryIdsValue, updatedAt = new Date().toISOString()) {
+ const entryIds = new Set(Array.isArray(entryIdsValue) ? entryIdsValue : []);
+ if (!entryIds.size) return entriesValue;
+ return entriesValue.map((entry) => entryIds.has(entry.id) ? touchEntry(entry, updatedAt) : entry);
+}
+
+function stringListsEqual(leftValue, rightValue) {
+ const left = Array.isArray(leftValue) ? leftValue : [];
+ const right = Array.isArray(rightValue) ? rightValue : [];
+ return left.length === right.length && left.every((value, index) => value === right[index]);
+}
+
+function userVisibleEntryEqual(left = {}, right = {}) {
+ return JSON.stringify({
+ title: left.title,
+ text: left.text,
+ customLabels: left.customLabels ?? [],
+ classification: left.classification ?? null,
+ facetAssignments: left.facetAssignments ?? [],
+ mediaPrompts: left.mediaPrompts ?? []
+ }) === JSON.stringify({
+ title: right.title,
+ text: right.text,
+ customLabels: right.customLabels ?? [],
+ classification: right.classification ?? null,
+ facetAssignments: right.facetAssignments ?? [],
+ mediaPrompts: right.mediaPrompts ?? []
+ });
+}
+
+function userVisibleEntryChanges(beforeValue, afterValue) {
+ const beforeById = new Map((Array.isArray(beforeValue) ? beforeValue : []).map((entry) => [entry.id, entry]));
+ return (Array.isArray(afterValue) ? afterValue : [])
+ .filter((entry) => beforeById.has(entry.id) && !userVisibleEntryEqual(beforeById.get(entry.id), entry))
+ .map((entry) => entry.id);
+}
+
+function changedProjectEntryIds(beforeValue, afterValue) {
+ const memberships = (value) => {
+ const result = new Map();
+ for (const collection of normalizeOrganizerState(value).collections) {
+ for (const entryId of collection.entryIds) {
+ const collectionIds = result.get(entryId) ?? [];
+ collectionIds.push(collection.id);
+ result.set(entryId, collectionIds);
+ }
+ }
+ return result;
+ };
+ const before = memberships(beforeValue);
+ const after = memberships(afterValue);
+ const entryIds = new Set([...before.keys(), ...after.keys()]);
+ return [...entryIds].filter((entryId) => {
+ const left = (before.get(entryId) ?? []).toSorted();
+ const right = (after.get(entryId) ?? []).toSorted();
+ return !stringListsEqual(left, right);
+ });
+}
+
function requireAnalysisBatch(value, jobId, kind) {
const job = normalizeAnalysisBatchJob(value);
if (!job || (jobId && job.id !== jobId)) throw new Error("批量分析任务已变化,请刷新页面");
@@ -5634,6 +6025,7 @@ function domainState(state) {
return {
schemaVersion: SCHEMA_VERSION,
entries: state.entries,
+ trashState: normalizeTrashState(state.trashState),
compoundCases: normalizeCompoundCases(state.compoundCases, state.entries),
taxonomy: state.taxonomy,
facetCatalog: state.facetCatalog,
@@ -5645,6 +6037,7 @@ function domainState(state) {
function publicDomainState(state) {
return {
entries: enrichContentMeanings(state.entries, state.taxonomy),
+ trashState: normalizeTrashState(state.trashState),
compoundCases: normalizeCompoundCases(state.compoundCases, state.entries),
taxonomy: state.taxonomy,
facetCatalog: state.facetCatalog,
@@ -5670,6 +6063,7 @@ function publicLibraryState(state) {
function folderBackupState(state) {
return {
entries: state.entries,
+ trashState: normalizeTrashState(state.trashState),
settings: state.settings,
taxonomy: state.taxonomy,
facetCatalog: state.facetCatalog,
@@ -5699,6 +6093,7 @@ function storagePayload(state) {
return {
[STORAGE_KEYS.schemaVersion]: SCHEMA_VERSION,
[STORAGE_KEYS.entries]: state.entries,
+ [STORAGE_KEYS.trashState]: normalizeTrashState(state.trashState),
[STORAGE_KEYS.compoundCases]: normalizeCompoundCases(state.compoundCases, state.entries),
[STORAGE_KEYS.taxonomy]: state.taxonomy,
[STORAGE_KEYS.facetCatalog]: normalizeFacetCatalog(state.facetCatalog),
@@ -6245,6 +6640,7 @@ async function synchronizeWithVault(vault, settingsValue, reason) {
async function prepareStateForSync(state, vault, onProgress = () => undefined) {
const prepared = structuredClone({
entries: state.entries,
+ trashState: normalizeTrashState(state.trashState),
compoundCases: state.compoundCases,
organizerState: state.organizerState,
taxonomy: state.taxonomy,
@@ -6260,6 +6656,11 @@ async function prepareStateForSync(state, vault, onProgress = () => undefined) {
const seenVisualIds = new Set();
const visuals = [
...prepared.entries.flatMap((entry) => entry.mediaAssets ?? entry.visuals ?? []),
+ ...prepared.trashState.items.flatMap((item) => {
+ if (item.kind === "entry") return item.snapshot?.mediaAssets ?? item.snapshot?.visuals ?? [];
+ if (item.kind === "media") return item.snapshot?.mediaAssets ?? item.snapshot?.visuals ?? [];
+ return [];
+ }),
...prepared.creativeRuns.flatMap((run) => run.outputs.map((output) => output.visual)),
...(prepared.creativeSkills?.items ?? []).flatMap((skill) => skill.packageFiles ?? []),
...prepared.composerSessions.flatMap((session) => (session.referenceSnapshots ?? [])
@@ -6309,6 +6710,7 @@ function synchronizedStatePayload(current, synced) {
const next = {
schemaVersion: SCHEMA_VERSION,
entries,
+ trashState: normalizeTrashState(synced.trashState ?? current.trashState),
compoundCases: normalizeCompoundCases(synced.compoundCases ?? current.compoundCases, entries),
taxonomy: synced.taxonomy ?? current.taxonomy,
facetCatalog: synced.facetCatalog ?? current.facetCatalog,
diff --git a/capture-draft.js b/capture-draft.js
index fa84b29..de5566c 100644
--- a/capture-draft.js
+++ b/capture-draft.js
@@ -1,7 +1,7 @@
import { normalizeVisual } from "./visuals.js";
import { uniqueNames } from "./facets.js";
-export const CAPTURE_DRAFT_VERSION = 3;
+export const CAPTURE_DRAFT_VERSION = 4;
export function createCaptureDraft(value = {}) {
const now = new Date().toISOString();
@@ -24,6 +24,8 @@ export function createCaptureDraft(value = {}) {
contentTypeExplicit: value.contentTypeExplicit === true,
customLabels: uniqueNames(value.customLabels),
customLabelsExplicit: value.customLabelsExplicit === true,
+ collectionId: clean(value.collectionId),
+ newCollectionName: clean(value.newCollectionName),
createdAt: validIso(value.createdAt) || now,
updatedAt: validIso(value.updatedAt) || now
};
diff --git a/capture-permissions.js b/capture-permissions.js
index 473a894..5e10798 100644
--- a/capture-permissions.js
+++ b/capture-permissions.js
@@ -1,5 +1,7 @@
export const CONTINUOUS_CAPTURE_ORIGINS = Object.freeze(["<all_urls>"]);
export const CLIPBOARD_READ_PERMISSIONS = Object.freeze(["clipboardRead"]);
+export const CAPTURE_PERMISSION_ONBOARDING_VERSION = 1;
+export const CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY = "capturePermissionOnboarding";
export const RESTRICTED_PAGE_MESSAGE = "当前页不可采集:Chrome 新标签页、设置页和扩展页不允许读取;普通网站请先点工具栏图标。";
const CLIPBOARD_IMAGE_MIME_TYPES = Object.freeze(["image/png", "image/jpeg", "image/webp"]);
@@ -12,9 +14,43 @@ export function pagePermissionPattern(pageUrl) {
}
export async function ensureContinuousCapturePermission(permissionsApi) {
- return Boolean(await permissionsApi.request({
- origins: [...CONTINUOUS_CAPTURE_ORIGINS]
- }));
+ const request = { origins: [...CONTINUOUS_CAPTURE_ORIGINS] };
+ if (typeof permissionsApi.contains === "function" && await permissionsApi.contains(request)) return true;
+ return Boolean(await permissionsApi.request(request));
+}
+
+export function normalizeCapturePermissionOnboarding(value) {
+ if (!value || value.version !== CAPTURE_PERMISSION_ONBOARDING_VERSION || !value.acknowledgedAt) {
+ return { version: CAPTURE_PERMISSION_ONBOARDING_VERSION, acknowledgedAt: "", clipboardIncluded: true };
+ }
+ return {
+ version: CAPTURE_PERMISSION_ONBOARDING_VERSION,
+ acknowledgedAt: String(value.acknowledgedAt),
+ clipboardIncluded: value.clipboardIncluded !== false
+ };
+}
+
+export async function inspectCapturePermissionBundle(permissionsApi) {
+ const [webCaptureGranted, clipboardGranted] = await Promise.all([
+ permissionsApi.contains({ origins: [...CONTINUOUS_CAPTURE_ORIGINS] }),
+ hasClipboardReadPermission(permissionsApi)
+ ]);
+ return { webCaptureGranted: Boolean(webCaptureGranted), clipboardGranted: Boolean(clipboardGranted) };
+}
+
+export async function requestCapturePermissionBundle(permissionsApi, {
+ includeClipboard = true,
+ current = null
+} = {}) {
+ const status = current ?? await inspectCapturePermissionBundle(permissionsApi);
+ const request = {};
+ if (!status.webCaptureGranted) request.origins = [...CONTINUOUS_CAPTURE_ORIGINS];
+ if (includeClipboard && !status.clipboardGranted) request.permissions = [...CLIPBOARD_READ_PERMISSIONS];
+ if (!request.origins && !request.permissions) return { granted: true, requested: null };
+ return {
+ granted: Boolean(await permissionsApi.request(request)),
+ requested: request
+ };
}
export async function ensurePagePermission(pageUrl, permissionsApi) {
diff --git a/collector.css b/collector.css
index 533ef34..402eb3c 100644
--- a/collector.css
+++ b/collector.css
@@ -372,6 +372,8 @@ main {
font-size: 11px;
font-weight: 700;
}
+.custom-label-editor { display: grid; gap: 7px; }
+.custom-label-editor > span { color: var(--muted); font-size: 11px; font-weight: 700; }
.custom-label-editor label { display: block; margin-top: 8px; }
.custom-label-editor small { display: block; margin-top: 5px; color: var(--muted); font-size: 10px; }
diff --git a/collector.html b/collector.html
index 859b315..79d7fc6 100644
--- a/collector.html
+++ b/collector.html
@@ -24,6 +24,55 @@
<button id="exit-target" class="quiet compact" type="button">退出</button>
</section>
+ <dialog id="capture-permission-onboarding" class="app-dialog" aria-labelledby="capture-permission-title">
+ <form id="capture-permission-form" class="app-dialog-form" method="dialog">
+ <header>
+ <div>
+ <h2 id="capture-permission-title">一次说明,之后直接采集</h2>
+ <p>只在你主动选择采集方式时使用这些能力;授权完成后会继续刚才的操作,不会自动保存案例。</p>
+ </div>
+ </header>
+ <div class="app-dialog-body">
+ <div>
+ <strong>网页采集</strong>
+ <p>读取你主动采集的普通网页内容,用于智能选图、文字提取和整页采集。</p>
+ </div>
+ <div>
+ <strong>截图</strong>
+ <p>只在你点击智能选图或框选截图后,读取当前网页的可见画面。</p>
+ </div>
+ <label class="app-dialog-check">
+ <input id="capture-permission-clipboard" type="checkbox" checked />
+ <span><strong>剪贴板读取(默认开启,可取消)</strong><br /><small>仅当你点击“提取文字/图片”且网页没有可提取的高亮时读取;打开侧栏、点击网页或高亮文字都不会读取剪贴板。</small></span>
+ </label>
+ <p id="capture-permission-status" class="app-dialog-status" role="status" aria-live="polite"></p>
+ </div>
+ <footer>
+ <button id="capture-permission-cancel" class="button-secondary" type="button">暂不授权</button>
+ <button id="capture-permission-confirm" class="primary" type="submit">授权并继续</button>
+ </footer>
+ </form>
+ </dialog>
+
+ <dialog id="clipboard-permission-dialog" class="app-dialog" aria-labelledby="clipboard-permission-title">
+ <form id="clipboard-permission-form" class="app-dialog-form" method="dialog">
+ <header>
+ <div>
+ <h2 id="clipboard-permission-title">启用剪贴板提取?</h2>
+ <p>你首次授权时取消了剪贴板读取。只有确认此操作后,才会读取当前剪贴板中的文字或图片。</p>
+ </div>
+ </header>
+ <div class="app-dialog-body">
+ <p>启用后仍只会在你主动点击“提取文字/图片”且网页没有可用高亮时读取;打开侧栏、浏览或点击网页不会触发读取。</p>
+ <p id="clipboard-permission-status" class="app-dialog-status" role="status" aria-live="polite"></p>
+ </div>
+ <footer>
+ <button id="clipboard-permission-cancel" class="button-secondary" type="button">保持关闭</button>
+ <button id="clipboard-permission-confirm" class="primary" type="submit">启用并提取</button>
+ </footer>
+ </form>
+ </dialog>
+
<section id="start-state" class="start-state">
<div id="result-start" class="result-start" hidden>
<div class="start-copy">
@@ -80,7 +129,7 @@
<p>正文内已定位媒体默认纳入;保存按钮就是最终授权。位置不确定的素材默认不选。</p>
<div id="page-capture-media-review-list" class="page-capture-media-review-list"></div>
</section>
- <div class="page-capture-actions">
+ <div id="page-capture-actions" class="page-capture-actions">
<button id="page-capture-cancel" class="button-secondary" type="button">取消</button>
<button id="page-capture-save-text-only" class="button-secondary" type="button" hidden>只保存正文</button>
<button id="page-capture-save" class="primary" type="button">保存为一个案例</button>
@@ -121,24 +170,27 @@
<section id="preview-state" class="preview-state" hidden>
<header class="preview-heading">
<div><small>待保存内容</small><h2 id="content-summary"></h2></div>
- <span>临时保存在本机</span>
</header>
<div id="quick-preview" class="quick-preview"></div>
- <section class="save-metadata" aria-label="保存设置">
+ <section id="capture-metadata" class="save-metadata" aria-label="保存设置">
+ <label>
+ <span>项目</span>
+ <select id="capture-collection"></select>
+ </label>
+ <label id="capture-new-collection-row" hidden>
+ <span>新项目名称</span>
+ <input id="capture-new-collection-name" autocomplete="off" placeholder="输入后会在保存案例时创建" />
+ </label>
<label>
<span data-i18n="一级分类">一级分类</span>
<select id="content-type"></select>
</label>
- <details class="custom-label-editor">
- <summary>自定义标签(可选)</summary>
- <label>
- <span class="sr-only">自定义标签</span>
- <input id="custom-labels" autocomplete="off" placeholder="例如:喜欢、待复刻、广告参考" />
- </label>
- <small>用逗号分隔</small>
- </details>
+ <div class="custom-label-editor">
+ <span>添加标签</span>
+ <div id="custom-labels"></div>
+ </div>
</section>
- <div class="add-more-actions">
+ <div id="capture-add-more-actions" class="add-more-actions">
<button id="add-smart-visuals" class="quiet" type="button">+ 智能选图</button>
<button id="add-selection" class="quiet" type="button" data-i18n="+ 提取文字/图片">+ 提取文字/图片</button>
<button id="add-page-capture" class="quiet" type="button">+ 网页采集</button>
diff --git a/collector.js b/collector.js
index 350e561..bd3bb69 100644
--- a/collector.js
+++ b/collector.js
@@ -8,11 +8,16 @@ import {
import { prepareLocalMedia } from "./local-media.js";
import { runCaptureTransaction } from "./capture-workspace.js";
import {
+ CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY,
+ CAPTURE_PERMISSION_ONBOARDING_VERSION,
ensureClipboardReadPermission,
ensurePagePermission,
+ inspectCapturePermissionBundle,
inspectPagePermission,
+ normalizeCapturePermissionOnboarding,
pageCapturePermissionFailureMessage,
readClipboardContentAfterFocus,
+ requestCapturePermissionBundle,
RESTRICTED_PAGE_MESSAGE,
resolveActivePage
} from "./capture-permissions.js";
@@ -29,12 +34,13 @@ import {
pageCaptureStructureMatches
} from "./page-capture.js";
import { PAGE_CAPTURE_LIMITS } from "./resource-limits.js";
+import { createTagEditor } from "./tag-editor.js";
await initializeUi();
const elements = Object.fromEntries([
"add-selection", "add-screenshot", "add-smart-visuals", "collector-footer", "content-summary", "discard-draft", "draft-title",
- "content-type", "custom-labels", "duplicate-panel", "duplicate-title", "exit-target", "feedback", "fragment-help", "fragment-list",
+ "content-type", "custom-labels", "capture-metadata", "capture-collection", "capture-new-collection-row", "capture-new-collection-name", "capture-add-more-actions", "duplicate-panel", "duplicate-title", "exit-target", "feedback", "fragment-help", "fragment-list",
"fragment-section", "merge-duplicate", "open-library", "organizer", "organize-toggle", "preview-state",
"quick-preview", "result-prompt-title", "result-screenshot", "result-smart-visuals", "result-start", "save-draft", "save-other-inspiration",
"save-separate", "start-screenshot", "start-selection", "start-smart-visuals", "start-state", "normal-start",
@@ -45,14 +51,17 @@ const elements = Object.fromEntries([
"page-capture-add-region", "page-capture-exclude-region", "page-capture-undo-region", "page-capture-reset-region",
"page-capture-media-close", "page-capture-media-prev", "page-capture-media-next",
"page-capture-list-setup", "page-capture-target-count", "page-capture-list-run", "page-capture-list-result", "page-capture-list-summary",
- "page-capture-save-mode", "page-capture-combined-title-row", "page-capture-combined-title",
+ "page-capture-save-mode", "page-capture-combined-title-row", "page-capture-combined-title", "page-capture-actions",
"region-capture-status", "region-capture-title", "region-capture-help", "region-capture-cancel",
+ "capture-permission-onboarding", "capture-permission-form", "capture-permission-clipboard", "capture-permission-status", "capture-permission-cancel", "capture-permission-confirm",
+ "clipboard-permission-dialog", "clipboard-permission-form", "clipboard-permission-status", "clipboard-permission-cancel", "clipboard-permission-confirm",
"target-banner", "target-label", "visual-help", "visual-list", "visual-section"
].map((id) => [camel(id), document.getElementById(id)]));
let draft = null;
let targetEntry = null;
let contentTypes = [];
+let collections = [];
let suggestedContentTypeId = "";
let partContentTypes = {};
let activeCreativeResult = null;
@@ -74,12 +83,24 @@ const visualUrls = new Map();
const FEEDBACK_DURATION_MS = 4000;
const ERROR_FEEDBACK_DURATION_MS = 8000;
let feedbackTimer = 0;
+let pendingCaptureAction = null;
+let pendingClipboardButton = null;
+let creatingCollection = false;
+const NEW_COLLECTION_OPTION_VALUE = "new-collection";
const CLIPBOARD_IMAGE_EXTENSIONS = Object.freeze({
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp"
});
+const customLabelEditor = createTagEditor({
+ onChange: async (values) => {
+ if (!draft) return false;
+ return Boolean(await updateDraft({ ...draft, customLabels: values, customLabelsExplicit: true }));
+ }
+});
+elements.customLabels.replaceChildren(customLabelEditor.element);
+
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "local" || !(changes.captureDraft || changes.activeCreativeResult || changes.composerSessions)) return;
refresh().catch(() => undefined);
@@ -100,17 +121,29 @@ chrome.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {
if (tab.active && changeInfo.url) void refreshPageCapturePermissionState();
});
window.addEventListener("pagehide", () => void clearPageCaptureMarkers());
-elements.startSelection.addEventListener("click", () => extractClipboardOrSelection(elements.startSelection));
-elements.startScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.startScreenshot));
-elements.startSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.startSmartVisuals));
-elements.startPageCapture.addEventListener("click", () => startPageCapture("loaded", elements.startPageCapture));
-elements.resultScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.resultScreenshot, true));
-elements.resultSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.resultSmartVisuals, true));
+elements.startSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractClipboardOrSelection(elements.startSelection, context)));
+elements.startScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.startScreenshot)));
+elements.startSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.startSmartVisuals)));
+elements.startPageCapture.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => startPageCapture("loaded", elements.startPageCapture)));
+elements.resultScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.resultScreenshot, true)));
+elements.resultSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.resultSmartVisuals, true)));
elements.saveOtherInspiration.addEventListener("click", () => clearActiveCreativeResult());
-elements.addSelection.addEventListener("click", () => extractClipboardOrSelection(elements.addSelection));
-elements.addScreenshot.addEventListener("click", () => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.addScreenshot));
-elements.addSmartVisuals.addEventListener("click", () => beginSmartVisualSelection(elements.addSmartVisuals));
-elements.addPageCapture.addEventListener("click", () => startPageCapture("loaded", elements.addPageCapture));
+elements.addSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractClipboardOrSelection(elements.addSelection, context)));
+elements.addScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.addScreenshot)));
+elements.addSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.addSmartVisuals)));
+elements.addPageCapture.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => startPageCapture("loaded", elements.addPageCapture)));
+elements.capturePermissionCancel.addEventListener("click", cancelCapturePermissionOnboarding);
+elements.capturePermissionForm.addEventListener("submit", confirmCapturePermissionOnboarding);
+elements.capturePermissionOnboarding.addEventListener("cancel", (event) => {
+ event.preventDefault();
+ cancelCapturePermissionOnboarding();
+});
+elements.clipboardPermissionCancel.addEventListener("click", cancelClipboardPermissionEnable);
+elements.clipboardPermissionForm.addEventListener("submit", confirmClipboardPermissionEnable);
+elements.clipboardPermissionDialog.addEventListener("cancel", (event) => {
+ event.preventDefault();
+ cancelClipboardPermissionEnable();
+});
elements.pageCaptureScan.addEventListener("click", () => {
elements.pageCaptureListSetup.open = true;
elements.pageCaptureTargetCount.focus();
@@ -175,15 +208,26 @@ elements.contentType.addEventListener("change", () => updateDraft({
contentTypeId: elements.contentType.value,
contentTypeExplicit: true
}));
-elements.customLabels.addEventListener("change", () => updateDraft({
+elements.captureCollection.addEventListener("change", () => {
+ creatingCollection = elements.captureCollection.value === NEW_COLLECTION_OPTION_VALUE;
+ const collectionId = creatingCollection ? "" : elements.captureCollection.value;
+ void updateDraft({
+ ...draft,
+ collectionId,
+ newCollectionName: creatingCollection ? draft.newCollectionName : ""
+ }).then(() => {
+ if (creatingCollection) elements.captureNewCollectionName.focus();
+ });
+});
+elements.captureNewCollectionName.addEventListener("change", () => updateDraft({
...draft,
- customLabels: parseCustomLabels(elements.customLabels.value),
- customLabelsExplicit: true
+ collectionId: "",
+ newCollectionName: elements.captureNewCollectionName.value
}));
-elements.customLabels.addEventListener("keydown", (event) => {
+elements.captureNewCollectionName.addEventListener("keydown", (event) => {
if (event.key !== "Enter") return;
event.preventDefault();
- elements.customLabels.blur();
+ elements.captureNewCollectionName.blur();
});
async function openLibraryTab() {
@@ -202,12 +246,88 @@ async function openLibraryTab() {
}
}
+async function runAfterCapturePermissionOnboarding(action) {
+ const stored = await chrome.storage.local.get(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY);
+ const onboarding = normalizeCapturePermissionOnboarding(stored[CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]);
+ if (onboarding.acknowledgedAt) {
+ return action({ clipboardPreferenceJustDeclined: false });
+ }
+ const permissionStatus = await inspectCapturePermissionBundle(chrome.permissions);
+ if (permissionStatus.webCaptureGranted && permissionStatus.clipboardGranted) {
+ await chrome.storage.local.set({
+ [CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]: {
+ ...onboarding,
+ acknowledgedAt: new Date().toISOString(),
+ clipboardIncluded: true
+ }
+ });
+ return action({ clipboardPreferenceJustDeclined: false });
+ }
+ pendingCaptureAction = { action, permissionStatus };
+ elements.capturePermissionClipboard.checked = true;
+ elements.capturePermissionStatus.textContent = "";
+ elements.capturePermissionStatus.classList.remove("error");
+ elements.capturePermissionOnboarding.showModal();
+}
+
+function cancelCapturePermissionOnboarding() {
+ pendingCaptureAction = null;
+ elements.capturePermissionOnboarding.close();
+ showFeedback("已取消授权,待保存内容没有改变");
+}
+
+async function confirmCapturePermissionOnboarding(event) {
+ event.preventDefault();
+ if (!pendingCaptureAction) return elements.capturePermissionOnboarding.close();
+ const pending = pendingCaptureAction;
+ const includeClipboard = elements.capturePermissionClipboard.checked;
+ elements.capturePermissionConfirm.disabled = true;
+ elements.capturePermissionCancel.disabled = true;
+ elements.capturePermissionStatus.textContent = "正在等待 Chrome 确认…";
+ elements.capturePermissionStatus.classList.remove("error");
+ let permissionGranted = false;
+ try {
+ const permission = await requestCapturePermissionBundle(chrome.permissions, {
+ includeClipboard,
+ current: pending.permissionStatus
+ });
+ if (!permission.granted) {
+ elements.capturePermissionStatus.textContent = "未获得所选权限,待保存内容没有改变。你可以调整选择后重试。";
+ elements.capturePermissionStatus.classList.add("error");
+ return;
+ }
+ await chrome.storage.local.set({
+ [CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]: {
+ version: CAPTURE_PERMISSION_ONBOARDING_VERSION,
+ acknowledgedAt: new Date().toISOString(),
+ clipboardIncluded: includeClipboard
+ }
+ });
+ permissionGranted = true;
+ pendingCaptureAction = null;
+ } catch (error) {
+ elements.capturePermissionStatus.textContent = error?.message || "权限申请失败,待保存内容没有改变。";
+ elements.capturePermissionStatus.classList.add("error");
+ } finally {
+ elements.capturePermissionConfirm.disabled = false;
+ elements.capturePermissionCancel.disabled = false;
+ }
+ if (!permissionGranted) return;
+ elements.capturePermissionOnboarding.close();
+ try {
+ await pending.action({ clipboardPreferenceJustDeclined: !includeClipboard });
+ } catch (error) {
+ showFeedback(error?.message || "采集没有完成,待保存内容没有改变", true);
+ }
+}
+
async function refresh() {
const response = await chrome.runtime.sendMessage({ type: "GET_CAPTURE_WORKSPACE" });
if (!response?.ok) return showFeedback(response?.message || "无法读取待保存内容", true);
draft = response.draft;
targetEntry = response.targetEntry ?? null;
contentTypes = response.contentTypes ?? [];
+ collections = response.collections ?? [];
suggestedContentTypeId = response.suggestedContentTypeId || "";
partContentTypes = response.partContentTypes ?? {};
activeCreativeResult = response.activeCreativeResult ?? null;
@@ -230,7 +350,7 @@ async function tryAutoSelection() {
}
}
-async function extractClipboardOrSelection(button) {
+async function extractClipboardOrSelection(button, { clipboardPreferenceJustDeclined = false } = {}) {
await withButton(button, async () => {
try {
let selection = null;
@@ -249,26 +369,20 @@ async function extractClipboardOrSelection(button) {
return;
}
- showFeedback("当前网页没有可提取的高亮;Chrome 将询问一次剪贴板读取权限");
- if (!await ensureClipboardReadPermission(chrome.permissions)) {
- showFeedback("未获得剪贴板读取权限,未提取文字或图片", true);
- return;
- }
- let clipboardContent;
- try {
- clipboardContent = await readClipboardContentAfterFocus();
- } catch {
- showFeedback("剪贴板读取失败,请保持采集台获得焦点后再试", true);
- return;
- }
- const response = await addClipboardContentToDraft(clipboardContent);
- if (!response.added) {
- showFeedback(response.message, true);
+ const stored = await chrome.storage.local.get(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY);
+ const onboarding = normalizeCapturePermissionOnboarding(stored[CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]);
+ if (onboarding.acknowledgedAt && !onboarding.clipboardIncluded) {
+ if (clipboardPreferenceJustDeclined) {
+ showFeedback("没有网页高亮;已按你的选择保持剪贴板关闭,未读取任何内容");
+ return;
+ }
+ pendingClipboardButton = button;
+ elements.clipboardPermissionStatus.textContent = "";
+ elements.clipboardPermissionStatus.classList.remove("error");
+ elements.clipboardPermissionDialog.showModal();
return;
}
- draft = response.draft;
- showFeedback(response.message);
- await refresh();
+ await extractClipboardContent();
} catch (error) {
if (error?.draft) draft = error.draft;
if (draft) render();
@@ -277,6 +391,61 @@ async function extractClipboardOrSelection(button) {
});
}
+function cancelClipboardPermissionEnable() {
+ pendingClipboardButton = null;
+ elements.clipboardPermissionDialog.close();
+ showFeedback("剪贴板仍保持关闭,未读取任何内容");
+}
+
+async function confirmClipboardPermissionEnable(event) {
+ event.preventDefault();
+ const button = pendingClipboardButton;
+ if (!button) return elements.clipboardPermissionDialog.close();
+ elements.clipboardPermissionConfirm.disabled = true;
+ elements.clipboardPermissionCancel.disabled = true;
+ elements.clipboardPermissionStatus.textContent = "正在等待 Chrome 确认…";
+ elements.clipboardPermissionStatus.classList.remove("error");
+ try {
+ if (!await ensureClipboardReadPermission(chrome.permissions)) {
+ elements.clipboardPermissionStatus.textContent = "未获得剪贴板读取权限,未读取任何内容。";
+ elements.clipboardPermissionStatus.classList.add("error");
+ return;
+ }
+ const stored = await chrome.storage.local.get(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY);
+ const onboarding = normalizeCapturePermissionOnboarding(stored[CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]);
+ await chrome.storage.local.set({
+ [CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]: { ...onboarding, clipboardIncluded: true }
+ });
+ pendingClipboardButton = null;
+ elements.clipboardPermissionDialog.close();
+ await withButton(button, extractClipboardContent);
+ } catch (error) {
+ showFeedback(error?.message || "剪贴板提取失败,未改变待保存内容", true);
+ } finally {
+ elements.clipboardPermissionConfirm.disabled = false;
+ elements.clipboardPermissionCancel.disabled = false;
+ }
+}
+
+async function extractClipboardContent() {
+ showFeedback("正在读取你明确授权的当前剪贴板内容");
+ let clipboardContent;
+ try {
+ clipboardContent = await readClipboardContentAfterFocus();
+ } catch {
+ showFeedback("剪贴板读取失败,请保持采集台获得焦点后再试", true);
+ return;
+ }
+ const response = await addClipboardContentToDraft(clipboardContent);
+ if (!response.added) {
+ showFeedback(response.message, true);
+ return;
+ }
+ draft = response.draft;
+ showFeedback(response.message);
+ await refresh();
+}
+
async function addClipboardContentToDraft({ text: clipboardText, image } = {}) {
let nextDraft = draft;
let addedText = false;
@@ -337,6 +506,12 @@ function render() {
elements.resultPromptTitle.textContent = activeCreativePrompt?.title || "";
elements.smartSelection.hidden = !smartVisualSession;
elements.pageCapture.hidden = !pageCaptureBatch;
+ if (pageCaptureBatch) {
+ elements.pageCaptureActions.before(elements.captureMetadata);
+ } else {
+ elements.captureAddMoreActions.before(elements.captureMetadata);
+ }
+ elements.captureMetadata.hidden = !pageCaptureBatch && !view.showPreview;
elements.regionCaptureStatus.hidden = !regionCaptureState;
elements.previewState.hidden = Boolean(smartVisualSession || pageCaptureBatch || regionCaptureState) || !view.showPreview;
elements.collectorFooter.hidden = Boolean(smartVisualSession || pageCaptureBatch || regionCaptureState) || !view.showFooter;
@@ -365,7 +540,8 @@ function render() {
elements.saveDraft.disabled = saving || !view.hasContent;
elements.draftTitle.disabled = saving;
elements.contentType.disabled = saving;
- elements.customLabels.disabled = saving;
+ elements.captureCollection.disabled = saving;
+ elements.captureNewCollectionName.disabled = saving;
for (const control of [
elements.addSelection,
elements.addScreenshot,
@@ -409,9 +585,21 @@ function render() {
option.selected = true;
elements.contentType.prepend(option);
}
- if (document.activeElement !== elements.customLabels) {
- elements.customLabels.value = (draft.customLabels ?? []).join(",");
+ const selectedCollectionId = draft.collectionId && collections.some((item) => item.id === draft.collectionId)
+ ? draft.collectionId
+ : "";
+ creatingCollection = creatingCollection || Boolean(draft.newCollectionName);
+ elements.captureCollection.replaceChildren(
+ optionElement("", "不分组", !creatingCollection && !selectedCollectionId),
+ ...collections.map((item) => optionElement(item.id, item.name, !creatingCollection && item.id === selectedCollectionId)),
+ optionElement(NEW_COLLECTION_OPTION_VALUE, "+ 新建项目", creatingCollection)
+ );
+ elements.captureNewCollectionRow.hidden = !creatingCollection;
+ if (document.activeElement !== elements.captureNewCollectionName) {
+ elements.captureNewCollectionName.value = draft.newCollectionName || "";
}
+ customLabelEditor.setValues(draft.customLabels ?? []);
+ customLabelEditor.setDisabled(saving);
elements.quickPreview.replaceChildren(...createQuickPreview());
elements.addOtherCaptureMethods.open = smartVisualFallback;
elements.otherCaptureMethods.classList.toggle("fallback-highlight", smartVisualFallback);
@@ -1191,7 +1379,8 @@ async function savePageCapture(textOnly = false) {
}
const response = await chrome.runtime.sendMessage({
type: "COMMIT_PAGE_CAPTURE",
- batch: normalizePageCaptureBatch({ ...pageCaptureBatch, sessionMediaAllowed })
+ batch: normalizePageCaptureBatch({ ...pageCaptureBatch, sessionMediaAllowed }),
+ ...captureMetadataForCommit()
});
if (!response?.ok) throw new Error(response?.message || t("网页内容保存失败"));
const partial = response.results?.filter((item) => item.status === "partial" || item.status === "failed") || [];
@@ -1282,8 +1471,10 @@ async function updateDraft(value) {
if (!response?.ok) throw new Error(response?.message || "标题更新失败");
draft = response.draft;
render();
+ return draft;
} catch (error) {
showFeedback(error.message || "标题更新失败", true);
+ return null;
}
}
@@ -1309,7 +1500,12 @@ async function commitDraft(duplicateAction = "", button) {
}
render();
try {
- const response = await chrome.runtime.sendMessage({ type: "COMMIT_CAPTURE_DRAFT", duplicateAction });
+ const metadata = captureMetadataForCommit();
+ const response = await chrome.runtime.sendMessage({
+ type: "COMMIT_CAPTURE_DRAFT",
+ duplicateAction,
+ ...metadata
+ });
if (response?.duplicate) {
elements.duplicateTitle.textContent = response.existing.title;
elements.duplicatePanel.hidden = false;
@@ -1320,6 +1516,7 @@ async function commitDraft(duplicateAction = "", button) {
draft = response.draft;
targetEntry = null;
organizing = false;
+ creatingCollection = false;
elements.duplicatePanel.hidden = true;
showFeedback(response.message);
} catch (error) {
@@ -1345,6 +1542,7 @@ async function discardDraft() {
draft = response.draft;
targetEntry = null;
organizing = false;
+ creatingCollection = false;
elements.duplicatePanel.hidden = true;
showFeedback("待保存内容已清空");
render();
@@ -1420,6 +1618,25 @@ function text(value, tag = "span") {
return node;
}
+function optionElement(value, label, selected = false) {
+ const option = document.createElement("option");
+ option.value = value;
+ option.textContent = label;
+ option.selected = selected;
+ return option;
+}
+
+function captureMetadataForCommit() {
+ const selectedCollection = elements.captureCollection.value;
+ return {
+ collectionId: selectedCollection === NEW_COLLECTION_OPTION_VALUE ? "" : selectedCollection,
+ newCollectionName: selectedCollection === NEW_COLLECTION_OPTION_VALUE
+ ? elements.captureNewCollectionName.value.trim()
+ : "",
+ customLabels: customLabelEditor.values
+ };
+}
+
function hostname(value) {
try {
return new URL(value).hostname;
@@ -1428,10 +1645,6 @@ function hostname(value) {
}
}
-function parseCustomLabels(value) {
- return [...new Set(String(value ?? "").split(/[,,\n]+/).map((item) => item.trim()).filter(Boolean))];
-}
-
function camel(value) {
return value.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
}
diff --git a/curated-import.js b/curated-import.js
index 21f738e..adbfa82 100644
--- a/curated-import.js
+++ b/curated-import.js
@@ -6,6 +6,10 @@ export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {},
const packageId = clean(options.packageId);
const projectName = clean(options.projectName);
const mode = options.mode === "package" ? "package" : "case";
+ const requestedCreatedAt = clean(options.now);
+ const projectCreatedAt = requestedCreatedAt && Number.isFinite(Date.parse(requestedCreatedAt))
+ ? new Date(requestedCreatedAt).toISOString()
+ : new Date().toISOString();
if (!packageId) throw new Error("精选案例包缺少稳定编号");
if (mode === "package" && !projectName) throw new Error("精选案例包缺少项目名称");
@@ -45,7 +49,8 @@ export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {},
visualIdMap: options.visualIdMap,
sessionIdMap: options.sessionIdMap,
runIdMap: options.runIdMap,
- preserveLibraryConfiguration: true
+ preserveLibraryConfiguration: true,
+ now: projectCreatedAt
});
const entriesBySourceEntryId = {};
@@ -72,7 +77,8 @@ export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {},
name: projectName,
order: organizer.collections.length,
entryIds,
- visibility: COLLECTION_VISIBILITY.library
+ visibility: COLLECTION_VISIBILITY.library,
+ createdAt: projectCreatedAt
});
}
result.state.organizerState = normalizeOrganizerState(organizer, result.state.entries.map((entry) => entry.id));
diff --git a/curated-page.js b/curated-page.js
index 298f547..d0bd27b 100644
--- a/curated-page.js
+++ b/curated-page.js
@@ -30,7 +30,7 @@ const elements = Object.fromEntries([
"case-detail-backdrop", "case-detail-close", "case-detail-content", "case-detail-drawer", "case-detail-next", "case-detail-prev",
"clear-filters", "curated-app", "curated-search", "curated-status", "curated-status-bar", "curated-toast",
"detail-close", "detail-content", "detail-dialog", "filter-button", "filter-count", "filter-popover",
- "retry-catalog", "return-library", "sort-downloads", "sort-label", "sort-menu"
+ "retry-catalog", "return-library", "sort-downloads", "sort-menu"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
await initializeUi();
@@ -91,15 +91,8 @@ elements.clearFilters.addEventListener("click", () => {
updateFilterCount();
renderGallery();
});
-elements.sortMenu.addEventListener("click", (event) => {
- const button = event.target.closest("[data-sort]");
- if (!button || button.disabled) return;
- state.sort = button.dataset.sort;
- elements.sortLabel.textContent = button.querySelector("span").textContent;
- elements.sortMenu.querySelectorAll("[data-sort]").forEach((candidate) => {
- candidate.setAttribute("aria-current", String(candidate === button));
- });
- elements.sortMenu.open = false;
+elements.sortMenu.addEventListener("change", () => {
+ state.sort = elements.sortMenu.value;
renderGallery();
});
document.addEventListener("click", (event) => {
@@ -107,7 +100,6 @@ document.addEventListener("click", (event) => {
elements.filterPopover.hidden = true;
elements.filterButton.setAttribute("aria-expanded", "false");
}
- if (!event.target.closest(".sort-menu")) elements.sortMenu.open = false;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && state.selectedEntryId) {
@@ -205,7 +197,7 @@ function updateMetricsUi() {
elements.sortDownloads.disabled = !state.metrics;
if (!state.metrics && state.sort === "downloads") {
state.sort = "recommended";
- elements.sortLabel.textContent = t("推荐");
+ elements.sortMenu.value = "recommended";
}
}
diff --git a/curated.css b/curated.css
index 6b3408a..297fcc0 100644
--- a/curated.css
+++ b/curated.css
@@ -18,7 +18,7 @@ body { min-width: 320px; }
.curated-header-actions button { min-height: 34px; }
.tool-button, .page-back-action { display: inline-flex; align-items: center; gap: 7px; }
.tool-button .ui-icon, .page-back-action .ui-icon { width: 15px; height: 15px; }
-.filter-wrap, .sort-menu { position: relative; }
+.filter-wrap { position: relative; }
.menu-panel { position: absolute; z-index: 30; top: calc(100% + 7px); right: 0; display: grid; border: 1px solid var(--ui-border-strong); border-radius: var(--curated-radius); padding: 5px; background: var(--ui-surface); box-shadow: var(--ui-shadow); }
.menu-panel[hidden] { display: none; }
.filter-panel { width: 210px; gap: 4px; padding: 9px; }
@@ -26,15 +26,7 @@ body { min-width: 320px; }
.filter-panel label { display: flex; min-height: 32px; align-items: center; gap: 8px; font-size: var(--ui-button-size); }
.filter-panel input { width: 15px; min-height: 15px; accent-color: var(--ui-accent); }
.filter-panel button { margin-top: 4px; }
-.sort-menu > summary { display: flex; min-width: 76px; min-height: 34px; align-items: center; justify-content: space-between; gap: 8px; padding: 7px 9px; cursor: pointer; font-size: var(--ui-button-size); font-weight: 750; list-style: none; }
-.sort-menu > summary::-webkit-details-marker { display: none; }
-.sort-menu > summary .ui-icon { width: 14px; height: 14px; transition: transform var(--ui-motion-fast) ease; }
-.sort-menu[open] > summary .ui-icon { transform: rotate(180deg); }
-.sort-panel { width: 110px; gap: 2px; }
-.sort-panel button { display: flex; min-height: 32px; align-items: center; justify-content: space-between; border: 0; padding: 5px 9px; color: var(--ui-text); background: transparent; text-align: left; }
-.sort-panel button:hover:not(:disabled), .sort-panel button[aria-current="true"] { background: var(--ui-hover); }
-.sort-panel .sort-check { display: none; width: 14px; height: 14px; }
-.sort-panel button[aria-current="true"] .sort-check { display: block; }
+.curated-sort select { width: 110px; min-height: 34px; padding-block: 5px; font-size: var(--ui-button-size); font-weight: 750; }
.curated-status-bar { position: sticky; z-index: 15; top: 58px; display: flex; min-height: 38px; align-items: center; justify-content: space-between; gap: 12px; border-bottom: 1px solid var(--ui-border); padding: 5px max(12px, calc((100vw - var(--curated-max-width)) / 2)); color: var(--ui-muted); background: var(--ui-raised); font-size: var(--ui-meta-size); }
.curated-status-bar[hidden] { display: none; }
diff --git a/curated.html b/curated.html
index b1bb883..0395a4c 100644
--- a/curated.html
+++ b/curated.html
@@ -27,14 +27,7 @@
<button id="clear-filters" type="button" data-i18n="清除筛选">清除筛选</button>
</div>
</div>
- <details id="sort-menu" class="sort-menu">
- <summary class="button-secondary"><span id="sort-label" data-i18n="推荐">推荐</span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-chevron-down"></use></svg></summary>
- <div class="menu-panel sort-panel">
- <button type="button" data-sort="recommended" aria-current="true"><span data-i18n="推荐">推荐</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
- <button type="button" data-sort="latest" aria-current="false"><span data-i18n="最新">最新</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
- <button id="sort-downloads" type="button" data-sort="downloads" aria-current="false" disabled><span data-i18n="下载">下载</span><svg class="ui-icon sort-check" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
- </div>
- </details>
+ <label class="curated-sort"><span class="visually-hidden">精选案例排序</span><select id="sort-menu" aria-label="精选案例排序"><option value="recommended" data-i18n="推荐">推荐</option><option value="latest" data-i18n="最新">最新</option><option id="sort-downloads" value="downloads" data-i18n="下载" disabled>下载</option></select></label>
<button id="return-library" class="button-secondary page-back-action" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-arrow-left"></use></svg><span data-i18n="返回案例库">返回案例库</span></button>
</div>
</header>
diff --git a/extension-update.js b/extension-update.js
new file mode 100644
index 0000000..ad05f7c
--- /dev/null
+++ b/extension-update.js
@@ -0,0 +1,332 @@
+export const EXTENSION_UPDATE_STORAGE_KEY = "extensionUpdateState";
+export const EXTENSION_UPDATE_STATUS_CHANGED = "EXTENSION_UPDATE_STATUS_CHANGED";
+
+const STATE_VERSION = 1;
+const CHECK_STATUSES = new Set(["no_update", "update_available", "throttled"]);
+
+export function parseExtensionVersion(value) {
+ const source = String(value ?? "");
+ if (!/^\d+(?:\.\d+){0,3}$/u.test(source)) return null;
+ const parts = source.split(".");
+ if (parts.some((part) => (part.length > 1 && part.startsWith("0")) || Number(part) > 65_535)) {
+ return null;
+ }
+ const numbers = parts.map(Number);
+ if (numbers.every((part) => part === 0)) return null;
+ return [...numbers, ...Array(4 - numbers.length).fill(0)];
+}
+
+export function compareExtensionVersions(left, right) {
+ const leftParts = parseExtensionVersion(left);
+ const rightParts = parseExtensionVersion(right);
+ if (!leftParts || !rightParts) {
+ throw new TypeError("扩展版本号格式无效");
+ }
+ for (let index = 0; index < 4; index += 1) {
+ if (leftParts[index] > rightParts[index]) return 1;
+ if (leftParts[index] < rightParts[index]) return -1;
+ }
+ return 0;
+}
+
+export function extensionUpdateChannel(manifest = {}) {
+ return typeof manifest.key === "string" && manifest.key.trim() ? "development" : "store";
+}
+
+export function githubLatestReleaseUrl(homepageUrl) {
+ try {
+ const url = new URL(String(homepageUrl ?? ""));
+ if (url.protocol !== "https:" || url.hostname !== "github.com") return "";
+ const pathParts = url.pathname.split("/").filter(Boolean);
+ if (pathParts.length !== 2) return "";
+ url.search = "";
+ url.hash = "";
+ url.pathname = `/${pathParts.join("/")}/releases/latest`;
+ return url.toString();
+ } catch {
+ return "";
+ }
+}
+
+function safeGithubReleaseUrl(value, homepageUrl) {
+ const latestUrl = githubLatestReleaseUrl(homepageUrl);
+ if (!latestUrl) return "";
+ try {
+ const candidate = new URL(String(value ?? ""));
+ const latest = new URL(latestUrl);
+ const repositoryPath = latest.pathname.replace(/\/releases\/latest$/u, "");
+ const isRepositoryRelease = candidate.protocol === "https:"
+ && candidate.hostname === "github.com"
+ && (candidate.pathname === `${repositoryPath}/releases/latest`
+ || candidate.pathname.startsWith(`${repositoryPath}/releases/tag/`));
+ return isRepositoryRelease ? candidate.toString() : latestUrl;
+ } catch {
+ return latestUrl;
+ }
+}
+
+export function releaseVersionFromUrl(releaseUrl) {
+ try {
+ const url = new URL(String(releaseUrl ?? ""));
+ const match = url.pathname.match(/\/releases\/tag\/([^/]+)\/?$/u);
+ if (!match) return "";
+ const tag = decodeURIComponent(match[1]);
+ const version = tag.match(/^v?(\d+(?:\.\d+){0,3})$/u)?.[1] ?? "";
+ return parseExtensionVersion(version) ? version : "";
+ } catch {
+ return "";
+ }
+}
+
+function normalizeTimestamp(value) {
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
+}
+
+function validVersionOrEmpty(value) {
+ const version = String(value ?? "");
+ return parseExtensionVersion(version) ? version : "";
+}
+
+function normalizedState(stored, manifest) {
+ const currentVersion = validVersionOrEmpty(manifest?.version);
+ if (!currentVersion) throw new Error("当前扩展版本号无效");
+ const channel = extensionUpdateChannel(manifest);
+ const source = stored && typeof stored === "object" ? stored : {};
+ let pendingVersion = validVersionOrEmpty(source.pendingVersion);
+ let latestVersion = validVersionOrEmpty(source.latestVersion);
+
+ if (channel !== "store" || (pendingVersion && compareExtensionVersions(pendingVersion, currentVersion) <= 0)) {
+ pendingVersion = "";
+ }
+ if (channel !== "development") latestVersion = "";
+
+ const releaseUrl = channel === "development"
+ ? safeGithubReleaseUrl(source.releaseUrl, manifest.homepage_url)
+ : "";
+ const storeUpdateAvailable = channel === "store" && Boolean(pendingVersion);
+ const developmentUpdateAvailable = channel === "development"
+ && Boolean(latestVersion)
+ && compareExtensionVersions(latestVersion, currentVersion) > 0;
+ const updateAvailable = storeUpdateAvailable || developmentUpdateAvailable;
+
+ return {
+ stateVersion: STATE_VERSION,
+ channel,
+ currentVersion,
+ pendingVersion,
+ latestVersion,
+ updateAvailable,
+ updateKind: storeUpdateAvailable
+ ? "store_downloaded"
+ : developmentUpdateAvailable ? "development_release" : null,
+ releaseUrl,
+ checkedAt: normalizeTimestamp(source.checkedAt),
+ checkStatus: ["idle", ...CHECK_STATUSES, "error"].includes(source.checkStatus)
+ ? source.checkStatus
+ : "idle",
+ lastError: String(source.lastError ?? ""),
+ installedVersion: validVersionOrEmpty(source.installedVersion) || currentVersion,
+ installedAt: normalizeTimestamp(source.installedAt),
+ canApply: storeUpdateAvailable || developmentUpdateAvailable,
+ applyBehavior: developmentUpdateAvailable
+ ? "reload_development_directory"
+ : storeUpdateAvailable ? "install_downloaded_update" : null
+ };
+}
+
+function persistedState(status) {
+ const { canApply: _canApply, applyBehavior: _applyBehavior, ...stored } = status;
+ return stored;
+}
+
+function errorMessage(error) {
+ return error instanceof Error ? error.message : String(error || "检查更新失败");
+}
+
+export function createExtensionUpdateLifecycle({
+ runtime,
+ storage,
+ fetchFn = globalThis.fetch,
+ now = () => Date.now(),
+ notify = () => undefined,
+ scheduleReload = (reload) => setTimeout(reload, 100)
+} = {}) {
+ if (!runtime?.getManifest || !storage?.get || !storage?.set) {
+ throw new TypeError("扩展更新服务缺少 runtime 或 storage");
+ }
+
+ let operationQueue = Promise.resolve();
+ const runExclusive = (operation) => {
+ const run = operationQueue.then(operation, operation);
+ operationQueue = run.catch(() => undefined);
+ return run;
+ };
+
+ async function readStatus() {
+ const manifest = runtime.getManifest();
+ const stored = await storage.get(EXTENSION_UPDATE_STORAGE_KEY);
+ return normalizedState(stored?.[EXTENSION_UPDATE_STORAGE_KEY], manifest);
+ }
+
+ async function writeStatus(status) {
+ const normalized = normalizedState(status, runtime.getManifest());
+ await storage.set({ [EXTENSION_UPDATE_STORAGE_KEY]: persistedState(normalized) });
+ await Promise.resolve(notify(normalized)).catch(() => undefined);
+ return normalized;
+ }
+
+ async function checkDevelopmentRelease() {
+ const status = await readStatus();
+ const releaseLookupUrl = githubLatestReleaseUrl(runtime.getManifest().homepage_url);
+ if (!releaseLookupUrl) {
+ return writeStatus({
+ ...status,
+ checkedAt: now(),
+ checkStatus: "error",
+ lastError: "扩展主页未配置有效的版本发布地址"
+ });
+ }
+ try {
+ if (typeof fetchFn !== "function") throw new Error("当前环境无法联网检查版本");
+ const response = await fetchFn(releaseLookupUrl, {
+ method: "HEAD",
+ redirect: "follow",
+ cache: "no-store"
+ });
+ if (!response?.ok) throw new Error(`版本发布页返回 ${response?.status || "未知状态"}`);
+ const resolvedReleaseUrl = safeGithubReleaseUrl(response.url, runtime.getManifest().homepage_url);
+ const latestVersion = releaseVersionFromUrl(resolvedReleaseUrl);
+ if (!latestVersion) throw new Error("最新发布标签不是有效的 Chrome 扩展版本号");
+ const updateAvailable = compareExtensionVersions(latestVersion, status.currentVersion) > 0;
+ return writeStatus({
+ ...status,
+ latestVersion,
+ releaseUrl: resolvedReleaseUrl,
+ checkedAt: now(),
+ checkStatus: updateAvailable ? "update_available" : "no_update",
+ lastError: ""
+ });
+ } catch (error) {
+ return writeStatus({
+ ...status,
+ releaseUrl: releaseLookupUrl,
+ checkedAt: now(),
+ checkStatus: "error",
+ lastError: errorMessage(error)
+ });
+ }
+ }
+
+ async function checkStoreUpdate() {
+ const status = await readStatus();
+ try {
+ if (typeof runtime.requestUpdateCheck !== "function") {
+ throw new Error("当前 Chrome 不支持手动检查扩展更新");
+ }
+ const result = await runtime.requestUpdateCheck();
+ const requestStatus = String(result?.status ?? "");
+ if (!CHECK_STATUSES.has(requestStatus)) throw new Error("Chrome 返回了未知的更新检查状态");
+ let pendingVersion = status.pendingVersion;
+ if (requestStatus === "update_available") {
+ pendingVersion = validVersionOrEmpty(result?.version);
+ if (!pendingVersion || compareExtensionVersions(pendingVersion, status.currentVersion) <= 0) {
+ throw new Error("Chrome 返回的待更新版本无效");
+ }
+ }
+ return writeStatus({
+ ...status,
+ pendingVersion,
+ checkedAt: now(),
+ checkStatus: requestStatus,
+ lastError: ""
+ });
+ } catch (error) {
+ return writeStatus({
+ ...status,
+ checkedAt: now(),
+ checkStatus: "error",
+ lastError: errorMessage(error)
+ });
+ }
+ }
+
+ return Object.freeze({
+ getStatus() {
+ return runExclusive(readStatus);
+ },
+
+ check() {
+ return runExclusive(async () => extensionUpdateChannel(runtime.getManifest()) === "development"
+ ? checkDevelopmentRelease()
+ : checkStoreUpdate());
+ },
+
+ handleStartup() {
+ if (extensionUpdateChannel(runtime.getManifest()) !== "development") return runExclusive(readStatus);
+ return runExclusive(checkDevelopmentRelease);
+ },
+
+ handleUpdateAvailable(details) {
+ return runExclusive(async () => {
+ const status = await readStatus();
+ if (status.channel !== "store") return status;
+ const pendingVersion = validVersionOrEmpty(details?.version);
+ if (!pendingVersion || compareExtensionVersions(pendingVersion, status.currentVersion) <= 0) {
+ return status;
+ }
+ return writeStatus({
+ ...status,
+ pendingVersion,
+ checkedAt: now(),
+ checkStatus: "update_available",
+ lastError: ""
+ });
+ });
+ },
+
+ handleInstalled(details) {
+ return runExclusive(async () => {
+ const status = await readStatus();
+ if (details?.reason !== "update") return status;
+ return writeStatus({
+ ...status,
+ pendingVersion: "",
+ latestVersion: "",
+ checkedAt: now(),
+ checkStatus: "no_update",
+ lastError: "",
+ installedVersion: status.currentVersion,
+ installedAt: now()
+ });
+ });
+ },
+
+ apply() {
+ return runExclusive(async () => {
+ const status = await readStatus();
+ if (!status.canApply || !status.applyBehavior) {
+ return {
+ ok: false,
+ status,
+ willReload: false,
+ installsUpdate: false,
+ message: status.channel === "store"
+ ? "Chrome 尚未下载可安装的更新"
+ : "当前目录已是最新版本"
+ };
+ }
+ scheduleReload(() => runtime.reload());
+ const installsUpdate = status.channel === "store";
+ return {
+ ok: true,
+ status,
+ willReload: true,
+ installsUpdate,
+ message: installsUpdate
+ ? "即将重载并应用 Chrome 已下载的更新"
+ : "即将重载当前开发目录;这不会下载或安装新版本"
+ };
+ });
+ }
+ });
+}
diff --git a/i18n.js b/i18n.js
index 650e606..6548ba6 100644
--- a/i18n.js
+++ b/i18n.js
@@ -281,7 +281,7 @@ const EN = Object.freeze({
"浏览器会把文件保存到“下载”目录下;可填写子文件夹。": "Chrome saves the file in Downloads. Subfolders are supported.",
"保存设置": "Save settings",
"展开或收起筛选": "Show or hide filters",
- "搜索提示词、来源或创作属性": "Search prompts, sources, or creative attributes",
+ "搜索提示词、来源或 AI 标签": "Search prompts, sources, or AI tags",
"搜索画面、提示词、风格、镜头…": "Search visuals, prompts, styles, shots...",
"正在读取本地案例…": "Loading local cases...",
"开始创作": "Create",
diff --git a/import-jobs.js b/import-jobs.js
index f85d321..adc6003 100644
--- a/import-jobs.js
+++ b/import-jobs.js
@@ -13,17 +13,22 @@ export function normalizeImportJobsState(value = {}, options = {}) {
export function normalizeImportJob(value, { recoverRunning = false } = {}) {
const id = clean(value?.id);
if (!id) return null;
+ const createdAt = clean(value?.createdAt);
+ const importBatchId = clean(value?.importBatchId) || id;
+ const libraryAddedAt = clean(value?.libraryAddedAt) || createdAt;
const items = (Array.isArray(value?.items) ? value.items : [])
- .map((item) => normalizeImportItem(item, { recoverRunning }))
+ .map((item) => normalizeImportItem(item, { importBatchId, libraryAddedAt }))
.filter(Boolean);
let status = JOB_STATUSES.has(value?.status) ? value.status : "queued";
if (recoverRunning && status === "running") status = "queued";
return {
id,
+ importBatchId,
status,
collectionId: clean(value?.collectionId),
- createdAt: clean(value?.createdAt),
+ createdAt,
updatedAt: clean(value?.updatedAt),
+ ...(libraryAddedAt ? { libraryAddedAt } : {}),
...(clean(value?.retryOf) ? { retryOf: clean(value.retryOf) } : {}),
...(clean(value?.undoneAt) ? { undoneAt: clean(value.undoneAt) } : {}),
...(clean(value?.analysisQueuedAt) ? { analysisQueuedAt: clean(value.analysisQueuedAt) } : {}),
@@ -55,7 +60,8 @@ export function createImportJob(stateValue, request = {}, options = {}) {
? request.items.map((item) => ({
stagedAssetId: clean(item?.stagedAssetId),
duplicateAssetId: clean(item?.duplicateAssetId),
- keepDuplicate: item?.keepDuplicate === true
+ keepDuplicate: item?.keepDuplicate === true,
+ libraryAddedAt: clean(item?.libraryAddedAt)
})).filter((item) => item.stagedAssetId)
: uniqueStrings(request.stagedAssetIds).map((stagedAssetId) => ({ stagedAssetId }));
const importItems = [...new Map(requestedItems.map((item) => [item.stagedAssetId, item])).values()];
@@ -64,8 +70,13 @@ export function createImportJob(stateValue, request = {}, options = {}) {
const makeItemId = typeof options.itemId === "function"
? options.itemId
: () => `import-item:${crypto.randomUUID()}`;
+ const jobId = clean(options.id) || `import-job:${crypto.randomUUID()}`;
+ const importBatchId = clean(request.importBatchId) || jobId;
+ const libraryAddedAt = clean(request.libraryAddedAt) || now;
const job = normalizeImportJob({
- id: clean(options.id) || `import-job:${crypto.randomUUID()}`,
+ id: jobId,
+ importBatchId,
+ libraryAddedAt,
collectionId: request.collectionId,
status: importItems.some((item) => !item.duplicateAssetId || item.keepDuplicate) ? "queued" : "completed",
createdAt: now,
@@ -75,6 +86,8 @@ export function createImportJob(stateValue, request = {}, options = {}) {
items: importItems.map((item) => ({
id: makeItemId(item.stagedAssetId),
stagedAssetId: item.stagedAssetId,
+ importBatchId,
+ libraryAddedAt: item.libraryAddedAt || libraryAddedAt,
status: item.duplicateAssetId && !item.keepDuplicate ? "skipped" : "queued",
...(item.duplicateAssetId && !item.keepDuplicate ? { skipReason: "duplicate" } : {})
}))
@@ -163,6 +176,8 @@ export function retryImportJob(stateValue, jobId, options = {}) {
: () => `import-item:${crypto.randomUUID()}`;
const job = normalizeImportJob({
id: clean(options.id) || `import-job:${crypto.randomUUID()}`,
+ importBatchId: source.importBatchId,
+ libraryAddedAt: source.libraryAddedAt,
retryOf: source.id,
collectionId: source.collectionId,
status: "queued",
@@ -171,6 +186,8 @@ export function retryImportJob(stateValue, jobId, options = {}) {
items: failed.map((item) => ({
id: makeItemId(item.stagedAssetId),
stagedAssetId: item.stagedAssetId,
+ importBatchId: item.importBatchId,
+ libraryAddedAt: item.libraryAddedAt,
status: "queued"
})),
options: source.options
@@ -178,7 +195,7 @@ export function retryImportJob(stateValue, jobId, options = {}) {
return { state: { ...state, items: [...state.items, job] }, job };
}
-function normalizeImportItem(value, { recoverRunning = false } = {}) {
+function normalizeImportItem(value, defaults = {}) {
const id = clean(value?.id);
const stagedAssetId = clean(value?.stagedAssetId);
if (!id || !stagedAssetId) return null;
@@ -186,6 +203,10 @@ function normalizeImportItem(value, { recoverRunning = false } = {}) {
return {
id,
stagedAssetId,
+ importBatchId: clean(value?.importBatchId) || clean(defaults.importBatchId),
+ ...(clean(value?.libraryAddedAt) || clean(defaults.libraryAddedAt)
+ ? { libraryAddedAt: clean(value?.libraryAddedAt) || clean(defaults.libraryAddedAt) }
+ : {}),
status,
...(clean(value?.entryId) ? { entryId: clean(value.entryId) } : {}),
...(clean(value?.skipReason) ? { skipReason: clean(value.skipReason) } : {}),
@@ -216,5 +237,10 @@ function uniqueStrings(value) {
function normalizeOptions(value) {
if (!value || typeof value !== "object") return {};
const duplicateAction = value.duplicateAction === "skip" ? "skip" : "import";
- return { duplicateAction, autoAnalyze: value.autoAnalyze === true };
+ const customLabels = uniqueStrings(value.customLabels);
+ return {
+ duplicateAction,
+ autoAnalyze: value.autoAnalyze === true,
+ ...(customLabels.length ? { customLabels } : {})
+ };
}
diff --git a/import-staging.js b/import-staging.js
index 7b1b394..5843025 100644
--- a/import-staging.js
+++ b/import-staging.js
@@ -1,6 +1,17 @@
-import { normalizeLocalRelativePath } from "./local-media.js";
+import {
+ LOCAL_ASSET_REFERENCE_RECORD_TYPE,
+ normalizeLocalRelativePath
+} from "./local-media.js";
+import {
+ SUPPORTED_ASSET_KINDS,
+ assetFormatForExtension,
+ assetFormatForFile,
+ fileExtension,
+ isReportedMimeCompatible
+} from "./asset-formats.js";
+import { ASSET_IMPORT_FAILURE_CODES } from "./resource-limits.js";
-const KINDS = new Set(["image", "video", "document"]);
+const KINDS = new Set(SUPPORTED_ASSET_KINDS);
export function normalizeImportStagingState(value = {}) {
return {
@@ -27,7 +38,9 @@ export function removeStagedAsset(stateValue, stagedAssetId) {
return {
state: { ...state, assets: state.assets.filter((item) => item.id !== id) },
asset,
- removedAssetIds: [...new Set([asset.assetId, asset.posterAssetId].filter(Boolean))]
+ removedAssetIds: asset.recordType === LOCAL_ASSET_REFERENCE_RECORD_TYPE
+ ? []
+ : [...new Set([asset.assetId, asset.posterAssetId].filter(Boolean))]
};
}
@@ -68,9 +81,15 @@ function normalizeStagedAsset(value) {
const name = fileName(value?.name);
const kind = KINDS.has(value?.kind) ? value.kind : "";
const mimeType = clean(value?.mimeType).toLocaleLowerCase("en-US");
+ const requestedSourceFormat = clean(value?.sourceFormat).toLocaleLowerCase("en-US").replace(/^\./u, "");
+ const format = assetFormatForExtension(requestedSourceFormat) ?? assetFormatForFile({ name, type: mimeType });
const byteSize = Math.max(0, Math.floor(Number(value?.byteSize) || 0));
const contentHash = clean(value?.contentHash).toLocaleLowerCase("en-US");
- if (!id || !assetId || !name || !kind || !mimeType || !byteSize || !/^[a-f0-9]{64}$/u.test(contentHash)) return null;
+ const matchesSupportedFormat = Boolean(format && format.kind === kind && isReportedMimeCompatible(format, mimeType));
+ const localReference = normalizeUnsupportedLocalReference(value, { kind, matchesSupportedFormat });
+ if (!id || !assetId || !name || !kind || !mimeType || !byteSize) return null;
+ if (!localReference && !/^[a-f0-9]{64}$/u.test(contentHash)) return null;
+ if (!localReference && !matchesSupportedFormat) return null;
let relativePath;
try {
relativePath = normalizeLocalRelativePath(value?.relativePath, name);
@@ -83,16 +102,22 @@ function normalizeStagedAsset(value) {
name,
relativePath,
kind,
+ storageMode: kind === "attachment" && value?.storageMode === "reference" ? "reference" : "managed",
mimeType,
byteSize,
- contentHash,
+ ...(nonNegativeIntegerOrNull(value?.sourceLastModified) !== null
+ ? { sourceLastModified: nonNegativeIntegerOrNull(value.sourceLastModified) }
+ : {}),
+ ...(contentHash ? { contentHash } : {}),
+ sourceFormat: requestedSourceFormat || fileExtension(name),
+ formatCategory: localReference ? "local-link" : format.category,
+ ...(localReference ?? {}),
...(positiveInteger(value?.width) ? { width: positiveInteger(value.width) } : {}),
...(positiveInteger(value?.height) ? { height: positiveInteger(value.height) } : {}),
...(positiveInteger(value?.durationMs) ? { durationMs: positiveInteger(value.durationMs) } : {}),
...(clean(value?.playbackCapability) ? { playbackCapability: clean(value.playbackCapability) } : {}),
...(clean(value?.contentText) ? { contentText: clean(value.contentText) } : {}),
...(["markdown", "plain"].includes(value?.contentFormat) ? { contentFormat: value.contentFormat } : {}),
- ...(clean(value?.sourceFormat) ? { sourceFormat: clean(value.sourceFormat) } : {}),
...(Array.isArray(value?.warnings) ? { warnings: [...new Set(value.warnings.map(clean).filter(Boolean))] } : {}),
...(clean(value?.posterAssetId) ? { posterAssetId: clean(value.posterAssetId) } : {}),
...(normalizePoster(value?.posterAsset) ? { posterAsset: normalizePoster(value.posterAsset) } : {}),
@@ -100,6 +125,56 @@ function normalizeStagedAsset(value) {
};
}
+function normalizeUnsupportedLocalReference(value, context) {
+ if (context.kind !== "attachment" || value?.storageMode !== "reference" || !["relink-required", "linked"].includes(value?.linkStatus)) {
+ return null;
+ }
+ if (value?.recordType !== LOCAL_ASSET_REFERENCE_RECORD_TYPE) return null;
+ if (context.matchesSupportedFormat) return null;
+ if (value?.importFailure?.code !== ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT) return null;
+ const message = clean(value.importFailure.message);
+ if (!message) return null;
+ return {
+ recordType: LOCAL_ASSET_REFERENCE_RECORD_TYPE,
+ linkStatus: value.linkStatus,
+ importFailure: {
+ code: ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT,
+ message,
+ forceAllowed: false
+ }
+ };
+}
+
+export function stagedAssetMediaRecord(value, options = {}) {
+ const staged = normalizeStagedAsset(value);
+ if (!staged) throw new Error("暂存资料缺少有效元数据");
+ const capturedAt = clean(options.capturedAt) || new Date().toISOString();
+ return {
+ id: staged.assetId,
+ kind: staged.kind,
+ storageMode: staged.storageMode,
+ mimeType: staged.mimeType,
+ byteSize: staged.byteSize,
+ sourceTitle: staged.name,
+ relativePath: staged.relativePath,
+ sourceFormat: staged.sourceFormat,
+ formatCategory: staged.formatCategory,
+ ...(staged.contentHash ? { contentHash: staged.contentHash } : {}),
+ ...(staged.sourceLastModified !== undefined ? { sourceLastModified: staged.sourceLastModified } : {}),
+ ...(staged.recordType ? { recordType: staged.recordType } : {}),
+ ...(staged.linkStatus ? { linkStatus: staged.linkStatus } : {}),
+ ...(staged.importFailure ? { importFailure: structuredClone(staged.importFailure) } : {}),
+ capturedAt,
+ reviewStatus: staged.storageMode === "reference" ? "unverified" : "verified",
+ ...(staged.width ? { width: staged.width } : {}),
+ ...(staged.height ? { height: staged.height } : {}),
+ ...(staged.durationMs ? { durationMs: staged.durationMs } : {}),
+ ...(staged.playbackCapability ? { playbackCapability: staged.playbackCapability } : {}),
+ ...(staged.kind === "document" && staged.contentFormat ? { extractedTextFormat: staged.contentFormat } : {}),
+ ...(staged.posterAssetId ? { posterAssetId: staged.posterAssetId } : {})
+ };
+}
+
function normalizePoster(value) {
if (!value || typeof value !== "object") return null;
const id = clean(value.id);
@@ -128,6 +203,11 @@ function positiveInteger(value) {
return Number.isSafeInteger(number) && number > 0 ? number : 0;
}
+function nonNegativeIntegerOrNull(value) {
+ const number = Number(value);
+ return Number.isSafeInteger(number) && number >= 0 ? number : null;
+}
+
function clean(value) {
return String(value ?? "").trim();
}
diff --git a/lib.js b/lib.js
index 8ea9c03..db7cc27 100644
--- a/lib.js
+++ b/lib.js
@@ -74,20 +74,22 @@ export function normalizeSettings(value = {}, defaults = DEFAULT_SETTINGS) {
};
}
-export function buildEntry({ text, title, url, savedAt, allowEmptyText = false }) {
+export function buildEntry({ text, title, url, savedAt, libraryAddedAt, allowEmptyText = false }) {
const normalizedText = normalizeSelection(text);
if (!normalizedText && !allowEmptyText) {
throw new Error("没有检测到高亮文字");
}
const parsedUrl = safeUrl(url);
+ const now = new Date().toISOString();
return {
id: globalThis.crypto.randomUUID(),
text: normalizedText,
textRevision: 1,
title: String(title ?? "").trim() || parsedUrl?.hostname || "未命名网页",
url: parsedUrl?.href || "",
- savedAt: savedAt ?? new Date().toISOString()
+ savedAt: savedAt ?? now,
+ libraryAddedAt: libraryAddedAt ?? now
};
}
@@ -287,9 +289,9 @@ function renderEntry(entry, index, taxonomy, facetCatalog, locale) {
`- 保存时间:${date}`,
...screenshot,
"",
- ...(attributeLines.length ? ["### 创作属性", "", ...attributeLines, ""] : []),
+ ...(attributeLines.length ? ["### AI 标签", "", ...attributeLines, ""] : []),
...(visionDescription ? ["### 画面描述", "", `${visionFence}text`, visionDescription, visionFence, ""] : []),
- ...(entry.text ? ["### 原始提示词", "", `${fence}text`, entry.text, fence] : ["### 案例说明", "", "这是一条仅包含截图和创作属性的图片案例。"]),
+ ...(entry.text ? ["### 原始提示词", "", `${fence}text`, entry.text, fence] : ["### 案例说明", "", "这是一条仅包含截图和 AI 标签的图片案例。"]),
...(suggestionLines.length ? ["", "### 待确认建议", "", ...suggestionLines] : [])
].join("\n");
}
diff --git a/library-package-format.js b/library-package-format.js
index 31a0438..ac30ebe 100644
--- a/library-package-format.js
+++ b/library-package-format.js
@@ -1,6 +1,6 @@
export const LIBRARY_PACKAGE_FORMAT = "prompt-case-library";
-export const CURRENT_LIBRARY_PACKAGE_VERSION = 3;
-export const SUPPORTED_LIBRARY_PACKAGE_VERSIONS = Object.freeze([1, 2, 3]);
+export const CURRENT_LIBRARY_PACKAGE_VERSION = 4;
+export const SUPPORTED_LIBRARY_PACKAGE_VERSIONS = Object.freeze([1, 2, 3, 4]);
export function isSupportedLibraryPackageVersion(value) {
return Number.isInteger(value) && SUPPORTED_LIBRARY_PACKAGE_VERSIONS.includes(value);
diff --git a/library-package.js b/library-package.js
index e12f139..d3c5c32 100644
--- a/library-package.js
+++ b/library-package.js
@@ -14,6 +14,11 @@ import { migrateLibraryState } from "./migration.js";
import { LIBRARY_PACKAGE_FORMAT, isSupportedLibraryPackageVersion } from "./library-package-format.js";
import { remapArticleDocumentAssets } from "./article-document.js";
import { boundedMediaBlobFromResponse, isSupportedDocumentMimeType } from "./bounded-media.js";
+import {
+ assetFormatForExtension,
+ fileExtension,
+ isReportedMimeCompatible
+} from "./asset-formats.js";
export async function parseCompleteFolderBackup(value, files = new Map(), limitsValue = {}) {
const preparedFiles = new Map(files);
@@ -50,8 +55,22 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
const assets = new Map();
const images = new Map();
const skillAssets = new Map();
+ if (value.version >= 4) {
+ for (const entry of data.entries) {
+ for (const asset of Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : []) {
+ if (asset?.storageMode === "reference") continue;
+ validatePortableMediaDescriptor(asset, clean(asset?.assetPath), value.version);
+ }
+ }
+ }
data.entries = data.entries.map((entry) => {
const normalized = normalizeEntryVisuals(entry);
+ if (value.version >= 4) {
+ const normalizedIds = new Set(normalized.mediaAssets.map((asset) => asset.id));
+ const missingAsset = (Array.isArray(entry?.mediaAssets) ? entry.mediaAssets : [])
+ .find((asset) => asset?.storageMode !== "reference" && clean(asset?.id) && !normalizedIds.has(clean(asset.id)));
+ if (missingAsset) throw new Error("案例包包含无法安全规范化的媒体描述");
+ }
normalized.customLabels = uniqueNames(entry?.customLabels);
normalized.metadataLabels = uniqueNames(entry?.metadataLabels);
return normalized;
@@ -71,9 +90,9 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})
visualIds.add(asset.id);
if (asset.storageMode === "reference") continue;
const path = clean(asset.assetPath);
- if (!validMediaPath(path, asset.kind)) throw new Error(`“${entry.title || "未命名案例"}”的媒体路径无效`);
+ const format = validatePortableMediaDescriptor(asset, path, value.version);
const blob = files.get(path);
- if (!(blob instanceof Blob) || !blobMatchesKind(blob, asset.kind)) {
+ if (!(blob instanceof Blob) || !blobMatchesKind(blob, asset, format, value.version)) {
throw new Error(asset.kind === "image"
? `“${entry.title || "未命名案例"}”的截图缺失`
: `“${entry.title || "未命名案例"}”的媒体文件缺失或类型不符`);
@@ -244,21 +263,43 @@ export function selectProjectPackage(state = {}, collectionId) {
const collection = organizer.collections.find((item) => item.id === clean(collectionId));
if (!collection) throw new Error("项目不存在");
if (!collection.entryIds.length) throw new Error("这个项目还没有可分享的案例");
- const selected = selectLibraryPackage(state, collection.entryIds);
+ const exportedEntryIds = projectPackageEntryIds(state, collection.id);
+ const selected = selectLibraryPackage(state, exportedEntryIds);
selected.organizerState = normalizeOrganizerState({
version: organizer.version,
collections: [{
id: collection.id,
name: collection.name,
order: 0,
- entryIds: collection.entryIds
+ entryIds: exportedEntryIds
}]
}, selected.entries.map((entry) => entry.id));
return selected;
}
+export function projectPackageEntryIds(state = {}, collectionId) {
+ const entries = Array.isArray(state.entries) ? state.entries : [];
+ const validEntryIds = new Set(entries.map((entry) => clean(entry?.id)).filter(Boolean));
+ const organizer = normalizeOrganizerState(state.organizerState, [...validEntryIds]);
+ const collection = organizer.collections.find((item) => item.id === clean(collectionId));
+ if (!collection) throw new Error("项目不存在");
+ const selectedIds = [...collection.entryIds];
+ const selectedSet = new Set(selectedIds);
+ for (const compound of normalizeCompoundCases(state.compoundCases, entries)) {
+ if (!compound.memberEntryIds.some((entryId) => selectedSet.has(entryId))) continue;
+ for (const entryId of compound.memberEntryIds) {
+ if (selectedSet.has(entryId)) continue;
+ selectedSet.add(entryId);
+ selectedIds.push(entryId);
+ }
+ }
+ return selectedIds.filter((entryId) => validEntryIds.has(entryId));
+}
+
function sanitizeSharedEntry(entry) {
const next = normalizeEntryVisuals(entry);
+ delete next.libraryAddedAt;
+ delete next.importBatchId;
next.mediaAssets = next.mediaAssets.map((asset) => {
if (!asset.visionAnalysis) return asset;
const {
@@ -285,13 +326,14 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
const imported = parseLibraryPackage(importedValue, packageImagePlaceholders(importedValue), {
skipMediaByteValidation: true
});
+ const importMetadata = localImportMetadata(options);
const empty = !(current.entries ?? []).length && options.preserveLibraryConfiguration !== true;
if (empty) {
const skillMerge = mergeCreativeSkillsState(current.creativeSkills, imported.creativeSkills, options);
return {
state: {
...structuredClone(current),
- entries: imported.entries.map(withoutArchivePath),
+ entries: imported.entries.map((entry) => withLocalImportMetadata(withoutArchivePath(entry), importMetadata)),
settings: imported.settings,
taxonomy: imported.taxonomy,
facetCatalog: imported.facetCatalog,
@@ -353,6 +395,7 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
const targetId = preferred && !usedEntryIds.has(preferred) ? preferred : source.id;
if (usedEntryIds.has(targetId)) throw new Error("导入期间案例库发生变化,请重试");
const entry = withoutArchivePath(structuredClone(source));
+ Object.assign(entry, importMetadata);
entry.id = targetId;
const sourceContentId = entry.classification?.pathIds?.[0];
const targetContentId = taxonomyMerge.idMap[sourceContentId];
@@ -400,7 +443,12 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
if (!importedEntry?.creationMeta?.sourceEntryIds) continue;
importedEntry.creationMeta.sourceEntryIds = importedEntry.creationMeta.sourceEntryIds.map((id) => organizerEntryIdMap[id] ?? id);
}
- next.organizerState = mergeOrganizerState(next.organizerState, imported.organizerState, organizerEntryIdMap);
+ next.organizerState = mergeOrganizerState(
+ next.organizerState,
+ imported.organizerState,
+ organizerEntryIdMap,
+ options.preserveLibraryConfiguration === true ? { createdAt: importMetadata.libraryAddedAt } : {}
+ );
const usedCompoundIds = new Set([
...next.entries.map((entry) => entry.id),
...next.compoundCases.map((item) => item.id)
@@ -472,6 +520,21 @@ export function mergeLibraryPackage(current = {}, importedValue = {}, options =
};
}
+function localImportMetadata(options = {}) {
+ const requestedTime = clean(options.libraryAddedAt ?? options.now);
+ const parsedTime = requestedTime && Number.isFinite(Date.parse(requestedTime))
+ ? new Date(requestedTime).toISOString()
+ : new Date().toISOString();
+ return {
+ libraryAddedAt: parsedTime,
+ importBatchId: clean(options.importBatchId) || `library-import:${globalThis.crypto.randomUUID()}`
+ };
+}
+
+function withLocalImportMetadata(entry, metadata) {
+ return { ...entry, ...metadata };
+}
+
function mergeComposerSessions(currentValue, importedValue, entryIdMap, preferredIds = {}, visualIdMap = {}) {
const current = normalizeComposerSessions(currentValue);
const used = new Set(current.map((item) => item.id));
@@ -570,7 +633,7 @@ function packageImagePlaceholders(value) {
const entryImages = (value?.entries ?? []).flatMap((entryValue) => {
const entry = normalizeEntryMedia(entryValue);
return entry.mediaAssets.flatMap((asset) => asset.assetPath
- ? [[asset.assetPath, new Blob(["placeholder"], { type: mediaType(asset.assetPath, asset.kind) })]] : []);
+ ? [[asset.assetPath, new Blob(["placeholder"], { type: mediaType(asset.assetPath, asset.kind, asset.mimeType) })]] : []);
});
const creativeAssets = normalizeCreativeRuns(value?.creativeRuns).flatMap((run) =>
run.outputs.flatMap((output) => (output.visual.assetPath || output.visual.screenshotPath)
@@ -634,7 +697,9 @@ function imageType(path) {
return "image/webp";
}
-function mediaType(path, kind) {
+function mediaType(path, kind, declaredMimeType = "") {
+ const declared = clean(declaredMimeType).toLocaleLowerCase("en-US");
+ if (declared) return declared;
if (kind === "image") return imageType(path);
if (/\.mp4$/i.test(path)) return "video/mp4";
if (/\.webm$/i.test(path)) return "video/webm";
@@ -648,11 +713,37 @@ function mediaType(path, kind) {
return "text/plain";
}
-function validMediaPath(path, kind) {
+function validatePortableMediaDescriptor(asset, path, packageVersion) {
+ if (!validMediaPath(path, asset.kind, packageVersion)) {
+ throw new Error("案例包包含无效或与媒体类型不符的文件路径");
+ }
+ if (packageVersion < 4) return null;
+ const extension = fileExtension(path);
+ const format = assetFormatForExtension(extension);
+ const genericAttachment = asset.kind === "attachment" && !format && /^[a-z0-9]+$/u.test(extension);
+ if (!format && !genericAttachment) throw new Error("案例包包含未登记的媒体格式");
+ if (format && (format.kind !== asset.kind || !isReportedMimeCompatible(format, asset.mimeType))) {
+ throw new Error("案例包中的扩展名、媒体类型和 MIME 不一致");
+ }
+ const declaredFormat = clean(asset.sourceFormat).toLocaleLowerCase("en-US").replace(/^\./u, "");
+ if (declaredFormat && declaredFormat !== extension) {
+ throw new Error("案例包中的源文件格式和文件扩展名不一致");
+ }
+ return format;
+}
+
+function validMediaPath(path, kind, packageVersion = 4) {
if (!path || path.includes("..")) return false;
- if (kind === "image") return /^images\/[A-Za-z0-9._/-]+\.(?:png|jpe?g|webp)$/i.test(path);
- if (kind === "video") return /^videos\/[A-Za-z0-9._/-]+\.(?:mp4|webm|mov|mkv|avi|video)$/i.test(path);
- return /^documents\/[A-Za-z0-9._/-]+\.(?:pdf|rtf|md|txt|html?|bin)$/i.test(path);
+ const safeFile = "[A-Za-z0-9._/-]+\\.[A-Za-z0-9]+";
+ const directories = packageVersion >= 4
+ ? { image: "images", video: "videos", audio: "audio", document: "documents", attachment: "attachments" }
+ : { image: "images", video: "videos", document: "documents" };
+ const directory = directories[kind];
+ if (!directory || !(new RegExp(`^${directory}\\/${safeFile}$`, "i")).test(path)) return false;
+ if (packageVersion >= 4) return true;
+ if (kind === "image") return /\.(?:png|jpe?g|webp)$/i.test(path);
+ if (kind === "video") return /\.(?:mp4|webm|mov|mkv|avi|video)$/i.test(path);
+ return /\.(?:pdf|rtf|md|txt|html?|bin)$/i.test(path);
}
function validCreativeResultPath(path, kind) {
@@ -661,10 +752,21 @@ function validCreativeResultPath(path, kind) {
return /^(?:images|creative-results)\/[A-Za-z0-9._/-]+\.(?:png|jpe?g|webp)$/i.test(path);
}
-function blobMatchesKind(blob, kind) {
- if (kind === "image") return blob.type.startsWith("image/");
- if (kind === "video") return blob.type.startsWith("video/");
- return isSupportedDocumentMimeType(blob.type);
+function blobMatchesKind(blob, asset, format, packageVersion) {
+ if (typeof asset === "string") {
+ if (asset === "image") return clean(blob.type).startsWith("image/");
+ if (asset === "video") return clean(blob.type).startsWith("video/");
+ return isSupportedDocumentMimeType(blob.type);
+ }
+ const blobType = clean(blob.type).toLocaleLowerCase("en-US");
+ if (packageVersion >= 4) {
+ if (!blobType || ["application/octet-stream", "application/x-unknown"].includes(blobType)) return true;
+ if (format) return isReportedMimeCompatible(format, blobType);
+ return asset.kind === "attachment";
+ }
+ if (asset.kind === "image") return blobType.startsWith("image/");
+ if (asset.kind === "video") return blobType.startsWith("video/");
+ return isSupportedDocumentMimeType(blobType);
}
function completeBackupDocumentPaths(value = {}) {
diff --git a/library-selection.js b/library-selection.js
new file mode 100644
index 0000000..e2464e4
--- /dev/null
+++ b/library-selection.js
@@ -0,0 +1,78 @@
+import { expandLogicalCaseIds } from "./compound-cases.js";
+import { uniqueNames } from "./facets.js";
+
+export const LIBRARY_BATCH_ACTIONS = Object.freeze({
+ addCustomLabels: "BATCH_ADD_CUSTOM_LABELS",
+ setProject: "BATCH_SET_PROJECT",
+ moveToTrash: "BATCH_MOVE_TO_TRASH"
+});
+
+const PROJECT_MODES = new Set(["add", "move"]);
+
+export function normalizeSelectedLogicalCaseIds(values = []) {
+ return uniqueIds(values);
+}
+
+export function selectAllFilteredLogicalCases(filteredLogicalCaseIds = []) {
+ return uniqueIds(filteredLogicalCaseIds);
+}
+
+export function clearLibrarySelection() {
+ return [];
+}
+
+export function toggleLibraryCaseSelection(selectedLogicalCaseIds = [], logicalCaseId) {
+ const selected = normalizeSelectedLogicalCaseIds(selectedLogicalCaseIds);
+ const id = clean(logicalCaseId);
+ if (!id) return selected;
+ return selected.includes(id)
+ ? selected.filter((selectedId) => selectedId !== id)
+ : [...selected, id];
+}
+
+export function expandLibrarySelection(selectedLogicalCaseIds = [], compoundCases = []) {
+ return expandLogicalCaseIds(normalizeSelectedLogicalCaseIds(selectedLogicalCaseIds), compoundCases);
+}
+
+export function buildLibraryBatchPayload(selectedLogicalCaseIds = [], compoundCases = [], operation = {}) {
+ const entryIds = expandLibrarySelection(selectedLogicalCaseIds, compoundCases);
+ if (!entryIds.length) throw new Error("请至少选择一个案例");
+
+ if (operation.type === LIBRARY_BATCH_ACTIONS.addCustomLabels) {
+ return {
+ type: LIBRARY_BATCH_ACTIONS.addCustomLabels,
+ entryIds,
+ customLabels: uniqueNames(operation.customLabels)
+ };
+ }
+
+ if (operation.type === LIBRARY_BATCH_ACTIONS.setProject) {
+ const collectionId = clean(operation.collectionId);
+ const mode = clean(operation.mode);
+ if (!collectionId) throw new Error("请选择项目");
+ if (!PROJECT_MODES.has(mode)) throw new Error("项目批量操作必须明确选择添加或移动");
+ return {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
+ entryIds,
+ collectionId,
+ mode
+ };
+ }
+
+ if (operation.type === LIBRARY_BATCH_ACTIONS.moveToTrash) {
+ return { type: LIBRARY_BATCH_ACTIONS.moveToTrash, entryIds };
+ }
+
+ throw new Error("不支持的批量操作");
+}
+
+function uniqueIds(values = []) {
+ const source = Array.isArray(values)
+ ? values
+ : values instanceof Set ? [...values] : [];
+ return [...new Set(source.map(clean).filter(Boolean))];
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+}
diff --git a/library-view.js b/library-view.js
new file mode 100644
index 0000000..83184ce
--- /dev/null
+++ b/library-view.js
@@ -0,0 +1,191 @@
+export const CASE_SORT_MODES = Object.freeze({
+ addedDesc: "added-desc",
+ updatedDesc: "updated-desc",
+ title: "title",
+ projectManual: "project-manual"
+});
+
+export const PROJECT_SORT_MODES = Object.freeze({
+ manual: "manual",
+ recent: "recent",
+ name: "name"
+});
+
+const CASE_SORT_VALUES = new Set(Object.values(CASE_SORT_MODES));
+const PROJECT_SORT_VALUES = new Set(Object.values(PROJECT_SORT_MODES));
+
+/**
+ * Projects the dates and physical membership of one gallery item without
+ * mutating or backfilling stored cases. Historical cases only fall back to
+ * their saved time while the view is being calculated.
+ */
+export function caseViewProjection(entry = {}) {
+ const members = logicalMembers(entry);
+ const compound = entry?.compoundCase && typeof entry.compoundCase === "object"
+ ? entry.compoundCase
+ : null;
+ const memberEntryIds = logicalMemberIds(entry, members);
+ const importBatchIds = uniqueStrings([
+ entry?.importBatchId,
+ ...members.map((member) => member?.importBatchId)
+ ]);
+ const memberAddedAt = members.map(memberAddedTime).filter(Boolean);
+ const addedAt = latestIso([
+ ...memberAddedAt,
+ compound?.createdAt,
+ !compound ? entry?.libraryAddedAt : "",
+ !compound ? entry?.savedAt : ""
+ ]);
+ const updatedAt = latestIso([
+ ...members.map(memberUpdatedTime),
+ libraryUpdatedTime(compound),
+ libraryUpdatedTime(entry)
+ ]);
+
+ return {
+ memberEntryIds,
+ importBatchIds,
+ addedAt,
+ updatedAt
+ };
+}
+
+export function sortLibraryCases(entriesValue = [], options = {}) {
+ const entries = Array.isArray(entriesValue) ? entriesValue : [];
+ const mode = CASE_SORT_VALUES.has(options.mode) ? options.mode : CASE_SORT_MODES.addedDesc;
+ const manualRank = projectManualRank(options.projectEntryIds);
+ const projections = new Map(entries.map((entry) => [entry, caseViewProjection(entry)]));
+ return stableSort(entries, (left, right) => {
+ if (mode === CASE_SORT_MODES.title) return compareNames(left?.title, right?.title);
+ if (mode === CASE_SORT_MODES.projectManual) {
+ return rankProjection(projections.get(left), manualRank) - rankProjection(projections.get(right), manualRank);
+ }
+ const leftProjection = projections.get(left);
+ const rightProjection = projections.get(right);
+ if (mode === CASE_SORT_MODES.updatedDesc) {
+ return compareIsoDescending(leftProjection.updatedAt, rightProjection.updatedAt);
+ }
+ return compareIsoDescending(leftProjection.addedAt, rightProjection.addedAt);
+ });
+}
+
+export function sortProjects(collectionsValue = [], modeValue = PROJECT_SORT_MODES.manual) {
+ const collections = Array.isArray(collectionsValue) ? collectionsValue : [];
+ const mode = PROJECT_SORT_VALUES.has(modeValue) ? modeValue : PROJECT_SORT_MODES.manual;
+ return stableSort(collections, (left, right) => {
+ if (mode === PROJECT_SORT_MODES.name) return compareNames(left?.name, right?.name);
+ if (mode === PROJECT_SORT_MODES.recent) {
+ return compareIsoDescending(validIso(left?.createdAt), validIso(right?.createdAt));
+ }
+ return finiteOrder(left?.order) - finiteOrder(right?.order);
+ });
+}
+
+export function moveProjectLogicalCase(entryIdsValue = [], currentEntry, adjacentEntry, direction) {
+ const entryIds = (Array.isArray(entryIdsValue) ? entryIdsValue : []).map(clean).filter(Boolean);
+ if (!["up", "down"].includes(direction)) return [...entryIds];
+ const currentIds = new Set(caseViewProjection(currentEntry).memberEntryIds);
+ const adjacentIds = new Set(caseViewProjection(adjacentEntry).memberEntryIds);
+ const moving = entryIds.filter((id) => currentIds.has(id));
+ if (!moving.length) return [...entryIds];
+ const remaining = entryIds.filter((id) => !currentIds.has(id));
+ const adjacentIndexes = remaining
+ .map((id, index) => adjacentIds.has(id) ? index : -1)
+ .filter((index) => index >= 0);
+ if (!adjacentIndexes.length) return [...entryIds];
+ const insertAt = direction === "up"
+ ? Math.min(...adjacentIndexes)
+ : Math.max(...adjacentIndexes) + 1;
+ return [...remaining.slice(0, insertAt), ...moving, ...remaining.slice(insertAt)];
+}
+
+function logicalMembers(entry) {
+ if (Array.isArray(entry?.memberEntries) && entry.memberEntries.length) return entry.memberEntries;
+ return entry && typeof entry === "object" ? [entry] : [];
+}
+
+function logicalMemberIds(entry, members) {
+ const declared = uniqueStrings(entry?.memberEntryIds);
+ if (declared.length) return declared;
+ const memberIds = uniqueStrings(members.map((member) => member?.id));
+ return memberIds.length ? memberIds : uniqueStrings([entry?.id]);
+}
+
+function memberAddedTime(member) {
+ return validIso(member?.libraryAddedAt) || validIso(member?.savedAt);
+}
+
+function memberUpdatedTime(member) {
+ return libraryUpdatedTime(member) || validIso(member?.savedAt);
+}
+
+function libraryUpdatedTime(value) {
+ return validIso(value?.libraryUpdatedAt) || validIso(value?.updatedAt);
+}
+
+function projectManualRank(entryIdsValue) {
+ const result = new Map();
+ uniqueStrings(entryIdsValue).forEach((id, index) => result.set(id, index));
+ return result;
+}
+
+function rankProjection(projection, rank) {
+ const positions = (projection?.memberEntryIds ?? [])
+ .map((id) => rank.get(id))
+ .filter(Number.isFinite);
+ return positions.length ? Math.min(...positions) : Number.POSITIVE_INFINITY;
+}
+
+function stableSort(values, compare) {
+ return values
+ .map((value, index) => ({ value, index }))
+ .sort((left, right) => compare(left.value, right.value) || left.index - right.index)
+ .map(({ value }) => value);
+}
+
+function compareIsoDescending(left, right) {
+ return compareDates(left, right, -1);
+}
+
+function compareDates(left, right, direction) {
+ const leftTime = timestamp(left);
+ const rightTime = timestamp(right);
+ if (leftTime === rightTime) return 0;
+ if (!Number.isFinite(leftTime)) return 1;
+ if (!Number.isFinite(rightTime)) return -1;
+ return (leftTime - rightTime) * direction;
+}
+
+function compareNames(left, right) {
+ return clean(left).localeCompare(clean(right), undefined, { numeric: true, sensitivity: "base" });
+}
+
+function latestIso(values) {
+ const valid = (Array.isArray(values) ? values : [])
+ .map(validIso)
+ .filter(Boolean);
+ return valid.sort((left, right) => timestamp(right) - timestamp(left))[0] || "";
+}
+
+function validIso(value) {
+ const text = clean(value);
+ return text && Number.isFinite(Date.parse(text)) ? new Date(text).toISOString() : "";
+}
+
+function timestamp(value) {
+ const text = validIso(value);
+ return text ? Date.parse(text) : Number.NaN;
+}
+
+function finiteOrder(value) {
+ const number = Number(value);
+ return Number.isFinite(number) ? number : Number.POSITIVE_INFINITY;
+}
+
+function uniqueStrings(values) {
+ return [...new Set((Array.isArray(values) ? values : []).map(clean).filter(Boolean))];
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+}
diff --git a/library.css b/library.css
index 0a8f5c5..fbac37d 100644
--- a/library.css
+++ b/library.css
@@ -23,8 +23,8 @@ body[data-library-state="ready"] > .library-loading { display: none; }
z-index: 30;
top: 0;
display: grid;
- grid-template-columns: auto minmax(220px, auto) minmax(280px, 1fr) auto auto;
- grid-template-areas: "toggle brand search summary actions";
+ grid-template-columns: auto minmax(220px, auto) minmax(280px, 1fr) auto;
+ grid-template-areas: "toggle brand search actions";
align-items: center;
gap: 14px;
min-height: 74px;
@@ -37,14 +37,14 @@ body[data-library-state="ready"] > .library-loading { display: none; }
#toggle-filters[data-filter-count]::after { content: attr(data-filter-count); position: absolute; top: -4px; right: -4px; display: grid; min-width: 17px; height: 17px; place-items: center; border: 2px solid var(--bar); border-radius: 50%; padding: 0 3px; color: var(--accent-contrast); background: var(--accent); font-size: 9px; font-weight: 800; line-height: 1; pointer-events: none; }
.topbar > .brand { grid-area: brand; }
.topbar > .global-search { grid-area: search; min-width: 0; }
-.topbar > #library-summary { grid-area: summary; }
.topbar > .top-actions { grid-area: actions; min-width: 0; justify-self: end; }
.brand { display: flex; align-items: center; gap: 10px; }
.brand-mark { width: 38px; height: 38px; border-radius: 50%; }
.brand h1 { margin: 0; font-size: 17px; line-height: 1.1; letter-spacing: -0.02em; }
.global-search input { padding-inline: 16px; background: var(--raised); }
-#library-summary { margin: 0; color: var(--muted); font-size: 11px; white-space: nowrap; }
.top-actions { display: flex; gap: 8px; }
+.settings-entry-button { position: relative; }
+.settings-update-badge { position: absolute; top: -2px; right: -2px; width: 9px; height: 9px; border: 2px solid var(--bar); border-radius: 50%; background: var(--accent); pointer-events: none; }
.package-menu { position: relative; }
.top-actions .package-menu { position: static; }
@@ -78,6 +78,9 @@ body[data-library-state="ready"] > .library-loading { display: none; }
background: var(--card);
box-shadow: var(--shadow);
}
+details:not([open]) > .package-menu-panel,
+details:not([open]) > .project-menu-panel,
+details:not([open]) > .detail-project-popover { display: none; }
.package-menu-panel button { display: grid; min-height: 50px; gap: 3px; justify-items: start; padding: 9px 10px; text-align: left; }
.package-menu-panel button span { color: var(--muted); font-size: 11px; font-weight: 500; }
.package-menu-panel button:not(.button-secondary) span { color: color-mix(in srgb, var(--accent-contrast) 78%, transparent); }
@@ -105,6 +108,22 @@ body[data-library-state="ready"] > .library-loading { display: none; }
box-shadow: var(--shadow);
}
.data-safety-dialog::backdrop { background: rgba(0, 0, 0, 0.62); }
+.trash-dialog { width: min(680px, calc(100vw - 32px)); }
+.trash-dialog-body { max-height: min(62dvh, 620px); overflow: auto; }
+.trash-list { display: grid; gap: 7px; }
+.trash-empty-title { padding: 28px 12px; text-align: center; }
+.trash-item { display: grid; min-width: 0; grid-template-columns: 68px minmax(0, 1fr) auto; align-items: center; gap: 12px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: 10px; background: var(--raised); }
+.trash-item-cover { display: grid; width: 68px; aspect-ratio: 1; overflow: hidden; place-items: center; border-radius: 8px; color: var(--muted); background: var(--paper); }
+.trash-item-cover img, .trash-item-cover video { width: 100%; height: 100%; object-fit: cover; }
+.trash-item-cover .ui-icon { width: 25px; height: 25px; }
+.trash-item-copy { display: grid; min-width: 0; gap: 4px; }
+.trash-item-copy strong { overflow-wrap: anywhere; line-height: 1.4; }
+.trash-item-copy small { color: var(--muted); font-size: 10px; }
+.trash-item-labels { display: flex; flex-wrap: wrap; gap: 4px; }
+.trash-item-labels span { max-width: 100%; border-radius: 999px; padding: 3px 7px; overflow-wrap: anywhere; color: var(--muted); background: var(--selection); font-size: 10px; }
+.trash-item-actions { display: flex; flex: 0 0 auto; gap: 6px; }
+.trash-item-actions button { width: 36px; min-height: 36px; padding: 0; }
+.trash-actions { display: flex; justify-content: flex-end; gap: 8px; border-top: 1px solid var(--line); padding: 12px 18px; }
.share-dialog { width: min(460px, calc(100vw - 28px)); }
.share-dialog-body { display: grid; gap: 14px; }
.share-dialog-meta { margin: 0; color: var(--muted); font-size: var(--ui-meta-size); }
@@ -123,6 +142,7 @@ body[data-library-state="ready"] > .library-loading { display: none; }
.about-dialog dd { margin: 0; }
.source-link { display: inline-block; max-width: 100%; overflow: hidden; color: var(--ink); font-weight: 700; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; }
.source-link:hover { color: var(--accent-ink); }
+.update-download-action { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; }
.data-safety-summary { display: flex; align-items: center; justify-content: space-between; gap: 12px; border-radius: 10px; padding: 12px; background: var(--raised); }
.data-safety-summary strong { font-size: 13px; }
.data-safety-summary span { color: var(--muted); font-size: 11px; text-align: right; }
@@ -165,8 +185,12 @@ body[data-library-state="ready"] > .library-loading { display: none; }
.import-summary strong { color: var(--ink); font-size: 14px; }
.import-options { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: 12px; }
.import-options > label:not(.import-check) { display: grid; gap: 5px; color: var(--muted); font-size: 11px; font-weight: 700; }
+.import-project-field small, .import-label-field > small { min-height: 1.4em; color: var(--muted); font-size: 10px; font-weight: 500; line-height: 1.4; }
+.import-project-field small:empty, .import-label-field > small:empty { display: none; }
.import-check { display: flex; min-height: 36px; align-items: center; gap: 7px; color: var(--ink); font-size: 12px; }
.import-check input, .import-file-row input { width: auto; min-height: auto; accent-color: var(--accent); }
+.import-label-field { display: grid; gap: 5px; color: var(--muted); font-size: 11px; font-weight: 700; }
+.import-label-editor { min-width: 0; }
.import-file-list { display: grid; max-height: 280px; overflow: auto; border-top: 1px solid var(--line); }
.import-file-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 44px; border-bottom: 1px solid var(--line); padding: 7px 2px; }
.import-file-row > span { min-width: 0; }
@@ -175,6 +199,9 @@ body[data-library-state="ready"] > .library-loading { display: none; }
.import-file-row small { margin-top: 2px; color: var(--muted); font-size: 10px; }
.import-file-row > em { color: var(--muted); font-size: 10px; font-style: normal; white-space: nowrap; }
.import-file-row.is-skipped { opacity: .62; }
+.import-file-row.is-skipped.has-action { opacity: 1; }
+.import-file-row .import-file-reason { color: var(--danger); white-space: normal; }
+.import-file-force { min-height: 28px; padding: 4px 8px; font-size: 10px; white-space: nowrap; }
.import-feedback { min-height: 0; margin: 0; color: var(--muted); font-size: 11px; }
.import-feedback:empty { display: none; }
.import-feedback.error { color: var(--danger); }
@@ -188,15 +215,35 @@ button[aria-busy="true"] { cursor: progress; }
.advanced-reanalysis > summary { color: var(--muted); cursor: pointer; font-size: 12px; font-weight: 700; }
.advanced-reanalysis > p { color: var(--muted); font-size: 12px; }
-.share-bar { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; gap: 12px; border: 1px solid var(--selection-edge); border-radius: var(--ui-container-radius); padding: 6px 8px; background: var(--selection); }
-.share-bar > span { margin-right: auto; color: var(--muted); font-size: 11px; }
-.share-bar > div { display: flex; align-items: center; gap: 7px; }
+.share-bar { display: flex; flex: 1 1 100%; min-width: 0; align-items: center; gap: 8px 12px; border: 1px solid var(--selection-edge); border-radius: var(--ui-container-radius); padding: 6px 8px; background: var(--selection); }
+.share-bar > strong { flex: none; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
+.share-bar > div { display: flex; min-width: 0; flex: 1 1 auto; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 7px; }
.share-bar select { width: min(180px, 24vw); min-height: 34px; }
-.gallery-heading.selection-mode { align-items: stretch; }
+.selection-label-field input { width: min(150px, 20vw); min-height: 34px; }
+.workspace-navigation-count { display: grid; min-width: 18px; height: 18px; margin-left: auto; place-items: center; border-radius: 999px; padding-inline: 5px; color: var(--muted); background: var(--raised); font-size: 9px; }
+.compact-select select { width: 92px; min-height: 28px; border-color: transparent; padding: 3px 22px 3px 6px; color: var(--muted); background-color: transparent; font-size: 10px; }
+.sidebar-trash-section { margin-bottom: 18px; border-bottom: 1px solid var(--line); padding-bottom: 14px; }
+.sidebar-trash-section .workspace-navigation-item { width: 100%; grid-template-columns: 18px minmax(0, 1fr) auto; }
+.gallery-view-controls { display: flex; align-items: center; gap: 2px; margin-left: auto; }
+.gallery-sort-field select { width: auto; min-width: 110px; min-height: 32px; border-color: transparent; padding: 5px 26px 5px 9px; color: var(--muted); background-color: transparent; box-shadow: none; font-size: 11px; }
+.gallery-sort-field select:hover:not(:disabled),
+.gallery-sort-field select:focus-visible { border-color: transparent; background-color: var(--hover); }
+.gallery-view-controls > .icon-button { border-color: transparent; background: transparent; box-shadow: none; }
+.gallery-view-controls > .icon-button:hover:not(:disabled),
+.gallery-view-controls > .icon-button:focus-visible { border-color: transparent; background: var(--hover); }
+.case-reorder-controls { position: absolute; z-index: 5; top: 8px; left: 8px; display: none; gap: 4px; }
+.case-card.manual-project-order .case-reorder-controls { display: flex; }
+.case-reorder-controls button { display: grid; width: 36px; min-height: 36px; place-items: center; border-color: rgba(255, 255, 255, .3); padding: 0; color: white; background: rgba(9, 11, 16, .72); font-size: 14px; }
+.case-reorder-controls button:disabled { opacity: .38; }
+.gallery-heading.selection-mode { align-items: center; }
.project-selection-actions button { min-height: 32px; padding: 5px 10px; font-size: 12px; }
-.workspace { display: grid; grid-template-columns: 244px minmax(0, 1fr); min-height: calc(100vh - 74px); }
-.workspace.filters-collapsed { grid-template-columns: 0 minmax(0, 1fr); }
+.workspace { display: grid; grid-template-columns: var(--sidebar-width, 244px) 6px minmax(0, 1fr); min-height: calc(100vh - 74px); }
+.workspace.filters-collapsed { grid-template-columns: 0 0 minmax(0, 1fr); }
+.sidebar-resizer { position: relative; z-index: 4; width: 6px; cursor: col-resize; touch-action: none; }
+.sidebar-resizer::after { position: absolute; inset: 0 2px; content: ""; background: transparent; transition: background 120ms ease; }
+.sidebar-resizer:hover::after, .sidebar-resizer:focus-visible::after, .sidebar-resizer.is-resizing::after { background: var(--accent); }
+.filters-collapsed .sidebar-resizer { pointer-events: none; opacity: 0; }
.filter-sidebar {
position: sticky;
top: 74px;
@@ -234,8 +281,29 @@ button[aria-busy="true"] { cursor: progress; }
.tag-navigation-section { margin-top: 18px; }
.project-list { display: grid; gap: 4px; }
.project-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 4px; }
+.project-row.project-ordering {
+ border: 1px solid transparent;
+ border-radius: var(--ui-container-radius);
+ cursor: grab;
+ touch-action: none;
+ -webkit-user-select: none;
+ user-select: none;
+}
+.project-row.project-ordering:hover,
+.project-row.project-ordering:focus-visible { border-color: var(--selection-edge); background: var(--selection-hover); }
+.project-row.project-ordering:active,
+.project-row.project-ordering.is-dragging { cursor: grabbing; }
+.project-row.project-ordering.is-dragging {
+ z-index: 4;
+ border-color: var(--accent);
+ background: var(--card);
+ box-shadow: var(--shadow);
+ opacity: .94;
+}
+.project-row.project-ordering .project-filter { pointer-events: none; }
+.project-list.is-project-dragging .project-row:not(.is-dragging) { transition: transform var(--ui-motion-fast) ease; }
.project-filter { display: grid; min-height: 30px; min-width: 0; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; overflow: hidden; padding: 5px 8px; color: var(--muted); background: transparent; font-size: 11px; text-align: left; }
-.project-filter-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.project-filter-name { overflow-wrap: anywhere; white-space: normal; }
.project-filter-meta, .content-filter-meta { display: flex; align-items: center; justify-content: flex-end; gap: 5px; white-space: nowrap; }
.project-filter-count { color: var(--muted); font-variant-numeric: tabular-nums; }
.project-filter:hover:not(:disabled) { color: var(--ink); background: var(--selection-hover); }
@@ -251,13 +319,14 @@ button[aria-busy="true"] { cursor: progress; }
.filter-heading { display: flex; align-items: center; justify-content: space-between; font-size: 11px; }
.filter-heading > span { display: flex; gap: 2px; }
.filter-heading button { min-height: 30px; padding: 3px 6px; color: var(--muted); background: transparent; font-size: 11px; }
+.filter-heading #manage-project-order, .gallery-heading #manage-case-order { width: 36px; min-height: 36px; padding: 0; }
.filter-options { display: grid; gap: 2px; }
.content-filter-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 2px; }
.content-filter-option { display: grid; min-height: 36px; grid-template-columns: 18px minmax(0, 1fr) auto; align-items: center; gap: 9px; padding: 7px 9px; color: var(--muted); border-color: transparent; background: transparent; text-align: left; }
.content-filter-option:hover:not(:disabled) { color: var(--ink); background: var(--hover); }
.content-filter-option[aria-pressed="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 2px 0 var(--selection-indicator); }
.content-filter-option[aria-pressed="true"] .ui-icon { color: var(--accent); }
-.content-filter-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.content-filter-name { overflow-wrap: anywhere; white-space: normal; }
.content-filter-count, .facet-option-count { color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
.content-visibility, .project-visibility { border: 1px solid var(--line); border-radius: 4px; padding: 1px 4px; color: var(--muted); font-size: 11px; font-weight: 700; }
.filter-option { min-height: 30px; padding: 5px 7px; color: var(--muted); border: 1px solid transparent; border-radius: var(--ui-control-radius); background: transparent; font-size: 11px; font-weight: 700; }
@@ -280,7 +349,7 @@ button[aria-busy="true"] { cursor: progress; }
.facet-option-check .ui-icon { width: 11px; height: 11px; opacity: 0; }
.facet-option-row[aria-pressed="true"] .facet-option-check { border-color: var(--accent); background: var(--accent); }
.facet-option-row[aria-pressed="true"] .facet-option-check .ui-icon { opacity: 1; }
-.facet-option-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.facet-option-name { overflow-wrap: anywhere; white-space: normal; }
.facet-filter-overflow { border-top: 1px solid var(--line); }
.facet-filter-overflow > summary { padding: 13px 2px; color: var(--muted); cursor: pointer; font-size: 11px; font-weight: 750; }
.facet-filter-overflow-body { padding-left: 8px; }
@@ -306,6 +375,11 @@ button[aria-busy="true"] { cursor: progress; }
.case-shot { display: block; width: 100%; height: auto; background: #151922; }
.case-image-wrap-fixed .case-shot { height: 100%; object-fit: cover; }
.case-shot-missing { display: grid; min-height: 170px; place-items: center; padding: 22px; color: var(--empty-ink); background: var(--empty-bg); font-size: 11px; text-align: center; }
+.case-asset-cover { display: grid; min-height: 170px; align-content: center; gap: 8px; padding: 18px; background: var(--raised); }
+.case-audio-cover { background: linear-gradient(145deg, color-mix(in srgb, var(--accent) 11%, var(--raised)), var(--raised)); }
+.case-audio-player { width: 100%; min-width: 0; height: 34px; }
+.case-asset-meta, .case-asset-path { margin: 0; overflow: hidden; color: var(--muted); font-size: 10px; line-height: 1.45; text-overflow: ellipsis; white-space: nowrap; }
+.case-local-link-badge { width: max-content; border: 1px solid var(--line); border-radius: 999px; padding: 3px 7px; color: var(--muted); font-size: 9px; font-weight: 750; }
.case-summary { margin: 0 0 9px; color: var(--muted); font-size: 11px; line-height: 1.5; }
.mini-tags { display: flex; flex-wrap: nowrap; align-items: center; gap: 3px; overflow: hidden; padding: 6px 6px 5px; }
.mini-tag { display: block; min-width: 0; min-height: 0; overflow: hidden; padding: 3px 6px; color: color-mix(in srgb, var(--facet-color) 70%, var(--ink)); border-radius: 999px; background: color-mix(in srgb, var(--facet-color) 13%, var(--card)); font-size: 10px; font-weight: 700; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
@@ -402,9 +476,19 @@ button[aria-busy="true"] { cursor: progress; }
.detail-visual-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; }
.detail-visual-actions button { min-height: 28px; padding: 4px 8px; color: #f4f5f7; border-color: rgba(255, 255, 255, 0.24); background: rgba(12, 14, 20, 0.72); font-size: 11px; }
.detail-placeholder { display: grid; min-height: 260px; place-items: center; color: var(--muted); background: #0d1016; }
+.detail-audio-wrap, .detail-source-file { display: grid; width: min(620px, calc(100% - 32px)); min-height: 280px; align-content: center; justify-self: center; gap: 10px; margin: 32px auto; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: 26px; background: var(--card); }
+.detail-audio { width: 100%; margin-block: 8px; }
+.asset-kind-badge { width: max-content; border-radius: 999px; padding: 4px 8px; color: var(--accent-ink); background: var(--accent-soft); font-size: 10px; font-weight: 800; }
+.asset-file-title { overflow-wrap: anywhere; font-size: 18px; }
+.asset-file-path, .asset-file-meta, .asset-inert-note, .asset-link-status { margin: 0; color: var(--muted); font-size: 11px; line-height: 1.55; overflow-wrap: anywhere; }
+.asset-link-status { color: var(--accent-ink); font-weight: 750; }
+.detail-local-asset-reference[data-link-status="missing"] .asset-link-status,
+.detail-local-asset-reference[data-link-status="changed"] .asset-link-status { color: var(--danger); }
+.asset-file-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 4px; }
+.detail-source-file > .media-open-link, .detail-audio-wrap > .media-open-link { width: max-content; }
.detail-section { padding: 16px 22px; border-bottom: 1px solid var(--line); }
.detail-section h2 { margin: 0 0 8px; font-size: 17px; line-height: 1.32; }
-.detail-title { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
+.detail-title { overflow-wrap: anywhere; }
.detail-section h3 { margin: 0 0 12px; font-size: 11px; }
.detail-section h4 { margin: 16px 0 7px; color: var(--muted); font-size: 11px; }
.detail-meta { display: flex; flex-wrap: wrap; gap: 8px 14px; color: var(--muted); font-size: 11px; }
@@ -421,9 +505,31 @@ button[aria-busy="true"] { cursor: progress; }
.screenshot-actions strong { margin-right: auto; color: var(--muted); font-size: 11px; }
.screenshot-actions button { min-height: 32px; padding: 5px 8px; font-size: 12px; }
.detail-tags { display: flex; flex-wrap: wrap; gap: 5px; }
-.attribute-pill { display: inline-flex; min-height: 0; align-items: center; padding: 4px 7px; color: color-mix(in srgb, var(--facet-color) 70%, var(--ink)); border-radius: 999px; background: color-mix(in srgb, var(--facet-color) 13%, var(--card)); font-size: 11px; font-weight: 700; line-height: 1.25; white-space: nowrap; }
+.attribute-pill { display: inline-flex; min-height: 0; align-items: center; padding: 4px 7px; overflow-wrap: anywhere; color: color-mix(in srgb, var(--facet-color) 70%, var(--ink)); border-radius: 999px; background: color-mix(in srgb, var(--facet-color) 13%, var(--card)); font-size: 11px; font-weight: 700; line-height: 1.25; white-space: normal; }
+.detail-quick-organization { position: relative; display: grid; gap: 12px; }
+.detail-organization-group { display: grid; gap: 8px; }
+.detail-organization-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }
+.detail-organization-heading strong { color: var(--ink); font-size: 12px; }
+.detail-organization-heading span, .detail-organization-empty { margin: 0; color: var(--muted); font-size: 10px; line-height: 1.45; }
+.detail-project-menu { position: relative; }
+.detail-project-menu > summary { display: flex; min-height: 36px; align-items: center; justify-content: space-between; gap: 10px; border: 1px solid var(--line); border-radius: var(--ui-control-radius); padding: 7px 10px; color: var(--ink); background: var(--raised); cursor: pointer; list-style: none; font-size: 11px; }
+.detail-project-menu > summary::-webkit-details-marker { display: none; }
+.detail-project-menu > summary .ui-icon { width: 15px; height: 15px; flex: 0 0 auto; color: var(--muted); }
+.detail-project-popover { position: absolute; z-index: 20; top: calc(100% + 5px); left: 0; display: grid; width: min(100%, 430px); max-height: min(330px, 48vh); overflow: auto; gap: 5px; border: 1px solid var(--line); border-radius: 12px; padding: 8px; background: var(--card); box-shadow: var(--shadow); }
+.detail-project-list { display: grid; gap: 5px; }
+.detail-project-option { display: flex; min-width: 0; min-height: 34px; align-items: center; gap: 7px; border: 1px solid var(--line); border-radius: var(--ui-control-radius); padding: 6px 8px; color: var(--ink); background: var(--raised); cursor: pointer; font-size: 11px; }
+.detail-project-option:hover { border-color: var(--ui-border-strong); }
+.detail-project-option input { width: 16px; min-height: 16px; flex: 0 0 auto; accent-color: var(--accent); }
+.detail-project-option span { overflow-wrap: anywhere; white-space: normal; }
+.detail-new-project { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 7px; }
+.detail-new-project input { min-width: 0; }
+.detail-new-project button { min-height: 34px; white-space: nowrap; }
+.detail-footer-actions { display: flex; justify-content: flex-end; border-top: 1px solid var(--line); padding: 16px 18px 22px; }
+.detail-delete-action { display: inline-flex; min-height: 36px; align-items: center; gap: 7px; }
+.detail-delete-action .ui-icon { width: 16px; height: 16px; }
.metadata-heading, .prompt-section-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.metadata-heading h3, .prompt-section-heading h3 { margin-bottom: 0; }
+.metadata-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 6px; }
.source-open-action { display: inline-flex; min-height: 30px; align-items: center; border: 1px solid var(--line); border-radius: var(--ui-control-radius); padding: 5px 9px; color: var(--ink); font-size: 11px; font-weight: 700; text-decoration: none; }
.source-open-action:hover { border-color: var(--ui-border-strong); background: var(--raised); }
.metadata-list { display: grid; margin: 12px 0 0; }
@@ -466,12 +572,14 @@ button[aria-busy="true"] { cursor: progress; }
.entry-editor[open] > summary::after { content: "−"; }
.entry-editor-body { padding-top: 4px; }
.entry-edit-field { display: grid; gap: 6px; }
+.entry-edit-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: 7px; }
+.entry-edit-row .entry-edit-field { min-width: 0; }
.compound-part { margin: 14px; overflow: hidden; border: 1px solid var(--line); border-radius: 12px; background: var(--card); }
.compound-part > .detail-section { padding-inline: 16px; }
.compound-part > .detail-visual-gallery { min-height: 300px; }
.compound-part-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--line); }
.compound-part-heading > div:first-child { flex: 1 1 auto; min-width: 0; }
-.compound-part-heading h3 { margin: 3px 0 5px; overflow: hidden; font-size: 14px; text-overflow: ellipsis; white-space: nowrap; }
+.compound-part-heading h3 { margin: 3px 0 5px; overflow-wrap: anywhere; font-size: 14px; }
.compound-part-heading-actions { display: flex; flex: 0 0 auto; align-items: center; gap: 7px; white-space: nowrap; }
.compound-primary-badge { padding: 5px 8px; color: var(--accent-ink); border-radius: 999px; background: var(--accent-soft); font-size: 11px; font-weight: 800; }
.compound-part-index { color: var(--accent); font-size: 10px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }
@@ -480,7 +588,7 @@ button[aria-busy="true"] { cursor: progress; }
.compound-organizer > summary { cursor: pointer; font-size: 12px; font-weight: 800; }
.compound-member-order { display: grid; gap: 6px; margin: 8px 0 12px; }
.compound-member-row { display: flex; min-height: 38px; align-items: center; justify-content: space-between; gap: 8px; border: 1px solid var(--line); border-radius: 8px; padding: 5px 7px 5px 10px; }
-.compound-member-row > span:first-child { min-width: 0; overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
+.compound-member-row > span:first-child { min-width: 0; overflow-wrap: anywhere; font-size: 12px; }
.compound-organizer-actions { display: flex; gap: 8px; margin-top: 12px; }
.compound-organizer-actions button { flex: 1; }
.entry-editor-row { display: grid; grid-template-columns: 1fr auto; gap: 7px; margin-bottom: 9px; }
@@ -663,8 +771,24 @@ button[aria-busy="true"] { cursor: progress; }
.settings-tabs button[aria-selected="true"] { color: var(--ink); background: var(--selection); box-shadow: inset 0 -1px var(--selection-indicator); }
.settings-panel { min-width: 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
.settings-general-section { grid-column: 1 / -1; display: grid; gap: 12px; border-top: 1px solid var(--line); padding-top: 16px; }
-.settings-about { grid-column: 1 / -1; display: grid; gap: 4px; border-top: 1px solid var(--line); padding-top: 14px; color: var(--muted); font-size: 11px; }
+.capture-permission-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
+.capture-permission-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; border: 1px solid var(--line); border-radius: 7px; padding: 11px 12px; background: var(--raised); }
+.capture-permission-row > div { display: grid; min-width: 0; gap: 3px; }
+.capture-permission-row strong { color: var(--ink); font-size: 11px; }
+.capture-permission-row span { color: var(--muted); font-size: 10px; }
+.capture-permission-row span.is-granted { color: var(--success); }
+.capture-permission-row button { min-height: 30px; padding: 5px 8px; font-size: 10px; }
+.settings-about { grid-column: 1 / -1; display: grid; gap: 9px; border-top: 1px solid var(--line); padding-top: 14px; color: var(--muted); font-size: 11px; }
.settings-about strong { color: var(--ink); font-size: 12px; }
+.settings-about-heading { display: flex; align-items: start; justify-content: space-between; gap: 12px; }
+.settings-about-heading > div { display: grid; gap: 3px; }
+.settings-update-details, .settings-update-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; }
+.settings-update-explanation { max-width: 720px; margin: 0; line-height: 1.55; }
+.settings-update-actions button { min-height: 32px; }
+.update-status-badge { flex: none; border-radius: 999px; padding: 5px 8px; color: var(--muted); background: var(--raised); font-size: 10px; }
+.update-status-badge.is-current { color: var(--success); background: color-mix(in srgb, var(--success) 10%, var(--raised)); }
+.update-status-badge.is-available { color: var(--accent-ink); background: var(--accent-soft); }
+.update-status-badge.is-error { color: var(--danger); background: color-mix(in srgb, var(--danger) 9%, var(--raised)); }
.settings-tasks-panel { gap: 12px; }
.analysis-settings-form { display: grid; gap: 14px; }
.analysis-settings-form label { display: grid; gap: 6px; color: var(--muted); font-size: 11px; font-weight: 700; }
@@ -722,7 +846,6 @@ button[aria-busy="true"] { cursor: progress; }
"toggle brand actions"
"search search search";
}
- #library-summary { display: none; }
.top-actions .package-menu-panel,
.top-actions .add-menu .package-menu-panel {
position: fixed;
@@ -735,6 +858,7 @@ button[aria-busy="true"] { cursor: progress; }
}
.gallery-heading.project-selection-mode { top: 126px; }
.workspace { grid-template-columns: 210px minmax(0, 1fr); }
+ .sidebar-resizer { display: none; }
.filter-sidebar { top: 126px; height: calc(100vh - 126px); }
.detail-drawer { --detail-panel-width: clamp(340px, 40vw, 420px); }
.inline-form, .tag-create-form { grid-template-columns: 1fr 1fr; }
@@ -766,6 +890,11 @@ button[aria-busy="true"] { cursor: progress; }
}
@media (max-width: 640px) {
+ .gallery-heading #manage-case-order,
+ .filter-heading #manage-project-order,
+ .case-reorder-controls button,
+ .trash-item-actions button,
+ .detail-delete-action { min-height: 44px; }
.topbar {
grid-template-columns: auto minmax(0, 1fr);
grid-template-areas:
@@ -779,7 +908,7 @@ button[aria-busy="true"] { cursor: progress; }
.top-actions { gap: 5px; }
.top-actions button, .package-menu > summary { min-height: 38px; padding: 7px 9px; font-size: 12px; white-space: nowrap; }
.top-actions .package-menu-panel,
- .top-actions .add-menu .package-menu-panel { top: 118px; right: 12px; left: 12px; width: auto; max-height: calc(100dvh - 130px); }
+ .top-actions .add-menu .package-menu-panel { position: fixed; top: 118px; right: 12px; left: 12px; width: auto; max-height: calc(100dvh - 130px); }
.share-bar { position: fixed; z-index: 44; top: auto; right: 10px; bottom: 10px; left: 10px; min-height: 62px; border: 1px solid var(--selection-edge); border-radius: 11px; padding: 8px 10px; box-shadow: var(--shadow); }
.share-bar > span { display: none; }
.share-bar > div { margin-left: auto; }
@@ -815,6 +944,7 @@ button[aria-busy="true"] { cursor: progress; }
.dimension-picker { width: 100%; }
.facet-name-form, .tag-create-form, .inline-form, .node-actions, .compact-settings-form { grid-template-columns: 1fr; }
.entry-tag-add { grid-template-columns: 1fr; }
+ .entry-edit-row { grid-template-columns: minmax(0, 1fr) auto; }
.node-term-fields, .pending-case-head { grid-template-columns: 1fr; }
.facet-name-form button, .tag-create-form button, .node-actions button { justify-self: start; }
.compact-settings-form h3, .compact-settings-form button { grid-column: auto; }
@@ -837,7 +967,7 @@ button[aria-busy="true"] { cursor: progress; }
.video-poster-badge { position: absolute; right: 8px; bottom: 8px; border-radius: 999px; padding: 4px 8px; color: #fff; background: rgba(7, 11, 14, .78); font-size: 10px; font-weight: 800; text-transform: capitalize; }
.case-text-cover { display: grid; min-height: 190px; align-content: start; gap: 10px; padding: 18px; background: var(--raised); }
.case-text-kind, .document-type-badge { width: max-content; border-radius: 999px; padding: 4px 7px; color: var(--accent-ink); background: var(--accent-soft); font-size: 10px; font-weight: 850; letter-spacing: .08em; }
-.case-text-title { overflow: hidden; font-size: 15px; text-overflow: ellipsis; white-space: nowrap; }
+.case-text-title { overflow-wrap: anywhere; font-size: 15px; }
.case-text-excerpt { display: -webkit-box; margin: 0; overflow: hidden; color: var(--muted); font-size: 12px; line-height: 1.65; -webkit-box-orient: vertical; -webkit-line-clamp: 6; white-space: pre-wrap; }
.case-pdf-cover { position: relative; display: grid; min-height: 210px; overflow: hidden; background: var(--raised); }
.case-pdf-cover .pdf-preview { width: 100%; min-height: 210px; object-fit: cover; object-position: top; }
@@ -991,7 +1121,7 @@ button[aria-busy="true"] { cursor: progress; }
.package-menu-panel button { border-radius: var(--ui-control-radius); }
.share-bar { background: var(--bar); }
-.workspace { grid-template-columns: 248px minmax(0, 1fr); min-height: calc(100vh - 64px); }
+.workspace { grid-template-columns: var(--sidebar-width, 244px) 6px minmax(0, 1fr); min-height: calc(100vh - 64px); }
.filter-sidebar {
top: 64px;
height: calc(100vh - 64px);
@@ -1075,6 +1205,7 @@ button[aria-busy="true"] { cursor: progress; }
.top-actions .package-menu-panel, .top-actions .add-menu .package-menu-panel { top: 112px; }
.gallery-heading.project-selection-mode { top: 112px; }
.workspace { grid-template-columns: 216px minmax(0, 1fr); }
+ .sidebar-resizer { display: none; }
.filter-sidebar { top: 112px; height: calc(100vh - 112px); }
.detail-drawer { --detail-panel-width: clamp(340px, 42vw, 440px); }
.compatibility-settings-grid { grid-template-columns: 1fr; }
@@ -1103,6 +1234,9 @@ button[aria-busy="true"] { cursor: progress; }
.detail-drawer { transform: translateY(8px); }
.detail-drawer.open { transform: translateY(0); }
.detail-section { padding-inline: 16px; }
+ .trash-item { grid-template-columns: 58px minmax(0, 1fr); }
+ .trash-item-cover { width: 58px; }
+ .trash-item-actions { grid-column: 1 / -1; justify-content: flex-end; }
.ai-routing-card, .video-analysis-header, .video-analysis-record > header { align-items: stretch; flex-direction: column; }
.import-dialog { width: 100vw; height: 100dvh; max-height: none; border-radius: 0; }
.import-dialog-body { max-height: none; }
@@ -1110,12 +1244,15 @@ button[aria-busy="true"] { cursor: progress; }
.import-summary span:nth-child(3) { border-left: 0; border-top: 1px solid var(--line); }
.import-summary span:nth-child(4) { border-top: 1px solid var(--line); }
.import-options { grid-template-columns: 1fr; align-items: stretch; }
+ .capture-permission-list { grid-template-columns: 1fr; }
.data-safety-actions.import-actions { position: sticky; bottom: 0; flex-wrap: wrap; background: var(--card); }
.import-actions #import-cancel { margin-right: 0; }
}
@media (max-width: 390px) {
.compatibility-settings-grid { grid-template-columns: 1fr; }
+ .detail-new-project { grid-template-columns: 1fr; }
+ .detail-new-project button { justify-self: start; }
.import-summary { grid-template-columns: 1fr; }
.import-summary span + span { border-top: 1px solid var(--line); border-left: 0; }
.detail-visual-gallery.is-video-detail .detail-visual-caption { align-items: flex-start; flex-direction: column; }
diff --git a/library.html b/library.html
index 09158ae..768cac6 100644
--- a/library.html
+++ b/library.html
@@ -23,10 +23,9 @@
<div><strong class="brand-wordmark">PromptDirector</strong><h1 id="library-title">视觉创作资料库</h1></div>
</div>
<label class="global-search">
- <span class="sr-only" data-i18n="搜索提示词、来源或创作属性">搜索提示词、来源或创作属性</span>
+ <span class="sr-only" data-i18n="搜索提示词、来源或 AI 标签">搜索提示词、来源或 AI 标签</span>
<input id="search-input" type="search" placeholder="搜索画面、提示词,或输入 type:video…" data-i18n-placeholder="搜索画面、提示词,或输入 type:video…" />
</label>
- <p id="library-summary"></p>
<div class="top-actions">
<details id="add-menu" class="package-menu add-menu">
<summary class="button-secondary" data-i18n="添加">添加</summary>
@@ -37,8 +36,8 @@
</div>
</details>
<button id="start-compose" type="button" data-i18n="开始创作">开始创作</button>
- <button id="open-settings" class="icon-button" type="button" aria-label="设置" data-i18n-aria-label="设置" title="设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-settings"></use></svg></button>
- <input id="media-file" class="sr-only" type="file" multiple accept="image/png,image/jpeg,image/webp,image/gif,video/mp4,video/webm,video/quicktime,video/x-matroska,video/x-msvideo,application/pdf,text/plain,text/markdown,text/html,.gif,.mov,.mkv,.avi,.md,.txt,.html" />
+ <button id="open-settings" class="icon-button settings-entry-button" type="button" aria-label="设置" data-i18n-aria-label="设置" title="设置"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-settings"></use></svg><span id="settings-update-badge" class="settings-update-badge" aria-label="有可用更新" hidden></span></button>
+ <input id="media-file" class="sr-only" type="file" multiple />
<input id="media-folder" class="sr-only" type="file" multiple webkitdirectory />
</div>
</header>
@@ -56,8 +55,12 @@
<button id="clear-filters" class="button-secondary" type="button" disabled data-i18n="清除全部筛选">清除全部筛选</button>
</div>
<section id="project-section" class="project-section">
- <div class="filter-heading"><strong data-i18n="项目">项目</strong><button id="create-collection" type="button" data-i18n="新建项目">新建项目</button></div>
- <div id="collection-filters" class="project-list"></div>
+ <div class="filter-heading"><strong data-i18n="项目">项目</strong><span><button id="create-collection" type="button" data-i18n="新建项目">新建项目</button><button id="manage-project-order" class="icon-button" type="button" aria-label="管理项目顺序" title="管理项目顺序"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-sliders-horizontal"></use></svg></button></span></div>
+ <div id="collection-filters" class="project-list" role="list"></div>
+ <p id="project-order-status" class="sr-only" role="status" aria-live="polite"></p>
+ </section>
+ <section class="sidebar-trash-section">
+ <button id="open-trash" class="workspace-navigation-item" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-trash-2"></use></svg><span>回收站</span><strong id="trash-count" class="workspace-navigation-count" hidden></strong></button>
</section>
<section class="filter-section">
<div class="filter-heading"><strong data-i18n="内容类型">内容类型</strong><button id="manage-facets" type="button" data-i18n="分类与标签">整理</button></div>
@@ -69,21 +72,30 @@
<div id="facet-filters" class="facet-filters"></div>
</section>
</aside>
+ <div id="sidebar-resizer" class="sidebar-resizer" role="separator" tabindex="0" aria-label="调整项目侧栏宽度" aria-orientation="vertical" aria-valuemin="216" aria-valuemax="420" aria-valuenow="244"></div>
<main class="gallery-shell">
<div id="gallery-heading" class="gallery-heading">
<strong id="result-count"></strong>
- <button id="select-cases" class="icon-button gallery-select-button" type="button" aria-label="选择案例" data-i18n-aria-label="选择案例" title="选择案例"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-check"></use></svg></button>
+ <div id="gallery-view-controls" class="gallery-view-controls">
+ <label class="gallery-sort-field"><span class="sr-only">案例排序</span><select id="gallery-sort" aria-label="案例排序"><option value="added-desc">最近加入</option><option value="updated-desc">最近更新</option><option value="title">标题</option><option id="project-manual-sort-option" value="project-manual" hidden>手动排序</option></select></label>
+ <button id="manage-case-order" class="icon-button" type="button" aria-label="管理案例顺序" title="管理案例顺序" hidden><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-sliders-horizontal"></use></svg></button>
+ <button id="select-cases" class="icon-button gallery-select-button" type="button" aria-label="选择案例" data-i18n-aria-label="选择案例" title="选择案例"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-square-check-big"></use></svg></button>
+ </div>
<div id="share-bar" class="share-bar" hidden>
- <strong id="share-count" data-i18n="选择案例">选择案例</strong>
- <span id="selection-hint" data-i18n="选择后再决定如何使用">选择后再决定如何使用</span>
+ <strong id="share-count">已选 0</strong>
<div id="selection-simple-actions">
+ <button id="selection-select-filtered" class="button-secondary" type="button">全选筛选结果</button>
+ <button id="selection-clear" class="button-secondary" type="button" disabled>清空</button>
+ <label class="selection-label-field"><span class="sr-only">批量添加标签</span><input id="selection-label-input" type="text" placeholder="添加标签" autocomplete="off" /></label>
+ <button id="selection-add-labels" class="button-secondary" type="button" disabled>添加标签</button>
<select id="selection-project-target" aria-label="选择目标项目" data-i18n-aria-label="选择目标项目"><option value="" data-i18n="加入项目…">加入项目…</option></select>
<button id="selection-add-project" class="button-secondary" type="button" disabled data-i18n="加入">加入</button>
<button id="selection-new-project" class="button-secondary" type="button" disabled data-i18n="新建项目">新建项目</button>
<button id="selection-combine" class="button-secondary" type="button" disabled data-i18n="组合">组合</button>
<button id="selection-analyze" class="button-secondary" type="button" disabled data-i18n="批量分析画面">批量分析画面</button>
<button id="share-export" type="button" disabled data-i18n="分享">分享</button>
+ <button id="selection-trash" class="quiet-danger" type="button" disabled>移入回收站</button>
<button id="share-cancel" class="button-secondary" type="button" data-i18n="取消">取消</button>
</div>
</div>
@@ -140,6 +152,21 @@
</div>
</dialog>
+ <dialog id="trash-dialog" class="data-safety-dialog trash-dialog" aria-labelledby="trash-dialog-title">
+ <header class="data-safety-header">
+ <div><h2 id="trash-dialog-title">回收站</h2></div>
+ <button id="trash-close" class="icon-button" type="button" aria-label="关闭回收站" title="关闭回收站"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-x"></use></svg></button>
+ </header>
+ <div class="data-safety-body trash-dialog-body">
+ <div id="trash-list" class="trash-list" aria-live="polite"></div>
+ <p id="trash-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
+ </div>
+ <footer class="data-safety-actions trash-actions">
+ <button id="trash-restore-all" class="button-secondary" type="button">全部恢复</button>
+ <button id="trash-empty" class="quiet-danger" type="button" disabled>清空回收站</button>
+ </footer>
+ </dialog>
+
<dialog id="import-dialog" class="data-safety-dialog import-dialog" aria-labelledby="import-dialog-title">
<header class="data-safety-header">
<div><p class="eyebrow">LOCAL IMPORT</p><h2 id="import-dialog-title">确认导入</h2></div>
@@ -150,7 +177,7 @@
<div class="import-drop-zone">
<svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-upload"></use></svg>
<strong>拖入文件或文件夹</strong>
- <span>自动识别图片、视频、PDF、Markdown、HTML、RTF 和纯文本,统一进入预检与重复检测</span>
+ <span>自动识别图片、视频、音频、字幕、文档和常用创作源文件;不支持的格式仍可保留本机链接</span>
<button id="import-choose-files" type="button">选择文件</button>
<button id="add-folder" class="import-folder-link" type="button">选择整个文件夹</button>
</div>
@@ -165,9 +192,13 @@
<span><strong id="import-byte-size">0 B</strong> 预计占用</span>
</div>
<div class="import-options">
- <label><span>目标项目</span><select id="import-project"></select></label>
+ <label class="import-project-field"><span>项目</span><input id="import-project" autocomplete="off" placeholder="选择已有项目或输入新项目名" /><small id="import-project-hint"></small></label>
<label class="import-check"><input id="import-auto-analyze" type="checkbox" /><span>导入后自动画面分析</span></label>
</div>
+ <div class="import-label-field">
+ <span>添加标签</span>
+ <div id="import-label-editor" class="import-label-editor"></div>
+ </div>
<div id="import-file-list" class="import-file-list" aria-label="待导入文件"></div>
<p id="import-feedback" class="import-feedback" role="status" aria-live="polite"></p>
</section>
@@ -217,6 +248,21 @@
<label><span data-i18n="分享包下载路径">分享包下载路径</span><input id="export-path-setting" autocomplete="off" /></label>
<div><button id="save-library-settings" class="button-secondary" type="button" disabled data-i18n="保存设置">保存设置</button></div>
</section>
+ <section class="settings-general-section capture-permission-settings">
+ <div class="section-heading section-heading-tight"><div><h3>采集权限</h3><p>仅在你主动截图、采集网页或提取剪贴板时使用。</p></div></div>
+ <div class="capture-permission-list">
+ <div class="capture-permission-row">
+ <div><strong>网页采集与截图</strong><span id="capture-web-permission-status">正在检查…</span></div>
+ <button id="revoke-capture-web-permission" class="button-secondary" type="button" disabled>撤销</button>
+ </div>
+ <div class="capture-permission-row">
+ <div><strong>剪贴板提取</strong><span id="capture-clipboard-permission-status">正在检查…</span></div>
+ <button id="revoke-capture-clipboard-permission" class="button-secondary" type="button" disabled>撤销</button>
+ </div>
+ </div>
+ <p id="capture-permission-settings-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
+ <p class="data-safety-note">这里不会读取剪贴板。撤销后,下次主动使用对应采集功能时会重新说明用途并由你确认。</p>
+ </section>
<section id="data-safety-dialog" class="settings-general-section settings-data-safety">
<div class="section-heading section-heading-tight"><div><h3 data-i18n="备份与同步">备份与同步</h3><p>备份、恢复或连接自己的同步文件夹。</p></div></div>
<section class="data-safety-summary">
@@ -249,7 +295,21 @@
</details>
</section>
<footer class="settings-about">
- <strong id="about-version">PromptDirector</strong>
+ <div class="settings-about-heading">
+ <div><strong id="about-version">PromptDirector</strong><span id="update-channel">正在确认安装方式…</span></div>
+ <strong id="update-status" class="update-status-badge">正在检查</strong>
+ </div>
+ <div class="settings-update-details">
+ <span id="update-checked-at">最近检查:—</span>
+ <span id="update-available-version">可用版本:—</span>
+ </div>
+ <p id="update-explanation" class="settings-update-explanation">商店版由 Chrome 自动更新;本地开发版可安全重载当前目录。</p>
+ <div class="settings-update-actions">
+ <button id="check-extension-update" class="button-secondary" type="button">检查更新</button>
+ <button id="apply-extension-update" type="button" hidden></button>
+ <a id="update-release-link" class="button-primary update-download-action" href="https://github.com/wchao6891/PromptDirector/releases" target="_blank" rel="noopener noreferrer" hidden>下载新版本</a>
+ </div>
+ <p id="update-feedback" class="data-safety-feedback" role="status" aria-live="polite"></p>
<span>免费、开源、本地优先 · Apache-2.0</span>
<a class="source-link" href="https://github.com/wchao6891/PromptDirector" target="_blank" rel="noopener noreferrer">github.com/wchao6891/PromptDirector</a>
</footer>
@@ -276,19 +336,18 @@
</div>
<details class="advanced-reanalysis"><summary>重建标签系统</summary><p>付费重跑全部文字案例;结果先暂存,全部成功后一次切换,并可完整撤回。</p><div class="batch-actions"><button id="preview-analysis-reanalyze" class="button-secondary" type="button">预览重建费用</button><button id="start-analysis-reanalyze" type="button" disabled hidden>确认付费并重建</button></div></details>
</div>
- <div class="batch-card">
- <h3 data-i18n="本地资料补全">本地资料补全</h3>
- <p data-i18n="在本机补齐内容类型和图片色卡,不调用 AI、不发送图片。任务会在后台分批运行,可以随时暂停。">在本机补齐内容类型和图片色卡,不调用 AI、不发送图片。任务会在后台分批运行,可以随时暂停。</p>
+ <div class="batch-card local-index-card">
+ <h3>补全资料索引</h3>
+ <p>补齐导入案例的内容类型和图片色卡,用于分类筛选、颜色展示和相似资料匹配;全程在本机运行,不调用 AI。</p>
<div class="batch-actions">
<button id="preview-reanalyze" type="button" data-i18n="检查缺失项">检查缺失项</button>
- <button id="apply-reanalyze" type="button" disabled data-i18n="开始后台补全">开始后台补全</button>
+ <button id="apply-reanalyze" type="button" hidden>开始补全</button>
<button id="pause-library-maintenance" class="button-secondary" type="button" hidden data-i18n="暂停">暂停</button>
<button id="resume-library-maintenance" type="button" hidden data-i18n="继续">继续</button>
<button id="retry-library-maintenance" class="button-secondary" type="button" hidden data-i18n="重试失败项">重试失败项</button>
<button id="cancel-library-maintenance" class="quiet-danger" type="button" hidden data-i18n="取消">取消</button>
</div>
- <div id="maintenance-progress" class="maintenance-progress" hidden><progress id="maintenance-progress-bar" max="1" value="0"></progress></div>
- <div id="reanalyze-preview" class="reanalyze-preview"></div>
+ <div id="reanalyze-preview" class="reanalyze-preview" role="status" aria-live="polite"></div>
</div>
<div id="legacy-candidates" class="batch-card"></div>
</section>
diff --git a/library.js b/library.js
index db8a345..68bd3be 100644
--- a/library.js
+++ b/library.js
@@ -11,18 +11,21 @@ import {
saveDerivedMedia,
saveMediaBlob
} from "./media-store.js";
-import { parseCompleteFolderBackup, parseLibraryPackage } from "./library-package.js";
+import { parseCompleteFolderBackup, parseLibraryPackage, projectPackageEntryIds } from "./library-package.js";
import { parseCreativeExperimentPackage } from "./creative-experiment-package.js";
import { readZipBlob } from "./zip.js";
import {
+ ASSET_IMPORT_FAILURE_CODES,
PORTABLE_LIBRARY_LIMITS,
assertImageDimensions,
- formatBytes
+ formatBytes,
+ importFailureDetails
} from "./resource-limits.js";
import {
facetNodes,
formatFacetNodePath,
- normalizeFacetCatalog
+ normalizeFacetCatalog,
+ uniqueNames
} from "./facets.js";
import { createDetailOrganizationChunks, detailNavigation } from "./tag-taxonomy.js";
import {
@@ -97,6 +100,13 @@ import {
materializeLogicalCases,
normalizeCompoundCases
} from "./compound-cases.js";
+import {
+ LIBRARY_BATCH_ACTIONS,
+ buildLibraryBatchPayload,
+ clearLibrarySelection,
+ selectAllFilteredLogicalCases,
+ toggleLibraryCaseSelection
+} from "./library-selection.js";
import { bindTransientMenus } from "./transient-menu.js";
import { bindVideoHoverPreview } from "./video-hover-preview.js";
import { CONTENT_ROLES, CONTENT_TYPE_VISIBILITY, contentRoleForEntry } from "./taxonomy.js";
@@ -118,20 +128,39 @@ import { markdownPlainText, renderMarkdownDocument } from "./markdown-renderer.j
import { COLLECTION_VISIBILITY, isEntryVisibleInLibrary } from "./organizer.js";
import { promptForEntryImage, visualAnalysisPromptReplacement } from "./image-prompt.js";
import {
+ CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY,
+ CLIPBOARD_READ_PERMISSIONS,
+ CONTINUOUS_CAPTURE_ORIGINS,
+ inspectCapturePermissionBundle
+} from "./capture-permissions.js";
+import {
+ LOCAL_ASSET_FILE_ACCEPT,
+ createUnsupportedLocalAssetReference,
extractLocalDocumentText,
findExactMediaDuplicate,
prepareLocalMedia as prepareSharedLocalMedia
} from "./local-media.js";
+import {
+ LOCAL_ASSET_LINK_STATUS,
+ deleteLocalAssetHandle,
+ getLocalAssetHandleRecord,
+ inspectLocalAssetHandle,
+ saveLocalAssetHandle
+} from "./local-asset-store.js";
import {
LIBRARY_RETURN_STORAGE_KEY,
parseLibraryReturnSnapshot,
serializeLibraryReturnSnapshot
} from "./navigation-state.js";
import { CURATED_SUBMISSION_URL } from "./curated-config.js";
+import { moveProjectLogicalCase, sortLibraryCases, sortProjects } from "./library-view.js";
+import { createTagEditor, normalizeTagValue } from "./tag-editor.js";
+import { attachProjectCombobox } from "./project-combobox.js";
+import { SIDEBAR_WIDTH_LIMITS, normalizeSidebarWidth } from "./preferences.js";
-const uiPreferences = await initializeUi();
+let uiPreferences = await initializeUi();
bindUiPreferenceReload();
-bindTransientMenus(document, ".package-menu, .project-menu, .detail-analysis-menu");
+bindTransientMenus(document, ".package-menu, .project-menu, .detail-analysis-menu, .detail-project-menu");
const libraryWindowId = (await chrome.windows.getCurrent()).id;
const elements = Object.fromEntries([
@@ -145,23 +174,26 @@ const elements = Object.fromEntries([
"creative-experiment-file", "export-creative-experiments", "import-creative-experiments",
"create-node-form", "delete-content-type", "detail-close", "detail-content", "detail-drawer", "detail-navigation", "detail-next",
"detail-prev", "drawer-backdrop", "drawer-toolbar", "empty-filter", "empty-library", "empty-state",
- "facet-filters", "feedback", "filter-sidebar", "gallery-heading", "legacy-candidates", "library-summary",
+ "facet-filters", "feedback", "filter-sidebar", "sidebar-resizer", "gallery-heading", "gallery-sort", "gallery-view-controls", "manage-case-order", "project-manual-sort-option", "legacy-candidates",
"image-lightbox", "image-lightbox-close", "image-lightbox-image", "library-title", "load-more", "load-sentinel", "manage-facets", "manager-close", "manager-dialog", "manager-feedback",
"manager-pending", "manager-content-types", "manager-vocabulary", "new-node-aliases",
"new-node-name", "new-node-parent", "pending-count", "pending-filter",
"add-quick-note", "organize-detail-tags", "organize-detail-status", "pause-analysis-batch", "pause-library-maintenance", "preview-analysis-batch", "preview-analysis-reanalyze", "preview-reanalyze", "reanalyze-preview", "result-count", "resume-analysis-batch", "resume-library-maintenance", "retry-analysis-failures", "retry-library-maintenance", "start-analysis-reanalyze",
- "project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "restore-analysis-default", "search-input", "selection-hint", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library",
+ "project-selection-actions", "project-selection-cancel", "project-selection-clear", "project-selection-count", "project-selection-save", "project-selection-select-all", "project-selection-select-filtered", "project-selection-title", "project-order-status", "restore-analysis-default", "search-input", "share-bar", "share-cancel", "share-count", "share-export", "start-analysis-batch", "start-compose", "toggle-filters", "undo-analysis-batch", "undo-facet", "vocabulary-facet", "workspace-library",
"share-dialog", "share-dialog-close", "share-dialog-title", "share-dialog-meta", "share-dialog-options", "share-dialog-export", "share-dialog-submit", "share-dialog-disclosure", "share-dialog-result", "share-dialog-result-text", "share-dialog-show-files", "share-dialog-open-form",
- "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-add-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-project-target", "open-settings", "settings-dialog", "settings-close",
- "project-section", "selection-simple-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree", "maintenance-progress", "maintenance-progress-bar",
+ "add-menu", "export-path-setting", "media-file", "media-folder", "library-name-setting", "save-library-settings", "select-cases", "selection-select-filtered", "selection-clear", "selection-label-input", "selection-add-labels", "selection-add-project", "selection-new-project", "selection-combine", "selection-analyze", "selection-project-target", "selection-trash", "open-settings", "settings-dialog", "settings-close", "settings-update-badge", "update-channel", "update-status", "update-checked-at", "update-available-version", "update-explanation", "check-extension-update", "apply-extension-update", "update-release-link", "update-feedback",
+ "project-section", "manage-project-order", "selection-simple-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",
"vision-instructions-en", "vision-instructions-zh", "vision-protocol", "vision-settings-form", "vision-settings-status", "restore-vision-default",
- "open-curated", "open-skills", "data-safety-dialog", "data-safety-count", "data-safety-status", "data-safety-feedback",
- "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder",
+ "open-curated", "open-skills", "open-trash", "trash-count", "trash-dialog", "trash-close", "trash-list", "trash-feedback", "trash-restore-all", "trash-empty", "data-safety-dialog", "data-safety-count", "data-safety-status", "data-safety-feedback",
+ "sync-settings", "data-safety-password", "sync-password", "connect-sync-folder", "unlock-sync-vault", "sync-now", "create-folder-backup", "restore-folder-backup", "import-library-package", "library-package-file", "disconnect-sync-folder", "capture-web-permission-status", "capture-clipboard-permission-status", "revoke-capture-web-permission", "revoke-capture-clipboard-permission", "capture-permission-settings-feedback",
"vision-batch-dialog", "vision-batch-close", "vision-batch-summary", "vision-batch-service", "vision-batch-all-images", "vision-batch-reanalyze",
"vision-batch-start", "vision-batch-pause", "vision-batch-resume", "vision-batch-retry", "vision-batch-cancel", "vision-batch-feedback",
- "library-drop-target", "import-dialog", "import-dialog-title", "import-close", "import-source", "import-choose-files", "import-last-job", "import-actions", "import-preparing", "import-confirmation", "import-supported-count", "import-skipped-count", "import-duplicate-count", "import-byte-size", "import-project", "import-auto-analyze", "import-file-list", "import-feedback", "import-job-panel", "import-job-title", "import-job-count", "import-job-progress", "import-job-feedback", "import-cancel", "import-retry", "import-undo", "import-view-project", "import-start"
+ "library-drop-target", "import-dialog", "import-dialog-title", "import-close", "import-source", "import-choose-files", "import-last-job", "import-actions", "import-preparing", "import-confirmation", "import-supported-count", "import-skipped-count", "import-duplicate-count", "import-byte-size", "import-project", "import-project-hint", "import-auto-analyze", "import-label-editor", "import-file-list", "import-feedback", "import-job-panel", "import-job-title", "import-job-count", "import-job-progress", "import-job-feedback", "import-cancel", "import-retry", "import-undo", "import-view-project", "import-start"
].map((id) => [camel(id), document.querySelector(`#${id}`)]));
+elements.mediaFile.accept = LOCAL_ASSET_FILE_ACCEPT;
+elements.mediaFolder.accept = LOCAL_ASSET_FILE_ACCEPT;
+
const managerTabs = [...document.querySelectorAll("[data-manager-tab]")];
const settingsTabs = [...document.querySelectorAll("[data-settings-tab]")];
const settingsPanels = [...document.querySelectorAll("[data-settings-panel]")];
@@ -210,6 +242,7 @@ let classificationRules = [];
let facetCatalog = { facets: [], nodes: [] };
let settings = {};
let organizerState = { collections: [] };
+let importJobsState = { items: [] };
let aiSettings = { configured: false, consent: false, analysisModel: "deepseek-v4-flash" };
let visionSettings = normalizeVisionSettings();
let aiServiceProfiles = { gemini: { configured: false, model: "" }, xai: { configured: false, textModel: "", imageModel: "", videoModel: "" } };
@@ -222,6 +255,11 @@ let visibleEntries = [];
let renderedCount = 0;
let selectedContentId = "";
let selectedCollectionId = "";
+let caseSortMode = "added-desc";
+let caseOrderManagementActive = false;
+let projectOrderManagementActive = false;
+let projectOrderSaving = false;
+let projectDragState = null;
let selectedFacets = new Map();
let activeManagerTab = "content-types";
let selectedVocabularyFacet = "";
@@ -244,7 +282,9 @@ let activeVideoAnalysisUi = null;
let selectionMode = "";
let projectSelectionId = "";
const selectedCaseIds = new Set();
+let trashItems = [];
let shareDialogContext = null;
+let shareLocalAssetRecords = [];
let submissionDownloadIds = [];
let analysisBatchJob = null;
let visionBatchJob = null;
@@ -289,6 +329,18 @@ let importPollTimer = 0;
let importDragDepth = 0;
let externalLibraryRefreshTimer = 0;
let externalLibraryRefreshPending = false;
+let extensionUpdateStatus = null;
+
+const importTagEditor = createTagEditor({
+ placeholder: "例如:风格不错,很喜欢",
+ onChange(values) {
+ if (!pendingLocalImport) return false;
+ pendingLocalImport.customLabels = values;
+ return true;
+ }
+});
+elements.importLabelEditor.replaceChildren(importTagEditor.element);
+const importProjectCombobox = attachProjectCombobox(elements.importProject, { projects: [] });
const mobileLayout = matchMedia("(max-width: 640px)");
if (mobileLayout.matches) workspace.classList.add("filters-collapsed");
@@ -321,6 +373,10 @@ chrome.storage.onChanged.addListener((changes, areaName) => {
externalLibraryRefreshPending = true;
scheduleExternalLibraryRefresh();
});
+chrome.runtime.onMessage.addListener((message) => {
+ if (message?.type !== "EXTENSION_UPDATE_STATUS_CHANGED") return;
+ renderExtensionUpdateStatus(message.status);
+});
document.addEventListener("visibilitychange", () => {
if (!document.hidden && externalLibraryRefreshPending) scheduleExternalLibraryRefresh();
});
@@ -335,6 +391,7 @@ elements.uiTheme.value = uiPreferences.theme;
elements.uiMotion.value = uiPreferences.motion;
elements.showAnalysisDiagnostics.checked = uiPreferences.analysisDiagnostics;
elements.aboutVersion.textContent = `PromptDirector ${chrome.runtime.getManifest().version}`;
+void refreshExtensionUpdateStatus();
await refreshLibrary();
await openRequestedLibraryTarget();
await resumeImportJob();
@@ -360,6 +417,13 @@ function scheduleExternalLibraryRefresh() {
}, 80);
}
+function consumePendingExternalLibraryRefresh() {
+ externalLibraryRefreshPending = false;
+ if (!externalLibraryRefreshTimer) return;
+ clearTimeout(externalLibraryRefreshTimer);
+ externalLibraryRefreshTimer = 0;
+}
+
async function previewDeepSeekAnalysisBatch(mode = "incremental") {
const button = mode === "rebuild" ? elements.previewAnalysisReanalyze : elements.previewAnalysisBatch;
button.disabled = true;
@@ -459,9 +523,9 @@ function bindEvents() {
elements.searchInput.addEventListener("input", () => { if (!searchComposing) scheduleSearchRender(); });
elements.pendingFilter.addEventListener("change", renderStructuredFilterResults);
elements.addMedia.addEventListener("click", () => { elements.addMenu.open = false; void openLocalImportSource(); });
- elements.importChooseFiles.addEventListener("click", () => elements.mediaFile.click());
+ elements.importChooseFiles.addEventListener("click", () => void chooseLocalImportFiles());
elements.mediaFile.addEventListener("change", importLocalMediaCases);
- elements.addFolder.addEventListener("click", () => elements.mediaFolder.click());
+ elements.addFolder.addEventListener("click", () => void chooseLocalImportFolder());
elements.mediaFolder.addEventListener("change", importLocalMediaFolder);
elements.importLastJob.addEventListener("click", () => void openLatestImportJob());
elements.importClose.addEventListener("click", closeImportDialog);
@@ -483,6 +547,10 @@ function bindEvents() {
elements.addQuickNote.addEventListener("click", () => { elements.addMenu.open = false; createQuickNote(); });
elements.openSettings.addEventListener("click", () => openSettingsDialog("general"));
elements.settingsClose.addEventListener("click", () => elements.settingsDialog.close());
+ elements.checkExtensionUpdate.addEventListener("click", checkExtensionUpdate);
+ elements.applyExtensionUpdate.addEventListener("click", applyExtensionUpdate);
+ elements.revokeCaptureWebPermission.addEventListener("click", () => void revokeCapturePermission("web"));
+ elements.revokeCaptureClipboardPermission.addEventListener("click", () => void revokeCapturePermission("clipboard"));
elements.settingsDialog.addEventListener("cancel", (event) => {
if (dataSafetyOperationActive) event.preventDefault();
});
@@ -497,6 +565,13 @@ function bindEvents() {
aiAdvancedSettingsSummary?.addEventListener("click", () => preserveSettingsAnchor(aiAdvancedSettingsSummary));
elements.clearFilters.addEventListener("click", clearFilters);
elements.createCollection.addEventListener("click", () => createProjectCollection(elements.createCollection));
+ elements.gallerySort.addEventListener("change", () => {
+ caseSortMode = elements.gallerySort.value;
+ caseOrderManagementActive = false;
+ renderGalleryResults({ refreshNavigation: false });
+ });
+ elements.manageCaseOrder.addEventListener("click", toggleCaseOrderManagement);
+ elements.manageProjectOrder.addEventListener("click", toggleProjectOrderManagement);
elements.projectSelectionSelectFiltered.addEventListener("click", () => selectVisionCases("filtered"));
elements.projectSelectionSelectAll.addEventListener("click", () => selectVisionCases("all"));
elements.projectSelectionClear.addEventListener("click", clearVisionSelection);
@@ -509,7 +584,8 @@ function bindEvents() {
locale: elements.uiLocale.value,
theme: elements.uiTheme.value,
motion: elements.uiMotion.value,
- analysisDiagnostics: uiPreferences.analysisDiagnostics
+ analysisDiagnostics: uiPreferences.analysisDiagnostics,
+ sidebarWidth: uiPreferences.sidebarWidth
});
});
}
@@ -518,6 +594,7 @@ function bindEvents() {
workspace.classList.toggle("filters-collapsed");
renderFilterToggleState();
});
+ bindSidebarResize();
elements.workspaceLibrary.addEventListener("click", clearFilters);
elements.openCurated.addEventListener("click", () => {
navigateWithinPromptDirector("curated.html");
@@ -576,10 +653,27 @@ function bindEvents() {
elements.shareDialogShowFiles.addEventListener("click", showSubmissionFiles);
elements.shareDialogOpenForm.addEventListener("click", () => chrome.tabs.create({ url: CURATED_SUBMISSION_URL, active: true }));
elements.selectionCombine.addEventListener("click", saveCompoundSelection);
+ elements.selectionSelectFiltered.addEventListener("click", selectAllFilteredCases);
+ elements.selectionClear.addEventListener("click", clearSelectedCases);
+ elements.selectionLabelInput.addEventListener("input", updateSelectionBar);
+ elements.selectionLabelInput.addEventListener("keydown", (event) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ void addLabelsToSelection();
+ });
+ elements.selectionAddLabels.addEventListener("click", addLabelsToSelection);
elements.selectionAddProject.addEventListener("click", addSelectionToProject);
elements.selectionNewProject.addEventListener("click", createProjectFromSelection);
elements.selectionAnalyze.addEventListener("click", analyzeSelectedCases);
+ elements.selectionTrash.addEventListener("click", moveSelectionToTrash);
elements.selectionProjectTarget.addEventListener("change", updateSelectionBar);
+ elements.openTrash.addEventListener("click", openTrashDialog);
+ elements.trashClose.addEventListener("click", () => elements.trashDialog.close());
+ elements.trashRestoreAll.addEventListener("click", restoreAllTrashItems);
+ elements.trashEmpty.addEventListener("click", emptyTrashFromDialog);
+ elements.trashDialog.addEventListener("click", (event) => {
+ if (event.target === elements.trashDialog) elements.trashDialog.close();
+ });
elements.manageFacets.addEventListener("click", () => {
elements.managerFeedback.hidden = true;
activeManagerTab = "content-types";
@@ -771,6 +865,10 @@ async function refreshLibrary() {
facetCatalog = normalizeFacetCatalog(response.facetCatalog);
settings = response.settings ?? {};
organizerState = response.organizerState ?? { collections: [] };
+ importJobsState = response.importJobs ?? { items: [] };
+ trashItems = Array.isArray(response.trashState?.items) ? response.trashState.items : [];
+ elements.trashCount.hidden = trashItems.length === 0;
+ elements.trashCount.textContent = String(trashItems.length);
aiSettings = response.aiSettings ?? aiSettings;
visionSettings = response.visionSettings ?? visionSettings;
aiServiceProfiles = response.aiServiceProfiles ?? aiServiceProfiles;
@@ -807,7 +905,6 @@ async function refreshLibrary() {
sanitizeSelections();
caseCardCache.clear();
rebuildLibraryDerivedState();
- updateLibrarySummary();
renderGallery();
document.body.dataset.libraryState = "ready";
restoreLibraryScrollPosition();
@@ -821,7 +918,7 @@ async function refreshLibrary() {
}).catch(() => undefined);
if (elements.managerDialog.open) renderManager();
if (elements.settingsDialog.open && activeSettingsTab === "tasks") renderBatchManager();
- if (currentDetailId && logicalCases.some((entry) => entry.id === currentDetailId) && !promptEditState?.dirty) renderDetail();
+ if (currentDetailId && logicalCases.some((entry) => entry.id === currentDetailId) && !promptEditState?.dirty) await renderDetail();
if (analysisBatchJob?.status === "running") runAnalysisBatch();
scheduleMaintenanceStatusPoll();
if (response.restoredArchivedFacetCount) {
@@ -896,7 +993,7 @@ function renderGallery() {
const projectEntryIds = selectedCollectionId && selectionMode !== "project"
? new Set(organizerState.collections.find((item) => item.id === selectedCollectionId)?.entryIds ?? [])
: null;
- const galleryEntries = projectEntryIds
+ let galleryEntries = projectEntryIds
? modeEntries.filter((entry) => entry.memberEntryIds
? entry.memberEntryIds.some((id) => projectEntryIds.has(id))
: projectEntryIds.has(entry.id))
@@ -951,11 +1048,20 @@ function renderGalleryResults({ refreshNavigation }) {
pendingOnly: elements.pendingFilter.checked
}, facetCatalog);
}
+ syncGallerySortControl();
+ const project = selectedCollectionId
+ ? organizerState.collections.find((item) => item.id === selectedCollectionId)
+ : null;
+ visibleEntries = sortLibraryCases(visibleEntries, {
+ mode: caseSortMode,
+ projectEntryIds: project?.entryIds ?? []
+ });
renderedCount = 0;
imageObserver.disconnect();
reconcileInitialCaseCards();
if (refreshNavigation) {
renderProjectFilters();
+ elements.workspaceLibrary.setAttribute("aria-current", selectedCollectionId ? "false" : "page");
renderContentFilters(galleryEntries);
renderFacetFilters(galleryEntries);
}
@@ -980,10 +1086,31 @@ function renderGalleryResults({ refreshNavigation }) {
elements.pendingCount.textContent = String(pendingCount);
}
-function updateLibrarySummary() {
- const screenshots = entries.reduce((count, entry) => count + entryMediaAssets(entry)
- .filter((asset) => asset.kind === "image" && asset.usage !== "poster").length, 0);
- elements.librarySummary.textContent = translateUiMessage(`${logicalCases.length} 条案例 / ${screenshots} 张截图`);
+function projectManualOrderAvailable() {
+ return Boolean(selectedCollectionId && !selectionMode &&
+ !selectedContentId && !selectedFacets.size && !elements.pendingFilter.checked && !elements.searchInput.value.trim());
+}
+
+function syncGallerySortControl() {
+ const available = projectManualOrderAvailable();
+ if (!available) caseOrderManagementActive = false;
+ elements.projectManualSortOption.hidden = !available;
+ elements.projectManualSortOption.disabled = !available;
+ if (!available && caseSortMode === "project-manual") caseSortMode = "added-desc";
+ elements.gallerySort.value = caseSortMode;
+ elements.manageCaseOrder.hidden = !available;
+ elements.selectCases.hidden = caseOrderManagementActive;
+ const label = caseOrderManagementActive ? "完成案例排序" : "管理案例顺序";
+ elements.manageCaseOrder.setAttribute("aria-label", label);
+ elements.manageCaseOrder.title = label;
+ elements.manageCaseOrder.replaceChildren(createUiIcon(caseOrderManagementActive ? "circle-check-big" : "sliders-horizontal"));
+}
+
+function toggleCaseOrderManagement() {
+ if (!projectManualOrderAvailable()) return;
+ caseOrderManagementActive = !caseOrderManagementActive;
+ if (caseOrderManagementActive) caseSortMode = "project-manual";
+ renderGalleryResults({ refreshNavigation: false });
}
function reconcileInitialCaseCards() {
@@ -1041,6 +1168,15 @@ function syncCaseCardInteraction(card, entry) {
card.setAttribute("aria-label", translateUiMessage(selectable ? `选择案例:${entry.title}` : `查看案例:${entry.title}`));
card.setAttribute("aria-pressed", selectable ? String(selectedCaseIds.has(entry.id)) : "false");
card.setAttribute("aria-disabled", String(ineligible));
+ const manualOrder = caseOrderManagementActive && projectManualOrderAvailable() && caseSortMode === "project-manual";
+ const reorderControls = card.querySelector(".case-reorder-controls");
+ card.classList.toggle("manual-project-order", manualOrder);
+ if (reorderControls) {
+ const index = visibleEntries.findIndex((item) => item.id === entry.id);
+ const [moveUp, moveDown] = reorderControls.querySelectorAll("button");
+ moveUp.disabled = !manualOrder || index <= 0;
+ moveDown.disabled = !manualOrder || index < 0 || index >= visibleEntries.length - 1;
+ }
}
function renderNextBatch(generation = galleryGeneration) {
@@ -1159,16 +1295,59 @@ function createCaseCard(entry) {
} else card.append(createVideoLinkCover(entry, mainVisual));
} else if (mainVisual?.kind === "document") {
card.append(mainVisual.mimeType === "application/pdf" ? createPdfCaseCover(entry, mainVisual) : createTextCaseCover(entry, mainVisual));
+ } else if (mainVisual?.kind === "audio") {
+ card.append(createAudioCaseCover(entry, mainVisual));
+ } else if (mainVisual?.kind === "attachment") {
+ card.append(createSourceFileCaseCover(entry, mainVisual));
} else {
card.append(entry.text?.trim() ? createTextCaseCover(entry) : textEl("div", "case-shot-missing", "无媒体"));
}
- card.append(textEl("span", "share-check", "✓"));
+ const reorderControls = el("span", "case-reorder-controls");
+ const moveUp = el("button", "case-move-up");
+ const moveDown = el("button", "case-move-down");
+ moveUp.append(createUiIcon("chevron-left"));
+ moveDown.append(createUiIcon("chevron-right"));
+ moveUp.type = moveDown.type = "button";
+ moveUp.setAttribute("aria-label", `上移案例:${entry.title}`);
+ moveDown.setAttribute("aria-label", `下移案例:${entry.title}`);
+ moveUp.title = `上移案例:${entry.title}`;
+ moveDown.title = `下移案例:${entry.title}`;
+ moveUp.addEventListener("click", (event) => {
+ event.stopPropagation();
+ void reorderProjectCase(entry, "up", moveUp);
+ });
+ moveDown.addEventListener("click", (event) => {
+ event.stopPropagation();
+ void reorderProjectCase(entry, "down", moveDown);
+ });
+ reorderControls.addEventListener("keydown", (event) => event.stopPropagation());
+ reorderControls.append(moveUp, moveDown);
+ card.append(reorderControls, textEl("span", "share-check", "✓"));
return card;
}
+async function reorderProjectCase(entry, direction, button) {
+ if (!caseOrderManagementActive || !projectManualOrderAvailable() || caseSortMode !== "project-manual") return;
+ const collection = organizerState.collections.find((item) => item.id === selectedCollectionId);
+ const index = visibleEntries.findIndex((item) => item.id === entry.id);
+ const adjacent = visibleEntries[index + (direction === "up" ? -1 : 1)];
+ if (!collection || !adjacent) return;
+ const entryIds = moveProjectLogicalCase(collection.entryIds, entry, adjacent, direction);
+ const response = await perform(button, {
+ type: "REPLACE_COLLECTION_ENTRIES",
+ collectionId: collection.id,
+ entryIds
+ }, false);
+ if (!response?.ok) return;
+ organizerState = response.organizerState ?? organizerState;
+ renderGallery();
+}
+
function createTextCaseCover(entry, asset = null) {
const mimeLabels = { "text/plain": "TXT", "text/markdown": "MD", "text/html": "HTML" };
- const label = asset ? mimeLabels[asset.mimeType] || "DOC" : "NOTE";
+ const label = asset ? (["srt", "vtt", "ass", "ssa", "sbv", "lrc"].includes(asset.sourceFormat)
+ ? `${assetFormatLabel(asset)} 字幕`
+ : mimeLabels[asset.mimeType] || assetFormatLabel(asset) || "DOC") : "NOTE";
const cover = el("div", "case-text-cover");
cover.append(rawTextEl("span", "case-text-kind", label), rawTextEl("strong", "case-text-title", entry.title || (asset ? asset.sourceTitle : "快速笔记")));
const source = String(entry.text ?? "").trim();
@@ -1177,6 +1356,75 @@ function createTextCaseCover(entry, asset = null) {
return cover;
}
+function createAudioCaseCover(entry, asset) {
+ const cover = el("div", "case-asset-cover case-audio-cover");
+ const format = assetFormatLabel(asset);
+ cover.append(
+ rawTextEl("span", "case-text-kind", `AUDIO · ${format}`),
+ rawTextEl("strong", "case-text-title", asset.sourceTitle || entry.title || "音频")
+ );
+ const metadata = rawTextEl("p", "case-asset-meta", mediaMetadataText(asset));
+ const audio = document.createElement("audio");
+ audio.className = "case-audio-player";
+ audio.controls = true;
+ audio.preload = "metadata";
+ audio.addEventListener("click", (event) => event.stopPropagation());
+ audio.addEventListener("keydown", (event) => event.stopPropagation());
+ audio.addEventListener("loadedmetadata", () => {
+ if (!asset.durationMs && Number.isFinite(audio.duration)) {
+ metadata.textContent = mediaMetadataText({ ...asset, durationMs: Math.round(audio.duration * 1000) });
+ }
+ });
+ void mediaObjectUrl(asset.id).then((url) => { if (url) audio.src = url; });
+ cover.append(metadata, audio);
+ return cover;
+}
+
+function createSourceFileCaseCover(entry, asset) {
+ const cover = el("div", "case-asset-cover case-source-file-cover");
+ cover.append(
+ rawTextEl("span", "case-text-kind", `${assetCategoryLabel(asset)} · ${assetFormatLabel(asset)}`),
+ rawTextEl("strong", "case-text-title", asset.sourceTitle || entry.title || "创作源文件"),
+ rawTextEl("p", "case-asset-path", asset.relativePath || "本机资料"),
+ rawTextEl("p", "case-asset-meta", mediaMetadataText(asset))
+ );
+ if (asset.recordType === "local-asset-reference") {
+ cover.append(rawTextEl("span", "case-local-link-badge", "本机链接"));
+ }
+ return cover;
+}
+
+function assetCategoryLabel(asset) {
+ return ({
+ "design-source": "设计源文件",
+ "motion-project": "动效工程",
+ "editing-project": "剪辑工程",
+ "audio-project": "音频工程",
+ font: "字体",
+ "3d-vfx": "三维 / 特效",
+ "local-link": "本机源文件"
+ })[asset?.formatCategory] || (asset?.kind === "document" ? "文档" : "创作源文件");
+}
+
+function assetFormatLabel(asset) {
+ const source = String(asset?.sourceFormat || asset?.sourceTitle?.split(".").at(-1) || "FILE").trim();
+ return source ? source.toLocaleUpperCase("en-US") : "FILE";
+}
+
+function mediaMetadataText(asset) {
+ return [asset?.durationMs ? formatMediaTime(asset.durationMs) : "", assetFormatLabel(asset), asset?.byteSize ? formatBytes(asset.byteSize) : ""]
+ .filter(Boolean).join(" · ");
+}
+
+async function mediaObjectUrl(assetId) {
+ if (originalUrls.has(assetId)) return originalUrls.get(assetId);
+ const blob = await getMediaBlob(assetId);
+ if (!blob) return "";
+ const url = URL.createObjectURL(blob);
+ originalUrls.set(assetId, url);
+ return url;
+}
+
function createVideoLinkCover(entry, asset) {
const provider = mediaReferenceProviderLabel(asset.reference?.provider);
const cover = el("div", "case-video-link-cover");
@@ -1279,17 +1527,35 @@ async function extractAndCachePdfText(assetId, blob, derived) {
function renderProjectFilters() {
const fragment = document.createDocumentFragment();
- for (const collection of organizerState.collections) {
+ const collections = sortProjects(organizerState.collections, "manual");
+ const projectOrderingUnavailable = Boolean(selectionMode);
+ elements.manageProjectOrder.hidden = false;
+ elements.manageProjectOrder.disabled = projectOrderingUnavailable;
+ const managementLabel = projectOrderingUnavailable
+ ? "结束案例选择后可排序项目"
+ : projectOrderManagementActive ? "完成项目排序" : "管理项目顺序";
+ elements.manageProjectOrder.setAttribute("aria-label", managementLabel);
+ elements.manageProjectOrder.title = managementLabel;
+ elements.manageProjectOrder.replaceChildren(createUiIcon(projectOrderManagementActive ? "circle-check-big" : "sliders-horizontal"));
+ for (const [projectIndex, collection] of collections.entries()) {
const row = el("div", "project-row");
+ row.dataset.collectionId = collection.id;
+ row.setAttribute("role", "listitem");
+ row.classList.toggle("project-ordering", projectOrderManagementActive);
+ row.tabIndex = projectOrderManagementActive ? 0 : -1;
+ row.setAttribute("aria-label", projectOrderManagementActive ? `拖动排序:${collection.name},当前位置 ${projectIndex + 1}` : collection.name);
const logicalCount = new Set(collection.entryIds.map((id) => logicalIdByEntryId.get(id)).filter(Boolean)).size;
const filter = el("button", "project-filter");
filter.type = "button";
+ filter.tabIndex = projectOrderManagementActive ? -1 : 0;
filter.disabled = ["project", "vision", "combine"].includes(selectionMode);
filter.setAttribute("aria-pressed", String(selectedCollectionId === collection.id));
filter.setAttribute("aria-label", `${collection.name} ${logicalCount}`);
const meta = el("span", "project-filter-meta");
meta.append(rawTextEl("span", "project-filter-count", String(logicalCount)));
filter.addEventListener("click", () => {
+ if (projectOrderManagementActive) return;
+ caseOrderManagementActive = false;
selectedCollectionId = selectedCollectionId === collection.id ? "" : collection.id;
renderGallery();
});
@@ -1298,7 +1564,7 @@ function renderProjectFilters() {
}
filter.append(rawTextEl("span", "project-filter-name", collection.name), meta);
const menu = el("details", "project-menu");
- menu.hidden = ["project", "vision", "combine"].includes(selectionMode);
+ menu.hidden = projectOrderManagementActive || ["project", "vision", "combine"].includes(selectionMode);
const summary = el("summary", "");
summary.append(createUiIcon("ellipsis"));
summary.setAttribute("aria-label", `${t("管理项目")}:${collection.name}`);
@@ -1306,15 +1572,15 @@ function renderProjectFilters() {
const actions = el("div", "project-menu-panel");
const manage = textEl("button", "project-menu-primary", "管理案例");
const share = textEl("button", "button-secondary", "分享项目");
- const analyze = textEl("button", "button-secondary", "批量分析画面");
+ const analyze = textEl("button", "button-secondary", "批量分析");
const visibility = textEl(
"button",
"button-secondary",
- collection.visibility === COLLECTION_VISIBILITY.projectOnly ? "在全部项目中显示" : "仅在项目内显示"
+ collection.visibility === COLLECTION_VISIBILITY.projectOnly ? "资料库可见" : "仅项目可见"
);
const rename = textEl("button", "button-secondary", "重命名");
- const remove = textEl("button", "quiet-danger", "删除项目");
- const removeWithEntries = textEl("button", "quiet-danger", "删除项目及全部案例…");
+ const remove = textEl("button", "quiet-danger", "仅删除项目");
+ const removeWithEntries = textEl("button", "quiet-danger", "删除项目及案例");
manage.addEventListener("click", () => enterProjectSelection(collection.id));
share.addEventListener("click", () => shareProjectCollection(collection));
analyze.addEventListener("click", () => enterVisionSelection(collection));
@@ -1324,12 +1590,123 @@ function renderProjectFilters() {
removeWithEntries.addEventListener("click", () => deleteProjectCollectionWithEntries(collection, removeWithEntries));
actions.append(manage, analyze, share, visibility, rename, remove, removeWithEntries);
menu.append(summary, actions);
+ if (projectOrderManagementActive) bindProjectOrderInteractions(row, collection);
row.append(filter, menu);
fragment.append(row);
}
elements.collectionFilters.replaceChildren(fragment);
}
+function toggleProjectOrderManagement() {
+ if (selectionMode) return;
+ cancelProjectDrag();
+ projectOrderManagementActive = !projectOrderManagementActive;
+ renderProjectFilters();
+}
+
+function bindProjectOrderInteractions(row, collection) {
+ row.addEventListener("pointerdown", (event) => {
+ if (projectOrderSaving || event.button > 0) return;
+ event.preventDefault();
+ row.focus({ preventScroll: true });
+ projectDragState = {
+ pointerId: event.pointerId,
+ row,
+ collectionId: collection.id,
+ startY: event.clientY,
+ moved: false,
+ beforeIds: sortProjects(organizerState.collections, "manual").map((item) => item.id)
+ };
+ try { row.setPointerCapture(event.pointerId); } catch {}
+ });
+ row.addEventListener("pointermove", (event) => {
+ const drag = projectDragState;
+ if (!drag || drag.row !== row || drag.pointerId !== event.pointerId) return;
+ if (!drag.moved && Math.abs(event.clientY - drag.startY) < 4) return;
+ event.preventDefault();
+ drag.moved = true;
+ row.classList.add("is-dragging");
+ elements.collectionFilters.classList.add("is-project-dragging");
+ const siblings = [...elements.collectionFilters.querySelectorAll(":scope > .project-row")].filter((item) => item !== row);
+ const before = siblings.find((item) => event.clientY < item.getBoundingClientRect().top + item.getBoundingClientRect().height / 2);
+ let reordered = false;
+ if (before && row.nextElementSibling !== before) {
+ elements.collectionFilters.insertBefore(row, before);
+ reordered = true;
+ } else if (!before && row !== elements.collectionFilters.lastElementChild) {
+ elements.collectionFilters.append(row);
+ reordered = true;
+ }
+ if (reordered && !row.hasPointerCapture(event.pointerId)) {
+ try { row.setPointerCapture(event.pointerId); } catch {}
+ }
+ });
+ const finish = (event) => {
+ const drag = projectDragState;
+ if (!drag || drag.row !== row || drag.pointerId !== event.pointerId) return;
+ const moved = drag.moved;
+ const beforeIds = drag.beforeIds;
+ cancelProjectDrag();
+ if (!moved) return;
+ const collectionIds = projectIdsFromRenderedRows();
+ if (collectionIds.every((id, index) => id === beforeIds[index])) return;
+ void persistProjectCollectionOrder(collectionIds, collection.id);
+ };
+ row.addEventListener("pointerup", finish);
+ row.addEventListener("pointercancel", () => {
+ cancelProjectDrag();
+ renderProjectFilters();
+ });
+ row.addEventListener("keydown", (event) => {
+ if (!projectOrderManagementActive || projectOrderSaving || !["ArrowUp", "ArrowDown"].includes(event.key)) return;
+ event.preventDefault();
+ const collectionIds = sortProjects(organizerState.collections, "manual").map((item) => item.id);
+ const index = collectionIds.indexOf(collection.id);
+ const target = index + (event.key === "ArrowUp" ? -1 : 1);
+ if (index < 0 || target < 0 || target >= collectionIds.length) return;
+ [collectionIds[index], collectionIds[target]] = [collectionIds[target], collectionIds[index]];
+ void persistProjectCollectionOrder(collectionIds, collection.id);
+ });
+}
+
+function projectIdsFromRenderedRows() {
+ return [...elements.collectionFilters.querySelectorAll(":scope > .project-row")]
+ .map((row) => row.dataset.collectionId)
+ .filter(Boolean);
+}
+
+function cancelProjectDrag() {
+ const drag = projectDragState;
+ if (!drag) return;
+ if (drag.row.hasPointerCapture?.(drag.pointerId)) {
+ try { drag.row.releasePointerCapture(drag.pointerId); } catch {}
+ }
+ drag.row.classList.remove("is-dragging");
+ elements.collectionFilters.classList.remove("is-project-dragging");
+ projectDragState = null;
+}
+
+async function persistProjectCollectionOrder(collectionIds, focusCollectionId) {
+ if (projectOrderSaving) return;
+ projectOrderSaving = true;
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "REORDER_COLLECTIONS", collectionIds });
+ if (!response?.ok) throw new Error(response?.message || "项目顺序保存失败");
+ organizerState = response.organizerState ?? organizerState;
+ const ordered = sortProjects(organizerState.collections, "manual");
+ const project = ordered.find((item) => item.id === focusCollectionId);
+ const position = ordered.findIndex((item) => item.id === focusCollectionId) + 1;
+ elements.projectOrderStatus.textContent = `已将${project?.name || "项目"}移动到第 ${position} 位`;
+ renderProjectFilters();
+ queueMicrotask(() => elements.collectionFilters.querySelector(`[data-collection-id="${CSS.escape(focusCollectionId)}"]`)?.focus());
+ } catch (error) {
+ showFeedback(error.message || "项目顺序保存失败", true);
+ renderProjectFilters();
+ } finally {
+ projectOrderSaving = false;
+ }
+}
+
async function updateProjectVisibility(collection, button) {
const visibility = collection.visibility === COLLECTION_VISIBILITY.projectOnly
? COLLECTION_VISIBILITY.library
@@ -1358,7 +1735,7 @@ async function renameProjectCollection(collection) {
}
async function deleteProjectCollection(collection) {
- if (!await confirmAppAction({ title: translateUiMessage(`删除项目“${collection.name}”?`), description: t("其中案例仍会保留在资料库。"), confirmLabel: t("删除项目"), danger: true })) return;
+ if (!await confirmAppAction({ title: translateUiMessage(`将项目“${collection.name}”移入回收站?`), description: t("其中案例仍会保留在资料库,可从回收站恢复项目。"), confirmLabel: t("移入回收站"), danger: true })) return;
if (selectedCollectionId === collection.id) selectedCollectionId = "";
await perform(elements.createCollection, { type: "DELETE_COLLECTION", collectionId: collection.id });
}
@@ -1369,24 +1746,17 @@ async function deleteProjectCollectionWithEntries(collection, button) {
const mediaCount = new Set(memberEntries.flatMap((entry) =>
normalizeEntryMedia(entry).mediaAssets.map((asset) => asset.id)
)).size;
- const result = await showAppDialog({
- title: `永久删除项目“${collection.name}”?`,
- description: `将删除 ${memberEntries.length} 个案例和 ${mediaCount} 项媒体;案例也会从其他项目及组合案例中移除。请输入完整项目名称以确认。`,
- confirmLabel: "永久删除",
- danger: true,
- fields: [{ id: "confirmationName", label: "项目名称", type: "text", required: true }],
- onSubmit: ({ confirmationName }) => {
- if (confirmationName.trim() !== collection.name) throw new Error("项目名称不匹配");
- return { confirmationName: confirmationName.trim() };
- }
- });
- if (!result) return;
- const confirmationName = result.confirmationName;
+ if (!await confirmAppAction({
+ title: `将项目“${collection.name}”及全部案例移入回收站?`,
+ description: `将归档 ${memberEntries.length} 个案例和 ${mediaCount} 项媒体;可从回收站恢复。`,
+ confirmLabel: "全部移入回收站",
+ danger: true
+ })) return;
if (selectedCollectionId === collection.id) selectedCollectionId = "";
await perform(button, {
type: "DELETE_COLLECTION_WITH_ENTRIES",
collectionId: collection.id,
- confirmationName
+ confirmationName: collection.name
});
}
@@ -1396,6 +1766,8 @@ async function enterProjectSelection(collectionId) {
if (!await closeDetail()) return;
selectionMode = "project";
projectSelectionId = collection.id;
+ caseOrderManagementActive = false;
+ projectOrderManagementActive = false;
selectedCollectionId = collection.id;
selectedCaseIds.clear();
const members = new Set(collection.entryIds);
@@ -1422,6 +1794,8 @@ async function enterVisionSelection(collection) {
if (!await closeDetail()) return;
selectionMode = "vision";
projectSelectionId = collection.id;
+ caseOrderManagementActive = false;
+ projectOrderManagementActive = false;
selectedCollectionId = collection.id;
selectedCaseIds.clear();
selectedContentId = "";
@@ -1435,6 +1809,8 @@ async function enterVisionSelection(collection) {
async function enterSelectMode() {
if (!await closeDetail()) return;
selectionMode = "select";
+ caseOrderManagementActive = false;
+ projectOrderManagementActive = false;
selectedCaseIds.clear();
updateSelectionBar();
renderGallery();
@@ -1444,6 +1820,7 @@ function exitSelectionMode() {
selectionMode = "";
projectSelectionId = "";
selectedCaseIds.clear();
+ elements.selectionLabelInput.value = "";
updateSelectionBar();
renderGallery();
}
@@ -1457,11 +1834,26 @@ function exitProjectSelection() {
}
function toggleCaseSelection(entryId, card) {
- if (selectedCaseIds.has(entryId)) selectedCaseIds.delete(entryId);
- else selectedCaseIds.add(entryId);
+ replaceSelectedCaseIds(toggleLibraryCaseSelection([...selectedCaseIds], entryId));
const selected = selectedCaseIds.has(entryId);
card.classList.toggle("selected-for-share", selected);
card.setAttribute("aria-pressed", String(selected));
+}
+
+function selectAllFilteredCases() {
+ if (selectionMode !== "select") return;
+ replaceSelectedCaseIds(selectAllFilteredLogicalCases(visibleEntries.map((entry) => entry.id)));
+ renderGallery();
+}
+
+function clearSelectedCases() {
+ replaceSelectedCaseIds(clearLibrarySelection());
+ renderGallery();
+}
+
+function replaceSelectedCaseIds(values) {
+ selectedCaseIds.clear();
+ values.forEach((id) => selectedCaseIds.add(id));
updateSelectionBar();
}
@@ -1479,8 +1871,9 @@ function updateSelectionBar() {
elements.selectionSimpleActions.hidden = false;
elements.projectSelectionActions.hidden = !taskSelecting;
elements.projectSelectionTitle.hidden = !taskSelecting;
- elements.resultCount.hidden = taskSelecting;
+ elements.resultCount.hidden = Boolean(selectionMode);
elements.selectCases.hidden = Boolean(selectionMode);
+ elements.galleryViewControls.hidden = Boolean(selectionMode);
elements.projectSelectionTitle.textContent = selectionMode === "combine"
? `${t("组合案例")} · ${translateUiMessage(`已选择 ${selectedCaseIds.size} 个案例`)}`
: project
@@ -1502,24 +1895,27 @@ function updateSelectionBar() {
elements.projectSelectionSelectAll.textContent = translateUiMessage(`选中全部可分析(${allEligibleCount})`);
elements.projectSelectionClear.hidden = !visionSelection;
elements.projectSelectionClear.disabled = selectedCaseIds.size === 0;
- elements.shareCount.textContent = selectedCaseIds.size
- ? translateUiMessage(`已选择 ${selectedCaseIds.size} 个案例`)
- : t("选择案例");
- elements.selectionHint.textContent = selectedCaseIds.size
- ? (currentLocale() === "en" ? "Add to a project, combine, or share" : "现在可以加入项目、组合或分享")
- : (currentLocale() === "en" ? "Select a case to begin" : "点击案例开始选择");
+ elements.shareCount.textContent = currentLocale() === "en" ? `Selected ${selectedCaseIds.size}` : `已选 ${selectedCaseIds.size}`;
const selectedProject = elements.selectionProjectTarget.value;
const options = [option("", t("加入项目…"))];
for (const collection of organizerState.collections) options.push(option(collection.id, collection.name));
elements.selectionProjectTarget.replaceChildren(...options);
elements.selectionProjectTarget.value = organizerState.collections.some((item) => item.id === selectedProject) ? selectedProject : "";
elements.selectionAddProject.disabled = !selectedCaseIds.size || !elements.selectionProjectTarget.value;
+ elements.selectionSelectFiltered.disabled = selectionMode !== "select" || visibleEntries.length === 0;
+ elements.selectionSelectFiltered.textContent = currentLocale() === "en" ? `Select current (${visibleEntries.length})` : `全选当前(${visibleEntries.length})`;
+ elements.selectionSelectFiltered.setAttribute("aria-label", currentLocale() === "en"
+ ? `Select all ${visibleEntries.length} cases in the current filtered results`
+ : `全选当前筛选结果,共 ${visibleEntries.length} 个案例`);
+ elements.selectionClear.disabled = selectedCaseIds.size === 0;
+ elements.selectionAddLabels.disabled = !selectedCaseIds.size || !splitInput(elements.selectionLabelInput.value).length;
elements.selectionCombine.disabled = selectedCaseIds.size < 2;
elements.selectionNewProject.disabled = !selectedCaseIds.size;
elements.selectionAnalyze.disabled = ![...selectedCaseIds]
.some((id) => isVisionSelectableEntry(logicalCases.find((entry) => entry.id === id)));
elements.shareExport.textContent = t("分享");
elements.shareExport.disabled = !selectedCaseIds.size;
+ elements.selectionTrash.disabled = !selectedCaseIds.size;
elements.createCollection.disabled = taskSelecting;
}
@@ -1565,13 +1961,12 @@ async function addSelectionToProject() {
if (!collection || !selectedCaseIds.size) return;
elements.selectionAddProject.disabled = true;
try {
- const entryIds = new Set(collection.entryIds);
- expandLogicalCaseIds([...selectedCaseIds], compoundCases).forEach((id) => entryIds.add(id));
- const response = await chrome.runtime.sendMessage({
- type: "REPLACE_COLLECTION_ENTRIES",
+ const message = buildLibraryBatchPayload([...selectedCaseIds], compoundCases, {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
collectionId: collection.id,
- entryIds: [...entryIds]
+ mode: "add"
});
+ const response = await chrome.runtime.sendMessage(message);
if (!response?.ok) throw new Error(response?.message || "加入项目失败");
organizerState = response.organizerState ?? organizerState;
showFeedback(`已加入项目“${collection.name}”`);
@@ -1582,6 +1977,39 @@ async function addSelectionToProject() {
}
}
+async function addLabelsToSelection() {
+ if (!selectedCaseIds.size) return;
+ const customLabels = splitInput(elements.selectionLabelInput.value);
+ if (!customLabels.length) return elements.selectionLabelInput.focus();
+ const message = buildLibraryBatchPayload([...selectedCaseIds], compoundCases, {
+ type: LIBRARY_BATCH_ACTIONS.addCustomLabels,
+ customLabels
+ });
+ const response = await perform(elements.selectionAddLabels, message, false);
+ if (!response?.ok) return;
+ elements.selectionLabelInput.value = "";
+ exitSelectionMode();
+ await refreshLibrary();
+}
+
+async function moveSelectionToTrash() {
+ if (!selectedCaseIds.size) return;
+ const logicalCount = selectedCaseIds.size;
+ const message = buildLibraryBatchPayload([...selectedCaseIds], compoundCases, {
+ type: LIBRARY_BATCH_ACTIONS.moveToTrash
+ });
+ if (!await confirmAppAction({
+ title: `将所选 ${logicalCount} 个案例移入回收站?`,
+ description: "案例及其媒体会保留在回收站,可以恢复。",
+ confirmLabel: "移入回收站",
+ danger: true
+ })) return;
+ const response = await perform(elements.selectionTrash, message, false);
+ if (!response?.ok) return;
+ exitSelectionMode();
+ await refreshLibrary();
+}
+
async function createProjectFromSelection() {
if (!selectedCaseIds.size) return;
const name = await promptAppText({
@@ -1653,12 +2081,18 @@ async function saveCompoundSelection() {
async function saveProjectSelection() {
const collectionId = projectSelectionId;
+ const collection = organizerState.collections.find((item) => item.id === collectionId);
+ const selectedEntryIds = expandLogicalCaseIds([...selectedCaseIds], compoundCases);
+ const selected = new Set(selectedEntryIds);
+ const retainedOrder = (collection?.entryIds ?? []).filter((entryId) => selected.has(entryId));
+ const retained = new Set(retainedOrder);
+ const entryIds = [...retainedOrder, ...selectedEntryIds.filter((entryId) => !retained.has(entryId))];
elements.projectSelectionSave.disabled = true;
try {
const response = await chrome.runtime.sendMessage({
type: "REPLACE_COLLECTION_ENTRIES",
collectionId,
- entryIds: expandLogicalCaseIds([...selectedCaseIds], compoundCases)
+ entryIds
});
if (!response?.ok) throw new Error(response?.message || "项目案例保存失败");
organizerState = response.organizerState ?? organizerState;
@@ -1686,40 +2120,131 @@ function openShareDialog({ entryIds = [], collectionId = "", title = "", count =
const selectedCount = count || entryIds.length;
if (!selectedCount) return showFeedback(t("请先选择要分享的案例"), true);
shareDialogContext = { entryIds, collectionId, title, count: selectedCount };
+ shareLocalAssetRecords = [];
submissionDownloadIds = [];
elements.shareDialogTitle.textContent = title || t("分享案例");
elements.shareDialogMeta.textContent = t("{count} 个案例", { count: selectedCount });
elements.shareDialogDisclosure.checked = false;
elements.shareDialogSubmit.disabled = true;
- elements.shareDialogExport.disabled = false;
+ elements.shareDialogExport.disabled = true;
elements.shareDialogResult.hidden = true;
elements.shareDialogOptions.hidden = false;
elements.shareDialog.showModal();
- elements.shareDialogExport.focus();
+ void prepareShareLocalAssetRecords();
}
function closeShareDialog() {
if (elements.shareDialog.open) elements.shareDialog.close();
shareDialogContext = null;
+ shareLocalAssetRecords = [];
submissionDownloadIds = [];
}
+async function prepareShareLocalAssetRecords() {
+ if (!shareDialogContext) return;
+ const context = shareDialogContext;
+ try {
+ const requestedIds = context.collectionId
+ ? projectPackageEntryIds({ entries, compoundCases, organizerState }, context.collectionId)
+ : expandLogicalCaseIds(context.entryIds, compoundCases);
+ const idSet = new Set(requestedIds);
+ const linked = entries.filter((entry) => idSet.has(entry.id)).flatMap((entry) =>
+ entryMediaAssets(entry)
+ .filter((asset) => asset.recordType === "local-asset-reference")
+ .map((asset) => ({ entry, asset }))
+ );
+ const records = await Promise.all(linked.map(async (item) => ({
+ ...item,
+ record: await getLocalAssetHandleRecord(item.asset.id)
+ })));
+ if (shareDialogContext !== context) return;
+ shareLocalAssetRecords = records;
+ elements.shareDialogMeta.textContent = linked.length
+ ? `${t("{count} 个案例", { count: context.count })} · ${linked.length} 个本机源文件将在导出时检查权限`
+ : t("{count} 个案例", { count: context.count });
+ elements.shareDialogExport.disabled = false;
+ elements.shareDialogExport.focus();
+ } catch (error) {
+ if (shareDialogContext !== context) return;
+ elements.shareDialogMeta.textContent = error.message || "无法检查本机源文件链接";
+ elements.shareDialogExport.disabled = true;
+ }
+}
+
+async function authorizeShareLocalAssets() {
+ for (const item of shareLocalAssetRecords) {
+ const { entry, asset, record } = item;
+ if (!record) {
+ showFeedback(`“${asset.sourceTitle || entry.title}”的本机链接已丢失,请先在详情中重新链接`, true);
+ return false;
+ }
+ let inspection = await inspectLocalAssetHandle(record, Number.isFinite(Number(asset.sourceLastModified)) ? asset : undefined);
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION) {
+ if (typeof record.handle.requestPermission !== "function") {
+ showFeedback(`当前浏览器无法重新授权“${asset.sourceTitle}”,请先重新链接源文件`, true);
+ return false;
+ }
+ const permission = await record.handle.requestPermission({ mode: "read" });
+ if (permission !== "granted") {
+ showFeedback(`你取消了“${asset.sourceTitle}”的读取授权,分享包未导出`, true);
+ return false;
+ }
+ inspection = await inspectLocalAssetHandle(record, Number.isFinite(Number(asset.sourceLastModified)) ? asset : undefined);
+ }
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.MISSING) {
+ showFeedback(`“${asset.sourceTitle || entry.title}”已移动、改名或删除,请先重新链接;分享包未导出`, true);
+ return false;
+ }
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.CHANGED) {
+ const file = inspection.file;
+ const confirmed = await confirmAppAction({
+ title: "源文件自上次链接后发生变化",
+ description: `“${asset.sourceTitle}”现在是 ${formatBytes(file.size)}。确认后会更新文件信息并把当前版本放入分享包;取消则不导出。`,
+ confirmLabel: "使用当前版本"
+ });
+ if (!confirmed) return false;
+ await saveLocalAssetHandle(asset.id, record.handle, file);
+ const response = await chrome.runtime.sendMessage({
+ type: "UPDATE_LOCAL_ASSET_REFERENCE",
+ entryId: entry.id,
+ assetId: asset.id,
+ sourceTitle: file.name,
+ relativePath: file.name,
+ sourceFormat: file.name.split(".").at(-1)?.toLocaleLowerCase("en-US") || asset.sourceFormat,
+ mimeType: file.type || asset.mimeType || "application/octet-stream",
+ byteSize: file.size,
+ sourceLastModified: file.lastModified
+ });
+ if (!response?.ok) throw new Error(response?.message || `无法更新“${file.name}”的文件信息`);
+ item.asset = response.asset ?? { ...asset, sourceTitle: file.name, byteSize: file.size, sourceLastModified: file.lastModified };
+ item.record = await getLocalAssetHandleRecord(asset.id);
+ }
+ }
+ return true;
+}
+
async function exportFromShareDialog() {
if (!shareDialogContext) return;
+ const context = shareDialogContext;
elements.shareDialogExport.disabled = true;
try {
- const message = shareDialogContext.collectionId
- ? { type: "EXPORT_PROJECT", collectionId: shareDialogContext.collectionId }
- : { type: "EXPORT_ARCHIVE", entryIds: shareDialogContext.entryIds };
+ if (!await authorizeShareLocalAssets()) {
+ if (shareDialogContext === context) elements.shareDialogExport.disabled = false;
+ return;
+ }
+ if (shareDialogContext !== context) return;
+ const message = context.collectionId
+ ? { type: "EXPORT_PROJECT", collectionId: context.collectionId }
+ : { type: "EXPORT_ARCHIVE", entryIds: context.entryIds };
const response = await chrome.runtime.sendMessage(message);
if (!response?.ok) throw new Error(response?.message || t("无法导出分享包"));
showFeedback(response.message);
- const selected = Boolean(shareDialogContext.entryIds.length);
+ const selected = Boolean(context.entryIds.length);
closeShareDialog();
if (selected) exitSelectionMode();
} catch (error) {
showFeedback(error.message || t("无法导出分享包"), true);
- elements.shareDialogExport.disabled = false;
+ if (shareDialogContext === context) elements.shareDialogExport.disabled = false;
}
}
@@ -1782,7 +2307,8 @@ function saveLibraryReturnSnapshot() {
facetNodeIds: [...selectedFacets.values()].flatMap((nodeIds) => [...nodeIds]),
pendingOnly: elements.pendingFilter.checked,
query: elements.searchInput.value,
- scrollY: window.scrollY
+ scrollY: window.scrollY,
+ sortMode: caseSortMode
}));
} catch {
}
@@ -1800,6 +2326,7 @@ function restoreLibraryReturnSnapshot() {
selectedCollectionId = organizerState.collections.some((item) => item.id === snapshot.collectionId)
? snapshot.collectionId
: "";
+ caseSortMode = snapshot.sortMode;
selectedContentId = snapshot.contentId;
selectedFacets = new Map();
const nodesById = new Map(facetCatalog.nodes.map((node) => [node.id, node]));
@@ -1838,6 +2365,8 @@ async function openRequestedLibraryTarget() {
try { sessionStorage.removeItem(LIBRARY_RETURN_STORAGE_KEY); } catch {}
selectedContentId = "";
selectedFacets.clear();
+ caseOrderManagementActive = false;
+ projectOrderManagementActive = false;
elements.pendingFilter.checked = false;
elements.searchInput.value = "";
libraryReturnScrollY = null;
@@ -2036,7 +2565,151 @@ function renderSettingsPanels({ resetActiveScroll = false } = {}) {
if (resetActiveScroll) resetActiveSettingsPanelScroll();
if (activeSettingsTab === "ai") renderAnalysisSettings();
if (activeSettingsTab === "tasks") renderBatchManager();
- if (activeSettingsTab === "general") void renderDataSafetyStatus();
+ if (activeSettingsTab === "general") {
+ void renderDataSafetyStatus();
+ void renderCapturePermissionStatus();
+ void refreshExtensionUpdateStatus();
+ }
+}
+
+async function refreshExtensionUpdateStatus() {
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "GET_EXTENSION_UPDATE_STATUS" });
+ if (!response?.ok || !response.status) throw new Error(response?.status?.lastError || response?.message || "无法读取更新状态");
+ renderExtensionUpdateStatus(response.status);
+ } catch (error) {
+ if (!extensionUpdateStatus) renderExtensionUpdateStatus(null, error?.message || "无法读取更新状态");
+ }
+}
+
+async function checkExtensionUpdate() {
+ elements.checkExtensionUpdate.disabled = true;
+ elements.checkExtensionUpdate.setAttribute("aria-busy", "true");
+ showUpdateFeedback("正在检查更新…");
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "CHECK_EXTENSION_UPDATE" });
+ if (response?.status) renderExtensionUpdateStatus(response.status);
+ if (!response?.ok) throw new Error(response?.status?.lastError || response?.message || "检查更新失败");
+ showUpdateFeedback(updateCheckFeedback(response.status));
+ } catch (error) {
+ showUpdateFeedback(error?.message || "检查更新失败", true);
+ } finally {
+ elements.checkExtensionUpdate.disabled = false;
+ elements.checkExtensionUpdate.removeAttribute("aria-busy");
+ }
+}
+
+async function applyExtensionUpdate() {
+ const status = extensionUpdateStatus;
+ if (!status?.canApply || !status.applyBehavior) return;
+ const development = status.applyBehavior === "reload_development_directory";
+ const confirmed = await confirmAppAction(development ? {
+ title: "安全重载当前目录?",
+ description: "当前资料库页面会关闭,Chrome 会重新载入你已经选择的本地目录。不会下载或覆盖代码,本地案例和素材不会丢失。",
+ confirmLabel: "安全重载"
+ } : {
+ title: "立即应用更新并重启 PromptDirector?",
+ description: "当前资料库页面会关闭,但本地案例和素材不会丢失。",
+ confirmLabel: "应用并重启"
+ });
+ if (!confirmed) return;
+ elements.applyExtensionUpdate.disabled = true;
+ elements.applyExtensionUpdate.setAttribute("aria-busy", "true");
+ showUpdateFeedback(development ? "正在安全重载当前目录…" : "正在应用更新并重启…");
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "APPLY_EXTENSION_UPDATE" });
+ if (response?.status) renderExtensionUpdateStatus(response.status);
+ if (!response?.ok) throw new Error(response?.status?.lastError || response?.message || "无法应用更新");
+ } catch (error) {
+ showUpdateFeedback(error?.message || "无法应用更新", true);
+ elements.applyExtensionUpdate.disabled = false;
+ elements.applyExtensionUpdate.removeAttribute("aria-busy");
+ }
+}
+
+function renderExtensionUpdateStatus(nextStatus, fallbackError = "") {
+ if (nextStatus) extensionUpdateStatus = { ...(extensionUpdateStatus ?? {}), ...nextStatus };
+ const status = extensionUpdateStatus;
+ const currentVersion = status?.currentVersion || chrome.runtime.getManifest().version;
+ elements.aboutVersion.textContent = `PromptDirector ${currentVersion}`;
+ if (!status) {
+ elements.updateChannel.textContent = "安装方式暂不可用";
+ elements.updateStatus.textContent = fallbackError ? "状态不可用" : "正在检查";
+ elements.updateStatus.className = `update-status-badge${fallbackError ? " is-error" : ""}`;
+ elements.updateCheckedAt.textContent = "最近检查:—";
+ elements.updateAvailableVersion.textContent = "可用版本:—";
+ elements.updateExplanation.textContent = "重新打开设置时会再次读取更新状态。";
+ showUpdateFeedback(fallbackError, Boolean(fallbackError));
+ return;
+ }
+
+ const development = status.channel === "development";
+ elements.updateChannel.textContent = development ? "本地开发版 · 手动替换代码" : "商店版 · Chrome 自动更新";
+ const updateVersion = status.pendingVersion || status.latestVersion || "—";
+ elements.updateCheckedAt.textContent = `最近检查:${formatUpdateCheckTime(status.checkedAt)}`;
+ elements.updateAvailableVersion.textContent = `可用版本:${updateVersion}`;
+
+ const display = updateStatusDisplay(status);
+ elements.updateStatus.textContent = display.label;
+ elements.updateStatus.className = `update-status-badge ${display.className}`.trim();
+ elements.updateExplanation.textContent = updateExplanation(status);
+
+ const releaseUrl = development && status.updateAvailable ? safeHttpUrl(status.releaseUrl) : "";
+ elements.updateReleaseLink.hidden = !releaseUrl;
+ if (releaseUrl) elements.updateReleaseLink.href = releaseUrl;
+ else elements.updateReleaseLink.removeAttribute("href");
+
+ elements.applyExtensionUpdate.hidden = !status.canApply;
+ elements.applyExtensionUpdate.disabled = false;
+ elements.applyExtensionUpdate.removeAttribute("aria-busy");
+ elements.applyExtensionUpdate.classList.toggle("button-secondary", development);
+ elements.applyExtensionUpdate.textContent = status.applyBehavior === "reload_development_directory"
+ ? "重新载入目录"
+ : "应用更新并重启";
+
+ const hasUpdate = Boolean(status.updateAvailable);
+ elements.settingsUpdateBadge.hidden = !hasUpdate;
+ elements.openSettings.setAttribute("aria-label", hasUpdate ? "设置,有可用更新" : "设置");
+ elements.openSettings.title = hasUpdate ? `设置 · ${display.label}` : "设置";
+ showUpdateFeedback(status.lastError || "", Boolean(status.lastError));
+}
+
+function updateStatusDisplay(status) {
+ if (status.updateKind === "store_downloaded") return { label: "已下载,可应用", className: "is-available" };
+ if (status.updateKind === "development_release" || status.updateAvailable) return { label: "发现新版本", className: "is-available" };
+ if (status.checkStatus === "error") return { label: "检查失败", className: "is-error" };
+ if (status.checkStatus === "no_update") return { label: "已是最新", className: "is-current" };
+ if (status.checkStatus === "throttled") return { label: "刚刚检查过", className: "is-current" };
+ return { label: "自动更新", className: "" };
+}
+
+function updateExplanation(status) {
+ if (status.channel === "development") {
+ return status.updateAvailable
+ ? "发现新的 GitHub Release。扩展无法自行覆盖本机目录;请从链接下载并替换代码,再安全重载。固定 ID 升级无需导出、导入案例。"
+ : "本地开发版不会被扩展自行覆盖。安全重载只会重新载入当前目录,不会下载或安装新版本;固定 ID 升级无需导出、导入案例。";
+ }
+ return status.updateKind === "store_downloaded"
+ ? "新版本已由 Chrome 下载。立即应用会关闭当前资料库页面并重启扩展;案例和素材不会丢失。"
+ : "商店版由 Chrome 自动更新,无需反复下载插件;更新下载完成后也可以在这里立即应用。";
+}
+
+function updateCheckFeedback(status) {
+ if (status?.updateAvailable) return status.channel === "development" ? "发现新版本,可打开 Release 下载。" : "新版本已下载,可以立即应用。";
+ if (status?.checkStatus === "throttled") return "刚刚检查过,已保留最近结果。";
+ return "已是最新版本。";
+}
+
+function formatUpdateCheckTime(value) {
+ if (!value) return "尚未检查";
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return "尚未检查";
+ return date.toLocaleString(currentLocale() === "en" ? "en" : "zh-CN");
+}
+
+function showUpdateFeedback(message, isError = false) {
+ elements.updateFeedback.textContent = message || "";
+ elements.updateFeedback.classList.toggle("error", isError);
}
function resetActiveSettingsPanelScroll() {
@@ -2188,11 +2861,20 @@ async function restoreCompleteFolderBackup() {
try { library = JSON.parse(await libraryFile.text()); }
catch { throw new Error("library.json 已损坏,无法恢复"); }
const backupPaths = backupMediaPaths(library);
- const totalBytes = [...backupPaths].reduce((sum, path) => sum + (files.get(path)?.size ?? 0), 0);
+ const backupMediaSizes = [...backupPaths].map((path) => files.get(path)?.size ?? 0);
+ const totalBytes = backupMediaSizes.reduce((sum, size) => sum + size, 0);
if (completion.mediaCount !== backupPaths.size || completion.byteSize !== totalBytes) {
throw new Error("完整备份的媒体数量或大小校验失败,未写入资料库");
}
- const parsed = await parseCompleteFolderBackup(library, files, { maxFileBytes: Number.MAX_SAFE_INTEGER });
+ const largestMediaBytes = Math.max(1, ...backupMediaSizes);
+ const restoreLimits = {
+ ...PORTABLE_LIBRARY_LIMITS,
+ maxArchiveBytes: Math.max(1, totalBytes),
+ maxFileBytes: largestMediaBytes,
+ maxImageBytes: largestMediaBytes,
+ maxVideoBytes: largestMediaBytes
+ };
+ const parsed = await parseCompleteFolderBackup(library, files, restoreLimits);
await validateImportedImageDimensions(parsed.images);
const restoredLibrary = { ...parsed };
delete restoredLibrary.assets;
@@ -2254,7 +2936,14 @@ async function importSharedLibraryPackage() {
setDataSafetyBusy(true);
try {
showDataSafetyFeedback(`正在检查 ${file.name}`);
- const files = await readZipBlob(file);
+ const packageLimits = {
+ ...PORTABLE_LIBRARY_LIMITS,
+ maxArchiveBytes: file.size,
+ maxFileBytes: file.size,
+ maxImageBytes: file.size,
+ maxVideoBytes: file.size
+ };
+ const files = await readZipBlob(file, packageLimits);
const libraryFile = files.get("library.json");
if (!libraryFile) throw new Error("分享包缺少 library.json");
if (libraryFile.size > PORTABLE_LIBRARY_LIMITS.maxLibraryJsonBytes) {
@@ -2263,7 +2952,7 @@ async function importSharedLibraryPackage() {
let library;
try { library = JSON.parse(await libraryFile.text()); }
catch { throw new Error("分享包中的 library.json 已损坏"); }
- const parsed = parseLibraryPackage(library, files);
+ const parsed = parseLibraryPackage(library, files, packageLimits);
await validateImportedImageDimensions(parsed.images);
const importLibrary = { ...parsed };
delete importLibrary.assets;
@@ -2763,8 +3452,65 @@ function renderFilterToggleState() {
elements.toggleFilters.title = label;
}
+function sidebarWidthLimit() {
+ return Math.max(SIDEBAR_WIDTH_LIMITS.min, Math.min(SIDEBAR_WIDTH_LIMITS.max, Math.floor(innerWidth * 0.45)));
+}
+
+function applySidebarWidth(value) {
+ const width = Math.min(normalizeSidebarWidth(value), sidebarWidthLimit());
+ workspace.style.setProperty("--sidebar-width", `${width}px`);
+ elements.sidebarResizer.setAttribute("aria-valuemax", String(sidebarWidthLimit()));
+ elements.sidebarResizer.setAttribute("aria-valuenow", String(width));
+ return width;
+}
+
+async function saveSidebarWidth(value) {
+ const sidebarWidth = normalizeSidebarWidth(value);
+ uiPreferences = await updateUiPreferences({ ...uiPreferences, sidebarWidth });
+ applySidebarWidth(sidebarWidth);
+}
+
+function bindSidebarResize() {
+ applySidebarWidth(uiPreferences.sidebarWidth);
+ let pointerId = null;
+ let originX = 0;
+ let originWidth = uiPreferences.sidebarWidth;
+ elements.sidebarResizer.addEventListener("pointerdown", (event) => {
+ if (innerWidth <= 900 || workspace.classList.contains("filters-collapsed")) return;
+ pointerId = event.pointerId;
+ originX = event.clientX;
+ originWidth = Number.parseInt(getComputedStyle(workspace).getPropertyValue("--sidebar-width"), 10) || uiPreferences.sidebarWidth;
+ elements.sidebarResizer.setPointerCapture(pointerId);
+ elements.sidebarResizer.classList.add("is-resizing");
+ event.preventDefault();
+ });
+ elements.sidebarResizer.addEventListener("pointermove", (event) => {
+ if (event.pointerId !== pointerId) return;
+ applySidebarWidth(originWidth + event.clientX - originX);
+ });
+ const finishPointerResize = (event) => {
+ if (event.pointerId !== pointerId) return;
+ const width = Number(elements.sidebarResizer.getAttribute("aria-valuenow"));
+ pointerId = null;
+ elements.sidebarResizer.classList.remove("is-resizing");
+ void saveSidebarWidth(width);
+ };
+ elements.sidebarResizer.addEventListener("pointerup", finishPointerResize);
+ elements.sidebarResizer.addEventListener("pointercancel", finishPointerResize);
+ elements.sidebarResizer.addEventListener("keydown", (event) => {
+ if (innerWidth <= 900 || !["ArrowLeft", "ArrowRight"].includes(event.key)) return;
+ event.preventDefault();
+ const current = Number(elements.sidebarResizer.getAttribute("aria-valuenow"));
+ const next = applySidebarWidth(current + (event.key === "ArrowRight" ? 16 : -16));
+ void saveSidebarWidth(next);
+ });
+ addEventListener("resize", () => applySidebarWidth(uiPreferences.sidebarWidth), { passive: true });
+}
+
function clearFilters() {
selectedCollectionId = "";
+ caseOrderManagementActive = false;
+ projectOrderManagementActive = false;
selectedContentId = "";
selectedFacets.clear();
elements.pendingFilter.checked = false;
@@ -2878,10 +3624,12 @@ async function renderDetail() {
if (visualSetAnalyses) body.append(visualSetAnalyses);
const attributes = createDetailAttributes(entry);
if (attributes) body.append(attributes);
- const metadata = createDetailMetadata(entry);
- if (metadata) body.append(metadata);
+ body.append(createDetailQuickOrganization(entry));
const breakdown = createFullAnalysis(entry);
if (breakdown) body.append(breakdown);
+ const metadata = createDetailMetadata(entry, { includeDelete: true });
+ if (metadata) body.append(metadata);
+ else body.append(createDetailFooterActions(entry));
primary.append(body);
content.append(primary);
const discovery = createLocalDiscovery(entry);
@@ -3014,7 +3762,7 @@ async function renderCompoundDetail(entry, content, body) {
section.append(heading);
if (entryHasMedia(member)) section.append(await createDetailMediaGallery(member));
if (isEntryPending(member)) section.append(createPendingReviewPanel(member));
- const prompt = createPromptSection(member);
+ const prompt = createPromptSection(member, { compoundMember: true });
if (prompt) section.append(prompt);
const vision = createVisionDescription(member);
if (vision) section.append(vision);
@@ -3025,6 +3773,7 @@ async function renderCompoundDetail(entry, content, body) {
section.append(createEntryEditor(member));
body.append(section);
}
+ body.append(createDetailQuickOrganization(entry), createDetailFooterActions(entry));
}
function createCompoundActions(entry) {
@@ -3352,6 +4101,8 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
gallery.classList.toggle("is-image-detail", asset.kind === "image");
gallery.classList.toggle("is-video-detail", asset.kind === "video");
gallery.classList.toggle("is-document-detail", asset.kind === "document");
+ gallery.classList.toggle("is-audio-detail", asset.kind === "audio");
+ gallery.classList.toggle("is-attachment-detail", asset.kind === "attachment");
gallery.classList.toggle("is-video-reference", asset.kind === "video" && asset.storageMode === "reference");
if (asset.kind !== "image") stage.style.removeProperty("height");
activeController?.destroy?.();
@@ -3374,7 +4125,8 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
}
activeController = body.mediaController || (localVideo ? localVideoController(localVideo) : null);
const caption = el("figcaption", "detail-visual-caption");
- caption.append(rawTextEl("span", "", asset.id === entry.primaryMediaId ? `主要媒体 · ${activeIndex + 1}/${entry.mediaAssets.length}` : `${activeIndex + 1}/${entry.mediaAssets.length}`));
+ const position = asset.id === entry.primaryMediaId ? `主要媒体 · ${activeIndex + 1}/${entry.mediaAssets.length}` : `${activeIndex + 1}/${entry.mediaAssets.length}`;
+ caption.append(rawTextEl("span", "", [position, mediaMetadataText(asset)].filter(Boolean).join(" · ")));
const actions = el("span", "detail-visual-actions");
if (!entry.compoundCase && asset.id !== entry.primaryMediaId) {
const primary = textEl("button", "button-secondary", "设为主要媒体");
@@ -3394,9 +4146,9 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
if (asset.kind === "video" && asset.storageMode === "reference") {
actions.append(createLocalMediaUploadControl(entry, { label: "附加本地视频", accept: "video/*" }));
}
- const remove = textEl("button", "button-danger-secondary", "删除此媒体");
+ const remove = textEl("button", "button-danger-secondary", "此媒体移入回收站");
remove.addEventListener("click", async () => {
- if (!await confirmAppAction({ title: "删除这项媒体?", description: "案例文字、笔记和其他媒体会保留。", confirmLabel: "删除媒体", danger: true })) return;
+ if (!await confirmAppAction({ title: "将这项媒体移入回收站?", description: "案例文字、笔记和其他媒体会保留;这项媒体可从回收站恢复。", confirmLabel: "媒体移入回收站", danger: true })) return;
clearMediaAssetCache(asset.id);
await perform(remove, { type: "DELETE_ENTRY_MEDIA", entryId: entry.id, assetId: asset.id });
});
@@ -3430,7 +4182,13 @@ async function createDetailMediaGallery(entryValue, { immersive = false } = {})
image.src = imageUrls[index];
button.append(image);
} else {
- button.append(textEl("span", "media-thumb-label", asset.kind === "video" ? "▶ 视频" : "PDF 文档"));
+ const labels = {
+ video: "▶ 视频",
+ audio: `♪ ${assetFormatLabel(asset)}`,
+ document: `${assetFormatLabel(asset)} 文档`,
+ attachment: `${assetFormatLabel(asset)} 源文件`
+ };
+ button.append(textEl("span", "media-thumb-label", labels[asset.kind] || "资料"));
}
button.addEventListener("click", async () => {
const railScrollLeft = rail.scrollLeft;
@@ -3594,6 +4352,7 @@ async function createMediaViewer(asset, imageUrl, entry) {
});
return image;
}
+ if (asset.recordType === "local-asset-reference") return createLocalAssetReferenceViewer(asset, entry);
if (asset.storageMode === "reference") return createReferencedMediaViewer(asset, entry);
const blob = await getMediaBlob(asset.id);
if (!blob) return textEl("div", "detail-placeholder", "本地媒体文件缺失;请从完整备份恢复");
@@ -3615,11 +4374,34 @@ async function createMediaViewer(asset, imageUrl, entry) {
wrap.append(video, fallback);
return wrap;
}
+ if (asset.kind === "audio") {
+ const wrap = el("div", "detail-audio-wrap");
+ const audio = document.createElement("audio");
+ audio.className = "detail-audio";
+ audio.controls = true;
+ audio.preload = "metadata";
+ audio.autoplay = false;
+ audio.src = url;
+ const metadata = rawTextEl("p", "asset-file-meta", mediaMetadataText(asset));
+ audio.addEventListener("loadedmetadata", () => {
+ if (!asset.durationMs && Number.isFinite(audio.duration)) {
+ metadata.textContent = mediaMetadataText({ ...asset, durationMs: Math.round(audio.duration * 1000) });
+ }
+ });
+ wrap.append(
+ rawTextEl("span", "asset-kind-badge", `音频 · ${assetFormatLabel(asset)}`),
+ rawTextEl("strong", "asset-file-title", asset.sourceTitle || entry.title || "音频"),
+ metadata,
+ audio,
+ managedAssetDownloadLink(asset, url)
+ );
+ return wrap;
+ }
+ if (asset.kind === "attachment") return createManagedSourceFileViewer(asset, url);
const wrap = el("div", "detail-document");
- const open = textEl("a", "button-secondary media-open-link", "打开或下载文档");
+ const open = textEl("a", "button-secondary media-open-link", "下载本机副本");
open.href = url;
- open.target = "_blank";
- open.rel = "noopener";
+ open.download = asset.sourceTitle || `document-${asset.id}`;
if (asset.mimeType === "application/pdf") {
try {
wrap.append(await createPdfViewer(blob, entry.title));
@@ -3629,7 +4411,7 @@ async function createMediaViewer(asset, imageUrl, entry) {
} else if (asset.extractedTextFormat === "markdown" || asset.mimeType === "text/markdown") {
const text = String(entry.text ?? "").trim() || await readDocumentText(blob, asset.mimeType);
const reader = el("article", "document-text-reader");
- reader.append(rawTextEl("div", "document-type-badge", documentTypeLabel(asset.mimeType)));
+ reader.append(rawTextEl("div", "document-type-badge", documentTypeLabel(asset.mimeType, asset.sourceFormat)));
reader.append(renderMarkdownDocument(text, {
loadRemoteImage: (urlValue) => loadRemoteMarkdownImage(asset.id, urlValue)
}));
@@ -3637,13 +4419,147 @@ async function createMediaViewer(asset, imageUrl, entry) {
} else {
const text = String(entry.text ?? "").trim() || await readDocumentText(blob, asset.mimeType);
const reader = el("article", "document-text-reader");
- reader.append(rawTextEl("div", "document-type-badge", documentTypeLabel(asset.mimeType)), rawTextEl("pre", "", text || "这个文档没有可显示的文字"));
+ reader.append(rawTextEl("div", "document-type-badge", documentTypeLabel(asset.mimeType, asset.sourceFormat)), rawTextEl("pre", "", text || "这个文档没有可显示的文字"));
wrap.append(reader);
}
wrap.append(open);
return wrap;
}
+function managedAssetDownloadLink(asset, url) {
+ const download = rawTextEl("a", "button-secondary media-open-link", "下载本机副本");
+ download.href = url;
+ download.download = asset.sourceTitle || `source-${asset.id}`;
+ return download;
+}
+
+function createManagedSourceFileViewer(asset, url) {
+ const panel = el("div", "detail-source-file");
+ panel.append(
+ rawTextEl("span", "asset-kind-badge", `${assetCategoryLabel(asset)} · ${assetFormatLabel(asset)}`),
+ rawTextEl("strong", "asset-file-title", asset.sourceTitle || "创作源文件"),
+ rawTextEl("p", "asset-file-path", asset.relativePath || "本机资料"),
+ rawTextEl("p", "asset-file-meta", mediaMetadataText(asset)),
+ rawTextEl("p", "asset-inert-note", "这是归档源文件。PromptDirector 不会执行或内嵌打开它。"),
+ managedAssetDownloadLink(asset, url)
+ );
+ return panel;
+}
+
+async function createLocalAssetReferenceViewer(asset, entry) {
+ const panel = el("div", "detail-source-file detail-local-asset-reference");
+ const expected = Number.isFinite(Number(asset.sourceLastModified)) ? asset : undefined;
+ let record = null;
+ let inspection;
+ try {
+ record = await getLocalAssetHandleRecord(asset.id);
+ inspection = await inspectLocalAssetHandle(record, expected);
+ } catch (error) {
+ inspection = { status: LOCAL_ASSET_LINK_STATUS.MISSING, permission: "unknown", error };
+ }
+ const statusLabels = {
+ [LOCAL_ASSET_LINK_STATUS.READY]: "链接可用",
+ [LOCAL_ASSET_LINK_STATUS.CHANGED]: "源文件已变化,请确认后重新链接",
+ [LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION]: "需要你重新授权读取",
+ [LOCAL_ASSET_LINK_STATUS.MISSING]: "源文件已移动、改名或链接缺失"
+ };
+ panel.dataset.linkStatus = inspection.status;
+ panel.append(
+ rawTextEl("span", "asset-kind-badge", `本机链接 · ${assetFormatLabel(asset)}`),
+ rawTextEl("strong", "asset-file-title", asset.sourceTitle || "本机源文件"),
+ rawTextEl("p", "asset-file-path", asset.relativePath || asset.sourceTitle || "未记录相对路径"),
+ rawTextEl("p", "asset-file-meta", mediaMetadataText(asset)),
+ rawTextEl("p", "asset-link-status", statusLabels[inspection.status] || "链接状态未知"),
+ rawTextEl("p", "asset-inert-note", "这里只保存文件信息与本机授权。不会自动读取、上传、执行或内嵌源文件;导出分享包时会再次明确检查权限。")
+ );
+ const actions = el("div", "asset-file-actions");
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION) {
+ const authorize = rawTextEl("button", "button-secondary", "重新授权读取");
+ authorize.addEventListener("click", () => void authorizeLocalAssetReference(asset, record, authorize));
+ actions.append(authorize);
+ }
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.READY) {
+ const download = rawTextEl("button", "button-secondary", "下载本机副本");
+ download.addEventListener("click", () => void downloadLocalAssetReference(asset, record, download));
+ actions.append(download);
+ }
+ const relink = rawTextEl("button", "button-secondary", "重新链接源文件");
+ relink.title = "由你选择新的本机文件;确认后更新文件名、大小、格式与修改时间";
+ relink.addEventListener("click", () => void relinkLocalAssetReference(entry, asset, relink));
+ actions.append(relink);
+ panel.append(actions);
+ return panel;
+}
+
+async function authorizeLocalAssetReference(asset, record, button) {
+ button.disabled = true;
+ try {
+ if (!record) throw new Error("没有找到原本的本机链接,请重新选择源文件");
+ if (typeof record.handle.requestPermission !== "function") throw new Error("当前浏览器不支持重新授权,请重新链接源文件");
+ const permission = await record.handle.requestPermission({ mode: "read" });
+ if (permission !== "granted") throw new Error("你没有允许读取本机源文件,链接保持不变");
+ await renderDetail();
+ } catch (error) {
+ showFeedback(error.message || "无法恢复本机文件权限", true);
+ } finally {
+ button.disabled = false;
+ }
+}
+
+async function relinkLocalAssetReference(entry, asset, button) {
+ if (typeof window.showOpenFilePicker !== "function") return showFeedback("当前浏览器不支持持久本机链接,请使用最新版 Chrome", true);
+ button.disabled = true;
+ try {
+ const [handle] = await window.showOpenFilePicker({ multiple: false });
+ if (!handle) return;
+ const file = await handle.getFile();
+ const reference = createUnsupportedLocalAssetReference(file, asset.id, { relativePath: file.name });
+ const changed = file.name !== asset.sourceTitle || file.size !== asset.byteSize || file.lastModified !== asset.sourceLastModified;
+ if (changed && !await confirmAppAction({
+ title: "确认更新本机源文件链接?",
+ description: `将链接更新为“${file.name}”(${formatBytes(file.size)})。只更新本机文件信息,不会立即上传或执行文件。`,
+ confirmLabel: "确认重新链接"
+ })) return;
+ await saveLocalAssetHandle(asset.id, handle, file);
+ const response = await chrome.runtime.sendMessage({
+ type: "UPDATE_LOCAL_ASSET_REFERENCE",
+ entryId: entry.id,
+ assetId: asset.id,
+ sourceTitle: reference.sourceTitle,
+ relativePath: reference.relativePath,
+ sourceFormat: reference.sourceFormat,
+ mimeType: reference.mimeType,
+ byteSize: reference.byteSize,
+ sourceLastModified: file.lastModified
+ });
+ if (!response?.ok) throw new Error(response?.message || "无法更新本机源文件信息");
+ showFeedback("本机源文件链接已更新");
+ await refreshLibrary();
+ } catch (error) {
+ if (error?.name !== "AbortError") showFeedback(error.message || "无法重新链接源文件", true);
+ } finally {
+ button.disabled = false;
+ }
+}
+
+async function downloadLocalAssetReference(asset, record, button) {
+ button.disabled = true;
+ try {
+ if (!record) throw new Error("本机源文件链接已丢失,请重新链接");
+ const file = await record.handle.getFile();
+ const url = URL.createObjectURL(file);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = file.name;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+ } catch (error) {
+ showFeedback(error.message || "无法读取本机源文件", true);
+ } finally {
+ button.disabled = false;
+ }
+}
+
async function loadRemoteMarkdownImage(assetId, urlValue) {
const url = new URL(urlValue);
const cached = await getDerivedMedia(assetId);
@@ -4050,6 +4966,164 @@ function createDetailHeader(entry) {
return section;
}
+function createDetailQuickOrganization(entry) {
+ const section = el("section", "detail-section detail-quick-organization");
+
+ const projects = el("div", "detail-organization-group");
+ const projectHeading = el("div", "detail-organization-heading");
+ projectHeading.append(textEl("strong", "", "项目"));
+ projects.append(projectHeading);
+ const entryIds = expandLogicalCaseIds([entry.id], compoundCases);
+ const selectedProjectsForEntry = () => organizerState.collections.filter((collection) => {
+ const members = new Set(collection.entryIds);
+ return entryIds.every((id) => members.has(id));
+ });
+ const selectedProjects = selectedProjectsForEntry();
+ const projectMenu = el("details", "detail-project-menu");
+ const projectSummary = el("summary", "");
+ const projectSummaryText = rawTextEl(
+ "span",
+ "detail-project-summary-text",
+ selectedProjects.length === 0
+ ? "选择项目"
+ : selectedProjects.length === 1
+ ? selectedProjects[0].name
+ : `已加入 ${selectedProjects.length} 个项目`
+ );
+ const syncProjectSummary = () => {
+ const selected = selectedProjectsForEntry();
+ projectSummaryText.textContent = selected.length === 0
+ ? "选择项目"
+ : selected.length === 1
+ ? selected[0].name
+ : `已加入 ${selected.length} 个项目`;
+ };
+ projectSummary.append(projectSummaryText, createUiIcon("chevron-down"));
+ const projectPopover = el("div", "detail-project-popover");
+ const projectList = el("div", "detail-project-list");
+ for (const collection of organizerState.collections) {
+ const members = new Set(collection.entryIds);
+ const matchingCount = entryIds.filter((id) => members.has(id)).length;
+ const selected = matchingCount === entryIds.length;
+ const partiallySelected = matchingCount > 0 && !selected;
+ const label = el("label", "detail-project-option");
+ const checkbox = document.createElement("input");
+ checkbox.type = "checkbox";
+ checkbox.checked = selected;
+ checkbox.indeterminate = partiallySelected;
+ checkbox.addEventListener("change", async () => {
+ const nextIds = new Set(collection.entryIds);
+ for (const id of entryIds) checkbox.checked ? nextIds.add(id) : nextIds.delete(id);
+ const response = await perform(checkbox, {
+ type: "REPLACE_COLLECTION_ENTRIES",
+ collectionId: collection.id,
+ entryIds: [...nextIds]
+ }, false);
+ if (!response) {
+ checkbox.checked = selected;
+ checkbox.indeterminate = partiallySelected;
+ return;
+ }
+ consumePendingExternalLibraryRefresh();
+ organizerState = response.organizerState ?? organizerState;
+ syncProjectSummary();
+ });
+ label.append(checkbox, rawTextEl("span", "", collection.name));
+ projectList.append(label);
+ }
+ const newProject = el("div", "detail-new-project");
+ const newProjectName = document.createElement("input");
+ newProjectName.placeholder = "输入新项目名称";
+ newProjectName.setAttribute("aria-label", "新项目名称");
+ const createProject = textEl("button", "button-secondary", "新建并加入");
+ const submitProject = async () => {
+ const name = newProjectName.value.trim();
+ if (!name) {
+ newProjectName.focus();
+ return;
+ }
+ const created = await perform(createProject, { type: "CREATE_COLLECTION", name }, false);
+ if (!created?.created?.id) return;
+ organizerState = created.organizerState ?? organizerState;
+ await perform(createProject, {
+ type: "REPLACE_COLLECTION_ENTRIES",
+ collectionId: created.created.id,
+ entryIds
+ });
+ };
+ createProject.addEventListener("click", submitProject);
+ newProjectName.addEventListener("keydown", (event) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ void submitProject();
+ });
+ newProject.append(newProjectName, createProject);
+ projectPopover.append(projectList, newProject);
+ projectMenu.append(projectSummary, projectPopover);
+ projects.append(projectMenu);
+
+ const labels = el("div", "detail-organization-group");
+ const labelHeading = el("div", "detail-organization-heading");
+ labelHeading.append(textEl("strong", "", "添加标签"));
+ labels.append(labelHeading);
+ const customLabels = uniqueNames(entry.compoundCase?.customLabels ?? entry.customLabels);
+ const editor = createTagEditor({
+ values: customLabels,
+ onChange: (values, trigger) => saveDetailCustomLabels(entry, trigger, values)
+ });
+ labels.append(editor.element);
+
+ section.append(projects, labels);
+ return section;
+}
+
+function createDetailDeleteAction(entry) {
+ const deleteButton = el("button", "button-danger-secondary detail-delete-action");
+ deleteButton.type = "button";
+ deleteButton.setAttribute("aria-label", `将“${entry.title}”移入回收站`);
+ deleteButton.append(createUiIcon("trash-2"), textEl("span", "", "移入回收站"));
+ deleteButton.addEventListener("click", async () => {
+ if (!await confirmAppAction({
+ title: `将“${entry.title}”移入回收站?`,
+ description: "案例及其媒体会移入回收站,可随时恢复。",
+ confirmLabel: "移入回收站",
+ danger: true
+ })) return;
+ await deleteCaseIncrementally(deleteButton, entry.id);
+ });
+ return deleteButton;
+}
+
+function createDetailFooterActions(entry) {
+ const footer = el("section", "detail-footer-actions");
+ const deleteButton = createDetailDeleteAction(entry);
+ footer.append(deleteButton);
+ return footer;
+}
+
+async function saveDetailCustomLabels(entry, button, customLabels) {
+ const response = entry.compoundCase
+ ? await perform(button, {
+ type: "UPDATE_COMPOUND_CASE",
+ compoundCaseId: entry.id,
+ customLabels: uniqueNames(customLabels)
+ }, false)
+ : await perform(button, {
+ type: "UPDATE_ENTRY_CUSTOM_LABELS",
+ entryId: entry.id,
+ customLabels: uniqueNames(customLabels)
+ }, false);
+ if (!response?.ok) return false;
+ consumePendingExternalLibraryRefresh();
+ if (entry.compoundCase && response.compoundCase) {
+ compoundCases = compoundCases.map((item) => item.id === response.compoundCase.id ? response.compoundCase : item);
+ } else if (Array.isArray(response.entries)) {
+ entries = response.entries;
+ }
+ rebuildLibraryDerivedState();
+ return true;
+}
+
function createComposerAction(entry) {
const targetType = composerTargetType(entry);
const activeAssetId = activeDetailMediaIdByEntry.get(entry.id) || entry.primaryMediaId;
@@ -4284,7 +5358,19 @@ function createLocalMediaUploadControl(entry, { label, accept = elements.mediaFi
input.accept = accept;
input.className = "sr-only";
const button = textEl("button", "button-secondary", label || "从本机添加媒体");
- button.addEventListener("click", () => input.click());
+ button.addEventListener("click", async () => {
+ if (typeof window.showOpenFilePicker !== "function") return input.click();
+ try {
+ const [handle] = await window.showOpenFilePicker({ multiple: false });
+ if (!handle) return;
+ button.disabled = true;
+ await uploadLocalMediaToEntry(await handle.getFile(), entry.id);
+ } catch (error) {
+ if (error?.name !== "AbortError") showFeedback(error.message || "无法读取所选文件", true);
+ } finally {
+ button.disabled = false;
+ }
+ });
input.addEventListener("change", async () => {
const file = input.files?.[0];
if (!file) return;
@@ -4359,6 +5445,48 @@ function renderImportSource() {
elements.importLastJob.hidden = !latestImportJob;
}
+async function chooseLocalImportFiles() {
+ if (typeof window.showOpenFilePicker !== "function") {
+ elements.mediaFile.click();
+ return;
+ }
+ try {
+ const handles = await window.showOpenFilePicker({ multiple: true });
+ const files = await Promise.all(handles.map(async (handle) => ({
+ handle,
+ file: await handle.getFile(),
+ relativePath: handle.name
+ })));
+ await prepareLocalImport(files, { source: "files" });
+ } catch (error) {
+ if (error?.name !== "AbortError") showImportFeedback(error.message || "无法读取所选文件", true);
+ }
+}
+
+async function chooseLocalImportFolder() {
+ if (typeof window.showDirectoryPicker !== "function") {
+ elements.mediaFolder.click();
+ return;
+ }
+ try {
+ const root = await window.showDirectoryPicker({ mode: "read" });
+ const files = await readImportDirectoryHandle(root, root.name);
+ await prepareLocalImport(files, { source: "folder" });
+ } catch (error) {
+ if (error?.name !== "AbortError") showImportFeedback(error.message || "无法读取所选文件夹", true);
+ }
+}
+
+async function readImportDirectoryHandle(directory, parentPath) {
+ const files = [];
+ for await (const [name, handle] of directory.entries()) {
+ const relativePath = `${parentPath}/${name}`;
+ if (handle.kind === "file") files.push({ handle, file: await handle.getFile(), relativePath });
+ else if (handle.kind === "directory") files.push(...await readImportDirectoryHandle(handle, relativePath));
+ }
+ return files;
+}
+
async function importLocalMediaCases() {
const files = [...(elements.mediaFile.files ?? [])].map((file) => ({ file, relativePath: file.name }));
elements.mediaFile.value = "";
@@ -4385,7 +5513,7 @@ async function prepareLocalImport(fileItems, { source = "files" } = {}) {
await discardPendingLocalImport();
const browsingScrollY = window.scrollY;
const rootName = source === "folder" ? commonImportRoot(fileItems) : "";
- const draft = { source, rootName, browsingScrollY, stagedAssets: [], skipped: [] };
+ const draft = { source, rootName, browsingScrollY, customLabels: [], stagedAssets: [], skipped: [] };
pendingLocalImport = draft;
elements.importDialogTitle.textContent = "确认导入";
elements.importSource.hidden = true;
@@ -4426,11 +5554,11 @@ async function prepareLocalImport(fileItems, { source = "files" } = {}) {
}
}
-async function prepareImportFile({ file, relativePath }, draft) {
+async function prepareImportFile({ file, handle = null, relativePath, forceImport = false }, draft) {
const assetId = globalThis.crypto.randomUUID();
let prepared = null;
try {
- prepared = await prepareLocalMedia(file, assetId, { relativePath });
+ prepared = await prepareLocalMedia(file, assetId, { relativePath, forceImport });
const duplicateProbe = new File([prepared.blob], file.name, {
type: prepared.blob.type,
lastModified: file.lastModified
@@ -4458,6 +5586,7 @@ async function prepareImportFile({ file, relativePath }, draft) {
name: file.name,
relativePath: prepared.asset.relativePath,
kind: prepared.asset.kind,
+ storageMode: prepared.asset.storageMode,
mimeType: prepared.asset.mimeType,
byteSize: prepared.blob.size,
contentHash: duplicate.contentHash,
@@ -4469,7 +5598,8 @@ async function prepareImportFile({ file, relativePath }, draft) {
...(prepared.asset.playbackCapability ? { playbackCapability: prepared.asset.playbackCapability } : {}),
...(prepared.contentText ? { contentText: prepared.contentText } : {}),
...(prepared.contentFormat ? { contentFormat: prepared.contentFormat } : {}),
- ...(prepared.sourceFormat ? { sourceFormat: prepared.sourceFormat } : {}),
+ ...(prepared.asset.sourceFormat || prepared.sourceFormat ? { sourceFormat: prepared.asset.sourceFormat || prepared.sourceFormat } : {}),
+ ...(prepared.asset.formatCategory ? { formatCategory: prepared.asset.formatCategory } : {}),
...(prepared.warnings?.length ? { warnings: prepared.warnings } : {}),
...(prepared.poster ? { posterAssetId: prepared.poster.asset.id, posterAsset: prepared.poster.asset } : {})
});
@@ -4477,18 +5607,42 @@ async function prepareImportFile({ file, relativePath }, draft) {
await deleteMediaBlob(assetId).catch(() => undefined);
if (prepared?.poster?.asset?.id) await deleteMediaBlob(prepared.poster.asset.id).catch(() => undefined);
if (pendingLocalImport === draft) {
- draft.skipped.push({ name: file.name || relativePath || "未命名文件", reason: error.message || "无法读取" });
+ const failure = importFailureDetails(error);
+ const { code, message, forceAllowed, ...details } = failure;
+ draft.skipped.push({
+ name: file.name || relativePath || "未命名文件",
+ relativePath,
+ file,
+ handle,
+ reason: message,
+ code,
+ details,
+ ...(code === ASSET_IMPORT_FAILURE_CODES.TOO_LARGE && (forceAllowed || error?.canForceImport === true)
+ ? { forceAllowed: true }
+ : {})
+ });
}
}
}
function renderImportProjectOptions(rootName = "") {
- const options = [option("", "不分组")];
- for (const collection of organizerState.collections) options.push(option(collection.id, collection.name));
const matching = rootName && organizerState.collections.find((item) => item.name.trim() === rootName);
- if (rootName && !matching) options.push(option(`create:${rootName}`, `新建项目“${rootName}”`));
- elements.importProject.replaceChildren(...options);
- elements.importProject.value = matching?.id || (rootName ? `create:${rootName}` : selectedCollectionId || "");
+ const selected = organizerState.collections.find((item) => item.id === selectedCollectionId);
+ importProjectCombobox.setProjects(organizerState.collections);
+ elements.importProject.value = matching?.name || rootName || selected?.name || "";
+ importTagEditor.input.value = "";
+ importTagEditor.setValues(pendingLocalImport?.customLabels ?? []);
+ elements.importProjectHint.textContent = rootName
+ ? "已按根文件夹建议项目;可以修改或清空。"
+ : "";
+}
+
+function normalizeImportLabel(value) {
+ return normalizeTagValue(value);
+}
+
+function importLabelKey(value) {
+ return normalizeImportLabel(value).toLocaleLowerCase();
}
function renderImportConfirmation() {
@@ -4528,14 +5682,103 @@ function createImportFileRow(item) {
}
function createSkippedImportRow(item) {
- const row = el("div", "import-file-row is-skipped");
+ const canForceImport = item.code === ASSET_IMPORT_FAILURE_CODES.TOO_LARGE
+ && item.forceAllowed === true
+ && item.file instanceof Blob;
+ const canKeepLocalLink = item.code === ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT
+ && item.file instanceof Blob;
+ const row = el("div", `import-file-row is-skipped${canForceImport || canKeepLocalLink ? " has-action" : ""}`);
const spacer = document.createElement("span");
const details = el("span");
- details.append(textEl("strong", "", item.name), textEl("small", "", item.reason));
- row.append(spacer, details, textEl("em", "", "跳过"));
+ details.append(textEl("strong", "", item.name), textEl("small", "import-file-reason", item.reason));
+ if (!canForceImport && !canKeepLocalLink) {
+ row.append(spacer, details, textEl("em", "", "未导入"));
+ return row;
+ }
+ if (canKeepLocalLink) {
+ const keepLink = rawTextEl("button", "button-secondary import-file-force", "保留本机链接");
+ keepLink.type = "button";
+ keepLink.title = "只保存文件信息与授权句柄,不复制或执行源文件;分享时才读取源文件";
+ keepLink.addEventListener("click", () => void preserveUnsupportedImportReference(item, keepLink));
+ row.append(spacer, details, keepLink);
+ return row;
+ }
+ const force = rawTextEl("button", "button-secondary import-file-force", "强制导入");
+ force.type = "button";
+ force.title = "忽略这项限制并再次检查;可能占用更多本机空间";
+ force.addEventListener("click", () => void forcePrepareSkippedImport(item, force));
+ row.append(spacer, details, force);
return row;
}
+async function preserveUnsupportedImportReference(item, button) {
+ const draft = pendingLocalImport;
+ if (!draft || !(item?.file instanceof Blob)) return;
+ button.disabled = true;
+ try {
+ let handle = item.handle;
+ let file = item.file;
+ let relativePath = item.relativePath || file.name;
+ if (!handle) {
+ if (typeof window.showOpenFilePicker !== "function") {
+ throw new Error("当前浏览器无法保存可跨重启使用的本机链接;请使用最新版 Chrome 后重新选择文件");
+ }
+ [handle] = await window.showOpenFilePicker({ multiple: false });
+ file = await handle.getFile();
+ relativePath = file.name;
+ if (file.name !== item.file.name || file.size !== item.file.size || file.lastModified !== item.file.lastModified) {
+ const confirmed = await confirmAppAction({
+ title: "改为链接刚选择的文件?",
+ description: `原失败项是“${item.file.name}”,刚选择的是“${file.name}”。只保存本机链接,不复制或执行文件。`,
+ confirmLabel: "链接这个文件"
+ });
+ if (!confirmed) return;
+ }
+ }
+ const assetId = globalThis.crypto.randomUUID();
+ const reference = createUnsupportedLocalAssetReference(file, assetId, { relativePath });
+ await saveLocalAssetHandle(assetId, handle, file);
+ if (pendingLocalImport !== draft) {
+ await deleteLocalAssetHandle(assetId).catch(() => undefined);
+ return;
+ }
+ draft.skipped = draft.skipped.filter((candidate) => candidate !== item);
+ draft.stagedAssets.push({
+ id: `staged:${globalThis.crypto.randomUUID()}`,
+ assetId,
+ name: reference.sourceTitle,
+ relativePath: reference.relativePath,
+ kind: reference.kind,
+ storageMode: reference.storageMode,
+ mimeType: reference.mimeType,
+ byteSize: reference.byteSize,
+ sourceFormat: reference.sourceFormat,
+ formatCategory: reference.formatCategory,
+ recordType: reference.recordType,
+ linkStatus: "linked",
+ sourceLastModified: file.lastModified,
+ importFailure: reference.importFailure,
+ keepDuplicate: false
+ });
+ showImportFeedback(`已保留“${reference.sourceTitle}”的本机链接;导出分享包时才会请求读取源文件`);
+ renderImportConfirmation();
+ } catch (error) {
+ if (error?.name !== "AbortError") showImportFeedback(error.message || "无法保留本机链接", true);
+ } finally {
+ button.disabled = false;
+ }
+}
+
+async function forcePrepareSkippedImport(item, button) {
+ const draft = pendingLocalImport;
+ if (!draft || !item?.file) return;
+ button.disabled = true;
+ draft.skipped = draft.skipped.filter((candidate) => candidate !== item);
+ showImportFeedback(`正在重新检查“${item.name}”…`);
+ await prepareImportFile({ file: item.file, relativePath: item.relativePath, forceImport: true }, draft);
+ if (pendingLocalImport === draft) renderImportConfirmation();
+}
+
function importSelectedByteSize(staged) {
return staged.filter((item) => !item.duplicateAssetId || item.keepDuplicate)
.reduce((sum, item) => sum + item.byteSize + Number(item.posterAsset?.byteSize || 0), 0);
@@ -4543,12 +5786,15 @@ function importSelectedByteSize(staged) {
async function startLocalImportJob() {
if (!pendingLocalImport?.stagedAssets.length) return;
+ if (importTagEditor.input.value.trim()) await importTagEditor.commit();
elements.importStart.disabled = true;
showImportFeedback("正在把资料交给后台导入…");
try {
- let collectionId = elements.importProject.value;
- if (collectionId.startsWith("create:")) {
- const response = await chrome.runtime.sendMessage({ type: "CREATE_COLLECTION", name: collectionId.slice(7) });
+ const projectName = String(elements.importProject.value || "").trim();
+ const existingCollection = organizerState.collections.find((item) => item.name.trim().toLocaleLowerCase() === projectName.toLocaleLowerCase());
+ let collectionId = existingCollection?.id || "";
+ if (projectName && !collectionId) {
+ const response = await chrome.runtime.sendMessage({ type: "CREATE_COLLECTION", name: projectName });
if (!response?.ok || !response.created?.id) throw new Error(response?.message || "无法创建目标项目");
organizerState = response.organizerState ?? organizerState;
collectionId = response.created.id;
@@ -4556,6 +5802,7 @@ async function startLocalImportJob() {
const response = await chrome.runtime.sendMessage({
type: "START_IMPORT_JOB",
collectionId,
+ customLabels: [...(pendingLocalImport.customLabels ?? [])],
stagedAssets: pendingLocalImport.stagedAssets,
items: pendingLocalImport.stagedAssets.map((item) => ({
stagedAssetId: item.id,
@@ -4716,6 +5963,7 @@ async function undoLocalImportJob() {
function viewImportedProject() {
const collectionId = activeImportJob?.collectionId;
if (!collectionId) return;
+ caseOrderManagementActive = false;
selectedCollectionId = collectionId;
renderGallery();
window.scrollTo({ top: 0, behavior: "instant" });
@@ -4737,6 +5985,9 @@ async function discardPendingLocalImport() {
const staged = pendingLocalImport?.stagedAssets ?? [];
pendingLocalImport = null;
await Promise.allSettled(staged.flatMap((item) => [item.assetId, item.posterAssetId].filter(Boolean)).map(deleteMediaBlob));
+ await Promise.allSettled(staged
+ .filter((item) => item.recordType === "local-asset-reference")
+ .map((item) => deleteLocalAssetHandle(item.assetId)));
}
function showImportFeedback(message, isError = false) {
@@ -4782,6 +6033,14 @@ async function handleLibraryDrop(event) {
}
async function droppedLocalFiles(dataTransfer) {
+ const handleRoots = (await Promise.all([...dataTransfer?.items ?? []].map(async (item) => {
+ if (item.kind !== "file" || typeof item.getAsFileSystemHandle !== "function") return null;
+ try { return await item.getAsFileSystemHandle(); } catch { return null; }
+ }))).filter(Boolean);
+ if (handleRoots.length) {
+ const nested = await Promise.all(handleRoots.map((handle) => readDroppedHandle(handle, "")));
+ return nested.flat();
+ }
const roots = [...(dataTransfer?.items ?? [])].flatMap((item) => {
const entry = item.kind === "file" ? item.webkitGetAsEntry?.() : null;
return entry ? [entry] : [];
@@ -4791,6 +6050,15 @@ async function droppedLocalFiles(dataTransfer) {
return nested.flat();
}
+async function readDroppedHandle(handle, parentPath) {
+ const relativePath = parentPath ? `${parentPath}/${handle.name}` : handle.name;
+ if (handle.kind === "file") return [{ handle, file: await handle.getFile(), relativePath }];
+ if (handle.kind !== "directory") return [];
+ const nested = [];
+ for await (const child of handle.values()) nested.push(...await readDroppedHandle(child, relativePath));
+ return nested;
+}
+
async function readDroppedEntry(entry, parentPath) {
const relativePath = parentPath ? `${parentPath}/${entry.name}` : entry.name;
if (entry.isFile) {
@@ -4810,6 +6078,7 @@ async function readDroppedEntry(entry, parentPath) {
}
async function addVideoReference(entryId = "") {
+ const organizationFields = entryId ? [] : caseCreationOrganizationFields();
const result = await showAppDialog({
title: "添加视频链接",
description: "支持 YouTube、Vimeo、Bilibili、抖音和 X。这里只保存来源引用卡,不下载视频文件。",
@@ -4822,8 +6091,13 @@ async function addVideoReference(entryId = "") {
placeholder: "https://…",
autocomplete: "url",
required: true
- }],
- onSubmit: async ({ url }) => saveVideoReference(url, entryId)
+ }, ...organizationFields],
+ onReady: ({ controls }) => attachProjectSuggestions(controls.get("projectName")),
+ onSubmit: async ({ url, projectName, customLabels }) => saveVideoReference(
+ url,
+ entryId,
+ caseCreationOrganization(projectName, customLabels)
+ )
});
if (result) {
showFeedback(result.message);
@@ -4831,7 +6105,7 @@ async function addVideoReference(entryId = "") {
}
}
-async function saveVideoReference(value, entryId = "") {
+async function saveVideoReference(value, entryId = "", organization = {}) {
let posterAssetId = "";
try {
const metadata = await resolveMediaReference(value, {
@@ -4876,7 +6150,7 @@ async function saveVideoReference(value, entryId = "") {
});
const response = await chrome.runtime.sendMessage(entryId
? { type: "ADD_UPLOADED_MEDIA", entryId, asset, posterAsset }
- : { type: "CREATE_MEDIA_REFERENCE", asset, posterAsset, title: metadata.title || url.hostname });
+ : { type: "CREATE_MEDIA_REFERENCE", asset, posterAsset, title: metadata.title || url.hostname, ...organization });
if (!response?.ok) throw new Error(response?.message || "视频链接保存失败");
return response;
} catch (error) {
@@ -4904,10 +6178,17 @@ async function createQuickNote() {
pendingLabel: "正在保存…",
fields: [
{ id: "title", label: "标题(可留空)", type: "text", required: false, autocomplete: "off" },
- { id: "text", label: "笔记正文", type: "textarea", rows: 8, required: true, placeholder: "写下创作想法、判断或待办…" }
+ { id: "text", label: "笔记正文", type: "textarea", rows: 8, required: true, placeholder: "写下创作想法、判断或待办…" },
+ ...caseCreationOrganizationFields()
],
- onSubmit: async ({ title, text }) => {
- const response = await chrome.runtime.sendMessage({ type: "CREATE_QUICK_NOTE", title, text });
+ onReady: ({ controls }) => attachProjectSuggestions(controls.get("projectName")),
+ onSubmit: async ({ title, text, projectName, customLabels }) => {
+ const response = await chrome.runtime.sendMessage({
+ type: "CREATE_QUICK_NOTE",
+ title,
+ text,
+ ...caseCreationOrganization(projectName, customLabels)
+ });
if (!response?.ok) throw new Error(response?.message || "笔记保存失败");
return response;
}
@@ -4919,9 +6200,52 @@ async function createQuickNote() {
}
}
+function caseCreationOrganizationFields() {
+ return [
+ {
+ id: "projectName",
+ label: "项目",
+ type: "text",
+ required: false,
+ autocomplete: "off",
+ placeholder: "选择已有项目或输入新项目名"
+ },
+ {
+ id: "customLabels",
+ label: "添加标签",
+ type: "text",
+ required: false,
+ autocomplete: "off",
+ placeholder: "例如:风格不错,很喜欢"
+ }
+ ];
+}
+
+function attachProjectSuggestions(input) {
+ if (!input) return;
+ attachProjectCombobox(input, { projects: organizerState.collections, destroyOnDialogClose: true });
+}
+
+function caseCreationOrganization(projectNameValue, customLabelsValue) {
+ const projectName = String(projectNameValue ?? "").trim();
+ const existing = organizerState.collections.find((item) => (
+ item.name.trim().toLocaleLowerCase() === projectName.toLocaleLowerCase()
+ ));
+ const customLabels = String(customLabelsValue ?? "")
+ .split(/[,,\n\r]+/u)
+ .map(normalizeImportLabel)
+ .filter(Boolean)
+ .filter((label, index, values) => values.findIndex((item) => importLabelKey(item) === importLabelKey(label)) === index);
+ return {
+ ...(existing ? { collectionId: existing.id } : projectName ? { newCollectionName: projectName } : {}),
+ customLabels
+ };
+}
+
async function prepareLocalMedia(file, assetId, options = {}) {
return prepareSharedLocalMedia(file, assetId, {
relativePath: options.relativePath || file.name,
+ forceImport: options.forceImport === true,
estimateStorage: () => navigator.storage?.estimate?.() ?? {},
readImageDimensions,
readVideoMedia,
@@ -4941,7 +6265,9 @@ async function readDocumentText(blob, mimeType) {
});
}
-function documentTypeLabel(mimeType) {
+function documentTypeLabel(mimeType, sourceFormat = "") {
+ const extension = String(sourceFormat || "").toLocaleLowerCase("en-US");
+ if (["srt", "vtt", "ass", "ssa", "sbv", "lrc"].includes(extension)) return `${extension.toLocaleUpperCase("en-US")} 字幕`;
return ({
"text/plain": "TXT",
"text/markdown": "Markdown",
@@ -5004,19 +6330,15 @@ function createDetailAttributes(entry) {
const grouped = groupEntryAssignments(entry, facetCatalog, "confirmed");
const tags = [];
let stableOrder = 0;
- const customFacet = { id: "custom", name: "自定义标签", color: "#65736d" };
for (const facet of facetCatalog.facets.filter((item) => item.status === "active").sort((a, b) => a.order - b.order)) {
const values = (grouped.get(facet.id) ?? []).toSorted((left, right) => Number(right.importance ?? 0) - Number(left.importance ?? 0));
- values.forEach((item) => tags.push({ facet, label: item.path, priority: 0, importance: Number(item.importance ?? 0), stableOrder: stableOrder++ }));
+ values.forEach((item) => tags.push({ facet, label: item.name, path: item.path, priority: 0, importance: Number(item.importance ?? 0), stableOrder: stableOrder++ }));
if (facet.id === "negative") entry.negativeTerms?.forEach((term) => tags.push({ facet, label: term, priority: 1, importance: 0, stableOrder: stableOrder++ }));
}
- for (const label of entry.customLabels ?? []) {
- tags.push({ facet: customFacet, label, priority: 1, importance: 0, stableOrder: stableOrder++ });
- }
if (!tags.length) return null;
tags.sort((left, right) => left.priority - right.priority || right.importance - left.importance || left.stableOrder - right.stableOrder);
const section = el("section", "detail-section attribute-section");
- section.append(textEl("h3", "", "标签"));
+ section.append(textEl("h3", "", "AI 标签"));
const visible = el("div", "detail-tags");
tags.slice(0, DETAIL_TAG_PREVIEW_LIMIT).forEach((item) => visible.append(detailTag(item)));
section.append(visible);
@@ -5032,20 +6354,23 @@ function createDetailAttributes(entry) {
return section;
}
-function createDetailMetadata(entry) {
+function createDetailMetadata(entry, { includeDelete = false } = {}) {
const rows = entrySourceMetadataRows(entry, currentLocale() === "en" ? "Source" : "来源");
const sourceUrl = safeHttpUrl(entry.url);
if (!rows.length && !sourceUrl) return null;
const section = el("section", "detail-section metadata-section");
const heading = el("div", "metadata-heading");
heading.append(textEl("h3", "", currentLocale() === "en" ? "Source details" : "来源信息"));
+ const actions = el("div", "metadata-actions");
if (sourceUrl) {
const openSource = textEl("a", "button-secondary source-open-action", currentLocale() === "en" ? "Open source" : "打开来源");
openSource.href = sourceUrl;
openSource.target = "_blank";
openSource.rel = "noopener noreferrer";
- heading.append(openSource);
+ actions.append(openSource);
}
+ if (includeDelete) actions.append(createDetailDeleteAction(entry));
+ if (actions.childElementCount) heading.append(actions);
section.append(heading);
const list = el("dl", "metadata-list");
rows.forEach((row) => {
@@ -5100,11 +6425,12 @@ function createVisualSetAnalyses(entry) {
return details;
}
-function detailTag({ facet, label }) {
+function detailTag({ facet, label, path = label }) {
const tag = rawTextEl("span", "attribute-pill", label);
tag.style.setProperty("--facet-color", facet.color);
- tag.title = facet.name;
- tag.setAttribute("aria-label", `${facet.name}:${label}`);
+ const fullPath = [facet.name, path].filter(Boolean).join(" / ");
+ tag.title = fullPath;
+ tag.setAttribute("aria-label", fullPath);
return tag;
}
@@ -5136,11 +6462,14 @@ function createAnalysisCandidate(entry, item, queueAware = false) {
return row;
}
-function createPromptSection(entry) {
+function createPromptSection(entry, options = {}) {
if (!entry.text && !entryHasMedia(entry)) return null;
const section = el("section", "detail-section prompt-section");
const activeAssetId = activeDetailMediaIdByEntry.get(entry.id) || entry.primaryMediaId;
const activeImage = entryMediaAssets(entry).find((asset) => asset.id === activeAssetId && asset.kind === "image" && asset.usage !== "poster");
+ const imageAssets = entryMediaAssets(entry).filter((asset) => asset.kind === "image" && asset.usage !== "poster");
+ const managedImageAssets = imageAssets.filter((asset) => asset.storageMode === "managed");
+ const separatesCurrentAndShared = Boolean(activeImage && (imageAssets.length > 1 || options.compoundMember));
const mediaPrompt = activeImage ? (entry.mediaPrompts || []).find((item) => item.assetId === activeImage.id) : null;
const displayedPrompt = activeImage ? promptForEntryImage(entry, activeImage.id) : String(entry.text ?? "").trim();
if (promptEditState?.entryId === entry.id) {
@@ -5190,7 +6519,7 @@ function createPromptSection(entry) {
}
const heading = el("div", "prompt-section-heading");
heading.append(textEl("h3", "", activeImage
- ? (mediaPrompt ? "当前图片提示词" : entry.text ? "当前图片 · 使用案例共享提示词" : "当前图片提示词")
+ ? separatesCurrentAndShared ? (mediaPrompt ? "当前图片提示词" : entry.text ? "当前图片 · 使用共享提示词" : "当前图片提示词") : "提示词"
: "提示词"));
const copy = textEl("button", "button-secondary", "复制提示词");
const vision = primaryVisionAnalysis(entry);
@@ -5199,8 +6528,8 @@ function createPromptSection(entry) {
? textEl("button", "button-secondary", vision ? "重新分析主图" : "分析主图")
: null;
const analyze = textEl("button", "button-secondary", "分析检索标签");
- const edit = textEl("button", "button-secondary", "编辑");
- const editShared = activeImage && entry.text ? textEl("button", "button-secondary", "编辑共享提示词") : null;
+ const edit = textEl("button", "button-secondary", separatesCurrentAndShared ? "编辑当前图片" : "编辑");
+ const editShared = separatesCurrentAndShared && entry.text ? textEl("button", "button-secondary", "编辑共享提示词") : null;
const promptReplacement = activeImage ? visualAnalysisPromptReplacement(entry, activeImage.id) : null;
const replaceAnalyzedPrompt = promptReplacement ? textEl("button", "button-secondary", "更新为 V2 提示词") : null;
copy.disabled = !displayedPrompt;
@@ -5214,7 +6543,7 @@ function createPromptSection(entry) {
analyzeVisual?.addEventListener("click", () => analyzeEntryVision(entry, analyzeVisual));
analyze.addEventListener("click", () => analyzeSingleEntry(entry, analyze));
edit.addEventListener("click", () => {
- promptEditState = { entryId: entry.id, assetId: activeImage?.id || "", originalText: displayedPrompt, draftText: displayedPrompt, dirty: false };
+ promptEditState = { entryId: entry.id, assetId: separatesCurrentAndShared ? activeImage?.id || "" : "", originalText: displayedPrompt, draftText: displayedPrompt, dirty: false };
renderDetail();
});
editShared?.addEventListener("click", () => {
@@ -5241,8 +6570,7 @@ function createPromptSection(entry) {
const analysisActions = el("div", "detail-analysis-actions");
if (replaceAnalyzedPrompt) analysisActions.append(replaceAnalyzedPrompt);
if (analyzeVisual) analysisActions.append(analyzeVisual);
- const imageAssets = entryMediaAssets(entry).filter((asset) => asset.kind === "image" && asset.usage !== "poster" && asset.storageMode === "managed");
- if (imageAssets.length > 1 && !entry.compoundCase) {
+ if (managedImageAssets.length > 1 && !entry.compoundCase) {
const analyzeSet = textEl("button", "button-secondary", "批量图片分析");
analyzeSet.addEventListener("click", () => analyzeEntryVisualSet(entry, analyzeSet));
analysisActions.append(analyzeSet);
@@ -5445,15 +6773,18 @@ function createEntryEditor(entry, options = {}) {
const titleField = el("label", "entry-edit-field");
const titleInput = document.createElement("input");
titleInput.value = entry.title || "";
- titleField.append(textEl("span", "", "案例标题"), titleInput);
- const saveTitle = textEl("button", "button-secondary", "保存标题");
+ titleField.append(textEl("span", "sr-only", "案例标题"), titleInput);
+ const saveTitle = textEl("button", "button-secondary", "保存");
saveTitle.addEventListener("click", () => {
const title = titleInput.value;
return perform(saveTitle, { type: "UPDATE_ENTRY_TITLE", entryId: entry.id, title: title.trim() });
});
- body.append(textEl("h4", "", "案例标题"), titleField, saveTitle);
+ const titleRow = el("div", "entry-edit-row");
+ titleRow.append(titleField, saveTitle);
+ body.append(textEl("h4", "", "案例标题"), titleRow);
if (entry.classification?.status !== "needs_review") {
const classification = createClassificationControl(entry, {
+ buttonLabel: "保存",
onSave: (button, select) => perform(button, { type: "CONFIRM_CLASSIFICATION", entryId: entry.id, pathIds: [select.value], rememberSource: false })
});
body.append(textEl("h4", "", "内容类型"), classification);
@@ -5464,8 +6795,8 @@ function createEntryEditor(entry, options = {}) {
const field = el("label", "vision-edit-field");
const textarea = document.createElement("textarea");
textarea.value = vision.description;
- field.append(textEl("span", "", "编辑画面描述"), textarea);
- const saveDescription = textEl("button", "button-secondary", "保存画面描述");
+ field.append(textEl("span", "sr-only", "画面描述"), textarea);
+ const saveDescription = textEl("button", "button-secondary", "保存");
saveDescription.addEventListener("click", () => perform(saveDescription, {
type: "UPDATE_VISION_DESCRIPTION", entryId: entry.id, visualId: visual.id, description: textarea.value
}));
@@ -5482,7 +6813,7 @@ function createEntryEditor(entry, options = {}) {
selected.append(remove);
}
}
- if (selected.childElementCount) body.append(textEl("h4", "", "已有标签"), selected);
+ if (selected.childElementCount) body.append(textEl("h4", "", "已有 AI 标签"), selected);
const activeFacets = facetCatalog.facets.filter((item) => item.status === "active").sort((a, b) => a.order - b.order);
if (activeFacets.length) {
const addRow = el("div", "entry-tag-add");
@@ -5505,7 +6836,7 @@ function createEntryEditor(entry, options = {}) {
tagSelect.addEventListener("change", () => { add.disabled = !tagSelect.value; });
add.addEventListener("click", () => perform(add, { type: "SET_ENTRY_FACET", entryId: entry.id, facetId: facetSelect.value, nodeId: tagSelect.value, selected: true }));
addRow.append(facetSelect, tagSelect, add);
- body.append(textEl("h4", "", "添加标签"), addRow);
+ body.append(textEl("h4", "", "添加 AI 标签"), addRow);
}
body.append(textEl("h4", "", "媒体与来源"), createMediaActions(entry));
const analysisCandidates = reusableAnalysisItems(entry.analysisCandidates);
@@ -5515,12 +6846,6 @@ function createEntryEditor(entry, options = {}) {
for (const item of analysisCandidates) suggestions.append(createAnalysisCandidate(entry, item));
body.append(suggestions);
}
- const deleteButton = textEl("button", "quiet-danger delete-entry", "删除这个案例");
- deleteButton.addEventListener("click", async () => {
- if (!await confirmAppAction({ title: `删除“${entry.title}”?`, description: "截图、文字和标签会一起从本机移除。", confirmLabel: "删除案例", danger: true })) return;
- await deleteCaseIncrementally(deleteButton, entry.id);
- });
- body.append(deleteButton);
section.append(body);
return section;
}
@@ -5835,18 +7160,18 @@ async function confirmArchiveChange(preview) {
function renderBatchManager() {
renderAnalysisBatch();
const maintenanceActive = Boolean(maintenanceJob && ["running", "paused"].includes(maintenanceJob.status));
- elements.previewReanalyze.hidden = maintenanceActive;
- elements.applyReanalyze.hidden = maintenanceActive;
- elements.applyReanalyze.disabled = !reanalysisPreview || !(
+ const maintenanceMissing = Boolean(reanalysisPreview && (
reanalysisPreview.confirmed || reanalysisPreview.suggested || reanalysisPreview.paletteCount
- );
+ ));
+ elements.previewReanalyze.hidden = maintenanceActive;
+ elements.previewReanalyze.textContent = reanalysisPreview || maintenanceJob ? "重新检查" : "检查缺失项";
+ elements.previewReanalyze.classList.toggle("button-secondary", Boolean(reanalysisPreview || maintenanceJob));
+ elements.applyReanalyze.hidden = maintenanceActive || !maintenanceMissing;
+ elements.applyReanalyze.disabled = !maintenanceMissing;
elements.pauseLibraryMaintenance.hidden = maintenanceJob?.status !== "running";
elements.resumeLibraryMaintenance.hidden = maintenanceJob?.status !== "paused";
elements.cancelLibraryMaintenance.hidden = !maintenanceActive;
elements.retryLibraryMaintenance.hidden = !maintenanceJob?.failed || maintenanceActive;
- elements.maintenanceProgress.hidden = !maintenanceJob?.total;
- elements.maintenanceProgressBar.max = Math.max(1, maintenanceJob?.total || 1);
- elements.maintenanceProgressBar.value = Math.min(maintenanceJob?.processed || 0, maintenanceJob?.total || 0);
renderReanalysisPreview();
const legacy = entries.filter((entry) => entry.legacyFacetCandidates?.length);
elements.legacyCandidates.hidden = !legacy.length;
@@ -6893,34 +8218,29 @@ function handleLibraryMaintenanceMessage(message) {
function renderReanalysisPreview() {
if (maintenanceJob?.total) {
- const rate = maintenanceJob.itemsPerSecond > 0 ? `${maintenanceJob.itemsPerSecond.toFixed(1)} 项/秒` : "正在准备";
- const eta = maintenanceJob.estimatedSeconds > 0 ? ` · 约剩 ${formatMaintenanceDuration(maintenanceJob.estimatedSeconds)}` : "";
- const status = ({ running: "后台补全中", paused: "已暂停", completed: "补全完成", canceled: "已取消" })[maintenanceJob.status] || maintenanceJob.status;
- elements.reanalyzePreview.textContent = `${status} · ${maintenanceJob.processed}/${maintenanceJob.total} · 成功 ${maintenanceJob.succeeded} · 失败 ${maintenanceJob.failed} · ${rate}${eta}`;
+ if (maintenanceJob.status === "completed" && !maintenanceJob.failed) {
+ elements.reanalyzePreview.textContent = "资料索引已完整";
+ return;
+ }
+ const status = ({ running: "补全中", paused: "已暂停", completed: "补全完成", canceled: "已取消" })[maintenanceJob.status] || maintenanceJob.status;
+ elements.reanalyzePreview.textContent = `${status} · 已处理 ${maintenanceJob.processed}/${maintenanceJob.total} · 成功 ${maintenanceJob.succeeded} · 失败 ${maintenanceJob.failed}`;
return;
}
if (!reanalysisPreview) {
- elements.reanalyzePreview.textContent = "尚未检查";
+ elements.reanalyzePreview.textContent = "";
return;
}
const wrapper = el("div", "");
const nothingMissing = !reanalysisPreview.confirmed && !reanalysisPreview.suggested && !reanalysisPreview.paletteCount;
wrapper.append(textEl("strong", "", nothingMissing
- ? "内容类型与色卡完整。"
- : `将补全 ${reanalysisPreview.confirmed} 条明确内容类型,保留 ${reanalysisPreview.suggested} 条非常不确定项,并为 ${reanalysisPreview.paletteCount} 张截图补充色卡。`));
+ ? "资料索引已完整"
+ : `待补全:${reanalysisPreview.confirmed} 条内容类型,${reanalysisPreview.paletteCount} 张图片色卡。`));
const list = el("div", "reanalyze-case-list");
reanalysisPreview.cases.forEach((item) => list.append(rawTextEl("p", "", `${item.title}:${t("确认")} ${item.confirmed},${currentLocale() === "en" ? "suggestions" : "建议"} ${item.suggested}`)));
wrapper.append(list);
elements.reanalyzePreview.replaceChildren(wrapper);
}
-function formatMaintenanceDuration(secondsValue) {
- const seconds = Math.max(0, Math.round(Number(secondsValue) || 0));
- if (seconds < 60) return `${seconds} 秒`;
- const minutes = Math.ceil(seconds / 60);
- return minutes < 60 ? `${minutes} 分钟` : `${Math.ceil(minutes / 60)} 小时`;
-}
-
function updateLibrarySettingsSaveState() {
const titleChanged = elements.libraryNameSetting.value !== (elements.libraryNameSetting.dataset.savedValue ?? "");
const pathChanged = elements.exportPathSetting.value !== (elements.exportPathSetting.dataset.savedValue ?? "");
@@ -7000,14 +8320,268 @@ function updateGalleryCounts() {
elements.resultCount.textContent = translateUiMessage(`${visibleEntries.length} 个案例`);
elements.pendingCount.textContent = String(pendingCount);
pendingSwitch.hidden = !pendingCount;
- const screenshots = entries.reduce((count, entry) => count + entryMediaAssets(entry)
- .filter((asset) => asset.kind === "image" && asset.usage !== "poster").length, 0);
- elements.librarySummary.textContent = translateUiMessage(`${logicalCases.length} 条案例 / ${screenshots} 张截图`);
elements.emptyState.hidden = visibleEntries.length > 0;
elements.emptyLibrary.hidden = logicalCases.length > 0;
elements.emptyFilter.hidden = logicalCases.length === 0;
}
+async function openTrashDialog() {
+ elements.trashFeedback.textContent = "";
+ if (!elements.trashDialog.open) elements.trashDialog.showModal();
+ await loadTrashItems();
+}
+
+async function loadTrashItems() {
+ elements.trashRestoreAll.disabled = true;
+ try {
+ const response = await chrome.runtime.sendMessage({ type: "GET_TRASH_ITEMS" });
+ if (!response?.ok) throw new Error(response?.message || "无法读取回收站");
+ trashItems = Array.isArray(response.items) ? response.items : [];
+ renderTrashItems();
+ } catch (error) {
+ showTrashFeedback(error.message || "无法读取回收站", true);
+ } finally {
+ elements.trashRestoreAll.disabled = trashItems.length === 0;
+ }
+}
+
+function renderTrashItems() {
+ elements.trashCount.hidden = trashItems.length === 0;
+ elements.trashCount.textContent = String(trashItems.length);
+ elements.trashEmpty.disabled = trashItems.length === 0;
+ elements.trashRestoreAll.disabled = trashItems.length === 0;
+ if (!trashItems.length) {
+ elements.trashList.replaceChildren(textEl("strong", "trash-empty-title", "回收站为空"));
+ return;
+ }
+ const kindNames = { entry: "案例", collection: "项目", media: "媒体" };
+ elements.trashList.replaceChildren(...trashItems.map((item) => {
+ const row = el("article", "trash-item");
+ const preview = trashItemPreview(item);
+ const cover = el("div", "trash-item-cover");
+ if (preview.imageAsset) {
+ const image = document.createElement("img");
+ image.alt = `${preview.title} 封面`;
+ image.decoding = "async";
+ cover.append(image);
+ void hydrateTrashCover(image, preview.imageAsset.id);
+ } else {
+ cover.append(createUiIcon(preview.icon));
+ cover.setAttribute("aria-label", `${kindNames[item.kind] || "内容"}封面`);
+ }
+ const copy = el("div", "trash-item-copy");
+ const title = rawTextEl("strong", "", preview.title || `${kindNames[item.kind] || "内容"} ${item.targetId}`);
+ title.title = title.textContent;
+ copy.append(
+ title,
+ rawTextEl("small", "", `${kindNames[item.kind] || "内容"} · ${formatDate(item.deletedAt)}`)
+ );
+ if (preview.labels.length) {
+ const labels = el("div", "trash-item-labels");
+ labels.append(...preview.labels.map((value) => rawTextEl("span", "", value)));
+ copy.append(labels);
+ }
+ const actions = el("div", "trash-item-actions");
+ const restore = el("button", "icon-button button-secondary");
+ restore.type = "button";
+ restore.setAttribute("aria-label", `恢复:${preview.title}`);
+ restore.title = "恢复";
+ restore.append(createUiIcon("refresh-cw"));
+ const remove = el("button", "icon-button quiet-danger");
+ remove.type = "button";
+ remove.setAttribute("aria-label", `永久删除:${preview.title}`);
+ remove.title = "永久删除";
+ remove.append(createUiIcon("trash-2"));
+ restore.addEventListener("click", () => restoreTrashItem(item, restore));
+ remove.addEventListener("click", () => permanentlyDeleteTrashItem(item, remove));
+ actions.append(restore, remove);
+ row.append(cover, copy, actions);
+ return row;
+ }));
+}
+
+function trashItemPreview(item) {
+ const entry = trashPreviewEntry(item);
+ const mediaAssets = entry ? entryMediaAssets(entry) : [];
+ const primary = item.kind === "media"
+ ? mediaAssets.find((asset) => asset.id === item.targetId) ?? mediaAssets.find((asset) => asset.usage !== "poster")
+ : primaryMediaAsset(entry ?? {});
+ const imageAsset = primary?.kind === "image"
+ ? primary
+ : primary?.kind === "video" ? posterAssetForVideo(entry ?? {}, primary) : null;
+ const title = item.kind === "collection"
+ ? String(item.snapshot?.name ?? "项目")
+ : item.kind === "media"
+ ? String(primary?.sourceTitle || entry?.title || "媒体")
+ : String(entry?.title ?? "案例");
+ const icon = item.kind === "collection"
+ ? "folder"
+ : ({ image: "image", video: "video", audio: "play", document: "file-text", attachment: "paperclip" }[primary?.kind] || "file-text");
+ return {
+ title,
+ imageAsset,
+ icon,
+ labels: item.kind === "entry" ? uniqueNames(entry?.customLabels) : []
+ };
+}
+
+function trashPreviewEntry(item) {
+ if (item.kind === "entry") return item.snapshot ?? null;
+ if (item.kind === "media") {
+ return {
+ title: entries.find((entry) => entry.id === item.relationships?.entryId)?.title || "媒体",
+ mediaAssets: item.snapshot?.mediaAssets ?? [],
+ primaryMediaId: item.targetId
+ };
+ }
+ for (const entryId of item.snapshot?.entryIds ?? []) {
+ const activeEntry = entries.find((entry) => entry.id === entryId);
+ if (activeEntry && primaryMediaAsset(activeEntry)) return activeEntry;
+ const deletedEntry = trashItems.find((candidate) => candidate.kind === "entry" && candidate.targetId === entryId)?.snapshot;
+ if (deletedEntry && primaryMediaAsset(deletedEntry)) return deletedEntry;
+ }
+ return null;
+}
+
+async function hydrateTrashCover(image, assetId) {
+ try {
+ let url = await createThumbnailUrl(assetId).catch(() => "");
+ if (!url) {
+ const blob = await getMediaBlob(assetId);
+ if (blob) {
+ url = URL.createObjectURL(blob);
+ thumbnailUrls.set(assetId, url);
+ }
+ }
+ if (url && image.isConnected) image.src = url;
+ else if (image.isConnected) image.replaceWith(createUiIcon("image"));
+ } catch {
+ if (image.isConnected) image.replaceWith(createUiIcon("image"));
+ }
+}
+
+async function restoreTrashItem(item, button) {
+ const response = await performTrashAction(button, {
+ type: "RESTORE_TRASH_ITEMS",
+ itemIds: relatedTrashGroupIds(item)
+ });
+ if (!response?.ok) return;
+ const unresolved = Array.isArray(response.unresolved) ? response.unresolved : [];
+ if (unresolved.length) {
+ showTrashFeedback(unresolved[0].reason || "当前关系已变化,暂时无法安全恢复", true);
+ } else {
+ showTrashFeedback(response.message || "已恢复");
+ }
+ await refreshLibrary();
+ await loadTrashItems();
+}
+
+async function restoreAllTrashItems() {
+ if (!trashItems.length) return;
+ const response = await performTrashAction(elements.trashRestoreAll, {
+ type: "RESTORE_TRASH_ITEMS",
+ itemIds: trashItems.map((item) => item.id)
+ });
+ if (!response?.ok) return;
+ const unresolved = Array.isArray(response.unresolved) ? response.unresolved : [];
+ const reasons = [...new Set(unresolved.map((item) => item.reason).filter(Boolean))];
+ showTrashFeedback([response.message || "恢复完成", ...reasons].join(";"), unresolved.length > 0);
+ await refreshLibrary();
+ await loadTrashItems();
+}
+
+function relatedTrashGroupIds(startItem) {
+ const selected = new Set([startItem.id]);
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const item of trashItems) {
+ if (!selected.has(item.id)) continue;
+ if (item.kind === "collection") {
+ const memberIds = new Set(item.snapshot?.entryIds ?? []);
+ for (const candidate of trashItems) {
+ if (candidate.kind === "entry" && memberIds.has(candidate.targetId) && !selected.has(candidate.id)) {
+ selected.add(candidate.id);
+ changed = true;
+ }
+ }
+ }
+ if (item.kind === "entry") {
+ const relatedCollectionIds = new Set((item.relationships?.collections ?? []).map((value) => value.id));
+ for (const candidate of trashItems) {
+ if (candidate.kind === "collection" && relatedCollectionIds.has(candidate.targetId) && !selected.has(candidate.id)) {
+ selected.add(candidate.id);
+ changed = true;
+ }
+ if (candidate.kind === "media" && candidate.relationships?.entryId === item.targetId && !selected.has(candidate.id)) {
+ selected.add(candidate.id);
+ changed = true;
+ }
+ }
+ }
+ if (item.kind === "media") {
+ const entryItem = trashItems.find((candidate) => (
+ candidate.kind === "entry" && candidate.targetId === item.relationships?.entryId
+ ));
+ if (entryItem && !selected.has(entryItem.id)) {
+ selected.add(entryItem.id);
+ changed = true;
+ }
+ }
+ }
+ }
+ return [...selected];
+}
+
+async function permanentlyDeleteTrashItem(item, button) {
+ const itemIds = relatedTrashGroupIds(item);
+ if (!await confirmAppAction({
+ title: "永久删除这项内容?",
+ description: itemIds.length > 1
+ ? `这项内容与另外 ${itemIds.length - 1} 项归档内容相互关联,将一起永久删除;本机文件也会被移除。`
+ : "本机保存的相关文件也会被移除,此操作无法恢复。",
+ confirmLabel: "永久删除",
+ danger: true
+ })) return;
+ const response = await performTrashAction(button, { type: "PERMANENT_DELETE_TRASH_ITEMS", itemIds });
+ if (!response?.ok) return;
+ showTrashFeedback(response.message || "已永久删除");
+ await loadTrashItems();
+}
+
+async function emptyTrashFromDialog() {
+ if (!trashItems.length) return;
+ if (!await confirmAppAction({
+ title: `清空回收站中的 ${trashItems.length} 项内容?`,
+ description: "相关本机文件会被永久移除,且无法恢复。",
+ confirmLabel: "永久清空",
+ danger: true
+ })) return;
+ const response = await performTrashAction(elements.trashEmpty, { type: "EMPTY_TRASH" });
+ if (!response?.ok) return;
+ showTrashFeedback(response.message || "回收站已清空");
+ await loadTrashItems();
+}
+
+function showTrashFeedback(message, isError = false) {
+ elements.trashFeedback.textContent = message;
+ elements.trashFeedback.classList.toggle("error", isError);
+}
+
+async function performTrashAction(button, message) {
+ button.disabled = true;
+ try {
+ const response = await chrome.runtime.sendMessage(message);
+ if (!response?.ok) throw new Error(response?.message || "回收站操作失败");
+ return response;
+ } catch (error) {
+ showTrashFeedback(error.message || "回收站操作失败", true);
+ return null;
+ } finally {
+ button.disabled = false;
+ }
+}
+
async function openDataSafety() {
elements.dataSafetyFeedback.textContent = "";
openSettingsDialog("general");
@@ -7039,6 +8613,57 @@ async function renderDataSafetyStatus() {
if (missingLocation) elements.syncSettings.open = true;
}
+async function renderCapturePermissionStatus() {
+ elements.capturePermissionSettingsFeedback.textContent = "";
+ elements.capturePermissionSettingsFeedback.classList.remove("error");
+ try {
+ const status = await inspectCapturePermissionBundle(chrome.permissions);
+ renderCapturePermissionItem(
+ elements.captureWebPermissionStatus,
+ elements.revokeCaptureWebPermission,
+ status.webCaptureGranted
+ );
+ renderCapturePermissionItem(
+ elements.captureClipboardPermissionStatus,
+ elements.revokeCaptureClipboardPermission,
+ status.clipboardGranted
+ );
+ } catch (error) {
+ elements.capturePermissionSettingsFeedback.textContent = error?.message || "无法读取采集权限状态";
+ elements.capturePermissionSettingsFeedback.classList.add("error");
+ }
+}
+
+function renderCapturePermissionItem(statusElement, button, granted) {
+ statusElement.textContent = granted ? "已授权" : "未授权";
+ statusElement.classList.toggle("is-granted", granted);
+ button.disabled = !granted;
+}
+
+async function revokeCapturePermission(kind) {
+ const web = kind === "web";
+ const button = web ? elements.revokeCaptureWebPermission : elements.revokeCaptureClipboardPermission;
+ const request = web
+ ? { origins: [...CONTINUOUS_CAPTURE_ORIGINS] }
+ : { permissions: [...CLIPBOARD_READ_PERMISSIONS] };
+ button.disabled = true;
+ elements.capturePermissionSettingsFeedback.textContent = "正在撤销权限…";
+ elements.capturePermissionSettingsFeedback.classList.remove("error");
+ try {
+ const removed = await chrome.permissions.remove(request);
+ if (!removed) throw new Error("Chrome 没有撤销这项权限,请稍后重试");
+ await chrome.storage.local.remove(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY);
+ await renderCapturePermissionStatus();
+ elements.capturePermissionSettingsFeedback.textContent = web
+ ? "已撤销网页采集与截图权限"
+ : "已撤销剪贴板提取权限";
+ } catch (error) {
+ elements.capturePermissionSettingsFeedback.textContent = error?.message || "权限撤销失败";
+ elements.capturePermissionSettingsFeedback.classList.add("error");
+ button.disabled = false;
+ }
+}
+
async function chooseSyncFolder() {
if (dataSafetyOperationActive) return;
const password = elements.syncPassword.value;
diff --git a/local-asset-store.js b/local-asset-store.js
new file mode 100644
index 0000000..dce1d2d
--- /dev/null
+++ b/local-asset-store.js
@@ -0,0 +1,224 @@
+const DATABASE_NAME = "prompt-director-local-assets";
+const DATABASE_VERSION = 1;
+const STORE_NAME = "file-handles";
+
+export const LOCAL_ASSET_LINK_STATUS = Object.freeze({
+ MISSING: "missing",
+ NEEDS_PERMISSION: "needs-permission",
+ READY: "ready",
+ CHANGED: "changed"
+});
+
+let databasePromise;
+
+export async function saveLocalAssetHandle(assetId, handle, metadata, options = {}) {
+ const id = validateAssetId(assetId);
+ validateFileHandle(handle);
+ const record = {
+ assetId: id,
+ handle,
+ metadata: normalizeLocalAssetMetadata(metadata),
+ linkedAt: clean(options.now) || new Date().toISOString()
+ };
+ const database = await resolveDatabase(options);
+ const transaction = database.transaction(STORE_NAME, "readwrite");
+ const completed = transactionAsPromise(transaction);
+ await Promise.all([
+ requestAsPromise(transaction.objectStore(STORE_NAME).put(record, id)),
+ completed
+ ]);
+ return record;
+}
+
+export async function getLocalAssetHandleRecord(assetId, options = {}) {
+ const id = validateAssetId(assetId);
+ const database = await resolveDatabase(options);
+ const value = await requestAsPromise(
+ database.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).get(id)
+ );
+ return normalizeStoredRecord(value, id);
+}
+
+export async function getLocalAssetHandle(assetId, options = {}) {
+ return (await getLocalAssetHandleRecord(assetId, options))?.handle ?? null;
+}
+
+export async function deleteLocalAssetHandle(assetId, options = {}) {
+ const id = validateAssetId(assetId);
+ const database = await resolveDatabase(options);
+ const transaction = database.transaction(STORE_NAME, "readwrite");
+ const completed = transactionAsPromise(transaction);
+ await Promise.all([
+ requestAsPromise(transaction.objectStore(STORE_NAME).delete(id)),
+ completed
+ ]);
+}
+
+export async function inspectStoredLocalAsset(assetId, expectedMetadata, options = {}) {
+ const record = await getLocalAssetHandleRecord(assetId, options);
+ return inspectLocalAssetHandle(record, expectedMetadata, options);
+}
+
+export async function inspectLocalAssetHandle(record, expectedMetadata, options = {}) {
+ const stored = normalizeStoredRecord(record);
+ if (!stored) return { status: LOCAL_ASSET_LINK_STATUS.MISSING, permission: "unknown" };
+ const permission = await queryLocalAssetHandlePermission(stored.handle, options);
+ if (permission !== "granted") {
+ return { status: LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION, permission };
+ }
+ let file;
+ try {
+ file = await stored.handle.getFile();
+ } catch (error) {
+ if (isMissingFileError(error)) {
+ return { status: LOCAL_ASSET_LINK_STATUS.MISSING, permission, error };
+ }
+ if (isPermissionError(error)) {
+ return { status: LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION, permission: "denied", error };
+ }
+ throw error;
+ }
+ const currentMetadata = normalizeLocalAssetMetadata(file);
+ const expected = normalizeLocalAssetMetadata(expectedMetadata ?? stored.metadata);
+ const changedFields = localAssetMetadataChanges(expected, currentMetadata);
+ return {
+ status: changedFields.length ? LOCAL_ASSET_LINK_STATUS.CHANGED : LOCAL_ASSET_LINK_STATUS.READY,
+ permission,
+ file,
+ expectedMetadata: expected,
+ currentMetadata,
+ changedFields
+ };
+}
+
+export async function queryLocalAssetHandlePermission(handle, options = {}) {
+ validateFileHandle(handle);
+ if (typeof handle.queryPermission !== "function") return "unsupported";
+ const permission = await handle.queryPermission({ mode: clean(options.mode) || "read" });
+ return ["granted", "prompt", "denied"].includes(permission) ? permission : "unsupported";
+}
+
+export async function readLocalAssetFile(recordOrHandle, options = {}) {
+ const handle = recordOrHandle?.handle ?? recordOrHandle;
+ validateFileHandle(handle);
+ const permission = await queryLocalAssetHandlePermission(handle, options);
+ if (permission !== "granted") {
+ throw localAssetStoreError(
+ "local_asset_permission_required",
+ "需要由用户重新授权后才能读取本机源文件"
+ );
+ }
+ try {
+ return await handle.getFile();
+ } catch (error) {
+ if (isMissingFileError(error)) {
+ throw localAssetStoreError("local_asset_missing", "本机源文件已移动、改名或删除", error);
+ }
+ if (isPermissionError(error)) {
+ throw localAssetStoreError("local_asset_permission_required", "需要由用户重新授权后才能读取本机源文件", error);
+ }
+ throw error;
+ }
+}
+
+export function normalizeLocalAssetMetadata(value = {}) {
+ const name = clean(value?.name ?? value?.sourceTitle);
+ const size = Number(value?.size ?? value?.byteSize);
+ const lastModified = Number(value?.lastModified ?? value?.sourceLastModified);
+ if (!name) throw new Error("本机源文件缺少文件名");
+ if (!Number.isFinite(size) || size < 0) throw new Error("本机源文件大小无效");
+ if (!Number.isFinite(lastModified) || lastModified < 0) throw new Error("本机源文件修改时间无效");
+ return { name, size, lastModified };
+}
+
+export function localAssetMetadataChanges(expected, current) {
+ const before = normalizeLocalAssetMetadata(expected);
+ const after = normalizeLocalAssetMetadata(current);
+ return ["name", "size", "lastModified"].filter((field) => before[field] !== after[field]);
+}
+
+export function validateFileHandle(handle) {
+ if (!handle || handle.kind !== "file" || typeof handle.getFile !== "function") {
+ throw new Error("没有选择有效的本机源文件");
+ }
+ return handle;
+}
+
+function validateAssetId(value) {
+ const assetId = clean(value);
+ if (!assetId) throw new Error("本机源文件缺少有效编号");
+ return assetId;
+}
+
+function normalizeStoredRecord(value, expectedAssetId = "") {
+ if (!value || typeof value !== "object") return null;
+ const assetId = clean(value.assetId);
+ if (!assetId || (expectedAssetId && assetId !== expectedAssetId)) return null;
+ try {
+ validateFileHandle(value.handle);
+ return {
+ assetId,
+ handle: value.handle,
+ metadata: normalizeLocalAssetMetadata(value.metadata),
+ linkedAt: clean(value.linkedAt)
+ };
+ } catch {
+ return null;
+ }
+}
+
+function resolveDatabase(options) {
+ if (options.database) return Promise.resolve(options.database);
+ if (typeof options.openDatabase === "function") return Promise.resolve(options.openDatabase());
+ return openDatabase();
+}
+
+function openDatabase() {
+ if (!databasePromise) {
+ databasePromise = new Promise((resolve, reject) => {
+ const request = indexedDB.open(DATABASE_NAME, DATABASE_VERSION);
+ request.onupgradeneeded = () => {
+ if (!request.result.objectStoreNames.contains(STORE_NAME)) {
+ request.result.createObjectStore(STORE_NAME);
+ }
+ };
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error || new Error("无法打开本机源文件链接数据库"));
+ request.onblocked = () => reject(new Error("本机源文件链接数据库正在被其他页面占用"));
+ });
+ }
+ return databasePromise;
+}
+
+function requestAsPromise(request) {
+ return new Promise((resolve, reject) => {
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error || new Error("无法读取本机源文件链接"));
+ });
+}
+
+function transactionAsPromise(transaction) {
+ return new Promise((resolve, reject) => {
+ transaction.oncomplete = () => resolve();
+ transaction.onabort = () => reject(transaction.error || new Error("本机源文件链接保存已取消"));
+ transaction.onerror = () => reject(transaction.error || new Error("无法保存本机源文件链接"));
+ });
+}
+
+function localAssetStoreError(code, message, cause) {
+ const error = new Error(message, cause ? { cause } : undefined);
+ error.code = code;
+ return error;
+}
+
+function isMissingFileError(error) {
+ return ["NotFoundError", "TypeMismatchError"].includes(clean(error?.name));
+}
+
+function isPermissionError(error) {
+ return ["NotAllowedError", "SecurityError"].includes(clean(error?.name));
+}
+
+function clean(value) {
+ return String(value ?? "").trim();
+}
diff --git a/local-media.js b/local-media.js
index 98a1d6e..36e9229 100644
--- a/local-media.js
+++ b/local-media.js
@@ -1,40 +1,43 @@
import { readImageDimensions as readStoredImageDimensions } from "./image-metadata.js";
-import { PORTABLE_LIBRARY_LIMITS, assertImageDimensions, formatBytes } from "./resource-limits.js";
-import { assertStorageCapacity, validateMediaBlob } from "./media-store.js";
+import {
+ ASSET_IMPORT_FAILURE_CODES,
+ assetImportError,
+ assertImageDimensions,
+ formatBytes,
+ isAssetImportError,
+ portableLibraryLimits
+} from "./resource-limits.js";
+import { assertStorageCapacity } from "./media-store.js";
import { ingestLocalDocument } from "./document-ingestion.js";
+import {
+ assetFileAccept,
+ assetFormatForExtension,
+ canonicalMimeType,
+ fileExtension,
+ isReportedMimeCompatible
+} from "./asset-formats.js";
-const FORMATS = Object.freeze({
- png: { kind: "image", mimeTypes: ["image/png"] },
- jpg: { kind: "image", mimeTypes: ["image/jpeg"] },
- jpeg: { kind: "image", mimeTypes: ["image/jpeg"] },
- webp: { kind: "image", mimeTypes: ["image/webp"] },
- gif: { kind: "image", mimeTypes: ["image/gif"] },
- mp4: { kind: "video", mimeTypes: ["video/mp4"] },
- webm: { kind: "video", mimeTypes: ["video/webm"] },
- mov: { kind: "video", mimeTypes: ["video/quicktime"] },
- mkv: { kind: "video", mimeTypes: ["video/x-matroska"] },
- avi: { kind: "video", mimeTypes: ["video/x-msvideo"] },
- pdf: { kind: "document", mimeTypes: ["application/pdf"] },
- txt: { kind: "document", mimeTypes: ["text/plain"] },
- md: { kind: "document", mimeTypes: ["text/markdown", "text/plain"] },
- markdown: { kind: "document", mimeTypes: ["text/markdown", "text/plain"] },
- html: { kind: "document", mimeTypes: ["text/html"] },
- htm: { kind: "document", mimeTypes: ["text/html"] },
- rtf: { kind: "document", mimeTypes: ["application/rtf", "text/rtf", "application/x-rtf"] }
-});
+export const LOCAL_ASSET_FILE_ACCEPT = assetFileAccept();
+export const LOCAL_ASSET_REFERENCE_RECORD_TYPE = "local-asset-reference";
export function detectLocalMediaFile(file, options = {}) {
- if (!(file instanceof Blob) || !file.size) throw new Error("文件为空或已经失效");
+ if (!(file instanceof Blob) || !file.size) {
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "文件为空或已经失效");
+ }
const name = clean(file.name);
const extension = fileExtension(name);
- const format = FORMATS[extension];
- if (!format) throw new Error("暂不支持这种文件格式");
- if (format.kind === "video" && options.allowVideo === false) throw new Error("暂不支持视频");
+ const format = assetFormatForExtension(extension);
+ if (!format) throw unsupportedFormatError(name);
+ if (format.kind === "video" && options.allowVideo === false) throw unsupportedFormatError(name, "当前入口暂不支持视频");
+ if (format.kind === "audio" && options.allowAudio === false) throw unsupportedFormatError(name, "当前入口暂不支持音频");
+ if (format.kind === "attachment" && options.allowAttachment === false) {
+ throw unsupportedFormatError(name, "当前入口暂不支持创作源文件");
+ }
const reportedMimeType = clean(file.type).toLocaleLowerCase("en-US");
- if (reportedMimeType && !format.mimeTypes.includes(reportedMimeType)) {
- throw new Error("扩展名和文件格式不一致,请检查原文件");
+ if (!isReportedMimeCompatible(format, reportedMimeType)) {
+ throw unsupportedFormatError(name, "扩展名和文件格式不一致,请检查原文件");
}
- const mimeType = reportedMimeType || format.mimeTypes[0];
+ const mimeType = canonicalMimeType(format, reportedMimeType);
return { extension, kind: format.kind, mimeType };
}
@@ -42,47 +45,115 @@ export function normalizeLocalRelativePath(value, fallbackName = "") {
const source = clean(value) || clean(fallbackName);
const normalized = source.replaceAll("\\", "/");
if (!normalized || normalized.startsWith("/") || /^[a-z]:\//iu.test(normalized)) {
- throw new Error("本机资料必须使用相对路径");
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "本机资料必须使用相对路径");
}
const parts = normalized.split("/");
if (parts.some((part) => !part || part === "." || part === "..")) {
- throw new Error("本机资料必须使用安全相对路径");
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "本机资料必须使用安全相对路径");
}
return parts.join("/");
}
export async function prepareLocalMedia(file, assetId, options = {}) {
- const format = detectLocalMediaFile(file, { allowVideo: options.allowVideo !== false });
- if (format.kind === "image" && file.size > PORTABLE_LIBRARY_LIMITS.maxImageBytes) {
- throw new Error(`图片超过 ${formatBytes(PORTABLE_LIBRARY_LIMITS.maxImageBytes)} 上限`);
+ try {
+ return await prepareLocalMediaValue(file, assetId, options);
+ } catch (error) {
+ if (isAssetImportError(error)) throw error;
+ const name = clean(file?.name) || "这个文件";
+ const explanation = clean(error?.message);
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.READ_OR_DECODE_FAILED,
+ explanation ? `无法读取或解析“${name}”:${explanation}` : `无法读取或解析“${name}”`,
+ {},
+ { cause: error }
+ );
+ }
+}
+
+export function createUnsupportedLocalAssetReference(file, assetId, options = {}) {
+ if (!(file instanceof Blob) || !file.size) {
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "文件为空或已经失效");
}
const id = clean(assetId);
- if (!id) throw new Error("媒体缺少有效编号");
+ if (!id) throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "媒体缺少有效编号");
+ let failure;
+ try {
+ detectLocalMediaFile(file);
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.INVALID_FILE,
+ "已支持的文件格式应使用正常导入流程"
+ );
+ } catch (error) {
+ if (!isAssetImportError(error) || error.code !== ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT) throw error;
+ failure = error;
+ }
+ const sourceTitle = clean(file.name);
+ const relativePath = normalizeLocalRelativePath(options.relativePath, sourceTitle);
+ const sourceFormat = fileExtension(sourceTitle);
+ const reportedMimeType = clean(file.type).toLocaleLowerCase("en-US");
+ const sourceLastModified = Number(file.lastModified);
+ return {
+ recordType: LOCAL_ASSET_REFERENCE_RECORD_TYPE,
+ id,
+ kind: "attachment",
+ storageMode: "reference",
+ linkStatus: "relink-required",
+ mimeType: reportedMimeType || "application/octet-stream",
+ byteSize: file.size,
+ ...(Number.isSafeInteger(sourceLastModified) && sourceLastModified >= 0 ? { sourceLastModified } : {}),
+ sourceTitle,
+ relativePath,
+ sourceFormat,
+ formatCategory: "local-link",
+ capturedAt: clean(options.now) || new Date().toISOString(),
+ reviewStatus: "unverified",
+ importFailure: {
+ code: failure.code,
+ message: failure.message,
+ forceAllowed: false
+ }
+ };
+}
+
+async function prepareLocalMediaValue(file, assetId, options) {
+ const limits = portableLibraryLimits(options.limits);
+ const format = detectLocalMediaFile(file, {
+ allowVideo: options.allowVideo !== false,
+ allowAudio: options.allowAudio !== false,
+ allowAttachment: options.allowAttachment !== false
+ });
+ if (format.kind === "image" && file.size > limits.maxImageBytes && options.forceImport !== true) {
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.TOO_LARGE,
+ `图片大小为 ${formatBytes(file.size)},超过默认 ${formatBytes(limits.maxImageBytes)} 上限;确认风险后可强制导入`,
+ { actualBytes: file.size, maxBytes: limits.maxImageBytes, forceAllowed: true }
+ );
+ }
+ const id = clean(assetId);
+ if (!id) throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "媒体缺少有效编号");
const blob = file.type === format.mimeType ? file : file.slice(0, file.size, format.mimeType);
- validateMediaBlob(blob);
const estimate = typeof options.estimateStorage === "function" ? await options.estimateStorage() : {};
assertStorageCapacity(estimate, file.size);
const relativePath = normalizeLocalRelativePath(options.relativePath, file.name);
const now = clean(options.now) || new Date().toISOString();
+ const definition = assetFormatForExtension(format.extension);
+ const storageMode = format.kind === "attachment" && options.storageMode === "reference" ? "reference" : "managed";
const base = {
id,
kind: format.kind,
- storageMode: "managed",
+ storageMode,
mimeType: format.mimeType,
byteSize: file.size,
sourceTitle: clean(file.name),
relativePath,
+ sourceFormat: format.extension,
+ formatCategory: definition.category,
contentHash: await sha256Blob(blob),
capturedAt: now,
reviewStatus: "verified"
};
if (format.kind === "document") {
- const document = await ingestLocalDocument(blob, {
- extension: format.extension,
- parseHtml: options.parseHtml,
- toMarkdown: options.toMarkdown,
- extractPdfText: options.extractPdfText
- });
+ const document = await ingestDetectedDocument(blob, definition, format.extension, options);
return {
blob,
asset: { ...base, extractedTextFormat: document.contentFormat },
@@ -101,11 +172,17 @@ export async function prepareLocalMedia(file, assetId, options = {}) {
...(videoMedia.poster ? { poster: videoMedia.poster } : {})
};
}
+ if (format.kind === "audio") {
+ return { blob, asset: { ...base, playbackCapability: "native" } };
+ }
+ if (format.kind === "attachment") {
+ return { blob, asset: base };
+ }
const readDimensions = typeof options.readImageDimensions === "function"
? options.readImageDimensions
: readLocalImageDimensions;
const dimensions = await readDimensions(blob);
- assertImageDimensions(dimensions.width, dimensions.height);
+ assertImageDimensions(dimensions.width, dimensions.height, limits);
let poster = null;
if (format.extension === "gif") {
const createFirstFrame = typeof options.createGifFirstFrame === "function"
@@ -113,7 +190,7 @@ export async function prepareLocalMedia(file, assetId, options = {}) {
: createGifFirstFrame;
const posterBlob = await createFirstFrame(blob);
const posterDimensions = await readDimensions(posterBlob);
- assertImageDimensions(posterDimensions.width, posterDimensions.height);
+ assertImageDimensions(posterDimensions.width, posterDimensions.height, limits);
const posterId = typeof options.posterId === "function" ? clean(options.posterId()) : `poster:${crypto.randomUUID()}`;
poster = {
blob: posterBlob,
@@ -128,7 +205,20 @@ export async function prepareLocalMedia(file, assetId, options = {}) {
}
export async function extractLocalDocumentText(blob, options = {}) {
- return (await ingestLocalDocument(blob, options)).contentText;
+ const extension = clean(options.extension).toLocaleLowerCase("en-US");
+ const definition = assetFormatForExtension(extension);
+ if (definition?.kind !== "document") throw unsupportedFormatError(clean(options.name));
+ try {
+ return (await ingestDetectedDocument(blob, definition, extension, options)).contentText;
+ } catch (error) {
+ if (isAssetImportError(error)) throw error;
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.READ_OR_DECODE_FAILED,
+ clean(error?.message) || "文件读取或解析失败",
+ {},
+ { cause: error }
+ );
+ }
}
export async function findExactMediaDuplicate(file, entries = [], options = {}) {
@@ -215,10 +305,38 @@ function posterAsset(id, derivedFromAssetId, blob, dimensions, capturedAt, sourc
};
}
-function fileExtension(name) {
- return String(name ?? "").trim().toLocaleLowerCase("en-US").match(/\.([a-z0-9]+)$/u)?.[1] ?? "";
+async function ingestDetectedDocument(blob, definition, extension, options) {
+ if (!definition?.plainText) {
+ return ingestLocalDocument(blob, {
+ extension,
+ parseHtml: options.parseHtml,
+ toMarkdown: options.toMarkdown,
+ extractPdfText: options.extractPdfText
+ });
+ }
+ return {
+ contentText: normalizePlainText(await blob.text()),
+ contentFormat: "plain",
+ sourceFormat: extension,
+ warnings: []
+ };
+}
+
+function normalizePlainText(value) {
+ return String(value ?? "")
+ .replace(/\r\n?/gu, "\n")
+ .replace(/[\u0000\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "")
+ .trim();
}
function clean(value) {
return String(value ?? "").trim();
}
+
+function unsupportedFormatError(name, message = "暂不支持这种文件格式") {
+ const sourceTitle = clean(name);
+ return assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT,
+ sourceTitle ? `${message}:${sourceTitle}` : message
+ );
+}
diff --git a/manifest.json b/manifest.json
index 5c104d9..d619a5a 100644
--- a/manifest.json
+++ b/manifest.json
@@ -1,11 +1,11 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.18.9",
+ "version": "1.18.13",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq2m8W9ACXJTkJqPAd36sPrtzonmHhOYU34uS7c+D7DXX6ggWNMwB4xZapGFJ4ScBQJv71PeG9KfsEnhcXFZ9RoX/X3wY+57evL19hf6woNX1xxhKOe1rtx5QmzWCEYIr99TzW50k/N9U6tS9Ri+2DHKYA85ssXTC8B2yRQ5zUXhsAWZe/HDU18UFuvUKXYt3ZdIUi31c2vIlgFFBfsyKbIUMny9LlxL/smb4vJzU/+A3LwJDjjvOtS/lmQ2vHoQGjHJItO18bYI6h67fIEvmWk+HJKtO08Ca+5RLS8TYhI+K7l7S0RyDVNujyVWtvhAULot1H0BvteYL87fKu3SNywIDAQAB",
"homepage_url": "https://github.com/wchao6891/PromptDirector",
"default_locale": "zh_CN",
- "minimum_chrome_version": "116",
+ "minimum_chrome_version": "134",
"description": "__MSG_extensionDescription__",
"icons": {
"16": "assets/icons/icon-16.png",
diff --git a/media-store.js b/media-store.js
index 6be3eac..a13714d 100644
--- a/media-store.js
+++ b/media-store.js
@@ -1,3 +1,10 @@
+import { assetFormatsForMimeType } from "./asset-formats.js";
+import {
+ ASSET_IMPORT_FAILURE_CODES,
+ assetImportError,
+ isAssetImportError
+} from "./resource-limits.js";
+
const DATABASE_NAME = "prompt-case-collector";
const DATABASE_VERSION = 4;
const MEDIA_STORE = "media";
@@ -14,12 +21,16 @@ export async function saveMediaBlob(assetId, blob, options = {}) {
const estimate = await storageEstimate(options.estimateStorage);
assertStorageCapacity(estimate, blob.size);
}
- const transaction = (await openDatabase()).transaction(MEDIA_STORE, "readwrite");
- const completed = transactionAsPromise(transaction);
- await Promise.all([
- requestAsPromise(transaction.objectStore(MEDIA_STORE).put(blob, assetId)),
- completed
- ]);
+ try {
+ const transaction = (await openDatabase()).transaction(MEDIA_STORE, "readwrite");
+ const completed = transactionAsPromise(transaction);
+ await Promise.all([
+ requestAsPromise(transaction.objectStore(MEDIA_STORE).put(blob, assetId)),
+ completed
+ ]);
+ } catch (error) {
+ throw mediaStorageWriteError(error);
+ }
}
export async function saveSkillPackageBlob(assetId, blob, options = {}) {
@@ -30,12 +41,16 @@ export async function saveSkillPackageBlob(assetId, blob, options = {}) {
const estimate = await storageEstimate(options.estimateStorage);
assertStorageCapacity(estimate, blob.size);
}
- const transaction = (await openDatabase()).transaction(MEDIA_STORE, "readwrite");
- const completed = transactionAsPromise(transaction);
- await Promise.all([
- requestAsPromise(transaction.objectStore(MEDIA_STORE).put(blob, assetId)),
- completed
- ]);
+ try {
+ const transaction = (await openDatabase()).transaction(MEDIA_STORE, "readwrite");
+ const completed = transactionAsPromise(transaction);
+ await Promise.all([
+ requestAsPromise(transaction.objectStore(MEDIA_STORE).put(blob, assetId)),
+ completed
+ ]);
+ } catch (error) {
+ throw mediaStorageWriteError(error);
+ }
}
export async function getMediaBlob(assetId) {
@@ -202,19 +217,26 @@ export function assertStorageCapacity(estimate = {}, incomingBytes = 0) {
const quota = Number(estimate?.quota);
const usage = Number(estimate?.usage);
const required = Number(incomingBytes);
- if (!Number.isFinite(required) || required < 0) throw new Error("媒体文件大小无效");
+ if (!Number.isFinite(required) || required < 0) {
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "媒体文件大小无效");
+ }
if (!Number.isFinite(quota) || !Number.isFinite(usage) || quota < usage) return;
if (quota - usage < required) {
- throw new Error(`本机可用空间不足:还需要 ${formatBytes(required)},请先释放磁盘空间`);
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.STORAGE_INSUFFICIENT,
+ `本机可用空间不足:导入需要 ${formatBytes(required)},当前仅剩 ${formatBytes(quota - usage)}`,
+ { requiredBytes: required, availableBytes: quota - usage }
+ );
}
}
export function validateMediaBlob(blob) {
- if (!(blob instanceof Blob) || !blob.size) throw new Error("媒体文件无效");
+ if (!(blob instanceof Blob) || !blob.size) {
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.INVALID_FILE, "媒体文件无效");
+ }
const type = String(blob.type || "").toLocaleLowerCase("en-US");
- if (!(type.startsWith("image/") || type.startsWith("video/") ||
- ["application/pdf", "text/plain", "text/markdown", "text/html", "application/rtf", "text/rtf", "application/x-rtf"].includes(type))) {
- throw new Error("暂不支持这种媒体格式");
+ if (!(type.startsWith("image/") || type.startsWith("video/") || assetFormatsForMimeType(type).length)) {
+ throw assetImportError(ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT, "暂不支持这种媒体格式");
}
}
@@ -294,3 +316,14 @@ function formatBytes(value) {
const mebibyte = 1024 * 1024;
return bytes >= mebibyte ? `${Math.ceil(bytes / mebibyte)} MiB` : `${Math.ceil(bytes / 1024)} KiB`;
}
+
+export function mediaStorageWriteError(error) {
+ if (isAssetImportError(error)) return error;
+ const explanation = String(error?.message ?? "").trim();
+ return assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.STORAGE_WRITE_FAILED,
+ explanation ? `文件写入本机资料库失败:${explanation}` : "文件写入本机资料库失败,请检查可用空间后重试",
+ {},
+ { cause: error }
+ );
+}
diff --git a/media.js b/media.js
index 029242c..4ea90b1 100644
--- a/media.js
+++ b/media.js
@@ -1,36 +1,51 @@
import { normalizeArticleDocument, removeArticleDocumentAsset } from "./article-document.js";
-
-const IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
-const VIDEO_MIME_TYPES = new Set([
- "video/mp4", "video/webm", "video/quicktime", "video/x-matroska", "video/x-msvideo"
-]);
-const DOCUMENT_MIME_TYPES = new Set(["application/pdf", "text/html", "text/markdown", "text/plain", "application/rtf", "text/rtf", "application/x-rtf"]);
-const MEDIA_KINDS = new Set(["image", "video", "document"]);
+import { LOCAL_ASSET_REFERENCE_RECORD_TYPE } from "./local-media.js";
+import { ASSET_IMPORT_FAILURE_CODES } from "./resource-limits.js";
+import {
+ SUPPORTED_ASSET_KINDS,
+ assetFormatForExtension,
+ assetFormatForFile,
+ assetKindFromFileMetadata,
+ fileExtension,
+ isReportedMimeCompatible
+} from "./asset-formats.js";
+
+const MEDIA_KINDS = new Set(SUPPORTED_ASSET_KINDS);
const STORAGE_MODES = new Set(["managed", "reference"]);
const MEDIA_USAGES = new Set(["content", "poster"]);
const PLAYBACK_MODES = new Set(["local", "embed", "source"]);
const OFFICIAL_EMBED_PROVIDERS = new Set(["youtube", "vimeo", "bilibili", "douyin", "x"]);
const PLAYBACK_CAPABILITIES = new Set(["native", "external", "unknown"]);
+const LOCAL_ASSET_LINK_STATUSES = new Set(["relink-required", "linked", "missing", "needs-permission", "changed"]);
+const GENERIC_ATTACHMENT_MIME_TYPES = new Set(["application/octet-stream", "application/x-unknown"]);
-export const SUPPORTED_MEDIA_KINDS = Object.freeze([...MEDIA_KINDS]);
+export const SUPPORTED_MEDIA_KINDS = SUPPORTED_ASSET_KINDS;
export function normalizeMediaAsset(value = {}) {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const id = clean(value.id);
if (!id) return null;
const mimeType = clean(value.mimeType).toLocaleLowerCase("en-US");
- const kind = inferKind(value.kind, mimeType);
+ const sourceTitle = clean(value.sourceTitle);
+ const requestedSourceFormat = clean(value.sourceFormat).toLocaleLowerCase("en-US").replace(/^\./u, "");
+ const format = assetFormatForExtension(requestedSourceFormat) ?? assetFormatForFile({ name: sourceTitle, type: mimeType });
+ const kind = inferKind(value.kind, mimeType, format);
if (!kind) return null;
+ const localAssetReference = normalizeLocalAssetReference(value, kind);
+ const genericManagedAttachment = normalizeGenericManagedAttachment(value, { kind, format, mimeType, requestedSourceFormat });
+ if (kind === "attachment" && !localAssetReference && !genericManagedAttachment &&
+ (format?.kind !== "attachment" || !isReportedMimeCompatible(format, mimeType))) return null;
const sourceUrl = safeHttpUrl(value.sourceUrl);
const reference = normalizeReference(value.reference, sourceUrl);
- const storageMode = kind === "video"
+ const storageMode = kind === "video" || kind === "audio" || kind === "attachment"
? STORAGE_MODES.has(value.storageMode)
? value.storageMode
- : reference.url && !value.assetPath && !value.screenshotPath
+ : kind === "video" && reference.url && !value.assetPath && !value.screenshotPath
? "reference"
: "managed"
: "managed";
const assetPath = safeAssetPath(value.assetPath || value.screenshotPath);
+ const relativePath = safeAssetPath(value.relativePath);
const width = positiveInteger(value.width);
const height = positiveInteger(value.height);
const durationMs = positiveInteger(value.durationMs);
@@ -43,31 +58,84 @@ export function normalizeMediaAsset(value = {}) {
usage,
storageMode,
sourceUrl,
- sourceTitle: clean(value.sourceTitle),
+ sourceTitle,
sourceAuthor: clean(value.sourceAuthor),
originalWorkUrl: safeHttpUrl(value.originalWorkUrl),
capturedAt,
- ...(mimeTypeForKind(kind, mimeType) ? { mimeType } : {}),
+ ...(mimeTypeForKind(kind, mimeType, format) || localAssetReference || genericManagedAttachment
+ ? { mimeType: mimeType || "application/octet-stream" }
+ : {}),
+ ...(format?.kind === kind
+ ? { sourceFormat: requestedSourceFormat || fileExtension(sourceTitle), formatCategory: format.category }
+ : localAssetReference ? {
+ sourceFormat: requestedSourceFormat || fileExtension(sourceTitle),
+ formatCategory: ["local-link", "other-source"].includes(value.formatCategory) ? value.formatCategory : "local-link"
+ } : genericManagedAttachment ? {
+ sourceFormat: genericManagedAttachment.sourceFormat,
+ formatCategory: "other-source"
+ } : {}),
...(width ? { width } : {}),
...(height ? { height } : {}),
...(durationMs ? { durationMs } : {}),
...(byteSize ? { byteSize } : {}),
+ ...(localAssetReference?.sourceLastModified !== undefined
+ ? { sourceLastModified: localAssetReference.sourceLastModified }
+ : {}),
...(/^[a-f0-9]{64}$/iu.test(clean(value.contentHash)) ? { contentHash: clean(value.contentHash).toLocaleLowerCase("en-US") } : {}),
...(["source", "css-background", "pixel-fallback"].includes(value.captureMethod) ? { captureMethod: value.captureMethod } : {}),
playbackCapability: PLAYBACK_CAPABILITIES.has(value.playbackCapability)
? value.playbackCapability
: storageMode === "reference" ? "external" : "unknown",
...(assetPath ? { assetPath } : {}),
+ ...(relativePath ? { relativePath } : {}),
...(clean(value.posterAssetId) ? { posterAssetId: clean(value.posterAssetId) } : {}),
- ...(kind === "document" ? { extractedTextFormat: normalizeExtractedTextFormat(value.extractedTextFormat, mimeType) } : {}),
+ ...(kind === "document" ? { extractedTextFormat: normalizeExtractedTextFormat(value.extractedTextFormat, format) } : {}),
...(usage === "poster" && clean(value.derivedFromAssetId) ? { derivedFromAssetId: clean(value.derivedFromAssetId) } : {}),
...(kind === "video" && storageMode === "reference" && reference.url ? { reference } : {}),
+ ...(localAssetReference ?? {}),
...(value.palette?.colors?.length ? { palette: structuredClone(value.palette) } : {}),
...(value.visionAnalysis?.description?.trim() ? { visionAnalysis: structuredClone(value.visionAnalysis) } : {}),
reviewStatus: value.reviewStatus === "verified" ? "verified" : "unverified"
};
}
+export function updateLocalAssetReferenceMetadata(entryValue, assetIdValue, metadata = {}) {
+ const entry = normalizeEntryMedia(entryValue);
+ const assetId = clean(assetIdValue);
+ const index = entry.mediaAssets.findIndex((asset) => asset.id === assetId);
+ if (index < 0) throw new Error("没有找到这个本机源文件链接");
+ const current = entry.mediaAssets[index];
+ if (current.kind !== "attachment" || current.recordType !== LOCAL_ASSET_REFERENCE_RECORD_TYPE) {
+ throw new Error("只有本机源文件链接可以更新链接状态");
+ }
+ const sourceTitle = clean(metadata.sourceTitle).replaceAll("\\", "/").split("/").at(-1) || "";
+ const byteSize = positiveInteger(metadata.byteSize);
+ const sourceLastModified = nonNegativeIntegerOrNull(metadata.sourceLastModified);
+ if (!sourceTitle || !byteSize || sourceLastModified === null) throw new Error("本机源文件核验信息不完整");
+ let relativePath = current.relativePath;
+ if (metadata.relativePath !== undefined) {
+ relativePath = safeAssetPath(metadata.relativePath);
+ if (!relativePath) throw new Error("本机源文件必须使用安全相对路径");
+ }
+ const sourceFormat = clean(metadata.sourceFormat).toLocaleLowerCase("en-US").replace(/^\./u, "") || fileExtension(sourceTitle);
+ const mimeType = clean(metadata.mimeType).toLocaleLowerCase("en-US") || current.mimeType || "application/octet-stream";
+ const asset = normalizeMediaAsset({
+ ...current,
+ storageMode: "reference",
+ sourceTitle,
+ relativePath,
+ sourceFormat,
+ mimeType,
+ byteSize,
+ sourceLastModified,
+ linkStatus: "linked",
+ reviewStatus: "unverified"
+ });
+ if (!asset) throw new Error("本机源文件链接元数据无效");
+ entry.mediaAssets[index] = asset;
+ return { entry, asset };
+}
+
export function normalizeEntryMedia(entryValue = {}) {
const entry = structuredClone(entryValue);
const mediaAssets = uniqueMediaAssets(
@@ -268,12 +336,7 @@ export function mediaDescriptions(entryValue = {}) {
}
export function mediaKindFromFile(file) {
- const mimeType = clean(file?.type).toLocaleLowerCase("en-US");
- const name = clean(file?.name).toLocaleLowerCase("en-US");
- if (mimeType.startsWith("image/") || /\.(?:avif|gif|png|jpe?g|webp)$/.test(name)) return "image";
- if (mimeType.startsWith("video/") || /\.(?:mp4|webm|mov|mkv|avi)$/.test(name)) return "video";
- if (DOCUMENT_MIME_TYPES.has(mimeType) || /\.(?:pdf|md|markdown|txt|html?|rtf)$/.test(name)) return "document";
- return "";
+ return assetKindFromFileMetadata(file);
}
function normalizeTimeNotes(values, assetIds) {
@@ -361,9 +424,9 @@ function uniqueMediaAssets(values) {
});
}
-function normalizeExtractedTextFormat(value, mimeType) {
+function normalizeExtractedTextFormat(value, format) {
if (value === "markdown" || value === "plain") return value;
- return mimeType === "text/markdown" || mimeType === "text/html" || ["application/rtf", "text/rtf", "application/x-rtf"].includes(mimeType)
+ return ["markdown", "html", "rtf"].includes(format?.id)
? "markdown"
: "plain";
}
@@ -381,23 +444,50 @@ function normalizeReference(value, fallbackUrl) {
return { url, provider, playbackMode, metadataStatus, ...(author ? { author } : {}) };
}
+function normalizeLocalAssetReference(value, kind) {
+ if (kind !== "attachment" || value?.storageMode !== "reference" || value?.recordType !== LOCAL_ASSET_REFERENCE_RECORD_TYPE) return null;
+ const linkStatus = LOCAL_ASSET_LINK_STATUSES.has(value?.linkStatus) ? value.linkStatus : "";
+ const message = clean(value?.importFailure?.message);
+ if (!linkStatus || value?.importFailure?.code !== ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT || !message) return null;
+ const sourceLastModified = nonNegativeIntegerOrNull(value.sourceLastModified);
+ return {
+ recordType: LOCAL_ASSET_REFERENCE_RECORD_TYPE,
+ linkStatus,
+ importFailure: {
+ code: ASSET_IMPORT_FAILURE_CODES.UNSUPPORTED_FORMAT,
+ message,
+ forceAllowed: false
+ },
+ ...(sourceLastModified !== null ? { sourceLastModified } : {})
+ };
+}
+
+function normalizeGenericManagedAttachment(value, context) {
+ if (context.kind !== "attachment" || value?.storageMode !== "managed" || value?.formatCategory !== "other-source") return null;
+ if (context.format || !GENERIC_ATTACHMENT_MIME_TYPES.has(context.mimeType)) return null;
+ if (!/^[a-z0-9]+$/u.test(context.requestedSourceFormat)) return null;
+ return { sourceFormat: context.requestedSourceFormat };
+}
+
function providerForUrl(url) {
return detectMediaReferenceProvider(url);
}
-function inferKind(value, mimeType) {
+function inferKind(value, mimeType, format) {
if (MEDIA_KINDS.has(value)) return value;
- if (IMAGE_MIME_TYPES.has(mimeType) || mimeType.startsWith("image/")) return "image";
- if (VIDEO_MIME_TYPES.has(mimeType) || mimeType.startsWith("video/")) return "video";
- if (DOCUMENT_MIME_TYPES.has(mimeType)) return "document";
+ if (format) return format.kind;
+ if (mimeType.startsWith("image/")) return "image";
+ if (mimeType.startsWith("video/")) return "video";
+ if (mimeType.startsWith("audio/")) return "audio";
return value ? "" : "image";
}
-function mimeTypeForKind(kind, mimeType) {
+function mimeTypeForKind(kind, mimeType, format) {
if (!mimeType) return false;
if (kind === "image") return mimeType.startsWith("image/");
if (kind === "video") return mimeType.startsWith("video/");
- return DOCUMENT_MIME_TYPES.has(mimeType);
+ if (kind === "audio") return mimeType.startsWith("audio/") || format?.kind === "audio";
+ return format?.kind === kind;
}
function safeAssetPath(value) {
@@ -424,6 +514,11 @@ function nonNegativeInteger(value) {
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
}
+function nonNegativeIntegerOrNull(value) {
+ const number = Number(value);
+ return Number.isSafeInteger(number) && number >= 0 ? number : null;
+}
+
function validIso(value) {
const text = clean(value);
return text && Number.isFinite(Date.parse(text)) ? new Date(text).toISOString() : "";
diff --git a/migration.js b/migration.js
index 824721a..de0b1d0 100644
--- a/migration.js
+++ b/migration.js
@@ -6,6 +6,7 @@ import { sortAnalysisBreakdown } from "./analysis-candidates.js";
import { normalizeEntryVisuals } from "./visuals.js";
import { normalizeCompoundCases } from "./compound-cases.js";
import { isFixedTagTree, migrateLegacyFacetState } from "./tag-taxonomy.js";
+import { normalizeTrashState } from "./trash.js";
const LEGACY_CONTENT_IDS = new Set([
"content:tutorial:image", "content:tutorial:video", "content:tutorial:general"
@@ -44,6 +45,7 @@ export function migrateLibraryState(stored = {}) {
facetCatalog,
classificationRules,
entries,
+ trashState: normalizeTrashState(stored.trashState),
compoundCases: normalizeCompoundCases(stored.compoundCases, entries),
organizerState: normalizeOrganizerState(stored.organizerState, entries.map((entry) => entry.id))
},
@@ -56,7 +58,7 @@ export function migrateLibraryState(stored = {}) {
export function needsMigration(stored = {}) {
return stored.schemaVersion !== SCHEMA_VERSION || !stored.taxonomy || !stored.facetCatalog ||
- !stored.organizerState || !Array.isArray(stored.compoundCases) ||
+ !stored.organizerState || !stored.trashState || !Array.isArray(stored.compoundCases) ||
!isFixedTagTree(stored.facetCatalog) ||
(stored.entries ?? []).some((entry) => entry.schemaVersion !== SCHEMA_VERSION);
}
diff --git a/navigation-state.js b/navigation-state.js
index cbaf00f..93cc451 100644
--- a/navigation-state.js
+++ b/navigation-state.js
@@ -93,6 +93,9 @@ function normalizeLibraryReturnSnapshot(value) {
const pendingOnly = typeof value?.pendingOnly === "boolean" ? value.pendingOnly : null;
const query = typeof value?.query === "string" ? value.query : null;
const scrollY = Number.isFinite(value?.scrollY) ? Math.max(0, Math.round(value.scrollY)) : null;
+ const sortMode = ["added-desc", "updated-desc", "title", "project-manual"].includes(value?.sortMode)
+ ? value.sortMode
+ : "added-desc";
if (collectionId === null || contentId === null || facetNodeIds === null || pendingOnly === null || query === null || scrollY === null) return null;
- return { collectionId, contentId, facetNodeIds, pendingOnly, query, scrollY };
+ return { collectionId, contentId, facetNodeIds, pendingOnly, query, scrollY, sortMode };
}
diff --git a/offscreen.js b/offscreen.js
index 88b828b..29bb512 100644
--- a/offscreen.js
+++ b/offscreen.js
@@ -31,17 +31,31 @@ import { normalizeCreativeRuns } from "./creative-runs.js";
import { buildCreativeExperimentPackage } from "./creative-experiment-package.js";
import { runCreativeJob } from "./creative-job-runner.js";
import { composerServiceErrorDetails } from "./composer-service.js";
+import {
+ assetFormatForExtension,
+ assetFormatsForMimeType,
+ canonicalMimeType,
+ fileExtension,
+ isReportedMimeCompatible
+} from "./asset-formats.js";
+import {
+ LOCAL_ASSET_LINK_STATUS,
+ getLocalAssetHandleRecord,
+ inspectStoredLocalAsset
+} from "./local-asset-store.js";
const blobUrls = new Set();
let creativeJobRunner = null;
-chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
- if (message?.target !== "offscreen") return false;
- handleMessage(message)
- .then(sendResponse)
- .catch((error) => sendResponse({ ok: false, message: error.message }));
- return true;
-});
+if (globalThis.chrome?.runtime?.onMessage) {
+ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
+ if (message?.target !== "offscreen") return false;
+ handleMessage(message)
+ .then(sendResponse)
+ .catch((error) => sendResponse({ ok: false, message: error.message }));
+ return true;
+ });
+}
async function handleMessage(message) {
switch (message.type) {
@@ -336,18 +350,27 @@ async function createArchiveUrl({
const mediaAssets = [];
for (const asset of normalized.mediaAssets) {
if (asset.storageMode === "reference") {
+ if (sharing && asset.recordType === "local-asset-reference") {
+ const blob = await readLinkedAssetForShare(asset, entry.title);
+ const extension = packageMediaExtension(asset, blob);
+ const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;
+ files.push({ name: assetPath, data: blob });
+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));
+ continue;
+ }
mediaAssets.push(asset);
continue;
}
const blob = await getMediaBlob(asset.id);
if (!blob) throw new Error(`“${entry.title || "未命名案例"}”的媒体文件缺失,请从完整备份恢复后再导出`);
- const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${mediaExtension(blob.type, asset.kind)}`;
+ const extension = packageMediaExtension(asset, blob);
+ const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;
files.push({ name: assetPath, data: blob });
if (asset.kind === "image") {
imagePaths.set(asset.id, assetPath);
imageCount += 1;
}
- mediaAssets.push({ ...asset, assetPath });
+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));
}
resolvedEntries.push({ ...normalized, mediaAssets });
}
@@ -454,9 +477,10 @@ async function createCuratedSubmissionUrls({
if (asset.storageMode !== "managed") throw new Error(`“${entry.title || "未命名案例"}”包含未保存到本地的媒体`);
const blob = await getMediaBlob(asset.id);
if (!blob) throw new Error(`“${entry.title || "未命名案例"}”的媒体文件缺失`);
- const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${mediaExtension(blob.type, asset.kind)}`;
+ const extension = packageMediaExtension(asset, blob);
+ const assetPath = `${mediaDirectory(asset.kind)}/${safeAssetName(entry.id)}/${safeAssetName(asset.id)}.${extension}`;
files.push({ name: assetPath, data: blob });
- mediaAssets.push({ ...asset, assetPath, byteSize: blob.size, mimeType: blob.type || asset.mimeType });
+ mediaAssets.push(portableManagedAsset(asset, blob, assetPath, extension));
mediaCount += 1;
}
resolvedEntries.push({ ...normalized, mediaAssets });
@@ -577,17 +601,92 @@ function imageExtension(mimeType) {
}
function mediaDirectory(kind) {
- return kind === "video" ? "videos" : kind === "document" ? "documents" : "images";
+ const directories = {
+ image: "images",
+ video: "videos",
+ audio: "audio",
+ document: "documents",
+ attachment: "attachments"
+ };
+ const directory = directories[kind];
+ if (!directory) throw new Error(`不支持的媒体类型:${kind || "未知"}`);
+ return directory;
}
-function mediaExtension(mimeType, kind) {
+export function packageMediaExtension(asset, blob) {
+ const candidates = [
+ cleanExtension(asset?.sourceFormat),
+ fileExtension(asset?.sourceTitle),
+ ...assetFormatsForMimeType(blob?.type).filter((item) => item.kind === asset?.kind).flatMap((item) => item.extensions),
+ ...assetFormatsForMimeType(asset?.mimeType).filter((item) => item.kind === asset?.kind).flatMap((item) => item.extensions)
+ ].filter(Boolean);
+ for (const extension of candidates) {
+ const format = assetFormatForExtension(extension);
+ if (format?.kind === asset?.kind && isReportedMimeCompatible(format, blob?.type || asset?.mimeType)) return extension;
+ if (!format && asset?.kind === "attachment" && /^[a-z0-9]+$/u.test(extension)) return extension;
+ }
const known = {
"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp",
"video/mp4": "mp4", "video/webm": "webm", "video/quicktime": "mov",
"video/x-matroska": "mkv", "video/x-msvideo": "avi",
- "application/pdf": "pdf", "text/plain": "txt", "text/markdown": "md", "text/html": "html"
+ "audio/mpeg": "mp3", "audio/wav": "wav", "audio/mp4": "m4a", "audio/aac": "aac",
+ "audio/flac": "flac", "audio/ogg": "ogg", "audio/opus": "opus",
+ "application/pdf": "pdf", "application/rtf": "rtf", "text/rtf": "rtf",
+ "text/plain": "txt", "text/markdown": "md", "text/html": "html", "text/vtt": "vtt"
};
- return known[mimeType] || (kind === "video" ? "video" : kind === "document" ? "bin" : imageExtension(mimeType));
+ const extension = known[blob?.type] || known[asset?.mimeType];
+ if (extension) return extension;
+ throw new Error(`“${asset?.sourceTitle || asset?.id || "未命名媒体"}”缺少可安全识别的文件扩展名`);
+}
+
+export function portableManagedAsset(asset, blob, assetPath, extension) {
+ const next = { ...asset };
+ for (const field of [
+ "recordType", "linkStatus", "importFailure", "sourceLastModified", "linkedAt",
+ "localPath", "absolutePath", "fileHandle", "handle", "reference"
+ ]) delete next[field];
+ const format = assetFormatForExtension(extension);
+ const reportedMimeType = String(blob?.type || asset?.mimeType || "").trim().toLocaleLowerCase("en-US");
+ const compatibleMimeType = [blob?.type, asset?.mimeType]
+ .map((value) => String(value ?? "").trim().toLocaleLowerCase("en-US"))
+ .find((value) => value && !["application/octet-stream", "application/x-unknown"].includes(value) &&
+ (!format || isReportedMimeCompatible(format, value)));
+ next.storageMode = "managed";
+ next.assetPath = assetPath;
+ next.byteSize = blob.size;
+ next.mimeType = format
+ ? canonicalMimeType(format, compatibleMimeType || "")
+ : compatibleMimeType || reportedMimeType || "application/octet-stream";
+ next.sourceFormat = extension;
+ next.formatCategory = format?.category || "other-source";
+ next.playbackCapability = ["image", "video", "audio"].includes(asset.kind) ? "native" : "unknown";
+ return next;
+}
+
+export async function readLinkedAssetForShare(asset, entryTitle, dependencies = {}) {
+ const label = `“${entryTitle || "未命名案例"}”中的“${asset.sourceTitle || "本机源文件"}”`;
+ const getRecord = dependencies.getLocalAssetHandleRecord || getLocalAssetHandleRecord;
+ const inspect = dependencies.inspectStoredLocalAsset || inspectStoredLocalAsset;
+ const record = await getRecord(asset.id);
+ if (!record) throw new Error(`${label}没有保存可读取的本机链接,请重新选择文件后再分享`);
+ const inspection = await inspect(asset.id);
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION) {
+ throw new Error(`${label}尚未获得读取权限,请在素材详情中授权后再分享`);
+ }
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.MISSING) {
+ throw new Error(`${label}已移动、改名或删除,请重新链接后再分享`);
+ }
+ if (inspection.status === LOCAL_ASSET_LINK_STATUS.CHANGED) {
+ throw new Error(`${label}自链接后发生了变化,请确认并重新链接后再分享`);
+ }
+ if (inspection.status !== LOCAL_ASSET_LINK_STATUS.READY || !(inspection.file instanceof Blob)) {
+ throw new Error(`${label}当前不可读取,请重新链接后再分享`);
+ }
+ return inspection.file;
+}
+
+function cleanExtension(value) {
+ return String(value ?? "").trim().toLocaleLowerCase("en-US").replace(/^\./u, "");
}
function loadImage(dataUrl) {
diff --git a/organizer.js b/organizer.js
index a689e52..1678383 100644
--- a/organizer.js
+++ b/organizer.js
@@ -20,7 +20,8 @@ export function normalizeOrganizerState(value = {}, validEntryIds) {
order: Number.isFinite(item.order) ? item.order : order,
entryIds: item.entryIds.filter((id) => !allowed || allowed.has(id))
}))
- .sort(byOrder);
+ .sort(byOrder)
+ .map((item, order) => ({ ...item, order }));
return { version: ORGANIZER_VERSION, collections };
}
@@ -36,7 +37,8 @@ export function createCollection(stateValue, name) {
name: cleaned,
order: state.collections.length,
entryIds: [],
- visibility: COLLECTION_VISIBILITY.library
+ visibility: COLLECTION_VISIBILITY.library,
+ createdAt: new Date().toISOString()
};
state.collections.push(item);
return { state, item };
@@ -59,7 +61,19 @@ export function deleteCollection(stateValue, collectionId) {
const id = cleanId(collectionId);
if (!state.collections.some((item) => item.id === id)) throw new Error("项目不存在");
state.collections = state.collections.filter((item) => item.id !== id);
- return state;
+ return normalizeOrganizerState(state);
+}
+
+export function reorderCollections(stateValue, collectionIds) {
+ const state = structuredClone(normalizeOrganizerState(stateValue));
+ const requested = uniqueIds(collectionIds);
+ const existingIds = new Set(state.collections.map((item) => item.id));
+ if (requested.length !== state.collections.length || requested.some((id) => !existingIds.has(id))) {
+ throw new Error("项目排序列表已经变化,请刷新后重试");
+ }
+ const byId = new Map(state.collections.map((item) => [item.id, item]));
+ state.collections = requested.map((id, order) => ({ ...byId.get(id), order }));
+ return normalizeOrganizerState(state);
}
export function planCollectionAndEntriesDeletion(stateValue, entriesValue, collectionId, confirmationName) {
@@ -124,10 +138,11 @@ export function removeEntriesFromOrganizer(stateValue, entryIds) {
return state;
}
-export function mergeOrganizerState(currentValue, importedValue, entryIdMap = {}) {
+export function mergeOrganizerState(currentValue, importedValue, entryIdMap = {}, options = {}) {
const current = structuredClone(normalizeOrganizerState(currentValue));
const imported = normalizeOrganizerState(importedValue);
const remap = (ids) => uniqueIds(ids).map((id) => cleanId(entryIdMap[id])).filter(Boolean);
+ const receiverCreatedAt = normalizeTimestamp(options.createdAt);
for (const source of imported.collections) {
const existing = current.collections.find((item) => canonical(item.name) === canonical(source.name));
@@ -138,7 +153,13 @@ export function mergeOrganizerState(currentValue, importedValue, entryIdMap = {}
const id = current.collections.some((item) => item.id === source.id)
? `collection:${globalThis.crypto.randomUUID()}`
: source.id;
- current.collections.push({ ...source, id, order: current.collections.length, entryIds: remap(source.entryIds) });
+ current.collections.push({
+ ...source,
+ id,
+ order: current.collections.length,
+ entryIds: remap(source.entryIds),
+ ...(receiverCreatedAt ? { createdAt: receiverCreatedAt } : {})
+ });
}
return normalizeOrganizerState(current);
}
@@ -147,15 +168,22 @@ function normalizeCollection(value = {}) {
const id = cleanId(value.id);
const name = cleanName(value.name);
if (!id || !name) return null;
+ const createdAt = normalizeTimestamp(value.createdAt);
return {
id,
name,
order: Number(value.order),
entryIds: uniqueIds(value.entryIds),
- visibility: normalizeVisibility(value.visibility)
+ visibility: normalizeVisibility(value.visibility),
+ ...(createdAt ? { createdAt } : {})
};
}
+function normalizeTimestamp(value) {
+ const timestamp = String(value ?? "").trim();
+ return timestamp && Number.isFinite(Date.parse(timestamp)) ? timestamp : "";
+}
+
function normalizeVisibility(value) {
return value === COLLECTION_VISIBILITY.projectOnly
? COLLECTION_VISIBILITY.projectOnly
diff --git a/package-lock.json b/package-lock.json
index 76fd663..91f3500 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.18.9",
+ "version": "1.18.13",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.18.9",
+ "version": "1.18.13",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 992f4b6..74eddb9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.18.9",
+ "version": "1.18.13",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/preferences.js b/preferences.js
index 62be8ea..c0ad8b9 100644
--- a/preferences.js
+++ b/preferences.js
@@ -2,15 +2,25 @@ export const DEFAULT_UI_PREFERENCES = Object.freeze({
locale: "system",
theme: "dark",
motion: "system",
- analysisDiagnostics: false
+ analysisDiagnostics: false,
+ sidebarWidth: 244
});
+export const SIDEBAR_WIDTH_LIMITS = Object.freeze({ min: 216, max: 420, default: 244 });
+
+export function normalizeSidebarWidth(value) {
+ const width = Number(value);
+ if (!Number.isFinite(width)) return SIDEBAR_WIDTH_LIMITS.default;
+ return Math.min(SIDEBAR_WIDTH_LIMITS.max, Math.max(SIDEBAR_WIDTH_LIMITS.min, Math.round(width)));
+}
+
export function normalizeUiPreferences(value = {}) {
return {
locale: ["system", "zh-CN", "en"].includes(value.locale) ? value.locale : "system",
theme: ["system", "light", "dark"].includes(value.theme) ? value.theme : "dark",
motion: value.motion === "none" ? "reduced" : (["system", "reduced"].includes(value.motion) ? value.motion : "system"),
- analysisDiagnostics: value.analysisDiagnostics === true
+ analysisDiagnostics: value.analysisDiagnostics === true,
+ sidebarWidth: normalizeSidebarWidth(value.sidebarWidth)
};
}
diff --git a/project-combobox.js b/project-combobox.js
new file mode 100644
index 0000000..9d316bf
--- /dev/null
+++ b/project-combobox.js
@@ -0,0 +1,185 @@
+export function projectComboboxOptions(projectsValue, queryValue = "") {
+ const query = normalize(queryValue).toLocaleLowerCase();
+ return (Array.isArray(projectsValue) ? projectsValue : [])
+ .map((project) => ({
+ value: normalize(project?.name ?? project?.value),
+ label: normalize(project?.name ?? project?.label ?? project?.value)
+ }))
+ .filter((project) => project.value && project.label)
+ .filter((project, index, projects) => projects.findIndex((item) => item.value.toLocaleLowerCase() === project.value.toLocaleLowerCase()) === index)
+ .filter((project) => !query || project.label.toLocaleLowerCase().includes(query));
+}
+
+export function projectComboboxPlacement({
+ inputTop,
+ inputBottom,
+ boundaryTop,
+ boundaryBottom,
+ contentHeight,
+ gap = 0
+}) {
+ const above = Math.max(0, Number(inputTop) - Number(boundaryTop) - Number(gap));
+ const below = Math.max(0, Number(boundaryBottom) - Number(inputBottom) - Number(gap));
+ const preferredHeight = Math.max(0, Number(contentHeight) || 0);
+ const placement = below >= preferredHeight || below >= above ? "bottom" : "top";
+ return {
+ placement,
+ maxHeight: Math.floor(placement === "top" ? above : below)
+ };
+}
+
+export function attachProjectCombobox(input, options = {}) {
+ if (!(input instanceof HTMLInputElement)) throw new TypeError("项目组合框需要输入框");
+ input.removeAttribute("list");
+ input.setAttribute("role", "combobox");
+ input.setAttribute("aria-autocomplete", "list");
+ input.setAttribute("aria-expanded", "false");
+
+ const listbox = document.createElement("div");
+ listbox.className = "project-combobox-listbox";
+ listbox.id = `project-combobox-${globalThis.crypto.randomUUID()}`;
+ listbox.setAttribute("role", "listbox");
+ listbox.hidden = true;
+ input.setAttribute("aria-controls", listbox.id);
+ input.insertAdjacentElement("afterend", listbox);
+
+ let projects = Array.isArray(options.projects) ? options.projects : [];
+ let activeIndex = -1;
+ const controller = new AbortController();
+ const eventOptions = { signal: controller.signal };
+ const boundary = input.closest(".app-dialog-body, .import-dialog-body") || input.closest("dialog") || document.documentElement;
+
+ function positionListbox() {
+ if (listbox.hidden || !input.isConnected) return;
+ listbox.dataset.placement = "bottom";
+ listbox.style.removeProperty("--project-combobox-available-height");
+ const styles = getComputedStyle(listbox);
+ const gap = Number.parseFloat(styles.getPropertyValue("--ui-popover-gap")) || 0;
+ const configuredMaxHeight = Number.parseFloat(styles.getPropertyValue("--ui-combobox-max-height"));
+ const contentHeight = Math.min(listbox.scrollHeight, configuredMaxHeight || listbox.scrollHeight);
+ const anchor = listbox.offsetParent instanceof HTMLElement ? listbox.offsetParent : input;
+ const inputBounds = anchor.getBoundingClientRect();
+ const boundaryBounds = boundary.getBoundingClientRect();
+ const placement = projectComboboxPlacement({
+ inputTop: inputBounds.top,
+ inputBottom: inputBounds.bottom,
+ boundaryTop: boundaryBounds.top,
+ boundaryBottom: boundaryBounds.bottom,
+ contentHeight,
+ gap
+ });
+ listbox.dataset.placement = placement.placement;
+ listbox.style.setProperty("--project-combobox-available-height", `${placement.maxHeight}px`);
+ }
+
+ function matching() {
+ return projectComboboxOptions(projects, input.value);
+ }
+
+ function render(open = true) {
+ const matches = matching();
+ if (!matches.length) activeIndex = -1;
+ else if (activeIndex >= matches.length) activeIndex = matches.length - 1;
+ listbox.replaceChildren(...matches.map((project, index) => {
+ const option = document.createElement("button");
+ option.type = "button";
+ option.className = "project-combobox-option";
+ option.setAttribute("role", "option");
+ option.setAttribute("aria-selected", String(index === activeIndex));
+ option.dataset.value = project.value;
+ option.textContent = project.label;
+ option.addEventListener("pointerdown", (event) => event.preventDefault(), eventOptions);
+ option.addEventListener("click", () => select(project.value), eventOptions);
+ return option;
+ }));
+ const visible = open && matches.length > 0;
+ listbox.hidden = !visible;
+ if (visible) positionListbox();
+ input.setAttribute("aria-expanded", String(visible));
+ input.setAttribute("aria-activedescendant", "");
+ const active = listbox.children[activeIndex];
+ if (visible && active) {
+ active.id = `${listbox.id}-option-${activeIndex}`;
+ input.setAttribute("aria-activedescendant", active.id);
+ }
+ }
+
+ function close() {
+ listbox.hidden = true;
+ input.setAttribute("aria-expanded", "false");
+ input.removeAttribute("aria-activedescendant");
+ activeIndex = -1;
+ }
+
+ function select(value) {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ close();
+ input.focus();
+ }
+
+ function move(offset) {
+ const matches = matching();
+ if (!matches.length) return close();
+ activeIndex = activeIndex < 0
+ ? offset > 0 ? 0 : matches.length - 1
+ : (activeIndex + offset + matches.length) % matches.length;
+ render(true);
+ listbox.children[activeIndex]?.scrollIntoView({ block: "nearest" });
+ }
+
+ input.addEventListener("focus", () => render(true), eventOptions);
+ input.addEventListener("click", () => render(true), eventOptions);
+ input.addEventListener("input", () => {
+ activeIndex = -1;
+ render(true);
+ }, eventOptions);
+ input.addEventListener("keydown", (event) => {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ move(event.key === "ArrowDown" ? 1 : -1);
+ return;
+ }
+ if (event.key === "Enter" && !listbox.hidden && activeIndex >= 0) {
+ event.preventDefault();
+ select(matching()[activeIndex]?.value || input.value);
+ return;
+ }
+ if (event.key === "Escape" && !listbox.hidden) {
+ event.preventDefault();
+ event.stopPropagation();
+ close();
+ }
+ }, eventOptions);
+ input.addEventListener("blur", () => queueMicrotask(() => {
+ if (!listbox.contains(document.activeElement)) close();
+ }), eventOptions);
+ boundary.addEventListener("scroll", positionListbox, { ...eventOptions, passive: true });
+ window.addEventListener("resize", positionListbox, { ...eventOptions, passive: true });
+
+ const dialog = input.closest("dialog");
+ if (options.destroyOnDialogClose) dialog?.addEventListener("close", () => controller.abort(), { once: true });
+
+ return {
+ element: listbox,
+ setProjects(nextProjects) {
+ projects = Array.isArray(nextProjects) ? nextProjects : [];
+ if (!listbox.hidden) render(true);
+ },
+ close,
+ destroy() {
+ controller.abort();
+ listbox.remove();
+ input.removeAttribute("role");
+ input.removeAttribute("aria-autocomplete");
+ input.removeAttribute("aria-expanded");
+ input.removeAttribute("aria-controls");
+ input.removeAttribute("aria-activedescendant");
+ }
+ };
+}
+
+function normalize(value) {
+ return String(value ?? "").replace(/\s+/g, " ").trim();
+}
diff --git a/resource-limits.js b/resource-limits.js
index e85f0a5..36b9344 100644
--- a/resource-limits.js
+++ b/resource-limits.js
@@ -1,5 +1,53 @@
const MEBIBYTE = 1024 * 1024;
+export const ASSET_IMPORT_FAILURE_CODES = Object.freeze({
+ INVALID_FILE: "invalid_file",
+ UNSUPPORTED_FORMAT: "unsupported_format",
+ TOO_LARGE: "too_large",
+ STORAGE_INSUFFICIENT: "storage_insufficient",
+ SAFETY_LIMIT_EXCEEDED: "safety_limit_exceeded",
+ READ_OR_DECODE_FAILED: "read_or_decode_failed",
+ STORAGE_WRITE_FAILED: "storage_write_failed"
+});
+
+const FAILURE_CODE_VALUES = new Set(Object.values(ASSET_IMPORT_FAILURE_CODES));
+
+export class AssetImportError extends Error {
+ constructor(code, message, details = {}, options = {}) {
+ super(String(message ?? "").trim() || "无法导入这个文件", options);
+ this.name = "AssetImportError";
+ this.code = FAILURE_CODE_VALUES.has(code) ? code : ASSET_IMPORT_FAILURE_CODES.READ_OR_DECODE_FAILED;
+ this.reasonCode = this.code;
+ this.details = normalizeFailureDetails(details);
+ this.forceAllowed = this.code === ASSET_IMPORT_FAILURE_CODES.TOO_LARGE && this.details.forceAllowed === true;
+ }
+}
+
+export function assetImportError(code, message, details = {}, options = {}) {
+ return new AssetImportError(code, message, details, options);
+}
+
+export function isAssetImportError(value) {
+ return value instanceof AssetImportError || (
+ value instanceof Error && FAILURE_CODE_VALUES.has(value.code)
+ );
+}
+
+export function importFailureDetails(value) {
+ const error = isAssetImportError(value)
+ ? value
+ : assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.READ_OR_DECODE_FAILED,
+ String(value?.message ?? value ?? "").trim() || "文件读取或解析失败"
+ );
+ return {
+ code: error.code,
+ message: error.message,
+ ...normalizeFailureDetails(error.details),
+ forceAllowed: error.forceAllowed === true
+ };
+}
+
export const PORTABLE_LIBRARY_LIMITS = Object.freeze({
maxArchiveBytes: 128 * MEBIBYTE,
maxFileCount: 4096,
@@ -45,10 +93,17 @@ export function assertImageDimensions(width, height, limitsValue = {}) {
const w = Number(width);
const h = Number(height);
if (!Number.isSafeInteger(w) || !Number.isSafeInteger(h) || w < 1 || h < 1) {
- throw new Error("图片尺寸无效");
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.READ_OR_DECODE_FAILED,
+ "无法读取有效的图片尺寸"
+ );
}
if (w * h > limits.maxImagePixels) {
- throw new Error(`图片像素超过 ${formatCount(limits.maxImagePixels)} 上限`);
+ throw assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.SAFETY_LIMIT_EXCEEDED,
+ `图片像素超过 ${formatCount(limits.maxImagePixels)} 安全上限,不能强制导入`,
+ { maxPixels: limits.maxImagePixels, actualPixels: w * h }
+ );
}
}
@@ -62,3 +117,14 @@ export function formatBytes(bytes) {
function formatCount(value) {
return Number(value).toLocaleString("en-US");
}
+
+function normalizeFailureDetails(value) {
+ if (!value || typeof value !== "object") return {};
+ const result = {};
+ for (const key of ["actualBytes", "maxBytes", "requiredBytes", "availableBytes", "actualPixels", "maxPixels"]) {
+ const number = Number(value[key]);
+ if (Number.isSafeInteger(number) && number >= 0) result[key] = number;
+ }
+ if (value.forceAllowed === true) result.forceAllowed = true;
+ return result;
+}
diff --git a/share-preview.js b/share-preview.js
index 2ee0e84..6981d15 100644
--- a/share-preview.js
+++ b/share-preview.js
@@ -6,6 +6,7 @@ import { entryPalette, normalizeEntryVisuals, primaryVisionDescription } from ".
import { posterAssetForVideo, primaryMediaAsset } from "./media.js";
import { createSimilarityIndex, rankSimilarEntries } from "./local-similarity.js";
import { promptForEntryImage } from "./image-prompt.js";
+import { assetFormatForExtension, fileExtension } from "./asset-formats.js";
const CONTENT_LABELS = Object.freeze({
"content:tutorial": ["攻略教程", "Tutorial"],
@@ -281,16 +282,18 @@ function renderCaseTile(entry, index, taxonomy, facetCatalog, className = "case-
function renderTileMedia(entry, primary, title) {
if (primary?.kind === "image") {
- const path = safeArchiveMediaPath(primary.assetPath, "image");
+ const path = safeArchiveMediaPath(primary.assetPath, primary);
if (path) return `<span class="tile-media"${aspectRatioStyle(primary)}><img src="${escapeAttribute(path)}" alt="${escapeAttribute(title)}" loading="lazy" decoding="async" /></span>`;
}
if (primary?.kind === "video") {
const poster = posterAssetForVideo(entry, primary);
- const path = safeArchiveMediaPath(poster?.assetPath, "image");
+ const path = safeArchiveMediaPath(poster?.assetPath, poster);
if (path) return `<span class="tile-media"${aspectRatioStyle(poster)}><img src="${escapeAttribute(path)}" alt="${escapeAttribute(`${title} 视频封面`)}" loading="lazy" decoding="async" /><span class="video-cue">▶</span>${primary.durationMs ? `<span class="video-duration">${formatDuration(primary.durationMs)}</span>` : ""}</span>`;
return renderFallbackCover("VIDEO", title, "video");
}
+ if (primary?.kind === "audio") return renderFallbackCover("AUDIO", title, "audio");
if (primary?.kind === "document") return renderFallbackCover(documentKind(primary), title, "document");
+ if (primary?.kind === "attachment") return renderFallbackCover(assetFormatLabel(primary), title, "attachment");
return renderFallbackCover("NOTE", title, "text");
}
@@ -303,7 +306,10 @@ function renderDetail(entry, index, taxonomy, facetCatalog, relatedEntries) {
const media = entry.mediaAssets.filter((asset) => asset.usage !== "poster");
const [contentZh, contentEn] = contentLabelPair(entry, taxonomy);
const [dateZh, dateEn] = formatDatePair(entry.savedAt);
- const attributes = entryAttributeSummary(entry, facetCatalog, 20);
+ const attributes = entryAttributeSummary(entry, facetCatalog, 20).map((item) => ({
+ ...item,
+ leafLabel: String(item.label || "").split("/").at(-1)?.trim() || item.label
+ }));
const palette = (entryPalette(entry)?.colors ?? []).filter(validColor);
const sourceUrl = safeWebUrl(entry.url);
const primary = primaryMediaAsset(entry);
@@ -319,7 +325,7 @@ function renderDetail(entry, index, taxonomy, facetCatalog, relatedEntries) {
<section class="detail-gallery">${renderDetailMedia(entry, media, title)}</section>
<aside class="detail-body">
<section class="detail-section detail-heading"><p class="eyebrow">PROMPTDIRECTOR</p><h2>${escapeHtml(title)}</h2><div class="detail-meta"><span data-zh="${escapeAttribute(contentZh)}" data-en="${escapeAttribute(contentEn)}">${escapeHtml(contentZh)}</span>${dateZh ? `<span data-zh="${escapeAttribute(dateZh)}" data-en="${escapeAttribute(dateEn)}">${escapeHtml(dateZh)}</span>` : ""}<span>${media.length} <span data-zh="项媒体" data-en="media items">项媒体</span></span></div>${palette.length ? `<div class="palette">${palette.map((color) => `<i style="background:${color}" title="${color}"></i>`).join("")}</div>` : ""}</section>
- ${attributes.length ? `<section class="detail-section"><h3 data-zh="创作属性" data-en="Creative attributes">创作属性</h3><div class="detail-tags">${attributes.map((item) => `<span>${escapeHtml(item.label)}</span>`).join("")}</div></section>` : ""}
+ ${attributes.length ? `<section class="detail-section"><h3 data-zh="AI 标签" data-en="AI tags">AI 标签</h3><div class="detail-tags">${attributes.map((item) => `<span title="${escapeAttribute(item.label)}">${escapeHtml(item.leafLabel)}</span>`).join("")}</div></section>` : ""}
${prompt ? `<section class="detail-section prompt-section"><div class="section-heading"><h3 data-zh="提示词" data-en="Prompt">提示词</h3><button class="button-secondary compact" type="button" data-copy-prompt="${escapeAttribute(prompt)}"><span data-zh="复制提示词" data-en="Copy prompt">复制提示词</span></button></div><pre class="prompt-text">${escapeHtml(prompt)}</pre><p class="compose-guide" data-zh="导入 PromptDirector 后可将当前图片作为具体参考继续创作。" data-en="Import this package into PromptDirector to continue creating with the current image as a specific reference.">导入 PromptDirector 后可将当前图片作为具体参考继续创作。</p></section>` : ""}
${visionDescription ? `<section class="detail-section"><h3 data-zh="画面描述" data-en="Visual description">画面描述</h3><p class="visual-description">${escapeHtml(visionDescription)}</p></section>` : ""}
${metadataRows || sourceUrl ? `<section class="detail-section"><div class="section-heading"><h3 data-zh="来源" data-en="Source">来源</h3>${sourceUrl ? `<a class="source-open-action" href="${escapeAttribute(sourceUrl)}" target="_blank" rel="noreferrer"><span data-zh="打开来源" data-en="Open source">打开来源</span></a>` : ""}</div>${metadataRows}</section>` : ""}
@@ -342,20 +348,26 @@ function renderMediaAsset(entry, asset, title) {
const description = clean(asset.visionAnalysis?.description);
let content;
if (asset.kind === "image") {
- const path = safeArchiveMediaPath(asset.assetPath, "image");
+ const path = safeArchiveMediaPath(asset.assetPath, asset);
content = path ? `<div class="detail-image-frame"><img src="${escapeAttribute(path)}" alt="${escapeAttribute(title)}" /></div>` : renderExternalMedia(asset, "图片");
} else if (asset.kind === "video") {
- const path = safeArchiveMediaPath(asset.assetPath, "video");
+ const path = safeArchiveMediaPath(asset.assetPath, asset);
const poster = posterAssetForVideo(entry, asset);
- const posterPath = safeArchiveMediaPath(poster?.assetPath, "image");
+ const posterPath = safeArchiveMediaPath(poster?.assetPath, poster);
content = path
? `<video controls preload="metadata"${posterPath ? ` poster="${escapeAttribute(posterPath)}"` : ""}><source src="${escapeAttribute(path)}" type="${escapeAttribute(asset.mimeType || "video/mp4")}" /></video>`
: renderExternalMedia(asset, "视频");
+ } else if (asset.kind === "audio") {
+ const path = safeArchiveMediaPath(asset.assetPath, asset);
+ content = path
+ ? `<div class="audio-panel"><strong>${escapeHtml(asset.sourceTitle || title)}</strong><audio controls preload="metadata"><source src="${escapeAttribute(path)}" type="${escapeAttribute(asset.mimeType || "audio/mpeg")}" /></audio><span>${escapeHtml(assetFileSummary(asset))}</span><a class="button-secondary" href="${escapeAttribute(path)}" download><span data-zh="下载源文件" data-en="Download source file">下载源文件</span></a></div>`
+ : renderExternalMedia(asset, "音频");
} else {
- const path = safeArchiveMediaPath(asset.assetPath, "document");
+ const path = safeArchiveMediaPath(asset.assetPath, asset);
+ const label = asset.kind === "attachment" ? "创作源文件" : "文档";
content = path
- ? `<div class="document-panel"><strong>${escapeHtml(documentKind(asset))}</strong><span>${escapeHtml(asset.sourceTitle || title)}</span><a class="button-primary" href="${escapeAttribute(path)}" target="_blank"><span data-zh="打开文档" data-en="Open document">打开文档</span></a></div>`
- : renderExternalMedia(asset, "文档");
+ ? `<div class="document-panel"><strong>${escapeHtml(assetFormatLabel(asset))}</strong><span>${escapeHtml(asset.sourceTitle || title)}</span><small>${escapeHtml(assetFileSummary(asset))}</small><a class="button-primary" href="${escapeAttribute(path)}" download><span data-zh="下载源文件" data-en="Download source file">下载源文件</span></a></div>`
+ : renderExternalMedia(asset, label);
}
const caption = prompt || description ? `<div class="media-caption">${prompt ? `<p><strong data-zh="本图提示词" data-en="Media prompt">本图提示词</strong>${escapeHtml(prompt)}</p>` : ""}${description ? `<p><strong data-zh="画面描述" data-en="Visual description">画面描述</strong>${escapeHtml(description)}</p>` : ""}</div>` : "";
return `${content}${caption}`;
@@ -368,9 +380,9 @@ function renderExternalMedia(asset, label) {
function renderMediaThumb(entry, asset, index) {
const image = asset.kind === "image" ? asset : asset.kind === "video" ? posterAssetForVideo(entry, asset) : null;
- const path = safeArchiveMediaPath(image?.assetPath, "image");
+ const path = safeArchiveMediaPath(image?.assetPath, image);
if (path) return `<img src="${escapeAttribute(path)}" alt="${index + 1}" loading="lazy" />`;
- return `<span>${escapeHtml(asset.kind === "video" ? "VIDEO" : documentKind(asset))}</span>`;
+ return `<span>${escapeHtml(asset.kind === "video" ? "VIDEO" : asset.kind === "audio" ? "AUDIO" : assetFormatLabel(asset))}</span>`;
}
function renderMetadataRows(labels = []) {
@@ -467,12 +479,16 @@ function safeWebUrl(value) {
}
}
-function safeArchiveMediaPath(value, kind) {
+function safeArchiveMediaPath(value, asset) {
const path = String(value ?? "");
if (!path || path.includes("..")) return "";
- if (kind === "image") return /^images\/[A-Za-z0-9._/-]+\.(?:png|jpe?g|webp)$/i.test(path) ? path : "";
- if (kind === "video") return /^videos\/[A-Za-z0-9._/-]+\.(?:mp4|webm|mov|mkv|avi|video)$/i.test(path) ? path : "";
- return /^documents\/[A-Za-z0-9._/-]+\.(?:pdf|md|txt|html?|bin)$/i.test(path) ? path : "";
+ const directories = { image: "images", video: "videos", audio: "audio", document: "documents", attachment: "attachments" };
+ const directory = directories[asset?.kind];
+ if (!directory || !(new RegExp(`^${directory}\\/[A-Za-z0-9._/-]+\\.[A-Za-z0-9]+$`, "i")).test(path)) return "";
+ const extension = fileExtension(path);
+ const format = assetFormatForExtension(extension);
+ if (format) return format.kind === asset.kind ? path : "";
+ return asset.kind === "attachment" && /^[a-z0-9]+$/u.test(extension) ? path : "";
}
function formatDatePair(value) {
@@ -499,6 +515,26 @@ function documentKind(asset) {
return "DOC";
}
+function assetFormatLabel(asset) {
+ const extension = clean(asset?.sourceFormat) || fileExtension(asset?.sourceTitle) || fileExtension(asset?.assetPath);
+ return extension ? extension.toLocaleUpperCase("en-US") : asset?.kind === "attachment" ? "FILE" : documentKind(asset);
+}
+
+function assetFileSummary(asset) {
+ const format = assetFormatLabel(asset);
+ const size = formatFileSize(asset?.byteSize);
+ return [format, size].filter(Boolean).join(" · ");
+}
+
+function formatFileSize(value) {
+ const bytes = Number(value);
+ if (!Number.isFinite(bytes) || bytes < 0) return "";
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
+ if (bytes >= 1024) return `${Math.round(bytes / 1024)} KiB`;
+ return `${Math.round(bytes)} B`;
+}
+
function aspectRatioStyle(asset) {
const width = Number(asset?.width);
const height = Number(asset?.height);
@@ -526,7 +562,7 @@ function escapeAttribute(value) {
function sharePreviewStyles() {
return `
- :root{--visual-wall-gap:2px;--visual-card-radius:2px}.share-icon-sprite{position:absolute;width:0;height:0;overflow:hidden}body{min-width:0;background:var(--ui-page)}body.detail-open{overflow:hidden}.app-header{position:sticky;z-index:20;top:0;display:flex;min-height:64px;align-items:center;gap:24px;border-bottom:1px solid var(--ui-border);padding:8px 12px;background:var(--bar);backdrop-filter:blur(16px)}.brand-block{display:grid;min-width:190px;gap:1px}.eyebrow{margin:0;color:var(--ui-accent);font-size:11px;font-weight:800;letter-spacing:.12em}.brand-block h1{max-width:340px;overflow:hidden;margin:0;color:var(--ui-text);font-size:18px;line-height:1.2;text-overflow:ellipsis;white-space:nowrap}.package-count{margin:0;color:var(--ui-muted);font-size:11px}.header-tools{display:flex;min-width:0;flex:1;align-items:center;justify-content:flex-end;gap:8px}.search-field{width:min(360px,32vw)}.type-field{width:min(180px,18vw)}.compact-setting{display:flex;align-items:center;gap:6px;color:var(--ui-muted);font-size:11px}.compact-setting select{width:auto;min-width:92px}.import-guide{display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--ui-border);padding:10px 14px;background:var(--ui-surface)}.import-guide p{margin:0;color:var(--ui-muted);font-size:11px;line-height:1.55}.import-guide strong{color:var(--ui-text)}.product-actions{display:flex;align-items:center;gap:7px}.install-action,.source-action{display:inline-flex;min-height:30px;align-items:center;padding:5px 9px;text-decoration:none;white-space:nowrap}.gallery-shell{padding:8px 6px 60px}.case-grid,.related-grid{position:relative;width:100%;overflow-anchor:none;--masonry-card-min-width:270px;--masonry-gap:var(--visual-wall-gap)}.case-card,.related-card{position:absolute;display:block;width:100%;min-height:0;overflow:hidden;border:0;border-radius:var(--visual-card-radius);padding:0;color:var(--ui-text);background:var(--ui-surface);cursor:pointer;vertical-align:top;white-space:normal}.case-card:hover,.related-card:hover{background:var(--ui-hover);box-shadow:0 8px 20px color-mix(in srgb,var(--ui-text) 10%,transparent)}.tile-media{position:relative;display:block;min-height:110px;overflow:hidden;background:var(--viewer-bg)}.tile-media img{display:block;width:100%;height:auto}.tile-media[style] img{height:100%;object-fit:cover}.video-cue{position:absolute;top:50%;left:50%;display:grid;width:38px;height:38px;place-items:center;border-radius:50%;color:white;background:rgba(7,9,11,.68);transform:translate(-50%,-50%)}.video-duration,.media-count{position:absolute;right:7px;bottom:7px;border-radius:3px;padding:2px 5px;color:white;background:rgba(7,9,11,.72);font-size:11px}.media-count{top:7px;bottom:auto}.fallback-cover{display:grid;min-height:190px;align-content:space-between;gap:18px;padding:16px;color:var(--ui-text);background:var(--ui-raised);text-align:left}.fallback-cover.document{background:linear-gradient(160deg,var(--ui-raised),var(--ui-surface))}.fallback-cover small{color:var(--ui-accent);font-size:11px;font-weight:800;letter-spacing:.12em}.fallback-cover strong{font-size:16px;line-height:1.35}.empty-state{padding:80px 20px;color:var(--ui-muted);text-align:center}.empty-state strong{color:var(--ui-text);font-size:18px}.detail-view{position:fixed;z-index:50;inset:0;overflow:auto;background:var(--viewer-bg)}.detail-toolbar{position:fixed;z-index:55;inset:0 0 auto;height:0;pointer-events:none}.detail-toolbar .icon-button{color:white;border-color:rgba(255,255,255,.22);background:rgba(15,17,19,.82);box-shadow:0 4px 18px rgba(0,0,0,.24);pointer-events:auto}.detail-toolbar>.icon-button{position:absolute;top:14px;right:14px}.detail-navigation{position:absolute;top:50dvh;right:clamp(380px,34vw,480px);left:0;display:flex;justify-content:space-between;padding:0 16px;transform:translateY(-50%)}.detail-stack{min-height:100%}.case-detail{min-height:100%;background:var(--ui-surface)}.detail-primary{display:grid;min-height:100dvh;grid-template-columns:minmax(0,1fr) clamp(380px,34vw,480px)}.detail-primary:not(.has-media){display:block}.detail-gallery{display:grid;min-width:0;min-height:100dvh;align-content:center;background:var(--viewer-bg)}.detail-media-stage{display:grid;min-height:0}.detail-media-panel{min-width:0}.detail-media-panel>video{display:block;width:100%;max-height:calc(100dvh - 88px);margin:auto;background:#06080c}.detail-image-frame{display:block;width:100%;min-height:0;margin:0;background:#06080c}.detail-image-frame img{display:block;width:100%;height:calc(100dvh - 88px);object-fit:contain}.detail-media-rail{display:flex;gap:7px;overflow-x:auto;padding:8px 10px 10px;background:var(--viewer-bg)}.detail-media-thumb{display:grid;width:76px;min-width:76px;min-height:58px;place-items:center;overflow:hidden;border:1px solid transparent;border-radius:6px;padding:0;color:white;background:#06080c;opacity:.72}.detail-media-thumb[aria-pressed="true"]{border-color:rgba(255,255,255,.62);opacity:1}.detail-media-thumb img{display:block;width:100%;height:56px;object-fit:cover}.media-caption{display:grid;gap:6px;padding:10px 12px;color:rgba(255,255,255,.82);background:color-mix(in srgb,var(--viewer-bg) 92%,white);font-size:11px}.media-caption p{margin:0}.media-caption strong{display:block;margin-bottom:2px;color:white}.document-panel,.detail-placeholder{display:grid;min-height:360px;place-items:center;align-content:center;gap:14px;padding:24px;color:var(--ui-muted);background:var(--ui-surface);text-align:center}.document-panel strong{color:var(--ui-accent);font-size:46px}.document-panel .button-primary{display:inline-flex;align-items:center;text-decoration:none}.detail-body{min-width:0;border-left:1px solid var(--ui-border);background:var(--ui-surface)}.detail-section{border-bottom:1px solid var(--ui-border);padding:16px 22px}.detail-section h2{margin:4px 0 8px;font-size:17px;line-height:1.35}.detail-section h3{margin:0 0 10px;font-size:11px}.detail-meta{display:flex;flex-wrap:wrap;gap:8px 14px;color:var(--ui-muted);font-size:11px}.palette{display:flex;height:16px;overflow:hidden;margin-top:12px;border-radius:4px}.palette i{flex:1}.detail-tags{display:flex;flex-wrap:wrap;gap:5px}.detail-tags span{padding:4px 7px;border-radius:999px;color:var(--ui-text);background:var(--ui-raised);font-size:11px;font-weight:700}.section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}.section-heading h3{margin:0}.prompt-text{max-height:360px;overflow:auto;margin:0;border-radius:6px;padding:14px;color:var(--prompt-ink);background:var(--prompt-bg);font:12px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.compose-guide,.visual-description{margin:10px 0 0;color:var(--ui-muted);font-size:11px;line-height:1.55}.source-open-action{display:inline-flex;min-height:30px;align-items:center;border:1px solid var(--ui-border);border-radius:4px;padding:5px 9px;color:var(--ui-text);font-size:11px;font-weight:700;text-decoration:none}.metadata-list{display:grid;margin:0}.metadata-row{display:grid;grid-template-columns:minmax(72px,104px) minmax(0,1fr);gap:12px;border-top:1px solid var(--ui-border);padding:7px 0}.metadata-row:first-child{border-top:0}.metadata-row dt{color:var(--ui-muted);font-size:11px;font-weight:700}.metadata-row dd{margin:0;overflow-wrap:anywhere;font-size:12px}.time-notes{display:grid;gap:8px;margin:0;padding:0;list-style:none}.time-notes li{display:grid;grid-template-columns:72px 1fr;gap:10px}.time-notes time{color:var(--ui-accent);font:11px ui-monospace,monospace}.time-notes span{font-size:12px}.related-section{border-top:1px solid var(--ui-border);padding:20px 6px 60px;background:var(--ui-page)}.related-section>header{display:flex;align-items:center;justify-content:space-between;margin:0 2px 10px}.related-section h3{margin:0;font-size:16px}.related-section header span{color:var(--ui-muted);font-size:11px}#feedback{position:fixed;z-index:90;right:18px;bottom:18px;max-width:min(360px,calc(100vw - 36px));margin:0;border:1px solid var(--ui-border-strong);border-radius:6px;padding:9px 12px;color:var(--ui-text);background:var(--ui-surface);box-shadow:var(--ui-shadow);font-size:12px;pointer-events:none}#feedback:empty{display:none}
+ :root{--visual-wall-gap:2px;--visual-card-radius:2px}.share-icon-sprite{position:absolute;width:0;height:0;overflow:hidden}body{min-width:0;background:var(--ui-page)}body.detail-open{overflow:hidden}.app-header{position:sticky;z-index:20;top:0;display:flex;min-height:64px;align-items:center;gap:24px;border-bottom:1px solid var(--ui-border);padding:8px 12px;background:var(--bar);backdrop-filter:blur(16px)}.brand-block{display:grid;min-width:190px;gap:1px}.eyebrow{margin:0;color:var(--ui-accent);font-size:11px;font-weight:800;letter-spacing:.12em}.brand-block h1{max-width:340px;overflow:hidden;margin:0;color:var(--ui-text);font-size:18px;line-height:1.2;text-overflow:ellipsis;white-space:nowrap}.package-count{margin:0;color:var(--ui-muted);font-size:11px}.header-tools{display:flex;min-width:0;flex:1;align-items:center;justify-content:flex-end;gap:8px}.search-field{width:min(360px,32vw)}.type-field{width:min(180px,18vw)}.compact-setting{display:flex;align-items:center;gap:6px;color:var(--ui-muted);font-size:11px}.compact-setting select{width:auto;min-width:92px}.import-guide{display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--ui-border);padding:10px 14px;background:var(--ui-surface)}.import-guide p{margin:0;color:var(--ui-muted);font-size:11px;line-height:1.55}.import-guide strong{color:var(--ui-text)}.product-actions{display:flex;align-items:center;gap:7px}.install-action,.source-action{display:inline-flex;min-height:30px;align-items:center;padding:5px 9px;text-decoration:none;white-space:nowrap}.gallery-shell{padding:8px 6px 60px}.case-grid,.related-grid{position:relative;width:100%;overflow-anchor:none;--masonry-card-min-width:270px;--masonry-gap:var(--visual-wall-gap)}.case-card,.related-card{position:absolute;display:block;width:100%;min-height:0;overflow:hidden;border:0;border-radius:var(--visual-card-radius);padding:0;color:var(--ui-text);background:var(--ui-surface);cursor:pointer;vertical-align:top;white-space:normal}.case-card:hover,.related-card:hover{background:var(--ui-hover);box-shadow:0 8px 20px color-mix(in srgb,var(--ui-text) 10%,transparent)}.tile-media{position:relative;display:block;min-height:110px;overflow:hidden;background:var(--viewer-bg)}.tile-media img{display:block;width:100%;height:auto}.tile-media[style] img{height:100%;object-fit:cover}.video-cue{position:absolute;top:50%;left:50%;display:grid;width:38px;height:38px;place-items:center;border-radius:50%;color:white;background:rgba(7,9,11,.68);transform:translate(-50%,-50%)}.video-duration,.media-count{position:absolute;right:7px;bottom:7px;border-radius:3px;padding:2px 5px;color:white;background:rgba(7,9,11,.72);font-size:11px}.media-count{top:7px;bottom:auto}.fallback-cover{display:grid;min-height:190px;align-content:space-between;gap:18px;padding:16px;color:var(--ui-text);background:var(--ui-raised);text-align:left}.fallback-cover.document,.fallback-cover.attachment{background:linear-gradient(160deg,var(--ui-raised),var(--ui-surface))}.fallback-cover.audio{background:linear-gradient(160deg,var(--viewer-bg),var(--ui-raised))}.fallback-cover small{color:var(--ui-accent);font-size:11px;font-weight:800;letter-spacing:.12em}.fallback-cover strong{font-size:16px;line-height:1.35}.empty-state{padding:80px 20px;color:var(--ui-muted);text-align:center}.empty-state strong{color:var(--ui-text);font-size:18px}.detail-view{position:fixed;z-index:50;inset:0;overflow:auto;background:var(--viewer-bg)}.detail-toolbar{position:fixed;z-index:55;inset:0 0 auto;height:0;pointer-events:none}.detail-toolbar .icon-button{color:white;border-color:rgba(255,255,255,.22);background:rgba(15,17,19,.82);box-shadow:0 4px 18px rgba(0,0,0,.24);pointer-events:auto}.detail-toolbar>.icon-button{position:absolute;top:14px;right:14px}.detail-navigation{position:absolute;top:50dvh;right:clamp(380px,34vw,480px);left:0;display:flex;justify-content:space-between;padding:0 16px;transform:translateY(-50%)}.detail-stack{min-height:100%}.case-detail{min-height:100%;background:var(--ui-surface)}.detail-primary{display:grid;min-height:100dvh;grid-template-columns:minmax(0,1fr) clamp(380px,34vw,480px)}.detail-primary:not(.has-media){display:block}.detail-gallery{display:grid;min-width:0;min-height:100dvh;align-content:center;background:var(--viewer-bg)}.detail-media-stage{display:grid;min-height:0}.detail-media-panel{min-width:0}.detail-media-panel>video{display:block;width:100%;max-height:calc(100dvh - 88px);margin:auto;background:#06080c}.detail-image-frame{display:block;width:100%;min-height:0;margin:0;background:#06080c}.detail-image-frame img{display:block;width:100%;height:calc(100dvh - 88px);object-fit:contain}.detail-media-rail{display:flex;gap:7px;overflow-x:auto;padding:8px 10px 10px;background:var(--viewer-bg)}.detail-media-thumb{display:grid;width:76px;min-width:76px;min-height:58px;place-items:center;overflow:hidden;border:1px solid transparent;border-radius:6px;padding:0;color:white;background:#06080c;opacity:.72}.detail-media-thumb[aria-pressed="true"]{border-color:rgba(255,255,255,.62);opacity:1}.detail-media-thumb img{display:block;width:100%;height:56px;object-fit:cover}.media-caption{display:grid;gap:6px;padding:10px 12px;color:rgba(255,255,255,.82);background:color-mix(in srgb,var(--viewer-bg) 92%,white);font-size:11px}.media-caption p{margin:0}.media-caption strong{display:block;margin-bottom:2px;color:white}.document-panel,.audio-panel,.detail-placeholder{display:grid;min-height:360px;place-items:center;align-content:center;gap:14px;padding:24px;color:var(--ui-muted);background:var(--ui-surface);text-align:center}.document-panel strong,.audio-panel>strong{color:var(--ui-accent);font-size:46px}.audio-panel>strong{font-size:18px}.audio-panel audio{width:min(520px,90%)}.document-panel .button-primary,.audio-panel .button-secondary{display:inline-flex;align-items:center;text-decoration:none}.detail-body{min-width:0;border-left:1px solid var(--ui-border);background:var(--ui-surface)}.detail-section{border-bottom:1px solid var(--ui-border);padding:16px 22px}.detail-section h2{margin:4px 0 8px;font-size:17px;line-height:1.35}.detail-section h3{margin:0 0 10px;font-size:11px}.detail-meta{display:flex;flex-wrap:wrap;gap:8px 14px;color:var(--ui-muted);font-size:11px}.palette{display:flex;height:16px;overflow:hidden;margin-top:12px;border-radius:4px}.palette i{flex:1}.detail-tags{display:flex;flex-wrap:wrap;gap:5px}.detail-tags span{padding:4px 7px;border-radius:999px;color:var(--ui-text);background:var(--ui-raised);font-size:11px;font-weight:700}.section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}.section-heading h3{margin:0}.prompt-text{max-height:360px;overflow:auto;margin:0;border-radius:6px;padding:14px;color:var(--prompt-ink);background:var(--prompt-bg);font:12px/1.7 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.compose-guide,.visual-description{margin:10px 0 0;color:var(--ui-muted);font-size:11px;line-height:1.55}.source-open-action{display:inline-flex;min-height:30px;align-items:center;border:1px solid var(--ui-border);border-radius:4px;padding:5px 9px;color:var(--ui-text);font-size:11px;font-weight:700;text-decoration:none}.metadata-list{display:grid;margin:0}.metadata-row{display:grid;grid-template-columns:minmax(72px,104px) minmax(0,1fr);gap:12px;border-top:1px solid var(--ui-border);padding:7px 0}.metadata-row:first-child{border-top:0}.metadata-row dt{color:var(--ui-muted);font-size:11px;font-weight:700}.metadata-row dd{margin:0;overflow-wrap:anywhere;font-size:12px}.time-notes{display:grid;gap:8px;margin:0;padding:0;list-style:none}.time-notes li{display:grid;grid-template-columns:72px 1fr;gap:10px}.time-notes time{color:var(--ui-accent);font:11px ui-monospace,monospace}.time-notes span{font-size:12px}.related-section{border-top:1px solid var(--ui-border);padding:20px 6px 60px;background:var(--ui-page)}.related-section>header{display:flex;align-items:center;justify-content:space-between;margin:0 2px 10px}.related-section h3{margin:0;font-size:16px}.related-section header span{color:var(--ui-muted);font-size:11px}#feedback{position:fixed;z-index:90;right:18px;bottom:18px;max-width:min(360px,calc(100vw - 36px));margin:0;border:1px solid var(--ui-border-strong);border-radius:6px;padding:9px 12px;color:var(--ui-text);background:var(--ui-surface);box-shadow:var(--ui-shadow);font-size:12px;pointer-events:none}#feedback:empty{display:none}select,select::picker(select){appearance:base-select}select::picker(select){max-height:min(360px,calc(100dvh - 32px));overflow:auto;border:1px solid var(--ui-border-strong);border-radius:var(--ui-container-radius);padding:6px;color:var(--ui-text);background:var(--ui-surface);box-shadow:var(--ui-shadow)}select option{min-height:36px;border-radius:var(--ui-control-radius);padding:7px 10px;color:var(--ui-text);background:var(--ui-surface)}select option:hover,select option:focus-visible{background:var(--ui-hover)}select option:checked{color:var(--ui-accent-contrast);background:var(--ui-accent);font-weight:750}
@media(max-width:860px){.app-header{align-items:flex-start;flex-direction:column;gap:8px}.header-tools{width:100%;flex-wrap:wrap;justify-content:flex-start}.search-field{flex:1 1 220px;width:auto}.type-field{flex:1 1 150px;width:auto}.compact-setting{flex:1 1 130px}.compact-setting select{flex:1}.import-guide{align-items:flex-start}.detail-primary{display:block}.detail-gallery{min-height:auto}.detail-image-frame img{height:min(62dvh,640px)}.detail-body{border-top:1px solid var(--ui-border);border-left:0}.detail-navigation{top:32dvh;right:0}.related-section{padding-bottom:28px}}
@media(max-width:520px){.app-header{position:static;padding:10px}.brand-block{min-width:0}.header-tools{display:grid;grid-template-columns:1fr 1fr}.search-field{grid-column:1/-1}.type-field{width:auto}.compact-setting{display:grid}.import-guide{flex-direction:column;padding:10px}.case-grid,.related-grid{--masonry-card-min-width:155px;--masonry-gap:var(--visual-wall-gap)}.detail-toolbar>.icon-button{top:10px;right:10px}.detail-navigation{top:31dvh;padding:0 10px}.detail-section{padding:14px 16px}.related-section{padding-inline:2px}.related-section>header{padding-inline:8px}.related-section header span{display:none}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index b4d6f3e..90fb6e8 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,9 +6,9 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current release candidate: `dist/PromptDirector-1.18.9.zip`.
-- Candidate size: `8,140,293` bytes.
-- Candidate SHA-256: `7a6471d13aea3f279577803b5672f91b80d85feaea6acfb87d83a5d7b2bb09ad`.
+- Current release candidate: `dist/PromptDirector-1.18.13.zip`.
+- Candidate size: `8,376,041` bytes.
+- Candidate SHA-256: `eb6d9281e4bfcdd879c1b4434691d4f4e93ad8b04ab3638132297f887b3499b0`.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest.
## Store listing
diff --git a/sync-model.js b/sync-model.js
index 8993613..be0cbd7 100644
--- a/sync-model.js
+++ b/sync-model.js
@@ -1,5 +1,6 @@
import { sha256Hex } from "./sync-crypto.js";
import { SCHEMA_VERSION, createDefaultTaxonomy, normalizeTaxonomy } from "./taxonomy.js";
+import { createDefaultTrashState } from "./trash.js";
export const SYNC_SNAPSHOT_FORMAT = "prompt-director-sync-state";
export const SYNC_SNAPSHOT_VERSION = 1;
@@ -18,7 +19,8 @@ const ARRAY_ENTITIES = Object.freeze({
collection: ["organizerState.collections", "id"],
composer_session: ["composerSessions", "id"],
creative_run: ["creativeRuns", "id"],
- creative_skill: ["creativeSkills.items", "id"]
+ creative_skill: ["creativeSkills.items", "id"],
+ trash_item: ["trashState.items", "id"]
});
const SINGLETON_ENTITIES = Object.freeze({
@@ -184,6 +186,27 @@ export function mergeRevisionSnapshots(values = []) {
records[key] = mergeCollectionRecords(key, heads, allRecords);
continue;
}
+ if (type === "trash_item") {
+ const active = heads.filter((item) => !item.deletedAt);
+ const deleted = heads.filter((item) => item.deletedAt);
+ if (deleted.length) {
+ records[key] = structuredClone(preferredRecord(deleted));
+ if (active.length) {
+ conflicts.push({ entityType: type, entityId, reason: "delete_edit", deviceId: preferredRecord(active).deviceId });
+ }
+ continue;
+ }
+ const winner = preferredRecord(active);
+ records[key] = structuredClone(winner);
+ for (const item of active.filter((candidate) => candidate.revisionId !== winner.revisionId)) {
+ conflictPayloads.push({
+ entityType: type,
+ payload: conflictEntity(type, item.payload, item, "concurrent_edit")
+ });
+ conflicts.push({ entityType: type, entityId, reason: "concurrent_edit", deviceId: item.deviceId });
+ }
+ continue;
+ }
if (["compound_case", "composer_session", "creative_run", "creative_skill"].includes(type)) {
const active = heads.filter((item) => !item.deletedAt);
const deleted = heads.filter((item) => item.deletedAt);
@@ -230,6 +253,7 @@ export function syncStateHasContent(state = {}) {
(state.composerSessions ?? []).length ||
(state.creativeRuns ?? []).length ||
(state.creativeSkills?.items ?? []).length ||
+ (state.trashState?.items ?? []).length ||
taxonomyHasUserChanges(state.taxonomy)
);
}
@@ -281,6 +305,7 @@ function restoreState(records) {
else if (type === "composer_session") state.composerSessions.push(payload);
else if (type === "creative_run") state.creativeRuns.push(payload);
else if (type === "creative_skill") state.creativeSkills.items.push(payload);
+ else if (type === "trash_item") state.trashState.items.push(payload);
else {
const target = SINGLETON_ENTITIES[type];
if (target === "libraryProfile") {
@@ -298,6 +323,10 @@ function restoreState(records) {
state.organizerState.collections.sort((left, right) =>
(Number(left.order) || 0) - (Number(right.order) || 0) || String(left.name).localeCompare(String(right.name))
);
+ state.trashState.items.sort((left, right) =>
+ String(left.deletedAt ?? "").localeCompare(String(right.deletedAt ?? "")) ||
+ String(left.id).localeCompare(String(right.id))
+ );
return { state, imageRefs };
}
@@ -345,6 +374,16 @@ function stripSyncImageRefs(payload, imageRefs) {
delete asset.syncContentType;
}
}
+ for (const asset of trashItemStoredAssets(payload)) {
+ const assetId = storedAssetId(asset);
+ if (!assetId || !asset?.syncObjectId) continue;
+ imageRefs[assetId] = {
+ objectId: asset.syncObjectId,
+ contentType: asset.syncContentType || asset.mimeType || "application/octet-stream"
+ };
+ delete asset.syncObjectId;
+ delete asset.syncContentType;
+ }
return payload;
}
@@ -359,10 +398,20 @@ function stateStoredAssets(stateValue) {
...(Array.isArray(stateValue?.composerSessions) ? stateValue.composerSessions : [])
.flatMap((session) => (Array.isArray(session?.referenceSnapshots) ? session.referenceSnapshots : [])
.filter((reference) => reference?.sourceType === "temporary")
- .flatMap((reference) => Array.isArray(reference?.assetRefs) ? reference.assetRefs : []))
+ .flatMap((reference) => Array.isArray(reference?.assetRefs) ? reference.assetRefs : [])),
+ ...(Array.isArray(stateValue?.trashState?.items) ? stateValue.trashState.items : [])
+ .flatMap(trashItemStoredAssets)
].filter(Boolean);
}
+function trashItemStoredAssets(item) {
+ if (!item || !["entry", "media"].includes(item.kind)) return [];
+ const snapshot = item.snapshot;
+ if (!snapshot || typeof snapshot !== "object") return [];
+ if (Array.isArray(snapshot.mediaAssets)) return snapshot.mediaAssets;
+ return Array.isArray(snapshot.visuals) ? snapshot.visuals : [];
+}
+
function storedAssetId(asset) {
return cleanId(asset?.id ?? asset?.assetId);
}
@@ -586,6 +635,15 @@ function conflictEntity(entityType, payload, record, reason) {
const source = structuredClone(payload);
const suffix = record.revisionId.replace(/[^a-z0-9]/gi, "").slice(-10);
source.id = `${source.id}-conflict-${suffix}`;
+ if (entityType === "trash_item") {
+ source.syncConflict = {
+ reason,
+ originalEntityId: record.entityId,
+ sourceDeviceId: record.deviceId,
+ revisionId: record.revisionId
+ };
+ return source;
+ }
source.title = `${cleanText(source.title) || "未命名记录"}(同步冲突副本)`;
source.syncConflict = {
reason,
@@ -637,7 +695,8 @@ function emptyState() {
organizerState: { version: 4, collections: [] },
composerSessions: [],
creativeRuns: [],
- creativeSkills: { version: 1, items: [] }
+ creativeSkills: { version: 1, items: [] },
+ trashState: createDefaultTrashState()
};
}
diff --git a/tag-editor.js b/tag-editor.js
new file mode 100644
index 0000000..8467997
--- /dev/null
+++ b/tag-editor.js
@@ -0,0 +1,153 @@
+export function normalizeTagValue(value) {
+ return String(value ?? "").normalize("NFKC")
+ .replace(/[\u0000-\u001f\u007f]/gu, "")
+ .replace(/\s+/gu, " ")
+ .trim()
+ .replace(/^[,,;;]+|[,,;;]+$/gu, "")
+ .trim();
+}
+
+export function normalizeTagValues(values = []) {
+ const result = [];
+ const keys = new Set();
+ for (const source of Array.isArray(values) ? values : splitTagInput(values)) {
+ const value = normalizeTagValue(source);
+ const key = value.toLocaleLowerCase();
+ if (!value || keys.has(key)) continue;
+ keys.add(key);
+ result.push(value);
+ }
+ return result;
+}
+
+export function addTagValues(current = [], additions = []) {
+ return normalizeTagValues([...normalizeTagValues(current), ...normalizeTagValues(additions)]);
+}
+
+export function splitTagInput(value) {
+ return String(value ?? "").split(/[,,;;\n\r]+/u);
+}
+
+export function createTagEditor(options = {}) {
+ const root = document.createElement("div");
+ root.className = ["tag-editor", options.className].filter(Boolean).join(" ");
+ const chips = document.createElement("div");
+ chips.className = "tag-editor-chips";
+ const row = document.createElement("div");
+ row.className = "tag-editor-row";
+ const input = document.createElement("input");
+ input.type = "text";
+ input.autocomplete = "off";
+ input.placeholder = options.placeholder || "输入标签,按回车或逗号添加";
+ input.setAttribute("aria-label", options.inputLabel || "添加标签");
+ const add = document.createElement("button");
+ add.type = "button";
+ add.className = "button-secondary";
+ add.textContent = options.addLabel || "添加";
+ row.append(input, add);
+ root.append(chips, row);
+
+ let values = normalizeTagValues(options.values);
+ let pendingChanges = 0;
+ let changeQueue = Promise.resolve(true);
+
+ const render = () => {
+ chips.hidden = values.length === 0;
+ chips.replaceChildren(...values.map((value) => {
+ const chip = document.createElement("span");
+ chip.className = "tag-editor-chip";
+ const text = document.createElement("span");
+ text.textContent = value;
+ const remove = document.createElement("button");
+ remove.type = "button";
+ remove.textContent = "×";
+ remove.setAttribute("aria-label", `删除标签:${value}`);
+ remove.addEventListener("click", () => void applyValues(values.filter((item) => item !== value), remove));
+ chip.append(text, remove);
+ return chip;
+ }));
+ };
+
+ const applyValues = (nextValue, trigger) => {
+ const previous = values;
+ const next = normalizeTagValues(nextValue);
+ if (sameValues(previous, next)) return Promise.resolve(true);
+ values = next;
+ render();
+ pendingChanges += 1;
+ root.setAttribute("aria-busy", "true");
+ const requested = [...next];
+ const run = async () => {
+ try {
+ const accepted = await options.onChange?.(requested, trigger);
+ if (accepted === false) {
+ if (sameValues(values, requested)) {
+ values = previous;
+ render();
+ }
+ return false;
+ }
+ return true;
+ } catch {
+ if (sameValues(values, requested)) {
+ values = previous;
+ render();
+ }
+ return false;
+ } finally {
+ pendingChanges -= 1;
+ if (pendingChanges === 0) root.removeAttribute("aria-busy");
+ }
+ };
+ changeQueue = changeQueue.then(run, run);
+ return changeQueue;
+ };
+
+ const commit = async () => {
+ const additions = normalizeTagValues(splitTagInput(input.value));
+ if (!additions.length) {
+ input.focus();
+ return false;
+ }
+ const changed = await applyValues(addTagValues(values, additions), add);
+ if (changed) input.value = "";
+ input.focus();
+ return changed;
+ };
+
+ add.addEventListener("click", () => void commit());
+ input.addEventListener("keydown", (event) => {
+ if (event.isComposing || !["Enter", ",", ","].includes(event.key)) return;
+ event.preventDefault();
+ void commit();
+ });
+ input.addEventListener("input", () => {
+ if (!/[,,\n\r]/u.test(input.value)) return;
+ const parts = input.value.split(/[,,\n\r]+/u);
+ input.value = parts.pop() ?? "";
+ const additions = normalizeTagValues(parts);
+ if (additions.length) void applyValues(addTagValues(values, additions), add);
+ });
+
+ render();
+ return {
+ element: root,
+ input,
+ button: add,
+ get values() { return [...values]; },
+ setValues(next) {
+ values = normalizeTagValues(next);
+ render();
+ },
+ setDisabled(disabled) {
+ input.disabled = Boolean(disabled);
+ add.disabled = Boolean(disabled);
+ chips.querySelectorAll("button").forEach((button) => { button.disabled = Boolean(disabled); });
+ },
+ commit
+ };
+}
+
+function sameValues(left, right) {
+ return left.length === right.length && left.every((value, index) => value === right[index]);
+}
diff --git a/taxonomy.js b/taxonomy.js
index db1698d..0801ba7 100644
--- a/taxonomy.js
+++ b/taxonomy.js
@@ -1,4 +1,4 @@
-export const SCHEMA_VERSION = 26;
+export const SCHEMA_VERSION = 27;
export const CONTENT_TYPE_VISIBILITY = Object.freeze({
library: "library",
diff --git a/test/asset-formats.test.js b/test/asset-formats.test.js
new file mode 100644
index 0000000..571d0e7
--- /dev/null
+++ b/test/asset-formats.test.js
@@ -0,0 +1,52 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ ASSET_FORMAT_REGISTRY,
+ SUPPORTED_ASSET_KINDS,
+ assetFileAccept,
+ assetFormatForExtension,
+ assetKindFromFileMetadata,
+ extensionsForAssetKind,
+ isReportedMimeCompatible
+} from "../asset-formats.js";
+
+test("asset format registry is the unique source for supported kinds extensions and picker values", () => {
+ assert.deepEqual(SUPPORTED_ASSET_KINDS, ["image", "video", "audio", "document", "attachment"]);
+ const extensions = ASSET_FORMAT_REGISTRY.flatMap((definition) => definition.extensions);
+ assert.equal(new Set(extensions).size, extensions.length);
+ assert.equal(assetFileAccept().split(",").length, extensions.length);
+ assert.equal(assetFileAccept({ kinds: ["audio"] }), extensionsForAssetKind("audio").map((value) => `.${value}`).join(","));
+});
+
+test("registry covers creator source files while keeping every proprietary format inert", () => {
+ for (const extension of [
+ "psd", "psb", "ai", "indd", "aep", "prproj", "sesx",
+ "ttf", "otf", "blend", "c4d", "ma", "mb", "hip", "fbx", "glb", "nk", "sbsar"
+ ]) {
+ const definition = assetFormatForExtension(extension);
+ assert.equal(definition?.kind, "attachment", extension);
+ assert.equal(definition?.preview, "inert", extension);
+ }
+ for (const executable of ["exe", "app", "dmg", "pkg", "js", "sh"]) {
+ assert.equal(assetFormatForExtension(executable), null);
+ }
+});
+
+test("subtitles are searchable documents and MIME conflicts do not change file identity", () => {
+ for (const extension of ["srt", "vtt", "ass", "ssa", "sbv", "lrc"]) {
+ const definition = assetFormatForExtension(extension);
+ assert.equal(definition?.kind, "document", extension);
+ assert.equal(definition?.category, "subtitle", extension);
+ assert.equal(definition?.plainText, true, extension);
+ }
+ assert.equal(assetKindFromFileMetadata({ name: "captions.srt", type: "text/plain" }), "document");
+ assert.equal(assetKindFromFileMetadata({ name: "captions.srt", type: "video/mp4" }), "");
+});
+
+test("generic browser MIME values are allowed only when a registered extension establishes the format", () => {
+ const photoshop = assetFormatForExtension("psd");
+ assert.equal(isReportedMimeCompatible(photoshop, "application/octet-stream"), true);
+ assert.equal(assetKindFromFileMetadata({ name: "source.psd", type: "application/octet-stream" }), "attachment");
+ assert.equal(assetKindFromFileMetadata({ name: "unknown.bin", type: "application/octet-stream" }), "");
+});
diff --git a/test/capture-draft.test.js b/test/capture-draft.test.js
index 142fa7d..8b0284c 100644
--- a/test/capture-draft.test.js
+++ b/test/capture-draft.test.js
@@ -45,7 +45,7 @@ test("X capture uses a compact account title while preserving the original sourc
assert.equal(captureTitleForSource("https://example.com/post", original), original);
});
-test("capture draft v3 groups repeated selections and retains normalized source context", () => {
+test("capture draft v4 groups repeated selections and retains normalized source context", () => {
let draft = createCaptureDraft({ targetCaseId: "compound:target" });
({ draft } = addDraftFragment(draft, { text: "第一段", sourceUrl: "https://a.example/post", sourceTitle: "A" }));
({ draft } = addDraftFragment(draft, { text: "第二段", sourceUrl: "https://a.example/post", sourceTitle: "A" }));
@@ -59,7 +59,7 @@ test("capture draft v3 groups repeated selections and retains normalized source
sourceFacts: { provider: "example", itemId: "work-1", author: "作者甲" }
}]
});
- assert.equal(draft.version, 3);
+ assert.equal(draft.version, 4);
assert.equal(draft.targetCaseId, "compound:target");
assert.equal(draft.sourceContexts[0].sourceFacts.author, "作者甲");
assert.deepEqual(draftParts(draft).map((part) => ({ url: part.sourceUrl, text: part.text })), [
@@ -82,13 +82,17 @@ test("capture metadata keeps an optional manual type and free-form labels withou
contentTypeId: "content:prompt:video",
contentTypeExplicit: true,
customLabels: ["待复刻", " 喜欢 ", "待复刻"],
- customLabelsExplicit: true
+ customLabelsExplicit: true,
+ collectionId: "collection:campaign",
+ newCollectionName: ""
});
assert.equal(draft.contentTypeId, "content:prompt:video");
assert.equal(draft.contentTypeExplicit, true);
assert.deepEqual(draft.customLabels, ["待复刻", "喜欢"]);
assert.equal(draft.customLabelsExplicit, true);
+ assert.equal(draft.collectionId, "collection:campaign");
+ assert.equal(draft.newCollectionName, "");
});
test("schema 12 visual normalization migrates one legacy screenshot without keeping singular screenshot fields", () => {
diff --git a/test/capture-permission-flow.test.js b/test/capture-permission-flow.test.js
index 77e4866..48f8bcd 100644
--- a/test/capture-permission-flow.test.js
+++ b/test/capture-permission-flow.test.js
@@ -3,6 +3,8 @@ import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import {
+ CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY,
+ CAPTURE_PERMISSION_ONBOARDING_VERSION,
CLIPBOARD_READ_PERMISSIONS,
CONTINUOUS_CAPTURE_ORIGINS,
ensureClipboardReadPermission,
@@ -10,9 +12,12 @@ import {
readClipboardContentAfterFocus,
ensureContinuousCapturePermission,
ensurePagePermission,
+ inspectCapturePermissionBundle,
inspectPagePermission,
+ normalizeCapturePermissionOnboarding,
pageCapturePermissionFailureMessage,
pagePermissionPattern,
+ requestCapturePermissionBundle,
RESTRICTED_PAGE_MESSAGE,
resolveActivePage
} from "../capture-permissions.js";
@@ -149,6 +154,7 @@ test("denied screenshot permission stops before tab lookup and leaves the draft
test("continuous capture requests the declared all-sites permission from the user gesture", async () => {
const requests = [];
const granted = await ensureContinuousCapturePermission({
+ contains: async () => false,
request: async (request) => {
requests.push(request);
return true;
@@ -159,6 +165,98 @@ test("continuous capture requests the declared all-sites permission from the use
assert.deepEqual(requests, [{ origins: [...CONTINUOUS_CAPTURE_ORIGINS] }]);
});
+test("first-use capture onboarding requests web capture and the default clipboard choice together", async () => {
+ const requests = [];
+ const permissions = {
+ contains: async () => false,
+ request: async (request) => {
+ requests.push(request);
+ return true;
+ }
+ };
+
+ assert.equal(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY, "capturePermissionOnboarding");
+ assert.deepEqual(normalizeCapturePermissionOnboarding(null), {
+ version: CAPTURE_PERMISSION_ONBOARDING_VERSION,
+ acknowledgedAt: "",
+ clipboardIncluded: true
+ });
+ const current = await inspectCapturePermissionBundle(permissions);
+ assert.deepEqual(current, { webCaptureGranted: false, clipboardGranted: false });
+ assert.deepEqual(await requestCapturePermissionBundle(permissions, { current }), {
+ granted: true,
+ requested: {
+ origins: [...CONTINUOUS_CAPTURE_ORIGINS],
+ permissions: [...CLIPBOARD_READ_PERMISSIONS]
+ }
+ });
+ assert.deepEqual(requests, [{
+ origins: [...CONTINUOUS_CAPTURE_ORIGINS],
+ permissions: [...CLIPBOARD_READ_PERMISSIONS]
+ }]);
+});
+
+test("first-use capture onboarding can omit clipboard without adding another request", async () => {
+ const requests = [];
+ const result = await requestCapturePermissionBundle({
+ request: async (request) => {
+ requests.push(request);
+ return true;
+ }
+ }, {
+ includeClipboard: false,
+ current: { webCaptureGranted: false, clipboardGranted: false }
+ });
+
+ assert.deepEqual(result, {
+ granted: true,
+ requested: { origins: [...CONTINUOUS_CAPTURE_ORIGINS] }
+ });
+ assert.deepEqual(requests, [{ origins: [...CONTINUOUS_CAPTURE_ORIGINS] }]);
+});
+
+test("collector explains every first-use capability and resumes only the pending capture action", async () => {
+ const [source, html] = await Promise.all([
+ readFile(new URL("collector.js", projectRoot), "utf8"),
+ readFile(new URL("collector.html", projectRoot), "utf8")
+ ]);
+ assert.match(html, /id="capture-permission-onboarding"/);
+ assert.match(html, /网页采集/);
+ assert.match(html, /截图/);
+ assert.match(html, /id="capture-permission-clipboard"[^>]*checked/);
+ assert.match(html, /打开侧栏、点击网页或高亮文字都不会读取剪贴板/);
+ assert.match(html, /不会自动保存案例/);
+ assert.match(source, /pendingCaptureAction = \{ action, permissionStatus \}/);
+ assert.match(source, /await pending\.action\(\{ clipboardPreferenceJustDeclined: !includeClipboard \}\)/);
+ const cancelFlow = source.slice(source.indexOf("function cancelCapturePermissionOnboarding"), source.indexOf("async function confirmCapturePermissionOnboarding"));
+ assert.doesNotMatch(cancelFlow, /storage\.local\.set|pending\.action/);
+ const autoFlow = source.slice(source.indexOf("async function tryAutoSelection"), source.indexOf("async function extractClipboardOrSelection"));
+ assert.doesNotMatch(autoFlow, /readClipboardContentAfterFocus|ensureClipboardReadPermission/);
+});
+
+test("declining clipboard is honored for the original action and later enablement stays explicit", async () => {
+ const [source, html] = await Promise.all([
+ readFile(new URL("collector.js", projectRoot), "utf8"),
+ readFile(new URL("collector.html", projectRoot), "utf8")
+ ]);
+ const fallback = source.slice(
+ source.indexOf("async function extractClipboardOrSelection"),
+ source.indexOf("function cancelClipboardPermissionEnable")
+ );
+ assert.match(fallback, /clipboardPreferenceJustDeclined/);
+ assert.match(fallback, /已按你的选择保持剪贴板关闭,未读取任何内容/);
+ assert.match(fallback, /pendingClipboardButton = button/);
+ assert.match(fallback, /clipboardPermissionDialog\.showModal\(\)/);
+ const explicitEnable = source.slice(
+ source.indexOf("async function confirmClipboardPermissionEnable"),
+ source.indexOf("async function extractClipboardContent")
+ );
+ assert.match(explicitEnable, /ensureClipboardReadPermission\(chrome\.permissions\)/);
+ assert.match(explicitEnable, /clipboardIncluded: true/);
+ assert.match(html, /id="clipboard-permission-confirm"[^>]*>启用并提取/);
+ assert.match(html, /打开侧栏、浏览或点击网页不会触发读取/);
+});
+
test("text collection keeps its narrower per-site permission", async () => {
const calls = [];
const permissions = {
diff --git a/test/case-management-ui.test.js b/test/case-management-ui.test.js
new file mode 100644
index 0000000..fadf902
--- /dev/null
+++ b/test/case-management-ui.test.js
@@ -0,0 +1,70 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const [html, source, icons] = await Promise.all([
+ readFile(new URL("../library.html", import.meta.url), "utf8"),
+ readFile(new URL("../library.js", import.meta.url), "utf8"),
+ readFile(new URL("../assets/ui-icons.svg", import.meta.url), "utf8")
+]);
+
+test("selection mode exposes all filtered results, user tags, projects, sharing, and recycle-bin actions", () => {
+ const bar = html.slice(html.indexOf('id="share-bar"'), html.indexOf('id="project-selection-title"'));
+ for (const id of [
+ "selection-select-filtered",
+ "selection-clear",
+ "selection-label-input",
+ "selection-add-labels",
+ "selection-project-target",
+ "selection-add-project",
+ "share-export",
+ "selection-trash"
+ ]) assert.match(bar, new RegExp(`id="${id}"`));
+
+ const selectAll = source.slice(source.indexOf("function selectAllFilteredCases"), source.indexOf("function clearSelectedCases"));
+ assert.match(selectAll, /visibleEntries\.map\(\(entry\) => entry\.id\)/);
+ assert.doesNotMatch(selectAll, /renderedCount|caseList\.children/);
+ const selectionSync = source.slice(source.indexOf("function replaceSelectedCaseIds"), source.indexOf("function updateSelectionBar"));
+ assert.match(selectionSync, /selectedCaseIds\.clear\(\)/);
+ assert.match(selectionSync, /updateSelectionBar\(\)/);
+ assert.match(source, /LIBRARY_BATCH_ACTIONS\.addCustomLabels/);
+ assert.match(source, /LIBRARY_BATCH_ACTIONS\.setProject/);
+ assert.match(source, /LIBRARY_BATCH_ACTIONS\.moveToTrash/);
+});
+
+test("recycle bin is a first-class workspace action with restore and explicit permanent cleanup", () => {
+ assert.match(html, /id="open-trash"/);
+ assert.match(html, /id="trash-dialog"/);
+ assert.match(icons, /id="icon-trash-2"/);
+ assert.match(source, /type: "GET_TRASH_ITEMS"/);
+ assert.match(source, /type: "RESTORE_TRASH_ITEMS"/);
+ assert.match(source, /type: "PERMANENT_DELETE_TRASH_ITEMS"/);
+ assert.match(source, /type: "EMPTY_TRASH"/);
+ assert.match(source, /itemIds: relatedTrashGroupIds\(item\)/);
+ assert.match(html, /id="trash-restore-all"[^>]*>全部恢复/);
+ assert.doesNotMatch(html, /id="trash-refresh"/);
+ const restoreAll = source.slice(source.indexOf("async function restoreAllTrashItems"), source.indexOf("function relatedTrashGroupIds"));
+ assert.match(restoreAll, /itemIds: trashItems\.map\(\(item\) => item\.id\)/);
+ assert.match(restoreAll, /response\.unresolved/);
+ const restoreGroup = source.slice(source.indexOf("function relatedTrashGroupIds"), source.indexOf("async function permanentlyDeleteTrashItem"));
+ assert.match(restoreGroup, /item\.kind === "collection"/);
+ assert.match(restoreGroup, /item\.kind === "entry"/);
+ assert.match(restoreGroup, /item\.kind === "media"/);
+ assert.match(source, /PERMANENT_DELETE_TRASH_ITEMS", itemIds/);
+ assert.match(source, /trashItemPreview/);
+ assert.match(source, /hydrateTrashCover/);
+ assert.match(source, /createUiIcon\("refresh-cw"\)/);
+ assert.doesNotMatch(html, /RECYCLE BIN|删除后会保留在这里/);
+});
+
+test("project and case removal use recoverable wording in normal management", () => {
+ assert.match(source, /"仅删除项目"/);
+ assert.match(source, /"删除项目及案例"/);
+ assert.match(source, /createUiIcon\("trash-2"\)/);
+ assert.match(source, /这项媒体可从回收站恢复/);
+ const projectHandler = source.slice(
+ source.indexOf("async function deleteProjectCollectionWithEntries"),
+ source.indexOf("function enterProjectSelection")
+ );
+ assert.doesNotMatch(projectHandler, /永久删除|请输入完整项目名称/);
+});
diff --git a/test/clipboard_capture_e2e.py b/test/clipboard_capture_e2e.py
index f770118..0e2be81 100644
--- a/test/clipboard_capture_e2e.py
+++ b/test/clipboard_capture_e2e.py
@@ -67,6 +67,13 @@ def main() -> None:
)
collector = session.open_page("collector.html")
expect(collector.locator("#start-state")).to_be_visible()
+ collector.evaluate("""() => chrome.storage.local.set({
+ capturePermissionOnboarding: {
+ version: 1,
+ acknowledgedAt: new Date().toISOString(),
+ clipboardIncluded: true
+ }
+ })""")
assert collector.evaluate("window.__promptDirectorClipboardReads") == 0
collector.locator("#start-selection").click()
@@ -107,12 +114,29 @@ def main() -> None:
cleared_text_draft = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_CAPTURE_WORKSPACE'}).then(result => result.draft)")
assert cleared_text_draft["fragments"] == [], cleared_text_draft
+ reads_before_decline = collector.evaluate("window.__promptDirectorClipboardReads")
+ collector.evaluate("""() => chrome.storage.local.set({
+ capturePermissionOnboarding: {
+ version: 1,
+ acknowledgedAt: new Date().toISOString(),
+ clipboardIncluded: false
+ }
+ })""")
+ collector.locator("#start-selection").click()
+ expect(collector.locator("#clipboard-permission-dialog")).to_be_visible()
+ assert collector.evaluate("window.__promptDirectorClipboardReads") == reads_before_decline
+ collector.locator("#clipboard-permission-cancel").click()
+ expect(collector.locator("#clipboard-permission-dialog")).to_be_hidden()
+ assert collector.evaluate("window.__promptDirectorClipboardReads") == reads_before_decline
+
print({
"automatic_clipboard_reads": 0,
"explicit_clipboard_reads": 3,
"copied_image_imported": True,
"saved_clipboard_can_be_extracted_again": True,
"single_item_removal": True,
+ "persisted_clipboard_opt_out_read": False,
+ "later_explicit_clipboard_enable_prompt": True,
"mobile_sidebar": True,
})
diff --git a/test/collector-view.test.js b/test/collector-view.test.js
index 3dd22cf..13f897c 100644
--- a/test/collector-view.test.js
+++ b/test/collector-view.test.js
@@ -207,3 +207,32 @@ test("the collector auto-reads only highlights and reserves clipboard access for
assert.match(collectorSource, /addOtherCaptureMethods\.open = smartVisualFallback/);
assert.match(collectorSource, /if \(draft\) render\(\)/);
});
+
+test("every captured draft exposes project and the shared multi-tag editor before save", async () => {
+ const [collectorSource, collectorHtml, draftSource] = await Promise.all([
+ readFile(new URL("../collector.js", import.meta.url), "utf8"),
+ readFile(new URL("../collector.html", import.meta.url), "utf8"),
+ readFile(new URL("../capture-draft.js", import.meta.url), "utf8")
+ ]);
+ const metadata = collectorHtml.slice(
+ collectorHtml.indexOf('<section id="capture-metadata"'),
+ collectorHtml.indexOf('<div id="capture-add-more-actions"')
+ );
+ assert.match(metadata, /id="capture-collection"/);
+ assert.match(metadata, /id="capture-new-collection-name"/);
+ assert.match(metadata, /添加标签/);
+ assert.doesNotMatch(metadata, /自由标签|可选|不用预先创建|输入任意新标签/);
+ assert.match(metadata, /id="custom-labels"/);
+ assert.doesNotMatch(metadata, /<details/);
+ assert.match(collectorSource, /collections = response\.collections \?\? \[\]/);
+ assert.match(collectorSource, /const selectedCollection = elements\.captureCollection\.value/);
+ assert.match(collectorSource, /newCollectionName: selectedCollection === NEW_COLLECTION_OPTION_VALUE/);
+ assert.match(collectorSource, /const customLabelEditor = createTagEditor/);
+ assert.match(collectorSource, /customLabels: customLabelEditor\.values/);
+ assert.match(collectorSource, /type: "COMMIT_CAPTURE_DRAFT",[\s\S]*\.\.\.metadata/);
+ assert.match(collectorSource, /type: "COMMIT_PAGE_CAPTURE",[\s\S]*\.\.\.captureMetadataForCommit\(\)/);
+ assert.match(collectorSource, /pageCaptureActions\.before\(elements\.captureMetadata\)/);
+ assert.match(collectorSource, /captureAddMoreActions\.before\(elements\.captureMetadata\)/);
+ assert.match(draftSource, /collectionId: clean\(value\.collectionId\)/);
+ assert.match(draftSource, /newCollectionName: clean\(value\.newCollectionName\)/);
+});
diff --git a/test/compound-ui.test.js b/test/compound-ui.test.js
index 330f3ff..dcbe8b9 100644
--- a/test/compound-ui.test.js
+++ b/test/compound-ui.test.js
@@ -27,9 +27,10 @@ test("compound details expose direct primary-case and cover-image actions", () =
assert.doesNotMatch(organizer, /labeledSelect\("封面"/);
});
-test("long compound-part titles stay on one line beside fixed actions", () => {
+test("long compound-part titles wrap fully beside fixed actions", () => {
assert.match(styles, /\.compound-part-heading\s*>\s*div:first-child\s*\{[^}]*min-width:\s*0/);
- assert.match(styles, /\.compound-part-heading h3\s*\{[^}]*overflow:\s*hidden[^}]*text-overflow:\s*ellipsis[^}]*white-space:\s*nowrap/);
+ assert.match(styles, /\.compound-part-heading h3\s*\{[^}]*overflow-wrap:\s*anywhere/);
+ assert.doesNotMatch(styles, /\.compound-part-heading h3\s*\{[^}]*text-overflow:\s*ellipsis/);
assert.match(styles, /\.compound-part-heading-actions\s*\{[^}]*flex:\s*0 0 auto/);
});
diff --git a/test/curated-import.test.js b/test/curated-import.test.js
index e132abd..3148e54 100644
--- a/test/curated-import.test.js
+++ b/test/curated-import.test.js
@@ -76,12 +76,14 @@ test("curated pack import creates one stable local project", () => {
const result = mergeCuratedLibraryPackage(emptyState(), library, {
packageId: catalogItem.packageId,
projectName: catalogItem.title,
- mode: "package"
+ mode: "package",
+ now: "2026-08-22T09:00:00.000Z"
});
assert.equal(result.importedCount, 2);
assert.equal(result.existingCount, 0);
assert.equal(result.projectId, "curated-project:test-pack");
assert.deepEqual(result.state.organizerState.collections[0].entryIds.toSorted(), result.importedEntryIds.toSorted());
+ assert.equal(result.state.organizerState.collections[0].createdAt, "2026-08-22T09:00:00.000Z");
});
test("curated updates preserve personal edits and add only missing stable sources", () => {
diff --git a/test/curated-navigation.test.js b/test/curated-navigation.test.js
index 6e8714e..94850a4 100644
--- a/test/curated-navigation.test.js
+++ b/test/curated-navigation.test.js
@@ -25,9 +25,11 @@ test("curated discovery keeps the pack wall concise and opens a separate read-on
const { page, html, css } = await sources();
assert.match(html, /id="curated-search"/);
assert.match(html, /id="filter-button"/);
- assert.match(html, /data-sort="recommended"/);
- assert.match(html, /data-sort="latest"/);
- assert.match(html, /data-sort="downloads"/);
+ assert.match(html, /<select id="sort-menu"/);
+ assert.match(html, /value="recommended"/);
+ assert.match(html, /value="latest"/);
+ assert.match(html, /value="downloads"/);
+ assert.doesNotMatch(html, /<details[^>]*class="sort-menu"/);
assert.match(html, /<dialog id="detail-dialog"/);
assert.match(html, /id="case-detail-drawer"/);
assert.match(html, /id="case-detail-prev"/);
diff --git a/test/curated_workflow_e2e.py b/test/curated_workflow_e2e.py
index f487533..f44eb2c 100644
--- a/test/curated_workflow_e2e.py
+++ b/test/curated_workflow_e2e.py
@@ -167,6 +167,18 @@ def main() -> None:
curated.locator("#retry-catalog").click()
expect(curated.locator(".pack-grid .pack-card")).to_have_count(1)
expect(curated.locator("#sort-downloads")).to_be_enabled()
+ sort_style = curated.locator("#sort-menu").evaluate(
+ """node => ({
+ appearance: getComputedStyle(node).appearance,
+ supported: CSS.supports('appearance: base-select'),
+ background: getComputedStyle(node).backgroundColor
+ })"""
+ )
+ assert sort_style["supported"] is True, sort_style
+ assert sort_style["appearance"] == "base-select", sort_style
+ assert sort_style["background"] not in {"rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"}, sort_style
+ curated.locator("#sort-menu").select_option("latest")
+ expect(curated.locator("#sort-menu")).to_have_value("latest")
expect(curated.locator("#filter-popover")).to_be_hidden()
expect(curated.locator(".pack-card h2")).to_have_text("工作流精选")
expect(curated.locator(".pack-card .pack-meta")).to_contain_text("PromptDirector 编辑精选")
diff --git a/test/custom-select-ui.test.js b/test/custom-select-ui.test.js
new file mode 100644
index 0000000..d91f8b0
--- /dev/null
+++ b/test/custom-select-ui.test.js
@@ -0,0 +1,18 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const [manifest, foundation, sharePreview] = await Promise.all([
+ readFile(new URL("../manifest.json", import.meta.url), "utf8"),
+ readFile(new URL("../ui-foundation.css", import.meta.url), "utf8"),
+ readFile(new URL("../share-preview.js", import.meta.url), "utf8")
+]);
+
+test("Chrome 134 customizable selects use the shared PromptDirector surface", () => {
+ assert.equal(JSON.parse(manifest).minimum_chrome_version, "134");
+ assert.match(foundation, /select,\s*select::picker\(select\)\s*\{\s*appearance: base-select/);
+ assert.match(foundation, /select::picker\(select\)[\s\S]*background: var\(--ui-surface\)/);
+ assert.match(foundation, /select option:checked[\s\S]*background: var\(--ui-accent\)/);
+ assert.match(foundation, /select:open::picker-icon/);
+ assert.match(sharePreview, /appearance:base-select/);
+});
diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.js
index 98abac9..3dcc15e 100644
--- a/test/data-safety-ui.test.js
+++ b/test/data-safety-ui.test.js
@@ -85,7 +85,7 @@ test("share-package import preserves local configuration and accepts historical
assert.match(action, /APPLY_LIBRARY_IMPORT/);
assert.equal((action.match(/preserveLibraryConfiguration:\s*true/g) ?? []).length, 2);
assert.match(parser, /isSupportedLibraryPackageVersion\(value\.version\)/);
- assert.match(format, /SUPPORTED_LIBRARY_PACKAGE_VERSIONS\s*=\s*Object\.freeze\(\[1, 2, 3\]\)/);
+ assert.match(format, /SUPPORTED_LIBRARY_PACKAGE_VERSIONS\s*=\s*Object\.freeze\(\[1, 2, 3, 4\]\)/);
});
test("data safety cannot be dismissed accidentally while a storage operation is running", async () => {
diff --git a/test/detail-quick-organize-ui.test.js b/test/detail-quick-organize-ui.test.js
new file mode 100644
index 0000000..c80b253
--- /dev/null
+++ b/test/detail-quick-organize-ui.test.js
@@ -0,0 +1,101 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const source = await readFile(new URL("../library.js", import.meta.url), "utf8");
+const css = await readFile(new URL("../library.css", import.meta.url), "utf8");
+const foundation = await readFile(new URL("../ui-foundation.css", import.meta.url), "utf8");
+const tagEditor = await readFile(new URL("../tag-editor.js", import.meta.url), "utf8");
+
+const quickOrganizer = source.slice(
+ source.indexOf("function createDetailQuickOrganization"),
+ source.indexOf("function createDetailDeleteAction")
+);
+const footerActions = source.slice(
+ source.indexOf("function createDetailDeleteAction"),
+ source.indexOf("function createComposerAction")
+);
+const editor = source.slice(
+ source.indexOf("function createEntryEditor"),
+ source.indexOf("function renderManager")
+);
+const attributes = source.slice(
+ source.indexOf("function createDetailAttributes"),
+ source.indexOf("function createDetailMetadata")
+);
+
+test("detail organization follows prompt and AI tags without an extra section title", () => {
+ const detail = source.slice(source.indexOf("async function renderDetail"), source.indexOf("function createLocalDiscovery"));
+ assert.ok(detail.indexOf("createDetailAttributes(entry)") < detail.indexOf("createDetailQuickOrganization(entry)"));
+ assert.doesNotMatch(quickOrganizer, /"快捷整理"/);
+ assert.match(quickOrganizer, /"项目"/);
+ assert.match(quickOrganizer, /"添加标签"/);
+ assert.doesNotMatch(quickOrganizer, /可选|任意输入|不用预先创建|还没有/);
+ assert.match(quickOrganizer, /entry\.compoundCase\?\.customLabels \?\? entry\.customLabels/);
+});
+
+test("detail projects use a compact multi-project dropdown and can be created in place", () => {
+ assert.match(quickOrganizer, /detail-project-menu/);
+ assert.match(quickOrganizer, /"选择项目"/);
+ assert.match(quickOrganizer, /`已加入 \$\{selectedProjects\.length\} 个项目`/);
+ assert.match(quickOrganizer, /checkbox\.type = "checkbox"/);
+ assert.match(quickOrganizer, /type: "REPLACE_COLLECTION_ENTRIES"/);
+ assert.match(quickOrganizer, /type: "CREATE_COLLECTION"/);
+ assert.match(quickOrganizer, /"新建并加入"/);
+ assert.match(quickOrganizer, /expandLogicalCaseIds\(\[entry\.id\], compoundCases\)/);
+});
+
+test("detail uses the shared removable multi-tag editor", () => {
+ assert.match(quickOrganizer, /createTagEditor/);
+ assert.match(tagEditor, /\["Enter", ",", ","\]\.includes\(event\.key\)/);
+ assert.match(tagEditor, /splitTagInput/);
+ assert.match(tagEditor, /删除标签/);
+ assert.match(source, /type: "UPDATE_ENTRY_CUSTOM_LABELS"/);
+ assert.match(source, /type: "UPDATE_COMPOUND_CASE"/);
+ assert.match(foundation, /\.tag-editor-chip\s*\{/);
+});
+
+test("case deletion is a visible one-step recycle-bin action and no longer lives in the editor", () => {
+ const detail = source.slice(source.indexOf("async function renderDetail"), source.indexOf("function createLocalDiscovery"));
+ const metadata = source.slice(source.indexOf("function createDetailMetadata"), source.indexOf("function createFullAnalysis"));
+ assert.doesNotMatch(quickOrganizer, /移入回收站|trash-2|deleteCaseIncrementally/);
+ assert.match(footerActions, /"移入回收站"/);
+ assert.match(footerActions, /createUiIcon\("trash-2"\)/);
+ assert.match(footerActions, /案例及其媒体会移入回收站,可随时恢复/);
+ assert.match(footerActions, /deleteCaseIncrementally\(deleteButton, entry\.id\)/);
+ assert.match(detail, /createDetailMetadata\(entry, \{ includeDelete: true \}\)/);
+ assert.match(detail, /else body\.append\(createDetailFooterActions\(entry\)\)/);
+ assert.match(metadata, /if \(includeDelete\) actions\.append\(createDetailDeleteAction\(entry\)\)/);
+ assert.doesNotMatch(detail, /content\.append\(createDetailFooterActions\(entry\)\)/);
+ assert.doesNotMatch(editor, /DELETE_ENTRY|deleteCaseIncrementally|删除这个案例/);
+});
+
+test("single-image prompts have one editor while multi-image prompts separate current and shared text", () => {
+ const prompt = source.slice(source.indexOf("function createPromptSection"), source.indexOf("async function analyzeEntryVisualSet"));
+ assert.match(prompt, /const separatesCurrentAndShared = Boolean/);
+ assert.match(prompt, /imageAssets\.length > 1 \|\| options\.compoundMember/);
+ assert.match(prompt, /separatesCurrentAndShared \? "编辑当前图片" : "编辑"/);
+ assert.match(prompt, /separatesCurrentAndShared && entry\.text \? textEl\("button", "button-secondary", "编辑共享提示词"\)/);
+});
+
+test("entry title editing keeps one visible heading and an inline save action", () => {
+ assert.match(editor, /textEl\("h4", "", "案例标题"\)/);
+ assert.match(editor, /textEl\("span", "sr-only", "案例标题"\)/);
+ assert.match(editor, /el\("div", "entry-edit-row"\)/);
+ assert.match(editor, /const saveTitle = textEl\("button", "button-secondary", "保存"\)/);
+ assert.doesNotMatch(editor, /保存标题/);
+});
+
+test("checkboxes are not stretched by the global text-input rule", () => {
+ assert.match(foundation, /input:not\(\[type="checkbox"\]\):not\(\[type="radio"\]\):not\(\[type="file"\]\), select, textarea/);
+ assert.match(css, /\.detail-project-option input\s*\{[^}]*width:\s*16px/);
+});
+
+test("AI tags show only leaf labels while preserving their full path for context", () => {
+ assert.match(attributes, /"AI 标签"/);
+ assert.match(attributes, /label: item\.name, path: item\.path/);
+ assert.match(source, /function detailTag\(\{ facet, label, path = label \}\)[\s\S]*setAttribute\("aria-label", fullPath\)/);
+ assert.doesNotMatch(attributes, /entry\.customLabels|customFacet|自定义标签/);
+ assert.match(editor, /"已有 AI 标签"/);
+ assert.match(editor, /"添加 AI 标签"/);
+});
diff --git a/test/entry-time.test.js b/test/entry-time.test.js
new file mode 100644
index 0000000..29b76a7
--- /dev/null
+++ b/test/entry-time.test.js
@@ -0,0 +1,26 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { buildEntry } from "../lib.js";
+
+test("a new case keeps source save time separate from when it joined this library", () => {
+ const entry = buildEntry({
+ text: "archived prompt",
+ title: "Imported historical case",
+ url: "https://example.com/source",
+ savedAt: "2024-03-01T08:00:00.000Z",
+ libraryAddedAt: "2026-08-08T08:00:00.000Z"
+ });
+
+ assert.equal(entry.savedAt, "2024-03-01T08:00:00.000Z");
+ assert.equal(entry.libraryAddedAt, "2026-08-08T08:00:00.000Z");
+});
+
+test("a directly created case receives both current-time fields without requiring new callers", () => {
+ const before = Date.now();
+ const entry = buildEntry({ text: "new prompt", title: "New case", url: "" });
+ const after = Date.now();
+
+ assert.ok(Date.parse(entry.savedAt) >= before && Date.parse(entry.savedAt) <= after);
+ assert.equal(entry.libraryAddedAt, entry.savedAt);
+});
diff --git a/test/extension-update-ui.test.js b/test/extension-update-ui.test.js
new file mode 100644
index 0000000..194bde5
--- /dev/null
+++ b/test/extension-update-ui.test.js
@@ -0,0 +1,65 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const root = new URL("../", import.meta.url);
+const [html, css, source] = await Promise.all([
+ readFile(new URL("library.html", root), "utf8"),
+ readFile(new URL("library.css", root), "utf8"),
+ readFile(new URL("library.js", root), "utf8")
+]);
+
+test("about settings expose status and state-specific update actions", () => {
+ const about = html.slice(html.indexOf('<footer class="settings-about">'), html.indexOf("</footer>", html.indexOf('<footer class="settings-about">')));
+ assert.match(about, /id="about-version"/);
+ assert.match(about, /id="update-channel"/);
+ assert.match(about, /id="update-checked-at"/);
+ assert.match(about, /id="update-available-version"/);
+ assert.match(about, /id="check-extension-update"/);
+ assert.match(about, /id="apply-extension-update"/);
+ assert.match(about, /id="update-release-link"/);
+ assert.match(source, /"应用更新并重启"/);
+ assert.match(source, /"重新载入目录"/);
+ assert.match(about, /class="button-primary update-download-action"[^>]*hidden>下载新版本/);
+ assert.match(css, /\.settings-update-actions/);
+});
+
+test("green actions are visible only for a real store or development update", () => {
+ const render = source.slice(source.indexOf("function renderExtensionUpdateStatus"), source.indexOf("function updateStatusDisplay"));
+ assert.match(render, /updateReleaseLink\.hidden = !releaseUrl/);
+ assert.match(render, /applyExtensionUpdate\.hidden = !status\.canApply/);
+ assert.match(render, /classList\.toggle\("button-secondary", development\)/);
+ assert.match(render, /development && status\.updateAvailable/);
+ assert.match(source, /settingsUpdateBadge\.hidden = !hasUpdate/);
+});
+
+test("update UI uses the background lifecycle protocol and refresh event", () => {
+ assert.match(source, /type: "GET_EXTENSION_UPDATE_STATUS"/);
+ assert.match(source, /type: "CHECK_EXTENSION_UPDATE"/);
+ assert.match(source, /type: "APPLY_EXTENSION_UPDATE"/);
+ assert.match(source, /message\?\.type !== "EXTENSION_UPDATE_STATUS_CHANGED"/);
+ assert.match(source, /renderExtensionUpdateStatus\(message\.status\)/);
+});
+
+test("development update wording never claims the extension installs or overwrites local code", () => {
+ const explanation = source.slice(source.indexOf("function updateExplanation"), source.indexOf("function updateCheckFeedback"));
+ assert.match(explanation, /扩展无法自行覆盖本机目录/);
+ assert.match(explanation, /安全重载只会重新载入当前目录,不会下载或安装新版本/);
+ assert.match(explanation, /固定 ID 升级无需导出、导入案例/);
+ assert.doesNotMatch(explanation, /一键安装|自动覆盖本地代码/);
+});
+
+test("applying a downloaded store update discloses that the page closes but library data remains", () => {
+ const applyFlow = source.slice(source.indexOf("async function applyExtensionUpdate"), source.indexOf("function renderExtensionUpdateStatus"));
+ assert.match(applyFlow, /当前资料库页面会关闭/);
+ assert.match(applyFlow, /本地案例和素材不会丢失|案例和素材不会丢失/);
+ assert.match(applyFlow, /confirmAppAction/);
+ assert.match(applyFlow, /applyBehavior === "reload_development_directory"/);
+});
+
+test("the settings entry uses a low-interruption update badge", () => {
+ assert.match(html, /id="settings-update-badge"[^>]*hidden/);
+ assert.match(css, /\.settings-update-badge/);
+ assert.match(source, /settingsUpdateBadge\.hidden = !hasUpdate/);
+ assert.match(source, /设置,有可用更新/);
+});
diff --git a/test/extension-update.test.js b/test/extension-update.test.js
new file mode 100644
index 0000000..2a6b279
--- /dev/null
+++ b/test/extension-update.test.js
@@ -0,0 +1,258 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+import {
+ compareExtensionVersions,
+ createExtensionUpdateLifecycle,
+ EXTENSION_UPDATE_STATUS_CHANGED,
+ EXTENSION_UPDATE_STORAGE_KEY,
+ extensionUpdateChannel,
+ githubLatestReleaseUrl,
+ parseExtensionVersion,
+ releaseVersionFromUrl
+} from "../extension-update.js";
+
+function memoryStorage(initial = {}) {
+ const values = structuredClone(initial);
+ return {
+ values,
+ async get(key) {
+ return { [key]: structuredClone(values[key]) };
+ },
+ async set(changes) {
+ Object.assign(values, structuredClone(changes));
+ }
+ };
+}
+
+function fakeRuntime(manifest, updateResult = { status: "no_update" }) {
+ return {
+ reloadCount: 0,
+ getManifest: () => structuredClone(manifest),
+ requestUpdateCheck: async () => structuredClone(updateResult),
+ reload() {
+ this.reloadCount += 1;
+ }
+ };
+}
+
+test("Chrome extension versions are parsed and compared with Chrome's strict rules", () => {
+ assert.deepEqual(parseExtensionVersion("1.18.9"), [1, 18, 9, 0]);
+ assert.deepEqual(parseExtensionVersion("0.1.0.0"), [0, 1, 0, 0]);
+ for (const invalid of ["", "0", "0.0.0.0", "01.2", "1.2.3.4.5", "1.65536", "v1.2", "1.2-beta"]) {
+ assert.equal(parseExtensionVersion(invalid), null, invalid);
+ }
+ assert.equal(compareExtensionVersions("1.2", "1.1.9.9999"), 1);
+ assert.equal(compareExtensionVersions("1.2", "1.2.0.0"), 0);
+ assert.equal(compareExtensionVersions("1.2.0.1", "1.2"), 1);
+ assert.throws(() => compareExtensionVersions("v1.2", "1.1"), /版本号格式无效/u);
+});
+
+test("package identity selects the update channel and GitHub release tags remain strict", () => {
+ assert.equal(extensionUpdateChannel({ version: "1.0" }), "store");
+ assert.equal(extensionUpdateChannel({ version: "1.0", key: "public-key" }), "development");
+ assert.equal(
+ githubLatestReleaseUrl("https://github.com/example/prompt-director/"),
+ "https://github.com/example/prompt-director/releases/latest"
+ );
+ assert.equal(githubLatestReleaseUrl("http://github.com/example/prompt-director"), "");
+ assert.equal(githubLatestReleaseUrl("https://example.com/example/prompt-director"), "");
+ assert.equal(
+ releaseVersionFromUrl("https://github.com/example/prompt-director/releases/tag/v1.18.10"),
+ "1.18.10"
+ );
+ assert.equal(releaseVersionFromUrl("https://github.com/example/prompt-director/releases/tag/v1.18.10-beta"), "");
+});
+
+test("development startup discovers a newer GitHub release without downloading code", async () => {
+ const runtime = fakeRuntime({
+ version: "1.18.9",
+ key: "fixed-development-id",
+ homepage_url: "https://github.com/example/prompt-director"
+ });
+ const storage = memoryStorage();
+ const notifications = [];
+ const fetchCalls = [];
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage,
+ now: () => 1_725_000_000_000,
+ fetchFn: async (url, options) => {
+ fetchCalls.push({ url, options });
+ return {
+ ok: true,
+ status: 200,
+ url: "https://github.com/example/prompt-director/releases/tag/v1.19.0"
+ };
+ },
+ notify: (status) => notifications.push(status)
+ });
+
+ const status = await lifecycle.handleStartup();
+ assert.equal(fetchCalls.length, 1);
+ assert.equal(fetchCalls[0].options.method, "HEAD");
+ assert.equal(status.channel, "development");
+ assert.equal(status.latestVersion, "1.19.0");
+ assert.equal(status.updateAvailable, true);
+ assert.equal(status.updateKind, "development_release");
+ assert.equal(status.canApply, true);
+ assert.equal(status.applyBehavior, "reload_development_directory");
+ assert.equal(status.checkStatus, "update_available");
+ assert.equal(notifications.length, 1);
+ assert.equal(storage.values[EXTENSION_UPDATE_STORAGE_KEY].latestVersion, "1.19.0");
+ assert.equal("canApply" in storage.values[EXTENSION_UPDATE_STORAGE_KEY], false);
+});
+
+test("development apply only reloads the current directory and never claims to install", async () => {
+ const runtime = fakeRuntime({
+ version: "1.18.9",
+ key: "fixed-development-id",
+ homepage_url: "https://github.com/example/prompt-director"
+ });
+ let scheduledReload;
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage: memoryStorage({
+ [EXTENSION_UPDATE_STORAGE_KEY]: {
+ stateVersion: 1,
+ channel: "development",
+ currentVersion: "1.18.9",
+ latestVersion: "1.19.0",
+ releaseUrl: "https://github.com/example/prompt-director/releases/tag/v1.19.0",
+ checkStatus: "update_available"
+ }
+ }),
+ scheduleReload: (reload) => { scheduledReload = reload; }
+ });
+
+ const result = await lifecycle.apply();
+ assert.equal(result.ok, true);
+ assert.equal(result.installsUpdate, false);
+ assert.equal(result.willReload, true);
+ assert.match(result.message, /不会下载或安装新版本/u);
+ assert.equal(runtime.reloadCount, 0);
+ scheduledReload();
+ assert.equal(runtime.reloadCount, 1);
+});
+
+test("development current version has no reload or primary update action", async () => {
+ const runtime = fakeRuntime({
+ version: "1.18.9",
+ key: "fixed-development-id",
+ homepage_url: "https://github.com/example/prompt-director"
+ });
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage: memoryStorage({
+ [EXTENSION_UPDATE_STORAGE_KEY]: {
+ stateVersion: 1,
+ channel: "development",
+ currentVersion: "1.18.9",
+ latestVersion: "1.18.9",
+ checkStatus: "no_update"
+ }
+ })
+ });
+ const status = await lifecycle.getStatus();
+ assert.equal(status.updateAvailable, false);
+ assert.equal(status.canApply, false);
+ assert.equal(status.applyBehavior, null);
+ const result = await lifecycle.apply();
+ assert.equal(result.ok, false);
+ assert.equal(runtime.reloadCount, 0);
+});
+
+test("store onUpdateAvailable persists the downloaded version until user applies it", async () => {
+ const runtime = fakeRuntime({ version: "1.18.9", homepage_url: "https://github.com/example/prompt-director" });
+ const storage = memoryStorage();
+ let scheduledReload;
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage,
+ now: () => 500,
+ scheduleReload: (reload) => { scheduledReload = reload; }
+ });
+
+ const available = await lifecycle.handleUpdateAvailable({ version: "1.19.0" });
+ assert.equal(available.channel, "store");
+ assert.equal(available.pendingVersion, "1.19.0");
+ assert.equal(available.updateKind, "store_downloaded");
+ assert.equal(available.canApply, true);
+ assert.equal(available.applyBehavior, "install_downloaded_update");
+ assert.equal(runtime.reloadCount, 0);
+
+ const result = await lifecycle.apply();
+ assert.equal(result.ok, true);
+ assert.equal(result.installsUpdate, true);
+ assert.equal(runtime.reloadCount, 0);
+ scheduledReload();
+ assert.equal(runtime.reloadCount, 1);
+});
+
+test("manual store checks preserve Chrome's no-update, available and throttled outcomes", async () => {
+ for (const expected of [
+ { result: { status: "no_update" }, checkStatus: "no_update", pendingVersion: "" },
+ { result: { status: "update_available", version: "1.19.0" }, checkStatus: "update_available", pendingVersion: "1.19.0" },
+ { result: { status: "throttled" }, checkStatus: "throttled", pendingVersion: "" }
+ ]) {
+ const runtime = fakeRuntime({ version: "1.18.9" }, expected.result);
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage: memoryStorage(),
+ now: () => 900
+ });
+ const status = await lifecycle.check();
+ assert.equal(status.checkStatus, expected.checkStatus);
+ assert.equal(status.pendingVersion, expected.pendingVersion);
+ }
+});
+
+test("store apply is blocked before Chrome downloads an update", async () => {
+ const runtime = fakeRuntime({ version: "1.18.9" });
+ const lifecycle = createExtensionUpdateLifecycle({ runtime, storage: memoryStorage() });
+ const result = await lifecycle.apply();
+ assert.equal(result.ok, false);
+ assert.equal(result.willReload, false);
+ assert.equal(runtime.reloadCount, 0);
+});
+
+test("successful store installation clears the applied reminder and records the current version", async () => {
+ const runtime = fakeRuntime({ version: "1.19.0" });
+ const storage = memoryStorage({
+ [EXTENSION_UPDATE_STORAGE_KEY]: {
+ stateVersion: 1,
+ channel: "store",
+ currentVersion: "1.18.9",
+ pendingVersion: "1.19.0",
+ checkStatus: "update_available"
+ }
+ });
+ const lifecycle = createExtensionUpdateLifecycle({
+ runtime,
+ storage,
+ now: () => 1_000
+ });
+ const status = await lifecycle.handleInstalled({ reason: "update", previousVersion: "1.18.9" });
+ assert.equal(status.currentVersion, "1.19.0");
+ assert.equal(status.pendingVersion, "");
+ assert.equal(status.updateAvailable, false);
+ assert.equal(status.canApply, false);
+ assert.equal(status.applyBehavior, null);
+ assert.equal(status.installedVersion, "1.19.0");
+ assert.equal(status.installedAt, 1_000);
+});
+
+test("background wires update events and the public message protocol", async () => {
+ const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+ assert.match(source, /chrome\.runtime\.onUpdateAvailable\.addListener/u);
+ assert.match(source, /chrome\.runtime\.onStartup\.addListener/u);
+ for (const type of [
+ "GET_EXTENSION_UPDATE_STATUS",
+ "CHECK_EXTENSION_UPDATE",
+ "APPLY_EXTENSION_UPDATE"
+ ]) {
+ assert.match(source, new RegExp(`case "${type}"`, "u"));
+ }
+ assert.match(source, new RegExp(EXTENSION_UPDATE_STATUS_CHANGED, "u"));
+});
diff --git a/test/image-transaction.test.js b/test/image-transaction.test.js
index b5637c0..cca198d 100644
--- a/test/image-transaction.test.js
+++ b/test/image-transaction.test.js
@@ -99,16 +99,17 @@ async function* replacements(values) {
for (const [id, blob] of values) yield { id, blob };
}
-test("case and creative-output deletion both use metadata-first image cleanup", async () => {
+test("case deletion retains blobs in trash while creative-output deletion still uses metadata-first cleanup", async () => {
const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
- for (const [startName, endName] of [
- ["async function deleteEntry(entryId)", "function enqueue(task)"],
- ["async function deleteCreativeOutput(message)", "async function analyzeCreativeOutput"]
- ]) {
- const block = source.slice(source.indexOf(startName), source.indexOf(endName, source.indexOf(startName)));
- assert.match(block, /commitMetadataThenDeleteImages/);
- assert.doesNotMatch(block, /await deleteScreenshotBlob/);
- }
+ const caseStart = source.indexOf("async function deleteEntry(entryId)");
+ const caseBlock = source.slice(caseStart, source.indexOf("async function deleteCollectionWithEntries", caseStart));
+ assert.match(caseBlock, /moveEntryBatchToTrash/);
+ assert.doesNotMatch(caseBlock, /deleteMediaBlob|deleteScreenshotBlob|commitMetadataThenDeleteImages/);
+
+ const outputStart = source.indexOf("async function deleteCreativeOutput(message)");
+ const outputBlock = source.slice(outputStart, source.indexOf("async function analyzeCreativeOutput", outputStart));
+ assert.match(outputBlock, /commitMetadataThenDeleteImages/);
+ assert.doesNotMatch(outputBlock, /await deleteScreenshotBlob/);
});
test("external Skill deletion commits metadata before cleaning package files", async () => {
diff --git a/test/import-jobs.test.js b/test/import-jobs.test.js
index 21e940d..1b5584e 100644
--- a/test/import-jobs.test.js
+++ b/test/import-jobs.test.js
@@ -37,6 +37,7 @@ test("retry creates a new job containing only failed items", () => {
const source = normalizeImportJobsState({ items: [{
id: "job:source",
status: "failed",
+ createdAt: "2026-08-08T00:30:00.000Z",
items: [
{ id: "item:done", stagedAssetId: "staged:done", status: "imported", entryId: "entry:done" },
{ id: "item:failed", stagedAssetId: "staged:failed", status: "failed", error: "文件损坏" }
@@ -53,11 +54,15 @@ test("retry creates a new job containing only failed items", () => {
});
assert.equal(result.job.retryOf, "job:source");
+ assert.equal(result.job.importBatchId, "job:source");
+ assert.equal(result.job.libraryAddedAt, "2026-08-08T00:30:00.000Z");
assert.equal(result.job.collectionId, "collection:one");
assert.deepEqual(result.job.options, { duplicateAction: "skip", autoAnalyze: true });
assert.deepEqual(result.job.items, [{
id: "item:retry:staged:failed",
stagedAssetId: "staged:failed",
+ importBatchId: "job:source",
+ libraryAddedAt: "2026-08-08T00:30:00.000Z",
status: "queued"
}]);
assert.equal(result.state.items.length, 2);
@@ -137,8 +142,64 @@ test("duplicate items default to skipped unless explicitly kept", () => {
});
assert.deepEqual(result.job.items, [
- { id: "item:staged:skip", stagedAssetId: "staged:skip", status: "skipped", skipReason: "duplicate" },
- { id: "item:staged:keep", stagedAssetId: "staged:keep", status: "queued" }
+ {
+ id: "item:staged:skip",
+ stagedAssetId: "staged:skip",
+ importBatchId: "job:duplicates",
+ libraryAddedAt: "2026-08-08T06:00:00.000Z",
+ status: "skipped",
+ skipReason: "duplicate"
+ },
+ {
+ id: "item:staged:keep",
+ stagedAssetId: "staged:keep",
+ importBatchId: "job:duplicates",
+ libraryAddedAt: "2026-08-08T06:00:00.000Z",
+ status: "queued"
+ }
]);
assert.equal(result.job.status, "queued");
});
+
+test("new import jobs expose one stable logical batch and library-added time", () => {
+ const result = createImportJob({}, {
+ stagedAssetIds: ["staged:one", "staged:two"],
+ options: { customLabels: ["客户 A", " 客户 A ", "待调整"] }
+ }, {
+ id: "job:first-attempt",
+ itemId: (assetId) => `item:${assetId}`,
+ now: "2026-08-08T07:00:00.000Z"
+ });
+
+ assert.equal(result.job.importBatchId, "job:first-attempt");
+ assert.equal(result.job.libraryAddedAt, "2026-08-08T07:00:00.000Z");
+ assert.deepEqual(result.job.options.customLabels, ["客户 A", "待调整"]);
+ assert.deepEqual(result.job.items.map((item) => ({
+ importBatchId: item.importBatchId,
+ libraryAddedAt: item.libraryAddedAt
+ })), [
+ { importBatchId: "job:first-attempt", libraryAddedAt: "2026-08-08T07:00:00.000Z" },
+ { importBatchId: "job:first-attempt", libraryAddedAt: "2026-08-08T07:00:00.000Z" }
+ ]);
+});
+
+test("legacy import jobs derive additive batch metadata without losing saved results", () => {
+ const state = normalizeImportJobsState({ items: [{
+ id: "job:legacy",
+ status: "completed",
+ createdAt: "2026-08-01T09:00:00.000Z",
+ items: [{
+ id: "item:legacy",
+ stagedAssetId: "staged:legacy",
+ status: "imported",
+ entryId: "entry:legacy"
+ }],
+ createdEntryIds: ["entry:legacy"]
+ }] });
+
+ assert.equal(state.items[0].importBatchId, "job:legacy");
+ assert.equal(state.items[0].libraryAddedAt, "2026-08-01T09:00:00.000Z");
+ assert.equal(state.items[0].items[0].importBatchId, "job:legacy");
+ assert.equal(state.items[0].items[0].libraryAddedAt, "2026-08-01T09:00:00.000Z");
+ assert.equal(state.items[0].items[0].entryId, "entry:legacy");
+});
diff --git a/test/import-staging.test.js b/test/import-staging.test.js
index 6da5eb5..979133e 100644
--- a/test/import-staging.test.js
+++ b/test/import-staging.test.js
@@ -6,8 +6,10 @@ import {
collectRetainedLocalAssetIds,
importStagingAssetIds,
normalizeImportStagingState,
- removeStagedAsset
+ removeStagedAsset,
+ stagedAssetMediaRecord
} from "../import-staging.js";
+import { normalizeMediaAsset } from "../media.js";
test("import staging persists only resumable metadata and safe relative paths", () => {
const result = addStagedAsset({}, {
@@ -16,9 +18,12 @@ test("import staging persists only resumable metadata and safe relative paths",
name: "frame.png",
relativePath: "folder/frame.png",
kind: "image",
+ storageMode: "managed",
mimeType: "image/png",
byteSize: 12,
contentHash: "a".repeat(64),
+ sourceFormat: "png",
+ formatCategory: "image",
posterAssetId: "poster:one",
duplicateAssetId: "existing:one",
absolutePath: "/Users/private/frame.png",
@@ -31,15 +36,108 @@ test("import staging persists only resumable metadata and safe relative paths",
name: "frame.png",
relativePath: "folder/frame.png",
kind: "image",
+ storageMode: "managed",
mimeType: "image/png",
byteSize: 12,
contentHash: "a".repeat(64),
+ sourceFormat: "png",
+ formatCategory: "image",
posterAssetId: "poster:one",
duplicateAssetId: "existing:one"
});
assert.equal(JSON.stringify(result.state).includes("/Users/private"), false);
});
+test("staging preserves audio and inert linked attachment boundaries", () => {
+ const state = normalizeImportStagingState({ assets: [
+ {
+ id: "staged:audio", assetId: "audio:one", name: "score.mp3", relativePath: "audio/score.mp3",
+ kind: "audio", mimeType: "audio/mpeg", byteSize: 8, contentHash: "e".repeat(64)
+ },
+ {
+ id: "staged:source", assetId: "attachment:one", name: "scene.aep", relativePath: "project/scene.aep",
+ kind: "attachment", storageMode: "reference", mimeType: "application/x-after-effects",
+ byteSize: 9, contentHash: "f".repeat(64)
+ }
+ ] });
+
+ assert.equal(state.assets[0].kind, "audio");
+ assert.equal(state.assets[0].formatCategory, "audio");
+ assert.equal(state.assets[1].kind, "attachment");
+ assert.equal(state.assets[1].storageMode, "reference");
+ assert.equal(state.assets[1].formatCategory, "motion-project");
+});
+
+test("staging preserves unsupported local links without pretending their source blob was copied", () => {
+ const state = normalizeImportStagingState({ assets: [{
+ id: "staged:unknown",
+ recordType: "local-asset-reference",
+ assetId: "attachment:unknown",
+ name: "custom.zzz",
+ relativePath: "unrecognized/custom.zzz",
+ kind: "attachment",
+ storageMode: "reference",
+ linkStatus: "relink-required",
+ mimeType: "application/x-custom",
+ byteSize: 20,
+ sourceLastModified: 1_776_500_123_000,
+ sourceFormat: "zzz",
+ importFailure: {
+ code: "unsupported_format",
+ message: "暂不支持这种文件格式:custom.zzz",
+ forceAllowed: false
+ },
+ handle: { kind: "file", getFile() {} },
+ absolutePath: "/Users/private/custom.zzz"
+ }] });
+
+ assert.equal(state.assets.length, 1);
+ assert.equal(state.assets[0].formatCategory, "local-link");
+ assert.equal(state.assets[0].recordType, "local-asset-reference");
+ assert.equal(state.assets[0].linkStatus, "relink-required");
+ assert.equal(state.assets[0].importFailure.code, "unsupported_format");
+ assert.equal(state.assets[0].sourceLastModified, 1_776_500_123_000);
+ assert.equal(Object.hasOwn(state.assets[0], "contentHash"), false);
+ assert.equal(Object.hasOwn(state.assets[0], "handle"), false);
+ assert.equal(JSON.stringify(state).includes("/Users/private"), false);
+});
+
+test("unsupported local link moves from staging to a case media record without a blob fingerprint", () => {
+ const staged = normalizeImportStagingState({ assets: [{
+ id: "staged:unknown",
+ recordType: "local-asset-reference",
+ assetId: "attachment:unknown",
+ name: "custom.zzz",
+ relativePath: "unrecognized/custom.zzz",
+ kind: "attachment",
+ storageMode: "reference",
+ linkStatus: "linked",
+ mimeType: "application/x-custom",
+ byteSize: 20,
+ sourceLastModified: 1_776_500_123_000,
+ sourceFormat: "zzz",
+ importFailure: {
+ code: "unsupported_format",
+ message: "暂不支持这种文件格式:custom.zzz",
+ forceAllowed: false
+ }
+ }] }).assets[0];
+ const asset = stagedAssetMediaRecord(staged, { capturedAt: "2026-08-22T11:00:00.000Z" });
+ const caseAsset = normalizeMediaAsset(asset);
+
+ assert.equal(asset.recordType, "local-asset-reference");
+ assert.equal(asset.storageMode, "reference");
+ assert.equal(asset.linkStatus, "linked");
+ assert.equal(asset.sourceLastModified, 1_776_500_123_000);
+ assert.equal(asset.importFailure.code, "unsupported_format");
+ assert.equal(Object.hasOwn(asset, "contentHash"), false);
+ assert.equal(caseAsset.recordType, "local-asset-reference");
+ assert.equal(caseAsset.linkStatus, "linked");
+ assert.equal(caseAsset.sourceLastModified, 1_776_500_123_000);
+ assert.equal(Object.hasOwn(caseAsset, "contentHash"), false);
+ assert.deepEqual(removeStagedAsset({ assets: [staged] }, staged.id).removedAssetIds, []);
+});
+
test("orphan cleanup retains assets referenced by sessions jobs cases and staging", () => {
const retained = collectRetainedLocalAssetIds({
entries: [{ mediaAssets: [{ id: "case:asset" }] }],
diff --git a/test/import-ui.test.js b/test/import-ui.test.js
index 58e2299..eae3953 100644
--- a/test/import-ui.test.js
+++ b/test/import-ui.test.js
@@ -5,6 +5,7 @@ import { readFile } from "node:fs/promises";
const html = await readFile(new URL("../library.html", import.meta.url), "utf8");
const css = await readFile(new URL("../library.css", import.meta.url), "utf8");
const js = await readFile(new URL("../library.js", import.meta.url), "utf8");
+const tagEditor = await readFile(new URL("../tag-editor.js", import.meta.url), "utf8");
function rule(source, selector) {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -18,11 +19,15 @@ test("add menu has one local import entry and the import dialog chooses files or
assert.doesNotMatch(actions, /id="add-folder"|id="open-import-job"|最近导入/);
assert.match(actions, /id="media-file"[^>]*type="file"[^>]*multiple/);
assert.match(actions, /id="media-folder"[^>]*type="file"[^>]*multiple[^>]*webkitdirectory/);
+ assert.doesNotMatch(actions, /id="media-file"[^>]*accept=/);
+ assert.match(js, /LOCAL_ASSET_FILE_ACCEPT/);
+ assert.match(js, /mediaFile\.accept\s*=\s*LOCAL_ASSET_FILE_ACCEPT/);
+ assert.match(js, /mediaFolder\.accept\s*=\s*LOCAL_ASSET_FILE_ACCEPT/);
const source = html.slice(html.indexOf('id="import-source"'), html.indexOf('id="import-preparing"'));
assert.match(source, /class="import-drop-zone"/);
assert.match(source, /拖入文件或文件夹/);
assert.match(source, /id="import-choose-files"/);
- assert.match(source, /自动识别图片、视频、PDF、Markdown、HTML、RTF 和纯文本/);
+ assert.match(source, /自动识别图片、视频、音频、字幕、文档和常用创作源文件/);
assert.match(source, /id="add-folder"/);
assert.match(source, /选择整个文件夹/);
assert.match(source, /class="import-folder-link"/);
@@ -30,6 +35,7 @@ test("add menu has one local import entry and the import dialog chooses files or
});
test("local import dialog includes drag target, confirmation summary, project assignment, auto-analyze, and job controls", () => {
+ const confirmation = html.slice(html.indexOf('id="import-confirmation"'), html.indexOf('id="import-job-panel"'));
assert.match(html, /id="library-drop-target"/);
assert.match(html, /松开以检查本机资料/);
assert.match(html, /id="import-dialog"/);
@@ -41,6 +47,12 @@ test("local import dialog includes drag target, confirmation summary, project as
assert.match(html, /id="import-duplicate-count"/);
assert.match(html, /id="import-byte-size"/);
assert.match(html, /id="import-project"/);
+ assert.match(html, /选择已有项目或输入新项目名/);
+ assert.doesNotMatch(html, /<datalist/);
+ assert.match(js, /attachProjectCombobox\(elements\.importProject/);
+ assert.match(html, /id="import-label-editor"/);
+ assert.match(html, /添加标签/);
+ assert.doesNotMatch(confirmation, /自由标签|可选|可以直接输入资料库里没有的新标签/);
assert.match(html, /id="import-auto-analyze"/);
assert.match(html, /导入后自动画面分析/);
assert.match(html, /id="import-file-list"/);
@@ -58,6 +70,7 @@ test("local import layout keeps summary, options, progress, and mobile stacking
const summary = rule(css, ".import-summary");
const options = rule(css, ".import-options");
const progress = rule(css, ".import-job-panel progress");
+ const labelEditor = rule(css, ".import-label-editor");
const dropZone = rule(css, ".import-drop-zone");
const folderLink = rule(css, ".import-drop-zone .import-folder-link");
const mobile = css.slice(css.indexOf("@media (max-width: 640px)"));
@@ -71,6 +84,8 @@ test("local import layout keeps summary, options, progress, and mobile stacking
assert.match(summary, /grid-template-columns:\s*repeat\(4,\s*minmax\(0,\s*1fr\)\)/);
assert.match(options, /grid-template-columns:\s*minmax\(0,\s*1fr\)\s+auto/);
assert.match(progress, /width:\s*100%/);
+ assert.match(labelEditor, /min-width:\s*0/);
+ assert.match(tagEditor, /tag-editor-chips/);
assert.match(mobile, /\.import-summary\s*\{[^}]*grid-template-columns:\s*1fr 1fr/);
assert.match(mobile, /\.import-options\s*\{[^}]*grid-template-columns:\s*1fr/);
@@ -93,12 +108,38 @@ test("duplicate choice and import start preserve the complete background job con
assert.match(js, /item\.keepDuplicate\s*=\s*keep\.checked/);
assert.match(js, /type:\s*"START_IMPORT_JOB"/);
assert.match(js, /collectionId,/);
+ assert.match(js, /customLabels:\s*\[\.\.\.\(pendingLocalImport\.customLabels\s*\?\?\s*\[\]\)\]/);
assert.match(js, /stagedAssets:\s*pendingLocalImport\.stagedAssets/);
+ assert.match(js, /storageMode:\s*prepared\.asset\.storageMode/);
+ assert.match(js, /sourceFormat:\s*prepared\.asset\.sourceFormat\s*\|\|\s*prepared\.sourceFormat/);
+ assert.match(js, /formatCategory:\s*prepared\.asset\.formatCategory/);
assert.match(js, /stagedAssetId:\s*item\.id/);
assert.match(js, /keepDuplicate:\s*item\.keepDuplicate\s*===\s*true/);
assert.match(js, /options:\s*\{\s*autoAnalyze:\s*elements\.importAutoAnalyze\.checked\s*===\s*true\s*\}/);
});
+test("project suggestions stay editable and import uses the shared multi-tag editor", () => {
+ assert.match(js, /importProject\.value\s*=\s*matching\?\.name\s*\|\|\s*rootName\s*\|\|\s*selected\?\.name\s*\|\|\s*""/);
+ assert.match(js, /已按根文件夹建议项目;可以修改或清空/);
+ assert.match(js, /const importTagEditor = createTagEditor/);
+ assert.match(js, /pendingLocalImport\.customLabels\s*=\s*values/);
+ assert.match(tagEditor, /\["Enter", ",", ","\]\.includes\(event\.key\)/);
+ assert.match(tagEditor, /删除标签/);
+ assert.match(js, /type:\s*"CREATE_COLLECTION",\s*name:\s*projectName/);
+});
+
+test("per-file failures always show their reason and only offer force import for a real capability", () => {
+ assert.match(js, /importFailureDetails\(error\)/);
+ assert.match(js, /const\s+\{\s*code,\s*message,\s*forceAllowed,\s*\.\.\.details\s*\}\s*=\s*failure/);
+ assert.match(js, /code\s*===\s*ASSET_IMPORT_FAILURE_CODES\.TOO_LARGE\s*&&\s*\(forceAllowed\s*\|\|\s*error\?\.canForceImport\s*===\s*true\)/);
+ assert.match(js, /item\.code\s*===\s*ASSET_IMPORT_FAILURE_CODES\.TOO_LARGE[\s\S]*?item\.forceAllowed\s*===\s*true[\s\S]*?item\.file\s*instanceof\s*Blob/);
+ assert.match(js, /"import-file-reason",\s*item\.reason/);
+ assert.match(js, /"强制导入"/);
+ assert.match(js, /forceImport:\s*true/);
+ const wrapper = js.slice(js.indexOf("async function prepareLocalMedia"), js.indexOf("async function readDocumentText"));
+ assert.match(wrapper, /forceImport:\s*options\.forceImport\s*===\s*true/);
+});
+
test("active import restoration and every terminal job action stay wired", () => {
assert.match(js, /await resumeImportJob\(\)/);
assert.match(js, /type:\s*"GET_IMPORT_JOB"/);
diff --git a/test/large_library_e2e.py b/test/large_library_e2e.py
index 446e912..6ff5224 100644
--- a/test/large_library_e2e.py
+++ b/test/large_library_e2e.py
@@ -164,6 +164,50 @@ def main() -> None:
assert tag_filter_ms < 250, f"6500-case tag category switch took {tag_filter_ms}ms"
style_category.click()
+ library.locator("#select-cases").click()
+ assert library.locator("#result-count").is_hidden()
+ assert library.locator("#gallery-view-controls").is_hidden()
+ assert library.locator("#share-count").inner_text() == "已选 0"
+ assert library.locator("#selection-select-filtered").inner_text() == "全选当前(6500)"
+ library.locator("#selection-select-filtered").click()
+ assert library.locator("#share-count").inner_text() == "已选 6500"
+ assert library.locator("#selection-clear").is_enabled()
+ library.set_viewport_size({"width": 390, "height": 844})
+ library.wait_for_function(
+ "() => document.documentElement.scrollWidth <= document.documentElement.clientWidth",
+ timeout=2_000,
+ )
+ selection_mobile = library.evaluate(
+ """() => {
+ const bar = document.querySelector('#share-bar').getBoundingClientRect();
+ const count = document.querySelector('#share-count').getBoundingClientRect();
+ return {
+ barLeft: bar.left,
+ barRight: bar.right,
+ countTop: count.top,
+ countBottom: count.bottom,
+ viewport: innerWidth,
+ overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
+ overflowWidth: document.documentElement.scrollWidth,
+ offenders: [...document.querySelectorAll('body *')].filter((element) => {
+ const rect = element.getBoundingClientRect();
+ return rect.right > innerWidth + 0.5 || rect.left < -0.5;
+ }).slice(0, 8).map((element) => ({
+ id: element.id,
+ className: String(element.className || ''),
+ left: element.getBoundingClientRect().left,
+ right: element.getBoundingClientRect().right
+ }))
+ };
+ }"""
+ )
+ assert selection_mobile["barLeft"] >= 0 and selection_mobile["barRight"] <= selection_mobile["viewport"], selection_mobile
+ assert selection_mobile["overflow"] is False, selection_mobile
+ library.set_viewport_size({"width": 1666, "height": 900})
+ library.locator("#selection-clear").click()
+ assert library.locator("#share-count").inner_text() == "已选 0"
+ library.locator("#share-cancel").click()
+
assert_columns_fill_width(library)
before_toggle = library.evaluate("document.querySelectorAll('.case-card').length")
library.locator("#toggle-filters").click()
diff --git a/test/lib.test.js b/test/lib.test.js
index 2b00b5c..3d85409 100644
--- a/test/lib.test.js
+++ b/test/lib.test.js
@@ -163,7 +163,7 @@ test("screenshot-only cases can have no prompt text and export as image referenc
}]);
assert.equal(entry.text, "");
assert.match(markdown, /- 内容类型:图片案例/);
- assert.match(markdown, /仅包含截图和创作属性/);
+ assert.match(markdown, /仅包含截图和 AI 标签/);
assert.doesNotMatch(markdown, /### 原始提示词/);
});
@@ -189,7 +189,7 @@ test("library JSON is machine-readable and references screenshots without base64
const parsed = JSON.parse(json);
assert.equal(parsed.format, "prompt-case-library");
- assert.equal(parsed.version, 3);
+ assert.equal(parsed.version, 4);
assert.equal(parsed.schemaVersion, SCHEMA_VERSION);
assert.equal(parsed.entries[0].visuals[0].screenshotPath, "images/case-1/visual-1.webp");
assert.equal(json.includes("base64,"), false);
diff --git a/test/library-detail-layout.test.js b/test/library-detail-layout.test.js
index 127b828..3ec022c 100644
--- a/test/library-detail-layout.test.js
+++ b/test/library-detail-layout.test.js
@@ -43,15 +43,15 @@ test("image details reserve an in-flow action row below the large image", async
assert.match(actions, /flex-wrap:\s*wrap/);
});
-test("detail titles clamp to two lines and project task actions wrap without overlap", async () => {
+test("detail titles stay fully readable and project task actions wrap without overlap", async () => {
const source = await readFile(cssUrl, "utf8");
const title = rule(source, ".detail-title");
const heading = rule(source, ".gallery-heading.project-selection-mode");
const actions = rule(source, ".project-selection-actions");
- assert.match(title, /display:\s*-webkit-box/);
- assert.match(title, /-webkit-line-clamp:\s*2/);
- assert.match(title, /overflow:\s*hidden/);
+ assert.match(title, /overflow-wrap:\s*anywhere/);
+ assert.doesNotMatch(title, /-webkit-line-clamp/);
+ assert.doesNotMatch(title, /text-overflow:\s*ellipsis/);
assert.match(heading, /flex-wrap:\s*wrap/);
assert.match(actions, /flex-wrap:\s*wrap/);
});
diff --git a/test/library-interaction-regressions.test.js b/test/library-interaction-regressions.test.js
index c8e3b5b..ccb912a 100644
--- a/test/library-interaction-regressions.test.js
+++ b/test/library-interaction-regressions.test.js
@@ -46,6 +46,14 @@ test("detail panels and selected projects use the themed surface and product acc
assert.match(css, /\.project-filter\[aria-pressed="true"\]\s*\{[^}]*color:\s*var\(--accent-ink\)[^}]*background:\s*var\(--accent-soft\)[^}]*var\(--accent\)/);
});
+test("library refresh waits for detail rebuilding before returning control", () => {
+ const refreshLibrary = library.slice(
+ library.indexOf("async function refreshLibrary"),
+ library.indexOf("async function loadImageDerivedMetadata")
+ );
+ assert.match(refreshLibrary, /if \(currentDetailId[\s\S]*await renderDetail\(\)/);
+});
+
test("composer keeps only primary controls exposed and moves secondary choices into one settings menu", () => {
assert.match(composerHtml, /class="composer-options-panel"/);
assert.match(composerHtml, /id="composer-applied-skills"[^>]*hidden/);
diff --git a/test/library-large-safety.test.js b/test/library-large-safety.test.js
index 557213a..620006b 100644
--- a/test/library-large-safety.test.js
+++ b/test/library-large-safety.test.js
@@ -26,5 +26,5 @@ test("visible thumbnails use a bounded queue and a rebuildable persistent cache"
test("narrow-screen add menu starts below the complete two-row header", () => {
assert.match(styles, /@media \(max-width: 900px\)[\s\S]*\.package-menu-panel,[\s\S]*top: 126px/);
- assert.match(styles, /@media \(max-width: 640px\)[\s\S]*\.add-menu \.package-menu-panel \{ top: 118px/);
+ assert.match(styles, /@media \(max-width: 640px\)[\s\S]*\.add-menu \.package-menu-panel \{[^}]*position:\s*fixed[^}]*top:\s*118px/);
});
diff --git a/test/library-navigation.test.js b/test/library-navigation.test.js
index 6d52f55..48fdece 100644
--- a/test/library-navigation.test.js
+++ b/test/library-navigation.test.js
@@ -26,11 +26,12 @@ test("top navigation keeps search-adjacent actions focused on adding, creating,
test("about information is inline at the bottom of general settings", async () => {
const about = html.slice(html.indexOf('<footer class="settings-about"'), html.indexOf("</footer>", html.indexOf('<footer class="settings-about"')));
const script = await readFile(new URL("../library.js", import.meta.url), "utf8");
- assert.equal((about.match(/<a\b/g) ?? []).length, 1);
+ assert.equal((about.match(/<a\b/g) ?? []).length, 2);
assert.match(about, /id="about-version">PromptDirector</);
assert.doesNotMatch(about, /PromptDirector\s+\d+\.\d+\.\d+/);
assert.match(script, /aboutVersion\.textContent\s*=\s*`PromptDirector \$\{chrome\.runtime\.getManifest\(\)\.version\}`/);
assert.match(about, /github\.com\/wchao6891\/PromptDirector/);
+ assert.match(about, /id="update-release-link"[^>]*github\.com\/wchao6891\/PromptDirector\/releases[^>]*hidden/);
assert.match(about, /Apache-2\.0/);
assert.doesNotMatch(about, /href="LICENSE"|href="NOTICE"|THIRD_PARTY_NOTICES/);
assert.doesNotMatch(html, /id="about-dialog"|id="open-about"/);
@@ -52,6 +53,16 @@ test("sidebar separates projects, content types, and on-demand attribute filters
assert.doesNotMatch(source.slice(source.indexOf("function renderFacetFilters"), source.indexOf("function createFacetFilterButton")), /name:\s*currentLocale\(\) === "en" \? "All"/);
});
+test("desktop sidebar width is adjustable and persists as a bounded UI preference", async () => {
+ const css = await readFile(new URL("../library.css", import.meta.url), "utf8");
+ assert.match(html, /id="sidebar-resizer"[^>]*role="separator"[^>]*tabindex="0"/);
+ assert.match(css, /grid-template-columns: var\(--sidebar-width, 244px\) 6px minmax\(0, 1fr\)/);
+ assert.match(css, /@media \(max-width: 900px\)[\s\S]*?\.sidebar-resizer \{ display: none; \}/);
+ assert.match(source, /event\.key === "ArrowRight" \? 16 : -16/);
+ assert.match(source, /updateUiPreferences\(\{ \.\.\.uiPreferences, sidebarWidth \}\)/);
+ assert.match(source, /Math\.floor\(innerWidth \* 0\.45\)/);
+});
+
test("share and combine are contextual actions after entering selection mode", () => {
const selection = html.slice(html.indexOf('id="gallery-heading"'), html.indexOf('<p id="feedback"'));
assert.match(selection, /id="selection-add-project"/);
diff --git a/test/library-package.test.js b/test/library-package.test.js
index fbea942..726a754 100644
--- a/test/library-package.test.js
+++ b/test/library-package.test.js
@@ -5,12 +5,14 @@ import {
mergeLibraryPackage,
parseCompleteFolderBackup,
parseLibraryPackage,
+ projectPackageEntryIds,
selectLibraryPackage,
selectProjectPackage
} from "../library-package.js";
import { createDefaultFacetCatalog, createFacet, createFacetNode } from "../facets.js";
import { CONTENT_IDS, CONTENT_ROLES, SCHEMA_VERSION, createContentType, createDefaultTaxonomy } from "../taxonomy.js";
import { COMPOSER_METHOD_VERSION, createComposerSession, normalizeComposerSettings } from "../composer.js";
+import { createZipBlob, readZipBlob } from "../zip.js";
function packageData(entries, facetCatalog) {
return {
@@ -145,6 +147,106 @@ test("v3 packages restore video documents and time notes with their media relati
])), /大小校验失败/);
});
+test("v4 mixed creative-asset ZIP restores image video audio subtitle PSD and font bytes", async () => {
+ const assets = [
+ { id: "image", kind: "image", mimeType: "image/png", sourceFormat: "png", path: "images/mixed/image.png", bytes: "image" },
+ { id: "video", kind: "video", mimeType: "video/mp4", sourceFormat: "mp4", path: "videos/mixed/video.mp4", bytes: "video" },
+ { id: "audio", kind: "audio", mimeType: "audio/mpeg", sourceFormat: "mp3", path: "audio/mixed/theme.mp3", bytes: "audio" },
+ { id: "subtitle", kind: "document", mimeType: "application/x-subrip", sourceFormat: "srt", path: "documents/mixed/subtitle.srt", bytes: "subtitle" },
+ { id: "psd", kind: "attachment", mimeType: "image/vnd.adobe.photoshop", sourceFormat: "psd", path: "attachments/mixed/artwork.psd", bytes: "psd-source" },
+ { id: "font", kind: "attachment", mimeType: "font/otf", sourceFormat: "otf", path: "attachments/mixed/typeface.otf", bytes: "font-source" }
+ ];
+ const data = packageData([], catalog());
+ data.version = 4;
+ data.entries = [{
+ ...entry("mixed"),
+ hasScreenshot: undefined,
+ screenshotPath: undefined,
+ mediaAssets: assets.map((asset) => ({
+ id: asset.id,
+ kind: asset.kind,
+ storageMode: "managed",
+ mimeType: asset.mimeType,
+ sourceFormat: asset.sourceFormat,
+ sourceTitle: asset.path.split("/").at(-1),
+ byteSize: new Blob([asset.bytes]).size,
+ assetPath: asset.path
+ })),
+ primaryMediaId: "image"
+ }];
+ const archive = await createZipBlob([
+ { name: "library.json", data: JSON.stringify(data) },
+ ...assets.map((asset) => ({ name: asset.path, data: new Blob([asset.bytes], { type: asset.mimeType }) }))
+ ]);
+ const files = await readZipBlob(archive, {
+ maxArchiveBytes: archive.size,
+ maxFileBytes: archive.size,
+ maxImageBytes: archive.size
+ });
+ const parsed = parseLibraryPackage(JSON.parse(await files.get("library.json").text()), files, {
+ maxArchiveBytes: archive.size,
+ maxFileBytes: archive.size,
+ maxImageBytes: archive.size
+ });
+
+ assert.deepEqual(parsed.entries[0].mediaAssets.map((asset) => asset.kind), [
+ "image", "video", "audio", "document", "attachment", "attachment"
+ ]);
+ for (const asset of assets) {
+ assert.equal(parsed.assets.get(asset.id)?.size, new Blob([asset.bytes]).size);
+ const restored = parsed.entries[0].mediaAssets.find((item) => item.id === asset.id);
+ assert.equal(restored.sourceFormat, asset.sourceFormat);
+ assert.equal(restored.mimeType, asset.mimeType);
+ }
+ const preview = mergeLibraryPackage({
+ entries: [], taxonomy: createDefaultTaxonomy(), facetCatalog: createDefaultFacetCatalog(),
+ classificationRules: [], settings: {}
+ }, data, { now: "2026-08-22T10:00:00.000Z", importBatchId: "mixed-zip" });
+ assert.deepEqual(preview.state.entries[0].mediaAssets.map((asset) => asset.sourceFormat), [
+ "png", "mp4", "mp3", "srt", "psd", "otf"
+ ]);
+});
+
+test("v4 package rejects asset paths whose registered extension kind or MIME disagrees", () => {
+ const data = packageData([], catalog());
+ data.version = 4;
+ data.entries = [{
+ ...entry("mismatch"), hasScreenshot: undefined, screenshotPath: undefined,
+ mediaAssets: [{
+ id: "fake-psd", kind: "attachment", storageMode: "managed", sourceTitle: "fake.psd",
+ sourceFormat: "psd", mimeType: "font/otf", byteSize: 4, assetPath: "attachments/mismatch/fake.psd"
+ }]
+ }];
+ assert.throws(() => parseLibraryPackage(data, new Map([[
+ "attachments/mismatch/fake.psd", new Blob(["fake"], { type: "application/octet-stream" })
+ ]])), /扩展名、媒体类型和 MIME 不一致/);
+});
+
+test("v4 package restores an unknown local source only as an inert managed attachment", () => {
+ const data = packageData([], catalog());
+ data.version = 4;
+ data.entries = [{
+ ...entry("generic-source"), hasScreenshot: undefined, screenshotPath: undefined,
+ mediaAssets: [{
+ id: "generic", kind: "attachment", storageMode: "managed", sourceTitle: "scene.customsource",
+ sourceFormat: "customsource", formatCategory: "other-source", mimeType: "application/octet-stream",
+ byteSize: 6, assetPath: "attachments/generic-source/scene.customsource"
+ }],
+ primaryMediaId: "generic"
+ }];
+ const parsed = parseLibraryPackage(data, new Map([[
+ "attachments/generic-source/scene.customsource", new Blob(["source"], { type: "application/octet-stream" })
+ ]]));
+ const restored = parsed.entries[0].mediaAssets[0];
+ assert.equal(restored.kind, "attachment");
+ assert.equal(restored.storageMode, "managed");
+ assert.equal(restored.formatCategory, "other-source");
+ assert.equal(restored.sourceFormat, "customsource");
+ for (const field of ["recordType", "linkStatus", "importFailure"]) {
+ assert.equal(Object.hasOwn(restored, field), false);
+ }
+});
+
test("complete folder backups restore genuine legacy RTF documents without trusting a .bin MIME type", async () => {
const rtf = String.raw`{\rtf1\ansi PromptDirector backup}`;
const path = "documents/rtf-case/rtf-asset.bin";
@@ -336,6 +438,24 @@ test("existing-library import merges new cases, reuses same-name vocabulary and
assert.equal(repeated.skippedCount, 1);
});
+test("package import keeps source time but assigns one receiver-local added time and batch", () => {
+ const source = entry("received");
+ source.libraryAddedAt = "2026-07-01T00:00:00.000Z";
+ source.importBatchId = "sender-batch";
+ const result = mergeLibraryPackage({
+ entries: [], taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(),
+ classificationRules: [], settings: {}
+ }, packageData([source], catalog()), {
+ now: "2026-08-22T08:30:00+08:00",
+ importBatchId: "receiver-batch"
+ });
+
+ const received = result.state.entries[0];
+ assert.equal(received.savedAt, "2026-07-18T10:00:00.000Z");
+ assert.equal(received.libraryAddedAt, "2026-08-22T00:30:00.000Z");
+ assert.equal(received.importBatchId, "receiver-batch");
+});
+
test("existing-library import carries user content types and keeps imported cases connected", () => {
const source = entry("document");
source.classification.pathIds = ["content:work-doc"];
@@ -366,6 +486,19 @@ test("selected share packages contain only chosen cases and the vocabulary they
assert.deepEqual(selected.organizerState.collections, []);
});
+test("selected share does not leak sender-local library time or import batch", () => {
+ const source = entry("one");
+ source.libraryAddedAt = "2026-08-21T00:00:00.000Z";
+ source.importBatchId = "local-import:one";
+ const selected = selectLibraryPackage({
+ entries: [source], taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(), classificationRules: []
+ }, ["one"]);
+
+ assert.equal(selected.entries[0].savedAt, source.savedAt);
+ assert.equal("libraryAddedAt" in selected.entries[0], false);
+ assert.equal("importBatchId" in selected.entries[0], false);
+});
+
test("sharing and importing a compound case preserves all members and remaps its relationship", () => {
const source = packageData([entry("one"), entry("two")], catalog());
source.version = 3;
@@ -401,6 +534,33 @@ test("project packages include every project member and only that project relati
assert.deepEqual(selected.organizerState.collections.map((item) => item.name), ["Campaign"]);
assert.deepEqual(selected.organizerState.collections[0].entryIds, ["one", "two"]);
assert.deepEqual(selected.composerSessions, []);
+
+ const received = mergeLibraryPackage({
+ entries: [entry("local")], taxonomy: createDefaultTaxonomy(), facetCatalog: catalog(),
+ classificationRules: [], settings: {}, organizerState: { collections: [] }
+ }, selected, {
+ preserveLibraryConfiguration: true,
+ now: "2026-08-22T09:00:00.000Z"
+ });
+ assert.equal(received.state.organizerState.collections[0].createdAt, "2026-08-22T09:00:00.000Z");
+});
+
+test("project packages keep a visible compound complete in the exported project", () => {
+ const source = packageData([entry("one"), entry("two"), entry("outside")], catalog());
+ source.compoundCases = [{
+ id: "compound:story", title: "完整流程", memberEntryIds: ["one", "two"], coverVisualId: "",
+ customLabels: [], createdAt: "2026-08-01T00:00:00.000Z", updatedAt: "2026-08-01T00:00:00.000Z"
+ }];
+ source.organizerState = {
+ version: 2,
+ collections: [{ id: "collection:project", name: "Campaign", order: 0, entryIds: ["one"] }]
+ };
+
+ assert.deepEqual(projectPackageEntryIds(source, "collection:project"), ["one", "two"]);
+ const selected = selectProjectPackage(source, "collection:project");
+ assert.deepEqual(selected.entries.map((item) => item.id), ["one", "two"]);
+ assert.deepEqual(selected.organizerState.collections[0].entryIds, ["one", "two"]);
+ assert.deepEqual(selected.compoundCases[0].memberEntryIds, ["one", "two"]);
});
test("share package keeps vision description but strips provider metadata", () => {
diff --git a/test/library-permission-settings.test.js b/test/library-permission-settings.test.js
new file mode 100644
index 0000000..3e03357
--- /dev/null
+++ b/test/library-permission-settings.test.js
@@ -0,0 +1,42 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const root = new URL("../", import.meta.url);
+const [html, css, js] = await Promise.all([
+ readFile(new URL("library.html", root), "utf8"),
+ readFile(new URL("library.css", root), "utf8"),
+ readFile(new URL("library.js", root), "utf8")
+]);
+
+test("general settings show separate web-capture and clipboard permission status", () => {
+ assert.match(html, /id="capture-web-permission-status"/);
+ assert.match(html, /id="capture-clipboard-permission-status"/);
+ assert.match(html, /id="revoke-capture-web-permission"/);
+ assert.match(html, /id="revoke-capture-clipboard-permission"/);
+ assert.match(html, /这里不会读取剪贴板/);
+ assert.match(css, /\.capture-permission-list\s*\{/);
+ assert.match(css, /\.capture-permission-row\s*\{/);
+});
+
+test("permission settings inspect grants without requesting or reading clipboard content", () => {
+ const renderFlow = js.slice(
+ js.indexOf("async function renderCapturePermissionStatus"),
+ js.indexOf("async function revokeCapturePermission")
+ );
+ assert.match(renderFlow, /inspectCapturePermissionBundle\(chrome\.permissions\)/);
+ assert.doesNotMatch(renderFlow, /permissions\.request|navigator\.clipboard|readClipboard/);
+});
+
+test("revocation removes the matching optional permission and resets first-use disclosure", () => {
+ const revokeFlow = js.slice(
+ js.indexOf("async function revokeCapturePermission"),
+ js.indexOf("async function chooseSyncFolder")
+ );
+ assert.match(revokeFlow, /origins:\s*\[\.\.\.CONTINUOUS_CAPTURE_ORIGINS\]/);
+ assert.match(revokeFlow, /permissions:\s*\[\.\.\.CLIPBOARD_READ_PERMISSIONS\]/);
+ assert.match(revokeFlow, /const\s+removed\s*=\s*await\s+chrome\.permissions\.remove\(request\)/);
+ assert.match(revokeFlow, /if\s*\(!removed\)\s*throw\s+new Error/);
+ assert.match(revokeFlow, /chrome\.storage\.local\.remove\(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY\)/);
+ assert.doesNotMatch(revokeFlow, /permissions\.request|navigator\.clipboard|readClipboard/);
+});
diff --git a/test/library-selection.test.js b/test/library-selection.test.js
new file mode 100644
index 0000000..f5ad701
--- /dev/null
+++ b/test/library-selection.test.js
@@ -0,0 +1,109 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ LIBRARY_BATCH_ACTIONS,
+ buildLibraryBatchPayload,
+ clearLibrarySelection,
+ expandLibrarySelection,
+ normalizeSelectedLogicalCaseIds,
+ selectAllFilteredLogicalCases,
+ toggleLibraryCaseSelection
+} from "../library-selection.js";
+
+test("select all uses every filtered logical result rather than the rendered page", () => {
+ const filteredLogicalCaseIds = Array.from({ length: 73 }, (_, index) => `case:${index + 1}`);
+ const renderedPageIds = filteredLogicalCaseIds.slice(0, 24);
+
+ const selected = selectAllFilteredLogicalCases(filteredLogicalCaseIds);
+
+ assert.equal(renderedPageIds.length, 24);
+ assert.equal(selected.length, 73);
+ assert.deepEqual(selected, filteredLogicalCaseIds);
+});
+
+test("selection can be normalized, toggled, and explicitly cleared without mutating input", () => {
+ const original = [" case:one ", "case:two", "case:one", ""];
+ const normalized = normalizeSelectedLogicalCaseIds(original);
+ const removed = toggleLibraryCaseSelection(normalized, "case:one");
+ const added = toggleLibraryCaseSelection(removed, "case:three");
+
+ assert.deepEqual(original, [" case:one ", "case:two", "case:one", ""]);
+ assert.deepEqual(normalized, ["case:one", "case:two"]);
+ assert.deepEqual(removed, ["case:two"]);
+ assert.deepEqual(added, ["case:two", "case:three"]);
+ assert.deepEqual(clearLibrarySelection(), []);
+});
+
+test("logical compound selections expand to stable unique member entry ids", () => {
+ const compounds = [{
+ id: "compound:campaign",
+ memberEntryIds: ["entry:visual", "entry:copy", "entry:visual"]
+ }];
+
+ assert.deepEqual(
+ expandLibrarySelection(["entry:standalone", "compound:campaign", "entry:copy"], compounds),
+ ["entry:standalone", "entry:visual", "entry:copy"]
+ );
+});
+
+test("free-tag batch payload expands compounds and normalizes optional labels", () => {
+ const compounds = [{ id: "compound:one", memberEntryIds: ["entry:a", "entry:b"] }];
+ const tagged = buildLibraryBatchPayload(["compound:one"], compounds, {
+ type: LIBRARY_BATCH_ACTIONS.addCustomLabels,
+ customLabels: [" 暖色氛围 ", "暖色 氛围", "客户A", "客户a", ""]
+ });
+ const withoutLabels = buildLibraryBatchPayload(["entry:c"], compounds, {
+ type: LIBRARY_BATCH_ACTIONS.addCustomLabels
+ });
+
+ assert.deepEqual(tagged, {
+ type: "BATCH_ADD_CUSTOM_LABELS",
+ entryIds: ["entry:a", "entry:b"],
+ customLabels: ["暖色氛围", "客户A"]
+ });
+ assert.deepEqual(withoutLabels.customLabels, []);
+});
+
+test("project batch payload requires explicit add or move semantics", () => {
+ const added = buildLibraryBatchPayload(["entry:a"], [], {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
+ collectionId: " collection:campaign ",
+ mode: "add"
+ });
+ const moved = buildLibraryBatchPayload(["entry:a"], [], {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
+ collectionId: "collection:archive",
+ mode: "move"
+ });
+
+ assert.deepEqual(added, {
+ type: "BATCH_SET_PROJECT",
+ entryIds: ["entry:a"],
+ collectionId: "collection:campaign",
+ mode: "add"
+ });
+ assert.equal(moved.mode, "move");
+ assert.throws(
+ () => buildLibraryBatchPayload(["entry:a"], [], {
+ type: LIBRARY_BATCH_ACTIONS.setProject,
+ collectionId: "collection:campaign"
+ }),
+ /明确选择添加或移动/
+ );
+});
+
+test("trash payload expands compound members and empty selection is rejected", () => {
+ const compounds = [{ id: "compound:one", memberEntryIds: ["entry:a", "entry:b"] }];
+
+ assert.deepEqual(buildLibraryBatchPayload(["compound:one"], compounds, {
+ type: LIBRARY_BATCH_ACTIONS.moveToTrash
+ }), {
+ type: "BATCH_MOVE_TO_TRASH",
+ entryIds: ["entry:a", "entry:b"]
+ });
+ assert.throws(
+ () => buildLibraryBatchPayload([], compounds, { type: LIBRARY_BATCH_ACTIONS.moveToTrash }),
+ /至少选择一个案例/
+ );
+});
diff --git a/test/library-sorting-ui.test.js b/test/library-sorting-ui.test.js
new file mode 100644
index 0000000..b66edd4
--- /dev/null
+++ b/test/library-sorting-ui.test.js
@@ -0,0 +1,72 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const [html, source, css] = await Promise.all([
+ readFile(new URL("../library.html", import.meta.url), "utf8"),
+ readFile(new URL("../library.js", import.meta.url), "utf8"),
+ readFile(new URL("../library.css", import.meta.url), "utf8")
+]);
+
+test("library exposes four case sorts and keeps project ordering as an on-demand action", () => {
+ const gallerySort = html.slice(html.indexOf('id="gallery-sort"'), html.indexOf("</select>", html.indexOf('id="gallery-sort"')));
+ assert.match(gallerySort, /value="added-desc">最近加入/);
+ assert.match(gallerySort, /value="updated-desc">最近更新/);
+ assert.match(gallerySort, /value="title">标题/);
+ assert.match(gallerySort, /value="project-manual"[^>]*hidden>手动排序/);
+ assert.doesNotMatch(gallerySort, /最早加入|项目手动顺序/);
+ assert.match(html, /id="manage-case-order"[^>]*aria-label="管理案例顺序"/);
+
+ assert.doesNotMatch(html, /id="project-sort"|最近创建|项目排序/);
+ assert.match(html, /id="manage-project-order"[^>]*aria-label="管理项目顺序"/);
+});
+
+test("sidebar keeps the recycle bin without smart or import-batch views", () => {
+ assert.match(html, /id="open-trash"/);
+ assert.doesNotMatch(html, /智能入口|未归项目|id="smart-unassigned"|id="import-batch-filters"/);
+ assert.doesNotMatch(source, /renderSmartFilters|filterCasesByImportBatch|filterUnassignedCases/);
+});
+
+test("case manual ordering is gated to an unfiltered project and project ordering uses direct drag", () => {
+ const availability = source.slice(source.indexOf("function projectManualOrderAvailable"), source.indexOf("function syncGallerySortControl"));
+ assert.match(availability, /selectedCollectionId/);
+ assert.match(availability, /!selectedContentId/);
+ assert.match(availability, /!selectedFacets\.size/);
+ assert.match(availability, /!elements\.pendingFilter\.checked/);
+ assert.match(availability, /!elements\.searchInput\.value\.trim\(\)/);
+ assert.match(source, /moveProjectLogicalCase/);
+ assert.match(source, /type: "REPLACE_COLLECTION_ENTRIES"/);
+ assert.match(source, /caseOrderManagementActive && projectManualOrderAvailable/);
+ assert.match(source, /projectOrderManagementActive/);
+ assert.match(source, /createUiIcon\(caseOrderManagementActive \? "circle-check-big" : "sliders-horizontal"\)/);
+ assert.match(source, /row\.addEventListener\("pointerdown"/);
+ assert.match(source, /row\.addEventListener\("pointermove"/);
+ assert.match(source, /\["ArrowUp", "ArrowDown"\]/);
+ assert.match(source, /type: "REORDER_COLLECTIONS", collectionIds/);
+ assert.match(source, /menu\.hidden = projectOrderManagementActive/);
+ assert.match(css, /\.project-row\.project-ordering/);
+ assert.match(css, /\.project-row\.project-ordering\s*\{[^}]*user-select:\s*none/);
+ assert.match(source, /elements\.manageProjectOrder\.disabled = projectOrderingUnavailable/);
+ assert.match(source, /"结束案例选择后可排序项目"/);
+ assert.doesNotMatch(source, /elements\.manageProjectOrder\.hidden = Boolean\(selectionMode\)/);
+ assert.doesNotMatch(source, /createUiIcon\("arrow-(?:up|down)"\)/);
+});
+
+test("gallery sorting and selection share a quiet secondary toolbar", () => {
+ assert.match(css, /\.gallery-sort-field select\s*\{[^}]*border-color:\s*transparent[^}]*background-color:\s*transparent/);
+ assert.match(css, /\.gallery-view-controls > \.icon-button\s*\{[^}]*border-color:\s*transparent[^}]*background:\s*transparent/);
+});
+
+test("saving project membership retains the existing manual order before appending new cases", () => {
+ const save = source.slice(source.indexOf("async function saveProjectSelection"), source.indexOf("async function shareProjectCollection"));
+ assert.match(save, /retainedOrder = \(collection\?\.entryIds \?\? \[\]\)\.filter/);
+ assert.match(save, /entryIds = \[\.\.\.retainedOrder, \.\.\.selectedEntryIds\.filter/);
+ assert.match(save, /type: "REPLACE_COLLECTION_ENTRIES"/);
+});
+
+test("library return snapshot saves persistent sorting but not transient management state", () => {
+ const snapshot = source.slice(source.indexOf("function saveLibraryReturnSnapshot"), source.indexOf("function restoreLibraryScrollPosition"));
+ assert.match(snapshot, /sortMode: caseSortMode/);
+ assert.match(snapshot, /snapshot\.sortMode/);
+ assert.doesNotMatch(snapshot, /projectSortMode|caseOrderManagementActive|projectOrderManagementActive|smartScope/);
+});
diff --git a/test/library-view.test.js b/test/library-view.test.js
new file mode 100644
index 0000000..95e4665
--- /dev/null
+++ b/test/library-view.test.js
@@ -0,0 +1,163 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ CASE_SORT_MODES,
+ PROJECT_SORT_MODES,
+ caseViewProjection,
+ moveProjectLogicalCase,
+ sortLibraryCases,
+ sortProjects
+} from "../library-view.js";
+
+test("recently added sorting uses the local join time and only views old savedAt as a fallback", () => {
+ const cases = [
+ entry("historical", { savedAt: "2025-01-01T00:00:00.000Z" }),
+ entry("new-import", {
+ savedAt: "2020-01-01T00:00:00.000Z",
+ libraryAddedAt: "2026-08-20T00:00:00.000Z"
+ }),
+ entry("older-import", {
+ savedAt: "2026-08-19T00:00:00.000Z",
+ libraryAddedAt: "2026-08-19T00:00:00.000Z"
+ })
+ ];
+ const before = structuredClone(cases);
+
+ assert.deepEqual(
+ sortLibraryCases(cases).map((item) => item.id),
+ ["new-import", "older-import", "historical"]
+ );
+ assert.deepEqual(
+ sortLibraryCases(cases, { mode: CASE_SORT_MODES.updatedDesc }).map((item) => item.id),
+ ["older-import", "historical", "new-import"]
+ );
+ assert.deepEqual(cases, before);
+ assert.equal("libraryAddedAt" in cases[0], false);
+});
+
+test("compound view time projects from the compound and its saved members", () => {
+ const compound = compoundEntry("compound:board", [
+ entry("member-old", {
+ savedAt: "2024-01-01T00:00:00.000Z",
+ importBatchId: "batch:old"
+ }),
+ entry("member-new", {
+ savedAt: "2020-01-01T00:00:00.000Z",
+ libraryAddedAt: "2026-08-18T00:00:00.000Z",
+ libraryUpdatedAt: "2026-08-22T00:00:00.000Z",
+ updatedAt: "2026-09-19T00:00:00.000Z",
+ importBatchId: "batch:new"
+ })
+ ], {
+ createdAt: "2026-08-20T00:00:00.000Z",
+ libraryUpdatedAt: "2026-08-21T00:00:00.000Z",
+ updatedAt: "2026-09-21T00:00:00.000Z"
+ });
+
+ assert.deepEqual(caseViewProjection(compound), {
+ memberEntryIds: ["member-old", "member-new"],
+ importBatchIds: ["batch:old", "batch:new"],
+ addedAt: "2026-08-20T00:00:00.000Z",
+ updatedAt: "2026-08-22T00:00:00.000Z"
+ });
+});
+
+test("case sorting supports recent updates, natural titles, stable ties, and project member order", () => {
+ const first = entry("first", {
+ title: "镜头 10",
+ libraryAddedAt: "2026-08-01T00:00:00.000Z",
+ libraryUpdatedAt: "2026-08-03T00:00:00.000Z",
+ updatedAt: "2026-09-03T00:00:00.000Z"
+ });
+ const second = entry("second", {
+ title: "镜头 2",
+ libraryAddedAt: "2026-08-01T00:00:00.000Z",
+ libraryUpdatedAt: "2026-08-04T00:00:00.000Z",
+ updatedAt: "2026-08-02T00:00:00.000Z"
+ });
+ const compound = compoundEntry("compound", [entry("member-a"), entry("member-b")]);
+
+ assert.deepEqual(
+ sortLibraryCases([second, first], { mode: CASE_SORT_MODES.updatedDesc }).map((item) => item.id),
+ ["second", "first"]
+ );
+ assert.deepEqual(
+ sortLibraryCases([first, second], { mode: CASE_SORT_MODES.title }).map((item) => item.id),
+ ["second", "first"]
+ );
+ assert.deepEqual(
+ sortLibraryCases([first, second]).map((item) => item.id),
+ ["first", "second"]
+ );
+ assert.deepEqual(
+ sortLibraryCases([first, compound, second], {
+ mode: CASE_SORT_MODES.projectManual,
+ projectEntryIds: ["second", "member-b", "member-a", "first"]
+ }).map((item) => item.id),
+ ["second", "compound", "first"]
+ );
+});
+
+test("project sorting supports manual, recent-created, and name modes without inventing dates", () => {
+ const projects = [
+ { id: "missing-date", name: "项目 10", order: 2 },
+ { id: "newer", name: "项目 2", order: 0, createdAt: "2026-08-20T00:00:00.000Z" },
+ { id: "older", name: "Alpha", order: 1, createdAt: "2026-08-10T00:00:00.000Z" }
+ ];
+
+ assert.deepEqual(sortProjects(projects).map((item) => item.id), ["newer", "older", "missing-date"]);
+ assert.deepEqual(
+ sortProjects(projects, PROJECT_SORT_MODES.recent).map((item) => item.id),
+ ["newer", "older", "missing-date"]
+ );
+ assert.deepEqual(
+ sortProjects(projects, PROJECT_SORT_MODES.name).map((item) => item.id),
+ ["older", "newer", "missing-date"]
+ );
+});
+
+test("moving one logical project case keeps compound members together and untouched raw ids stable", () => {
+ const current = compoundEntry("compound", [entry("member-a"), entry("member-b")]);
+ const adjacent = entry("adjacent");
+ const raw = ["adjacent", "hidden:one", "member-a", "hidden:two", "member-b", "tail"];
+
+ assert.deepEqual(
+ moveProjectLogicalCase(raw, current, adjacent, "up"),
+ ["member-a", "member-b", "adjacent", "hidden:one", "hidden:two", "tail"]
+ );
+ assert.deepEqual(
+ moveProjectLogicalCase(
+ ["member-a", "hidden:one", "member-b", "adjacent", "hidden:two"],
+ current,
+ adjacent,
+ "down"
+ ),
+ ["hidden:one", "adjacent", "member-a", "member-b", "hidden:two"]
+ );
+});
+
+function entry(id, overrides = {}) {
+ return {
+ id,
+ title: id,
+ savedAt: "2026-08-01T00:00:00.000Z",
+ ...overrides
+ };
+}
+
+function compoundEntry(id, members, compoundOverrides = {}) {
+ return {
+ id,
+ title: id,
+ memberEntries: members,
+ memberEntryIds: members.map((member) => member.id),
+ compoundCase: {
+ id,
+ memberEntryIds: members.map((member) => member.id),
+ createdAt: "2026-08-01T00:00:00.000Z",
+ updatedAt: "2026-08-01T00:00:00.000Z",
+ ...compoundOverrides
+ }
+ };
+}
diff --git a/test/library_detail_actions_e2e.py b/test/library_detail_actions_e2e.py
index 6eb277c..8c8739d 100644
--- a/test/library_detail_actions_e2e.py
+++ b/test/library_detail_actions_e2e.py
@@ -32,32 +32,88 @@ def main() -> None:
"reviewStatus": "verified",
}]
entry["primaryMediaId"] = "detail-actions-image"
+ no_source_entry = base_entry(
+ "detail-no-source",
+ "无来源详情验收案例",
+ "用于确认没有来源信息时仍能删除案例。",
+ "content:prompt:text",
+ 7,
+ )
+ no_source_entry["url"] = ""
+ no_source_entry["metadataLabels"] = []
+ projects = [{
+ "id": f"collection:detail-{index}",
+ "name": f"详情项目 {index:02d} " + ("完整项目名称需要换行显示" if index == 20 else ""),
+ "order": index,
+ "entryIds": [entry["id"]],
+ "visibility": "library",
+ } for index in range(21)]
screenshots = Path(tempfile.gettempdir())
with extension_session("prompt-director-detail-actions-", viewport={"width": 1440, "height": 900}) as session:
setup = session.open_page("collector.html")
setup.evaluate(
- """async ({entry, png}) => {
+ """async ({entry, noSourceEntry, projects, png}) => {
const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));
const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));
await chrome.storage.local.clear();
await chrome.storage.local.set({
schemaVersion: 25,
- entries: [entry],
+ entries: [entry, noSourceEntry],
+ organizerState: {version: 5, collections: projects},
uiPreferences: {locale: 'zh-CN', theme: 'dark', motion: 'reduced'}
});
await saveMediaBlob(entry.primaryMediaId, new Blob([bytes], {type: 'image/png'}), {checkCapacity: false});
}""",
- {"entry": entry, "png": PNG_BASE64},
+ {"entry": entry, "noSourceEntry": no_source_entry, "projects": projects, "png": PNG_BASE64},
)
library = session.open_page("library.html", wait_until="networkidle")
- library.locator(".case-card").click()
+ library.locator(f'.case-card[data-entry-id="{entry["id"]}"]').click()
expect(library.locator(".detail-header-section .entry-editor-inline > summary")).to_be_visible()
expect(library.locator(".prompt-section-heading", has_text="提示词")).to_be_visible()
expect(library.locator(".detail-core-actions > button")).to_have_count(2)
expect(library.get_by_role("button", name="复制提示词")).to_be_enabled()
expect(library.get_by_role("button", name="以此创作")).to_be_enabled()
+ expect(library.get_by_role("button", name="编辑共享提示词", exact=True)).to_have_count(0)
+ project_menu = library.locator(".detail-project-menu")
+ expect(project_menu.locator(":scope > summary")).to_have_text("已加入 21 个项目")
+ closed_height = project_menu.locator(":scope > summary").evaluate("node => node.getBoundingClientRect().height")
+ assert closed_height <= 40, closed_height
+ project_menu.locator(":scope > summary").click()
+ expect(project_menu.locator(".detail-project-option")).to_have_count(21)
+ checkbox_widths = project_menu.locator('.detail-project-option input[type="checkbox"]').evaluate_all(
+ "nodes => nodes.map(node => node.getBoundingClientRect().width)"
+ )
+ assert checkbox_widths and max(checkbox_widths) <= 18, checkbox_widths
+ long_project = project_menu.locator(".detail-project-option").nth(20)
+ expect(long_project).to_contain_text("完整项目名称需要换行显示")
+ long_project.locator("input").click()
+ expect(project_menu.locator(":scope > summary")).to_have_text("已加入 20 个项目")
+ project_menu.locator('input[aria-label="新项目名称"]').fill("详情新建项目")
+ project_menu.get_by_role("button", name="新建并加入", exact=True).click()
+ expect(library.locator(".detail-project-menu > summary")).to_have_text("已加入 21 个项目")
+ expect(library.locator(".detail-quick-organization")).not_to_contain_text("快捷整理")
+ detail_order = library.evaluate(
+ """() => {
+ const prompt = document.querySelector('.prompt-section');
+ const organizer = document.querySelector('.detail-quick-organization');
+ return Boolean(prompt && organizer && (prompt.compareDocumentPosition(organizer) & Node.DOCUMENT_POSITION_FOLLOWING));
+ }"""
+ )
+ assert detail_order is True
+ tag_input = library.locator(".detail-quick-organization .tag-editor input")
+ tag_input.fill("客户喜欢,待复刻")
+ library.locator(".detail-quick-organization .tag-editor").get_by_role("button", name="添加", exact=True).click()
+ expect(library.locator(".detail-quick-organization .tag-editor-chip")).to_have_count(2)
+ expect(library.locator(".detail-quick-organization .tag-editor-chip")).to_contain_text(["客户喜欢", "待复刻"])
+ expect(library.locator(".detail-quick-organization")).not_to_contain_text("可选")
+ expect(library.locator(".detail-quick-organization")).not_to_contain_text("不用预先创建")
+ expect(library.locator(".detail-quick-organization")).not_to_contain_text("任意输入")
+ expect(library.locator(".detail-quick-organization .detail-delete-action")).to_have_count(0)
+ expect(library.locator(".metadata-section .detail-delete-action")).to_contain_text("移入回收站")
+ expect(library.locator(".metadata-actions > *")).to_have_count(2)
+ expect(library.locator(".detail-content > .detail-footer-actions")).to_have_count(0)
core_geometry = library.locator(".detail-core-actions > button").evaluate_all(
"buttons => buttons.map(button => ({width: button.getBoundingClientRect().width, height: button.getBoundingClientRect().height}))"
@@ -75,6 +131,13 @@ def main() -> None:
assert edit_geometry["delta"] < 8, edit_geometry
library.locator(".entry-editor-inline > summary").click()
expect(library.locator(".entry-editor-inline .entry-editor-body")).to_be_visible()
+ expect(library.locator(".entry-editor-inline h4", has_text="案例标题")).to_have_count(1)
+ expect(library.locator(".entry-editor-inline .entry-edit-row")).to_be_visible()
+ expect(library.locator(".entry-editor-inline .entry-edit-row").get_by_role("button", name="保存", exact=True)).to_be_visible()
+ title_row = library.locator(".entry-editor-inline .entry-edit-row").evaluate(
+ """node => ({display: getComputedStyle(node).display, columns: node.children.length})"""
+ )
+ assert title_row == {"display": "grid", "columns": 2}, title_row
library.locator(".entry-editor-inline > summary").click()
library.get_by_role("button", name="编辑", exact=True).click()
@@ -91,9 +154,16 @@ def main() -> None:
expect(source).to_have_attribute("href", entry["url"])
expect(source).to_have_attribute("target", "_blank")
expect(source).to_have_attribute("rel", "noopener noreferrer")
+ expect(library.locator(".metadata-actions .detail-delete-action")).to_be_visible()
library.screenshot(path=str(screenshots / "promptdirector-step3-detail-desktop.png"), full_page=True)
library.set_viewport_size({"width": 390, "height": 844})
+ mobile_project_menu = library.locator(".detail-project-menu")
+ mobile_project_popover = library.locator(".detail-project-popover")
+ if mobile_project_menu.get_attribute("open") is None:
+ mobile_project_menu.locator(":scope > summary").click()
+ expect(mobile_project_menu).to_have_attribute("open", "")
+ expect(mobile_project_popover).to_be_visible()
library.locator(".prompt-section").scroll_into_view_if_needed()
mobile = library.evaluate(
"""() => {
@@ -113,6 +183,12 @@ def main() -> None:
expect(library.get_by_role("button", name="以此创作")).to_be_visible()
library.screenshot(path=str(screenshots / "promptdirector-step3-detail-mobile.png"), full_page=True)
+ library.locator("#detail-close").click()
+ library.locator(f'.case-card[data-entry-id="{no_source_entry["id"]}"]').click()
+ expect(library.locator(".metadata-section")).to_have_count(0)
+ expect(library.locator(".detail-body > .detail-footer-actions .detail-delete-action")).to_contain_text("移入回收站")
+ expect(library.locator(".detail-body > .detail-footer-actions")).to_be_visible()
+
print({
"core_actions": core_geometry,
"title_edit_alignment": edit_geometry,
diff --git a/test/library_import_ui_e2e.py b/test/library_import_ui_e2e.py
index 50572d6..7f5624f 100644
--- a/test/library_import_ui_e2e.py
+++ b/test/library_import_ui_e2e.py
@@ -118,6 +118,8 @@ def main() -> None:
library.wait_for_selector("body[data-library-state='ready']", timeout=10_000)
library.evaluate(
"""() => {
+ Object.defineProperty(window, 'showOpenFilePicker', {value: undefined, configurable: true});
+ Object.defineProperty(window, 'showDirectoryPicker', {value: undefined, configurable: true});
const send = chrome.runtime.sendMessage.bind(chrome.runtime);
chrome.runtime.sendMessage = (message, ...rest) => {
if (message?.type !== 'START_IMPORT_JOB') return send(message, ...rest);
@@ -152,7 +154,23 @@ def main() -> None:
expect(new_row.locator("input")).to_be_checked()
expect(new_row.locator("input")).to_be_disabled()
expect(library.locator("#import-auto-analyze")).to_be_checked()
- library.locator("#import-project").select_option("collection:fixture")
+ expect(library.locator("#import-project")).to_have_attribute("role", "combobox")
+ library.locator("#import-project").click()
+ expect(library.locator(".project-combobox-option")).to_have_count(1)
+ import_project_menu = library.locator(".project-combobox-listbox").evaluate(
+ """node => {
+ const menu = node.getBoundingClientRect();
+ const boundary = node.closest('.import-dialog-body').getBoundingClientRect();
+ return {background: getComputedStyle(node).backgroundColor, visible: !node.hidden, top: menu.top, bottom: menu.bottom, boundaryTop: boundary.top, boundaryBottom: boundary.bottom};
+ }"""
+ )
+ assert import_project_menu["visible"] is True
+ assert import_project_menu["background"] not in {"rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"}, import_project_menu
+ assert import_project_menu["top"] >= import_project_menu["boundaryTop"] - 1, import_project_menu
+ assert import_project_menu["bottom"] <= import_project_menu["boundaryBottom"] + 1, import_project_menu
+ library.locator("#import-project").press("Escape")
+ expect(library.locator("#import-project")).to_have_attribute("aria-expanded", "false")
+ library.locator("#import-project").fill("Import Review")
duplicate_row.locator("input").check()
expect(duplicate_row).to_contain_text("仍导入")
@@ -237,7 +255,7 @@ def main() -> None:
expect(library.locator("#import-file-list")).to_contain_text("Reference Folder/brief.txt")
expect(library.locator("#import-file-list")).to_contain_text("Reference Folder/nested/brief.txt")
expect(library.locator("#import-file-list")).to_contain_text("Reference Folder/nested/shot.md")
- expect(library.locator("#import-project")).to_have_value("create:Reference Folder")
+ expect(library.locator("#import-project")).to_have_value("Reference Folder")
library.locator("#import-cancel").click()
expect(library.locator("#import-dialog")).not_to_be_visible()
@@ -323,6 +341,7 @@ def main() -> None:
"duplicateDefaultSkip": True,
"duplicateKeep": True,
"mobileNoOverflow": True,
+ "projectCombobox": import_project_menu,
"startPayloadFields": sorted(payload.keys()),
"refreshRestoredActiveJob": True,
"actions": ["cancel", "retry", "undo", "view-project"],
diff --git a/test/library_media_actions_e2e.py b/test/library_media_actions_e2e.py
index 177cf6d..29907b2 100644
--- a/test/library_media_actions_e2e.py
+++ b/test/library_media_actions_e2e.py
@@ -1,5 +1,8 @@
from __future__ import annotations
+import tempfile
+from pathlib import Path
+
from playwright.sync_api import expect
from e2e_support import base_entry, extension_session
@@ -70,6 +73,8 @@ def main() -> None:
expect(library.locator(".case-card")).to_have_count(1)
library.locator(".case-card").click()
expect(library.locator(".detail-visual-thumb")).to_have_count(15)
+ expect(library.get_by_role("button", name="编辑当前图片", exact=True)).to_be_visible()
+ expect(library.get_by_role("button", name="编辑共享提示词", exact=True)).to_be_visible()
stable_before = library.evaluate(
"""() => {
const gallery = document.querySelector('.detail-visual-gallery');
@@ -115,12 +120,12 @@ def main() -> None:
library.locator(".detail-visual-thumb").nth(14).click()
assert_action_is_reachable(library, "设为主要媒体")
- assert_action_is_reachable(library, "删除此媒体")
+ assert_action_is_reachable(library, "此媒体移入回收站")
library.set_viewport_size({"width": 390, "height": 844})
expect(library.locator(".detail-visual-caption")).to_be_visible()
assert_action_is_reachable(library, "设为主要媒体")
- assert_action_is_reachable(library, "删除此媒体")
+ assert_action_is_reachable(library, "此媒体移入回收站")
library.get_by_role("button", name="设为主要媒体").click()
expect(library.locator(".detail-visual-caption")).to_contain_text("主要媒体")
@@ -128,10 +133,10 @@ def main() -> None:
assert state["entries"][0]["primaryMediaId"] == "multi-image-15"
expect(library.locator(".case-card img[data-visual-id]")).to_have_attribute("data-visual-id", "multi-image-15")
- library.get_by_role("button", name="删除此媒体").click()
+ library.get_by_role("button", name="此媒体移入回收站").click()
delete_dialog = library.locator("#promptdirector-app-dialog")
expect(delete_dialog).to_be_visible()
- delete_dialog.get_by_role("button", name="删除媒体", exact=True).click()
+ delete_dialog.get_by_role("button", name="媒体移入回收站", exact=True).click()
expect(library.locator(".detail-visual-thumb")).to_have_count(14)
expect(library.locator("#detail-content")).to_contain_text("切换主图后保留的案例文字。")
state = library.evaluate("async () => chrome.runtime.sendMessage({type: 'GET_STATE'})")
@@ -139,11 +144,43 @@ def main() -> None:
assert state["entries"][0]["primaryMediaId"] == "multi-image-1"
expect(library.locator(".case-card img[data-visual-id]")).to_have_attribute("data-visual-id", "multi-image-1")
+ library.locator(".detail-visual-thumb").nth(13).click()
+ library.get_by_role("button", name="此媒体移入回收站").click()
+ expect(delete_dialog).to_be_visible()
+ delete_dialog.get_by_role("button", name="媒体移入回收站", exact=True).click()
+ expect(library.locator(".detail-visual-thumb")).to_have_count(13)
+
+ library.locator("#detail-close").click()
+ library.locator("#toggle-filters").click()
+ expect(library.locator(".workspace")).to_have_class("workspace")
+ library.locator("#open-trash").click()
+ expect(library.locator("#trash-dialog")).to_be_visible()
+ expect(library.locator(".trash-item")).to_have_count(2)
+ expect(library.locator(".trash-item-cover img")).to_have_count(2)
+ expect(library.locator(".trash-item-copy strong")).to_have_text(["多图案例", "多图案例"])
+ restore = library.locator(".trash-item button[aria-label^='恢复:']").first
+ remove = library.locator(".trash-item button[aria-label^='永久删除:']").first
+ expect(restore).to_have_attribute("title", "恢复")
+ expect(remove).to_have_attribute("title", "永久删除")
+ assert restore.evaluate("node => node.getBoundingClientRect().height") >= 44
+ trash_screenshot = Path(tempfile.gettempdir()) / "promptdirector-trash-mobile.png"
+ library.screenshot(path=str(trash_screenshot), full_page=True)
+ restore.focus()
+ restore.press("Enter")
+ expect(library.locator(".trash-item")).to_have_count(1)
+ expect(library.get_by_role("button", name="全部恢复", exact=True)).to_be_enabled()
+ library.get_by_role("button", name="全部恢复", exact=True).click()
+ expect(library.locator(".trash-empty-title")).to_have_text("回收站为空")
+ expect(library.get_by_role("button", name="全部恢复", exact=True)).to_be_disabled()
+ expect(library.locator("#trash-dialog")).not_to_contain_text("RECYCLE BIN")
+
print({
"desktop_actions_reachable": True,
"mobile_actions_reachable": True,
"primary_media_updated": True,
"delete_preserved_case": True,
+ "trash_cover_and_keyboard_restore": True,
+ "trash_screenshot": str(trash_screenshot),
"rapid_selection_last_wins": "12/15",
"visual_anchor_shift_px": 1,
})
diff --git a/test/library_navigation_e2e.py b/test/library_navigation_e2e.py
index a96254f..f7ee3ef 100644
--- a/test/library_navigation_e2e.py
+++ b/test/library_navigation_e2e.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import tempfile
from pathlib import Path
+import re
from playwright.sync_api import expect
@@ -67,6 +68,23 @@ def main() -> None:
expect(library.locator("#collection-filters .project-filter")).to_have_count(1)
expect(library.locator("#collection-filters .project-filter-name")).to_have_text("导航验收项目")
expect(library.locator("#collection-filters .project-filter-count")).to_have_text("1")
+ expect(library.locator("#project-sort")).to_have_count(0)
+ expect(library.locator(".project-row.project-ordering")).to_have_count(0)
+ library.locator("#manage-project-order").click()
+ expect(library.locator(".project-row.project-ordering")).to_have_count(1)
+ expect(library.locator(".project-row > .project-menu")).to_be_hidden()
+ expect(library.locator("#manage-project-order use")).to_have_attribute("href", re.compile(r"assets/ui-icons\.svg#icon-circle-check-big$"))
+ library.locator("#manage-project-order").click()
+ expect(library.locator(".project-row.project-ordering")).to_have_count(0)
+ expect(library.locator(".project-row > .project-menu")).to_be_visible()
+
+ resizer = library.locator("#sidebar-resizer")
+ expect(resizer).to_be_visible()
+ resizer.focus()
+ resizer.press("ArrowRight")
+ expect(resizer).to_have_attribute("aria-valuenow", "260")
+ saved_width = library.evaluate("async () => (await chrome.storage.local.get('uiPreferences')).uiPreferences.sidebarWidth")
+ assert saved_width == 260, saved_width
expect(library.locator("#content-filters .content-filter-option")).to_have_count(6)
expect(library.locator("#content-filters")).not_to_contain_text("全部")
expect(library.locator("#facet-filters .facet-filter-body .filter-option", has_text="全部")).to_have_count(0)
@@ -90,10 +108,27 @@ def main() -> None:
})"""
)
assert wall == {"gap": "2px", "cardRadius": "2px"}, wall
+ library.locator("#select-cases").click()
+ expect(library.locator("#result-count")).to_be_hidden()
+ expect(library.locator("#gallery-view-controls")).to_be_hidden()
+ expect(library.locator("#manage-project-order")).to_be_visible()
+ expect(library.locator("#manage-project-order")).to_be_disabled()
+ expect(library.locator("#share-count")).to_have_text("已选 0")
+ library.locator("#selection-select-filtered").click()
+ expect(library.locator("#selection-clear")).to_be_enabled()
+ expect(library.locator("#share-count")).to_have_text("已选 2")
+ expect(library.locator("#selection-select-filtered")).to_have_text("全选当前(2)")
+ library.locator("#selection-clear").click()
+ expect(library.locator("#selection-clear")).to_be_disabled()
+ expect(library.locator("#share-count")).to_have_text("已选 0")
+ expect(library.locator(".case-card.selected-for-share")).to_have_count(0)
+ library.locator("#share-cancel").click()
+ expect(library.locator("#manage-project-order")).to_be_enabled()
library.locator("#filter-sidebar").evaluate("node => { node.scrollTop = 0; }")
library.screenshot(path=str(screenshots / "promptdirector-step2-library-desktop.png"), full_page=True)
library.set_viewport_size({"width": 390, "height": 844})
+ expect(library.locator("#sidebar-resizer")).to_be_hidden()
expect(library.locator(".workspace")).to_have_class("workspace filters-collapsed")
library.wait_for_function(
"""() => new Promise((resolve) => requestAnimationFrame(
@@ -120,7 +155,13 @@ def main() -> None:
library.locator('[data-content-filter-id="content:prompt:image"]').click()
expect(library.locator("#case-list > .case-card")).to_have_count(1)
overflow = library.evaluate("document.documentElement.scrollWidth > document.documentElement.clientWidth")
- assert overflow is False
+ overflow_nodes = library.evaluate(
+ """() => [...document.querySelectorAll('body *')].flatMap(node => {
+ const rect = node.getBoundingClientRect();
+ return rect.right > innerWidth + 1 ? [{tag: node.tagName, id: node.id, className: String(node.className), right: rect.right}] : [];
+ }).slice(0, 12)"""
+ )
+ assert overflow is False, overflow_nodes
library.screenshot(path=str(screenshots / "promptdirector-step2-library-mobile.png"), full_page=True)
print({
diff --git a/test/local-asset-reference-background.test.js b/test/local-asset-reference-background.test.js
new file mode 100644
index 0000000..7366905
--- /dev/null
+++ b/test/local-asset-reference-background.test.js
@@ -0,0 +1,27 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const source = await readFile(new URL("../background.js", import.meta.url), "utf8");
+
+test("background imports inert local references without reading a managed media blob", () => {
+ const start = source.indexOf("async function startImportJobAction");
+ const end = source.indexOf("async function getImportJobAction", start);
+ const action = source.slice(start, end);
+ assert.match(action, /isLocalReference[\s\S]*addStagedAsset\(staging, value\)[\s\S]*continue;[\s\S]*getMediaBlob\(assetId\)/u);
+
+ const itemStart = source.indexOf("async function importStagedItem");
+ const itemEnd = source.indexOf("function importedEntryFromStagedAsset", itemStart);
+ const item = source.slice(itemStart, itemEnd);
+ assert.match(item, /staged\.storageMode !== "reference" && !await getMediaBlob/u);
+});
+
+test("relink metadata action touches the case and never accepts a file handle", () => {
+ assert.match(source, /case "UPDATE_LOCAL_ASSET_REFERENCE"/u);
+ const start = source.indexOf("async function updateLocalAssetReferenceAction");
+ const end = source.indexOf("async function addUploadedMedia", start);
+ const action = source.slice(start, end);
+ assert.match(action, /updateLocalAssetReferenceMetadata/u);
+ assert.match(action, /const entry = touchEntry\(updated\.entry\)/u);
+ assert.doesNotMatch(action, /handle|saveLocalAssetHandle|saveMediaBlob/u);
+});
diff --git a/test/local-asset-store.test.js b/test/local-asset-store.test.js
new file mode 100644
index 0000000..2cf9a94
--- /dev/null
+++ b/test/local-asset-store.test.js
@@ -0,0 +1,167 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+import {
+ LOCAL_ASSET_LINK_STATUS,
+ deleteLocalAssetHandle,
+ getLocalAssetHandle,
+ inspectLocalAssetHandle,
+ localAssetMetadataChanges,
+ queryLocalAssetHandlePermission,
+ readLocalAssetFile,
+ saveLocalAssetHandle
+} from "../local-asset-store.js";
+
+const source = await readFile(new URL("../local-asset-store.js", import.meta.url), "utf8");
+
+function fileMetadata(overrides = {}) {
+ return { name: "scene.psd", size: 128, lastModified: 42, ...overrides };
+}
+
+function fileHandle({ permission = "granted", file = fileMetadata(), getFileError } = {}) {
+ const calls = { query: 0, getFile: 0, request: 0 };
+ return {
+ kind: "file",
+ calls,
+ async queryPermission() {
+ calls.query += 1;
+ return permission;
+ },
+ async requestPermission() {
+ calls.request += 1;
+ return "granted";
+ },
+ async getFile() {
+ calls.getFile += 1;
+ if (getFileError) throw getFileError;
+ return file;
+ }
+ };
+}
+
+function fakeDatabase() {
+ const values = new Map();
+ return {
+ values,
+ transaction() {
+ const transaction = {
+ objectStore() {
+ return {
+ put(value, key) {
+ values.set(key, value);
+ return settledRequest(value, transaction);
+ },
+ get(key) {
+ return settledRequest(values.get(key), transaction);
+ },
+ delete(key) {
+ values.delete(key);
+ return settledRequest(undefined, transaction);
+ }
+ };
+ }
+ };
+ return transaction;
+ }
+ };
+}
+
+function settledRequest(result, transaction) {
+ const request = {};
+ queueMicrotask(() => {
+ request.result = result;
+ request.onsuccess?.();
+ transaction.oncomplete?.();
+ });
+ return request;
+}
+
+test("local source handles use an independent version-one database", () => {
+ assert.match(source, /prompt-director-local-assets/);
+ assert.match(source, /DATABASE_VERSION = 1/);
+ assert.doesNotMatch(source, /requestPermission\s*\(/);
+});
+
+test("handle records persist by asset id through an injected database", async () => {
+ const database = fakeDatabase();
+ const handle = fileHandle();
+ const saved = await saveLocalAssetHandle("asset:1", handle, fileMetadata(), {
+ database,
+ now: "2026-08-22T00:00:00.000Z"
+ });
+ assert.equal(saved.assetId, "asset:1");
+ assert.equal(await getLocalAssetHandle("asset:1", { database }), handle);
+ await deleteLocalAssetHandle("asset:1", { database });
+ assert.equal(await getLocalAssetHandle("asset:1", { database }), null);
+});
+
+test("permission checks never read the file or request permission", async () => {
+ const handle = fileHandle({ permission: "prompt" });
+ assert.equal(await queryLocalAssetHandlePermission(handle), "prompt");
+ assert.deepEqual(handle.calls, { query: 1, getFile: 0, request: 0 });
+});
+
+test("inspection distinguishes missing permission ready and changed", async () => {
+ assert.deepEqual(await inspectLocalAssetHandle(null), {
+ status: LOCAL_ASSET_LINK_STATUS.MISSING,
+ permission: "unknown"
+ });
+
+ const promptHandle = fileHandle({ permission: "prompt" });
+ const needsPermission = await inspectLocalAssetHandle({
+ assetId: "asset:1",
+ handle: promptHandle,
+ metadata: fileMetadata()
+ });
+ assert.equal(needsPermission.status, LOCAL_ASSET_LINK_STATUS.NEEDS_PERMISSION);
+ assert.equal(promptHandle.calls.getFile, 0);
+
+ const ready = await inspectLocalAssetHandle({
+ assetId: "asset:2",
+ handle: fileHandle(),
+ metadata: fileMetadata()
+ });
+ assert.equal(ready.status, LOCAL_ASSET_LINK_STATUS.READY);
+ assert.deepEqual(ready.changedFields, []);
+
+ const changed = await inspectLocalAssetHandle({
+ assetId: "asset:3",
+ handle: fileHandle({ file: fileMetadata({ size: 256, lastModified: 84 }) }),
+ metadata: fileMetadata()
+ });
+ assert.equal(changed.status, LOCAL_ASSET_LINK_STATUS.CHANGED);
+ assert.deepEqual(changed.changedFields, ["size", "lastModified"]);
+});
+
+test("missing files are reported without disguising them as permission failures", async () => {
+ const error = new Error("gone");
+ error.name = "NotFoundError";
+ const result = await inspectLocalAssetHandle({
+ assetId: "asset:1",
+ handle: fileHandle({ getFileError: error }),
+ metadata: fileMetadata()
+ });
+ assert.equal(result.status, LOCAL_ASSET_LINK_STATUS.MISSING);
+ assert.equal(result.permission, "granted");
+});
+
+test("file reads require an already granted permission and never request it", async () => {
+ const promptHandle = fileHandle({ permission: "prompt" });
+ await assert.rejects(readLocalAssetFile(promptHandle), (error) => {
+ assert.equal(error.code, "local_asset_permission_required");
+ return true;
+ });
+ assert.deepEqual(promptHandle.calls, { query: 1, getFile: 0, request: 0 });
+
+ const grantedHandle = fileHandle();
+ assert.deepEqual(await readLocalAssetFile(grantedHandle), fileMetadata());
+ assert.deepEqual(grantedHandle.calls, { query: 1, getFile: 1, request: 0 });
+});
+
+test("metadata comparison includes name size and last modified time", () => {
+ assert.deepEqual(localAssetMetadataChanges(
+ fileMetadata(),
+ fileMetadata({ name: "renamed.psd", size: 256, lastModified: 84 })
+ ), ["name", "size", "lastModified"]);
+});
diff --git a/test/local-index-maintenance-ui.test.js b/test/local-index-maintenance-ui.test.js
new file mode 100644
index 0000000..218a0c2
--- /dev/null
+++ b/test/local-index-maintenance-ui.test.js
@@ -0,0 +1,28 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const [html, source] = await Promise.all([
+ readFile(new URL("../library.html", import.meta.url), "utf8"),
+ readFile(new URL("../library.js", import.meta.url), "utf8")
+]);
+
+test("local index maintenance explains its result and has no decorative progress bar", () => {
+ const card = html.slice(html.indexOf('<div class="batch-card local-index-card">'), html.indexOf('id="legacy-candidates"'));
+ assert.match(card, /补全资料索引/);
+ assert.match(card, /补齐导入案例的内容类型和图片色卡,用于分类筛选、颜色展示和相似资料匹配;全程在本机运行,不调用 AI。/);
+ assert.match(card, /id="preview-reanalyze"[^>]*>检查缺失项/);
+ assert.match(card, /id="apply-reanalyze"[^>]*hidden>开始补全/);
+ assert.doesNotMatch(card, /<progress|maintenance-progress/);
+});
+
+test("local index maintenance exposes checked, running, complete, and failed text states", () => {
+ const manager = source.slice(source.indexOf("function renderBatchManager"), source.indexOf("function renderAnalysisSettings"));
+ const status = source.slice(source.indexOf("function renderReanalysisPreview"), source.indexOf("function updateLibrarySettingsSaveState"));
+ assert.match(manager, /reanalysisPreview \|\| maintenanceJob \? "重新检查" : "检查缺失项"/);
+ assert.match(manager, /elements\.applyReanalyze\.hidden = maintenanceActive \|\| !maintenanceMissing/);
+ assert.match(status, /资料索引已完整/);
+ assert.match(status, /待补全:\$\{reanalysisPreview\.confirmed\} 条内容类型,\$\{reanalysisPreview\.paletteCount\} 张图片色卡/);
+ assert.match(status, /已处理 \$\{maintenanceJob\.processed\}\/\$\{maintenanceJob\.total\}/);
+ assert.match(status, /成功 \$\{maintenanceJob\.succeeded\} · 失败 \$\{maintenanceJob\.failed\}/);
+});
diff --git a/test/local-media.test.js b/test/local-media.test.js
index 522a5f2..ad6e74a 100644
--- a/test/local-media.test.js
+++ b/test/local-media.test.js
@@ -2,6 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import {
+ createUnsupportedLocalAssetReference,
detectLocalMediaFile,
findExactMediaDuplicate,
normalizeLocalRelativePath,
@@ -22,15 +23,58 @@ test("local media detection keeps only supported formats and safe relative paths
assert.deepEqual(detectLocalMediaFile(new File(["movie"], "clip.mov")), {
extension: "mov", kind: "video", mimeType: "video/quicktime"
});
- assert.throws(
- () => detectLocalMediaFile(new File(["html"], "frame.png", { type: "text/html" })),
- /扩展名和文件格式不一致/
- );
+ assert.deepEqual(detectLocalMediaFile(new File(["audio"], "score.wav", { type: "audio/wav" })), {
+ extension: "wav", kind: "audio", mimeType: "audio/wav"
+ });
+ assert.deepEqual(detectLocalMediaFile(new File(["source"], "layout.psd", { type: "application/octet-stream" })), {
+ extension: "psd", kind: "attachment", mimeType: "image/vnd.adobe.photoshop"
+ });
+ assert.throws(() => detectLocalMediaFile(new File(["html"], "frame.png", { type: "text/html" })), (error) => {
+ assert.equal(error.code, "unsupported_format");
+ assert.match(error.message, /扩展名和文件格式不一致/);
+ return true;
+ });
assert.equal(normalizeLocalRelativePath("folder/reference/frame.gif", "frame.gif"), "folder/reference/frame.gif");
assert.throws(() => normalizeLocalRelativePath("/Users/private/frame.gif", "frame.gif"), /相对路径/);
assert.throws(() => normalizeLocalRelativePath("../private/frame.gif", "frame.gif"), /相对路径/);
});
+test("subtitle preparation extracts safe plain text as a document", async () => {
+ const subtitle = new File(["1\r\n00:00:01,000 --> 00:00:02,000\r\nOpening\u0000\r\n"], "captions.srt", {
+ type: "text/plain"
+ });
+ const prepared = await prepareLocalMedia(subtitle, "document:subtitle", {
+ estimateStorage: async () => ({ quota: 1000, usage: 0 })
+ });
+
+ assert.equal(prepared.asset.kind, "document");
+ assert.equal(prepared.asset.formatCategory, "subtitle");
+ assert.equal(prepared.contentFormat, "plain");
+ assert.equal(prepared.sourceFormat, "srt");
+ assert.equal(prepared.contentText, "1\n00:00:01,000 --> 00:00:02,000\nOpening");
+});
+
+test("audio and creator source preparation preserve originals without parsing proprietary contents", async () => {
+ const estimateStorage = async () => ({ quota: 10_000, usage: 0 });
+ const audio = await prepareLocalMedia(
+ new File(["audio"], "score.flac", { type: "audio/flac" }),
+ "audio:score",
+ { estimateStorage }
+ );
+ const source = await prepareLocalMedia(
+ new File(["private format bytes"], "scene.aep", { type: "application/octet-stream" }),
+ "attachment:scene",
+ { estimateStorage, storageMode: "reference" }
+ );
+
+ assert.equal(audio.asset.kind, "audio");
+ assert.equal(audio.asset.playbackCapability, "native");
+ assert.equal(source.asset.kind, "attachment");
+ assert.equal(source.asset.storageMode, "reference");
+ assert.equal(source.asset.formatCategory, "motion-project");
+ assert.equal(Object.hasOwn(source, "contentText"), false);
+});
+
test("GIF preparation retains the original and creates one first-frame poster", async () => {
const gif = new File(["gif-bytes"], "motion.gif", { type: "image/gif" });
const posterBlob = new Blob(["poster"], { type: "image/webp" });
@@ -68,11 +112,98 @@ test("local image preparation rejects files above the portable image limit befor
return { width: 1, height: 1 };
}
}),
- /16 MiB/
+ (error) => {
+ assert.equal(error.code, "too_large");
+ assert.equal(error.forceAllowed, true);
+ assert.equal(error.details.actualBytes, oversized.size);
+ assert.equal(error.details.maxBytes, PORTABLE_LIBRARY_LIMITS.maxImageBytes);
+ assert.match(error.message, /16 MiB/);
+ return true;
+ }
);
assert.equal(dimensionReads, 0);
});
+test("explicit force import bypasses only the default image byte limit", async () => {
+ const image = new File(["12345"], "large.png", { type: "image/png" });
+ const prepared = await prepareLocalMedia(image, "asset:forced", {
+ forceImport: true,
+ limits: { maxImageBytes: 4, maxImagePixels: 100 },
+ estimateStorage: async () => ({ quota: 100, usage: 0 }),
+ readImageDimensions: async () => ({ width: 5, height: 5 })
+ });
+
+ assert.equal(prepared.asset.byteSize, 5);
+ assert.equal(prepared.asset.width, 5);
+ assert.equal(prepared.asset.height, 5);
+});
+
+test("force import cannot bypass physical storage capacity or the image pixel safety limit", async () => {
+ const image = new File(["12345"], "large.png", { type: "image/png" });
+ await assert.rejects(() => prepareLocalMedia(image, "asset:no-space", {
+ forceImport: true,
+ limits: { maxImageBytes: 4 },
+ estimateStorage: async () => ({ quota: 4, usage: 0 }),
+ readImageDimensions: async () => ({ width: 1, height: 1 })
+ }), (error) => {
+ assert.equal(error.code, "storage_insufficient");
+ assert.equal(error.forceAllowed, false);
+ return true;
+ });
+
+ await assert.rejects(() => prepareLocalMedia(image, "asset:unsafe-pixels", {
+ forceImport: true,
+ limits: { maxImageBytes: 4, maxImagePixels: 20 },
+ estimateStorage: async () => ({ quota: 100, usage: 0 }),
+ readImageDimensions: async () => ({ width: 5, height: 5 })
+ }), (error) => {
+ assert.equal(error.code, "safety_limit_exceeded");
+ assert.equal(error.forceAllowed, false);
+ assert.match(error.message, /不能强制导入/);
+ return true;
+ });
+});
+
+test("decode failures expose a stable per-file reason code", async () => {
+ const image = new File(["not really png"], "broken.png", { type: "image/png" });
+ await assert.rejects(() => prepareLocalMedia(image, "asset:broken", {
+ estimateStorage: async () => ({ quota: 100, usage: 0 }),
+ readImageDimensions: async () => { throw new Error("decoder stopped"); }
+ }), (error) => {
+ assert.equal(error.code, "read_or_decode_failed");
+ assert.match(error.message, /broken\.png.*decoder stopped/);
+ return true;
+ });
+});
+
+test("unsupported files can become inert relink metadata without copying their blob", () => {
+ const file = new File(["binary"], "references/custom.zzz", {
+ type: "application/x-custom",
+ lastModified: 1_776_500_123_000
+ });
+ const reference = createUnsupportedLocalAssetReference(file, "attachment:unknown", {
+ relativePath: "references/custom.zzz",
+ now: "2026-08-22T10:00:00.000Z"
+ });
+
+ assert.equal(reference.storageMode, "reference");
+ assert.equal(reference.recordType, "local-asset-reference");
+ assert.equal(reference.linkStatus, "relink-required");
+ assert.equal(reference.importFailure.code, "unsupported_format");
+ assert.equal(reference.relativePath, "references/custom.zzz");
+ assert.equal(reference.sourceFormat, "zzz");
+ assert.equal(reference.sourceLastModified, 1_776_500_123_000);
+ assert.equal(Object.hasOwn(reference, "blob"), false);
+ assert.equal(Object.hasOwn(reference, "contentHash"), false);
+ assert.throws(
+ () => createUnsupportedLocalAssetReference(
+ new File(["source"], "scene.aep", { type: "application/x-after-effects" }),
+ "attachment:supported"
+ ),
+ (error) => error.code === "invalid_file" && /正常导入流程/u.test(error.message)
+ );
+});
+
test("exact duplicate detection hashes only size type and name candidates", async () => {
const incoming = new File(["same bytes"], "frame.png", { type: "image/png" });
const blobs = new Map([
diff --git a/test/manager_regression_e2e.py b/test/manager_regression_e2e.py
index 8bbfebd..fc688b6 100644
--- a/test/manager_regression_e2e.py
+++ b/test/manager_regression_e2e.py
@@ -4,7 +4,7 @@ import tempfile
import os
from pathlib import Path
-from playwright.sync_api import sync_playwright
+from playwright.sync_api import expect, sync_playwright
EXTENSION_DIR = Path(__file__).resolve().parents[1]
@@ -31,7 +31,7 @@ def main() -> None:
page_errors = []
page.on("pageerror", lambda error: page_errors.append(str(error)))
page.goto(f"chrome-extension://{extension_id}/library.html")
- page.locator("#library-summary").get_by_text("0 条案例", exact=False).wait_for(timeout=1500)
+ expect(page.locator("#result-count")).to_have_text("0 个案例", timeout=1500)
page.evaluate(
"""async (nodeCount) => {
const {SCHEMA_VERSION, createDefaultTaxonomy} = await import(chrome.runtime.getURL('taxonomy.js'));
@@ -43,6 +43,7 @@ def main() -> None:
text: `tracking shot ${index}`,
url: `https://example.com/${index}`,
savedAt: '2026-07-19T00:00:00.000Z',
+ classification: {pathIds: ['content:prompt:image'], status: 'confirmed', source: 'manual'},
facetAssignments: [{
facetId: 'camera', nodeId: `detail:camera.lens:e2e-${index % nodeCount}`,
status: 'confirmed', source: 'manual'
@@ -74,7 +75,7 @@ def main() -> None:
)
page.reload()
page.wait_for_load_state("networkidle")
- page.locator("#library-summary").get_by_text("43 条案例", exact=False).wait_for(timeout=1500)
+ expect(page.locator("#result-count")).to_have_text("43 个案例", timeout=1500)
started = page.evaluate("performance.now()")
page.locator("#manage-facets").click(timeout=1500)
page.locator("#manager-dialog").wait_for(state="visible", timeout=1500)
diff --git a/test/material_management_regressions_e2e.py b/test/material_management_regressions_e2e.py
new file mode 100644
index 0000000..7818028
--- /dev/null
+++ b/test/material_management_regressions_e2e.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+from playwright.sync_api import expect
+
+from e2e_support import extension_session
+
+
+def main() -> None:
+ with extension_session("prompt-director-material-management-", viewport={"width": 1180, "height": 820}) as session:
+ collector = session.open_page("collector.html")
+ collector.evaluate(
+ """async () => chrome.runtime.sendMessage({
+ type: 'UPDATE_CAPTURE_DRAFT',
+ draft: {
+ title: '素材整理验收',
+ fragments: [{id: 'material-text', text: '验证采集侧栏的多标签编辑。'}],
+ visuals: []
+ }
+ })"""
+ )
+ collector.reload(wait_until="networkidle")
+ collector.locator("#organize-toggle").click()
+ expect(collector.locator("#capture-metadata")).to_be_visible()
+ expect(collector.locator("#capture-metadata")).to_contain_text("添加标签")
+ expect(collector.locator("#capture-metadata")).not_to_contain_text("自由标签")
+
+ tag_input = collector.locator("#custom-labels .tag-editor input")
+ tag_input.fill("外部采集,连续标签")
+ collector.locator("#custom-labels .tag-editor").get_by_role("button", name="添加", exact=True).click()
+ expect(collector.locator("#custom-labels .tag-editor-chip")).to_have_count(2)
+ saved_labels = collector.evaluate("async () => (await chrome.storage.local.get('captureDraft')).captureDraft.customLabels")
+ assert saved_labels == ["外部采集", "连续标签"], saved_labels
+
+ select_style = collector.locator("#content-type").evaluate(
+ """node => ({
+ appearance: getComputedStyle(node).appearance,
+ supported: CSS.supports('appearance: base-select'),
+ background: getComputedStyle(node).backgroundColor
+ })"""
+ )
+ assert select_style["supported"] is True, select_style
+ assert select_style["appearance"] == "base-select", select_style
+ assert select_style["background"] not in {"rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"}, select_style
+
+ print({"collector_tags": saved_labels, "select_style": select_style})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/test/media-archive-ui.test.js b/test/media-archive-ui.test.js
new file mode 100644
index 0000000..9cc16b0
--- /dev/null
+++ b/test/media-archive-ui.test.js
@@ -0,0 +1,91 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const js = await readFile(new URL("../library.js", import.meta.url), "utf8");
+const html = await readFile(new URL("../library.html", import.meta.url), "utf8");
+const css = await readFile(new URL("../library.css", import.meta.url), "utf8");
+
+test("modern file and folder pickers preserve handles and relative paths before falling back", () => {
+ assert.match(js, /showOpenFilePicker\(\{ multiple: true \}\)/);
+ assert.match(js, /showDirectoryPicker\(\{ mode: "read" \}\)/);
+ assert.match(js, /readImportDirectoryHandle\(root, root\.name\)/);
+ assert.match(js, /\{\s*handle,\s*file:\s*await handle\.getFile\(\),\s*relativePath/);
+ assert.match(js, /elements\.mediaFile\.click\(\)/);
+ assert.match(js, /elements\.mediaFolder\.click\(\)/);
+ assert.match(js, /getAsFileSystemHandle/);
+});
+
+test("unsupported failures can become inert persistent local references", () => {
+ assert.match(js, /ASSET_IMPORT_FAILURE_CODES\.UNSUPPORTED_FORMAT/);
+ assert.match(js, /"保留本机链接"/);
+ assert.match(js, /createUnsupportedLocalAssetReference\(file, assetId/);
+ assert.match(js, /saveLocalAssetHandle\(assetId, handle, file\)/);
+ assert.match(js, /recordType:\s*reference\.recordType/);
+ assert.match(js, /sourceLastModified:\s*file\.lastModified/);
+ assert.match(js, /deleteLocalAssetHandle\(item\.assetId\)/);
+});
+
+test("audio and creative source files have useful card and detail surfaces", () => {
+ const card = js.slice(js.indexOf("function createCaseCard"), js.indexOf("async function reorderProjectCase"));
+ const viewer = js.slice(js.indexOf("async function createMediaViewer"), js.indexOf("async function loadRemoteMarkdownImage"));
+ assert.match(card, /createAudioCaseCover/);
+ assert.match(card, /createSourceFileCaseCover/);
+ assert.match(js, /case-audio-player/);
+ assert.match(viewer, /asset\.kind === "audio"/);
+ assert.match(viewer, /audio\.controls = true/);
+ assert.match(viewer, /asset\.kind === "attachment"/);
+ assert.match(viewer, /不会执行或内嵌打开/);
+ assert.match(viewer, /下载本机副本/);
+ assert.match(js, /formatMediaTime\(asset\.durationMs\)/);
+ assert.match(js, /formatBytes\(asset\.byteSize\)/);
+ assert.match(css, /\.detail-audio-wrap/);
+ assert.match(css, /\.detail-source-file/);
+});
+
+test("local reference details report state and require explicit user actions", () => {
+ const viewer = js.slice(js.indexOf("async function createLocalAssetReferenceViewer"), js.indexOf("async function createReferencedMediaViewer"));
+ assert.match(viewer, /inspectLocalAssetHandle/);
+ assert.match(viewer, /重新授权读取/);
+ assert.match(viewer, /重新链接源文件/);
+ assert.match(viewer, /UPDATE_LOCAL_ASSET_REFERENCE/);
+ assert.match(viewer, /只保存文件信息与本机授权/);
+ assert.doesNotMatch(viewer, /createElement\("iframe"\)|createElement\("script"\)|innerHTML/);
+});
+
+test("share export checks every linked source and stops when permission is canceled", () => {
+ const exportFlow = js.slice(js.indexOf("async function prepareShareLocalAssetRecords"), js.indexOf("async function submitFromShareDialog"));
+ assert.match(exportFlow, /getLocalAssetHandleRecord/);
+ assert.match(exportFlow, /requestPermission\(\{ mode: "read" \}\)/);
+ assert.match(exportFlow, /if \(!await authorizeShareLocalAssets\(\)\)/);
+ assert.match(exportFlow, /分享包未导出/);
+ assert.match(exportFlow, /源文件自上次链接后发生变化/);
+ assert.match(exportFlow, /UPDATE_LOCAL_ASSET_REFERENCE/);
+});
+
+test("project share preflight uses the same compound-complete member selection as packaging", () => {
+ assert.match(js, /projectPackageEntryIds\(\{ entries, compoundCases, organizerState \}, context\.collectionId\)/u);
+});
+
+test("share package import sizes only this user-selected package by its real file size", () => {
+ const imported = js.slice(js.indexOf("async function importSharedLibraryPackage"), js.indexOf("function backupMediaPaths"));
+ assert.match(imported, /maxArchiveBytes:\s*file\.size/);
+ assert.match(imported, /maxFileBytes:\s*file\.size/);
+ assert.match(imported, /maxImageBytes:\s*file\.size/);
+ assert.match(imported, /readZipBlob\(file, packageLimits\)/);
+ assert.match(imported, /parseLibraryPackage\(library, files, packageLimits\)/);
+});
+
+test("complete folder restore derives its media budget from the selected verified backup", () => {
+ const restore = js.slice(js.indexOf("async function restoreCompleteFolderBackup"), js.indexOf("async function importSharedLibraryPackage"));
+ assert.match(restore, /largestMediaBytes = Math\.max\(1, \.\.\.backupMediaSizes\)/);
+ assert.match(restore, /maxFileBytes: largestMediaBytes/);
+ assert.match(restore, /maxImageBytes: largestMediaBytes/);
+ assert.match(restore, /maxVideoBytes: largestMediaBytes/);
+ assert.match(restore, /parseCompleteFolderBackup\(library, files, restoreLimits\)/);
+ assert.doesNotMatch(restore, /maxFileBytes: Number\.MAX_SAFE_INTEGER/);
+});
+
+test("import copy tells creators that unsupported formats can remain linked", () => {
+ assert.match(html, /不支持的格式仍可保留本机链接/);
+});
diff --git a/test/media-store.test.js b/test/media-store.test.js
index 200818b..f53e5f9 100644
--- a/test/media-store.test.js
+++ b/test/media-store.test.js
@@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
import {
assertStorageCapacity,
+ mediaStorageWriteError,
normalizeDerivedMedia,
normalizeDerivedMetadata,
validateMediaBlob
@@ -11,11 +12,16 @@ import {
const source = await readFile(new URL("../media-store.js", import.meta.url), "utf8");
-test("media storage accepts images videos and creative documents", () => {
+test("media storage accepts images videos audio documents and inert creator sources", () => {
assert.doesNotThrow(() => validateMediaBlob(new Blob(["frame"], { type: "image/webp" })));
assert.doesNotThrow(() => validateMediaBlob(new Blob(["clip"], { type: "video/mp4" })));
+ assert.doesNotThrow(() => validateMediaBlob(new Blob(["audio"], { type: "audio/flac" })));
assert.doesNotThrow(() => validateMediaBlob(new Blob(["pdf"], { type: "application/pdf" })));
- assert.throws(() => validateMediaBlob(new Blob(["binary"], { type: "application/octet-stream" })), /暂不支持/);
+ assert.doesNotThrow(() => validateMediaBlob(new Blob(["source"], { type: "application/x-after-effects" })));
+ assert.throws(() => validateMediaBlob(new Blob(["binary"], { type: "application/octet-stream" })), (error) => {
+ assert.equal(error.code, "unsupported_format");
+ return true;
+ });
});
test("derived document data remains a rebuildable cache with bounded metadata", () => {
@@ -62,5 +68,19 @@ test("undoing a media replacement invalidates the replacement thumbnail before r
test("media import blocks only when the reported physical capacity is insufficient", () => {
assert.doesNotThrow(() => assertStorageCapacity({}, 500));
assert.doesNotThrow(() => assertStorageCapacity({ quota: 1000, usage: 200 }, 800));
- assert.throws(() => assertStorageCapacity({ quota: 1000, usage: 201 }, 800), /可用空间不足/);
+ assert.throws(() => assertStorageCapacity({ quota: 1000, usage: 201 }, 800), (error) => {
+ assert.equal(error.code, "storage_insufficient");
+ assert.equal(error.details.requiredBytes, 800);
+ assert.equal(error.details.availableBytes, 799);
+ assert.match(error.message, /可用空间不足/);
+ return true;
+ });
+});
+
+test("unexpected IndexedDB write failures keep their cause and expose a stable reason code", () => {
+ const cause = new Error("transaction aborted");
+ const error = mediaStorageWriteError(cause);
+ assert.equal(error.code, "storage_write_failed");
+ assert.equal(error.cause, cause);
+ assert.match(error.message, /写入本机资料库失败.*transaction aborted/);
});
diff --git a/test/media-ui.test.js b/test/media-ui.test.js
index aeb0786..29edef4 100644
--- a/test/media-ui.test.js
+++ b/test/media-ui.test.js
@@ -102,10 +102,11 @@ test("one top search surface keeps only a concise placeholder hint", () => {
assert.doesNotMatch(html, /id="search-help"|source:x\.com.*tag:电影感.*has:video/);
});
-test("screenshot counts use canonical media assets after extension messaging", () => {
- const gallery = source.slice(source.indexOf("function renderGallery"), source.indexOf("function scheduleLoadCheck"));
- assert.match(gallery, /entryMediaAssets\(entry\)\s*\.filter\(\(asset\) => asset\.kind === "image" && asset\.usage !== "poster"\)/);
- assert.doesNotMatch(gallery, /entry\.visuals\?\.length/);
+test("the gallery keeps one current-result count instead of a duplicate global media summary", () => {
+ const gallery = source.slice(source.indexOf("function renderGalleryResults"), source.indexOf("function projectManualOrderAvailable"));
+ assert.match(gallery, /elements\.resultCount\.textContent/);
+ assert.match(gallery, /visibleEntries\.length/);
+ assert.doesNotMatch(html, /id="library-summary"/);
});
test("fixed-ratio gallery covers crop mismatched source images inside the card", () => {
@@ -137,9 +138,24 @@ test("the library includes a local quick-note entry that does not invoke AI", ()
assert.match(html, /id="add-quick-note"/);
const quickNote = source.slice(source.indexOf("async function createQuickNote"), source.indexOf("async function prepareLocalMedia"));
assert.match(quickNote, /CREATE_QUICK_NOTE/);
+ assert.match(quickNote, /caseCreationOrganizationFields\(\)/);
+ assert.match(quickNote, /caseCreationOrganization\(projectName, customLabels\)/);
assert.doesNotMatch(quickNote, /ANALY|DeepSeek|OpenAI/);
});
+test("new video references and quick notes accept an existing or new project plus user tags", () => {
+ const video = source.slice(source.indexOf("async function addVideoReference"), source.indexOf("async function fetchVideoReferencePoster"));
+ const note = source.slice(source.indexOf("async function createQuickNote"), source.indexOf("async function prepareLocalMedia"));
+ assert.match(video, /caseCreationOrganizationFields\(\)/);
+ assert.match(video, /caseCreationOrganization\(\s*projectName,\s*customLabels\s*\)/);
+ assert.match(video, /CREATE_MEDIA_REFERENCE[\s\S]*?\.\.\.organization/);
+ assert.match(note, /CREATE_QUICK_NOTE[\s\S]*?\.\.\.caseCreationOrganization\(projectName, customLabels\)/);
+ assert.match(note, /label:\s*"添加标签"/);
+ assert.match(note, /newCollectionName:\s*projectName/);
+ assert.match(note, /collectionId:\s*existing\.id/);
+ assert.match(note, /attachProjectSuggestions/);
+});
+
test("similar material stays local, image-led, and free of project-age resurfacing", () => {
const discovery = source.slice(source.indexOf("function createLocalDiscovery"), source.indexOf("async function renderCompoundDetail"));
assert.match(discovery, /rankSimilarEntries/);
@@ -156,7 +172,7 @@ test("similar material stays local, image-led, and free of project-age resurfaci
});
test("the home wall shows every library-visible content type and hides only explicit category-only types", () => {
- const gallery = source.slice(source.indexOf("function renderGalleryResults"), source.indexOf("function updateLibrarySummary"));
+ const gallery = source.slice(source.indexOf("function renderGalleryResults"), source.indexOf("function projectManualOrderAvailable"));
assert.match(gallery, /CONTENT_TYPE_VISIBILITY\.categoryOnly/);
assert.match(gallery, /const browseEntries = selectedContentId/);
assert.match(gallery, /isEntryPending\(entry\)/);
diff --git a/test/media.test.js b/test/media.test.js
index 0a4c183..2d5fa37 100644
--- a/test/media.test.js
+++ b/test/media.test.js
@@ -9,7 +9,8 @@ import {
normalizeMediaAsset,
posterAssetForVideo,
removeEntryMedia,
- setPrimaryMedia
+ setPrimaryMedia,
+ updateLocalAssetReferenceMetadata
} from "../media.js";
import { normalizeEntryVisuals, reorderEntryVisuals } from "../visuals.js";
@@ -167,6 +168,139 @@ test("file media kinds are derived from actual file metadata and supported exten
assert.equal(mediaKindFromFile({ name: "notes.pdf", type: "" }), "document");
assert.equal(mediaKindFromFile({ name: "frame.webp", type: "image/webp" }), "image");
assert.equal(mediaKindFromFile({ name: "motion.gif", type: "image/gif" }), "image");
+ assert.equal(mediaKindFromFile({ name: "score.wav", type: "audio/wav" }), "audio");
+ assert.equal(mediaKindFromFile({ name: "captions.srt", type: "text/plain" }), "document");
+ assert.equal(mediaKindFromFile({ name: "layout.psd", type: "application/octet-stream" }), "attachment");
+ assert.equal(mediaKindFromFile({ name: "font.otf", type: "font/otf" }), "attachment");
assert.equal(normalizeMediaAsset({ id: "gif", kind: "image", mimeType: "image/gif" }).mimeType, "image/gif");
assert.equal(mediaKindFromFile({ name: "archive.bin", type: "application/octet-stream" }), "");
});
+
+test("audio and inert attachment assets survive canonical normalization", () => {
+ const audio = normalizeMediaAsset({
+ id: "audio:score",
+ kind: "audio",
+ storageMode: "managed",
+ sourceTitle: "score.wav",
+ mimeType: "audio/wav",
+ durationMs: 3200
+ });
+ const attachment = normalizeMediaAsset({
+ id: "attachment:scene",
+ kind: "attachment",
+ storageMode: "reference",
+ sourceTitle: "scene.aep",
+ relativePath: "project/scene.aep",
+ mimeType: "application/x-after-effects"
+ });
+
+ assert.equal(audio.kind, "audio");
+ assert.equal(audio.formatCategory, "audio");
+ assert.equal(attachment.kind, "attachment");
+ assert.equal(attachment.storageMode, "reference");
+ assert.equal(attachment.sourceFormat, "aep");
+ assert.equal(attachment.formatCategory, "motion-project");
+ assert.equal(attachment.relativePath, "project/scene.aep");
+ assert.equal(normalizeMediaAsset({
+ id: "attachment:unsafe",
+ kind: "attachment",
+ sourceTitle: "payload.exe",
+ mimeType: "application/octet-stream"
+ }), null);
+});
+
+test("unknown local source references require record identity while packaged copies require a generic managed descriptor", () => {
+ const reference = {
+ id: "attachment:unknown",
+ kind: "attachment",
+ storageMode: "reference",
+ recordType: "local-asset-reference",
+ linkStatus: "linked",
+ sourceTitle: "custom.zzz",
+ relativePath: "sources/custom.zzz",
+ sourceFormat: "zzz",
+ formatCategory: "local-link",
+ mimeType: "application/x-custom",
+ byteSize: 20,
+ sourceLastModified: 1_776_500_123_000,
+ importFailure: {
+ code: "unsupported_format",
+ message: "暂不支持这种文件格式:custom.zzz",
+ forceAllowed: false
+ }
+ };
+ const normalized = normalizeMediaAsset(reference);
+ const packaged = normalizeMediaAsset({
+ id: "attachment:packaged",
+ kind: "attachment",
+ storageMode: "managed",
+ sourceTitle: "custom.zzz",
+ sourceFormat: "zzz",
+ formatCategory: "other-source",
+ mimeType: "application/octet-stream",
+ byteSize: 20,
+ assetPath: "attachments/case/custom.zzz"
+ });
+
+ assert.equal(normalized.recordType, "local-asset-reference");
+ assert.equal(normalized.linkStatus, "linked");
+ assert.equal(normalized.sourceLastModified, 1_776_500_123_000);
+ assert.equal(normalized.importFailure.code, "unsupported_format");
+ assert.equal(packaged.storageMode, "managed");
+ assert.equal(packaged.formatCategory, "other-source");
+ assert.equal(packaged.sourceFormat, "zzz");
+ assert.equal(packaged.recordType, undefined);
+ assert.equal(normalizeMediaAsset({ ...packaged, id: "attachment:reference", storageMode: "reference" }), null);
+ assert.equal(normalizeMediaAsset({ ...packaged, id: "attachment:wrong-category", formatCategory: "local-link" }), null);
+ assert.equal(normalizeMediaAsset({ ...packaged, id: "attachment:unsafe-format", sourceFormat: "../zzz" }), null);
+ assert.equal(normalizeMediaAsset({ ...packaged, id: "attachment:specific-mime", mimeType: "application/x-custom" }), null);
+ assert.equal(normalizeMediaAsset({
+ ...packaged,
+ id: "attachment:registered-mismatch",
+ sourceTitle: "layout.psd",
+ sourceFormat: "psd",
+ mimeType: "text/html"
+ }), null);
+});
+
+test("relinking an inert local source updates only verifiable file metadata", () => {
+ const original = normalizeEntryMedia({
+ id: "entry:source",
+ primaryMediaId: "attachment:unknown",
+ mediaAssets: [{
+ id: "attachment:unknown",
+ kind: "attachment",
+ storageMode: "reference",
+ recordType: "local-asset-reference",
+ linkStatus: "relink-required",
+ sourceTitle: "custom.zzz",
+ relativePath: "old/custom.zzz",
+ sourceFormat: "zzz",
+ mimeType: "application/x-custom",
+ byteSize: 20,
+ importFailure: {
+ code: "unsupported_format",
+ message: "暂不支持这种文件格式:custom.zzz",
+ forceAllowed: false
+ }
+ }]
+ });
+ const updated = updateLocalAssetReferenceMetadata(original, "attachment:unknown", {
+ sourceTitle: "custom-v2.zzz",
+ relativePath: "new/custom-v2.zzz",
+ sourceFormat: "zzz",
+ mimeType: "application/x-custom",
+ byteSize: 32,
+ sourceLastModified: 1_776_500_999_000
+ });
+
+ assert.equal(updated.asset.linkStatus, "linked");
+ assert.equal(updated.asset.sourceTitle, "custom-v2.zzz");
+ assert.equal(updated.asset.relativePath, "new/custom-v2.zzz");
+ assert.equal(updated.asset.byteSize, 32);
+ assert.equal(updated.asset.sourceLastModified, 1_776_500_999_000);
+ assert.equal(updated.entry.primaryMediaId, "attachment:unknown");
+ assert.throws(() => updateLocalAssetReferenceMetadata(original, "attachment:unknown", {
+ sourceTitle: "custom.zzz", relativePath: "../custom.zzz", byteSize: 20, sourceLastModified: 1
+ }), /安全相对路径/u);
+});
diff --git a/test/migration.test.js b/test/migration.test.js
index a80418f..d9cf107 100644
--- a/test/migration.test.js
+++ b/test/migration.test.js
@@ -16,9 +16,38 @@ test("older schemas upgrade without changing entry content", () => {
assert.deepEqual(result.state.compoundCases, []);
assert.equal(result.state.entries[0].id, entry.id);
assert.equal(result.state.entries[0].text, entry.text);
+ assert.equal("libraryAddedAt" in result.state.entries[0], false);
+ assert.deepEqual(result.state.trashState, { version: 1, items: [] });
assert.equal(needsMigration(result.state), false);
});
+test("schema upgrade preserves valid recycle-bin snapshots without reviving them", () => {
+ const stored = {
+ schemaVersion: 26,
+ taxonomy: createDefaultTaxonomy(),
+ facetCatalog: { version: 2, revision: 1, facets: [], nodes: [] },
+ organizerState: { version: 6, collections: [] },
+ compoundCases: [],
+ entries: [],
+ trashState: {
+ version: 1,
+ items: [{
+ id: "trash:entry:removed",
+ kind: "entry",
+ targetId: "removed",
+ deletedAt: "2026-08-22T00:00:00.000Z",
+ snapshot: { id: "removed", title: "已删除案例" },
+ relationships: { collections: [] }
+ }]
+ }
+ };
+
+ const result = migrateLibraryState(stored).state;
+ assert.deepEqual(result.entries, []);
+ assert.equal(result.trashState.items[0].snapshot.title, "已删除案例");
+ assert.equal(needsMigration(result), false);
+});
+
test("fixed-tree upgrade keeps mapped DeepSeek labels usable until an explicit rebuild", () => {
const stored = {
schemaVersion: 24,
diff --git a/test/navigation-state.test.js b/test/navigation-state.test.js
index 70153c5..6840763 100644
--- a/test/navigation-state.test.js
+++ b/test/navigation-state.test.js
@@ -97,7 +97,9 @@ test("library return snapshots serialize canonical collection, facets, query, an
facetNodeIds: ["facet:2", "facet:1", "facet:2"],
pendingOnly: true,
query: "银色角色",
- scrollY: 428.7
+ scrollY: 428.7,
+ sortMode: "updated-desc",
+ projectSortMode: "recent"
});
assert.deepEqual(JSON.parse(serialized), {
@@ -106,7 +108,8 @@ test("library return snapshots serialize canonical collection, facets, query, an
facetNodeIds: ["facet:2", "facet:1"],
pendingOnly: true,
query: "银色角色",
- scrollY: 429
+ scrollY: 429,
+ sortMode: "updated-desc"
});
});
@@ -150,8 +153,42 @@ test("library return restore waits for initialization readiness and only applies
facetNodeIds: ["facet:1"],
pendingOnly: false,
query: "雾夜",
- scrollY: 320
+ scrollY: 320,
+ sortMode: "added-desc"
}]);
assert.equal(restore(true), false);
assert.equal(storage.has(LIBRARY_RETURN_STORAGE_KEY), true);
});
+
+test("old library return snapshots gain safe default sorting", () => {
+ assert.deepEqual(parseLibraryReturnSnapshot(JSON.stringify({
+ collectionId: "",
+ contentId: "",
+ facetNodeIds: [],
+ pendingOnly: false,
+ query: "",
+ scrollY: 0
+ })), {
+ collectionId: "",
+ contentId: "",
+ facetNodeIds: [],
+ pendingOnly: false,
+ query: "",
+ scrollY: 0,
+ sortMode: "added-desc"
+ });
+});
+
+test("removed oldest-first snapshots fall back to recent-first", () => {
+ const snapshot = parseLibraryReturnSnapshot(JSON.stringify({
+ collectionId: "",
+ contentId: "",
+ facetNodeIds: [],
+ pendingOnly: false,
+ query: "",
+ scrollY: 0,
+ sortMode: "added-asc",
+ projectSortMode: "manual"
+ }));
+ assert.equal(snapshot.sortMode, "added-desc");
+});
diff --git a/test/offscreen-share-package.test.js b/test/offscreen-share-package.test.js
new file mode 100644
index 0000000..5799c3a
--- /dev/null
+++ b/test/offscreen-share-package.test.js
@@ -0,0 +1,92 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ packageMediaExtension,
+ portableManagedAsset,
+ readLinkedAssetForShare
+} from "../offscreen.js";
+
+const linkedAsset = Object.freeze({
+ id: "source:psd",
+ recordType: "local-asset-reference",
+ kind: "attachment",
+ storageMode: "reference",
+ linkStatus: "ready",
+ importFailure: { code: "unsupported_format", message: "旧机器状态" },
+ sourceTitle: "artwork.psd",
+ sourceFormat: "psd",
+ mimeType: "image/vnd.adobe.photoshop",
+ byteSize: 3,
+ sourceLastModified: 42
+});
+
+test("share export reads a ready local source without requesting permission itself", async () => {
+ const file = new Blob(["psd"], { type: "image/vnd.adobe.photoshop" });
+ const calls = [];
+ const result = await readLinkedAssetForShare(linkedAsset, "Key art", {
+ getLocalAssetHandleRecord: async (assetId) => {
+ calls.push(["record", assetId]);
+ return { assetId, handle: {} };
+ },
+ inspectStoredLocalAsset: async (assetId) => {
+ calls.push(["inspect", assetId]);
+ return { status: "ready", permission: "granted", file };
+ }
+ });
+
+ assert.equal(result, file);
+ assert.deepEqual(calls, [["record", "source:psd"], ["inspect", "source:psd"]]);
+});
+
+test("share export reports missing permission changed and missing local sources instead of skipping", async () => {
+ const record = async () => ({ assetId: linkedAsset.id, handle: {} });
+ for (const [status, message] of [
+ ["needs-permission", /尚未获得读取权限/],
+ ["changed", /发生了变化/],
+ ["missing", /移动、改名或删除/]
+ ]) {
+ await assert.rejects(() => readLinkedAssetForShare(linkedAsset, "Key art", {
+ getLocalAssetHandleRecord: record,
+ inspectStoredLocalAsset: async () => ({ status })
+ }), message);
+ }
+ await assert.rejects(() => readLinkedAssetForShare(linkedAsset, "Key art", {
+ getLocalAssetHandleRecord: async () => null
+ }), /没有保存可读取的本机链接/);
+});
+
+test("linked source becomes a portable managed copy with accurate format and no machine state", () => {
+ const blob = new Blob(["psd-source"], { type: "image/vnd.adobe.photoshop" });
+ const extension = packageMediaExtension(linkedAsset, blob);
+ const packaged = portableManagedAsset(linkedAsset, blob, "attachments/case/source.psd", extension);
+
+ assert.equal(extension, "psd");
+ assert.equal(packaged.storageMode, "managed");
+ assert.equal(packaged.assetPath, "attachments/case/source.psd");
+ assert.equal(packaged.byteSize, blob.size);
+ assert.equal(packaged.mimeType, "image/vnd.adobe.photoshop");
+ assert.equal(packaged.sourceFormat, "psd");
+ assert.equal(packaged.formatCategory, "design-source");
+ for (const field of ["recordType", "linkStatus", "importFailure", "sourceLastModified", "reference"]) {
+ assert.equal(Object.hasOwn(packaged, field), false);
+ }
+});
+
+test("unknown linked source stays an inert downloadable attachment in the package", () => {
+ const blob = new Blob(["source"], { type: "application/octet-stream" });
+ const asset = {
+ ...linkedAsset,
+ sourceTitle: "scene.customsource",
+ sourceFormat: "customsource",
+ mimeType: "application/octet-stream"
+ };
+ const extension = packageMediaExtension(asset, blob);
+ const packaged = portableManagedAsset(asset, blob, `attachments/case/source.${extension}`, extension);
+
+ assert.equal(extension, "customsource");
+ assert.equal(packaged.kind, "attachment");
+ assert.equal(packaged.storageMode, "managed");
+ assert.equal(packaged.formatCategory, "other-source");
+ assert.equal(packaged.mimeType, "application/octet-stream");
+});
diff --git a/test/organizer-background.test.js b/test/organizer-background.test.js
new file mode 100644
index 0000000..f006b91
--- /dev/null
+++ b/test/organizer-background.test.js
@@ -0,0 +1,57 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
+
+function functionBlock(name, nextName) {
+ const start = background.indexOf(`async function ${name}(`);
+ const end = background.indexOf(`async function ${nextName}(`, start + 1);
+ assert.ok(start >= 0, `${name} should exist`);
+ assert.ok(end > start, `${nextName} should follow ${name}`);
+ return background.slice(start, end);
+}
+
+test("background exposes explicit project reorder without rebuilding member lists", () => {
+ assert.match(background, /case "REORDER_COLLECTIONS":\s*case "REPLACE_COLLECTION_ENTRIES"/);
+ const update = functionBlock("updateOrganizer", "decideAnalysisCandidate");
+ assert.match(update, /reorderCollections\(organizerState, message\.collectionIds\)/);
+ assert.match(update, /replaceCollectionEntries\(organizerState, message\.collectionId, entryIds\)/);
+ assert.match(update, /changedProjectEntryIds\(beforeOrganizer, organizerState\)/);
+});
+
+test("manual content edits use one library update timestamp boundary", () => {
+ for (const name of [
+ "setEntryPrimaryVisual",
+ "addUploadedVisual",
+ "setEntryPrimaryMedia",
+ "moveEntryMediaToTrash",
+ "addUploadedMedia",
+ "addEntryTimeNote",
+ "addVideoKeyframe",
+ "deleteEntryTimeNote",
+ "updateEntryMediaPromptAction",
+ "updateEntryFacet",
+ "updateCaseText",
+ "updateCaseTitle",
+ "updateEntryCustomLabels"
+ ]) {
+ const start = background.indexOf(`async function ${name}(`);
+ const end = background.indexOf("\nasync function ", start + 1);
+ assert.ok(start >= 0 && end > start, `${name} should exist`);
+ assert.match(background.slice(start, end), /touchEntr(?:y|ies)\(/, `${name} should touch user-visible update time`);
+ }
+ assert.match(background, /function touchEntry\(entry, updatedAt = new Date\(\)\.toISOString\(\)\)/);
+});
+
+test("project membership changes touch cases but pure project ordering does not", () => {
+ const batch = functionBlock("batchSetProject", "updateOrganizer");
+ assert.match(batch, /changedProjectEntryIds\(beforeOrganizer, organizerState\)/);
+ assert.match(batch, /touchEntries\(state\.entries, changedEntryIds\)/);
+
+ const helperStart = background.indexOf("function changedProjectEntryIds(");
+ const helperEnd = background.indexOf("\nfunction requireAnalysisBatch", helperStart);
+ const helper = background.slice(helperStart, helperEnd);
+ assert.match(helper, /collection\.entryIds/);
+ assert.doesNotMatch(helper, /collection\.order/);
+});
diff --git a/test/organizer.test.js b/test/organizer.test.js
index 8d6d264..cfa8ee7 100644
--- a/test/organizer.test.js
+++ b/test/organizer.test.js
@@ -8,6 +8,7 @@ import {
mergeOrganizerState,
normalizeOrganizerState,
planCollectionAndEntriesDeletion,
+ reorderCollections,
removeEntriesFromOrganizer,
replaceCollectionEntries,
renameCollection,
@@ -51,6 +52,20 @@ test("organizer merge remaps entry ids and merges same-name collections", () =>
assert.deepEqual(merged.collections[0].entryIds, ["local", "imported"]);
});
+test("receiver-local project creation time is assigned only to newly imported projects", () => {
+ const merged = mergeOrganizerState({
+ collections: [{ id: "existing", name: "已有", order: 0, entryIds: ["one"], createdAt: "2026-01-01T00:00:00.000Z" }]
+ }, {
+ collections: [
+ { id: "same-name", name: "已有", order: 0, entryIds: ["two"] },
+ { id: "new", name: "新项目", order: 1, entryIds: ["three"], createdAt: "2025-01-01T00:00:00.000Z" }
+ ]
+ }, { two: "two", three: "three" }, { createdAt: "2026-08-22T00:00:00.000Z" });
+
+ assert.equal(merged.collections[0].createdAt, "2026-01-01T00:00:00.000Z");
+ assert.equal(merged.collections[1].createdAt, "2026-08-22T00:00:00.000Z");
+});
+
test("removing a case also removes private organizer references", () => {
const state = removeEntriesFromOrganizer({
collections: [{ id: "collection:a", name: "A", entryIds: ["one", "two"] }]
@@ -76,7 +91,7 @@ test("project and entries deletion is planned atomically and removes shared proj
assert.deepEqual(result.organizerState.collections, [{
id: "collection:keep",
name: "保留项目",
- order: 1,
+ order: 0,
entryIds: ["three"],
visibility: COLLECTION_VISIBILITY.library
}]);
@@ -95,6 +110,46 @@ test("project membership can be replaced atomically in visual selection order",
assert.deepEqual(state.collections[0].entryIds, ["keep", "new"]);
});
+test("project order is normalized after deletion so a new project cannot reuse a stale order", () => {
+ const initial = {
+ collections: [
+ { id: "collection:a", name: "A", order: 4, entryIds: [] },
+ { id: "collection:b", name: "B", order: 9, entryIds: [] }
+ ]
+ };
+ const afterDelete = deleteCollection(initial, "collection:a");
+ assert.deepEqual(afterDelete.collections.map((item) => item.order), [0]);
+ const created = createCollection(afterDelete, "C");
+ assert.deepEqual(created.state.collections.map((item) => item.order), [0, 1]);
+ assert.ok(Number.isFinite(Date.parse(created.item.createdAt)));
+});
+
+test("projects can be reordered without changing member order or inventing legacy creation time", () => {
+ const reordered = reorderCollections({
+ collections: [
+ { id: "collection:a", name: "A", order: 0, entryIds: ["one", "two"] },
+ { id: "collection:b", name: "B", order: 1, entryIds: ["three"], createdAt: "2026-08-22T01:02:03.000Z" }
+ ]
+ }, ["collection:b", "collection:a"]);
+ assert.deepEqual(reordered.collections.map((item) => item.id), ["collection:b", "collection:a"]);
+ assert.deepEqual(reordered.collections.map((item) => item.order), [0, 1]);
+ assert.deepEqual(reordered.collections[1].entryIds, ["one", "two"]);
+ assert.equal(Object.hasOwn(reordered.collections[1], "createdAt"), false);
+ assert.equal(reordered.collections[0].createdAt, "2026-08-22T01:02:03.000Z");
+});
+
+test("project reorder rejects stale, incomplete, or duplicate project lists", () => {
+ const state = {
+ collections: [
+ { id: "collection:a", name: "A", entryIds: [] },
+ { id: "collection:b", name: "B", entryIds: [] }
+ ]
+ };
+ assert.throws(() => reorderCollections(state, ["collection:a"]), /刷新后重试/);
+ assert.throws(() => reorderCollections(state, ["collection:a", "collection:a"]), /刷新后重试/);
+ assert.throws(() => reorderCollections(state, ["collection:a", "collection:missing"]), /刷新后重试/);
+});
+
test("project-only cases leave the main library unless another visible project also contains them", () => {
let state = createCollection({}, "字体参考").state;
state = createCollection(state, "当前项目").state;
diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.py
index 0556577..34e1e33 100644
--- a/test/page_capture_e2e.py
+++ b/test/page_capture_e2e.py
@@ -81,7 +81,15 @@ def main() -> None:
run.context.route(f"{FIXTURE_ORIGIN}/**", route_fixture)
collector = run.open_page("collector.html", wait_until="networkidle")
- run.seed_storage(collector, {"schemaVersion": 24, "entries": []})
+ run.seed_storage(collector, {
+ "schemaVersion": 24,
+ "entries": [],
+ "capturePermissionOnboarding": {
+ "version": 1,
+ "acknowledgedAt": "2026-08-22T00:00:00.000Z",
+ "clipboardIncluded": True,
+ },
+ })
fixture = run.context.new_page()
fixture.goto(fixture_url, wait_until="networkidle")
fixture.bring_to_front()
diff --git a/test/preferences.test.js b/test/preferences.test.js
index 5360fc3..a8ec4d6 100644
--- a/test/preferences.test.js
+++ b/test/preferences.test.js
@@ -1,25 +1,35 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { normalizeUiPreferences, resolveLocale } from "../preferences.js";
+import { normalizeSidebarWidth, normalizeUiPreferences, resolveLocale } from "../preferences.js";
test("UI preferences accept only supported locale theme and motion values", () => {
assert.deepEqual(normalizeUiPreferences({ locale: "fr", theme: "neon", motion: "spin" }), {
locale: "system",
theme: "dark",
motion: "system",
- analysisDiagnostics: false
+ analysisDiagnostics: false,
+ sidebarWidth: 244
});
assert.deepEqual(normalizeUiPreferences({ locale: "en", theme: "dark", motion: "none", analysisDiagnostics: true }), {
locale: "en",
theme: "dark",
motion: "reduced",
- analysisDiagnostics: true
+ analysisDiagnostics: true,
+ sidebarWidth: 244
});
assert.equal(normalizeUiPreferences({ theme: "light", motion: "reduced" }).theme, "light");
assert.equal(normalizeUiPreferences({ theme: "system", motion: "reduced" }).theme, "system");
});
+test("sidebar width keeps old preferences compatible and clamps unsafe values", () => {
+ assert.equal(normalizeSidebarWidth(undefined), 244);
+ assert.equal(normalizeSidebarWidth(180), 216);
+ assert.equal(normalizeSidebarWidth(336.4), 336);
+ assert.equal(normalizeSidebarWidth(600), 420);
+ assert.equal(normalizeUiPreferences({ sidebarWidth: 320 }).sidebarWidth, 320);
+});
+
test("system locale resolves Chinese browsers to Chinese and everything else to English", () => {
assert.equal(resolveLocale({ locale: "system" }, "zh-TW"), "zh-CN");
assert.equal(resolveLocale({ locale: "system" }, "en-US"), "en");
diff --git a/test/project-combobox.test.js b/test/project-combobox.test.js
new file mode 100644
index 0000000..108fb49
--- /dev/null
+++ b/test/project-combobox.test.js
@@ -0,0 +1,55 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { projectComboboxOptions, projectComboboxPlacement } from "../project-combobox.js";
+
+test("project combobox exposes existing projects while preserving their real names", () => {
+ assert.deepEqual(projectComboboxOptions([
+ { name: "优质精选" },
+ { name: "AIArtWorks · MJ 精选" }
+ ]), [
+ { value: "优质精选", label: "优质精选" },
+ { value: "AIArtWorks · MJ 精选", label: "AIArtWorks · MJ 精选" }
+ ]);
+});
+
+test("project combobox filters case-insensitively and removes duplicate or empty projects", () => {
+ assert.deepEqual(projectComboboxOptions([
+ { name: " AIArtWorks 精选 " },
+ { name: "aiartworks 精选" },
+ { name: "" },
+ null,
+ { value: "Higgsfield" }
+ ], "AIART"), [
+ { value: "AIArtWorks 精选", label: "AIArtWorks 精选" }
+ ]);
+});
+
+test("project combobox opens toward the side that can contain its options", () => {
+ assert.deepEqual(projectComboboxPlacement({
+ inputTop: 420,
+ inputBottom: 456,
+ boundaryTop: 80,
+ boundaryBottom: 520,
+ contentHeight: 220,
+ gap: 5
+ }), { placement: "top", maxHeight: 335 });
+ assert.deepEqual(projectComboboxPlacement({
+ inputTop: 120,
+ inputBottom: 156,
+ boundaryTop: 80,
+ boundaryBottom: 520,
+ contentHeight: 220,
+ gap: 5
+ }), { placement: "bottom", maxHeight: 359 });
+});
+
+test("project combobox keeps the larger side when neither direction fits fully", () => {
+ assert.deepEqual(projectComboboxPlacement({
+ inputTop: 230,
+ inputBottom: 266,
+ boundaryTop: 100,
+ boundaryBottom: 360,
+ contentHeight: 320,
+ gap: 5
+ }), { placement: "top", maxHeight: 125 });
+});
diff --git a/test/project-deletion-ui.test.js b/test/project-deletion-ui.test.js
index de448e0..7f76bef 100644
--- a/test/project-deletion-ui.test.js
+++ b/test/project-deletion-ui.test.js
@@ -2,24 +2,27 @@ import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
-test("project menu separates deleting only the project from permanently deleting its cases", async () => {
+test("project menu separates archiving only the project from archiving it with its cases", async () => {
const library = await readFile(new URL("../library.js", import.meta.url), "utf8");
- assert.match(library, /"删除项目"/);
- assert.match(library, /"删除项目及全部案例…"/);
+ assert.match(library, /"仅删除项目"/);
+ assert.match(library, /"删除项目及案例"/);
const handlerStart = library.indexOf("async function deleteProjectCollectionWithEntries");
const handlerEnd = library.indexOf("function enterProjectSelection", handlerStart);
const handler = library.slice(handlerStart, handlerEnd);
- assert.match(handler, /请输入完整项目名称以确认/);
+ assert.match(handler, /可从回收站恢复/);
+ assert.match(handler, /confirmAppAction/);
assert.match(handler, /DELETE_COLLECTION_WITH_ENTRIES/);
- assert.match(handler, /confirmationName\.trim\(\) !== collection\.name/);
+ assert.match(handler, /confirmationName: collection\.name/);
+ assert.doesNotMatch(handler, /showAppDialog|永久删除/);
});
-test("permanent project deletion is serialized through the background write queue", async () => {
+test("project and case deletion is serialized and archives all selected content without deleting blobs", async () => {
const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
assert.match(background, /case "DELETE_COLLECTION_WITH_ENTRIES":\s*return enqueue\(async \(\) => deleteCollectionWithEntries\(message\)\)/);
const handlerStart = background.indexOf("async function deleteCollectionWithEntries");
- const handlerEnd = background.indexOf("function enqueue", handlerStart);
+ const handlerEnd = background.indexOf("async function moveEntryBatchToTrash", handlerStart);
const handler = background.slice(handlerStart, handlerEnd);
- assert.match(handler, /commitMetadataThenDeleteImages/);
- assert.match(handler, /deleteImages: deleteMediaBlobs/);
+ assert.match(handler, /moveCollectionWithEntriesToTrash/);
+ assert.match(handler, /STORAGE_KEYS\.trashState/);
+ assert.doesNotMatch(handler, /deleteMediaBlob|deleteMediaBlobs|deleteScreenshotBlob/);
});
diff --git a/test/projects_and_categories_e2e.py b/test/projects_and_categories_e2e.py
index 402409c..f8218dc 100644
--- a/test/projects_and_categories_e2e.py
+++ b/test/projects_and_categories_e2e.py
@@ -20,19 +20,102 @@ def main() -> None:
"entries": [entry, second_entry],
"organizerState": {
"version": 4,
- "collections": [{
- "id": project_id,
- "name": "项目与分类验收",
- "order": 0,
- "entryIds": [entry["id"], second_entry["id"]],
- }],
+ "collections": [
+ {
+ "id": project_id,
+ "name": "项目与分类验收的完整长项目名称",
+ "order": 0,
+ "entryIds": [entry["id"], second_entry["id"]],
+ },
+ {
+ "id": "collection:e2e-extra",
+ "name": "辅助项目",
+ "order": 1,
+ "entryIds": [],
+ },
+ ],
},
},
)
library = session.open_page("library.html", wait_until="networkidle")
+ expect(library.locator(".project-row.project-ordering")).to_have_count(0)
+ long_name = library.locator(".project-filter-name", has_text="完整长项目名称")
+ expect(long_name).to_be_visible()
+ assert long_name.evaluate("node => getComputedStyle(node).whiteSpace") == "normal"
+ library.locator("#manage-project-order").click()
+ expect(library.locator("#manage-project-order")).to_have_attribute("aria-label", "完成项目排序")
+ expect(library.locator(".project-row.project-ordering")).to_have_count(2)
+ assert library.locator(".project-row.project-ordering").first.evaluate("node => getComputedStyle(node).userSelect") == "none"
+ expect(library.locator(".project-row > .project-menu:visible")).to_have_count(0)
+ expect(library.locator(".project-row.project-ordering .project-filter").first).to_have_attribute("tabindex", "-1")
+ source_box = library.locator(".project-row", has_text="辅助项目").bounding_box()
+ target_box = library.locator(".project-row", has_text="项目与分类验收").bounding_box()
+ assert source_box and target_box
+ library.mouse.move(source_box["x"] + source_box["width"] / 2, source_box["y"] + source_box["height"] / 2)
+ library.mouse.down()
+ library.mouse.move(target_box["x"] + target_box["width"] / 2, target_box["y"] + 3, steps=8)
+ library.mouse.up()
+ assert library.evaluate("window.getSelection()?.toString() || ''") == ""
+ expect(library.locator(".project-filter-name").first).to_have_text("辅助项目")
+ library.locator(".project-row", has_text="辅助项目").focus()
+ library.locator(".project-row", has_text="辅助项目").press("ArrowDown")
+ expect(library.locator("#project-order-status")).to_contain_text("辅助项目")
+ expect(library.locator(".project-filter-name").first).to_contain_text("项目与分类验收")
+
+ touch_source = library.locator(".project-row", has_text="辅助项目").bounding_box()
+ touch_target = library.locator(".project-row", has_text="项目与分类验收").bounding_box()
+ assert touch_source and touch_target
+ touch_x = touch_source["x"] + touch_source["width"] / 2
+ touch_row = library.locator(".project-row", has_text="辅助项目")
+ touch_row.dispatch_event("pointerdown", {"pointerId": 71, "pointerType": "touch", "button": 0, "clientX": touch_x, "clientY": touch_source["y"] + touch_source["height"] / 2})
+ touch_row.dispatch_event("pointermove", {"pointerId": 71, "pointerType": "touch", "button": -1, "clientX": touch_x, "clientY": touch_source["y"] - 8})
+ touch_row.dispatch_event("pointermove", {"pointerId": 71, "pointerType": "touch", "button": -1, "clientX": touch_x, "clientY": touch_target["y"] + 3})
+ touch_row.dispatch_event("pointerup", {"pointerId": 71, "pointerType": "touch", "button": 0, "clientX": touch_x, "clientY": touch_target["y"] + 3})
+ expect(library.locator(".project-filter-name").first).to_have_text("辅助项目")
+
+ library.evaluate("""() => {
+ window.__originalProjectSendMessage = chrome.runtime.sendMessage;
+ chrome.runtime.sendMessage = (message, ...rest) => message?.type === 'REORDER_COLLECTIONS'
+ ? Promise.resolve({ok: false, message: '模拟项目排序保存失败'})
+ : window.__originalProjectSendMessage.call(chrome.runtime, message, ...rest);
+ }""")
+ failed_source = library.locator(".project-row", has_text="辅助项目").bounding_box()
+ failed_target = library.locator(".project-row", has_text="项目与分类验收").bounding_box()
+ assert failed_source and failed_target
+ failed_x = failed_source["x"] + failed_source["width"] / 2
+ failed_row = library.locator(".project-row", has_text="辅助项目")
+ failed_row.dispatch_event("pointerdown", {"pointerId": 72, "pointerType": "mouse", "button": 0, "clientX": failed_x, "clientY": failed_source["y"] + failed_source["height"] / 2})
+ failed_row.dispatch_event("pointermove", {"pointerId": 72, "pointerType": "mouse", "button": -1, "clientX": failed_x, "clientY": failed_target["y"] + failed_target["height"] - 2})
+ failed_row.dispatch_event("pointerup", {"pointerId": 72, "pointerType": "mouse", "button": 0, "clientX": failed_x, "clientY": failed_target["y"] + failed_target["height"] - 2})
+ expect(library.locator("#feedback")).to_contain_text("模拟项目排序保存失败")
+ expect(library.locator(".project-filter-name").first).to_have_text("辅助项目")
+ library.evaluate("""() => { chrome.runtime.sendMessage = window.__originalProjectSendMessage; }""")
+ library.locator("#manage-project-order").click()
+ expect(library.locator(".project-row.project-ordering")).to_have_count(0)
+ expect(library.locator(".project-row > .project-menu:visible")).to_have_count(2)
+
+ library.locator(".project-filter", has_text="项目与分类验收").click()
+ expect(library.locator("#manage-case-order")).to_be_visible()
+ library.locator("#gallery-sort").select_option("project-manual")
+ expect(library.locator(".case-reorder-controls:visible")).to_have_count(0)
+ library.locator("#manage-case-order").click()
+ expect(library.locator("#manage-case-order")).to_have_attribute("aria-label", "完成案例排序")
+ expect(library.locator(".case-reorder-controls:visible")).to_have_count(2)
+ library.locator(f".case-card[data-entry-id='{second_entry['id']}'] .case-move-up").click()
+ library.locator("#manage-case-order").click()
+ expect(library.locator(".case-reorder-controls:visible")).to_have_count(0)
+ order = library.evaluate(
+ "async (id) => (await chrome.storage.local.get('organizerState')).organizerState.collections.find(item => item.id === id).entryIds",
+ project_id,
+ )
+ assert order == [second_entry["id"], entry["id"]], order
+
library.locator("#search-input").fill("project-case")
expect(library.locator(".case-card")).to_have_count(2)
library.locator("#select-cases").click()
+ expect(library.locator("#manage-project-order")).to_be_visible()
+ expect(library.locator("#manage-project-order")).to_be_disabled()
+ expect(library.locator("#manage-project-order")).to_have_attribute("title", "结束案例选择后可排序项目")
library.locator(".case-card").nth(0).click()
library.locator(".case-card").nth(1).click()
library.locator("#selection-combine").click()
@@ -98,7 +181,7 @@ def main() -> None:
assert transferred == {"pathIds": ["content:prompt:image"], "deleted": True}
library.locator("#manager-close").click()
- expect(library.locator("#collection-filters")).to_contain_text("项目与分类验收")
+ expect(library.locator("#collection-filters")).to_contain_text("项目与分类验收的完整长项目名称")
page_count = len(session.context.pages)
library.locator("#open-skills").click()
expect(library).to_have_url(re.compile(r"skills\.html"))
diff --git a/test/resource-limits.test.js b/test/resource-limits.test.js
new file mode 100644
index 0000000..ac36d32
--- /dev/null
+++ b/test/resource-limits.test.js
@@ -0,0 +1,32 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ ASSET_IMPORT_FAILURE_CODES,
+ assetImportError,
+ importFailureDetails
+} from "../resource-limits.js";
+
+test("asset import failures expose a serializable reason for the UI and background job", () => {
+ const error = assetImportError(
+ ASSET_IMPORT_FAILURE_CODES.TOO_LARGE,
+ "文件超过默认上限",
+ { actualBytes: 20, maxBytes: 10, forceAllowed: true, ignored: "private" }
+ );
+
+ assert.deepEqual(importFailureDetails(error), {
+ code: "too_large",
+ message: "文件超过默认上限",
+ forceAllowed: true,
+ actualBytes: 20,
+ maxBytes: 10
+ });
+});
+
+test("unknown runtime errors become non-forceable read failures", () => {
+ assert.deepEqual(importFailureDetails(new Error("decoder stopped")), {
+ code: "read_or_decode_failed",
+ message: "decoder stopped",
+ forceAllowed: false
+ });
+});
diff --git a/test/run_e2e.py b/test/run_e2e.py
index bd799ba..719002f 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -46,6 +46,7 @@ SCRIPTS = [
"library-thumbnail-rebind-e2e.py",
"creative_feedback_e2e.py",
"ui_foundation_e2e.py",
+ "material_management_regressions_e2e.py",
"ui_regressions_e2e.py",
"settings_visual_anchor_e2e.py",
]
diff --git a/test/settings_visual_anchor_e2e.py b/test/settings_visual_anchor_e2e.py
index ca3359b..a1efe9c 100644
--- a/test/settings_visual_anchor_e2e.py
+++ b/test/settings_visual_anchor_e2e.py
@@ -73,6 +73,16 @@ def exercise_settings(page, viewport: dict) -> None:
settle(page)
assert_anchor_stable(baseline, settings_metrics(page), f"settings:{tab}", viewport)
+ page.locator('[data-settings-tab="tasks"]').click()
+ local_index = page.locator(".local-index-card")
+ expect(local_index).to_contain_text("补全资料索引")
+ expect(local_index).to_contain_text("全程在本机运行,不调用 AI")
+ expect(local_index.locator("progress")).to_have_count(0)
+ expect(local_index.locator("#apply-reanalyze")).to_be_hidden()
+ page.locator("#preview-reanalyze").click()
+ expect(page.locator("#reanalyze-preview")).to_contain_text("资料索引已完整")
+ expect(local_index.locator("#apply-reanalyze")).to_be_hidden()
+
page.locator('[data-settings-tab="ai"]').click()
advanced_summary = page.locator(".ai-advanced-settings > summary")
advanced_summary.scroll_into_view_if_needed()
diff --git a/test/share-preview.test.js b/test/share-preview.test.js
index 01f84eb..877e60f 100644
--- a/test/share-preview.test.js
+++ b/test/share-preview.test.js
@@ -102,15 +102,25 @@ test("share preview renders every portable media kind and its time notes", () =>
{ id: "image", kind: "image", storageMode: "managed", mimeType: "image/webp", assetPath: "images/mixed/image.webp", width: 800, height: 1200 },
{ id: "video", kind: "video", storageMode: "managed", mimeType: "video/mp4", assetPath: "videos/mixed/video.mp4", posterAssetId: "poster" },
{ id: "poster", kind: "image", usage: "poster", storageMode: "managed", mimeType: "image/webp", assetPath: "images/mixed/poster.webp", derivedFromAssetId: "video" },
- { id: "document", kind: "document", storageMode: "managed", mimeType: "application/pdf", assetPath: "documents/mixed/brief.pdf", sourceTitle: "Brief" }
+ { id: "audio", kind: "audio", storageMode: "managed", mimeType: "audio/mpeg", sourceFormat: "mp3", byteSize: 5242880, assetPath: "audio/mixed/theme.mp3", sourceTitle: "Theme.mp3" },
+ { id: "document", kind: "document", storageMode: "managed", mimeType: "application/x-subrip", sourceFormat: "srt", byteSize: 2048, assetPath: "documents/mixed/subtitle.srt", sourceTitle: "Subtitle.srt" },
+ { id: "source", kind: "attachment", storageMode: "managed", mimeType: "image/vnd.adobe.photoshop", sourceFormat: "psd", byteSize: 10485760, assetPath: "attachments/mixed/artwork.psd", sourceTitle: "Artwork.psd" },
+ { id: "font", kind: "attachment", storageMode: "managed", mimeType: "font/otf", sourceFormat: "otf", byteSize: 4096, assetPath: "attachments/mixed/typeface.otf", sourceTitle: "Typeface.otf" }
],
primaryMediaId: "video",
timeNotes: [{ id: "note", assetId: "video", startMs: 1250, endMs: 3400, text: "镜头加速" }]
}], { libraryTitle: "Archive" }, createDefaultTaxonomy(), createDefaultFacetCatalog(), previewOptions);
assert.match(html, /<video controls preload="metadata" poster="images\/mixed\/poster\.webp">/);
- assert.match(html, /documents\/mixed\/brief\.pdf/);
- assert.match(html, /打开文档/);
+ assert.match(html, /<audio controls preload="metadata">/);
+ assert.match(html, /audio\/mixed\/theme\.mp3/);
+ assert.match(html, /documents\/mixed\/subtitle\.srt/);
+ assert.match(html, /attachments\/mixed\/artwork\.psd/);
+ assert.match(html, /attachments\/mixed\/typeface\.otf/);
+ assert.match(html, /SRT · 2 KiB/);
+ assert.match(html, /PSD · 10\.0 MiB/);
+ assert.match(html, /下载源文件/);
+ assert.match(html, /href="attachments\/mixed\/artwork\.psd" download/);
assert.match(html, /时间笔记/);
assert.match(html, /0:01–0:03/);
assert.match(html, /镜头加速/);
diff --git a/test/sharing_and_data_safety_e2e.py b/test/sharing_and_data_safety_e2e.py
index 6c7f813..82028bf 100644
--- a/test/sharing_and_data_safety_e2e.py
+++ b/test/sharing_and_data_safety_e2e.py
@@ -65,7 +65,7 @@ def main() -> None:
expect(library.locator("#share-bar")).to_be_visible()
library.locator(".case-card").nth(0).click()
library.locator(".case-card").nth(1).click()
- expect(library.locator("#share-count")).to_have_text("已选择 2 个案例")
+ expect(library.locator("#share-count")).to_have_text("已选 2")
library.locator("#share-export").click()
expect(library.locator("#share-dialog")).to_be_visible()
expect(library.locator("#share-dialog-submit")).to_be_disabled()
diff --git a/test/sync-model.test.js b/test/sync-model.test.js
index e8c602c..3741ac3 100644
--- a/test/sync-model.test.js
+++ b/test/sync-model.test.js
@@ -109,6 +109,100 @@ test("temporary composer references keep encrypted media through private sync",
assert.deepEqual(merged.imageRefs["temp-reference-asset:one"], { objectId, contentType: "image/webp" });
});
+test("trashed entries sync as trash records without becoming active entries", async () => {
+ const source = state();
+ source.trashState.items.push(trashItem({
+ id: "trash:entry:case:one",
+ kind: "entry",
+ targetId: "case:one",
+ snapshot: entry("case:one", "已删除案例")
+ }));
+
+ const snapshot = await createRevisionSnapshot(source, { deviceId: "device-a", logicalClock: 1 });
+ const merged = mergeRevisionSnapshots([snapshot]);
+
+ assert.equal(snapshot.version, 1);
+ assert.equal(merged.state.entries.length, 0);
+ assert.equal(merged.state.trashState.items.length, 1);
+ assert.equal(merged.state.trashState.items[0].snapshot.id, "case:one");
+ assert.equal(syncStateHasContent(merged.state), true);
+});
+
+test("managed assets inside entry and media trash snapshots keep their encrypted sync references", async () => {
+ const entryObjectId = "e".repeat(64);
+ const mediaObjectId = "f".repeat(64);
+ const source = state();
+ source.trashState.items.push(
+ trashItem({
+ id: "trash:entry:case:one",
+ kind: "entry",
+ targetId: "case:one",
+ snapshot: {
+ ...entry("case:one", "已删除案例"),
+ mediaAssets: [{ id: "asset:entry", kind: "image", storageMode: "managed", mimeType: "image/webp" }]
+ }
+ }),
+ trashItem({
+ id: "trash:media:case:two:asset:media",
+ kind: "media",
+ targetId: "asset:media",
+ snapshot: {
+ mediaAssets: [{ id: "asset:media", kind: "video", storageMode: "managed", mimeType: "video/mp4" }]
+ }
+ })
+ );
+ const attached = attachSyncImageReferences(source, {
+ "asset:entry": { objectId: entryObjectId, contentType: "image/webp" },
+ "asset:media": { objectId: mediaObjectId, contentType: "video/mp4" }
+ });
+
+ assert.equal(attached.trashState.items[0].snapshot.mediaAssets[0].syncObjectId, entryObjectId);
+ assert.equal(attached.trashState.items[1].snapshot.mediaAssets[0].syncObjectId, mediaObjectId);
+ assert.deepEqual(collectSyncImageReferences(attached), {
+ "asset:entry": { objectId: entryObjectId, contentType: "image/webp" },
+ "asset:media": { objectId: mediaObjectId, contentType: "video/mp4" }
+ });
+
+ const snapshot = await createRevisionSnapshot(attached, { deviceId: "device-a", logicalClock: 1 });
+ const merged = mergeRevisionSnapshots([snapshot]);
+ assert.equal(merged.state.entries.length, 0);
+ assert.equal(merged.state.trashState.items.length, 2);
+ assert.deepEqual(merged.imageRefs, {
+ "asset:entry": { objectId: entryObjectId, contentType: "image/webp" },
+ "asset:media": { objectId: mediaObjectId, contentType: "video/mp4" }
+ });
+});
+
+test("emptying trash wins over a concurrent trash edit without resurrecting the item", async () => {
+ const baseState = state();
+ baseState.trashState.items.push(trashItem({
+ id: "trash:entry:case:one",
+ kind: "entry",
+ targetId: "case:one",
+ snapshot: entry("case:one", "base")
+ }));
+ const base = await createRevisionSnapshot(baseState, { deviceId: "device-a", logicalClock: 1 });
+ const emptied = await createRevisionSnapshot(state(), {
+ deviceId: "device-a",
+ logicalClock: 2,
+ baseSnapshot: base
+ });
+ const editedState = structuredClone(baseState);
+ editedState.trashState.items[0].snapshot.title = "concurrent edit";
+ const edited = await createRevisionSnapshot(editedState, {
+ deviceId: "device-b",
+ logicalClock: 2,
+ baseSnapshot: base
+ });
+
+ const merged = mergeRevisionSnapshots([base, emptied, edited]);
+ assert.equal(merged.state.entries.length, 0);
+ assert.equal(merged.state.trashState.items.length, 0);
+ assert.deepEqual(merged.conflicts.map(({ entityType, reason }) => ({ entityType, reason })), [
+ { entityType: "trash_item", reason: "delete_edit" }
+ ]);
+});
+
function state(entries = [], collections = [], compoundCases = []) {
return {
entries,
@@ -119,7 +213,19 @@ function state(entries = [], collections = [], compoundCases = []) {
classificationRules: [],
composerSessions: [],
creativeRuns: [],
- creativeSkills: { version: 1, items: [] }
+ creativeSkills: { version: 1, items: [] },
+ trashState: { version: 1, items: [] }
+ };
+}
+
+function trashItem({ id, kind, targetId, snapshot }) {
+ return {
+ id,
+ kind,
+ targetId,
+ deletedAt: "2026-08-22T00:00:00.000Z",
+ snapshot,
+ relationships: {}
};
}
diff --git a/test/tag-editor.test.js b/test/tag-editor.test.js
new file mode 100644
index 0000000..f13fc83
--- /dev/null
+++ b/test/tag-editor.test.js
@@ -0,0 +1,15 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { addTagValues, normalizeTagValue, normalizeTagValues, splitTagInput } from "../tag-editor.js";
+
+test("tag values support multiple Chinese and English separators without duplicates", () => {
+ assert.deepEqual(splitTagInput("参考,构图,夜景\n客户喜欢"), ["参考", "构图", "夜景", "客户喜欢"]);
+ assert.deepEqual(normalizeTagValues(splitTagInput("参考, 参考,夜景, NIGHT, night")), ["参考", "夜景", "NIGHT"]);
+ assert.deepEqual(addTagValues(["参考"], ["夜景", "参考", "待复刻"]), ["参考", "夜景", "待复刻"]);
+});
+
+test("tag normalization removes control characters and empty separators", () => {
+ assert.equal(normalizeTagValue(" , 客户\u0000 喜欢; "), "客户 喜欢");
+ assert.deepEqual(normalizeTagValues(["", ",", " "]), []);
+});
diff --git a/test/transient-menu.test.js b/test/transient-menu.test.js
index a588fd0..c871243 100644
--- a/test/transient-menu.test.js
+++ b/test/transient-menu.test.js
@@ -13,7 +13,7 @@ test("transient menus share outside-click, action, peer-open, and Escape dismiss
assert.match(source, /event\.key !== "Escape"/);
assert.match(source, /closest\("button, a\[href\]"\)/);
assert.match(source, /!action\.closest\("\.package-preferences"\)/);
- assert.match(library, /bindTransientMenus\(document, "\.package-menu, \.project-menu, \.detail-analysis-menu"\)/);
+ assert.match(library, /bindTransientMenus\(document, "\.package-menu, \.project-menu, \.detail-analysis-menu, \.detail-project-menu"\)/);
assert.match(composer, /bindTransientMenus\(document, "\.composer-options"\)/);
assert.doesNotMatch(composer, /\.composer-result-more/);
});
diff --git a/test/trash-background.test.js b/test/trash-background.test.js
new file mode 100644
index 0000000..392ac40
--- /dev/null
+++ b/test/trash-background.test.js
@@ -0,0 +1,54 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const background = await readFile(new URL("../background.js", import.meta.url), "utf8");
+
+function functionBlock(name, nextName) {
+ const start = background.indexOf(`async function ${name}(`);
+ const end = background.indexOf(`async function ${nextName}(`, start + 1);
+ assert.ok(start >= 0, `${name} should exist`);
+ assert.ok(end > start, `${nextName} should follow ${name}`);
+ return background.slice(start, end);
+}
+
+test("all user-facing case, media, and project deletion routes move metadata to trash", () => {
+ assert.match(background, /case "DELETE_ENTRY":\s*return enqueue\(async \(\) => deleteEntry\(message\.entryId\)\)/);
+ assert.match(background, /case "BATCH_MOVE_TO_TRASH":\s*return enqueue\(async \(\) => moveEntryBatchToTrash\(message\.entryIds\)\)/);
+ assert.match(background, /case "DELETE_ENTRY_MEDIA":\s*return enqueue\(async \(\) => deleteEntryMedia/);
+ assert.match(background, /case "DELETE_ENTRY_VISUAL":\s*return enqueue\(async \(\) => deleteEntryVisual/);
+ assert.match(background, /case "DELETE_COLLECTION_WITH_ENTRIES":\s*return enqueue\(async \(\) => deleteCollectionWithEntries/);
+
+ const caseDeletion = functionBlock("deleteEntry", "deleteCollectionWithEntries");
+ assert.match(caseDeletion, /moveEntryBatchToTrash/);
+ assert.doesNotMatch(caseDeletion, /deleteMediaBlob|deleteScreenshotBlob/);
+ const mediaDeletion = functionBlock("moveEntryMediaToTrash", "addUploadedMedia");
+ assert.match(mediaDeletion, /moveMediaToTrash/);
+ assert.doesNotMatch(mediaDeletion, /deleteMediaBlob|deleteScreenshotBlob/);
+ const projectDeletion = functionBlock("deleteCollectionWithEntries", "moveEntryBatchToTrash");
+ assert.match(projectDeletion, /moveCollectionWithEntriesToTrash/);
+ assert.doesNotMatch(projectDeletion, /deleteMediaBlob|deleteScreenshotBlob/);
+});
+
+test("trash restore and irreversible cleanup have separate explicit message contracts", () => {
+ for (const type of ["GET_TRASH_ITEMS", "RESTORE_TRASH_ITEMS", "PERMANENT_DELETE_TRASH_ITEMS", "EMPTY_TRASH"]) {
+ assert.match(background, new RegExp(`case "${type}"`));
+ }
+ const cleanup = functionBlock("commitTrashCleanup", "restrictLocalStorageAccess");
+ assert.match(cleanup, /commitMetadataThenDeleteImages/);
+ assert.match(cleanup, /deleteMediaBlobs/);
+ assert.match(cleanup, /screenshotStorageKey/);
+ assert.match(cleanup, /永久删除/);
+});
+
+test("free-label and project batch actions are wired with additive and move modes", () => {
+ for (const type of ["UPDATE_ENTRY_CUSTOM_LABELS", "BATCH_ADD_CUSTOM_LABELS", "BATCH_SET_PROJECT"]) {
+ assert.match(background, new RegExp(`case "${type}"`));
+ }
+ const labels = functionBlock("updateEntryCustomLabels", "batchAddCustomLabels");
+ assert.match(labels, /customLabels/);
+ const projects = functionBlock("batchSetProject", "updateOrganizer");
+ assert.match(projects, /message\.mode === "move"/);
+ assert.match(projects, /removeEntriesFromOrganizer/);
+ assert.match(projects, /setEntriesCollection/);
+});
diff --git a/test/trash.test.js b/test/trash.test.js
new file mode 100644
index 0000000..f1816bb
--- /dev/null
+++ b/test/trash.test.js
@@ -0,0 +1,368 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ TRASH_VERSION,
+ createDefaultTrashState,
+ emptyTrash,
+ listTrashItems,
+ moveCollectionsToTrash,
+ moveCollectionWithEntriesToTrash,
+ moveEntriesToTrash,
+ moveMediaToTrash,
+ normalizeTrashState,
+ restoreTrashItems,
+ takeTrashItems
+} from "../trash.js";
+
+test("trash state normalizes serializable items and valid deletion times", () => {
+ assert.deepEqual(createDefaultTrashState(), { version: TRASH_VERSION, items: [] });
+ const normalized = normalizeTrashState({
+ version: 0,
+ items: [
+ {
+ id: "trash:entry:one",
+ kind: "entry",
+ targetId: "one",
+ deletedAt: "2026-08-22T08:00:00+08:00",
+ snapshot: { id: "one", customLabels: ["喜欢"] },
+ relationships: { collections: [{ id: "collection:a", index: 2 }] },
+ ignored: () => true
+ },
+ { id: "trash:broken", kind: "entry", targetId: "", deletedAt: "not-a-date" }
+ ]
+ });
+
+ assert.deepEqual(normalized, {
+ version: TRASH_VERSION,
+ items: [{
+ id: "trash:entry:one",
+ kind: "entry",
+ targetId: "one",
+ deletedAt: "2026-08-22T00:00:00.000Z",
+ snapshot: { id: "one", customLabels: ["喜欢"] },
+ relationships: { collections: [{ id: "collection:a", index: 2 }] }
+ }]
+ });
+ assert.doesNotThrow(() => JSON.stringify(normalized));
+});
+
+test("listing and permanently taking trash items is pure and returns an explicit physical cleanup plan", () => {
+ const state = normalizeTrashState({
+ items: [
+ {
+ id: "trash:entry:one", kind: "entry", targetId: "one", deletedAt: "2026-08-21T00:00:00Z",
+ snapshot: {
+ id: "one",
+ mediaAssets: [
+ { id: "managed:image", storageMode: "managed" },
+ { id: "linked:video", storageMode: "reference" }
+ ]
+ },
+ relationships: {}
+ },
+ {
+ id: "trash:media:one:image:second", kind: "media", targetId: "image:second", deletedAt: "2026-08-22T00:00:00Z",
+ snapshot: { mediaAssets: [{ id: "image:second", storageMode: "managed" }] },
+ relationships: { entryId: "one" }
+ },
+ {
+ id: "trash:collection:a", kind: "collection", targetId: "a", deletedAt: "2026-08-20T00:00:00Z",
+ snapshot: { id: "a", name: "A" }, relationships: {}
+ }
+ ]
+ });
+ const before = structuredClone(state);
+
+ assert.deepEqual(listTrashItems(state).map((item) => item.kind), ["media", "entry", "collection"]);
+ assert.deepEqual(listTrashItems(state, { kind: "entry" }).map((item) => item.targetId), ["one"]);
+ const taken = takeTrashItems(state, ["trash:entry:one", "trash:media:one:image:second"]);
+ assert.deepEqual(state, before);
+ assert.deepEqual(taken.trashState.items.map((item) => item.kind), ["collection"]);
+ assert.deepEqual(taken.cleanup, {
+ entryIds: ["one"],
+ collectionIds: [],
+ mediaIds: ["managed:image", "image:second"],
+ screenshotEntryIds: ["one"]
+ });
+
+ const emptied = emptyTrash(state);
+ assert.deepEqual(emptied.trashState, createDefaultTrashState());
+ assert.deepEqual(emptied.cleanup.collectionIds, ["a"]);
+ assert.equal(emptied.takenItems.length, 3);
+});
+
+test("restoring a case recreates its project positions and does not duplicate labels", () => {
+ const moved = moveEntriesToTrash({
+ trashState: {},
+ entries: [{ id: "one", title: "案例一", customLabels: ["喜欢"] }, { id: "two" }],
+ organizerState: {
+ collections: [{ id: "collection:a", name: "A", entryIds: ["one", "two"] }]
+ }
+ }, ["one"], { deletedAt: "2026-08-22T04:00:00Z" });
+ const restored = restoreTrashItems(moved, ["trash:entry:one"]);
+
+ assert.deepEqual(restored.entries.find((entry) => entry.id === "one"), {
+ id: "one", title: "案例一", customLabels: ["喜欢"]
+ });
+ assert.deepEqual(restored.organizerState.collections[0].entryIds, ["one", "two"]);
+ assert.deepEqual(restored.trashState.items, []);
+ assert.deepEqual(restored.restoredItemIds, ["trash:entry:one"]);
+ assert.deepEqual(restored.unresolved, []);
+});
+
+test("project restoration waits for missing members but can restore a project and its trashed case together", () => {
+ const trashState = {
+ items: [
+ {
+ id: "trash:collection:project", kind: "collection", targetId: "project", deletedAt: "2026-08-22T00:00:00Z",
+ snapshot: { id: "project", name: "项目", order: 0, entryIds: ["one"] }, relationships: {}
+ },
+ {
+ id: "trash:entry:one", kind: "entry", targetId: "one", deletedAt: "2026-08-22T00:01:00Z",
+ snapshot: { id: "one", title: "案例" }, relationships: { collections: [] }
+ }
+ ]
+ };
+ const partial = restoreTrashItems({ trashState, entries: [], organizerState: {} }, ["trash:collection:project"]);
+ assert.deepEqual(partial.organizerState.collections, []);
+ assert.deepEqual(partial.unresolved[0].missingEntryIds, ["one"]);
+ assert.equal(partial.trashState.items.length, 2);
+
+ const together = restoreTrashItems(
+ { trashState, entries: [], organizerState: {} },
+ ["trash:collection:project", "trash:entry:one"]
+ );
+ assert.deepEqual(together.entries, [{ id: "one", title: "案例" }]);
+ assert.deepEqual(together.organizerState.collections[0].entryIds, ["one"]);
+ assert.deepEqual(together.trashState.items, []);
+});
+
+test("restore keeps unresolved items when a relationship is missing or a live id has different content", () => {
+ const missingProject = restoreTrashItems({
+ entries: [],
+ organizerState: { collections: [] },
+ trashState: {
+ items: [{
+ id: "trash:entry:one", kind: "entry", targetId: "one", deletedAt: "2026-08-22T00:00:00Z",
+ snapshot: { id: "one", title: "已删除" },
+ relationships: { collections: [{ id: "collection:gone", index: 0 }] }
+ }]
+ }
+ }, ["trash:entry:one"]);
+ assert.equal(missingProject.entries.length, 0);
+ assert.equal(missingProject.trashState.items.length, 1);
+ assert.deepEqual(missingProject.unresolved[0].missingCollectionIds, ["collection:gone"]);
+
+ const collision = restoreTrashItems({
+ ...missingProject,
+ entries: [{ id: "one", title: "当前不同内容" }]
+ }, ["trash:entry:one"], { collectionReplacements: { "collection:gone": [] } });
+ assert.equal(collision.entries[0].title, "当前不同内容");
+ assert.equal(collision.trashState.items.length, 1);
+ assert.match(collision.unresolved[0].reason, /同编号/);
+});
+
+test("restoring media returns its original relationships when the case has not changed incompatibly", () => {
+ const source = {
+ id: "case:one",
+ mediaAssets: [
+ { id: "video:one", kind: "video", storageMode: "managed", mimeType: "video/mp4", capturedAt: "2026-08-20T00:00:00Z" },
+ { id: "image:keep", kind: "image", storageMode: "managed", mimeType: "image/webp", capturedAt: "2026-08-20T00:00:00Z" }
+ ],
+ primaryMediaId: "video:one",
+ timeNotes: [{ id: "note:one", assetId: "video:one", startMs: 100, text: "动作", createdAt: "2026-08-20T00:01:00Z" }],
+ articleDocument: { version: 1, blocks: [{ id: "video", kind: "video", assetId: "video:one", sourceOrder: 0 }] }
+ };
+ const moved = moveMediaToTrash({ entries: [source], trashState: {} }, "case:one", ["video:one"], {
+ deletedAt: "2026-08-22T05:00:00Z"
+ });
+ const restored = restoreTrashItems(moved, moved.movedItemIds);
+
+ assert.deepEqual(restored.entries[0].mediaAssets.map((asset) => asset.id), ["video:one", "image:keep"]);
+ assert.equal(restored.entries[0].primaryMediaId, "video:one");
+ assert.equal(restored.entries[0].timeNotes[0].id, "note:one");
+ assert.equal(restored.entries[0].articleDocument.blocks[0].assetId, "video:one");
+ assert.deepEqual(restored.trashState.items, []);
+});
+
+test("moving media to trash keeps its poster and case-local relationships without deleting blobs", () => {
+ const entry = {
+ id: "case:video",
+ title: "视频案例",
+ mediaAssets: [
+ {
+ id: "video:one", kind: "video", storageMode: "managed", mimeType: "video/mp4",
+ posterAssetId: "poster:one", capturedAt: "2026-08-20T00:00:00Z"
+ },
+ {
+ id: "poster:one", kind: "image", usage: "poster", storageMode: "managed", mimeType: "image/webp",
+ derivedFromAssetId: "video:one", capturedAt: "2026-08-20T00:00:00Z"
+ },
+ { id: "image:keep", kind: "image", storageMode: "managed", mimeType: "image/webp", capturedAt: "2026-08-20T00:00:00Z" }
+ ],
+ primaryMediaId: "video:one",
+ timeNotes: [{ id: "note:one", assetId: "video:one", startMs: 1000, text: "转场", createdAt: "2026-08-20T00:01:00Z" }],
+ videoAnalyses: [{ id: "analysis:one", assetId: "video:one", text: "分析", createdAt: "2026-08-20T00:02:00Z" }],
+ articleDocument: {
+ version: 1,
+ blocks: [
+ { id: "text", kind: "paragraph", text: "正文", sourceOrder: 0 },
+ { id: "video", kind: "video", assetId: "video:one", sourceOrder: 1 }
+ ]
+ }
+ };
+ const moved = moveMediaToTrash({ trashState: {}, entries: [entry] }, "case:video", ["video:one"], {
+ deletedAt: "2026-08-22T03:00:00Z"
+ });
+
+ assert.deepEqual(moved.entries[0].mediaAssets.map((asset) => asset.id), ["image:keep"]);
+ assert.deepEqual(moved.entries[0].timeNotes, []);
+ assert.deepEqual(moved.entries[0].videoAnalyses, []);
+ assert.deepEqual(moved.entries[0].articleDocument.blocks.map((block) => block.id), ["text"]);
+ assert.deepEqual(moved.trashState.items[0].snapshot.mediaAssets.map((asset) => asset.id), ["video:one", "poster:one"]);
+ assert.deepEqual(moved.trashState.items[0].relationships.positions, [
+ { id: "video:one", index: 0 },
+ { id: "poster:one", index: 1 }
+ ]);
+ assert.equal(moved.trashState.items[0].relationships.entryId, "case:video");
+ assert.equal(moved.trashState.items[0].relationships.primaryMediaId, "video:one");
+ assert.deepEqual(moved.pendingBlobDeletes, []);
+});
+
+test("moving a project to trash leaves its member cases active", () => {
+ const moved = moveCollectionsToTrash({
+ trashState: {},
+ entries: [{ id: "one" }, { id: "two" }],
+ organizerState: {
+ collections: [
+ { id: "collection:a", name: "项目 A", order: 0, entryIds: ["one", "two"] },
+ { id: "collection:b", name: "项目 B", order: 1, entryIds: ["two"] }
+ ]
+ }
+ }, ["collection:a"], { deletedAt: "2026-08-22T02:00:00Z" });
+
+ assert.deepEqual(moved.entries, [{ id: "one" }, { id: "two" }]);
+ assert.deepEqual(moved.organizerState.collections.map((item) => item.id), ["collection:b"]);
+ assert.deepEqual(moved.trashState.items[0], {
+ id: "trash:collection:collection:a",
+ kind: "collection",
+ targetId: "collection:a",
+ deletedAt: "2026-08-22T02:00:00.000Z",
+ snapshot: {
+ id: "collection:a",
+ name: "项目 A",
+ order: 0,
+ entryIds: ["one", "two"],
+ visibility: "library"
+ },
+ relationships: {}
+ });
+});
+
+test("moving a case to trash keeps its labels and exact project memberships without ghost references", () => {
+ const source = {
+ trashState: createDefaultTrashState(),
+ entries: [
+ { id: "one", title: "案例一", customLabels: ["老板喜欢", "第二版"] },
+ { id: "two", title: "案例二", customLabels: [] }
+ ],
+ organizerState: {
+ version: 6,
+ collections: [
+ { id: "collection:a", name: "A", order: 0, entryIds: ["two", "one"] },
+ { id: "collection:b", name: "B", order: 1, entryIds: ["one"] }
+ ]
+ }
+ };
+
+ const moved = moveEntriesToTrash(source, ["one", "one", "missing"], {
+ deletedAt: "2026-08-22T09:30:00+08:00"
+ });
+ assert.deepEqual(moved.entries.map((entry) => entry.id), ["two"]);
+ assert.deepEqual(moved.organizerState.collections.map((collection) => collection.entryIds), [["two"], []]);
+ assert.deepEqual(moved.movedItemIds, ["trash:entry:one"]);
+ assert.deepEqual(moved.trashState.items[0], {
+ id: "trash:entry:one",
+ kind: "entry",
+ targetId: "one",
+ deletedAt: "2026-08-22T01:30:00.000Z",
+ snapshot: { id: "one", title: "案例一", customLabels: ["老板喜欢", "第二版"] },
+ relationships: {
+ collections: [
+ { id: "collection:a", index: 1 },
+ { id: "collection:b", index: 0 }
+ ]
+ }
+ });
+
+ const repeated = moveEntriesToTrash(moved, ["one"], { deletedAt: "2026-08-23T00:00:00Z" });
+ assert.deepEqual(repeated, { ...moved, movedItemIds: [] });
+});
+
+test("moving a project with its cases preserves project and compound relationships until permanent deletion", () => {
+ const source = {
+ trashState: createDefaultTrashState(),
+ entries: [
+ { id: "one", title: "A", mediaAssets: [{ id: "image:one", kind: "image", storageMode: "managed", capturedAt: "2026-08-20T00:00:00Z" }] },
+ { id: "two", title: "B", mediaAssets: [{ id: "image:two", kind: "image", storageMode: "managed", capturedAt: "2026-08-20T00:00:00Z" }] }
+ ],
+ organizerState: {
+ collections: [{ id: "collection:a", name: "项目 A", order: 0, entryIds: ["one", "two"] }]
+ },
+ compoundCases: [{
+ id: "compound:a",
+ title: "组合",
+ memberEntryIds: ["one", "two"],
+ coverVisualId: "image:one",
+ customLabels: ["成套"],
+ createdAt: "2026-08-20T00:00:00Z",
+ updatedAt: "2026-08-20T00:00:00Z"
+ }]
+ };
+ const moved = moveCollectionWithEntriesToTrash(source, "collection:a", {
+ deletedAt: "2026-08-22T06:00:00Z"
+ });
+
+ assert.deepEqual(moved.entries, []);
+ assert.deepEqual(moved.organizerState.collections, []);
+ assert.deepEqual(moved.compoundCases, []);
+ assert.equal(moved.trashState.items.length, 3);
+ assert.deepEqual(
+ moved.trashState.items.find((item) => item.id === "trash:entry:one").relationships.collections,
+ [{ id: "collection:a", index: 0 }]
+ );
+ assert.equal(
+ moved.trashState.items.find((item) => item.id === "trash:entry:one").relationships.compoundCases[0].id,
+ "compound:a"
+ );
+
+ const restored = restoreTrashItems(moved, moved.movedItemIds);
+ assert.deepEqual(restored.entries.map((entry) => entry.id), ["one", "two"]);
+ assert.deepEqual(restored.organizerState.collections[0].entryIds, ["one", "two"]);
+ assert.deepEqual(restored.compoundCases[0].memberEntryIds, ["one", "two"]);
+ assert.deepEqual(restored.trashState.items, []);
+});
+
+test("media trash restores visual-derived labels and permanent cleanup protects active shared blobs", () => {
+ const entry = {
+ id: "case:one",
+ mediaAssets: [
+ { id: "image:shared", kind: "image", storageMode: "managed", capturedAt: "2026-08-20T00:00:00Z" },
+ { id: "image:keep", kind: "image", storageMode: "managed", capturedAt: "2026-08-20T00:00:00Z" }
+ ],
+ facetAssignments: [
+ { facetId: "look", nodeId: "look:cinematic", source: "vision_model", visualId: "image:shared" },
+ { facetId: "tone", nodeId: "tone:warm", source: "manual" }
+ ]
+ };
+ const moved = moveMediaToTrash({ entries: [entry], trashState: {} }, entry.id, ["image:shared"], {
+ deletedAt: "2026-08-22T07:00:00Z"
+ });
+ assert.deepEqual(moved.entries[0].facetAssignments.map((item) => item.nodeId), ["tone:warm"]);
+ const restored = restoreTrashItems(moved, moved.movedItemIds);
+ assert.deepEqual(restored.entries[0].facetAssignments.map((item) => item.nodeId), ["tone:warm", "look:cinematic"]);
+
+ const taken = takeTrashItems(moved.trashState, moved.movedItemIds, { retainedMediaIds: ["image:shared"] });
+ assert.deepEqual(taken.cleanup.mediaIds, []);
+});
diff --git a/test/ui_foundation_e2e.py b/test/ui_foundation_e2e.py
index 308ff74..f742b8a 100644
--- a/test/ui_foundation_e2e.py
+++ b/test/ui_foundation_e2e.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from playwright.sync_api import expect
+
from e2e_support import extension_session
@@ -93,6 +95,68 @@ def main() -> None:
)
assert wall_metrics == {"gap": "2px", "radius": "2px"}, wall_metrics
+ library.evaluate(
+ """async () => chrome.storage.local.set({
+ organizerState: {version: 5, collections: [
+ {id: 'collection:combobox-one', name: '优质精选', order: 0, entryIds: [], visibility: 'library'},
+ {id: 'collection:combobox-two', name: 'AIArtWorks · MJ 精选', order: 1, entryIds: [], visibility: 'library'}
+ ]}
+ })"""
+ )
+ library.reload(wait_until="networkidle")
+ library.set_viewport_size({"width": 560, "height": 620})
+ library.locator("#add-menu > summary").click()
+ library.locator("#add-quick-note").click()
+ project_input = library.locator("#promptdirector-app-dialog-projectName")
+ expect(project_input).to_have_attribute("role", "combobox")
+ expect(project_input).to_have_attribute("aria-autocomplete", "list")
+ project_input.click()
+ dialog = library.locator("#promptdirector-app-dialog")
+ expect(dialog.locator(".project-combobox-option")).to_have_count(2)
+ menu_style = dialog.locator(".project-combobox-listbox").evaluate(
+ "node => ({background: getComputedStyle(node).backgroundColor, border: getComputedStyle(node).borderColor})"
+ )
+ assert menu_style["background"] not in {"rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"}, menu_style
+ quick_note_menu = dialog.locator(".project-combobox-listbox").evaluate(
+ """node => {
+ const menu = node.getBoundingClientRect();
+ const boundary = node.closest('.app-dialog-body').getBoundingClientRect();
+ const footer = node.closest('form').querySelector('footer').getBoundingClientRect();
+ return {placement: node.dataset.placement, top: menu.top, bottom: menu.bottom, boundaryTop: boundary.top, boundaryBottom: boundary.bottom, footerTop: footer.top};
+ }"""
+ )
+ assert quick_note_menu["placement"] == "top", quick_note_menu
+ assert quick_note_menu["top"] >= quick_note_menu["boundaryTop"] - 1, quick_note_menu
+ assert quick_note_menu["bottom"] <= min(quick_note_menu["boundaryBottom"], quick_note_menu["footerTop"]) + 1, quick_note_menu
+ project_input.press("ArrowDown")
+ project_input.press("Enter")
+ expect(project_input).to_have_value("优质精选")
+ project_input.fill("新建导演项目")
+ expect(project_input).to_have_value("新建导演项目")
+ project_input.fill("优")
+ expect(project_input).to_have_attribute("aria-expanded", "true")
+ project_input.press("Escape")
+ expect(project_input).to_have_attribute("aria-expanded", "false")
+ dialog.get_by_role("button", name="取消", exact=True).click()
+
+ library.locator("#add-menu > summary").click()
+ library.locator("#add-video-reference").click()
+ video_dialog = library.locator("#promptdirector-app-dialog")
+ video_project = video_dialog.locator("#promptdirector-app-dialog-projectName")
+ video_project.click()
+ video_menu = video_dialog.locator(".project-combobox-listbox").evaluate(
+ """node => {
+ const menu = node.getBoundingClientRect();
+ const boundary = node.closest('.app-dialog-body').getBoundingClientRect();
+ const footer = node.closest('form').querySelector('footer').getBoundingClientRect();
+ return {top: menu.top, bottom: menu.bottom, boundaryTop: boundary.top, boundaryBottom: boundary.bottom, footerTop: footer.top};
+ }"""
+ )
+ assert video_menu["top"] >= video_menu["boundaryTop"] - 1, video_menu
+ assert video_menu["bottom"] <= min(video_menu["boundaryBottom"], video_menu["footerTop"]) + 1, video_menu
+ video_dialog.get_by_role("button", name="取消", exact=True).click()
+ library.set_viewport_size({"width": 1440, "height": 900})
+
first_page.evaluate(
"""async () => {
await chrome.storage.local.set({uiPreferences: {locale: 'system', theme: 'light', motion: 'none'}});
@@ -133,6 +197,7 @@ def main() -> None:
"pages": page_metrics,
"icon": icon_metrics,
"wall": wall_metrics,
+ "project_combobox": menu_style,
"migrated": migrated,
})
diff --git a/test/ui_regressions_e2e.py b/test/ui_regressions_e2e.py
index 2d3289c..570985d 100644
--- a/test/ui_regressions_e2e.py
+++ b/test/ui_regressions_e2e.py
@@ -75,7 +75,7 @@ def main() -> None:
project_row = library.locator(".project-row", has_text="项目隐藏验收")
project_row.locator("summary").click()
- project_row.get_by_role("button", name="仅在项目内显示", exact=True).click()
+ project_row.get_by_role("button", name="仅项目可见", exact=True).click()
expect(library.locator("#feedback")).to_contain_text("项目显示范围已更新")
expect(library.locator("#case-list > .case-card")).to_have_count(1)
visibility = library.evaluate(
diff --git a/test/video_detail_layout_e2e.py b/test/video_detail_layout_e2e.py
index 5bb406f..d8c1867 100644
--- a/test/video_detail_layout_e2e.py
+++ b/test/video_detail_layout_e2e.py
@@ -90,7 +90,7 @@ def main() -> None:
library.locator(".detail-visual-thumb").nth(1).click()
expect(library.locator(".detail-video")).to_be_visible()
expect(library.get_by_role("button", name="设为主要媒体")).to_be_visible()
- expect(library.get_by_role("button", name="删除此媒体")).to_be_visible()
+ expect(library.get_by_role("button", name="此媒体移入回收站")).to_be_visible()
desktop = layout_snapshot(library)
assert desktop["safetyBand"] >= 16, desktop
@@ -112,7 +112,7 @@ def main() -> None:
print({
"desktop": desktop,
"mobile": mobile,
- "dangerActionSeparated": library.get_by_role("button", name="删除此媒体").evaluate(
+ "dangerActionSeparated": library.get_by_role("button", name="此媒体移入回收站").evaluate(
"button => button.classList.contains('button-danger-secondary')"
),
})
diff --git a/test/zip.test.js b/test/zip.test.js
index ca3f598..c028bad 100644
--- a/test/zip.test.js
+++ b/test/zip.test.js
@@ -24,6 +24,22 @@ test("createZipBlob produces a UTF-8 ZIP containing markdown and image paths", a
assert.deepEqual(Array.from(bytes.slice(-22, -18)), [80, 75, 5, 6]);
});
+test("createZipBlob streams source CRC instead of buffering a large source file", async () => {
+ const source = new Blob([new Uint8Array(96 * 1024).fill(3)], { type: "application/octet-stream" });
+ Object.defineProperty(source, "arrayBuffer", {
+ value: async () => { throw new Error("source file must not be buffered as one ArrayBuffer"); }
+ });
+
+ const archive = await createZipBlob([{ name: "attachments/source.psd", data: source }]);
+ const files = await readZipBlob(archive, {
+ maxArchiveBytes: archive.size,
+ maxFileBytes: archive.size,
+ maxFileCount: 10
+ });
+
+ assert.equal(files.get("attachments/source.psd").size, source.size);
+});
+
test("readZipBlob restores every file written by the local ZIP exporter", async () => {
const archive = await createZipBlob([
{ name: "library.json", data: '{"format":"prompt-case-library"}\n' },
@@ -83,6 +99,36 @@ test("openZipBlob validates the whole directory but materializes only requested
await assert.rejects(() => reader.read(["videos/missing.mp4"]), /ZIP 内缺少文件/);
});
+test("openZipBlob range-reads the directory and selected STORE entry without buffering the whole archive", async () => {
+ const archive = await createZipBlob([
+ { name: "library.json", data: "{}" },
+ { name: "attachments/selected.psd", data: new Uint8Array(96 * 1024).fill(7) },
+ { name: "attachments/unselected.psd", data: new Uint8Array(96 * 1024).fill(9) }
+ ]);
+ const ranges = [];
+ const originalSlice = archive.slice.bind(archive);
+ Object.defineProperty(archive, "arrayBuffer", {
+ value: async () => { throw new Error("whole archive must not be buffered"); }
+ });
+ Object.defineProperty(archive, "slice", {
+ value: (start, end, type) => {
+ ranges.push([start, end]);
+ return originalSlice(start, end, type);
+ }
+ });
+
+ const reader = await openZipBlob(archive, {
+ maxArchiveBytes: archive.size,
+ maxFileBytes: archive.size,
+ maxFileCount: 10
+ });
+ const files = await reader.read(["attachments/selected.psd"]);
+
+ assert.equal(files.get("attachments/selected.psd").size, 96 * 1024);
+ assert.equal(ranges.some(([start, end]) => start === 0 && end === archive.size), false);
+ assert.equal(ranges.some(([start, end]) => end - start === 96 * 1024), true);
+});
+
test("readZipBlob rejects unsupported or damaged archives", async () => {
await assert.rejects(() => readZipBlob(new Blob(["not a zip"])), /不是有效的 ZIP/);
const archive = await createZipBlob([{ name: "library.json", data: "valid" }]);
diff --git a/tools/build-ui-icons.mjs b/tools/build-ui-icons.mjs
index 38822d9..b9ba6da 100644
--- a/tools/build-ui-icons.mjs
+++ b/tools/build-ui-icons.mjs
@@ -6,10 +6,10 @@ const projectRoot = fileURLToPath(new URL("../", import.meta.url));
const sourcePath = join(projectRoot, "node_modules", "lucide-static", "icon-nodes.json");
const outputPath = join(projectRoot, "assets", "ui-icons.svg");
const iconNames = [
- "arrow-left", "check", "chevron-down", "chevron-left", "chevron-right", "copy",
+ "arrow-down", "arrow-left", "arrow-up", "check", "chevron-down", "chevron-left", "chevron-right", "circle-check-big", "copy",
"download", "ellipsis", "external-link", "file-text", "folder", "image", "library",
- "maximize-2", "menu", "moon", "panel-left", "paperclip", "pencil", "play", "plus",
- "refresh-cw", "save", "search", "send", "settings", "sliders-horizontal", "sparkles",
+ "list-checks", "maximize-2", "menu", "moon", "panel-left", "paperclip", "pencil", "play", "plus",
+ "refresh-cw", "save", "search", "send", "settings", "sliders-horizontal", "sparkles", "square-check-big",
"square", "sun", "tag", "trash-2", "upload", "video", "wand-sparkles", "x"
];
diff --git a/trash.js b/trash.js
new file mode 100644
index 0000000..1e3bb42
--- /dev/null
+++ b/trash.js
@@ -0,0 +1,507 @@
+import { normalizeOrganizerState, removeEntriesFromOrganizer } from "./organizer.js";
+import { normalizeEntryMedia, removeEntryMedia } from "./media.js";
+import { normalizeCompoundCases, removeEntriesFromCompoundCases } from "./compound-cases.js";
+
+export const TRASH_VERSION = 1;
+
+const TRASH_KINDS = new Set(["entry", "media", "collection"]);
+const OMIT = Symbol("omit");
+
+export function createDefaultTrashState() {
+ return { version: TRASH_VERSION, items: [] };
+}
+
+export function normalizeTrashState(value = {}) {
+ const items = [];
+ const seen = new Set();
+ for (const valueItem of Array.isArray(value?.items) ? value.items : []) {
+ const item = normalizeTrashItem(valueItem);
+ if (!item || seen.has(item.id)) continue;
+ seen.add(item.id);
+ items.push(item);
+ }
+ return { version: TRASH_VERSION, items };
+}
+
+export function moveEntriesToTrash(contextValue = {}, entryIds = [], options = {}) {
+ const deletedAt = operationTime(options.deletedAt);
+ const entries = Array.isArray(contextValue.entries) ? contextValue.entries : [];
+ const organizerState = normalizeOrganizerState(contextValue.organizerState);
+ const trashState = normalizeTrashState(contextValue.trashState);
+ const requested = new Set(uniqueIds(entryIds));
+ const existingTrashIds = new Set(trashState.items.map((item) => item.id));
+ const compoundCases = Array.isArray(contextValue.compoundCases)
+ ? normalizeCompoundCases(contextValue.compoundCases, entries)
+ : null;
+ const moved = [];
+
+ for (const entry of entries) {
+ const targetId = clean(entry?.id);
+ const trashId = trashItemId("entry", targetId);
+ if (!requested.has(targetId) || existingTrashIds.has(trashId)) continue;
+ moved.push({
+ id: trashId,
+ kind: "entry",
+ targetId,
+ deletedAt,
+ snapshot: serializableObject(entry),
+ relationships: {
+ collections: organizerState.collections.flatMap((collection) => {
+ const index = collection.entryIds.indexOf(targetId);
+ return index < 0 ? [] : [{ id: collection.id, index }];
+ }),
+ ...(compoundCases?.some((compound) => compound.memberEntryIds.includes(targetId)) ? {
+ compoundCases: compoundCases.filter((compound) => compound.memberEntryIds.includes(targetId))
+ .map(serializableObject)
+ } : {})
+ }
+ });
+ existingTrashIds.add(trashId);
+ }
+
+ const movedIds = new Set(moved.map((item) => item.targetId));
+ const result = {
+ ...contextValue,
+ trashState: normalizeTrashState({ items: [...trashState.items, ...moved] }),
+ entries: entries.filter((entry) => !movedIds.has(clean(entry?.id))),
+ organizerState: removeEntriesFromOrganizer(organizerState, [...movedIds]),
+ movedItemIds: moved.map((item) => item.id)
+ };
+ if (compoundCases) {
+ result.compoundCases = removeEntriesFromCompoundCases(compoundCases, entries, [...movedIds]);
+ }
+ return result;
+}
+
+export function moveCollectionWithEntriesToTrash(contextValue = {}, collectionIdValue, options = {}) {
+ const entries = Array.isArray(contextValue.entries) ? contextValue.entries : [];
+ const organizerState = normalizeOrganizerState(contextValue.organizerState, entries.map((entry) => clean(entry?.id)));
+ const collectionId = clean(collectionIdValue);
+ const collection = organizerState.collections.find((item) => item.id === collectionId);
+ if (!collection) throw new Error("项目不存在");
+
+ const entriesMoved = moveEntriesToTrash({ ...contextValue, organizerState }, collection.entryIds, options);
+ const collectionMoved = moveCollectionsToTrash({
+ ...contextValue,
+ trashState: entriesMoved.trashState,
+ organizerState
+ }, [collection.id], options);
+ return {
+ ...contextValue,
+ trashState: collectionMoved.trashState,
+ entries: entriesMoved.entries,
+ organizerState: removeEntriesFromOrganizer(collectionMoved.organizerState, collection.entryIds),
+ ...(Array.isArray(contextValue.compoundCases) ? { compoundCases: entriesMoved.compoundCases } : {}),
+ movedItemIds: [...entriesMoved.movedItemIds, ...collectionMoved.movedItemIds],
+ movedEntryIds: collection.entryIds.filter((id) => entries.some((entry) => clean(entry?.id) === id)),
+ collection: structuredClone(collection)
+ };
+}
+
+export function moveCollectionsToTrash(contextValue = {}, collectionIds = [], options = {}) {
+ const deletedAt = operationTime(options.deletedAt);
+ const organizerState = normalizeOrganizerState(contextValue.organizerState);
+ const trashState = normalizeTrashState(contextValue.trashState);
+ const requested = new Set(uniqueIds(collectionIds));
+ const existingTrashIds = new Set(trashState.items.map((item) => item.id));
+ const moved = organizerState.collections.flatMap((collection) => {
+ const trashId = trashItemId("collection", collection.id);
+ if (!requested.has(collection.id) || existingTrashIds.has(trashId)) return [];
+ existingTrashIds.add(trashId);
+ return [{
+ id: trashId,
+ kind: "collection",
+ targetId: collection.id,
+ deletedAt,
+ snapshot: serializableObject(collection),
+ relationships: {}
+ }];
+ });
+ const movedIds = new Set(moved.map((item) => item.targetId));
+ return {
+ ...contextValue,
+ trashState: normalizeTrashState({ items: [...trashState.items, ...moved] }),
+ organizerState: {
+ ...organizerState,
+ collections: organizerState.collections.filter((collection) => !movedIds.has(collection.id))
+ },
+ movedItemIds: moved.map((item) => item.id)
+ };
+}
+
+export function moveMediaToTrash(contextValue = {}, entryIdValue, mediaIds = [], options = {}) {
+ const deletedAt = operationTime(options.deletedAt);
+ const entryId = clean(entryIdValue);
+ const requested = uniqueIds(mediaIds);
+ const sourceEntries = Array.isArray(contextValue.entries) ? contextValue.entries : [];
+ const entryIndex = sourceEntries.findIndex((entry) => clean(entry?.id) === entryId);
+ if (entryIndex < 0) throw new Error("案例不存在");
+ const entries = structuredClone(sourceEntries);
+ const trashState = normalizeTrashState(contextValue.trashState);
+ const existingTrashIds = new Set(trashState.items.map((item) => item.id));
+ const moved = [];
+ let entry = normalizeEntryMedia(entries[entryIndex]);
+
+ for (const targetId of requested) {
+ const trashId = trashItemId("media", targetId, entryId);
+ if (existingTrashIds.has(trashId) || !entry.mediaAssets.some((asset) => asset.id === targetId)) continue;
+ const before = entry;
+ const after = removeEntryMedia(before, targetId);
+ const remainingIds = new Set(after.mediaAssets.map((asset) => asset.id));
+ const removedAssets = before.mediaAssets.filter((asset) => !remainingIds.has(asset.id));
+ const removedIds = new Set(removedAssets.map((asset) => asset.id));
+ moved.push({
+ id: trashId,
+ kind: "media",
+ targetId,
+ deletedAt,
+ snapshot: { mediaAssets: removedAssets },
+ relationships: {
+ entryId,
+ positions: removedAssets.map((asset) => ({ id: asset.id, index: before.mediaAssets.findIndex((item) => item.id === asset.id) })),
+ primaryMediaId: removedIds.has(before.primaryMediaId) ? before.primaryMediaId : "",
+ timeNotes: relatedValues(before.timeNotes, removedIds, ["assetId", "frameAssetId"]),
+ mediaPrompts: relatedValues(before.mediaPrompts, removedIds, ["assetId"]),
+ videoAnalyses: relatedValues(before.videoAnalyses, removedIds, ["assetId"]),
+ facetAssignments: relatedValues(before.facetAssignments, removedIds, ["visualId"]),
+ articleDocument: before.articleDocument ?? null,
+ articleDocumentAfterDelete: after.articleDocument ?? null
+ }
+ });
+ existingTrashIds.add(trashId);
+ entry = {
+ ...after,
+ facetAssignments: (after.facetAssignments ?? []).filter((assignment) =>
+ !removedIds.has(clean(assignment?.visualId))
+ )
+ };
+ }
+
+ entries[entryIndex] = entry;
+ return {
+ ...contextValue,
+ trashState: normalizeTrashState({ items: [...trashState.items, ...moved] }),
+ entries,
+ movedItemIds: moved.map((item) => item.id),
+ pendingBlobDeletes: []
+ };
+}
+
+export function restoreTrashItems(contextValue = {}, itemIds = [], options = {}) {
+ const trashState = normalizeTrashState(contextValue.trashState);
+ const requested = new Set(uniqueIds(itemIds));
+ const entries = structuredClone(Array.isArray(contextValue.entries) ? contextValue.entries : []);
+ let organizerState = structuredClone(normalizeOrganizerState(contextValue.organizerState));
+ const restored = new Set();
+ const unresolved = [];
+ const kindOrder = { collection: 0, entry: 1, media: 2 };
+ const candidates = trashState.items
+ .filter((item) => requested.has(item.id))
+ .toSorted((left, right) => kindOrder[left.kind] - kindOrder[right.kind]);
+ const restorableEntryIds = new Set([
+ ...entries.map((entry) => clean(entry?.id)).filter(Boolean),
+ ...candidates.filter((item) => item.kind === "entry").map((item) => item.targetId)
+ ]);
+
+ for (const item of candidates) {
+ let result;
+ if (item.kind === "collection") {
+ result = restoreCollectionItem(item, organizerState, restorableEntryIds);
+ if (result.ok) organizerState = result.organizerState;
+ } else if (item.kind === "entry") {
+ result = restoreEntryItem(item, entries, organizerState, options.collectionReplacements);
+ if (result.ok) organizerState = result.organizerState;
+ } else {
+ result = restoreMediaItem(item, entries);
+ }
+ if (result.ok) restored.add(item.id);
+ else unresolved.push({ itemId: item.id, kind: item.kind, targetId: item.targetId, ...result.issue });
+ }
+
+ const compoundCases = restoreRelatedCompoundCases(
+ contextValue.compoundCases,
+ entries,
+ candidates.filter((item) => restored.has(item.id))
+ );
+
+ return {
+ ...contextValue,
+ trashState: normalizeTrashState({ items: trashState.items.filter((item) => !restored.has(item.id)) }),
+ entries,
+ organizerState,
+ ...(Array.isArray(contextValue.compoundCases) ? { compoundCases } : {}),
+ restoredItemIds: trashState.items.filter((item) => restored.has(item.id)).map((item) => item.id),
+ unresolved
+ };
+}
+
+export function listTrashItems(stateValue = {}, options = {}) {
+ const kind = clean(options.kind);
+ return structuredClone(normalizeTrashState(stateValue).items
+ .filter((item) => !kind || item.kind === kind)
+ .toSorted((left, right) => right.deletedAt.localeCompare(left.deletedAt) || left.id.localeCompare(right.id)));
+}
+
+export function takeTrashItems(stateValue = {}, itemIds = [], options = {}) {
+ const state = normalizeTrashState(stateValue);
+ const requested = new Set(uniqueIds(itemIds));
+ const takenItems = state.items.filter((item) => requested.has(item.id));
+ const remainingItems = state.items.filter((item) => !requested.has(item.id));
+ const retainedMediaIds = new Set([
+ ...uniqueIds(options.retainedMediaIds),
+ ...remainingItems.flatMap(mediaIdsInTrashItem)
+ ]);
+ const retainedEntryIds = new Set(uniqueIds(options.retainedEntryIds));
+ const cleanupMediaIds = uniqueIds(takenItems.flatMap(mediaIdsInTrashItem))
+ .filter((id) => !retainedMediaIds.has(id));
+ const entryIds = uniqueIds(takenItems.filter((item) => item.kind === "entry").map((item) => item.targetId));
+ return {
+ trashState: normalizeTrashState({ items: remainingItems }),
+ takenItems: structuredClone(takenItems),
+ cleanup: {
+ entryIds,
+ collectionIds: uniqueIds(takenItems.filter((item) => item.kind === "collection").map((item) => item.targetId)),
+ mediaIds: cleanupMediaIds,
+ screenshotEntryIds: entryIds.filter((id) => !retainedEntryIds.has(id))
+ }
+ };
+}
+
+export function emptyTrash(stateValue = {}, options = {}) {
+ const state = normalizeTrashState(stateValue);
+ return takeTrashItems(state, state.items.map((item) => item.id), options);
+}
+
+function restoreCollectionItem(item, organizerState, restorableEntryIds) {
+ const normalized = normalizeOrganizerState({ collections: [item.snapshot] }).collections[0];
+ if (!normalized || normalized.id !== item.targetId) {
+ return unresolvedIssue("项目快照无效");
+ }
+ const existing = organizerState.collections.find((collection) => collection.id === item.targetId);
+ if (existing) {
+ return jsonEqual(existing, normalized)
+ ? { ok: true, organizerState }
+ : unresolvedIssue("当前资料库存在同编号但内容不同的项目");
+ }
+ const missingEntryIds = normalized.entryIds.filter((entryId) => !restorableEntryIds.has(entryId));
+ if (missingEntryIds.length) {
+ return unresolvedIssue("项目成员案例不存在", { missingEntryIds });
+ }
+ return {
+ ok: true,
+ organizerState: normalizeOrganizerState({
+ ...organizerState,
+ collections: [...organizerState.collections, normalized]
+ })
+ };
+}
+
+function mediaIdsInTrashItem(item) {
+ if (!item || !["entry", "media"].includes(item.kind)) return [];
+ const assets = Array.isArray(item.snapshot?.mediaAssets)
+ ? item.snapshot.mediaAssets
+ : Array.isArray(item.snapshot?.visuals) ? item.snapshot.visuals : [];
+ return assets
+ .filter((asset) => asset?.storageMode !== "reference")
+ .map((asset) => clean(asset?.id))
+ .filter(Boolean);
+}
+
+function restoreEntryItem(item, entries, organizerState, replacementValue) {
+ const snapshot = serializableObject(item.snapshot);
+ if (clean(snapshot.id) !== item.targetId) return unresolvedIssue("案例快照无效");
+ const existing = entries.find((entry) => clean(entry?.id) === item.targetId);
+ if (existing && !jsonEqual(serializableObject(existing), snapshot)) {
+ return unresolvedIssue("当前资料库存在同编号但内容不同的案例");
+ }
+ const replacements = replacementValue && typeof replacementValue === "object" ? replacementValue : {};
+ const collectionIds = new Set(organizerState.collections.map((collection) => collection.id));
+ const relationships = Array.isArray(item.relationships?.collections) ? item.relationships.collections : [];
+ const resolvedRelationships = [];
+ const missingCollectionIds = [];
+ for (const relationship of relationships) {
+ const originalId = clean(relationship?.id);
+ if (collectionIds.has(originalId)) {
+ resolvedRelationships.push({ id: originalId, index: safeIndex(relationship?.index) });
+ continue;
+ }
+ if (!Object.hasOwn(replacements, originalId)) {
+ missingCollectionIds.push(originalId);
+ continue;
+ }
+ const replacementIds = uniqueIds(replacements[originalId]);
+ const invalidReplacementIds = replacementIds.filter((id) => !collectionIds.has(id));
+ if (invalidReplacementIds.length) missingCollectionIds.push(...invalidReplacementIds);
+ else replacementIds.forEach((id) => resolvedRelationships.push({ id, index: Number.MAX_SAFE_INTEGER }));
+ }
+ if (missingCollectionIds.length) {
+ return unresolvedIssue("原项目关系不存在", { missingCollectionIds: [...new Set(missingCollectionIds)] });
+ }
+ if (!existing) entries.push(snapshot);
+ for (const relationship of resolvedRelationships) {
+ const collection = organizerState.collections.find((candidate) => candidate.id === relationship.id);
+ if (!collection || collection.entryIds.includes(item.targetId)) continue;
+ collection.entryIds.splice(Math.min(relationship.index, collection.entryIds.length), 0, item.targetId);
+ }
+ return { ok: true, organizerState: normalizeOrganizerState(organizerState) };
+}
+
+function restoreMediaItem(item, entries) {
+ const entryIndex = entries.findIndex((entry) => clean(entry?.id) === clean(item.relationships?.entryId));
+ if (entryIndex < 0) return unresolvedIssue("媒体所属案例不存在");
+ const entry = normalizeEntryMedia(entries[entryIndex]);
+ const restoredAssets = Array.isArray(item.snapshot?.mediaAssets) ? item.snapshot.mediaAssets : [];
+ if (!restoredAssets.length || !restoredAssets.some((asset) => clean(asset?.id) === item.targetId)) {
+ return unresolvedIssue("媒体快照无效");
+ }
+ const currentById = new Map(entry.mediaAssets.map((asset) => [asset.id, asset]));
+ for (const asset of restoredAssets) {
+ const existing = currentById.get(clean(asset?.id));
+ if (existing && !jsonEqual(existing, asset)) {
+ return unresolvedIssue("案例中存在同编号但内容不同的媒体");
+ }
+ }
+ const expectedDocument = item.relationships?.articleDocumentAfterDelete ?? null;
+ const currentDocument = entry.articleDocument ?? null;
+ if (!jsonEqual(currentDocument, expectedDocument)) {
+ return unresolvedIssue("案例正文在删除媒体后已经改变,无法安全覆盖");
+ }
+ const positions = new Map((Array.isArray(item.relationships?.positions) ? item.relationships.positions : [])
+ .map((position) => [clean(position?.id), safeIndex(position?.index)]));
+ const mediaAssets = [...entry.mediaAssets];
+ for (const asset of restoredAssets.toSorted((left, right) =>
+ (positions.get(clean(left?.id)) ?? Number.MAX_SAFE_INTEGER) - (positions.get(clean(right?.id)) ?? Number.MAX_SAFE_INTEGER)
+ )) {
+ if (currentById.has(clean(asset?.id))) continue;
+ const index = Math.min(positions.get(clean(asset?.id)) ?? mediaAssets.length, mediaAssets.length);
+ mediaAssets.splice(index, 0, asset);
+ }
+ const next = {
+ ...entry,
+ mediaAssets,
+ timeNotes: mergeRelated(entry.timeNotes, item.relationships?.timeNotes, "id"),
+ mediaPrompts: mergeRelated(entry.mediaPrompts, item.relationships?.mediaPrompts, "assetId"),
+ videoAnalyses: mergeRelated(entry.videoAnalyses, item.relationships?.videoAnalyses, "id"),
+ facetAssignments: mergeRelated(entry.facetAssignments, item.relationships?.facetAssignments, "nodeId"),
+ primaryMediaId: clean(item.relationships?.primaryMediaId) || entry.primaryMediaId
+ };
+ const originalDocument = item.relationships?.articleDocument ?? null;
+ if (originalDocument) next.articleDocument = originalDocument;
+ else delete next.articleDocument;
+ entries[entryIndex] = normalizeEntryMedia(next);
+ return { ok: true };
+}
+
+function restoreRelatedCompoundCases(currentValue, entries, restoredEntryItems) {
+ if (!Array.isArray(currentValue)) return undefined;
+ const activeEntryIds = new Set(entries.map((entry) => clean(entry?.id)).filter(Boolean));
+ const snapshots = new Map();
+ for (const item of restoredEntryItems) {
+ for (const snapshot of Array.isArray(item.relationships?.compoundCases) ? item.relationships.compoundCases : []) {
+ const id = clean(snapshot?.id);
+ if (id && Array.isArray(snapshot?.memberEntryIds) && snapshot.memberEntryIds.every((entryId) => activeEntryIds.has(clean(entryId)))) {
+ snapshots.set(id, snapshot);
+ }
+ }
+ }
+ const current = normalizeCompoundCases(currentValue, entries);
+ if (!snapshots.size) return current;
+ const replacedIds = new Set(snapshots.keys());
+ return normalizeCompoundCases([
+ ...current.filter((compound) => !replacedIds.has(compound.id)),
+ ...snapshots.values()
+ ], entries);
+}
+
+function unresolvedIssue(reason, details = {}) {
+ return { ok: false, issue: { reason, ...details } };
+}
+
+function mergeRelated(currentValue, restoredValue, key) {
+ const current = Array.isArray(currentValue) ? currentValue : [];
+ const seen = new Set(current.map((item) => clean(item?.[key])).filter(Boolean));
+ return [...current, ...(Array.isArray(restoredValue) ? restoredValue : []).filter((item) => {
+ const id = clean(item?.[key]);
+ if (!id || seen.has(id)) return false;
+ seen.add(id);
+ return true;
+ })];
+}
+
+function safeIndex(value) {
+ const number = Number(value);
+ return Number.isSafeInteger(number) && number >= 0 ? number : Number.MAX_SAFE_INTEGER;
+}
+
+function jsonEqual(left, right) {
+ return JSON.stringify(left) === JSON.stringify(right);
+}
+
+function normalizeTrashItem(value = {}) {
+ const id = clean(value?.id);
+ const kind = clean(value?.kind);
+ const targetId = clean(value?.targetId);
+ const deletedAt = validIso(value?.deletedAt);
+ if (!id || !TRASH_KINDS.has(kind) || !targetId || !deletedAt) return null;
+ const snapshot = serializableObject(value.snapshot);
+ const relationships = serializableObject(value.relationships);
+ return { id, kind, targetId, deletedAt, snapshot, relationships };
+}
+
+function serializableObject(value) {
+ const normalized = toSerializable(value, new Set());
+ return normalized && normalized !== OMIT && !Array.isArray(normalized) ? normalized : {};
+}
+
+function toSerializable(value, ancestors) {
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
+ if (typeof value === "number") return Number.isFinite(value) ? value : OMIT;
+ if (typeof value !== "object") return OMIT;
+ if (ancestors.has(value)) return OMIT;
+ ancestors.add(value);
+ let result;
+ if (Array.isArray(value)) {
+ result = value.flatMap((item) => {
+ const normalized = toSerializable(item, ancestors);
+ return normalized === OMIT ? [] : [normalized];
+ });
+ } else {
+ result = {};
+ for (const [key, item] of Object.entries(value)) {
+ if (["__proto__", "prototype", "constructor"].includes(key)) continue;
+ const normalized = toSerializable(item, ancestors);
+ if (normalized !== OMIT) result[key] = normalized;
+ }
+ }
+ ancestors.delete(value);
+ return result;
+}
+
+function validIso(value) {
+ const text = clean(value);
+ return text && Number.isFinite(Date.parse(text)) ? new Date(text).toISOString() : "";
+}
+
+function operationTime(value) {
+ const normalized = validIso(value ?? new Date().toISOString());
+ if (!normalized) throw new Error("删除时间无效");
+ return normalized;
+}
+
+function trashItemId(kind, targetId, parentId = "") {
+ return ["trash", kind, parentId, targetId].filter(Boolean).join(":");
+}
+
+function uniqueIds(values) {
+ return [...new Set((Array.isArray(values) ? values : []).map(clean).filter(Boolean))];
+}
+
+function relatedValues(values, ids, fields) {
+ return (Array.isArray(values) ? values : []).filter((value) =>
+ fields.some((field) => ids.has(clean(value?.[field])))
+ );
+}
+
+function clean(value) {
+ return String(value ?? "").replace(/[\u0000-\u001f\u007f]/g, "").trim();
+}
diff --git a/ui-foundation.css b/ui-foundation.css
index f70ce3c..8734a31 100644
--- a/ui-foundation.css
+++ b/ui-foundation.css
@@ -33,6 +33,8 @@
--ui-meta-size: 11px;
--ui-motion-fast: 120ms;
--ui-motion-normal: 160ms;
+ --ui-popover-gap: 5px;
+ --ui-combobox-max-height: 320px;
/* Compatibility aliases while page-specific layout styles are migrated. */
--ink: var(--ui-text);
@@ -192,7 +194,7 @@ button.compact {
line-height: 1;
}
-input, select, textarea {
+input:not([type="checkbox"]):not([type="radio"]):not([type="file"]), select, textarea {
width: 100%;
min-height: var(--ui-control-height);
border: 1px solid var(--ui-border);
@@ -202,6 +204,82 @@ input, select, textarea {
background: var(--input);
font-size: var(--ui-body-size);
}
+select,
+select::picker(select) {
+ appearance: base-select;
+}
+select { align-items: center; gap: 8px; cursor: pointer; }
+select::picker(select) {
+ max-height: min(360px, calc(100dvh - 32px));
+ overflow: auto;
+ border: 1px solid var(--ui-border-strong);
+ border-radius: var(--ui-container-radius);
+ padding: 6px;
+ color: var(--ui-text);
+ background: var(--ui-surface);
+ box-shadow: var(--ui-shadow);
+}
+select option {
+ min-height: var(--ui-control-height);
+ align-items: center;
+ border-radius: var(--ui-control-radius);
+ padding: 7px 10px;
+ color: var(--ui-text);
+ background: var(--ui-surface);
+ cursor: pointer;
+}
+select option:hover,
+select option:focus-visible { background: var(--ui-hover); }
+select option:checked {
+ color: var(--ui-accent-contrast);
+ background: var(--ui-accent);
+ font-weight: 750;
+}
+select::picker-icon {
+ color: var(--ui-muted);
+ transition: rotate var(--ui-motion-fast) ease;
+}
+select:open::picker-icon { rotate: 180deg; }
+select:disabled { cursor: not-allowed; }
+.project-combobox-listbox {
+ position: absolute;
+ z-index: 80;
+ top: calc(100% + var(--ui-popover-gap));
+ right: 0;
+ left: 0;
+ display: grid;
+ min-height: 0;
+ max-height: min(var(--ui-combobox-max-height), var(--project-combobox-available-height, calc(100dvh - 32px)));
+ overflow: auto;
+ gap: 2px;
+ border: 1px solid var(--ui-border-strong);
+ border-radius: var(--ui-container-radius);
+ padding: 6px;
+ color: var(--ui-text);
+ background: var(--ui-surface);
+ box-shadow: var(--ui-shadow);
+}
+.project-combobox-listbox[data-placement="top"] {
+ top: auto;
+ bottom: calc(100% + var(--ui-popover-gap));
+}
+.project-combobox-option {
+ min-height: var(--ui-control-height);
+ border: 0;
+ border-radius: var(--ui-control-radius);
+ padding: 7px 10px;
+ color: var(--ui-text);
+ background: transparent;
+ font-weight: 600;
+ text-align: left;
+}
+.project-combobox-option:hover:not(:disabled),
+.project-combobox-option[aria-selected="true"] {
+ color: var(--ui-accent-contrast);
+ background: var(--ui-accent);
+}
+.app-dialog-field:has(> input[role="combobox"]),
+.import-project-field:has(> input[role="combobox"]) { position: relative; }
button:focus-visible,
input:focus-visible,
select:focus-visible,
@@ -239,6 +317,49 @@ summary:focus-visible,
white-space: nowrap;
}
+.tag-editor { display: grid; gap: 7px; }
+.tag-editor-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }
+.tag-editor-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 7px; }
+.tag-editor-row input { min-width: 0; }
+.tag-editor-row button { min-height: var(--ui-control-height); white-space: nowrap; }
+.tag-editor-chip {
+ display: inline-flex;
+ max-width: 100%;
+ min-height: 26px;
+ align-items: center;
+ gap: 4px;
+ border-radius: 999px;
+ padding: 3px 4px 3px 9px;
+ color: var(--ui-text);
+ background: color-mix(in srgb, var(--ui-accent) 16%, transparent);
+ font-size: var(--ui-meta-size);
+ font-weight: 700;
+}
+.tag-editor-chip > span { overflow-wrap: anywhere; }
+.tag-editor-chip button {
+ display: grid;
+ width: 20px;
+ min-width: 20px;
+ min-height: 20px;
+ place-items: center;
+ border: 0;
+ border-radius: 50%;
+ padding: 0;
+ color: var(--ui-muted);
+ background: transparent;
+ font-size: 15px;
+ line-height: 1;
+}
+.tag-editor-chip button:hover:not(:disabled) {
+ color: var(--ui-danger);
+ background: color-mix(in srgb, var(--ui-danger) 10%, transparent);
+}
+
+@media (max-width: 390px) {
+ .tag-editor-row { grid-template-columns: 1fr; }
+ .tag-editor-row button { justify-self: start; }
+}
+
.ui-feedback-toast {
position: fixed;
z-index: 90;
diff --git a/zip.js b/zip.js
index 6f43492..7c336ee 100644
--- a/zip.js
+++ b/zip.js
@@ -1,4 +1,5 @@
import { formatBytes, portableLibraryLimits } from "./resource-limits.js";
+import { assetFormatForExtension } from "./asset-formats.js";
const encoder = new TextEncoder();
const UTF8_FLAG = 0x0800;
@@ -18,9 +19,8 @@ export async function createZipBlob(files) {
const name = normalizeArchivePath(file?.name);
const nameBytes = encoder.encode(name);
const dataPart = archivePart(file?.data);
- const dataBytes = new Uint8Array(await dataPart.arrayBuffer());
ensureUint32(dataPart.size, "单个文件过大");
- const checksum = crc32(dataBytes);
+ const checksum = await crc32Blob(dataPart);
const localHeader = makeLocalHeader(nameBytes, dataPart.size, checksum);
records.push({ nameBytes, dataPart, checksum, offset });
offset += localHeader.byteLength + nameBytes.byteLength + dataPart.size;
@@ -65,31 +65,36 @@ export async function openZipBlob(archive, limitsValue = {}) {
if (archive.size > limits.maxArchiveBytes) {
throw new Error(`ZIP 超过 ${formatBytes(limits.maxArchiveBytes)} 上限`);
}
- const bytes = new Uint8Array(await archive.arrayBuffer());
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- const endOffset = findEndRecord(view);
- if (endOffset < 0) throw invalidZip();
- const disk = view.getUint16(endOffset + 4, true);
- const directoryDisk = view.getUint16(endOffset + 6, true);
- const diskCount = view.getUint16(endOffset + 8, true);
- const fileCount = view.getUint16(endOffset + 10, true);
- const directorySize = view.getUint32(endOffset + 12, true);
- const directoryOffset = view.getUint32(endOffset + 16, true);
- const commentLength = view.getUint16(endOffset + 20, true);
- if (disk || directoryDisk || diskCount !== fileCount || endOffset + 22 + commentLength !== bytes.byteLength) {
+ const tailOffset = Math.max(0, archive.size - 0xffff - 22);
+ const tailBytes = await readBlobBytes(archive, tailOffset, archive.size);
+ const tailView = dataView(tailBytes);
+ const relativeEndOffset = findEndRecord(tailView);
+ if (relativeEndOffset < 0) throw invalidZip();
+ const endOffset = tailOffset + relativeEndOffset;
+ const disk = tailView.getUint16(relativeEndOffset + 4, true);
+ const directoryDisk = tailView.getUint16(relativeEndOffset + 6, true);
+ const diskCount = tailView.getUint16(relativeEndOffset + 8, true);
+ const fileCount = tailView.getUint16(relativeEndOffset + 10, true);
+ const directorySize = tailView.getUint32(relativeEndOffset + 12, true);
+ const directoryOffset = tailView.getUint32(relativeEndOffset + 16, true);
+ const commentLength = tailView.getUint16(relativeEndOffset + 20, true);
+ if (disk || directoryDisk || diskCount !== fileCount || endOffset + 22 + commentLength !== archive.size ||
+ fileCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
throw new Error("暂不支持分卷或 ZIP64 压缩包");
}
if (fileCount > limits.maxFileCount) {
throw new Error(`ZIP 文件数量超过 ${limits.maxFileCount} 个上限`);
}
if (directoryOffset + directorySize !== endOffset) throw invalidZip();
+ const directoryBytes = await readBlobBytes(archive, directoryOffset, endOffset);
+ const view = dataView(directoryBytes);
const records = [];
const names = new Set();
let declaredBytes = 0;
- let cursor = directoryOffset;
+ let cursor = 0;
for (let index = 0; index < fileCount; index += 1) {
- if (cursor + 46 > endOffset || view.getUint32(cursor, true) !== 0x02014b50) throw invalidZip();
+ if (cursor + 46 > directoryBytes.byteLength || view.getUint32(cursor, true) !== 0x02014b50) throw invalidZip();
const flags = view.getUint16(cursor + 8, true);
const method = view.getUint16(cursor + 10, true);
const checksum = view.getUint32(cursor + 16, true);
@@ -106,12 +111,12 @@ export async function openZipBlob(archive, limitsValue = {}) {
if (![STORE_METHOD, DEFLATE_METHOD].includes(method)) throw new Error("ZIP 使用了浏览器不支持的压缩方式");
if (method === STORE_METHOD && compressedSize !== size) throw invalidZip();
const nameEnd = cursor + 46 + nameLength;
- if (nameEnd + extraLength + entryCommentLength > endOffset) throw invalidZip();
- if (!(flags & UTF8_FLAG) && bytes.subarray(cursor + 46, nameEnd).some((byte) => byte > 0x7f)) {
+ if (nameEnd + extraLength + entryCommentLength > directoryBytes.byteLength) throw invalidZip();
+ if (!(flags & UTF8_FLAG) && directoryBytes.subarray(cursor + 46, nameEnd).some((byte) => byte > 0x7f)) {
throw new Error("ZIP 文件名不是可安全识别的 UTF-8 或 ASCII 编码");
}
const decodedName = new TextDecoder("utf-8", { fatal: true })
- .decode(bytes.subarray(cursor + 46, nameEnd));
+ .decode(directoryBytes.subarray(cursor + 46, nameEnd));
const directoryEntry = decodedName.endsWith("/");
if (directoryEntry && !safeDirectoryPath(decodedName)) throw new Error("ZIP 内包含不安全的目录路径");
if (directoryEntry && (size !== 0 || compressedSize !== 0)) throw invalidZip();
@@ -122,33 +127,14 @@ export async function openZipBlob(archive, limitsValue = {}) {
const name = normalizeArchivePath(decodedName);
if (name !== decodedName || names.has(name)) throw new Error("ZIP 内包含不安全或重复的文件路径");
- if (localOffset + 30 > directoryOffset || view.getUint32(localOffset, true) !== 0x04034b50) throw invalidZip();
- const localFlags = view.getUint16(localOffset + 6, true);
- const localMethod = view.getUint16(localOffset + 8, true);
- const localChecksum = view.getUint32(localOffset + 14, true);
- const localCompressedSize = view.getUint32(localOffset + 18, true);
- const localSize = view.getUint32(localOffset + 22, true);
- const localNameLength = view.getUint16(localOffset + 26, true);
- const localExtraLength = view.getUint16(localOffset + 28, true);
- const localNameEnd = localOffset + 30 + localNameLength;
- if (localNameEnd > directoryOffset) throw invalidZip();
- const localName = new TextDecoder("utf-8", { fatal: true })
- .decode(bytes.subarray(localOffset + 30, localNameEnd));
- const descriptor = Boolean(flags & DATA_DESCRIPTOR_FLAG);
- if (localFlags !== flags || localMethod !== method || localName !== name) throw invalidZip();
- if (!descriptor && (localChecksum !== checksum || localCompressedSize !== compressedSize || localSize !== size)) throw invalidZip();
- if (descriptor && ((localChecksum && localChecksum !== checksum) ||
- (localCompressedSize && localCompressedSize !== compressedSize) || (localSize && localSize !== size))) throw invalidZip();
- const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
- const dataEnd = dataOffset + compressedSize;
- if (dataEnd > directoryOffset) throw invalidZip();
+ if (localOffset + 30 > directoryOffset) throw invalidZip();
declaredBytes += size;
if (declaredBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
names.add(name);
- records.push({ name, method, checksum, compressedSize, size, dataOffset, dataEnd });
+ records.push({ name, flags, method, checksum, compressedSize, size, localOffset });
cursor = nameEnd + extraLength + entryCommentLength;
}
- if (cursor !== endOffset) throw invalidZip();
+ if (cursor !== directoryBytes.byteLength) throw invalidZip();
return {
names: Object.freeze([...names]),
async read(selectedNames = null, options = {}) {
@@ -166,15 +152,23 @@ export async function openZipBlob(archive, limitsValue = {}) {
let extractedBytes = 0;
for (let index = 0; index < targets.length; index += 1) {
const record = targets[index];
- const compressed = bytes.subarray(record.dataOffset, record.dataEnd);
- const data = record.method === STORE_METHOD
- ? compressed
- : await inflateRaw(compressed, record.size, record.name);
- if (data.byteLength !== record.size) throw new Error(`ZIP 内的文件解压大小不符:${record.name}`);
- extractedBytes += data.byteLength;
+ const { dataOffset, dataEnd } = await resolveLocalRecord(archive, record, directoryOffset);
+ const compressed = archive.slice(dataOffset, dataEnd);
+ let data;
+ let actualChecksum;
+ if (record.method === STORE_METHOD) {
+ data = compressed.slice(0, compressed.size, mimeTypeForPath(record.name));
+ actualChecksum = await crc32Blob(data);
+ } else {
+ const inflated = await inflateRaw(compressed, record.size, record.name);
+ data = inflated.blob.slice(0, inflated.blob.size, mimeTypeForPath(record.name));
+ actualChecksum = inflated.checksum;
+ }
+ if (data.size !== record.size) throw new Error(`ZIP 内的文件解压大小不符:${record.name}`);
+ extractedBytes += data.size;
if (extractedBytes > limits.maxArchiveBytes) throw new Error("ZIP 解压内容超过安全上限");
- if (crc32(data) !== record.checksum) throw new Error(`ZIP 内的文件已损坏:${record.name}`);
- files.set(record.name, new Blob([data], { type: mimeTypeForPath(record.name) }));
+ if (actualChecksum !== record.checksum) throw new Error(`ZIP 内的文件已损坏:${record.name}`);
+ files.set(record.name, data);
onProgress({ completed: index + 1, total: targets.length, name: record.name, extractedBytes });
if ((index + 1) % 8 === 0 && index + 1 < targets.length) await yieldToMain();
}
@@ -183,11 +177,41 @@ export async function openZipBlob(archive, limitsValue = {}) {
};
}
-async function inflateRaw(bytes, expectedSize, name) {
+async function resolveLocalRecord(archive, record, directoryOffset) {
+ const headerBytes = await readBlobBytes(archive, record.localOffset, record.localOffset + 30);
+ if (headerBytes.byteLength !== 30) throw invalidZip();
+ const view = dataView(headerBytes);
+ if (view.getUint32(0, true) !== 0x04034b50) throw invalidZip();
+ const localFlags = view.getUint16(6, true);
+ const localMethod = view.getUint16(8, true);
+ const localChecksum = view.getUint32(14, true);
+ const localCompressedSize = view.getUint32(18, true);
+ const localSize = view.getUint32(22, true);
+ const localNameLength = view.getUint16(26, true);
+ const localExtraLength = view.getUint16(28, true);
+ const localNameEnd = record.localOffset + 30 + localNameLength;
+ const dataOffset = localNameEnd + localExtraLength;
+ const dataEnd = dataOffset + record.compressedSize;
+ if (localNameEnd > directoryOffset || dataEnd > directoryOffset) throw invalidZip();
+ const localNameBytes = await readBlobBytes(archive, record.localOffset + 30, localNameEnd);
+ const localName = new TextDecoder("utf-8", { fatal: true }).decode(localNameBytes);
+ const descriptor = Boolean(record.flags & DATA_DESCRIPTOR_FLAG);
+ if (localFlags !== record.flags || localMethod !== record.method || localName !== record.name) throw invalidZip();
+ if (!descriptor && (localChecksum !== record.checksum || localCompressedSize !== record.compressedSize || localSize !== record.size)) {
+ throw invalidZip();
+ }
+ if (descriptor && ((localChecksum && localChecksum !== record.checksum) ||
+ (localCompressedSize && localCompressedSize !== record.compressedSize) || (localSize && localSize !== record.size))) {
+ throw invalidZip();
+ }
+ return { dataOffset, dataEnd };
+}
+
+async function inflateRaw(compressedBlob, expectedSize, name) {
if (typeof DecompressionStream !== "function") throw new Error("当前浏览器不支持读取压缩 ZIP");
let reader;
try {
- const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
+ const stream = compressedBlob.stream().pipeThrough(new DecompressionStream("deflate-raw"));
reader = stream.getReader();
} catch {
throw new Error(`ZIP 内的文件无法解压:${name}`);
@@ -195,6 +219,7 @@ async function inflateRaw(bytes, expectedSize, name) {
const chunks = [];
let total = 0;
+ let checksum = 0xffffffff;
try {
while (true) {
const { done, value } = await reader.read();
@@ -205,6 +230,7 @@ async function inflateRaw(bytes, expectedSize, name) {
throw new Error(`ZIP 解压内容超过声明大小:${name}`);
}
chunks.push(value);
+ checksum = crc32Update(checksum, value);
}
} catch (error) {
if (total > expectedSize) throw error;
@@ -213,13 +239,30 @@ async function inflateRaw(bytes, expectedSize, name) {
reader.releaseLock();
}
- const data = new Uint8Array(total);
- let offset = 0;
- for (const chunk of chunks) {
- data.set(chunk, offset);
- offset += chunk.byteLength;
+ return { blob: new Blob(chunks), checksum: (checksum ^ 0xffffffff) >>> 0 };
+}
+
+async function readBlobBytes(blob, start, end) {
+ return new Uint8Array(await blob.slice(start, end).arrayBuffer());
+}
+
+function dataView(bytes) {
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+}
+
+async function crc32Blob(blob) {
+ const reader = blob.stream().getReader();
+ let checksum = 0xffffffff;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ checksum = crc32Update(checksum, value);
+ }
+ } finally {
+ reader.releaseLock();
}
- return data;
+ return (checksum ^ 0xffffffff) >>> 0;
}
function makeLocalHeader(name, size, checksum) {
@@ -304,11 +347,7 @@ function mimeTypeForPath(path) {
const extension = path.split(".").pop()?.toLocaleLowerCase("en-US");
if (extension === "json") return "application/json";
if (extension === "md") return "text/markdown";
- if (extension === "png") return "image/png";
- if (extension === "jpg" || extension === "jpeg") return "image/jpeg";
- if (extension === "webp") return "image/webp";
- if (extension === "mp4") return "video/mp4";
- return "application/octet-stream";
+ return assetFormatForExtension(extension)?.mimeTypes?.[0] || "application/octet-stream";
}
function ensureUint32(value, message) {
@@ -317,12 +356,12 @@ function ensureUint32(value, message) {
}
}
-function crc32(bytes) {
- let checksum = 0xffffffff;
+function crc32Update(initial, bytes) {
+ let checksum = initial;
for (let index = 0; index < bytes.length; index += 1) {
checksum = CRC_TABLE[(checksum ^ bytes[index]) & 0xff] ^ (checksum >>> 8);
}
- return (checksum ^ 0xffffffff) >>> 0;
+ return checksum >>> 0;
}
function yieldToMain() {