Skip to content

Build your personal knowledge base with Trilium Notes

refactor(web-clipper): rewrite the popup in Preact

Elian Doran8b1679ff7491
diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
index 2d3d3e28f9..821ee23c58 100644
--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
@@ -1,6 +1,6 @@
const PROTOCOL_VERSION_MAJOR = 1;
-type TriliumSearchStatus = {
+export type TriliumSearchStatus = {
status: "searching";
} | {
status: "not-found"
@@ -18,7 +18,7 @@ type TriliumSearchStatus = {
triliumMajor: number;
};
-type TriliumSearchNoteStatus = {
+export type TriliumSearchNoteStatus = {
status: "not-found",
noteId: null
} | {
diff --git a/apps/web-clipper/entrypoints/popup/index.html b/apps/web-clipper/entrypoints/popup/index.html
index 207d6433cb..03dc61baea 100644
--- a/apps/web-clipper/entrypoints/popup/index.html
+++ b/apps/web-clipper/entrypoints/popup/index.html
@@ -2,51 +2,13 @@
<html>
<head>
- <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
- <meta content="utf-8" http-equiv="encoding">
- <link rel="stylesheet" href="popup.css"/>
+ <meta charset="utf-8">
</head>
<body>
- <div style="display: flex; justify-content: space-between; vertical-align: middle;">
- <h3>Trilium Web Clipper</h3>
-
+ <div id="root"></div>
- <div style="position: relative; top: 6px;">
- <button class="button" id="show-options-button">Options</button>
-
- <button class="button" id="show-help-button">Help</button>
- </div>
- </div>
- <div id="already-visited"></div>
-
- <button class="button full needs-connection" id="save-cropped-screenshot-button">Crop screenshot</button>
- <button class="button full needs-connection" id="save-whole-screenshot-button">Save whole screenshot</button>
- <button class="button full needs-connection" id="save-whole-page-button">Save whole page</button>
- <button class="button full needs-connection" id="save-link-with-note-button">Save link with a note</button>
- <button class="button full needs-connection" id="save-tabs-button">Save window's tabs as a list</button>
-
- <div id="save-link-with-note-wrapper">
- <textarea id="save-link-with-note-textarea" rows="5"></textarea>
-
- <div>
- <input type="checkbox" id="keep-title-checkbox" name="keep-title-checkbox" value="Bike">
- <label for="keep-title-checkbox">Keep page title as note title</label><br>
- </div>
- <div style="display: flex;">
- <button type="submit" class="button wide" id="save-button">Save</button>
-
- <button type="submit" class="button wide" id="cancel-button">Cancel</button>
- </div>
- </div>
-
- <div style="margin-top: 15px;">
- <button class="button" id="check-connection-button">check</button>
-
- <div>Status: <span id="connection-status">unknown</span></div>
- </div>
-
- <script type="module" src="popup.ts"></script>
+ <script type="module" src="main.tsx"></script>
</body>
</html>
diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsx
new file mode 100644
index 0000000000..0dda05aae0
--- /dev/null
+++ b/apps/web-clipper/entrypoints/popup/main.tsx
@@ -0,0 +1,243 @@
+import "./popup.css";
+
+import { render } from "preact";
+import { useEffect, useRef, useState } from "preact/hooks";
+
+import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background/trilium_server_facade";
+
+const HELP_URL = "https://docs.triliumnotes.org/user-guide/setup/web-clipper";
+
+type PopupMessage = {
+ name: "trilium-search-status";
+ triliumSearch?: TriliumSearchStatus;
+} | {
+ name: "trilium-previously-visited";
+ searchNote: TriliumSearchNoteStatus;
+};
+
+const root = document.getElementById("root");
+if (root) {
+ render(<Popup />, root);
+}
+
+export function Popup() {
+ const [ searchStatus, setSearchStatus ] = useState<TriliumSearchStatus>();
+ const [ clippedNoteId, setClippedNoteId ] = useState<string | null>(null);
+ const [ isWritingNote, setIsWritingNote ] = useState(false);
+
+ useEffect(() => {
+ function onMessage(message: PopupMessage) {
+ if (message.name === "trilium-search-status") {
+ setSearchStatus(message.triliumSearch);
+
+ if (message.triliumSearch && isConnected(message.triliumSearch)) {
+ void sendMessage({ name: "trigger-trilium-search-note-url" });
+ }
+ } else if (message.name === "trilium-previously-visited") {
+ const { searchNote } = message;
+ setClippedNoteId(searchNote.status === "found" ? searchNote.noteId : null);
+ }
+ }
+
+ browser.runtime.onMessage.addListener(onMessage);
+ void sendMessage({ name: "send-trilium-search-status" });
+
+ 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();
+ }
+
+ return (
+ <div className="popup">
+ <div className="popup-header">
+ <h3>Trilium Web Clipper</h3>
+
+ <div className="popup-header-buttons">
+ <button className="button" onClick={() => browser.runtime.openOptionsPage()}>Options</button>
+ <button className="button" onClick={() => window.open(HELP_URL, "_blank")}>Help</button>
+ </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>
+ </>
+ )}
+ </div>
+
+ <button className="button full" {...needsConnection} onClick={() => sendAndClose("save-cropped-screenshot")}>
+ Crop screenshot
+ </button>
+ <button className="button full" {...needsConnection} onClick={() => sendAndClose("save-whole-screenshot")}>
+ Save whole screenshot
+ </button>
+ <button className="button full" {...needsConnection} onClick={() => sendMessage({ name: "save-whole-page" })}>
+ Save whole page
+ </button>
+ <button className="button full" {...needsConnection} onClick={() => setIsWritingNote(true)}>
+ Save link with a note
+ </button>
+ <button className="button full" {...needsConnection} onClick={() => sendMessage({ name: "save-tabs" })}>
+ Save window's tabs as a list
+ </button>
+
+ {isWritingNote && <LinkWithNoteForm onCancel={() => setIsWritingNote(false)} />}
+
+ <div className="connection">
+ <button className="button check-connection-button" onClick={() => sendMessage({ name: "trigger-trilium-search" })}>
+ check
+ </button>
+
+ <div>Status: <ConnectionStatus status={searchStatus} /></div>
+ </div>
+ </div>
+ );
+}
+
+function LinkWithNoteForm({ onCancel }: { onCancel: () => void }) {
+ const [ text, setText ] = useState("");
+ const [ keepTitle, setKeepTitle ] = useState(false);
+ const textAreaRef = useRef<HTMLTextAreaElement>(null);
+
+ useEffect(() => textAreaRef.current?.focus(), []);
+
+ async function save() {
+ const { title, content } = parseLinkNote(text, keepTitle);
+ const result = await sendMessage({ name: "save-link-with-note", title, content: textToHtml(content) });
+
+ if (result) {
+ setText("");
+ window.close();
+ }
+ }
+
+ return (
+ <div className="save-link-with-note">
+ <textarea
+ ref={textAreaRef}
+ rows={5}
+ value={text}
+ onInput={(e) => setText(e.currentTarget.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && e.ctrlKey) {
+ e.preventDefault();
+ void save();
+ }
+ }}
+ />
+
+ <div>
+ <label>
+ <input
+ type="checkbox"
+ checked={keepTitle}
+ onChange={(e) => setKeepTitle(e.currentTarget.checked)}
+ />
+ {" "}Keep page title as note title
+ </label>
+ </div>
+ <div className="save-link-with-note-buttons">
+ <button type="submit" className="button wide save-button" onClick={save}>Save</button>
+ <button
+ type="submit"
+ className="button wide"
+ onClick={() => {
+ onCancel();
+ window.close();
+ }}
+ >Cancel</button>
+ </div>
+ </div>
+ );
+}
+
+function ConnectionStatus({ status }: { status: TriliumSearchStatus | undefined }) {
+ switch (status?.status) {
+ case undefined:
+ return <span>unknown</span>;
+ case "searching":
+ return <span>searching</span>;
+ 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>
+ );
+ }
+ case "found-desktop":
+ return <span className="status-ok">Connected on port {status.port}</span>;
+ case "found-server":
+ return <span className="status-ok" title={`Connected to ${status.url}`}>Connected to the server</span>;
+ }
+}
+
+/** A version mismatch counts as connected, so the buttons stay enabled and report it on use. */
+function isConnected(status: TriliumSearchStatus) {
+ return status.status === "found-desktop" || status.status === "found-server" || status.status === "version-mismatch";
+}
+
+async function sendMessage(message: object) {
+ try {
+ console.log("Sending message", message);
+ return await browser.runtime.sendMessage(message);
+ } catch (e) {
+ console.log("Calling browser runtime failed:", e);
+ alert("Calling browser runtime failed. Refreshing page might help.");
+ }
+}
+
+/**
+ * Splits the text of a link note into the note's title and content: the first sentence or line is
+ * the title, unless the page title is kept, in which case all of the text is content.
+ */
+export function parseLinkNote(text: string, keepTitle: boolean) {
+ const trimmed = text.trim();
+
+ if (!trimmed) {
+ return { title: "", content: "" };
+ }
+
+ if (keepTitle) {
+ return { title: "", content: trimmed };
+ }
+
+ const match = /^(.*?)([.?!]\s|\n)/.exec(trimmed);
+ if (!match) {
+ return { title: trimmed, content: "" };
+ }
+
+ const title = match[0].trim();
+ return { title, content: trimmed.substring(title.length).trim() };
+}
+
+/** Escapes plain text as HTML, with one paragraph per line. */
+export function textToHtml(text: string) {
+ const escaped = text
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+
+ return `<p>${escaped.replaceAll("\n", "</p><p>")}</p>`;
+}
diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.css
index 7d1258a1ce..0466910bcf 100644
--- a/apps/web-clipper/entrypoints/popup/popup.css
+++ b/apps/web-clipper/entrypoints/popup/popup.css
@@ -1,48 +1,80 @@
body {
- width: 300px;
- font-size: 12px;
- font-family: sans-serif;
+ width: 300px;
+ font-size: 12px;
+ font-family: sans-serif;
}
-.button {
- margin: 3% auto;
- padding: 4px;
- text-align: center;
- border: 1px solid #ccc;
- border-radius: 3px;
- background-color: #eee;
- cursor: pointer;
- color: black;
-}
+.popup {
+ .popup-header {
+ display: flex;
+ justify-content: space-between;
+ }
-.wide {
- min-width: 8em;
-}
+ .popup-header-buttons {
+ position: relative;
+ top: 6px;
+ }
-.full {
- display: block;
- width: 100%;
-}
+ .button {
+ margin: 3% auto;
+ padding: 4px;
+ text-align: center;
+ border: 1px solid #ccc;
+ border-radius: 3px;
+ background-color: #eee;
+ cursor: pointer;
+ color: black;
-#save-link-with-note-wrapper {
- display: none;
-}
+ &[disabled] {
+ color: #aaa;
+ }
+ }
-#save-link-with-note-textarea {
- width: 100%;
-}
+ .wide {
+ min-width: 8em;
+ }
-#save-button {
- border-color: #0062cc;
- background-color: #0069d9;
- color: white;
-}
+ .full {
+ display: block;
+ width: 100%;
+ }
-#check-connection-button {
- float: right;
- margin-top: -6px;
-}
+ .already-visited a {
+ color: lightskyblue;
+ }
+
+ .save-link-with-note textarea {
+ width: 100%;
+ }
+
+ .save-link-with-note-buttons {
+ display: flex;
+ }
+
+ .save-button {
+ border-color: #0062cc;
+ background-color: #0069d9;
+ color: white;
+ }
+
+ .connection {
+ margin-top: 15px;
+ }
+
+ .check-connection-button {
+ float: right;
+ margin-top: -6px;
+ }
+
+ .status-ok {
+ color: green;
+ }
+
+ .status-warning {
+ color: orange;
+ }
-button[disabled] {
- color: #aaa;
+ .status-error {
+ color: red;
+ }
}
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
new file mode 100644
index 0000000000..16e4e404f8
--- /dev/null
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -0,0 +1,164 @@
+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 { parseLinkNote, Popup, textToHtml } from "./main";
+
+const sendMessage = vi.fn(async (_message: object): Promise<unknown> => undefined);
+const openOptionsPage = vi.fn(async () => {});
+const closeWindow = vi.fn();
+let container: HTMLElement;
+
+describe("popup", () => {
+ beforeEach(async () => {
+ fakeBrowser.reset();
+ Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });
+ vi.spyOn(window, "close").mockImplementation(closeWindow);
+ vi.spyOn(console, "log").mockImplementation(() => {});
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ await act(() => render(<Popup />, container));
+ });
+
+ afterEach(async () => {
+ await act(() => render(null, container));
+ container.remove();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ });
+
+ it("asks for the connection status and shows it", async () => {
+ expect(sendMessage).toHaveBeenCalledWith({ name: "send-trilium-search-status" });
+ expect(statusText()).toBe("unknown");
+ 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(captureButtons().every((button) => !button.disabled && !button.title)).toBe(true);
+ expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search-note-url" });
+
+ await receive({
+ 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");
+
+ 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(captureButtons().every((button) => !button.disabled)).toBe(true);
+
+ await receive({ name: "trilium-search-status", triliumSearch: { status: "searching" } });
+ expect(statusText()).toBe("searching");
+ expect(captureButtons().every((button) => button.disabled)).toBe(true);
+ });
+
+ it("offers to open a page that was already clipped", async () => {
+ 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.");
+
+ await act(() => container.querySelector<HTMLAnchorElement>(".already-visited a")?.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("");
+ });
+
+ it("sends the capture actions, closing the popup for screenshots", async () => {
+ await click("Crop screenshot");
+ expect(sendMessage).toHaveBeenCalledWith({ name: "save-cropped-screenshot" });
+ await click("Save whole 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");
+ expect(sendMessage).toHaveBeenCalledWith({ name: "save-tabs" });
+ await click("check");
+ expect(sendMessage).toHaveBeenCalledWith({ name: "trigger-trilium-search" });
+ await click("Options");
+ expect(openOptionsPage).toHaveBeenCalledOnce();
+ expect(closeWindow).toHaveBeenCalledTimes(2);
+ });
+
+ 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("parseLinkNote", () => {
+ it("takes the first sentence or line as the title, unless the page title is kept", () => {
+ expect(parseLinkNote(" ", false)).toEqual({ title: "", content: "" });
+ expect(parseLinkNote(" Great read! Worth it. ", false)).toEqual({ title: "Great read!", content: "Worth it." });
+ expect(parseLinkNote("First line\nsecond line", false)).toEqual({ title: "First line", content: "second line" });
+ expect(parseLinkNote("Just a title", false)).toEqual({ title: "Just a title", content: "" });
+ expect(parseLinkNote(" Great read! Worth it. ", true)).toEqual({ title: "", content: "Great read! Worth it." });
+ });
+});
+
+describe("textToHtml", () => {
+ it("escapes the text and makes a paragraph of each line", () => {
+ expect(textToHtml("a & <b>\nc")).toBe("<p>a &amp; &lt;b&gt;</p><p>c</p>");
+ expect(textToHtml("")).toBe("<p></p>");
+ });
+});
+
+async function receive(message: object) {
+ await act(async () => {
+ await fakeBrowser.runtime.onMessage.trigger(message, {}, () => {});
+ });
+}
+
+async function click(text: string) {
+ const button = [ ...container.querySelectorAll("button") ].find((b) => b.textContent?.trim() === text);
+ expect(button, text).toBeDefined();
+ await act(() => button?.click());
+}
+
+function captureButtons() {
+ return [ ...container.querySelectorAll<HTMLButtonElement>("button.full") ];
+}
+
+function statusText() {
+ return container.querySelector(".connection > div")?.textContent?.replace("Status: ", "");
+}
diff --git a/apps/web-clipper/entrypoints/popup/popup.ts b/apps/web-clipper/entrypoints/popup/popup.ts
deleted file mode 100644
index c68e7e6af9..0000000000
--- a/apps/web-clipper/entrypoints/popup/popup.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import $ from "cash-dom";
-
-import { createLink } from "@/utils";
-
-async function sendMessage(message: object) {
- try {
- console.log("Sending message", message);
- return await browser.runtime.sendMessage(message);
- }
- catch (e) {
- console.log("Calling browser runtime failed:", e);
-
- alert("Calling browser runtime failed. Refreshing page might help.");
- }
-}
-
-const $showOptionsButton = $("#show-options-button");
-const $saveCroppedScreenShotButton = $("#save-cropped-screenshot-button");
-const $saveWholeScreenShotButton = $("#save-whole-screenshot-button");
-const $saveWholePageButton = $("#save-whole-page-button");
-const $saveTabsButton = $("#save-tabs-button");
-
-$showOptionsButton.on("click", () => browser.runtime.openOptionsPage());
-
-$saveCroppedScreenShotButton.on("click", () => {
- sendMessage({name: 'save-cropped-screenshot'});
-
- window.close();
-});
-
-$saveWholeScreenShotButton.on("click", () => {
- sendMessage({name: 'save-whole-screenshot'});
-
- window.close();
-});
-
-$saveWholePageButton.on("click", () => sendMessage({name: 'save-whole-page'}));
-
-$saveTabsButton.on("click", () => sendMessage({name: 'save-tabs'}));
-
-const $saveLinkWithNoteWrapper = $("#save-link-with-note-wrapper");
-const $textNote = $("#save-link-with-note-textarea");
-const $keepTitle = $("#keep-title-checkbox");
-
-$textNote.on('keypress', (event) => {
- if ((event.which === 10 || event.which === 13) && event.ctrlKey) {
- saveLinkWithNote();
- return false;
- }
-
- return true;
-});
-
-$("#save-link-with-note-button").on("click", () => {
- $saveLinkWithNoteWrapper.show();
-
- $textNote[0]?.focus();
-});
-
-$("#cancel-button").on("click", () => {
- $saveLinkWithNoteWrapper.hide();
- $textNote.val("");
-
- window.close();
-});
-
-async function saveLinkWithNote() {
- const textNoteVal = ($textNote.val() as string | undefined ?? "").trim();
- let title, content;
-
- if (!textNoteVal) {
- title = '';
- content = '';
- }
- else if (($keepTitle[0] as HTMLInputElement | undefined)?.checked){
- title = '';
- content = textNoteVal;
- }
- else {
- const match = /^(.*?)([.?!]\s|\n)/.exec(textNoteVal);
-
- if (match) {
- title = match[0].trim();
- content = textNoteVal.substr(title.length).trim();
- }
- else {
- title = textNoteVal;
- content = '';
- }
- }
-
- content = escapeHtml(content);
-
- const result = await sendMessage({name: 'save-link-with-note', title, content});
-
- if (result) {
- $textNote.val('');
-
- window.close();
- }
-}
-
-$("#save-button").on("click", saveLinkWithNote);
-
-$("#show-help-button").on("click", () => {
- window.open("https://docs.triliumnotes.org/user-guide/setup/web-clipper", '_blank');
-});
-
-function escapeHtml(string) {
- const pre = document.createElement('pre');
- const text = document.createTextNode(string);
- pre.appendChild(text);
-
- const htmlWithPars = pre.innerHTML.replace(/\n/g, "</p><p>");
-
- return `<p>${htmlWithPars}</p>`;
-}
-
-const $connectionStatus = $("#connection-status");
-const $needsConnection = $(".needs-connection");
-const $alreadyVisited = $("#already-visited");
-
-browser.runtime.onMessage.addListener(request => {
- if (request.name === 'trilium-search-status') {
- const {triliumSearch} = request;
-
- let statusText = triliumSearch.status;
- let isConnected;
-
- if (triliumSearch.status === 'not-found') {
- statusText = `<span style="color: red">Not found</span>`;
- isConnected = false;
- }
- else if (triliumSearch.status === 'version-mismatch') {
- const whatToUpgrade = triliumSearch.extensionMajor > triliumSearch.triliumMajor ? "Trilium Notes" : "this extension";
-
- statusText = `<span style="color: orange">Trilium instance found, but it is not compatible with this extension version. Please update ${whatToUpgrade} to the latest version.</span>`;
- isConnected = true;
- }
- else if (triliumSearch.status === 'found-desktop') {
- statusText = `<span style="color: green">Connected on port ${triliumSearch.port}</span>`;
- isConnected = true;
- }
- else if (triliumSearch.status === 'found-server') {
- statusText = `<span style="color: green" title="Connected to ${triliumSearch.url}">Connected to the server</span>`;
- isConnected = true;
- }
-
- $connectionStatus.html(statusText);
-
- if (isConnected) {
- $needsConnection.removeAttr("disabled");
- $needsConnection.removeAttr("title");
- browser.runtime.sendMessage({name: "trigger-trilium-search-note-url"});
- }
- else {
- $needsConnection.attr("disabled", "disabled");
- $needsConnection.attr("title", "This action can't be performed without active connection to Trilium.");
- }
- }
- else if (request.name == "trilium-previously-visited"){
- const {searchNote} = request;
- if (searchNote.status === 'found'){
- const a = createLink({name: 'openNoteInTrilium', noteId: searchNote.noteId},
- "Open in Trilium.");
- $alreadyVisited.text(`Web page already clipped. `);
- $alreadyVisited[0]?.appendChild(a);
- }else{
- $alreadyVisited.html('');
- }
-
-
- }
-});
-
-const $checkConnectionButton = $("#check-connection-button");
-
-$checkConnectionButton.on("click", () => {
- browser.runtime.sendMessage({
- name: "trigger-trilium-search"
- });
-});
-
-$(() => browser.runtime.sendMessage({name: "send-trilium-search-status"}));