Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(web-clipper): preview and save the selection from the popup
Elian Dorane43d5b89d8f8
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.htmlindex b87e63ac44..370f0375ea 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html@@ -41,6 +41,11 @@cannot be saved or captured, so only <em>Note</em> and <em>Tabs</em> remainavailable there. The keyboard shortcut and the context menu still savethe page right away, without a preview.</li>+ <li>If text is selected on the page, the preview shows the selection instead,+ and <em>Save selection</em> saves it into the note of that page's+ clippings, as the context menu does. When the page also has an article,+ a switch above the preview chooses between <em>Selection</em> and <em>Whole page</em>.+ A selection can be saved even on a page that has no article.</li><li>Below the preview, a row of buttons offers the other actions: <em>Crop</em> (ascreenshot of an area you select), <em>Screenshot</em> (of the visible partof the page), <em>Note</em> (a link with a note) and <em>Tabs</em> (saves thediff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 961568f322..b33f88a7dd 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -308,6 +308,24 @@ describe("background", () => {});expect(await lastToast()).toMatchObject({ message: "Page has been saved to Trilium.", noteId: "saved" });});++ it("saves the selection the popup read as a clipping, without reading it again", async () => {+ const selection = {+ title: "Edited title",+ content: `<p>Quote</p><img src="i1">`,+ images: [ { imageId: "i1", src: "https://example.com/a.png" } ],+ pageUrl: PAGE_URL+ };++ await sendRuntimeMessage({ name: "save-selection", selection });++ expect(tabsSendMessage).not.toHaveBeenCalledWith(7, { name: "trilium-save-selection" });+ expect(facade.callService).toHaveBeenCalledWith("POST", "clippings", {+ ...selection,+ images: [ { ...selection.images[0], dataUrl: expect.stringMatching(PNG_DATA_URL) } ]+ });+ expect(await lastToast()).toMatchObject({ message: "Selection has been saved to Trilium.", noteId: "saved" });+ });});describe("screenshots", () => {diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex 0750288395..a48c746425 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -256,8 +256,9 @@ export default defineBackground(() => {return failedCount;}- async function saveSelection() {- const payload = await requestFromPage({name: 'trilium-save-selection'});+ /** Saves the selection on the page, or the one the popup already read and the user titled. */+ async function saveSelection(selection?: object) {+ const payload = selection ?? await requestFromPage({name: 'trilium-save-selection'});const failedImages = await postProcessImages(payload);@@ -461,6 +462,9 @@ export default defineBackground(() => {else if (request.name === 'save-whole-page') {return await saveWholePage(request.page);}+ else if (request.name === 'save-selection') {+ return await saveSelection(request.selection);+ }else if (request.name === 'save-link-with-note') {return await saveLinkWithNote(request.title, request.content);}diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex d5eccf7576..6a3cbe61dc 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -9,6 +9,7 @@ import Crop from "@boxicons/js/icons/Crop";import FileX from "@boxicons/js/icons/FileX";import Globe from "@boxicons/js/icons/Globe";import HelpCircle from "@boxicons/js/icons/HelpCircle";+import Highlight from "@boxicons/js/icons/Highlight";import Link from "@boxicons/js/icons/Link";import Lock from "@boxicons/js/icons/Lock";import RefreshCw from "@boxicons/js/icons/RefreshCw";@@ -36,12 +37,16 @@ type PopupMessage = {/** The keyboard shortcut of each command, by command name; unbound commands are absent. */type Shortcuts = Record<string, string>;-/** A page as the content script extracts it, its images referenced in `content` by `imageId`. */-interface ExtractedPage {+/** Content as the content script reads it from the page, its images referenced in `content` by `imageId`. */+interface SelectedContent {title: string;content: string;images: { imageId: string, src: string }[];pageUrl: string;+}++/** The readable page, as the content script extracts it. */+interface ExtractedPage extends SelectedContent {clipType: "page";labels: Record<string, string>;}@@ -49,6 +54,13 @@ interface ExtractedPage {/** The current page: its readable version, or why there is none. */type PageState = ExtractedPage | "unreadable" | "inaccessible";+/** What the active tab offers to save. */+interface TabContent {+ page: PageState;+ /** `null` when nothing is selected, or the page is out of reach. */+ selection: SelectedContent | null;+}+const PREVIEW_STYLE = `:root { color-scheme: light dark; }body { margin: 8px; font: 12px/1.5 system-ui, sans-serif; overflow-wrap: anywhere; }@@ -168,10 +180,10 @@ function CaptureActions({ disabled, shortcuts, onWriteNote }: {onWriteNote: () => void;}) {/** `undefined` while the page is read. */- const [ page, setPage ] = useState<PageState>();+ const [ tab, setTab ] = useState<TabContent>();useEffect(() => {- void extractPage().then(setPage);+ void readActiveTab().then(setTab);}, []);function sendAndClose(name: string) {@@ -180,19 +192,26 @@ function CaptureActions({ disabled, shortcuts, onWriteNote }: {}const disabledReason = disabled ? DISCONNECTED_TITLE : undefined;- const pageDisabledReason = disabledReason ?? (page === "inaccessible" ? UNREACHABLE_TITLE : undefined);+ const pageDisabledReason = disabledReason ?? (tab?.page === "inaccessible" ? UNREACHABLE_TITLE : undefined);let main: ComponentChildren;- if (page === "inaccessible") {+ if (tab?.page === "inaccessible") {main = (<EmptyState icon={Lock}>{"The extension cannot access this page.\nIf it is a regular web page, reload it."}</EmptyState>);- } else if (page === "unreadable") {+ } else if (tab?.page === "unreadable" && !tab.selection) {main = <EmptyState icon={FileX}>This page has no article to save.</EmptyState>;} else {- main = <PagePreview page={page} disabled={disabled} shortcut={shortcuts.saveWholePage} />;+ main = (+ <PagePreview+ article={typeof tab?.page === "object" ? tab.page : undefined}+ selection={tab?.selection ?? undefined}+ disabled={disabled}+ shortcuts={shortcuts}+ />+ );}return (@@ -259,29 +278,39 @@ function EmptyState({ icon, className, children }: {}/**- * The readable version of the current page, with its title editable, and the button that saves it.- * The page's HTML comes from an arbitrary website, so it is shown only in a sandboxed frame.+ * What the popup saves from the page, with its title editable, and the button that saves it: the+ * selection when there is one, otherwise the readable page, with a switch between the two when the+ * page has both. The page's HTML comes from an arbitrary website, so it is shown only in a sandboxed+ * frame.*/-function PagePreview({ page, disabled, shortcut }: {- /** `undefined` while the page is read. */- page: ExtractedPage | undefined;+function PagePreview({ article, selection, disabled, shortcuts }: {+ /** `undefined` while the page is read, or when it has no article. */+ article: ExtractedPage | undefined;+ selection: SelectedContent | undefined;disabled: boolean;- shortcut: string | undefined;+ shortcuts: Shortcuts;}) {- const [ title, setTitle ] = useState("");-- useEffect(() => setTitle(page?.title ?? ""), [ page ]);-- function save(extracted: ExtractedPage) {- void sendMessage({ name: "save-whole-page", page: { ...extracted, title: title.trim() || extracted.title } });+ const [ mode, setMode ] = useState<"selection" | "page">("selection");+ /** `undefined` until the user edits the title. */+ const [ title, setTitle ] = useState<string>();++ const clip = selection && (mode === "selection" || !article) ? selection : article;+ const isSelection = !!clip && clip === selection;+ const shownTitle = title ?? (article ?? selection)?.title ?? "";++ function save(content: SelectedContent | ExtractedPage) {+ const titled = { ...content, title: shownTitle.trim() || content.title };+ void sendMessage(isSelection+ ? { name: "save-selection", selection: titled }+ : { name: "save-whole-page", page: titled });window.close();}- const published = page?.labels.publishedDate;+ const published = clip && !isSelection ? article?.labels.publishedDate : undefined;return (<div className="page-preview">- {page && (+ {clip && (<div className="page-heading"><span className="page-icon"><Icon icon={Globe} /></span><div className="page-heading-text">@@ -290,31 +319,38 @@ function PagePreview({ page, disabled, shortcut }: {className="page-title"aria-label="Note title"placeholder="Note title"- value={title}+ value={shownTitle}onInput={(e) => setTitle(e.currentTarget.value)}/><div className="page-meta">- {new URL(page.pageUrl).hostname}{published && ` · Published ${published}`}+ {new URL(clip.pageUrl).hostname}{published && ` · Published ${published}`}</div></div></div>)}+ {article && selection && (+ <div className="clip-mode" role="group" aria-label="What to save">+ <button aria-pressed={mode === "selection"} onClick={() => setMode("selection")}>Selection</button>+ <button aria-pressed={mode === "page"} onClick={() => setMode("page")}>Whole page</button>+ </div>+ )}+<div className="page-body">- {page- ? <iframe className="page-content" title="Preview of the page" sandbox="" srcDoc={previewDocument(page)} />+ {clip+ ? <iframe className="page-content" title="Preview of the page" sandbox="" srcDoc={previewDocument(clip)} />: <div className="page-preview-placeholder">Reading the page…</div>}</div><buttonclassName="btn btn-primary primary-action"- disabled={disabled || !page}+ disabled={disabled || !clip}title={disabled ? DISCONNECTED_TITLE : undefined}- onClick={page ? () => save(page) : undefined}+ onClick={clip ? () => save(clip) : undefined}>- <Icon icon={Article} />- <span className="action-label">Save page to Trilium</span>- <Shortcut keys={shortcut} />+ <Icon icon={isSelection ? Highlight : Article} />+ <span className="action-label">{isSelection ? "Save selection" : "Save page to Trilium"}</span>+ <Shortcut keys={isSelection ? shortcuts.saveSelection : shortcuts.saveWholePage} /></button></div>);@@ -430,22 +466,40 @@ function describeStatus(status: TriliumSearchStatus | undefined) {}}+/** Asks the content script of the active tab for its readable page and its selection, together. */+async function readActiveTab(): Promise<TabContent> {+ const [ tab ] = await browser.tabs.query({ active: true, currentWindow: true });+ if (tab?.id === undefined) return { page: "inaccessible", selection: null };++ const [ page, selection ] = await Promise.all([ extractPage(tab.id), readSelection(tab.id) ]);+ return { page, selection };+}+/**- * Asks the content script of the active tab for its readable page, as it extracts it for saving.- * Returns `null` on pages where no content script runs (browser pages, extension stores) and when- * the page cannot be extracted.+ * The content script answers `undefined` when Readability cannot parse the page, and the message+ * fails where no content script runs.*/+async function extractPage(tabId: number): Promise<PageState> {+ try {+ return await browser.tabs.sendMessage(tabId, { name: "trilium-save-page" }) ?? "unreadable";+ } catch {+ return "inaccessible";+ }+}+/**- * Asks the content script of the active tab for its readable page. The script answers `undefined`- * when Readability cannot parse the page, and the message fails where no content script runs.+ * The selection on the page, or `null` when there is none. A click on the page leaves a collapsed+ * selection, which the content script still answers with, empty.*/-async function extractPage(): Promise<PageState> {+async function readSelection(tabId: number): Promise<SelectedContent | null> {try {- const [ tab ] = await browser.tabs.query({ active: true, currentWindow: true });- if (tab?.id === undefined) return "inaccessible";- return await browser.tabs.sendMessage(tab.id, { name: "trilium-save-page" }) ?? "unreadable";+ const selection: SelectedContent | undefined = await browser.tabs.sendMessage(tabId, { name: "trilium-save-selection" });+ if (!selection) return null;++ const text = new DOMParser().parseFromString(selection.content, "text/html").body.textContent;+ return text.trim() || selection.images.length ? selection : null;} catch {- return "inaccessible";+ return null;}}diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.cssindex d5a4774931..7dce482142 100644--- a/apps/web-clipper/entrypoints/popup/popup.css+++ b/apps/web-clipper/entrypoints/popup/popup.css@@ -100,6 +100,35 @@ body {text-overflow: ellipsis;}+ .clip-mode {+ display: flex;+ gap: 2px;+ padding: 2px;+ border-radius: 8px;+ background: var(--input-background-color);++ button {+ flex: 1;+ padding: 3px 8px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--muted-text-color);+ font-size: 0.9em;+ cursor: pointer;++ &:hover {+ color: var(--main-text-color);+ }++ &[aria-pressed="true"] {+ background: var(--cmd-button-background-color);+ box-shadow: 1px 1px 1px var(--cmd-button-shadow-color);+ color: var(--cmd-button-text-color);+ }+ }+ }+.page-body {position: relative;overflow: hidden;@@ -159,6 +188,9 @@ body {.action-label {flex-grow: 1;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;text-align: start;}}diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex ae99a2710e..081a037329 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -28,13 +28,23 @@ const PAGE = {labels: { publishedDate: "2024-05-01" }};const tabsQuery = vi.fn(async (): Promise<{ id?: number }[]> => [ { id: 7 } ]);-const tabsSendMessage = vi.fn(async (_tabId: number, _message: object): Promise<unknown> => PAGE);+const SELECTION = {+ title: "Page title",+ content: `<p>A quote</p><img src="i2">`,+ images: [ { imageId: "i2", src: "https://example.com/c.png" } ],+ pageUrl: "https://example.com/post?id=1#part"+};+/** What the content script answers to `trilium-save-selection`; nothing is selected unless a test says so. */+let selection: unknown;+const tabsSendMessage = vi.fn(async (_tabId: number, message: { name: string }): Promise<unknown> =>+ message.name === "trilium-save-page" ? PAGE : selection);const closeWindow = vi.fn();let container: HTMLElement;describe("popup", () => {beforeEach(async () => {fakeBrowser.reset();+ selection = undefined;Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });Object.assign(fakeBrowser.commands, { getAll: getAllCommands });Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });@@ -242,7 +252,9 @@ describe("popup", () => {});it("keeps only the actions that need no access to a page out of reach", async () => {- tabsSendMessage.mockRejectedValueOnce(new Error("Could not establish connection."));+ tabsSendMessage+ .mockRejectedValueOnce(new Error("Could not establish connection."))+ .mockRejectedValueOnce(new Error("Could not establish connection."));await rerender();expect(unavailable()).toBe("The extension cannot access this page.\nIf it is a regular web page, reload it."@@ -256,7 +268,52 @@ describe("popup", () => {tabsQuery.mockResolvedValueOnce([ {} ]);await rerender();expect(unavailable()).toContain("The extension cannot access this page.");- expect(tabsSendMessage).toHaveBeenCalledTimes(2);+ expect(tabsSendMessage).toHaveBeenCalledTimes(4);+ });++ it("previews the selection first, and switches to the whole page", async () => {+ selection = SELECTION;+ await rerender();+ expect(tabsSendMessage).toHaveBeenCalledWith(7, { name: "trilium-save-selection" });+ expect(modes()).toEqual([ [ "Selection", "true" ], [ "Whole page", "false" ] ]);+ expect(frameDocument()).toBe(previewDocument(SELECTION));+ expect(shortcutOf("Save selection").keys).toEqual([ "Ctrl", "Shift", "S" ]);+ expect(container.querySelector(".page-meta")?.textContent).toBe("example.com");++ await click("Whole page");+ expect(modes()).toEqual([ [ "Selection", "false" ], [ "Whole page", "true" ] ]);+ expect(frameDocument()).toBe(previewDocument(PAGE));+ expect(container.querySelector(".page-meta")?.textContent).toBe("example.com · Published 2024-05-01");+ await click("Save page to Trilium");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-whole-page", page: PAGE });++ await click("Selection");+ await type(".page-title", " Quote ");+ await click("Save selection");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-selection", selection: { ...SELECTION, title: "Quote" } });+ expect(closeWindow).toHaveBeenCalledTimes(2);+ });++ it("saves the selection of a page that has no article, and ignores an empty one", async () => {+ selection = SELECTION;+ tabsSendMessage.mockResolvedValueOnce(undefined);+ await rerender();+ expect(container.querySelector(".no-items")).toBeNull();+ expect(container.querySelector(".clip-mode")).toBeNull();+ expect(frameDocument()).toBe(previewDocument(SELECTION));+ expect(container.querySelector<HTMLInputElement>(".page-title")?.value).toBe("Page title");+ await click("Save selection");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-selection", selection: SELECTION });++ selection = { ...SELECTION, content: " <p> </p>", images: [] };+ await rerender();+ expect(container.querySelector(".clip-mode")).toBeNull();+ expect(frameDocument()).toBe(previewDocument(PAGE));++ selection = { ...SELECTION, content: `<img src="i2">` };+ await rerender();+ expect(modes()).toHaveLength(2);+ expect(frameDocument()).toBe(previewDocument(selection as typeof SELECTION));});it("tells the user when the background script cannot be reached", async () => {@@ -501,6 +558,18 @@ function toolbar() {});}+/** The clip mode switch's options, each with whether it is the current one. */+function modes() {+ return [ ...container.querySelectorAll(".clip-mode button") ]+ .map((option) => [ option.textContent, option.getAttribute("aria-pressed") ]);+}++function frameDocument() {+ const frame = container.querySelector(".page-body iframe.page-content");+ expect(frame).not.toBeNull();+ return frame?.getAttribute("srcdoc");+}+/** The class names of the preview card's parts, in order. */function cardParts() {const card = container.querySelector(".page-preview");diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 25074a541d..99ce97792c 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -30,6 +30,7 @@ The extension is available from the official browser web stores:Clicking the extension's button in the browser toolbar opens its popup:* The popup reads the current page as an article and shows a preview of what will be saved: the note's title, which can be edited before saving, the website and the publication date (when the page states one), and the article's text and images. _Save page to Trilium_ saves it. When the page has no article (Readability cannot find one), the popup says so in place of the preview, and the other actions still work. Pages the extension cannot access (the browser's own pages, the extension stores, and pages that were open before the extension was installed until they are reloaded) cannot be saved or captured, so only _Note_ and _Tabs_ remain available there. The keyboard shortcut and the context menu still save the page right away, without a preview.+* If text is selected on the page, the preview shows the selection instead, and _Save selection_ saves it into the note of that page's clippings, as the context menu does. When the page also has an article, a switch above the preview chooses between _Selection_ and _Whole page_. A selection can be saved even on a page that has no article.* Below the preview, a row of buttons offers the other actions: _Crop_ (a screenshot of an area you select), _Screenshot_ (of the visible part of the page), _Note_ (a link with a note) and _Tabs_ (saves the links of every tab in the current window as a list). Hovering over a button shows its full name and, if it has one, its keyboard shortcut.* _Note_ opens a small editor in place of the actions. The first sentence or line of the text becomes the note's title, unless _Keep page title as note title_ is checked. Press _Save_ or <kbd>Ctrl</kbd>+<kbd>Enter</kbd> to save it, or the back arrow to return to the actions.* If the current page was already clipped, a notice at the top offers to open the note in Trilium.