Skip to content

Build your personal knowledge base with Trilium Notes

feat(web-clipper): lay the popup out around its main action

Elian Doran40e2feda0db8
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 f85831451c..fa253f5353 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
@@ -27,6 +27,27 @@
<li>save screenshot (with crop tool) from either popup or context menu</li>
<li>create short text note from popup</li>
</ul>
+<h2>The popup</h2>
+<p>Clicking the extension's button in the browser toolbar opens its popup:</p>
+<ul>
+ <li>The header 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 the buttons for the extension's
+ options and for this help page.</li>
+ <li><em>Save whole page</em> is the main action. Below it are <em>Crop screenshot</em>, <em>Visible area screenshot</em>, <em>Link with a note</em> and <em>All tabs in window</em> (which
+ saves the links of every tab in the current window as a list). An action
+ that has a keyboard shortcut shows it.</li>
+ <li><em>Link with a note</em> opens a small editor in place of the actions.
+ The first sentence or line of the text becomes the note's title, unless <em>Keep page title as note title</em> is
+ checked. Press <em>Save</em> or <kbd>Ctrl</kbd>+<kbd>Enter</kbd> to save it,
+ or the back arrow to return to the actions.</li>
+ <li>If the current page was already clipped, a notice at the top offers to
+ open the note in Trilium.</li>
+ <li>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.</li>
+ <li>The bottom of the popup describes the connection, with a button to check
+ it again.</li>
+</ul>
<h2>Location of clippings</h2>
<p>Trilium will save these clippings as a new child note under a "clipper
inbox" note.</p>
@@ -63,7 +84,8 @@
If the desktop application runs on a different port (for example because
it was started with the <code>TRILIUM_PORT</code> environment variable),
enter that port in the extension's options. The extension checks for Trilium
- again every minute, or right away when pressing <em>check</em> in its popup.</p>
+ again every minute, or right away when pressing the refresh button at the
+ bottom of its popup.</p>
<p>It's also possible to configure the <a href="#root/_help_WOcw2SLH6tbX">server</a> address
if you don't run the desktop application, or want it to work without the
desktop application running.</p>
diff --git a/apps/web-clipper/assets/theme.css b/apps/web-clipper/assets/theme.css
index 1dd725b357..0bad8e5445 100644
--- a/apps/web-clipper/assets/theme.css
+++ b/apps/web-clipper/assets/theme.css
@@ -32,6 +32,8 @@
--cmd-button-shadow-color: #00000040;
--cmd-button-icon-color: black;
--cmd-button-disabled-opacity: 0.5;
+ --cmd-button-keyboard-shortcut-background: #00000017;
+ --cmd-button-keyboard-shortcut-color: black;
--input-background-color: #00000012;
--input-text-color: black;
@@ -86,6 +88,8 @@
--cmd-button-hover-text-color: white;
--cmd-button-shadow-color: #00000080;
--cmd-button-icon-color: white;
+ --cmd-button-keyboard-shortcut-background: #0000004d;
+ --cmd-button-keyboard-shortcut-color: white;
--input-background-color: #ffffff12;
--input-text-color: #ffffffc7;
@@ -180,6 +184,14 @@ a {
}
}
+kbd {
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: var(--input-background-color);
+ font-family: inherit;
+ font-size: 0.85em;
+}
+
h2,
h3 {
font-weight: 500;
diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsx
index 3c38a0f45d..24e46ed625 100644
--- a/apps/web-clipper/entrypoints/popup/main.tsx
+++ b/apps/web-clipper/entrypoints/popup/main.tsx
@@ -2,6 +2,7 @@ import "@/assets/theme.css";
import "./popup.css";
import type { IconData, IconDefinition } from "@boxicons/js";
+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";
@@ -10,6 +11,7 @@ import Link from "@boxicons/js/icons/Link";
import RefreshCw from "@boxicons/js/icons/RefreshCw";
import Screenshot from "@boxicons/js/icons/Screenshot";
import Tabs from "@boxicons/js/icons/Tabs";
+import type { ComponentChildren } from "preact";
import { render } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
@@ -25,6 +27,9 @@ type PopupMessage = {
searchNote: TriliumSearchNoteStatus;
};
+/** The keyboard shortcut of each command, by command name; unbound commands are absent. */
+type Shortcuts = Record<string, string>;
+
const root = document.getElementById("root");
if (root) {
render(<Popup />, root);
@@ -34,6 +39,7 @@ export function Popup() {
const [ searchStatus, setSearchStatus ] = useState<TriliumSearchStatus>();
const [ clippedNoteId, setClippedNoteId ] = useState<string | null>(null);
const [ isWritingNote, setIsWritingNote ] = useState(false);
+ const [ shortcuts, setShortcuts ] = useState<Shortcuts>({});
useEffect(() => {
function onMessage(message: PopupMessage) {
@@ -51,26 +57,34 @@ export function Popup() {
browser.runtime.onMessage.addListener(onMessage);
void sendMessage({ name: "send-trilium-search-status" });
+ void browser.commands.getAll().then((commands) => setShortcuts(shortcutsByCommand(commands)));
return () => browser.runtime.onMessage.removeListener(onMessage);
}, []);
- const needsConnection = {
- disabled: !!searchStatus && !isConnected(searchStatus),
- title: searchStatus && !isConnected(searchStatus)
- ? "This action can't be performed without active connection to Trilium."
- : undefined
- };
-
- function sendAndClose(name: string) {
- void sendMessage({ name });
- window.close();
+ const status = describeStatus(searchStatus);
+
+ let body: ComponentChildren;
+ if (isWritingNote) {
+ body = <LinkWithNoteForm onBack={() => setIsWritingNote(false)} />;
+ } else if (searchStatus?.status === "not-found") {
+ body = <TriliumNotFound />;
+ } else {
+ body = (
+ <CaptureActions
+ disabled={!!searchStatus && !isConnected(searchStatus)}
+ shortcuts={shortcuts}
+ onWriteNote={() => setIsWritingNote(true)}
+ />
+ );
}
return (
<div className="popup">
<div className="popup-header">
+ <img className="logo" src="/icons/48.png" alt="" />
<h3>Trilium Web Clipper</h3>
+ <span className={`status-dot status-dot-${status.kind}`} title={status.text} />
<div className="popup-header-buttons">
<button className="icon-action" title="Options" aria-label="Options" onClick={() => browser.runtime.openOptionsPage()}>
@@ -82,63 +96,111 @@ export function Popup() {
</div>
</div>
- <div className="already-visited">
- {clippedNoteId && (
- <>
- Web page already clipped.{" "}
- <a
- href="#"
- onClick={(e) => {
- e.preventDefault();
- void sendMessage({ name: "openNoteInTrilium", noteId: clippedNoteId });
- }}
- >Open in Trilium.</a>
- </>
- )}
+ {clippedNoteId && (
+ <div className="callout callout-info already-visited">
+ <span>Web page already clipped.</span>
+ <a
+ href="#"
+ onClick={(e) => {
+ e.preventDefault();
+ void sendMessage({ name: "openNoteInTrilium", noteId: clippedNoteId });
+ }}
+ >Open in Trilium</a>
+ </div>
+ )}
+
+ {searchStatus?.status === "version-mismatch" && (
+ <div className="callout callout-warning">
+ Trilium instance found, but it is not compatible with this extension version.
+ Please update {searchStatus.extensionMajor > searchStatus.triliumMajor ? "Trilium Notes" : "this extension"} to
+ the latest version.
+ </div>
+ )}
+
+ {body}
+
+ <div className="connection">
+ <span className={`status-${status.kind}`} title={status.title}>{status.text}</span>
+
+ <button
+ className="icon-action"
+ title="Check the connection again"
+ aria-label="Check the connection again"
+ onClick={() => sendMessage({ name: "trigger-trilium-search" })}
+ >
+ <Icon icon={RefreshCw} />
+ </button>
</div>
+ </div>
+ );
+}
+
+function CaptureActions({ disabled, shortcuts, onWriteNote }: {
+ disabled: boolean;
+ shortcuts: Shortcuts;
+ onWriteNote: () => void;
+}) {
+ const actionProps = {
+ disabled,
+ title: disabled ? "This action can't be performed without active connection to Trilium." : undefined
+ };
- <div className="capture-buttons">
- <button className="btn btn-secondary" {...needsConnection} onClick={() => sendAndClose("save-cropped-screenshot")}>
+ function sendAndClose(name: string) {
+ void sendMessage({ name });
+ window.close();
+ }
+
+ return (
+ <div className="capture-actions">
+ <button className="btn btn-primary primary-action" {...actionProps} onClick={() => sendMessage({ name: "save-whole-page" })}>
+ <Icon icon={Article} />
+ <span className="action-label">Save whole page</span>
+ <Shortcut keys={shortcuts.saveWholePage} />
+ </button>
+
+ <div className="action-tiles">
+ <button className="btn btn-secondary action-tile" {...actionProps} onClick={() => sendAndClose("save-cropped-screenshot")}>
<Icon icon={Crop} />
- Crop screenshot
+ <span className="action-label">Crop screenshot</span>
+ <Shortcut keys={shortcuts.saveCroppedScreenshot} />
</button>
- <button className="btn btn-secondary" {...needsConnection} onClick={() => sendAndClose("save-whole-screenshot")}>
+ <button className="btn btn-secondary action-tile" {...actionProps} onClick={() => sendAndClose("save-whole-screenshot")}>
<Icon icon={Screenshot} />
- Save whole screenshot
- </button>
- <button className="btn btn-secondary" {...needsConnection} onClick={() => sendMessage({ name: "save-whole-page" })}>
- <Icon icon={Article} />
- Save whole page
+ <span className="action-label">Visible area screenshot</span>
</button>
- <button className="btn btn-secondary" {...needsConnection} onClick={() => setIsWritingNote(true)}>
+ <button className="btn btn-secondary action-tile" {...actionProps} onClick={onWriteNote}>
<Icon icon={Link} />
- Save link with a note
+ <span className="action-label">Link with a note</span>
</button>
- <button className="btn btn-secondary" {...needsConnection} onClick={() => sendMessage({ name: "save-tabs" })}>
+ <button className="btn btn-secondary action-tile" {...actionProps} onClick={() => sendMessage({ name: "save-tabs" })}>
<Icon icon={Tabs} />
- Save window's tabs as a list
+ <span className="action-label">All tabs in window</span>
+ <Shortcut keys={shortcuts.saveTabs} />
</button>
</div>
+ </div>
+ );
+}
- {isWritingNote && <LinkWithNoteForm onCancel={() => setIsWritingNote(false)} />}
+function Shortcut({ keys }: { keys: string | undefined }) {
+ return keys ? <kbd>{keys}</kbd> : null;
+}
- <div className="connection">
- <div>Status: <ConnectionStatus status={searchStatus} /></div>
+function TriliumNotFound() {
+ return (
+ <div className="not-found">
+ <strong>Trilium was not found.</strong>
+ <p>Start the Trilium desktop application, or connect to a Trilium server in the options.</p>
- <button
- className="icon-action"
- title="Check the connection again"
- aria-label="Check the connection again"
- onClick={() => sendMessage({ name: "trigger-trilium-search" })}
- >
- <Icon icon={RefreshCw} />
- </button>
+ <div className="not-found-buttons">
+ <button className="btn btn-primary" onClick={() => sendMessage({ name: "trigger-trilium-search" })}>Retry</button>
+ <button className="btn btn-secondary" onClick={() => browser.runtime.openOptionsPage()}>Open options</button>
</div>
</div>
);
}
-function LinkWithNoteForm({ onCancel }: { onCancel: () => void }) {
+function LinkWithNoteForm({ onBack }: { onBack: () => void }) {
const [ text, setText ] = useState("");
const [ keepTitle, setKeepTitle ] = useState(false);
const textAreaRef = useRef<HTMLTextAreaElement>(null);
@@ -157,10 +219,20 @@ function LinkWithNoteForm({ onCancel }: { onCancel: () => void }) {
return (
<div className="save-link-with-note">
+ <div className="view-header">
+ <button className="icon-action" title="Back" aria-label="Back" onClick={onBack}>
+ <Icon icon={ArrowLeft} />
+ </button>
+ <h4>Link with a note</h4>
+ </div>
+
<textarea
ref={textAreaRef}
rows={5}
value={text}
+ placeholder={keepTitle
+ ? "The note's text."
+ : "The first sentence becomes the note's title, the rest its text."}
onInput={(e) => setText(e.currentTarget.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && e.ctrlKey) {
@@ -170,53 +242,49 @@ function LinkWithNoteForm({ onCancel }: { onCancel: () => void }) {
}}
/>
- <div>
- <label className="tn-checkbox">
- <input
- type="checkbox"
- checked={keepTitle}
- onChange={(e) => setKeepTitle(e.currentTarget.checked)}
- />
- {" "}Keep page title as note title
- </label>
- </div>
+ <label className="tn-checkbox">
+ <input
+ type="checkbox"
+ checked={keepTitle}
+ onChange={(e) => setKeepTitle(e.currentTarget.checked)}
+ />
+ {" "}Keep page title as note title
+ </label>
+
<div className="save-link-with-note-buttons">
+ <span className="hint"><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to save</span>
<button type="submit" className="btn btn-primary" onClick={save}>Save</button>
- <button
- type="submit"
- className="btn btn-secondary"
- onClick={() => {
- onCancel();
- window.close();
- }}
- >Cancel</button>
</div>
</div>
);
}
-function ConnectionStatus({ status }: { status: TriliumSearchStatus | undefined }) {
+/** The state of the connection to Trilium: a kind for its color, and its description. */
+function describeStatus(status: TriliumSearchStatus | undefined) {
switch (status?.status) {
case undefined:
- return <span>unknown</span>;
case "searching":
- return <span>searching</span>;
+ return { kind: "pending", text: "Looking for Trilium…" };
case "not-found":
- return <span className="status-error">Not found</span>;
- case "version-mismatch": {
- const whatToUpgrade = status.extensionMajor > status.triliumMajor ? "Trilium Notes" : "this extension";
- return (
- <span className="status-warning">
- Trilium instance found, but it is not compatible with this extension version.
- Please update {whatToUpgrade} to the latest version.
- </span>
- );
- }
+ return { kind: "error", text: "Not found" };
+ case "version-mismatch":
+ return { kind: "warning", text: "Incompatible version" };
case "found-desktop":
- return <span className="status-ok">Connected on port {status.port}</span>;
+ return { kind: "ok", text: `Connected to the desktop app on port ${status.port}` };
case "found-server":
- return <span className="status-ok" title={`Connected to ${status.url}`}>Connected to the server</span>;
+ return { kind: "ok", text: "Connected to the server", title: `Connected to ${status.url}` };
+ }
+}
+
+/** Maps each bound command to its shortcut, as the browser shows it. */
+export function shortcutsByCommand(commands: { name?: string, shortcut?: string }[]): Shortcuts {
+ const shortcuts: Shortcuts = {};
+ for (const { name, shortcut } of commands) {
+ if (name && shortcut) {
+ shortcuts[name] = shortcut;
+ }
}
+ return shortcuts;
}
/** A Boxicons v3 icon, drawn inline in the current text color. */
diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.css
index e641b95fca..ec4afed125 100644
--- a/apps/web-clipper/entrypoints/popup/popup.css
+++ b/apps/web-clipper/entrypoints/popup/popup.css
@@ -1,5 +1,5 @@
body {
- width: 320px;
+ width: 340px;
}
.popup {
@@ -11,9 +11,13 @@ body {
.popup-header {
display: flex;
align-items: center;
- justify-content: space-between;
gap: 8px;
+ .logo {
+ width: 24px;
+ height: 24px;
+ }
+
h3 {
margin: 0;
font-size: 1.1em;
@@ -22,21 +26,112 @@ body {
.popup-header-buttons {
display: flex;
- gap: 4px;
+ gap: 2px;
+ margin-inline-start: auto;
+ }
+
+ .status-dot {
+ flex-shrink: 0;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ }
+
+ .status-dot-pending {
+ background: var(--muted-text-color);
+ opacity: 0.5;
+ }
+
+ .status-dot-ok {
+ background: var(--status-ok-color);
+ }
+
+ .status-dot-warning {
+ background: var(--status-warning-color);
+ }
+
+ .status-dot-error {
+ background: var(--status-error-color);
+ }
+
+ .callout {
+ padding: 8px 10px;
+ border-radius: 6px;
+ }
+
+ .callout-info {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ background: var(--link-hover-background);
+ }
+
+ .callout-warning {
+ background: color-mix(in srgb, var(--status-warning-color) 18%, transparent);
+ }
+
+ .capture-actions {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ }
+
+ .primary-action {
+ justify-content: flex-start;
+ width: 100%;
+ padding: 8px 12px;
+
+ .action-label {
+ flex-grow: 1;
+ text-align: start;
+ }
+ }
+
+ .action-tiles {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
}
- .already-visited:empty {
- display: none;
+ button.btn.action-tile {
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+ padding: 10px 8px;
+
+ > svg.icon {
+ width: 1.6em;
+ height: 1.6em;
+ margin: 0;
+ }
+
+ kbd {
+ margin: 0;
+ }
}
- .capture-buttons {
+ .not-found {
display: flex;
flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ border-radius: 6px;
+ background: var(--input-background-color);
+
+ p {
+ margin: 0 0 8px;
+ color: var(--muted-text-color);
+ }
+ }
+
+ .not-found-buttons {
+ display: flex;
gap: 6px;
button.btn {
- justify-content: flex-start;
- width: 100%;
+ min-width: 0;
+ flex-grow: 1;
}
}
@@ -51,13 +146,27 @@ body {
}
}
+ .view-header {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ --icon-button-size: 28px;
+
+ h4 {
+ margin: 0;
+ font-weight: 500;
+ }
+ }
+
.save-link-with-note-buttons {
display: flex;
- justify-content: flex-end;
+ align-items: center;
+ justify-content: space-between;
gap: 6px;
- button.btn {
- min-width: 80px;
+ .hint {
+ color: var(--muted-text-color);
+ font-size: 0.9em;
}
}
@@ -66,7 +175,7 @@ body {
align-items: center;
justify-content: space-between;
gap: 8px;
- padding-top: 10px;
+ padding-top: 8px;
border-top: 1px solid var(--main-border-color);
color: var(--muted-text-color);
--icon-button-size: 26px;
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
index ad3b93907a..c25fbdeb5e 100644
--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -1,14 +1,21 @@
+import Crop from "@boxicons/js/icons/Crop";
import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fakeBrowser } from "wxt/testing/fake-browser";
-import Crop from "@boxicons/js/icons/Crop";
+import { basicIcon, parseLinkNote, Popup, shortcutsByCommand, textToHtml } from "./main";
-import { basicIcon, parseLinkNote, Popup, textToHtml } from "./main";
+const DISCONNECTED = "This action can't be performed without active connection to Trilium.";
const sendMessage = vi.fn(async (_message: object): Promise<unknown> => undefined);
const openOptionsPage = vi.fn(async () => {});
+const getAllCommands = vi.fn(async () => [
+ { name: "saveSelection", shortcut: "Ctrl+Shift+S" },
+ { name: "saveWholePage", shortcut: "Alt+Shift+S" },
+ { name: "saveCroppedScreenshot", shortcut: "Ctrl+Shift+E" },
+ { name: "saveTabs", shortcut: "" }
+]);
const closeWindow = vi.fn();
let container: HTMLElement;
@@ -16,12 +23,14 @@ describe("popup", () => {
beforeEach(async () => {
fakeBrowser.reset();
Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });
+ Object.assign(fakeBrowser.commands, { getAll: getAllCommands });
vi.spyOn(window, "close").mockImplementation(closeWindow);
vi.spyOn(console, "log").mockImplementation(() => {});
container = document.createElement("div");
document.body.appendChild(container);
await act(() => render(<Popup />, container));
+ await flush();
});
afterEach(async () => {
@@ -32,21 +41,15 @@ describe("popup", () => {
vi.restoreAllMocks();
});
- it("asks for the connection status and shows it", async () => {
+ it("asks for the connection status and shows it in the header and the footer", async () => {
expect(sendMessage).toHaveBeenCalledWith({ name: "send-trilium-search-status" });
- expect(statusText()).toBe("unknown");
+ expect(status()).toEqual({ dot: "status-dot status-dot-pending", text: "Looking for Trilium…" });
+ expect(captureButtons()).toHaveLength(5);
expect(captureButtons().every((button) => !button.disabled)).toBe(true);
- await receive({ name: "trilium-search-status", triliumSearch: { status: "not-found" } });
- expect(container.querySelector(".status-error")?.textContent).toBe("Not found");
- for (const button of captureButtons()) {
- expect(button.disabled).toBe(true);
- expect(button.title).toBe("This action can't be performed without active connection to Trilium.");
- }
- expect(sendMessage).not.toHaveBeenCalledWith({ name: "trigger-trilium-search-note-url" });
-
await receive({ name: "trilium-search-status", triliumSearch: { status: "found-desktop", port: 37840, url: "" } });
- expect(container.querySelector(".status-ok")?.textContent).toBe("Connected on port 37840");
+ expect(status()).toEqual({ dot: "status-dot status-dot-ok", text: "Connected to the desktop app on port 37840" });
+ expect(container.querySelector(".connection .status-ok")).not.toBeNull();
expect(captureButtons().every((button) => !button.disabled && !button.title)).toBe(true);
expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search-note-url" });
@@ -54,53 +57,80 @@ describe("popup", () => {
name: "trilium-search-status",
triliumSearch: { status: "found-server", url: "https://trilium.example", token: "t" }
});
- const server = container.querySelector<HTMLElement>(".status-ok");
- expect(server?.textContent).toBe("Connected to the server");
- expect(server?.title).toBe("Connected to https://trilium.example");
+ expect(status().text).toBe("Connected to the server");
+ expect(container.querySelector<HTMLElement>(".connection .status-ok")?.title)
+ .toBe("Connected to https://trilium.example");
+
+ await receive({ name: "trilium-search-status", triliumSearch: { status: "searching" } });
+ expect(status()).toEqual({ dot: "status-dot status-dot-pending", text: "Looking for Trilium…" });
+ for (const button of captureButtons()) {
+ expect(button.disabled).toBe(true);
+ expect(button.title).toBe(DISCONNECTED);
+ }
+
+ await receive({ name: "unrelated" });
+ expect(status().text).toBe("Looking for Trilium…");
+ });
+
+ it("explains a version mismatch above the actions, which stay enabled", async () => {
+ expect(container.querySelector(".callout-warning")).toBeNull();
await receive({
name: "trilium-search-status",
triliumSearch: { status: "version-mismatch", extensionMajor: 2, triliumMajor: 1 }
});
- expect(container.querySelector(".status-warning")?.textContent).toContain("Please update Trilium Notes");
+ expect(status()).toEqual({ dot: "status-dot status-dot-warning", text: "Incompatible version" });
+ expect(container.querySelector(".callout-warning")?.textContent).toContain("Please update Trilium Notes");
expect(captureButtons().every((button) => !button.disabled)).toBe(true);
await receive({
name: "trilium-search-status",
triliumSearch: { status: "version-mismatch", extensionMajor: 1, triliumMajor: 2 }
});
- expect(container.querySelector(".status-warning")?.textContent).toContain("Please update this extension");
+ expect(container.querySelector(".callout-warning")?.textContent).toContain("Please update this extension");
+ });
- await receive({ name: "trilium-search-status", triliumSearch: { status: "searching" } });
- expect(statusText()).toBe("searching");
- expect(captureButtons().every((button) => button.disabled)).toBe(true);
+ it("replaces the actions with a way out when Trilium is not found", async () => {
+ await receive({ name: "trilium-search-status", triliumSearch: { status: "not-found" } });
+ expect(status()).toEqual({ dot: "status-dot status-dot-error", text: "Not found" });
+ expect(captureButtons()).toHaveLength(0);
+ expect(container.querySelector(".not-found strong")?.textContent).toBe("Trilium was not found.");
+ expect(sendMessage).not.toHaveBeenCalledWith({ name: "trigger-trilium-search-note-url" });
- await receive({ name: "unrelated" });
- expect(statusText()).toBe("searching");
+ await click("Retry");
+ expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search" });
+ await click("Open options");
+ expect(openOptionsPage).toHaveBeenCalledOnce();
+ expect(closeWindow).not.toHaveBeenCalled();
});
it("offers to open a page that was already clipped", async () => {
+ expect(container.querySelector(".already-visited")).toBeNull();
+
await receive({ name: "trilium-previously-visited", searchNote: { status: "found", noteId: "clipped" } });
- expect(container.querySelector(".already-visited")?.textContent)
- .toBe("Web page already clipped. Open in Trilium.");
+ expect(container.querySelector(".already-visited span")?.textContent).toBe("Web page already clipped.");
+ const link = container.querySelector<HTMLAnchorElement>(".already-visited a");
+ expect(link?.textContent).toBe("Open in Trilium");
- await act(() => container.querySelector<HTMLAnchorElement>(".already-visited a")?.click());
+ await act(() => link?.click());
expect(sendMessage).toHaveBeenCalledWith({ name: "openNoteInTrilium", noteId: "clipped" });
await receive({ name: "trilium-previously-visited", searchNote: { status: "not-found", noteId: null } });
- expect(container.querySelector(".already-visited")?.textContent).toBe("");
+ expect(container.querySelector(".already-visited")).toBeNull();
});
it("sends the capture actions, closing the popup for screenshots", async () => {
+ expect(container.querySelector(".primary-action .action-label")?.textContent).toBe("Save whole page");
+
await click("Crop screenshot");
expect(sendMessage).toHaveBeenCalledWith({ name: "save-cropped-screenshot" });
- await click("Save whole screenshot");
+ await click("Visible area screenshot");
expect(sendMessage).toHaveBeenCalledWith({ name: "save-whole-screenshot" });
expect(closeWindow).toHaveBeenCalledTimes(2);
await click("Save whole page");
expect(sendMessage).toHaveBeenCalledWith({ name: "save-whole-page" });
- await click("Save window's tabs as a list");
+ await click("All tabs in window");
expect(sendMessage).toHaveBeenCalledWith({ name: "save-tabs" });
await click("Check the connection again");
expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search" });
@@ -113,6 +143,15 @@ describe("popup", () => {
expect(openWindow).toHaveBeenCalledWith("https://docs.triliumnotes.org/user-guide/setup/web-clipper", "_blank");
});
+ it("shows the keyboard shortcut of each action that has one", () => {
+ expect(getAllCommands).toHaveBeenCalledOnce();
+ expect(shortcutOf("Save whole page")).toBe("Alt+Shift+S");
+ expect(shortcutOf("Crop screenshot")).toBe("Ctrl+Shift+E");
+ expect(shortcutOf("All tabs in window")).toBeUndefined();
+ expect(shortcutOf("Visible area screenshot")).toBeUndefined();
+ expect(shortcutOf("Link with a note")).toBeUndefined();
+ });
+
it("tells the user when the background script cannot be reached", async () => {
const alertMock = vi.fn();
vi.stubGlobal("alert", alertMock);
@@ -123,8 +162,46 @@ describe("popup", () => {
expect(alertMock).toHaveBeenCalledWith("Calling browser runtime failed. Refreshing page might help.");
});
+ it("writes a link note in a view of its own, and goes back to the actions", async () => {
+ expect(container.querySelector("textarea")).toBeNull();
+ await click("Link with a note");
+ const textArea = container.querySelector("textarea");
+ expect(textArea).not.toBeNull();
+ expect(document.activeElement).toBe(textArea);
+ expect(captureButtons()).toHaveLength(0);
+ expect(container.querySelector(".view-header h4")?.textContent).toBe("Link with a note");
+ expect(textArea?.placeholder).toBe("The first sentence becomes the note's title, the rest its text.");
+ expect(container.querySelector(".hint")?.textContent).toBe("Ctrl+Enter to save");
+
+ await click("Back");
+ expect(container.querySelector("textarea")).toBeNull();
+ expect(captureButtons()).toHaveLength(5);
+ expect(closeWindow).not.toHaveBeenCalled();
+ });
+
+ it("saves a link with a note on Ctrl+Enter", async () => {
+ await click("Link with a note");
+ const textArea = container.querySelector("textarea");
+
+ await act(() => {
+ if (!textArea) return;
+ textArea.value = "Read later. It has <b>tips</b>\nand more";
+ textArea.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ sendMessage.mockResolvedValueOnce(true);
+ await act(async () => {
+ textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true }));
+ });
+ expect(sendMessage).toHaveBeenCalledWith({
+ name: "save-link-with-note",
+ title: "Read later.",
+ content: "<p>It has &lt;b&gt;tips&lt;/b&gt;</p><p>and more</p>"
+ });
+ expect(closeWindow).toHaveBeenCalledOnce();
+ });
+
it("keeps the note open when it could not be saved, and keeps the page title on request", async () => {
- await click("Save link with a note");
+ await click("Link with a note");
const textArea = container.querySelector("textarea");
const keepTitle = container.querySelector<HTMLInputElement>("input[type=checkbox]");
expect(textArea).not.toBeNull();
@@ -137,6 +214,7 @@ describe("popup", () => {
keepTitle.click();
});
expect(keepTitle?.checked).toBe(true);
+ expect(textArea?.placeholder).toBe("The note's text.");
await act(async () => {
textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
@@ -165,39 +243,23 @@ describe("popup", () => {
expect(root.querySelector(".popup")).not.toBeNull();
root.remove();
});
+});
- it("saves a link with a note on Ctrl+Enter, and cancels it", async () => {
- expect(container.querySelector("textarea")).toBeNull();
- await click("Save link with a note");
- const textArea = container.querySelector("textarea");
- expect(textArea).not.toBeNull();
- expect(document.activeElement).toBe(textArea);
-
- await act(() => {
- if (!textArea) return;
- textArea.value = "Read later. It has <b>tips</b>\nand more";
- textArea.dispatchEvent(new Event("input", { bubbles: true }));
- });
- sendMessage.mockResolvedValueOnce(true);
- await act(async () => {
- textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true }));
- });
- expect(sendMessage).toHaveBeenCalledWith({
- name: "save-link-with-note",
- title: "Read later.",
- content: "<p>It has &lt;b&gt;tips&lt;/b&gt;</p><p>and more</p>"
- });
- expect(closeWindow).toHaveBeenCalledOnce();
-
- await click("Cancel");
- expect(container.querySelector("textarea")).toBeNull();
- expect(closeWindow).toHaveBeenCalledTimes(2);
+describe("shortcutsByCommand", () => {
+ it("keeps only the commands that have a shortcut", () => {
+ expect(shortcutsByCommand([
+ { name: "saveWholePage", shortcut: "Alt+Shift+S" },
+ { name: "saveTabs", shortcut: "" },
+ { name: "saveSelection" },
+ { shortcut: "Ctrl+Q" }
+ ])).toEqual({ saveWholePage: "Alt+Shift+S" });
});
});
describe("icons", () => {
it("draws each button's Boxicon inline, hidden from assistive technology", async () => {
vi.spyOn(console, "log").mockImplementation(() => {});
+ Object.assign(fakeBrowser.commands, { getAll: getAllCommands });
const container = document.createElement("div");
await act(() => render(<Popup />, container));
@@ -245,18 +307,39 @@ async function receive(message: object) {
});
}
-/** Clicks the button with the given label, or with that `aria-label` when it shows only an icon. */
+/** Lets the promises the effects start, such as reading the shortcuts, settle. */
+async function flush() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve));
+ });
+}
+
+/** The button with the given label, or with that `aria-label` when it shows only an icon. */
+function button(text: string) {
+ const found = [ ...container.querySelectorAll("button") ].find((b) => {
+ const label = b.querySelector(".action-label")?.textContent ?? b.textContent?.trim();
+ return label === text || b.getAttribute("aria-label") === text;
+ });
+ expect(found, text).toBeDefined();
+ return found;
+}
+
async function click(text: string) {
- const button = [ ...container.querySelectorAll("button") ]
- .find((b) => b.textContent?.trim() === text || b.getAttribute("aria-label") === text);
- expect(button, text).toBeDefined();
- await act(() => button?.click());
+ const target = button(text);
+ await act(() => target?.click());
+}
+
+function shortcutOf(text: string) {
+ return button(text)?.querySelector("kbd")?.textContent;
}
function captureButtons() {
- return [ ...container.querySelectorAll<HTMLButtonElement>(".capture-buttons button") ];
+ return [ ...container.querySelectorAll<HTMLButtonElement>(".capture-actions button") ];
}
-function statusText() {
- return container.querySelector(".connection > div")?.textContent?.replace("Status: ", "");
+function status() {
+ return {
+ dot: container.querySelector<HTMLElement>(".status-dot")?.className,
+ text: container.querySelector(".connection > span")?.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 74c9dba201..c3988bbabc 100644
--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md
@@ -25,6 +25,17 @@ The extension is available from the official browser web stores:
* save screenshot (with crop tool) from either popup or context menu
* create short text note from popup
+## The popup
+
+Clicking the extension's button in the browser toolbar opens its popup:
+
+* The header 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 the buttons for the extension's options and for this help page.
+* _Save whole page_ is the main action. Below it are _Crop screenshot_, _Visible area screenshot_, _Link with a note_ and _All tabs in window_ (which saves the links of every tab in the current window as a list). An action that has a keyboard shortcut shows it.
+* _Link with a 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.
+* 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 describes the connection, with a button to check it again.
+
## Location of clippings
Trilium will save these clippings as a new child note under a "clipper inbox" note.
@@ -52,7 +63,7 @@ To set custom shortcuts, follow the directions for your browser.
## Configuration
-The extension needs to connect to a running Trilium instance. By default, it looks for the desktop application on port 37840 of the local computer. If the desktop application runs on a different port (for example because it was started with the `TRILIUM_PORT` environment variable), enter that port in the extension's options. The extension checks for Trilium again every minute, or right away when pressing _check_ in its popup.
+The extension needs to connect to a running Trilium instance. By default, it looks for the desktop application on port 37840 of the local computer. If the desktop application runs on a different port (for example because it was started with the `TRILIUM_PORT` environment variable), enter that port in the extension's options. The extension checks for Trilium again every minute, or right away when pressing the refresh button at the bottom of its popup.
It's also possible to configure the [server](Server%20Installation.md) address if you don't run the desktop application, or want it to work without the desktop application running.