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): leave the scrollbars out of a full-page screenshot
Elian Doran96103513aace
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 991621a0d1..4713fa6508 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@@ -94,13 +94,14 @@<li><p><em>Full page</em> scrolls through the page, takes a screenshot of eachpart and joins them into one image, then scrolls back to where the page- was. Stay on the tab until it is saved: switching to another tab stops- the screenshot. A header that stays at the top of the window appears once,- at the top of the image, and headings that stick while scrolling appear- where they are in the page. Other elements that stay in place while scrolling- (such as cookie banners and chat buttons) are left out, while a background- that fills the whole window repeats on every screen. A very long page is- cut off.</p>+ was. The scrollbars are hidden while it does, so they do not appear in+ the image. Stay on the tab until it is saved: switching to another tab+ stops the screenshot. A header that stays at the top of the window appears+ once, at the top of the image, and headings that stick while scrolling+ appear where they are in the page. Other elements that stay in place while+ scrolling (such as cookie banners and chat buttons) are left out, while+ a background that fills the whole window repeats on every screen. A very+ long page is cut off.</p></li><li><p>If the current page was already clipped, a notice at the top offers todiff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex d528353468..2ffd30c36c 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -552,7 +552,7 @@ describe("background", () => {await run(onCommand("saveFullPageScreenshot"));- expect(pageSteps()).toEqual([ undefined, 0, "first", "rest", 500, 1000, "restore", 300 ]);+ expect(pageSteps()).toEqual([ undefined, 0, "first", 0, "rest", 500, 1000, "restore", 300 ]);expect(stitchRequest()).toEqual({slices: [ { dataUrl: PNG, y: 0 }, { dataUrl: PNG, y: 500 }, { dataUrl: PNG, y: 700 } ],viewportHeight: 500,@@ -580,6 +580,18 @@ describe("background", () => {expect(stitchRequest()).toMatchObject({ slices: [ { y: 0 }, { y: 2000 }, { y: 4000 } ] });});+ it("captures the page as it is laid out once its scrollbars are hidden", async () => {+ simulatePage({ viewportHeight: 500, pageHeight: 1200, prepared: { viewportHeight: 515, pageHeight: 1100 } });++ await run(onCommand("saveFullPageScreenshot"));++ expect(stitchRequest()).toEqual({+ slices: [ { dataUrl: PNG, y: 0 }, { dataUrl: PNG, y: 515 }, { dataUrl: PNG, y: 585 } ],+ viewportHeight: 515,+ pageHeight: 1100+ });+ });+it("stops and scrolls back when another tab is opened, even if scrolling back fails", async () => {simulatePage({ startY: 300, viewportHeight: 500, pageHeight: 1200 });const scrollPage = tabMessageHandler;@@ -593,7 +605,7 @@ describe("background", () => {await run(sendRuntimeMessage({ name: "save-full-page-screenshot" }));expect(captureVisibleTab).not.toHaveBeenCalled();- expect(pageSteps()).toEqual([ undefined, 0, "first", "restore", 300 ]);+ expect(pageSteps()).toEqual([ undefined, 0, "first", 0, "restore", 300 ]);expect(await lastToast()).toMatchObject({message: "Saving to Trilium failed: The screenshot was stopped because another tab was opened."});@@ -949,17 +961,27 @@ async function lastToast() {* Answers the content script's scroll messages for a page of `pageHeight` that scrolls no further* than `scrollLimit`, starting at `startY`.*/-function simulatePage({ startY = 0, viewportHeight, pageHeight, scrollLimit = pageHeight, devicePixelRatio = 1 }: {- startY?: number, viewportHeight: number, pageHeight: number, scrollLimit?: number, devicePixelRatio?: number+/**+ * Answers the content script's messages for a page of `pageHeight` that scrolls no further than+ * `scrollLimit`, starting at `startY`. `prepared` is the size it has once its scrollbars are+ * hidden.+ */+function simulatePage({ startY = 0, viewportHeight, pageHeight, scrollLimit = pageHeight, devicePixelRatio = 1, prepared }: {+ startY?: number, viewportHeight: number, pageHeight: number, scrollLimit?: number, devicePixelRatio?: number,+ prepared?: { viewportHeight: number, pageHeight: number }}) {let scrollY = startY;+ let size = { viewportHeight, pageHeight, scrollLimit };tabMessageHandler = (message) => {+ const { y, step } = message as { y?: number, step?: string };+ if (step === "first" && prepared) {+ size = { ...prepared, scrollLimit: prepared.pageHeight };+ }if (message.name !== "trilium-scroll-to") return undefined;- const { y } = message as { y?: number };if (y !== undefined) {- scrollY = Math.max(0, Math.min(y, scrollLimit - viewportHeight));+ scrollY = Math.max(0, Math.min(y, size.scrollLimit - size.viewportHeight));}- return { scrollX: 0, scrollY, viewportHeight, pageHeight, devicePixelRatio };+ return { scrollX: 0, scrollY, viewportHeight: size.viewportHeight, pageHeight: size.pageHeight, devicePixelRatio };};}diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex 6500edfd57..2daab7a180 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -18,7 +18,10 @@ type BackgroundMessage = {} | {name: "trilium-get-page-metadata";} | {- /** Changes the page's fixed and sticky elements for a full-page screenshot, or restores them. */+ /**+ * Changes the page for a full-page screenshot (its scrollbars, fixed and sticky elements), or+ * restores it.+ */name: "trilium-set-floating-elements";step: "first" | "rest" | "restore";} | {@@ -162,19 +165,22 @@ export default defineBackground(() => {}const start = await scrollTab(tabId);- const height = Math.min(start.pageHeight, MAX_SCREENSHOT_HEIGHT / start.devicePixelRatio);+ // Measured again once the page is prepared: without its scrollbars, it can lay out differently.+ let page = start;const slices: ScreenshotSlice[] = [];let lastCaptureAt = 0;try {let y = 0;- while (y < height) {- const position = await scrollTab(tabId, start.scrollX, y);+ while (y < Math.min(page.pageHeight, MAX_SCREENSHOT_HEIGHT / page.devicePixelRatio)) {+ let position = await scrollTab(tabId, start.scrollX, y);const previous = slices.at(-1);// The page stopped scrolling short of the height it reported.if (previous && position.scrollY <= previous.y) break;if (!previous) {await setFloatingElements(tabId, "first");+ position = await scrollTab(tabId, start.scrollX, y);+ page = position;}await delay(Math.max(SCROLL_SETTLE_MS, lastCaptureAt + CAPTURE_INTERVAL_MS - Date.now()));@@ -189,14 +195,14 @@ export default defineBackground(() => {if (!previous) {await setFloatingElements(tabId, "rest");}- y = position.scrollY + start.viewportHeight;+ y = position.scrollY + page.viewportHeight;}} finally {await setFloatingElements(tabId, "restore").catch(() => undefined);await scrollTab(tabId, start.scrollX, start.scrollY).catch(() => undefined);}- return await stitch({ slices, viewportHeight: start.viewportHeight, pageHeight: start.pageHeight });+ return await stitch({ slices, viewportHeight: page.viewportHeight, pageHeight: page.pageHeight });}/** Scrolls the tab when given a position, and answers where it is scrolled to. */diff --git a/apps/web-clipper/floating_elements.spec.ts b/apps/web-clipper/floating_elements.spec.tsindex a91b339002..8c0c01ead3 100644--- a/apps/web-clipper/floating_elements.spec.ts+++ b/apps/web-clipper/floating_elements.spec.ts@@ -44,6 +44,19 @@ describe("setFloatingElements", () => {expect(styleOf(".gone")).toBeNull();});+ it("hides the scrollbars until the page is restored", () => {+ const scrollbarStyles = () => [ ...document.querySelectorAll("style") ]+ .filter((style) => style.textContent?.includes("scrollbar-width: none !important"));++ setFloatingElements("first");+ setFloatingElements("first");+ expect(scrollbarStyles()).toHaveLength(1);+ expect(scrollbarStyles()[0]?.textContent).toContain("html::-webkit-scrollbar");++ setFloatingElements("restore");+ expect(scrollbarStyles()).toHaveLength(0);+ });+it("puts back every inline style as it was", () => {const before = [ ...document.body.querySelectorAll("*") ].map((element) => element.getAttribute("style"));diff --git a/apps/web-clipper/floating_elements.ts b/apps/web-clipper/floating_elements.tsindex 31e3f3f095..2375671854 100644--- a/apps/web-clipper/floating_elements.ts+++ b/apps/web-clipper/floating_elements.ts@@ -1,7 +1,7 @@/*** The steps of a full-page screenshot that change the page:- * - `first`, before the first capture, pins sticky elements where they are in the page and hides- * the fixed elements that are not at the top of the viewport;+ * - `first`, before the first capture, hides the scrollbars, pins sticky elements where they are+ * in the page and hides the fixed elements that are not at the top of the viewport;* - `rest`, after the first capture, hides the fixed elements at the top too, so a header appears* once, at the top of the screenshot;* - `restore` puts back every inline style the other steps changed.@@ -22,6 +22,15 @@ const PINNED_STICKY: [ string, string ][] = [];const HIDDEN: [ string, string ][] = [ [ "display", "none" ] ];+/**+ * Hides the page's scrollbars, which would otherwise be in every capture. The page can still be+ * scrolled. `scrollbar-width` is for Firefox and Chrome 121 or later, `::-webkit-scrollbar` for+ * older Chrome.+ */+const HIDE_SCROLLBARS_CSS = `+ html, body { scrollbar-width: none !important; }+ html::-webkit-scrollbar, body::-webkit-scrollbar { display: none !important; }`;+interface SavedStyle {/** The element's `style` attribute before any change, or null when it had none. */attribute: string | null;@@ -33,6 +42,7 @@ interface SavedStyle {const saved = new Map<HTMLElement, SavedStyle>();let topFixedElements: HTMLElement[] = [];let restoreTimer: ReturnType<typeof setTimeout> | undefined;+let scrollbarStyle: HTMLStyleElement | undefined;export function setFloatingElements(step: FloatingElementsStep) {if (step === "first") {@@ -50,6 +60,10 @@ export function setFloatingElements(step: FloatingElementsStep) {}function prepareFirstCapture() {+ scrollbarStyle = document.createElement("style");+ scrollbarStyle.textContent = HIDE_SCROLLBARS_CSS;+ document.documentElement.append(scrollbarStyle);+for (const element of document.body.querySelectorAll<HTMLElement>("*")) {const style = getComputedStyle(element);if (style.display === "none") continue;@@ -100,6 +114,8 @@ function override(element: HTMLElement, properties: [ string, string ][]) {function restoreFloatingElements() {clearTimeout(restoreTimer);restoreTimer = undefined;+ scrollbarStyle?.remove();+ scrollbarStyle = undefined;for (const [ element, original ] of saved) {for (const [ name, { value, priority } ] of original.properties) {diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 0c45e63236..22c1fb7d1b 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -40,7 +40,7 @@ Clicking the extension's button in the browser toolbar opens its popup:The popup opens on the selection if there is one, otherwise on _Page_, showing the article, or the whole page when the page has no article. On a page that shows nothing to save, it opens on _Bookmark_ and says so. The keyboard shortcuts and the context menu still save right away, without a preview: saving the whole page that way saves the article, or the whole page when the page has no article.* 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.* 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), _Full page_ (a screenshot of the whole page) and _Tabs_ (saves the links of every tab in the current window as a list of <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a>, or of plain links when _Autogenerate link previews_ is turned off). Hovering over a button shows its full name and, if it has one, its keyboard shortcut.-* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. A very long page is cut off.+* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. The scrollbars are hidden while it does, so they do not appear in the image. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. A very long page is cut off.* 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.