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(share-theme): cover the whole theme and hold it at 100%
Elian Doran3a01fad91ff0
diff --git a/packages/share-theme/src/api.ts b/packages/share-theme/src/api.tsdeleted file mode 100644index adaca77d14..0000000000--- a/packages/share-theme/src/api.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Fetch note with given ID from backend- *- * @param noteId of the given note to be fetched. If false, fetches current note.- */-async function fetchNote(noteId: string | null = null) {- if (!noteId) {- noteId = document.body.getAttribute("data-note-id");- }-- const resp = await fetch(`api/notes/${noteId}`);-- return await resp.json();-}--export default {- fetchNote-};diff --git a/packages/share-theme/src/common/debounce.ts b/packages/share-theme/src/common/debounce.tsdeleted file mode 100644index bdebdad92c..0000000000--- a/packages/share-theme/src/common/debounce.ts+++ /dev/null@@ -1,11 +0,0 @@-export default function debounce<T extends (...args: unknown[]) => unknown>(executor: T, delay: number) {- let timeout: ReturnType<typeof setTimeout> | null;- return function(...args: Parameters<T>): void {- const callback = () => {- timeout = null;- Reflect.apply(executor, null, args);- };- if (timeout) clearTimeout(timeout);- timeout = setTimeout(callback, delay);- };-}\ No newline at end of filediff --git a/packages/share-theme/src/common/parents.ts b/packages/share-theme/src/common/parents.tsdeleted file mode 100644index cfe0a7fce2..0000000000--- a/packages/share-theme/src/common/parents.ts+++ /dev/null@@ -1,7 +0,0 @@-export default function parents<T extends HTMLElement>(el: T, selector: string) {- const result = [];- for (let p = el && el.parentElement; p; p = p.parentElement) {- if (p.matches(selector)) result.push(p);- }- return result;-}\ No newline at end of filediff --git a/packages/share-theme/src/common/parsehtml.ts b/packages/share-theme/src/common/parsehtml.tsdeleted file mode 100644index 2563e1c871..0000000000--- a/packages/share-theme/src/common/parsehtml.ts+++ /dev/null@@ -1,7 +0,0 @@-export default function parseHTML(html: string, fragment = false) {- const template = document.createElement("template");- template.innerHTML = html;- const node = template.content.cloneNode(true);- if (fragment) return node;- return node.childNodes.length > 1 ? node.childNodes : node.childNodes[0];-}\ No newline at end of filediff --git a/packages/share-theme/src/content/math.spec.ts b/packages/share-theme/src/content/math.spec.tsnew file mode 100644index 0000000000..fa6f3baaca--- /dev/null+++ b/packages/share-theme/src/content/math.spec.ts@@ -0,0 +1,36 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";++import setupMath from "./math.js";++const renderMathInElement = vi.hoisted(() => vi.fn());+vi.mock("katex/contrib/auto-render", () => ({ default: renderMathInElement }));+vi.mock("katex/contrib/mhchem", () => ({}));++describe("setupMath", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ document.body.className = "";+ renderMathInElement.mockClear();+ });++ it("renders the formulas of the content, showing an invalid one as an error", async () => {+ document.body.innerHTML = `<div id="content"><span class="math-tex">\\(x^2\\)</span></div>`;++ await setupMath();++ expect(renderMathInElement).toHaveBeenCalledWith(document.getElementById("content"),+ expect.objectContaining({ throwOnError: false, macros: expect.any(Object) }));+ expect(document.body.classList.contains("math-loaded")).toBe(true);+ });++ it("loads nothing for content without formulas", async () => {+ document.body.innerHTML = `<div id="content"><p>x^2</p></div>`+ + `<span class="math-tex"></span>`;++ await setupMath();++ expect(renderMathInElement).not.toHaveBeenCalled();+ expect(document.body.classList.contains("math-loaded")).toBe(false);+ });+});diff --git a/packages/share-theme/src/content/math.ts b/packages/share-theme/src/content/math.tsindex c720ac6e25..03088933de 100644--- a/packages/share-theme/src/content/math.ts+++ b/packages/share-theme/src/content/math.ts@@ -2,16 +2,14 @@ import { KATEX_MACROS } from "@triliumnext/commons/src/lib/katex_macros.js";import "./katex.scss";export default async function setupMath() {- const anyMathBlock = document.querySelector("#content .math-tex");- if (!anyMathBlock) {+ const contentEl = document.getElementById("content");+ if (!contentEl?.querySelector(".math-tex")) {return;}const renderMathInElement = (await import("katex/contrib/auto-render")).default;await import("katex/contrib/mhchem");- const contentEl = document.getElementById("content");- if (!contentEl) return;// throwOnError: false renders invalid formulas as an inline red error instead of// throwing and leaving raw `$…$` text plus a console error (matches the editor).// macros map MathLive-only commands (e.g. \differentialD) onto KaTeX equivalents.diff --git a/packages/share-theme/src/content/mermaid.spec.ts b/packages/share-theme/src/content/mermaid.spec.tsindex 781f5139c6..f83114a560 100644--- a/packages/share-theme/src/content/mermaid.spec.ts+++ b/packages/share-theme/src/content/mermaid.spec.ts@@ -85,7 +85,28 @@ describe("setupMermaid", () => {});});-const MERMAID_NOTE = `<div id="content"><div class="mermaid-note">`+describe("setupMermaid without diagrams", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+ });++ it("loads nothing for other code blocks or a Mermaid note without its source", async () => {+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ document.body.innerHTML = `<div id="content">`+ + `<pre><code class="language-javascript">graph TD;</code></pre>`+ + `<div class="mermaid-note"><img class="mermaid-note-image" src="diagram.svg"></div>`+ + `</div>`;++ await setupMermaid();++ expect(fetchMock).not.toHaveBeenCalled();+ expect(document.querySelectorAll("#content pre, #content img")).toHaveLength(2);+ });+});++const MERMAID_NOTE =`<div id="content"><div class="mermaid-note">`+ `<img class="mermaid-note-image" src="api/images/abc/diagram">`+ `<hr><details><summary>Chart source</summary>`+ `<pre class="mermaid-note-source">graph TD; A-->B</pre></details>`diff --git a/packages/share-theme/src/content/mermaid.ts b/packages/share-theme/src/content/mermaid.tsindex 93c51c4012..a61b131ee6 100644--- a/packages/share-theme/src/content/mermaid.ts+++ b/packages/share-theme/src/content/mermaid.ts@@ -46,9 +46,10 @@ interface Diagram {function findPlaceholders() {const placeholders: { placeholder: Element; source: string }[] = [];- for (const codeBlock of document.querySelectorAll("#content pre code.language-mermaid")) {- if (codeBlock.parentElement) {- placeholders.push({ placeholder: codeBlock.parentElement, source: codeBlock.textContent ?? "" });+ for (const block of document.querySelectorAll("#content pre")) {+ const code = block.querySelector(":scope > code.language-mermaid");+ if (code) {+ placeholders.push({ placeholder: block, source: code.textContent });}}@@ -56,7 +57,7 @@ function findPlaceholders() {const image = note.querySelector(":scope > .mermaid-note-image");const source = note.querySelector(".mermaid-note-source");if (image && source) {- placeholders.push({ placeholder: image, source: source.textContent ?? "" });+ placeholders.push({ placeholder: image, source: source.textContent });}}diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.tsnew file mode 100644index 0000000000..c347b3b3dc--- /dev/null+++ b/packages/share-theme/src/index.spec.ts@@ -0,0 +1,126 @@+// @vitest-environment happy-dom+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ setupLayout: vi.fn(),+ setupExpanders: vi.fn(),+ setupThemeSelector: vi.fn().mockImplementation(() => {+ throw new Error("theme switch failed");+ }),+ setupSearch: vi.fn().mockRejectedValue(new Error("search failed")),+ setupToC: vi.fn(),+ setupFooter: vi.fn(),+ setupMath: vi.fn(),+ setupMermaid: vi.fn(),+ applyTabs: vi.fn(),+ revealFragment: vi.fn(),+ enhanceLinkPreviews: vi.fn()+}));++vi.mock("./page/layout.js", () => ({ default: mocks.setupLayout }));+vi.mock("./page/navigation.js", () => ({ default: mocks.setupExpanders }));+vi.mock("./page/theme_switch.js", () => ({ default: mocks.setupThemeSelector }));+vi.mock("./page/search.js", () => ({ default: mocks.setupSearch }));+vi.mock("./page/toc.js", () => ({ default: mocks.setupToC }));+vi.mock("./page/footer.js", () => ({ default: mocks.setupFooter }));+vi.mock("./content/math.js", () => ({ default: mocks.setupMath }));+vi.mock("./content/mermaid.js", () => ({ default: mocks.setupMermaid }));+vi.mock("@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js", () => ({+ applyTabs: mocks.applyTabs,+ revealFragment: mocks.revealFragment+}));+vi.mock("@triliumnext/commons/src/lib/link_embed_dom.js", () => ({+ enhanceLinkPreviews: mocks.enhanceLinkPreviews+}));++const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});++describe("share theme entry", () => {+ // Vitest clears the calls of every mock before each test.+ let pageSetupCalls: number[] = [];+ let loggedErrors: unknown[] = [];++ beforeAll(async () => {+ await import("./index.js");+ await vi.waitFor(() => expect(consoleError).toHaveBeenCalledTimes(2));+ pageSetupCalls = [ mocks.setupThemeSelector, mocks.setupToC, mocks.setupExpanders,+ mocks.setupLayout, mocks.setupSearch, mocks.setupFooter ]+ .map((setup) => setup.mock.calls.length);+ loggedErrors = consoleError.mock.calls.map(([ error ]) => (error as Error).message);+ });++ afterEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ document.body.className = "";+ document.body.innerHTML = "";+ });++ it("sets up every part of the page, logging what one throws or rejects with", () => {+ expect(pageSetupCalls).toEqual([ 1, 1, 1, 1, 1, 1 ]);+ expect(loggedErrors.sort()).toEqual([ "search failed", "theme switch failed" ]);+ });++ it("gives `~shareJs` scripts `fetchNote()`, which defaults to the page's note", async () => {+ const fetchMock = vi.fn(async (_url: string) => Response.json({ noteId: "fetched" }));+ vi.stubGlobal("fetch", fetchMock);+ document.body.dataset.noteId = "current";+ const { fetchNote } = window as unknown as { fetchNote(noteId?: string): Promise<unknown> };++ expect(await fetchNote()).toEqual({ noteId: "fetched" });+ await fetchNote("other");++ expect(fetchMock.mock.calls.map(([ url ]) => url))+ .toEqual([ "api/notes/current", "api/notes/other" ]);+ });++ it("enhances a text note's content and reveals the tab panel the address points to", () => {+ document.body.className = "type-text";+ document.body.innerHTML = `<div id="content" data-tab-title-placeholder="Tab"></div>`;+ const panel = { scrollIntoView: vi.fn() };+ mocks.revealFragment.mockReturnValue(panel);++ document.dispatchEvent(new Event("DOMContentLoaded"));++ const content = document.getElementById("content");+ expect(mocks.setupMermaid).toHaveBeenCalledOnce();+ expect(mocks.setupMath).toHaveBeenCalledOnce();+ expect(mocks.enhanceLinkPreviews).toHaveBeenCalledWith(document.body);+ expect(mocks.applyTabs).toHaveBeenCalledWith(content, { placeholder: "Tab" });+ expect(panel.scrollIntoView).toHaveBeenCalledOnce();++ window.dispatchEvent(new Event("hashchange"));+ expect(panel.scrollIntoView).toHaveBeenCalledTimes(2);+ });++ it("treats content styled as text like a text note, with or without a content element", () => {+ document.body.className = "type-book";+ document.body.innerHTML = `<div id="content" class="ck-content"></div>`;++ document.dispatchEvent(new Event("DOMContentLoaded"));++ expect(mocks.applyTabs)+ .toHaveBeenCalledWith(document.getElementById("content"), { placeholder: "" });++ mocks.applyTabs.mockClear();+ document.body.className = "type-text";+ document.body.innerHTML = "";+ document.dispatchEvent(new Event("DOMContentLoaded"));++ expect(mocks.setupMath).toHaveBeenCalledTimes(2);+ expect(mocks.applyTabs).not.toHaveBeenCalled();+ });++ it("draws a Mermaid note's diagram and leaves other notes alone", () => {+ document.body.className = "type-mermaid";+ document.dispatchEvent(new Event("DOMContentLoaded"));++ expect(mocks.setupMermaid).toHaveBeenCalledOnce();+ expect(mocks.setupMath).not.toHaveBeenCalled();++ document.body.className = "type-code";+ document.dispatchEvent(new Event("DOMContentLoaded"));++ expect(mocks.setupMermaid).toHaveBeenCalledOnce();+ });+});diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex ce91f8eb79..30f913494f 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -17,7 +17,6 @@ import "./content/adaptive_colors.css";import "./content/link_embed.css";import setupMath from "./content/math.js";import setupMermaid from "./content/mermaid.js";-import api from "./api.js";import "virtual:code-themes.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";import "@triliumnext/ckeditor5/src/theme/tabs.css";@@ -26,16 +25,25 @@ import "@triliumnext/ckeditor5/src/theme/multicolumn.css";import { applyTabs, revealFragment } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";import { enhanceLinkPreviews } from "@triliumnext/commons/src/lib/link_embed_dom.js";-function $try<T extends (...a: unknown[]) => unknown>(func: T, ...args: Parameters<T>) {+/** Runs a setup function, logging what it throws or rejects with instead of stopping the others. */+function $try(func: () => unknown) {try {- func.apply(func, args);- }- catch (e) {- console.error(e); // eslint-disable-line no-console+ Promise.resolve(func()).catch(console.error);+ } catch (e) {+ console.error(e);}}-Object.assign(window, api);+/**+ * Fetches a shared note as JSON, the page's own note by default. Scripts added with `~shareJs` call+ * it as `fetchNote()`.+ */+async function fetchNote(noteId: string | null = null) {+ const resp = await fetch(`api/notes/${noteId ?? document.body.dataset.noteId}`);+ return await resp.json();+}++Object.assign(window, { fetchNote });$try(setupThemeSelector);$try(setupToC);$try(setupExpanders);@@ -50,19 +58,14 @@ function setupTextNote() {$try(setupTabs);}-document.addEventListener(- "DOMContentLoaded",- () => {- const noteType = determineNoteType();-- if (noteType === "text" || document.querySelector("#content.ck-content")) {- setupTextNote();- } else if (noteType === "mermaid") {- $try(setupMermaid);- }- },- false-);+document.addEventListener("DOMContentLoaded", () => {+ const { classList } = document.body;+ if (classList.contains("type-text") || document.querySelector("#content.ck-content")) {+ setupTextNote();+ } else if (classList.contains("type-mermaid")) {+ $try(setupMermaid);+ }+});function setupTabs() {const content = document.getElementById("content");@@ -75,9 +78,3 @@ function setupTabs() {showFragment();window.addEventListener("hashchange", showFragment);}--function determineNoteType() {- const bodyClass = document.body.className;- const match = bodyClass.match(/type-([^\s]+)/);- return match ? match[1] : null;-}diff --git a/packages/share-theme/src/model/page.spec.ts b/packages/share-theme/src/model/page.spec.tsindex 36c2f56ebb..f4c6744331 100644--- a/packages/share-theme/src/model/page.spec.ts+++ b/packages/share-theme/src/model/page.spec.ts@@ -135,7 +135,7 @@ describe("getPageHead", () => {});describe("getHtmlSnippets", () => {- it("joins the snippets of each location, at the end of the content by default", () => {+ it("joins the snippets of each location, at the end of the content by default, text only", () => {const page = fakeNote({noteId: "page",snippets: [@@ -143,6 +143,9 @@ describe("getHtmlSnippets", () => {fakeNote({ noteId: "b", content: "<p>b</p>" }),fakeNote({ noteId: "c", content: "<meta c>", labels: { shareHtmlLocation: "head:end" } }),fakeNote({ noteId: "d", content: "<p>d</p>", labels: { shareHtmlLocation: "body:start" } }),+ fakeNote({+ noteId: "e", content: new Uint8Array([ 60 ]), labels: { shareHtmlLocation: "body:end" }+ }),null]});@@ -246,10 +249,11 @@ describe("getPrevNextLinks", () => {expect(getPrevNextLinks(a, site).next).toStrictEqual({ title: "a1", href: "./a1-alias" });});- it("gives no links to a note hidden from the tree, nor past a site without pages", () => {+ it("links nothing from a hidden note or one outside the site, nor past an empty site", () => {expect(links(hidden)).toStrictEqual([ null, null ]);expect(links(h1)).toStrictEqual([ "hidden", null ]);expect(links(lonely, lonely)).toStrictEqual([ null, null ]);+ expect(links(elsewhere)).toStrictEqual([ null, null ]);});});@@ -335,6 +339,7 @@ describe("getPageLanguages", () => {expect(languages("en", "en", "de").content).toBeNull();expect(languages(null, "en", "de").content).toStrictEqual({ lang: "de", dir: "ltr" });expect(languages("he", "en").content).toStrictEqual({ lang: "he", dir: "rtl" });+ expect(languages(null, "").content).toBeNull();});});@@ -402,7 +407,7 @@ interface FakeNoteOptions {labels?: Record<string, string>;relations?: Record<string, string>;snippets?: (ShareNote | null)[];- content?: string;+ content?: string | Uint8Array;type?: string;mime?: string;icon?: string;diff --git a/packages/share-theme/src/page/footer.spec.ts b/packages/share-theme/src/page/footer.spec.tsindex 4998d23e69..83f81bd897 100644--- a/packages/share-theme/src/page/footer.spec.ts+++ b/packages/share-theme/src/page/footer.spec.ts@@ -26,4 +26,16 @@ describe("setupFooter", () => {expect(valid.textContent).toMatch(/Oktober 2026$/);expect(invalid.textContent).toBe("kept");});++ it("writes the dates out in the browser's language when the page has none", () => {+ document.body.innerHTML = `+ <footer id="content-footer"><time datetime="2026-10-09T12:00:00.000Z"></time></footer>+ `;++ setupFooter();++ const expected = new Intl.DateTimeFormat(undefined, { dateStyle: "long" })+ .format(new Date("2026-10-09T12:00:00.000Z"));+ expect(document.querySelector("time")?.textContent).toBe(expected);+ });});diff --git a/packages/share-theme/src/page/layout.spec.ts b/packages/share-theme/src/page/layout.spec.tsnew file mode 100644index 0000000000..30a09fdc82--- /dev/null+++ b/packages/share-theme/src/page/layout.spec.ts@@ -0,0 +1,75 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";++import setupLayout from "./layout.js";++describe("setupLayout", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ document.body.className = "";+ document.documentElement.className = "";+ localStorage.clear();+ vi.unstubAllGlobals();+ });++ it("collapses a pane on a wide screen and remembers it", () => {+ vi.stubGlobal("innerWidth", 1024);+ renderPage();++ click("left-pane-toggle-button");+ expect(document.documentElement.classList.contains("left-pane-collapsed")).toBe(true);+ expect(localStorage.getItem("left-pane-collapsed")).toBe("true");++ click("toc-pane-toggle-button");+ click("left-pane-toggle-button");+ expect(document.documentElement.className).toBe("toc-pane-collapsed");+ expect(localStorage.getItem("left-pane-collapsed")).toBe("false");+ expect(localStorage.getItem("toc-pane-collapsed")).toBe("true");+ });++ it("opens one pane at a time on a narrow screen, closed by the backdrop or a return", () => {+ vi.stubGlobal("innerWidth", 768);+ renderPage();++ click("left-pane-toggle-button");+ expect(document.body.className).toBe("menu-open");+ click("toc-pane-toggle-button");+ expect(document.body.className).toBe("toc-open");+ expect(localStorage.length).toBe(0);++ click("mobile-backdrop");+ expect(document.body.className).toBe("");++ click("left-pane-toggle-button");+ window.dispatchEvent(pageShow(false));+ expect(document.body.className).toBe("menu-open");+ window.dispatchEvent(pageShow(true));+ expect(document.body.className).toBe("");+ });++ it("leaves out the controls a page does not have", () => {+ expect(() => setupLayout()).not.toThrow();+ });+});++function renderPage() {+ document.body.innerHTML = `+ <button id="left-pane-toggle-button"></button>+ <button id="toc-pane-toggle-button"></button>+ <div id="mobile-backdrop"></div>+ `;+ setupLayout();+}++function click(id: string) {+ const element = document.getElementById(id);+ if (!element) {+ throw new Error(`#${id} is missing.`);+ }+ element.click();+}++/** A `pageshow` event, for a page restored from the back/forward cache when `persisted`. */+function pageShow(persisted: boolean) {+ return Object.assign(new Event("pageshow"), { persisted });+}diff --git a/packages/share-theme/src/page/navigation.spec.ts b/packages/share-theme/src/page/navigation.spec.tsnew file mode 100644index 0000000000..3daf0e5f87--- /dev/null+++ b/packages/share-theme/src/page/navigation.spec.ts@@ -0,0 +1,64 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";++import setupExpanders from "./navigation.js";++describe("setupExpanders", () => {+ afterEach(() => {+ document.body.innerHTML = "";+ vi.useRealTimers();+ });++ it("expands and collapses a page's subtree, animating its height", () => {+ vi.useFakeTimers();+ document.body.innerHTML = `+ <nav id="menu">+ <ul>+ <li class="submenu-item">+ <a href="./parent">Parent <span class="collapse-button"></span></a>+ <ul><li><a href="./child">Child</a></li></ul>+ </li>+ </ul>+ </nav>+ `;+ const item = document.querySelector(".submenu-item");+ const subtree = item?.querySelector("ul");+ const expander = item?.querySelector<HTMLElement>(".collapse-button");+ if (!item || !subtree || !expander) {+ throw new Error("The tree is incomplete.");+ }+ Object.defineProperty(subtree, "scrollHeight", { value: 40 });+ setupExpanders();++ const click = new MouseEvent("click", { bubbles: true, cancelable: true });+ expander.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(true);+ expect(item.classList.contains("expanded")).toBe(true);+ expect(subtree.style.height).toBe("40px");+ vi.advanceTimersByTime(200);+ expect(subtree.style.height).toBe("");++ expander.click();+ expect(item.classList.contains("expanded")).toBe(false);+ expect(subtree.style.height).toBe("0px");+ vi.advanceTimersByTime(200);+ expect(subtree.style.height).toBe("");+ });++ it("ignores an expander without a subtree or outside a list item", () => {+ document.body.innerHTML = `+ <nav id="menu">+ <div class="submenu-item"><span class="collapse-button" id="loose"></span></div>+ <ul>+ <li class="submenu-item"><span class="collapse-button" id="leaf"></span></li>+ </ul>+ </nav>+ `;+ setupExpanders();++ document.getElementById("loose")?.click();+ document.getElementById("leaf")?.click();++ expect(document.querySelector(".expanded")).toBeNull();+ });+});diff --git a/packages/share-theme/src/page/search.spec.ts b/packages/share-theme/src/page/search.spec.tsindex cb83eda9da..9e5b55861f 100644--- a/packages/share-theme/src/page/search.spec.ts+++ b/packages/share-theme/src/page/search.spec.ts@@ -1,7 +1,8 @@+// @vitest-environment happy-domimport type { FuseResultMatch } from "fuse.js";-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";-import { buildStaticSnippet } from "./search.js";+import setupSearch, { buildStaticSnippet } from "./search.js";describe("buildStaticSnippet", () => {const contentMatch = (...indices: [number, number][]): FuseResultMatch => ({@@ -101,3 +102,110 @@ describe("buildStaticSnippet", () => {expect(result).toBe("abc def ghi");});});++describe("setupSearch", () => {+ afterEach(() => {+ document.head.innerHTML = "";+ document.body.innerHTML = "";+ delete window.glob;+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it("asks the server once typing pauses and lists the first five results", async () => {+ const fetchMock = vi.fn(async (_url: string) => Response.json({ results: [+ { id: "a", title: "<A>", path: "Home > Docs", highlightedSnippet: "<b>abc</b>" },+ { id: "b", title: "B", path: "", snippet: "<plain>" },+ { id: "c", title: "C", path: "Docs" },+ { id: "d", title: "D", path: "Docs" },+ { id: "e", title: "E", path: "Docs" },+ { id: "f", title: "F", path: "Docs" }+ ] }));+ const input = renderSearch(fetchMock);+ document.body.dataset.ancestorNoteId = "root";++ await type(input, "ab");+ expect(fetchMock).not.toHaveBeenCalled();++ await type(input, "a&b c");+ expect(fetchMock.mock.calls.map(([ url ]) => url))+ .toEqual([ "api/notes?search=a%26b+c&ancestorNoteId=root" ]);+ const items = [ ...document.querySelectorAll<HTMLAnchorElement>(".search-results a") ];+ expect(items.map((item) => item.getAttribute("href")))+ .toEqual([ "./a", "./b", "./c", "./d", "./e" ]);+ expect(items[0].querySelector(".search-result-title")?.textContent).toBe("<A>");+ expect(items[0].querySelector(".search-result-snippet")?.innerHTML).toBe("<b>abc</b>");+ expect(items[1].querySelector(".search-result-note")?.textContent).toBe("Home");+ expect(items[1].querySelector(".search-result-snippet")?.textContent).toBe("<plain>");+ expect(items[2].querySelector(".search-result-snippet")).toBeNull();++ delete document.body.dataset.ancestorNoteId;+ await type(input, "abc");+ expect(fetchMock).toHaveBeenLastCalledWith("api/notes?search=abc&ancestorNoteId=");+ expect(document.querySelectorAll(".search-results")).toHaveLength(1);+ });++ it("closes the results on a click outside them and the search box", async () => {+ const input = renderSearch(vi.fn(async () => Response.json({ results: [] })));+ document.body.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ await type(input, "abc");+ const click = () => new MouseEvent("click", { bubbles: true });+ document.querySelector(".search-results")?.dispatchEvent(click());+ input.dispatchEvent(click());+ expect(document.querySelector(".search-results")).not.toBeNull();++ document.body.dispatchEvent(click());+ expect(document.querySelector(".search-results")).toBeNull();+ });++ it("searches the index of a static export, loaded once", async () => {+ window.glob = { isStatic: true, theme: "light" };+ document.head.innerHTML = `<link rel="stylesheet" href="../../assets/style.css">`;+ const fetchMock = vi.fn(async (_url: string) => Response.json([+ { id: "drip", title: "Treatment", path: "Home", content: "Patient on magnesium drip." },+ { id: "other", title: "Unrelated", path: "Home", content: "Nothing here." }+ ]));+ const input = renderSearch(fetchMock);++ await type(input, "'magnesium");+ await type(input, "'treatment");++ const item = await vi.waitFor(() => {+ const result = document.querySelector<HTMLAnchorElement>(".search-results a");+ expect(result).not.toBeNull();+ return result;+ });+ expect(fetchMock.mock.calls.map(([ url ]) => url)).toEqual([ "../../search-index.json" ]);+ expect(document.querySelectorAll(".search-results a")).toHaveLength(1);+ expect(item?.getAttribute("href")).toBe("./../../drip");+ expect(item?.querySelector(".search-result-snippet")?.textContent)+ .toBe("Patient on magnesium drip.");+ });++ it("does nothing on a page without a search box", () => {+ expect(() => setupSearch()).not.toThrow();+ });+});++function renderSearch(fetchMock: (url: string) => Promise<Response>) {+ vi.useFakeTimers();+ vi.stubGlobal("fetch", fetchMock);+ document.body.innerHTML = `<div class="search-item"><input class="search-input"></div>`;+ setupSearch();+ const input = document.querySelector<HTMLInputElement>(".search-input");+ if (!input) {+ throw new Error("The search box is missing.");+ }+ return input;+}++/** Types a query key by key and waits out the pause after which the search runs. */+async function type(input: HTMLInputElement, query: string) {+ for (const length of query.split("").keys()) {+ input.value = query.slice(0, length + 1);+ input.dispatchEvent(new KeyboardEvent("keyup"));+ await vi.advanceTimersByTimeAsync(100);+ }+ await vi.advanceTimersByTimeAsync(500);+}diff --git a/packages/share-theme/src/page/search.ts b/packages/share-theme/src/page/search.tsindex 00a1d44b23..e3d629f949 100644--- a/packages/share-theme/src/page/search.ts+++ b/packages/share-theme/src/page/search.ts@@ -1,12 +1,9 @@import { escapeHtml } from "@triliumnext/commons/src/lib/utils.js";import type { default as Fuse, FuseResultMatch } from "fuse.js";-import debounce from "../common/debounce.js";-import parents from "../common/parents.js";-import parseHTML from "../common/parsehtml.js";import "./search.css";-let fuseInstance: Fuse<SearchResult> | null = null;+let fuseIndex: Promise<Fuse<SearchResult>> | undefined;interface SearchResults {results: SearchResult[];@@ -46,19 +43,13 @@ export default function setupSearch() {}searchInput.addEventListener("keyup", debounce(async () => {- // console.log("CHANGE EVENT");const query = searchInput.value;if (query.length < 3) return;const resp = await fetchResults(query);- const results = resp.results.slice(0, 5);- const lines = [`<div class="search-results">`];- for (const result of results) {- lines.push(buildResultItem(result));- }- lines.push("</div>");+ const container = document.createElement("div");+ container.className = "search-results";+ container.innerHTML = resp.results.slice(0, 5).map(buildResultItem).join("");- const container = parseHTML(lines.join("")) as HTMLDivElement;- // console.log(container, lines);const rect = searchInput.getBoundingClientRect();container.style.top = `${rect.bottom}px`;container.style.left = `${rect.left}px`;@@ -72,12 +63,22 @@ export default function setupSearch() {window.addEventListener("click", e => {const existing = document.querySelector(".search-results");if (!existing) return;- // If the click was anywhere search components ignore it- if (parents(e.target as HTMLElement, ".search-results,.search-item").length) return;- if (existing) existing.remove();+ // A click inside the results or the search box keeps the results open.+ if (e.target instanceof Element && e.target.closest(".search-results, .search-item")) {+ return;+ }+ existing.remove();});}+function debounce(executor: () => Promise<void>, delay: number) {+ let timeout: ReturnType<typeof setTimeout> | undefined;+ return () => {+ clearTimeout(timeout);+ timeout = setTimeout(executor, delay);+ };+}+/*** Build a content snippet around the first Fuse match for the static-export search index.* Returns an HTML string with the matched ranges wrapped in <b>...</b>.@@ -139,29 +140,9 @@ async function fetchResults(query: string): Promise<SearchResults> {const linkHref = document.head.querySelector("link[rel=stylesheet]")?.getAttribute("href");const rootUrl = linkHref?.split("/").slice(0, -2).join("/") || ".";- if ((window as any).glob.isStatic) {- // Load the search index.- if (!fuseInstance) {- const searchIndex = await (await fetch(`${rootUrl}/search-index.json`)).json();- const Fuse = (await import("fuse.js")).default;- fuseInstance = new Fuse(searchIndex, {- keys: [- "title",- "content"- ],- includeScore: true,- includeMatches: true,- threshold: 0.65,- ignoreDiacritics: true,- ignoreLocation: true,- ignoreFieldNorm: true,- useExtendedSearch: true- });- }-- // Do the search.- const results = fuseInstance.search(query, { limit: 5 });- console.debug("Search results:", results);+ if (window.glob?.isStatic) {+ fuseIndex ??= loadSearchIndex(rootUrl);+ const results = (await fuseIndex).search(query, { limit: 5 });const processedResults = results.map(({ item, score, matches }) => {const itemWithContent = item as SearchResult & { content?: string };const highlightedSnippet = buildStaticSnippet(itemWithContent.content, matches);@@ -175,7 +156,27 @@ async function fetchResults(query: string): Promise<SearchResults> {return { results: processedResults };} else {const ancestor = document.body.dataset.ancestorNoteId;- const resp = await fetch(`api/notes?search=${query}&ancestorNoteId=${ancestor}`);+ const params = new URLSearchParams({ search: query, ancestorNoteId: ancestor ?? "" });+ const resp = await fetch(`api/notes?${params}`);return await resp.json() as SearchResults;}}++/** Loads the search index of a static export, which every later search of the page reuses. */+async function loadSearchIndex(rootUrl: string) {+ const searchIndex = await (await fetch(`${rootUrl}/search-index.json`)).json();+ const Fuse = (await import("fuse.js")).default;+ return new Fuse<SearchResult>(searchIndex, {+ keys: [+ "title",+ "content"+ ],+ includeScore: true,+ includeMatches: true,+ threshold: 0.65,+ ignoreDiacritics: true,+ ignoreLocation: true,+ ignoreFieldNorm: true,+ useExtendedSearch: true+ });+}diff --git a/packages/share-theme/src/page/theme_switch.spec.ts b/packages/share-theme/src/page/theme_switch.spec.tsindex 3b154fb6ed..43f92b1aa4 100644--- a/packages/share-theme/src/page/theme_switch.spec.ts+++ b/packages/share-theme/src/page/theme_switch.spec.ts@@ -25,5 +25,14 @@ describe("setupThemeSelector", () => {input.dispatchEvent(new Event("change"));expect(document.documentElement.className).toBe("theme-light");expect(localStorage.getItem("theme")).toBe("light");++ input.checked = true;+ input.dispatchEvent(new Event("change"));+ expect(document.documentElement.className).toBe("theme-dark");+ expect(localStorage.getItem("theme")).toBe("dark");+ });++ it("does nothing on a page without the switch", () => {+ expect(() => setupThemeSelector()).not.toThrow();});});diff --git a/packages/share-theme/src/page/toc.spec.ts b/packages/share-theme/src/page/toc.spec.tsindex 0ae54812a3..68d4e507a6 100644--- a/packages/share-theme/src/page/toc.spec.ts+++ b/packages/share-theme/src/page/toc.spec.ts@@ -36,6 +36,24 @@ describe("setupToC", () => {expect(scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth" });});++ it("leaves an entry without a heading to the browser, and a page without one alone", () => {+ expect(() => setupToC()).not.toThrow();++ document.body.innerHTML = `+ <div id="right-pane">+ <ul id="toc"><li><a href="#missing">Missing</a></li><li><a>No link</a></li></ul>+ </div>+ `;+ setupToC();++ for (const link of document.querySelectorAll("#toc a")) {+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });+ link.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(false);+ }+ expect(activeEntry()).toBeUndefined();+ });});/**diff --git a/packages/share-theme/src/page/toc.ts b/packages/share-theme/src/page/toc.tsindex 4edbf2fcd7..c4e6950b73 100644--- a/packages/share-theme/src/page/toc.ts+++ b/packages/share-theme/src/page/toc.ts@@ -18,12 +18,11 @@ export default function setupToC() {const toc = document.getElementById("toc");if (!toc || !container) return;- // Get all relevant elementsconst sections = [ ...document.querySelectorAll("#content .toc-anchor") ]- .map((anchor) => anchor.parentElement);- const links = toc.querySelectorAll("a");+ .map((anchor) => anchor.parentElement)+ .filter((heading) => heading !== null);+ const links = [ ...toc.querySelectorAll("a") ];- // Setup smooth scroll on clickfor (const link of links) {link.addEventListener("click", e => {const target = document.getElementById(link.getAttribute("href")?.slice(1) ?? "");@@ -37,19 +36,18 @@ export default function setupToC() {});}- // Setup a moving "active" in the ToC that adjusts with the scroll state- function changeLinkState() {+ // Marks the entry of the last section scrolled past, or the first entry above every section.+ const changeLinkState = () => {let index = sections.length;+ while (--index > 0 && container.scrollTop + 50 < sections[index].offsetTop) {+ // Walk back to the last section scrolled past.+ }- // Work backwards to find the first matching section- while (--index && container!.scrollTop + 50 < (sections[index] as HTMLElement).offsetTop) {} // eslint-disable-line no-empty+ for (const [ linkIndex, link ] of links.entries()) {+ link.classList.toggle("active", linkIndex === index);+ }+ };- // Update the "active" item in ToC- links.forEach((link) => link.classList.remove("active"));- links[index].classList.add("active");- }-- // Initial renderchangeLinkState();container.addEventListener("scroll", changeLinkState);}diff --git a/packages/share-theme/src/types.d.ts b/packages/share-theme/src/types.d.tsindex 006c1f7b02..c6f2abbcf8 100644--- a/packages/share-theme/src/types.d.ts+++ b/packages/share-theme/src/types.d.ts@@ -1 +1,9 @@declare module "katex/contrib/mhchem" {}++interface Window {+ /** Set by `boot_script.ejs` before the first paint. */+ glob?: {+ isStatic: boolean;+ theme: string;+ };+}diff --git a/packages/share-theme/vitest.config.ts b/packages/share-theme/vitest.config.tsindex 3a5b305bc5..0186a37317 100644--- a/packages/share-theme/vitest.config.ts+++ b/packages/share-theme/vitest.config.ts@@ -1,7 +1,41 @@+import { resolve } from "node:path";+import { defineConfig } from "vitest/config";export default defineConfig({+ plugins: [+ {+ // Stands in for the build script's `virtual:code-themes.css`, which `index.ts` imports.+ name: "code-themes",+ resolveId: (id) => (id === "virtual:code-themes.css" ? `\0${id}` : null),+ load: (id) => (id === "\0virtual:code-themes.css" ? "" : null)+ }+ ],test: {- include: [ "src/**/*.spec.ts" ]+ include: [ "src/**/*.spec.ts" ],+ environmentOptions: {+ happyDOM: {+ settings: { disableCSSFileLoading: true, handleDisabledFileLoadingAsSuccess: true }+ }+ },+ reporters: [+ "default",+ [ "junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true } ]+ ],+ coverage: {+ thresholds: {+ lines: 100,+ functions: 100,+ branches: 100,+ statements: 100+ },+ reportsDirectory: "./test-output/vitest/coverage",+ provider: "v8",+ include: [ "src/**/*.ts" ],+ exclude: [ "src/**/*.spec.ts", "src/**/*.d.ts" ],+ // Codecov matches an lcov `SF:` path against the files of the whole repository, where a+ // package-relative `src/index.ts` is ambiguous.+ reporter: [ "text", "html", [ "lcov", { projectRoot: resolve(__dirname, "../..") } ] ]+ }}});