Skip to content

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

发布 1.20.8:完整保留文章案例与图片墙提示词

wchao689122fec685587c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e0b67a..c59cd8b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,14 @@
了解每个版本带来的功能变化与使用改善。下载请前往 [GitHub Releases](https://github.com/wchao6891/PromptDirector/releases/latest)。
+## 1.20.8
+
+- 新增“文章内案例”采集:按明确的案例标题或编号拆分提示词与对应图片,逐组勾选、分别保存,同时保留整篇文章保存。
+- 改善小黑盒等长图文文章的懒加载图片采集;图片墙与正文分开的单案例帖子可一起保存完整提示词和多张图片,排除头像与评论;未能明确分组的导读等内容单列核对。
+- 加强通用文档及内部滚动列表采集,保留重复段落的原始位置,并提示未完成的扫描。
+- 改善飞书文档正文采集,保存表格内图文、合并单元格及长文档内容;无法取得原件的画布内容保留可见快照。
+- 区分原网页高亮定位提示与实际保存失败,避免误解采集状态。
+
## 1.20.7
- 创作台可按对话需要找案例、读资料、查询精选目录和已有 Skill;提炼 Skill 与标签建议可查看、编辑后保存。
diff --git a/extension/article-case-groups.js b/extension/article-case-groups.js
new file mode 100644
index 0000000..bd33693
--- /dev/null
+++ b/extension/article-case-groups.js
@@ -0,0 +1,75 @@
+import { normalizeArticleDocument, articleDocumentText } from './article-document.js';
+
+// Split only when repeated source boundaries contain evidence of independent prompt/image cases.
+// Keep uncertain fragments separate so adjacency never silently invents a prompt association.
+export function splitArticleCases(candidate) {
+ const document = normalizeArticleDocument(candidate?.articleDocument);
+ if (!document) return [];
+ const blocks = document.blocks;
+ const owned = new Set(blocks.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
+ const top = blocks.filter(block => !owned.has(block.id));
+ const promptLabel = text => /(?:提示词|prompt|生成指令)/iu.test(text || '');
+ const sectionLabel = text => /^(?:[\p{Emoji_Presentation}\s📝📖🖼📌]*)(?:描述|提示词|生成图片|参考图|详情|说明|description|prompt|generated images?|details)\s*[::]?$/iu.test(text || '');
+ const numbered = text => /^(?:(?:no\.?|case|案例|示例)\s*\d+\s*[::.、-]?|第[\d一二三四五六七八九十百]+[个项章节]|\d+[、..)]\s*\S)/iu.test(text || '');
+ const bonus = text => /^(?:彩蛋|番外|bonus\b)/iu.test(text || '');
+ const isTitle = block => !sectionLabel(block.text) && (block.kind === 'heading' || block.kind === 'paragraph' && !block.text.includes('\n') && numbered(block.text));
+ const mediaIds = new Set((candidate.media || []).map(media => media.id));
+ const hasMedia = parts => parts.some(block => block.assetId && mediaIds.has(block.assetId));
+ const hasPrompt = parts => parts.some(block => ['heading','paragraph'].includes(block.kind) && promptLabel(block.text))
+ || parts.some(block => ['code','quote'].includes(block.kind) && block.text);
+ const expand = parts => {
+ const ids = new Set(parts.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
+ return blocks.filter(block => parts.includes(block) || ids.has(block.id));
+ };
+ let ranges = [];
+ for (const level of [1,2,3,4,5,6,0]) {
+ const starts = top.flatMap((block,index) => isTitle(block) && (level ? block.kind === 'heading' && block.level === level : block.kind === 'paragraph') ? [index] : []);
+ if (starts.length < 2) continue;
+ const proposal = starts.map((start,index) => ({ start, end: starts[index+1] ?? top.length }));
+ if (proposal.filter(({start,end}) => {
+ const parts = expand(top.slice(start,end));
+ return hasMedia(parts) && hasPrompt(parts);
+ }).length >= 2) { ranges = proposal; break; }
+ }
+ if (!ranges.length) return [];
+ // Bonus sections can use a paragraph rather than the numbered heading level.
+ ranges = ranges.flatMap(range => {
+ const extra = top.findIndex((block,index) => index > range.start && index < range.end && ['heading','paragraph'].includes(block.kind) && bonus(block.text));
+ if (extra < 0 || !hasPrompt(expand(top.slice(extra,range.end))) || !hasMedia(expand(top.slice(extra,range.end)))) return [range];
+ return [{start:range.start,end:extra},{start:extra,end:range.end}];
+ });
+ const groups = [];
+ const used = new Set();
+ for (const {start,end} of ranges) {
+ const parts = expand(top.slice(start,end));
+ if (!hasPrompt(parts)) continue;
+ parts.forEach(block => used.add(block.id));
+ groups.push(makeGroup(top[start].text, parts, groups.length, !hasMedia(parts)));
+ }
+ if (groups.length < 2) return [];
+ const remainder = blocks.filter(block => !used.has(block.id));
+ if (remainder.length) groups.push(makeGroup('未分组内容 · ' + candidate.title, remainder, groups.length, true));
+ return groups;
+
+ function makeGroup(title, parts, index, review) {
+ const articleDocument = normalizeArticleDocument({blocks:parts.map((block, sourceOrder) => ({...block,sourceOrder}))});
+ const selectedIds = new Set(parts.flatMap(block => block.assetId ? [block.assetId] : []));
+ const media = (candidate.media || []).filter(media => selectedIds.has(media.id));
+ return {
+ ...candidate,
+ id: `${candidate.id}:section:${index}`,
+ title,
+ pageType: 'artwork',
+ contentText: articleDocumentText(articleDocument),
+ contentHtml: '',
+ articleDocument,
+ textBlocks: parts.filter(block => block.text && !owned.has(block.id)).map(block => ({id:block.id,text:block.text,kind:block.kind,sourceOrder:block.sourceOrder})),
+ media,
+ possibleOmissions: [], supplements: [],
+ batchStructureStatus: review ? 'review' : 'matched',
+ sourceFacts: {...candidate.sourceFacts, pageType:'artwork', itemId:`${candidate.sourceFacts?.itemId || candidate.id}:section:${index}`},
+ region: candidate.region ? {...candidate.region, contentTargets:(candidate.region.contentTargets || []).filter(target =>
+ target.articleBlockIds?.some(id=>parts.some(block=>block.id===id)) || target.mediaIds?.some(id=>selectedIds.has(id)))} : null
+ };
+ }
+}
diff --git a/extension/article-document.js b/extension/article-document.js
index b2b29c8..b272a6f 100644
--- a/extension/article-document.js
+++ b/extension/article-document.js
@@ -14,14 +14,23 @@ export function normalizeArticleDocument(value) {
return [normalized];
}).sort((left, right) => left.sourceOrder - right.sourceOrder);
if (!blocks.length) return null;
+ const byId = new Map(blocks.map(block => [block.id, block]));
+ const owned = new Set();
+ for (const table of blocks.filter(block => block.rows)) {
+ for (const row of table.rows) for (const cell of row) {
+ cell.blockIds = cell.blockIds.filter(id => byId.has(id) && !byId.get(id).rows && !owned.has(id) && id !== table.id && (owned.add(id), true));
+ }
+ table.text = table.rows.map(row => row.map(cell => cell.blockIds.map(id => byId.get(id).text || "").filter(Boolean).join("\n")).join("\t")).join("\n").trim();
+ }
return { version: ARTICLE_DOCUMENT_VERSION, blocks };
}
export function articleDocumentText(value) {
const documentValue = normalizeArticleDocument(value);
if (!documentValue) return "";
+ const cellIds = new Set(documentValue.blocks.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
return documentValue.blocks
- .filter((block) => TEXT_BLOCK_KINDS.has(block.kind))
+ .filter((block) => TEXT_BLOCK_KINDS.has(block.kind) && !cellIds.has(block.id))
.map((block) => block.text)
.filter(Boolean)
.join("\n\n");
@@ -79,7 +88,7 @@ function normalizeArticleBlock(value, index) {
: cleanMultiline(value.text);
const assetId = clean(value.assetId);
const sourceUrl = safeHttpUrl(value.sourceUrl || value.url);
- if (TEXT_BLOCK_KINDS.has(kind) && !text) return null;
+ if (TEXT_BLOCK_KINDS.has(kind) && !text && !(kind === "table" && Array.isArray(value.rows) && value.rows.length)) return null;
if (ASSET_BLOCK_KINDS.has(kind) && !assetId && !sourceUrl) return null;
if (kind === "link" && !sourceUrl) return null;
const sourceOrderValue = Number(value.sourceOrder);
@@ -96,6 +105,17 @@ function normalizeArticleBlock(value, index) {
...(label ? { label } : {}),
...(mimeType ? { mimeType } : {})
};
+ if (kind === "table" && Array.isArray(value.rows) && value.rows.length) {
+ block.rows = value.rows.filter(Array.isArray).map(row => row.filter(cell => cell && typeof cell === "object").map(cell => ({
+ header: cell.header === true,
+ rowspan: Number.isSafeInteger(cell.rowspan) && cell.rowspan > 0 ? cell.rowspan : 1,
+ colspan: Number.isSafeInteger(cell.colspan) && cell.colspan > 0 ? cell.colspan : 1,
+ ...(Number.isFinite(cell.width) && cell.width > 0 ? { width: cell.width } : {}),
+ ...(["left", "right", "center", "justify", "start", "end"].includes(cell.align) ? { align: cell.align } : {}),
+ ...(["top", "middle", "bottom", "baseline"].includes(cell.valign) ? { valign: cell.valign } : {}),
+ blockIds: Array.isArray(cell.blockIds) ? cell.blockIds.map(clean).filter(Boolean) : []
+ })));
+ }
if (kind === "heading") block.level = Math.min(6, Math.max(1, Math.trunc(Number(value.level) || 2)));
if (kind === "list") block.ordered = value.ordered === true;
if (kind === "video" && safeHttpUrl(value.posterUrl)) block.posterUrl = safeHttpUrl(value.posterUrl);
diff --git a/extension/background.js b/extension/background.js
index 591d7dc..434f751 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -1,3 +1,5 @@
+import { splitArticleCases } from "./article-case-groups.js";
+import { collectFeishuDocument } from "./feishu-document-capture.js";
import { saveComposerToolDraft, preserveSavedToolDrafts } from './composer-tool-drafts.js';
import { renderPageCaptureRegionPreview, clearPageCapturePageState } from "./page-capture-highlight.js";
import { collectLibTvPublicPayload, normalizeLibTvPublicPayload } from "./libtv-capture.js";
@@ -1203,7 +1205,11 @@ async function startPageCapture(mode = "loaded", targetCountValue = 0, requestId
break;
}
const before = candidates.size;
- for (const candidate of snapshot.candidates || []) {
+ const pageCandidates = (snapshot.candidates || []).flatMap(candidate => {
+ const groups = splitArticleCases(candidate);
+ return groups.length ? groups : [candidate];
+ });
+ for (const candidate of pageCandidates) {
const key = `${candidate.canonicalUrl || ""}\n${candidate.sourceFacts?.itemId || ""}\n${candidate.title || ""}`;
if (!candidates.has(key)) candidates.set(key, candidate);
if (candidates.size >= targetCount) break;
@@ -1252,6 +1258,11 @@ async function startPageCapture(mode = "loaded", targetCountValue = 0, requestId
}
if (activePageCapture?.sessionId === sessionId) activePageCapture = null;
}
+ if (mode === "article") {
+ const groups = (result?.result?.candidates || []).flatMap(splitArticleCases);
+ if (!groups.length) return { ok: false, message: "未识别到可靠的多个案例边界,请保留整篇文章或手动选择内容" };
+ result.result = {...result.result, candidates:groups, captureMode:"list", saveMode:"multiple", articleSplit:true};
+ }
const batch = normalizePageCaptureBatch({
...result?.result,
...(listMode ? {
@@ -1281,6 +1292,14 @@ async function startPageCapture(mode = "loaded", targetCountValue = 0, requestId
}
async function collectPageCaptureTab(tab, options) {
+ let feishuDocument = null;
+ if (/^https:\/\/(?:[^/]+\.)?feishu\.cn\//iu.test(tab.url) && !options.editedRegion) {
+ const [documentResult] = await chrome.scripting.executeScript({
+ target: { tabId: tab.id }, func: collectFeishuDocument,
+ args: [{ sessionId: options.sessionId, timeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs }]
+ });
+ feishuDocument = documentResult?.result || null;
+ }
let siteData = await readPageCaptureSiteData(tab);
if (activePageCapture?.sessionId === options.sessionId && activePageCapture.cancelled) return { candidates: [] };
const adapter = PAGE_CAPTURE_ADAPTERS.find((item) => item.id === siteData?.adapter);
@@ -1312,7 +1331,8 @@ async function collectPageCaptureTab(tab, options) {
maxCandidates: options.maxCandidates,
maxRegionCandidates: PAGE_CAPTURE_QUALITY_LIMITS.maxRegionCandidates,
maxContentTargets: PAGE_CAPTURE_QUALITY_LIMITS.maxContentTargetsPerCandidate,
- maxMedia: PAGE_CAPTURE_LIMITS.maxMediaPerCandidate,
+ feishuDocument,
+ maxMedia: Math.max(PAGE_CAPTURE_LIMITS.maxMediaPerCandidate, feishuDocument?.mediaCount || 0),
maxScrollSteps: PAGE_CAPTURE_LIMITS.maxScrollSteps,
mediaTimeoutMs: PAGE_CAPTURE_LIMITS.navigationTimeoutMs,
maxInlinePixelDataCharacters: PAGE_CAPTURE_LIMITS.maxInlinePixelDataCharacters,
@@ -1502,7 +1522,7 @@ async function previewPageCaptureRegion(tabIdValue, preview) {
});
return result?.result?.ok
? { ok: true }
- : { ok: false, message: "部分内容无法在网页定位,请以保存预览为准" };
+ : { ok: false, message: "原网页暂时无法高亮定位,请在采集预览中核对内容" };
} catch {
return { ok: false, message: "无法在当前网页显示区域高亮" };
}
diff --git a/extension/case-presentation.js b/extension/case-presentation.js
index 4bcdfd6..8c13c0c 100644
--- a/extension/case-presentation.js
+++ b/extension/case-presentation.js
@@ -7,6 +7,7 @@ function usesCreativeCase(entry) {
}
export function usesArticleReader(entry = {}) {
+ if (entry.articleDocument?.blocks?.some(block => block.kind === "table" && block.rows?.length)) return true;
if (usesCreativeCase(entry) || !entry.articleDocument?.blocks?.length) return false;
const role = contentRoleForEntry(entry);
return [CONTENT_ROLES.tutorial, CONTENT_ROLES.reference].includes(role)
diff --git a/extension/collector.html b/extension/collector.html
index c9287ac..73df7dc 100644
--- a/extension/collector.html
+++ b/extension/collector.html
@@ -95,7 +95,7 @@
<section id="page-capture" class="page-capture" hidden aria-live="polite">
<header>
<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>
+ <select id="page-capture-mode" aria-label="采集方式" data-i18n-aria-label="采集方式"><option value="single" data-i18n="单个案例">单个案例</option><option value="list" data-i18n="列表批量">列表批量</option><option value="article" 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>
diff --git a/extension/collector.js b/extension/collector.js
index e53efb5..276fd37 100644
--- a/extension/collector.js
+++ b/extension/collector.js
@@ -164,10 +164,17 @@ elements.clipboardPermissionDialog.addEventListener("cancel", (event) => {
});
elements.pageCaptureScan.addEventListener("click", () => {
pageCaptureListRequested = false;
- void startPageCapture("loaded", elements.pageCaptureScan);
+ void startPageCapture(pageCaptureBatch?.articleSplit ? "article" : "loaded", elements.pageCaptureScan);
});
-elements.pageCaptureMode.addEventListener("change", () => {
- pageCaptureListRequested = elements.pageCaptureMode.value === "list";
+elements.pageCaptureMode.addEventListener("change", async () => {
+ const mode = elements.pageCaptureMode.value;
+ if (mode === "article") { await startPageCapture("article", elements.pageCaptureScan); return; }
+ if (pageCaptureBatch?.articleSplit) {
+ await startPageCapture("loaded", elements.pageCaptureScan);
+ pageCaptureListRequested = mode === "list";
+ render(); return;
+ }
+ pageCaptureListRequested = mode === "list";
if (!pageCaptureListRequested && pageCaptureBatch?.captureMode === "list") void startPageCapture("loaded", elements.pageCaptureScan);
else render();
});
@@ -720,7 +727,7 @@ function renderPageCapture() {
elements.pageCaptureScan.hidden = false;
elements.pageCaptureScan.disabled = busy;
elements.pageCaptureMode.disabled = busy;
- elements.pageCaptureMode.value = listMode || pageCaptureListRequested ? "list" : "single";
+ elements.pageCaptureMode.value = pageCaptureBatch.articleSplit ? "article" : listMode || pageCaptureListRequested ? "list" : "single";
elements.pageCaptureListSetup.hidden = listMode || !pageCaptureListRequested;
elements.pageCaptureListRun.disabled = busy || selectedCount !== 1;
elements.pageCaptureTargetCount.disabled = busy;
@@ -735,7 +742,9 @@ function renderPageCapture() {
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}", {
+ elements.pageCaptureListSummary.textContent = pageCaptureBatch.articleSplit
+ ? t("已拆分 {count} 个案例,另有 {review} 组内容需要核对。", {count:pageCaptureBatch.candidates.length-reviewCount, review:reviewCount})
+ : t("目标 {target} 个,实际识别 {actual} 个。{reason}", {
target: pageCaptureBatch.targetCount,
actual: pageCaptureBatch.candidates.length,
reason: pageCaptureStopReasonLabel(pageCaptureBatch.stopReason)
@@ -961,7 +970,8 @@ async function previewPageCaptureRegion(candidate, locate = false) {
edits: candidate?.region?.edits || [], locate
}
}).catch(() => ({ ok: false, message: t("无法在当前网页显示区域高亮") }));
- if (request === pageCapturePreviewRequest && candidate && !response?.ok) showFeedback(response?.message || t("部分内容无法在网页定位,请以保存预览为准"), true);
+ // Highlight availability is separate from capture/save completeness.
+ if (request === pageCapturePreviewRequest && candidate && !response?.ok) showFeedback(response?.message || t("原网页暂时无法高亮定位,请在采集预览中核对内容"));
}
async function editConfirmedPageCaptureRegion(mode, button) {
@@ -1506,12 +1516,12 @@ async function startPageCapture(mode, button) {
}
});
const normalized = { ...candidate, contentText, textBlocks };
- return representative
+ return representative && !normalized.batchStructureStatus
? { ...normalized, batchStructureStatus: pageCaptureStructureMatches(representative, normalized) ? "matched" : "review" }
: normalized;
});
const batch = normalizePageCaptureBatch({ ...response.batch, candidates, status: "preview" });
- const selections = mode === "list"
+ const selections = mode === "list" || mode === "article"
? batch.candidates.filter((candidate) => candidate.batchStructureStatus !== "review").map((candidate) => normalizePageCaptureSelection({
candidateId: candidate.id,
selectedTextBlockIds: candidate.textBlocks.map((item) => item.id),
diff --git a/extension/feishu-document-capture.js b/extension/feishu-document-capture.js
new file mode 100644
index 0000000..e669497
--- /dev/null
+++ b/extension/feishu-document-capture.js
@@ -0,0 +1,203 @@
+// Runs in the page's isolated world. Accumulate rendered blocks before virtualization removes them.
+export async function collectFeishuDocument({ sessionId, timeoutMs } = {}) {
+ const rootSelector = '.docx-page-block .page-block.root-block';
+ const root = document.querySelector(rootSelector);
+ if (!root || String(window.getSelection?.() || '').trim()) return null;
+ let scroller = root.parentElement;
+ while (scroller && !(scroller.scrollHeight > scroller.clientHeight && /auto|scroll/.test(getComputedStyle(scroller).overflowY))) scroller = scroller.parentElement;
+ if (!scroller) return null;
+ const start = { top: scroller.scrollTop, left: scroller.scrollLeft };
+ let cancelled = false;
+ const cancel = (message, _sender, reply) => {
+ if (message?.type === 'PROMPTDIRECTOR_PAGE_CAPTURE' && message.sessionId === sessionId && message.action === 'cancel') {
+ cancelled = true;
+ reply({ ok: true, cancelled: true });
+ }
+ };
+ chrome.runtime.onMessage.addListener(cancel);
+ const clean = text => String(text || '').replace(/[\u200b\ufeff]/g, '').trim();
+ const escape = text => String(text).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
+ const items = new Map();
+ const pending = new Set();
+ const pendingPositions = new Map();
+ const mediaByKey = new Map();
+ const blobData = new Map();
+ const tables = new Map();
+ const targets = new Map();
+ const marker = `feishu:${sessionId}`;
+ const rootTitle = clean(root.querySelector('h1')?.textContent);
+ let sequence = 0;
+ let timedOut = false;
+ const position = node => {
+ const r = node.getBoundingClientRect(), s = scroller.getBoundingClientRect();
+ return { top: r.top - s.top + scroller.scrollTop, left: r.left - s.left + scroller.scrollLeft };
+ };
+ const ordered = values => [...values].sort((a,b)=>a.top-b.top || a.left-b.left || a.order-b.order);
+ function registerCell(cell) {
+ const table = cell.closest('[data-block-type=table]');
+ const tableId = table?.getAttribute('data-record-id');
+ const cellId = cell.getAttribute('data-record-id');
+ const row = cell.parentElement;
+ const rowKey = row.getAttribute('data-index');
+ if (!tableId || !cellId || rowKey === null || !Number.isFinite(Number(rowKey))) return null;
+ let group = tables.get(tableId);
+ if (!group) { group = { ...position(table), order: sequence++, rows: new Map() }; tables.set(tableId, group); }
+ if (!group.rows.has(rowKey)) group.rows.set(rowKey, new Map());
+ const cells = group.rows.get(rowKey);
+ if (!cells.has(cellId)) cells.set(cellId, { index:[...row.cells].indexOf(cell), rowspan:cell.rowSpan, colspan:cell.colSpan,
+ width:cell.getBoundingClientRect().width, align:getComputedStyle(cell).textAlign, valign:getComputedStyle(cell).verticalAlign, header:cell.tagName==='TH', items:new Map() });
+ return { tableId, cell: cells.get(cellId) };
+ }
+ async function collect() {
+ const current = document.querySelector(rootSelector);
+ if (!current) return false;
+ current.setAttribute('data-promptdirector-capture-region', marker);
+ // Empty cells and rows also carry layout, even when there is no text or media to collect.
+ for (const cell of current.querySelectorAll('td[data-record-id],th[data-record-id]')) registerCell(cell);
+ for (const node of current.querySelectorAll('h1,h2,h3,h4,h5,h6,.zone-container.text-editor,img,video,canvas')) {
+ if (node.closest('nav,aside,[role=complementary],#docCommentContainer')) continue;
+ if (node.matches('img,canvas') && (!node.getBoundingClientRect().width || !node.getBoundingClientRect().height)) continue;
+ if (node.matches('.zone-container.text-editor') && node.closest('h1,h2,h3,h4,h5,h6')) continue;
+ const block = node.closest('[data-record-id]');
+ const identity = block?.getAttribute('data-record-id');
+ const peers = block ? [...block.querySelectorAll('h1,h2,h3,h4,h5,h6,.zone-container.text-editor,img,video,canvas')] : [];
+ const ownImage = node.matches('img') && block?.getAttribute('data-block-type') === 'image';
+ const canvasNode = node.matches('canvas');
+ const key = identity ? `${identity}:${ownImage ? 'image' : canvasNode ? 'canvas' : peers.indexOf(node)}` : node.matches('h1') ? 'title' : '';
+ if (!key) continue;
+ if (canvasNode) {
+ const layers=[...block.querySelectorAll('canvas')].filter(layer=>layer.getBoundingClientRect().width && layer.getBoundingClientRect().height);
+ if (layers[0] !== node) continue;
+ const r=node.getBoundingClientRect(), v=scroller.getBoundingClientRect();
+ if (r.bottom<=v.top || r.top>=v.bottom) continue;
+ }
+ let html = '';
+ const canvas = node.matches('canvas');
+ const image = node.matches('img') || canvas;
+ const video = node.matches('video');
+ const text = clean(node.textContent);
+ if (image || video) {
+ const src = canvas ? '' : node.currentSrc || node.getAttribute('src');
+ if (!canvas && (!src || image && (!node.complete || !node.naturalWidth))) { pending.add(key); pendingPositions.set(key,position(node).top); continue; }
+ let dataUrl = blobData.get(src) || "";
+ if (canvas) {
+ try {
+ const layers=[...block.querySelectorAll('canvas')].filter(layer=>layer.getBoundingClientRect().width && layer.getBoundingClientRect().height);
+ const base=node.getBoundingClientRect();
+ const snapshot=document.createElement('canvas');snapshot.width=node.width;snapshot.height=node.height;
+ const context=snapshot.getContext('2d');
+ for(const layer of layers) {
+ const rect=layer.getBoundingClientRect();
+ context.drawImage(layer,(rect.left-base.left)*node.width/base.width,(rect.top-base.top)*node.height/base.height,rect.width*node.width/base.width,rect.height*node.height/base.height);
+ }
+ dataUrl=snapshot.toDataURL('image/png');
+ }
+ catch { pending.add(key); pendingPositions.set(key,position(node).top); continue; }
+ }
+ if (image && src.startsWith('blob:') && !dataUrl) {
+ try {
+ const response = await fetch(src);
+ if (!response.ok) throw new Error('Image unavailable');
+ const blob = await response.blob();
+ dataUrl = await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(blob);});
+ blobData.set(src,dataUrl);
+ } catch { pending.add(key); pendingPositions.set(key,position(node).top); continue; }
+ }
+ pending.delete(key);
+ const width = node.naturalWidth || node.videoWidth || node.width || 0;
+ const height = node.naturalHeight || node.videoHeight || node.height || 0;
+ const previous = mediaByKey.get(key);
+ if (!canvas && previous && previous.width * previous.height > width * height) continue;
+ const assetId = `feishu-media:${key}`;
+ mediaByKey.set(key,{id:assetId,kind:image?'image':'video',url:src.startsWith('blob:')?'':src,dataUrl,
+ width,height,alt:canvas?'思维导图画面快照':node.alt||'',captureMethod:canvas?'pixel-fallback':dataUrl?'page-session':'source',placement:'inline'});
+ html = image ? `<img data-promptdirector-asset-id="${escape(assetId)}" src="${escape(canvas ? dataUrl : src)}" width="${width}" height="${height}" alt="${escape(node.alt || '')}">` : `<video controls src="${escape(src)}" poster="${escape(node.poster || '')}"></video>`;
+ } else {
+ if (!text) continue;
+ const tag = /^H[1-6]$/.test(node.tagName) ? node.tagName.toLowerCase() : 'p';
+ const clone = node.cloneNode(true);
+ for (const line of clone.querySelectorAll('div')) {
+ const span = document.createElement('span'); span.innerHTML = line.innerHTML;
+ if (line.nextSibling) span.append(document.createElement('br'));
+ line.replaceWith(span);
+ }
+ for (const element of clone.querySelectorAll('*')) for (const attr of [...element.attributes]) {
+ if (!['href','style'].includes(attr.name)) element.removeAttribute(attr.name);
+ }
+ html = `<${tag}>${clone.innerHTML}</${tag}>`;
+ }
+ const old = items.get(key);
+ const item = { key, html, ...position(node), order: old?.order ?? sequence++ };
+ const cell = node.closest('td[data-record-id],th[data-record-id]');
+ const table = cell?.closest('[data-block-type=table]');
+ if (cell && table) {
+ const registered = registerCell(cell);
+ if (!registered) continue;
+ registered.cell.items.set(key, item);
+ item.table = registered.tableId;
+ }
+ items.set(key, item);
+ if (identity && !image && !video) targets.set(key, { kind:'text',path:`[data-record-id="${identity}"] .zone-container.text-editor`,articleBlockIds:[],mediaIds:[] });
+ }
+ return true;
+ }
+ async function settle() {
+ // Require a quiet DOM after scroll-triggered asynchronous block rendering.
+ await new Promise(resolve => {
+ let quiet;
+ const done = () => { clearTimeout(quiet); clearTimeout(deadline); observer.disconnect(); resolve(); };
+ const changed = () => { clearTimeout(quiet); quiet = setTimeout(done, 150); };
+ const observer = new MutationObserver(changed);
+ observer.observe(root, { childList:true, subtree:true, characterData:true });
+ const deadline = setTimeout(()=>{ timedOut=true; done(); }, timeoutMs);
+ changed();
+ });
+ const images = [...(document.querySelector(rootSelector)?.querySelectorAll('img') || [])].filter(node => {
+ const r=node.getBoundingClientRect(), s=scroller.getBoundingClientRect(); return r.bottom>s.top && r.top<s.bottom;
+ });
+ let timer;
+ await Promise.race([Promise.allSettled(images.map(node=>node.decode())),new Promise(resolve=>{timer=setTimeout(()=>{timedOut=true;resolve();},timeoutMs);})]);
+ clearTimeout(timer);
+ }
+ let reachedEnd = false;
+ try {
+ scroller.scrollTo({top:0,left:0,behavior:'instant'});
+ let bottomPasses = 0;
+ while (!cancelled) {
+ await settle();
+ if (!await collect()) break;
+ const end = Math.max(0, scroller.scrollHeight-scroller.clientHeight);
+ if (scroller.scrollTop >= end-1) {
+ bottomPasses += 1;
+ if (bottomPasses >= 2) { reachedEnd=true; break; }
+ } else bottomPasses=0;
+ const next = Math.min(end, scroller.scrollTop + Math.max(1,Math.floor(scroller.clientHeight * 0.85)));
+ const previous=scroller.scrollTop;
+ scroller.scrollTo({top:next,behavior:'instant'});
+ if (next>previous && scroller.scrollTop===previous) break;
+ }
+ // Revisit unloaded media once it has a chance to enter the viewport, including clipped table cells.
+ for (const key of [...pending]) {
+ if (cancelled) break;
+ scroller.scrollTo({top:pendingPositions.get(key),behavior:'instant'});
+ await settle();
+ const recordId=key.slice(0,key.lastIndexOf(':'));
+ const node=document.querySelector(`[data-record-id="${recordId}"] img`);
+ node?.scrollIntoView({block:'center',inline:'nearest',behavior:'instant'});
+ await settle();
+ await collect();
+ }
+ } finally {
+ scroller.scrollTo({...start,behavior:'instant'});
+ chrome.runtime.onMessage.removeListener(cancel);
+ }
+ const output = ordered([...items.values()].filter(item=>!item.table));
+ for (const table of tables.values()) {
+ const rows=[...table.rows].sort((a,b)=>Number(a[0])-Number(b[0])).map(([,cells])=>'<tr>'+[...cells.values()].sort((a,b)=>a.index-b.index).map(cell=>`<${cell.header?'th':'td'} rowspan="${cell.rowspan}" colspan="${cell.colspan}" width="${cell.width}" align="${escape(cell.align)}" valign="${escape(cell.valign)}">${ordered(cell.items.values()).map(item=>item.html).join('')}</${cell.header?'th':'td'}>`).join('')+'</tr>').join('');
+ output.push({...table,html:`<table>${rows}</table>`});
+ }
+ const html=ordered(output).map(item=>item.html).join('\n');
+ const fragment=document.createElement('div');fragment.innerHTML=html;
+ return { html, media:[...mediaByKey.values()], title:rootTitle, text:clean(fragment.textContent), mediaCount:fragment.querySelectorAll('img,video').length,
+ complete:reachedEnd&&!cancelled&&!timedOut&&!pending.size, pendingMediaCount:pending.size, reachedEnd, timedOut, cancelled, marker, targets:[...targets.values()] };
+}
diff --git a/extension/i18n.js b/extension/i18n.js
index d471892..ade2f62 100644
--- a/extension/i18n.js
+++ b/extension/i18n.js
@@ -1,6 +1,9 @@
import { normalizeUiPreferences, resolveLocale } from "./preferences.js";
const EN = Object.freeze({
+ "文章内案例": "Cases within article",
+ "已拆分 {count} 个案例,另有 {review} 组内容需要核对。": "Split into {count} cases; {review} additional groups need review.",
+ "未识别到可靠的多个案例边界,请保留整篇文章或手动选择内容": "No reliable boundaries between multiple cases were found. Keep the full article or select content manually.",
"案例库:按需;仅在你要求查询或参考时使用,点击关闭": "Library: on demand. Used only when you ask to search or reference it. Click to turn off.",
"案例库:关闭,点击开启": "Library: off. Click to enable.",
"当前模型未声明工具能力,可通过选择案例手动查询;点击关闭案例库": "Tool support is not declared for this model. Search manually using Select cases. Click to disable the library.",
@@ -51,7 +54,7 @@ const EN = Object.freeze({
"停止扫描": "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.",
+ "原网页暂时无法高亮定位,请在采集预览中核对内容": "Highlighting is temporarily unavailable on the source page. Check the capture preview.",
"无法在当前网页显示区域高亮": "Could not highlight content on this page",
"清理升级临时文件": "Clear temporary update files",
diff --git a/extension/library.css b/extension/library.css
index 13b8cb5..df1b797 100644
--- a/extension/library.css
+++ b/extension/library.css
@@ -1545,3 +1545,11 @@ details:not([open]) > .selection-menu-panel { display: none; }
html[lang="en"] .share-dialog-options { grid-template-columns: minmax(0, 1fr); }
}
#settings-ai-panel .ai-model-choice { font-weight: 400; }
+
+.article-table-scroll { max-width: 100%; overflow-x: auto; }
+.article-structured-table { border-collapse: collapse; width: 100%; font-weight: 400; }
+.article-structured-table td, .article-structured-table th { border: 1px solid var(--line); padding: 12px; vertical-align: top; min-width: 180px; text-align: left; }
+.article-structured-table th { background: var(--raised); }
+.article-structured-table td > * + *, .article-structured-table th > * + * { margin-top: 12px; }
+.article-structured-table .article-document-media { margin: 12px 0; }
+.article-structured-table .article-document-image { max-width: 100%; height: auto; }
diff --git a/extension/library.js b/extension/library.js
index 5fd1f0d..d383913 100644
--- a/extension/library.js
+++ b/extension/library.js
@@ -5504,63 +5504,89 @@ async function createArticleDocumentReader(entryValue) {
const entry = normalizeEntryMedia(entryValue);
const reader = el("article", "article-document-reader");
const assets = new Map(entry.mediaAssets.map((asset) => [asset.id, asset]));
- for (const block of entry.articleDocument?.blocks || []) {
- if (block.kind === "heading") {
- const heading = rawTextEl(`h${Math.min(6, Math.max(1, Number(block.level) || 2))}`, "", block.text);
- heading.dataset.articleBlockId = block.id;
- reader.append(heading);
- continue;
- }
- if (["paragraph", "list", "quote", "code", "table"].includes(block.kind)) {
- 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);
- renderArticleBlockText(node, block);
- node.dataset.articleBlockId = block.id;
- reader.append(node);
- continue;
- }
- const asset = block.assetId ? assets.get(block.assetId) : null;
- if (block.kind === "image") {
- const figure = el("figure", "article-document-media");
- if (asset?.kind === "image" && asset.storageMode === "managed") {
- const image = document.createElement("img");
- image.className = "article-document-image";
- image.classList.toggle("has-alpha-channel", alphaCapableImage(asset));
- image.alt = block.label || entry.title;
- image.src = await originalScreenshotUrl(asset.id);
- image.loading = "lazy";
- image.addEventListener("click", () => openImageLightbox(image, entry));
- figure.append(image);
- } else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开原图"));
- if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
- reader.append(figure);
- continue;
- }
- if (block.kind === "video") {
- const figure = el("figure", "article-document-media article-document-video");
- if (asset?.kind === "video" && asset.storageMode !== "reference") figure.append(await createMediaViewer(asset, "", entry));
- else if (asset?.kind === "video") figure.append(await createCompactCapturedMedia(entry, asset));
- else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开视频来源"));
- if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
- reader.append(figure);
- continue;
- }
- if (["document", "attachment", "link"].includes(block.kind)) {
- const card = el("div", "article-document-resource");
- card.append(
- rawTextEl("span", "article-document-resource-type", block.kind === "attachment" ? "SKILL" : block.kind === "document" ? "DOC" : "LINK"),
- rawTextEl("strong", "", block.label || asset?.sourceTitle || t("文章资源"))
- );
- const sourceUrl = block.sourceUrl || asset?.sourceUrl || "";
- if (sourceUrl) card.append(articleSourceLink(sourceUrl, asset ? "打开来源" : "打开链接"));
- if (["document", "attachment"].includes(asset?.kind) && asset.storageMode === "managed") {
- const blob = await getMediaBlob(asset.id);
- if (blob) card.append(managedAssetDownloadLink(asset, rememberDetailBlobUrl(blob)));
- card.append(rawTextEl("small", "", t("本地副本已保存在案例媒体中")));
+ const allBlocks = entry.articleDocument?.blocks || [];
+ const blockById = new Map(allBlocks.map(block => [block.id, block]));
+ const cellOwned = new Set(allBlocks.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
+ async function appendBlocks(reader, blocks) {
+ for (const block of blocks) {
+ if (block.kind === "table" && block.rows) {
+ const wrap = el("div", "article-table-scroll");
+ const table = el("table", "article-structured-table");
+ const body = document.createElement("tbody");
+ for (const row of block.rows) {
+ const tr = document.createElement("tr");
+ for (const cell of row) {
+ const td = document.createElement(cell.header ? "th" : "td");
+ td.rowSpan = cell.rowspan; td.colSpan = cell.colspan;
+ if (cell.align) td.style.textAlign = cell.align;
+ if (cell.valign) td.style.verticalAlign = cell.valign;
+ if (cell.width) td.style.minWidth = `${cell.width}px`;
+ await appendBlocks(td, cell.blockIds.map(id => blockById.get(id)).filter(Boolean));
+ tr.append(td);
+ }
+ body.append(tr);
+ }
+ table.append(body); wrap.append(table); reader.append(wrap);
+ continue;
+ }
+ if (block.kind === "heading") {
+ const heading = rawTextEl(`h${Math.min(6, Math.max(1, Number(block.level) || 2))}`, "", block.text);
+ heading.dataset.articleBlockId = block.id;
+ reader.append(heading);
+ continue;
+ }
+ if (["paragraph", "list", "quote", "code", "table"].includes(block.kind)) {
+ 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);
+ renderArticleBlockText(node, block);
+ node.dataset.articleBlockId = block.id;
+ reader.append(node);
+ continue;
+ }
+ const asset = block.assetId ? assets.get(block.assetId) : null;
+ if (block.kind === "image") {
+ const figure = el("figure", "article-document-media");
+ if (asset?.kind === "image" && asset.storageMode === "managed") {
+ const image = document.createElement("img");
+ image.className = "article-document-image";
+ image.classList.toggle("has-alpha-channel", alphaCapableImage(asset));
+ image.alt = block.label || entry.title;
+ image.src = await originalScreenshotUrl(asset.id);
+ image.loading = "lazy";
+ image.addEventListener("click", () => openImageLightbox(image, entry));
+ figure.append(image);
+ } else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开原图"));
+ if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
+ reader.append(figure);
+ continue;
+ }
+ if (block.kind === "video") {
+ const figure = el("figure", "article-document-media article-document-video");
+ if (asset?.kind === "video" && asset.storageMode !== "reference") figure.append(await createMediaViewer(asset, "", entry));
+ else if (asset?.kind === "video") figure.append(await createCompactCapturedMedia(entry, asset));
+ else figure.append(articleSourceLink(block.sourceUrl, block.label || "打开视频来源"));
+ if (block.label) figure.append(rawTextEl("figcaption", "", block.label));
+ reader.append(figure);
+ continue;
+ }
+ if (["document", "attachment", "link"].includes(block.kind)) {
+ const card = el("div", "article-document-resource");
+ card.append(
+ rawTextEl("span", "article-document-resource-type", block.kind === "attachment" ? "SKILL" : block.kind === "document" ? "DOC" : "LINK"),
+ rawTextEl("strong", "", block.label || asset?.sourceTitle || t("文章资源"))
+ );
+ const sourceUrl = block.sourceUrl || asset?.sourceUrl || "";
+ if (sourceUrl) card.append(articleSourceLink(sourceUrl, asset ? "打开来源" : "打开链接"));
+ if (["document", "attachment"].includes(asset?.kind) && asset.storageMode === "managed") {
+ const blob = await getMediaBlob(asset.id);
+ if (blob) card.append(managedAssetDownloadLink(asset, rememberDetailBlobUrl(blob)));
+ card.append(rawTextEl("small", "", t("本地副本已保存在案例媒体中")));
+ }
+ reader.append(card);
}
- reader.append(card);
}
}
+ await appendBlocks(reader, allBlocks.filter(block => !cellOwned.has(block.id)));
attachArticleEditor(reader, entry, {
t, onError: error => showFeedback(error.message, true),
contextParts: [entry.sourceFacts?.author, entry.sourceFacts?.handle ? `@${entry.sourceFacts.handle}` : "",
diff --git a/extension/manifest.json b/extension/manifest.json
index 982f90e..850e118 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "__MSG_extensionName__",
- "version": "1.20.7",
+ "version": "1.20.8",
"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/extension/page-capture-adapter-registry.js b/extension/page-capture-adapter-registry.js
index f74ae5f..806217b 100644
--- a/extension/page-capture-adapter-registry.js
+++ b/extension/page-capture-adapter-registry.js
@@ -60,9 +60,19 @@ export const PAGE_CAPTURE_ADAPTERS = Object.freeze([
adapter("douban", "豆瓣相册", ["douban.com"], "generic", ["main article", ".photo_wrap", ".photolst li"]),
adapter("poco", "POCO", ["poco.cn"], "generic", ["main article", "[class*=work]"]),
+ adapter("xiaoheihe", "小黑盒", ["xiaoheihe.cn"], "verified-declarative", [], {
+ content: [".hb-article", ".hb-bbs-image-text"],
+ contentRequiredPathPrefixes: ["/app/bbs/link/"],
+ contentParts: [".image-text__header-image .swiper-wrapper", ".image-text__content"],
+ title: [".section-title__content"], author: [".link-user__username"]
+ }),
adapter("wechat", "微信公众号", ["mp.weixin.qq.com"], "verified-declarative", ["#js_content"], {
- title: ["#activity-name"], author: ["#js_name"], publishedAt: ["#publish_time", "em#publish_time"]
+ content: ["#js_content"], title: ["#activity-name"], author: ["#js_name"], publishedAt: ["#publish_time", "em#publish_time"]
}, ["qpic.cn", "qlogo.cn"]),
+ adapter("feishu", "飞书文档", ["feishu.cn"], "verified-declarative", [], {
+ content: [".docx-page-block .page-block.root-block"],
+ title: ["h1.page-block-content"]
+ }),
adapter("medium", "Medium", ["medium.com"], "generic", ["main article", "article"]),
adapter("jd", "京东", ["jd.com"], "generic", ["main", "[class*=product-intro]"]),
diff --git a/extension/page-capture.js b/extension/page-capture.js
index 99be3e4..828201e 100644
--- a/extension/page-capture.js
+++ b/extension/page-capture.js
@@ -40,11 +40,12 @@ export function reconcilePageCaptureArticlePlacement({ articleDocument, media: m
const blocksById = new Map(documentValue.blocks.map((block) => [block.id, block]));
const blocksByAssetId = new Map(documentValue.blocks.flatMap((block) => block.assetId ? [[block.assetId, block]] : []));
const inlineIds = new Set(documentValue.blocks.flatMap((block) => block.assetId && mediaById.has(block.assetId) ? [block.assetId] : []));
+ const tableCellIds = new Set(documentValue.blocks.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
const emittedBlockIds = new Set();
const emittedAssetIds = new Set();
const orderedBlocks = [];
const emit = (block) => {
- if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId)) return;
+ if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId) && !tableCellIds.has(block.id)) return;
emittedBlockIds.add(block.id);
if (block.assetId) emittedAssetIds.add(block.assetId);
orderedBlocks.push(block);
@@ -104,6 +105,7 @@ export function normalizePageCaptureBatch(value = {}) {
sourceUrl: safeUrl(value.sourceUrl),
adapter: clean(value.adapter) || "generic",
captureMode: value.captureMode === "list" ? "list" : "single",
+ articleSplit: value.articleSplit === true,
saveMode: value.saveMode === "combined" ? "combined" : value.saveMode === "multiple" ? "multiple" : value.captureMode === "list" ? "" : "single",
combinedTitle: clean(value.combinedTitle),
targetCount: positiveInteger(value.targetCount, 0),
@@ -139,7 +141,8 @@ export function combinePageCaptureCandidates(values = [], options = {}) {
const blocks = documentValue?.blocks || [];
return [
{ id: `combined:${index}:title`, kind: "heading", level: 2, text: candidate.title, sourceOrder: 0 },
- ...blocks.map((block) => ({ ...block, id: `combined:${index}:${block.id}` }))
+ ...blocks.map((block) => ({ ...block, id: `combined:${index}:${block.id}`,
+ ...(block.rows ? { rows: block.rows.map(row => row.map(cell => ({ ...cell, blockIds: cell.blockIds.map(id => `combined:${index}:${id}`) }))) } : {}) }))
];
}).map((block, sourceOrder) => ({ ...block, sourceOrder }));
return normalizePageCaptureCandidate({
@@ -328,12 +331,14 @@ export function pageCaptureStructureMatches(referenceValue, candidateValue) {
function filterCandidateArticleDocument(value, selection) {
const documentValue = normalizeArticleDocument(value);
if (!documentValue) return null;
+ const selectedChildren = new Set(documentValue.blocks.filter(block => block.rows && selection.includeText && (selection.selectedAllText || selection.selectedTextBlockIds.has(block.id)))
+ .flatMap(block => block.rows.flatMap(row => row.flatMap(cell => cell.blockIds))));
return normalizeArticleDocument({
...documentValue,
blocks: documentValue.blocks.filter((block) => {
if (["image", "video", "document", "attachment"].includes(block.kind)) return selection.selectedMediaIds.has(block.assetId);
if (block.kind === "link") return true;
- return selection.includeText && (selection.selectedAllText || selection.selectedTextBlockIds.has(block.id));
+ return selection.includeText && (selection.selectedAllText || selection.selectedTextBlockIds.has(block.id) || selectedChildren.has(block.id));
})
});
}
@@ -612,7 +617,8 @@ export async function resolvePageCaptureImage(mediaValue = {}, options = {}) {
const dataUrl = safeImageDataUrl(mediaValue.dataUrl || mediaValue.previewDataUrl);
if (dataUrl) {
try {
- return { blob: await options.decodeDataUrl(dataUrl), sourceUrl: "", captureMethod: "pixel-fallback", usedPixelFallback: true, failures };
+ const sessionBytes = mediaValue.captureMethod === "page-session" && Boolean(mediaValue.dataUrl);
+ return { blob: await options.decodeDataUrl(dataUrl), sourceUrl: "", captureMethod: sessionBytes ? "page-session" : "pixel-fallback", usedPixelFallback: !sessionBytes, failures };
} catch (error) {
failures.push({ url: "pixel-fallback", message: String(error?.message || error) });
}
@@ -628,6 +634,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
const capturedAt = new Date().toISOString();
const sessionId = clean(options.sessionId);
let cancelled = false;
+ let scanIncomplete = false;
const cancellation = new AbortController();
const handleCaptureMessage = (message, _sender, sendResponse) => {
if (message?.type !== "PROMPTDIRECTOR_PAGE_CAPTURE" || message.sessionId !== sessionId) return undefined;
@@ -641,7 +648,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
};
if (sessionId) globalThis.chrome?.runtime?.onMessage?.addListener?.(handleCaptureMessage);
const maxCandidates = positiveInteger(options.maxCandidates, 100);
- const maxMedia = positiveInteger(options.maxMedia, 24);
+ let maxMedia = positiveInteger(options.maxMedia, 24);
const maxInlinePixelDataCharacters = positiveInteger(options.maxInlinePixelDataCharacters, 1);
const wholePage = options.mode === "whole";
const originalScroll = { x: window.scrollX, y: window.scrollY };
@@ -659,17 +666,28 @@ export async function collectPageCaptureSnapshot(options = {}) {
element.removeAttribute?.("data-promptdirector-capture-region");
}
const adapter = detectAdapter(location.hostname);
- const pendingContentMedia = await prepareContentMedia(adapter) + (Number(options.downloads?.failures) || 0);
+ const declaredContent = (adapter.fields?.content || []).map(selector => document.querySelector(selector)).find(Boolean);
+ if (declaredContent) maxMedia = Math.max(maxMedia, declaredContent.querySelectorAll("img,video").length);
+ const pendingContentMedia = (options.feishuDocument ? 0 : await prepareArticleImages(declaredContent)) + await prepareContentMedia(adapter) + (Number(options.downloads?.failures) || 0) + (Number(options.feishuDocument?.pendingMediaCount) || 0);
const canonicalUrl = safeHttpUrl(document.querySelector('link[rel="canonical"]')?.href || location.href);
const metadata = collectMetadata();
const structured = collectStructuredData();
const article = readArticle();
const siteData = options.siteData && typeof options.siteData === "object" ? options.siteData : null;
const pageSelection = options.mode === "whole" ? null : collectPageSelection();
- const contentRoot = !pageSelection
+ let contentRoot = !pageSelection
? (adapter.fields?.content || []).map((selector) => document.querySelector(selector))
.find((element) => cleanBlockText(element?.innerText)) || null
: null;
+ if (adapter.id === "feishu" && options.feishuDocument?.html && !pageSelection) {
+ contentRoot = document.createElement("div");
+ contentRoot.innerHTML = options.feishuDocument.html;
+ }
+ // A known document route without its body must not turn navigation into a case.
+ const requiresContentRoot = adapter.id === "feishu" || (adapter.fields?.contentRequiredPathPrefixes || []).some(prefix => location.pathname.startsWith(prefix));
+ if (requiresContentRoot && !contentRoot && !pageSelection && !editedRoot) {
+ return { id: sessionId, sourceUrl: canonicalUrl, adapter: adapter.id, candidates: [], capturedAt, siteStatus: "partial" };
+ }
if (editedRoot) {
const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: 0 });
const candidate = candidateForRoot(editedRoot, 0, {
@@ -721,6 +739,53 @@ export async function collectPageCaptureSnapshot(options = {}) {
return { id: sessionId, sourceUrl: canonicalUrl, adapter: adapter.id, candidates, capturedAt };
}
}
+ // A single semantic article is a document, not a feed of its paragraphs.
+ const semanticArticles = !contentRoot && !siteData && !pageSelection && adapter.id === "generic"
+ ? [...document.querySelectorAll("main article,[role=main] article,article[role=document],[role=document]")]
+ .filter(node => (node.matches("[role=document]") || node.querySelector("h1")) && !node.closest("nav,aside,[role=navigation],[role=complementary]") && !node.parentElement?.closest("article,[role=document]"))
+ : [];
+ let documentRoot = semanticArticles.length === 1 ? semanticArticles[0] : null;
+ if (documentRoot && !wholePage) {
+ let internalScroll = false;
+ for (let node = documentRoot; node && node !== document.body && node !== document.documentElement; node = node.parentElement) {
+ if (node.scrollHeight > node.clientHeight && /auto|scroll/u.test(getComputedStyle(node).overflowY)) { internalScroll = true; break; }
+ }
+ if (!internalScroll) documentRoot = null;
+ }
+ if (documentRoot) contentRoot = documentRoot;
+ const documentParts = new Map();
+ const documentNodes = new WeakMap();
+ let documentSequence = 0;
+ const collectDocumentParts = () => {
+ if (!documentRoot) return;
+ const selector = "h1,h2,h3,h4,h5,h6,p,ul,ol,blockquote,pre,table,figure,img,video";
+ if ([...documentParts.values()].some(part => !part.identity && !part.node.isConnected)) scanIncomplete = true;
+ for (const node of documentRoot.querySelectorAll(selector)) {
+ if (isPageChrome(node) || node.parentElement?.closest(selector)) continue;
+ const identity = node.id || node.getAttribute("data-block-id") || node.getAttribute("data-record-id");
+ let key = identity ? `${node.tagName}:${identity}` : documentNodes.get(node);
+ if (!key) { key = `node:${documentSequence++}`; documentNodes.set(node, key); }
+ const previous = documentParts.get(key);
+ // Without a stable ID, detached/recycled blocks cannot prove document continuity.
+ if (previous && !identity && previous.text !== node.textContent) scanIncomplete = true;
+ const rect = node.getBoundingClientRect();
+ let offset = 0;
+ for (let parent = node.parentElement; parent && parent !== documentRoot.parentElement; parent = parent.parentElement) offset += parent.scrollTop;
+ const clone = node.cloneNode(true);
+ // Resolve relative and lazy image URLs before the live node disappears.
+ const sourceImages = node.matches("img") ? [node] : [...node.querySelectorAll("img")];
+ const clonedImages = clone.matches("img") ? [clone] : [...clone.querySelectorAll("img")];
+ sourceImages.forEach((image, index) => {
+ const url = collectImageVariants(image)[0]?.url || safeHttpUrl(image.currentSrc || image.src);
+ if (url) clonedImages[index].setAttribute("src", url);
+ else scanIncomplete = true;
+ });
+ if (previous && node.matches("table") && previous.text !== node.textContent) scanIncomplete = true;
+ documentParts.set(key, { identity, node, text: node.textContent, html: clone.outerHTML,
+ top: rect.top - documentRoot.getBoundingClientRect().top + offset, left: rect.left,
+ order: previous?.order ?? documentParts.size });
+ }
+ };
const accumulated = new Map();
const collectVisible = () => {
if (contentRoot || siteData?.pageKind === "detail") return [];
@@ -739,6 +804,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
return current;
};
const collectVisibleWithFallbacks = async () => {
+ collectDocumentParts();
const current = collectVisible();
await attachViewportFallbacks(current);
for (const candidate of current) {
@@ -746,15 +812,25 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
};
await collectVisibleWithFallbacks();
- if (wholePage) await scanLoadedPage(collectVisibleWithFallbacks);
- await collectVisibleWithFallbacks();
+ if (wholePage || documentRoot) await scanLoadedPage(collectVisibleWithFallbacks, contentRoot);
+ if (!documentRoot) await collectVisibleWithFallbacks();
+ if (documentRoot && documentParts.size) {
+ contentRoot = document.createElement("div");
+ contentRoot.innerHTML = [...documentParts.values()].sort((a,b) => a.top-b.top || a.left-b.left || a.order-b.order).map(part => part.html).join("\n");
+ }
+ const documentMediaLimit = documentRoot ? Math.max(maxMedia, contentRoot.querySelectorAll("img,video").length) : maxMedia;
const capturedCards = [...accumulated.values()];
const pageType = detectPageType({ adapter, metadata, structured, article, cardCount: capturedCards.length });
const pageRoot = contentRoot || document.body;
const bodyCandidate = candidateForRoot(pageRoot, 0, {
- adapter, metadata, structured, article, siteData, pageSelection, canonicalUrl,
- pageType: contentRoot ? "article" : siteData?.pageType || pageType, maxMedia, pageRoot, contentRoot
+ adapter, metadata, structured, article: contentRoot ? null : article, siteData, pageSelection, canonicalUrl,
+ pageType: contentRoot ? "article" : siteData?.pageType || pageType, maxMedia: documentMediaLimit, pageRoot, contentRoot
});
+ if (bodyCandidate && documentRoot) {
+ bodyCandidate.region = markCaptureRegion(documentRoot, 0, bodyCandidate.contentText, bodyCandidate.media.length);
+ if (bodyCandidate.region) bodyCandidate.region.contentTargets = collectContentTargets(documentRoot,
+ bodyCandidate.articleDocument?.blocks || [], bodyCandidate.media, positiveInteger(options.maxContentTargets, 200));
+ }
if (bodyCandidate) await attachViewportFallbacks([bodyCandidate]);
const regionCandidates = !contentRoot && !siteData && !pageSelection && !["feed", "gallery"].includes(pageType)
? collectSubjectRegionRoots(positiveInteger(options.maxRegionCandidates, 5)).flatMap((root, index) => {
@@ -769,7 +845,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
? capturedCards.slice(0, maxCandidates)
: regionCandidates.length ? regionCandidates
: bodyCandidate ? [bodyCandidate] : capturedCards.slice(0, maxCandidates);
- if (pendingContentMedia) {
+ if (pendingContentMedia || scanIncomplete) {
for (const candidate of candidates) {
candidate.completeness = "partial";
candidate.sourceFacts.status = "partial";
@@ -788,28 +864,45 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (sessionId) globalThis.chrome?.runtime?.onMessage?.removeListener?.(handleCaptureMessage);
}
- async function scanLoadedPage(collectVisible) {
+ async function scanLoadedPage(collectVisible, contentHint = null) {
const maxSteps = positiveInteger(options.maxScrollSteps, 30);
const feedRoot = options.siteData?.adapter === "jimeng" ? document.querySelector?.('[aria-label="Explore content"]') : null;
let scrollRoot = null;
- if (feedRoot) {
- for (let element = feedRoot.parentElement;
- element && element !== document.body; element = element.parentElement) {
+ const anchors = feedRoot ? [feedRoot] : contentHint?.isConnected ? [contentHint]
+ : [...document.querySelectorAll("main,[role=main]")].filter(node => !node.closest("nav,aside,[role=navigation],[role=complementary]"));
+ const roots = new Set();
+ if (!feedRoot && !contentHint) {
+ for (const main of [...anchors]) {
+ for (const node of main.querySelectorAll("article,[role=feed],[role=list]")) {
+ if (!node.closest("nav,aside,[role=navigation],[role=complementary]")) anchors.push(node);
+ }
+ }
+ }
+ for (const anchor of anchors) {
+ for (let element = feedRoot ? anchor.parentElement : anchor; element && element !== document.body && element !== document.documentElement; element = element.parentElement) {
if (element.scrollHeight > element.clientHeight && /auto|scroll/u.test(getComputedStyle(element).overflowY)) {
- scrollRoot = element;
- break;
+ roots.add(element); break;
}
}
}
+ if (roots.size === 1) scrollRoot = [...roots][0];
+ else if (roots.size > 1) { scanIncomplete = true; return; }
const start = scrollRoot ? { top: scrollRoot.scrollTop, left: scrollRoot.scrollLeft } : null;
let stableRounds = 0;
let previousPosition = -1;
try {
+ if (!feedRoot) {
+ (scrollRoot || window).scrollTo({ top: 0, behavior: "instant" });
+ await waitForScrollRender(scrollRoot || document.body);
+ await waitForVisibleMedia();
+ await collectVisible();
+ }
for (let step = 0; step < maxSteps && stableRounds < 3 && !cancelled; step += 1) {
const height = scrollRoot ? scrollRoot.scrollHeight : Math.max(document.body?.scrollHeight || 0, document.documentElement.scrollHeight);
const viewport = Math.max(1, scrollRoot ? scrollRoot.clientHeight : Number(window.innerHeight) || 720);
const nextTop = Math.min(Math.max(0, height - viewport), Math.max(0, scrollRoot ? scrollRoot.scrollTop : window.scrollY) + Math.round(viewport * 0.85));
(scrollRoot || window).scrollTo({ top: nextTop, behavior: "instant" });
+ if (!feedRoot) await waitForScrollRender(scrollRoot || document.body);
await waitForVisibleMedia();
if (feedRoot?.getAttribute?.("aria-busy") === "true" && !cancelled) {
await new Promise((resolve, reject) => {
@@ -833,15 +926,58 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (feedRoot && [...feedRoot.querySelectorAll?.(".masonry-layout-item[data-index]") || []]
.some((element) => Number(element.getAttribute("data-index")) + 1 >= maxCandidates)) break;
const nextHeight = scrollRoot ? scrollRoot.scrollHeight : Math.max(document.body?.scrollHeight || 0, document.documentElement.scrollHeight);
- const position = Math.max(0, Number(scrollRoot ? scrollRoot.scrollTop : window.scrollY) || nextTop);
+ const position = Math.max(0, Number(scrollRoot ? scrollRoot.scrollTop : window.scrollY) || 0);
stableRounds = position === previousPosition && position + viewport >= nextHeight ? stableRounds + 1 : 0;
previousPosition = position;
}
+ if (!feedRoot && (stableRounds < 3 || cancelled)) scanIncomplete = true;
} finally {
if (scrollRoot) scrollRoot.scrollTo({ ...start, behavior: "instant" });
}
}
+ async function waitForScrollRender(root) {
+ if (typeof MutationObserver !== "function" || !root) return;
+ // Two paint frames allow scroll handlers to run; then require a quiet render interval.
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ if (cancelled) return;
+ await new Promise(resolve => {
+ let quiet;
+ const finish = () => { clearTimeout(quiet); clearTimeout(deadline); observer.disconnect(); cancellation.signal.removeEventListener("abort", finish); resolve(); };
+ const changed = () => { clearTimeout(quiet); quiet = setTimeout(() => {
+ if (root.matches?.('[aria-busy="true"]') || root.querySelector?.('[aria-busy="true"]')) return;
+ finish();
+ }, 150); };
+ const observer = new MutationObserver(changed);
+ observer.observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["aria-busy"] });
+ const deadline = setTimeout(() => { scanIncomplete = true; finish(); }, positiveInteger(options.mediaTimeoutMs, 1200));
+ cancellation.signal.addEventListener("abort", finish, { once: true });
+ changed();
+ });
+ }
+
+ async function prepareArticleImages(root) {
+ if (!root) return 0;
+ const images = [...root.querySelectorAll("img")];
+ const pending = images.filter(image => !collectImageVariants(image).length);
+ if (!pending.length) return 0;
+ const positions = [];
+ for (let node = root; node; node = node.parentElement) positions.push({node,top:node.scrollTop,left:node.scrollLeft});
+ const windowPosition = {left:window.scrollX,top:window.scrollY};
+ try {
+ for (const image of pending) {
+ if (cancelled) break;
+ image.scrollIntoView({block:"center",inline:"nearest",behavior:"instant"});
+ await waitForScrollRender(root);
+ await waitForVisibleMedia();
+ }
+ } finally {
+ for (const {node,top,left} of positions) node.scrollTo?.({top,left,behavior:"instant"});
+ window.scrollTo({...windowPosition,behavior:"instant"});
+ }
+ return images.filter(image => !collectImageVariants(image).length).length;
+ }
+
async function prepareContentMedia(adapter) {
const root = (adapter.fields?.content || []).map((selector) => document.querySelector(selector)).find(Boolean);
if (!root || !adapter.fields?.mediaContainers?.length || typeof MutationObserver !== "function") return 0;
@@ -1023,11 +1159,12 @@ export async function collectPageCaptureSnapshot(options = {}) {
const blocksById = new Map(blocks.map((block) => [block.id, block]));
const blocksByAssetId = new Map(blocks.flatMap((block) => block.assetId ? [[block.assetId, block]] : []));
const inlineIds = new Set(blocks.flatMap((block) => block.assetId && mediaById.has(block.assetId) ? [block.assetId] : []));
+ const tableCellIds = new Set(blocks.flatMap(block => (block.rows || []).flatMap(row => row.flatMap(cell => cell.blockIds))));
const emittedBlockIds = new Set();
const emittedAssetIds = new Set();
const orderedBlocks = [];
const emit = (block) => {
- if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId)) return;
+ if (!block || emittedBlockIds.has(block.id) || block.assetId && emittedAssetIds.has(block.assetId) && !tableCellIds.has(block.id)) return;
emittedBlockIds.add(block.id);
if (block.assetId) emittedAssetIds.add(block.assetId);
orderedBlocks.push(block);
@@ -1119,14 +1256,18 @@ export async function collectPageCaptureSnapshot(options = {}) {
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] || {};
let title = cleanText(isPageRoot
- ? siteData?.title || context.article?.title || structured.headline || structured.name || (context.pageType === "post" ? "" : context.metadata.title)
+ ? options.feishuDocument?.title || siteData?.title || (context.contentRoot ? adapterFields.title : "") || context.article?.title || structured.headline || structured.name || (context.pageType === "post" ? "" : context.metadata.title)
: 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 = post ? post.text : cleanBlockText(context.contentRoot ? root.innerText : isPageRoot
+ // One work can place its gallery and prompt in sibling regions, outside ordinary article markup.
+ const partSelectors = context.contentRoot ? context.adapter.fields?.contentParts || [] : [];
+ const contentParts = partSelectors.length ? [...root.querySelectorAll(partSelectors.join(","))] : [];
+ const captureRoots = contentParts.length ? contentParts : [root];
+ const text = post ? post.text : cleanBlockText(context.contentRoot ? (options.feishuDocument?.text || (contentParts.length ? contentParts.map(readBlockText).filter(Boolean).join("\n\n") : root.innerText || root.textContent)) : isPageRoot
? pageSelection?.text || articleText || siteData?.contentText || context.article?.textContent || structured.articleBody || root.innerText || context.metadata.description
: root.innerText || root.textContent);
- const contentHtml = post ? post.html : context.contentRoot ? root.innerHTML : isPageRoot
+ const contentHtml = post ? post.html : context.contentRoot ? contentRootHtml(root, contentParts) : isPageRoot
? pageSelection?.html || context.article?.content || ""
: "";
const structuredTextBlocks = !context.contentRoot && !articleText && siteData?.contentText
@@ -1140,8 +1281,8 @@ export async function collectPageCaptureSnapshot(options = {}) {
}]
: null;
const textBlocks = post?.textBlocks || pageSelection?.textBlocks || structuredTextBlocks || collectTextBlocks(root, contentHtml, text);
- const siteMedia = [...(Array.isArray(siteData?.media) ? siteData.media : []), ...collectStructuredMedia(structured)];
- const domMedia = post?.media || (pageSelection || root.isConnected === false ? [] : collectMedia(root, context.maxMedia));
+ const siteMedia = [...(options.feishuDocument?.media || []), ...(Array.isArray(siteData?.media) ? siteData.media : []), ...collectStructuredMedia(structured)];
+ const domMedia = post?.media || (pageSelection || root.isConnected === false ? [] : captureRoots.flatMap(part => collectMedia(part, context.maxMedia)));
const pairedDomIds = new Set();
const pairedSiteMedia = siteMedia.map((item) => {
const visible = domMedia.find((candidate) => mediaValuesOverlap(item, candidate));
@@ -1186,8 +1327,15 @@ export async function collectPageCaptureSnapshot(options = {}) {
? "selection"
: siteData?.sourceFacts?.extractionMethod === "structured" ? "structured"
: context.article?.content ? "readability" : structured.articleBody ? "structured" : "page";
- const complete = !post?.partial && (siteData?.completeness === "complete" || Boolean(title && (text || media.length)));
+ // Feishu virtualizes document blocks; a DOM snapshot cannot certify the whole document.
+ const documentPartial = scanIncomplete || (context.adapter.id === "feishu" && !pageSelection && !options.feishuDocument?.complete);
+ const complete = !documentPartial && !post?.partial && (siteData?.completeness === "complete" || Boolean(title && (text || media.length)));
const region = markCaptureRegion(root, index, text, media.length);
+ if (region && options.feishuDocument) {
+ region.marker = options.feishuDocument.marker;
+ region.id = options.feishuDocument.marker;
+ region.contentTargets = options.feishuDocument.targets;
+ }
if (region && root.isConnected !== false) {
region.contentTargets = collectContentTargets(
root,
@@ -1231,7 +1379,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
},
completeness: complete ? "complete" : "partial",
extraction: {
- textTruncated: post?.partial === true,
+ textTruncated: documentPartial || post?.partial === true,
scope: captureScope,
method: extractionMethod,
textBlockCount: textBlocks.length
@@ -1363,8 +1511,23 @@ export async function collectPageCaptureSnapshot(options = {}) {
};
}
+ function isPageChrome(element) {
+ const semantic = "nav,aside,header,footer,[role=navigation],[role=banner],[role=complementary],[role=contentinfo]";
+ const feishu = location.hostname === "feishu.cn" || location.hostname.endsWith(".feishu.cn");
+ if (!feishu) return Boolean(element.closest?.(`${semantic},[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]`));
+ for (let node = element; node; node = node.parentElement) {
+ if (node.matches?.(semantic)) return true;
+ // Feishu's comment-capable block wrappers contain document text, not replies.
+ const classes = [...(node.classList || [])].filter(name =>
+ name !== "block-comment" && !name.endsWith("-block-comment") &&
+ name !== "local-comment-all-third-party" && name !== "ai-recommend-content-hidden");
+ if (/comment|recommend/u.test(classes.join(" ")) || /comment|recommend/u.test(node.getAttribute?.("data-testid") || "")) return true;
+ if (node.matches?.(".page-block.root-block")) break;
+ }
+ return false;
+ }
+
function collectContentTargets(root, articleBlocks, media, limit) {
- const excludedSelector = "nav,aside,header,footer,[role=navigation],[role=banner],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]";
const semanticSelector = "h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,code[data-language],table,img,video,iframe,a[href]";
const pathFor = (element) => {
const parts = [];
@@ -1414,20 +1577,20 @@ export async function collectPageCaptureSnapshot(options = {}) {
return cleanBlockText(element.textContent) ? "text" : "";
};
const candidates = [...root.querySelectorAll?.(`${semanticSelector},div,section,figure`) || []]
- .filter((element) => !element.closest?.(excludedSelector));
+ .filter((element) => !isPageChrome(element));
const leafElements = candidates.filter((element) => {
const kind = kindFor(element);
if (!kind) return false;
if (kind !== "text") return true;
if (element.matches?.(semanticSelector)) return true;
- return !element.querySelector?.(semanticSelector) && cleanBlockText(element.textContent);
+ return !element.querySelector?.(`${semanticSelector},div,section`) && cleanBlockText(element.textContent);
});
+ const remainingTextBlocks = articleBlocks.filter((block) => !block.assetId);
const leaves = leafElements.flatMap((element, sourceOrder) => {
const kind = kindFor(element);
const text = kind === "text" ? readBlockText(element) : "";
- const articleBlockIds = kind === "text"
- ? articleBlocks.filter((block) => !block.assetId && cleanBlockText(block.text) === text).map((block) => block.id)
- : [];
+ const textIndex = kind === "text" ? remainingTextBlocks.findIndex((block) => cleanBlockText(block.text) === text) : -1;
+ const articleBlockIds = textIndex >= 0 ? [remainingTextBlocks.splice(textIndex, 1)[0].id] : [];
const mediaIds = mediaIdsFor(element, kind);
if (kind !== "text" && !mediaIds.length) return [];
const path = pathFor(element);
@@ -1465,6 +1628,31 @@ export async function collectPageCaptureSnapshot(options = {}) {
.slice(0, limit);
}
+ function contentRootHtml(root, parts = []) {
+ const fragment = root.cloneNode(!parts.length);
+ for (const part of parts) fragment.append(part.cloneNode(true));
+ // Preserve editor paragraphs as semantic HTML for sectioning and saved reading order.
+ for (const node of fragment.querySelectorAll("div.zone-container.text-editor")) {
+ if (node.closest("h1,h2,h3,h4,h5,h6")) continue;
+ const paragraph = document.createElement("p");
+ paragraph.innerHTML = node.innerHTML;
+ // Editor line divs cannot survive inside a serialized HTML paragraph.
+ for (const line of paragraph.querySelectorAll("div")) {
+ const span = document.createElement("span");
+ span.innerHTML = line.innerHTML;
+ if (line.nextSibling) span.append(document.createElement("br"));
+ line.replaceWith(span);
+ }
+ node.replaceWith(paragraph);
+ }
+ // Rich-text publishers often use section/div wrappers instead of paragraph tags.
+ for (const node of fragment.querySelectorAll("div,section")) {
+ if (node.matches(".rde-asset-embed") || !cleanBlockText(node.textContent) || node.querySelector("div,section,p,h1,h2,h3,h4,h5,h6,ul,ol,blockquote,pre,table,figure,button,input,select,textarea")) continue;
+ const paragraph = document.createElement("p"); paragraph.innerHTML = node.innerHTML; node.replaceWith(paragraph);
+ }
+ return fragment.innerHTML;
+ }
+
function collectTextBlocks(root, contentHtml, contentText) {
let blockRoot = root;
if (contentHtml) {
@@ -1490,7 +1678,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
html: serializeBlockHtml(node),
kind: /^h[1-6]$/u.test(tagName)
? "heading"
- : node.closest?.("nav,aside,header,footer,[role=navigation],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]")
+ : isPageChrome(node)
? "noise"
: tagName === "li" ? "list" : tagName === "blockquote" ? "quote" : ["pre", "code"].includes(tagName) ? "code" : tagName === "figure" ? "figure" : tagName === "table" ? "table" : "paragraph",
sourceOrder: blocks.length
@@ -1516,15 +1704,47 @@ export async function collectPageCaptureSnapshot(options = {}) {
const textByValue = new Map();
for (const block of textBlocks || []) {
const key = cleanBlockText(block.text);
- if (key && !textByValue.has(key)) textByValue.set(key, block);
+ if (key) textByValue.set(key, [...(textByValue.get(key) || []), block]);
}
const downloadCards = [...(blockRoot.querySelectorAll?.(".rde-asset-embed") || [])];
const selector = "h1,h2,h3,h4,h5,h6,p,ul,ol,blockquote,pre,code[data-language],table,figcaption,img,video,iframe,a[href],.rde-asset-embed";
const structuralContainers = "p,ul,ol,blockquote,pre,code[data-language],table,figcaption";
const elements = [...(blockRoot?.querySelectorAll?.(selector) || [])];
for (const element of elements) {
- if (element.closest?.("nav,aside,header,footer,[role=navigation],[role=complementary],[role=contentinfo],[class*=comment],[class*=recommend],[data-testid*=comment],[data-testid*=recommend]")) continue;
+ if (isPageChrome(element)) continue;
const tagName = cleanText(element.tagName).toLowerCase();
+ // A table owns its cell blocks; keep their IDs in the flat asset/edit registry.
+ if (element.parentElement?.closest("table")) continue;
+ if (tagName === "table") {
+ const text = readBlockText(element);
+ const id = textByValue.get(text)?.shift()?.id || `article:table:${blocks.length}:${hashText(text)}`;
+ const tableBlock = { id, kind: "table", text, sourceOrder: blocks.length, rows: [] };
+ blocks.push(tableBlock);
+ for (const row of element.rows) {
+ const cells = [];
+ for (const cell of row.cells) {
+ const fragment = document.createElement("div");
+ fragment.innerHTML = cell.innerHTML;
+ // Preserve bare cell text alongside paragraphs and media.
+ for (const node of [...fragment.childNodes]) {
+ if (node.nodeType === 3 && cleanText(node.textContent)) {
+ const paragraph = document.createElement("p"); paragraph.textContent = node.textContent; node.replaceWith(paragraph);
+ }
+ }
+ const child = collectArticleDocument(fragment, fragment.innerHTML, [], [...knownMedia, ...media], limit);
+ media.push(...child.media);
+ const cellBlocks = child.blocks.map((block, index) => ({ ...block,
+ id: `${id}:cell:${tableBlock.rows.length}:${cells.length}:${index}`, sourceOrder: blocks.length + index }));
+ blocks.push(...cellBlocks);
+ cells.push({ header: cell.tagName === "TH", rowspan: cell.rowSpan, colspan: cell.colSpan,
+ width: Number(cell.getAttribute("width")) || parseFloat(cell.style.width) || 0,
+ align: cell.style.textAlign || cell.getAttribute("align"), valign: cell.style.verticalAlign || cell.getAttribute("valign"),
+ blockIds: cellBlocks.map(block => block.id) });
+ }
+ tableBlock.rows.push(cells);
+ }
+ continue;
+ }
if (element.matches?.(".rde-asset-embed")) {
const download = options.downloads?.items?.find((item) => item.index === downloadCards.indexOf(element));
if (download) {
@@ -1565,7 +1785,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (playerForCompanionPoster(element, blockRoot)) continue;
const variants = collectImageVariants(element);
const sourceUrl = variants[0]?.url || safeHttpUrl(element.currentSrc || element.src);
- const existing = findKnownMedia(knownMedia, sourceUrl, variants, "image");
+ const existing = knownMedia.find(item => item.id === element.getAttribute?.("data-promptdirector-asset-id")) || findKnownMedia(knownMedia, sourceUrl, variants, "image");
const item = existing || (sourceUrl ? {
id: `article:image:${hashText(sourceUrl)}`,
kind: "image",
@@ -1606,7 +1826,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
if (parentContainer && parentContainer !== element) continue;
const text = readBlockText(element);
if (!text) continue;
- const known = textByValue.get(text);
+ const known = textByValue.get(text)?.shift();
const kind = /^h[1-6]$/u.test(tagName)
? "heading"
: ["ul", "ol"].includes(tagName) ? "list"
@@ -1956,7 +2176,7 @@ export async function collectPageCaptureSnapshot(options = {}) {
}
const currentUrl = safeHttpUrl(image.currentSrc);
if (currentUrl) candidates.push({ url: currentUrl, sourceKind: "current", declaredWidth: 0, density: 0 });
- const sourceUrl = safeHttpUrl(image.src);
+ const sourceUrl = image.getAttribute?.("src") === "" ? "" : safeHttpUrl(image.src);
if (sourceUrl) candidates.push({ url: sourceUrl, sourceKind: "source", declaredWidth: 0, density: 0 });
const adapter = detectAdapter(location.hostname);
if (adapter.id === "higgsfield") {
diff --git a/package-lock.json b/package-lock.json
index 0a8c09b..face5e8 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "prompt-case-collector",
- "version": "1.20.7",
+ "version": "1.20.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prompt-case-collector",
- "version": "1.20.7",
+ "version": "1.20.8",
"license": "Apache-2.0",
"dependencies": {
"@jonahschulte/rtf-toolkit": "0.5.0",
diff --git a/package.json b/package.json
index 8b470dd..f6c8bd9 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "prompt-case-collector",
- "version": "1.20.7",
+ "version": "1.20.8",
"private": false,
"license": "Apache-2.0",
"repository": "https://github.com/wchao6891/PromptDirector",
diff --git a/store/CHROME_WEB_STORE_SUBMISSION.md b/store/CHROME_WEB_STORE_SUBMISSION.md
index cd68716..d0f5a46 100644
--- a/store/CHROME_WEB_STORE_SUBMISSION.md
+++ b/store/CHROME_WEB_STORE_SUBMISSION.md
@@ -6,7 +6,7 @@ This file is the source-of-truth worksheet for the current PromptDirector manife
- Chrome Web Store item public key: stored in the source `manifest.json` for local identity verification only; `package:release` removes `key` from the upload manifest.
- Expected extension ID: `iahakaahijddcjjldidbclicedibgpjm`.
-- Current upload artifact: `dist/PromptDirector-1.20.7.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
+- Current upload artifact: `dist/PromptDirector-1.20.8.zip`. The GitHub `FIXED-ID-DEV` artifact is for local installations only.
- Generate a candidate only with `npm run package:release`; the command verifies the source public key against the expected identity, then removes `key` from the Web Store upload manifest and excludes the local program installer. Record the generated ZIP size and SHA-256 from the final release assets.
## Store listing
diff --git a/test/article-case-groups.test.js b/test/article-case-groups.test.js
new file mode 100644
index 0000000..a45935e
--- /dev/null
+++ b/test/article-case-groups.test.js
@@ -0,0 +1,24 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { splitArticleCases } from '../extension/article-case-groups.js';
+const heading = (id,text,level=2) => ({id,kind:'heading',text,level});
+const paragraph = (id,text) => ({id,kind:'paragraph',text});
+const image = id => ({id,kind:'image',assetId:id});
+function candidate(blocks) { return {id:'article',title:'Article',canonicalUrl:'https://example.com/article',sourceFacts:{},media:blocks.filter(b=>b.kind==='image').map(b=>({id:b.id,kind:'image',url:`https://example.com/${b.id}.png`})),articleDocument:{blocks:blocks.map((b,sourceOrder)=>({...b,sourceOrder}))}}; }
+test('case boundaries keep multiple images with the correct prompt and leave intro separate',()=>{
+ const groups=splitArticleCases(candidate([paragraph('intro','Introduction'),image('cover'),heading('a','No. 1: Portrait'),heading('ap','提示词',3),paragraph('at','Portrait prompt'),image('a1'),image('a2'),heading('b','No. 2: Landscape'),heading('bp','提示词',3),paragraph('bt','Landscape prompt'),image('b1'),paragraph('bonus','彩蛋:Extra case'),image('c1'),{id:'ct',kind:'quote',text:'Extra prompt'}]));
+ assert.equal(groups.length,4);
+ assert.deepEqual(groups.map(g=>g.media.map(m=>m.id)),[['a1','a2'],['b1'],['c1'],['cover']]);
+ assert.ok(groups[0].contentText.includes('Portrait prompt'));
+ assert.ok(!groups[0].contentText.includes('Landscape prompt'));
+ assert.equal(groups[3].batchStructureStatus,'review');
+});
+test('ordinary article headings and images alone do not invent independent prompt cases',()=>{
+ assert.deepEqual(splitArticleCases(candidate([heading('a','Chapter 1'),paragraph('x','Some prose'),image('a1'),heading('b','Chapter 2'),paragraph('y','More prose'),image('b1')])),[]);
+});
+test('numbered paragraph headings can delimit styled articles; numbers inside prompt code cannot',()=>{
+ const groups=splitArticleCases(candidate([paragraph('a','1、人物案例'),paragraph('ap','提示词:portrait'),{id:'code',kind:'code',text:'1. lighting\n2. composition'},image('a1'),paragraph('b','2、建筑案例'),paragraph('bp','Prompt: architecture'),image('b1')]));
+ assert.equal(groups.length,2);
+ assert.deepEqual(groups[0].media.map(m=>m.id),['a1']);
+ assert.ok(groups[0].contentText.includes('2. composition'));
+});
diff --git a/test/article-document.test.js b/test/article-document.test.js
index 70625ac..7f5765b 100644
--- a/test/article-document.test.js
+++ b/test/article-document.test.js
@@ -60,3 +60,24 @@ test("legacy cases can omit an article document", () => {
assert.equal(normalizeArticleDocument(null), null);
assert.equal(normalizeArticleDocument({ blocks: [] }), null);
});
+
+test("table cells retain ordered editable blocks across asset remapping and removal", () => {
+ const value = { blocks: [
+ { id: "table", kind: "table", text: "old flattened text", rows: [[
+ { rowspan: 2, colspan: 1, width: 320, blockIds: ["before", "image", "after"] },
+ { blockIds: [] }
+ ]] },
+ { id: "before", kind: "paragraph", text: "Before image" },
+ { id: "image", kind: "image", assetId: "capture:image" },
+ { id: "after", kind: "paragraph", text: "After image" }
+ ] };
+ const saved = finalizeArticleDocumentAssets(value, { "capture:image": "saved:image" });
+ assert.deepEqual(saved.blocks[0].rows[0][0].blockIds, ["before", "image", "after"]);
+ assert.equal(saved.blocks[0].rows[0][0].rowspan, 2);
+ assert.equal(saved.blocks[0].rows[0][0].width, 320);
+ assert.equal(saved.blocks[2].assetId, "saved:image");
+ assert.equal(articleDocumentText(saved), "Before image\nAfter image");
+ const removed = removeArticleDocumentAsset(saved, "saved:image");
+ assert.deepEqual(removed.blocks[0].rows[0][0].blockIds, ["before", "after"]);
+ assert.equal(removed.blocks[0].rows[0].length, 2);
+});
diff --git a/test/article_cases_capture_e2e.py b/test/article_cases_capture_e2e.py
new file mode 100644
index 0000000..55b8cda
--- /dev/null
+++ b/test/article_cases_capture_e2e.py
@@ -0,0 +1,61 @@
+"""Synthetic WeChat-style rich text. No request to a real WeChat article is made."""
+import json,tempfile,hashlib,struct,zlib
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import EXTENSION_DIR,extension_session
+def image_bytes(url):
+ # Distinct valid pixels prevent the library's content deduplication merging fixture images.
+ rgb=hashlib.sha256(url.encode()).digest()[:3]
+ 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,2,0,0,0))+chunk(b'IDAT',zlib.compress(b'\0'+rgb))+chunk(b'IEND',b'')
+URL='https://mp.weixin.qq.com/s/promptdirector-synthetic-article'
+HTML='''<html><head><meta charset="utf-8"><title>Rich text cases</title></head><body><h1 id="activity-name">Rich text cases</h1><span id="js_name">Fixture author</span><div id="js_content"><p>Article introduction</p><img data-src="https://mmbiz.qpic.cn/intro.png" width="160" height="120">'''+''.join(f'''<section><section><strong>{i}、案例{i}</strong></section><section><span>提示词:</span></section><section><span>Generate scene {i} with its own visual composition.</span></section>'''+''.join(f'<img data-src="https://mmbiz.qpic.cn/case-{i}-{n}.png" width="160" height="120">' for n in range(i))+ '</section>' for i in range(1,4))+ '</div></body></html>'
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='pd-article-case-fixture-') as tmp:
+ ext=Path(tmp)
+ for f in EXTENSION_DIR.iterdir():
+ if f.name!='manifest.json':(ext/f.name).symlink_to(f,target_is_directory=f.is_dir())
+ manifest=json.loads((EXTENSION_DIR/'manifest.json').read_text());manifest['host_permissions']+=['https://mp.weixin.qq.com/*','https://*.qpic.cn/*']
+ (ext/'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('pd-article-cases-',extension_dir=ext) as run:
+ run.context.route('https://mp.weixin.qq.com/**',lambda r:r.fulfill(body=HTML,content_type='text/html'))
+ run.context.route('https://*.qpic.cn/**',lambda r:r.fulfill(body=image_bytes(r.request.url),content_type='image/png'))
+ panel=run.open_page('collector.html');panel.set_viewport_size({'width':390,'height':844})
+ run.seed_storage(panel,{'entries':[],'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-12T00:00:00Z','clipboardIncluded':True}})
+ source=run.context.new_page();source.goto(URL);source.bring_to_front()
+ panel.locator('#start-page-capture').evaluate('e=>e.click()')
+ expect(panel.locator('.page-capture-item')).to_have_count(1)
+ panel.locator('#page-capture-mode').select_option('article')
+ expect(panel.locator('.page-capture-item')).to_have_count(4,timeout=30000)
+ expect(panel.locator('#page-capture-mode')).to_have_value('article')
+ expect(panel.locator('#page-capture-save-mode')).to_have_value('multiple')
+ expect(panel.locator('#page-capture-list-summary')).to_contain_text('3 个案例')
+ expect(panel.locator('#page-capture-list-summary')).to_contain_text('1 组')
+ panel.screenshot(path=str(ext/'article-cases-preview.png'),full_page=True)
+ # Whole article remains available via the same mode control.
+ source.bring_to_front()
+ panel.locator('#page-capture-mode').select_option('single')
+ expect(panel.locator('.page-capture-item')).to_have_count(1,timeout=30000)
+ expect(panel.locator('#page-capture-mode')).to_have_value('single')
+ result=panel.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert len(result['batch']['candidates'])==1
+ assert len(result['batch']['candidates'][0]['media'])==7
+ batch_result=panel.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'list',targetCount:6})")
+ assert batch_result['ok'] and len(batch_result['batch']['candidates'])==4,batch_result
+ source.bring_to_front()
+ panel.locator('#page-capture-mode').select_option('article')
+ expect(panel.locator('.page-capture-item')).to_have_count(4,timeout=30000)
+ panel.locator('#page-capture-save').click()
+ panel.wait_for_function("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries.length===3}")
+ entries=panel.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ for i in range(1,4):
+ entry=next(e for e in entries if e['title']==f'{i}、案例{i}')
+ assert len(entry['mediaAssets'])==i,(i,entry)
+ assert f'Generate scene {i}' in entry['text']
+ assert 'Article introduction' not in entry['text']
+ assert all(a.get('byteSize',0)>0 for a in entry['mediaAssets'])
+ print('PASS: rich-text paragraph boundaries, per-case image sets, unassigned intro, UI mode/saving and whole-article retention')
+
+if __name__=='__main__':main()
diff --git a/test/case-presentation.test.js b/test/case-presentation.test.js
index 8c61a82..a30b8cd 100644
--- a/test/case-presentation.test.js
+++ b/test/case-presentation.test.js
@@ -40,3 +40,10 @@ test("media format comes from recognized file metadata, never a creator's title"
assert.equal(mediaFormatLabel({ sourceTitle: "Test film" }), "FILE");
assert.equal(mediaFormatLabel({ sourceTitle: "Test animation.mov" }), "MOV");
});
+
+test("a short document with a structured table keeps the article reader despite image classification", () => {
+ assert.equal(usesArticleReader({
+ contentRole: "image_case", sourceFacts: { pageType: "article" },
+ articleDocument: { blocks: [{ id: "table", kind: "table", rows: [[{ blockIds: [] }]] }] }
+ }), true);
+});
diff --git a/test/feishu_capture_e2e.py b/test/feishu_capture_e2e.py
new file mode 100644
index 0000000..3ae9254
--- /dev/null
+++ b/test/feishu_capture_e2e.py
@@ -0,0 +1,116 @@
+"""Reduced observed Feishu DOM; isolated capture/save regression, not installed-site acceptance."""
+import json
+import tempfile
+from pathlib import Path
+from e2e_support import EXTENSION_DIR, extension_session
+from page_capture_e2e import PNG
+
+VIRTUAL = """<div id="scroll" style="height:400px;overflow:auto"><div class="docx-page-block"><div class="page-block root-block" style="height:7440px;position:relative"><h1 class="page-block-content">虚拟长文</h1><div id="rendered"></div><div data-record-id="mindmap" style="position:absolute;top:7200px"><img src="" style="display:none"><canvas width="160" height="160"></canvas></div></div></div></div><script>
+const scroller=document.querySelector('#scroll');
+const ctx=document.querySelector('canvas').getContext('2d');ctx.fillStyle='blue';ctx.fillRect(0,0,160,160);
+let sessionImage='';fetch('/session-image.png').then(r=>r.blob()).then(b=>{sessionImage=URL.createObjectURL(b);render();});
+function render(){const first=Math.max(0,Math.floor(scroller.scrollTop/240)-1);document.querySelector('#rendered').innerHTML=Array.from({length:Math.min(4,30-first)},(_,n)=>{const i=first+n;return `<div data-block-type="table" data-record-id="table-${Math.floor(i/10)}" style="position:absolute;top:${i*240}px"><table><tr data-index="${i%10}"><td data-record-id="cell-${i}"><div data-record-id="text-${i}"><div class="zone-container text-editor"><div class="ace-line">正文段落 ${i} 必须保留</div></div></div><div data-record-id="image-${i}"><img width="160" height="160" src="${i===29 && sessionImage ? sessionImage : `/image-${i}.png`}"></div></td></tr></table></div>`}).join('');}
+scroller.addEventListener('scroll',()=>setTimeout(render,30));render();
+</script>"""
+
+SITE = 'https://capture-fixture.feishu.cn'
+BODY = '''<aside><article><h1>侧边栏</h1><p>最近访问 收藏 目录 导航</p></article></aside>
+<div class="ai-recommend-content-hidden"><div class="docx-page-block"><div class="page-block root-block" contenteditable="false">
+<h1 class="page-block-content">文档正文测试</h1><div class="block-comment callout-block-comment local-comment-all-third-party"><div class="zone-container text-editor"><div class="ace-line"><span data-leaf="true">版更阶段性目标:维护口碑,提高留存。此处是应该保存的正文,不能用侧边栏取代。</span></div></div></div>
+<div class="block-comment table-block-comment local-comment-all-third-party"><table><tr><td>名称</td><td>最佳实践</td></tr><tr><td rowspan="2">版本预约</td><td><p>图片前说明</p><img src="/case.png" width="640" height="480"><p>更新图文素材</p></td></tr><tr><td></td></tr></table></div>
+</div></div></div>'''
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='feishu-capture-extension-') as temp:
+ extension = Path(temp)
+ for file in EXTENSION_DIR.iterdir():
+ if file.name != 'manifest.json':
+ (extension / file.name).symlink_to(file, target_is_directory=file.is_dir())
+ manifest = json.loads((EXTENSION_DIR / 'manifest.json').read_text())
+ manifest['host_permissions'] += [SITE + '/*']
+ (extension / 'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('feishu-capture-', extension_dir=extension) as run:
+ def route(r):
+ if r.request.url.endswith('.png'):
+ r.fulfill(body=PNG, content_type='image/png')
+ else:
+ body = VIRTUAL if r.request.url.endswith('/docx/virtual') else BODY if r.request.url.endswith('/docx/test') else '<aside><h1>侧边栏</h1><p>最近访问 收藏 目录 导航</p></aside>'
+ r.fulfill(body='<html><head><title>飞书云文档</title></head><body>'+body+'</body></html>', content_type='text/html; charset=utf-8')
+ run.context.route(SITE + '/**', route)
+ collector = run.open_page('collector.html')
+ run.seed_storage(collector, {'schemaVersion':24,'entries':[], 'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-11T00:00:00Z','clipboardIncluded':True}})
+ source = run.context.new_page()
+ source.goto(SITE + '/docx/test', wait_until='networkidle')
+ source.bring_to_front()
+ response = collector.evaluate("async () => chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert response['ok'], response
+ batch = response['batch']
+ assert len(batch['candidates']) == 1, batch
+ case = batch['candidates'][0]
+ assert case['title'] == '文档正文测试', case
+ assert '最近访问' not in case['contentText'], case
+ assert '版更阶段性目标' in case['contentText'] and '更新图文素材' in case['contentText'], case
+ assert case['completeness'] == 'partial', case
+ assert case['extraction']['method'] == 'page', case
+ assert len(case['media']) == 1, case
+ assert any(t['kind'] == 'text' for t in case['region']['contentTargets']), case
+ preview = collector.evaluate("async c => chrome.runtime.sendMessage({type:'PREVIEW_PAGE_CAPTURE_REGION',tabId:c.tabId,preview:c.preview})", {'tabId':batch['tabId'],'preview':{'marker':case['region']['marker'],'targets':case['region']['contentTargets'],'text':case['contentText'],'mediaIds':[m['id'] for m in case['media']]}})
+ assert preview['ok'], preview
+ batch['selections'] = [{'candidateId':case['id'],'includeText':True,'selectedMediaIds':[m['id'] for m in case['media']],'mediaDecision':'confirmed'}]
+ saved = collector.evaluate("async batch => chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})", batch)
+ assert saved['ok'], saved
+ entries = collector.evaluate("async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ assert len(entries) == 1, entries
+ assert '版更阶段性目标' in json.dumps(entries, ensure_ascii=False), entries
+ assert '最近访问' not in json.dumps(entries, ensure_ascii=False), entries
+ library = run.open_page('library.html?case=' + entries[0]['id'])
+ table = library.locator('.article-structured-table')
+ table.wait_for()
+ assert table.locator('tr').count() == 3
+ assert table.locator('tr').nth(1).locator('td').first.get_attribute('rowspan') == '2'
+ cell = table.locator('tr').nth(1).locator('td').nth(1)
+ assert cell.locator('img').count() == 1
+ assert cell.evaluate("e => [...e.children].map(n => n.tagName)") == ['P', 'FIGURE', 'P']
+ assert library.locator('.article-document-reader > figure').count() == 0
+ assert table.locator('tr').nth(2).locator('td').inner_text() == ''
+ library.reload()
+ library.locator('.case-card[data-entry-id="' + entries[0]['id'] + '"]').click()
+ library.locator('.article-structured-table img').wait_for()
+ source.goto(SITE + '/docx/loading' , wait_until='networkidle')
+ source.bring_to_front()
+ empty = collector.evaluate("async () => chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert not empty.get('batch',{}).get('candidates'), empty
+ source.goto(SITE + '/docx/virtual', wait_until='networkidle')
+ source.bring_to_front()
+ source.locator('#scroll').evaluate('(e)=>e.scrollTop=720')
+ long_result = collector.evaluate("async () => chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert long_result['ok'], long_result
+ long_batch = long_result['batch']
+ long_case = long_batch['candidates'][0]
+ assert any(m.get('dataUrl','').startswith('data:image/png;base64,') for m in long_case['media']), 'Session image bytes must survive virtual unmount'
+ assert any(m.get('captureMethod') == 'pixel-fallback' for m in long_case['media']), 'Mindmap canvas must be retained'
+ assert len(long_case['media']) == 31, (len(long_case['media']),long_case['contentText'])
+ for i in range(30):
+ assert f'正文段落 {i} 必须保留' in long_case['contentText'], (i,long_case['contentText'])
+ assert long_case['completeness'] == 'complete', long_case['extraction']
+ assert len([b for b in long_case['articleDocument']['blocks'] if b['kind']=='table']) == 3
+ assert source.locator('#scroll').evaluate('(e)=>e.scrollTop') == 720
+ long_batch['selections']=[{'candidateId':long_case['id'],'includeText':True,'selectedMediaIds':[m['id'] for m in long_case['media']],'mediaDecision':'confirmed'}]
+ result=collector.evaluate("async batch => chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",long_batch)
+ assert result['ok'],result
+ entries=collector.evaluate("async () => (await chrome.runtime.sendMessage({type:'GET_STATE'})).entries")
+ saved=next(e for e in entries if e.get('sourceUrl','').endswith('/docx/virtual') or '正文段落 29' in json.dumps(e,ensure_ascii=False))
+ assert '正文段落 0' in json.dumps(saved,ensure_ascii=False) and '正文段落 29' in json.dumps(saved,ensure_ascii=False)
+ library.goto('chrome-extension://' + run.extension_id + '/library.html?case=' + saved['id'])
+ library.locator('.article-structured-table').first.wait_for()
+ assert library.locator('.article-structured-table').count() == 3
+ for i in range(30):
+ cell = library.locator('.article-structured-table td').nth(i)
+ assert f'正文段落 {i} 必须保留' in cell.inner_text()
+ assert cell.locator('img').count() == 1
+ assert library.locator('.article-document-reader > figure').count() == 1
+ print('PASS: rendered body/save/highlight; virtual document retains 30 images plus mindmap, all paragraphs, 3 tables and restores scroll')
+
+if __name__ == '__main__':
+ main()
diff --git a/test/generic_scroll_capture_e2e.py b/test/generic_scroll_capture_e2e.py
new file mode 100644
index 0000000..f3ef1ad
--- /dev/null
+++ b/test/generic_scroll_capture_e2e.py
@@ -0,0 +1,78 @@
+"""Unregistered-site fixtures: semantic articles, internal scroll and virtualized blocks."""
+from e2e_support import extension_session
+from page_capture_e2e import FIXTURE_ORIGIN, PNG
+
+
+def document_fixture(role=False):
+ opening = '<section id="scroll" style="height:400px;overflow:auto"><div role="main"><div role="document"' if role else '<main><div id="scroll" style="height:400px;overflow:auto"><article'
+ closing = '</div></div></section>' if role else '</article></div></main>'
+ return '''<html><head><title>Unregistered document</title></head><body>
+<aside style="height:150px;overflow:auto"><div style="height:6000px">SIDEBAR MUST NOT BE CAPTURED</div></aside>'''+opening+''' style="height:4600px;position:relative"><h1 id="title">Unregistered document</h1><div id="blocks"></div>
+<table id="table" style="position:absolute;top:4100px"><tr><td rowspan="2">Source column</td><td><p>Before image</p><img width="160" height="120" src="/inside.png"><p>After image</p></td></tr><tr><td>Final cell</td></tr></table>'''+closing+'''
+<script>
+const scroll=document.querySelector('#scroll');
+function render(){const first=Math.max(0,Math.floor((scroll.scrollTop-100)/220)-1);document.querySelector('#blocks').innerHTML=Array.from({length:Math.min(4,18-first)},(_,n)=>{const i=first+n;return `<p id="paragraph-${i}" style="position:absolute;top:${100+i*220}px">Section ${i}: preserved text from a virtual document.</p>`}).join('');}
+scroll.addEventListener('scroll',()=>{scroll.setAttribute('aria-busy','true');setTimeout(()=>{render();scroll.setAttribute('aria-busy','false');},220);});render();
+</script></body></html>'''
+
+
+FEED = """<html><head><title>Unknown gallery</title></head><body><aside style="height:120px;overflow:auto"><p style="height:5000px">SIDEBAR</p></aside><main id="scroll" style="height:400px;overflow:auto"><div style="height:2800px;position:relative" id="feed"></div></main><script>
+const scroll=document.querySelector('#scroll');
+function render(){let first=Math.max(0,Math.floor(scroll.scrollTop/260)-1);document.querySelector('#feed').innerHTML=Array.from({length:Math.min(4,10-first)},(_,n)=>{let i=first+n;return `<article style="position:absolute;top:${i*260}px"><a href="/work/${i}"><h2>Work ${i}</h2></a><p>Independent work number ${i}, retain its own description.</p><img src="/work-${i}.png" width="160" height="120"></article>`}).join('');}
+scroll.addEventListener('scroll',()=>setTimeout(render,40));render();
+</script></body></html>"""
+
+def main():
+ with extension_session('pd-generic-scroll-') as run:
+ run.context.route(FIXTURE_ORIGIN+'/**', lambda r: r.fulfill(body=PNG,content_type='image/png') if r.request.url.endswith('.png') else r.fulfill(body=(FEED.replace('<main id=', '<main><section id=').replace('</div></main><script>', '</div></section></main><script>') if r.request.url.endswith('/feed-inner') else FEED) if '/feed' in r.request.url else document_fixture(r.request.url.endswith('/roles')),content_type='text/html'))
+ collector=run.open_page('collector.html')
+ run.seed_storage(collector,{'entries':[],'capturePermissionOnboarding':{'version':1,'acknowledgedAt':'2026-09-12T00:00:00Z','clipboardIncluded':True}})
+ page=run.context.new_page()
+ for path in ['/semantic','/roles']:
+ page.goto(FIXTURE_ORIGIN+path)
+ page.locator('#scroll').evaluate('e=>e.scrollTop=440')
+ page.bring_to_front()
+ response=collector.evaluate("async mode=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode})", "loaded" if path=="/semantic" else "whole")
+ assert response['ok'],response
+ batch=response['batch'];assert len(batch['candidates'])==1,batch
+ case=batch['candidates'][0]
+ assert case['adapter']=='generic',case['adapter']
+ for i in range(18):
+ assert f'Section {i}:' in case['contentText'],(i,case['contentText'])
+ assert 'SIDEBAR' not in case['contentText']
+ assert case['completeness']=='complete',case['extraction']
+ assert page.locator('#scroll').evaluate('e=>e.scrollTop')==440
+ assert page.locator('aside').evaluate('e=>e.scrollTop')==0
+ batch['selections']=[{'candidateId':case['id'],'includeText':True,'selectedMediaIds':[m['id'] for m in case['media']],'mediaDecision':'confirmed'}]
+ saved=collector.evaluate("async batch=>chrome.runtime.sendMessage({type:'COMMIT_PAGE_CAPTURE',batch})",batch)
+ assert saved['ok'],saved
+ entry_id=saved['results'][0]['entryId']
+ library=run.open_page('library.html?case='+entry_id)
+ library.locator('.article-structured-table img').wait_for()
+ text=library.locator('.article-document-reader').inner_text()
+ assert text.index('Section 0:') < text.index('Section 17:') < text.index('Source column'),text
+ assert library.locator('.article-structured-table tr').first.locator('td').first.get_attribute('rowspan')=='2'
+ library.close()
+ # A deliberately tiny scan budget must not be reported as a complete document.
+ page.bring_to_front()
+ from pathlib import Path
+ source=Path('extension/page-capture.js').read_text()
+ function=source[source.index('export async function collectPageCaptureSnapshot'):]
+ # Invoke the shipped self-contained function with a test-only traversal budget.
+ function=function[:function.index('\nexport ',10)] if '\nexport ' in function[10:] else function
+ snapshot=page.evaluate('async()=>{'+function.replace('export async','async',1)+';return collectPageCaptureSnapshot({mode:"whole",maxScrollSteps:1,maxMedia:24});}')
+ assert snapshot['candidates'][0]['completeness']=='partial'
+ for feed_path in ['/feed','/feed-inner']:
+ page.goto(FIXTURE_ORIGIN+feed_path)
+ page.locator('#scroll').evaluate('e=>e.scrollTop=520')
+ page.bring_to_front()
+ response=collector.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'whole'})")
+ assert response['ok'],response
+ works=response['batch']['candidates']
+ assert len(works)==10,[(c['title'],c['canonicalUrl']) for c in works]
+ assert {c['canonicalUrl'] for c in works}=={FIXTURE_ORIGIN+'/work/'+str(i) for i in range(10)}
+ assert page.locator('#scroll').evaluate('e=>e.scrollTop')==520
+ assert page.locator('aside').evaluate('e=>e.scrollTop')==0
+ print('PASS: two unregistered virtual document structures retain 18 ordered sections, table/media placement, restore scroll, report a limited scan as partial, and collect 10 independent works from two internal feed layouts')
+
+if __name__=='__main__': main()
diff --git a/test/page-capture-adapter-registry.test.js b/test/page-capture-adapter-registry.test.js
index 0548bbf..08e67f5 100644
--- a/test/page-capture-adapter-registry.test.js
+++ b/test/page-capture-adapter-registry.test.js
@@ -26,6 +26,7 @@ test("the capture registry covers the requested public-site families without dup
["https://www.douban.com/photos/album/1/", "douban"],
["https://www.poco.cn/works/detail_id1", "poco"],
["https://mp.weixin.qq.com/s/example", "wechat"],
+ ["https://tenant.feishu.cn/docx/example", "feishu"],
["https://www.liblib.art/imageinfo/example", "liblibai"],
["https://www.krea.ai/feed/example-00000000-0000-0000-0000-000000000000", "krea"],
["https://higgsfield.ai/@creator/projects/example", "higgsfield"],
diff --git a/test/page-capture.test.js b/test/page-capture.test.js
index ae1a5b2..95db10c 100644
--- a/test/page-capture.test.js
+++ b/test/page-capture.test.js
@@ -352,7 +352,7 @@ test("the generic capture exposes meaningful nested blocks without turning every
assert.match(targets, /articleBlockIds/);
assert.match(targets, /mediaIds/);
assert.match(targets, /div,section,figure/);
- assert.match(targets, /!element\.querySelector\?\.\(semanticSelector\)/);
+ assert.match(targets, /!element\.querySelector\?\.\(`\$\{semanticSelector\},div,section`\)/);
assert.match(source, /playerForCompanionPoster/);
assert.match(source, /companionPosterForPlayer/);
});
@@ -1070,3 +1070,14 @@ test("list capture inherits a representative structure without auto-accepting a
articleDocument: { version: 1, blocks: [{ id: "video-block", kind: "video", assetId: "video", sourceOrder: 0 }] }
}), false);
});
+
+test("session image file bytes are not mislabeled as a screenshot fallback", async () => {
+ const bytes = new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" });
+ const result = await resolvePageCaptureImage({ dataUrl: "data:image/png;base64,AQID", captureMethod: "page-session" }, {
+ fetchMedia: async () => { throw new Error("No network URL expected"); },
+ decodeDataUrl: async () => bytes
+ });
+ assert.equal(result.blob, bytes);
+ assert.equal(result.captureMethod, "page-session");
+ assert.equal(result.usedPixelFallback, false);
+});
diff --git a/test/run_e2e.py b/test/run_e2e.py
index 3a90e64..25d8f14 100644
--- a/test/run_e2e.py
+++ b/test/run_e2e.py
@@ -70,6 +70,10 @@ SCRIPTS = [
"x_capture_extraction_e2e.py",
"x_video_playback_e2e.py",
"higgsfield_capture_e2e.py",
+ "feishu_capture_e2e.py",
+ "generic_scroll_capture_e2e.py",
+ "article_cases_capture_e2e.py",
+ "xiaoheihe_capture_e2e.py",
"artstation_capture_e2e.py",
"krea_capture_e2e.py",
"libtv_capture_e2e.py",
diff --git a/test/xiaoheihe_capture_e2e.py b/test/xiaoheihe_capture_e2e.py
new file mode 100644
index 0000000..f8d103b
--- /dev/null
+++ b/test/xiaoheihe_capture_e2e.py
@@ -0,0 +1,61 @@
+"""Synthetic image-wall post: a single prompt belongs to every gallery image."""
+import json
+import tempfile
+from pathlib import Path
+from playwright.sync_api import expect
+from e2e_support import EXTENSION_DIR, extension_session
+from article_cases_capture_e2e import image_bytes
+
+URL = 'https://www.xiaoheihe.cn/app/bbs/link/synthetic-gallery-post'
+PROMPT = 'One outfit, four viewpoints.\n\n完整提示词:Create an editorial lookbook.\nNegative prompt: blurry, duplicate limbs.'
+IMAGES = [f'https://imgheybox.max-c.com/case-{i}.png' for i in range(17)]
+HTML = '<html><head><meta charset="utf-8"><title>Gallery case</title></head><body><div class="hb-bbs-image-text"><div class="image-text__header-image"><div class="swiper-wrapper">' + ''.join(f'<div class="swiper-slide"><img src="{url}" width="160" height="120"></div>' for url in IMAGES) + '''</div><div class="header-image__indicator">4/17</div><button>Next image</button></div><div class="image-text__container"><div class="link-section-user"><img src="https://imgheybox.max-c.com/avatar.png"><div class="link-user__username">Fixture author</div></div><div class="section-title__content">Gallery case</div><div class="image-text__content">''' + PROMPT + '''</div><div class="link-section-tags"><button>Community tag</button></div></div></div><aside>Recommendations</aside><div class="comment-item"><p>A reply must not become the prompt.</p><img src="https://imgheybox.max-c.com/comment.png"></div></body></html>'''
+
+
+def main():
+ with tempfile.TemporaryDirectory(prefix='pd-gallery-post-') as tmp:
+ ext = Path(tmp)
+ for path in EXTENSION_DIR.iterdir():
+ if path.name != 'manifest.json':
+ (ext / path.name).symlink_to(path, target_is_directory=path.is_dir())
+ manifest = json.loads((EXTENSION_DIR / 'manifest.json').read_text())
+ manifest['host_permissions'] += ['https://www.xiaoheihe.cn/*', 'https://*.max-c.com/*']
+ (ext / 'manifest.json').write_text(json.dumps(manifest))
+ with extension_session('pd-gallery-post-', extension_dir=ext) as run:
+ run.context.route('https://www.xiaoheihe.cn/**', lambda route: route.fulfill(body=HTML, content_type='text/html; charset=utf-8'))
+ run.context.route('https://*.max-c.com/**', lambda route: route.fulfill(body=image_bytes(route.request.url), content_type='image/png'))
+ panel = run.open_page('collector.html')
+ run.seed_storage(panel, {'entries': [], 'capturePermissionOnboarding': {'version': 1, 'acknowledgedAt': '2026-09-12T00:00:00Z', 'clipboardIncluded': True}})
+ source = run.context.new_page()
+ source.goto(URL)
+ source.bring_to_front()
+ panel.locator('#start-page-capture').evaluate('e=>e.click()')
+ expect(panel.locator('.page-capture-item')).to_have_count(1)
+ result = panel.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert result['ok'] and len(result['batch']['candidates']) == 1, result
+ case = result['batch']['candidates'][0]
+ assert case['contentText'] == PROMPT, case['contentText']
+ assert case['sourceFacts']['author'] == 'Fixture author'
+ assert {m['url'] for m in case['media']} == set(IMAGES)
+ assert case['textBlocks'] and PROMPT in '\n'.join(b['text'] for b in case['textBlocks'])
+ assert case['completeness'] == 'complete'
+ panel.locator('.page-capture-confirm').click()
+ panel.locator('#page-capture-save').click()
+ panel.wait_for_function("async()=>{const s=await chrome.runtime.sendMessage({type:'GET_STATE'});return s.entries.length===1}")
+ entry = panel.evaluate("async()=>(await chrome.runtime.sendMessage({type:'GET_STATE'})).entries[0]")
+ assert entry['text'] == PROMPT, entry['text']
+ assert len(entry['mediaAssets']) == 17
+ assert all(asset['byteSize'] > 0 for asset in entry['mediaAssets'])
+ assert {asset['sourceUrl'] for asset in entry['mediaAssets']} == set(IMAGES)
+ split = panel.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'article'})")
+ assert not split['ok'], 'A single shared prompt must not become one case per image.'
+ run.context.route('https://www.xiaoheihe.cn/**', lambda route: route.fulfill(body='<html><body><nav>Home Community Login</nav><img src="https://imgheybox.max-c.com/site-logo.png"></body></html>', content_type='text/html'))
+ source.reload()
+ source.bring_to_front()
+ empty = panel.evaluate("async()=>chrome.runtime.sendMessage({type:'START_PAGE_CAPTURE',mode:'loaded'})")
+ assert not empty['ok'], 'An unloaded post must not become a navigation or logo case.'
+ print('PASS: default capture/save retains one full prompt with all 17 images, excludes profile/replies/tags, and does not invent multiple cases')
+
+
+if __name__ == '__main__':
+ main()