Skip to content

Build your personal knowledge base with Trilium Notes

feat(web-clipper): say why a page cannot be saved, and keep what still works

Elian Doran4a42938e4847
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.html
index 943c524bdb..b87e63ac44 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
@@ -33,10 +33,14 @@
<li>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. <em>Save page to Trilium</em> saves it. Pages
- the extension cannot read, such as the browser's own pages, say so instead.
- The keyboard shortcut and the context menu still save the page right away,
- without a preview.</li>
+ article's text and images. <em>Save page to Trilium</em> 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 <em>Note</em> and <em>Tabs</em> remain
+ available there. The keyboard shortcut and the context menu still save
+ the page right away, without a preview.</li>
<li>Below the preview, a row of buttons offers the other actions: <em>Crop</em> (a
screenshot of an area you select), <em>Screenshot</em> (of the visible part
of the page), <em>Note</em> (a link with a note) and <em>Tabs</em> (saves the
diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsx
index c1621b9050..be1b06a6d6 100644
--- a/apps/web-clipper/entrypoints/popup/main.tsx
+++ b/apps/web-clipper/entrypoints/popup/main.tsx
@@ -6,9 +6,11 @@ import ArrowLeft from "@boxicons/js/icons/ArrowLeft";
import Article from "@boxicons/js/icons/Article";
import Cog from "@boxicons/js/icons/Cog";
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 Link from "@boxicons/js/icons/Link";
+import Lock from "@boxicons/js/icons/Lock";
import RefreshCw from "@boxicons/js/icons/RefreshCw";
import Screenshot from "@boxicons/js/icons/Screenshot";
import Tabs from "@boxicons/js/icons/Tabs";
@@ -20,6 +22,7 @@ import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background
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.";
type PopupMessage = {
name: "trilium-search-status";
@@ -42,6 +45,9 @@ interface ExtractedPage {
labels: Record<string, string>;
}
+/** The current page: its readable version, or why there is none. */
+type PageState = ExtractedPage | "unreadable" | "inaccessible";
+
const PREVIEW_STYLE = `
:root { color-scheme: light dark; }
body { margin: 8px; font: 12px/1.5 system-ui, sans-serif; overflow-wrap: anywhere; }
@@ -160,29 +166,56 @@ function CaptureActions({ disabled, shortcuts, onWriteNote }: {
shortcuts: Shortcuts;
onWriteNote: () => void;
}) {
+ /** `undefined` while the page is read. */
+ const [ page, setPage ] = useState<PageState>();
+
+ useEffect(() => {
+ void extractPage().then(setPage);
+ }, []);
+
function sendAndClose(name: string) {
void sendMessage({ name });
window.close();
}
+ const disabledReason = disabled ? DISCONNECTED_TITLE : undefined;
+ const pageDisabledReason = disabledReason ?? (page === "inaccessible" ? UNREACHABLE_TITLE : undefined);
+
+ let main: ComponentChildren;
+ if (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") {
+ main = <EmptyState icon={FileX}>This page has no article to save.</EmptyState>;
+ } else {
+ main = <PagePreview page={page} disabled={disabled} shortcut={shortcuts.saveWholePage} />;
+ }
+
return (
<div className="capture-actions">
- <PagePreview disabled={disabled} shortcut={shortcuts.saveWholePage} />
+ {main}
<div className="toolbar">
<ToolbarAction
icon={Crop} label="Crop" name="Crop screenshot"
- shortcut={shortcuts.saveCroppedScreenshot} disabled={disabled}
+ shortcut={shortcuts.saveCroppedScreenshot} disabledReason={pageDisabledReason}
onClick={() => sendAndClose("save-cropped-screenshot")}
/>
<ToolbarAction
- icon={Screenshot} label="Screenshot" name="Visible area screenshot" disabled={disabled}
+ icon={Screenshot} label="Screenshot" name="Visible area screenshot"
+ disabledReason={pageDisabledReason}
onClick={() => sendAndClose("save-whole-screenshot")}
/>
- <ToolbarAction icon={Link} label="Note" name="Link with a note" disabled={disabled} onClick={onWriteNote} />
+ <ToolbarAction
+ icon={Link} label="Note" name="Link with a note"
+ disabledReason={disabledReason} onClick={onWriteNote}
+ />
<ToolbarAction
icon={Tabs} label="Tabs" name="All tabs in window"
- shortcut={shortcuts.saveTabs} disabled={disabled}
+ shortcut={shortcuts.saveTabs} disabledReason={disabledReason}
onClick={() => sendMessage({ name: "save-tabs" })}
/>
</div>
@@ -191,42 +224,48 @@ function CaptureActions({ disabled, shortcuts, onWriteNote }: {
}
/** A secondary action: an icon over a short label, its full name and shortcut in the tooltip. */
-function ToolbarAction({ icon, label, name, shortcut, disabled, onClick }: {
+function ToolbarAction({ icon, label, name, shortcut, disabledReason, onClick }: {
icon: IconDefinition;
label: string;
name: string;
shortcut?: string;
- disabled: boolean;
+ /** Why the action is disabled, shown in place of its name; the action is enabled without one. */
+ disabledReason: string | undefined;
onClick: () => void;
}) {
- let title = shortcut ? `${name} (${shortcut})` : name;
- if (disabled) {
- title = DISCONNECTED_TITLE;
- }
+ const title = disabledReason ?? (shortcut ? `${name} (${shortcut})` : name);
return (
- <button className="toolbar-action" disabled={disabled} title={title} aria-label={name} onClick={onClick}>
+ <button className="toolbar-action" disabled={!!disabledReason} title={title} aria-label={name} onClick={onClick}>
<Icon icon={icon} />
<span className="action-label">{label}</span>
</button>
);
}
+/** Takes the place of the page preview when the page cannot be saved, in the style of the app's `NoItems`. */
+function EmptyState({ icon, children }: { icon: IconDefinition, children: ComponentChildren }) {
+ return (
+ <div className="no-items">
+ <Icon icon={icon} />
+ {children}
+ </div>
+ );
+}
+
/**
* 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.
*/
-function PagePreview({ disabled, shortcut }: { disabled: boolean, shortcut: string | undefined }) {
- /** `undefined` while the page is read, `null` when it cannot be. */
- const [ page, setPage ] = useState<ExtractedPage | null>();
+function PagePreview({ page, disabled, shortcut }: {
+ /** `undefined` while the page is read. */
+ page: ExtractedPage | undefined;
+ disabled: boolean;
+ shortcut: string | undefined;
+}) {
const [ title, setTitle ] = useState("");
- useEffect(() => {
- void extractPage().then((extracted) => {
- setPage(extracted);
- setTitle(extracted?.title ?? "");
- });
- }, []);
+ useEffect(() => setTitle(page?.title ?? ""), [ page ]);
function save(extracted: ExtractedPage) {
void sendMessage({ name: "save-whole-page", page: { ...extracted, title: title.trim() || extracted.title } });
@@ -257,16 +296,9 @@ function PagePreview({ disabled, shortcut }: { disabled: boolean, shortcut: stri
)}
<div className="page-body">
- {page === undefined && <div className="page-preview-placeholder">Reading the page…</div>}
- {page === null && <div className="page-preview-placeholder">This page cannot be saved as an article.</div>}
- {page && (
- <iframe
- className="page-content"
- title="Preview of the page"
- sandbox=""
- srcDoc={previewDocument(page)}
- />
- )}
+ {page
+ ? <iframe className="page-content" title="Preview of the page" sandbox="" srcDoc={previewDocument(page)} />
+ : <div className="page-preview-placeholder">Reading the page…</div>}
</div>
<button
@@ -382,13 +414,17 @@ function describeStatus(status: TriliumSearchStatus | undefined) {
* Returns `null` on pages where no content script runs (browser pages, extension stores) and when
* the page cannot be extracted.
*/
-async function extractPage(): Promise<ExtractedPage | null> {
+/**
+ * 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.
+ */
+async function extractPage(): Promise<PageState> {
try {
const [ tab ] = await browser.tabs.query({ active: true, currentWindow: true });
- if (tab?.id === undefined) return null;
- return await browser.tabs.sendMessage(tab.id, { name: "trilium-save-page" }) ?? null;
+ if (tab?.id === undefined) return "inaccessible";
+ return await browser.tabs.sendMessage(tab.id, { name: "trilium-save-page" }) ?? "unreadable";
} catch {
- return null;
+ return "inaccessible";
}
}
diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.css
index df06bf29bf..a54b81be67 100644
--- a/apps/web-clipper/entrypoints/popup/popup.css
+++ b/apps/web-clipper/entrypoints/popup/popup.css
@@ -135,6 +135,23 @@ body {
}
}
+ .no-items {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: 1.25em 0.75em;
+ color: var(--muted-text-color);
+ text-align: center;
+ white-space: pre-line;
+
+ svg.icon {
+ width: 2em;
+ height: 2em;
+ margin-bottom: 0.5rem;
+ opacity: 0.65;
+ }
+ }
+
.primary-action {
justify-content: flex-start;
width: 100%;
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
index 511d748140..49ca2f919e 100644
--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -9,6 +9,7 @@ import { fakeBrowser } from "wxt/testing/fake-browser";
import { basicIcon, parseLinkNote, Popup, previewDocument, shortcutsByCommand, textToHtml } from "./main";
const DISCONNECTED = "This action can't be performed without active connection to Trilium.";
+const UNREACHABLE = "This action is not available on this page.";
const sendMessage = vi.fn(async (_message: object): Promise<unknown> => undefined);
const openOptionsPage = vi.fn(async () => {});
@@ -206,7 +207,7 @@ describe("popup", () => {
expect(container.querySelector(".page-meta")?.textContent).toBe("example.com");
});
- it("says so while the page is read, and when it cannot be", async () => {
+ it("says so while the page is read", async () => {
let resolvePage: (page: unknown) => void = () => {};
tabsSendMessage.mockReturnValueOnce(new Promise((resolve) => {
resolvePage = resolve;
@@ -216,20 +217,35 @@ describe("popup", () => {
expect(cardParts()).toEqual([ "page-body", "btn btn-primary primary-action" ]);
expect(button("Save page to Trilium")?.disabled).toBe(true);
- resolvePage(undefined);
+ resolvePage(PAGE);
await flush();
- expect(placeholder()).toBe("This page cannot be saved as an article.");
- expect(button("Save page to Trilium")?.disabled).toBe(true);
- expect(container.querySelector("iframe")).toBeNull();
+ expect(container.querySelector(".page-body iframe")).not.toBeNull();
+ });
+ it("keeps every other action on a page with no article", async () => {
+ tabsSendMessage.mockResolvedValueOnce(undefined);
+ await rerender();
+ expect(unavailable()).toBe("This page has no article to save.");
+ expect(container.querySelector(".page-preview")).toBeNull();
+ expect(captureButtons().map((action) => action.disabled)).toEqual([ false, false, false, false ]);
+ });
+
+ it("keeps only the actions that need no access to a page out of reach", async () => {
tabsSendMessage.mockRejectedValueOnce(new Error("Could not establish connection."));
await rerender();
- expect(placeholder()).toBe("This page cannot be saved as an article.");
+ expect(unavailable()).toBe(
+ "The extension cannot access this page.\nIf it is a regular web page, reload it."
+ );
+ expect(container.querySelector(".page-preview")).toBeNull();
+ expect(captureButtons().map((action) => action.disabled)).toEqual([ true, true, false, false ]);
+ expect(button("Crop screenshot")?.title).toBe(UNREACHABLE);
+ expect(button("Visible area screenshot")?.title).toBe(UNREACHABLE);
+ expect(button("Link with a note")?.title).toBe("Link with a note");
tabsQuery.mockResolvedValueOnce([ {} ]);
await rerender();
- expect(placeholder()).toBe("This page cannot be saved as an article.");
- expect(tabsSendMessage).toHaveBeenCalledTimes(3);
+ expect(unavailable()).toContain("The extension cannot access this page.");
+ expect(tabsSendMessage).toHaveBeenCalledTimes(2);
});
it("tells the user when the background script cannot be reached", async () => {
@@ -442,6 +458,13 @@ async function type(selector: string, value: string) {
});
}
+function unavailable() {
+ const empty = container.querySelector(".capture-actions > .no-items");
+ expect(empty).not.toBeNull();
+ expect(empty?.querySelector("svg.icon path")).not.toBeNull();
+ return empty?.textContent;
+}
+
function placeholder() {
return container.querySelector(".page-body > .page-preview-placeholder")?.textContent;
}
diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
index 2e01b4ec40..25074a541d 100644
--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
@@ -29,7 +29,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. Pages the extension cannot read, such as the browser's own pages, say so instead. The keyboard shortcut and the context menu still save the page right away, without a preview.
+* 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.
* 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.