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
server/share pages: fix some issues
Adorian Doran2be7329c8d61
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 6cbbb475d5..c7b0911948 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -642,9 +642,19 @@ describe("rewriteMermaidDiagramsInContainer", () => {const div = container.querySelector("div.mermaid-diagram");expect(div).not.toBeNull();expect(div?.textContent).toContain("graph TD;");+ expect(div?.hasAttribute("data-trilium-block-id")).toBe(false);expect(container.querySelector("pre")).toBeNull();});+ it("keeps the block ID of a code block on its diagram, for links to the block", async () => {+ const container = document.createElement("div");+ container.innerHTML = `<pre><code class="language-mermaid" data-trilium-block-id="d1">`+ + `graph TD;A-->B;</code></pre>`;+ await rewriteMermaidDiagramsInContainer(container);+ const diagram = container.querySelector("div.mermaid-diagram");+ expect(diagram?.getAttribute("data-trilium-block-id")).toBe("d1");+ });+it("uses an empty body when the code element is missing", async () => {const container = document.createElement("div");// A <pre> matched by :has(code) whose <code> has no inner content, so thediff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex c8df92a5d5..4939d0203b 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -1,6 +1,7 @@import {- type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey, getNestedEmbedOptions,- getNoteEmbedHref, KATEX_MACROS, resolveContentEmbed, sliceToBlockReference+ BLOCK_ID_ATTRIBUTE, type ContentEmbedContext, getAttachmentEmbedHref, getEmbedKey,+ getNestedEmbedOptions, getNoteEmbedHref, KATEX_MACROS, resolveContentEmbed,+ sliceToBlockReference} from "@triliumnext/commons";import FAttachment from "../entities/fattachment.js";@@ -194,6 +195,10 @@ export async function rewriteMermaidDiagramsInContainer(container: HTMLDivElemenconst div = document.createElement("div");div.classList.add("mermaid-diagram");div.textContent = code.textContent;+ const blockId = code.getAttribute(BLOCK_ID_ATTRIBUTE);+ if (blockId) {+ div.setAttribute(BLOCK_ID_ATTRIBUTE, blockId);+ }mermaidBlock.replaceWith(div);}}diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.tsindex 57c3c02c60..acca9d73da 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts@@ -68,6 +68,23 @@ describe("showBlockReference", () => {expect(getOffset(scroller, "from")).toBeCloseTo(100);});+ it("opens a collapsed block around the end of a range before measuring the range", () => {+ // Some browsers give the content of a closed `<details>` no box at all.+ const scroller = mountScroller(+ "<style>details:not([open]) > :not(summary) { display: none; }</style>"+ + SPACER + block("from", 50) + "<details><summary>s</summary>" + block("to", 50)+ + "</details>" + SPACER+ );+ const details = scroller.querySelector("details");++ showBlockReference(scroller, "from:to");++ expect(details?.open).toBe(true);+ const height = getBlock(scroller, "to").getBoundingClientRect().bottom+ - getBlock(scroller, "from").getBoundingClientRect().top;+ expect(getOffset(scroller, "from")).toBeCloseTo((400 - height) / 2);+ });+it("scrolls the document when no ancestor of the blocks scrolls", () => {const page = mount("<div style=\"overflow-x: auto\">"+ SPACER + SPACER + block("a", 100) + SPACER + SPACER + "</div>");diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.tsindex cbf757b542..6ab52f1fc8 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts@@ -22,6 +22,8 @@ export function showBlockReference(container: Element, value: string) {const first = start ?? end;if (first) {const last = start && end ? end : first;+ // `first` is revealed last, so it stays shown when both are in different tabs of a block.+ reveal(last);reveal(first);scrollToBlocks(first, last);flashBlocks(getBlockRangeElements(first, last));diff --git a/packages/share-theme/src/content/mermaid.spec.ts b/packages/share-theme/src/content/mermaid.spec.tsindex 68fabc130a..4eb57496f6 100644--- a/packages/share-theme/src/content/mermaid.spec.ts+++ b/packages/share-theme/src/content/mermaid.spec.ts@@ -54,6 +54,18 @@ describe("setupMermaid", () => {expect(diagram?.querySelector("svg")?.id).not.toBe(firstId);});+ it("keeps the block ID of a code block on its drawing, for links to the block", async () => {+ stubMermaid();+ document.body.innerHTML = `<div id="content"><pre>`+ + `<code class="language-mermaid" data-trilium-block-id="d1">graph TD; A-->B</code>`+ + `</pre></div>`;++ await setupMermaid();++ expect(document.querySelector("#content > .mermaid")?.getAttribute("data-trilium-block-id"))+ .toBe("d1");+ });+it("draws a Mermaid note in place of its image, keeping the source", async () => {const fakeMermaid = stubMermaid();document.body.innerHTML = MERMAID_NOTE;diff --git a/packages/share-theme/src/content/mermaid.ts b/packages/share-theme/src/content/mermaid.tsindex abb0c8fa18..22ee4de074 100644--- a/packages/share-theme/src/content/mermaid.ts+++ b/packages/share-theme/src/content/mermaid.ts@@ -36,6 +36,8 @@ interface Diagram {/** The element the drawings go into. */element: HTMLElement;source: string;+ /** The block ID of a code block, which its drawing keeps for links to the block. */+ blockId?: string;}/** The diagrams on the page, each with the element its drawing replaces. */@@ -43,9 +45,13 @@ function findDiagrams() {const placeholders: Omit<Diagram, "element">[] = [];for (const block of document.querySelectorAll("#content pre")) {- const code = block.querySelector(":scope > code.language-mermaid");+ const code = block.querySelector<HTMLElement>(":scope > code.language-mermaid");if (code) {- placeholders.push({ placeholder: block, source: code.textContent });+ placeholders.push({+ placeholder: block,+ source: code.textContent,+ blockId: code.dataset.triliumBlockId+ });}}@@ -60,6 +66,9 @@ function findDiagrams() {return placeholders.map((placeholder): Diagram => {const element = document.createElement("div");element.classList.add("mermaid");+ if (placeholder.blockId) {+ element.dataset.triliumBlockId = placeholder.blockId;+ }return { ...placeholder, element };});}diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.tsindex 651c947857..f7eabcac41 100644--- a/packages/share-theme/src/index.spec.ts+++ b/packages/share-theme/src/index.spec.ts@@ -112,13 +112,20 @@ describe("share theme entry", () => {expect(panel.scrollIntoView).toHaveBeenCalledTimes(2);});- it("shows the blocks the address links to once the page is shown, after the tabs", async () => {+ it("shows the linked blocks once the page is shown, after the tabs and diagrams", async () => {+ let drawDiagrams = () => {};+ mocks.setupMermaid.mockReturnValueOnce(new Promise<void>((resolve) => {+ drawDiagrams = resolve;+ }));document.body.className = "type-text";document.body.innerHTML = `<div id="content"></div>`;history.replaceState(null, "", "?block=a%201:b");document.dispatchEvent(new Event("DOMContentLoaded"));+ await vi.dynamicImportSettled();+ expect(mocks.showBlockReference).not.toHaveBeenCalled();+ drawDiagrams();await vi.waitFor(() => expect(mocks.showBlockReference).toHaveBeenCalledExactlyOnceWith(document.body, "a 1:b"));expect(mocks.whenActivated).toHaveBeenCalledOnce();diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex a979c9fbc3..554917e309 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -31,12 +31,16 @@ import "@triliumnext/ckeditor5/src/theme/todo_lists.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";-/** Runs a setup function, logging what it throws or rejects with instead of stopping the others. */-function $try(func: () => unknown) {+/**+ * Runs a setup function, logging what it throws or rejects with instead of stopping the others.+ * Returns a promise that settles once the function is done, and never rejects.+ */+function $try(func: () => unknown): Promise<unknown> {try {- Promise.resolve(func()).catch(console.error);+ return Promise.resolve(func()).catch(console.error);} catch (e) {console.error(e);+ return Promise.resolve();}}@@ -60,17 +64,20 @@ $try(setupSearch);$try(setupFooter);$try(setupSpeculation);+/** Enhances the content of a text note. Returns a promise that settles once diagrams are drawn. */function setupTextNote() {- $try(setupMermaid);+ const diagrams = $try(setupMermaid);$try(setupMath);$try(() => enhanceLinkPreviews(document.body));$try(setupTabs);+ return diagrams;}document.addEventListener("DOMContentLoaded", () => {const { classList } = document.body;+ let diagrams: Promise<unknown> | undefined;if (classList.contains("type-text") || document.querySelector("#content.ck-content")) {- setupTextNote();+ diagrams = setupTextNote();} else if (document.querySelector("#content .share-note-view")) {$try(() => setupAppView(".share-note-view", () => import("./content/note_view.js")));} else if (classList.contains("type-mermaid")) {@@ -78,7 +85,7 @@ document.addEventListener("DOMContentLoaded", () => {} else if (classList.contains("type-book")) {$try(() => setupAppView(".share-collection", () => import("./content/collection_view.js")));}- whenActivated(() => $try(showLinkedBlocks));+ whenActivated(() => $try(() => showLinkedBlocks(diagrams)));});function setupTabs() {@@ -93,12 +100,16 @@ function setupTabs() {window.addEventListener("hashchange", showFragment);}-/** Scrolls to the blocks that the `block` URL parameter points at and flashes them. */-async function showLinkedBlocks() {+/**+ * Scrolls to the blocks that the `block` URL parameter points at and flashes them, once `diagrams`+ * are drawn: a drawing replaces its code block and changes the height of the page.+ */+async function showLinkedBlocks(diagrams?: Promise<unknown>) {const block = new URLSearchParams(location.search).get("block");if (block) {- const { showBlockReference } = await import(- "@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js");+ const [ { showBlockReference } ] = await Promise.all([ import(+ "@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js"+ ), diagrams ]);showBlockReference(document.body, block);}}