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): show the outcome of saving a PDF in the popup
Elian Doranb580c0232e60
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 65f12b24f4..8732c874ea 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,8 +59,10 @@<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.- 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+ 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> 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@@ -237,8 +239,9 @@and otherwise the note shows them from the website for as long as it servesthem.</p><p>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- and the extension stores).</p>+ 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.</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 e6325bf00f..98d37fc8de 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -437,7 +437,8 @@ describe("background", () => {answerPdf();const pdfUrl = "https://example.com/files/report";- await sendRuntimeMessage({ name: "save-pdf", url: pdfUrl, title: "Edited", description: "Summary" });+ await expect(sendRuntimeMessage({ name: "save-pdf", url: pdfUrl, title: "Edited", description: "Summary" }))+ .resolves.toEqual({ noteId: "saved" });expect(fetchMock).toHaveBeenCalledWith(pdfUrl, { credentials: "include" });expect(lastPayload()).toEqual({@@ -472,9 +473,11 @@ describe("background", () => {const failure = async (message: object) => {facade.callService.mockClear();tabsSendMessage.mockClear();- await sendRuntimeMessage({ name: "save-pdf", url: PAGE_URL, title: "T", ...message });+ const answer = await sendRuntimeMessage({ name: "save-pdf", url: PAGE_URL, title: "T", ...message });expect(facade.callService).not.toHaveBeenCalled();- return (await lastToast() as { message?: string } | undefined)?.message;+ const toastMessage = (await lastToast() as { message?: string } | undefined)?.message;+ expect(answer).toEqual({ error: toastMessage });+ return toastMessage;};facade.requireMinorVersion.mockRejectedValueOnce(diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex b3a4e5e855..c9b0dada61 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -323,12 +323,16 @@ export default defineBackground(() => {try {return await action();} catch (e) {- console.error("Web clipper action failed", e);- toast(failureMessage(e));+ reportFailure(e);return undefined;}}+ function reportFailure(error: unknown) {+ console.error("Web clipper action failed", error);+ toast(failureMessage(error));+ }+async function requestFromPage(message: BackgroundMessage) {const response = await sendMessageToActiveTab(message);if (!response) {@@ -518,6 +522,7 @@ export default defineBackground(() => {});toast(savedMessage("PDF", 0), resp.noteId);+ return resp.noteId as string;}async function downloadPdf(url: string) {@@ -720,7 +725,13 @@ export default defineBackground(() => {return await saveWholePage(request.page);}else if (request.name === 'save-pdf') {- return await savePdf(request.url, request.title, request.description);+ // 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) };+ }}else if (request.name === 'save-selection') {return await saveSelection(request.selection);diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex a5792a1c1a..92750ac8d2 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -83,6 +83,9 @@ 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 };+/** What the user has chosen and typed in the card, kept by `Popup` so a reconnection does not lose it. */interface Draft {mode?: ClipMode;@@ -372,6 +375,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {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";@@ -431,13 +435,22 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {window.close();}- function savePdf() {- void sendMessage({+ /** 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({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();}@@ -445,7 +458,9 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {if (mode === "note") {onSave = () => void saveNote();} else if (mode === "pdf") {- onSave = savePdf;+ if (pdfSave?.status !== "saving" && pdfSave?.status !== "saved") {+ onSave = () => void savePdf();+ }} else if (clip) {onSave = () => saveClip(clip);}@@ -462,6 +477,7 @@ 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">@@ -610,6 +626,22 @@ 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}@@ -617,7 +649,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {onClick={onSave}><Icon icon={button.icon} />- <span className="action-label">{button.label}</span>+ <span className="action-label">{buttonLabel}</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 7d144d1730..e796a016f7 100644--- a/apps/web-clipper/entrypoints/popup/popup.css+++ b/apps/web-clipper/entrypoints/popup/popup.css@@ -36,6 +36,10 @@ body {background: color-mix(in srgb, var(--admonition-warning-accent-color) 15%, var(--main-background-color));}+ .save-result {+ border-radius: 6px;+ }+.capture-actions {display: flex;flex-direction: column;diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex be3fc2f661..a9f14361db 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -768,13 +768,30 @@ describe("popup", () => {await type(".page-title", "Edited");await type(".page-description", " Key figures ");+ let answerSave: (answer: unknown) => void = () => {};+ sendMessage.mockReturnValueOnce(new Promise((resolve) => answerSave = resolve));await click("Save PDF to Trilium");expect(sendMessage).toHaveBeenLastCalledWith({name: "save-pdf", url: PDF_TAB.url, title: "Edited", description: "Key figures"});+ expect(button("Saving PDF…")?.disabled).toBe(true);+ await ctrlEnter(".page-title");+ expect(sendMessageCalls("save-pdf")).toBe(1);+ expect(saveResult()).toBeUndefined();++ answerSave({ noteId: "n1" });+ await flush();+ expect(saveResult()).toEqual({ kind: "callout callout-info save-result", text: "PDF has been saved to Trilium.Open in Trilium" });+ 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(container.querySelector(".note-text")).not.toBeNull();expect(container.querySelector(".clip-hint")).toBeNull();});@@ -795,8 +812,21 @@ describe("popup", () => {expect(button("Crop screenshot")?.disabled).toBe(true);expect(button("All tabs in window")?.disabled).toBe(false);+ sendMessage.mockResolvedValueOnce({ error: "Saving a PDF needs a newer version of Trilium." });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",+ 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(sendMessageCalls("save-pdf")).toBe(2);+ expect(closeWindow).not.toHaveBeenCalled();});});@@ -919,6 +949,16 @@ 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;+}++function sendMessageCalls(name: string) {+ return sendMessage.mock.calls.filter(([ message ]) => (message as { name?: string }).name === name).length;+}+/** Lets the promises the effects start, such as reading the shortcuts, settle. */async function flush() {await act(async () => {diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex a708d92a71..cfb0d4ea28 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. 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. 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.* _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.@@ -109,7 +109,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 and the extension stores).+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.## Testing development versions