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. 提示词导演
JavaScript ai-artai-videochrome-extensionclaude-codecodexhiggsfieldjimenglocal-firstmcpmidjourneymoodboardprompt-engineeringprompt-libraryprompt-managerreference-libraryseedancevisual-bookmarksweb-clipper
发布 1.19.0 项目树与可靠批量分析
MigenAId129daa95d1c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 477f1b1..24c6dbc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## 1.19.0++- 项目升级为可嵌套的树形结构:支持空父项目、跨层级拖动、键盘管理、子树去重统计,并无损迁移原有项目、案例归属与顺序。+- 项目内容区会先展示直接子项目,再展示直接案例;分享、批量分析、Composer 与 Skill 来源默认覆盖完整子树。+- 案例勾选管理的“项目”菜单新增批量移出,只解除目标项目关系,不删除案例或影响其他项目。+- 项目树已覆盖回收站恢复、新旧分享包、精选导入与手动同步;完整路径选择始终使用项目 ID,不再依赖可能重名的显示文字。+- 批量 AI 分析改为可并发、可后台恢复的持久任务,修复多结果提交丢失、异常高频重试和中断后不继续执行的问题。+## 1.18.16- 统一创作 Skill、精选 Skill 与创作台参考区的分段导航和卡片密度,去除多余空白、整卡高亮与页面间的尺寸漂移。diff --git a/README.md b/README.mdindex 49730d1..39af0bb 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@ PromptDirector 是一个免费、开源、本地优先的 Chrome 扩展。它把- 高亮网页文字、框选画面或选择页面媒体,将提示词与视觉素材一起保存;- 在图片优先的资料墙中搜索、筛选、标记和管理案例;- 保存本地图片、视频、PDF、Markdown、TXT、HTML、视频时间点笔记和快速笔记;-- 将相关案例整理进项目、组合案例或分享包;+- 用可嵌套的项目树整理案例,并支持组合案例、批量加入或移出项目以及子树分享;- 浏览经过审核的精选案例,并把需要的内容保存进自己的本地资料库;- 把案例提炼成可复用的创作 Skill,在创作台组合案例、Skill 和临时附件;- 生成可编辑的图片或视频提示词,也可以连接自己的服务直接生成媒体;diff --git a/background.js b/background.jsindex 1611d8a..defbf76 100644--- a/background.js+++ b/background.js@@ -184,6 +184,9 @@ import { mergeCuratedLibraryPackage } from "./curated-import.js";import { prepareCuratedSubmissionState } from "./curated-submission.js";import {createCollection,+ collectionPathLabel,+ collectionSelectorLabelsById,+ moveCollection,normalizeOrganizerState,removeEntriesFromOrganizer,reorderCollections,@@ -892,6 +895,7 @@ async function handleMessage(message, interaction = {}) {case "RENAME_COLLECTION":case "DELETE_COLLECTION":case "REORDER_COLLECTIONS":+ case "MOVE_COLLECTION":case "REPLACE_COLLECTION_ENTRIES":case "SET_COLLECTION_VISIBILITY":return enqueue(async () => updateOrganizer(message));@@ -1018,13 +1022,18 @@ async function captureWorkspace() {const name = contentType?.name || "待确认";return [part.sourceUrl || "source:unknown", { id, name, customized: contentType?.customized === true }];}));+ const selectorLabelsByProject = collectionSelectorLabelsById(state.organizerState);return {ok: true,draft,targetEntry,suggestedContentTypeId: suggested?.pathIds?.[0] || "",contentTypes: state.taxonomy.nodes.map((item) => ({ id: item.id, name: item.name, customized: item.customized === true })),- collections: state.organizerState.collections.map((item) => ({ id: item.id, name: item.name })),+ collections: state.organizerState.collections.map((item) => ({+ id: item.id,+ name: selectorLabelsByProject.get(item.id),+ parentId: item.parentId+ })),partContentTypes,activeCreativeResult: state.activeCreativeResult,activeCreativePrompt: activeCreativePromptSummary(state.activeCreativeResult, state.composerSessions),@@ -2574,7 +2583,9 @@ async function deleteCollectionWithEntries(message) {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("这个项目没有可删除的案例");+ if (!collectionEntryIds(organizerState, collection.id, { subtree: true }).length) {+ throw new Error("这个项目及其子项目没有可删除的案例");+ }const moved = moveCollectionWithEntriesToTrash({entries: state.entries,trashState: state.trashState,@@ -2663,11 +2674,13 @@ async function restoreSelectedTrashItems(message = {}) {[STORAGE_KEYS.compoundCases]: restored.compoundCases});const unresolvedMessage = restored.unresolved.length ? `;另有 ${restored.unresolved.length} 项因关系冲突未恢复` : "";+ const warningMessage = restored.warnings?.length ? `;${restored.warnings[0].reason}` : "";return {ok: true,- message: `已恢复 ${restored.restoredItemIds.length} 项${unresolvedMessage}`,+ message: `已恢复 ${restored.restoredItemIds.length} 项${unresolvedMessage}${warningMessage}`,restoredItemIds: restored.restoredItemIds,unresolved: restored.unresolved,+ warnings: restored.warnings ?? [],...publicDomainState({ ...state, ...restored })};}@@ -5086,17 +5099,34 @@ async function batchAddCustomLabels(message) {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";+ const requestedEntryIds = uniqueNames(message.entryIds);+ const entryIds = requestedEntryIds.filter((entryId) => validIds.has(entryId));+ if (!entryIds.length) return { ok: false, message: "案例不存在,未更新项目关系" };+ const missingCount = requestedEntryIds.length - entryIds.length;+ const mode = ["remove", "move"].includes(message.mode) ? message.mode : "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);+ organizerState = setEntriesCollection(organizerState, message.collectionId, entryIds, mode !== "remove");const changedEntryIds = changedProjectEntryIds(beforeOrganizer, organizerState);+ const updatedCount = changedEntryIds.length;+ const skippedCount = Math.max(0, requestedEntryIds.length - updatedCount);+ const unchangedCount = Math.max(0, entryIds.length - updatedCount);+ if (!updatedCount) {+ return {+ ok: true,+ message: `${mode === "remove" ? "所选案例原本不在这个项目中" : "所选案例已经在这个项目中"}${missingCount ? `;${missingCount} 个案例不存在` : ""}`,+ updatedCount,+ skippedCount,+ unchangedCount,+ missingCount,+ entries: state.entries,+ organizerState: beforeOrganizer+ };+ }const entries = touchEntries(state.entries, changedEntryIds);await commitLocalChanges({...(changedEntryIds.length ? { [STORAGE_KEYS.entries]: entries } : {}),@@ -5104,8 +5134,15 @@ async function batchSetProject(message) {});return {ok: true,- message: mode === "move" ? `已将 ${entryIds.length} 个案例移动到项目` : `已将 ${entryIds.length} 个案例加入项目`,- updatedCount: entryIds.length,+ message: mode === "move"+ ? `已将 ${updatedCount} 个案例移动到项目`+ : mode === "remove"+ ? `已将 ${updatedCount} 个案例移出项目${unchangedCount ? `,${unchangedCount} 个原本不在该项目` : ""}${missingCount ? `;${missingCount} 个案例不存在` : ""}`+ : `已将 ${updatedCount} 个案例加入项目${unchangedCount ? `,${unchangedCount} 个已经在该项目` : ""}${missingCount ? `;${missingCount} 个案例不存在` : ""}`,+ updatedCount,+ skippedCount,+ unchangedCount,+ missingCount,entries,organizerState};@@ -5118,7 +5155,7 @@ async function updateOrganizer(message) {let trashState = normalizeTrashState(state.trashState);let created = null;if (message.type === "CREATE_COLLECTION") {- const result = createCollection(organizerState, message.name);+ const result = createCollection(organizerState, message.name, message.parentId);organizerState = result.state;created = result.item;} else if (message.type === "RENAME_COLLECTION") {@@ -5130,6 +5167,8 @@ async function updateOrganizer(message) {trashState = moved.trashState;} else if (message.type === "REORDER_COLLECTIONS") {organizerState = reorderCollections(organizerState, message.collectionIds);+ } else if (message.type === "MOVE_COLLECTION") {+ organizerState = moveCollection(organizerState, message.collectionId, message.parentId, message.index);} 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));@@ -5153,6 +5192,7 @@ function organizerMessage(type) {RENAME_COLLECTION: "项目名称已保存",DELETE_COLLECTION: "项目已移入回收站,案例仍保留在资料库",REORDER_COLLECTIONS: "项目顺序已保存",+ MOVE_COLLECTION: "项目结构已保存",REPLACE_COLLECTION_ENTRIES: "项目案例已更新",SET_COLLECTION_VISIBILITY: "项目显示范围已更新"})[type] || "项目已更新";@@ -5542,6 +5582,10 @@ async function recoverDeepSeekBatch() {}const recovered = recoverInterruptedAnalysisBatch(job);await commitLocalChanges({ [STORAGE_KEYS.batchJob]: recovered });+ if (recovered.status === "running") {+ await ensureAnalysisBatchAlarm(true);+ scheduleAnalysisBatchRunner();+ }return { ok: true, message: "已从上次中断处继续", analysisBatchJob: analysisBatchSummary(recovered) };}@@ -5734,8 +5778,9 @@ async function runPersistedAnalysisBatch() {} catch (error) {console.error("PromptDirector persisted analysis batch failed", error);const stored = await chrome.storage.local.get(STORAGE_KEYS.batchJob).catch(() => ({}));- continueRunning = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob])?.status === "running";- await ensureAnalysisBatchAlarm(continueRunning);+ const stillRunning = normalizeAnalysisBatchJob(stored[STORAGE_KEYS.batchJob])?.status === "running";+ await ensureAnalysisBatchAlarm(stillRunning);+ continueRunning = false;} finally {analysisBatchRunnerActive = false;if (continueRunning) scheduleAnalysisBatchRunner();diff --git a/composer-page.js b/composer-page.jsindex bae4f89..06115b8 100644--- a/composer-page.js+++ b/composer-page.js@@ -72,6 +72,7 @@ import { renderMarkdownDocument } from "./markdown-renderer.js";import { assertImageDimensions } from "./resource-limits.js";import { blobToDataUrl, normalizeVisionSettings } from "./vision.js";import { CONTENT_ROLES, contentRoleForEntry } from "./taxonomy.js";+import { collectionEntryIds, collectionSelectorLabelsById } from "./organizer.js";import { createUiIcon, setUiIcon } from "./ui-icons.js";import {bindUiPreferenceReload,@@ -117,6 +118,7 @@ let composerSearchIndex = [];let composerDocumentTextByEntryId = new Map();let reuseRetrievedSourcesNextTurn = false;let creativeStateRefreshRevision = 0;+let initialProjectFilterId = "";const imageWorkspace = createComposerImageWorkspace({translate: t,@@ -346,6 +348,10 @@ async function initializeComposer() {elements.composerDiagnosticExport.hidden = response.uiPreferences?.analysisDiagnostics !== true;const params = new URLSearchParams(location.search);+ const requestedProjectId = params.get("project");+ if ((organizerState.collections ?? []).some((item) => item.id === requestedProjectId)) {+ initialProjectFilterId = requestedProjectId;+ }const sessionId = params.get("session");const requestedSkillId = params.get("skill");const requestedType = ["image", "video"].includes(params.get("type")) ? params.get("type") : "";@@ -1863,8 +1869,9 @@ function renderReferencePicker() {}function renderProjectFilter() {- const selected = elements.composerReferenceProjectFilter.value;- const options = [["", t("全部项目")], ...(organizerState.collections ?? []).map((item) => [item.id, item.name])];+ const selected = elements.composerReferenceProjectFilter.value || initialProjectFilterId;+ const selectorLabelsByProject = collectionSelectorLabelsById(organizerState);+ const options = [["", t("全部项目")], ...(organizerState.collections ?? []).map((item) => [item.id, selectorLabelsByProject.get(item.id)])];elements.composerReferenceProjectFilter.replaceChildren(...options.map(([value, label]) => {const option = document.createElement("option");option.value = value;@@ -1872,6 +1879,7 @@ function renderProjectFilter() {return option;}));elements.composerReferenceProjectFilter.value = options.some(([value]) => value === selected) ? selected : "";+ initialProjectFilterId = "";}function renderSkills() {@@ -1912,7 +1920,7 @@ function renderCasePicker() {const query = elements.composerReferenceSearch.value.trim().toLocaleLowerCase();const projectId = elements.composerReferenceProjectFilter.value;const projectIds = projectId- ? new Set((organizerState.collections ?? []).find((item) => item.id === projectId)?.entryIds ?? [])+ ? new Set(collectionEntryIds(organizerState, projectId, { subtree: true })): null;const targetType = composerSession?.targetType === "video" ? "video" : "image";const eligible = entries.filter((entry) => isComposerEligibleEntry(entry, targetType)).filter((entry) => {diff --git a/curated-catalog.js b/curated-catalog.jsindex 166ca60..2e913d2 100644--- a/curated-catalog.js+++ b/curated-catalog.js@@ -208,10 +208,15 @@ export function prepareCuratedPackageVersion(libraryValue = {}, itemValue) {return next;});if (library.organizerState?.collections) {- library.organizerState.collections = library.organizerState.collections.map((collection, index) => ({+ const collectionIds = new Map(library.organizerState.collections.map((collection, index) => [+ clean(collection.id),+ `${prefix}:collection:${safeId(collection.id || index)}`+ ]));+ library.organizerState.collections = library.organizerState.collections.map((collection) => ({...collection,- id: `${prefix}:collection:${safeId(collection.id || index)}`,- entryIds: (collection.entryIds ?? []).map((id) => entryIds.get(id)).filter(Boolean),+ id: collectionIds.get(clean(collection.id)),+ parentId: collectionIds.get(clean(collection.parentId)) ?? null,+ entryIds: (collection.entryIds ?? []).map((id) => entryIds.get(id)).filter(Boolean)}));}return library;@@ -231,11 +236,26 @@ export function prepareCuratedEntriesPackage(libraryValue = {}, entryIdValues =const selected = selectLibraryPackage(libraryValue, entryIds);if (selected.entries.length !== entryIds.length) throw new Error("精选案例批次不完整,无法保存");const selectedIds = new Set(entryIds);+ const collections = Array.isArray(libraryValue.organizerState?.collections)+ ? libraryValue.organizerState.collections+ : [];+ const byId = new Map(collections.map((collection) => [clean(collection.id), collection]));+ const includedIds = new Set(collections+ .filter((collection) => (collection.entryIds ?? []).some((id) => selectedIds.has(id)))+ .map((collection) => clean(collection.id)));+ for (const collectionId of [...includedIds]) {+ let parentId = clean(byId.get(collectionId)?.parentId);+ while (parentId && byId.has(parentId) && !includedIds.has(parentId)) {+ includedIds.add(parentId);+ parentId = clean(byId.get(parentId)?.parentId);+ }+ }selected.organizerState = {...(selected.organizerState ?? {}),- collections: (libraryValue.organizerState?.collections ?? []).flatMap((collection) => {+ collections: collections.flatMap((collection) => {+ if (!includedIds.has(clean(collection.id))) return [];const memberIds = (collection.entryIds ?? []).filter((id) => selectedIds.has(id));- return memberIds.length ? [{ ...structuredClone(collection), entryIds: memberIds }] : [];+ return [{ ...structuredClone(collection), entryIds: memberIds }];})};return selected;diff --git a/curated-import.js b/curated-import.jsindex adbfa82..a9f4714 100644--- a/curated-import.js+++ b/curated-import.js@@ -1,6 +1,6 @@import { curatedSourceKey } from "./curated-catalog.js";import { mergeLibraryPackage } from "./library-package.js";-import { COLLECTION_VISIBILITY, normalizeOrganizerState } from "./organizer.js";+import { COLLECTION_VISIBILITY, createDefaultOrganizerState, normalizeOrganizerState } from "./organizer.js";export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {}, options = {}) {const packageId = clean(options.packageId);@@ -41,7 +41,7 @@ export function mergeCuratedLibraryPackage(currentValue = {}, libraryValue = {},if (existing) existingSourceEntryIds.add(sourceEntryId);}remapEntryRelationships(imported, originalToAdaptedId);- imported.organizerState = { version: 6, collections: [] };+ imported.organizerState = createDefaultOrganizerState();const result = mergeLibraryPackage(current, imported, {entryIdMap: remapPreferredIds(options.entryIdMap, originalToAdaptedId),diff --git a/curated-submission.js b/curated-submission.jsindex 662506c..70649f7 100644--- a/curated-submission.js+++ b/curated-submission.js@@ -1,5 +1,6 @@import { selectLibraryPackage, selectProjectPackage } from "./library-package.js";import { normalizeEntryMedia } from "./media.js";+import { createDefaultOrganizerState } from "./organizer.js";export const CURATED_SUBMISSION_FORMAT = "prompt-director-curated-submission";export const CURATED_SUBMISSION_VERSION = 1;@@ -30,7 +31,7 @@ export function prepareCuratedSubmissionState(stateValue = {}, selection = {}) {taxonomy,facetCatalog: { version: 2, revision: 1, facets: [], nodes: [] },classificationRules: [],- organizerState: { version: 4, collections: [], projectMethods: {} },+ organizerState: createDefaultOrganizerState(),compoundCases: []}};diff --git a/design-qa.md b/design-qa.mdindex 4e4b99f..5aabf01 100644--- a/design-qa.md+++ b/design-qa.md@@ -89,7 +89,7 @@ The focused comparison confirms that the batch bar no longer looks like a second- Spacing and layout rhythm: entering selection mode preserves the first card at the same vertical coordinate; the automated measurement was `114 px` before and after. Desktop actions stay on one 34 px row. The 390 px toolbar floats at the bottom without changing document width.- Colors and visual tokens: existing dark/light surfaces, restrained borders, lime primary action, danger action, and focus ring are reused. No new palette or gradient was introduced.- Image and icon fidelity: existing local UI sprite icons are reused. Selection circles were normalized to 24 px with one restrained edge and the existing lime checked state; no replacement image assets were required.-- Copy and content: zero-selection copy is reduced to `已选 0`, `全选当前(数量)`, and `取消`. Selected-only actions are grouped under `加标签`, `加入项目`, `分享`, and `更多` while all prior capabilities remain available.+- Copy and content: zero-selection copy is reduced to `已选 0`, `全选当前(数量)`, and `取消`. Selected-only actions are grouped under `加标签`, `项目(加入 / 移出)`, `分享`, and `更多` while all prior capabilities remain available.### Findingsdiff --git a/i18n.js b/i18n.jsindex 603d0c0..ae13efe 100644--- a/i18n.js+++ b/i18n.js@@ -230,6 +230,10 @@ const EN = Object.freeze({"这个来源已经保存过": "This source has already been saved","有可用更新": "Update available","管理项目顺序": "Manage project order",+ "管理项目结构": "Manage project structure",+ "移到根级": "Move to root",+ "项目树": "Project tree",+ "子项目": "Subprojects","调整项目侧栏宽度": "Resize project sidebar","管理案例顺序": "Manage case order","关闭分享": "Close sharing",@@ -796,6 +800,10 @@ const EN = Object.freeze({"选择目标项目": "Choose a target project","加入项目": "Add to project","加入项目…": "Add to project...",+ "选择项目…": "Choose a project...",+ "移出项目": "Remove from project",+ "新建项目并加入": "Create project and add",+ "新建时,所选项目作为父项目;不选则创建在根级。": "When creating, the selected project becomes the parent; leave it empty to create at the root.","加入": "Add","组合": "Combine","分享": "Share",diff --git a/library-package-format.js b/library-package-format.jsindex ac30ebe..c02f654 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 = 4;-export const SUPPORTED_LIBRARY_PACKAGE_VERSIONS = Object.freeze([1, 2, 3, 4]);+export const CURRENT_LIBRARY_PACKAGE_VERSION = 5;+export const SUPPORTED_LIBRARY_PACKAGE_VERSIONS = Object.freeze([1, 2, 3, 4, 5]);export function isSupportedLibraryPackageVersion(value) {return Number.isInteger(value) && SUPPORTED_LIBRARY_PACKAGE_VERSIONS.includes(value);diff --git a/library-package.js b/library-package.jsindex d3c5c32..1cb834e 100644--- a/library-package.js+++ b/library-package.js@@ -1,7 +1,13 @@import { normalizeFacetCatalog, uniqueNames } from "./facets.js";import { normalizeSettings } from "./lib.js";import { SCHEMA_VERSION, mergeTaxonomies, normalizeTaxonomy } from "./taxonomy.js";-import { createDefaultOrganizerState, mergeOrganizerState, normalizeOrganizerState } from "./organizer.js";+import {+ collectionEntryIds,+ collectionSubtreeIds,+ createDefaultOrganizerState,+ mergeOrganizerState,+ normalizeOrganizerState+} from "./organizer.js";import { normalizeComposerSessions, normalizeComposerSettings } from "./composer.js";import { normalizeCreativeExperimentSettings, normalizeCreativeRuns } from "./creative-runs.js";import { mergeCreativeSkillsState, normalizeCreativeSkillsState } from "./creative-skills.js";@@ -45,6 +51,9 @@ export function parseLibraryPackage(value, files = new Map(), limitsValue = {})if (value.entries.length > limits.maxEntries) {throw new Error(`案例数量超过 ${limits.maxEntries} 条上限`);}+ if (Array.isArray(value.organizerState?.collections) && value.organizerState.collections.length > limits.maxCollections) {+ throw new Error(`项目数量超过 ${limits.maxCollections} 个上限`);+ }const data = structuredClone(value);data.settings = normalizeSettings(data.settings);data.taxonomy = normalizeTaxonomy(data.taxonomy);@@ -262,17 +271,21 @@ export function selectProjectPackage(state = {}, collectionId) {const organizer = normalizeOrganizerState(state.organizerState, (state.entries ?? []).map((entry) => entry.id));const collection = organizer.collections.find((item) => item.id === clean(collectionId));if (!collection) throw new Error("项目不存在");- if (!collection.entryIds.length) throw new Error("这个项目还没有可分享的案例");+ const subtreeIds = collectionSubtreeIds(organizer, collection.id);+ if (!collectionEntryIds(organizer, collection.id, { subtree: true }).length) throw new Error("这个项目及其子项目还没有可分享的案例");const exportedEntryIds = projectPackageEntryIds(state, collection.id);const selected = selectLibraryPackage(state, exportedEntryIds);+ const selectedEntryIds = new Set(selected.entries.map((entry) => entry.id));selected.organizerState = normalizeOrganizerState({version: organizer.version,- collections: [{- id: collection.id,- name: collection.name,- order: 0,- entryIds: exportedEntryIds- }]+ collections: organizer.collections+ .filter((item) => subtreeIds.includes(item.id))+ .map((item) => ({+ ...structuredClone(item),+ parentId: item.id === collection.id ? null : item.parentId,+ order: item.id === collection.id ? 0 : item.order,+ entryIds: item.entryIds.filter((entryId) => selectedEntryIds.has(entryId))+ }))}, selected.entries.map((entry) => entry.id));return selected;}@@ -283,7 +296,7 @@ export function projectPackageEntryIds(state = {}, collectionId) {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 selectedIds = collectionEntryIds(organizer, collection.id, { subtree: true });const selectedSet = new Set(selectedIds);for (const compound of normalizeCompoundCases(state.compoundCases, entries)) {if (!compound.memberEntryIds.some((entryId) => selectedSet.has(entryId))) continue;diff --git a/library-selection.js b/library-selection.jsindex e2464e4..b0aa5d8 100644--- a/library-selection.js+++ b/library-selection.js@@ -7,7 +7,7 @@ export const LIBRARY_BATCH_ACTIONS = Object.freeze({moveToTrash: "BATCH_MOVE_TO_TRASH"});-const PROJECT_MODES = new Set(["add", "move"]);+const PROJECT_MODES = new Set(["add", "remove", "move"]);export function normalizeSelectedLogicalCaseIds(values = []) {return uniqueIds(values);@@ -50,7 +50,7 @@ export function buildLibraryBatchPayload(selectedLogicalCaseIds = [], compoundCaconst collectionId = clean(operation.collectionId);const mode = clean(operation.mode);if (!collectionId) throw new Error("请选择项目");- if (!PROJECT_MODES.has(mode)) throw new Error("项目批量操作必须明确选择添加或移动");+ if (!PROJECT_MODES.has(mode)) throw new Error("项目批量操作必须明确选择加入、移出或移动");return {type: LIBRARY_BATCH_ACTIONS.setProject,entryIds,diff --git a/library.css b/library.cssindex 9c4f65f..eb6484a 100644--- a/library.css+++ b/library.css@@ -290,7 +290,17 @@ details:not([open]) > .selection-menu-panel { display: none; }.project-section { margin-bottom: 18px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }.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 {+ position: relative;+ display: grid;+ grid-template-columns: 18px minmax(0, 1fr) auto;+ align-items: center;+ gap: 3px;+ padding-left: calc(var(--project-depth, 0) * 16px);+}+.project-disclosure { display: grid; width: 18px; min-height: 28px; place-items: center; padding: 0; color: var(--muted); border: 0; background: transparent; }+.project-disclosure .ui-icon { width: 13px; height: 13px; }+.project-disclosure.is-placeholder { visibility: hidden; }.project-row.project-ordering {border: 1px solid transparent;border-radius: var(--ui-container-radius);@@ -310,8 +320,15 @@ details:not([open]) > .selection-menu-panel { display: none; }box-shadow: var(--shadow);opacity: .94;}+.project-row.drop-before::before,+.project-row.drop-after::after { content: ""; position: absolute; z-index: 6; right: 4px; left: calc(var(--project-depth, 0) * 16px + 4px); height: 2px; border-radius: 2px; background: var(--accent-emphasis); }+.project-row.drop-before::before { top: -3px; }+.project-row.drop-after::after { bottom: -3px; }+.project-row.drop-inside { border-color: var(--accent-emphasis); background: var(--selection); }.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-root-drop { min-height: 34px; border: 1px dashed var(--line); border-radius: var(--ui-container-radius); padding: 8px; color: var(--muted); font-size: 11px; font-weight: 700; text-align: center; }+.project-root-drop.is-drop-target { border-color: var(--accent-emphasis); color: var(--accent-ink); background: var(--selection); }.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-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; }@@ -326,6 +343,8 @@ details:not([open]) > .selection-menu-panel { display: none; }.project-menu-panel .project-menu-primary { color: var(--accent-contrast); border-color: var(--accent); background: var(--accent); }.project-menu-panel .quiet-danger { border-color: color-mix(in srgb, var(--danger) 18%, var(--line)); background: color-mix(in srgb, var(--danger) 5%, var(--card)); }.project-menu-panel .button-secondary + .quiet-danger { margin-top: 4px; }+.selection-project-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }+.selection-project-actions button { min-width: 0; }.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; }@@ -347,6 +366,15 @@ details:not([open]) > .selection-menu-panel { display: none; }.pending-switch { display: flex; align-items: center; gap: 8px; color: var(--warning); font-size: 11px; }.pending-switch input { width: auto; min-height: auto; accent-color: var(--warning); }.pending-switch strong { margin-left: auto; }+.project-folder-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 10px; margin-bottom: 14px; }+.project-folder-list:empty { display: none; }+.project-folder-card { display: grid; min-width: 0; grid-template-columns: 28px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 58px; padding: 10px 12px; color: var(--ink); border: 1px solid var(--line); border-radius: var(--ui-container-radius); background: var(--card); text-align: left; box-shadow: var(--ui-card-shadow); }+.project-folder-card:hover { border-color: var(--selection-edge); background: var(--selection-hover); }+.project-folder-card > .ui-icon { width: 24px; height: 24px; color: var(--accent-ink); }+.project-folder-copy { display: grid; min-width: 0; gap: 2px; }+.project-folder-name { overflow: hidden; font-weight: 750; text-overflow: ellipsis; white-space: nowrap; }+.project-folder-meta { color: var(--muted); font-size: 11px; }+.project-folder-arrow { color: var(--muted); }.facet-filters { display: grid; gap: 0; margin-top: 4px; border-top: 1px solid var(--line); padding-top: 5px; }.facet-filter { border-top: 1px solid var(--line); }.facet-filter:first-child { border-top: 0; }@@ -910,6 +938,7 @@ details:not([open]) > .selection-menu-panel { display: none; }}@media (max-width: 640px) {+ body:has(#share-bar:not([hidden])) #feedback { --ui-feedback-bottom: 82px; }.gallery-heading #manage-case-order,.filter-heading #manage-project-order,.case-reorder-controls button,diff --git a/library.html b/library.htmlindex 678dc58..03074ad 100644--- a/library.html+++ b/library.html@@ -51,8 +51,9 @@<button id="open-skills" 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-wand-sparkles"></use></svg><span data-i18n="创作 Skill">创作 Skill</span></button></nav><section id="project-section" class="project-section">- <div class="filter-heading"><strong data-i18n="项目">项目</strong><span><button id="create-collection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-plus"></use></svg><span data-i18n="新建">新建</span></button><button id="manage-project-order" class="icon-button" type="button" aria-label="管理项目顺序" title="管理项目顺序" data-i18n-aria-label="管理项目顺序" data-i18n-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>+ <div class="filter-heading"><strong data-i18n="项目">项目</strong><span><button id="create-collection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-plus"></use></svg><span data-i18n="新建">新建</span></button><button id="manage-project-order" class="icon-button" type="button" aria-label="管理项目结构" title="管理项目结构" data-i18n-aria-label="管理项目结构" data-i18n-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="project-root-drop" class="project-root-drop" hidden data-i18n="移到根级">移到根级</div>+ <div id="collection-filters" class="project-list" role="tree" aria-label="项目树" data-i18n-aria-label="项目树"></div><p id="project-order-status" class="sr-only" role="status" aria-live="polite"></p></section><section class="sidebar-trash-section">@@ -92,11 +93,15 @@</div></details><details id="selection-project-menu" class="selection-menu">- <summary aria-label="加入项目" data-i18n-aria-label="加入项目"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span class="selection-action-label" data-i18n="加入项目">加入项目</span></summary>+ <summary aria-label="项目" data-i18n-aria-label="项目"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-folder"></use></svg><span class="selection-action-label" data-i18n="项目">项目</span></summary><div class="project-menu-panel selection-menu-panel selection-project-panel">- <label><span data-i18n="选择目标项目">选择目标项目</span><select id="selection-project-target" aria-label="选择目标项目" data-i18n-aria-label="选择目标项目"><option value="" data-i18n="加入项目…">加入项目…</option></select></label>- <button id="selection-add-project" class="project-menu-primary" type="button" disabled data-i18n="加入">加入</button>- <button id="selection-new-project" class="button-secondary" type="button" disabled data-i18n="新建项目">新建项目</button>+ <label><span data-i18n="选择目标项目">选择目标项目</span><select id="selection-project-target" aria-label="选择目标项目" data-i18n-aria-label="选择目标项目"><option value="" data-i18n="选择项目…">选择项目…</option></select></label>+ <div class="selection-project-actions">+ <button id="selection-add-project" class="project-menu-primary" type="button" disabled data-i18n="加入项目">加入项目</button>+ <button id="selection-remove-project" class="button-secondary" type="button" disabled data-i18n="移出项目">移出项目</button>+ </div>+ <button id="selection-new-project" class="button-secondary" type="button" disabled data-i18n="新建项目并加入">新建项目并加入</button>+ <small data-i18n="新建时,所选项目作为父项目;不选则创建在根级。">新建时,所选项目作为父项目;不选则创建在根级。</small></div></details><button id="share-export" type="button" disabled data-i18n="分享">分享</button>@@ -123,6 +128,7 @@</div></div><p id="feedback" class="ui-feedback-toast" role="status" aria-live="polite"></p>+ <section id="project-folder-list" class="project-folder-list" aria-label="子项目" data-i18n-aria-label="子项目"></section><section id="case-list" class="masonry" aria-live="polite"></section><div id="load-sentinel" class="load-sentinel" aria-hidden="true"></div><button id="load-more" class="button-secondary load-more" type="button" hidden></button>diff --git a/library.js b/library.jsindex e37b8f3..f0d8e04 100644--- a/library.js+++ b/library.js@@ -121,7 +121,17 @@ import {import { ensureYouTubePlaybackPermission, youtubePlaybackError } from "./media-playback.js";import { createPdfPreview, createPdfViewer, extractPdfSearchText } from "./document-viewer.js";import { markdownPlainText, renderMarkdownDocument } from "./markdown-renderer.js";-import { COLLECTION_VISIBILITY, isEntryVisibleInLibrary } from "./organizer.js";+import {+ COLLECTION_VISIBILITY,+ collectionEntryIds,+ collectionPath,+ collectionPathLabel,+ collectionPathLabelsById,+ collectionSelectorLabelsById,+ collectionSubtreeEntryIdsById,+ collectionSubtreeIds,+ isEntryVisibleInLibrary+} from "./organizer.js";import { promptForEntryImage, visualAnalysisPromptReplacement } from "./image-prompt.js";import {CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY,@@ -149,7 +159,7 @@ import {serializeLibraryReturnSnapshot} from "./navigation-state.js";import { CURATED_SUBMISSION_URL } from "./curated-config.js";-import { moveProjectLogicalCase, sortLibraryCases, sortProjects } from "./library-view.js";+import { moveProjectLogicalCase, sortLibraryCases } 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";@@ -160,7 +170,7 @@ bindTransientMenus(document, ".package-menu, .project-menu, .detail-analysis-menconst libraryWindowId = (await chrome.windows.getCurrent()).id;const elements = Object.fromEntries([- "about-version", "add-folder", "add-media", "add-video-reference", "ai-settings-form", "ai-settings-status", "ai-routing-summary", "ai-provider-list", "ai-assignment-list", "open-ai-routing", "analysis-instructions-en", "analysis-instructions-zh", "analysis-protocol", "apply-reanalyze", "case-list", "cancel-library-maintenance",+ "about-version", "add-folder", "add-media", "add-video-reference", "ai-settings-form", "ai-settings-status", "ai-routing-summary", "ai-provider-list", "ai-assignment-list", "open-ai-routing", "analysis-instructions-en", "analysis-instructions-zh", "analysis-protocol", "apply-reanalyze", "case-list", "project-folder-list", "cancel-library-maintenance","content-filters", "content-type-count", "content-type-name", "content-type-replacement", "content-type-replacement-field", "content-type-role", "content-type-role-help","content-type-list", "content-type-editor", "content-type-editor-title", "content-type-delete-transfer", "content-type-delete-message","add-content-type", "cancel-content-type-edit", "cancel-delete-content-type", "confirm-delete-content-type", "save-content-type",@@ -177,8 +187,8 @@ const elements = Object.fromEntries(["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", "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-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", "selection-selected-actions", "show-analysis-diagnostics", "ui-locale", "ui-theme", "ui-motion", "vocabulary-tree",+ "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-remove-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", "project-root-drop", "manage-project-order", "selection-simple-actions", "selection-selected-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", "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", "cancel-sync", "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",@@ -256,6 +266,8 @@ let caseOrderManagementActive = false;let projectOrderManagementActive = false;let projectOrderSaving = false;let projectDragState = null;+const expandedProjectIds = new Set();+let selectionProjectTargetTouched = false;let selectedFacets = new Map();let activeManagerTab = "content-types";let selectedVocabularyFacet = "";@@ -335,6 +347,14 @@ const importTagEditor = createTagEditor({elements.importLabelEditor.replaceChildren(importTagEditor.element);const importProjectCombobox = attachProjectCombobox(elements.importProject, { projects: [] });+function projectComboboxCollections() {+ const labelsById = collectionSelectorLabelsById(organizerState);+ return organizerState.collections.map((collection) => ({+ ...collection,+ pathLabel: labelsById.get(collection.id)+ }));+}+const mobileLayout = matchMedia("(max-width: 640px)");if (mobileLayout.matches) workspace.classList.add("filters-collapsed");mobileLayout.addEventListener("change", (event) => {@@ -641,7 +661,7 @@ function bindEvents() {elements.libraryNameSetting.addEventListener("input", updateLibrarySettingsSaveState);elements.exportPathSetting.addEventListener("input", updateLibrarySettingsSaveState);elements.selectCases.addEventListener("click", enterSelectMode);- elements.startCompose.addEventListener("click", openComposerPage);+ elements.startCompose.addEventListener("click", () => openComposerPage(selectedCollectionId));elements.shareCancel.addEventListener("click", exitSelectionMode);elements.shareExport.addEventListener("click", completeSelection);elements.shareDialogClose.addEventListener("click", closeShareDialog);@@ -666,10 +686,14 @@ function bindEvents() {});elements.selectionAddLabels.addEventListener("click", addLabelsToSelection);elements.selectionAddProject.addEventListener("click", addSelectionToProject);+ elements.selectionRemoveProject.addEventListener("click", removeSelectionFromProject);elements.selectionNewProject.addEventListener("click", createProjectFromSelection);elements.selectionAnalyze.addEventListener("click", analyzeSelectedCases);elements.selectionTrash.addEventListener("click", moveSelectionToTrash);- elements.selectionProjectTarget.addEventListener("change", updateSelectionBar);+ elements.selectionProjectTarget.addEventListener("change", () => {+ selectionProjectTargetTouched = true;+ updateSelectionBar();+ });elements.openTrash.addEventListener("click", openTrashDialog);elements.trashClose.addEventListener("click", () => elements.trashDialog.close());elements.trashRestoreAll.addEventListener("click", restoreAllTrashItems);@@ -989,7 +1013,9 @@ function renderGallery() {: logicalCases.filter((entry) => (entry.memberEntryIds ?? [entry.id]).some((entryId) => isEntryVisibleInLibrary(organizerState, entryId)));const projectEntryIds = selectedCollectionId && selectionMode !== "project"- ? new Set(organizerState.collections.find((item) => item.id === selectedCollectionId)?.entryIds ?? [])+ ? new Set(selectionMode === "vision"+ ? collectionEntryIds(organizerState, selectedCollectionId, { subtree: true })+ : organizerState.collections.find((item) => item.id === selectedCollectionId)?.entryIds ?? []): null;let galleryEntries = projectEntryIds? modeEntries.filter((entry) => entry.memberEntryIds@@ -1050,6 +1076,7 @@ function renderGalleryResults({ refreshNavigation }) {const project = selectedCollectionId? organizerState.collections.find((item) => item.id === selectedCollectionId): null;+ const childProjects = project ? projectChildren(project.id) : [];visibleEntries = sortLibraryCases(visibleEntries, {mode: caseSortMode,projectEntryIds: project?.entryIds ?? []@@ -1057,6 +1084,7 @@ function renderGalleryResults({ refreshNavigation }) {renderedCount = 0;imageObserver.disconnect();reconcileInitialCaseCards();+ renderProjectFolderCards(childProjects);if (refreshNavigation) {renderProjectFilters();elements.workspaceLibrary.setAttribute("aria-current", selectedCollectionId ? "false" : "page");@@ -1076,14 +1104,45 @@ function renderGalleryResults({ refreshNavigation }) {loadObserver.observe(elements.loadSentinel);scheduleLoadCheck(generation);});- elements.emptyState.hidden = visibleEntries.length > 0;+ elements.emptyState.hidden = visibleEntries.length > 0 || childProjects.length > 0;elements.emptyLibrary.hidden = logicalCases.length > 0;elements.emptyFilter.hidden = logicalCases.length === 0;renderEmptyFilter();- elements.resultCount.textContent = translateUiMessage(`${visibleEntries.length} 个案例`);+ elements.libraryTitle.textContent = project?.name || libraryTitleForLocale(settings.libraryTitle, currentLocale());+ elements.resultCount.textContent = project+ ? `${visibleEntries.length} 个直接案例 · ${childProjects.length} 个子项目`+ : translateUiMessage(`${visibleEntries.length} 个案例`);elements.pendingCount.textContent = String(pendingCount);}+function renderProjectFolderCards(childProjects) {+ if (!elements.projectFolderList) return;+ const cards = childProjects.map((collection) => {+ const button = el("button", "project-folder-card");+ button.type = "button";+ button.dataset.collectionId = collection.id;+ button.setAttribute("aria-label", `进入子项目 ${collection.name}`);+ const directCases = collection.entryIds.length;+ const nestedProjects = collectionSubtreeIds(organizerState, collection.id).length - 1;+ const copy = el("span", "project-folder-copy");+ copy.append(+ rawTextEl("span", "project-folder-name", collection.name),+ rawTextEl("span", "project-folder-meta", `${directCases} 个直接案例${nestedProjects ? ` · ${nestedProjects} 个下级项目` : ""}`)+ );+ button.append(createUiIcon("folder"), copy, createUiIcon("chevron-right"));+ button.lastElementChild.classList.add("project-folder-arrow");+ button.addEventListener("click", () => {+ selectedCollectionId = collection.id;+ expandedProjectIds.add(collection.parentId);+ caseOrderManagementActive = false;+ renderGallery();+ window.scrollTo({ top: 0, behavior: uiPreferences.motion === "reduced" ? "auto" : "smooth" });+ });+ return button;+ });+ elements.projectFolderList.replaceChildren(...cards);+}+function projectManualOrderAvailable() {return Boolean(selectedCollectionId && !selectionMode &&!selectedContentId && !selectedFacets.size && !elements.pendingFilter.checked && !elements.searchInput.value.trim());@@ -1525,24 +1584,63 @@ async function extractAndCachePdfText(assetId, blob, derived) {function renderProjectFilters() {const fragment = document.createDocumentFragment();- const collections = sortProjects(organizerState.collections, "manual");+ const subtreeEntryIdsByProject = collectionSubtreeEntryIdsById(organizerState);+ const pathLabelsByProject = collectionPathLabelsById(organizerState);+ const childrenByParent = indexProjectChildren();const projectOrderingUnavailable = Boolean(selectionMode);elements.manageProjectOrder.hidden = false;elements.manageProjectOrder.disabled = projectOrderingUnavailable;const managementLabel = projectOrderingUnavailable- ? "结束案例选择后可排序项目"- : projectOrderManagementActive ? "完成项目排序" : "管理项目顺序";+ ? "结束案例选择后可管理项目结构"+ : 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()) {+ elements.projectRootDrop.hidden = !projectOrderManagementActive;+ if (selectedCollectionId) {+ for (const ancestor of collectionPath(organizerState, selectedCollectionId).slice(0, -1)) expandedProjectIds.add(ancestor.id);+ }+ const visibleCollections = [];+ const pendingCollections = [...(childrenByParent.get(null) ?? [])]+ .reverse()+ .map((collection) => ({ collection, depth: 0 }));+ while (pendingCollections.length) {+ const current = pendingCollections.pop();+ visibleCollections.push(current);+ if (!expandedProjectIds.has(current.collection.id)) continue;+ const children = childrenByParent.get(current.collection.id) ?? [];+ for (let index = children.length - 1; index >= 0; index -= 1) {+ pendingCollections.push({ collection: children[index], depth: current.depth + 1 });+ }+ }+ for (const [projectIndex, { collection, depth }] of visibleCollections.entries()) {+ const children = childrenByParent.get(collection.id) ?? [];+ const siblings = childrenByParent.get(collection.parentId) ?? [];const row = el("div", "project-row");row.dataset.collectionId = collection.id;- row.setAttribute("role", "listitem");+ row.style.setProperty("--project-depth", String(depth));+ row.setAttribute("role", "treeitem");+ row.setAttribute("aria-level", String(depth + 1));+ row.setAttribute("aria-setsize", String(siblings.length));+ row.setAttribute("aria-posinset", String(siblings.findIndex((item) => item.id === collection.id) + 1));+ if (children.length) row.setAttribute("aria-expanded", String(expandedProjectIds.has(collection.id)));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;+ row.setAttribute("aria-label", projectOrderManagementActive ? `移动项目:${pathLabelsByProject.get(collection.id)},树中位置 ${projectIndex + 1}` : collection.name);+ const disclosure = el("button", "project-disclosure");+ disclosure.type = "button";+ disclosure.tabIndex = -1;+ disclosure.disabled = projectOrderManagementActive;+ disclosure.setAttribute("aria-label", expandedProjectIds.has(collection.id) ? `折叠 ${collection.name}` : `展开 ${collection.name}`);+ disclosure.classList.toggle("is-placeholder", !children.length);+ if (children.length) disclosure.append(createUiIcon(expandedProjectIds.has(collection.id) ? "chevron-down" : "chevron-right"));+ disclosure.addEventListener("click", () => {+ if (expandedProjectIds.has(collection.id)) expandedProjectIds.delete(collection.id);+ else expandedProjectIds.add(collection.id);+ renderProjectFilters();+ });+ const logicalCount = new Set((subtreeEntryIdsByProject.get(collection.id) ?? [])+ .map((id) => logicalIdByEntryId.get(id)).filter(Boolean)).size;const filter = el("button", "project-filter");filter.type = "button";filter.tabIndex = projectOrderManagementActive ? -1 : 0;@@ -1589,16 +1687,37 @@ function renderProjectFilters() {actions.append(manage, analyze, share, visibility, rename, remove, removeWithEntries);menu.append(summary, actions);if (projectOrderManagementActive) bindProjectOrderInteractions(row, collection);- row.append(filter, menu);+ else bindProjectTreeNavigation(row, collection);+ row.append(disclosure, filter, menu);fragment.append(row);}elements.collectionFilters.replaceChildren(fragment);}+function projectChildren(parentId = null) {+ return indexProjectChildren().get(parentId || null) ?? [];+}++function indexProjectChildren() {+ const result = new Map();+ for (const collection of organizerState.collections) {+ const children = result.get(collection.parentId) ?? [];+ children.push(collection);+ result.set(collection.parentId, children);+ }+ for (const children of result.values()) {+ children.sort((left, right) => left.order - right.order || left.name.localeCompare(right.name, "zh-CN"));+ }+ return result;+}+function toggleProjectOrderManagement() {if (selectionMode) return;cancelProjectDrag();projectOrderManagementActive = !projectOrderManagementActive;+ if (projectOrderManagementActive) {+ for (const parentId of indexProjectChildren().keys()) if (parentId) expandedProjectIds.add(parentId);+ }renderProjectFilters();}@@ -1613,7 +1732,7 @@ function bindProjectOrderInteractions(row, collection) {collectionId: collection.id,startY: event.clientY,moved: false,- beforeIds: sortProjects(organizerState.collections, "manual").map((item) => item.id)+ drop: null};try { row.setPointerCapture(event.pointerId); } catch {}});@@ -1625,30 +1744,31 @@ function bindProjectOrderInteractions(row, collection) {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 {}+ clearProjectDropIndicators();+ const hit = document.elementFromPoint(event.clientX, event.clientY);+ if (hit?.closest?.("#project-root-drop")) {+ elements.projectRootDrop.classList.add("is-drop-target");+ drag.drop = { parentId: null, index: projectChildren(null).filter((item) => item.id !== collection.id).length };+ return;}+ const targetRow = hit?.closest?.(".project-row");+ if (!targetRow || targetRow === row) return;+ const target = organizerState.collections.find((item) => item.id === targetRow.dataset.collectionId);+ if (!target) return;+ const rect = targetRow.getBoundingClientRect();+ const ratio = (event.clientY - rect.top) / Math.max(1, rect.height);+ const position = ratio < .28 ? "before" : ratio > .72 ? "after" : "inside";+ targetRow.classList.add(`drop-${position}`);+ drag.drop = projectDropPlan(collection.id, target, position);});const finish = (event) => {const drag = projectDragState;if (!drag || drag.row !== row || drag.pointerId !== event.pointerId) return;const moved = drag.moved;- const beforeIds = drag.beforeIds;+ const drop = drag.drop;cancelProjectDrag();- if (!moved) return;- const collectionIds = projectIdsFromRenderedRows();- if (collectionIds.every((id, index) => id === beforeIds[index])) return;- void persistProjectCollectionOrder(collectionIds, collection.id);+ if (!moved || !drop) return;+ void persistProjectCollectionMove(collection.id, drop.parentId, drop.index);};row.addEventListener("pointerup", finish);row.addEventListener("pointercancel", () => {@@ -1656,21 +1776,45 @@ function bindProjectOrderInteractions(row, collection) {renderProjectFilters();});row.addEventListener("keydown", (event) => {- if (!projectOrderManagementActive || projectOrderSaving || !["ArrowUp", "ArrowDown"].includes(event.key)) return;+ if (!projectOrderManagementActive || projectOrderSaving || !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End"].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);+ const siblings = projectChildren(collection.parentId);+ const index = siblings.findIndex((item) => item.id === collection.id);+ if (event.key === "Home" || event.key === "End") {+ const target = event.key === "Home" ? siblings[0] : siblings.at(-1);+ return focusProjectRow(target?.id);+ }+ if (event.key === "ArrowUp" && index > 0) return void persistProjectCollectionMove(collection.id, collection.parentId, index - 1);+ if (event.key === "ArrowDown" && index >= 0 && index < siblings.length - 1) return void persistProjectCollectionMove(collection.id, collection.parentId, index + 1);+ if (event.key === "ArrowRight" && index > 0) {+ const parent = siblings[index - 1];+ expandedProjectIds.add(parent.id);+ return void persistProjectCollectionMove(collection.id, parent.id, projectChildren(parent.id).length);+ }+ if (event.key === "ArrowLeft" && collection.parentId) {+ const parent = organizerState.collections.find((item) => item.id === collection.parentId);+ if (!parent) return;+ const parentSiblings = projectChildren(parent.parentId).filter((item) => item.id !== collection.id);+ const parentIndex = parentSiblings.findIndex((item) => item.id === parent.id);+ return void persistProjectCollectionMove(collection.id, parent.parentId, parentIndex + 1);+ }});}-function projectIdsFromRenderedRows() {- return [...elements.collectionFilters.querySelectorAll(":scope > .project-row")]- .map((row) => row.dataset.collectionId)- .filter(Boolean);+function projectDropPlan(collectionId, target, position) {+ if (position === "inside") {+ return { parentId: target.id, index: projectChildren(target.id).filter((item) => item.id !== collectionId).length };+ }+ const siblings = projectChildren(target.parentId).filter((item) => item.id !== collectionId);+ const targetIndex = siblings.findIndex((item) => item.id === target.id);+ return { parentId: target.parentId, index: targetIndex + (position === "after" ? 1 : 0) };+}++function clearProjectDropIndicators() {+ elements.projectRootDrop.classList.remove("is-drop-target");+ for (const item of elements.collectionFilters.querySelectorAll(".drop-before, .drop-inside, .drop-after")) {+ item.classList.remove("drop-before", "drop-inside", "drop-after");+ }}function cancelProjectDrag() {@@ -1681,30 +1825,66 @@ function cancelProjectDrag() {}drag.row.classList.remove("is-dragging");elements.collectionFilters.classList.remove("is-project-dragging");+ clearProjectDropIndicators();projectDragState = null;}-async function persistProjectCollectionOrder(collectionIds, focusCollectionId) {+async function persistProjectCollectionMove(collectionId, parentId, index) {if (projectOrderSaving) return;projectOrderSaving = true;try {- const response = await chrome.runtime.sendMessage({ type: "REORDER_COLLECTIONS", collectionIds });- if (!response?.ok) throw new Error(response?.message || "项目顺序保存失败");+ const response = await chrome.runtime.sendMessage({ type: "MOVE_COLLECTION", collectionId, parentId, index });+ 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 = t("已将 {project} 移动到第 {position} 位", { project: project?.name || t("项目"), position });+ const project = organizerState.collections.find((item) => item.id === collectionId);+ elements.projectOrderStatus.textContent = `已移动“${project?.name || "项目"}”到 ${collectionPathLabel(organizerState, collectionId)}`;renderProjectFilters();- queueMicrotask(() => elements.collectionFilters.querySelector(`[data-collection-id="${CSS.escape(focusCollectionId)}"]`)?.focus());+ queueMicrotask(() => focusProjectRow(collectionId));} catch (error) {- showFeedback(error.message || "项目顺序保存失败", true);+ showFeedback(error.message || "项目结构保存失败", true);renderProjectFilters();} finally {projectOrderSaving = false;}}+function bindProjectTreeNavigation(row, collection) {+ row.addEventListener("keydown", (event) => {+ const rows = [...elements.collectionFilters.querySelectorAll(".project-row")];+ const index = rows.indexOf(row);+ if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Home" || event.key === "End") {+ event.preventDefault();+ const target = event.key === "Home" ? rows[0]+ : event.key === "End" ? rows.at(-1)+ : rows[index + (event.key === "ArrowDown" ? 1 : -1)];+ target?.querySelector(".project-filter")?.focus();+ } else if (event.key === "ArrowRight") {+ event.preventDefault();+ if (projectChildren(collection.id).length && !expandedProjectIds.has(collection.id)) {+ expandedProjectIds.add(collection.id);+ renderProjectFilters();+ queueMicrotask(() => focusProjectRow(collection.id, true));+ } else if (projectChildren(collection.id).length) focusProjectRow(projectChildren(collection.id)[0].id, true);+ } else if (event.key === "ArrowLeft") {+ event.preventDefault();+ if (expandedProjectIds.has(collection.id)) {+ expandedProjectIds.delete(collection.id);+ renderProjectFilters();+ queueMicrotask(() => focusProjectRow(collection.id, true));+ } else if (collection.parentId) focusProjectRow(collection.parentId, true);+ } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {+ const match = rows.find((candidate, candidateIndex) => candidateIndex > index && candidate.querySelector(".project-filter-name")?.textContent?.toLocaleLowerCase().startsWith(event.key.toLocaleLowerCase()))+ ?? rows.find((candidate) => candidate.querySelector(".project-filter-name")?.textContent?.toLocaleLowerCase().startsWith(event.key.toLocaleLowerCase()));+ match?.querySelector(".project-filter")?.focus();+ }+ });+}++function focusProjectRow(collectionId, filter = false) {+ const row = elements.collectionFilters.querySelector(`[data-collection-id="${CSS.escape(collectionId || "")}"]`);+ (filter ? row?.querySelector(".project-filter") : row)?.focus({ preventScroll: true });+}+async function updateProjectVisibility(collection, button) {const visibility = collection.visibility === COLLECTION_VISIBILITY.projectOnly? COLLECTION_VISIBILITY.library@@ -1720,9 +1900,15 @@ async function updateProjectVisibility(collection, button) {}async function createProjectCollection(button) {- const name = await promptAppText({ title: t("新建项目"), label: t("项目名称"), confirmLabel: t("新建") });+ const parent = organizerState.collections.find((item) => item.id === selectedCollectionId);+ const name = await promptAppText({+ title: t("新建项目"),+ description: parent ? `将创建在“${collectionPathLabel(organizerState, parent.id)}”下面` : "将创建为根项目",+ label: t("项目名称"),+ confirmLabel: t("新建")+ });if (!name?.trim()) return;- const response = await perform(button, { type: "CREATE_COLLECTION", name });+ const response = await perform(button, { type: "CREATE_COLLECTION", name, parentId: parent?.id ?? null });if (response?.created?.id) enterProjectSelection(response.created.id);}@@ -1733,24 +1919,30 @@ async function renameProjectCollection(collection) {}async function deleteProjectCollection(collection) {- if (!await confirmAppAction({ title: translateUiMessage(`将项目“${collection.name}”移入回收站?`), description: t("其中案例仍会保留在资料库,可从回收站恢复项目。"), confirmLabel: t("移入回收站"), danger: true })) return;- if (selectedCollectionId === collection.id) selectedCollectionId = "";+ const subtreeIds = collectionSubtreeIds(organizerState, collection.id);+ if (!await confirmAppAction({ title: translateUiMessage(`将项目“${collection.name}”及其 ${subtreeIds.length - 1} 个子项目移入回收站?`), description: t("其中案例仍会保留在资料库,可从回收站恢复项目。"), confirmLabel: t("移入回收站"), danger: true })) return;+ if (subtreeIds.includes(selectedCollectionId)) selectedCollectionId = "";await perform(elements.createCollection, { type: "DELETE_COLLECTION", collectionId: collection.id });}async function deleteProjectCollectionWithEntries(collection, button) {- const memberIds = new Set(collection.entryIds);+ const subtreeIds = collectionSubtreeIds(organizerState, collection.id);+ const memberIds = new Set(collectionEntryIds(organizerState, collection.id, { subtree: true }));const memberEntries = entries.filter((entry) => memberIds.has(entry.id));+ const otherProjectEntryIds = new Set(organizerState.collections+ .filter((item) => !subtreeIds.includes(item.id))+ .flatMap((item) => item.entryIds));+ const sharedCount = memberEntries.filter((entry) => otherProjectEntryIds.has(entry.id)).length;const mediaCount = new Set(memberEntries.flatMap((entry) =>normalizeEntryMedia(entry).mediaAssets.map((asset) => asset.id))).size;if (!await confirmAppAction({title: `将项目“${collection.name}”及全部案例移入回收站?`,- description: `将归档 ${memberEntries.length} 个案例和 ${mediaCount} 项媒体;可从回收站恢复。`,+ description: `将归档 ${subtreeIds.length} 个项目、${memberEntries.length} 个去重案例和 ${mediaCount} 项媒体;其中 ${sharedCount} 个案例也属于其他项目。可从回收站恢复。`,confirmLabel: "全部移入回收站",danger: true})) return;- if (selectedCollectionId === collection.id) selectedCollectionId = "";+ if (subtreeIds.includes(selectedCollectionId)) selectedCollectionId = "";await perform(button, {type: "DELETE_COLLECTION_WITH_ENTRIES",collectionId: collection.id,@@ -1788,7 +1980,7 @@ async function enterVisionSelection(collection) {if (!elements.visionBatchDialog.open) elements.visionBatchDialog.showModal();return;}- if (!collection?.entryIds?.length) return showFeedback("这个项目还没有可分析的案例", true);+ if (!collectionEntryIds(organizerState, collection?.id, { subtree: true }).length) return showFeedback("这个项目及其子项目还没有可分析的案例", true);if (!await closeDetail()) return;selectionMode = "vision";projectSelectionId = collection.id;@@ -1809,6 +2001,8 @@ async function enterSelectMode() {selectionMode = "select";caseOrderManagementActive = false;projectOrderManagementActive = false;+ selectionProjectTargetTouched = false;+ elements.selectionProjectTarget.value = selectedCollectionId || "";selectedCaseIds.clear();updateSelectionBar();renderGallery();@@ -1819,6 +2013,7 @@ function exitSelectionMode() {projectSelectionId = "";selectedCaseIds.clear();elements.selectionLabelInput.value = "";+ selectionProjectTargetTouched = false;updateSelectionBar();renderGallery();requestAnimationFrame(() => elements.selectCases.focus());@@ -1896,12 +2091,26 @@ function updateSelectionBar() {elements.projectSelectionClear.hidden = !visionSelection;elements.projectSelectionClear.disabled = selectedCaseIds.size === 0;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));+ const selectedProject = selectionProjectTargetTouched+ ? elements.selectionProjectTarget.value+ : elements.selectionProjectTarget.value || selectedCollectionId;+ const options = [option("", t("选择项目…"))];+ const selectorLabelsByProject = collectionSelectorLabelsById(organizerState);+ for (const collection of organizerState.collections) {+ options.push(option(collection.id, selectorLabelsByProject.get(collection.id)));+ }elements.selectionProjectTarget.replaceChildren(...options);elements.selectionProjectTarget.value = organizerState.collections.some((item) => item.id === selectedProject) ? selectedProject : "";- elements.selectionAddProject.disabled = !selectedCaseIds.size || !elements.selectionProjectTarget.value;+ const targetCollection = organizerState.collections.find((item) => item.id === elements.selectionProjectTarget.value);+ const selectedEntryIds = expandLogicalCaseIds([...selectedCaseIds], compoundCases);+ const targetEntryIds = new Set(targetCollection?.entryIds ?? []);+ const removableCount = selectedEntryIds.filter((id) => targetEntryIds.has(id)).length;+ const projectActionUnavailable = !selectedCaseIds.size || !targetCollection;+ elements.selectionAddProject.disabled = projectActionUnavailable;+ elements.selectionRemoveProject.disabled = projectActionUnavailable || removableCount === 0;+ elements.selectionRemoveProject.title = projectActionUnavailable+ ? "请先选择案例和目标项目"+ : removableCount === 0 ? "所选案例都不在该项目中" : `可移出 ${removableCount} 个案例`;elements.selectionSelectFiltered.disabled = selectionMode !== "select" || visibleEntries.length === 0;elements.selectionSelectFiltered.hidden = selectedCaseIds.size > 0;elements.selectionSelectFiltered.textContent = currentLocale() === "en" ? `Select current (${visibleEntries.length})` : `全选当前(${visibleEntries.length})`;@@ -1944,7 +2153,7 @@ function getVisionSelectableEntries(scope = "filtered") {if (scope === "filtered") return visibleEntries.filter(isVisionSelectableEntry);const collection = organizerState.collections.find((item) => item.id === projectSelectionId || item.id === selectedCollectionId);if (!collection) return logicalCases.filter(isVisionSelectableEntry);- const memberIds = new Set(collection.entryIds);+ const memberIds = new Set(collectionEntryIds(organizerState, collection.id, { subtree: true }));return logicalCases.filter((entry) =>isVisionSelectableEntry(entry) &&(entry.memberEntryIds?.length@@ -1965,22 +2174,30 @@ function completeSelection() {}async function addSelectionToProject() {+ return updateSelectionProjectMembership("add", elements.selectionAddProject);+}++async function removeSelectionFromProject() {+ return updateSelectionProjectMembership("remove", elements.selectionRemoveProject);+}++async function updateSelectionProjectMembership(mode, button) {const collection = organizerState.collections.find((item) => item.id === elements.selectionProjectTarget.value);if (!collection || !selectedCaseIds.size) return;- elements.selectionAddProject.disabled = true;+ button.disabled = true;try {const message = buildLibraryBatchPayload([...selectedCaseIds], compoundCases, {type: LIBRARY_BATCH_ACTIONS.setProject,collectionId: collection.id,- mode: "add"+ mode});const response = await chrome.runtime.sendMessage(message);- if (!response?.ok) throw new Error(response?.message || "加入项目失败");+ if (!response?.ok) throw new Error(response?.message || (mode === "remove" ? "移出项目失败" : "加入项目失败"));organizerState = response.organizerState ?? organizerState;- showFeedback(`已加入项目“${collection.name}”`);+ showFeedback(response.message || (mode === "remove" ? `已移出项目“${collection.name}”` : `已加入项目“${collection.name}”`));exitSelectionMode();} catch (error) {- showFeedback(error.message || "加入项目失败", true);+ showFeedback(error.message || (mode === "remove" ? "移出项目失败" : "加入项目失败"), true);updateSelectionBar();}}@@ -2027,7 +2244,10 @@ async function createProjectFromSelection() {selectFirst: true});if (!name?.trim()) return;- const createResponse = await perform(elements.selectionNewProject, { type: "CREATE_COLLECTION", name: name.trim() }, false);+ const parentId = organizerState.collections.some((item) => item.id === elements.selectionProjectTarget.value)+ ? elements.selectionProjectTarget.value+ : null;+ const createResponse = await perform(elements.selectionNewProject, { type: "CREATE_COLLECTION", name: name.trim(), parentId }, false);if (!createResponse?.ok || !createResponse.created?.id) return;organizerState = createResponse.organizerState ?? organizerState;const entryIds = expandLogicalCaseIds([...selectedCaseIds], compoundCases);@@ -2119,8 +2339,8 @@ async function saveProjectSelection() {}async function shareProjectCollection(collection) {- const memberIds = new Set(collection.entryIds);- const count = entries.filter((entry) => memberIds.has(entry.id)).length;+ const memberIds = new Set(collectionEntryIds(organizerState, collection.id, { subtree: true }));+ const count = new Set([...memberIds].map((id) => logicalIdByEntryId.get(id)).filter(Boolean)).size;openShareDialog({ collectionId: collection.id, title: collection.name, count });}@@ -4932,7 +5152,7 @@ function createDetailQuickOrganization(entry) {selectedProjects.length === 0? t("选择项目"): selectedProjects.length === 1- ? selectedProjects[0].name+ ? collectionPathLabel(organizerState, selectedProjects[0].id): t("已加入 {count} 个项目", { count: selectedProjects.length }));const syncProjectSummary = () => {@@ -4940,12 +5160,13 @@ function createDetailQuickOrganization(entry) {projectSummaryText.textContent = selected.length === 0? t("选择项目"): selected.length === 1- ? selected[0].name+ ? collectionPathLabel(organizerState, selected[0].id): t("已加入 {count} 个项目", { count: selected.length });};projectSummary.append(projectSummaryText, createUiIcon("chevron-down"));const projectPopover = el("div", "detail-project-popover");const projectList = el("div", "detail-project-list");+ const selectorLabelsByProject = collectionSelectorLabelsById(organizerState);for (const collection of organizerState.collections) {const members = new Set(collection.entryIds);const matchingCount = entryIds.filter((id) => members.has(id)).length;@@ -4973,7 +5194,7 @@ function createDetailQuickOrganization(entry) {organizerState = response.organizerState ?? organizerState;syncProjectSummary();});- label.append(checkbox, rawTextEl("span", "", collection.name));+ label.append(checkbox, rawTextEl("span", "", selectorLabelsByProject.get(collection.id)));projectList.append(label);}const newProject = el("div", "detail-new-project");@@ -5578,10 +5799,14 @@ async function prepareImportFile({ file, handle = null, relativePath, forceImpor}function renderImportProjectOptions(rootName = "") {- const matching = rootName && organizerState.collections.find((item) => item.name.trim() === rootName);+ const matching = rootName && organizerState.collections.find((item) => item.parentId === null && item.name.trim() === rootName);const selected = organizerState.collections.find((item) => item.id === selectedCollectionId);- importProjectCombobox.setProjects(organizerState.collections);- elements.importProject.value = matching?.name || rootName || selected?.name || "";+ importProjectCombobox.setProjects(projectComboboxCollections());+ const selectedProject = matching || (!rootName ? selected : null);+ if (!selectedProject || !importProjectCombobox.setSelected(selectedProject.id)) {+ elements.importProject.value = rootName;+ delete elements.importProject.dataset.projectId;+ }importTagEditor.input.value = "";importTagEditor.setValues(pendingLocalImport?.customLabels ?? []);elements.importProjectHint.textContent = rootName@@ -5743,7 +5968,7 @@ async function startLocalImportJob() {showImportFeedback("正在把资料交给后台导入…");try {const projectName = String(elements.importProject.value || "").trim();- const existingCollection = organizerState.collections.find((item) => item.name.trim().toLocaleLowerCase() === projectName.toLocaleLowerCase());+ const existingCollection = organizerState.collections.find((item) => item.id === elements.importProject.dataset.projectId);let collectionId = existingCollection?.id || "";if (projectName && !collectionId) {const response = await chrome.runtime.sendMessage({ type: "CREATE_COLLECTION", name: projectName });@@ -6031,6 +6256,7 @@ async function readDroppedEntry(entry, parentPath) {async function addVideoReference(entryId = "") {const organizationFields = entryId ? [] : caseCreationOrganizationFields();+ let projectInput = null;const result = await showAppDialog({title: "添加视频链接",description: "支持 YouTube、Vimeo、Bilibili、抖音和 X。这里只保存来源引用卡,不下载视频文件。",@@ -6044,11 +6270,14 @@ async function addVideoReference(entryId = "") {autocomplete: "url",required: true}, ...organizationFields],- onReady: ({ controls }) => attachProjectSuggestions(controls.get("projectName")),+ onReady: ({ controls }) => {+ projectInput = controls.get("projectName");+ attachProjectSuggestions(projectInput);+ },onSubmit: async ({ url, projectName, customLabels }) => saveVideoReference(url,entryId,- caseCreationOrganization(projectName, customLabels)+ caseCreationOrganization(projectName, customLabels, projectInput?.dataset.projectId))});if (result) {@@ -6123,6 +6352,7 @@ async function fetchVideoReferencePoster(value) {}async function createQuickNote() {+ let projectInput = null;const result = await showAppDialog({title: "快速笔记",description: "标题和正文一次填写,保存后会作为资料文档显示在案例库。",@@ -6133,13 +6363,16 @@ async function createQuickNote() {{ id: "text", label: "笔记正文", type: "textarea", rows: 8, required: true, placeholder: "写下创作想法、判断或待办…" },...caseCreationOrganizationFields()],- onReady: ({ controls }) => attachProjectSuggestions(controls.get("projectName")),+ onReady: ({ controls }) => {+ projectInput = controls.get("projectName");+ attachProjectSuggestions(projectInput);+ },onSubmit: async ({ title, text, projectName, customLabels }) => {const response = await chrome.runtime.sendMessage({type: "CREATE_QUICK_NOTE",title,text,- ...caseCreationOrganization(projectName, customLabels)+ ...caseCreationOrganization(projectName, customLabels, projectInput?.dataset.projectId)});if (!response?.ok) throw new Error(response?.message || "笔记保存失败");return response;@@ -6175,14 +6408,12 @@ function caseCreationOrganizationFields() {function attachProjectSuggestions(input) {if (!input) return;- attachProjectCombobox(input, { projects: organizerState.collections, destroyOnDialogClose: true });+ attachProjectCombobox(input, { projects: projectComboboxCollections(), destroyOnDialogClose: true });}-function caseCreationOrganization(projectNameValue, customLabelsValue) {+function caseCreationOrganization(projectNameValue, customLabelsValue, projectIdValue = "") {const projectName = String(projectNameValue ?? "").trim();- const existing = organizerState.collections.find((item) => (- item.name.trim().toLocaleLowerCase() === projectName.toLocaleLowerCase()- ));+ const existing = organizerState.collections.find((item) => item.id === String(projectIdValue ?? "").trim());const customLabels = String(customLabelsValue ?? "").split(/[,,\n\r]+/u).map(normalizeImportLabel)@@ -8447,6 +8678,12 @@ function relatedTrashGroupIds(startItem) {if (item.kind === "collection") {const memberIds = new Set(item.snapshot?.entryIds ?? []);for (const candidate of trashItems) {+ if (candidate.kind === "collection" && (+ candidate.snapshot?.parentId === item.targetId || item.snapshot?.parentId === candidate.targetId+ ) && !selected.has(candidate.id)) {+ selected.add(candidate.id);+ changed = true;+ }if (candidate.kind === "entry" && memberIds.has(candidate.targetId) && !selected.has(candidate.id)) {selected.add(candidate.id);changed = true;diff --git a/manifest.json b/manifest.jsonindex 057df37..4c5b712 100644--- a/manifest.json+++ b/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "__MSG_extensionName__",- "version": "1.18.17",+ "version": "1.19.0","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",diff --git a/migration.js b/migration.jsindex de0b1d0..c49b124 100644--- a/migration.js+++ b/migration.js@@ -1,7 +1,7 @@import { CLASSIFIER_VERSION, classifyContent, classifyImportedMedia } from "./classifier.js";import { createDefaultFacetCatalog, normalizeFacetCatalog, uniqueNames } from "./facets.js";import { CONTENT_IDS, SCHEMA_VERSION, isValidContentPath, normalizeTaxonomy } from "./taxonomy.js";-import { normalizeOrganizerState } from "./organizer.js";+import { ORGANIZER_VERSION, normalizeOrganizerState } from "./organizer.js";import { sortAnalysisBreakdown } from "./analysis-candidates.js";import { normalizeEntryVisuals } from "./visuals.js";import { normalizeCompoundCases } from "./compound-cases.js";@@ -58,7 +58,7 @@ export function migrateLibraryState(stored = {}) {export function needsMigration(stored = {}) {return stored.schemaVersion !== SCHEMA_VERSION || !stored.taxonomy || !stored.facetCatalog ||- !stored.organizerState || !stored.trashState || !Array.isArray(stored.compoundCases) ||+ !stored.organizerState || stored.organizerState.version !== ORGANIZER_VERSION || !stored.trashState || !Array.isArray(stored.compoundCases) ||!isFixedTagTree(stored.facetCatalog) ||(stored.entries ?? []).some((entry) => entry.schemaVersion !== SCHEMA_VERSION);}diff --git a/organizer.js b/organizer.jsindex 1678383..768ef09 100644--- a/organizer.js+++ b/organizer.js@@ -1,4 +1,4 @@-export const ORGANIZER_VERSION = 6;+export const ORGANIZER_VERSION = 7;export const COLLECTION_VISIBILITY = Object.freeze({library: "library",@@ -19,23 +19,63 @@ export function normalizeOrganizerState(value = {}, validEntryIds) {...item,order: Number.isFinite(item.order) ? item.order : order,entryIds: item.entryIds.filter((id) => !allowed || allowed.has(id))- }))- .sort(byOrder)- .map((item, order) => ({ ...item, order }));- return { version: ORGANIZER_VERSION, collections };+ }));+ const ids = new Set(collections.map((item) => item.id));+ const byId = new Map(collections.map((item) => [item.id, item]));+ for (const item of collections) {+ if (!ids.has(item.parentId) || item.parentId === item.id) item.parentId = null;+ }+ const resolved = new Set();+ for (const item of collections) {+ if (resolved.has(item.id)) continue;+ const path = [];+ const positions = new Map();+ let current = item;+ while (current && !resolved.has(current.id)) {+ if (positions.has(current.id)) {+ current.parentId = null;+ break;+ }+ positions.set(current.id, path.length);+ path.push(current);+ current = current.parentId ? byId.get(current.parentId) : null;+ }+ path.forEach((entry) => resolved.add(entry.id));+ }+ const childrenByParent = new Map();+ for (const item of collections) {+ const siblings = childrenByParent.get(item.parentId) ?? [];+ siblings.push(item);+ childrenByParent.set(item.parentId, siblings);+ }+ for (const siblings of childrenByParent.values()) {+ siblings.sort(byOrder).forEach((item, order) => { item.order = order; });+ }+ const ordered = [];+ const stack = [...(childrenByParent.get(null) ?? [])].reverse();+ while (stack.length) {+ const item = stack.pop();+ ordered.push(item);+ const children = childrenByParent.get(item.id) ?? [];+ for (let index = children.length - 1; index >= 0; index -= 1) stack.push(children[index]);+ }+ return { version: ORGANIZER_VERSION, collections: ordered };}-export function createCollection(stateValue, name) {+export function createCollection(stateValue, name, parentId = null) {const state = structuredClone(normalizeOrganizerState(stateValue));const cleaned = cleanName(name);+ const parent = cleanId(parentId) || null;if (!cleaned) throw new Error("项目名称不能为空");- if (state.collections.some((item) => canonical(item.name) === canonical(cleaned))) {+ if (parent && !state.collections.some((item) => item.id === parent)) throw new Error("父项目不存在");+ if (state.collections.some((item) => item.parentId === parent && canonical(item.name) === canonical(cleaned))) {throw new Error("这个项目已经存在");}const item = {id: `collection:${globalThis.crypto.randomUUID()}`,name: cleaned,- order: state.collections.length,+ parentId: parent,+ order: state.collections.filter((collection) => collection.parentId === parent).length,entryIds: [],visibility: COLLECTION_VISIBILITY.library,createdAt: new Date().toISOString()@@ -49,7 +89,7 @@ export function renameCollection(stateValue, collectionId, name) {const target = state.collections.find((item) => item.id === cleanId(collectionId));const cleaned = cleanName(name);if (!target || !cleaned) throw new Error("项目名称无效");- if (state.collections.some((item) => item.id !== target.id && canonical(item.name) === canonical(cleaned))) {+ if (state.collections.some((item) => item.id !== target.id && item.parentId === target.parentId && canonical(item.name) === canonical(cleaned))) {throw new Error("这个项目已经存在");}target.name = cleaned;@@ -60,22 +100,98 @@ export function deleteCollection(stateValue, collectionId) {const state = structuredClone(normalizeOrganizerState(stateValue));const id = cleanId(collectionId);if (!state.collections.some((item) => item.id === id)) throw new Error("项目不存在");- state.collections = state.collections.filter((item) => item.id !== id);+ const removed = new Set(collectionSubtreeIds(state, id));+ state.collections = state.collections.filter((item) => !removed.has(item.id));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))) {+ const roots = state.collections.filter((item) => item.parentId === null);+ const existingIds = new Set(roots.map((item) => item.id));+ if (requested.length !== roots.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 }));+ requested.forEach((id, order) => { byId.get(id).order = order; });+ return normalizeOrganizerState(state);+}++export function moveCollection(stateValue, collectionId, parentId = null, index = 0) {+ const state = structuredClone(normalizeOrganizerState(stateValue));+ const id = cleanId(collectionId);+ const parent = cleanId(parentId) || null;+ const target = state.collections.find((item) => item.id === id);+ if (!target) throw new Error("项目不存在");+ if (parent && !state.collections.some((item) => item.id === parent)) throw new Error("父项目不存在");+ if (parent === id || collectionSubtreeIds(state, id).includes(parent)) throw new Error("不能把项目移入自身或其子项目");+ const oldParent = target.parentId;+ const oldSiblings = state.collections.filter((item) => item.parentId === oldParent && item.id !== id);+ const newSiblings = oldParent === parent+ ? oldSiblings+ : state.collections.filter((item) => item.parentId === parent && item.id !== id);+ const insertAt = Math.max(0, Math.min(newSiblings.length, Math.floor(Number(index) || 0)));+ target.parentId = parent;+ newSiblings.splice(insertAt, 0, target);+ newSiblings.forEach((item, order) => { item.order = order; });+ if (oldParent !== parent) oldSiblings.forEach((item, order) => { item.order = order; });return normalizeOrganizerState(state);}+export function collectionSubtreeIds(stateValue, collectionId) {+ const state = normalizeOrganizerState(stateValue);+ const id = cleanId(collectionId);+ return subtreeIdsFromCollections(state.collections, id);+}++export function collectionEntryIds(stateValue, collectionId, options = {}) {+ const state = normalizeOrganizerState(stateValue);+ const id = cleanId(collectionId);+ if (options.subtree === true) return collectionSubtreeEntryIdsById(state).get(id) ?? [];+ return [...(state.collections.find((item) => item.id === id)?.entryIds ?? [])];+}++export function collectionSubtreeEntryIdsById(stateValue) {+ const state = normalizeOrganizerState(stateValue);+ const result = new Map(state.collections.map((item) => [item.id, new Set(item.entryIds)]));+ for (let index = state.collections.length - 1; index >= 0; index -= 1) {+ const item = state.collections[index];+ if (!item.parentId) continue;+ const parentEntries = result.get(item.parentId);+ for (const entryId of result.get(item.id) ?? []) parentEntries?.add(entryId);+ }+ return new Map([...result].map(([id, entryIds]) => [id, [...entryIds]]));+}++export function collectionPath(stateValue, collectionId) {+ const state = normalizeOrganizerState(stateValue);+ const byId = new Map(state.collections.map((item) => [item.id, item]));+ const result = [];+ let current = byId.get(cleanId(collectionId));+ while (current) {+ result.unshift(current);+ current = current.parentId ? byId.get(current.parentId) : null;+ }+ return result;+}++export function collectionPathLabel(stateValue, collectionId, separator = " / ") {+ return collectionPath(stateValue, collectionId).map((item) => item.name).join(separator);+}++export function collectionSelectorLabel(stateValue, collectionId) {+ return collectionSelectorLabelsById(stateValue).get(cleanId(collectionId)) ?? "";+}++export function collectionPathLabelsById(stateValue, separator = " / ") {+ return collectionLabelsById(stateValue, separator, (name) => name);+}++export function collectionSelectorLabelsById(stateValue) {+ return collectionLabelsById(stateValue, " › ", (name) => name.replaceAll("›", "››"));+}+export function planCollectionAndEntriesDeletion(stateValue, entriesValue, collectionId, confirmationName) {const entries = Array.isArray(entriesValue) ? entriesValue : [];const organizerState = normalizeOrganizerState(stateValue, entries.map((entry) => entry?.id));@@ -83,7 +199,7 @@ export function planCollectionAndEntriesDeletion(stateValue, entriesValue, colleconst collection = organizerState.collections.find((item) => item.id === id);if (!collection) throw new Error("项目不存在");if (cleanName(confirmationName) !== collection.name) throw new Error("项目名称不匹配,未执行删除");- const deletedEntryIds = [...collection.entryIds];+ const deletedEntryIds = collectionEntryIds(organizerState, collection.id, { subtree: true });const deletedIds = new Set(deletedEntryIds);const remainingEntries = entries.filter((entry) => !deletedIds.has(cleanId(entry?.id)));const withoutEntries = removeEntriesFromOrganizer(organizerState, deletedEntryIds);@@ -144,10 +260,13 @@ export function mergeOrganizerState(currentValue, importedValue, entryIdMap = {}const remap = (ids) => uniqueIds(ids).map((id) => cleanId(entryIdMap[id])).filter(Boolean);const receiverCreatedAt = normalizeTimestamp(options.createdAt);+ const collectionIdMap = new Map();for (const source of imported.collections) {- const existing = current.collections.find((item) => canonical(item.name) === canonical(source.name));+ const parentId = source.parentId ? collectionIdMap.get(source.parentId) ?? null : null;+ const existing = current.collections.find((item) => item.parentId === parentId && canonical(item.name) === canonical(source.name));if (existing) {existing.entryIds = uniqueIds([...existing.entryIds, ...remap(source.entryIds)]);+ collectionIdMap.set(source.id, existing.id);continue;}const id = current.collections.some((item) => item.id === source.id)@@ -156,10 +275,12 @@ export function mergeOrganizerState(currentValue, importedValue, entryIdMap = {}current.collections.push({...source,id,- order: current.collections.length,+ parentId,+ order: current.collections.filter((item) => item.parentId === parentId).length,entryIds: remap(source.entryIds),...(receiverCreatedAt ? { createdAt: receiverCreatedAt } : {})});+ collectionIdMap.set(source.id, id);}return normalizeOrganizerState(current);}@@ -172,6 +293,7 @@ function normalizeCollection(value = {}) {return {id,name,+ parentId: cleanId(value.parentId) || null,order: Number(value.order),entryIds: uniqueIds(value.entryIds),visibility: normalizeVisibility(value.visibility),@@ -218,3 +340,33 @@ function canonical(value) {function byOrder(left, right) {return left.order - right.order || left.name.localeCompare(right.name);}++function subtreeIdsFromCollections(collections, collectionId) {+ if (!collections.some((item) => item.id === collectionId)) return [];+ const childrenByParent = new Map();+ for (const item of collections) {+ const children = childrenByParent.get(item.parentId) ?? [];+ children.push(item.id);+ childrenByParent.set(item.parentId, children);+ }+ const result = [];+ const stack = [collectionId];+ while (stack.length) {+ const id = stack.pop();+ result.push(id);+ const children = childrenByParent.get(id) ?? [];+ for (let index = children.length - 1; index >= 0; index -= 1) stack.push(children[index]);+ }+ return result;+}++function collectionLabelsById(stateValue, separator, transformName) {+ const state = normalizeOrganizerState(stateValue);+ const result = new Map();+ for (const item of state.collections) {+ const name = transformName(item.name);+ const parentLabel = item.parentId ? result.get(item.parentId) : "";+ result.set(item.id, parentLabel ? `${parentLabel}${separator}${name}` : name);+ }+ return result;+}diff --git a/package-lock.json b/package-lock.jsonindex 8126802..d25a6ee 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "prompt-case-collector",- "version": "1.18.17",+ "version": "1.19.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "prompt-case-collector",- "version": "1.18.17",+ "version": "1.19.0","license": "Apache-2.0","dependencies": {"@jonahschulte/rtf-toolkit": "0.5.0",diff --git a/package.json b/package.jsonindex 922313a..d0a3bcf 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "prompt-case-collector",- "version": "1.18.17",+ "version": "1.19.0","private": false,"license": "Apache-2.0","repository": "https://github.com/wchao6891/PromptDirector",diff --git a/project-combobox.js b/project-combobox.jsindex 6df44e1..7707b50 100644--- a/project-combobox.js+++ b/project-combobox.js@@ -1,10 +1,13 @@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)- }))+ .map((project) => {+ const label = normalize(project?.pathLabel ?? project?.name ?? project?.label ?? project?.value);+ return {+ value: normalize(project?.id ?? project?.value ?? label),+ label+ };+ }).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));@@ -107,7 +110,7 @@ export function attachProjectCombobox(input, options = {}) {option.dataset.value = project.value;option.textContent = project.label;option.addEventListener("pointerdown", (event) => event.preventDefault(), eventOptions);- option.addEventListener("click", () => select(project.value), eventOptions);+ option.addEventListener("click", () => select(project), eventOptions);return option;}));const visible = open && matches.length > 0;@@ -129,8 +132,10 @@ export function attachProjectCombobox(input, options = {}) {activeIndex = -1;}- function select(value) {- input.value = value;+ function select(project) {+ if (!project) return;+ input.value = project.label;+ input.dataset.projectId = project.value;input.dispatchEvent(new Event("input", { bubbles: true }));input.dispatchEvent(new Event("change", { bubbles: true }));close();@@ -150,6 +155,8 @@ export function attachProjectCombobox(input, options = {}) {input.addEventListener("focus", () => render(true), eventOptions);input.addEventListener("click", () => render(true), eventOptions);input.addEventListener("input", () => {+ const selected = projectComboboxOptions(projects).find((project) => project.value === input.dataset.projectId);+ if (!selected || normalize(input.value) !== selected.label) delete input.dataset.projectId;activeIndex = -1;render(true);}, eventOptions);@@ -161,7 +168,7 @@ export function attachProjectCombobox(input, options = {}) {}if (event.key === "Enter" && !listbox.hidden && activeIndex >= 0) {event.preventDefault();- select(matching()[activeIndex]?.value || input.value);+ select(matching()[activeIndex]);return;}if (event.key === "Escape" && !listbox.hidden) {@@ -183,8 +190,21 @@ export function attachProjectCombobox(input, options = {}) {element: listbox,setProjects(nextProjects) {projects = Array.isArray(nextProjects) ? nextProjects : [];+ if (!projectComboboxOptions(projects).some((project) => project.value === input.dataset.projectId)) {+ delete input.dataset.projectId;+ }if (!listbox.hidden) render(true);},+ setSelected(projectId) {+ const selected = projectComboboxOptions(projects).find((project) => project.value === normalize(projectId));+ if (!selected) {+ delete input.dataset.projectId;+ return false;+ }+ input.value = selected.label;+ input.dataset.projectId = selected.value;+ return true;+ },close,destroy() {controller.abort();@@ -194,6 +214,7 @@ export function attachProjectCombobox(input, options = {}) {input.removeAttribute("aria-expanded");input.removeAttribute("aria-controls");input.removeAttribute("aria-activedescendant");+ delete input.dataset.projectId;}};}diff --git a/resource-limits.js b/resource-limits.jsindex 36b9344..e482d35 100644--- a/resource-limits.js+++ b/resource-limits.js@@ -54,6 +54,7 @@ export const PORTABLE_LIBRARY_LIMITS = Object.freeze({maxFileBytes: 16 * MEBIBYTE,maxLibraryJsonBytes: 16 * MEBIBYTE,maxEntries: 5000,+ maxCollections: 5000,maxImageBytes: 16 * MEBIBYTE,maxImagePixels: 40_000_000,maxVideoBytes: 128 * MEBIBYTEdiff --git a/skills-page.js b/skills-page.jsindex 4afb41e..3c34a8e 100644--- a/skills-page.js+++ b/skills-page.js@@ -56,6 +56,7 @@ import {deriveNavigationSnapshot} from "./navigation-state.js";import { bindTransientMenus } from "./transient-menu.js";+import { collectionEntryIds, collectionSelectorLabelsById } from "./organizer.js";await initializeUi();bindTransientMenus(document, ".skill-detail-more, .skill-project-picker");@@ -411,7 +412,11 @@ function renderRunEvidence(view = activeView) {}function renderProjectControls() {- const options = [["", t("全部项目")], ...organizerState.collections.map((project) => [project.id, project.name])];+ const selectorLabelsByProject = collectionSelectorLabelsById(organizerState);+ const options = [["", t("全部项目")], ...organizerState.collections.map((project) => [+ project.id,+ selectorLabelsByProject.get(project.id)+ ])];if (!options.some(([value]) => value === selectedProjectId)) selectedProjectId = "";elements.skillProjectLabel.textContent = options.find(([value]) => value === selectedProjectId)?.[1] || t("全部项目");elements.skillProjectFilter.replaceChildren(...options.map(([value, name]) => {@@ -432,7 +437,7 @@ function renderProjectControls() {function renderCases(options = {}) {releaseThumbnails();const projectId = selectedProjectId;- const members = projectId ? new Set(organizerState.collections.find((item) => item.id === projectId)?.entryIds ?? []) : null;+ const members = projectId ? new Set(collectionEntryIds(organizerState, projectId, { subtree: true })) : null;const visible = filterSkillSourceEntries(entries, {projectEntryIds: members,query: elements.skillCaseSearch.valuediff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.mdindex 262b137..b765ea7 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.17.zip`.-- Candidate size: `8,462,460` bytes.-- Candidate SHA-256: `49f6bd04d05fd5c6ef8515fe6307e0d130d08196e04698a7afd82d4cca5ebc05`.+- Current release candidate: `dist/PromptDirector-1.19.0.zip`.+- Candidate size: `8,616,920` bytes.+- Candidate SHA-256: `03620a885fcc7eb6590d8d08d1f41da24307367207f0eb42a63f31e3961207d8`.- 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 listingdiff --git a/sync-model.js b/sync-model.jsindex 8f1ad28..65e76e3 100644--- a/sync-model.js+++ b/sync-model.js@@ -3,7 +3,8 @@ import { SCHEMA_VERSION, createDefaultTaxonomy, normalizeTaxonomy } from "./taxoimport { createDefaultTrashState } from "./trash.js";export const SYNC_SNAPSHOT_FORMAT = "prompt-director-sync-state";-export const SYNC_SNAPSHOT_VERSION = 1;+export const SYNC_SNAPSHOT_VERSION = 2;+export const SUPPORTED_SYNC_SNAPSHOT_VERSIONS = Object.freeze([1, 2]);export const DEFAULT_SYNC_RETENTION = 10;export const SYNC_ERROR_CODES = Object.freeze({LOCATION_NOT_FOUND: "location_not_found",@@ -232,7 +233,7 @@ export async function createRevisionSnapshot(stateValue = {}, options = {}) {}export function mergeRevisionSnapshots(values = []) {- const snapshots = (Array.isArray(values) ? values : []).filter(validSnapshot);+ const snapshots = (Array.isArray(values) ? values : []).filter(validSnapshot).map(upgradeSyncSnapshot);if (!snapshots.length) {return { state: emptyState(), records: {}, conflicts: [], imageRefs: {} };}@@ -773,10 +774,29 @@ function uniqueRevisions(values) {function validSnapshot(value) {return value?.format === SYNC_SNAPSHOT_FORMAT &&- value.version === SYNC_SNAPSHOT_VERSION &&+ isSupportedSyncSnapshotVersion(value.version) &&value.records && typeof value.records === "object";}+export function isSupportedSyncSnapshotVersion(value) {+ return Number.isInteger(value) && SUPPORTED_SYNC_SNAPSHOT_VERSIONS.includes(value);+}++function upgradeSyncSnapshot(value) {+ if (value.version !== 1) return value;+ const snapshot = structuredClone(value);+ snapshot.version = SYNC_SNAPSHOT_VERSION;+ for (const [key, record] of Object.entries(snapshot.records ?? {})) {+ if (!key.startsWith("collection:") || !record?.payload) continue;+ record.payload.parentId = null;+ // Legacy flat devices may continue writing after a tree exists. Keeping their+ // collection clock at the migration baseline prevents a flat snapshot from+ // winning a concurrent conflict over a newer tree-aware collection record.+ record.logicalClock = 0;+ }+ return snapshot;+}+function validRecord(key, value) {const [type, id] = splitKey(key);return value && type === value.entityType && id === value.entityId &&@@ -789,7 +809,7 @@ function emptyState() {entries: [],taxonomy: { version: SCHEMA_VERSION, revision: 1, nodes: [] },compoundCases: [],- organizerState: { version: 4, collections: [] },+ organizerState: { version: 7, collections: [] },composerSessions: [],creativeRuns: [],creativeSkills: { version: 1, items: [] },diff --git a/sync-vault.js b/sync-vault.jsindex 6d7e08d..89f1286 100644--- a/sync-vault.js+++ b/sync-vault.js@@ -11,7 +11,8 @@ import {import {DEFAULT_SYNC_RETENTION,SYNC_SNAPSHOT_FORMAT,- SYNC_SNAPSHOT_VERSION+ SYNC_SNAPSHOT_VERSION,+ isSupportedSyncSnapshotVersion} from "./sync-model.js";import { assetFormatsForMimeType } from "./asset-formats.js";@@ -79,7 +80,7 @@ export async function listSyncSnapshots(vault, options = {}) {const encrypted = await readJsonHandle(fileHandle);throwIfAborted(options.signal);const snapshot = await decryptVaultValue(encrypted, vault.key);- if (snapshot?.format !== SYNC_SNAPSHOT_FORMAT || snapshot.version !== SYNC_SNAPSHOT_VERSION) {+ if (snapshot?.format !== SYNC_SNAPSHOT_FORMAT || !isSupportedSyncSnapshotVersion(snapshot.version)) {throw new Error("状态版本无效");}snapshots.push(snapshot);diff --git a/taxonomy.js b/taxonomy.jsindex 0801ba7..d312dfe 100644--- a/taxonomy.js+++ b/taxonomy.js@@ -1,4 +1,4 @@-export const SCHEMA_VERSION = 27;+export const SCHEMA_VERSION = 28;export const CONTENT_TYPE_VISIBILITY = Object.freeze({library: "library",diff --git a/test/ai-background-v4.test.js b/test/ai-background-v4.test.jsindex 411f8ce..89f5a88 100644--- a/test/ai-background-v4.test.js+++ b/test/ai-background-v4.test.js@@ -37,3 +37,18 @@ test("background keeps service profiles for job execution but stops publishing oassert.match(source, /aiServiceProfiles: publicAiServiceProfiles/);assert.doesNotMatch(source, /aiTaskRoutes:/);});++test("persisted batch recovery wakes the runner while runner exceptions wait for the alarm", () => {+ const recovery = source.slice(+ source.indexOf("async function recoverDeepSeekBatch"),+ source.indexOf("async function undoDeepSeekBatch")+ );+ assert.match(recovery, /ensureAnalysisBatchAlarm\(true\)/);+ assert.match(recovery, /scheduleAnalysisBatchRunner\(\)/);++ const runner = source.slice(+ source.indexOf("async function runPersistedAnalysisBatch"),+ source.indexOf("async function runPersistedTextBatchSlice")+ );+ assert.match(runner, /catch \(error\)[\s\S]*ensureAnalysisBatchAlarm\(stillRunning\)[\s\S]*continueRunning = false/);+});diff --git a/test/case-management-ui.test.js b/test/case-management-ui.test.jsindex 4b04a05..99af03e 100644--- a/test/case-management-ui.test.js+++ b/test/case-management-ui.test.js@@ -17,6 +17,7 @@ test("selection mode exposes all filtered results, user tags, projects, sharing,"selection-add-labels","selection-project-target","selection-add-project",+ "selection-remove-project","share-export","selection-trash"]) assert.match(bar, new RegExp(`id="${id}"`));diff --git a/test/curated-catalog.test.js b/test/curated-catalog.test.jsindex 1ee383d..6db139d 100644--- a/test/curated-catalog.test.js+++ b/test/curated-catalog.test.js@@ -185,6 +185,23 @@ test("each curated package version uses deterministic local ids so updates neverassert.equal(first.entries[0].primaryVisualId, first.entries[0].visuals[0].id);});+test("curated package namespacing remaps project parents together with project ids", () => {+ const prepared = prepareCuratedPackageVersion({+ entries: [{ id: "original", mediaAssets: [] }],+ organizerState: {+ collections: [+ { id: "root", name: "根项目", parentId: null, order: 0, entryIds: [] },+ { id: "child", name: "子项目", parentId: "root", order: 0, entryIds: ["original"] }+ ]+ }+ }, catalogItem());+ const [root, child] = prepared.organizerState.collections;++ assert.equal(root.parentId, null);+ assert.equal(child.parentId, root.id);+ assert.equal(child.entryIds[0], prepared.entries[0].id);+});+test("legacy version-scoped curated ids resolve to the same stable source identity", () => {const legacy = {id: "curated:cinematic-foundations:1.0.0:entry:original",@@ -253,6 +270,27 @@ test("theme saves select a deterministic batch while preserving its collection",assert.deepEqual(selected.organizerState.collections[0].entryIds, selected.entries.map((entry) => entry.id));});+test("theme saves retain empty project ancestors needed by selected child cases", () => {+ const prepared = prepareCuratedPackageVersion({+ entries: [+ { id: "one", title: "案例一", mediaAssets: [], primaryMediaId: "" },+ { id: "two", title: "案例二", mediaAssets: [], primaryMediaId: "" }+ ],+ organizerState: {+ collections: [+ { id: "root", name: "主题", parentId: null, order: 0, entryIds: [] },+ { id: "child", name: "子主题", parentId: "root", order: 0, entryIds: ["one", "two"] }+ ]+ }+ }, catalogItem());+ const selected = prepareCuratedEntriesPackage(prepared, [prepared.entries[0].id]);+ const [root, child] = selected.organizerState.collections;++ assert.equal(root.entryIds.length, 0);+ assert.equal(child.parentId, root.id);+ assert.deepEqual(child.entryIds, [selected.entries[0].id]);+});+test("a curated package must match the reviewed catalog counts", () => {const item = catalogItem({ imageCount: 1 });assert.doesNotThrow(() => validateCuratedPackageContents(item, {diff --git a/test/data-safety-ui.test.js b/test/data-safety-ui.test.jsindex f98766e..29a6f9d 100644--- a/test/data-safety-ui.test.js+++ b/test/data-safety-ui.test.js@@ -86,7 +86,7 @@ test("share-package import preserves local configuration and accepts historicalassert.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, 4\]\)/);+ assert.match(format, /SUPPORTED_LIBRARY_PACKAGE_VERSIONS\s*=\s*Object\.freeze\(\[1, 2, 3, 4, 5\]\)/);});test("data safety cannot be dismissed accidentally while a storage operation is running", async () => {diff --git a/test/import-ui.test.js b/test/import-ui.test.jsindex eae3953..8b161f0 100644--- a/test/import-ui.test.js+++ b/test/import-ui.test.js@@ -119,7 +119,10 @@ test("duplicate choice and import start preserve the complete background job con});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, /importProjectCombobox\.setProjects\(projectComboboxCollections\(\)\)/);+ assert.match(js, /importProjectCombobox\.setSelected\(selectedProject\.id\)/);+ assert.match(js, /item\.id === elements\.importProject\.dataset\.projectId/);+ assert.doesNotMatch(js, /collectionPathLabel\(organizerState, item\.id\)\.toLocaleLowerCase\(\) === projectName/);assert.match(js, /已按根文件夹建议项目;可以修改或清空/);assert.match(js, /const importTagEditor = createTagEditor/);assert.match(js, /pendingLocalImport\.customLabels\s*=\s*values/);diff --git a/test/lib.test.js b/test/lib.test.jsindex 79e7e91..d1878d3 100644--- a/test/lib.test.js+++ b/test/lib.test.js@@ -215,7 +215,7 @@ test("library JSON is machine-readable and references screenshots without base64const parsed = JSON.parse(json);assert.equal(parsed.format, "prompt-case-library");- assert.equal(parsed.version, 4);+ assert.equal(parsed.version, 5);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-package.test.js b/test/library-package.test.jsindex 726a754..2017a5c 100644--- a/test/library-package.test.js+++ b/test/library-package.test.js@@ -65,6 +65,12 @@ test("parseLibraryPackage validates the portable library format and referenced sassert.throws(() => parseLibraryPackage({ ...data, version: "3" }, new Map()), /不是受支持/);});+test("parseLibraryPackage rejects project trees beyond the portable package safety limit", () => {+ const data = packageData([entry("one")], catalog());+ data.organizerState.collections.push({ id: "collection:extra", name: "额外项目", entryIds: [] });+ assert.throws(() => parseLibraryPackage(data, new Map(), { maxCollections: 1 }), /项目数量超过 1 个上限/);+});+test("legacy v1 and v2 share packages preserve multiple visuals and their primary relationship", () => {const data = packageData([], catalog());data.version = 2;@@ -545,6 +551,28 @@ test("project packages include every project member and only that project relatiassert.equal(received.state.organizerState.collections[0].createdAt, "2026-08-22T09:00:00.000Z");});+test("project packages preserve a selected project subtree and deduplicate its cases", () => {+ const source = packageData([entry("root-case"), entry("child-case"), entry("shared"), entry("outside")], catalog());+ source.organizerState = {+ version: 7,+ collections: [+ { id: "collection:root", name: "Campaign", parentId: null, order: 0, entryIds: ["root-case", "shared"] },+ { id: "collection:child", name: "References", parentId: "collection:root", order: 0, entryIds: ["child-case", "shared"] },+ { id: "collection:outside", name: "Outside", parentId: null, order: 1, entryIds: ["outside"] }+ ]+ };++ const selected = selectProjectPackage(source, "collection:root");++ assert.deepEqual(selected.entries.map((item) => item.id), ["root-case", "child-case", "shared"]);+ assert.deepEqual(selected.organizerState.collections.map((item) => ({ id: item.id, parentId: item.parentId })), [+ { id: "collection:root", parentId: null },+ { id: "collection:child", parentId: "collection:root" }+ ]);+ assert.deepEqual(selected.organizerState.collections[0].entryIds, ["root-case", "shared"]);+ assert.deepEqual(selected.organizerState.collections[1].entryIds, ["child-case", "shared"]);+});+test("project packages keep a visible compound complete in the exported project", () => {const source = packageData([entry("one"), entry("two"), entry("outside")], catalog());source.compoundCases = [{@@ -559,7 +587,7 @@ test("project packages keep a visible compound complete in the exported project"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.organizerState.collections[0].entryIds, ["one"]);assert.deepEqual(selected.compoundCases[0].memberEntryIds, ["one", "two"]);});diff --git a/test/library-selection.test.js b/test/library-selection.test.jsindex f5ad701..1eec4b4 100644--- a/test/library-selection.test.js+++ b/test/library-selection.test.js@@ -65,7 +65,7 @@ test("free-tag batch payload expands compounds and normalizes optional labels",assert.deepEqual(withoutLabels.customLabels, []);});-test("project batch payload requires explicit add or move semantics", () => {+test("project batch payload requires explicit add, remove, or move semantics", () => {const added = buildLibraryBatchPayload(["entry:a"], [], {type: LIBRARY_BATCH_ACTIONS.setProject,collectionId: " collection:campaign ",@@ -76,6 +76,11 @@ test("project batch payload requires explicit add or move semantics", () => {collectionId: "collection:archive",mode: "move"});+ const removed = buildLibraryBatchPayload(["entry:a"], [], {+ type: LIBRARY_BATCH_ACTIONS.setProject,+ collectionId: "collection:campaign",+ mode: "remove"+ });assert.deepEqual(added, {type: "BATCH_SET_PROJECT",@@ -84,12 +89,13 @@ test("project batch payload requires explicit add or move semantics", () => {mode: "add"});assert.equal(moved.mode, "move");+ assert.equal(removed.mode, "remove");assert.throws(() => buildLibraryBatchPayload(["entry:a"], [], {type: LIBRARY_BATCH_ACTIONS.setProject,collectionId: "collection:campaign"}),- /明确选择添加或移动/+ /明确选择加入、移出或移动/);});diff --git a/test/library-sorting-ui.test.js b/test/library-sorting-ui.test.jsindex 8c8d48c..06708be 100644--- a/test/library-sorting-ui.test.js+++ b/test/library-sorting-ui.test.js@@ -8,7 +8,7 @@ const [html, source, css] = await Promise.all([readFile(new URL("../library.css", import.meta.url), "utf8")]);-test("library exposes four case sorts and keeps project ordering as an on-demand action", () => {+test("library exposes four case sorts and keeps project structure management on demand", () => {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"[^>]*>最近更新/);@@ -18,7 +18,7 @@ test("library exposes four case sorts and keeps project ordering as an on-demandassert.match(html, /id="manage-case-order"[^>]*aria-label="管理案例顺序"/);assert.doesNotMatch(html, /id="project-sort"|最近创建|项目排序/);- assert.match(html, /id="manage-project-order"[^>]*aria-label="管理项目顺序"/);+ assert.match(html, /id="manage-project-order"[^>]*aria-label="管理项目结构"/);});test("sidebar keeps the recycle bin without smart or import-batch views", () => {@@ -27,7 +27,7 @@ test("sidebar keeps the recycle bin without smart or import-batch views", () =>assert.doesNotMatch(source, /renderSmartFilters|filterCasesByImportBatch|filterUnassignedCases/);});-test("case manual ordering is gated to an unfiltered project and project ordering uses direct drag", () => {+test("case manual ordering is gated to an unfiltered project and project tree uses direct drag", () => {const availability = source.slice(source.indexOf("function projectManualOrderAvailable"), source.indexOf("function syncGallerySortControl"));assert.match(availability, /selectedCollectionId/);assert.match(availability, /!selectedContentId/);@@ -41,17 +41,29 @@ test("case manual ordering is gated to an unfiltered project and project orderinassert.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, /"ArrowLeft", "ArrowRight", "Home", "End"/);+ assert.match(source, /type: "MOVE_COLLECTION", collectionId, parentId, index/);+ assert.match(source, /position === "inside"/);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.match(source, /"结束案例选择后可管理项目结构"/);assert.doesNotMatch(source, /elements\.manageProjectOrder\.hidden = Boolean\(selectionMode\)/);assert.doesNotMatch(source, /createUiIcon\("arrow-(?:up|down)"\)/);});+test("project tree rendering indexes children once and traverses deep trees iteratively", () => {+ const render = source.slice(source.indexOf("function renderProjectFilters"), source.indexOf("function projectChildren"));+ assert.match(render, /const childrenByParent = indexProjectChildren\(\)/);+ assert.match(render, /while \(pendingCollections\.length\)/);+ assert.doesNotMatch(render, /appendVisible|renderProjectFilters\([^)]*depth/);++ const index = source.slice(source.indexOf("function indexProjectChildren"), source.indexOf("function toggleProjectOrderManagement"));+ assert.match(index, /const result = new Map\(\)/);+ assert.match(index, /for \(const collection of organizerState\.collections\)/);+});+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/);diff --git a/test/library_navigation_e2e.py b/test/library_navigation_e2e.pyindex 7aa7f79..2c8ae3c 100644--- a/test/library_navigation_e2e.py+++ b/test/library_navigation_e2e.py@@ -216,6 +216,16 @@ def main() -> None: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("#select-cases").click()+ library.locator("#selection-select-filtered").click()+ library.locator("#selection-project-menu > summary").click()+ library.locator("#selection-project-target").select_option("collection:navigation")+ expect(library.locator("#selection-remove-project")).to_be_enabled()+ library.locator("#selection-remove-project").click()+ expect(library.locator("#feedback")).to_contain_text("已将 1 个案例移出项目,1 个原本不在该项目")+ expect(library.locator("#case-list > .case-card")).to_have_count(2)+ project_members = library.evaluate("async () => (await chrome.storage.local.get('organizerState')).organizerState.collections[0].entryIds")+ assert project_members == [], project_memberslibrary.locator("#filter-sidebar").evaluate("node => { node.scrollTop = 0; }")library.screenshot(path=str(screenshots / "promptdirector-step2-library-desktop.png"), full_page=True)diff --git a/test/media-ui.test.js b/test/media-ui.test.jsindex 29edef4..e07d150 100644--- a/test/media-ui.test.js+++ b/test/media-ui.test.js@@ -139,7 +139,7 @@ test("the library includes a local quick-note entry that does not invoke AI", ()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.match(quickNote, /caseCreationOrganization\(projectName, customLabels, projectInput\?\.dataset\.projectId\)/);assert.doesNotMatch(quickNote, /ANALY|DeepSeek|OpenAI/);});@@ -147,9 +147,9 @@ test("new video references and quick notes accept an existing or new project pluconst 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, /caseCreationOrganization\(\s*projectName,\s*customLabels,\s*projectInput\?\.dataset\.projectId\s*\)/);assert.match(video, /CREATE_MEDIA_REFERENCE[\s\S]*?\.\.\.organization/);- assert.match(note, /CREATE_QUICK_NOTE[\s\S]*?\.\.\.caseCreationOrganization\(projectName, customLabels\)/);+ assert.match(note, /CREATE_QUICK_NOTE[\s\S]*?\.\.\.caseCreationOrganization\(projectName, customLabels, projectInput\?\.dataset\.projectId\)/);assert.match(note, /label:\s*"添加标签"/);assert.match(note, /newCollectionName:\s*projectName/);assert.match(note, /collectionId:\s*existing\.id/);diff --git a/test/organizer-background.test.js b/test/organizer-background.test.jsindex f006b91..5a0a7ff 100644--- a/test/organizer-background.test.js+++ b/test/organizer-background.test.js@@ -12,10 +12,11 @@ function functionBlock(name, nextName) {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"/);+test("background exposes tree moves without rebuilding member lists", () => {+ assert.match(background, /case "REORDER_COLLECTIONS":\s*case "MOVE_COLLECTION":\s*case "REPLACE_COLLECTION_ENTRIES"/);const update = functionBlock("updateOrganizer", "decideAnalysisCandidate");assert.match(update, /reorderCollections\(organizerState, message\.collectionIds\)/);+ assert.match(update, /moveCollection\(organizerState, message\.collectionId, message\.parentId, message\.index\)/);assert.match(update, /replaceCollectionEntries\(organizerState, message\.collectionId, entryIds\)/);assert.match(update, /changedProjectEntryIds\(beforeOrganizer, organizerState\)/);});diff --git a/test/organizer.test.js b/test/organizer.test.jsindex cfa8ee7..95fa3ff 100644--- a/test/organizer.test.js+++ b/test/organizer.test.js@@ -13,6 +13,12 @@ import {replaceCollectionEntries,renameCollection,isEntryVisibleInLibrary,+ collectionEntryIds,+ collectionPathLabel,+ collectionSelectorLabel,+ collectionSubtreeEntryIdsById,+ collectionSubtreeIds,+ moveCollection,setCollectionVisibility,setEntriesCollection} from "../organizer.js";@@ -29,7 +35,7 @@ test("organizer drops obsolete saved searches and only keeps explicit projects",savedViews: [{ id: "view:old", name: "视频参考", query: "type:video" }],collections: [{ id: "collection:a", name: "项目 A", entryIds: [] }]});- assert.equal(normalized.version, 6);+ assert.equal(normalized.version, 7);assert.deepEqual(Object.keys(normalized), ["version", "collections"]);});@@ -91,6 +97,7 @@ test("project and entries deletion is planned atomically and removes shared projassert.deepEqual(result.organizerState.collections, [{id: "collection:keep",name: "保留项目",+ parentId: null,order: 0,entryIds: ["three"],visibility: COLLECTION_VISIBILITY.library@@ -172,3 +179,76 @@ test("organizer upgrade permanently discards legacy project methods", () => {}, ["one"]);assert.equal(Object.hasOwn(normalized.collections[0], "projectMethods"), false);});++test("legacy flat projects migrate to roots without changing membership or order", () => {+ const normalized = normalizeOrganizerState({+ version: 6,+ collections: [+ { id: "collection:a", name: "A", order: 1, entryIds: ["one"] },+ { id: "collection:b", name: "B", order: 0, entryIds: ["one", "two"] }+ ]+ });+ assert.deepEqual(normalized.collections.map(({ id, parentId, order, entryIds }) => ({ id, parentId, order, entryIds })), [+ { id: "collection:b", parentId: null, order: 0, entryIds: ["one", "two"] },+ { id: "collection:a", parentId: null, order: 1, entryIds: ["one"] }+ ]);+});++test("projects move across parents and reject cycles", () => {+ const state = normalizeOrganizerState({ collections: [+ { id: "root", name: "根", order: 0, entryIds: ["one"] },+ { id: "peer", name: "同级", order: 1, entryIds: [] },+ { id: "child", name: "子项目", parentId: "root", order: 0, entryIds: ["two"] }+ ] });+ const moved = moveCollection(state, "peer", "root", 0);+ assert.deepEqual(moved.collections.map(({ id, parentId, order }) => ({ id, parentId, order })), [+ { id: "root", parentId: null, order: 0 },+ { id: "peer", parentId: "root", order: 0 },+ { id: "child", parentId: "root", order: 1 }+ ]);+ assert.throws(() => moveCollection(moved, "root", "child", 0), /自身或其子项目/);+});++test("tree helpers preserve paths and deduplicate subtree cases", () => {+ const state = { collections: [+ { id: "root", name: "根", entryIds: ["one"] },+ { id: "child", name: "素材", parentId: "root", entryIds: ["one", "two"] }+ ] };+ assert.deepEqual(collectionSubtreeIds(state, "root"), ["root", "child"]);+ assert.deepEqual(collectionEntryIds(state, "root", { subtree: true }), ["one", "two"]);+ assert.equal(collectionPathLabel(state, "child"), "根 / 素材");+ assert.deepEqual(collectionSubtreeEntryIdsById(state).get("root"), ["one", "two"]);+});++test("project selector labels distinguish literal separators from nested paths", () => {+ const state = { collections: [+ { id: "literal", name: "A › B", entryIds: [] },+ { id: "root", name: "A", entryIds: [] },+ { id: "child", name: "B", parentId: "root", entryIds: [] }+ ] };+ assert.equal(collectionSelectorLabel(state, "literal"), "A ›› B");+ assert.equal(collectionSelectorLabel(state, "child"), "A › B");+});++test("deep project trees normalize and traverse without recursive stack overflow", () => {+ const collections = Array.from({ length: 6000 }, (_, index) => ({+ id: `project:${index}`,+ name: `P${index}`,+ parentId: index ? `project:${index - 1}` : null,+ entryIds: index === 5999 ? ["case:deep"] : []+ }));+ const state = normalizeOrganizerState({ collections });+ assert.equal(state.collections.length, 6000);+ assert.equal(collectionSubtreeIds(state, "project:0").length, 6000);+ assert.deepEqual(collectionEntryIds(state, "project:0", { subtree: true }), ["case:deep"]);+});++test("project names are unique only among siblings", () => {+ let state = createCollection({}, "根 A").state;+ state = createCollection(state, "根 B").state;+ const [rootA, rootB] = state.collections;+ state = createCollection(state, "素材", rootA.id).state;+ state = createCollection(state, "素材", rootB.id).state;+ assert.equal(state.collections.filter((item) => item.name === "素材").length, 2);+ assert.throws(() => createCollection(state, "素材", rootA.id), /已经存在/);+});diff --git a/test/project-combobox.test.js b/test/project-combobox.test.jsindex 108fb49..a86405c 100644--- a/test/project-combobox.test.js+++ b/test/project-combobox.test.js@@ -24,6 +24,16 @@ test("project combobox filters case-insensitively and removes duplicate or empty]);});+test("project combobox keeps project identity separate from duplicate display paths", () => {+ assert.deepEqual(projectComboboxOptions([+ { id: "project:literal", pathLabel: "A › B" },+ { id: "project:nested", pathLabel: "A › B" }+ ]), [+ { value: "project:literal", label: "A › B" },+ { value: "project:nested", label: "A › B" }+ ]);+});+test("project combobox opens toward the side that can contain its options", () => {assert.deepEqual(projectComboboxPlacement({inputTop: 420,diff --git a/test/projects_and_categories_e2e.py b/test/projects_and_categories_e2e.pyindex 2bc8c95..4784549 100644--- a/test/projects_and_categories_e2e.py+++ b/test/projects_and_categories_e2e.py@@ -43,7 +43,7 @@ def main() -> None: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("#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)@@ -75,7 +75,7 @@ def main() -> None:library.evaluate("""() => {window.__originalProjectSendMessage = chrome.runtime.sendMessage;- chrome.runtime.sendMessage = (message, ...rest) => message?.type === 'REORDER_COLLECTIONS'+ chrome.runtime.sendMessage = (message, ...rest) => message?.type === 'MOVE_COLLECTION'? Promise.resolve({ok: false, message: '模拟项目排序保存失败'}): window.__originalProjectSendMessage.call(chrome.runtime, message, ...rest);}""")@@ -93,11 +93,17 @@ def main() -> None: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(".project-row", has_text="项目与分类验收").focus()+ library.locator(".project-row", has_text="项目与分类验收").press("ArrowRight")+ expect(library.locator(".project-row", has_text="项目与分类验收")).to_have_attribute("aria-level", "2")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()+ library.locator(".project-filter", has_text="辅助项目").click()+ expect(library.locator("#project-folder-list .project-folder-card", has_text="项目与分类验收")).to_be_visible()+ expect(library.locator("#result-count")).to_have_text("0 个直接案例 · 1 个子项目")+ library.locator("#project-folder-list .project-folder-card", 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)@@ -118,7 +124,7 @@ def main() -> None: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", "结束案例选择后可排序项目")+ 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-more-menu > summary").click()diff --git a/test/skill-project-tree-ui.test.js b/test/skill-project-tree-ui.test.jsnew file mode 100644index 0000000..ad5caba--- /dev/null+++ b/test/skill-project-tree-ui.test.js@@ -0,0 +1,11 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";++const source = await readFile(new URL("../skills-page.js", import.meta.url), "utf8");++test("Skill source projects display full paths and include descendant cases", () => {+ assert.match(source, /collectionSelectorLabelsById\(organizerState\)/);+ assert.match(source, /collectionEntryIds\(organizerState, projectId, \{ subtree: true \}\)/);+ assert.doesNotMatch(source, /projectId \? new Set\(organizerState\.collections\.find/);+});diff --git a/test/sync-model.test.js b/test/sync-model.test.jsindex 0e828ce..04a5091 100644--- a/test/sync-model.test.js+++ b/test/sync-model.test.js@@ -68,6 +68,33 @@ test("canonical video media references survive sync snapshots without reverting});});+test("legacy flat sync snapshots migrate projects to roots", async () => {+ const legacyState = state([], [{ id: "collection:legacy", name: "Legacy", order: 0, entryIds: [] }]);+ const snapshot = await createRevisionSnapshot(legacyState, { deviceId: "legacy-device", logicalClock: 4 });+ snapshot.version = 1;+ delete snapshot.records["collection:collection%3Alegacy"].payload.parentId;++ const merged = mergeRevisionSnapshots([snapshot]);+ assert.equal(merged.state.organizerState.collections[0].parentId, null);+});++test("a later legacy flat snapshot cannot flatten a tree-aware project record", async () => {+ const treeState = state([], [+ { id: "collection:root", name: "Root", parentId: null, order: 0, entryIds: [] },+ { id: "collection:child", name: "Child", parentId: "collection:root", order: 0, entryIds: [] }+ ]);+ const legacyState = state([], [+ { id: "collection:child", name: "Child", order: 0, entryIds: [] }+ ]);+ const tree = await createRevisionSnapshot(treeState, { deviceId: "tree-device", logicalClock: 5 });+ const legacy = await createRevisionSnapshot(legacyState, { deviceId: "legacy-device", logicalClock: 99 });+ legacy.version = 1;+ delete legacy.records["collection:collection%3Achild"].payload.parentId;++ const merged = mergeRevisionSnapshots([tree, legacy]);+ assert.equal(merged.state.organizerState.collections.find((item) => item.id === "collection:child").parentId, "collection:root");+});+test("external Skill package files keep encrypted object references through sync", async () => {const objectId = "c".repeat(64);const source = state();@@ -144,7 +171,7 @@ test("trashed entries sync as trash records without becoming active entries", asconst snapshot = await createRevisionSnapshot(source, { deviceId: "device-a", logicalClock: 1 });const merged = mergeRevisionSnapshots([snapshot]);- assert.equal(snapshot.version, 1);+ assert.equal(snapshot.version, 2);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");diff --git a/test/taxonomy.test.js b/test/taxonomy.test.jsindex 946da7c..a0de424 100644--- a/test/taxonomy.test.js+++ b/test/taxonomy.test.js@@ -164,7 +164,7 @@ test("older editable vocabulary migrates to schema 12 with an empty project orgaassert.equal(migrated.state.facetCatalog.facets.length, 10);assert.deepEqual(migrated.state.entries[0].facetAssignments, []);assert.deepEqual(migrated.state.entries[0].customLabels, ["私人风格"]);- assert.deepEqual(migrated.state.organizerState, { version: 6, collections: [] });+ assert.deepEqual(migrated.state.organizerState, { version: 7, collections: [] });});test("schema 9 migration removes old DeepSeek review noise while preserving confirmed and image analysis data", () => {diff --git a/test/trash-background.test.js b/test/trash-background.test.jsindex 392ac40..81e637b 100644--- a/test/trash-background.test.js+++ b/test/trash-background.test.js@@ -27,6 +27,7 @@ test("all user-facing case, media, and project deletion routes move metadata toassert.doesNotMatch(mediaDeletion, /deleteMediaBlob|deleteScreenshotBlob/);const projectDeletion = functionBlock("deleteCollectionWithEntries", "moveEntryBatchToTrash");assert.match(projectDeletion, /moveCollectionWithEntriesToTrash/);+ assert.match(projectDeletion, /collectionEntryIds\(organizerState, collection\.id, \{ subtree: true \}\)/);assert.doesNotMatch(projectDeletion, /deleteMediaBlob|deleteScreenshotBlob/);});@@ -41,14 +42,15 @@ test("trash restore and irreversible cleanup have separate explicit message contassert.match(cleanup, /永久删除/);});-test("free-label and project batch actions are wired with additive and move modes", () => {+test("free-label and project batch actions are wired with add, remove, 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, /\["remove", "move"\]\.includes\(message\.mode\)/);+ assert.match(projects, /mode !== "remove"/);assert.match(projects, /removeEntriesFromOrganizer/);assert.match(projects, /setEntriesCollection/);});diff --git a/test/trash.test.js b/test/trash.test.jsindex f1816bb..284e52f 100644--- a/test/trash.test.js+++ b/test/trash.test.js@@ -249,10 +249,11 @@ test("moving a project to trash leaves its member cases active", () => {kind: "collection",targetId: "collection:a",deletedAt: "2026-08-22T02:00:00.000Z",- snapshot: {- id: "collection:a",- name: "项目 A",- order: 0,+ snapshot: {+ id: "collection:a",+ name: "项目 A",+ parentId: null,+ order: 0,entryIds: ["one", "two"],visibility: "library"},@@ -260,6 +261,45 @@ test("moving a project to trash leaves its member cases active", () => {});});+test("moving and restoring a project subtree preserves parents and sibling order atomically", () => {+ const context = {+ trashState: {},+ entries: [{ id: "root-case" }, { id: "child-case" }],+ organizerState: {+ version: 7,+ collections: [+ { id: "collection:root", name: "Root", parentId: null, order: 0, entryIds: ["root-case"] },+ { id: "collection:first", name: "First", parentId: "collection:root", order: 0, entryIds: ["child-case"] },+ { id: "collection:second", name: "Second", parentId: "collection:root", order: 1, entryIds: [] }+ ]+ }+ };+ const moved = moveCollectionsToTrash(context, ["collection:root"], { deletedAt: "2026-08-24T00:00:00Z" });+ assert.deepEqual(moved.organizerState.collections, []);+ assert.deepEqual(moved.trashState.items.map((item) => item.targetId), ["collection:root", "collection:first", "collection:second"]);++ const restored = restoreTrashItems(moved, moved.movedItemIds);+ assert.deepEqual(restored.organizerState.collections.map((item) => ({ id: item.id, parentId: item.parentId, order: item.order })), [+ { id: "collection:root", parentId: null, order: 0 },+ { id: "collection:first", parentId: "collection:root", order: 0 },+ { id: "collection:second", parentId: "collection:root", order: 1 }+ ]);+ assert.deepEqual(restored.warnings, []);+});++test("restoring a child without its missing parent moves it to root and reports the fallback", () => {+ const moved = moveCollectionsToTrash({+ trashState: {},+ organizerState: { collections: [+ { id: "collection:root", name: "Root", parentId: null, order: 0, entryIds: [] },+ { id: "collection:child", name: "Child", parentId: "collection:root", order: 0, entryIds: [] }+ ] }+ }, ["collection:root"], { deletedAt: "2026-08-24T00:00:00Z" });+ const restored = restoreTrashItems(moved, ["trash:collection:collection:child"]);+ assert.equal(restored.organizerState.collections[0].parentId, null);+ assert.match(restored.warnings[0].reason, /恢复到根级/);+});+test("moving a case to trash keeps its labels and exact project memberships without ghost references", () => {const source = {trashState: createDefaultTrashState(),diff --git a/trash.js b/trash.jsindex 1e3bb42..b764f5f 100644--- a/trash.js+++ b/trash.js@@ -1,4 +1,9 @@-import { normalizeOrganizerState, removeEntriesFromOrganizer } from "./organizer.js";+import {+ collectionEntryIds,+ collectionSubtreeIds,+ normalizeOrganizerState,+ removeEntriesFromOrganizer+} from "./organizer.js";import { normalizeEntryMedia, removeEntryMedia } from "./media.js";import { normalizeCompoundCases, removeEntriesFromCompoundCases } from "./compound-cases.js";@@ -80,20 +85,22 @@ export function moveCollectionWithEntriesToTrash(contextValue = {}, collectionIdconst collection = organizerState.collections.find((item) => item.id === collectionId);if (!collection) throw new Error("项目不存在");- const entriesMoved = moveEntriesToTrash({ ...contextValue, organizerState }, collection.entryIds, options);+ const subtreeCollectionIds = collectionSubtreeIds(organizerState, collection.id);+ const subtreeEntryIds = collectionEntryIds(organizerState, collection.id, { subtree: true });+ const entriesMoved = moveEntriesToTrash({ ...contextValue, organizerState }, subtreeEntryIds, options);const collectionMoved = moveCollectionsToTrash({...contextValue,trashState: entriesMoved.trashState,organizerState- }, [collection.id], options);+ }, subtreeCollectionIds, options);return {...contextValue,trashState: collectionMoved.trashState,entries: entriesMoved.entries,- organizerState: removeEntriesFromOrganizer(collectionMoved.organizerState, collection.entryIds),+ organizerState: removeEntriesFromOrganizer(collectionMoved.organizerState, subtreeEntryIds),...(Array.isArray(contextValue.compoundCases) ? { compoundCases: entriesMoved.compoundCases } : {}),movedItemIds: [...entriesMoved.movedItemIds, ...collectionMoved.movedItemIds],- movedEntryIds: collection.entryIds.filter((id) => entries.some((entry) => clean(entry?.id) === id)),+ movedEntryIds: subtreeEntryIds.filter((id) => entries.some((entry) => clean(entry?.id) === id)),collection: structuredClone(collection)};}@@ -102,7 +109,8 @@ export function moveCollectionsToTrash(contextValue = {}, collectionIds = [], opconst deletedAt = operationTime(options.deletedAt);const organizerState = normalizeOrganizerState(contextValue.organizerState);const trashState = normalizeTrashState(contextValue.trashState);- const requested = new Set(uniqueIds(collectionIds));+ const requestedRoots = uniqueIds(collectionIds);+ const requested = new Set(requestedRoots.flatMap((id) => collectionSubtreeIds(organizerState, id)));const existingTrashIds = new Set(trashState.items.map((item) => item.id));const moved = organizerState.collections.flatMap((collection) => {const trashId = trashItemId("collection", collection.id);@@ -194,6 +202,7 @@ export function restoreTrashItems(contextValue = {}, itemIds = [], options = {})let organizerState = structuredClone(normalizeOrganizerState(contextValue.organizerState));const restored = new Set();const unresolved = [];+ const warnings = [];const kindOrder = { collection: 0, entry: 1, media: 2 };const candidates = trashState.items.filter((item) => requested.has(item.id))@@ -203,12 +212,19 @@ export function restoreTrashItems(contextValue = {}, itemIds = [], options = {})...candidates.filter((item) => item.kind === "entry").map((item) => item.targetId)]);- for (const item of candidates) {+ const collectionRestore = restoreCollectionItems(+ candidates.filter((item) => item.kind === "collection"),+ organizerState,+ restorableEntryIds+ );+ organizerState = collectionRestore.organizerState;+ collectionRestore.restoredItemIds.forEach((id) => restored.add(id));+ unresolved.push(...collectionRestore.unresolved);+ warnings.push(...collectionRestore.warnings);++ for (const item of candidates.filter((candidate) => candidate.kind !== "collection")) {let result;- if (item.kind === "collection") {- result = restoreCollectionItem(item, organizerState, restorableEntryIds);- if (result.ok) organizerState = result.organizerState;- } else if (item.kind === "entry") {+ if (item.kind === "entry") {result = restoreEntryItem(item, entries, organizerState, options.collectionReplacements);if (result.ok) organizerState = result.organizerState;} else {@@ -231,7 +247,8 @@ export function restoreTrashItems(contextValue = {}, itemIds = [], options = {})organizerState,...(Array.isArray(contextValue.compoundCases) ? { compoundCases } : {}),restoredItemIds: trashState.items.filter((item) => restored.has(item.id)).map((item) => item.id),- unresolved+ unresolved,+ warnings};}@@ -272,27 +289,51 @@ export function emptyTrash(stateValue = {}, options = {}) {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("当前资料库存在同编号但内容不同的项目");+function restoreCollectionItems(items, organizerState, restorableEntryIds) {+ const unresolved = [];+ const warnings = [];+ const accepted = [];+ const existingById = new Map(organizerState.collections.map((collection) => [collection.id, collection]));+ for (const item of items) {+ const snapshot = serializableObject(item.snapshot);+ if (clean(snapshot.id) !== item.targetId || !clean(snapshot.name)) {+ unresolved.push({ itemId: item.id, kind: item.kind, targetId: item.targetId, reason: "项目快照无效" });+ continue;+ }+ const existing = existingById.get(item.targetId);+ if (existing) {+ const normalizedSnapshot = normalizeOrganizerState({+ ...organizerState,+ collections: [...organizerState.collections.filter((collection) => collection.id !== item.targetId), snapshot]+ }).collections.find((collection) => collection.id === item.targetId);+ if (jsonEqual(existing, normalizedSnapshot)) accepted.push({ item, snapshot: null });+ else unresolved.push({ itemId: item.id, kind: item.kind, targetId: item.targetId, reason: "当前资料库存在同编号但内容不同的项目" });+ continue;+ }+ const missingEntryIds = uniqueIds(snapshot.entryIds).filter((entryId) => !restorableEntryIds.has(entryId));+ if (missingEntryIds.length) {+ unresolved.push({ itemId: item.id, kind: item.kind, targetId: item.targetId, reason: "项目成员案例不存在", missingEntryIds });+ continue;+ }+ accepted.push({ item, snapshot });}- const missingEntryIds = normalized.entryIds.filter((entryId) => !restorableEntryIds.has(entryId));- if (missingEntryIds.length) {- return unresolvedIssue("项目成员案例不存在", { missingEntryIds });+ const availableIds = new Set([...existingById.keys(), ...accepted.map(({ item }) => item.targetId)]);+ for (const acceptedItem of accepted) {+ if (!acceptedItem.snapshot) continue;+ const originalParentId = clean(acceptedItem.snapshot.parentId);+ if (originalParentId && !availableIds.has(originalParentId)) {+ acceptedItem.snapshot.parentId = null;+ warnings.push({ itemId: acceptedItem.item.id, reason: "原父项目不存在,已恢复到根级", missingParentId: originalParentId });+ }}return {- ok: true,organizerState: normalizeOrganizerState({...organizerState,- collections: [...organizerState.collections, normalized]- })+ collections: [...organizerState.collections, ...accepted.map(({ snapshot }) => snapshot).filter(Boolean)]+ }),+ restoredItemIds: accepted.map(({ item }) => item.id),+ unresolved,+ warnings};}