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
client/text editor/block references: highlight the target blocks in the note tooltips for links containing block references
Adorian Doran2f5976f98e5f
diff --git a/apps/client/src/services/block_reference.css b/apps/client/src/services/block_reference.cssindex bdd1c3b234..d0729b8914 100644--- a/apps/client/src/services/block_reference.css+++ b/apps/client/src/services/block_reference.css@@ -21,6 +21,12 @@}}+.block-reference-highlight {+ box-shadow:+ 0 0 0 4px var(--block-reference-flash-color),+ inset 0 0 0 100vmax var(--block-reference-flash-color);+}+.block-reference-broken {color: var(--block-reference-broken-color);font-style: italic;diff --git a/apps/client/src/services/block_reference.spec.ts b/apps/client/src/services/block_reference.spec.tsindex 342b788c64..268cf66355 100644--- a/apps/client/src/services/block_reference.spec.ts+++ b/apps/client/src/services/block_reference.spec.ts@@ -2,7 +2,8 @@ import type { CKTextEditor } from "@triliumnext/ckeditor5";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {- consumeBlockReference, copyBlockReference, getBlockRangeElements, openBlockHandleMenu+ consumeBlockReference, copyBlockReference, getBlockRangeElements, highlightBlockReference,+ openBlockHandleMenu, revealHighlightedBlocks} from "./block_reference.js";import type { ViewScope } from "./link.js";@@ -109,6 +110,64 @@ describe("getBlockRangeElements", () => {});});+describe("highlightBlockReference", () => {+ it("highlights a range and opens the collapsed blocks at its ends", () => {+ const container = buildContainer(+ "<details><summary>s1</summary><p data-trilium-block-id=\"a\">A</p></details>"+ + "<blockquote><p>quote</p></blockquote>"+ + "<details><summary>s2</summary><p data-trilium-block-id=\"b\">B</p></details>"+ );++ highlightBlockReference(container, "a:b");++ expect(getHighlighted(container)).toEqual([ "A", "quote", "s2", "B" ]);+ expect([ ...container.querySelectorAll("details") ].map((details) => details.open))+ .toEqual([ true, true ]);+ });++ it("highlights the block found of a broken range, and nothing for a missing block", () => {+ const container = buildContainer("<p data-trilium-block-id=\"b\">B</p><p>other</p>");++ highlightBlockReference(container, "gone");+ highlightBlockReference(container, "a:b:c");+ expect(getHighlighted(container)).toEqual([]);++ highlightBlockReference(container, "gone:b");+ expect(getHighlighted(container)).toEqual([ "B" ]);+ });+});++describe("revealHighlightedBlocks", () => {+ it("centers the highlighted blocks, or scrolls to their top when they don't fit", () => {+ const container = buildContainer(+ "<p>before</p><p class=\"block-reference-highlight\">A</p>"+ + "<p class=\"block-reference-highlight\">B</p>"+ );+ const [ , first, last ] = container.querySelectorAll("p");+ Object.defineProperty(container, "clientHeight", { value: 300 });+ stubRect(container, 100, 400);+ stubRect(first, 600, 650);+ stubRect(last, 650, 700);++ revealHighlightedBlocks(container);+ expect(container.scrollTop).toBe(400);++ container.scrollTop = 0;+ stubRect(last, 650, 1200);+ revealHighlightedBlocks(container);+ expect(container.scrollTop).toBe(500);+ });++ it("leaves the scroll position alone without highlighted blocks", () => {+ const container = buildContainer("<p>A</p>");+ container.scrollTop = 20;++ revealHighlightedBlocks(container);++ expect(container.scrollTop).toBe(20);+ });+});+describe("copyBlockReference", () => {it("copies a link to the selected blocks, named by their text, and flashes them", async () => {const root = buildContainer(@@ -168,6 +227,15 @@ function getFlashed(container: HTMLElement) {.map((element) => element.textContent);}+function getHighlighted(container: HTMLElement) {+ return [ ...container.querySelectorAll(".block-reference-highlight") ]+ .map((element) => element.textContent);+}++function stubRect(element: Element, top: number, bottom: number) {+ vi.spyOn(element, "getBoundingClientRect").mockReturnValue({ top, bottom } as DOMRect);+}+function buildEditor(root: HTMLElement, target: unknown) {return {execute: vi.fn(() => target),diff --git a/apps/client/src/services/block_reference.ts b/apps/client/src/services/block_reference.tsindex 8b405c5dfe..eca0e9a209 100644--- a/apps/client/src/services/block_reference.ts+++ b/apps/client/src/services/block_reference.ts@@ -12,6 +12,7 @@ import toast from "./toast.js";const FLASH_CLASS = "block-reference-flash";/** The duration of the `block-reference-flash` animation in `block_reference.css`. */const FLASH_DURATION_MS = 1500;+const HIGHLIGHT_CLASS = "block-reference-highlight";/** Opens the menu of the block handle at `event`, which copies a reference to `count` blocks. */export function openBlockHandleMenu(event: MouseEvent, count: number, copyReference: () => void) {@@ -80,6 +81,45 @@ export function consumeBlockReference(}}+/**+ * Highlights the blocks that `value`, a `block` link parameter, points at in `container`, and opens+ * the collapsed blocks around its first and last block. Of a broken range, the block found is+ * highlighted.+ */+export function highlightBlockReference(container: HTMLElement, value: string) {+ const { start, end } = resolveBlockReference<HTMLElement>(container, value);+ const first = start ?? end;+ if (!first) {+ return;+ }++ for (const block of [ start, end ]) {+ if (block) {+ expandAncestorDetails(block);+ }+ }+ const elements = start && end ? getBlockRangeElements(start, end) : [ first ];+ for (const element of elements) {+ element.classList.add(HIGHLIGHT_CLASS);+ }+}++/** Scrolls `container` to center its highlighted blocks, or to their top if they do not fit. */+export function revealHighlightedBlocks(container: HTMLElement) {+ const blocks = Array.from(container.querySelectorAll(`.${HIGHLIGHT_CLASS}`));+ const first = blocks.at(0);+ const last = blocks.at(-1);+ if (!first || !last) {+ return;+ }++ const top = first.getBoundingClientRect().top;+ const height = last.getBoundingClientRect().bottom - top;+ const viewportTop = container.getBoundingClientRect().top + container.clientTop;+ const margin = Math.max(0, (container.clientHeight - height) / 2);+ container.scrollTop += top - viewportTop - margin;+}+/** The outermost elements inside the range from `start` to `end`, both included. */export function getBlockRangeElements(start: Element, end: Element) {const range = start.ownerDocument.createRange();diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex 5430c4b936..6d21c71bd2 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -70,6 +70,8 @@ export interface RenderOptions {block?: string;/** Points the embed of `block` at the blocks that its editor holds, once they change. */onBlockChange?: (block: string) => void;+ /** The blocks of a text note to highlight, a `block` link parameter. Embeds are left out. */+ highlightBlock?: string;showTextRepresentation?: boolean;/*** If enabled, note types that have a richer live representation (currently only web views) arediff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.tsindex 65031b1f0e..854b3106d0 100644--- a/apps/client/src/services/content_renderer_text.spec.ts+++ b/apps/client/src/services/content_renderer_text.spec.ts@@ -827,6 +827,26 @@ describe("Block embeds", () => {expect(contentEl.querySelectorAll(".include-note[data-block='loop']")).toHaveLength(1);});+ it("highlights the referenced blocks of the note, not those of its embeds", async () => {+ buildNote({+ id: "hlSource",+ title: "Source",+ content: "<p data-trilium-block-id=\"b1\">Embedded</p>"+ });+ const note = buildNote({+ title: "Host",+ content: blockEmbed("hlSource", "b1")+ + "<p data-trilium-block-id=\"b1\">Own</p><p data-trilium-block-id=\"b2\">Next</p>"+ + "<p>Outro</p>"+ });+ const contentEl = document.createElement("div");++ await renderText(note, $(contentEl), { highlightBlock: "b1:b2" });++ expect([ ...contentEl.querySelectorAll(".block-reference-highlight") ]+ .map((element) => element.textContent)).toEqual([ "Own", "Next" ]);+ });+it("links to the blocks of an embed one level down", async () => {const note = buildNote({ title: "Host", content: blockEmbed("blkSource", "b1:b 2") });const contentEl = document.createElement("div");diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.tsindex 8f2a7bc5a9..c6b3930af4 100644--- a/apps/client/src/services/content_renderer_text.ts+++ b/apps/client/src/services/content_renderer_text.ts@@ -2,6 +2,7 @@ import { encodeBlockParameter, KATEX_MACROS, sliceToBlockReference } from "@trilimport FAttachment from "../entities/fattachment.js";import FNote from "../entities/fnote.js";+import { highlightBlockReference } from "./block_reference.js";import { default as content_renderer, type RenderOptions } from "./content_renderer.js";import froca from "./froca.js";import { t } from "./i18n.js";@@ -39,6 +40,10 @@ export async function renderTextContent(.addClass("block-reference-broken").text(t("block_reference.broken")));} else if (hasContent) {+ // Runs before `postProcessRichContent()` renders embeds, so their blocks are not searched.+ if (options.highlightBlock) {+ highlightBlockReference($content[0], options.highlightBlock);+ }$renderedContent.append($content);await postProcessRichContent(note, $renderedContent, options);} else if (note instanceof FNote && !options.noChildrenList) {diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.tsindex 87f156d81c..2056e974bc 100644--- a/apps/client/src/services/note_tooltip.spec.ts+++ b/apps/client/src/services/note_tooltip.spec.ts@@ -9,6 +9,7 @@ const {getRenderedContent,getNoteTitleWithPathAsSuffix,getActiveContext,+ revealHighlightedBlocks,t} = vi.hoisted(() => ({parseNavigationStateFromUrl: vi.fn(),@@ -16,6 +17,7 @@ const {getRenderedContent: vi.fn(),getNoteTitleWithPathAsSuffix: vi.fn(),getActiveContext: vi.fn(),+ revealHighlightedBlocks: vi.fn(),t: vi.fn((key: string) => key)}));@@ -41,6 +43,8 @@ vi.mock("../components/app_context.js", () => ({vi.mock("./i18n.js", () => ({ t }));+vi.mock("./block_reference.js", () => ({ revealHighlightedBlocks }));+// Imports AFTER vi.mock calls.import DeletedFNote from "../entities/deleted_fnote.js";import froca from "./froca.js";@@ -638,6 +642,7 @@ describe("mouseEnterHandler", () => {// color class folded into the tooltip templateexpect(initCall?.[0].template).toContain("color-blue");expect(tooltipMock).toHaveBeenCalledWith("show");+ expect(revealHighlightedBlocks).not.toHaveBeenCalled();// the watchdog re-arms while still hovering...await vi.advanceTimersByTimeAsync(1000);@@ -648,6 +653,40 @@ describe("mouseEnterHandler", () => {const disposeAfter = tooltipMock.mock.calls.filter((c) => c[0] === "dispose").length;expect(disposeAfter).toBeGreaterThan(disposeBefore);});++ it("highlights the blocks of a block link and scrolls its tooltip to them", async () => {+ vi.useFakeTimers();+ const $link = makeLink('<a href="#root/abc?block=b1">x</a>');+ parseNavigationStateFromUrl.mockReturnValue({+ notePath: "root/abc",+ noteId: "abc",+ viewScope: { viewMode: "default", block: "b1" }+ });+ const note = fakeNote({ noteId: "abc", bestPath: "root/abc" });+ froca.getNote = vi.fn(async () => note) as any;+ hoverActive = true;+ // Insert the tooltip on show, as Bootstrap does.+ const $tooltip = $("<div>");+ ($.fn as any).tooltip = vi.fn(function (this: unknown, arg: unknown) {+ if (arg && typeof arg === "object" && "title" in arg) {+ $tooltip.html(String(arg.title));+ } else if (arg === "show") {+ $("body").append($tooltip.addClass(String($link.attr("data-link-id"))));+ }+ return this;+ });++ const promise = mouseEnterHandler.call($link[0], eventFor($link));+ await vi.advanceTimersByTimeAsync(600);+ await promise;++ expect(getRenderedContent)+ .toHaveBeenCalledWith(note, expect.objectContaining({ highlightBlock: "b1" }));+ const tooltipContent = $tooltip.find(".note-tooltip-content")[0];+ expect(tooltipContent).toBeDefined();+ expect(revealHighlightedBlocks).toHaveBeenCalledWith(tooltipContent);+ $tooltip.remove();+ });});/**diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.tsindex 514d6575b3..87a25bc109 100644--- a/apps/client/src/services/note_tooltip.ts+++ b/apps/client/src/services/note_tooltip.ts@@ -2,6 +2,7 @@ import appContext from "../components/app_context.js";import type FAttachment from "../entities/fattachment.js";import type FNote from "../entities/fnote.js";import attributeRenderer from "./attribute_renderer.js";+import { revealHighlightedBlocks } from "./block_reference.js";import contentRenderer from "./content_renderer.js";import froca from "./froca.js";import { t } from "./i18n.js";@@ -114,7 +115,7 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere// Default route: a live note. A missing note (deleted/erased) renders the "note has been// deleted" placeholder — content previews of deleted notes are opt-in via `data-note-deleted`.note = await froca.getNote(noteId);- renderPromise = renderTooltip(note, detail);+ renderPromise = renderTooltip(note, detail, viewScope?.block);}const [content] = await Promise.all([@@ -164,6 +165,11 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.TriggereopenTooltipElements.push($link);+ const tooltipContent = $(`.${linkId} .note-tooltip-content`).get(0);+ if (viewScope?.block && tooltipContent) {+ revealHighlightedBlocks(tooltipContent);+ }+// Dismiss the tooltip immediately if a link was clicked inside the tooltip.$(`.${tooltipClass} a`).on("click", (e) => {dismissAllTooltips();@@ -192,8 +198,13 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere* @param detail plain text the trigger element contributed about this note (see the `data-tooltip-detail`* attribute), shown under the title. Absent on the vast majority of links, which say* nothing beyond the note itself.+ * @param block the blocks of the note to highlight, a `block` link parameter.*/-export async function renderTooltip(entity: FNote | FAttachment | null, detail?: string) {+export async function renderTooltip(+ entity: FNote | FAttachment | null,+ detail?: string,+ block?: string+) {const attachment = entity && "attachmentId" in entity ? entity : null;const note = attachment ? attachment.getNote() : entity as FNote | null;if (!entity || !note) {@@ -223,7 +234,8 @@ export async function renderTooltip(entity: FNote | FAttachment | null, detail?:const { $renderedContent } = await contentRenderer.getRenderedContent(entity, {tooltip: true,- trim: true+ trim: true,+ highlightBlock: block});const isContentEmpty = $renderedContent[0].innerHTML.length === 0;