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(clipper): report every save from the popup in the popup
Elian Doran760d5d0b6656
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 8732c874ea..2418dc2c34 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@@ -59,10 +59,8 @@<li><em>PDF</em>, when the tab shows a PDF in the browser's viewer: <em>Save PDF to Trilium</em> downloadsthe PDF and saves it as a file note, which Trilium opens in its <aclass="reference-link" href="#root/_help_XJGJrpu7F9sh">PDFs</a> viewer.- The popup stays open while the PDF downloads, then says that it was saved,- with a link to open the note, or why it was not. Only the title and the- description can be edited, since a file note has no text of its own for- your note. The page's address is saved in the note's <code>#pageUrl</code> label+ Only the title and the description can be edited, since a file note has+ no text of its own for your note. The page's address is saved in the note's <code>#pageUrl</code> labeland the PDF's file name in <code>#originalFileName</code>. Saving a PDFneeds Trilium v0.107.0 or later.</li><li><em>Bookmark</em>, always: there is no preview, and <em>Save bookmark</em> saves@@ -122,6 +120,18 @@longer than 100 screens is cut off there, and the message after savingsays so.</p></li>+ <li>+ <p>The popup stays open while Trilium saves, which can take a few seconds+ for a long page or a large PDF, and the other actions wait until it is+ done. The bar at the top of the popup then says, in green, that the clipping+ was saved (in place of the notice that the page was already clipped), with <em>Open note</em> to+ open it in Trilium (and, after <em>Tabs</em>, <em>Close saved tabs</em>),+ or, in red, why it could not be saved. The same clipping cannot be saved+ twice by accident: the save button stays disabled until another mode is+ chosen. <em>Crop</em> is the exception: the popup closes so that an area+ of the page can be selected, and the notification on the page reports the+ outcome.</p>+ </li><li><p>If the current page was already clipped, a notice at the top offers toopen the note in Trilium.</p>@@ -214,9 +224,11 @@and the code are used only once, to obtain a token for the extension, andare not stored.</p><h3>When a clipping fails</h3>-<p>After each clipping, a notification in the corner of the page confirms- that it was saved, with a link to open the new note in Trilium. If the- clipping could not be saved, the notification says why instead:</p>+<p>After each clipping made with a keyboard shortcut or the context menu,+ a notification in the corner of the page confirms that it was saved, with+ a link to open the new note in Trilium. A clipping made from the popup+ reports in the popup instead, unless the popup was closed before it was+ saved. If the clipping could not be saved, the message says why instead:</p><ul><li>Trilium was not found: start the desktop application, or check the serveraddress and token in the extension's options.</li>@@ -240,8 +252,8 @@them.</p><p>The notification is shown on the page itself, so it does not appear onpages where extensions cannot run (such as the browser's own settings pages,- the extension stores and Firefox's PDF viewer). A PDF saved from the popup- reports the outcome in the popup instead.</p>+ the extension stores and Firefox's PDF viewer). A clipping saved from the+ popup on such a page still reports in the popup.</p><h2>Testing development versions</h2><p>Development versions are version pre-release versions, generally meantfor testing purposes. These are not available in the Google or Firefoxdiff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 98d37fc8de..976fc12eac 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -69,6 +69,7 @@ const GENERIC_FAILURE_TOAST = { name: "toast", message: expect.any(String), notelet onCommand: (command: string) => Promise<void>;let onContextMenuClicked: (info: ContextMenuClick) => Promise<void>;+let onConnect: (port: FakePort) => void;let tabs: Tab[];let tabMessageHandler: (message: { name: string }) => unknown;const tabsSendMessage = vi.fn(@@ -126,7 +127,15 @@ describe("background", () => {getZoom: async () => 1.5,captureVisibleTab: async () => PNG});- Object.assign(fakeBrowser.runtime, { getContexts, sendMessage: runtimeSendMessage });+ Object.assign(fakeBrowser.runtime, {+ getContexts,+ sendMessage: runtimeSendMessage,+ onConnect: {+ addListener: (listener: typeof onConnect) => {+ onConnect = listener;+ }+ }+ });Object.assign(fakeBrowser, { offscreen: { createDocument }, scripting: { executeScript } });background.main();@@ -438,7 +447,7 @@ describe("background", () => {const pdfUrl = "https://example.com/files/report";await expect(sendRuntimeMessage({ name: "save-pdf", url: pdfUrl, title: "Edited", description: "Summary" }))- .resolves.toEqual({ noteId: "saved" });+ .resolves.toEqual({ noteId: "saved", message: "PDF has been saved to Trilium." });expect(fetchMock).toHaveBeenCalledWith(pdfUrl, { credentials: "include" });expect(lastPayload()).toEqual({@@ -1011,7 +1020,9 @@ describe("background", () => {content});- await expect(saveWithTitle(" ", "Note")).resolves.toBe(true);+ await expect(saveWithTitle(" ", "Note")).resolves.toEqual({+ noteId: "saved", message: "Link with note has been saved to Trilium."+ });expect(facade.callService).toHaveBeenLastCalledWith("POST", "notes", {title: "Active page",content: "Note",@@ -1021,7 +1032,7 @@ describe("background", () => {expect(await lastToast()).toMatchObject({ noteId: "saved" });facade.callService.mockRejectedValue(TRILIUM_FAILURE);- await expect(saveWithTitle("Mine")).resolves.toBeUndefined();+ await expect(saveWithTitle("Mine")).resolves.toEqual({ error: "Trilium was not found." });expect(lastPayload()).toMatchObject({ title: "Mine" });tabs = [ { id: 7, url: "https://example.com/untitled" } ];@@ -1029,6 +1040,45 @@ describe("background", () => {expect(lastPayload()).toMatchObject({ title: "" });});+ it("answers the popup with the outcome of each save, toasting only once it is closed", async () => {+ const popup = connect("popup");+ connect("other");+ const page = { title: "Article", content: "<p>Body</p>", images: [], clipType: "page" };+ const selectionClip = { title: "Quote", content: "<p>Quote</p>", images: [] };+ tabs = [ ACTIVE_TAB, { id: 8, title: "Other", url: "https://example.org/" } ];++ await expect(sendRuntimeMessage({ name: "save-whole-page", page })).resolves.toEqual({+ noteId: "saved", message: "Page has been saved to Trilium."+ });+ await expect(sendRuntimeMessage({ name: "save-selection", selection: selectionClip })).resolves.toEqual({+ noteId: "saved", message: "Selection has been saved to Trilium."+ });+ await expect(sendRuntimeMessage({ name: "save-whole-screenshot" })).resolves.toEqual({+ noteId: "saved", message: "Screenshot has been saved to Trilium."+ });+ await expect(sendRuntimeMessage({ name: "save-tabs" })).resolves.toEqual({+ noteId: "saved", message: "2 links have been saved to Trilium.", tabIds: [ 7, 8 ]+ });+ facade.callService.mockRejectedValueOnce(TRILIUM_FAILURE);+ await expect(sendRuntimeMessage({ name: "save-whole-page", page })).resolves.toEqual({+ error: "Trilium was not found."+ });+ expect(await lastToast()).toBeUndefined();++ popup.disconnect();+ await expect(sendRuntimeMessage({ name: "save-whole-page", page })).resolves.toMatchObject({ noteId: "saved" });+ expect(await lastToast()).toMatchObject({ message: "Page has been saved to Trilium.", noteId: "saved" });+ facade.callService.mockRejectedValueOnce(TRILIUM_FAILURE);+ await sendRuntimeMessage({ name: "save-whole-page", page });+ expect(await lastToast()).toMatchObject(FAILURE_TOAST);+ });++ it("answers nothing for a crop the user cancels", async () => {+ tabMessageHandler = () => ({ rect: null });+ await expect(sendRuntimeMessage({ name: "save-cropped-screenshot" })).resolves.toBeUndefined();+ expect(facade.callService).not.toHaveBeenCalled();+ });+it("labels a bookmark with the description the popup sends", async () => {const save = (description?: string) => sendRuntimeMessage({ name: "save-link-with-note", title: "T", content: "", description });@@ -1089,6 +1139,20 @@ describe("background", () => {});});+type FakePort = { name: string, onDisconnect: { addListener(listener: () => void): void }, disconnect(): void };++/** Connects a page of the extension to the background, as the popup does while it is open. */+function connect(name: string) {+ let onDisconnect = () => {};+ const port: FakePort = {+ name,+ onDisconnect: { addListener: (listener) => onDisconnect = listener },+ disconnect: () => onDisconnect()+ };+ onConnect(port);+ return port;+}+async function sendRuntimeMessage(message: object) {const [ result ] = await fakeBrowser.runtime.onMessage.trigger(message, {}, () => {});return result;diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex c9b0dada61..457162550f 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -1,7 +1,7 @@import {type ScreenshotSlice, ScreenshotStitcher, type StitchMessage, type StitchRequest} from "@/screenshot";-import { extractPage, isPdfTab, randomString, type Rect } from "@/utils";+import { extractPage, isPdfTab, randomString, type Rect, type SaveOutcome, type Saved } from "@/utils";import setupContextMenu from "./context_menu";import TriliumServerFacade, { TriliumError } from "./trilium_server_facade";@@ -63,27 +63,35 @@ type ContextMenuInfo = Browser.contextMenus.OnClickData & { linkText?: string };export default defineBackground(() => {const triliumServerFacade = new TriliumServerFacade();+ /** How many popups are open: each keeps a port named "popup" connected while it is. */+ let openPopups = 0;++ browser.runtime.onConnect.addListener((port) => {+ if (port.name !== "popup") return;+ openPopups++;+ port.onDisconnect.addListener(() => openPopups--);+ });// Keyboard shortcutsbrowser.commands.onCommand.addListener((command) => showFailures(async () => {switch (command) {case "saveSelection":- await saveSelection();+ notify(await saveSelection());break;case "saveWholePage":- await saveWholePage();+ notify(await saveWholePage());break;case "saveTabs":- await saveTabs();+ notify(await saveTabs());break;case "saveCroppedScreenshot": {const activeTab = await getActiveTab();- await saveCroppedScreenshot(activeTab.url);+ notify(await saveCroppedScreenshot(activeTab.url));break;}case "saveFullPageScreenshot": {const activeTab = await getActiveTab();- await saveFullPageScreenshot(activeTab.url);+ notify(await saveFullPageScreenshot(activeTab.url));break;}default:@@ -217,7 +225,7 @@ export default defineBackground(() => {async function saveFullPageScreenshot(pageUrl: string | null | undefined) {const { parts, cutOff } = await takeFullPageScreenshot();- await saveScreenshot(parts, pageUrl, cutOff+ return await saveScreenshot(parts, pageUrl, cutOff? "Screenshot has been saved to Trilium, but the page was too long to capture in full.": undefined);}@@ -318,19 +326,36 @@ export default defineBackground(() => {});}+ function notify(saved: Saved | undefined) {+ if (saved) toast(saved.message, saved.noteId, saved.tabIds);+ }+/** Runs a user action, and reports its failure in a toast instead of rejecting. */async function showFailures<T>(action: () => Promise<T>) {try {return await action();} catch (e) {- reportFailure(e);+ console.error("Web clipper action failed", e);+ toast(failureMessage(e));return undefined;}}- function reportFailure(error: unknown) {- console.error("Web clipper action failed", error);- toast(failureMessage(error));+ /**+ * Runs a save the popup asked for, and answers it with the outcome, which the popup shows. A+ * popup closed before the save ends (as it is to crop a screenshot) shows nothing, so the page+ * shows a toast instead.+ */+ async function saveForPopup(save: () => Promise<Saved | undefined>): Promise<SaveOutcome | undefined> {+ try {+ const saved = await save();+ if (!openPopups) notify(saved);+ return saved;+ } catch (e) {+ console.error("Web clipper action failed", e);+ if (!openPopups) toast(failureMessage(e));+ return { error: failureMessage(e) };+ }}async function requestFromPage(message: BackgroundMessage) {@@ -413,14 +438,14 @@ export default defineBackground(() => {}/** Saves the selection on the page, or the one the popup already read and the user titled. */- async function saveSelection(selection?: object) {+ async function saveSelection(selection?: object): Promise<Saved> {const payload = selection ?? await requestFromPage({name: 'trilium-save-selection'});const failedImages = await postProcessImages(payload);const resp = await triliumServerFacade.callService('POST', 'clippings', payload);- toast(savedMessage("Selection", failedImages), resp.noteId);+ return { noteId: resp.noteId, message: savedMessage("Selection", failedImages) };}/** A clipping of the images, one after another. */@@ -458,42 +483,41 @@ export default defineBackground(() => {const { rect, devicePixelRatio } = await requestFromPage({name: 'trilium-get-rectangle-for-screenshot'});- if (!rect) return;+ if (!rect) return undefined;- await saveScreenshot([ await takeCroppedScreenshot(rect, devicePixelRatio) ], pageUrl);+ return await saveScreenshot([ await takeCroppedScreenshot(rect, devicePixelRatio) ], pageUrl);}async function saveScreenshot(srcs: string[],pageUrl: string | null | undefined,message = "Screenshot has been saved to Trilium."- ) {+ ): Promise<Saved> {const { payload } = await getImagePayload(srcs, pageUrl);const resp = await triliumServerFacade.callService("POST", "clippings", payload);- toast(message, resp.noteId);+ return { noteId: resp.noteId, message };}- async function saveImage(srcUrl: string, pageUrl: string | null | undefined) {+ async function saveImage(srcUrl: string, pageUrl: string | null | undefined): Promise<Saved> {const { payload, failedImages } = await getImagePayload([ srcUrl ], pageUrl);const resp = await triliumServerFacade.callService("POST", "clippings", payload);- toast(savedMessage("Image", failedImages), resp.noteId);+ return { noteId: resp.noteId, message: savedMessage("Image", failedImages) };}/*** Saves the page the popup already extracted and the user edited, or else the article, or the* whole page when it has none.*/- async function saveWholePage(page?: object) {+ async function saveWholePage(page?: object): Promise<Saved> {let payload = page;if (!payload) {const activeTab = await getActiveTab();if (activeTab.url && await isPdfTab(activeTab)) {- await savePdf(activeTab.url, activeTab.title);- return;+ return await savePdf(activeTab.url, activeTab.title);}payload = await readPage(activeTab);}@@ -502,14 +526,14 @@ export default defineBackground(() => {const resp = await triliumServerFacade.callService('POST', 'notes', payload);- toast(savedMessage("Page", failedImages), resp.noteId);+ return { noteId: resp.noteId, message: savedMessage("Page", failedImages) };}/*** Downloads the PDF at `url`, as the browser does, with the website's cookies, and saves it as a* file note. Trilium has the route for it since protocol version 1.1.*/- async function savePdf(url: string, title: string | undefined, description?: string) {+ async function savePdf(url: string, title: string | undefined, description?: string): Promise<Saved> {await triliumServerFacade.requireMinorVersion(1, "Saving a PDF");const { dataUrl, fileName } = await downloadPdf(url);@@ -521,8 +545,7 @@ export default defineBackground(() => {...(description && { labels: { pageDescription: description } })});- toast(savedMessage("PDF", 0), resp.noteId);- return resp.noteId as string;+ return { noteId: resp.noteId, message: savedMessage("PDF", 0) };}async function downloadPdf(url: string) {@@ -562,7 +585,7 @@ export default defineBackground(() => {throw new Error("Trilium found nothing to save on this page.");}- async function saveLinkWithNote(title: string, content: string, description?: string) {+ async function saveLinkWithNote(title: string, content: string, description?: string): Promise<Saved> {const activeTab = await getActiveTab();if (!title.trim()) {@@ -577,9 +600,7 @@ export default defineBackground(() => {...(description && { labels: { pageDescription: description } })});- toast("Link with note has been saved to Trilium.", resp.noteId);-- return true;+ return { noteId: resp.noteId, message: "Link with note has been saved to Trilium." };}async function getTabsPayload(tabs: (Browser.tabs.Tab & { url: string })[]) {@@ -627,7 +648,7 @@ export default defineBackground(() => {}}- async function saveTabs() {+ async function saveTabs(): Promise<Saved> {const tabs = (await getWindowTabs()).filter((tab): tab is Browser.tabs.Tab & { url: string } => !!tab.url);@@ -636,25 +657,25 @@ export default defineBackground(() => {const resp = await triliumServerFacade.callService('POST', 'notes', payload);const tabIds = tabs.map(tab => tab.id).filter(id => id !== undefined) as number[];- toast(`${tabs.length} links have been saved to Trilium.`, resp.noteId, tabIds);+ return { noteId: resp.noteId, message: `${tabs.length} links have been saved to Trilium.`, tabIds };}browser.contextMenus.onClicked.addListener((info: ContextMenuInfo) => showFailures(async () => {if (info.menuItemId === 'trilium-save-selection') {- await saveSelection();+ notify(await saveSelection());}else if (info.menuItemId === 'trilium-save-cropped-screenshot') {- await saveCroppedScreenshot(info.pageUrl);+ notify(await saveCroppedScreenshot(info.pageUrl));}else if (info.menuItemId === 'trilium-save-whole-screenshot') {- await saveScreenshot([ await takeWholeScreenshot() ], info.pageUrl);+ notify(await saveScreenshot([ await takeWholeScreenshot() ], info.pageUrl));}else if (info.menuItemId === 'trilium-save-full-page-screenshot') {- await saveFullPageScreenshot(info.pageUrl);+ notify(await saveFullPageScreenshot(info.pageUrl));}else if (info.menuItemId === 'trilium-save-image') {if (!info.srcUrl) return;- await saveImage(info.srcUrl, info.pageUrl);+ notify(await saveImage(info.srcUrl, info.pageUrl));}else if (info.menuItemId === 'trilium-save-link') {if (!info.linkUrl) return;@@ -669,10 +690,10 @@ export default defineBackground(() => {pageUrl: info.pageUrl});- toast("Link has been saved to Trilium.", resp.noteId);+ notify({ noteId: resp.noteId, message: "Link has been saved to Trilium." });}else if (info.menuItemId === 'trilium-save-page') {- await saveWholePage();+ notify(await saveWholePage());}else {console.log("Unrecognized menuItemId", info.menuItemId);@@ -707,40 +728,31 @@ export default defineBackground(() => {return await browser.tabs.remove(request.tabIds);}else if (request.name === 'save-cropped-screenshot') {- const activeTab = await getActiveTab();-- return await saveCroppedScreenshot(activeTab.url);+ return await saveForPopup(async () => saveCroppedScreenshot((await getActiveTab()).url));}else if (request.name === 'save-whole-screenshot') {- const activeTab = await getActiveTab();-- return await saveScreenshot([ await takeWholeScreenshot() ], activeTab.url);+ return await saveForPopup(async () => {+ const activeTab = await getActiveTab();+ return saveScreenshot([ await takeWholeScreenshot() ], activeTab.url);+ });}else if (request.name === 'save-full-page-screenshot') {- const activeTab = await getActiveTab();-- return await saveFullPageScreenshot(activeTab.url);+ return await saveForPopup(async () => saveFullPageScreenshot((await getActiveTab()).url));}else if (request.name === 'save-whole-page') {- return await saveWholePage(request.page);+ return await saveForPopup(() => saveWholePage(request.page));}else if (request.name === 'save-pdf') {- // The popup stays open while the PDF downloads, and shows the outcome.- try {- return { noteId: await savePdf(request.url, request.title, request.description) };- } catch (e) {- reportFailure(e);- return { error: failureMessage(e) };- }+ return await saveForPopup(() => savePdf(request.url, request.title, request.description));}else if (request.name === 'save-selection') {- return await saveSelection(request.selection);+ return await saveForPopup(() => saveSelection(request.selection));}else if (request.name === 'save-link-with-note') {- return await saveLinkWithNote(request.title, request.content, request.description);+ return await saveForPopup(() => saveLinkWithNote(request.title, request.content, request.description));}else if (request.name === 'save-tabs') {- return await saveTabs();+ return await saveForPopup(saveTabs);}else if (request.name === 'trigger-trilium-search') {triliumServerFacade.triggerSearchForTrilium();diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex 92750ac8d2..536efbcf66 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -28,13 +28,14 @@ import type { ComponentChildren } from "preact";import { Fragment, render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";-import { extractPage, isPdfTab, type PageVariant, type ReadablePage } from "@/utils";+import { extractPage, isPdfTab, type PageVariant, type ReadablePage, type SaveOutcome } from "@/utils";import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background/trilium_server_facade";const HELP_URL = "https://docs.triliumnotes.org/user-guide/setup/web-clipper";const DISCONNECTED_TITLE = "This action can't be performed without active connection to Trilium.";const UNREACHABLE_TITLE = "This action is not available on this page.";+const SAVING_TITLE = "Trilium is saving the last clipping.";type PopupMessage = {name: "trilium-search-status";@@ -83,8 +84,14 @@ interface TabContent {*/type ClipMode = "selection" | "page" | "pdf" | "note";-/** How saving the PDF went, once the user saved it: the note it made, or why it failed. */-type PdfSave = { status: "saving" } | { status: "saved", noteId: string } | { status: "failed", message: string };+/**+ * A save the popup asked for, in progress or as it went. `mode` is the card's mode when the card+ * saved, which keeps the card from saving the same clip twice.+ */+type SaveState = ({ status: "saving" } | SaveOutcome) & { mode?: ClipMode };++/** Sends a save to the background, and the card's mode when the card saves. */+type SaveHandler = (message: object, mode?: ClipMode) => void;/** What the user has chosen and typed in the card, kept by `Popup` so a reconnection does not lose it. */interface Draft {@@ -168,6 +175,7 @@ export function Popup() {const [ clippedNoteId, setClippedNoteId ] = useState<string | null>(null);const [ shortcuts, setShortcuts ] = useState<Shortcuts>({});const [ draft, setDraft ] = useState<Draft>({ text: "" });+ const [ saveState, setSaveState ] = useState<SaveState>();useEffect(() => {function onMessage(message: PopupMessage) {@@ -184,12 +192,24 @@ export function Popup() {}browser.runtime.onMessage.addListener(onMessage);+ // Tells the background that the popup is open, so it leaves the outcome of a save to it.+ const port = browser.runtime.connect({ name: "popup" });void sendMessage({ name: "send-trilium-search-status" });void browser.commands.getAll().then((commands) => setShortcuts(shortcutsByCommand(commands)));- return () => browser.runtime.onMessage.removeListener(onMessage);+ return () => {+ browser.runtime.onMessage.removeListener(onMessage);+ port.disconnect();+ };}, []);+ /** Keeps the popup open while Trilium saves, and shows how it went. */+ async function save(message: object, mode?: ClipMode) {+ setSaveState({ status: "saving", mode });+ const outcome = await sendMessage(message) as SaveOutcome | undefined;+ setSaveState({ ...outcome ?? { error: "Saving to Trilium failed." }, mode });+ }+const status = describeStatus(searchStatus);const isMismatch = searchStatus?.status === "version-mismatch";@@ -203,15 +223,18 @@ export function Popup() {shortcuts={shortcuts}draft={draft}onDraftChange={setDraft}+ saveState={saveState}+ onSave={(message, mode) => void save(message, mode)}/>);}return (<div className="popup">- {(clippedNoteId || isMismatch) && (+ {(saveState || clippedNoteId || isMismatch) && (<div className="notices">- {clippedNoteId && (+ {saveState && <SaveStatus state={saveState} />}+ {!saveState && clippedNoteId && (<div className="callout callout-info already-visited"><span>Web page already clipped.</span><a@@ -261,11 +284,13 @@ export function Popup() {);}-function CaptureActions({ disabled, shortcuts, draft, onDraftChange }: {+function CaptureActions({ disabled, shortcuts, draft, onDraftChange, saveState, onSave: save }: {disabled: boolean;shortcuts: Shortcuts;draft: Draft;onDraftChange: (draft: Draft) => void;+ saveState: SaveState | undefined;+ onSave: SaveHandler;}) {/** `undefined` while the page is read. */const [ tab, setTab ] = useState<TabContent>();@@ -274,12 +299,14 @@ function CaptureActions({ disabled, shortcuts, draft, onDraftChange }: {void readActiveTab().then(setTab);}, []);- function sendAndClose(name: string) {- void sendMessage({ name });+ /** Cropping happens on the page, which the popup would cover, so it closes. */+ function cropScreenshot() {+ void sendMessage({ name: "save-cropped-screenshot" });window.close();}- const disabledReason = disabled ? DISCONNECTED_TITLE : undefined;+ const saving = saveState && "status" in saveState;+ const disabledReason = disabled ? DISCONNECTED_TITLE : saving ? SAVING_TITLE : undefined;const pageDisabledReason = disabledReason ?? (tab?.page === "inaccessible" ? UNREACHABLE_TITLE : undefined);let main: ComponentChildren;@@ -290,7 +317,12 @@ function CaptureActions({ disabled, shortcuts, draft, onDraftChange }: {</EmptyState>);} else {- main = <PagePreview tab={tab} disabled={disabled} shortcuts={shortcuts} draft={draft} onDraftChange={onDraftChange} />;+ main = (+ <PagePreview+ tab={tab} disabled={disabled} shortcuts={shortcuts} draft={draft} onDraftChange={onDraftChange}+ saveState={saveState} onSave={save}+ />+ );}return (@@ -301,28 +333,66 @@ function CaptureActions({ disabled, shortcuts, draft, onDraftChange }: {<ToolbarActionicon={Crop} label="Crop" name="Crop screenshot"shortcut={shortcuts.saveCroppedScreenshot} disabledReason={pageDisabledReason}- onClick={() => sendAndClose("save-cropped-screenshot")}+ onClick={cropScreenshot}/><ToolbarActionicon={Screenshot} label="Screenshot" name="Visible area screenshot"disabledReason={pageDisabledReason}- onClick={() => sendAndClose("save-whole-screenshot")}+ onClick={() => save({ name: "save-whole-screenshot" })}/><ToolbarActionicon={ImagePortrait} label="Full page" name="Full page screenshot"shortcut={shortcuts.saveFullPageScreenshot} disabledReason={pageDisabledReason}- onClick={() => sendAndClose("save-full-page-screenshot")}+ onClick={() => save({ name: "save-full-page-screenshot" })}/><ToolbarActionicon={Tabs} label="Tabs" name="All tabs in window"shortcut={shortcuts.saveTabs} disabledReason={disabledReason}- onClick={() => sendMessage({ name: "save-tabs" })}+ onClick={() => save({ name: "save-tabs" })}/></div></div>);}+/**+ * The save in progress, or how the last one went, with links to the note and the saved tabs. It+ * takes the place of the notice that the page was already clipped.+ */+function SaveStatus({ state }: { state: SaveState }) {+ if ("status" in state) {+ return <div className="callout callout-info save-status">Saving to Trilium…</div>;+ }+ if ("error" in state) {+ return <div className="callout callout-error save-status">{state.error}</div>;+ }++ const { noteId, tabIds } = state;+ return (+ <div className="callout callout-success save-status">+ <span>{state.message}</span>+ <span className="save-status-links">+ <ActionLink message={{ name: "openNoteInTrilium", noteId }}>Open note</ActionLink>+ {tabIds && <ActionLink message={{ name: "closeTabs", tabIds }}>Close saved tabs</ActionLink>}+ </span>+ </div>+ );+}++/** A link that sends `message` to the background, and closes the popup. */+function ActionLink({ message, children }: { message: object, children: ComponentChildren }) {+ return (+ <a+ href="#"+ onClick={(e) => {+ e.preventDefault();+ void sendMessage(message);+ window.close();+ }}+ >{children}</a>+ );+}+/** A secondary action: an icon over a short label, its full name and shortcut in the tooltip. */function ToolbarAction({ icon, label, name, shortcut, disabledReason, onClick }: {icon: IconDefinition;@@ -363,19 +433,20 @@ function EmptyState({ icon, className, children }: {* page offers. The page's HTML comes from an arbitrary website, so it is shown only in a sandboxed* frame.*/-function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {+function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange, saveState, onSave: save }: {/** `undefined` while the page is read. */tab: TabContent | undefined;disabled: boolean;shortcuts: Shortcuts;draft: Draft;onDraftChange: (draft: Draft) => void;+ saveState: SaveState | undefined;+ onSave: SaveHandler;}) {const { mode: chosenMode, variant: chosenVariant, title, description, author, text } = draft;const textAreaRef = useRef<HTMLTextAreaElement>(null);/** The readings of the page made after the popup opened, when the user switched to them. */const [ laterReadings, setLaterReadings ] = useState<Partial<PageReadings>>({});- const [ pdfSave, setPdfSave ] = useState<PdfSave>();const page = typeof tab?.page === "object" ? { ...tab.page, ...laterReadings } : undefined;const variant = chosenVariant && page?.[chosenVariant] !== null ? chosenVariant : page?.article ? "article" : "wholePage";@@ -406,16 +477,14 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {textAreaRef.current?.focus();}, [ mode ]);- /** Keeps the popup open when the note could not be saved, so its text is not lost. */- async function saveNote() {+ function saveNote() {const content = text.trim();- const result = await sendMessage({+ save({name: "save-link-with-note",title: shownTitle.trim(),content: content ? textToHtml(content) : "",...(savedDescription && { description: savedDescription })- });- if (result) window.close();+ }, mode);}function saveClip(content: SelectedContent) {@@ -429,41 +498,30 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {content: withNote(content.content, text),...(labels && { labels })};- void sendMessage(mode === "selection"+ save(mode === "selection"? { name: "save-selection", selection: titled }- : { name: "save-whole-page", page: titled });- window.close();+ : { name: "save-whole-page", page: titled }, mode);}- /** Keeps the popup open while the PDF downloads, which can take a while, and shows the outcome. */- async function savePdf() {- setPdfSave({ status: "saving" });- const answer = await sendMessage({+ function savePdf() {+ save({name: "save-pdf",url: tab?.url,title: shownTitle.trim(),...(savedDescription && { description: savedDescription })- }) as { noteId?: string, error?: string } | undefined;- setPdfSave(answer?.noteId- ? { status: "saved", noteId: answer.noteId }- : { status: "failed", message: answer?.error ?? "Saving to Trilium failed." });- }-- function openSavedNote(noteId: string) {- void sendMessage({ name: "openNoteInTrilium", noteId });- window.close();+ }, mode);}+ const busy = saveState && ("status" in saveState || ("noteId" in saveState && saveState.mode === mode));let onSave: (() => void) | undefined;if (mode === "note") {- onSave = () => void saveNote();+ onSave = saveNote;} else if (mode === "pdf") {- if (pdfSave?.status !== "saving" && pdfSave?.status !== "saved") {- onSave = () => void savePdf();- }+ onSave = savePdf;} else if (clip) {onSave = () => saveClip(clip);}+ if (busy) onSave = undefined;function saveOnCtrlEnter(e: KeyboardEvent) {if (onSave && e.key === "Enter" && e.ctrlKey) {@@ -477,7 +535,6 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {const published = pageLabels?.publishedDate;const modified = pageLabels?.modifiedDate;const button = SAVE_BUTTONS[mode ?? "page"];- const buttonLabel = mode === "pdf" && pdfSave?.status === "saving" ? "Saving PDF…" : button.label;return (<div className="page-preview">@@ -626,22 +683,6 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {{(!mode || (mode === "page" && !clip)) && <div className="page-preview-placeholder">Reading the page…</div>}</div>- {mode === "pdf" && pdfSave?.status === "saved" && (- <div className="callout callout-info save-result">- <span>PDF has been saved to Trilium.</span>- <a- href="#"- onClick={(e) => {- e.preventDefault();- openSavedNote(pdfSave.noteId);- }}- >Open in Trilium</a>- </div>- )}- {mode === "pdf" && pdfSave?.status === "failed" && (- <div className="callout callout-warning save-result">{pdfSave.message}</div>- )}-<buttonclassName="btn btn-primary primary-action"disabled={disabled || !onSave}@@ -649,7 +690,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {onClick={onSave}><Icon icon={button.icon} />- <span className="action-label">{buttonLabel}</span>+ <span className="action-label">{button.label}</span><Shortcut keys={button.shortcut ?? shortcuts[button.command]} /></button></div>diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.cssindex e796a016f7..18e47a332b 100644--- a/apps/web-clipper/entrypoints/popup/popup.css+++ b/apps/web-clipper/entrypoints/popup/popup.css@@ -17,12 +17,12 @@ body {padding: 10px 12px;}- .callout-info {+ .callout-info,+ .save-status {display: flex;align-items: center;justify-content: space-between;gap: 8px;- background: color-mix(in srgb, var(--admonition-note-accent-color) 15%, var(--main-background-color));a {flex-shrink: 0;@@ -32,12 +32,29 @@ body {}}+ .callout-info {+ background: color-mix(in srgb, var(--admonition-note-accent-color) 15%, var(--main-background-color));+ }++ .callout-success {+ background: color-mix(in srgb, var(--status-ok-color) 18%, var(--main-background-color));+ }+.callout-warning {background: color-mix(in srgb, var(--admonition-warning-accent-color) 15%, var(--main-background-color));}- .save-result {- border-radius: 6px;+ .callout-error {+ background: color-mix(in srgb, var(--status-error-color) 18%, var(--main-background-color));+ }++ .save-status-links {+ display: flex;+ flex-direction: column;+ flex-shrink: 0;+ align-items: flex-end;+ gap: 6px;+ white-space: nowrap;}.capture-actions {diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex a9f14361db..850fb638c9 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -59,6 +59,8 @@ const tabsSendMessage = vi.fn(async (_tabId: number, message: { name: string }):return selection;});const closeWindow = vi.fn();+const disconnect = vi.fn();+const connect = vi.fn((_info: { name: string }) => ({ disconnect }));let container: HTMLElement;describe("popup", () => {@@ -68,7 +70,7 @@ describe("popup", () => {metadata = {};pageReadings = { article: PAGE, wholePage: WHOLE_PAGE };pdfTab = false;- Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });+ Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage, connect });Object.assign(fakeBrowser.commands, { getAll: getAllCommands });Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });Object.assign(fakeBrowser, { scripting: { executeScript } });@@ -183,22 +185,25 @@ describe("popup", () => {expect(container.querySelector(".notices")).toBeNull();});- it("sends the capture actions, closing the popup for screenshots", async () => {+ it("sends the capture actions, closing the popup only to crop on the page", async () => {await click("Crop screenshot");expect(sendMessage).toHaveBeenCalledWith({ name: "save-cropped-screenshot" });+ expect(closeWindow).toHaveBeenCalledOnce();await click("Visible area screenshot");+ await flush();expect(sendMessage).toHaveBeenCalledWith({ name: "save-whole-screenshot" });await click("Full page screenshot");+ await flush();expect(sendMessage).toHaveBeenCalledWith({ name: "save-full-page-screenshot" });- expect(closeWindow).toHaveBeenCalledTimes(3);await click("All tabs in window");+ await flush();expect(sendMessage).toHaveBeenCalledWith({ name: "save-tabs" });await click("Check the connection again");expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search" });await click("Options");expect(openOptionsPage).toHaveBeenCalledOnce();- expect(closeWindow).toHaveBeenCalledTimes(3);+ expect(closeWindow).toHaveBeenCalledOnce();const openWindow = vi.spyOn(window, "open").mockImplementation(() => null);await click("Help");@@ -322,11 +327,10 @@ describe("popup", () => {expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-whole-page", page: WHOLE_PAGE });});- it("saves the extracted page with the edited title, and closes", async () => {+ it("saves the extracted page with the edited title", async () => {await type(".page-title", " My title ");await click("Save page to Trilium");expect(sendMessage).toHaveBeenCalledWith({ name: "save-whole-page", page: { ...PAGE, title: "My title" } });- expect(closeWindow).toHaveBeenCalledOnce();await type(".page-title", " ");await click("Save page to Trilium");@@ -416,7 +420,7 @@ describe("popup", () => {await type(".page-title", " Quote ");await click("Save selection");expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-selection", selection: { ...SELECTION, title: "Quote" } });- expect(closeWindow).toHaveBeenCalledTimes(2);+ expect(closeWindow).not.toHaveBeenCalled();});it("saves the selection of a page with nothing else to save, and ignores an empty one", async () => {@@ -477,14 +481,16 @@ describe("popup", () => {expect(container.querySelector<HTMLTextAreaElement>(".page-body .note-text")?.value).toBe("Worth a read");expect(closeWindow).not.toHaveBeenCalled();- sendMessage.mockResolvedValueOnce(true);+ sendMessage.mockResolvedValueOnce({ noteId: "n1", message: "Link with note has been saved to Trilium." });await click("Save bookmark");+ await flush();expect(sendMessage).toHaveBeenLastCalledWith({name: "save-link-with-note",title: "An article",content: "<p>Worth a read</p>"});- expect(closeWindow).toHaveBeenCalledOnce();+ expect(saveStatus()?.text).toBe("Link with note has been saved to Trilium.Open note");+ expect(closeWindow).not.toHaveBeenCalled();});it("shows the page's description atop the preview in every mode, and saves it as edited", async () => {@@ -679,14 +685,12 @@ describe("popup", () => {await click("Bookmark");await type(".page-title", " Read later. Soon ");await type(".page-body .note-text", " It has <b>tips</b>\nand more ");- sendMessage.mockResolvedValueOnce(true);await ctrlEnter(".page-body .note-text");expect(sendMessage).toHaveBeenCalledWith({name: "save-link-with-note",title: "Read later. Soon",content: "<p>It has <b>tips</b></p><p>and more</p>"});- expect(closeWindow).toHaveBeenCalledOnce();});it("keeps the bookmark open when it could not be saved, and leaves an empty title to the page", async () => {@@ -698,16 +702,18 @@ describe("popup", () => {});expect(sendMessage).not.toHaveBeenCalledWith(expect.objectContaining({ name: "save-link-with-note" }));- sendMessage.mockResolvedValueOnce(undefined);+ sendMessage.mockResolvedValueOnce({ error: "Trilium was not found." });await ctrlEnter(".page-title");+ await flush();expect(sendMessage).toHaveBeenCalledWith({ name: "save-link-with-note", title: "", content: "" });expect(container.querySelector(".page-body .note-text")).not.toBeNull();- expect(closeWindow).not.toHaveBeenCalled();+ expect(saveStatus()).toEqual({ kind: "callout callout-error save-status", text: "Trilium was not found." });+ expect(button("Save bookmark")?.disabled).toBe(false);await click("Page");await ctrlEnter(".page-title");expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-whole-page", page: PAGE });- expect(closeWindow).toHaveBeenCalledOnce();+ expect(closeWindow).not.toHaveBeenCalled();});it("asks for a note in every mode, and saves it above the clipped content", async () => {@@ -774,24 +780,21 @@ describe("popup", () => {expect(sendMessage).toHaveBeenLastCalledWith({name: "save-pdf", url: PDF_TAB.url, title: "Edited", description: "Key figures"});- expect(button("Saving PDF…")?.disabled).toBe(true);+ expect(saveStatus()).toEqual({ kind: "callout callout-info save-status", text: "Saving to Trilium…" });+ expect(button("Save PDF to Trilium")?.disabled).toBe(true);await ctrlEnter(".page-title");expect(sendMessageCalls("save-pdf")).toBe(1);- expect(saveResult()).toBeUndefined();- answerSave({ noteId: "n1" });+ answerSave({ noteId: "n1", message: "PDF has been saved to Trilium." });await flush();- expect(saveResult()).toEqual({ kind: "callout callout-info save-result", text: "PDF has been saved to Trilium.Open in Trilium" });+ expect(saveStatus()).toEqual({+ kind: "callout callout-success save-status", text: "PDF has been saved to Trilium.Open note"+ });expect(button("Save PDF to Trilium")?.disabled).toBe(true);expect(closeWindow).not.toHaveBeenCalled();- const open = container.querySelector<HTMLAnchorElement>(".save-result a");- await act(() => open?.click());- expect(sendMessage).toHaveBeenLastCalledWith({ name: "openNoteInTrilium", noteId: "n1" });- expect(closeWindow).toHaveBeenCalledOnce();-await click("Bookmark");- expect(saveResult()).toBeUndefined();+ expect(button("Save bookmark")?.disabled).toBe(false);expect(container.querySelector(".note-text")).not.toBeNull();expect(container.querySelector(".clip-hint")).toBeNull();});@@ -816,20 +819,60 @@ describe("popup", () => {await click("Save PDF to Trilium");expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-pdf", url: PDF_TAB.url, title: "report.pdf" });await flush();- expect(saveResult()).toEqual({- kind: "callout callout-warning save-result",+ expect(saveStatus()).toEqual({+ kind: "callout callout-error save-status",text: "Saving a PDF needs a newer version of Trilium."});sendMessage.mockResolvedValueOnce(undefined);await click("Save PDF to Trilium");await flush();- expect(saveResult()?.text).toBe("Saving to Trilium failed.");+ expect(saveStatus()?.text).toBe("Saving to Trilium failed.");expect(sendMessageCalls("save-pdf")).toBe(2);expect(closeWindow).not.toHaveBeenCalled();});});+ it("stays open while a save runs, then shows how it went in place of the clipped notice", async () => {+ expect(connect).toHaveBeenCalledWith({ name: "popup" });+ await receive({ name: "trilium-previously-visited", searchNote: { status: "found", noteId: "clipped" } });+ expect(container.querySelector(".already-visited")).not.toBeNull();+ let answerSave: (answer: unknown) => void = () => {};+ sendMessage.mockReturnValueOnce(new Promise((resolve) => answerSave = resolve));+ await click("All tabs in window");+ expect(saveStatus()).toEqual({ kind: "callout callout-info save-status", text: "Saving to Trilium…" });+ expect(container.querySelector(".already-visited")).toBeNull();+ expect(container.querySelector(".capture-actions .save-status")).toBeNull();+ for (const action of captureButtons()) {+ expect(action.disabled, action.getAttribute("aria-label") ?? "").toBe(true);+ }+ expect(button("Crop screenshot")?.title).toBe("Trilium is saving the last clipping.");++ answerSave({ noteId: "n1", message: "2 links have been saved to Trilium.", tabIds: [ 7, 8 ] });+ await flush();+ expect(saveStatus()).toEqual({+ kind: "callout callout-success save-status",+ text: "2 links have been saved to Trilium.Open noteClose saved tabs"+ });+ expect(captureButtons().every((action) => !action.disabled)).toBe(true);+ await clickLink("Close saved tabs");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "closeTabs", tabIds: [ 7, 8 ] });+ expect(closeWindow).toHaveBeenCalledOnce();++ sendMessage.mockResolvedValueOnce({ noteId: "n2", message: "Page has been saved to Trilium." });+ await click("Save page to Trilium");+ await flush();+ expect(saveStatus()?.text).toBe("Page has been saved to Trilium.Open note");+ expect(button("Save page to Trilium")?.disabled).toBe(true);+ expect(button("All tabs in window")?.disabled).toBe(false);+ await clickLink("Open note");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "openNoteInTrilium", noteId: "n2" });+ expect(closeWindow).toHaveBeenCalledTimes(2);++ await act(() => render(null, container));+ expect(disconnect).toHaveBeenCalledOnce();+ });+it("renders itself into the page's root element", async () => {const root = document.createElement("div");root.id = "root";@@ -949,16 +992,22 @@ async function receive(message: object) {});}-/** The outcome of saving a PDF, as the card shows it: its kind of callout and its text. */-function saveResult() {- const result = container.querySelector(".page-preview .save-result");- return result ? { kind: result.className, text: result.textContent } : undefined;+/** The save in progress or how the last one went, as the popup shows it: its classes and its text. */+function saveStatus() {+ const status = container.querySelector(".popup > .notices:first-child > .save-status");+ return status ? { kind: status.className, text: status.textContent } : undefined;}function sendMessageCalls(name: string) {return sendMessage.mock.calls.filter(([ message ]) => (message as { name?: string }).name === name).length;}+async function clickLink(text: string) {+ const link = [ ...container.querySelectorAll("a") ].find((a) => a.textContent === text);+ expect(link, text).toBeDefined();+ await act(() => link?.click());+}+/** Lets the promises the effects start, such as reading the shortcuts, settle. */async function flush() {await act(async () => {diff --git a/apps/web-clipper/utils.ts b/apps/web-clipper/utils.tsindex 91c79402b3..2b132571ce 100644--- a/apps/web-clipper/utils.ts+++ b/apps/web-clipper/utils.ts@@ -13,6 +13,12 @@ export interface ReadablePage {labels: Record<string, string>;}+/** What a save made: the note, the message that reports it, and the tabs it saved, if any. */+export type Saved = { noteId: string, message: string, tabIds?: number[] };++/** How a save the popup asked for went, as the background answers it. */+export type SaveOutcome = Saved | { error: string };+/** The two ways to read a page: its article, as Defuddle finds it, and all of it. */export type PageVariant = "article" | "wholePage";diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex cfb0d4ea28..82ab726075 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -34,7 +34,7 @@ Clicking the extension's button in the browser toolbar opens its popup:* _Selection_, when text is selected on the page: _Save selection_ saves it into the note of that page's clippings, as the context menu does.* _Page_: _Save page to Trilium_ saves the page's text and images. A smaller switch at the top of the preview chooses how much of the page to keep: _Article_ keeps only the page's main text, without its menus, sidebars and footers, and _Whole page_ keeps everything the page shows. _Whole page_ is for pages that are not an article (such as a gallery or a page of cards), where _Article_ can leave out part of the content; the preview shows what each one keeps. _Article_ is unavailable on a page where Trilium finds no article. The author the page names shows under the description, marked by the <span class="tn-icon bx bx-user"></span> icon. It can be edited or cleared before saving, or written in when the page names none, and is saved in the `#pageAuthor` label of the note. When the page states when it was published, that date shows under the author, marked by the <span class="tn-icon bx bx-calendar"></span> icon, and is saved in the `#publishedDate` label of the note. When it states when it was last modified, that date shows below, marked by the <span class="tn-icon bx bx-history"></span> icon, and is saved in the `#modifiedDate` label.- * _PDF_, when the tab shows a PDF in the browser's viewer: _Save PDF to Trilium_ downloads the PDF and saves it as a file note, which Trilium opens in its <a class="reference-link" href="../Note%20Types/File/PDFs.md">PDFs</a> viewer. The popup stays open while the PDF downloads, then says that it was saved, with a link to open the note, or why it was not. Only the title and the description can be edited, since a file note has no text of its own for your note. The page's address is saved in the note's `#pageUrl` label and the PDF's file name in `#originalFileName`. Saving a PDF needs Trilium v0.107.0 or later.+ * _PDF_, when the tab shows a PDF in the browser's viewer: _Save PDF to Trilium_ downloads the PDF and saves it as a file note, which Trilium opens in its <a class="reference-link" href="../Note%20Types/File/PDFs.md">PDFs</a> viewer. Only the title and the description can be edited, since a file note has no text of its own for your note. The page's address is saved in the note's `#pageUrl` label and the PDF's file name in `#originalFileName`. Saving a PDF needs Trilium v0.107.0 or later.* _Bookmark_, always: there is no preview, and _Save bookmark_ saves a link to the page with your note as the content of the note. Left empty, the title stays the page's title.The box for your note, marked by the <span class="tn-icon bx bx-info-circle"></span> icon, has the cursor when the popup opens, so a note (such as why the page is worth keeping) can be typed right away. It grows with its text, and keeps it when switching between _Selection_, _Page_ and _Bookmark_. A note on a selection or a page is saved above the clipped content, in a _Note_ admonition. Left empty, nothing is added. <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in any of the popup's fields saves, whichever is chosen.@@ -45,6 +45,7 @@ Clicking the extension's button in the browser toolbar opens its popup:* 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 the popup says so in place of the preview, and only _Tabs_ remains available there.* 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), _Full page_ (a screenshot of the whole page) and _Tabs_ (saves the links of every tab in the current window as a list of <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a>, or of plain links when _Autogenerate link previews_ is turned off). Hovering over a button shows its full name and, if it has one, its keyboard shortcut.* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. The scrollbars are hidden while it does, so they do not appear in the image. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. A long page is saved as several images, one below the other in the note. A page longer than 100 screens is cut off there, and the message after saving says so.+* The popup stays open while Trilium saves, which can take a few seconds for a long page or a large PDF, and the other actions wait until it is done. The bar at the top of the popup then says, in green, that the clipping was saved (in place of the notice that the page was already clipped), with _Open note_ to open it in Trilium (and, after _Tabs_, _Close saved tabs_), or, in red, why it could not be saved. The same clipping cannot be saved twice by accident: the save button stays disabled until another mode is chosen. _Crop_ is the exception: the popup closes so that an area of the page can be selected, and the notification on the page reports the outcome.* If the current page was already clipped, a notice at the top offers to open the note in Trilium.* If Trilium cannot be found, the popup explains why instead of showing the actions, with buttons to look for Trilium again and to open the options.* The bottom of the popup shows whether the extension is connected to Trilium, as a colored dot (green when connected, amber when the versions are not compatible, red when Trilium was not found) next to a description of the connection, followed by the buttons for the extension's options and for this help page. A button to check the connection again appears next to them when hovering over the bar, and stays visible while Trilium cannot be reached or is not compatible.@@ -100,7 +101,7 @@ To connect to a server, enter its address and your password in the extension's o### When a clipping fails-After each clipping, a notification in the corner of the page confirms that it was saved, with a link to open the new note in Trilium. If the clipping could not be saved, the notification says why instead:+After each clipping made with a keyboard shortcut or the context menu, a notification in the corner of the page confirms that it was saved, with a link to open the new note in Trilium. A clipping made from the popup reports in the popup instead, unless the popup was closed before it was saved. If the clipping could not be saved, the message says why instead:* Trilium was not found: start the desktop application, or check the server address and token in the extension's options.* The versions of Trilium and the extension are not compatible: update the one the message names.@@ -109,7 +110,7 @@ After each clipping, a notification in the corner of the page confirms that it wThe extension downloads the images of a clipping itself, so that they are stored in Trilium together with the note. If some of them cannot be downloaded (for example because the website refuses the request), the clipping is still saved, and the notification says how many images are missing. Those images keep their address on the original website: Trilium tries to download them once more if _Download images automatically_ is enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Media_, and otherwise the note shows them from the website for as long as it serves them.-The notification is shown on the page itself, so it does not appear on pages where extensions cannot run (such as the browser's own settings pages, the extension stores and Firefox's PDF viewer). A PDF saved from the popup reports the outcome in the popup instead.+The notification is shown on the page itself, so it does not appear on pages where extensions cannot run (such as the browser's own settings pages, the extension stores and Firefox's PDF viewer). A clipping saved from the popup on such a page still reports in the popup.## Testing development versions