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(web-clipper): give "Link with a note" a title field of its own
Elian Doran8814767e7f91
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 370f0375ea..41eb7b54af 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@@ -51,10 +51,11 @@of the page), <em>Note</em> (a link with a note) and <em>Tabs</em> (saves thelinks of every tab in the current window as a list). Hovering over a buttonshows its full name and, if it has one, its keyboard shortcut.</li>- <li><em>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><em>Note</em> opens a small editor in place of the actions, to save a link+ to the page with a note about it. The note's title starts as the page's+ title and can be edited (left empty, it stays the page's title); the text+ below it becomes the note's content. 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 toopen the note in Trilium.</li><li>If Trilium cannot be found, the popup explains why instead of showingdiff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex 6a3cbe61dc..1448a29845 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -391,22 +391,39 @@ function TriliumNotFound() {}function LinkWithNoteForm({ onBack }: { onBack: () => void }) {+ const [ title, setTitle ] = useState("");+ const [ pageUrl, setPageUrl ] = useState<string>();const [ text, setText ] = useState("");- const [ keepTitle, setKeepTitle ] = useState(false);const textAreaRef = useRef<HTMLTextAreaElement>(null);- useEffect(() => textAreaRef.current?.focus(), []);+ useEffect(() => {+ textAreaRef.current?.focus();+ void browser.tabs.query({ active: true, currentWindow: true }).then(([ tab ]) => {+ setTitle(tab?.title ?? "");+ setPageUrl(tab?.url);+ });+ }, []);async function save() {- const { title, content } = parseLinkNote(text, keepTitle);- const result = await sendMessage({ name: "save-link-with-note", title, content: textToHtml(content) });+ const content = text.trim();+ const result = await sendMessage({+ name: "save-link-with-note",+ title: title.trim(),+ content: content ? textToHtml(content) : ""+ });if (result) {- setText("");window.close();}}+ function saveOnCtrlEnter(e: KeyboardEvent) {+ if (e.key === "Enter" && e.ctrlKey) {+ e.preventDefault();+ void save();+ }+ }+return (<div className="save-link-with-note"><div className="view-header">@@ -416,31 +433,31 @@ function LinkWithNoteForm({ onBack }: { onBack: () => void }) {<h4>Link with a note</h4></div>+ <div className="page-heading">+ <span className="page-icon"><Icon icon={Globe} /></span>+ <div className="page-heading-text">+ <input+ type="text"+ className="page-title"+ aria-label="Note title"+ placeholder="Note title"+ value={title}+ onInput={(e) => setTitle(e.currentTarget.value)}+ onKeyDown={saveOnCtrlEnter}+ />+ {pageUrl && <div className="page-meta">{new URL(pageUrl).hostname}</div>}+ </div>+ </div>+<textarearef={textAreaRef}rows={5}value={text}- placeholder={keepTitle- ? "The note's text."- : "The first sentence becomes the note's title, the rest its text."}+ placeholder="Your note about this page"onInput={(e) => setText(e.currentTarget.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && e.ctrlKey) {- e.preventDefault();- void save();- }- }}+ onKeyDown={saveOnCtrlEnter}/>- <label className="tn-checkbox">- <input- type="checkbox"- checked={keepTitle}- onChange={(e) => setKeepTitle(e.currentTarget.checked)}- />- {" "}Keep page title as note title- </label>-<button type="submit" className="btn btn-primary primary-action" onClick={save}><span className="action-label">Save</span><Shortcut keys="Ctrl+Enter" />@@ -566,30 +583,6 @@ async function sendMessage(message: object) {}}-/**- * 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 = textdiff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.cssindex 7dce482142..b4e2c7939a 100644--- a/apps/web-clipper/entrypoints/popup/popup.css+++ b/apps/web-clipper/entrypoints/popup/popup.css@@ -42,63 +42,63 @@ body {gap: 16px;}- .page-preview {+ .page-heading {display: flex;- flex-direction: column;- gap: 10px;- padding: 10px;- border-radius: 8px;- background: var(--card-background-color);-- .page-heading {- display: flex;- align-items: center;- gap: 8px;- }+ align-items: center;+ gap: 8px;+ }- .page-icon {- display: flex;- flex-shrink: 0;- align-items: center;- justify-content: center;- width: 40px;- height: 40px;- border-radius: 50%;- background: var(--note-icon-background-color);- color: var(--note-icon-color);+ .page-icon {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ width: 40px;+ height: 40px;+ border-radius: 50%;+ background: var(--note-icon-background-color);+ color: var(--note-icon-color);- svg.icon {- width: 22px;- height: 22px;- }+ svg.icon {+ width: 22px;+ height: 22px;}+ }- .page-heading-text {- display: flex;- flex-direction: column;- flex-grow: 1;- min-width: 0;- }+ .page-heading-text {+ display: flex;+ flex-direction: column;+ flex-grow: 1;+ min-width: 0;+ }- .page-title {- --input-background-color: transparent;+ .page-title {+ --input-background-color: transparent;- width: 100%;- padding: 0 6px;- border: 0;- border-radius: 6px;- font-size: 1.35em;- font-weight: 500;- }+ width: 100%;+ padding: 0 6px;+ border: 0;+ border-radius: 6px;+ font-size: 1.35em;+ font-weight: 500;+ }- .page-meta {- overflow: hidden;- padding-inline: 6px;- color: var(--muted-text-color);- font-size: 0.85em;- white-space: nowrap;- text-overflow: ellipsis;- }+ .page-meta {+ overflow: hidden;+ padding-inline: 6px;+ color: var(--muted-text-color);+ font-size: 0.85em;+ white-space: nowrap;+ text-overflow: ellipsis;+ }++ .page-preview {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 10px;+ border-radius: 8px;+ background: var(--card-background-color);.clip-mode {display: flex;diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex 081a037329..0b0635d155 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -6,7 +6,7 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";-import { basicIcon, parseLinkNote, Popup, previewDocument, shortcutsByCommand, textToHtml } from "./main";+import { basicIcon, 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.";@@ -27,7 +27,7 @@ const PAGE = {clipType: "page",labels: { publishedDate: "2024-05-01" }};-const tabsQuery = vi.fn(async (): Promise<{ id?: number }[]> => [ { id: 7 } ]);+const tabsQuery = vi.fn(async (): Promise<{ id?: number, title?: string, url?: string }[]> => [ { id: 7 } ]);const SELECTION = {title: "Page title",content: `<p>A quote</p><img src="i2">`,@@ -328,15 +328,22 @@ describe("popup", () => {it("writes a link note in a view of its own, and goes back to the actions", async () => {expect(container.querySelector("textarea")).toBeNull();+ tabsQuery.mockResolvedValueOnce([ { id: 7, title: "A page", url: "https://example.com/post" } ]);await click("Link with a note");+ await flush();const textArea = container.querySelector("textarea");expect(textArea).not.toBeNull();expect(document.activeElement).toBe(textArea);+ expect(textArea?.placeholder).toBe("Your note about this page");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.");+ const heading = container.querySelector(".save-link-with-note .page-heading");+ expect(heading).not.toBeNull();+ expect(heading?.querySelector(".page-icon svg path")).not.toBeNull();+ expect(heading?.querySelector<HTMLInputElement>(".page-title")?.value).toBe("A page");+ expect(heading?.querySelector(".page-meta")?.textContent).toBe("example.com");+ expect(container.querySelector("input[type=checkbox]")).toBeNull();expect(shortcutOf("Save")).toEqual({ text: "Ctrl+Enter", keys: [ "Ctrl", "Enter" ] });- expect(container.querySelector(".hint")).toBeNull();await click("Back");expect(container.querySelector("textarea")).toBeNull();@@ -344,56 +351,44 @@ describe("popup", () => {expect(closeWindow).not.toHaveBeenCalled();});- it("saves a link with a note on Ctrl+Enter", async () => {+ it("saves the title and the text as they are, on Ctrl+Enter from either field", async () => {+ tabsQuery.mockResolvedValueOnce([ { id: 7, title: "A page", url: "https://example.com/post" } ]);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 }));- });+ await flush();+ await type(".save-link-with-note .page-title", " Read later. Soon ");+ await type(".save-link-with-note textarea", " It has <b>tips</b>\nand more ");sendMessage.mockResolvedValueOnce(true);await act(async () => {- textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true }));+ container.querySelector(".save-link-with-note textarea")+ ?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true }));});expect(sendMessage).toHaveBeenCalledWith({name: "save-link-with-note",- title: "Read later.",+ title: "Read later. Soon",content: "<p>It has <b>tips</b></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 () => {+ it("keeps the note open when it could not be saved, and leaves an empty title to the page", async () => {+ tabsQuery.mockResolvedValueOnce([ {} ]);await click("Link with a note");- const textArea = container.querySelector("textarea");- const keepTitle = container.querySelector<HTMLInputElement>("input[type=checkbox]");- expect(textArea).not.toBeNull();- expect(keepTitle?.checked).toBe(false);-- await act(() => {- if (!textArea || !keepTitle) return;- textArea.value = "First. Second.";- textArea.dispatchEvent(new Event("input", { bubbles: true }));- keepTitle.click();- });- expect(keepTitle?.checked).toBe(true);- expect(textArea?.placeholder).toBe("The note's text.");+ await flush();+ const title = container.querySelector<HTMLInputElement>(".save-link-with-note .page-title");+ expect(title?.value).toBe("");+ expect(container.querySelector(".save-link-with-note .page-meta")).toBeNull();await act(async () => {- textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ title?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));});expect(sendMessage).not.toHaveBeenCalledWith(expect.objectContaining({ name: "save-link-with-note" }));sendMessage.mockResolvedValueOnce(undefined);- await click("Save");- expect(sendMessage).toHaveBeenCalledWith({- name: "save-link-with-note",- title: "",- content: "<p>First. Second.</p>"+ await act(async () => {+ title?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", ctrlKey: true, bubbles: true }));});- expect(textArea?.value).toBe("First. Second.");+ expect(sendMessage).toHaveBeenCalledWith({ name: "save-link-with-note", title: "", content: "" });+ expect(container.querySelector(".save-link-with-note")).not.toBeNull();expect(closeWindow).not.toHaveBeenCalled();});@@ -468,16 +463,6 @@ describe("icons", () => {});});-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 & <b></p><p>c</p>");diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 99ce97792c..21576144c1 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -32,7 +32,7 @@ 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. 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.* If text is selected on the page, the preview shows the selection instead, and _Save selection_ saves it into the note of that page's clippings, as the context menu does. When the page also has an article, a switch above the preview chooses between _Selection_ and _Whole page_. A selection can be saved even on a page that has no article.* 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.+* _Note_ opens a small editor in place of the actions, to save a link to the page with a note about it. The note's title starts as the page's title and can be edited (left empty, it stays the page's title); the text below it becomes the note's content. 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 shows whether the extension is connected to Trilium, as a colored dot (green when connected, amber when the versions are not compatible, red when Trilium was not found) next to a description of the connection, followed by the buttons for the extension's options and for this help page. A button to check the connection again appears next to them when hovering over the bar, and stays visible while Trilium cannot be reached or is not compatible.