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
让采集补充保持一个案例并修复组图漏采
MigenAIac29a33c7395
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2074ead..7154c2b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,13 @@# Changelog+## 1.20.3++- 采集侧栏统一选图、选区、剪贴板、截图和网页补充入口,同一案例可连续追加、去重、移除和撤销。+- 修复 X 轮播组图漏采;主帖图片默认选中,引用帖图片可整组加入,减少无关页面内容。+- 分类、项目和标签直接可见并随网页采集保存;只保存正文时保留未保存图片。+- 修复采集取消、重新确认、截图完成与高亮定位的状态问题。+- 图片和视频提示词案例按内容分类使用既有详情结构;清理帖子杂文、文章排版与重复媒体占位。+## 1.20.2- 修复文件夹备份目录选择器丢失用户手势;预检后才创建备份目录,写入和回读验证后再生成完成标记,取消及失败反馈更准确。diff --git a/article-editor.js b/article-editor.jsindex 1f723f8..ca820e4 100644--- a/article-editor.js+++ b/article-editor.js@@ -1,14 +1,27 @@import { ARTICLE_TEXT_KINDS } from "./article-edit.js";import { preserveElementPosition } from "./detail-position.js";+import { renderArticleBlockText } from "./article-text-view.js";+import { createUiIcon } from "./ui-icons.js";-export function attachArticleEditor(reader, entry, { onSave, onError, t }) {+export function attachArticleEditor(reader, entry, { onSave, onError, onCopy, contextParts = [], t }) {const toolbar = document.createElement("div");toolbar.className = "article-editor-toolbar";- const edit = button("编辑正文", "button-secondary");+ const context = document.createElement("span");+ context.className = "article-reader-context";+ for (const text of contextParts.length ? contextParts : [t("正文")]) {+ const part = document.createElement("span");+ part.textContent = text;+ context.append(part);+ }+ toolbar.append(context);+ const copy = iconButton("复制文字", "copy");+ copy.disabled = !entry.text;+ copy.addEventListener("click", () => onCopy(copy));+ const edit = iconButton("编辑正文", "pencil");const save = button("保存");const cancel = button("取消", "button-secondary");save.hidden = cancel.hidden = true;- toolbar.append(edit, save, cancel);+ toolbar.append(copy, edit, save, cancel);reader.prepend(toolbar);reader.dataset.articleIdentity = JSON.stringify(entry.articleDocument);let blocks = entry.articleDocument.blocks;@@ -17,8 +30,11 @@ export function attachArticleEditor(reader, entry, { onSave, onError, t }) {const setEditing = editing => {reader.dataset.editing = String(editing);edit.hidden = editing;+ copy.hidden = editing;save.hidden = cancel.hidden = !editing;for (const node of textNodes()) {+ const block = blocks.find(item => item.id === node.dataset.articleBlockId);+ if (block?.kind === "list") renderArticleBlockText(node, block, { editing });node.contentEditable = editing ? "plaintext-only" : "false";if (editing) {node.setAttribute("role", "textbox");@@ -45,7 +61,7 @@ export function attachArticleEditor(reader, entry, { onSave, onError, t }) {const resetText = () => {for (const node of textNodes()) {const block = blocks.find(item => item.id === node.dataset.articleBlockId);- if (block) node.textContent = block.text;+ if (block) renderArticleBlockText(node, block, { editing: reader.dataset.editing === "true" });else node.remove();}reader.dataset.dirty = "false";@@ -88,4 +104,11 @@ export function attachArticleEditor(reader, entry, { onSave, onError, t }) {node.className = className;return node;}+ function iconButton(label, icon) {+ const node = button(label, "button-secondary prompt-icon-action");+ node.title = t(label);+ node.setAttribute("aria-label", t(label));+ node.replaceChildren(createUiIcon(icon));+ return node;+ }}diff --git a/article-text-view.js b/article-text-view.jsnew file mode 100644index 0000000..c691abb--- /dev/null+++ b/article-text-view.js@@ -0,0 +1,14 @@+// Keep the stored block text intact while giving lists their reading structure.+export function renderArticleBlockText(node, block, { editing = false } = {}) {+ if (block.kind !== "list" || editing) {+ node.textContent = block.text;+ return;+ }+ const list = node.ownerDocument.createElement(block.ordered ? "ol" : "ul");+ for (const text of block.text.split("\n").filter(line => line.trim())) {+ const item = node.ownerDocument.createElement("li");+ item.textContent = text;+ list.append(item);+ }+ node.replaceChildren(list);+}diff --git a/assets/ui-icons.svg b/assets/ui-icons.svgindex 73facf2..3a76d4b 100644--- a/assets/ui-icons.svg+++ b/assets/ui-icons.svg@@ -28,6 +28,10 @@<path d="M21.801 10A10 10 0 1 1 17 3.335" /><path d="m9 11 3 3L22 4" /></symbol>+ <symbol id="icon-clipboard" viewBox="0 0 24 24">+ <rect width="8" height="4" x="8" y="2" rx="1" ry="1" />+ <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />+ </symbol><symbol id="icon-copy" viewBox="0 0 24 24"><rect width="14" height="14" x="8" y="8" rx="2" ry="2" /><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />@@ -176,6 +180,10 @@<path d="M3 6h18" /><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /></symbol>+ <symbol id="icon-undo-2" viewBox="0 0 24 24">+ <path d="M9 14 4 9l5-5" />+ <path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11" />+ </symbol><symbol id="icon-upload" viewBox="0 0 24 24"><path d="M12 3v12" /><path d="m17 8-5-5-5 5" />diff --git a/background.js b/background.jsindex 5ad44ce..186229a 100644--- a/background.js+++ b/background.js@@ -1,3 +1,4 @@+import { renderPageCaptureRegionPreview, clearPageCapturePageState } from "./page-capture-highlight.js";import { collectLibTvPublicPayload, normalizeLibTvPublicPayload } from "./libtv-capture.js";import { updateArticleText } from "./article-edit.js";import { showPageToast } from "./capture-region.js";@@ -686,13 +687,13 @@ async function handleMessage(message, interaction = {}) {case "CANCEL_PAGE_CAPTURE":return cancelPageCapture(message.sessionId);case "PREVIEW_PAGE_CAPTURE_REGION":- return previewPageCaptureRegion(message.tabId, message.marker);+ return previewPageCaptureRegion(message.tabId, message.preview);case "CLEAR_PAGE_CAPTURE_MARKERS":return clearPageCaptureMarkers(message.tabId, message.removeRegionMarkers !== false);case "EDIT_PAGE_CAPTURE_REGION":return editPageCaptureRegion(message.tabId, message.candidate, message.mode);case "COMMIT_PAGE_CAPTURE":- return enqueueCapture(async () => enqueue(async () => commitPageCapture(message.batch)));+ return enqueueCapture(async () => enqueue(async () => commitPageCapture(message.batch, message)));case "PAGE_CAPTURE_VIEWPORT_FALLBACKS":return capturePageCaptureViewportFallbacks(message, interaction.sender);case "SMART_VISUAL_SELECTION_CHANGED":@@ -1136,6 +1137,7 @@ async function captureWorkspace() {draft,targetEntry,suggestedContentTypeId: suggested?.pathIds?.[0] || "",+ classificationContext: { taxonomy: state.taxonomy, rules: state.classificationRules },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,@@ -1469,18 +1471,18 @@ async function cancelPageCapture(sessionIdValue) {}}-async function previewPageCaptureRegion(tabIdValue, markerValue) {+async function previewPageCaptureRegion(tabIdValue, preview) {const tabId = Number(tabIdValue);if (!Number.isInteger(tabId)) return { ok: false, message: "采集页面已经关闭" };try {const [result] = await chrome.scripting.executeScript({target: { tabId },func: renderPageCaptureRegionPreview,- args: [String(markerValue || "")]+ args: [preview || {}]});- return result?.result+ return result?.result?.ok? { ok: true }- : { ok: false, message: markerValue ? "原网页区域已经变化,请重新扫描" : "区域高亮已关闭" };+ : { ok: false, message: "部分内容无法在网页定位,请以保存预览为准" };} catch {return { ok: false, message: "无法在当前网页显示区域高亮" };}@@ -1511,23 +1513,6 @@ async function clearPageCaptureEditorMarkers(tabIdValue) {});}-function clearPageCapturePageState(optionsValue = {}) {- const options = optionsValue && typeof optionsValue === "object" ? optionsValue : {};- if (options.removePreview !== false) document.getElementById("promptdirector-page-capture-region-preview")?.remove();- if (options.removeEditor !== false) document.getElementById("promptdirector-page-capture-region-editor")?.remove();- for (const element of document.querySelectorAll("[data-promptdirector-page-edit-include],[data-promptdirector-page-edit-exclude],[data-promptdirector-page-edit-hover]")) {- element.removeAttribute("data-promptdirector-page-edit-include");- element.removeAttribute("data-promptdirector-page-edit-exclude");- element.removeAttribute("data-promptdirector-page-edit-hover");- }- if (options.removeRegionMarkers) {- for (const element of document.querySelectorAll("[data-promptdirector-capture-region]")) {- element.removeAttribute("data-promptdirector-capture-region");- }- }- return true;-}-async function editPageCaptureRegion(tabIdValue, candidateValue, modeValue) {const tabId = Number(tabIdValue);const candidate = normalizePageCaptureCandidate(candidateValue);@@ -1565,6 +1550,7 @@ async function editPageCaptureRegion(tabIdValue, candidateValue, modeValue) {function runPageCaptureRegionEditor(markerValue, modeValue, tokenValue, priorEditsValue, contentTargetsValue) {const overlayId = "promptdirector-page-capture-region-editor";+ document.getElementById(overlayId)?.dispatchEvent(new Event("promptdirector-cancel"));document.getElementById(overlayId)?.remove();const marker = String(markerValue || "");const mode = modeValue === "exclude" ? "exclude" : "include";@@ -1614,7 +1600,6 @@ function runPageCaptureRegionEditor(markerValue, modeValue, tokenValue, priorEdistyle.textContent = `[${includeAttribute}="${token}"]{outline:4px solid #8fcf3a!important;outline-offset:3px!important}[${excludeAttribute}="${token}"]{outline:4px solid #ff6b5f!important;outline-offset:3px!important;opacity:.48!important}[${hoverAttribute}="${token}"]{outline:3px dashed #ffd65c!important;outline-offset:2px!important}`;root.append(style);document.documentElement.append(root);- baseRoot.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });const changes = [];const targetSelector = "img,video,iframe,a[download],a[href$='.pdf' i],a[href$='.md' i],a[href$='.txt' i],a[href$='.rtf' i],h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,figure,article,section,div";const updateCount = () => {@@ -1719,6 +1704,7 @@ function runPageCaptureRegionEditor(markerValue, modeValue, tokenValue, priorEdiapplyEdits();updateCount();return new Promise((resolve) => {+ root.addEventListener("promptdirector-cancel", () => cancel.click(), { once: true });group.addEventListener("click", (event) => {event.stopPropagation();groupMode = !groupMode;@@ -1745,37 +1731,8 @@ function runPageCaptureRegionEditor(markerValue, modeValue, tokenValue, priorEdi});}-function renderPageCaptureRegionPreview(markerValue) {- const overlayId = "promptdirector-page-capture-region-preview";- document.getElementById(overlayId)?.remove();- const marker = String(markerValue || "");- if (!marker) return true;- const target = [...document.querySelectorAll("[data-promptdirector-capture-region]")]- .find((element) => element.getAttribute("data-promptdirector-capture-region") === marker);- if (!target) return false;- target.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });- const rect = target.getBoundingClientRect();- const overlay = document.createElement("div");- overlay.id = overlayId;- overlay.setAttribute("aria-hidden", "true");- Object.assign(overlay.style, {- position: "fixed",- left: `${Math.max(0, rect.left)}px`,- top: `${Math.max(0, rect.top)}px`,- width: `${Math.max(1, Math.min(window.innerWidth, rect.right) - Math.max(0, rect.left))}px`,- height: `${Math.max(1, Math.min(window.innerHeight, rect.bottom) - Math.max(0, rect.top))}px`,- border: "3px solid Highlight",- borderRadius: "8px",- background: "color-mix(in srgb, Highlight 12%, transparent)",- boxSizing: "border-box",- pointerEvents: "none",- zIndex: "2147483647"- });- document.documentElement.append(overlay);- return true;-}--async function commitPageCapture(batchValue) {+async function commitPageCapture(batchValue, metadata = {}) {+ const captureMetadata = createCaptureDraft(metadata);let batch = normalizePageCaptureBatch(batchValue);if (Number.isInteger(batch.tabId) && batch.candidates.some((candidate) => candidate.media.some((media) => media.fallbackRect && !media.dataUrl))) {try {@@ -1955,7 +1912,10 @@ async function commitPageCapture(batchValue) {}const assetId = repair?.matched.get(media.id)?.id || crypto.randomUUID();try {- const resolved = await resolvePageCaptureImage(media, {+ const localBlob = media.localAssetId ? await getScreenshotBlob(media.localAssetId) : null;+ if (media.localAssetId && !localBlob) throw new Error("待补充的本地图片已不可用,请重新选择");+ const resolved = localBlob ? { blob: localBlob, sourceUrl: media.url, captureMethod: "source" }+ : await resolvePageCaptureImage(media, {sessionMediaAllowed: batch.sessionMediaAllowed,fetchMedia: async (url) => {let metadata = null;@@ -1974,7 +1934,7 @@ async function commitPageCapture(batchValue) {});const blob = resolved.blob;const contentHash = await sha256Blob(blob);- const existing = entries.flatMap(entryMediaAssets).find((asset) => asset.contentHash === contentHash);+ const existing = [...mediaAssets, ...entries.flatMap(entryMediaAssets)].find((asset) => asset.contentHash === contentHash);if (existing && await getMediaBlob(existing.id)) {if (!mediaAssets.some((asset) => asset.id === existing.id)) mediaAssets.push({ ...existing,sourceUrl: media.url, sourceTitle: media.filename || media.sourceTitle || media.alt || candidate.title,@@ -2030,7 +1990,6 @@ async function commitPageCapture(batchValue) {results.push({ candidateId: candidate.id, status: "failed", title: candidate.title, warnings: [...warnings, "没有可保存的正文或媒体"] });continue;}- const classificationMediaAssets = candidate.sourceFacts.pageType === "post" && base.text ? [] : mediaAssets;const entry = normalizeEntryMedia({...base,schemaVersion: SCHEMA_VERSION,@@ -2042,7 +2001,7 @@ async function commitPageCapture(batchValue) {? mediaAssets.find((asset) => asset.kind === "video"): mediaAssets.find((asset) => asset.kind === "image" && asset.usage !== "poster"))?.id|| mediaAssets.find((asset) => asset.usage !== "poster")?.id || "",- classification: classifyContent({ ...base, sourceFacts: candidate.sourceFacts, mediaAssets: classificationMediaAssets }, state.classificationRules, state.taxonomy),+ classification: classifyContent({ ...base, sourceFacts: candidate.sourceFacts, mediaAssets }, state.classificationRules, state.taxonomy),customLabels: [], metadataLabels: [], facetAssignments: [], analysisCandidates: [], analysisBreakdown: [],rejectedCandidateKeys: [], negativeTerms: [], legacyFacetCandidates: [], analysisPending: false});@@ -2052,7 +2011,16 @@ async function commitPageCapture(batchValue) {if (!results.some((item) => ["saved", "partial"].includes(item.status))) {return { ok: true, message: "所选内容均已存在或无法保存", results };}- await commitLocalChanges({ [STORAGE_KEYS.entries]: entries });+ const affectedIds = results.filter(item => ["saved", "partial"].includes(item.status)).map(item => item.entryId);+ entries = entries.map(entry => !affectedIds.includes(entry.id) ? entry : {+ ...entry,+ customLabels: uniqueNames([...(entry.customLabels || []), ...captureMetadata.customLabels]),+ classification: captureMetadata.contentTypeExplicit && isValidContentPath(state.taxonomy, [captureMetadata.contentTypeId])+ ? { pathIds: [captureMetadata.contentTypeId], status: "confirmed", source: "manual", reason: "保存前人工确认" }+ : entry.classification+ });+ const organizerState = organizerAfterCapturePlacement(state.organizerState, entries, affectedIds, captureMetadata);+ await commitLocalChanges({ [STORAGE_KEYS.entries]: entries, [STORAGE_KEYS.organizerState]: organizerState });metadataCommitted = true;const postCommitWarnings = [];try { await notifySaved(entries.length); }@@ -2069,6 +2037,8 @@ async function commitPageCapture(batchValue) {ok: true,message: `已保存 ${savedCount} 项${duplicateCount ? `,跳过 ${duplicateCount} 项重复内容` : ""}${postCommitWarnings.length ? `;${postCommitWarnings.join(";")}` : ""}`,results,+ collectionId: captureMetadata.collectionId || (captureMetadata.newCollectionName+ ? organizerState.collections.find(collection => !state.organizerState.collections.some(prior => prior.id === collection.id))?.id || "" : ""),warnings: postCommitWarnings};} catch (error) {diff --git a/capture-additions.js b/capture-additions.jsnew file mode 100644index 0000000..1872cb8--- /dev/null+++ b/capture-additions.js@@ -0,0 +1,73 @@+import { normalizePageCaptureCandidate, pageCaptureMediaIdentity } from "./page-capture.js";++// Add only new material. Existing block IDs and selection decisions remain authoritative.+export function appendCaptureCandidate(candidate, addition, selection) {+ const textBlocks = [...candidate.textBlocks];+ const media = [...candidate.media];+ const blocks = [...(candidate.articleDocument?.blocks || [])];+ const textIds = new Set(selection.selectedTextBlockIds || (selection.includeText ? textBlocks.map(b => b.id) : []));+ const mediaIds = new Set(selection.selectedMediaIds);+ const knownTexts = new Set(textBlocks.map(b => b.text.trim()));+ const remapped = new Map();+ for (const item of addition.textBlocks || []) {+ if (knownTexts.has(item.text.trim())) continue;+ knownTexts.add(item.text.trim());+ const block = { ...item, id: `added:${addition.id}:${item.id}`, sourceOrder: textBlocks.length };+ textBlocks.push(block);+ textIds.add(block.id);+ remapped.set(item.id, block.id);+ }+ for (const item of addition.media || []) {+ const existing = media.find(m => m.id === item.id || item.localAssetId && m.localAssetId === item.localAssetId+ || item.contentHash && m.contentHash === item.contentHash+ || item.url && m.url && pageCaptureMediaIdentity(item.url) === pageCaptureMediaIdentity(m.url));+ if (existing) { remapped.set(item.id, existing.id); continue; }+ const added = { ...item, id: `added:${addition.id}:${item.id}`, placement: "inline" };+ media.push(added);+ mediaIds.add(added.id);+ remapped.set(item.id, added.id);+ }+ const newTextBlocks = textBlocks.slice(candidate.textBlocks.length);+ for (const item of addition.articleDocument?.blocks || []) {+ if (item.assetId) {+ const assetId = remapped.get(item.assetId);+ if (assetId && !blocks.some(b => b.assetId === assetId)) blocks.push({ ...item, id: `added:${addition.id}:${item.id}`, assetId });+ } else if (item.text && newTextBlocks.some(b => comparableText(b.text).includes(comparableText(item.text)))) {+ blocks.push({ ...item, id: remapped.get(item.id) || `added:${addition.id}:${item.id}` });+ }+ }+ for (const item of textBlocks) {+ const articleText = comparableText(blocks.map(b => b.text || "").join("\n"));+ if (!articleText.includes(comparableText(item.text))) blocks.push({ ...item, kind: "paragraph" });+ }+ const merged = normalizePageCaptureCandidate({ ...candidate, textBlocks: textBlocks.map(b => ({ ...b, kind: "section" })), contentText: textBlocks.map(b => b.text).join("\n\n"),+ media, articleDocument: { version: 1, blocks: blocks.map((b, sourceOrder) => ({ ...b, sourceOrder })) } });+ return { candidate: merged, selection: { ...selection, mediaDecision: mediaIds.size ? "confirmed" : selection.mediaDecision, selectedTextBlockIds: [...textIds], selectedMediaIds: [...mediaIds] } };+}++export function draftCaptureAddition(draft, consumed = new Set()) {+ const fragments = draft.fragments.filter(f => !consumed.has(`text:${f.id}`));+ const visuals = draft.visuals.filter(v => !consumed.has(`image:${v.id}`));+ const textBlocks = fragments.map(f => ({ id: f.id, text: f.text, kind: "paragraph", relevance: "explicit-creative", html: "" }));+ return { id: draft.id, canonicalUrl: "", title: draft.title, textBlocks,+ media: visuals.map(v => ({ id: v.id, localAssetId: v.id, kind: "image", placement: "inline", url: "",+ contentHash: v.contentHash, mimeType: v.mimeType, width: v.width, height: v.height, sourceTitle: v.sourceTitle, originalWorkUrl: v.originalWorkUrl || v.sourceUrl })),+ articleDocument: { version: 1, blocks: [...textBlocks, ...visuals.map(v => ({ id: `image:${v.id}`, kind: "image", assetId: v.id }))] },+ consumed: [...fragments.map(f => `text:${f.id}`), ...visuals.map(v => `image:${v.id}`)] };+}++// Remove only draft material represented in the successful save. Excluded or undone items stay pending.+export function savedDraftCaptureItems(draft, candidates, consumed) {+ const blocks = candidates.flatMap(c => c.textBlocks);+ const media = candidates.flatMap(c => c.media);+ return [+ ...draft.fragments.filter(f => consumed.has(`text:${f.id}`) && blocks.some(b =>+ b.id === `added:${draft.id}:${f.id}` || b.text.trim() === f.text.trim())).map(f => ({ kind: "text", id: f.id })),+ ...draft.visuals.filter(v => consumed.has(`image:${v.id}`) && media.some(m =>+ m.localAssetId === v.id || v.contentHash && m.contentHash === v.contentHash)).map(v => ({ kind: "image", id: v.id }))+ ];+}++function comparableText(value) {+ return String(value || "").replace(/\s+/gu, " ").trim();+}diff --git a/case-presentation.js b/case-presentation.jsindex 94fe75b..4bcdfd6 100644--- a/case-presentation.js+++ b/case-presentation.js@@ -1,8 +1,20 @@import { assetFormatForExtension, assetFormatForFile } from "./asset-formats.js";+import { CONTENT_ROLES, contentRoleForEntry } from "./taxonomy.js";++function usesCreativeCase(entry) {+ return [CONTENT_ROLES.promptImage, CONTENT_ROLES.promptVideo, CONTENT_ROLES.imageCase, CONTENT_ROLES.videoCase]+ .includes(contentRoleForEntry(entry));+}export function usesArticleReader(entry = {}) {- return !["video", "artwork", "post"].includes(entry.sourceFacts?.pageType)- && Boolean(entry.articleDocument?.blocks?.length);+ if (usesCreativeCase(entry) || !entry.articleDocument?.blocks?.length) return false;+ const role = contentRoleForEntry(entry);+ return [CONTENT_ROLES.tutorial, CONTENT_ROLES.reference].includes(role)+ || !["video", "artwork"].includes(entry.sourceFacts?.pageType);+}++export function usesPostReader(entry = {}) {+ return entry.sourceFacts?.pageType === "post" && !usesCreativeCase(entry) && !usesArticleReader(entry);}export function mediaFormatLabel(asset = {}) {diff --git a/collector-page-capture-view.js b/collector-page-capture-view.jsnew file mode 100644index 0000000..31c1a61--- /dev/null+++ b/collector-page-capture-view.js@@ -0,0 +1,144 @@+import { t } from "./i18n.js";+import { createUiIcon } from "./ui-icons.js";++export function captureIconButton(icon, label, onClick, className = "") {+ const button = document.createElement("button");+ button.type = "button";+ button.className = `button-secondary compact capture-icon-button ${className}`;+ button.title = t(label);+ button.setAttribute("aria-label", t(label));+ button.append(createUiIcon(icon));+ button.addEventListener("click", onClick);+ return button;+}++export function createPageCaptureCard(candidate, {+ selected, listMode, busy, hidden, meta, onSelect, onLocate, onPreviewMedia, createArticlePreview, previewOpen, onIncludeSupplement, selectedMediaIds = [], onIncludeMediaGroup, onRemoveMedia, loadLocalVisual+}) {+ const card = document.createElement("article");+ card.className = `page-capture-item${selected ? " confirmed" : ""}`;+ card.hidden = hidden;+ if (candidate.batchStructureStatus === "review") card.classList.add("structure-review");+ const choose = document.createElement("button");+ choose.type = "button";+ choose.className = "page-capture-confirm";+ choose.setAttribute("aria-pressed", String(selected));+ choose.disabled = busy;+ const indicator = document.createElement("span");+ indicator.className = `page-capture-selection${listMode ? " multiple" : ""}`;+ indicator.setAttribute("aria-hidden", "true");+ const copy = document.createElement("span");+ const title = document.createElement("strong");+ title.textContent = candidate.title;+ const info = document.createElement("small");+ info.textContent = meta;+ copy.append(title, info);+ choose.append(indicator, copy);+ choose.addEventListener("click", onSelect);+ card.append(choose);+ const excerpt = document.createElement("p");+ excerpt.className = "page-capture-excerpt";+ excerpt.textContent = candidate.contentText || candidate.textBlocks.map(block => block.text).join("\n");+ card.append(excerpt);+ if (candidate.extraction?.textTruncated) {+ const notice = document.createElement("small");+ notice.textContent = t("正文尚未展开,当前只会保存已显示内容");+ card.append(notice);+ }+ const strip = document.createElement("div");+ strip.className = "page-capture-thumbnails";+ strip.classList.toggle("photo-group", candidate.pageType === "post" && candidate.media.filter(m => m.kind === "image" && m.originalWorkUrl).length > 1);+ candidate.media.forEach((media, index) => {+ if (!["image", "video"].includes(media.kind) || media.placement !== "inline" || (selected || media.quotedPostUrl) && !selectedMediaIds.includes(media.id)) return;+ const button = document.createElement("button");+ button.type = "button";+ button.title = media.alt || t(media.kind === "video" ? "视频" : "图片");+ button.setAttribute("aria-label", button.title);+ const url = media.kind === "video" ? media.posterUrl : media.previewDataUrl || media.dataUrl || media.url;+ if (url || media.localAssetId) {+ const image = document.createElement("img");+ if (media.localAssetId) loadLocalVisual(image, media.localAssetId);+ else image.src = url;+ image.alt = "";+ image.referrerPolicy = "no-referrer";+ image.addEventListener("error", () => button.replaceChildren(createUiIcon(media.kind === "video" ? "video" : "image")), { once: true });+ button.append(image);+ } else button.append(createUiIcon(media.kind === "video" ? "video" : "image"));+ button.addEventListener("click", () => onPreviewMedia(index));+ const thumbnail = document.createElement("span");+ thumbnail.className = "page-capture-thumbnail";+ thumbnail.append(button);+ if (selected) {+ const remove = captureIconButton("x", "移除", () => onRemoveMedia(media), "page-capture-thumbnail-remove");+ remove.disabled = busy;+ thumbnail.append(remove);+ }+ strip.append(thumbnail);+ });+ if (strip.childElementCount) card.append(strip);+ if (selected) for (const groupUrl of new Set(candidate.media.map(m => m.quotedPostUrl).filter(Boolean))) {+ const group = candidate.media.filter(m => m.quotedPostUrl === groupUrl);+ const row = document.createElement("div");+ row.className = "page-capture-media-group";+ const label = document.createElement("span");+ label.textContent = t("引用帖 · {count} 张图", { count: group.length });+ const add = document.createElement("button");+ add.type = "button";+ const included = group.every(m => selectedMediaIds.includes(m.id));+ add.textContent = t(included ? "已加入" : "加入这组");+ add.disabled = busy || included;+ add.addEventListener("click", () => onIncludeMediaGroup(group));+ row.append(label, add);+ card.append(row);+ }+ const actions = document.createElement("div");+ actions.className = "page-capture-card-actions";+ if (!listMode) {+ const locate = captureIconButton("search", "在网页中定位", onLocate, "page-capture-inspect");+ locate.disabled = busy || !candidate.region?.marker;+ actions.append(locate);+ }+ const details = document.createElement("details");+ details.className = "page-capture-preview-details";+ details.open = previewOpen;+ const summary = document.createElement("summary");+ summary.textContent = t("预览完整内容");+ details.append(summary, createArticlePreview());+ if (candidate.possibleOmissions?.length) {+ const omissions = document.createElement("details");+ omissions.className = "page-capture-omissions";+ const heading = document.createElement("summary");+ heading.textContent = t("可能遗漏({count})", { count: candidate.possibleOmissions.length });+ omissions.append(heading);+ for (const item of candidate.possibleOmissions) {+ const p = document.createElement("p");+ p.textContent = item.text;+ omissions.append(p);+ }+ details.append(omissions);+ }+ if (selected && candidate.supplements?.length) {+ const supplements = document.createElement("details");+ supplements.className = "page-capture-supplements";+ const heading = document.createElement("summary");+ heading.textContent = t("作者补充({count})", { count: candidate.supplements.length });+ supplements.append(heading);+ for (const item of candidate.supplements) {+ const section = document.createElement("section");+ const text = document.createElement("p");+ text.textContent = item.text;+ const add = document.createElement("button");+ add.type = "button";+ add.textContent = t(item.partial ? "补入已显示内容" : "补入当前案例");+ add.disabled = busy;+ add.addEventListener("click", () => onIncludeSupplement(item));+ section.append(text, add);+ supplements.append(section);+ }+ card.append(supplements);+ }+ actions.append(details);+ card.append(actions);+ card.dataset.candidateId = candidate.id;+ return card;+}diff --git a/collector.css b/collector.cssindex 9199517..a3705ac 100644--- a/collector.css+++ b/collector.css@@ -130,37 +130,44 @@ main {border: 0;background: transparent;}-.normal-start .capture-actions { grid-template-columns: minmax(0, 1fr); }-.normal-start .capture-actions > button {- min-height: 58px;- justify-content: flex-start;- padding: 12px 16px;- text-align: left;-}-.normal-start .capture-actions > button .ui-icon { width: 20px; height: 20px; }--.page-capture { display: grid; gap: 12px; border: 1px solid var(--line); border-radius: var(--ui-container-radius); padding: 14px; background: var(--card); }-.page-capture > header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }+.normal-start .capture-actions { grid-template-columns: repeat(4, minmax(0, 1fr)); }+.normal-start .capture-actions > button { min-height: 40px; padding: 8px; font-size: 11px; }+.normal-start .capture-actions > #start-page-capture { grid-column: 1 / -1; min-height: 46px; font-size: 13px; }+.normal-start .other-capture-methods { grid-column: auto; }+.normal-start .other-capture-methods button { width: 100%; min-height: 40px; padding: 8px; font-size: 11px; }+.normal-start .capture-actions button .ui-icon { width: 17px; height: 17px; }+.capture-icon-button { display: inline-grid; place-items: center; width: 34px; min-width: 34px; min-height: 34px; padding: 7px; }+.capture-icon-button .ui-icon { width: 17px; height: 17px; }+body.page-capture-active { height: 100dvh; overflow: hidden; }+.page-capture-active main { height: 100%; min-height: 0; grid-template-rows: auto auto minmax(0, 1fr); gap: 10px; padding-bottom: 0; }+.page-capture { display: block; min-height: 0; overflow-y: auto; padding: 0 2px; background: var(--paper); }+.page-capture > * { margin-bottom: 12px; }+.page-capture > header { display: flex; align-items: center; gap: 8px; }+#page-capture-mode { width: auto; min-height: 32px; padding: 4px 7px; font-size: 11px; }+#page-capture-scan { margin-left: auto; }.page-capture h2 { margin: 2px 0 0; font-size: 16px; }.page-capture small, .page-capture > p { color: var(--muted); font-size: 11px; }.page-capture > p { margin: 0; line-height: 1.5; }-.page-capture-tools { border: 1px solid var(--line); border-radius: 6px; background: var(--paper); }-.page-capture-tools > summary { padding: 9px 10px; color: var(--muted); cursor: pointer; font-size: 11px; font-weight: 800; }+.page-capture-tools { background: var(--paper); }+.page-capture-tools > summary { padding: 7px 0; color: var(--muted); cursor: pointer; font-size: 11px; font-weight: 800; }.page-capture-bulk-actions { display: flex; flex-wrap: wrap; gap: 6px; }-.page-capture-tools .page-capture-bulk-actions { padding: 0 9px 9px; }+.page-capture-tools .page-capture-bulk-actions { padding: 0 0 9px; }.page-capture-bulk-actions button { width: auto; }.page-capture-list-setup, .page-capture-list-result { border: 1px solid var(--line); border-radius: 6px; padding: 9px; background: var(--paper); }.page-capture-list-setup summary { cursor: pointer; font-size: 12px; font-weight: 800; }.page-capture-list-setup > p, .page-capture-list-result > p { margin: 7px 0; color: var(--muted); font-size: 11px; line-height: 1.5; }-.page-capture-list-setup label, .page-capture-list-result label { display: grid; gap: 5px; margin: 8px 0; color: var(--muted); font-size: 11px; }+.page-capture-list-setup label, .page-capture-list-result label { display: flex; align-items: center; gap: 7px; margin: 8px 0; color: var(--muted); font-size: 11px; }+.page-capture-list-controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }+.page-capture-list-setup #page-capture-target-count { width: 72px; }+.page-capture-list-result label > span { flex: none; }.page-capture-list-setup input, .page-capture-list-result input, .page-capture-list-result select { width: 100%; }.page-capture-list { display: grid; gap: 8px; }.page-capture-item { display: grid; gap: 9px; border: 1px solid var(--line); border-radius: 6px; padding: 10px; background: var(--paper); }-.page-capture-item.confirmed { border-color: var(--selection-edge); box-shadow: inset 3px 0 var(--selection-indicator); }+.page-capture-item.confirmed { border-color: var(--selection-edge); }.page-capture-item.structure-review { border-style: dashed; border-color: var(--warning, #b98a2e); }.page-capture-item > header { display: flex; align-items: start; justify-content: space-between; gap: 8px; }.page-capture-item > header > div { display: grid; min-width: 0; gap: 3px; }-.page-capture-item strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }+.page-capture-item strong { font-size: 13px; overflow-wrap: anywhere; white-space: normal; }.page-capture-component { display: grid; min-width: 0; align-items: start; gap: 8px; border: 1px solid var(--line); border-radius: 5px; padding: 8px; background: var(--card); cursor: pointer; }.page-capture-component:hover { border-color: var(--line-strong); }.page-capture-text-section { display: grid; gap: 6px; }@@ -179,10 +186,29 @@ main {.page-capture-media-preview img { display: block; width: 100%; height: 100%; object-fit: contain; }.page-capture-media > span:last-child { display: grid; min-width: 0; gap: 3px; }.page-capture-media small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }-.page-capture-confirm { width: 100%; }-.page-capture-media-review { display: grid; gap: 9px; border: 1px solid var(--selection-edge); border-radius: 6px; padding: 10px; background: var(--paper); }+.page-capture-confirm { display: flex; align-items: start; justify-content: flex-start; white-space: normal; gap: 9px; width: 100%; border: 0; padding: 2px 0; background: transparent; text-align: left; color: var(--ink); }+.page-capture .page-capture-confirm:hover:not(:disabled) { background: var(--ui-hover); }+.page-capture-confirm[aria-pressed="true"] { background: transparent; color: var(--ink); box-shadow: none; }+.page-capture-confirm > span:last-child { display: grid; gap: 3px; min-width: 0; }+.page-capture-selection { width: 17px; height: 17px; margin-top: 3px; flex: none; border: 1px solid var(--muted); border-radius: 50%; }+.page-capture-selection.multiple { border-radius: 3px; }+.confirmed .page-capture-selection { border: 5px solid var(--selection-indicator); }+.page-capture-excerpt { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; margin: 0 0 0 26px; color: var(--muted); font-size: 12px; line-height: 1.6; }+.page-capture-thumbnails { display: flex; gap: 6px; overflow-x: auto; margin-left: 26px; padding: 2px 0; }+.page-capture-thumbnails button { flex: 0 0 78px; width: 78px; height: 58px; padding: 0; overflow: hidden; background: var(--raised); }+.page-capture-thumbnails img { display: block; width: 100%; height: 100%; object-fit: contain; }+.page-capture-card-actions { display: flex; align-items: start; flex-wrap: wrap; gap: 6px; margin-left: 26px; }+.page-capture-card-actions > details { flex: 1; min-width: 0; }+.page-capture-card-actions > details[open] { flex-basis: 100%; }+.page-capture-edit-status { border: 1px solid var(--selection-edge); border-radius: 6px; padding: 9px; }+.page-capture-edit-status p { margin: 0 0 7px; font-size: 12px; }+.page-capture-active .save-metadata { padding: 0; border: 0; background: transparent; }++.page-capture-media-review { display: block; gap: 9px; border: 1px solid var(--selection-edge); border-radius: 6px; padding: 10px; background: var(--paper); }.page-capture-media-review[hidden] { display: none; }-.page-capture-media-review > header { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }+.page-capture-media-review > summary { cursor: pointer; font-size: 12px; }+.page-capture-media-review > summary small { margin-left: 8px; }+.page-capture-media-review[open] > .page-capture-media-review-list { margin-top: 9px; }.page-capture-media-review-list { display: grid; gap: 6px; }.page-capture-media-review-item { display: grid; grid-template-columns: 72px minmax(0, 1fr) auto; align-items: center; gap: 8px; border: 1px solid var(--line); border-radius: 5px; padding: 6px; }.page-capture-media-review-item.media-excluded { opacity: .55; }@@ -195,7 +221,10 @@ main {.page-capture-media-review-group > div { display: grid; gap: 6px; margin-top: 6px; }.page-capture-article-media.media-excluded, .page-capture-article-resource.media-excluded { opacity: .4; text-decoration: line-through; }.page-capture-article-media.media-pending, .page-capture-article-resource.media-pending { outline: 1px dashed var(--selection-edge); }-.page-capture-actions { display: grid; grid-template-columns: auto auto minmax(0, 1.4fr); gap: 8px; }+.page-capture-actions { position: sticky; bottom: 0; z-index: 2; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; padding: 10px 0 14px; background: var(--paper); border-top: 1px solid var(--line); }+#page-capture-save-summary { flex-basis: 100%; }+#page-capture-save { flex: 1; }+#page-capture-save-text-only { font-size: 11px; padding-inline: 8px; }.page-capture-media-viewer { width: min(92vw, 720px); max-width: 720px; border: 1px solid var(--line); border-radius: 10px; padding: 12px; color: var(--ink); background: var(--card); }.page-capture-media-viewer::backdrop { background: rgb(0 0 0 / 72%); }.page-capture-media-viewer > header, .page-capture-media-viewer > footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; }@@ -217,28 +246,8 @@ main {.page-capture-article-media .page-capture-media-preview { width: 96px; height: 72px; }.page-capture-article-resource { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 9px; border: 1px solid var(--line); border-radius: 5px; padding: 9px; color: inherit; background: var(--paper); text-align: left; }.page-capture-article-resource > span:first-child { display: grid; width: 38px; height: 38px; place-items: center; border-radius: 5px; color: var(--accent-ink); background: var(--accent-soft); font-size: 10px; font-weight: 850; }-.capture-actions .other-capture-methods > button {- width: 100%;- height: 30px;- min-height: 30px;- color: var(--muted);- background: transparent;-}+.other-capture-methods > button .ui-icon { width: 15px; height: 15px; }-.compact-capture-methods { border: 1px solid var(--line); background: var(--paper); }-.compact-capture-methods summary {- padding: 9px 11px;- color: var(--muted);- cursor: pointer;- font-size: 11px;- font-weight: 750;-}-.compact-capture-methods > div {- display: grid;- grid-template-columns: 1fr;- gap: 8px;- padding: 0 8px 8px;-}.other-capture-methods.fallback-highlight {border-color: var(--selection-edge);background: var(--selection);@@ -359,7 +368,7 @@ main {padding: 10px 11px;background: var(--card);}-.save-metadata > label {+.save-metadata label {display: grid;grid-template-columns: auto minmax(0, 1fr);align-items: center;@@ -391,7 +400,6 @@ main {.add-more-actions { display: grid; grid-template-columns: 1fr; gap: 8px; }.add-more-actions button { min-height: 36px; font-size: 12px; }-.compact-capture-methods > div { grid-template-columns: 1fr; }.organize-toggle {justify-self: center;min-height: 30px;@@ -530,7 +538,6 @@ main {@media (max-width: 330px) {.add-more-actions { grid-template-columns: 1fr; }- .compact-capture-methods > div { grid-template-columns: 1fr; }}/* Compact capture surface using the same director workbench language. */@@ -550,7 +557,6 @@ main { gap: 12px; padding: 12px 12px 82px; }.capture-actions { gap: 6px; }.capture-actions button { min-height: 52px; border-radius: var(--ui-control-radius); }.capture-actions button:not(.primary) { background: var(--soft); }-.compact-capture-methods > summary { padding: 8px 10px; }.quick-item { border-radius: 7px; box-shadow: none; }.quick-item > strong { border-radius: 5px; color: var(--accent-ink); }.quick-image-item img, .visual-card img { border-radius: 5px; }@@ -564,3 +570,57 @@ main { gap: 12px; padding: 12px 12px 82px; }.other-capture-methods,.visual-card { transition: color 140ms ease, background-color 140ms ease, border-color 140ms ease, box-shadow 140ms ease, transform 120ms ease; }}++/* Same-level capture actions remain readable in a narrow side panel. */+.collector-header { display: flex; align-items: center; gap: 8px; }+.collector-header .brand { flex: 1; min-width: 0; }+.collector-header .product-brand-tagline { display: none; }+.collector-header .library-entry { width: 36px; min-width: 36px; min-height: 36px; padding: 8px; margin: 0; }+.collector-header .library-entry strong, .collector-header .library-entry > svg { display: none; }+.normal-start .capture-actions { grid-template-columns: repeat(4, minmax(0, 1fr)); }+.normal-start .other-capture-methods { display: contents; }+.normal-start .capture-actions > button, .normal-start .capture-actions .other-capture-methods > button {+ display: flex; align-items: center; justify-content: center; gap: 4px; height: 40px; min-height: 40px;+ padding: 6px 4px; font-size: 12px; color: var(--ink); background: var(--card); white-space: nowrap;+}+.normal-start .capture-actions #start-page-capture { min-height: 46px; height: auto; background: var(--accent-emphasis); color: var(--accent-emphasis-contrast); }+.normal-start .capture-actions .ui-icon { width: 16px; height: 16px; flex-shrink: 0; }+.add-more-actions { grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 5px; align-items: start; }+.add-more-actions > button { padding: 6px 3px; white-space: nowrap; min-width: 0; }+.custom-label-editor { grid-template-columns: auto minmax(0, 1fr); align-items: start; gap: 10px; }+.custom-label-editor > span { padding-top: 8px; white-space: nowrap; }+.custom-label-editor .tag-editor { min-width: 0; display: flex; flex-direction: column; }+.custom-label-editor .tag-editor-chips { order: 1; }+.custom-label-editor .tag-editor-row { display: flex; gap: 6px; }+.custom-label-editor .tag-editor-row input { min-width: 0; flex: 1; }+.custom-label-editor .tag-editor-row button { white-space: nowrap; flex-shrink: 0; padding: 6px 8px; }+.save-metadata label > span { white-space: nowrap; }+.collector-footer button, .page-capture-actions button { white-space: nowrap; }+.preview-heading small { display: none; }+.quick-copy small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }++.page-capture-supplements { min-width: 0; margin: 8px 0; }+.page-capture-supplements summary { cursor: pointer; color: var(--muted); font-size: 12px; }+.page-capture-supplements p { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.6; }+.page-capture-supplements button { white-space: nowrap; }++.preview-heading .organize-toggle { width: 36px; min-height: 36px; padding: 8px; border: 1px solid var(--line); }+.quick-image-strip:has(.quick-image-item:only-child) .quick-image-item { flex: 1; width: 100%; }+.quick-image-strip:has(.quick-image-item:only-child) img { height: auto; max-height: 220px; object-fit: contain; }++.page-capture > .add-more-actions { margin: 10px 0; }+.page-capture-media-group { display: flex; gap: 8px; align-items: center; margin: 8px 0; font-size: 12px; }+.page-capture-media-group > span { flex: 1; min-width: 0; }+.page-capture-media-group > button { white-space: nowrap; }++.page-capture-thumbnail { position: relative; flex: 0 0 78px; }+.page-capture-thumbnails .page-capture-thumbnail-remove { position: absolute; top: 2px; right: 2px; width: 22px; height: 22px; min-height: 22px; border-radius: 4px; padding: 3px; background: var(--paper); }+.page-capture-thumbnail-remove .ui-icon { width: 14px; height: 14px; }++.page-capture-thumbnails.photo-group { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-left: 0; overflow: visible; }+.photo-group .page-capture-thumbnail { min-width: 0; }+.photo-group .page-capture-thumbnail > button:first-child { width: 100%; height: auto; aspect-ratio: 3 / 4; }+.photo-group .page-capture-thumbnail img { object-fit: cover; }++.add-more-actions > button { display: grid; justify-items: center; align-content: center; gap: 3px; min-height: 48px; }+.add-more-actions > button .ui-icon { width: 16px; height: 16px; }diff --git a/collector.html b/collector.htmlindex 9a8c68d..c9287ac 100644--- a/collector.html+++ b/collector.html@@ -12,12 +12,13 @@<main><header class="collector-header"><div class="brand product-brand"><img class="product-brand-mark" src="assets/icons/icon-source.svg" alt="" /><div class="product-brand-copy"><p class="product-brand-name">PromptDirector</p><h1 class="product-brand-tagline" data-i18n="视觉创作灵感库">视觉创作灵感库</h1></div></div>- </header>-- <button id="open-library" class="library-entry" type="button">+ <button id="open-library" aria-label="打开灵感库" title="打开灵感库" data-i18n-aria-label="打开灵感库" data-i18n-title="打开灵感库" class="library-entry" type="button"><span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><strong data-i18n="打开灵感库">打开灵感库</strong></span><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-chevron-right"></use></svg></button>+ </header>++<section id="target-banner" class="target-banner" hidden><div><small data-i18n="目标案例">目标案例</small><strong id="target-label"></strong></div>@@ -35,7 +36,7 @@<div class="app-dialog-body"><label class="app-dialog-check"><input id="capture-permission-clipboard" type="checkbox" checked />- <span><strong data-i18n="同时开启剪贴板提取">同时开启剪贴板提取</strong><br /><small data-i18n="可取消;仅在你主动点击“提取文字/图片”且网页没有高亮内容时读取。">可取消;仅在你主动点击“提取文字/图片”且网页没有高亮内容时读取。</small></span>+ <span><strong data-i18n="同时开启剪贴板提取">同时开启剪贴板提取</strong><br /><small data-i18n="仅在你点击“剪贴板”时读取。">仅在你点击“剪贴板”时读取。</small></span></label><p id="capture-permission-status" class="app-dialog-status" role="status" aria-live="polite"></p></div>@@ -55,7 +56,7 @@</div></header><div class="app-dialog-body">- <p data-i18n="启用后仍只会在你主动点击“提取文字/图片”且网页没有可用高亮时读取;打开侧栏、浏览或点击网页不会触发读取。">启用后仍只会在你主动点击“提取文字/图片”且网页没有可用高亮时读取;打开侧栏、浏览或点击网页不会触发读取。</p>+ <p data-i18n="仅在你点击“剪贴板”时读取;打开侧栏、浏览或点击网页不会触发读取。">仅在你点击“剪贴板”时读取;打开侧栏、浏览或点击网页不会触发读取。</p><p id="clipboard-permission-status" class="app-dialog-status" role="status" aria-live="polite"></p></div><footer>@@ -79,11 +80,13 @@</div><div id="normal-start" class="normal-start"><div class="capture-actions" aria-label="从当前网页采集" data-i18n-aria-label="从当前网页采集">- <button id="start-smart-visuals" class="primary smart-visuals" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-image"></use></svg><strong data-i18n="智能选图">智能选图</strong></button>- <button id="start-selection" class="direct-selection" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-file-text"></use></svg><strong data-i18n="提取文字/图片">提取文字/图片</strong></button>- <button id="start-page-capture" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><strong data-i18n="网页采集">网页采集</strong></button>+ <button id="start-page-capture" class="primary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-library"></use></svg><strong data-i18n="网页采集">网页采集</strong></button>+ <button id="start-smart-visuals" class="smart-visuals" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-image"></use></svg><strong data-i18n="选图">选图</strong></button>+ <button id="start-selection" class="direct-selection" type="button" title="提取选中文字" aria-label="提取选中文字" data-i18n-title="提取选中文字" 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-file-text"></use></svg><strong data-i18n="选区">选区</strong></button>++ <button id="start-clipboard" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-copy"></use></svg><strong data-i18n="剪贴板">剪贴板</strong></button><div id="other-capture-methods" class="other-capture-methods">- <button id="start-screenshot" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-maximize-2"></use></svg><strong data-i18n="框选截图">框选截图</strong></button>+ <button id="start-screenshot" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><use href="assets/ui-icons.svg#icon-maximize-2"></use></svg><strong data-i18n="截图">截图</strong></button></div></div></div>@@ -91,26 +94,16 @@<section id="page-capture" class="page-capture" hidden aria-live="polite"><header>- <div><small data-i18n="网页采集">网页采集</small><h2 id="page-capture-title" data-i18n="选择要保存的内容">选择要保存的内容</h2></div>- <button id="page-capture-scan" class="button-secondary compact" type="button" data-i18n="重新扫描">重新扫描</button>+ <h2 id="page-capture-title" data-i18n="网页采集">网页采集</h2>+ <select id="page-capture-mode" aria-label="采集方式" data-i18n-aria-label="采集方式"><option value="single" data-i18n="单个案例">单个案例</option><option value="list" data-i18n="列表批量">列表批量</option></select>+ <button id="page-capture-undo-region" class="button-secondary compact capture-icon-button" type="button" title="撤销" aria-label="撤销" data-i18n-title="撤销" data-i18n-aria-label="撤销"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-undo-2"></use></svg></button>+ <button id="page-capture-scan" class="button-secondary compact capture-icon-button" type="button" title="重新扫描" aria-label="重新扫描" data-i18n-title="重新扫描" data-i18n-aria-label="重新扫描"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-refresh-cw"></use></svg></button></header>- <p id="page-capture-help" data-i18n="确认一个主体后即可保存;需要时再展开预览或修正识别结果。">确认一个主体后即可保存;需要时再展开预览或修正识别结果。</p>- <details class="page-capture-tools">- <summary data-i18n="修正识别结果">修正识别结果</summary>- <div class="page-capture-bulk-actions" aria-label="主体区域确认" data-i18n-aria-label="主体区域确认">- <button id="page-capture-clear" class="button-secondary compact" type="button" data-i18n="取消确认">取消确认</button>- <button id="page-capture-add-region" class="button-secondary compact" type="button" data-i18n="添加遗漏">添加遗漏</button>- <button id="page-capture-exclude-region" class="button-secondary compact" type="button" data-i18n="排除错误">排除错误</button>- <button id="page-capture-undo-region" class="button-secondary compact" type="button" data-i18n="撤销">撤销</button>- <button id="page-capture-reset-region" class="button-secondary compact" type="button" data-i18n="恢复识别">恢复识别</button>- </div>- </details>- <details id="page-capture-list-setup" class="page-capture-list-setup">- <summary data-i18n="同一列表批量采集">同一列表批量采集</summary>- <p data-i18n="先确认上方一个代表案例,再输入目标数量。只滚动、加载当前列表或沿列表翻页,不进入详情页。">先确认上方一个代表案例,再输入目标数量。只滚动、加载当前列表或沿列表翻页,不进入详情页。</p>- <label><span data-i18n="目标案例数">目标案例数</span><input id="page-capture-target-count" type="number" min="1" inputmode="numeric" placeholder="请输入数量" data-i18n-placeholder="请输入数量" /></label>- <button id="page-capture-list-run" class="primary" type="button" data-i18n="按这个样本继续采集">按这个样本继续采集</button>- </details>+ <p id="page-capture-help"></p>+ <section id="page-capture-list-setup" class="page-capture-list-setup" hidden>+ <p data-i18n="选一个代表案例,再采集同类内容">选一个代表案例,再采集同类内容</p>+ <div class="page-capture-list-controls"><label><span data-i18n="目标案例数">目标案例数</span><input id="page-capture-target-count" type="number" min="1" inputmode="numeric" placeholder="数量" data-i18n-placeholder="数量" /></label><button id="page-capture-list-run" class="button-secondary" type="button" data-i18n="读取列表">读取列表</button></div>+ </section><section id="page-capture-list-result" class="page-capture-list-result" hidden><strong data-i18n="批量保存方式">批量保存方式</strong><p id="page-capture-list-summary"></p>@@ -118,12 +111,24 @@<label id="page-capture-combined-title-row" hidden><span data-i18n="合并案例标题">合并案例标题</span><input id="page-capture-combined-title" autocomplete="off" placeholder="默认使用列表页标题" data-i18n-placeholder="默认使用列表页标题" /></label></section><div id="page-capture-list" class="page-capture-list"></div>- <section id="page-capture-media-review" class="page-capture-media-review" hidden>- <header><strong data-i18n="保存的图片与视频">保存的图片与视频</strong><small id="page-capture-media-review-status" data-i18n="当前方案 0 项">当前方案 0 项</small></header>+ <details id="page-capture-tools" class="page-capture-tools" hidden>+ <summary data-i18n="调整内容">调整内容</summary>+ <div class="page-capture-bulk-actions">+ <button id="page-capture-add-region" class="button-secondary compact" type="button" data-i18n="补选">补选</button>+ <button id="page-capture-exclude-region" class="button-secondary compact" type="button" data-i18n="排除">排除</button>++ <button id="page-capture-reset-region" class="button-secondary compact" type="button" data-i18n="恢复识别">恢复识别</button>+ <button id="page-capture-clear" class="button-secondary compact" type="button" data-i18n="换一项">换一项</button>+ </div>+ </details>+ <div id="page-capture-edit-status" class="page-capture-edit-status" hidden><p id="page-capture-edit-help"></p><button id="page-capture-edit-cancel" class="button-secondary" type="button" data-i18n="取消调整">取消调整</button></div>+ <details id="page-capture-media-review" class="page-capture-media-review" hidden>+ <summary><strong data-i18n="检查媒体">检查媒体</strong><small id="page-capture-media-review-status"></small></summary><div id="page-capture-media-review-list" class="page-capture-media-review-list"></div>- </section>+ </details><div id="page-capture-actions" class="page-capture-actions">- <button id="page-capture-cancel" class="button-secondary" type="button" data-i18n="取消">取消</button>+ <small id="page-capture-save-summary"></small>+ <button id="page-capture-cancel" class="button-secondary" type="button" data-i18n="退出">退出</button><button id="page-capture-save-text-only" class="button-secondary" type="button" hidden data-i18n="只保存正文">只保存正文</button><button id="page-capture-save" class="primary" type="button" data-i18n="保存为一个案例">保存为一个案例</button></div>@@ -162,7 +167,7 @@<section id="preview-state" class="preview-state" hidden><header class="preview-heading">- <div><small data-i18n="待保存内容">待保存内容</small><h2 id="content-summary"></h2></div>+ <div><small data-i18n="待保存内容">待保存内容</small><h2 id="content-summary"></h2></div><button id="organize-toggle" class="organize-toggle" type="button" aria-expanded="false" title="编辑与整理" aria-label="编辑与整理" data-i18n-title="编辑与整理" data-i18n-aria-label="编辑与整理"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-pencil"></use></svg></button></header><div id="quick-preview" class="quick-preview"></div><section id="capture-metadata" class="save-metadata" aria-label="保存设置" data-i18n-aria-label="保存设置">@@ -174,27 +179,23 @@<span data-i18n="新项目名称">新项目名称</span><input id="capture-new-collection-name" autocomplete="off" placeholder="输入后会在保存案例时创建" data-i18n-placeholder="输入后会在保存案例时创建" /></label>- <label>- <span data-i18n="一级分类">一级分类</span>+ <label id="capture-extra-metadata">+ <span data-i18n="分类">分类</span><select id="content-type"></select></label><div class="custom-label-editor">- <span data-i18n="添加标签">添加标签</span>+ <span data-i18n="标签">标签</span><div id="custom-labels"></div></div></section><div id="capture-add-more-actions" class="add-more-actions">- <button id="add-smart-visuals" class="quiet" type="button" data-i18n="+ 智能选图">+ 智能选图</button>- <button id="add-selection" class="quiet" type="button" data-i18n="+ 提取文字/图片">+ 提取文字/图片</button>- <button id="add-page-capture" class="quiet" type="button" data-i18n="+ 网页采集">+ 网页采集</button>- <details id="add-other-capture-methods" class="other-capture-methods compact-capture-methods">- <summary data-i18n="智能选图无法识别?">智能选图无法识别?</summary>- <div>- <button id="add-screenshot" class="quiet" type="button" data-i18n="+ 框选截图">+ 框选截图</button>- </div>- </details>+ <button id="add-smart-visuals" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-image"></use></svg><span data-i18n="选图">选图</span></button>+ <button id="add-selection" class="button-secondary" type="button" title="提取选中文字" aria-label="提取选中文字" data-i18n-title="提取选中文字" data-i18n-aria-label="提取选中文字"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-file-text"></use></svg><span data-i18n="选区">选区</span></button>+ <button id="add-clipboard" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-clipboard"></use></svg><span data-i18n="剪贴板">剪贴板</span></button>+ <button id="add-screenshot" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-maximize-2"></use></svg><span data-i18n="截图">截图</span></button>+ <button id="add-page-capture" class="button-secondary" type="button"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-library"></use></svg><span data-i18n="网页">网页</span></button></div>- <button id="organize-toggle" class="organize-toggle" type="button" aria-expanded="false" data-i18n="编辑与整理">编辑与整理</button>+<div id="organizer" class="organizer" hidden><details class="title-editor">@@ -221,7 +222,7 @@<p id="feedback" class="ui-feedback-toast" role="status" aria-live="polite"></p><footer id="collector-footer" class="collector-footer" hidden>- <button id="discard-draft" class="quiet" type="button" data-i18n="清空">清空</button>+ <button id="discard-draft" class="quiet capture-icon-button" type="button" title="清空" aria-label="清空" data-i18n-title="清空" data-i18n-aria-label="清空"><svg class="ui-icon" viewBox="0 0 24 24" aria-hidden="true"><use href="assets/ui-icons.svg#icon-trash-2"></use></svg></button><button id="save-draft" class="primary" type="button" data-i18n="保存案例">保存案例</button></footer></main>diff --git a/collector.js b/collector.jsindex 0e3a8a9..941d6ec 100644--- a/collector.js+++ b/collector.js@@ -1,3 +1,5 @@+import { appendCaptureCandidate, draftCaptureAddition, savedDraftCaptureItems } from "./capture-additions.js";+import { createPageCaptureCard } from "./collector-page-capture-view.js";import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";import { addDraftFragment, addDraftVisual } from "./capture-draft.js";import { createTextCandidate } from "./capture-text-candidate.js";@@ -5,6 +7,8 @@ import {assignVisualPreviewSource,collectorViewState} from "./collector-view.js";+import { classifyContent } from "./classifier.js";+import { sha256Blob } from "./blob-digest.js";import { prepareLocalMedia } from "./local-media.js";import { runCaptureTransaction } from "./capture-workspace.js";import {@@ -39,13 +43,14 @@ import { createTagEditor } from "./tag-editor.js";await initializeUi();const elements = Object.fromEntries([- "add-selection", "add-screenshot", "add-smart-visuals", "collector-footer", "content-summary", "discard-draft", "draft-title",+ "start-clipboard", "add-clipboard", "add-selection", "add-screenshot", "add-smart-visuals", "collector-footer", "content-summary", "discard-draft", "draft-title","content-type", "custom-labels", "capture-metadata", "capture-collection", "capture-new-collection-row", "capture-new-collection-name", "capture-add-more-actions", "duplicate-panel", "duplicate-title", "exit-target", "feedback", "fragment-help", "fragment-list","fragment-section", "merge-duplicate", "open-library", "organizer", "organize-toggle", "preview-state","quick-preview", "result-prompt-title", "result-screenshot", "result-smart-visuals", "result-start", "save-draft", "save-other-inspiration","save-separate", "start-screenshot", "start-selection", "start-smart-visuals", "start-state", "normal-start",- "other-capture-methods", "add-other-capture-methods", "smart-selection", "smart-selection-count", "smart-selection-help", "smart-selection-warning", "smart-selection-cancel", "smart-selection-confirm",+ "other-capture-methods", "smart-selection", "smart-selection-count", "smart-selection-help", "smart-selection-warning", "smart-selection-cancel", "smart-selection-confirm","start-page-capture", "add-page-capture", "page-capture", "page-capture-title", "page-capture-help", "page-capture-list", "page-capture-scan", "page-capture-cancel", "page-capture-save", "page-capture-save-text-only",+ "page-capture-mode", "page-capture-tools", "page-capture-save-summary", "capture-extra-metadata", "page-capture-edit-status", "page-capture-edit-help", "page-capture-edit-cancel","page-capture-clear", "page-capture-media-viewer", "page-capture-media-stage", "page-capture-media-position", "page-capture-media-title", "page-capture-media-meta","page-capture-media-review", "page-capture-media-review-status", "page-capture-media-review-list","page-capture-add-region", "page-capture-exclude-region", "page-capture-undo-region", "page-capture-reset-region",@@ -63,6 +68,7 @@ let targetEntry = null;let contentTypes = [];let collections = [];let suggestedContentTypeId = "";+let captureClassificationContext = {};let partContentTypes = {};let activeCreativeResult = null;let activeCreativePrompt = null;@@ -74,6 +80,9 @@ let smartVisualSession = null;let smartVisualCommitCreative = false;let regionCaptureState = null;let pageCaptureBatch = null;+let pageCaptureAppendBase = null;+let pageCaptureDraftIds = new Set();+const draftVisualHashes = new Map();let pageCaptureSession = null;let pageCaptureMediaView = null;let pageCaptureEditHistory = [];@@ -84,6 +93,11 @@ const FEEDBACK_DURATION_MS = 4000;const ERROR_FEEDBACK_DURATION_MS = 8000;let feedbackTimer = 0;let pageCaptureRequestId = "";+let pageCaptureListRequested = false;+let pageCaptureEditing = null;+let pageCaptureCancelling = false;+let pageCapturePreviewRequest = 0;+const cancelledPageCaptureRequests = new Set();let pendingCaptureAction = null;let pendingClipboardButton = null;let creatingCollection = false;@@ -95,6 +109,7 @@ const CLIPBOARD_IMAGE_EXTENSIONS = Object.freeze({});const customLabelEditor = createTagEditor({+ placeholder: t("输入标签,回车添加"),onChange: async (values) => {if (!draft) return false;return Boolean(await updateDraft({ ...draft, customLabels: values, customLabelsExplicit: true }));@@ -122,14 +137,16 @@ chrome.tabs.onUpdated.addListener((_tabId, changeInfo, tab) => {if (tab.active && changeInfo.url) void refreshPageCapturePermissionState();});window.addEventListener("pagehide", () => void clearPageCaptureMarkers());-elements.startSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractClipboardOrSelection(elements.startSelection, context)));+elements.startSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractPageSelection(elements.startSelection)));+elements.startClipboard.addEventListener("click", () => extractClipboard(elements.startClipboard));+elements.addClipboard.addEventListener("click", () => extractClipboard(elements.addClipboard));elements.startScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.startScreenshot)));elements.startSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.startSmartVisuals)));elements.startPageCapture.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => startPageCapture("loaded", elements.startPageCapture)));elements.resultScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.resultScreenshot, true)));elements.resultSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.resultSmartVisuals, true)));elements.saveOtherInspiration.addEventListener("click", () => clearActiveCreativeResult());-elements.addSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractClipboardOrSelection(elements.addSelection, context)));+elements.addSelection.addEventListener("click", () => runAfterCapturePermissionOnboarding((context) => extractPageSelection(elements.addSelection)));elements.addScreenshot.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => captureFromActivePage("CAPTURE_ACTIVE_TAB_TO_DRAFT", elements.addScreenshot)));elements.addSmartVisuals.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => beginSmartVisualSelection(elements.addSmartVisuals)));elements.addPageCapture.addEventListener("click", () => runAfterCapturePermissionOnboarding(() => startPageCapture("loaded", elements.addPageCapture)));@@ -146,8 +163,17 @@ elements.clipboardPermissionDialog.addEventListener("cancel", (event) => {cancelClipboardPermissionEnable();});elements.pageCaptureScan.addEventListener("click", () => {- elements.pageCaptureListSetup.open = true;- elements.pageCaptureTargetCount.focus();+ pageCaptureListRequested = false;+ void startPageCapture("loaded", elements.pageCaptureScan);+});+elements.pageCaptureMode.addEventListener("change", () => {+ pageCaptureListRequested = elements.pageCaptureMode.value === "list";+ if (!pageCaptureListRequested && pageCaptureBatch?.captureMode === "list") void startPageCapture("loaded", elements.pageCaptureScan);+ else render();+});+elements.pageCaptureEditCancel.addEventListener("click", async () => {+ if (!pageCaptureEditing) return;+ await chrome.runtime.sendMessage({ type: "CLEAR_PAGE_CAPTURE_MARKERS", tabId: pageCaptureBatch?.tabId, removeRegionMarkers: false });});elements.pageCaptureListRun.addEventListener("click", () => startPageListCapture(elements.pageCaptureListRun));elements.pageCaptureSaveMode.addEventListener("change", () => {@@ -187,6 +213,10 @@ chrome.runtime.onMessage.addListener((message) => {showFeedback(regionCaptureMessage(message.phase), message.phase === "failed");render();} else if (message?.type === "PAGE_CAPTURE_CHANGED") {+ if (cancelledPageCaptureRequests.has(message.requestId)) {+ void chrome.runtime.sendMessage({ type: "CANCEL_PAGE_CAPTURE", sessionId: message.sessionId });+ return;+ }if (!pageCaptureRequestId || message.requestId !== pageCaptureRequestId) return;pageCaptureSession = { sessionId: message.sessionId, phase: message.phase };pageCaptureBatch = normalizePageCaptureBatch(pageCaptureBatch@@ -326,19 +356,29 @@ async function confirmCapturePermissionOnboarding(event) {async function refresh() {const response = await chrome.runtime.sendMessage({ type: "GET_CAPTURE_WORKSPACE" });if (!response?.ok) return showFeedback(response?.message || "无法读取待保存内容", true);- draft = response.draft;+ const refreshedDraft = response.draft;+ await Promise.all(refreshedDraft.visuals.map(async visual => {+ if (!visual.contentHash) {+ if (!draftVisualHashes.has(visual.id)) draftVisualHashes.set(visual.id,+ getScreenshotBlob(visual.id).then(blob => blob ? sha256Blob(blob) : ""));+ visual.contentHash = await draftVisualHashes.get(visual.id);+ }+ }));+ draft = refreshedDraft;targetEntry = response.targetEntry ?? null;contentTypes = response.contentTypes ?? [];collections = response.collections ?? [];suggestedContentTypeId = response.suggestedContentTypeId || "";+ captureClassificationContext = response.classificationContext || {};partContentTypes = response.partContentTypes ?? {};activeCreativeResult = response.activeCreativeResult ?? null;activeCreativePrompt = response.activeCreativePrompt ?? null;+ syncDraftIntoPageCapture();render();}async function tryAutoSelection() {- if (autoTextCaptureActive || !draft || activeCreativePrompt || draft.fragments.length || draft.visuals.length) return;+ if (autoTextCaptureActive || pageCaptureBatch || !draft || activeCreativePrompt || draft.fragments.length || draft.visuals.length) return;autoTextCaptureActive = true;try {const response = await chrome.runtime.sendMessage({ type: "TRY_ACTIVE_SELECTION_TO_DRAFT" });@@ -352,30 +392,33 @@ async function tryAutoSelection() {}}-async function extractClipboardOrSelection(button, { clipboardPreferenceJustDeclined = false } = {}) {+async function extractPageSelection(button) {await withButton(button, async () => {try {- let selection = null;- try {- selection = await runCaptureTransaction({- type: "ADD_ACTIVE_SELECTION_TO_DRAFT",- chromeApi: chrome,- onStatus: showFeedback- });- } catch {- }- if (selection && (selection.captured?.added || selection.captured?.reason !== "empty-selection")) {- draft = selection.draft;- showFeedback(selection.message || "已提取网页高亮文字");- await refresh();+ const selection = await runCaptureTransaction({+ type: "ADD_ACTIVE_SELECTION_TO_DRAFT", chromeApi: chrome, onStatus: showFeedback+ });+ if (selection.captured?.reason === "empty-selection") {+ showFeedback("请先在网页中选中文字");return;}+ draft = selection.draft;+ showFeedback(selection.message || "已提取网页高亮文字");+ await refresh();+ } catch (error) {+ showFeedback(error.message || "文字提取失败", true);+ }+ });+}+async function extractClipboard(button, { clipboardPreferenceJustDeclined = false } = {}) {+ await withButton(button, async () => {+ try {const stored = await chrome.storage.local.get(CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY);const onboarding = normalizeCapturePermissionOnboarding(stored[CAPTURE_PERMISSION_ONBOARDING_STORAGE_KEY]);if (onboarding.acknowledgedAt && !onboarding.clipboardIncluded) {if (clipboardPreferenceJustDeclined) {- showFeedback("没有网页高亮;已按你的选择保持剪贴板关闭,未读取任何内容");+ showFeedback("已按你的选择保持剪贴板关闭,未读取任何内容");return;}pendingClipboardButton = button;@@ -507,13 +550,17 @@ function render() {elements.normalStart.hidden = showCreativeResult;elements.resultPromptTitle.textContent = activeCreativePrompt?.title || "";elements.smartSelection.hidden = !smartVisualSession;- elements.pageCapture.hidden = !pageCaptureBatch;+ elements.pageCapture.hidden = !pageCaptureBatch || Boolean(smartVisualSession || regionCaptureState);+ document.body.classList.toggle("page-capture-active", Boolean(pageCaptureBatch));if (pageCaptureBatch) {+ elements.pageCaptureTools.before(elements.captureAddMoreActions);elements.pageCaptureActions.before(elements.captureMetadata);} else {+ elements.organizer.before(elements.captureAddMoreActions);elements.captureAddMoreActions.before(elements.captureMetadata);}- elements.captureMetadata.hidden = !pageCaptureBatch && !view.showPreview;+ elements.captureAddMoreActions.hidden = Boolean(pageCaptureBatch && (pageCaptureAppendBase || pageCaptureBatch.selections.length !== 1));+ elements.captureMetadata.hidden = pageCaptureBatch ? !pageCaptureBatch.selections.length : !view.showPreview;elements.regionCaptureStatus.hidden = !regionCaptureState;elements.previewState.hidden = Boolean(smartVisualSession || pageCaptureBatch || regionCaptureState) || !view.showPreview;elements.collectorFooter.hidden = Boolean(smartVisualSession || pageCaptureBatch || regionCaptureState) || !view.showFooter;@@ -545,6 +592,8 @@ function render() {elements.captureCollection.disabled = saving;elements.captureNewCollectionName.disabled = saving;for (const control of [+ elements.addClipboard,+ elements.startClipboard,elements.addSelection,elements.addScreenshot,elements.addSmartVisuals,@@ -564,7 +613,8 @@ function render() {}elements.organizer.hidden = !view.showOrganizer;elements.organizeToggle.setAttribute("aria-expanded", String(view.showOrganizer));- elements.organizeToggle.textContent = t(view.showOrganizer ? "收起整理" : "编辑与整理");+ elements.organizeToggle.title = t(view.showOrganizer ? "收起整理" : "编辑与整理");+ elements.organizeToggle.setAttribute("aria-label", elements.organizeToggle.title);elements.fragmentSection.hidden = !view.showOrganizer || !draft.fragments.length;elements.visualSection.hidden = !view.showOrganizer || !draft.visuals.length;elements.fragmentHelp.textContent = view.canReorderFragments ? t("使用箭头调整段落顺序") : "";@@ -572,7 +622,12 @@ function render() {if (document.activeElement !== elements.draftTitle) {elements.draftTitle.value = draft.title || targetEntry?.title || "";}- const selectedContentType = draft.contentTypeId || suggestedContentTypeId;+ const pageCandidate = pageCaptureBatch?.selections.length === 1 ? applyPageCaptureSelections(finalizePageCaptureSelectionsForSave(pageCaptureBatch))[0] : null;+ const pageClassification = pageCandidate ? classifyContent({ text: pageCandidate.contentText,+ title: pageCandidate.title, url: pageCandidate.canonicalUrl, sourceFacts: pageCandidate.sourceFacts, mediaAssets: pageCandidate.media },+ captureClassificationContext.rules, captureClassificationContext.taxonomy) : null;+ const selectedContentType = draft.contentTypeExplicit ? draft.contentTypeId+ : pageCandidate ? pageClassification?.pathIds?.[0] : draft.contentTypeId || suggestedContentTypeId;elements.contentType.replaceChildren(...contentTypes.map((item) => {const option = document.createElement("option");option.value = item.id;@@ -603,9 +658,11 @@ function render() {customLabelEditor.setValues(draft.customLabels ?? []);customLabelEditor.setDisabled(saving);elements.quickPreview.replaceChildren(...createQuickPreview());- elements.addOtherCaptureMethods.open = smartVisualFallback;elements.otherCaptureMethods.classList.toggle("fallback-highlight", smartVisualFallback);- elements.addOtherCaptureMethods.classList.toggle("fallback-highlight", smartVisualFallback);+ elements.addScreenshot.classList.toggle("fallback-highlight", smartVisualFallback);+ for (const button of [elements.addSmartVisuals, elements.addSelection, elements.addClipboard, elements.addScreenshot, elements.addPageCapture]) {+ button.disabled = saving || button.hasAttribute("aria-busy") || Boolean(pageCaptureBatch && (pageCaptureRequestId || pageCaptureEditing || pageCaptureCancelling || pageCaptureBatch.status === "saving" || pageCaptureBatch.selections.length !== 1));+ }renderPageCapturePermissionAction();elements.fragmentList.replaceChildren(...draft.fragments.map((fragment, index) =>createFragmentCard(fragment, index, view.canReorderFragments)));@@ -629,38 +686,53 @@ async function refreshPageCapturePermissionState() {}function renderPageCapturePermissionAction() {- const needsGrant = pageCapturePermissionState.status === "missing";- const needsInvocation = pageCapturePermissionState.status === "active-tab-required";- const startLabel = needsInvocation ? t("点插件图标后再采集") : needsGrant ? t("授权当前网站并扫描") : t("网页采集");const startText = elements.startPageCapture.querySelector("strong");- if (startText) startText.textContent = startLabel;- elements.addPageCapture.textContent = needsInvocation- ? t("+ 点插件图标后再采集")- : needsGrant ? t("+ 授权当前网站并扫描") : t("+ 网页采集");+ if (startText) startText.textContent = t("网页采集");+ elements.addPageCapture.querySelector("span").textContent = t("网页");+}function renderPageCapture() {+ const activeCardId = document.activeElement?.closest(".page-capture-item")?.dataset.candidateId;+ const activeMediaId = document.activeElement?.closest(".page-capture-media-review-item")?.dataset.mediaId;const selections = new Map(pageCaptureBatch.selections.map((selection) => [selection.candidateId, selection]));const selectedCount = pageCaptureBatch.selections.length;const listMode = pageCaptureBatch.captureMode === "list";const scanning = pageCaptureBatch.status === "scanning";- elements.pageCaptureTitle.textContent = scanning ? t("正在读取网页正文和媒体…") : t("识别到 {count} 个可保存区域 · 已选 {selected} 个", { count: pageCaptureBatch.candidates.length, selected: selectedCount });+ const busy = scanning || pageCaptureBatch.status === "saving" || Boolean(pageCaptureEditing) || pageCaptureCancelling;+ elements.pageCaptureTitle.textContent = t("网页采集");elements.pageCaptureHelp.textContent = pageCaptureBatch.status === "scanning"? t("正在扫描已加载内容;可随时停止,结束后会恢复原滚动位置。")- : pageCaptureBatch.error || t("确认一个主体后即可保存;需要时再展开预览或修正识别结果。");+ : pageCaptureBatch.error || (selectedCount ? t("已选 {count} 项内容", { count: selectedCount }) : pageCaptureBatch.candidates.length ? t("选择要保存的内容") : t("未识别到内容,可重新扫描或返回选择其他采集方式"));const selectedMediaCount = pageCaptureBatch.selections.reduce((count, selection) => count + selection.selectedMediaIds.length, 0);- const saveBlocked = scanning || !selectedCount || pageCaptureBatch.status === "saving" || (listMode && !["multiple", "combined"].includes(pageCaptureBatch.saveMode));+ const saveBlocked = busy || !selectedCount || (listMode && !["multiple", "combined"].includes(pageCaptureBatch.saveMode));elements.pageCaptureSave.disabled = saveBlocked;elements.pageCaptureSaveTextOnly.disabled = saveBlocked;elements.pageCaptureSaveTextOnly.hidden = selectedMediaCount === 0;elements.pageCaptureSave.textContent = listMode- ? selectedMediaCount- ? t("保存 {cases} 个案例 · 含 {media} 项媒体", { cases: selectedCount, media: selectedMediaCount })- : t("只保存 {count} 个正文案例", { count: selectedCount })- : selectedMediaCount ? t("保存案例 · 含 {count} 项媒体", { count: selectedMediaCount }) : t("只保存正文");- elements.pageCaptureScan.hidden = listMode || scanning;- elements.pageCaptureListSetup.hidden = listMode || scanning || !pageCaptureBatch.candidates.length;+ ? pageCaptureBatch.saveMode === "combined" ? t("合并保存案例") : t("保存 {count} 个案例", { count: selectedCount })+ : t("保存案例");+ elements.pageCaptureSaveSummary.textContent = scanning ? t("正在读取网页正文和媒体…")+ : pageCaptureBatch.status === "saving" ? t("正在保存…")+ : selectedCount ? t("已选 {count} 项内容 · {media} 项媒体", { count: selectedCount, media: selectedMediaCount }) : t("请选择一项内容");+ elements.pageCaptureCancel.textContent = scanning ? t("停止扫描") : t("退出");+ elements.pageCaptureCancel.disabled = pageCaptureBatch.status === "saving" || pageCaptureCancelling;+ elements.pageCaptureScan.hidden = false;+ elements.pageCaptureScan.disabled = busy;+ elements.pageCaptureMode.disabled = busy;+ elements.pageCaptureMode.value = listMode || pageCaptureListRequested ? "list" : "single";+ elements.pageCaptureListSetup.hidden = listMode || !pageCaptureListRequested;+ elements.pageCaptureListRun.disabled = busy || selectedCount !== 1;+ elements.pageCaptureTargetCount.disabled = busy;elements.pageCaptureListResult.hidden = !listMode;+ elements.pageCaptureSaveMode.disabled = busy;+ elements.pageCaptureCombinedTitle.disabled = busy;+ elements.pageCaptureTools.hidden = !selectedCount;+ if (!selectedCount) elements.pageCaptureTools.open = false;+ elements.pageCaptureClear.textContent = listMode ? t("取消选择") : t("换一项");+ elements.pageCaptureClear.disabled = busy;+ elements.pageCaptureEditStatus.hidden = !pageCaptureEditing;+ elements.pageCaptureEditHelp.textContent = pageCaptureEditing?.mode === "include" ? t("点击网页中遗漏的内容,完成后返回") : t("点击网页中不想保存的内容,完成后返回");if (listMode) {const reviewCount = pageCaptureBatch.candidates.filter((candidate) => candidate.batchStructureStatus === "review").length;elements.pageCaptureListSummary.textContent = t("目标 {target} 个,实际识别 {actual} 个。{reason}", {@@ -672,57 +744,37 @@ function renderPageCapture() {elements.pageCaptureCombinedTitleRow.hidden = pageCaptureBatch.saveMode !== "combined";if (document.activeElement !== elements.pageCaptureCombinedTitle) elements.pageCaptureCombinedTitle.value = pageCaptureBatch.combinedTitle;}- elements.pageCaptureList.replaceChildren(...pageCaptureBatch.candidates.map((candidate) => {- const card = document.createElement("article");- const confirmed = selections.has(candidate.id);- card.className = `page-capture-item${confirmed ? " confirmed" : ""}`;- if (candidate.batchStructureStatus === "review") card.classList.add("structure-review");- const heading = document.createElement("header");- const copy = document.createElement("div");- const title = document.createElement("strong");- title.textContent = candidate.title;- const meta = document.createElement("small");- const captureScope = candidate.extraction.scope === "selection" ? t("原网页选区") : pageCaptureExtractionLabel(candidate.extraction.method);- meta.textContent = `${pageCaptureTypeLabel(candidate.pageType)} · ${hostname(candidate.canonicalUrl) || t("当前网页")} · ${captureScope}${candidate.sourceFacts.author ? ` · ${candidate.sourceFacts.author}` : ""}${candidate.batchStructureStatus === "review" ? ` · ${t("结构需复核")}` : ""}`;- copy.append(title, meta);- const inspect = document.createElement("button");- inspect.type = "button";- inspect.className = "button-secondary compact page-capture-inspect";- inspect.textContent = t("查看网页区域");- inspect.addEventListener("click", () => previewPageCaptureRegion(candidate));- heading.append(copy);- if (!listMode) heading.append(inspect);- card.append(heading);- const previewDetails = document.createElement("details");- previewDetails.className = "page-capture-preview-details";- const previewSummary = document.createElement("summary");- previewSummary.textContent = t("预览完整内容");- previewDetails.append(previewSummary, createPageCaptureArticlePreview(candidate, selections.get(candidate.id)));- card.append(previewDetails);- if (candidate.possibleOmissions?.length) {- const omissions = document.createElement("details");- omissions.className = "page-capture-omissions";- const summary = document.createElement("summary");- summary.textContent = t("可能遗漏({count})", { count: candidate.possibleOmissions.length });- const list = document.createElement("div");- list.append(...candidate.possibleOmissions.map((item) => {- const block = document.createElement("p");- block.textContent = item.text;- return block;- }));- omissions.append(summary, list);- card.append(omissions);- }- const confirm = document.createElement("button");- confirm.type = "button";- confirm.className = confirmed ? "button-secondary page-capture-confirm" : "primary page-capture-confirm";- confirm.textContent = listMode && confirmed ? t("移除此案例") : confirmed ? t("已确认这个主体") : t("确认这个主体");- confirm.disabled = confirmed && !listMode;- confirm.addEventListener("click", () => listMode && confirmed ? removePageCaptureCandidate(candidate.id) : confirmPageCaptureCandidate(candidate));- card.append(confirm);- return card;- }));- const canEditRegion = !listMode && selectedCount === 1;+ const expandedPreviews = new Set([...elements.pageCaptureList.querySelectorAll(".page-capture-item")]+ .filter(card => card.querySelector(".page-capture-preview-details")?.open).map(card => card.dataset.candidateId));+ elements.pageCaptureList.replaceChildren(...pageCaptureBatch.candidates.map(candidate => createPageCaptureCard(candidate, {+ selected: selections.has(candidate.id), listMode, busy,+ hidden: !listMode && !pageCaptureListRequested && selectedCount > 0 && !selections.has(candidate.id),+ meta: [pageCaptureTypeLabel(candidate.pageType), candidate.extraction.scope === "selection" ? t("原网页选区") : "", hostname(candidate.canonicalUrl), candidate.sourceFacts.author,+ candidate.batchStructureStatus === "review" ? t("结构需复核") : ""].filter(Boolean).join(" · "),+ onSelect: () => selections.has(candidate.id) ? (listMode ? removePageCaptureCandidate(candidate.id) : clearPageCaptureConfirmation()) : confirmPageCaptureCandidate(candidate),+ onLocate: () => previewPageCaptureRegion(candidate, true),+ onIncludeSupplement: item => includePageCaptureSupplement(candidate, item),+ selectedMediaIds: selections.get(candidate.id)?.selectedMediaIds || [],+ loadLocalVisual: loadVisual,+ onIncludeMediaGroup: group => {+ const selection = selections.get(candidate.id);+ pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate), selection: structuredClone(selection) });+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections: pageCaptureBatch.selections.map(s => s.candidateId === candidate.id+ ? { ...s, mediaDecision: "confirmed", selectedMediaIds: [...new Set([...s.selectedMediaIds, ...group.map(m => m.id)])] } : s) });+ render();+ },+ onRemoveMedia: media => {+ const selection = selections.get(candidate.id);+ pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate), selection: structuredClone(selection) });+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections: pageCaptureBatch.selections.map(s => s.candidateId === candidate.id+ ? { ...s, mediaDecision: "confirmed", selectedMediaIds: s.selectedMediaIds.filter(id => id !== media.id) } : s) });+ render();+ },+ onPreviewMedia: index => openPageCaptureMediaViewer(candidate, index),+ createArticlePreview: () => createPageCaptureArticlePreview(candidate, selections.get(candidate.id)),+ previewOpen: expandedPreviews.has(candidate.id)+ })));+ const canEditRegion = !busy && !listMode && selectedCount === 1;elements.pageCaptureAddRegion.disabled = !canEditRegion;elements.pageCaptureExcludeRegion.disabled = !canEditRegion;elements.pageCaptureUndoRegion.disabled = !canEditRegion || !pageCaptureEditHistory.length;@@ -732,6 +784,8 @@ function renderPageCapture() {elements.pageCaptureUndoRegion.hidden = listMode;elements.pageCaptureResetRegion.hidden = listMode;renderPageCaptureMediaReview(selections);+ if (activeCardId) elements.pageCaptureList.querySelector(`[data-candidate-id="${CSS.escape(activeCardId)}"] .page-capture-confirm`)?.focus({ preventScroll: true });+ if (activeMediaId) elements.pageCaptureMediaReviewList.querySelector(`[data-media-id="${CSS.escape(activeMediaId)}"] button:last-child`)?.focus({ preventScroll: true });}function createPageCaptureArticlePreview(candidate, selection) {@@ -746,7 +800,7 @@ function createPageCaptureArticlePreview(candidate, selection) {];heading.append(textNode("strong", candidate.extraction.scope === "selection" ? t("原网页选区") : "完整文章预览"),- textNode("small", `${blocks.length} 个有序内容块`)+ textNode("small", `${pageCaptureExtractionLabel(candidate.extraction.method)} · ${blocks.length} 个有序内容块`));section.append(heading);const mediaById = new Map(candidate.media.map((media) => [media.id, media]));@@ -780,9 +834,10 @@ function createPageCaptureArticleMedia(candidate, media, block, selection) {const preview = document.createElement("span");preview.className = "page-capture-media-preview";const previewUrl = media?.kind === "video" ? media.posterUrl : media?.previewDataUrl || media?.dataUrl || media?.url || block.posterUrl || block.sourceUrl;- if (previewUrl) {+ if (previewUrl || media?.localAssetId) {const image = document.createElement("img");- image.src = previewUrl;+ if (media?.localAssetId) loadVisual(image, media.localAssetId);+ else image.src = previewUrl;image.alt = "";image.referrerPolicy = "no-referrer";image.addEventListener("error", () => {@@ -838,7 +893,38 @@ function textNode(tagName, value) {return node;}+function appendToPageCapture(addition) {+ const selection = pageCaptureBatch?.selections[0];+ if (!selection || pageCaptureBatch.selections.length !== 1) return;+ const candidate = pageCaptureBatch.candidates.find(c => c.id === selection.candidateId);+ const result = appendCaptureCandidate(candidate, addition, selection);+ pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate), selection: structuredClone(selection) });+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch,+ candidates: pageCaptureBatch.candidates.map(c => c.id === candidate.id ? result.candidate : c),+ selections: [result.selection] });+}++function syncDraftIntoPageCapture() {+ if (!draft || !pageCaptureBatch || pageCaptureAppendBase || pageCaptureBatch.selections.length !== 1 || pageCaptureBatch.status === "saving") return;+ const addition = draftCaptureAddition(draft, pageCaptureDraftIds);+ if (!addition.consumed.length) return;+ appendToPageCapture(addition);+ addition.consumed.forEach(id => pageCaptureDraftIds.add(id));+}+function confirmPageCaptureCandidate(candidate) {+ if (pageCaptureRequestId || pageCaptureEditing || pageCaptureCancelling || pageCaptureBatch?.status === "saving") return;+ if (pageCaptureAppendBase) {+ const selected = applyPageCaptureSelections(normalizePageCaptureBatch({ ...pageCaptureBatch,+ selections: [{ candidateId: candidate.id, selectedTextBlockIds: candidate.textBlocks.map(b => b.id),+ selectedMediaIds: pageCaptureDefaultMediaIds(candidate), mediaDecision: "confirmed" }] }))[0];+ pageCaptureBatch = pageCaptureAppendBase;+ pageCaptureAppendBase = null;+ appendToPageCapture(selected);+ render();+ return;+ }+ pageCaptureDraftIds = new Set();const next = normalizePageCaptureSelection({candidateId: candidate.id,selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),@@ -847,45 +933,91 @@ function confirmPageCaptureCandidate(candidate) {}, pageCaptureBatch.candidates);pageCaptureBatch = normalizePageCaptureBatch({...pageCaptureBatch,- selections: next ? [next] : []+ selections: next ? (pageCaptureBatch.captureMode === "list" ? [...pageCaptureBatch.selections, next] : [next]) : []});+ syncDraftIntoPageCapture();previewPageCaptureRegion(candidate);render();}function clearPageCaptureConfirmation() {+ if (pageCaptureRequestId || pageCaptureEditing || pageCaptureCancelling || pageCaptureBatch?.status === "saving") return;pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections: [] });previewPageCaptureRegion(null);render();}-function previewPageCaptureRegion(candidate) {- chrome.runtime.sendMessage({- type: "PREVIEW_PAGE_CAPTURE_REGION",- tabId: pageCaptureBatch?.tabId,- marker: candidate?.region?.marker || ""- }).catch(() => undefined);+async function previewPageCaptureRegion(candidate, locate = false) {+ const request = ++pageCapturePreviewRequest;+ const selection = pageCaptureBatch?.selections.find(item => item.candidateId === candidate?.id);+ const response = await chrome.runtime.sendMessage({+ type: "PREVIEW_PAGE_CAPTURE_REGION", tabId: pageCaptureBatch?.tabId,+ preview: {+ marker: candidate?.region?.marker || "", targets: candidate?.region?.contentTargets || [],+ text: [candidate?.contentText, ...(candidate?.articleDocument?.blocks || []).map(block => block.text)].filter(Boolean).join("\n"),+ mediaIds: selection?.selectedMediaIds || (candidate ? pageCaptureDefaultMediaIds(candidate) : []),+ mediaUrls: (candidate?.media || []).filter(media => (selection?.selectedMediaIds || pageCaptureDefaultMediaIds(candidate)).includes(media.id))+ .flatMap(media => [media.url, ...(media.variants || []).map(variant => variant.url)]).filter(Boolean),+ edits: candidate?.region?.edits || [], locate+ }+ }).catch(() => ({ ok: false, message: t("无法在当前网页显示区域高亮") }));+ if (request === pageCapturePreviewRequest && candidate && !response?.ok) showFeedback(response?.message || t("部分内容无法在网页定位,请以保存预览为准"), true);}async function editConfirmedPageCaptureRegion(mode, button) {+ if (pageCaptureRequestId || pageCaptureEditing || pageCaptureCancelling || pageCaptureBatch?.status === "saving") return;+ const batchId = pageCaptureBatch?.id;const selectedId = pageCaptureBatch?.selections?.[0]?.candidateId;- const candidate = pageCaptureBatch?.candidates?.find((item) => item.id === selectedId);+ const candidate = pageCaptureBatch?.candidates?.find(item => item.id === selectedId);if (!candidate) return showFeedback("请先确认一个主体方案", true);+ const edit = { mode, batchId };await withButton(button, async () => {- const response = await chrome.runtime.sendMessage({- type: "EDIT_PAGE_CAPTURE_REGION",- tabId: pageCaptureBatch.tabId,- candidate,- mode- });- if (!response?.ok) {- if (!response?.cancelled) showFeedback(response?.message || "网页区域没有修改", true);- return;+ pageCaptureEditing = edit;+ render();+ try {+ const response = await chrome.runtime.sendMessage({ type: "EDIT_PAGE_CAPTURE_REGION", tabId: pageCaptureBatch.tabId, candidate, mode });+ if (pageCaptureEditing !== edit || pageCaptureBatch?.id !== batchId) return;+ if (!response?.ok) {+ if (!response?.cancelled) showFeedback(response?.message || "网页区域没有修改", true);+ void previewPageCaptureRegion(candidate);+ return;+ }+ pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate) });+ replacePageCaptureCandidate(response.candidate);+ showFeedback(response.message);+ } catch (error) {+ showFeedback(error.message || "网页区域没有修改", true);+ } finally {+ if (pageCaptureEditing === edit) pageCaptureEditing = null;+ render();}- pageCaptureEditHistory.push({ candidateId: candidate.id, candidate: structuredClone(candidate) });- replacePageCaptureCandidate(response.candidate);- showFeedback(response.message);});+ render();+}++function includePageCaptureSupplement(candidate, item) {+ if (!candidate.supplements.some(value => value.id === item.id)) return;+ const paragraph = document.createElement("p");+ paragraph.textContent = item.text;+ const block = { id: item.id, kind: "section", text: item.text, html: paragraph.outerHTML, sourceOrder: candidate.textBlocks.length };+ const revised = {+ ...candidate,+ textBlocks: [...candidate.textBlocks, block],+ contentText: [candidate.contentText, item.text].filter(Boolean).join("\n\n"),+ articleDocument: { version: 1, blocks: [...(candidate.articleDocument?.blocks || []),+ { id: item.id + ":source", kind: "link", sourceUrl: item.sourceUrl, label: t("作者补充") },+ { ...block, kind: "paragraph" }] },+ supplements: candidate.supplements.filter(value => value.id !== item.id),+ completeness: item.partial ? "partial" : candidate.completeness,+ sourceFacts: { ...candidate.sourceFacts, status: item.partial ? "partial" : candidate.sourceFacts.status }+ };+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch,+ candidates: pageCaptureBatch.candidates.map(value => value.id === candidate.id ? revised : value),+ selections: pageCaptureBatch.selections.map(selection => selection.candidateId === candidate.id+ ? { ...selection, includeText: true, selectedTextBlockIds: [...(selection.selectedTextBlockIds || (selection.includeText ? candidate.textBlocks.map(value => value.id) : [])), item.id] }+ : selection)+ });+ render();}function replacePageCaptureCandidate(candidate) {@@ -913,20 +1045,22 @@ function renderPageCaptureMediaReview(selections) {}const proposedCount = pageCaptureBatch.selections.reduce((count, selection) => count + selection.selectedMediaIds.length, 0);elements.pageCaptureMediaReviewStatus.textContent = selected.length- ? t("保存时将确认 {count} 项媒体", { count: proposedCount })+ ? t("{count} 项媒体", { count: proposedCount }): t("未识别到媒体,可返回网页补选");const createRow = ({ candidate, media, mediaIndex, selection }) => {const row = document.createElement("div");row.className = "page-capture-media-review-item";+ row.dataset.mediaId = `${candidate.id}:${media.id}`;setPageCaptureMediaDecisionClass(row, media.id, selection);const preview = document.createElement("button");preview.type = "button";preview.className = "page-capture-media-review-preview";preview.addEventListener("click", () => openPageCaptureMediaViewer(candidate, mediaIndex));const previewUrl = media.kind === "video" ? media.posterUrl : media.previewDataUrl || media.dataUrl || media.url;- if (previewUrl) {+ if (previewUrl || media.localAssetId) {const image = document.createElement("img");- image.src = previewUrl;+ if (media.localAssetId) loadVisual(image, media.localAssetId);+ else image.src = previewUrl;image.alt = "";image.referrerPolicy = "no-referrer";image.addEventListener("error", () => preview.replaceChildren(textNode("span", t("预览不可用"))), { once: true });@@ -942,6 +1076,7 @@ function renderPageCaptureMediaReview(selections) {toggle.className = "button-secondary compact";const included = selection.mediaDecision !== "none" && selection.selectedMediaIds.includes(media.id);toggle.textContent = included ? t("排除") : t("恢复");+ toggle.disabled = Boolean(pageCaptureRequestId || pageCaptureEditing || pageCaptureBatch.status === "saving");toggle.addEventListener("click", () => updatePageCaptureMediaSelection(candidate.id, media.id));row.append(preview, copy, toggle);return row;@@ -978,6 +1113,7 @@ function updatePageCaptureMediaSelection(candidateId, mediaId) {return { ...selection, selectedMediaIds: [...selected], mediaDecision: "pending" };});pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, selections });+ if (pageCaptureBatch.captureMode !== "list") void previewPageCaptureRegion(pageCaptureBatch.candidates.find(item => item.id === candidateId));render();}@@ -999,8 +1135,13 @@ function finalizePageCaptureSelectionsForSave(batchValue, textOnly = false) {function undoPageCaptureRegionEdit() {const previous = pageCaptureEditHistory.pop();if (!previous) return;- replacePageCaptureCandidate(previous.candidate);- showFeedback("已撤销上一次主体修正");+ if (previous.selection) {+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch,+ candidates: pageCaptureBatch.candidates.map(c => c.id === previous.candidate.id ? previous.candidate : c),+ selections: pageCaptureBatch.selections.map(s => s.candidateId === previous.candidate.id ? previous.selection : s) });+ render();+ } else replacePageCaptureCandidate(previous.candidate);+ showFeedback(t("已撤销上次调整"));}function resetPageCaptureRegionEdit() {@@ -1048,7 +1189,8 @@ function renderPageCaptureMediaViewer() {}const sourceUrl = media.kind === "video" ? media.url : media.previewDataUrl || media.dataUrl || media.url;const visual = document.createElement(media.kind === "video" ? "video" : "img");- visual.src = sourceUrl || media.posterUrl || "";+ if (media.localAssetId) loadVisual(visual, media.localAssetId);+ else visual.src = sourceUrl || media.posterUrl || "";visual.setAttribute("referrerpolicy", "no-referrer");if (media.kind === "video") {visual.controls = true;@@ -1099,23 +1241,36 @@ function pageCaptureMediaSourceLabel(value, captureMethod = "") {}async function cancelPageCapture() {- if (pageCaptureBatch?.status !== "scanning" || !pageCaptureSession?.sessionId) {- pageCaptureRequestId = "";- await clearPageCaptureMarkers();- pageCaptureBatch = null;- pageCaptureSession = null;- pageCaptureEditHistory = [];- pageCaptureOriginalCandidates = new Map();- return render();- }- const sessionId = pageCaptureSession.sessionId;+ if (pageCaptureCancelling || pageCaptureBatch?.status === "saving") return;+ pageCaptureCancelling = true;+ const requestId = pageCaptureRequestId;+ const sessionId = pageCaptureSession?.sessionId;+ const scanning = pageCaptureBatch?.status === "scanning";+ if (requestId) cancelledPageCaptureRequests.add(requestId);pageCaptureRequestId = "";pageCaptureSession = null;- pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "preview" });+ pageCaptureEditing = null;+ pageCapturePreviewRequest += 1;+ closePageCaptureMediaViewer();render();- const response = await chrome.runtime.sendMessage({ type: "CANCEL_PAGE_CAPTURE", sessionId });- await clearPageCaptureMarkers();- showFeedback(response?.message || t("正在停止整页扫描"), !response?.ok);+ try {+ if (sessionId) await chrome.runtime.sendMessage({ type: "CANCEL_PAGE_CAPTURE", sessionId });+ await clearPageCaptureMarkers();+ if (pageCaptureAppendBase) {+ pageCaptureBatch = pageCaptureAppendBase;+ pageCaptureAppendBase = null;+ } else if (scanning && pageCaptureBatch) {+ pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "preview", selections: [], error: t("扫描已停止,可重新扫描") });+ } else {+ pageCaptureBatch = null;+ pageCaptureListRequested = false;+ pageCaptureEditHistory = [];+ pageCaptureOriginalCandidates = new Map();+ }+ } finally {+ pageCaptureCancelling = false;+ render();+ }}async function clearPageCaptureMarkers() {@@ -1134,7 +1289,7 @@ function createQuickPreview() {const card = div("quick-item quick-text");const marker = text("Aa", "strong");const copy = div("quick-copy");- copy.append(text(fragment.text, "p"), text(fragment.sourceTitle || hostname(fragment.sourceUrl) || t("当前网页"), "small"));+ copy.append(text(fragment.text, "p"), text(hostname(fragment.sourceUrl) || fragment.sourceTitle || t("当前网页"), "small"));const remove = createQuickRemoveButton(`删除第 ${index + 1} 段文字`, (button) =>sendDraftAction(button, "REMOVE_CAPTURE_FRAGMENT", { fragmentId: fragment.id }));card.append(marker, copy, remove);@@ -1154,7 +1309,7 @@ function createQuickPreview() {strip.append(item);});const copy = div("quick-copy");- copy.append(text(t("{count} 张图片", { count: draft.visuals.length }), "strong"), text(draft.visuals[0].sourceTitle || hostname(draft.visuals[0].sourceUrl) || t("当前网页"), "small"));+ copy.append(text(hostname(draft.visuals[0].sourceUrl) || draft.visuals[0].sourceTitle || t("当前网页"), "small"));card.append(strip, copy);nodes.push(card);}@@ -1177,7 +1332,7 @@ function createFragmentCard(fragment, index, canReorder) {textarea.addEventListener("change", () =>sendDraftAction(null, "UPDATE_CAPTURE_FRAGMENT", { fragmentId: fragment.id, text: textarea.value }));const meta = div("item-meta");- const source = text(fragment.sourceTitle || hostname(fragment.sourceUrl) || t("当前网页"));+ const source = text(hostname(fragment.sourceUrl) || fragment.sourceTitle || t("当前网页"));const partContentType = partContentTypes[fragment.sourceUrl || "source:unknown"];const partType = text(partContentType?.customized ? partContentType.name : t(partContentType?.name || "待确认"), "small");meta.append(source, partType);@@ -1238,6 +1393,7 @@ async function captureFromActivePage(type, button, commitCreative = false) {chromeApi: chrome,onStatus: showFeedback});+ if (type === "CAPTURE_ACTIVE_TAB_TO_DRAFT") regionCaptureState = null;smartVisualFallback = response.fallbackAction === "capture-region";draft = response.draft;elements.duplicatePanel.hidden = true;@@ -1299,7 +1455,10 @@ async function beginSmartVisualSelection(button, commitCreative = false) {}async function startPageCapture(mode, button) {- if (pageCaptureRequestId) return;+ if (pageCaptureRequestId || pageCaptureEditing || pageCaptureCancelling || pageCaptureBatch?.status === "saving" || button?.disabled) return;+ if (mode !== "list" && pageCaptureBatch?.selections.length === 1 && button === elements.addPageCapture) {+ pageCaptureAppendBase = structuredClone(pageCaptureBatch);+ } else if (!pageCaptureBatch) pageCaptureDraftIds = new Set();const requestId = crypto.randomUUID();pageCaptureRequestId = requestId;await withButton(button, async () => {@@ -1309,13 +1468,13 @@ async function startPageCapture(mode, button) {: null;const tab = await resolveActivePage(chrome.tabs, chrome.scripting);if (!tab?.url && Number.isInteger(tab?.id)) {- throw new Error(t("Chrome 不会在点击插件图标时弹出授权窗口。请先在当前网页点击工具栏里的 PromptDirector 图标,再回到侧栏点击“授权当前网站并扫描”;待保存内容没有改变。"));+ throw new Error(t("Chrome 不会在点击插件图标时弹出授权窗口。请先在当前网页点击工具栏里的 PromptDirector 图标,再回到侧栏点击“网页采集”;待保存内容没有改变。"));}if (!tab?.url) throw new Error(t(RESTRICTED_PAGE_MESSAGE));let permission = await inspectPagePermission(tab.url, chrome.permissions);if (permission.status === "missing") {if (!await ensurePagePermission(tab.url, chrome.permissions)) {- throw new Error(t("你没有授予当前网站访问权限。请再次点击“授权当前网站并扫描”,或在 Chrome 扩展详情的“网站访问权限”中允许此网站;待保存内容没有改变。"));+ throw new Error(t("你没有授予当前网站访问权限。请再次点击“网页采集”,或在 Chrome 扩展详情的“网站访问权限”中允许此网站;待保存内容没有改变。"));}permission = { ...permission, status: "granted" };}@@ -1325,10 +1484,10 @@ async function startPageCapture(mode, button) {throw new Error(t("Chrome 内部页、扩展页或本机设置页不能采集,请切换到普通网页"));}if (pageCaptureRequestId !== requestId) return;- if (mode === "whole" && pageCaptureBatch) {- pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "scanning" });- render();- }+ await clearPageCaptureMarkers();+ if (pageCaptureRequestId !== requestId) return;+ pageCaptureBatch = normalizePageCaptureBatch({ ...(pageCaptureBatch || { id: requestId, candidates: [] }), tabId: tab.id, status: "scanning", error: "" });+ render();const targetCount = mode === "list" ? Number(elements.pageCaptureTargetCount.value) : 0;const response = await chrome.runtime.sendMessage({ type: "START_PAGE_CAPTURE", mode, targetCount, requestId });if (pageCaptureRequestId !== requestId) return;@@ -1362,18 +1521,25 @@ async function startPageCapture(mode, button) {}, batch.candidates)).filter(Boolean): batch.selections;pageCaptureBatch = normalizePageCaptureBatch({ ...batch, selections });- pageCaptureEditHistory = [];- pageCaptureOriginalCandidates = new Map(pageCaptureBatch.candidates.map((candidate) => [candidate.id, structuredClone(candidate)]));+ if (!pageCaptureAppendBase) pageCaptureEditHistory = [];+ if (!pageCaptureAppendBase) pageCaptureOriginalCandidates = new Map(pageCaptureBatch.candidates.map((candidate) => [candidate.id, structuredClone(candidate)]));pageCaptureSession = null;- showFeedback(response.message);+ pageCaptureListRequested = mode === "list";+ closePageCaptureMediaViewer();+ elements.pageCaptureMediaReview.open = false;render();} catch (error) {if (pageCaptureRequestId !== requestId) return;+ if (pageCaptureAppendBase) {+ pageCaptureBatch = pageCaptureAppendBase;+ pageCaptureAppendBase = null;+ }if (pageCaptureBatch) pageCaptureBatch = normalizePageCaptureBatch({ ...pageCaptureBatch, status: "preview", error: error.message });pageCaptureSession = null;showFeedback(error.message || t("网页采集失败"), true);render();} finally {+ cancelledPageCaptureRequests.delete(requestId);if (pageCaptureRequestId === requestId) {pageCaptureRequestId = "";pageCaptureSession = null;@@ -1398,10 +1564,11 @@ async function startPageListCapture(button) {}async function savePageCapture(textOnly = false) {- if (!pageCaptureBatch) return;+ if (!pageCaptureBatch || pageCaptureRequestId || pageCaptureEditing || pageCaptureBatch.status === "saving") return;const trigger = textOnly ? elements.pageCaptureSaveTextOnly : elements.pageCaptureSave;await withButton(trigger, async () => {const reviewBatch = pageCaptureBatch;+ const metadata = captureMetadataForCommit();const saveBatch = finalizePageCaptureSelectionsForSave(reviewBatch, textOnly);const selected = applyPageCaptureSelections(saveBatch);const origins = pageCapturePermissionOrigins(selected);@@ -1419,22 +1586,39 @@ async function savePageCapture(textOnly = false) {const response = await chrome.runtime.sendMessage({type: "COMMIT_PAGE_CAPTURE",batch: normalizePageCaptureBatch({ ...pageCaptureBatch, sessionMediaAllowed }),- ...captureMetadataForCommit()+ ...metadata});if (!response?.ok) throw new Error(response?.message || t("网页内容保存失败"));const partial = response.results?.filter((item) => item.status === "partial" || item.status === "failed") || [];if (partial.length) {+ if (metadata.newCollectionName && response.collectionId) {+ creatingCollection = false;+ await updateDraft({ ...draft, collectionId: response.collectionId, newCollectionName: "" });+ }const reasons = [...new Set(partial.flatMap(item => item.warnings || []))];pageCaptureBatch = normalizePageCaptureBatch({ ...saveBatch, status: "preview", error: reasons.join(";") });+ elements.pageCaptureMediaReview.open = true;showFeedback(t("{message};{count} 项存在媒体下载问题", { message: response.message, count: partial.length }), true);await refresh();return;}await clearPageCaptureMarkers();+ const savedCandidateIds = new Set(response.results.filter(item => item.status === "saved").map(item => item.candidateId));+ const savedDraftItems = savedDraftCaptureItems(draft, selected.filter(c => savedCandidateIds.has(c.id)), pageCaptureDraftIds);+ const cleanupErrors = [];+ for (const item of savedDraftItems) {+ try {+ const cleanup = await chrome.runtime.sendMessage(item.kind === "image"+ ? { type: "REMOVE_CAPTURE_VISUAL", visualId: item.id }+ : { type: "REMOVE_CAPTURE_FRAGMENT", fragmentId: item.id });+ if (!cleanup?.ok) throw new Error(cleanup?.message || t("待保存内容没有更新"));+ } catch (error) { cleanupErrors.push(error.message); }+ }+ pageCaptureDraftIds = new Set();pageCaptureBatch = null;pageCaptureEditHistory = [];pageCaptureOriginalCandidates = new Map();- showFeedback(response.message);+ showFeedback(cleanupErrors.length ? `${response.message};${cleanupErrors.join(";")}` : response.message, Boolean(cleanupErrors.length));await refresh();} catch (error) {pageCaptureBatch = normalizePageCaptureBatch({ ...reviewBatch, status: "preview", error: error.message });@@ -1679,7 +1863,9 @@ function captureMetadataForCommit() {newCollectionName: selectedCollection === NEW_COLLECTION_OPTION_VALUE? elements.captureNewCollectionName.value.trim(): "",- customLabels: customLabelEditor.values+ customLabels: customLabelEditor.values,+ contentTypeId: draft.contentTypeId,+ contentTypeExplicit: draft.contentTypeExplicit};}diff --git a/i18n.js b/i18n.jsindex 90bd69d..df278ad 100644--- a/i18n.js+++ b/i18n.js@@ -1,6 +1,33 @@import { normalizeUiPreferences, resolveLocale } from "./preferences.js";const EN = Object.freeze({+ "取消选择": "Clear selection",+ "扫描已停止,可重新扫描": "Scan stopped. You can rescan.",+ "采集网页内容": "Capture page content",+ "采集方式": "Capture mode",+ "单个案例": "Single case",+ "列表批量": "Capture list",+ "选一个代表案例,再采集同类内容": "Select an example case, then capture similar items",+ "数量": "Count",+ "读取列表": "Read list",+ "调整内容": "Adjust content",+ "补选": "Add content",+ "换一项": "Choose another",+ "取消调整": "Cancel adjustment",+ "检查媒体": "Review media",+ "在网页中定位": "Locate on page",+ "已选 {count} 项内容": "{count} items selected",+ "未识别到内容,可重新扫描或返回选择其他采集方式": "No content found. Rescan or return to other capture tools.",+ "合并保存案例": "Save as one case",+ "保存 {count} 个案例": "Save {count} cases",+ "已选 {count} 项内容 · {media} 项媒体": "{count} items \u00b7 {media} media selected",+ "请选择一项内容": "Select some content",+ "停止扫描": "Stop scanning",+ "点击网页中遗漏的内容,完成后返回": "Click missing content on the page, then finish",+ "点击网页中不想保存的内容,完成后返回": "Click unwanted content on the page, then finish",+ "部分内容无法在网页定位,请以保存预览为准": "Some content cannot be located on the page. Check the save preview.",+ "无法在当前网页显示区域高亮": "Could not highlight content on this page",+"清理升级临时文件": "Clear temporary update files","已清理升级临时文件": "Temporary update files cleared","上次准备更新中断,原插件未更改。清理临时程序副本后继续。": "Update preparation was interrupted; the extension was not changed. Clear the temporary program copy to continue.",@@ -390,6 +417,24 @@ const EN = Object.freeze({"投稿采用 CC BY 4.0:其他用户必须保留你的公开署名,并可保存、使用和修改这份 Skill。": "Submissions use CC BY 4.0. Others must retain your public attribution and may save, use, and modify this Skill.","需要先处理的隐私风险": "Privacy risks to resolve first","最终投稿文件与全文": "Final submission files and full text",+ "仅在你点击“剪贴板”时读取。": "Read only when you click Clipboard.",+ "仅在你点击“剪贴板”时读取;打开侧栏、浏览或点击网页不会触发读取。": "Read only when you click Clipboard; opening the panel, browsing, or clicking the page does not read it.",+ "输入标签,回车添加": "Type a tag, press Enter",+ "选图": "Images",+ "提取选中文字": "Capture selected text",+ "选区": "Select",+ "剪贴板": "Paste",+ "截图": "Shot",+ "分类": "Category",+ "其他采集方式": "More capture options",+ "正文尚未展开,当前只会保存已显示内容": "The post is collapsed. Only visible content will be saved.",+ "作者补充": "Author follow-up",+ "作者补充({count})": "Author follow-ups ({count})",+ "补入已显示内容": "Add visible content",+ "补入当前案例": "Add to this case",+ "请先在网页中选中文字": "Select text on the page first",+ "文字提取失败": "Could not capture selected text",+ "已按你的选择保持剪贴板关闭,未读取任何内容": "Clipboard access remains off as requested. Nothing was read.","提示词导演采集台": "PromptDirector Collector","目标案例": "Target case","本次统一开启网页读取与截图能力,只在你主动采集时使用;不会自动保存案例。": "This enables page reading and screenshots together for active capture only. Cases are never saved automatically.",@@ -993,6 +1038,11 @@ const EN = Object.freeze({"CSS 背景图": "CSS background image","公开原图失败时,将使用当前网页已有登录状态读取所选图片;不会读取或保存登录信息。": "If public originals fail, the selected images will be read through the current page session. Sign-in information is never read or saved.","公开原图失败时,只会使用当前网页已有登录状态读取已确认主体内的相关媒体;不会读取或保存登录信息。": "If public originals fail, only related media inside the confirmed subject may be read through the current page session. Sign-in information is never read or saved.",+ "网页": "Webpage",+ "待保存内容没有更新": "The capture draft was not updated",+ "引用帖 · {count} 张图": "Quoted post · {count} images",+ "已撤销上次调整": "Last change undone",+ "加入这组": "Add this group","正在停止整页扫描": "Stopping full-page scan","文章": "Article","作品": "Work",@@ -1008,10 +1058,10 @@ const EN = Object.freeze({"+ 授权当前网站并扫描": "+ Allow this site and scan","点插件图标后再采集": "Click the extension icon, then capture","+ 点插件图标后再采集": "+ Click the extension icon, then capture",- "Chrome 不会在点击插件图标时弹出授权窗口。请先在当前网页点击工具栏里的 PromptDirector 图标,再回到侧栏点击“授权当前网站并扫描”;待保存内容没有改变。": "Chrome does not show a permission prompt when you click the extension icon. Click the PromptDirector toolbar icon on the current page, then return to the side panel and click Allow this site and scan. Unsaved content was not changed.",+ "Chrome 不会在点击插件图标时弹出授权窗口。请先在当前网页点击工具栏里的 PromptDirector 图标,再回到侧栏点击“网页采集”;待保存内容没有改变。": "Chrome does not show a permission prompt when you click the extension icon. Click the PromptDirector toolbar icon on the current page, then return to the side panel and click Capture page. Unsaved content was not changed.","Chrome 内部页、扩展页或本机设置页不能采集,请切换到普通网页": "Chrome internal pages, extension pages, and browser settings cannot be captured. Switch to a regular web page.","当前页不可采集:Chrome 新标签页、设置页和扩展页不允许读取;普通网站请先点工具栏图标。": "This page cannot be captured. Chrome new tabs, settings, and extension pages cannot be read. On a regular website, click the toolbar icon first.",- "你没有授予当前网站访问权限。请再次点击“授权当前网站并扫描”,或在 Chrome 扩展详情的“网站访问权限”中允许此网站;待保存内容没有改变。": "Access to this site was not granted. Click Allow this site and scan again, or allow this site under the extension's Site access settings. Unsaved content was not changed.",+ "你没有授予当前网站访问权限。请再次点击“网页采集”,或在 Chrome 扩展详情的“网站访问权限”中允许此网站;待保存内容没有改变。": "Access to this site was not granted. Click Capture page again, or allow this site under the extension's Site access settings. Unsaved content was not changed.","媒体域名权限未获授权;仍会保存正文和可用引用,并逐项显示下载失败原因。": "Media-domain access was not granted. Text and usable references will still be saved, with download failures shown per item.","网页内容保存失败": "Web content could not be saved","{message};{count} 项存在媒体下载问题": "{message}; {count} items have media download issues",diff --git a/library.css b/library.cssindex 5512d15..c8d7e8c 100644--- a/library.css+++ b/library.css@@ -1122,32 +1122,45 @@ details:not([open]) > .selection-menu-panel { display: none; }.pdf-page-viewport canvas { display: block; max-width: none; margin: 0 auto; background: #fff; box-shadow: 0 8px 24px rgba(0,0,0,.24); }.document-text-reader { width: 100%; border: 1px solid var(--line); border-radius: 10px; padding: 18px; background: var(--raised); }.document-text-reader pre { margin: 12px 0 0; overflow: auto; color: var(--ink); font: inherit; font-size: 13px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }-.article-document-reader { display: grid; gap: 16px; padding: 22px; border-bottom: 1px solid var(--line); background: var(--card); }+.article-document-reader { display: grid; min-width: 0; gap: 16px; padding: 22px; border-bottom: 1px solid var(--line); background: var(--card); font-weight: 400; }.article-document-reader h1, .article-document-reader h2, .article-document-reader h3, .article-document-reader h4, .article-document-reader h5, .article-document-reader h6 { margin: 12px 0 0; color: var(--ink); line-height: 1.35; }.article-document-reader p, .article-document-reader blockquote, .article-document-reader pre { margin: 0; color: var(--ink); font-size: 14px; line-height: 1.8; white-space: pre-wrap; overflow-wrap: anywhere; }.article-document-reader blockquote { border-left: 3px solid var(--line-strong); padding-left: 14px; color: var(--muted); }+.article-document-reader > * { min-width: 0; }+.article-document-reader ul, .article-document-reader ol { margin: 0; padding-left: 1.5em; font-size: 14px; line-height: 1.8; overflow-wrap: anywhere; }+.article-document-reader li + li { margin-top: .3em; }+.is-article-detail .detail-header-section { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: 10px 16px; }+.is-article-detail .detail-header-section > .detail-title { grid-column: 1; padding-right: 0; margin: 0; font-size: 20px; line-height: 1.45; }+.is-article-detail .detail-header-section > .entry-editor-inline { display: contents; }+.is-article-detail .entry-editor-inline > summary { position: static; grid-column: 2; grid-row: 1; white-space: nowrap; }+.is-article-detail .entry-editor-inline > .entry-editor-body { grid-column: 1 / -1; grid-row: 4; }+.is-article-detail .detail-header-section > .detail-meta { grid-column: 1; }+.is-article-detail .detail-header-section > .palette { grid-column: 1 / -1; }.article-document-reader pre { overflow: auto; border-radius: 8px; padding: 12px; background: var(--raised); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }.article-document-media { display: grid; gap: 7px; margin: 0; }.article-document-image { display: block; max-width: 100%; max-height: 78dvh; margin: 0 auto; border-radius: 8px; object-fit: contain; cursor: zoom-in; }.article-document-media figcaption { color: var(--muted); font-size: 11px; line-height: 1.5; }.article-document-video .detail-video-wrap, .article-document-video .detail-video { width: 100%; }-.article-document-resource { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; border: 1px solid var(--line); border-radius: 8px; padding: 12px; background: var(--raised); }+.article-document-resource { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; border: 1px solid var(--line); border-radius: 8px; padding: 12px; background: var(--raised); }+.article-document-resource > strong { flex: 1; min-width: 0; overflow-wrap: anywhere; }+.article-document-resource .media-open-link { white-space: nowrap; }.article-document-resource-type { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 7px; color: var(--accent-ink); background: var(--accent-soft); font-size: 10px; font-weight: 850; }-.article-document-resource small { grid-column: 2 / -1; color: var(--muted); }+.article-document-resource small { color: var(--muted); }.article-media-library { padding: 16px 22px; border-bottom: 1px solid var(--line); }.article-media-library > summary { cursor: pointer; font-size: 12px; font-weight: 800; }.article-media-library > .detail-visual-gallery { margin-top: 12px; }.captured-post-view { display: grid; gap: 14px; padding: 20px 22px; border-bottom: 1px solid var(--line); background: var(--card); }-.captured-post-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; }+.captured-post-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 12px; }.captured-post-heading h3 { margin: 0; }.captured-post-heading small { color: var(--muted); }-.captured-post-text { margin: 0; color: var(--ink); font-size: 15px; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }+.captured-post-text { margin: 0; color: var(--ink); font-size: 15px; font-weight: 400; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }.captured-post-editor { min-height: 180px; line-height: 1.7; }.captured-post-actions { display: flex; flex-wrap: wrap; gap: 8px; }.captured-post-media { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }.compact-captured-media { display: grid; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 9px; background: var(--raised); }.compact-captured-media > img { display: block; width: 100%; max-height: 420px; object-fit: contain; cursor: zoom-in; }-.compact-media-link { position: relative; display: grid; min-height: 116px; place-items: center; overflow: hidden; padding: 14px; color: var(--ink); text-align: center; text-decoration: none; }+.compact-media-link { position: relative; display: grid; min-height: 44px; place-items: center; overflow: hidden; padding: 12px; color: var(--ink); text-align: center; text-decoration: none; }+.compact-media-link.has-poster { min-height: 116px; aspect-ratio: 16 / 9; }.compact-media-link img { position: absolute; width: 100%; height: 100%; object-fit: cover; inset: 0; }.compact-media-link img + strong { position: relative; z-index: 1; border-radius: 999px; padding: 8px 12px; color: #fff; background: rgba(0, 0, 0, .72); }.unplaced-media-section { display: grid; gap: 10px; }@@ -1421,7 +1434,10 @@ details:not([open]) > .selection-menu-panel { display: none; }.entry-original-summary .prompt-read-body:empty { display: none; }.entry-original-summary .prompt-expand { display: none; }.entry-original-summary .prompt-editor { min-height: 220px; resize: vertical; }-.article-editor-toolbar { display: flex; justify-content: flex-end; gap: 8px; padding: 8px 0; }+.article-editor-toolbar { display: flex; align-items: center; gap: 8px; }+.article-reader-context { display: flex; flex-wrap: wrap; gap: 2px 8px; flex: 1; min-width: 0; color: var(--muted); font-size: 11px; line-height: 1.6; overflow-wrap: anywhere; }+.article-reader-context > span { flex: none; max-width: 100%; overflow-wrap: anywhere; }+.article-editor-toolbar button { flex-shrink: 0; white-space: nowrap; }.article-document-reader [contenteditable="plaintext-only"] { outline: 1px solid var(--line); border-radius: 6px; padding: 10px; background: var(--raised); white-space: pre-wrap; }.article-document-reader [contenteditable="plaintext-only"]:focus { outline: 2px solid var(--accent); }.media-thumb-play { position: absolute; right: 4px; bottom: 4px; padding: 1px 4px; border-radius: 4px; color: white; background: rgba(0,0,0,.72); font-size: 11px; }diff --git a/library.js b/library.jsindex 4aeaad6..9234739 100644--- a/library.js+++ b/library.js@@ -1,8 +1,9 @@import { attachArticleEditor } from "./article-editor.js";+import { renderArticleBlockText } from "./article-text-view.js";import { libraryTitleForLocale, libraryTitleForStorage, renderLibraryJson, screenshotStorageKey } from "./lib.js";import { readImageDimensions } from "./image-metadata.js";import { readVideoMedia } from "./browser-video-media.js";-import { mediaFormatLabel, usesArticleReader } from "./case-presentation.js";+import { mediaFormatLabel, usesArticleReader, usesPostReader } from "./case-presentation.js";import { deleteScreenshotBlob, getScreenshotBlob, saveScreenshotBlob } from "./image-store.js";import {assertStorageCapacity,@@ -4985,6 +4986,7 @@ function bindDetailSidebarResize() {elements.detailResizer.classList.add("is-resizing");event.preventDefault();});+ const presentation = usesArticleReader(entry) ? "article" : usesPostReader(entry) ? "post" : "case";elements.detailResizer.addEventListener("pointermove", (event) => {if (event.pointerId !== pointerId) return;const width = detailSidebarRuntimeWidth(startWidth + startX - event.clientX);@@ -5024,12 +5026,14 @@ function clearFilters() {renderGallery();}+ body.dataset.presentation = presentation;function openUnassignedView() {selectedCollectionId = "";unassignedViewActive = true;caseOrderManagementActive = false;projectOrderManagementActive = false;selectedContentId = "";+ elements.detailContent.classList.toggle("is-article-detail", presentation !== "case" && !entry.compoundCase);selectedFacets.clear();elements.pendingFilter.checked = false;elements.searchInput.value = "";@@ -5109,15 +5113,15 @@ async function renderDetail({ resetScroll = false } = {}) {const mountedBody = elements.detailContent.querySelector(".detail-primary > .detail-body");const mountedArticle = mountedBody?.querySelector(":scope > .article-document-reader");if (!resetScroll && usesArticleReader(entry) && elements.detailDrawer.dataset.entryId === entry.id- && mountedBody?.dataset.mediaIdentity === mediaIdentity+ && mountedBody?.dataset.mediaIdentity === mediaIdentity && mountedBody.dataset.presentation === presentation&& (mountedArticle?.dataset.editing === "true" || mountedArticle?.dataset.articleIdentity === JSON.stringify(normalizeEntryMedia(entry).articleDocument))) {const header = mountedBody.querySelector(":scope > .detail-header-section");if (header) replaceDetailSection(header, createDetailHeader(entry));refreshActiveDetailAssetSections(entry);return;}- if (!resetScroll && !entry.compoundCase && !isCapturedPost(entry) && !usesArticleReader(entry)- && elements.detailDrawer.dataset.entryId === entry.id && mountedBody?.dataset.mediaIdentity === mediaIdentity) {+ if (!resetScroll && !entry.compoundCase && !usesPostReader(entry) && !usesArticleReader(entry)+ && elements.detailDrawer.dataset.entryId === entry.id && mountedBody?.dataset.mediaIdentity === mediaIdentity && mountedBody.dataset.presentation === presentation) {elements.detailContent.querySelector(".detail-visual-gallery")?.updateEntry?.(entry);refreshActiveDetailAssetSections(entry);// Editors stay mounted while open; updates to unrelated sections remain local.@@ -5146,7 +5150,7 @@ async function renderDetail({ resetScroll = false } = {}) {const body = el("div", "detail-body");body.dataset.mediaIdentity = mediaIdentity;const hasPrimaryMedia = entryHasMedia(entry);- const capturedPost = isCapturedPost(entry);+ const capturedPost = usesPostReader(entry);const hasArticleDocument = !capturedPost && usesArticleReader(entry);const usesStageNavigation = !capturedPost && !hasArticleDocument && (entryHasMedia(entry, "image") || entryHasMedia(entry, "video"));elements.detailContent.classList.toggle("has-primary-media", hasPrimaryMedia && !hasArticleDocument && !capturedPost);@@ -5220,7 +5224,7 @@ function invalidateDetailContent(entryId) {elements.detailDrawer.dataset.loadingEntryId = entryId;elements.drawerToolbar.prepend(elements.detailNavigation);elements.drawerToolbar.classList.add("has-document-navigation");- elements.detailContent.classList.remove("has-primary-media", "is-compound-detail");+ elements.detailContent.classList.remove("has-primary-media", "is-compound-detail", "is-article-detail");const loading = el("div", "detail-loading");loading.setAttribute("role", "status");loading.setAttribute("aria-label", `正在打开${entry?.title ? `:${entry.title}` : "案例"}`);@@ -5428,6 +5432,7 @@ function createCompoundOrganizer(entry) {renderOrder();const actions = el("div", "compound-organizer-actions");const save = textEl("button", "", "保存整理");+ link.classList.add("has-poster");save.addEventListener("click", async () => {const response = await perform(save, {type: "UPDATE_COMPOUND_CASE",@@ -5443,10 +5448,6 @@ function createCompoundOrganizer(entry) {return details;}-function isCapturedPost(entry) {- return entry?.sourceFacts?.pageType === "post";-}-function articleReferencedAssetIds(entry) {return new Set((entry?.articleDocument?.blocks || []).flatMap((block) => block.assetId ? [block.assetId] : []));}@@ -5463,6 +5464,7 @@ async function createCapturedPostView(entryValue) {heading.append(textEl("h3", "", "帖子文字"), rawTextEl("small", "", facts));section.append(heading);if (promptEditState?.entryId === entry.id && !promptEditState.assetId) {+ renderArticleBlockText(node, block);const textarea = document.createElement("textarea");textarea.className = "captured-post-editor";textarea.value = promptEditState.draftText;@@ -5511,6 +5513,9 @@ async function createCapturedPostView(entryValue) {renderDetail();});actions.append(copy, edit);+ contextParts: [entry.sourceFacts?.author, entry.sourceFacts?.handle ? `@${entry.sourceFacts.handle}` : "",+ entry.sourceFacts?.publishedAt ? formatDate(entry.sourceFacts.publishedAt) : ""].filter(Boolean),+ onCopy: button => copyTextWithFeedback(button, entry.text, "已复制", "浏览器未允许复制,请选中文字后复制"),section.append(actions);}const media = entry.mediaAssets.filter((asset) => asset.usage !== "poster");@@ -5582,7 +5587,7 @@ async function createArticleDocumentReader(entryValue) {continue;}if (["paragraph", "list", "quote", "code", "table"].includes(block.kind)) {- const tagName = block.kind === "quote" ? "blockquote" : block.kind === "code" || block.kind === "table" ? "pre" : "p";+ const tagName = block.kind === "quote" ? "blockquote" : block.kind === "list" ? "div" : block.kind === "code" || block.kind === "table" ? "pre" : "p";const node = rawTextEl(tagName, block.kind === "table" ? "article-table-text" : "", block.text);node.dataset.articleBlockId = block.id;reader.append(node);diff --git a/manifest.json b/manifest.jsonindex b374a02..4b11238 100644--- a/manifest.json+++ b/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "__MSG_extensionName__",- "version": "1.20.2",+ "version": "1.20.3","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/package-lock.json b/package-lock.jsonindex df6ad97..829effe 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "prompt-case-collector",- "version": "1.20.2",+ "version": "1.20.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "prompt-case-collector",- "version": "1.20.2",+ "version": "1.20.3","license": "Apache-2.0","dependencies": {"@jonahschulte/rtf-toolkit": "0.5.0",diff --git a/package.json b/package.jsonindex bf8be1f..1fed6c6 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "prompt-case-collector",- "version": "1.20.2",+ "version": "1.20.3","private": false,"license": "Apache-2.0","repository": "https://github.com/wchao6891/PromptDirector",diff --git a/page-capture-highlight.js b/page-capture-highlight.jsnew file mode 100644index 0000000..32b2da6--- /dev/null+++ b/page-capture-highlight.js@@ -0,0 +1,72 @@+// These functions run in the page's isolated world via chrome.scripting.+export function renderPageCaptureRegionPreview({ marker = "", targets = [], text = "", mediaIds = [], mediaUrls = [], edits = [], locate = false } = {}) {+ const id = "promptdirector-page-capture-region-preview";+ const attribute = "data-promptdirector-capture-highlight";+ document.getElementById(id)?.remove();+ document.querySelectorAll(`[${attribute}]`).forEach(element => element.removeAttribute(attribute));+ if (!marker) return { ok: true, count: 0 };+ const root = [...document.querySelectorAll("[data-promptdirector-capture-region]")]+ .find(element => element.getAttribute("data-promptdirector-capture-region") === marker);+ if (!root) return { ok: false };+ const clean = value => String(value || "").replace(/\s+/gu, " ").trim();+ const savedText = clean(text);+ const selectedMedia = new Set(mediaIds);+ const selectedUrls = new Set(mediaUrls);+ const resolved = new Set();+ for (const target of targets) {+ if (target.kind === "group") continue;+ let element;+ try { element = document.querySelector(target.path); } catch { continue; }+ if (!element) continue;+ if (target.kind === "text") {+ const value = clean(element.innerText || element.textContent);+ if (!value || !savedText.includes(value)) continue;+ } else if (!target.mediaIds?.some(id => selectedMedia.has(id))) continue;+ resolved.add(element);+ }+ // Added content can lie outside the original root. Its saved text/media,+ // rather than the parent container rectangle, determines the visible marks.+ const selector = "h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,table,img,video,iframe,a[href]";+ for (const edit of edits) {+ if (edit.mode !== "include") continue;+ let included;+ try { included = document.querySelector(edit.path); } catch { continue; }+ if (!included) continue;+ const leaves = [...included.querySelectorAll(selector)];+ if (included.matches(selector) || !leaves.length) leaves.unshift(included);+ for (const element of leaves) {+ const value = clean(element.innerText || element.textContent);+ const urls = [element.currentSrc, element.src, element.href, element.getAttribute("data-src")];+ if ((value && savedText.includes(value)) || urls.some(url => selectedUrls.has(url))) resolved.add(element);+ }+ }+ if (!resolved.size) return { ok: false };+ const style = document.createElement("style");+ style.id = id;+ style.textContent = `[${attribute}="true"]{outline:2px solid #809329!important;outline-offset:3px!important}`;+ document.documentElement.append(style);+ resolved.forEach(element => element.setAttribute(attribute, "true"));+ if (locate) [...resolved][0].scrollIntoView({ block: "center", inline: "nearest", behavior: "instant" });+ return { ok: true, count: resolved.size };+}++export function clearPageCapturePageState(options = {}) {+ if (options.removePreview !== false) {+ document.getElementById("promptdirector-page-capture-region-preview")?.remove();+ document.querySelectorAll("[data-promptdirector-capture-highlight]").forEach(element => element.removeAttribute("data-promptdirector-capture-highlight"));+ }+ if (options.removeEditor !== false) {+ const editor = document.getElementById("promptdirector-page-capture-region-editor");+ editor?.dispatchEvent(new Event("promptdirector-cancel"));+ editor?.remove();+ }+ for (const element of document.querySelectorAll("[data-promptdirector-page-edit-include],[data-promptdirector-page-edit-exclude],[data-promptdirector-page-edit-hover]")) {+ element.removeAttribute("data-promptdirector-page-edit-include");+ element.removeAttribute("data-promptdirector-page-edit-exclude");+ element.removeAttribute("data-promptdirector-page-edit-hover");+ }+ if (options.removeRegionMarkers) {+ for (const element of document.querySelectorAll("[data-promptdirector-capture-region]")) element.removeAttribute("data-promptdirector-capture-region");+ }+ return true;+}diff --git a/page-capture.js b/page-capture.jsindex b8cde4e..6fb1b66 100644--- a/page-capture.js+++ b/page-capture.js@@ -14,7 +14,7 @@ export function detectPageCaptureAdapter(value, adapters = PAGE_CAPTURE_ADAPTERSexport function pageCaptureDefaultMediaIds(candidateValue = {}) {return (normalizePageCaptureCandidate(candidateValue)?.media || [])- .filter((item) => item.placement === "inline" || item.isCover)+ .filter((item) => !item.quotedPostUrl && (item.placement === "inline" || item.isCover)).map((item) => item.id);}@@ -359,6 +359,11 @@ export function normalizePageCaptureCandidate(value = {}) {textBlocks,articleDocument,possibleOmissions: prepared.possibleOmissions,+ supplements: (Array.isArray(value.supplements) ? value.supplements : []).flatMap(item => {+ const text = normalizeText(item?.text);+ const sourceUrl = safeUrl(item?.sourceUrl);+ return text && sourceUrl ? [{ id: clean(item.id) || stableCandidateId(sourceUrl, text), text, sourceUrl, partial: item.partial === true }] : [];+ }),batchStructureStatus: value.batchStructureStatus === "review" ? "review" : value.batchStructureStatus === "matched" ? "matched" : "",region: normalizeCaptureRegion(value.region),excerpt: clean(value.excerpt),@@ -371,7 +376,8 @@ export function normalizePageCaptureCandidate(value = {}) {? value.extraction.method: "page",textBlockCount: textBlocks.length,- pendingMediaCount: positiveInteger(value.extraction?.pendingMediaCount, 0)+ pendingMediaCount: positiveInteger(value.extraction?.pendingMediaCount, 0),+ textTruncated: value.extraction?.textTruncated === true},adapter: clean(value.adapter) || "generic"};@@ -539,7 +545,7 @@ export function pageCapturePermissionOrigins(candidates = []) {const origins = new Set();for (const candidate of candidates) {for (const media of normalizePageCaptureCandidate(candidate)?.media || []) {- if (media.kind === "document" && !isSupportedDocumentMimeType(media.mimeType)) continue;+ if (media.localAssetId || media.kind === "document" && !isSupportedDocumentMimeType(media.mimeType)) continue;for (const value of [media.posterUrl, ...pageCaptureMediaFetchCandidates(media)]) {try {const url = new URL(value);@@ -671,6 +677,30 @@ export async function collectPageCaptureSnapshot(options = {}) {siteStatus: siteData.completeness === "complete" ? "complete" : "partial"};}+ if (adapter.id === "x" && !pageSelection) {+ const posts = [...document.querySelectorAll('article[data-testid="tweet"]')];+ const current = posts.find(post => ownPostLinks(post).some(link => sameUrl(link.href, canonicalUrl)));+ if (current || !wholePage) {+ const roots = current ? [current] : posts;+ const candidates = roots.slice(0, maxCandidates).flatMap((root, index) => {+ const candidate = candidateForRoot(root, index, {+ adapter, metadata, structured: [], article: null, siteData: null,+ canonicalUrl, pageType: "post", maxMedia+ });+ return candidate ? [candidate] : [];+ });+ if (current && candidates[0]) {+ const author = collectAdapterFields(current, adapter).handle;+ candidates[0].supplements = posts.filter(post => post !== current && author && collectAdapterFields(post, adapter).handle === author)+ .flatMap(post => {+ const content = xPostContent(post);+ const url = collectAdapterFields(post, adapter).canonicalUrl;+ return content?.text && url ? [{ id: "supplement:" + hashText(url), text: content.text, sourceUrl: url, partial: content.partial }] : [];+ });+ }+ return { id: sessionId, sourceUrl: canonicalUrl, adapter: adapter.id, candidates, capturedAt };+ }+ }const accumulated = new Map();const collectVisible = () => {if (contentRoot || siteData?.pageKind === "detail") return [];@@ -973,10 +1003,61 @@ export async function collectPageCaptureSnapshot(options = {}) {};}+ function ownPostLinks(root) {+ return [...root.querySelectorAll('a[href*="/status/"]')].filter(link =>+ link.querySelector("time") && !link.closest('[role="link"][data-testid="quoteTweet"], [data-testid="quoteTweet"], [role="link"][tabindex="0"]'));+ }++ function copyPostInline(source, target) {+ for (const child of source.childNodes) {+ if (child.nodeType === 3) target.append(child.cloneNode());+ else if (child.nodeType === 1) {+ const tag = child.tagName.toLowerCase();+ if (["button", "script", "style"].includes(tag)) continue;+ if (tag === "img") {+ if (child.alt) target.append(document.createTextNode(child.alt));+ } else if (tag === "br") target.append(document.createElement("br"));+ else {+ const inline = document.createElement(["a", "strong", "em", "b", "i", "code"].includes(tag) ? tag : "span");+ if (tag === "a" && safeHttpUrl(child.href)) inline.setAttribute("href", child.href);+ if (["div", "p"].includes(tag)) target.append(document.createTextNode("\n"));+ copyPostInline(child, inline);+ target.append(inline);+ if (["div", "p"].includes(tag)) target.append(document.createTextNode("\n"));+ }+ }+ }+ }++ function xPostContent(root) {+ const texts = [...root.querySelectorAll('[data-testid="tweetText"]')];+ if (!texts.length && !root.querySelector("video, [data-testid=tweetPhoto]")) return null;+ const fragment = document.createElement("div");+ const content = [];+ for (const node of texts) {+ const value = cleanBlockText(node.innerText || node.textContent);+ if (!value) continue;+ const quote = node.closest('[data-testid="quoteTweet"], [role="link"][tabindex="0"]');+ const p = document.createElement(quote ? "blockquote" : "p");+ // Keep inline links and paragraph breaks, without nesting tweet divs inside paragraphs.+ copyPostInline(node, p);+ fragment.append(p);+ content.push({ id: "text:x:" + hashText(value), text: value, html: p.outerHTML,+ kind: quote ? "quote" : "paragraph", relevance: "explicit-creative", sourceOrder: content.length });+ }+ const media = collectMedia(root, maxMedia).filter(item => item.kind !== "image" ||+ !/profile_images|profile_banners/u.test(item.url));+ return { text: content.map(b => b.text).join("\n\n"), html: fragment.innerHTML, textBlocks: content, media,+ partial: Boolean(root.querySelector('[data-testid="tweet-text-show-more-link"]')) };+ }+function candidateForRoot(root, index, context) {const isPageRoot = root === document.body || root === context.pageRoot;const siteData = isPageRoot ? context.siteData : null;const adapterFields = collectAdapterFields(root, context.adapter);+ const capturePost = context.adapter.id === "x" && !context.pageSelection && !options.editedRegion?.token;+ const post = capturePost ? xPostContent(root) : null;+ if (capturePost && !post) return null;const cardLink = isPageRoot || context.pageType === "article" ? "" : safeHttpUrl(root.querySelector("a[href]")?.href);const canonicalUrl = adapterFields.canonicalUrl || cardLink || safeHttpUrl(siteData?.canonicalUrl) || context.canonicalUrl;const structured = context.structured.find((item) => sameUrl(item.url || item.mainEntityOfPage, canonicalUrl)) || context.structured[0] || {};@@ -985,10 +1066,10 @@ export async function collectPageCaptureSnapshot(options = {}) {: adapterFields.title || root.querySelector("h1,h2,h3,[role=heading]")?.textContent || structured.headline || structured.name || (context.pageType === "post" ? "" : root.querySelector("img[alt]")?.alt));const pageSelection = isPageRoot ? context.pageSelection : null;const articleText = context.pageType === "article" ? context.article?.textContent : "";- const text = cleanBlockText(context.contentRoot ? root.innerText : isPageRoot+ const text = post ? post.text : cleanBlockText(context.contentRoot ? root.innerText : isPageRoot? pageSelection?.text || articleText || siteData?.contentText || context.article?.textContent || structured.articleBody || root.innerText || context.metadata.description: root.innerText || root.textContent);- const contentHtml = context.contentRoot ? root.innerHTML : isPageRoot+ const contentHtml = post ? post.html : context.contentRoot ? root.innerHTML : isPageRoot? pageSelection?.html || context.article?.content || "": "";const structuredTextBlocks = !context.contentRoot && !articleText && siteData?.contentText@@ -1001,9 +1082,9 @@ export async function collectPageCaptureSnapshot(options = {}) {sourceOrder: 0}]: null;- const textBlocks = pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);+ const textBlocks = post?.textBlocks || pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);const siteMedia = Array.isArray(siteData?.media) ? siteData.media : [];- const domMedia = pageSelection || root.isConnected === false ? [] : collectMedia(root, context.maxMedia);+ const domMedia = post?.media || (pageSelection || root.isConnected === false ? [] : collectMedia(root, context.maxMedia));const pairedDomIds = new Set();const pairedSiteMedia = siteMedia.map((item) => {const visible = domMedia.find((candidate) => mediaValuesOverlap(item, candidate));@@ -1025,6 +1106,16 @@ export async function collectPageCaptureSnapshot(options = {}) {...domMedia.filter((item) => !pairedDomIds.has(item.id))], context.maxMedia);const article = collectArticleDocument(root, contentHtml, textBlocks, media, context.maxMedia);+ if (capturePost) {+ for (const item of media.filter(item => item.postPhotoUrl)) {+ item.quotedPostUrl = sameUrl(item.postPhotoUrl, canonicalUrl) ? "" : item.postPhotoUrl;+ item.originalWorkUrl = item.postPhotoUrl;+ if (!article.blocks.some(block => block.assetId === item.id)) article.blocks.push({+ id: `article:photo:${item.id}`, kind: "image", assetId: item.id, sourceUrl: item.url,+ sourceOrder: article.blocks.length+ });+ }+ }media = mergeCollectedMedia([...media, ...article.media], context.maxMedia);if (!title && !text && !media.length) return null;const pageType = isPageRoot || context.pageType === "article" ? context.pageType : ["post", "video"].includes(context.adapter.pageType) ? context.adapter.pageType : "artwork";@@ -1039,7 +1130,7 @@ export async function collectPageCaptureSnapshot(options = {}) {? "selection": siteData?.sourceFacts?.extractionMethod === "structured" ? "structured": context.article?.content ? "readability" : structured.articleBody ? "structured" : "page";- const complete = siteData?.completeness === "complete" || Boolean(title && (text || media.length));+ const complete = !post?.partial && (siteData?.completeness === "complete" || Boolean(title && (text || media.length)));const region = markCaptureRegion(root, index, text, media.length);if (region && root.isConnected !== false) {region.contentTargets = collectContentTargets(@@ -1082,6 +1173,7 @@ export async function collectPageCaptureSnapshot(options = {}) {},completeness: complete ? "complete" : "partial",extraction: {+ textTruncated: post?.partial === true,scope: captureScope,method: extractionMethod,textBlockCount: textBlocks.length@@ -1533,7 +1625,8 @@ export async function collectPageCaptureSnapshot(options = {}) {function isVideoUrl(value) {try {const url = new URL(value);- return /\.(?:mp4|webm|mov)(?:$|[?#])/iu.test(url.pathname) || ["youtube.com", "youtu.be", "vimeo.com", "bilibili.com", "douyin.com", "x.com"].some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`));+ if (["x.com", "twitter.com"].some(host => url.hostname === host || url.hostname.endsWith(`.${host}`))) return /^\/[^/]+\/status\/\d+\/video\/\d+\/?$/u.test(url.pathname);+ return /\.(?:mp4|webm|mov)(?:$|[?#])/iu.test(url.pathname) || ["youtube.com", "youtu.be", "vimeo.com", "bilibili.com", "douyin.com"].some((host) => url.hostname === host || url.hostname.endsWith(`.${host}`));} catch {return false;}@@ -1649,9 +1742,9 @@ export async function collectPageCaptureSnapshot(options = {}) {title: firstText(fields.title),author: firstText(fields.author),handle: handleFromLink(fields.handle),- canonicalUrl: firstUrl(fields.canonicalUrl),+ canonicalUrl: adapter.id === "x" ? safeHttpUrl(ownPostLinks(root)[0]?.href) : firstUrl(fields.canonicalUrl),model: firstText(fields.model),- publishedAt: firstText(fields.publishedAt),+ publishedAt: adapter.id === "x" ? cleanText(ownPostLinks(root)[0]?.querySelector("time")?.dateTime) : firstText(fields.publishedAt),engagement};}@@ -1691,6 +1784,7 @@ export async function collectPageCaptureSnapshot(options = {}) {kind,url,posterUrl,+ postPhotoUrl: xPostPhotoUrl(element),alt: cleanText(element.alt),width: imageSource?.declaredWidth || (responsiveCandidate ? 0 : Number(element.naturalWidth || element.videoWidth || element.width) || 0),height: responsiveCandidate ? 0 : Number(element.naturalHeight || element.videoHeight || element.height) || 0,@@ -1711,7 +1805,7 @@ export async function collectPageCaptureSnapshot(options = {}) {const url = safeHttpUrl(match?.[1]);const rect = element.getBoundingClientRect();if (!url || sameUrl(url, location.href) || rect.width < 48 || rect.height < 48) continue;- media.push({ id: `background:${hashText(url)}`, kind: "image", url, posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background", sourceKind: "css-background", variants: [{ url, sourceKind: "css-background", width: element.clientWidth, height: element.clientHeight }] });+ media.push({ id: `background:${hashText(url)}`, kind: "image", url, postPhotoUrl: xPostPhotoUrl(element), posterUrl: "", alt: "", width: element.clientWidth, height: element.clientHeight, captureMethod: "css-background", sourceKind: "css-background", variants: [{ url, sourceKind: "css-background", width: element.clientWidth, height: element.clientHeight }] });if (media.length >= limit) break;}}@@ -1922,14 +2016,24 @@ export async function collectPageCaptureSnapshot(options = {}) {return candidates;}+ function xPostPhotoUrl(element) {+ if (!["x.com", "twitter.com"].includes(location.hostname) || !element.closest('article[data-testid="tweet"]')) return "";+ const link = element.closest('a[href*="/photo/"]');+ const url = safeHttpUrl(link?.href);+ if (!url) return "";+ const match = new URL(url).pathname.match(/^\/([^/]+)\/status\/(\d+)\/photo\/\d+\/?$/);+ return match ? new URL(`/${match[1]}/status/${match[2]}`, url).href : "";+ }+function isExcludedMedia(element) {- if (element.closest("nav,aside,header,[role=banner],[aria-label*=广告],[aria-label*=advertisement]")) return true;+ const postPhoto = Boolean(xPostPhotoUrl(element));+ if (!postPhoto && element.closest("nav,aside,header,[role=banner],[aria-label*=广告],[aria-label*=advertisement]")) return true;const rect = element.getBoundingClientRect();if (rect.width <= 0 || rect.height <= 0 || rect.width < 48 || rect.height < 48) return true;const style = typeof globalThis.getComputedStyle === "function" ? globalThis.getComputedStyle(element) : null;- if (style?.display === "none" || style?.visibility === "hidden" || Number(style?.opacity) === 0) return true;+ if (style?.display === "none" || style?.visibility === "hidden" || !postPhoto && Number(style?.opacity) === 0) return true;const description = `${element.alt || ""} ${element.className || ""} ${element.id || ""} ${element.getAttribute?.("aria-label") || ""}`.toLowerCase();- return /avatar|emoji|icon|logo|badge|advert|qr[-_ ]?code|二维码/.test(description);+ return !postPhoto && /avatar|emoji|icon|logo|badge|advert|qr[-_ ]?code|二维码/.test(description);}function isContentRoot(root) {@@ -2011,11 +2115,15 @@ function uniqueMedia(values) {const id = clean(value?.id) || stableCandidateId(url || posterUrl || dataUrl || previewDataUrl, value?.kind);const keyUrl = url || posterUrl;const kind = ["video", "document", "attachment"].includes(value?.kind) ? value.kind : "image";- if (!keyUrl && !dataUrl && !previewDataUrl) continue;+ const localAssetId = clean(value?.localAssetId);+ if (!keyUrl && !dataUrl && !previewDataUrl && !localAssetId) continue;const item = {id,kind,placement: value?.placement === "inline" ? "inline" : "unplaced",+ ...(localAssetId ? { localAssetId } : {}),+ ...(value?.contentHash ? { contentHash: clean(value.contentHash) } : {}),+ ...(safeUrl(value?.quotedPostUrl) ? { quotedPostUrl: safeUrl(value.quotedPostUrl) } : {}),...(value?.isCover === true && kind === "image" ? { isCover: true } : {}),url,posterUrl,@@ -2068,12 +2176,13 @@ function uniqueMedia(values) {return items;}-function pageCaptureMediaIdentity(value) {+export function pageCaptureMediaIdentity(value) {try {const url = new URL(value);for (const key of [...url.searchParams.keys()]) {if (/^(?:w|width|h|height|q|quality|resize|size|dpr|format)$/iu.test(key)) url.searchParams.delete(key);}+ if (url.hostname === "pbs.twimg.com" && url.pathname.startsWith("/media/")) url.searchParams.delete("name");url.hash = "";return url.href;} catch {diff --git a/test/capture-additions.test.js b/test/capture-additions.test.jsnew file mode 100644index 0000000..5c04a48--- /dev/null+++ b/test/capture-additions.test.js@@ -0,0 +1,55 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { appendCaptureCandidate, draftCaptureAddition, savedDraftCaptureItems } from '../capture-additions.js';+import { normalizePageCaptureCandidate, normalizePageCaptureBatch, applyPageCaptureSelections, pageCaptureDefaultMediaIds } from '../page-capture.js';+const candidate = () => normalizePageCaptureCandidate({id:'main',title:'main',canonicalUrl:'https://x.com/user/status/1',contentText:'Original',+ textBlocks:[{id:'body',kind:'paragraph',relevance:'explicit-creative',text:'Original'}],articleDocument:{blocks:[{id:'body',kind:'paragraph',relevance:'explicit-creative',text:'Original'}]},+ media:[{id:'one',url:'https://pbs.twimg.com/media/image?format=jpg&name=small',kind:'image',placement:'inline'},+ {id:'quote',url:'https://pbs.twimg.com/media/quote',kind:'image',placement:'inline',quotedPostUrl:'https://x.com/user/status/2'}]});+const selection={candidateId:'main',selectedTextBlockIds:candidate().textBlocks.map(b=>b.id),selectedMediaIds:['one'],mediaDecision:'confirmed'};+test('quoted images remain optional while the main image group is selected',()=>assert.deepEqual(pageCaptureDefaultMediaIds(candidate()),['one']));+test('appending selected text and local media preserves prior selections and saves one complete candidate',()=>{+ const draft={id:'draft',fragments:[{id:'f',text:'Extra selected text'}],visuals:[{id:'local',mimeType:'image/avif'}]};+ const addition=draftCaptureAddition(draft);+ const result=appendCaptureCandidate(candidate(),addition,selection);+ const [saved]=applyPageCaptureSelections(normalizePageCaptureBatch({candidates:[result.candidate],selections:[result.selection]}));+ assert.match(saved.contentText,/Original/);assert.match(saved.contentText,/Extra selected text/);+ assert.equal(saved.media.length,2);assert.equal(saved.media[1].localAssetId,'local');assert.equal(saved.media[1].mimeType,'image/avif');+ assert.ok(!result.selection.selectedMediaIds.includes('quote'));+ assert.equal(draftCaptureAddition(draft,new Set(addition.consumed)).media.length,0);+});+test('duplicate image URLs and text do not override exclusions or grow the draft',()=>{+ const base=candidate();+ const addition={...base,id:'again',media:[{...base.media[0],id:'same-original',url:'https://pbs.twimg.com/media/image?name=orig&format=jpg'}]};+ const result=appendCaptureCandidate(base,addition,{...selection,selectedMediaIds:[]});+ assert.equal(result.candidate.media.length,2);assert.equal(result.candidate.textBlocks.length,1);assert.deepEqual(result.selection.selectedMediaIds,[]);+});++test('text-only save retains local images and excluded fragments in the pending draft', () => {+ const draft = { id: 'draft', fragments: [{ id: 'saved', text: 'keep' }, { id: 'excluded', text: 'later' }], visuals: [{ id: 'image' }] };+ const consumed = new Set(['text:saved', 'text:excluded', 'image:image']);+ const selected = [{ textBlocks: [{ id: 'added:draft:saved', text: 'edited keep' }], media: [] }];+ assert.deepEqual(savedDraftCaptureItems(draft, selected, consumed), [{ kind: 'text', id: 'saved' }]);+ assert.deepEqual(savedDraftCaptureItems(draft, [], consumed), []);+});+test('identical local image bytes with a new selection ID stay as one image', () => {+ const draft = { id: 'draft', fragments: [], visuals: [{ id: 'local1', contentHash: 'a'.repeat(64) }] };+ const first = appendCaptureCandidate(candidate(), draftCaptureAddition(draft), selection);+ const nextDraft = { ...draft, visuals: [{ ...draft.visuals[0], id: 'local2' }] };+ const second = appendCaptureCandidate(first.candidate, draftCaptureAddition(nextDraft), first.selection);+ assert.equal(second.candidate.media.filter(m => m.localAssetId).length, 1);+ assert.deepEqual(savedDraftCaptureItems(nextDraft, [second.candidate], new Set(['image:local2'])), [{ kind: 'image', id: 'local2' }]);+});++test('adding a webpage preserves headings and quotes without repeating original section text', () => {+ const base = candidate();+ const addition = normalizePageCaptureCandidate({ id: 'article', title: 'Supplement', pageType: 'article', canonicalUrl: 'https://example.com/article',+ textBlocks: [{ id: 'heading', kind: 'heading', text: 'A heading' }, { id: 'quote', kind: 'quote', text: 'A quoted creative direction.' }],+ articleDocument: { blocks: [{ id: 'heading', kind: 'heading', text: 'A heading' }, { id: 'quote', kind: 'quote', text: 'A quoted creative direction.' }] } });+ const result = appendCaptureCandidate(base, addition, selection);+ const blocks = result.candidate.articleDocument.blocks;+ assert.equal(blocks.filter(b => b.text === 'Original').length, 1);+ assert.ok(blocks.some(b => b.kind === 'heading' && b.text === 'A heading'));+ assert.ok(blocks.some(b => b.kind === 'quote' && b.text === 'A quoted creative direction.'));+ assert.equal(blocks.map(b => b.text || '').join(' ').match(/A quoted creative direction/g).length, 1);+});diff --git a/test/capture-permission-flow.test.js b/test/capture-permission-flow.test.jsindex 2328e95..2471a38 100644--- a/test/capture-permission-flow.test.js+++ b/test/capture-permission-flow.test.js@@ -224,13 +224,13 @@ test("collector presents one compact first-use authorization and resumes only thassert.match(html, /一次授权,之后直接采集/);assert.match(html, /统一开启网页读取与截图能力/);assert.match(html, /id="capture-permission-clipboard"[^>]*checked/);- assert.match(html, /仅在你主动点击“提取文字\/图片”且网页没有高亮内容时读取/);+ assert.match(html, /仅在你点击“剪贴板”时读取/);assert.match(html, /不会自动保存案例/);assert.match(source, /pendingCaptureAction = \{ action, permissionStatus \}/);assert.match(source, /await pending\.action\(\{ clipboardPreferenceJustDeclined: !includeClipboard \}\)/);const cancelFlow = source.slice(source.indexOf("function cancelCapturePermissionOnboarding"), source.indexOf("async function confirmCapturePermissionOnboarding"));assert.doesNotMatch(cancelFlow, /storage\.local\.set|pending\.action/);- const autoFlow = source.slice(source.indexOf("async function tryAutoSelection"), source.indexOf("async function extractClipboardOrSelection"));+ const autoFlow = source.slice(source.indexOf("async function tryAutoSelection"), source.indexOf("async function extractPageSelection"));assert.doesNotMatch(autoFlow, /readClipboardContentAfterFocus|ensureClipboardReadPermission/);});@@ -240,7 +240,7 @@ test("declining clipboard is honored for the original action and later enablemenreadFile(new URL("collector.html", projectRoot), "utf8")]);const fallback = source.slice(- source.indexOf("async function extractClipboardOrSelection"),+ source.indexOf("async function extractClipboard("),source.indexOf("function cancelClipboardPermissionEnable"));assert.match(fallback, /clipboardPreferenceJustDeclined/);diff --git a/test/capture-runtime-wiring.test.js b/test/capture-runtime-wiring.test.jsindex 4e06e53..c76709e 100644--- a/test/capture-runtime-wiring.test.js+++ b/test/capture-runtime-wiring.test.js@@ -50,13 +50,13 @@ test("creative result capture and metadata commit cross both queues as one transassert.ok(transaction.indexOf("dispatchCaptureMessage") < transaction.indexOf("commitCreativeOutputsTransaction"));});-test("a text-bearing captured post is classified from its text instead of its video attachment", async () => {+test("captured posts retain real media facts when suggesting a case category", async () => {const source = await readFile(new URL("../background.js", import.meta.url), "utf8");const start = source.indexOf("async function commitPageCapture");const end = source.indexOf("async function", start + 20);const save = source.slice(start, end);- assert.match(save, /candidate\.sourceFacts\.pageType === "post" && base\.text/);- assert.match(save, /classificationMediaAssets/);+ assert.match(save, /classifyContent\(\{ \.\.\.base, sourceFacts: candidate\.sourceFacts, mediaAssets \}/);+ assert.doesNotMatch(save, /classificationMediaAssets/);});test("restoring an overwritten screenshot marks that existing media id dirty", async () => {diff --git a/test/capture_additions_e2e.py b/test/capture_additions_e2e.pynew file mode 100644index 0000000..4ee58c0--- /dev/null+++ b/test/capture_additions_e2e.py@@ -0,0 +1,124 @@+"""Capture transports are fixtures; draft writes, merge, media storage and final save are real."""+from playwright.sync_api import expect+from pathlib import Path+import tempfile+from e2e_support import extension_session++def main():+ with extension_session('capture-additions-', viewport={'width':390,'height':844}) as run:+ page=run.open_page('collector.html')+ run.seed_storage(page,{'entries':[], 'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-07T00:00:00Z','clipboardIncluded':True}})+ page.evaluate("""async()=>{+ const send=chrome.runtime.sendMessage.bind(chrome.runtime);+ const {createCaptureDraft,addDraftFragment,addDraftVisual}=await import('./capture-draft.js');+ const {saveScreenshotBlob}=await import('./image-store.js');+ async function image(id,color) {+ const canvas=document.createElement('canvas');canvas.width=100;canvas.height=120;+ const ctx=canvas.getContext('2d');ctx.fillStyle=color;ctx.fillRect(0,0,100,120);+ const blob=await new Promise(r=>canvas.toBlob(r,'image/png'));await saveScreenshotBlob(id,blob);+ return {id,mimeType:'image/png',width:100,height:120,sourceTitle:id};+ }+ const first=await image('first-image','#336699'), extra=await image('extra-image','#996633');+ window.makeImage=image;window.extraImage=extra; window.captureKinds=[];window.cancelScreenshot=false;+ const initial=createCaptureDraft({title:'已有草稿',fragments:[{id:'first-text',text:'已有的选中文字,必须与网页内容保存在同一个案例。',sourceUrl:'https://example.com/first'}],visuals:[first],customLabels:['保留标签']});+ await send({type:'UPDATE_CAPTURE_DRAFT',draft:initial});+ const snapshot={id:'web-batch',sourceUrl:'https://example.com/post',candidates:[{id:'main',canonicalUrl:'https://example.com/post',title:'网页的案例',pageType:'post',contentText:'网页主帖原始提示词:主体在漫展中自然行动,镜头记录人物与环境。',textBlocks:[{id:'main-text',kind:'section',text:'网页主帖原始提示词:主体在漫展中自然行动,镜头记录人物与环境。'}],media:[],sourceFacts:{provider:'example.com',pageType:'post'}}],selections:[]};+ window.webSnapshot=snapshot;+ chrome.permissions.contains=async()=>true;chrome.permissions.request=async()=>true;+ const query=chrome.tabs.query.bind(chrome.tabs);chrome.tabs.query=async q=>q.active?[{id:999,url:'https://example.com/post'}]:query(q);+ Object.defineProperty(navigator,'clipboard',{configurable:true,value:{read:async()=>[{types:['text/plain'],getType:async()=>new Blob(['剪贴板补充:保持动作连续。'],{type:'text/plain'})}]}});+ chrome.runtime.sendMessage=async m=>{+ if(m.type==='START_PAGE_CAPTURE')return {ok:true,batch:window.webSnapshot};+ if(m.type==='PREVIEW_PAGE_CAPTURE_REGION'||m.type==='CLEAR_PAGE_CAPTURE_MARKERS')return {ok:true};+ if(m.type==='START_SMART_VISUAL_SELECTION')return {ok:true,session:{sessionId:'smart',selectedCount:1,candidateCount:1}};+ if(m.type==='CANCEL_SMART_VISUAL_SELECTION')return {ok:true};+ if(['ADD_ACTIVE_SELECTION_TO_DRAFT','CONFIRM_SMART_VISUAL_SELECTION','CAPTURE_ACTIVE_TAB_TO_DRAFT'].includes(m.type)) {+ window.captureKinds.push(m.type);+ if(m.type==='CAPTURE_ACTIVE_TAB_TO_DRAFT'&&window.cancelScreenshot)return {ok:false,message:'已取消框选截图'};+ const current=(await send({type:'GET_CAPTURE_WORKSPACE'})).draft;+ const next=m.type==='ADD_ACTIVE_SELECTION_TO_DRAFT'+ ? addDraftFragment(current,{id:'selected-extra',text:'网页高亮补充:使用自然光与清晰构图。',sourceUrl:'https://example.com/post'}).draft+ :addDraftVisual(current,extra);+ return send({type:'UPDATE_CAPTURE_DRAFT',draft:next});+ }+ return send(m);+ };+ }""")+ # Trigger ordinary focus refresh without losing transport fixtures.+ page.evaluate("()=>window.dispatchEvent(new Event('focus'))")+ expect(page.locator('#preview-state')).to_be_visible()+ page.locator('#add-page-capture').click()+ page.locator('.page-capture-confirm').click()+ expect(page.locator('.page-capture-excerpt')).to_contain_text('已有的选中文字')+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(1)+ expect(page.locator('#page-capture #capture-add-more-actions')).to_be_visible()+ for width in (320,390):+ page.set_viewport_size({'width':width,'height':844})+ boxes=page.locator('#capture-add-more-actions > button').evaluate_all('es=>es.map(e=>({top:e.getBoundingClientRect().top,h:e.getBoundingClientRect().height,overflow:e.scrollWidth>e.clientWidth}))')+ assert len(boxes)==5 and len({b['top'] for b in boxes})==1 and len({b['h'] for b in boxes})==1 and not any(b['overflow'] for b in boxes),boxes+ page.locator('#add-selection').click()+ expect(page.locator('.page-capture-excerpt')).to_contain_text('网页高亮补充')+ page.locator('#add-clipboard').click()+ expect(page.locator('.page-capture-excerpt')).to_contain_text('剪贴板补充')+ page.locator('#add-smart-visuals').click()+ expect(page.locator('#smart-selection')).to_be_visible()+ expect(page.locator('#page-capture')).to_be_hidden()+ page.locator('#smart-selection-cancel').click()+ expect(page.locator('#page-capture')).to_be_visible()+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(1)+ page.locator('#add-smart-visuals').click();page.locator('#smart-selection-confirm').click()+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)+ page.evaluate('()=>window.cancelScreenshot=true')+ page.locator('#add-screenshot').click()+ expect(page.locator('#page-capture')).to_be_visible()+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)+ page.evaluate('()=>window.cancelScreenshot=false')+ page.locator('#add-screenshot').click()+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)+ expect(page.locator('#page-capture')).to_be_visible()+ # Supplementary webpage cancel and confirmation both retain the current case.+ page.locator('#add-page-capture').click();page.locator('#page-capture-cancel').click()+ expect(page.locator('.page-capture-excerpt')).to_contain_text('剪贴板补充')+ page.locator('#add-page-capture').click();page.locator('.page-capture-confirm').click()+ expect(page.locator('.page-capture-thumbnails img')).to_have_count(2)+ expect(page.locator('.page-capture-excerpt')).to_contain_text('网页高亮补充')+ for width in (320,390):+ page.set_viewport_size({'width':width,'height':844})+ page.locator('#capture-add-more-actions').scroll_into_view_if_needed()+ page.screenshot(path=str(Path(tempfile.gettempdir()) / f'pd-capture-additions-{width}.png'))+ page.locator('#content-type').select_option('content:prompt:image')+ page.locator('#capture-collection').select_option('new-collection')+ page.locator('#capture-new-collection-name').fill('采集补充测试')+ page.locator('#page-capture-save').click()+ expect(page.locator('#page-capture')).to_be_hidden(timeout=15000)+ saved=page.evaluate("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries}")+ assert len(saved)==1,saved+ entry=saved[0]+ for text in ['已有的选中文字','网页主帖','网页高亮补充','剪贴板补充']:assert text in entry['text'],entry['text']+ assert len(entry['mediaAssets'])==2,entry['mediaAssets']+ assert '保留标签' in entry['customLabels'],entry+ assert entry['classification']['pathIds']==['content:prompt:image'],entry['classification']+ projects=page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).organizerState.collections")+ assert any(p['name']=='采集补充测试' and entry['id'] in p['entryIds'] for p in projects),projects+ blobs=page.evaluate("async ids=>{const {getMediaBlob}=await import('./media-store.js');return Promise.all(ids.map(async id=>(await getMediaBlob(id))?.size))}",[m['id'] for m in entry['mediaAssets']])+ assert all(blobs),blobs+ draft=page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_CAPTURE_WORKSPACE'})).draft")+ assert not draft['fragments'] and not draft['visuals'],draft+ # Text-only save must leave unsaved image bytes available in the draft.+ page.evaluate('''async()=>{+ const image=await window.makeImage('pending-image','#551133');+ const {createCaptureDraft}=await import('./capture-draft.js');+ await chrome.runtime.sendMessage({type:'UPDATE_CAPTURE_DRAFT',draft:createCaptureDraft({visuals:[image]})});+ window.webSnapshot={...window.webSnapshot,candidates:window.webSnapshot.candidates.map(c=>({...c,id:'second',canonicalUrl:'https://example.com/second'}))};+ window.dispatchEvent(new Event('focus'));+ }''')+ expect(page.locator('#preview-state')).to_be_visible()+ page.locator('#add-page-capture').click();page.locator('.page-capture-confirm').click()+ page.locator('#page-capture-save-text-only').click()+ expect(page.locator('#page-capture')).to_be_hidden()+ remaining=page.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_CAPTURE_WORKSPACE'})).draft")+ assert [v['id'] for v in remaining['visuals']]==['pending-image'],remaining+ assert page.evaluate("async()=>(await (await import('./image-store.js')).getScreenshotBlob('pending-image')).size")>0+ print({'text_only_keeps_image':True,'project_saved':True,'manual_type_saved':True})+ print({'one_case':True,'all_five_methods':True,'cancel_preserved':True,'duplicate_ignored':True,'media_readback':blobs,'tags_preserved':True,'widths':[320,390]})+if __name__=='__main__':main()diff --git a/test/case-presentation.test.js b/test/case-presentation.test.jsindex 1976b41..8ed5cbf 100644--- a/test/case-presentation.test.js+++ b/test/case-presentation.test.js@@ -1,14 +1,38 @@import test from "node:test";import assert from "node:assert/strict";-import { usesArticleReader, mediaFormatLabel } from "../case-presentation.js";+import { usesArticleReader, usesPostReader, mediaFormatLabel } from "../case-presentation.js";-test("captured prompt works use the media stage even when capture retains structured text", () => {+test("creative classifications open existing case details regardless of webpage origin", () => {const articleDocument = { blocks: [{ kind: "paragraph", text: "Original prompt" }] };- for (const pageType of ["video", "artwork", "post"]) {- assert.equal(usesArticleReader({ articleDocument, sourceFacts: { pageType } }), false);+ for (const id of ["content:prompt:image", "content:prompt:video", "content:image-case", "content:video-case"]) {+ for (const pageType of ["article", "post", "video", "artwork"]) {+ const entry = { classification: { pathIds: [id] }, articleDocument, sourceFacts: { pageType } };+ assert.equal(usesArticleReader(entry), false);+ assert.equal(usesPostReader(entry), false);+ assert.equal(usesPostReader({ ...entry, articleDocument: null }), false);+ }+ }+});++test("article roles retain structured reading including X quotes and media", () => {+ const articleDocument = { blocks: [{ kind: "quote", text: "Quoted context" }] };+ for (const id of ["content:tutorial", "content:reference"]) {+ for (const pageType of ["article", "post", "video", "artwork"]) {+ const entry = { classification: { pathIds: [id] }, articleDocument, sourceFacts: { pageType } };+ assert.equal(usesArticleReader(entry), true);+ assert.equal(usesPostReader(entry), false);+ }}- assert.equal(usesArticleReader({ articleDocument, sourceFacts: { pageType: "article" } }), true);assert.equal(usesArticleReader({ articleDocument }), true);+ assert.equal(usesPostReader({ sourceFacts: { pageType: "post" } }), true);+ assert.equal(usesArticleReader({ text: "Ordinary text case" }), false);+});++test("renamed and custom categories use their resolved purpose, not their display label", () => {+ const base = { articleDocument: { blocks: [{ kind: "paragraph", text: "text" }] }, sourceFacts: { pageType: "post" } };+ assert.equal(usesArticleReader({ ...base, contentRole: "prompt_video" }), false);+ assert.equal(usesPostReader({ ...base, contentRole: "prompt_video" }), false);+ assert.equal(usesArticleReader({ ...base, contentRole: "reference" }), true);});test("media format comes from recognized file metadata, never a creator's title", () => {diff --git a/test/clipboard_capture_e2e.py b/test/clipboard_capture_e2e.pyindex 0e2be81..5a679cb 100644--- a/test/clipboard_capture_e2e.py+++ b/test/clipboard_capture_e2e.py@@ -1,6 +1,9 @@from __future__ import annotationsimport re+import os+import tempfile+from pathlib import Pathfrom playwright.sync_api import expect@@ -36,7 +39,7 @@ def main() -> None:Object.defineProperty(chrome.tabs, 'query', {configurable: true,value: async query => query?.active- ? [{id: 999, url: 'chrome://extensions/', title: '扩展程序'}]+ ? [{id: 999, url: 'https://example.com/capture-fixture', title: 'Selection fixture'}]: originalQuery(query)});}@@ -76,7 +79,20 @@ def main() -> None:})""")assert collector.evaluate("window.__promptDirectorClipboardReads") == 0- collector.locator("#start-selection").click()+ for width in (320, 390):+ collector.set_viewport_size({'width': width, 'height':844})+ boxes=collector.locator('#normal-start .capture-actions button').evaluate_all("es=>es.map(e=>({top:e.getBoundingClientRect().top,height:e.getBoundingClientRect().height,overflow:e.scrollWidth>e.clientWidth}))")+ assert len(boxes)==5 and len({b['top'] for b in boxes[1:]})==1,boxes+ assert len({b['height'] for b in boxes[1:]})==1 and not any(b['overflow'] for b in boxes),boxes+ collector.locator('#start-selection').click()+ expect(collector.locator('#feedback')).to_contain_text('请先在网页中选中文字')+ assert collector.evaluate('window.__promptDirectorClipboardReads')==0+ expect(collector.locator('#preview-state')).to_be_hidden()+ screenshot_dir=Path(os.environ.get('PROMPTDIRECTOR_E2E_SCREENSHOT_DIR',tempfile.gettempdir()))+ screenshot_dir.mkdir(parents=True,exist_ok=True)+ collector.screenshot(path=str(screenshot_dir/'sidebar-entry-390.png'),full_page=True)++ collector.locator("#start-clipboard").click()expect(collector.locator("#preview-state")).to_be_visible()expect(collector.locator("#content-summary")).to_have_text("1 张图片")expect(collector.locator("#quick-preview .quick-visuals img")).to_have_count(1)@@ -88,15 +104,27 @@ def main() -> None:cleared_image_draft = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_CAPTURE_WORKSPACE'}).then(result => result.draft)")assert cleared_image_draft["visuals"] == [], cleared_image_draft- collector.locator("#start-selection").click()+ collector.locator("#start-clipboard").click()expect(collector.locator("#preview-state")).to_be_visible()expect(collector.locator("#content-summary")).to_have_text("1 张图片")assert collector.evaluate("window.__promptDirectorClipboardReads") == 2+ expect(collector.get_by_role('textbox',name='添加标签',exact=True)).to_be_visible()+ collector.get_by_role('textbox',name='添加标签',exact=True).fill('镜头参考')+ collector.get_by_role('textbox',name='添加标签',exact=True).press('Enter')+ expect(collector.locator('.tag-editor-chip')).to_contain_text('镜头参考')+ for width in (320,390):+ collector.set_viewport_size({'width':width,'height':844})+ assert collector.locator('#capture-add-more-actions > button').evaluate_all("es=>es.every(e=>e.scrollWidth<=e.clientWidth && getComputedStyle(e).whiteSpace==='nowrap')")+ expect(collector.get_by_role('textbox',name='添加标签',exact=True)).to_be_visible()+ tops=collector.locator('#capture-add-more-actions > *').evaluate_all('es=>es.map(e=>e.getBoundingClientRect().top)')+ assert len(set(tops))==1,tops+ collector.screenshot(path=str(screenshot_dir/'sidebar-image-draft-390.png'),full_page=True)collector.locator("#save-draft").click()expect(collector.locator("#start-state")).to_be_visible()saved = collector.evaluate("() => chrome.runtime.sendMessage({type: 'GET_STATE'}).then(result => result.entries)")assert len(saved) == 1 and len(saved[0]["mediaAssets"]) == 1, saved+ assert "镜头参考" in saved[0]["customLabels"],savedcollector.evaluate("window.dispatchEvent(new Event('focus'))")collector.wait_for_timeout(250)@@ -104,7 +132,7 @@ def main() -> None:assert collector.evaluate("window.__promptDirectorClipboardReads") == 2collector.evaluate("window.__promptDirectorClipboardMode = 'text'")- collector.locator("#start-selection").click()+ collector.locator("#start-clipboard").click()expect(collector.locator("#preview-state")).to_be_visible()expect(collector.locator("#quick-preview")).to_contain_text("第一段剪贴板文字")assert collector.evaluate("window.__promptDirectorClipboardReads") == 3@@ -122,7 +150,7 @@ def main() -> None:clipboardIncluded: false}})""")- collector.locator("#start-selection").click()+ collector.locator("#start-clipboard").click()expect(collector.locator("#clipboard-permission-dialog")).to_be_visible()assert collector.evaluate("window.__promptDirectorClipboardReads") == reads_before_declinecollector.locator("#clipboard-permission-cancel").click()diff --git a/test/collector-view.test.js b/test/collector-view.test.jsindex 21f83f3..8b93859 100644--- a/test/collector-view.test.js+++ b/test/collector-view.test.js@@ -70,12 +70,13 @@ test("page capture replaces failed remote thumbnails with an explicit unavailablassert.match(pageCaptureRenderer, /preview\.replaceChildren\(textNode\("span", t\("预览不可用"\)\)\)/);assert.match(pageCaptureRenderer, /pageCaptureMediaSourceLabel\(media\.sourceKind, media\.captureMethod\)/);const collectorHtml = await readFile(new URL("../collector.html", import.meta.url), "utf8");- assert.match(collectorHtml, /id="page-capture-help"[^>]*>确认一个主体后即可保存/);+ assert.match(collectorHtml, /id="page-capture-help"/);+ assert.match(collectorSource, /t\("选择要保存的内容"\)/);});test("page capture uses the final save as media authorization and keeps uncertain media separate", async () => {const [collectorSource, collectorHtml, backgroundSource] = await Promise.all([- readFile(new URL("../collector.js", import.meta.url), "utf8"),+ Promise.all(["../collector.js", "../collector-page-capture-view.js"].map(path => readFile(new URL(path, import.meta.url), "utf8"))).then(parts => parts.join("\n")),readFile(new URL("../collector.html", import.meta.url), "utf8"),readFile(new URL("../background.js", import.meta.url), "utf8")]);@@ -88,12 +89,12 @@ test("page capture uses the final save as media authorization and keeps uncertaiassert.match(pageCaptureRenderer, /pageCaptureDefaultMediaIds\(candidate\)/);assert.match(pageCaptureRenderer, /mediaDecision: "pending"/);assert.match(pageCaptureRenderer, /finalizePageCaptureSelectionsForSave/);- assert.match(pageCaptureRenderer, /t\("保存案例 · 含 \{count\} 项媒体"/);+ assert.match(pageCaptureRenderer, /t\("已选 \{count\} 项内容 · \{media\} 项媒体"/);assert.match(pageCaptureRenderer, /可能遗漏媒体/);assert.match(pageCaptureRenderer, /batchStructureStatus === "review"/);assert.match(pageCaptureRenderer, /updatePageCaptureMediaSelection/);assert.match(pageCaptureRenderer, /openPageCaptureMediaViewer/);- assert.match(pageCaptureRenderer, /possibleOmissions/);+ assert.match(collectorSource, /possibleOmissions/);assert.match(collectorHtml, /id="page-capture-media-review"/);assert.doesNotMatch(collectorHtml, /id="page-capture-confirm-media"/);assert.match(collectorHtml, /id="page-capture-save-text-only"/);@@ -184,9 +185,15 @@ test("the collector auto-reads only highlights and reserves clipboard access for);assert.match(focusFlow, /void tryAutoSelection\(\)/);assert.match(focusFlow, /void refreshPageCapturePermissionState\(\)/);- const autoFlow = collectorSource.slice(collectorSource.indexOf("async function tryAutoSelection"), collectorSource.indexOf("async function extractClipboardOrSelection"));+ const autoFlow = collectorSource.slice(collectorSource.indexOf("async function tryAutoSelection"), collectorSource.indexOf("async function extractPageSelection"));assert.doesNotMatch(autoFlow, /clipboard|readClipboardContentAfterFocus|ensureClipboardReadPermission/);- const explicitFlow = collectorSource.slice(collectorSource.indexOf("async function extractClipboardOrSelection"), collectorSource.indexOf("function render"));+ const explicitFlow = collectorSource.slice(collectorSource.indexOf("async function extractPageSelection"), collectorSource.indexOf("function render"));+ const selectionOnly = collectorSource.slice(collectorSource.indexOf("async function extractPageSelection"), collectorSource.indexOf("async function extractClipboard("));+ assert.doesNotMatch(selectionOnly, /readClipboard|extractClipboardContent|pendingClipboardButton/);+ const clipboardOnly = collectorSource.slice(collectorSource.indexOf("async function extractClipboard("), collectorSource.indexOf("function cancelClipboardPermissionEnable"));+ assert.doesNotMatch(clipboardOnly, /ADD_ACTIVE_SELECTION_TO_DRAFT/);+ assert.match(collectorHtml, /id="start-clipboard"/);+ assert.match(collectorHtml, /id="add-clipboard"/);assert.match(explicitFlow, /ADD_ACTIVE_SELECTION_TO_DRAFT/);assert.match(explicitFlow, /ensureClipboardReadPermission/);assert.match(explicitFlow, /readClipboardContentAfterFocus/);@@ -198,8 +205,8 @@ test("the collector auto-reads only highlights and reserves clipboard access forassert.match(backgroundSource, /case "TRY_ACTIVE_SELECTION_TO_DRAFT"/);assert.match(backgroundSource, /case "ADD_CLIPBOARD_TEXT_TO_DRAFT"/);assert.doesNotMatch(backgroundSource, /lastCommittedClipboardFingerprint/);- assert.match(collectorHtml, /id="start-selection"[^>]*>[\s\S]*?<strong[^>]*>提取文字\/图片<\/strong>/);- assert.match(collectorHtml, /id="add-selection"[^>]*>[\s\S]*?提取文字\/图片<\/button>/);+ assert.match(collectorHtml, /id="start-selection"[^>]*>[\s\S]*?<strong[^>]*>选区<\/strong>/);+ assert.match(collectorHtml, /id="add-selection"[^>]*>[\s\S]*?选区<\/span><\/button>/);assert.doesNotMatch(collectorHtml, /自动识别已复制文字|id="clipboard-access"|id="enable-clipboard"/);assert.doesNotMatch(collectorSource, /querySelectorAll\("button"\)/);assert.ok(collectorHtml.indexOf('id="start-smart-visuals"') < collectorHtml.indexOf('id="start-selection"'));@@ -211,11 +218,12 @@ test("the collector auto-reads only highlights and reserves clipboard access forassert.match(collectorHtml, /id="start-selection"[\s\S]*icon-file-text/);assert.match(collectorHtml, /id="start-screenshot"[\s\S]*icon-maximize-2/);assert.ok(collectorHtml.indexOf('id="add-smart-visuals"') < collectorHtml.indexOf('id="add-selection"'));- assert.ok(collectorHtml.indexOf('id="add-selection"') < collectorHtml.indexOf('id="add-other-capture-methods"'));+ assert.ok(collectorHtml.indexOf('id="add-selection"') < collectorHtml.indexOf('id="add-page-capture"'));+ assert.doesNotMatch(collectorHtml, /id="add-other-capture-methods"/);assert.doesNotMatch(collectorHtml.match(/id="add-other-capture-methods"[\s\S]*?<\/details>/)?.[0] || "", /id="add-selection"/);assert.match(collectorSource, /fallbackAction === "capture-region"/);assert.doesNotMatch(collectorSource, /otherCaptureMethods\.open = smartVisualFallback/);- assert.match(collectorSource, /addOtherCaptureMethods\.open = smartVisualFallback/);+ assert.match(collectorSource, /addScreenshot\.classList\.toggle\("fallback-highlight", smartVisualFallback\)/);assert.match(collectorSource, /if \(draft\) render\(\)/);});@@ -231,17 +239,19 @@ test("every captured draft exposes project and the shared multi-tag editor befor);assert.match(metadata, /id="capture-collection"/);assert.match(metadata, /id="capture-new-collection-name"/);- assert.match(metadata, /添加标签/);+ assert.match(metadata, /data-i18n="标签"/);assert.doesNotMatch(metadata, /自由标签|可选|不用预先创建|输入任意新标签/);assert.match(metadata, /id="custom-labels"/);- assert.doesNotMatch(metadata, /<details/);+ assert.doesNotMatch(metadata, /id="capture-extra-metadata"[^>]*open/);+ assert.ok(metadata.indexOf("</details>") < metadata.indexOf('id="custom-labels"'));+ assert.doesNotMatch(collectorSource, /captureExtraMetadata\.open = !pageCaptureBatch/);assert.match(collectorSource, /collections = response\.collections \?\? \[\]/);assert.match(collectorSource, /const selectedCollection = elements\.captureCollection\.value/);assert.match(collectorSource, /newCollectionName: selectedCollection === NEW_COLLECTION_OPTION_VALUE/);assert.match(collectorSource, /const customLabelEditor = createTagEditor/);assert.match(collectorSource, /customLabels: customLabelEditor\.values/);assert.match(collectorSource, /type: "COMMIT_CAPTURE_DRAFT",[\s\S]*\.\.\.metadata/);- assert.match(collectorSource, /type: "COMMIT_PAGE_CAPTURE",[\s\S]*\.\.\.captureMetadataForCommit\(\)/);+ assert.match(collectorSource, /type: "COMMIT_PAGE_CAPTURE",[\s\S]*\.\.\.metadata/);assert.match(collectorSource, /pageCaptureActions\.before\(elements\.captureMetadata\)/);assert.match(collectorSource, /captureAddMoreActions\.before\(elements\.captureMetadata\)/);assert.match(draftSource, /collectionId: clean\(value\.collectionId\)/);diff --git a/test/detail_content_editing_e2e.py b/test/detail_content_editing_e2e.pyindex 5759754..5b6edf1 100644--- a/test/detail_content_editing_e2e.py+++ b/test/detail_content_editing_e2e.py@@ -10,7 +10,7 @@ PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY4def main():- article = base_entry("article-edit", "文章编辑回归", "文章正文只读一次。", "content:prompt:image")+ article = base_entry("article-edit", "文章编辑回归", "文章正文只读一次。", "content:reference")article["sourceFacts"] = {"pageType": "article"}article["articleDocument"] = {"version": 1, "blocks": [{"kind": "paragraph", "text": article["text"]}]}article["mediaAssets"] = [{"id": f"article-image-{i}", "kind": "image", "usage": "content", "storageMode": "managed", "mimeType": "image/png"} for i in range(2)]diff --git a/test/i18n.test.js b/test/i18n.test.jsindex 973b9a3..456b568 100644--- a/test/i18n.test.js+++ b/test/i18n.test.js@@ -43,7 +43,7 @@ test("product pages do not leave Chinese interface text outside the translation});test("dynamic interface helpers only receive Chinese copy with an English translation", async () => {- const paths = ["../library.js", "../composer-page.js", "../skills-page.js", "../collector.js", "../curated-page.js", "../ui-dialogs.js", "../tag-editor.js", "../local-extension-upgrade-ui.js"];+ const paths = ["../library.js", "../composer-page.js", "../skills-page.js", "../collector.js", "../collector-page-capture-view.js", "../curated-page.js", "../ui-dialogs.js", "../tag-editor.js", "../local-extension-upgrade-ui.js"];const missing = [];for (const path of paths) {const source = await readFile(new URL(path, import.meta.url), "utf8");diff --git a/test/image-transaction.test.js b/test/image-transaction.test.jsindex cca198d..75cbb31 100644--- a/test/image-transaction.test.js+++ b/test/image-transaction.test.js@@ -122,7 +122,7 @@ test("external Skill deletion commits metadata before cleaning package files", atest("page capture never deletes committed media when a post-commit action fails", async () => {const source = await readFile(new URL("../background.js", import.meta.url), "utf8");- const start = source.indexOf("async function commitPageCapture(batchValue)");+ const start = source.indexOf("async function commitPageCapture(");const block = source.slice(start, source.indexOf("async function startCaptureForCase", start));assert.match(block, /metadataCommitted = true/);assert.match(block, /if \(!metadataCommitted\) await Promise\.allSettled/);diff --git a/test/jimeng_capture_e2e.py b/test/jimeng_capture_e2e.pyindex ea80070..a18c932 100644--- a/test/jimeng_capture_e2e.py+++ b/test/jimeng_capture_e2e.py@@ -100,7 +100,7 @@ def run_jimeng_flow(home_html: bytes, detail_html: bytes) -> None:first_candidate.locator(".page-capture-confirm").click()expect(collector.locator("#page-capture-media-review")).to_be_visible()expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(1)- expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 1 项媒体")+ expect(collector.locator("#page-capture-save-summary")).to_contain_text("1 项媒体")collector.evaluate("() => document.querySelector('#page-capture-save').click()")expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)diff --git a/test/library-detail-layout.test.js b/test/library-detail-layout.test.jsindex 8e0ff42..a1c3ac7 100644--- a/test/library-detail-layout.test.js+++ b/test/library-detail-layout.test.js@@ -135,11 +135,11 @@ test("document navigation moves into the top toolbar and long documents use a reassert.match(documentItem, /overflow:\s*visible/);});-test("captured posts use a compact post view while articles show only genuinely unplaced media separately", async () => {+test("text-only posts retain their reader while structured articles show only genuinely unplaced media separately", async () => {const script = await readFile(new URL("../library.js", import.meta.url), "utf8");const styles = await readFile(cssUrl, "utf8");const detail = script.slice(script.indexOf("async function renderDetail"), script.indexOf("function createLocalDiscovery"));- assert.match(detail, /const capturedPost = isCapturedPost\(entry\)/);+ assert.match(detail, /const capturedPost = usesPostReader\(entry\)/);assert.match(detail, /createCapturedPostView\(entry\)/);assert.match(detail, /createUnplacedMediaShelf\(entry\)/);assert.match(script, /function articleReferencedAssetIds/);diff --git a/test/page_capture_e2e.py b/test/page_capture_e2e.pyindex 9e77a11..e1bdc6b 100644--- a/test/page_capture_e2e.py+++ b/test/page_capture_e2e.py@@ -36,6 +36,16 @@ PNG = bytes.fromhex("0000000d49444154789c6360f8cfc000000301010018dd8db10000000049454e44ae426082")+def fixture_png(url):+ # Distinct artwork bytes; all responsive variants of the same artwork remain identical.+ import struct, zlib+ import re+ list_image = re.search(r'list-image-(\d+)', url)+ rgba = bytes([int(list_image[1]) * 40, 80, 150, 255] if list_image else [220, 50, 50, 255] if 'secondary' in url else [50, 50, 220, 255] if 'placeholder' in url else [50, 220, 50, 255])+ def chunk(kind, data):+ return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))+ return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 6, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'\0' + rgba)) + chunk(b'IEND', b'')+GIF = bytes.fromhex("47494638396101000100800000000000ffffff21f90401000000002c00000000010001000002024401003b")@@ -84,7 +94,7 @@ def main() -> None:returnroute.fulfill(status=200,- body=ARTICLE if request_url == fixture_url else PNG,+ body=ARTICLE if request_url == fixture_url else fixture_png(request_url),content_type="text/html; charset=utf-8" if request_url == fixture_url else "image/png",)@@ -107,9 +117,9 @@ def main() -> None:capture_entry_boxes = collector.locator("#normal-start .capture-actions > button").evaluate_all("nodes => nodes.map(node => ({top: node.getBoundingClientRect().top, height: node.getBoundingClientRect().height}))")- assert len(capture_entry_boxes) == 3, capture_entry_boxes- assert all(item["height"] >= 58 for item in capture_entry_boxes), capture_entry_boxes- assert capture_entry_boxes[0]["top"] < capture_entry_boxes[1]["top"] < capture_entry_boxes[2]["top"], capture_entry_boxes+ assert len(capture_entry_boxes) == 4, capture_entry_boxes+ assert all(item["height"] >= 40 for item in capture_entry_boxes), capture_entry_boxes+ assert capture_entry_boxes[0]["top"] < capture_entry_boxes[1]["top"] == capture_entry_boxes[2]["top"], capture_entry_boxescollector.screenshot(path=str(screenshots / "promptdirector-collector-entry-390.png"), full_page=True)collector.evaluate("() => document.querySelector('#capture-permission-onboarding').showModal()")permission_layout = collector.locator("#capture-permission-onboarding").evaluate(@@ -159,13 +169,13 @@ def main() -> None:collector.locator("#page-capture-media-close").click()collector.locator(".page-capture-inspect").first.click()- expect(fixture.locator("#promptdirector-page-capture-region-preview")).to_be_visible(timeout=8000)+ expect(fixture.locator("[data-promptdirector-capture-highlight]").first).to_be_attached(timeout=8000)collector.locator(".page-capture-confirm").first.click()expect(collector.locator(".page-capture-item.confirmed")).to_have_count(1)expect(collector.locator("#page-capture-media-review")).to_be_visible()expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(6)expect(collector.locator(".page-capture-media-review-group")).to_contain_text("可能遗漏媒体(1)")- expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 5 项媒体")+ expect(collector.locator("#page-capture-save-summary")).to_contain_text("5 项媒体")expect(collector.locator("#page-capture-save")).to_be_enabled()collector.locator(".page-capture-tools > summary").click()collector.locator("#page-capture-add-region").click()@@ -175,11 +185,13 @@ def main() -> None:fixture.get_by_role("button", name="完成").click()confirmed_article = collector.locator(".page-capture-item.confirmed .page-capture-article")expect(confirmed_article).to_contain_text("downloadable production notes", timeout=8000)+ expect(fixture.locator("#appendix p")).to_have_attribute("data-promptdirector-capture-highlight", "true")collector.locator("#page-capture-exclude-region").click()fixture.bring_to_front()fixture.locator("article p").nth(1).click()fixture.get_by_role("button", name="完成").click()expect(confirmed_article).not_to_contain_text("A second paragraph", timeout=8000)+ expect(fixture.locator("article p").nth(1)).not_to_have_attribute("data-promptdirector-capture-highlight", "true")collector.locator("#page-capture-undo-region").click()expect(confirmed_article).to_contain_text("A second paragraph")collector.locator("#page-capture-exclude-region").click()@@ -187,8 +199,9 @@ def main() -> None:fixture.locator("article p").nth(1).click()fixture.get_by_role("button", name="完成").click()expect(confirmed_article).not_to_contain_text("A second paragraph", timeout=8000)+ expect(fixture.locator("article p").nth(1)).not_to_have_attribute("data-promptdirector-capture-highlight", "true")expect(collector.locator("#page-capture-media-review-list .page-capture-media-review-item")).to_have_count(7)- expect(collector.locator("#page-capture-save")).to_have_text("保存案例 · 含 6 项媒体")+ expect(collector.locator("#page-capture-save-summary")).to_contain_text("6 项媒体")expect(collector.locator("#page-capture-save")).to_be_enabled()collector.locator("#page-capture-save").click()# A media failure must remain reviewable and retryable, with the real reason.@@ -245,10 +258,11 @@ def main() -> None:fixture.bring_to_front()collector.evaluate("() => document.querySelector('#start-page-capture').click()")expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)- expect(collector.locator(".page-capture-item > header small")).to_contain_text("原网页选区")+ expect(collector.locator(".page-capture-confirm small")).to_contain_text("原网页选区")expect(collector.locator(".page-capture-article p")).to_have_count(1)collector.locator(".page-capture-confirm").click()- expect(collector.locator("#page-capture-save")).to_have_text("只保存正文")+ expect(collector.locator("#page-capture-save")).to_have_text("保存案例")+ expect(collector.locator("#page-capture-save-summary")).to_contain_text("0 项媒体")collector.locator("#page-capture-save").click()expect(collector.locator("#page-capture")).to_be_hidden(timeout=8000)selected_saved = collector.evaluate("() => chrome.storage.local.get('entries').then(({entries}) => entries)")@@ -266,7 +280,7 @@ def main() -> None:expect(collector.locator("#page-capture")).to_be_visible(timeout=8000)expect(collector.locator(".page-capture-item")).to_have_count(2)collector.locator(".page-capture-confirm").first.click()- collector.locator("#page-capture-scan").click()+ collector.locator("#page-capture-mode").select_option("list")collector.locator("#page-capture-target-count").fill("3")collector.locator("#page-capture-list-run").click()expect(collector.locator("#page-capture-list-result")).to_be_visible(timeout=15000)@@ -290,7 +304,7 @@ def main() -> None:collector.evaluate("() => document.querySelector('#start-page-capture').click()")expect(collector.locator(".page-capture-item")).to_have_count(2)collector.locator(".page-capture-confirm").first.click()- collector.locator("#page-capture-scan").click()+ collector.locator("#page-capture-mode").select_option("list")collector.locator("#page-capture-target-count").fill("3")collector.locator("#page-capture-list-run").click()expect(collector.locator("#page-capture-list-result")).to_be_visible(timeout=15000)diff --git a/test/page_capture_sidebar_e2e.py b/test/page_capture_sidebar_e2e.pynew file mode 100644index 0000000..e21dedc--- /dev/null+++ b/test/page_capture_sidebar_e2e.py@@ -0,0 +1,128 @@+"""Capture cancellation, real rescan, and content-attached highlights in a disposable profile."""+import sys+import tempfile+from pathlib import Path++from playwright.sync_api import expect++from e2e_support import extension_session+from page_capture_e2e import ARTICLE, PNG, FIXTURE_ORIGIN+++def main():+ with extension_session('pd-capture-sidebar-') as run:+ url = FIXTURE_ORIGIN + '/capture-sidebar-fixture'+ run.context.route(FIXTURE_ORIGIN + '/**', lambda route: route.fulfill(+ body=ARTICLE if route.request.url == url else PNG,+ content_type='text/html' if route.request.url == url else 'image/png'))+ panel = run.open_page('collector.html', wait_until='networkidle')+ panel.set_viewport_size({'width': 390, 'height': 844})+ run.seed_storage(panel, {'entries': [], 'capturePermissionOnboarding': {+ 'version': 1, 'acknowledgedAt': '2026-09-07T00:00:00Z', 'clipboardIncluded': True}})+ page = run.context.new_page()+ page.goto(url)+ page.bring_to_front()+ panel.evaluate("""() => {+ window.captureMessages = [];+ const send = chrome.runtime.sendMessage.bind(chrome.runtime);+ chrome.runtime.sendMessage = (...args) => {+ window.captureMessages.push(args[0]?.type);+ const result = send(...args);+ if (args[0]?.type === 'START_PAGE_CAPTURE' && window.holdNextCaptureReply) {+ window.holdNextCaptureReply = false;+ return result.then(value => new Promise(resolve => {window.releaseCaptureReply = () => resolve(value)}));+ }+ return result;+ };+ }""")+ panel.locator('#start-page-capture').evaluate('e => e.click()')+ expect(panel.locator('.page-capture-item').first).to_be_visible(timeout=10000)+ if '--highlight' not in sys.argv:+ panel.locator('.page-capture-confirm').first.click()+ panel.locator('.page-capture-tools > summary').click()+ panel.locator('#page-capture-clear').click()+ expect(panel.locator('#page-capture-save')).to_be_disabled()+ scans = panel.evaluate("window.captureMessages.filter(t => t === 'START_PAGE_CAPTURE').length")+ panel.locator('#page-capture-scan').click()+ panel.wait_for_function("n => window.captureMessages.filter(t => t === 'START_PAGE_CAPTURE').length > n", arg=scans, timeout=4000)+ expect(panel.locator('.page-capture-confirm').first).to_be_enabled(timeout=10000)+ expect(panel.locator('#page-capture-list-setup')).to_be_hidden()+ panel.locator('.page-capture-confirm').first.click()+ expect(panel.locator('#page-capture-save')).to_be_enabled()+ panel.locator('#page-capture-cancel').click()+ expect(panel.locator('#page-capture')).to_be_hidden()+ page.bring_to_front()+ panel.locator('#start-page-capture').evaluate('e => e.click()')+ expect(panel.locator('.page-capture-confirm').first).to_be_enabled(timeout=10000)++ page.evaluate('window.scrollTo(0,0)')+ panel.locator('.page-capture-confirm').first.click()+ page.wait_for_timeout(500)+ assert page.evaluate('window.scrollY') == 0, 'Selecting content must not move the reader to the middle of an article'+ target = page.locator('article p').first+ expect(target).to_have_attribute('data-promptdirector-capture-highlight', 'true')+ assert target.evaluate("e => getComputedStyle(e).outlineStyle") == 'solid'+ assert page.locator('#promptdirector-page-capture-region-preview').evaluate('e => e.tagName') == 'STYLE'+ before = target.bounding_box()+ page.evaluate('window.scrollBy(0,350)')+ after = target.bounding_box()+ assert abs(before['y'] - after['y'] - 350) < 1+ assert target.evaluate("e => getComputedStyle(e).outlineStyle") == 'solid'+ # Browser layout owns the outline: an inner scroll or reflow moves the+ # marked content, without a stale viewport-sized rectangle.+ page.locator('main').evaluate("e => {e.style.height='220px';e.style.overflow='auto'}")+ before_inner = target.bounding_box()+ page.locator('main').evaluate('e => e.scrollTop = 100')+ after_inner = target.bounding_box()+ assert abs(before_inner['y'] - after_inner['y'] - 100) < 1+ page.set_viewport_size({'width': 900, 'height': 700})+ assert target.evaluate("e => getComputedStyle(e).outlineStyle") == 'solid'+ page.locator('main').evaluate("e => {e.removeAttribute('style')}")++ panel.locator('#page-capture-media-review > summary').click()+ first_media = panel.locator('.page-capture-media-review-item').first+ first_media.get_by_role('button', name='排除', exact=True).click()+ expect(first_media).to_have_class('page-capture-media-review-item media-excluded media-pending')+ first_media.get_by_role('button', name='恢复', exact=True).click()+ expect(first_media).to_have_class('page-capture-media-review-item media-proposed media-pending')+ panel.locator('#page-capture-media-review > summary').click()+ panel.locator('.page-capture-tools > summary').click()+ panel.locator('#page-capture-add-region').click()+ expect(page.locator('#promptdirector-page-capture-region-editor')).to_be_visible()+ panel.locator('#page-capture-edit-cancel').click()+ expect(page.locator('#promptdirector-page-capture-region-editor')).to_have_count(0)+ expect(panel.locator('#page-capture-save')).to_be_enabled()+ expect(target).to_have_attribute('data-promptdirector-capture-highlight', 'true')++ # A completed but late response from a cancelled scan must not replace+ # the fresh result or the user's new selection.+ panel.evaluate('window.holdNextCaptureReply = true')+ page.bring_to_front()+ panel.locator('#page-capture-scan').click()+ panel.wait_for_function("() => typeof window.releaseCaptureReply === 'function'")+ panel.locator('#page-capture-cancel').click()+ expect(panel.locator('#page-capture-scan')).to_be_enabled()+ panel.locator('#page-capture-scan').click()+ expect(panel.locator('.page-capture-confirm').first).to_be_enabled(timeout=10000)+ panel.locator('.page-capture-confirm').first.click()+ panel.evaluate('window.releaseCaptureReply()')+ expect(panel.locator('.page-capture-item.confirmed')).to_have_count(1)+ expect(panel.locator('#page-capture-save')).to_be_enabled()+ for width in [320, 390]:+ panel.set_viewport_size({'width': width, 'height': 640})+ box = panel.locator('#page-capture-save').bounding_box()+ assert box and box['y'] >= 0 and box['y'] + box['height'] <= 640, box+ assert panel.evaluate('document.documentElement.scrollWidth <= innerWidth')+ assert panel.locator('.page-capture-confirm').first.evaluate('e => getComputedStyle(e).backgroundColor') != panel.locator('#page-capture-save').evaluate('e => getComputedStyle(e).backgroundColor')+ panel.screenshot(path=str(Path(tempfile.gettempdir()) / 'promptdirector-capture-sidebar-implemented.png'))+ panel.locator('.page-capture-tools > summary').click()+ panel.locator('#page-capture-clear').click()+ expect(page.locator('[data-promptdirector-capture-highlight]')).to_have_count(0)+ assert panel.evaluate("() => chrome.storage.local.get('entries').then(s => s.entries.length)") == 0+ print({'rescan': '--highlight' not in sys.argv, 'selectPreservesScroll': True, 'contentAttachedOutline': True,+ 'innerScrollAndResize': True, 'cancelRegionEdit': True, 'lateResponseIgnored': True,+ 'saveVisibleAt320And390': True, 'clearRemovesHighlight': True})+++if __name__ == '__main__':+ main()diff --git a/test/run_e2e.py b/test/run_e2e.pyindex f9f51c5..c32a051 100644--- a/test/run_e2e.py+++ b/test/run_e2e.py@@ -25,6 +25,7 @@ SCRIPTS = ["prompt_panels_e2e.py","detail_visual_stability_e2e.py","detail_content_editing_e2e.py",+ "x_post_capture_e2e.py","media_reference_cards_e2e.py","library_detail_actions_e2e.py","library_detail_rendering_e2e.py",@@ -51,6 +52,9 @@ SCRIPTS = ["smart_visual_picker_e2e.py","page_capture_e2e.py","higgsfield_capture_e2e.py",+ "page_capture_sidebar_e2e.py",+ "capture_additions_e2e.py",+ "x_capture_extraction_e2e.py","libtv_capture_e2e.py","jimeng_capture_e2e.py","ai_provider_registry_e2e.py",diff --git a/test/x_capture_extraction_e2e.py b/test/x_capture_extraction_e2e.pynew file mode 100644index 0000000..7661722--- /dev/null+++ b/test/x_capture_extraction_e2e.py@@ -0,0 +1,123 @@+"""Run the production DOM scanner on a synthetic X conversation in an isolated browser."""+from playwright.sync_api import expect+from e2e_support import extension_session++URL = 'https://x.com/director/status/123'+HTML = '''<!doctype html><html><head><link rel="canonical" href="https://x.com/director/status/123"></head><body><main>+<article data-testid="tweet">+<div data-testid="User-Name"><a href="/director"><span>Director</span></a><a href="/director">@director</a></div>+<button>Subscribe</button><button>Show translation</button>+<div data-testid="tweetText">Main filmmaking notes: preserve clear positions and continuous action. Subscribe is a word in this author's sentence and must survive. <a href="https://example.com/prompt-notes">Reference notes</a></div>+<video poster="https://pbs.twimg.com/main.jpg" style="width:600px;height:340px"></video>+<div role="link" tabindex="0"><div data-testid="User-Name"><a href="/other"><span>Other author</span></a></div>+<a href="/other/status/456"><time datetime="2026-09-05T00:00:00Z">Old quote date</time></a>+<div data-testid="tweetText">Quoted filmmaking reference: preserve this separate source and its genuine second video.</div>+<video poster="https://pbs.twimg.com/quote.jpg" style="width:600px;height:340px"></video></div>+<a href="/director/status/123"><time datetime="2026-09-07T00:00:00Z">Main post date</time></a>+<a href="/director/status/123/analytics">Views 9000</a><a href="/director/status/123/quotes">View quotes</a>+<button data-testid="like">123</button><button data-testid="retweet">45</button>+</article>+<article data-testid="tweet"><div data-testid="User-Name"><a href="/director"><span>Director</span></a></div>+<div data-testid="tweetText">Author prompt: generate a cinematic palace scene with six continuous shots.</div>+<button data-testid="tweet-text-show-more-link">Show more</button>+<a href="/director/status/124"><time datetime="2026-09-07T01:00:00Z">Reply date</time></a></article>+<article data-testid="tweet"><div data-testid="User-Name"><a href="/outsider"><span>Outsider</span></a></div>+<div data-testid="tweetText">UNRELATED COMMENT must not join the main case.</div><a href="/outsider/status/125"><time>Now</time></a></article>+</main></body></html>'''+++def main():+ with extension_session('pd-x-extraction-') as run:+ run.context.route('https://x.com/**', lambda r:r.fulfill(body=HTML, content_type='text/html'))+ run.context.route('https://pbs.twimg.com/**', lambda r:r.abort())+ setup=run.open_page('collector.html')+ scanner=setup.evaluate("""async () => ({+ fn: (await import(chrome.runtime.getURL('page-capture.js'))).collectPageCaptureSnapshot.toString(),+ adapters: (await import(chrome.runtime.getURL('page-capture-adapter-registry.js'))).PAGE_CAPTURE_ADAPTERS+ })""")+ page=run.context.new_page();page.goto(URL)+ snapshot=page.evaluate('async options => ('+scanner['fn']+')(options)', {'adapters':scanner['adapters']})+ assert len(snapshot['candidates'])==1, snapshot+ c=snapshot['candidates'][0]+ assert c['canonicalUrl']==URL,c+ assert 'https://example.com/prompt-notes' in c['contentHtml'],c['contentHtml']+ assert c['sourceFacts']['publishedAt']=='2026-09-07T00:00:00Z',c['sourceFacts']+ assert c['sourceFacts']['author']=='Director',c['sourceFacts']+ assert 'Subscribe is a word' in c['contentText'],c['contentText']+ assert 'Quoted filmmaking' in c['contentText'],c['contentText']+ for noise in ['Show translation','Views 9000','View quotes','UNRELATED COMMENT','Author prompt:']:+ assert noise not in c['contentText'],(noise,c['contentText'])+ assert len(c['media'])==2 and all(m['kind']=='video' for m in c['media']),c['media']+ assert all(not m['url'] for m in c['media']),c['media'] # no invented video route+ assert len(c['supplements'])==1 and c['supplements'][0]['partial'],c['supplements']+ normalized=setup.evaluate("""async snapshot => {+ const {normalizePageCaptureBatch, applyPageCaptureSelections} = await import(chrome.runtime.getURL('page-capture.js'));+ const candidate=snapshot.candidates[0];+ const batch=normalizePageCaptureBatch({...snapshot,status:'ready',selections:[{candidateId:candidate.id,includeText:true,selectedMediaIds:candidate.media.map(m=>m.id),mediaDecision:'confirmed'}]});+ return {batch, saved:applyPageCaptureSelections(batch)};+ }""",snapshot)+ assert len(normalized['batch']['candidates'][0]['supplements'])==1+ saved=normalized['saved'][0]+ assert len(saved['media'])==2,saved['media']+ doc='\n'.join(b.get('text','') for b in saved['articleDocument']['blocks'])+ assert 'Main filmmaking' in doc and 'Quoted filmmaking' in doc,doc+ assert 'View quotes' not in doc and 'Show translation' not in doc,doc+ # Real X carousel shape: NAV + transparent IMG + visible CSS background.+ carousel = '<nav>' + ''.join(f'<a href="/director/status/{post}/photo/{i}"><div style="width:200px;height:300px;background-image:url(https://pbs.twimg.com/media/{post}-{i}?format=jpg&name=small)"><img alt="Prompt: portrait photography" src="https://pbs.twimg.com/media/{post}-{i}?format=jpg&name=small" style="width:200px;height:300px;opacity:0"></div></a>' for post in [123,456] for i in range(1,5)) + '</nav>'+ page.locator('article[data-testid="tweet"]').first.evaluate('(root,html)=>root.insertAdjacentHTML("beforeend",html)', carousel)+ grouped=page.evaluate('async options => ('+scanner['fn']+')(options)', {'adapters':scanner['adapters']})['candidates'][0]+ images=[m for m in grouped['media'] if m['kind']=='image']+ assert len(images)==8, images+ assert len([m for m in images if m.get('quotedPostUrl')])==4, images+ selected_ids=setup.evaluate("async c=>(await import('./page-capture.js')).pageCaptureDefaultMediaIds(c)",grouped)+ assert len([m for m in images if m['id'] in selected_ids])==4, (selected_ids,images)+ print({'carousel_images':8,'main_default':4,'quoted_optional':4})+ # Use actual scanner output in the sidebar; mock only browser dispatch of this already-read fixture.+ setup.evaluate("""snapshot=>{+ window.captureSnapshot=snapshot;+ const contains=chrome.permissions.contains.bind(chrome.permissions);+ chrome.permissions.contains=async q=>q.origins?.includes('https://x.com/*')?true:contains(q);+ const query=chrome.tabs.query.bind(chrome.tabs);+ chrome.tabs.query=async q=>q.active?[{id:999,url:'https://x.com/director/status/123'}]:query(q);+ const send=chrome.runtime.sendMessage.bind(chrome.runtime);+ chrome.runtime.sendMessage=async m=>m.type==='START_PAGE_CAPTURE'?{ok:true,batch:{...window.captureSnapshot,status:'ready'}}:send(m);+ }""",snapshot)+ run.seed_storage(setup,{'entries':[],'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-07T00:00:00Z','clipboardIncluded':True}})+ setup.locator('#start-page-capture').click()+ expect(setup.locator('.page-capture-confirm')).to_be_visible()+ setup.locator('.page-capture-confirm').click()+ setup.locator('.page-capture-supplements > summary').click()+ setup.get_by_role('button',name='补入已显示内容',exact=True).click()+ expect(setup.locator('.page-capture-excerpt')).to_contain_text('Author prompt:')+ expect(setup.locator('.page-capture-supplements')).to_have_count(0)+ setup.locator('#page-capture-save-text-only').click()+ expect(setup.locator('#page-capture')).to_be_hidden(timeout=10000)+ entries=setup.evaluate("() => chrome.runtime.sendMessage({type:'GET_STATE'}).then(r=>r.entries)")+ assert len(entries)==1,entries+ for kept in ['Main filmmaking','Quoted filmmaking','Author prompt:']:+ assert kept in entries[0]['text'],(kept,entries[0]['text'])+ assert entries[0]['sourceFacts']['status']=='partial',entries[0]['sourceFacts']+ # Group additions are independently selectable and undoable in the production sidebar.+ setup.evaluate("candidate=>window.captureSnapshot={candidates:[candidate]}",grouped)+ setup.locator('#start-page-capture').click();setup.locator('.page-capture-confirm').click()+ expect(setup.locator('.page-capture-media-group')).to_contain_text('引用帖 · 4 张图')+ baseline=setup.locator('.page-capture-thumbnail').count()+ setup.get_by_role('button',name='加入这组',exact=True).click()+ expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline+4)+ setup.locator('#page-capture-undo-region').click()+ expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline)+ setup.locator('.page-capture-thumbnail-remove').first.click()+ expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline-1)+ setup.locator('#page-capture-undo-region').click()+ expect(setup.locator('.page-capture-thumbnail')).to_have_count(baseline)+ setup.locator('#page-capture-cancel').click()+ print({'group_add_undo':True,'single_media_remove_undo':True})+ # Explicit selection must outrank site auto-detection.+ page.evaluate("""() => {const text=document.querySelector('[data-testid=tweetText]');const r=document.createRange();r.selectNodeContents(text);getSelection().removeAllRanges();getSelection().addRange(r)}""")+ selection=page.evaluate('async options => ('+scanner['fn']+')(options)', {'adapters':scanner['adapters']})+ assert len(selection['candidates'])==1,selection+ assert 'Quoted filmmaking' not in selection['candidates'][0]['contentText'],selection+ assert not selection['candidates'][0]['media'],selection+ print({'saved_reply_readback':True,'selection_scope':True,'x_primary_scope':True,'quote_preserved':True,'two_real_videos_only':True,'own_date':True,'optional_author_reply':True,'partial_reply_explicit':True})++if __name__=='__main__':main()diff --git a/test/x_post_capture_e2e.py b/test/x_post_capture_e2e.pyindex ddcbe84..6352eab 100644--- a/test/x_post_capture_e2e.py+++ b/test/x_post_capture_e2e.py@@ -1,5 +1,9 @@from __future__ import annotations+import os+from pathlib import Path+from tempfile import mkdtemp+from playwright.sync_api import expectfrom e2e_support import base_entry, extension_session@@ -42,6 +46,7 @@ def main() -> None:"height": 1067,"capturedAt": "2026-08-16T09:31:00.000Z","reviewStatus": "verified",+ "palette": {"colors": ["#080808"], "source": "screenshot", "version": 2},},{"id": "post-video",@@ -70,39 +75,103 @@ def main() -> None:},})+ entry["articleDocument"]["blocks"].extend([+ {"id": "quote", "kind": "quote", "text": "引用:先明确人物站位,再描述镜头运动。", "sourceOrder": 3},+ {"id": "steps", "kind": "list", "ordered": True, "text": "确定主体位置\n安排运动方向\n检查前后衔接", "sourceOrder": 4},+ {"id": "code", "kind": "code", "text": "camera: tracking\n subject: walking", "sourceOrder": 5},+ {"id": "link", "kind": "link", "label": "原始参考资料 " + "reference/" * 15,+ "sourceUrl": "https://example.com/reference", "sourceOrder": 6},+ ])+ evidence = Path(os.environ.get("PROMPTDIRECTOR_LAB_EVIDENCE_DIR") or mkdtemp(prefix="post-detail-evidence-"))+ evidence.mkdir(parents=True, exist_ok=True)with extension_session("prompt-director-x-post-") as run:setup = run.open_page("collector.html")+ run.seed_storage(setup, {"entries": [entry], "uiPreferences": {"theme": "dark", "locale": "zh-CN", "motion": "reduced"}})setup.evaluate(- """async ({entry, png}) => {+ """async png => {const {saveMediaBlob} = await import(chrome.runtime.getURL('media-store.js'));const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));await saveMediaBlob('post-image', new Blob([bytes], {type: 'image/png'}), {checkCapacity: false});- await chrome.storage.local.clear();- await chrome.storage.local.set({schemaVersion: 24, entries: [entry]});- }""",- {"entry": entry, "png": PNG_BASE64},- )-+ }""", PNG_BASE64)library = run.open_page("library.html", wait_until="networkidle")expect(library.locator(".case-card")).to_have_count(1)library.locator(".case-card").click()- expect(library.locator(".captured-post-view")).to_be_visible(timeout=8000)- expect(library.locator(".captured-post-text")).to_contain_text("practical lighting breakdown")- expect(library.locator(".captured-post-heading")).to_contain_text("Director Name")- expect(library.locator(".captured-post-heading")).to_contain_text("@director")- expect(library.locator(".compact-captured-image img")).to_have_count(1)- expect(library.get_by_text("打开原帖观看视频")).to_have_count(1)- expect(library.locator(".article-document-reader")).to_have_count(0)- expect(library.locator(".detail-video, iframe")).to_have_count(0)- expect(library.get_by_text("单独查看文章媒体")).to_have_count(0)+ expect(library.locator(".detail-visual-gallery")).to_be_visible(timeout=8000)+ expect(library.locator(".original-prompt-panel")).to_contain_text("practical lighting breakdown")+ expect(library.locator(".captured-post-view, .article-document-reader")).to_have_count(0)+ expect(library.locator("#detail-content")).to_have_class("detail-content has-primary-media")+ before = setup.evaluate("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries[0]}")- print({- "page_type": "post",- "author": "Director Name",- "saved_media": 2,- "compact_post": True,- "black_video_embed": False,- })+ def classify(category):+ result = setup.evaluate("""async category => chrome.runtime.sendMessage({+ type:'CONFIRM_CLASSIFICATION', entryId:'captured-x-post', pathIds:[category], rememberSource:false+ })""", category)+ assert result['ok'], result++ classify('content:reference')+ reader = library.locator('.article-document-reader')+ expect(reader).to_be_visible(timeout=8000)+ expect(library.locator('.detail-visual-gallery, .captured-post-view')).to_have_count(0)+ expect(library.locator('.original-prompt-panel')).to_have_count(0)+ expect(reader.locator('blockquote')).to_have_text('引用:先明确人物站位,再描述镜头运动。')+ expect(reader.locator('ol > li')).to_have_count(3)+ expect(reader.locator('pre')).to_have_text('camera: tracking\n subject: walking')+ expect(reader.locator('.article-document-image')).to_have_count(1)+ expect(reader.locator('.compact-media-link')).to_have_count(1)+ assert reader.locator('.compact-media-link').bounding_box()['height'] < 80, '没有封面的视频不能撑成空白大卡片'+ expect(reader.locator('iframe')).to_have_count(0)+ for theme in ('dark', 'light'):+ library.evaluate("async theme=>{const {initializeUi}=await import('./i18n.js');await initializeUi({theme,locale:'zh-CN',motion:'reduced'})}", theme)+ for width in (1280, 390, 320):+ library.set_viewport_size({'width': width, 'height': 900})+ assert reader.evaluate('e=>e.scrollWidth<=e.clientWidth'), (theme, width, 'article overflow')+ header = library.locator('.detail-header-section')+ assert header.evaluate('e=>e.scrollWidth<=e.clientWidth'), (theme, width, 'header overflow')+ title = header.locator('.detail-title').bounding_box()+ edit = header.locator('.entry-editor-inline > summary').bounding_box()+ assert title['x'] + title['width'] <= edit['x'] + 1, (theme, width, 'title overlap')+ resource = reader.locator('.article-document-resource')+ assert resource.evaluate('e=>{const t=e.querySelector("strong").getBoundingClientRect(), a=e.querySelector("a").getBoundingClientRect();return a.x>=t.right-1 && a.y<t.bottom && a.bottom>t.y}'), (theme,width,'resource action must stay beside its label')+ assert reader.locator('p').first.evaluate('e=>getComputedStyle(e).fontWeight') == '400'+ library.screenshot(path=str(evidence / f'article-detail-{theme}-{width}.png'))++ # A category change on the open article must remount the existing case template.+ classify('content:prompt:video')+ expect(library.locator('.detail-visual-gallery')).to_be_visible(timeout=8000)+ expect(reader).to_have_count(0)+ expect(library.locator('.original-prompt-panel')).to_contain_text('practical lighting breakdown')+ library.locator('.detail-visual-thumb').nth(1).click()+ expect(library.locator('.detail-visual-gallery')).to_have_class(__import__('re').compile('is-video-detail'))+ expect(library.locator('.original-prompt-panel')).to_contain_text('practical lighting breakdown')+ classify('content:reference')+ expect(reader).to_be_visible(timeout=8000)+ after = setup.evaluate("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries[0]}")+ for key in ('text', 'mediaAssets', 'articleDocument', 'sourceFacts'):+ assert before[key] == after[key], (key, before[key], after[key])++ # List editing stays a plain-text edit, then restores the reading structure.+ reader.get_by_role('button', name='编辑正文', exact=True).click()+ steps = reader.locator('[data-article-block-id="steps"]')+ steps.fill('取消的修改')+ reader.get_by_role('button', name='取消', exact=True).click()+ expect(reader.locator('ol > li')).to_have_count(3)+ reader.get_by_role('button', name='编辑正文', exact=True).click()+ steps.fill('新的第一步\n新的第二步')+ reader.get_by_role('button', name='保存', exact=True).click()+ expect(reader.locator('ol > li')).to_have_count(2)+ expect(reader.locator('ol')).to_contain_text('新的第二步')+ reader.get_by_role('button', name='复制文字', exact=True).click()+ copied = library.evaluate('async()=>navigator.clipboard.readText()')+ assert '新的第二步' in copied and '取消的修改' not in copied+ assert reader.get_by_role('button', name='复制文字', exact=True).locator('svg').count() == 1+ library.reload(wait_until='networkidle')+ library.locator('.case-card').click()+ expect(library.locator('.article-document-reader ol > li')).to_have_count(2)+ stored = setup.evaluate("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries[0]}")+ assert stored['mediaAssets'] == before['mediaAssets']+ assert next(b for b in stored['articleDocument']['blocks'] if b['id']=='steps')['text'] == '新的第一步\n新的第二步'+ print({'classification_routes_detail': True, 'live_mode_switch': True, 'structured_article': True,+ 'list_edit_readback': True, 'media_unchanged': True, 'widths': [1280,390,320], 'themes': 2, 'evidence': str(evidence)})if __name__ == "__main__":diff --git a/tools/build-ui-icons.mjs b/tools/build-ui-icons.mjsindex b9ba6da..ca53317 100644--- a/tools/build-ui-icons.mjs+++ b/tools/build-ui-icons.mjs@@ -6,11 +6,11 @@ const projectRoot = fileURLToPath(new URL("../", import.meta.url));const sourcePath = join(projectRoot, "node_modules", "lucide-static", "icon-nodes.json");const outputPath = join(projectRoot, "assets", "ui-icons.svg");const iconNames = [- "arrow-down", "arrow-left", "arrow-up", "check", "chevron-down", "chevron-left", "chevron-right", "circle-check-big", "copy",+ "arrow-down", "arrow-left", "arrow-up", "check", "chevron-down", "chevron-left", "chevron-right", "circle-check-big", "clipboard", "copy","download", "ellipsis", "external-link", "file-text", "folder", "image", "library","list-checks", "maximize-2", "menu", "moon", "panel-left", "paperclip", "pencil", "play", "plus","refresh-cw", "save", "search", "send", "settings", "sliders-horizontal", "sparkles", "square-check-big",- "square", "sun", "tag", "trash-2", "upload", "video", "wand-sparkles", "x"+ "square", "sun", "tag", "trash-2", "undo-2", "upload", "video", "wand-sparkles", "x"];const iconNodes = JSON.parse(await readFile(sourcePath, "utf8"));