Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(clipper): show the page's description atop the preview (#802)
Elian Doran10e303a3437c
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 092d518fd7..847306ca62 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@@ -32,8 +32,8 @@<ul><li><p>The popup shows what will be saved from the current page: the note's title,- which can be edited before saving, the website, the page's description- if it has one, and below them a preview. A switch above the preview chooses+ which can be edited before saving, the website, and below them a preview,+ which starts with the page's description. A switch above the preview chooseswhat to save, among what the page offers:</p><ul><li><em>Selection</em>, when text is selected on the page: <em>Save selection</em> saves@@ -46,12 +46,13 @@saves a link to the page with that note. Left empty, the title stays thepage's title.</li></ul>- <p>The description comes from the page's <code>description</code> meta tag,- or the one it gives social sites. It can be edited or cleared before saving,- and is saved in the <code>#pageDescription</code> label of the note. Clippings- saved with the keyboard shortcuts or the context menu, screenshots and- images included, get the description as the page gives it. Each clipping- that brings a description updates the label.</p>+ <p>The description, marked by the <span class="tn-icon bx bx-align-left"></span> icon,+ comes from the page's <code>description</code> meta tag, or the one it gives+ social sites. It can be edited or cleared before saving, or written in+ when the page has none, and is saved in the <code>#pageDescription</code> label+ of the note. Clippings saved with the keyboard shortcuts or the context+ menu, screenshots and images included, get the description as the page+ gives it. Each clipping that brings a description updates the label.</p><p>The popup opens on the selection if there is one, otherwise on the article.On a page with no article (Readability cannot find one) and no selection,it opens on <em>Bookmark</em> and says the page has no article. The keyboarddiff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex 473b9a0b18..4926755cf5 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, IconPack } from "@boxicons/js";+import AlignLeft from "@boxicons/js/icons/AlignLeft";import Article from "@boxicons/js/icons/Article";import Bookmark from "@boxicons/js/icons/Bookmark";import Cog from "@boxicons/js/icons/Cog";@@ -324,8 +325,8 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {const mode = chosenMode && modes.includes(chosenMode) ? chosenMode : modes[0];const clip = mode === "selection" ? selection : mode === "page" ? article : undefined;const shownTitle = title ?? (article ?? selection)?.title ?? tab?.title ?? "";- const shownDescription = description ?? tab?.description;- const savedDescription = shownDescription?.replace(/\s+/g, " ").trim();+ const shownDescription = description ?? tab?.description ?? "";+ const savedDescription = shownDescription.replace(/\s+/g, " ").trim();useEffect(() => {if (mode === "note") textAreaRef.current?.focus();@@ -344,9 +345,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {}function saveClip(content: SelectedContent) {- const labels = savedDescription === undefined- ? content.labels- : withDescription(content.labels, savedDescription);+ const labels = withDescription(content.labels, savedDescription);const titled = { ...content, title: shownTitle.trim() || content.title, ...(labels && { labels }) };void sendMessage(mode === "selection"? { name: "save-selection", selection: titled }@@ -392,16 +391,6 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {{new URL(pageUrl).hostname}{published && ` · Published ${published}`}</div>)}- {shownDescription !== undefined && (- <textarea- className="page-description"- aria-label="Page description"- rows={2}- value={shownDescription}- onInput={(e) => onDraftChange({ ...draft, description: e.currentTarget.value })}- onKeyDown={saveNoteOnCtrlEnter}- />- )}</div></div>)}@@ -421,6 +410,25 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {)}<div className="page-body">+ {mode && (+ <div className="page-description-row">+ <span+ className="page-description-icon"+ title="The page's description. It is saved in the #pageDescription label of the note."+ >+ <Icon icon={AlignLeft} />+ </span>+ <textarea+ className="page-description"+ aria-label="Page description"+ placeholder="Add a description"+ rows={2}+ value={shownDescription}+ onInput={(e) => onDraftChange({ ...draft, description: e.currentTarget.value })}+ onKeyDown={saveNoteOnCtrlEnter}+ />+ </div>+ )}{mode === "note" && (<textarearef={textAreaRef}@@ -431,7 +439,15 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {onKeyDown={saveNoteOnCtrlEnter}/>)}- {clip && <iframe className="page-content" title="Preview of the page" sandbox="" srcDoc={previewDocument(clip)} />}+ {clip && (+ <iframe+ className="page-content"+ title="Preview of the page"+ sandbox="allow-same-origin"+ srcDoc={previewDocument(clip)}+ onLoad={(e) => fitToContent(e.currentTarget)}+ />+ )}{!mode && <div className="page-preview-placeholder">Reading the page…</div>}</div>@@ -449,10 +465,20 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {);}-/** A clip's labels with `#pageDescription` as the user left it, or without one when it was cleared. */+/** A clip's labels with `#pageDescription` as the user left it, or without one when it is empty. */function withDescription(labels: Record<string, string> | undefined, description: string) {const { pageDescription: _, ...others } = labels ?? {};- return description ? { ...others, pageDescription: description } : others;+ return description ? { ...others, pageDescription: description } : labels && others;+}++/**+ * Makes the preview as tall as the page it shows, so that the page scrolls in `.page-body` together+ * with the description above it. `allow-same-origin` lets the popup read the height; the sandbox+ * still runs no script.+ */+function fitToContent(frame: HTMLIFrameElement) {+ const height = frame.contentDocument?.documentElement.scrollHeight;+ if (height) frame.style.height = `${height}px`;}/** The modes the page offers, the default first: the selection, then the article, then a note. */@@ -577,7 +603,7 @@ export function previewDocument({ content, images }: Pick<ExtractedPage, "contenimg.setAttribute("src", image.src);}}- // An empty `sandbox` still lets the frame navigate itself: through a link, which the keyboard+ // The sandbox still lets the frame navigate itself: through a link, which the keyboard// can follow, or through a `<meta http-equiv="refresh">`.for (const link of doc.querySelectorAll("a[href], area[href]")) {link.removeAttribute("href");diff --git a/apps/web-clipper/entrypoints/popup/popup.css b/apps/web-clipper/entrypoints/popup/popup.cssindex e0ff50729e..01d61527cc 100644--- a/apps/web-clipper/entrypoints/popup/popup.css+++ b/apps/web-clipper/entrypoints/popup/popup.css@@ -130,23 +130,64 @@ body {}.page-body {- position: relative;- overflow: hidden;+ display: flex;+ flex-direction: column;+ height: 240px;+ overflow-y: auto;border-radius: 6px;background: var(--main-background-color);&:has(.page-content)::after {content: "";- position: absolute;- inset: auto 0 0;+ flex: none;+ position: sticky;+ bottom: 0;height: 24px;+ margin-top: -24px;background: linear-gradient(transparent, var(--main-background-color));pointer-events: none;}}+ .page-description-row {+ display: flex;+ flex: none;+ align-items: flex-start;+ gap: 4px;+ padding: 6px 8px 6px 6px;+ border-bottom: 1px solid var(--main-border-color);+ }++ .page-description-icon {+ display: flex;+ flex: none;+ padding: 3px 2px;+ color: var(--muted-text-color);+ cursor: help;++ svg.icon {+ width: 16px;+ height: 16px;+ }+ }++ .page-description {+ --input-background-color: transparent;++ flex-grow: 1;+ min-width: 0;+ padding: 2px 4px;+ border: 0;+ border-radius: 4px;+ color: var(--muted-text-color);+ font-size: 0.85em;+ field-sizing: content;+ resize: none;+ }+.page-content {display: block;+ flex: none;width: 100%;height: 200px;border: 0;@@ -159,8 +200,8 @@ body {--input-focus-background: transparent;display: block;+ flex: 1 0 120px;width: 100%;- height: 200px;padding: 8px;border: 0;border-radius: 6px;@@ -172,19 +213,6 @@ body {}}- .page-description {- --input-background-color: transparent;-- display: block;- width: 100%;- padding: 2px 6px;- border: 0;- border-radius: 6px;- color: var(--muted-text-color);- font-size: 0.85em;- resize: none;- }-.clip-hint {padding-inline: 6px;color: var(--muted-text-color);@@ -194,8 +222,8 @@ body {.page-preview-placeholder {display: flex;align-items: center;+ flex-grow: 1;justify-content: center;- height: 120px;padding: 12px;color: var(--muted-text-color);text-align: center;diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex 2826fcd97e..31ca796c3a 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -215,8 +215,10 @@ describe("popup", () => {expect(heading?.querySelector<HTMLInputElement>(".page-title")?.value).toBe("An article");expect(heading?.querySelector(".page-meta")?.textContent).toBe("example.com · Published 2024-05-01");const frame = container.querySelector<HTMLIFrameElement>(".page-body iframe.page-content");- expect(frame?.getAttribute("sandbox")).toBe("");+ expect(frame?.getAttribute("sandbox")).toBe("allow-same-origin");expect(frame?.getAttribute("srcdoc")).toBe(previewDocument(PAGE));+ expect([ ...container.querySelector(".page-body")?.children ?? [] ].map((part) => part.className))+ .toEqual([ "page-description-row", "page-content" ]);expect(button("Save page to Trilium")?.disabled).toBe(false);});@@ -258,7 +260,7 @@ describe("popup", () => {expect(container.querySelector(".no-items")).toBeNull();expect(container.querySelector(".clip-mode")).toBeNull();expect(container.querySelector(".clip-hint")?.textContent).toBe("This page has no article; save it as a bookmark.");- expect(document.activeElement).toBe(container.querySelector(".page-body textarea"));+ expect(document.activeElement).toBe(container.querySelector(".page-body .note-text"));expect(container.querySelector(".page-meta")).toBeNull();expect(button("Save bookmark")?.disabled).toBe(false);expect(captureButtons().map((action) => action.disabled)).toEqual([ false, false, false, false ]);@@ -341,11 +343,11 @@ describe("popup", () => {it("writes a bookmark in the card, keeping the note across modes", async () => {tabsQuery.mockResolvedValueOnce([ { id: 7, title: "A page", url: "https://example.com/post" } ]);await rerender();- expect(container.querySelector("textarea")).toBeNull();+ expect(container.querySelector(".note-text")).toBeNull();await click("Bookmark");expect(modes()).toEqual([ [ "Page", "false" ], [ "Bookmark", "true" ] ]);- const textArea = container.querySelector(".page-body textarea");+ const textArea = container.querySelector(".page-body .note-text");expect(textArea).not.toBeNull();expect(document.activeElement).toBe(textArea);expect(textArea?.getAttribute("placeholder")).toBe("Add a note about this page");@@ -354,11 +356,11 @@ describe("popup", () => {expect(container.querySelector(".page-meta")?.textContent).toBe("example.com");expect(shortcutOf("Save bookmark")).toEqual({ text: "Ctrl+Enter", keys: [ "Ctrl", "Enter" ] });- await type(".page-body textarea", "Worth a read");+ await type(".page-body .note-text", "Worth a read");await click("Page");- expect(container.querySelector("textarea")).toBeNull();+ expect(container.querySelector(".note-text")).toBeNull();await click("Bookmark");- expect(container.querySelector<HTMLTextAreaElement>(".page-body textarea")?.value).toBe("Worth a read");+ expect(container.querySelector<HTMLTextAreaElement>(".page-body .note-text")?.value).toBe("Worth a read");expect(closeWindow).not.toHaveBeenCalled();sendMessage.mockResolvedValueOnce(true);@@ -371,14 +373,19 @@ describe("popup", () => {expect(closeWindow).toHaveBeenCalledOnce();});- it("shows the page's description under the title in every mode, and saves it as edited", async () => {+ it("shows the page's description atop the preview in every mode, and saves it as edited", async () => {metadata = { description: "All about the post" };selection = SELECTION;await rerender();- const description = () => container.querySelector<HTMLTextAreaElement>(".page-heading .page-description");+ const description = () =>+ container.querySelector<HTMLTextAreaElement>(".page-body > .page-description-row .page-description");expect(description()?.value).toBe("All about the post");expect(description()?.getAttribute("aria-label")).toBe("Page description");- expect(cardParts()).toEqual([ "page-heading", "clip-mode", "page-body", "btn btn-primary primary-action" ]);+ expect(description()?.getAttribute("placeholder")).toBe("Add a description");+ const icon = container.querySelector<HTMLElement>(".page-description-row .page-description-icon");+ expect(icon?.querySelector("svg.icon path")).not.toBeNull();+ expect(icon?.title).toBe(+ "The page's description. It is saved in the #pageDescription label of the note.");await click("Save selection");expect(sendMessage).toHaveBeenLastCalledWith({@@ -418,42 +425,67 @@ describe("popup", () => {});});- it("shows no description where the page gives none or cannot be asked for one", async () => {+ it("offers an empty description where the page gives none or cannot be asked for one", async () => {+ const description = () => container.querySelector<HTMLTextAreaElement>(".page-description");// An outdated content script answers nothing.metadata = undefined;await rerender();- expect(container.querySelector(".page-description")).toBeNull();- await click("Bookmark");- expect(container.querySelector(".page-description")).toBeNull();+ expect(description()?.value).toBe("");+ await type(".page-description", "Written by hand");+ await click("Save page to Trilium");+ expect(sendMessage).toHaveBeenLastCalledWith({+ name: "save-whole-page",+ page: { ...PAGE, labels: { publishedDate: "2024-05-01", pageDescription: "Written by hand" } }+ });metadata = new Error("Could not establish connection.");await rerender();await click("Bookmark");- expect(container.querySelector(".page-description")).toBeNull();- expect(container.querySelector(".page-body textarea")).not.toBeNull();+ expect(description()?.value).toBe("");+ expect(container.querySelector(".page-body .note-text")).not.toBeNull();+ });++ it("sizes the preview to the page, so that it scrolls with the description", async () => {+ const frame = container.querySelector<HTMLIFrameElement>(".page-body iframe.page-content");+ expect(frame).not.toBeNull();+ if (!frame) return;+ Object.defineProperty(frame, "contentDocument", {+ configurable: true,+ value: { documentElement: { scrollHeight: 640 } }+ });+ await act(() => {+ frame.dispatchEvent(new Event("load"));+ });+ expect(frame.style.height).toBe("640px");++ Object.defineProperty(frame, "contentDocument", { configurable: true, value: null });+ await act(() => {+ frame.dispatchEvent(new Event("load"));+ });+ expect(frame.style.height).toBe("640px");});it("keeps a draft bookmark while Trilium is briefly not found", async () => {await click("Bookmark");await type(".page-title", "My title");- await type(".page-body textarea", "Half-written note");+ await type(".page-body .note-text", "Half-written note");await receive({ name: "trilium-search-status", triliumSearch: { status: "not-found" } });- expect(container.querySelector(".page-body textarea")).toBeNull();+ expect(container.querySelector(".page-body .note-text")).toBeNull();await receive({ name: "trilium-search-status", triliumSearch: { status: "found-desktop", port: 37840, url: "" } });await flush();expect(modes()).toEqual([ [ "Page", "false" ], [ "Bookmark", "true" ] ]);expect(container.querySelector<HTMLInputElement>(".page-title")?.value).toBe("My title");- expect(container.querySelector<HTMLTextAreaElement>(".page-body textarea")?.value).toBe("Half-written note");+ expect(container.querySelector<HTMLTextAreaElement>(".page-body .note-text")?.value).toBe("Half-written note");});it("saves the title and the text as they are, on Ctrl+Enter from either field", async () => {await click("Bookmark");await type(".page-title", " Read later. Soon ");- await type(".page-body textarea", " It has <b>tips</b>\nand more ");+ await type(".page-body .note-text", " It has <b>tips</b>\nand more ");sendMessage.mockResolvedValueOnce(true);- await ctrlEnter(".page-body textarea");+ await ctrlEnter(".page-body .note-text");expect(sendMessage).toHaveBeenCalledWith({name: "save-link-with-note",title: "Read later. Soon",@@ -474,7 +506,7 @@ describe("popup", () => {sendMessage.mockResolvedValueOnce(undefined);await ctrlEnter(".page-title");expect(sendMessage).toHaveBeenCalledWith({ name: "save-link-with-note", title: "", content: "" });- expect(container.querySelector(".page-body textarea")).not.toBeNull();+ expect(container.querySelector(".page-body .note-text")).not.toBeNull();expect(closeWindow).not.toHaveBeenCalled();const calls = sendMessage.mock.calls.length;diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex d89a44f195..74bbd74f3c 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -29,13 +29,13 @@ The extension is available from the official browser web stores:Clicking the extension's button in the browser toolbar opens its popup:-* The popup shows what will be saved from the current page: the note's title, which can be edited before saving, the website, the page's description if it has one, and below them a preview. A switch above the preview chooses what to save, among what the page offers:+* The popup shows what will be saved from the current page: the note's title, which can be edited before saving, the website, and below them a preview, which starts with the page's description. A switch above the preview chooses what to save, among what the page offers:* _Selection_, when text is selected on the page: _Save selection_ saves it into the note of that page's clippings, as the context menu does.* _Page_, when the page has an article: _Save page to Trilium_ saves the article's text and images, and the publication date shows next to the website when the page states one.* _Bookmark_, always: a text box for a note about the page replaces the preview, and _Save bookmark_ (or <kbd>Ctrl</kbd>+<kbd>Enter</kbd>) saves a link to the page with that note. Left empty, the title stays the page's title.- The description comes from the page's `description` meta tag, or the one it gives social sites. It can be edited or cleared before saving, and is saved in the `#pageDescription` label of the note. Clippings saved with the keyboard shortcuts or the context menu, screenshots and images included, get the description as the page gives it. Each clipping that brings a description updates the label.+ The description, marked by the <span class="tn-icon bx bx-align-left"></span> icon, comes from the page's `description` meta tag, or the one it gives social sites. It can be edited or cleared before saving, or written in when the page has none, and is saved in the `#pageDescription` label of the note. Clippings saved with the keyboard shortcuts or the context menu, screenshots and images included, get the description as the page gives it. Each clipping that brings a description updates the label.The popup opens on the selection if there is one, otherwise on the article. On a page with no article (Readability cannot find one) and no selection, it opens on _Bookmark_ and says the page has no article. The keyboard shortcuts and the context menu still save right away, without a preview.* 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 the popup says so in place of the preview, and only _Tabs_ remains available there.