AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(extension): add webpage region selection clipping (#703)
sivdeadbb3d726ceb73
diff --git a/apps/extension/README.md b/apps/extension/README.mdindex 4420751d..0f6afe11 100644--- a/apps/extension/README.md+++ b/apps/extension/README.md@@ -7,6 +7,7 @@ Chrome, Edge, and Firefox Manifest V3 extension for saving the current webpage,- Configure an EdgeEver instance URL and API Token.- Test the connection and select a default notebook.- Click the extension action to capture the selected content, or extract the article body with Mozilla Readability when there is no selection.+- Choose **Select area** in the popup to highlight and select a content region, adjust its size with Left/Right or switch adjacent regions with Up/Down, then save only that area. Escape cancels without writing. See [region clipping](../../docs/browser-clipper-regions.md) ([简体中文](../../docs/browser-clipper-regions.zh-CN.md)).- Convert the extracted article HTML into Markdown with Turndown before uploading it.- Copy the images in a saved page or selection into the note itself, so the note still shows them if the source page removes or changes them. The note is saved first; up to 30 images (20 MB each, 60 MB in total) are then uploaded as note attachments and the note is pointed at them. An image the extension cannot read, such as one blocked by its site or in an unsupported format, keeps its original address. If the note is edited before the images finish copying, the edit is kept and the images keep their original addresses. No extra site access is requested for this.- Right-click an image and choose **Save image to EdgeEver**. The image file is uploaded into a new note in the default notebook, with the source page linked underneath. An image saved from Google Search records “Google Search” and the search keyword instead of the results URL.diff --git a/apps/extension/THIRD_PARTY_NOTICES.md b/apps/extension/THIRD_PARTY_NOTICES.mdnew file mode 100644index 00000000..6d2e246a--- /dev/null+++ b/apps/extension/THIRD_PARTY_NOTICES.md@@ -0,0 +1,27 @@+# Third-party notices++The wrapper normalization and parent/child selection history in+`src/region-selection.ts` are adapted from [MaoXian Web Clipper](https://github.com/mika-cn/maoxian-web-clipper),+`src/js/content/ui.js`, revision `e69fbf9c04bad7051d3810e1cef4d82138f812df`.++MIT License++Copyright (c) 2018 Mika++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/apps/extension/capture-bundle.test.mjs b/apps/extension/capture-bundle.test.mjsindex 862d6cbf..97b8a23f 100644--- a/apps/extension/capture-bundle.test.mjs+++ b/apps/extension/capture-bundle.test.mjs@@ -128,6 +128,10 @@ test("the injected page capture is a standalone classic script", async () => {const capture = await readFile(join(outDir, "assets/capture.js"), "utf8");expect(() => new Script(capture)).not.toThrow();expect(capture).toContain("capturedPage");+ const region = await readFile(join(outDir, "assets/region-clip.js"), "utf8");+ expect(() => new Script(region)).not.toThrow();+ expect(region).toContain("saveRegionClip");+ expect(await readFile(join(outDir, "THIRD_PARTY_NOTICES.txt"), "utf8")).toContain("Copyright (c) 2018 Mika");const platform = await readFile(join(outDir, "assets/capture-platform.js"), "utf8");expect(() => new Script(platform)).not.toThrow();expect(platform).toContain("pagePlatformRead");diff --git a/apps/extension/package.json b/apps/extension/package.jsonindex 462390c8..ec345c67 100644--- a/apps/extension/package.json+++ b/apps/extension/package.json@@ -1,6 +1,6 @@{"name": "@edgeever/extension",- "version": "0.3.0",+ "version": "0.4.0","private": true,"type": "module","scripts": {@@ -9,7 +9,7 @@"dev": "vite --config vite.config.ts","lint:firefox": "web-ext lint --source-dir dist-firefox --output text","package:firefox": "bun run build:firefox && bun run lint:firefox && web-ext build --source-dir dist-firefox --artifacts-dir web-ext-artifacts --overwrite-dest",- "test": "bun test manifest.test.mjs context-menus.test.mjs popup.test.mjs capture-bundle.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs zhihu-clip.test.mjs reddit-clip.test.mjs video-clip.test.mjs page-images.test.mjs notebook-clip.test.mjs clip-time.test.mjs platform-clip.test.mjs social-clip.test.mjs platform-capture.test.mjs platform-save.test.mjs vertical-clip.test.mjs article-clip.test.mjs"+ "test": "bun test manifest.test.mjs context-menus.test.mjs popup.test.mjs capture-bundle.test.mjs image-clip.test.mjs tweet-clip.test.mjs selection-clip.test.mjs region-clip.test.mjs github-repo.test.mjs xhs-clip.test.mjs zhihu-clip.test.mjs reddit-clip.test.mjs video-clip.test.mjs page-images.test.mjs notebook-clip.test.mjs clip-time.test.mjs platform-clip.test.mjs social-clip.test.mjs platform-capture.test.mjs platform-save.test.mjs vertical-clip.test.mjs article-clip.test.mjs"},"dependencies": {"@mixmark-io/domino": "2.2.0",diff --git a/apps/extension/platform-save.test.mjs b/apps/extension/platform-save.test.mjsindex 53178861..8deae9e8 100644--- a/apps/extension/platform-save.test.mjs+++ b/apps/extension/platform-save.test.mjs@@ -129,7 +129,7 @@ const harness = (options = {}) => {await options.captureGate?.(target.tabId);runInContext(pageCaptureScript, scriptContext);}- else if (!["assets/capture-image.js", "assets/clip-feedback.js"].includes(files?.[0])) throw new Error(`Unexpected generic fallback: ${files}`);+ else if (!["assets/capture-image.js", "assets/clip-feedback.js", "assets/region-clip.js"].includes(files?.[0])) throw new Error(`Unexpected generic fallback: ${files}`);return [];} },@@ -155,6 +155,9 @@ const harness = (options = {}) => {calls,toolbar: () => new Promise((resolve) => onMessage({ type: "captureCurrentPage" }, { id: chrome.runtime.id }, resolve)),mode: () => new Promise((resolve) => onMessage({ type: "getCurrentPageCaptureMode" }, { id: chrome.runtime.id }, resolve)),+ message: (message, sender = { id: chrome.runtime.id, tab: { id: 7 }, frameId: 0, url: pageUrl }) => new Promise(resolve => {+ if (!onMessage(message, sender, resolve)) resolve({ ignored: true });+ }),menu: () => new Promise((resolve) => { menuDone = resolve; onClick({ menuItemId: `save-${platform}`, pageUrl, frameId: 0 }, { id: 7, url: pageUrl }); }),selectionMenu: () => new Promise((resolve) => {menuDone = resolve;@@ -165,6 +168,42 @@ const harness = (options = {}) => {};};+test("starting the region picker only injects its explicit script and writes nothing", async () => {+ const h = harness();+ expect(await h.message({ type: "startRegionClip" })).toMatchObject({ ok: true });+ expect(h.calls.injections).toEqual([{ target: { tabId: 7, frameIds: [0] }, files: ["assets/region-clip.js"] }]);+ expect(h.calls.requests).toHaveLength(0);+ const denied = harness({ denyScripting: true });+ expect(await denied.message({ type: "startRegionClip" })).toMatchObject({ ok: false, message: "pageAccessDenied" });+ expect(denied.calls.requests).toHaveLength(0);+});++test("a selected region uses the memo and image-localization pipeline without whole-page capture", async () => {+ const h = harness();+ const page = { title: "Selected section", url: urls["hacker-news"], markdown: "## Chosen\n\nOnly this paragraph.\n\n", kind: "region" };+ expect(await h.message({ type: "saveRegionClip", page })).toMatchObject({ ok: true });+ expect(h.calls.creates).toHaveLength(1);+ expect(h.calls.creates[0].notebookId).toBe("nb_inbox");+ expect(h.calls.creates[0].contentMarkdown).toContain("Only this paragraph.");+ expect(h.calls.uploads).toHaveLength(1);+ expect(h.calls.saves[0].contentMarkdown).toContain("/api/v1/resources/res_1/blob");+ expect(h.calls.injections.some(call => call.files?.includes("assets/capture.js"))).toBe(false);+});++for (const failure of ["wrong-frame", "no-tab", "wrong-extension", "changed-url", "empty", "not-region"]) test(`region ${failure} cannot create a note`, async () => {+ const h = harness();+ const page = { title: "Selected", url: urls["hacker-news"], markdown: "Chosen content", kind: "region" };+ const sender = { id: "extension-under-test", tab: { id: 7 }, frameId: 0, url: page.url };+ if (failure === "wrong-frame") sender.frameId = 1;+ if (failure === "no-tab") delete sender.tab;+ if (failure === "wrong-extension") sender.id = "another-extension";+ if (failure === "changed-url") page.url += "&different=1";+ if (failure === "empty") page.markdown = " ";+ if (failure === "not-region") page.kind = "page";+ expect(await h.message({ type: "saveRegionClip", page }, sender)).toMatchObject({ ok: false });+ expect(h.calls.creates).toHaveLength(0);+});+test("Android without desktop menu/window APIs can initialize and save from the popup", async () => {const h = harness({ withoutDesktopApis: true });expect(() => h.installed()).not.toThrow();diff --git a/apps/extension/popup.test.mjs b/apps/extension/popup.test.mjsindex 050c01fd..830b1f9f 100644--- a/apps/extension/popup.test.mjs+++ b/apps/extension/popup.test.mjs@@ -3,6 +3,21 @@ import { captureCurrentPage } from "./src/popup";import { testConnection } from "./src/extension";const settings = { instanceUrl: "https://example.com", token: "token", notebookId: "" };++test("area selection requests permission in the click and starts the picker without capturing the page", async () => {+ const { startRegionClip } = await import("./src/popup");+ let insideClick = true;+ const messages = [];+ await withChrome({+ permissions: { request: async () => { expect(insideClick).toBe(true); return true; } },+ runtime: { sendMessage: async message => { messages.push(message); return { ok: true }; } },+ }, async () => {+ const starting = startRegionClip(settings);+ insideClick = false;+ await starting;+ expect(messages).toEqual([{ type: "startRegionClip" }]);+ });+});async function withChrome(overrides, run) {const previous = globalThis.chrome;globalThis.chrome = { i18n: { getMessage: key => key }, ...overrides };diff --git a/apps/extension/public/_locales/en/messages.json b/apps/extension/public/_locales/en/messages.jsonindex 5fbe76a2..fb0a7ae2 100644--- a/apps/extension/public/_locales/en/messages.json+++ b/apps/extension/public/_locales/en/messages.json@@ -787,5 +787,38 @@},"modelDirectDenied": {"message": "Model access was not granted."+ },+ "regionSelect": {+ "message": "Select area"+ },+ "regionPickerTitle": {+ "message": "Select an area to clip"+ },+ "regionPickHint": {+ "message": "Move over the page and click a content block. Esc to cancel."+ },+ "regionSelected": {+ "message": "Area selected"+ },+ "regionAdjustHint": {+ "message": "← → Larger / smaller · ↑ ↓ Adjacent area · Enter to save"+ },+ "regionExpand": {+ "message": "Larger"+ },+ "regionShrink": {+ "message": "Smaller"+ },+ "regionReselect": {+ "message": "Reselect"+ },+ "regionSave": {+ "message": "Save to EdgeEver"+ },+ "regionCancel": {+ "message": "Cancel"+ },+ "regionEmpty": {+ "message": "This area is empty or no longer available. Select another area."}}diff --git a/apps/extension/public/_locales/ja/messages.json b/apps/extension/public/_locales/ja/messages.jsonindex 5d8df496..9024eed2 100644--- a/apps/extension/public/_locales/ja/messages.json+++ b/apps/extension/public/_locales/ja/messages.json@@ -787,5 +787,38 @@},"modelDirectDenied": {"message": "Model access was not granted."+ },+ "regionSelect": {+ "message": "範囲を選択"+ },+ "regionPickerTitle": {+ "message": "クリップする範囲を選択"+ },+ "regionPickHint": {+ "message": "マウスを動かして内容をクリックします。Esc でキャンセル。"+ },+ "regionSelected": {+ "message": "範囲を選択済み"+ },+ "regionAdjustHint": {+ "message": "← → 拡大 / 縮小 · ↑ ↓ 隣の範囲 · Enter で保存"+ },+ "regionExpand": {+ "message": "拡大"+ },+ "regionShrink": {+ "message": "縮小"+ },+ "regionReselect": {+ "message": "選び直す"+ },+ "regionSave": {+ "message": "EdgeEver に保存"+ },+ "regionCancel": {+ "message": "キャンセル"+ },+ "regionEmpty": {+ "message": "この範囲は空か、すでに削除されています。選び直してください。"}}diff --git a/apps/extension/public/_locales/pl/messages.json b/apps/extension/public/_locales/pl/messages.jsonindex 6f06c30c..2580f419 100644--- a/apps/extension/public/_locales/pl/messages.json+++ b/apps/extension/public/_locales/pl/messages.json@@ -787,5 +787,38 @@},"modelDirectDenied": {"message": "Model access was not granted."+ },+ "regionSelect": {+ "message": "Wybierz obszar"+ },+ "regionPickerTitle": {+ "message": "Wybierz obszar do zapisania"+ },+ "regionPickHint": {+ "message": "Wskaż i kliknij blok treści. Esc anuluje wybór."+ },+ "regionSelected": {+ "message": "Obszar wybrany"+ },+ "regionAdjustHint": {+ "message": "← → Większy / mniejszy · ↑ ↓ Sąsiedni obszar · Enter zapisuje"+ },+ "regionExpand": {+ "message": "Większy"+ },+ "regionShrink": {+ "message": "Mniejszy"+ },+ "regionReselect": {+ "message": "Wybierz ponownie"+ },+ "regionSave": {+ "message": "Zapisz w EdgeEver"+ },+ "regionCancel": {+ "message": "Anuluj"+ },+ "regionEmpty": {+ "message": "Ten obszar jest pusty lub już niedostępny. Wybierz inny."}}diff --git a/apps/extension/public/_locales/zh_CN/messages.json b/apps/extension/public/_locales/zh_CN/messages.jsonindex 7ecedc1c..2296b28c 100644--- a/apps/extension/public/_locales/zh_CN/messages.json+++ b/apps/extension/public/_locales/zh_CN/messages.json@@ -787,5 +787,38 @@},"modelDirectDenied": {"message": "未获得模型访问权限。"+ },+ "regionSelect": {+ "message": "选择区域"+ },+ "regionPickerTitle": {+ "message": "选择要剪藏的区域"+ },+ "regionPickHint": {+ "message": "移动鼠标预览,点击选中内容块。Esc 取消。"+ },+ "regionSelected": {+ "message": "已选中区域"+ },+ "regionAdjustHint": {+ "message": "← → 扩大 / 缩小 · ↑ ↓ 相邻区域 · Enter 保存"+ },+ "regionExpand": {+ "message": "扩大"+ },+ "regionShrink": {+ "message": "缩小"+ },+ "regionReselect": {+ "message": "重新选择"+ },+ "regionSave": {+ "message": "保存到 EdgeEver"+ },+ "regionCancel": {+ "message": "取消"+ },+ "regionEmpty": {+ "message": "该区域没有可读内容或已被移除,请重新选择。"}}diff --git a/apps/extension/region-clip.test.mjs b/apps/extension/region-clip.test.mjsnew file mode 100644index 00000000..17d7036e--- /dev/null+++ b/apps/extension/region-clip.test.mjs@@ -0,0 +1,45 @@+import { expect, test } from "bun:test";+import { createWindow } from "@mixmark-io/domino";++test("region conversion preserves only chosen visible content and does not alter the source DOM", async () => {+ const { regionMarkdown } = await import("./src/region-selection");+ const window = createWindow('<title>Page</title><nav>Outside navigation</nav><section id="chosen"><h2>Chosen heading</h2><p>Text <a href="/link">link</a></p><table><tr><th>A</th></tr><tr><td>Cell</td></tr></table><pre><code>line 1\n\nline 2</code></pre><img src="/photo.png"><p hidden>Hidden text</p><script>bad()</script><input value="private"><div id="edgeever-region-picker">Picker controls</div></section><aside>Outside recommendations</aside>', "https://example.test/story");+ const original = window.document.documentElement.outerHTML;+ const markdown = regionMarkdown(window.document.getElementById("chosen"), window.location.href);+ for (const expected of ["## Chosen heading", "[link](https://example.test/link)", "Cell", "line 1\n\nline 2", "https://example.test/photo.png"]) expect(markdown).toContain(expected);+ for (const excluded of ["Outside", "Hidden text", "bad()", "private", "Picker controls"]) expect(markdown).not.toContain(excluded);+ expect(window.document.documentElement.outerHTML).toBe(original);+});++test("shrinking a table or code block keeps indivisible Markdown containers intact", async () => {+ const { RegionSelection, regionMarkdown, regionWrapper } = await import("./src/region-selection");+ const window = createWindow('<section id="chosen"><table id="tbl"><caption id="cap">Summary</caption><tbody id="body"><tr id="row"><th id="h1">H1</th><th id="h2">H2</th></tr><tr><td>A</td><td>B</td></tr></tbody></table><pre id="pre"><code id="code">line 1\n\nline 2</code></pre></section>', "https://example.test/story");+ for (const element of Array.from(window.document.querySelectorAll("*"))) {+ element.getBoundingClientRect = () => ({ width: 120, height: 40, left: 0, top: 0, right: 120, bottom: 40 });+ }+ const tableSelection = new RegionSelection(regionWrapper(window.document.getElementById("h1")));+ expect(tableSelection.element.id).toBe("tbl");+ expect(tableSelection.canShrink).toBe(true);+ tableSelection.child();+ expect(tableSelection.element.id).toBe("cap");+ tableSelection.sibling("nextElementSibling");+ expect(tableSelection.element.id).toBe("cap");++ const bodyTable = createWindow('<section><table id="tbl"><tbody id="body"><tr><th>H1</th><th>H2</th></tr><tr><td>A</td><td>B</td></tr></tbody></table><p>Other</p></section>', "https://example.test/story");+ for (const element of Array.from(bodyTable.document.querySelectorAll("*"))) {+ element.getBoundingClientRect = () => ({ width: 120, height: 40, left: 0, top: 0, right: 120, bottom: 40 });+ }+ const wholeTable = new RegionSelection(regionWrapper(bodyTable.document.querySelector("td")));+ expect(wholeTable.element.id).toBe("tbl");+ expect(wholeTable.canShrink).toBe(false);+ wholeTable.child();+ expect(wholeTable.element.id).toBe("tbl");+ expect(regionMarkdown(wholeTable.element, "https://example.test/story")).toBe("| H1 | H2 |\n| --- | --- |\n| A | B |");++ const codeSelection = new RegionSelection(regionWrapper(window.document.getElementById("code")));+ expect(codeSelection.element.id).toBe("pre");+ expect(codeSelection.canShrink).toBe(false);+ codeSelection.child();+ expect(codeSelection.element.id).toBe("pre");+ expect(regionMarkdown(codeSelection.element, "https://example.test/story")).toBe("```\nline 1\n\nline 2\n```");+});diff --git a/apps/extension/src/background.ts b/apps/extension/src/background.tsindex 9bc75dff..ab6676da 100644--- a/apps/extension/src/background.ts+++ b/apps/extension/src/background.ts@@ -114,7 +114,7 @@ type CapturedPage = {url: string;markdown: string;plainText?: string;- kind?: "page" | "selection";+ kind?: "page" | "selection" | "region";platform?: "medium" | "substack";author?: string;publishedAt?: PublishedTime;@@ -1865,7 +1865,41 @@ const currentPageCaptureRoute = (pageUrl: string) => {return { kind:/^https?:\/\//i.test(pageUrl) ? 'page' : 'unavailable' };};-chrome.runtime.onMessage.addListener((message: { type?: string; page?: unknown; requestId?: string; result?: unknown }, _sender: unknown, sendResponse: (response: unknown) => void) => {+chrome.runtime.onMessage.addListener((message: { type?: string; page?: unknown; requestId?: string; result?: unknown }, _sender: { id?: string; tab?: { id?: number }; frameId?: number; url?: string }, sendResponse: (response: unknown) => void) => {+ if (message.type === "startRegionClip") {+ void (async () => {+ try {+ await ensureClipperReady();+ const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });+ if (!tab?.id) throw new Error(t("currentPageNotFound"));+ if (!/^https?:\/\//i.test(tab.url || "")) throw new Error(t("pageAccessDenied"));+ try { await chrome.scripting.executeScript({ target: { tabId: tab.id, frameIds: [0] }, files: ["assets/region-clip.js"] }); }+ catch (error) { throw new Error(describeCaptureError(error)); }+ sendResponse({ ok: true });+ } catch (error) { sendResponse({ ok: false, message: error instanceof Error ? error.message : t("saveFailed") }); }+ })();+ return true;+ }+ if (message.type === "saveRegionClip") {+ void (async () => {+ try {+ const tabId = _sender.tab?.id;+ const page = message.page;+ if (_sender.id !== chrome.runtime.id || _sender.frameId !== 0 || typeof tabId !== "number"+ || !isCapturedPage(page) || page.kind !== "region" || !page.markdown.trim()+ || page.url !== _sender.url || !/^https?:\/\//i.test(page.url)) throw new Error(t("regionEmpty"));+ const settings = await ensureClipperReady();+ const images = await enqueueClip(() => createMemo(settings, page, tabId, page.url));+ const feedback = clipImageFeedback(images);+ await showFeedback(tabId, 0, feedback, "success");+ sendResponse({ ok: true, message: feedback });+ } catch (error) {+ const message = error instanceof Error ? error.message : "";+ sendResponse({ ok: false, message: message === t("regionEmpty") || message === t("platformPageChanged") ? message : describeSelectionError(error) });+ }+ })();+ return true;+ }if (message.type === 'getCurrentPageCaptureMode') {void (async()=>{const [tab]=await chrome.tabs.query({active:true,currentWindow:true});diff --git a/apps/extension/src/popup.ts b/apps/extension/src/popup.tsindex 459c708e..d6ede929 100644--- a/apps/extension/src/popup.ts+++ b/apps/extension/src/popup.ts@@ -10,3 +10,10 @@ export async function captureCurrentPage(settings: ExtensionSettings): Promise<sif (!response?.ok) throw new Error(response?.message || t("saveFailed"));return typeof response.message === "string" && response.message ? response.message : t("savedToEdgeEver");}++export async function startRegionClip(settings: ExtensionSettings): Promise<void> {+ if (!settings.instanceUrl || !settings.token) throw new Error(t("completePluginConfiguration"));+ await requestInstancePermission(settings.instanceUrl);+ const response = await chrome.runtime.sendMessage({ type: "startRegionClip" });+ if (!response?.ok) throw new Error(response?.message || t("saveFailed"));+}diff --git a/apps/extension/src/region-clip.ts b/apps/extension/src/region-clip.tsnew file mode 100644index 00000000..76eecb76--- /dev/null+++ b/apps/extension/src/region-clip.ts@@ -0,0 +1,3 @@+import { startRegionPicker } from "./ui/region-picker";++startRegionPicker();diff --git a/apps/extension/src/region-selection.ts b/apps/extension/src/region-selection.tsnew file mode 100644index 00000000..e75ea817--- /dev/null+++ b/apps/extension/src/region-selection.ts@@ -0,0 +1,64 @@+import { createDocument } from "@mixmark-io/domino";+import { platformElementHidden, platformHtmlMarkdown, platformReadableCopy } from "./platform-clip";++// Wrapper normalization and parent/child history adapted from MaoXian Web+// Clipper, src/js/content/ui.js (e69fbf9c), Copyright (c) 2018 Mika, MIT.+// See ../THIRD_PARTY_NOTICES.md. No source-page elements are modified.+const excluded = "html,head,script,style,template,iframe,object,embed,canvas,svg,video,audio,form,input,textarea,select,button,#edgeever-region-picker,#edgeever-clipper-toast";++export const selectableRegion = (element: Element | null): element is HTMLElement => {+ if (!element || element.matches(excluded) || element.closest("#edgeever-region-picker,#edgeever-clipper-toast") || platformElementHidden(element)) return false;+ const box = element.getBoundingClientRect();+ return box.width > 0 && box.height > 0 && !!(element.textContent?.trim() || element.matches("img") || element.querySelector("img"));+};++const sameBox = (a: Element, b: Element) => {+ const first = a.getBoundingClientRect(), second = b.getBoundingClientRect();+ return first.width === second.width && first.height === second.height;+};++const indivisibleChild = (element: Element, parent: Element | null) =>+ !!parent && ((element.matches("code") && parent.matches("pre"))+ || (element.matches("thead,tbody,tfoot,tr,td,th") && parent.matches("table,thead,tbody,tfoot,tr")));++const selectableDirectChild = (parent: Element): HTMLElement | undefined =>+ Array.from(parent.children).find((child): child is HTMLElement => selectableRegion(child) && !indivisibleChild(child, parent));++export const regionWrapper = (element: HTMLElement): HTMLElement => {+ const parent = element.parentElement;+ if (!parent || element.tagName === "BODY" || !selectableRegion(parent)) return element;+ const hasSibling = Array.from(parent.children).some(child => child !== element && selectableRegion(child));+ return indivisibleChild(element, parent) || (sameBox(element, parent) && !hasSibling) ? regionWrapper(parent) : element;+};++export class RegionSelection {+ private history: HTMLElement[] = [];+ constructor(public element: HTMLElement) {}+ parent() {+ const parent = this.element.parentElement;+ if (selectableRegion(parent)) { this.history.push(this.element); this.element = regionWrapper(parent); }+ }+ child() {+ const previous = this.history.pop();+ if (previous && previous !== this.element && this.element.contains(previous) && selectableRegion(previous)) this.element = previous;+ else {+ const child = selectableDirectChild(this.element);+ if (child) this.element = child;+ }+ }+ sibling(direction: "previousElementSibling" | "nextElementSibling") {+ let next = this.element[direction];+ while (next && (!selectableRegion(next) || indivisibleChild(next, this.element.parentElement))) next = next[direction];+ if (selectableRegion(next)) { this.history = []; this.element = next; }+ }+ get canExpand() { return selectableRegion(this.element.parentElement); }+ get canShrink() { return this.history.some(element => element.isConnected && this.element.contains(element)) || !!selectableDirectChild(this.element); }+}++export const regionMarkdown = (element: Element, pageUrl: string): string => {+ if (!element.isConnected || platformElementHidden(element)) return "";+ const copy = platformReadableCopy(element);+ copy.querySelectorAll("#edgeever-region-picker,#edgeever-clipper-toast").forEach(node => node.remove());+ // Inert parsing keeps conversion from activating copied scripts or images.+ return platformHtmlMarkdown(createDocument(copy.outerHTML).body, pageUrl);+};diff --git a/apps/extension/src/ui/popup.tsx b/apps/extension/src/ui/popup.tsxindex 0528b472..f6b29324 100644--- a/apps/extension/src/ui/popup.tsx+++ b/apps/extension/src/ui/popup.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from "react";-import { Check, LockKeyhole, Save, Settings } from "lucide-react";+import { Check, LockKeyhole, MousePointer2, Save, Settings } from "lucide-react";import { getSettings, type ExtensionSettings } from "../extension";-import { captureCurrentPage } from "../popup";+import { captureCurrentPage, startRegionClip } from "../popup";import { t } from "../i18n";import { Button, Status, type Feedback } from "./primitives";@@ -33,6 +33,13 @@ export function Popup() {catch (error) { setFeedback({ message: error instanceof Error ? error.message : t("saveFailed"), kind: "error" }); }finally { setBusy(false); }}+ async function selectRegion() {+ if (!settings || busy || mode?.kind === "unavailable") return;+ setBusy(true); setFeedback({ message: "" });+ try { await startRegionClip(settings); window.close(); }+ catch (error) { setFeedback({ message: error instanceof Error ? error.message : t("saveFailed"), kind: "error" }); }+ finally { setBusy(false); }+ }return <main className="w-80 p-5"><header className="flex items-center gap-2.5"><img src="/icons/icon-32.png" width={32} height={32} alt="" className="rounded-lg" />@@ -42,6 +49,7 @@ export function Popup() {</div></header><Button id="save" className="mt-6 h-11 w-full gap-2 rounded-lg" disabled={!settings || !mode || busy || mode.kind === "unavailable"} onClick={() => void save()}><Save aria-hidden="true" className="size-4" />{t("saveCurrentPage")}</Button>+ <Button id="select-region" variant="outline" className="mt-2 h-10 w-full gap-2 rounded-lg" disabled={!settings || !mode || busy || mode.kind === "unavailable"} onClick={() => void selectRegion()}><MousePointer2 aria-hidden="true" className="size-4" />{t("regionSelect")}</Button><Status {...feedback} message={feedback.message || hint} busy={busy} /><Button id="settings" variant="ghost" className="mt-3 w-full gap-2 text-xs" onClick={() => void chrome.runtime.openOptionsPage()}><Settings aria-hidden="true" className="size-4" />{t("pluginSettings")}</Button></main>;diff --git a/apps/extension/src/ui/region-picker.tsx b/apps/extension/src/ui/region-picker.tsxnew file mode 100644index 00000000..a292d3ca--- /dev/null+++ b/apps/extension/src/ui/region-picker.tsx@@ -0,0 +1,145 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { ArrowLeft, ArrowRight, MousePointer2, Save, X } from "lucide-react";+import { Button, Status } from "./primitives";+import { t } from "../i18n";+import { regionMarkdown, regionWrapper, RegionSelection, selectableRegion } from "../region-selection";++declare const __CLIP_REGION_CSS__: string;+type PickerService = { dispose: () => void; busy: () => boolean };+const scope = globalThis as typeof globalThis & { __edgeeverRegionPicker?: PickerService };++export function startRegionPicker() {+ // A second activation must not unlock confirmation of an in-flight save.+ if (scope.__edgeeverRegionPicker?.busy()) return;+ scope.__edgeeverRegionPicker?.dispose();+ const pageUrl = location.href;+ const previousFocus = document.activeElement;+ const host = document.createElement("div");+ host.id = "edgeever-region-picker";+ host.style.cssText = "all:initial!important;position:fixed!important;inset:0!important;z-index:2147483646!important;pointer-events:none!important;color-scheme:light!important";+ const shadow = host.attachShadow({ mode: "open" });+ const style = document.createElement("style");+ style.textContent = __CLIP_REGION_CSS__;+ const outline = document.createElement("div");+ outline.setAttribute("aria-hidden", "true");+ outline.style.cssText = "position:fixed;pointer-events:none;box-sizing:border-box;border:2px dashed #07130b;background:#07130b0a;display:none";+ const mount = document.createElement("div");+ shadow.append(style, outline, mount);+ document.documentElement.appendChild(host);+ const root = createRoot(mount);+ let hovered: HTMLElement | null = null;+ let selection: RegionSelection | null = null;+ let busy = false;+ let error = "";+ let disposed = false;+ const abort = new AbortController();++ const dispose = () => {+ if (disposed) return;+ disposed = true;+ abort.abort();+ root.unmount();+ host.remove();+ if (scope.__edgeeverRegionPicker === service) delete scope.__edgeeverRegionPicker;+ if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus({ preventScroll: true });+ };+ const service: PickerService = { dispose, busy: () => busy };+ scope.__edgeeverRegionPicker = service;+ const target = () => selection?.element ?? hovered;+ const draw = () => {+ const element = target();+ if (!element?.isConnected) { outline.style.display = "none"; return; }+ const box = element.getBoundingClientRect();+ Object.assign(outline.style, {+ display: "block", left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px`,+ borderStyle: selection ? "solid" : "dashed",+ boxShadow: selection ? "0 0 0 9999px #07130b14" : "none",+ });+ };+ const focusSave = () => shadow.querySelector<HTMLButtonElement>("#region-save")?.focus({ preventScroll: true });+ const adjust = (direction: "parent" | "child" | "previousElementSibling" | "nextElementSibling") => {+ if (!selection || busy) return;+ if (direction === "parent" || direction === "child") selection[direction]();+ else selection.sibling(direction);+ error = "";+ draw(); render();+ };+ const reselect = () => { selection = null; hovered = null; error = ""; draw(); render(); };+ const save = async () => {+ if (!selection || busy || disposed) return;+ busy = true; error = ""; render();+ try {+ if (location.href !== pageUrl) throw new Error(t("platformPageChanged"));+ const markdown = regionMarkdown(selection.element, pageUrl);+ if (!markdown) throw new Error(t("regionEmpty"));+ const response = await chrome.runtime.sendMessage({ type: "saveRegionClip", page: {+ title: document.title.trim() || location.hostname, url: pageUrl, markdown, kind: "region",+ } });+ if (!response?.ok) throw new Error(response?.message || t("saveFailed"));+ dispose();+ } catch (failure) {+ error = failure instanceof Error ? failure.message : t("saveFailed");+ } finally {+ busy = false;+ if (!disposed) render();+ }+ };+ function render() {+ flushSync(() => root.render(<section role="region" aria-label={t("regionPickerTitle")} lang={(chrome.i18n.getMessage("@@ui_locale") || "en").replace("_", "-")}+ onClick={event => event.stopPropagation()}+ className="fixed bottom-5 left-1/2 rounded-xl border border-border bg-card p-4 font-sans text-foreground"+ style={{ pointerEvents: "auto", width: "min(580px, calc(100% - 24px))", transform: "translateX(-50%)", boxShadow: "0 8px 32px #07130b24", zIndex: 1 }}>+ <div className="flex items-center gap-2 text-sm font-semibold"><MousePointer2 className="size-4" aria-hidden="true" />{t(selection ? "regionSelected" : "regionPickerTitle")}</div>+ <p className="mt-1.5 text-xs leading-5 text-muted-foreground">{t(selection ? "regionAdjustHint" : "regionPickHint")}</p>+ <div className="mt-3 flex flex-wrap items-center gap-2" role="toolbar" aria-label={t("regionPickerTitle")}>+ {selection && <>+ <Button size="sm" disabled={busy || !selection.canExpand} onClick={() => adjust("parent")}><ArrowLeft className="size-3.5" aria-hidden="true" />{t("regionExpand")}</Button>+ <Button size="sm" disabled={busy || !selection.canShrink} onClick={() => adjust("child")}><ArrowRight className="size-3.5" aria-hidden="true" />{t("regionShrink")}</Button>+ <Button size="sm" variant="ghost" disabled={busy} onClick={reselect}>{t("regionReselect")}</Button>+ </>}+ <Button id="region-save" size="sm" className="ms-auto" disabled={!selection || busy} onClick={() => void save()}><Save className="size-3.5" aria-hidden="true" />{t("regionSave")}</Button>+ <Button size="sm" variant="ghost" disabled={busy} onClick={dispose}><X className="size-3.5" aria-hidden="true" />{t("regionCancel")}</Button>+ </div>+ <Status message={busy ? t("readingAndSaving") : error} busy={busy} kind={error ? "error" : "normal"} />+ </section>));+ }+ const ours = (event: Event) => event.composedPath().includes(host);+ const regionAt = (event: Event) => {+ const element = event.composedPath().find(node => node instanceof HTMLElement);+ return element instanceof HTMLElement && selectableRegion(element) ? regionWrapper(element) : null;+ };+ window.addEventListener("pointermove", event => {+ if (ours(event) || selection || busy) return;+ hovered = regionAt(event);+ draw();+ }, { capture: true, signal: abort.signal });+ const intercept = (event: Event) => {+ if (ours(event)) return;+ event.preventDefault(); event.stopImmediatePropagation();+ if (event.type === "click" && !selection && !busy) {+ hovered = regionAt(event);+ if (hovered?.isConnected) { selection = new RegionSelection(hovered); draw(); render(); focusSave(); }+ }+ };+ for (const name of ["pointerdown", "pointerup", "mousedown", "mouseup", "click", "dblclick", "contextmenu"]) {+ window.addEventListener(name, intercept, { capture: true, signal: abort.signal });+ }+ window.addEventListener("keydown", event => {+ if (event.altKey || event.ctrlKey || event.metaKey) return;+ if (event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); if (!busy) dispose(); return; }+ if (!selection || busy) return;+ const directions = { ArrowLeft: "parent", ArrowRight: "child", ArrowUp: "previousElementSibling", ArrowDown: "nextElementSibling" } as const;+ if (event.key in directions) {+ event.preventDefault(); event.stopImmediatePropagation(); adjust(directions[event.key as keyof typeof directions]);+ } else if (event.key === "Enter" && (!ours(event) || shadow.activeElement?.id === "region-save")) {+ event.preventDefault(); event.stopImmediatePropagation(); void save();+ }+ }, { capture: true, signal: abort.signal });+ window.addEventListener("scroll", draw, { capture: true, passive: true, signal: abort.signal });+ window.addEventListener("resize", draw, { signal: abort.signal });+ for (const name of ["pagehide", "hashchange", "popstate"]) window.addEventListener(name, dispose, { signal: abort.signal });+ render();+ shadow.querySelector<HTMLElement>("section")?.setAttribute("tabindex", "-1");+ shadow.querySelector<HTMLElement>("section")?.focus({ preventScroll: true });+}diff --git a/apps/extension/vite.config.ts b/apps/extension/vite.config.tsindex 6d0381b4..79e7c9e0 100644--- a/apps/extension/vite.config.ts+++ b/apps/extension/vite.config.ts@@ -54,6 +54,15 @@ export default defineConfig({.map((item) => item.type === "asset" ? typeof item.source === "string" ? item.source : new TextDecoder().decode(item.source) : "").join("\n");if (!themeStyles) throw new Error("Missing compiled extension theme for shadow notifications");+ const region = await buildStandaloneScript({+ entryPoints: [fileURLToPath(new URL("./src/region-clip.ts", import.meta.url))],+ bundle: true, format: "iife", platform: "browser", target: "es2022", minify: true, write: false,+ jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"', __CLIP_REGION_CSS__: JSON.stringify(themeStyles) },+ legalComments: "eof",+ });+ this.emitFile({ type: "asset", fileName: "assets/region-clip.js", source: region.outputFiles[0].contents });+ this.emitFile({ type: "asset", fileName: "THIRD_PARTY_NOTICES.txt", source: await readFile(new URL("./THIRD_PARTY_NOTICES.md", import.meta.url), "utf8") });const feedback = await buildStandaloneScript({entryPoints: [fileURLToPath(new URL("./src/ui/clip-feedback.tsx", import.meta.url))],bundle: true, format: "iife", platform: "browser", target: "es2022", minify: true, write: false,diff --git a/bun.lock b/bun.lockindex 1da2672f..f892ac36 100644--- a/bun.lock+++ b/bun.lock@@ -122,7 +122,7 @@},"apps/extension": {"name": "@edgeever/extension",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@joplin/turndown-plugin-gfm": "1.0.68","@mixmark-io/domino": "2.2.0",diff --git a/docs/browser-clipper-regions.md b/docs/browser-clipper-regions.mdnew file mode 100644index 00000000..a7b481dd--- /dev/null+++ b/docs/browser-clipper-regions.md@@ -0,0 +1,22 @@+# Save only part of a webpage++[简体中文](browser-clipper-regions.zh-CN.md)++Open the EdgeEver extension and choose **Select area**. Move over the page to preview its content boundaries, then click the area you want to keep. The click selects the content instead of opening its links.++- **Larger / Smaller**, or **Left / Right**, adjusts the selected parent/child region.+- **Up / Down** moves to the previous/next visible sibling region.+- **Reselect** returns to pointer selection. **Cancel** or **Esc** exits without saving.+- **Save to EdgeEver**, or **Enter** after selecting, creates a note in the extension's configured notebook. Scroll normally to inspect a long selection before saving.++The note keeps the page title, source link, capture time and the chosen content as Markdown, including supported tables, code, links and images. It uses the existing image-localization process and its partial-image feedback. Hidden content and form controls are omitted. The original webpage is not edited. An empty or removed region produces an error rather than saving the whole page.++Saving disables repeated confirmation and cancellation until the request finishes. On failure, the picker keeps the selection and displays the error; it does not retry automatically.++The picker works on accessible HTTP(S) pages. Browser-internal pages and extension-store restrictions still apply. It selects DOM content, not screenshot rectangles or iframe interiors. The existing **Clip current page** and selected-text actions remain available.++## Reference and verification++The selection interaction and wrapper/history algorithm are adapted from [MaoXian Web Clipper](https://github.com/mika-cn/maoxian-web-clipper/blob/e69fbf9c04bad7051d3810e1cef4d82138f812df/src/js/content/ui.js). Its MIT notice is preserved in [third-party notices](../apps/extension/THIRD_PARTY_NOTICES.md) and included in built extension packages.++See the [change checklist](changes/2026-10-29-region-clip.md) for validation evidence and remaining platform checks. Build Chromium with `bun run build:extension` and load `apps/extension/dist` as an unpacked development extension; Firefox uses `bun run build:extension:firefox`. These builds do not update an installed extension or publish to a store.diff --git a/docs/browser-clipper-regions.zh-CN.md b/docs/browser-clipper-regions.zh-CN.mdnew file mode 100644index 00000000..4ee61100--- /dev/null+++ b/docs/browser-clipper-regions.zh-CN.md@@ -0,0 +1,22 @@+# 只剪藏网页的一部分++[English](browser-clipper-regions.md)++打开 EdgeEver 插件,点击“选择区域”。移动鼠标预览页面中的内容边界,点击要保留的区域;这次点击用于选择,不会打开网页里的链接。++- 用“扩大/缩小”或左/右方向键调整父子区域。+- 用上/下方向键切换到前一个/后一个可见的同级区域。+- “重新选择”回到鼠标选择状态;“取消”或 Esc 退出,不保存。+- 选好后点击“保存到 EdgeEver”或按 Enter,在插件配置的笔记本中创建笔记。长区域可以先滚动检查,再保存。++笔记保留网页标题、来源链接、采集时间及所选内容的 Markdown,包括支持的表格、代码、链接和图片。图片沿用既有本地化流程,部分图片失败时使用原提示。隐藏内容和表单控件不进入笔记,原网页不被修改。区域为空或已移除时显示错误,不会改为保存整页。++保存开始后禁用重复确认和取消,直到请求完成。失败时保留选区并显示错误,不自动重试。++选择器用于可访问的 HTTP(S) 页面;浏览器内部页面和扩展商店的限制仍然适用。选择的是 DOM 内容,不是截图矩形或 iframe 内部。原“剪藏当前网页”和选中文字操作仍可使用。++## 参考与验证++选择交互及包裹层/历史回退算法参考并改编自 [MaoXian Web Clipper](https://github.com/mika-cn/maoxian-web-clipper/blob/e69fbf9c04bad7051d3810e1cef4d82138f812df/src/js/content/ui.js),MIT 署名保留在[第三方声明](../apps/extension/THIRD_PARTY_NOTICES.md)中,并随构建后的插件包一起提供。++验证证据和未完成的平台检查见[变更清单](changes/2026-10-29-region-clip.zh-CN.md)。Chromium 使用 `bun run build:extension` 构建,再以“加载已解压的扩展程序”加载 `apps/extension/dist`;Firefox 使用 `bun run build:extension:firefox`。构建不会更新已安装插件,也不会发布到商店。diff --git a/docs/changes/2026-10-29-region-clip.md b/docs/changes/2026-10-29-region-clip.mdnew file mode 100644index 00000000..3ab3d389--- /dev/null+++ b/docs/changes/2026-10-29-region-clip.md@@ -0,0 +1,29 @@+# Select a webpage region to clip++[简体中文](2026-10-29-region-clip.zh-CN.md) · [Issue #703](https://github.com/tianma-if/edgeever/issues/703)++## Problem and outcome++Automatic article extraction can include unrelated content. Add an explicit DOM-region picker to the browser extension so the user can save only the content they choose. Baseline: `a2342067`.++## Allowed changes and acceptance++1. Add **Select area** beside the existing popup capture action. Request the configured instance permission inside the click gesture, as today. Start the picker only on accessible HTTP(S) pages; surface existing access/configuration errors. Do not add browser permissions or persistent content scripts.+2. Highlight the content block under the pointer without changing source elements. Clicking locks the block, not its link or website action. Offer larger/smaller parent-child selection, reselect, save, and cancel. Follow MaoXian's keyboard model: Left/Right expands/shrinks, Up/Down selects adjacent visible siblings, Enter confirms a locked selection, and Escape leaves before saving. Reuse its wrapper normalization and parent-child history algorithm with MIT attribution (reference `e69fbf9c`, `src/js/content/ui.js`); omit its source-DOM hiding and saved-selector subsystem. Keep page scrolling available. Reinjection replaces the previous picker. Cancel/reinjection removes its UI/listeners and restores focus; neither creates a note.+3. Only an explicit save converts the selected, still-connected visible DOM into Markdown. Reuse the existing visible-content filter and HTML/table/code/link/image conversion; omit hidden content, scripts, form controls and extension UI. Keep the page title, source URL, capture time and existing image-localization behavior. Never fall back to the full page if the region is empty, removed or unreadable. Do not capture iframe interiors, screenshots or off-page private content.+4. Save through the existing notebook selection, memo creation, serialization queue and image pipeline. Validate the content-script sender and unchanged source page before writing. Disable duplicate confirmation while saving; show conversion/save failures with the selected area retained, and reuse existing success/partial-image feedback. No automatic retries. Cancellation is available before save, not after a write has begun.+5. Reuse the shared extension buttons/theme in a Shadow DOM toolbar; localize every new string in English, Simplified Chinese, Japanese and Polish. Add only the injection/build wiring needed for this entry, plus bilingual usage documentation. Keep current page/selection/platform capture behavior unchanged.++Acceptance: first add focused popup/background/capture checks for the new path; exercise the built picker in a real browser with selection, adjustment, scrolling, cancellation, repeated activation, visible-content conversion, failures and save readback. Inspect actual UI and verify a selected image uses the existing attachment pipeline. Run affected extension checks, Chromium/Firefox builds and Firefox lint, plus required root/mobile typechecks and Web build. Use isolated fixtures and storage, not user notes.++## Boundaries and risk++No API/schema/migration, authentication, backup, native client, main app release version, store submission, or deployment changes. The browser extension package version is bumped to `0.4.0` for this new capability. No new dependency.++The main risks are interference with webpage controls and saving the wrong region. The picker suppresses page activation only while selecting, shows the locked boundary, and checks the page again before saving. Revert the added popup/injection modules to roll back; notes already explicitly saved remain ordinary notes. Chromium and Firefox runtime compatibility must be reported separately from compilation.++## Completion++Items 1–5 are implemented and match the diff: popup action, attributed region-selection module and isolated toolbar, existing save/image pipeline, four locales, injection/build wiring, notices, usage documentation and extension version `0.4.0`. Duplicate activation replaces a selection-stage picker; during an in-flight save it keeps the original busy picker to prevent another confirmation. No permissions, API, schema, dependencies, main app release versions or original capture paths changed.++The final 149 affected checks, required typechecks/Web build, both extension builds and targeted lint passed. Browser fixture interactions and selected-content readback passed, including error/no-write paths and 390px layout. Firefox lint has 0 errors and 10 library warnings. [Evidence](evidence/2026-10-29-region-clip/README.md) records the initial aggregate popup timeout, successful affected rerun, actual test boundaries and screenshots. Installed-browser / real-instance acceptance remains outstanding. Changes are local and uncommitted; no push, publication or deployment.diff --git a/docs/changes/2026-10-29-region-clip.zh-CN.md b/docs/changes/2026-10-29-region-clip.zh-CN.mdnew file mode 100644index 00000000..296cebd6--- /dev/null+++ b/docs/changes/2026-10-29-region-clip.zh-CN.md@@ -0,0 +1,29 @@+# 网页区域剪藏++[English](2026-10-29-region-clip.md) · [Issue #703](https://github.com/tianma-if/edgeever/issues/703)++## 问题与目标++自动正文提取会混入无关内容。在浏览器插件中增加明确的 DOM 内容区域选择,让用户只保存所选部分。基线:`a2342067`。++## 允许变更与验收++1. 在插件弹窗现有采集入口旁增加“选择区域”。沿用点击手势内申请实例权限的机制,仅在可访问的 HTTP(S) 页面启动;配置或权限错误使用既有提示。不增加浏览器权限或常驻脚本。+2. 悬停高亮内容块,不改动来源元素;点击锁定区域,不触发网页链接或操作。提供扩大/缩小父子区域、重新选择、保存、取消。沿用 MaoXian 的键盘模型:左/右键扩大/缩小,上/下键选择相邻可见区域,锁定后 Enter 确认,保存前 Escape 退出。复用其同尺寸包裹层归一化和父子选区历史算法,保留 MIT 署名(参考 `e69fbf9c` 的 `src/js/content/ui.js`),不引入隐藏原 DOM 或保存历史选择器的系统。保留页面滚动;重复启动替换旧选择器;取消或替换清理界面和监听并恢复焦点,不创建笔记。+3. 仅明确保存时把仍存在的所选可见 DOM 转为 Markdown。复用可见性过滤及现有 HTML、表格、代码、链接和图片转换;去掉隐藏内容、脚本、表单控件及插件界面。保留网页标题、来源、采集时间及原图片本地化规则。区域为空、移除或不可读时不回退整页;不采集 iframe 内部、截图或页面之外的私有内容。+4. 复用笔记本选择、笔记创建、串行保存队列及图片流程。写入前检查内容脚本来源和网页地址未变;保存中禁用重复确认,转换或保存失败保留区域并显示错误,成功或部分图片失败复用原反馈。不自动重试;取消只适用于尚未开始保存的阶段。+5. 使用插件共享按钮、主题及 Shadow DOM 工具条,新文案同步英文、简体中文、日文、波兰文。仅增加此入口所需的注入/构建接入及双语使用文档;原整页、文字选择和平台专用采集行为不变。++验收:先加入新入口的针对性弹窗、后台及内容转换检查,再实现。真实浏览器运行构建后的选择器,覆盖选择、调整、滚动、取消、重复启动、可见内容转换、失败及保存读回;检查实际界面及所选图片沿用附件流程。执行受影响插件检查、Chromium/Firefox 构建和 Firefox lint,以及项目要求的主端/移动端类型检查和 Web 构建。使用隔离页面与存储,不操作用户笔记。++## 边界与风险++不修改 API、数据库或 migration、认证、备份、原生客户端、主应用版本号、商店发布和部署;浏览器插件版本提升至 `0.4.0`;不增加依赖。++主要风险是干扰网页操作及保存错区域。仅选择期间阻止网页激活,锁定后显示边界,写入前核对来源。回退新增弹窗/注入模块即可撤回功能;已经明确保存的笔记仍是普通笔记。Chromium、Firefox 的真实运行兼容性与构建结果分别报告。++## 完成核对++第1–5项已完成,与实际 diff 对应:弹窗入口、保留署名的区域选择模块及隔离工具条、原保存/图片流程接入、四种语言、注入/构建接入、许可声明、使用文档及插件版本 `0.4.0`。重复启动在选择阶段替换旧选择器;已有保存进行时保留原忙碌选择器,防止再次确认。未修改权限、API、数据库、依赖、主应用版本号或原采集路径。++最终149项受影响检查、必需类型检查/Web构建、两种插件构建及目标 lint 通过;隔离浏览器交互和所选内容读回通过,包括错误/零写入路径和390px布局。Firefox lint 为0错误、10项依赖告警。[验收记录](evidence/2026-10-29-region-clip/README.zh-CN.md)保留首轮全插件弹窗超时、受影响重跑通过、实际测试边界及截图。已安装浏览器和真实实例验收仍待完成。修改仅在本地,未提交、推送、发布或部署。diff --git a/docs/changes/evidence/2026-10-29-region-clip/README.md b/docs/changes/evidence/2026-10-29-region-clip/README.mdnew file mode 100644index 00000000..d96a5bd4--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/README.md@@ -0,0 +1,22 @@+# Region clipping verification++[简体中文](README.zh-CN.md)++## Browser interaction and content++The actual built popup and `region-clip.js` were exercised in Ego Lite Chromium on an isolated page. `serve-ui.mjs` supplies the browser-extension message boundary and records save payloads; it does not use a real instance or installed extension. Run `bun run build:extension`, then `bun docs/changes/evidence/2026-10-29-region-clip/serve-ui.mjs` and visit `http://127.0.0.1:18703/` to reproduce the UI fixture.++- Pointer preview, lock, Left/Right expansion/history, Up/Down sibling selection, Enter save and source link suppression worked. After cancellation the original link handler worked again, without creating a note.+- Selected output preserved headings, links, a table, code blank lines and the image URL. Navigation, the intro, the next section, CSS/HTML-hidden text and input values were absent from the selected payload. See `browser-captures.json`.+- Repeated activation left one picker. Scrolling kept the outline at the selected element's rectangle (observed top: `-57.4844px`, element: `-57.484375px`).+- A controlled save failure retained the region and showed the error. Repeated Enter while the save response was held produced exactly one completed save. Removed regions and changed URLs produced no write. Replacing the hovered DOM before clicking selected the new click target, not the stale element.+- At a 390px viewport / 375px available width, the toolbar occupied x=12–363, width=351, and bottom=809 inside height=844. See `selected-390px.png`; `selected-desktop.png` and `popup.png` show the other states. Shadow-root translation and sizing were corrected during inspection.++## Source and build checks++- Nine initial checks failed before implementation because the new popup action, content conversion and background handler did not exist.+- The final affected check set passed: **149 tests**, 0 failures (`affected-tests.txt`), including actual bundled-background memo creation and image upload/rewrite with mocked HTTP boundaries. New sender/frame validation, indivisible container shrinking, and injection-without-write checks passed.+- The first aggregate extension command passed 505 checks but timed out in the first React popup test at its 5-second limit; two following popup checks then encountered overlapping `act()` state. The isolated popup file passed all 9 checks, and the final 149-test affected run also passed. Unchanged extension checks were reused rather than rerunning the aggregate command.+- `bun run typecheck`, `bun run typecheck:mobile`, `bun run build:web`, targeted oxlint, Chromium and Firefox builds passed. Firefox lint: 0 errors, 0 notices, 10 bundled-library warnings (`firefox-lint.txt`), including React DOM's static innerHTML warnings in the added self-contained bundle; no warning was suppressed.++Installed Chrome/Edge/Firefox runtime acceptance and saving to a real instance remain unverified. The source changes are local, uncommitted and unpushed; no store submission or deployment was performed.diff --git a/docs/changes/evidence/2026-10-29-region-clip/README.zh-CN.md b/docs/changes/evidence/2026-10-29-region-clip/README.zh-CN.mdnew file mode 100644index 00000000..0d3432e6--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/README.zh-CN.md@@ -0,0 +1,22 @@+# 区域剪藏验收++[English](README.md)++## 浏览器交互与内容++在 Ego Lite Chromium 的隔离页面中运行实际构建的弹窗和 `region-clip.js`。`serve-ui.mjs` 模拟浏览器扩展消息边界并记录保存内容,不连接真实实例或已安装插件。先执行 `bun run build:extension`,再执行 `bun docs/changes/evidence/2026-10-29-region-clip/serve-ui.mjs`,访问 `http://127.0.0.1:18703/` 可复现界面夹具。++- 悬停预览、点击锁定、左右键扩大与历史回退、上下键切换同级、Enter 保存和阻止网页链接激活均通过。取消后原链接处理器恢复,未创建笔记。+- 输出保留标题、链接、表格、代码空行及图片 URL,不含导航、导语、下一节、CSS/HTML 隐藏内容和输入框值,见 `browser-captures.json`。+- 重复启动只保留一个选择器;滚动后边框仍贴合选区,观察到边框 top 为 `-57.4844px`、元素 top 为 `-57.484375px`。+- 受控保存失败时保留区域并显示错误;挂起保存响应期间连续按 Enter,最终仅保存一次。区域移除或 URL 改变均未写入;悬停后替换 DOM,再点击会选中新的实际目标,不会保存旧元素。+- 390px 视口、375px 可用宽度下,工具条 x=12–363、宽351、bottom=809,位于高844的视口内,见 `selected-390px.png`;桌面选区及弹窗见 `selected-desktop.png`、`popup.png`。检查中修正了 Shadow DOM 内的平移和宽度计算。++## 源码与构建检查++- 实现前9项新检查失败:当时缺少新弹窗入口、内容转换及后台处理器。+- 最终受影响检查 **149项通过、0失败**,见 `affected-tests.txt`。包含真实后台 bundle 的创建笔记、图片上传与地址改写,HTTP 边界使用模拟响应;新增发送者/帧检查、表格与代码块不可分割缩小保护及启动时零写入检查通过。+- 首次全插件命令中505项通过,首个 React 弹窗检查超过既有5秒限制,后续两项出现未完成 `act()` 的状态交叠;单独执行弹窗文件9项通过,最终149项受影响检查也通过。其余未变化检查复用,不再重复运行全插件命令。+- `bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`、目标 oxlint、Chromium/Firefox 构建通过。Firefox lint 为0错误、0提示、10项打包依赖告警,见 `firefox-lint.txt`,包含新增独立 bundle 中 React DOM 的静态 innerHTML 告警,未屏蔽告警。++尚未完成安装到 Chrome/Edge/Firefox 后的运行验收及连接真实实例保存。源码仅在本地,未提交、推送、商店发布或部署。diff --git a/docs/changes/evidence/2026-10-29-region-clip/affected-tests.txt b/docs/changes/evidence/2026-10-29-region-clip/affected-tests.txtnew file mode 100644index 00000000..14b1f1e6--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/affected-tests.txt@@ -0,0 +1,163 @@+bun test v1.3.14 (0d9b296a)++apps/extension/platform-save.test.mjs:+(pass) starting the region picker only injects its explicit script and writes nothing [30.68ms]+(pass) a selected region uses the memo and image-localization pipeline without whole-page capture [11.10ms]+(pass) region wrong-frame cannot create a note [3.76ms]+(pass) region no-tab cannot create a note [3.40ms]+(pass) region wrong-extension cannot create a note [3.28ms]+(pass) region changed-url cannot create a note [3.16ms]+(pass) region empty cannot create a note [6.86ms]+(pass) region not-region cannot create a note [3.51ms]+(pass) Android without desktop menu/window APIs can initialize and save from the popup [17.84ms]+(pass) BOSS popup detects login preview through the serialized DOM probe without creating or expanding anything [8.67ms]+(pass) BOSS readable page retains the adapted badge; failed or stale probes are unknown [15.72ms]+(pass) BOSS login preview can still save an explicit text selection without capturing the incomplete job [10.09ms]+(pass) wechat: toolbar and dedicated menu save the same note through the real parser [117.73ms]+(pass) jike: toolbar and dedicated menu save the same note through the real parser [24.03ms]+(pass) sspai: toolbar and dedicated menu save the same note through the real parser [53.36ms]+(pass) juejin: toolbar and dedicated menu save the same note through the real parser [105.14ms]+(pass) douban: toolbar and dedicated menu save the same note through the real parser [25.56ms]+(pass) boss: toolbar and dedicated menu save the same note through the real parser [21.45ms]+(pass) xueqiu: toolbar and dedicated menu save the same note through the real parser [40.74ms]+(pass) substack-note: toolbar and dedicated menu save the same note through the real parser [27.70ms]+(pass) hacker-news: toolbar and dedicated menu save the same note through the real parser [33.56ms]+(pass) v2ex: toolbar and dedicated menu save the same note through the real parser [21.45ms]+(pass) xiaoyuzhou: toolbar and dedicated menu save the same note through the real parser [46.53ms]+(pass) facebook: toolbar and dedicated menu save the same note through the real parser [55.06ms]+(pass) instagram: toolbar and dedicated menu save the same note through the real parser [72.96ms]+(pass) threads: toolbar and dedicated menu save the same note through the real parser [42.15ms]+(pass) bluesky: toolbar and dedicated menu save the same note through the real parser [39.04ms]+(pass) linkedin: toolbar and dedicated menu save the same note through the real parser [57.83ms]+(pass) Douban toolbar keeps paragraphs and archives all images after installing its own request rule [13.66ms]+(pass) Douban menu keeps paragraphs and archives all images after installing its own request rule [12.72ms]+(pass) Douban rule failure preserves one note and reports incomplete archival [11.06ms]+(pass) Sspai toolbar supplies its image source header before archiving [23.99ms]+(pass) Sspai menu supplies its image source header before archiving [25.45ms]+(pass) Juejin toolbar saves the complete comparison table alongside archived article images [67.40ms]+(pass) Juejin menu saves the complete comparison table alongside archived article images [72.64ms]+(pass) Sspai toolbar retains article updates and archives their images without changing publication time [27.26ms]+(pass) Sspai menu retains article updates and archives their images without changing publication time [25.89ms]+(pass) WeChat toolbar cleans publisher promotions before archiving body images [45.50ms]+(pass) WeChat menu cleans publisher promotions before archiving body images [44.52ms]+(pass) a new platform toolbar still saves a valid selection instead of its full article [9.11ms]+(pass) Xiaoyuzhou saves the current client route using MAIN-world props while bootstrap JSON stays old [11.98ms]+(pass) request, extension, tab and frame correlation reject unrelated responses [9.22ms]+(pass) failDownload: keeps the saved body, reports external images, and never creates twice [18.66ms]+(pass) failUpload: keeps the saved body, reports external images, and never creates twice [33.70ms]+(pass) failRewrite: keeps the saved body, reports external images, and never creates twice [22.09ms]+(pass) editConflict: keeps the saved body, reports external images, and never creates twice [20.17ms]+(pass) images beyond the limit count towards partial status after 30 successful uploads [15.54ms]+(pass) no Show Notes is a successful, explicitly qualified note [10.68ms]+(pass) wechat: unreadable content never falls back to a whole-page note [7.14ms]+(pass) jike: unreadable content never falls back to a whole-page note [5.65ms]+(pass) sspai: unreadable content never falls back to a whole-page note [6.44ms]+(pass) juejin: unreadable content never falls back to a whole-page note [6.66ms]+(pass) douban: unreadable content never falls back to a whole-page note [5.90ms]+(pass) boss: unreadable content never falls back to a whole-page note [5.73ms]+(pass) xueqiu: unreadable content never falls back to a whole-page note [5.75ms]+(pass) substack-note: unreadable content never falls back to a whole-page note [5.81ms]+(pass) hacker-news: unreadable content never falls back to a whole-page note [5.89ms]+(pass) v2ex: unreadable content never falls back to a whole-page note [5.42ms]+(pass) xiaoyuzhou: unreadable content never falls back to a whole-page note [5.86ms]+(pass) facebook: unreadable content never falls back to a whole-page note [6.28ms]+(pass) instagram: unreadable content never falls back to a whole-page note [6.32ms]+(pass) threads: unreadable content never falls back to a whole-page note [7.86ms]+(pass) bluesky: unreadable content never falls back to a whole-page note [7.08ms]+(pass) linkedin: unreadable content never falls back to a whole-page note [39.82ms]+(pass) navigation while resolving the notebook cancels the old content before creation [10.70ms]+(pass) denyInstance: gives an actionable permission error without creating a note [4.75ms]+(pass) denyScripting: gives an actionable permission error without creating a note [5.28ms]+(pass) a stale sender URL after SPA navigation does not reject the current post [33.43ms]+(pass) a stale sender URL after SPA navigation still cancels real navigation [20.19ms]+(pass) a pending saving toast cannot replace the already clicked post with a later right-click [17.61ms]+(pass) queued social menu clips freeze each clicked post before a later right-click [99.29ms]+(pass) Bluesky toolbar saves rendered link destinations without hidden text [16.74ms]+(pass) Bluesky menu saves rendered link destinations without hidden text [15.75ms]+(pass) medium-article: unreadable rendered article returns an error without creating a fallback note [27.93ms]+(pass) substack-article: unreadable rendered article returns an error without creating a fallback note [8.68ms]+(pass) Douban list menu saves only the selected own short comment [11.37ms]+(pass) Jike Web detail login redirects show access guidance and never save the QR page as a post [4.63ms]+(pass) jike: no clicked selection still rejects the restricted whole page [4.17ms]+(pass) jike: a lost selection retains the clicked text without saving the restricted whole page [7.07ms]+(pass) jike: a stable selection saves only the selected passage [11.05ms]+(pass) jike: navigateBeforeSelectionCapture refuses a stale selection before note creation [6.92ms]+(pass) jike: navigateDuringNotebookLookup refuses a stale selection before note creation [6.66ms]+(pass) douban: no clicked selection still rejects the restricted whole page [5.46ms]+(pass) douban: a lost selection retains the clicked text without saving the restricted whole page [8.63ms]+(pass) douban: a stable selection saves only the selected passage [9.47ms]+(pass) douban: navigateBeforeSelectionCapture refuses a stale selection before note creation [6.96ms]+(pass) douban: navigateDuringNotebookLookup refuses a stale selection before note creation [7.15ms]+(pass) restricted toolbar and another tab's selection-menu never exchange capture replies [119.38ms]+(pass) restricted toolbar and another tab's generic-toolbar never exchange capture replies [123.49ms]+(pass) selection menu rejects navigation during capture without saving a different page [7.43ms]+(pass) selection menu rejects navigation during notebook without saving a different page [7.38ms]+(pass) selection menu rejects navigation during queued without saving a different page [10.68ms]+(pass) iframe selection keeps its own source while binding the top-level tab [8.41ms]+(pass) iframe selection navigation is rejected [7.39ms]+(pass) selection menu retains the browser text fallback when injection is unavailable on the same page [6.34ms]+(pass) a timed-out capture's late reply cannot complete the next queued selection [16.42ms]+(pass) medium-article: actual capture/save keeps platform metadata and uses shared image archival [47.63ms]+(pass) substack-article: actual capture/save keeps platform metadata and uses shared image archival [16.83ms]+(pass) Jike topic menu saves precisely the marked card while toolbar asks for a post or selection [26.29ms]+(pass) a real Substack paywall warns and refuses a whole-article preview [9.28ms]+(pass) Substack restricted article still saves an explicit visible passage [9.94ms]+(pass) Substack article identity survives missing body and refuses a paywall-only generic fallback [29.83ms]+(pass) medium-article: failDownload keeps one note and reports incomplete image archival [34.63ms]+(pass) medium-article: failUpload keeps one note and reports incomplete image archival [35.69ms]+(pass) medium-article: failRewrite keeps one note and reports incomplete image archival [39.63ms]+(pass) substack-article: failDownload keeps one note and reports incomplete image archival [13.63ms]+(pass) substack-article: failUpload keeps one note and reports incomplete image archival [13.24ms]+(pass) substack-article: failRewrite keeps one note and reports incomplete image archival [15.72ms]+(pass) generic toolbar and selection report failDownload instead of complete image archival [17.96ms]+(pass) generic toolbar and selection report failUpload instead of complete image archival [17.41ms]+(pass) generic toolbar and selection report failRewrite instead of complete image archival [18.57ms]+(pass) LinkedIn toolbar saves professional metadata without changing the author or publication label [22.28ms]+(pass) LinkedIn menu saves professional metadata without changing the author or publication label [22.99ms]+(pass) Xueqiu right-click on a truncated feed saves only the selected full public detail and archives its image [14.24ms]+(pass) selection-menu: a queued click keeps A after the live selection becomes B [37.32ms]+(pass) generic-toolbar: a queued click keeps A after the live selection becomes B [22.51ms]+(pass) platform-toolbar: a queued click keeps A after the live selection becomes B [21.95ms]+(pass) feed-toolbar: a queued click keeps A after the live selection becomes B [21.45ms]+(pass) a whole-page toolbar click cannot become a later selection while queued [24.07ms]+(pass) selection feedback delay cannot change the clicked passage [8.37ms]+(pass) changed selection saves the original literal text without Markdown reinterpretation [9.58ms]+(pass) stable rich selection preserves code blank lines and archives its selected image [12.22ms]+(pass) current signed-in Jike Web detail saves through the platform route [22.97ms]+(pass) current signed-in Jike Web detail cancels navigation [12.61ms]+(pass) native Jike Web feed menu resolves current props and expands only the selected original post [18.38ms]+(pass) Jike Web card identity recycling during notebook lookup cancels before creating a memo [11.11ms]+(pass) Jike Web detail same-author post mismatch before-capture creates no memo [7.32ms]+(pass) Jike Web detail same-author post mismatch during-notebook-lookup creates no memo [13.19ms]+(pass) legacy Jike Web share detail retains its H5 data identity checks [11.77ms]+(pass) Jike Web detail rejects DOM from another post even when current props match the route [9.03ms]+(pass) Jike Web gallery detail normal verifies content and retains nine images [15.17ms]+(pass) Jike Web gallery detail images-only verifies content and retains nine images [14.74ms]+(pass) Jike Web gallery detail changed-image verifies content and retains nine images [9.13ms]+(pass) Jike Web detail expands its selected card before verifying the full public body [29.27ms]++apps/extension/capture-bundle.test.mjs:+(pass) whole-page and selection captures share table conversion and preserve code blank lines [143.18ms]+(pass) Medium page capture retains story blocks and both images without article controls [237.86ms]+(pass) Substack article capture retains sections and images on custom domains without subscription UI [114.67ms]+(pass) the injected page capture is a standalone classic script [583.95ms]++apps/extension/popup.test.mjs:+(pass) area selection requests permission in the click and starts the picker without capturing the page [0.31ms]+(pass) popup requests instance permission synchronously within the click before capturing [0.14ms]+(pass) denied permission prevents popup capture [0.08ms]+(pass) instance permission omits nonstandard ports while connection keeps the configured endpoint [0.26ms]+(pass) missing configuration never requests permissions or capture [0.04ms]+(pass) popup retains background failures and localized success fallback [0.07ms]+(pass) React popup shows login-required while retaining explicit selected-text capture [160.50ms]+(pass) React popup shows content-restricted while retaining explicit selected-text capture [16.63ms]+(pass) React popup does not label an unknown page adapted from a platform name alone [16.62ms]++apps/extension/region-clip.test.mjs:+(pass) region conversion preserves only chosen visible content and does not alter the source DOM [7.99ms]+(pass) shrinking a table or code block keeps indivisible Markdown containers intact [3.23ms]++ 149 pass+ 0 fail+ 828 expect() calls+Ran 149 tests across 4 files. [4.61s]diff --git a/docs/changes/evidence/2026-10-29-region-clip/browser-captures.json b/docs/changes/evidence/2026-10-29-region-clip/browser-captures.jsonnew file mode 100644index 00000000..7a32b741--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/browser-captures.json@@ -0,0 +1 @@+[{"type":"saveRegionClip","page":{"title":"区域剪藏验收文章","url":"http://127.0.0.1:18703/","markdown":"## 只剪藏这一节\n\n保留这段文字和 [原文链接](http://127.0.0.1:18703/should-not-navigate)。\n\n| 项目 | 结果 |\n| --- | --- |\n| 区域内容 | 完整保留 |\n\n```\nconst first = 1;\n\nconst second = 2;\n```\n\n","kind":"region"}},{"type":"saveRegionClip","page":{"title":"区域剪藏验收文章","url":"http://127.0.0.1:18703/","markdown":"## 只剪藏这一节\n\n保留这段文字和 [原文链接](http://127.0.0.1:18703/should-not-navigate)。\n\n| 项目 | 结果 |\n| --- | --- |\n| 区域内容 | 完整保留 |\n\n```\nconst first = 1;\n\nconst second = 2;\n```\n\n","kind":"region"}},{"type":"saveRegionClip","page":{"title":"区域剪藏验收文章","url":"http://127.0.0.1:18703/","markdown":"## 动态替换后的选区","kind":"region"}}]\ No newline at end of filediff --git a/docs/changes/evidence/2026-10-29-region-clip/firefox-lint.txt b/docs/changes/evidence/2026-10-29-region-clip/firefox-lint.txtnew file mode 100644index 00000000..1ad0adc1--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/firefox-lint.txt@@ -0,0 +1,122 @@+$ bun run --cwd apps/extension lint:firefox+$ web-ext lint --source-dir dist-firefox --output text+Validation Summary:++errors 0+notices 0+warnings 10++WARNINGS:++Code Message Description File L+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/cap… 2+ assignment and performance ture.js+ to concerns, this may not+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/cap… 2+ assignment and performance ture.js+ to concerns, this may not+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/cli… 9+ assignment and performance p-feedback…+ to concerns, this may not .js+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/cli… 9+ assignment and performance p-feedback…+ to concerns, this may not .js+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/mai… 9+ assignment and performance n-DOlhqLeB…+ to concerns, this may not .js+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/mai… 9+ assignment and performance n-DOlhqLeB…+ to concerns, this may not .js+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe call Due to both security assets/bac… 6+ to and performance kground.js+ Nn(n).docu… concerns, this may not+ ment().wri… be set using dynamic+ te for values which have not+ argument 0 been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+DANGEROUS_EVAL The Evaluation of strings assets/bac… 1+ Function as code can lead to kground.js+ constructor security+ is eval. vulnerabilities and+ performance issues,+ even in the most+ innocuous of+ circumstances. Please+ avoid using `eval` and+ the `Function`+ constructor when at+ all possible.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/reg… 9+ assignment and performance ion-clip.js+ to concerns, this may not+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.+UNSAFE_VAR_ASSIGNMENT Unsafe Due to both security assets/reg… 9+ assignment and performance ion-clip.js+ to concerns, this may not+ innerHTML be set using dynamic+ values which have not+ been adequately+ sanitized. This can+ lead to security+ issues or fairly+ serious performance+ degradation.diff --git a/docs/changes/evidence/2026-10-29-region-clip/popup.png b/docs/changes/evidence/2026-10-29-region-clip/popup.pngnew file mode 100644index 00000000..857b0164Binary files /dev/null and b/docs/changes/evidence/2026-10-29-region-clip/popup.png differdiff --git a/docs/changes/evidence/2026-10-29-region-clip/selected-390px.png b/docs/changes/evidence/2026-10-29-region-clip/selected-390px.pngnew file mode 100644index 00000000..950842f5Binary files /dev/null and b/docs/changes/evidence/2026-10-29-region-clip/selected-390px.png differdiff --git a/docs/changes/evidence/2026-10-29-region-clip/selected-desktop.png b/docs/changes/evidence/2026-10-29-region-clip/selected-desktop.pngnew file mode 100644index 00000000..ee347c1fBinary files /dev/null and b/docs/changes/evidence/2026-10-29-region-clip/selected-desktop.png differdiff --git a/docs/changes/evidence/2026-10-29-region-clip/serve-ui.mjs b/docs/changes/evidence/2026-10-29-region-clip/serve-ui.mjsnew file mode 100644index 00000000..af110f9a--- /dev/null+++ b/docs/changes/evidence/2026-10-29-region-clip/serve-ui.mjs@@ -0,0 +1,8 @@+import { readFile } from 'node:fs/promises';+const root=import.meta.dir + '/../../../../apps/extension';+const messages=JSON.parse(await readFile(root+'/public/_locales/zh_CN/messages.json','utf8'));+const saved=[];let failNext=false;+const bridge=`const labels=${JSON.stringify(messages)}; window.chrome={i18n:{getMessage:(k)=>k==='@@ui_locale'?'zh_CN':(labels[k]?.message||k),getUILanguage:()=> 'zh-CN'},storage:{local:{get:async()=>({instanceUrl:'https://fixture.test',token:'fixture-only',notebookId:''})}},permissions:{request:async()=>true},runtime:{openOptionsPage:async()=>{},sendMessage:async(m)=>{if(m.type==='getCurrentPageCaptureMode')return {kind:'page'};if(m.type==='startRegionClip'){const s=document.createElement('script');s.src='/assets/region-clip.js?'+Date.now();await new Promise((res,rej)=>{s.onload=res;s.onerror=rej;document.head.append(s)});return {ok:true}}if(m.type==='saveRegionClip')return fetch('/captures',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(m)}).then(r=>r.json());throw Error('Unexpected message '+m.type)}}};`;+const fixture=`<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>区域剪藏验收文章</title><style>body{margin:0;background:#f5f5f3;color:#222;font:16px/1.8 system-ui}header{padding:22px 6vw;background:white;border-bottom:1px solid #ddd}main{max-width:1040px;margin:50px auto;display:grid;grid-template-columns:1fr 240px;gap:50px}article{background:white;padding:40px;border-radius:12px}h1{font-size:32px;line-height:1.3}h2{font-size:22px}aside{font-size:14px;color:#777}a{color:#244c36}img{width:280px;height:100px}.secret{display:none}pre{padding:16px;background:#f5f5f5}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:8px 20px}iframe{position:fixed;right:14px;top:14px;width:320px;height:330px;border:1px solid #ddd;border-radius:12px;z-index:100;background:#fff}#lower{margin-top:500px;padding:50px}button{padding:10px}</style><header><strong>Field Notes</strong> · 网页区域剪藏测试 <button id="open-popup" onclick="document.querySelector('iframe').hidden=false">打开插件</button><button id="restart" onclick="chrome.runtime.sendMessage({type:'startRegionClip'})">再次选择</button></header><main><article id="article"><h1>把需要的内容留下</h1><p id="intro">这段导语不属于目标区域。</p><section id="chosen"><h2 id="heading">只剪藏这一节</h2><p id="paragraph">保留这段文字和 <a id="source-link" href="/should-not-navigate" onclick="window.linkClicks=(window.linkClicks||0)+1">原文链接</a>。</p><table><tr><th>项目</th><th>结果</th></tr><tr><td>区域内容</td><td>完整保留</td></tr></table><pre><code>const first = 1;\n\nconst second = 2;</code></pre><img src="/photo.svg" alt="所选图片"><p class="secret">CSS 隐藏的私密内容</p><p hidden>hidden 私密内容</p><input value="表单私密值"></section><section id="sibling"><h2>下一节</h2><p>这是相邻区域,用方向键切换。</p></section></article><aside>广告和推荐内容<br>这一栏不应该进入笔记。</aside></main><section id="lower"><h2>页面底部</h2><p>用于滚动位置与边界验证。</p></section><iframe src="/popup.html" hidden></iframe><script>${bridge}</script></html>`;+Bun.serve({port:18703,hostname:'127.0.0.1',async fetch(req){const u=new URL(req.url);if(u.pathname==='/')return new Response(fixture,{headers:{'content-type':'text/html;charset=utf-8'}});if(u.pathname==='/photo.svg')return new Response('<svg xmlns="http://www.w3.org/2000/svg" width="280" height="100"><rect width="280" height="100" fill="#dae4d8"/><text x="20" y="60" fill="#07130b">Selected image</text></svg>',{headers:{'content-type':'image/svg+xml'}});if(u.pathname==='/fail-next'){failNext=true;return Response.json({ok:true})}if(u.pathname==='/captures'){if(req.method==='POST'){const value=await req.json();if(failNext){failNext=false;return Response.json({ok:false,message:'测试保存失败,请稍后重试'})}saved.push(value);return Response.json({ok:true,message:'已保存'})}return Response.json(saved)}if(u.pathname==='/popup.html'){let html=await readFile(root+'/dist/popup.html','utf8');html=html.replace('<head>',`<head><script>window.chrome=parent.chrome;window.close=()=>parent.document.querySelector('iframe').hidden=true;</script>`);return new Response(html,{headers:{'content-type':'text/html;charset=utf-8'}})}try{const file=await readFile(root+'/dist'+u.pathname);const type=u.pathname.endsWith('.js')?'text/javascript':u.pathname.endsWith('.css')?'text/css':u.pathname.endsWith('.png')?'image/png':'text/plain';return new Response(file,{headers:{'content-type':type}})}catch{return new Response('Not found',{status:404})}}});+console.log('Region UI fixture http://127.0.0.1:18703');