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
test: cover the pictures a note fetches, and the icons it judges
Elian Doran55396dc9652b
diff --git a/apps/client/src/services/favicon_contrast.spec.tsx b/apps/client/src/services/favicon_contrast.spec.tsxnew file mode 100644index 0000000000..decf974b47--- /dev/null+++ b/apps/client/src/services/favicon_contrast.spec.tsx@@ -0,0 +1,199 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useFaviconContrastClass } from "./favicon_contrast.js";+import { renderMentionPreview } from "./link_embed.js";++/**+ * The verdicts are cached for the life of the page — a note linking one site twenty times measures+ * it once — so every test names its own icon rather than sharing one with the test before it.+ */+let counter = 0;+const freshIcon = () => `api/attachments/att${++counter}/image/icon.png`;++/** The icon the browser would have loaded, with its `load`/`error` left for the test to fire. */+class FakeImage {+ static instances: FakeImage[] = [];++ src = "";+ private handlers: Record<string, () => void> = {};++ constructor() {+ FakeImage.instances.push(this);+ }++ addEventListener(type: string, handler: () => void) {+ this.handlers[type] = handler;+ }++ fire(type: "load" | "error") {+ this.handlers[type]?.();+ }+}++/**+ * A canvas that answers with the pixels the test names, so a verdict can be reached at all: happy-dom+ * implements no 2d context, and without one the measurement rightly declines to judge anything.+ */+function stubCanvas(pixels: Uint8ClampedArray) {+ const realCreateElement = document.createElement.bind(document);++ vi.spyOn(document, "createElement").mockImplementation(((tag: string, options?: ElementCreationOptions) => {+ if (tag !== "canvas") {+ return realCreateElement(tag, options);+ }++ return {+ width: 0,+ height: 0,+ getContext: () => ({+ drawImage: () => {},+ getImageData: () => ({ data: pixels })+ })+ } as unknown as HTMLCanvasElement;+ }) as typeof document.createElement);+}++/** An icon that is a black mark on nothing — GitHub's octocat, which a dark theme has to correct. */+const BLACK_ON_NOTHING = new Uint8ClampedArray([+ ...Array.from({ length: 60 }, () => [ 0, 0, 0, 0 ]).flat(),+ ...Array.from({ length: 40 }, () => [ 0, 0, 0, 255 ]).flat()+]);++function Probe({ src }: { src?: string | null }) {+ return <span className={useFaviconContrastClass(src) ?? "unjudged"} />;+}++const containers: HTMLDivElement[] = [];++function renderProbe(src?: string | null) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ containers.push(container);+ act(() => render(<Probe src={src} />, container));++ return () => container.querySelector("span")?.className;+}++/** Lets the measurement's promise resolve and the render it schedules run. */+const settle = () => act(async () => { await Promise.resolve(); });++beforeEach(() => {+ FakeImage.instances = [];+ vi.stubGlobal("Image", FakeImage);+ stubCanvas(BLACK_ON_NOTHING);+});++afterEach(() => {+ for (const container of containers) {+ act(() => render(null, container));+ container.remove();+ }+ containers.length = 0;+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("useFaviconContrastClass", () => {+ it("measures an icon, then hands the verdict to the theme as a class", async () => {+ const src = freshIcon();+ const classOf = renderProbe(src);++ // Drawn as the site drew it while the measurement runs: guessing first would mean+ // occasionally correcting an icon that turns out to be fine.+ expect(classOf()).toBe("unjudged");+ expect(FakeImage.instances).toHaveLength(1);+ expect(FakeImage.instances[0].src).toBe(src);++ FakeImage.instances[0].fire("load");+ await settle();++ expect(classOf()).toBe("link-embed-favicon-dark");+ });++ it("answers a second preview of the same icon without measuring it again", async () => {+ const src = freshIcon();+ const first = renderProbe(src);+ FakeImage.instances[0].fire("load");+ await settle();+ expect(first()).toBe("link-embed-favicon-dark");++ // A note linking one site twenty times draws twenty of these.+ const second = renderProbe(src);+ await settle();++ expect(second()).toBe("link-embed-favicon-dark");+ expect(FakeImage.instances).toHaveLength(1);+ });++ it("shares one measurement between the previews that ask for it at once", async () => {+ const src = freshIcon();+ const first = renderProbe(src);+ const second = renderProbe(src);++ // Both mounted before either answer arrived: one load, one measurement, one verdict.+ expect(FakeImage.instances).toHaveLength(1);++ FakeImage.instances[0].fire("load");+ await settle();++ expect(first()).toBe("link-embed-favicon-dark");+ expect(second()).toBe("link-embed-favicon-dark");+ });++ it("leaves an icon alone when there is nothing to measure", async () => {+ // Nothing to draw at all.+ expect(renderProbe(undefined)()).toBe("unjudged");+ // A remote address, which no preview may load — the reader would be announced to whoever+ // serves it. It never reaches an <img>, so it is never measured either.+ expect(renderProbe("https://tracker.test/favicon.ico")()).toBe("unjudged");+ expect(FakeImage.instances).toEqual([]);++ // An icon that will not load is one the preview already shows its placeholder for.+ const classOf = renderProbe(freshIcon());+ FakeImage.instances[0].fire("error");+ await settle();+ expect(classOf()).toBe("unjudged");++ // And an icon the canvas will not give up its pixels for is left as the site drew it.+ vi.restoreAllMocks();+ const unreadable = renderProbe(freshIcon());+ FakeImage.instances[1].fire("load");+ await settle();+ expect(unreadable()).toBe("unjudged");+ });++ it("puts the verdict on the icon a preview actually draws", async () => {+ // What the class is for: the theme corrects the icon by it, so it has to arrive on the+ // rendered <img> alongside the class that sizes it, rather than in place of it.+ const container = document.createElement("div");+ document.body.appendChild(container);+ containers.push(container);++ act(() => renderMentionPreview(container, {+ url: "https://example.com",+ favicon: freshIcon()+ }));++ FakeImage.instances[0].fire("load");+ await settle();++ expect(container.querySelector("img.link-embed-mention-favicon")?.className)+ .toBe("link-embed-mention-favicon link-embed-favicon-dark");+ });++ it("drops the verdict of a preview that has gone before its measurement arrives", async () => {+ const src = freshIcon();+ const classOf = renderProbe(src);+ const [ image ] = FakeImage.instances;++ // Scrolling away from a note unmounts its previews mid-measurement, which must not be a+ // state update against something no longer rendered.+ act(() => render(null, containers[containers.length - 1]));+ image.fire("load");+ await settle();++ expect(classOf()).toBeUndefined();+ });+});diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex f21c1c1add..80dd8b29e1 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -420,26 +420,35 @@ describe("link-embed getMetadata", () => {});it("drops a favicon whose stream exceeds the limit despite a smaller advertised size", async () => {- // A lying content-length must not bypass the cap: the limit is enforced while streaming too.+ // A lying content-length must not bypass the cap: the limit is enforced while streaming too,+ // so the read is abandoned partway rather than after the whole of it has arrived.const html = `<html><head><title>Plain</title><link rel="icon" href="/liar.ico"></head></html>`;- const chunk = Buffer.alloc(40 * 1024, 7);+ const chunk = Buffer.alloc(64 * 1024, 7);+ // How far each read of the body got. One entry per fetch of it: the icon is a candidate for+ // the card's picture as well, and that one is allowed to read far more before it stops.+ const reads: number[] = [];+ let cancelled = false;safeFetch.mockImplementation(async (url: string) => {if (url.includes("liar.ico")) {- let sent = 0;return {ok: true,status: 200,// No content-type either, exercising the caller-provided default.headers: { get: (h: string) => (h.toLowerCase() === "content-length" ? "10" : null) },body: {- getReader: () => ({- async read() {- if (sent >= 2) return { done: true, value: undefined };- sent++;- return { done: false, value: new Uint8Array(chunk) };- },- async cancel() {}- })+ getReader: () => {+ const at = reads.push(0) - 1;++ return {+ async read() {+ reads[at]++;+ return { done: false, value: new Uint8Array(chunk) };+ },+ async cancel() {+ cancelled = true;+ }+ };+ }},json: async () => undefined};@@ -450,6 +459,27 @@ describe("link-embed getMetadata", () => {const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));expect(result.title).toBe("Plain");expect(result.favicon).toBeUndefined();+ // A body with no end to it: abandoned at the ceiling rather than read for as long as it+ // comes. Four 64KB chunks fit under the 256KB an icon may be fetched at; the fifth is what+ // carries the total past it.+ expect(cancelled).toBe(true);+ expect(reads[0]).toBe(5);+ });++ it("keeps nothing it cannot reference, when the store answers without an id", async () => {+ // Every picture is referenced by `api/attachments/<id>/…`, so a store that answers without+ // one leaves the preview naming an address that could not be built.+ const html = `<html><head><title>Plain</title><link rel="icon" href="/fav.ico"></head></html>`;+ saveImageToAttachment.mockImplementation((_noteId: string, _buffer: Buffer, fileName: string) => ({ title: fileName }));+ safeFetch.mockImplementation(async (url: string) => {+ if (url.includes("fav.ico")) return fakeResponse(makeIco(), { contentType: "image/x-icon" });+ return fakeResponse(html, { contentType: "text/html" });+ });++ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));++ expect(result.title).toBe("Plain");+ expect(result.favicon).toBeUndefined();});it("names a favicon by its own bytes rather than by the content type it was served under", async () => {@@ -547,7 +577,9 @@ describe("link-embed getMetadata", () => {// read a site writing any of the others — `rel="icon shortcut"`, the precomposed// apple-touch-icon — as declaring no icon at all.const head = `<link rel="mask-icon" href="/pinned.svg">`+ + `<link rel="mask-icon" href="/pinned.png">`+ `<link rel="ICON SHORTCUT" sizes="16x16" href="/tiny.png">`+ + `<link rel="icon" sizes="32x32" href="/small.png">`+ `<link rel="apple-touch-icon-precomposed" sizes="180x180" href="/touch.png">`+ `<link rel="icon" sizes="48x48" href="/right.png">`;const serve = (declared = head) => {@@ -569,7 +601,9 @@ describe("link-embed getMetadata", () => {expect(iconsRequested().slice(0, 4)).toEqual(["https://example.com/right.png","https://example.com/touch.png",- "https://example.com/tiny.png",+ // Of the two that would have to be upscaled, the larger — and both before the tinted+ // silhouette, which is past the cap.+ "https://example.com/small.png","https://example.com/favicon.ico"]);@@ -593,6 +627,23 @@ describe("link-embed getMetadata", () => {serve(`<link rel="apple-touch-icon" href="/touch.png"><link rel="icon" href="/fav.ico">`);await linkEmbedRoute.getMetadata(req("https://example.com/page"));expect(iconsRequested()[0]).toBe("https://example.com/touch.png");++ // A site naming the conventional path itself is not asked for it twice: it is appended only+ // where the ranked candidates do not already hold it. The page carries a picture of its own+ // so that the card never goes looking through the icons as well.+ const cover = await makePng(600, 300, 0xff0000ff);+ safeFetch.mockReset();+ safeFetch.mockImplementation(async (url: string) => {+ if (url.endsWith("/cover.png")) return fakeResponse(cover, { contentType: "image/png" });+ if (url.endsWith("/page")) {+ return fakeResponse(`<html><head><title>T</title><meta property="og:image" content="/cover.png">`+ + `<link rel="icon" href="/favicon.ico"></head></html>`, { contentType: "text/html" });+ }+ return fakeResponse("", { ok: false });+ });++ await linkEmbedRoute.getMetadata(req("https://example.com/page"));+ expect(iconsRequested().filter((url) => url.endsWith("/favicon.ico"))).toEqual([ "https://example.com/favicon.ico" ]);});it("keeps trying after an icon that fails to arrive, down to the conventional path", async () => {diff --git a/packages/trilium-core/src/services/image_download.spec.ts b/packages/trilium-core/src/services/image_download.spec.tsindex b94b780e8e..e6d8c1e014 100644--- a/packages/trilium-core/src/services/image_download.spec.ts+++ b/packages/trilium-core/src/services/image_download.spec.ts@@ -1,4 +1,4 @@-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type BNote from "../becca/entities/bnote.js";import { getContext } from "./context.js";@@ -76,6 +76,15 @@ beforeEach(() => {answerWith = () => PIXEL_PNG;});+/**+ * Lets whatever a save started run to wherever it gets to.+ *+ * `downloadImages` answers without waiting for the network — a save cannot be held up by someone+ * else's server — so a test that asserts nothing was fetched has to give the fetch that was not+ * started the chance to have been.+ */+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+describe("downloadPictureToAttachment (real DB)", () => {it("keeps the picture as an attachment under the role and title it is given", async () => {const note = createNote("<p>x</p>");@@ -142,6 +151,129 @@ describe("downloadImages (real DB)", () => {expect(rewritten).toContain(stored);expect(asked).toEqual([]);});++ /**+ * A distinct address per test. The module keeps one url→attachment map for the life of the+ * process, deliberately — a picture pasted into twenty notes is fetched once — so two tests+ * sharing an address would be two tests sharing a result.+ */+ const freshUrl = () => `https://pictures.test/${++counter}.png`;++ /** Runs `work` with the reader's answer to "may a note fetch what it names" set either way. */+ function withDownloads<T>(allowed: boolean, work: () => T): T {+ const previously = optionService.getOptionBool("downloadImagesAutomatically");+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", String(allowed)));++ try {+ return getContext().init(work);+ } finally {+ getContext().init(() => optionService.setOption("downloadImagesAutomatically", String(previously)));+ }+ }++ it("fetches what a note names elsewhere, and rewrites a later save from what it kept", async () => {+ const note = createNote("<p>x</p>");+ const url = freshUrl();++ // The fetch is deliberately not waited for: a save happens on every keystroke's pause, and+ // a third party's server is not something to hold one up. So the content comes back naming+ // the address it named before.+ expect(withDownloads(true, () => downloadImages(note.noteId, `<p><img src="${url}"></p>`))).toContain(url);++ await vi.waitFor(() => expect(note.getAttachments()).toHaveLength(1));+ expect(asked).toEqual([ url ]);++ // The next save of the same address is answered from what was kept, without asking again —+ // which is the whole point of remembering it.+ const [ attachment ] = note.getAttachments();+ const later = withDownloads(true, () => downloadImages(note.noteId, `<p><img src="${url}"></p>`));++ expect(later).toContain(`src="api/attachments/${attachment.attachmentId}/image/`);+ expect(asked).toEqual([ url ]);++ // And when what was kept has since been erased, the note is left naming the address rather+ // than pointed at an attachment that is not there.+ getContext().init(() => attachment.markAsDeleted());+ expect(withDownloads(true, () => downloadImages(note.noteId, `<p><img src="${url}"></p>`))).toContain(url);+ });++ it("asks for nothing at all when the reader has said not to fetch", async () => {+ const note = createNote("<p>x</p>");+ const url = freshUrl();++ expect(withDownloads(false, () => downloadImages(note.noteId, `<p><img src="${url}"></p>`))).toContain(url);++ await settle();+ expect(asked).toEqual([]);+ expect(note.getAttachments()).toHaveLength(0);+ });++ it("refuses an address that is not a website, whatever the content says", async () => {+ // The content is whatever was pasted, imported or synced, so the scheme is checked here and+ // not taken on trust: `file://` would otherwise have the server read its own disk.+ const note = createNote("<p>x</p>");++ withDownloads(true, () => downloadImages(note.noteId, `<p><img src="file:///etc/passwd"></p>`));++ await settle();+ expect(asked).toEqual([]);+ expect(note.getAttachments()).toHaveLength(0);+ });++ it("leaves alone what is already ours, and what the clipper is still to resolve", async () => {+ const note = createNote("<p>x</p>");+ // An image note's own address, an attachment's, and the web clipper's 20-character id —+ // none of them a third party's, so none of them anything to go and fetch.+ const content = `<p><img src="api/images/abc123456789/x.png">`+ + `<img src="api/attachments/abc123456789/image/y.png">`+ + `<img src="12345678901234567890"></p>`;++ expect(withDownloads(true, () => downloadImages(note.noteId, content))).toBe(content);++ await settle();+ expect(asked).toEqual([]);+ });++ it("goes back over the note once the pictures it started have arrived", async () => {+ // The flow this exists for: the reader pastes a picture and leaves the note before the+ // fetch finishes, so nothing rewrites the address at save time. A while later the note is+ // read again and mended — or found gone, and left alone.+ vi.useFakeTimers();++ try {+ const url = freshUrl();+ const content = `<p><img src="${url}"></p>`;+ const note = createNote(content);++ withDownloads(true, () => downloadImages(note.noteId, content));++ // Long enough for the fetch to have answered and the pass over the note to have run.+ await vi.advanceTimersByTimeAsync(10_000);++ const [ attachment ] = note.getAttachments();+ // The reader is left with a note that names what this instance holds rather than what+ // someone else's server does — without their having saved again to get it.+ expect(String(note.getContent()))+ .toBe(`<p><img src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"></p>`);+ } finally {+ vi.useRealTimers();+ }+ });++ it("asks once for an address that appears twice before the first answer arrives", async () => {+ const note = createNote("<p>x</p>");+ const url = freshUrl();++ // Two saves in quick succession, which is what typing produces. The second finds the first+ // still in flight: neither the map nor the note has the picture yet.+ withDownloads(true, () => {+ downloadImages(note.noteId, `<p><img src="${url}"></p>`);+ downloadImages(note.noteId, `<p><img src="${url}"></p>`);+ });++ await vi.waitFor(() => expect(note.getAttachments()).toHaveLength(1));+ expect(asked).toEqual([ url ]);+ });});describe("storeLinkPreviewPictures (real DB)", () => {